text
stringlengths 54
60.6k
|
---|
<commit_before><commit_msg>correct comment<commit_after><|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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 (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef VLA_HH_
#define VLA_HH_
#include <memory>
#include <new>
#include <assert.h>
#include <type_traits>
// Some C APIs have a structure with a variable length array at the end.
// This is a helper function to help allocate it.
//
// for a structure
//
// struct xx { int a; float b[0]; };
//
// use
//
// make_struct_with_vla(&xx::b, number_of_bs);
//
// to allocate it.
//
template <class S, typename E>
inline
std::unique_ptr<S>
make_struct_with_vla(E S::*last, size_t nr) {
auto fake = reinterpret_cast<S*>(0);
size_t offset = reinterpret_cast<uintptr_t>(&(fake->*last));
size_t element_size = sizeof((fake->*last)[0]);
assert(offset == sizeof(S));
auto p = ::operator new(offset + element_size * nr);
return std::unique_ptr<S>(new (p) S());
}
#endif /* VLA_HH_ */
<commit_msg>vla: Ensure memory is correctly freed<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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 (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef VLA_HH_
#define VLA_HH_
#include <memory>
#include <new>
#include <assert.h>
#include <type_traits>
#include <core/reactor.hh>
// Some C APIs have a structure with a variable length array at the end.
// This is a helper function to help allocate it.
//
// for a structure
//
// struct xx { int a; float b[0]; };
//
// use
//
// make_struct_with_vla(&xx::b, number_of_bs);
//
// to allocate it.
//
template <class S, typename E>
inline
std::unique_ptr<S, free_deleter>
make_struct_with_vla(E S::*last, size_t nr) {
auto fake = reinterpret_cast<S*>(0);
size_t offset = reinterpret_cast<uintptr_t>(&(fake->*last));
size_t element_size = sizeof((fake->*last)[0]);
assert(offset == sizeof(S));
auto p = ::malloc(offset + element_size * nr);
return std::unique_ptr<S, free_deleter>(new (p) S());
}
#endif /* VLA_HH_ */
<|endoftext|> |
<commit_before>// Copyright 2017 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 "shell/browser/extensions/electron_messaging_delegate.h"
#include <memory>
#include "base/callback.h"
#include "base/logging.h"
#include "build/build_config.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/api/messaging/extension_message_port.h"
#include "extensions/browser/api/messaging/native_message_host.h"
#include "extensions/browser/extension_api_frame_id_map.h"
#include "extensions/browser/pref_names.h"
#include "extensions/common/api/messaging/port_id.h"
#include "extensions/common/extension.h"
#include "ui/gfx/native_widget_types.h"
#include "url/gurl.h"
#include "shell/browser/api/electron_api_web_contents.h"
namespace extensions {
ElectronMessagingDelegate::ElectronMessagingDelegate() = default;
ElectronMessagingDelegate::~ElectronMessagingDelegate() = default;
MessagingDelegate::PolicyPermission
ElectronMessagingDelegate::IsNativeMessagingHostAllowed(
content::BrowserContext* browser_context,
const std::string& native_host_name) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
return PolicyPermission::DISALLOW;
}
std::unique_ptr<base::DictionaryValue>
ElectronMessagingDelegate::MaybeGetTabInfo(content::WebContents* web_contents) {
if (web_contents) {
auto* api_contents = electron::api::WebContents::FromWrappedClass(
v8::Isolate::GetCurrent(), web_contents);
if (api_contents) {
auto tab = std::make_unique<base::DictionaryValue>();
tab->SetWithoutPathExpansion(
"id", std::make_unique<base::Value>(api_contents->ID()));
return tab;
}
}
return nullptr;
}
content::WebContents* ElectronMessagingDelegate::GetWebContentsByTabId(
content::BrowserContext* browser_context,
int tab_id) {
auto* contents = electron::api::WebContents::FromWeakMapID(
v8::Isolate::GetCurrent(), tab_id);
if (!contents) {
return nullptr;
}
return contents->web_contents();
}
std::unique_ptr<MessagePort> ElectronMessagingDelegate::CreateReceiverForTab(
base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
const std::string& extension_id,
const PortId& receiver_port_id,
content::WebContents* receiver_contents,
int receiver_frame_id) {
// Frame ID -1 is every frame in the tab.
bool include_child_frames = receiver_frame_id == -1;
content::RenderFrameHost* receiver_rfh =
include_child_frames ? receiver_contents->GetMainFrame()
: ExtensionApiFrameIdMap::GetRenderFrameHostById(
receiver_contents, receiver_frame_id);
if (!receiver_rfh)
return nullptr;
return std::make_unique<ExtensionMessagePort>(
channel_delegate, receiver_port_id, extension_id, receiver_rfh,
include_child_frames);
}
std::unique_ptr<MessagePort>
ElectronMessagingDelegate::CreateReceiverForNativeApp(
content::BrowserContext* browser_context,
base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
content::RenderFrameHost* source,
const std::string& extension_id,
const PortId& receiver_port_id,
const std::string& native_app_name,
bool allow_user_level,
std::string* error_out) {
return nullptr;
}
void ElectronMessagingDelegate::QueryIncognitoConnectability(
content::BrowserContext* context,
const Extension* target_extension,
content::WebContents* source_contents,
const GURL& source_url,
const base::Callback<void(bool)>& callback) {
DCHECK(context->IsOffTheRecord());
callback.Run(false);
}
} // namespace extensions
<commit_msg>fix(extensions): add more properties to port.sender.tab (#22592)<commit_after>// Copyright 2017 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 "shell/browser/extensions/electron_messaging_delegate.h"
#include <memory>
#include "base/callback.h"
#include "base/logging.h"
#include "build/build_config.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/api/messaging/extension_message_port.h"
#include "extensions/browser/api/messaging/native_message_host.h"
#include "extensions/browser/extension_api_frame_id_map.h"
#include "extensions/browser/pref_names.h"
#include "extensions/common/api/messaging/port_id.h"
#include "extensions/common/extension.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "ui/gfx/native_widget_types.h"
#include "url/gurl.h"
namespace extensions {
ElectronMessagingDelegate::ElectronMessagingDelegate() = default;
ElectronMessagingDelegate::~ElectronMessagingDelegate() = default;
MessagingDelegate::PolicyPermission
ElectronMessagingDelegate::IsNativeMessagingHostAllowed(
content::BrowserContext* browser_context,
const std::string& native_host_name) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
return PolicyPermission::DISALLOW;
}
std::unique_ptr<base::DictionaryValue>
ElectronMessagingDelegate::MaybeGetTabInfo(content::WebContents* web_contents) {
if (web_contents) {
auto* api_contents = electron::api::WebContents::FromWrappedClass(
v8::Isolate::GetCurrent(), web_contents);
if (api_contents) {
auto tab = std::make_unique<base::DictionaryValue>();
tab->SetWithoutPathExpansion(
"id", std::make_unique<base::Value>(api_contents->ID()));
tab->SetWithoutPathExpansion(
"url", std::make_unique<base::Value>(api_contents->GetURL().spec()));
tab->SetWithoutPathExpansion(
"title", std::make_unique<base::Value>(api_contents->GetTitle()));
tab->SetWithoutPathExpansion(
"audible",
std::make_unique<base::Value>(api_contents->IsCurrentlyAudible()));
return tab;
}
}
return nullptr;
}
content::WebContents* ElectronMessagingDelegate::GetWebContentsByTabId(
content::BrowserContext* browser_context,
int tab_id) {
auto* contents = electron::api::WebContents::FromWeakMapID(
v8::Isolate::GetCurrent(), tab_id);
if (!contents) {
return nullptr;
}
return contents->web_contents();
}
std::unique_ptr<MessagePort> ElectronMessagingDelegate::CreateReceiverForTab(
base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
const std::string& extension_id,
const PortId& receiver_port_id,
content::WebContents* receiver_contents,
int receiver_frame_id) {
// Frame ID -1 is every frame in the tab.
bool include_child_frames = receiver_frame_id == -1;
content::RenderFrameHost* receiver_rfh =
include_child_frames ? receiver_contents->GetMainFrame()
: ExtensionApiFrameIdMap::GetRenderFrameHostById(
receiver_contents, receiver_frame_id);
if (!receiver_rfh)
return nullptr;
return std::make_unique<ExtensionMessagePort>(
channel_delegate, receiver_port_id, extension_id, receiver_rfh,
include_child_frames);
}
std::unique_ptr<MessagePort>
ElectronMessagingDelegate::CreateReceiverForNativeApp(
content::BrowserContext* browser_context,
base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
content::RenderFrameHost* source,
const std::string& extension_id,
const PortId& receiver_port_id,
const std::string& native_app_name,
bool allow_user_level,
std::string* error_out) {
return nullptr;
}
void ElectronMessagingDelegate::QueryIncognitoConnectability(
content::BrowserContext* context,
const Extension* target_extension,
content::WebContents* source_contents,
const GURL& source_url,
const base::Callback<void(bool)>& callback) {
DCHECK(context->IsOffTheRecord());
callback.Run(false);
}
} // namespace extensions
<|endoftext|> |
<commit_before>#include "imagewidget.h"
#include "renderers.h"
#include <QResizeEvent>
#include <QPainter>
#include <QTime>
ImageWidget::ImageWidget(QWidget *parent) : QWidget(parent), mode(AnglaphFull), zoom(0.0), swapLR(false), panButtons(Qt::LeftButton | Qt::MidButton),
mouseTimer(this), hBar(Qt::Horizontal, this), vBar(Qt::Vertical, this), continuousPan(true), scrollbarsVisible(true),
maskInterlacedHorizontal(":/masks/interlacedH.pbm"), maskInterlacedVertical(":/masks/interlacedV.pbm"), maskCheckerboard(":/masks/checkerboard.pbm") {
setMouseTracking(true);
recalculatescroolmax();
connect(&hBar, SIGNAL(valueChanged(int)), this, SLOT(update()));
connect(&vBar, SIGNAL(valueChanged(int)), this, SLOT(update()));
mouseTimer.setSingleShot(true);
connect(&mouseTimer, SIGNAL(timeout()), this, SLOT(hideCursor()));
}
void ImageWidget::resizeEvent(QResizeEvent *e){
hBar.resize(e->size().width() - vBar.sizeHint().width(), hBar.sizeHint().height());
hBar.move(0, e->size().height() - hBar.sizeHint().height());
vBar.resize(vBar.sizeHint().width(), e->size().height() - hBar.sizeHint().height());
vBar.move(e->size().width() - vBar.sizeHint().width(), 0);
recalculatescroolmax();
}
void ImageWidget::paintEvent(QPaintEvent *e){
QPainter painter(this);
painter.setBrush(QBrush(Qt::black));
painter.drawRect(e->rect());
if(imgL.isNull() && imgR.isNull()){
painter.setPen(Qt::gray);
QFont font;
font.setPointSize(32);
painter.setFont(font);
painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, tr("No Image Loaded"));
}else if(parentWidget() && !parentWidget()->isFullScreen() && (mode == InterlacedHorizontal || mode == InterlacedVertical || mode == Checkerboard)){
painter.setPen(Qt::gray);
QFont font;
font.setPointSize(24);
painter.setFont(font);
painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, tr("%1 Display Must Be Fullscreen").arg(mode == Checkerboard ? "Checkerboard" : "Interlaced"));
/* keep scrollbars hidden. */
zoom = 0.0f;
recalculatescroolmax();
}else{
QTime starttime = QTime::currentTime();
if(swapLR){
draw(pixmapR, pixmapL, painter);
}else{
draw(pixmapL, pixmapR, painter);
}
qDebug("Draw time: %ims", starttime.msecsTo(QTime::currentTime()));
}
}
bool ImageWidget::loadStereoImage(const QString &filename){
QImage img(filename);
imgR = img.copy(0, 0, img.width() / 2, img.height());
imgL = img.copy(img.width() / 2, 0, img.width() / 2, img.height());
pixmapL = QPixmap::fromImage(imgL);
pixmapR = QPixmap::fromImage(imgR);
recalculatescroolmax();
updateAnglaph();
repaint();
return !img.isNull();
}
void ImageWidget::mouseMoveEvent(QMouseEvent *e){
if((e->buttons() & panButtons) && (vBar.maximum() > 0 || hBar.maximum() > 0)){
vBar.setValue(vBar.value() + lastmousepos.y() - e->y());
hBar.setValue(hBar.value() + lastmousepos.x() - e->x());
if(continuousPan){
QPoint warpto = e->pos();
if(e->x() <= 0){
warpto.setX(width() - 3);
}else if(e->x() >= width() - 1){
warpto.setX(2);
}
if(e->y() <= 0){
warpto.setY(height() - 3);
}else if(e->y() >= height() - 1){
warpto.setY(2);
}
if(warpto != e->pos()){
QCursor::setPos(mapToGlobal(warpto));
}
lastmousepos = warpto;
}else{
lastmousepos = e->pos();
}
setCursor(Qt::SizeAllCursor);
}else{
setCursor(Qt::ArrowCursor);
lastmousepos = e->pos();
}
mouseTimer.start(4000);
}
void ImageWidget::mouseReleaseEvent(QMouseEvent *e){
if(panButtons.testFlag(e->button())){
setCursor(Qt::ArrowCursor);
}
}
void ImageWidget::wheelEvent(QWheelEvent *e){
addZoom(e->delta() / 1000.0);
}
void ImageWidget::recalculatescroolmax(){
bool isSidebySide = (mode == SidebySide || mode == SidebySideMLeft || mode == SidebySideMRight || mode == SidebySideMBoth);
bool isTopBottom = (mode == TopBottom || mode == TopBottomMTop || mode == TopBottomMBottom || mode == TopBottomMBoth);
int hmax = qMax(int((imgL.width() << isSidebySide) * zoom - width()) >> (isSidebySide + 1), 0);
hBar.setRange(-hmax, hmax);
int vmax = qMax(int((imgL.height() << isTopBottom) * zoom - height()) >> (isTopBottom + 1), 0);
vBar.setRange(-vmax, vmax);
hBar.setVisible(scrollbarsVisible && hmax != 0);
vBar.setVisible(scrollbarsVisible && vmax != 0);
}
void ImageWidget::setZoom(qreal val){
zoom = val;
recalculatescroolmax();
repaint();
}
void ImageWidget::zoomIn(){
addZoom( 0.1);
}
void ImageWidget::zoomOut(){
addZoom(-0.1);
}
void ImageWidget::addZoom(qreal amount){
if(zoom <= 0.0){
bool isSidebySide = (mode == SidebySide || mode == SidebySideMLeft || mode == SidebySideMRight || mode == SidebySideMBoth);
bool isTopBottom = (mode == TopBottom || mode == TopBottomMTop || mode == TopBottomMBottom || mode == TopBottomMBoth);
zoom = qMin(qreal(width()) / qreal(imgL.width() << isSidebySide), qreal(height()) / qreal(imgL.height() << isTopBottom));
}
qreal zoomorig = zoom;
zoom += amount * zoom;
zoom = qBound(0.2, zoom, 4.0);
recalculatescroolmax();
vBar.setValue(vBar.value() * zoom / zoomorig);
hBar.setValue(hBar.value() * zoom / zoomorig);
repaint();
}
void ImageWidget::enableSwapLR(bool enable){
swapLR = enable;
updateAnglaph();
repaint();
}
void ImageWidget::showScrollbars(bool show){
scrollbarsVisible = show;
recalculatescroolmax();
}
void ImageWidget::enableContinuousPan(bool enable){
continuousPan = enable;
}
void ImageWidget::hideCursor(){
setCursor(Qt::BlankCursor);
}
void ImageWidget::draw(const QPixmap &L, const QPixmap &R, QPainter &painter){
switch(mode){
case AnglaphFull:
case AnglaphHalf:
case AnglaphGreyscale:
drawSingle(anglaph, -hBar.value(), -vBar.value(), painter, zoom);
break;
case SidebySide:
drawSideBySide(L, R, -hBar.value(), -vBar.value(), painter, zoom);
break;
case SidebySideMLeft:
drawSideBySide(L, R, -hBar.value(), -vBar.value(), painter, zoom, true);
break;
case SidebySideMRight:
drawSideBySide(L, R, -hBar.value(), -vBar.value(), painter, zoom, false, true);
break;
case SidebySideMBoth:
drawSideBySide(L, R, -hBar.value(), -vBar.value(), painter, zoom, true, true);
break;
case TopBottom:
drawTopBottom(L, R, -hBar.value(), -vBar.value(), painter, zoom);
break;
case TopBottomMTop:
drawTopBottom(L, R, -hBar.value(), -vBar.value(), painter, zoom, true);
break;
case TopBottomMBottom:
drawTopBottom(L, R, -hBar.value(), -vBar.value(), painter, zoom, false, true);
break;
case TopBottomMBoth:
drawTopBottom(L, R, -hBar.value(), -vBar.value(), painter, zoom, true, true);
break;
case InterlacedHorizontal:
drawInterlaced(L, R, -hBar.value(), -vBar.value(), painter, maskInterlacedHorizontal, zoom);
break;
case InterlacedVertical:
drawInterlaced(L, R, -hBar.value(), -vBar.value(), painter, maskInterlacedVertical, zoom);
break;
case Checkerboard:
drawInterlaced(L, R, -hBar.value(), -vBar.value(), painter, maskCheckerboard, zoom);
break;
case MonoLeft:
drawSingle(L, -hBar.value(), -vBar.value(), painter, zoom);
break;
case MonoRight:
drawSingle(R, -hBar.value(), -vBar.value(), painter, zoom);
break;
}
}
void ImageWidget::setRenderMode(DrawMode m){
mode = m;
recalculatescroolmax();
updateAnglaph();
repaint();
}
void ImageWidget::setPanButtons(Qt::MouseButtons buttons){
panButtons = buttons;
}
void ImageWidget::updateAnglaph(){
const QImage &L = swapLR ? imgR : imgL;
const QImage &R = swapLR ? imgL : imgR;
switch(mode){
case AnglaphFull:
anglaph = QPixmap::fromImage(drawAnglaph(L, R));
break;
case AnglaphHalf:
anglaph = QPixmap::fromImage(drawAnglaphHalf(L, R));
break;
case AnglaphGreyscale:
anglaph = QPixmap::fromImage(drawAnglaphGrey(L, R));
break;
default: break;
}
}
QMap<QString, ImageWidget::DrawMode> initDrawModeList(){
QMap<QString, ImageWidget::DrawMode> list;
list.insert("Anglaph, Full Color", ImageWidget::AnglaphFull);
list.insert("Anglaph, Half Color", ImageWidget::AnglaphHalf);
list.insert("Anglaph, Greyscale", ImageWidget::AnglaphGreyscale);
list.insert("Side by Side, No Mirror", ImageWidget::SidebySide);
list.insert("Side by Side, Mirror Left", ImageWidget::SidebySideMLeft);
list.insert("Side by Side, Mirror Right", ImageWidget::SidebySideMRight);
list.insert("Side by Side, Mirror Both", ImageWidget::SidebySideMBoth);
list.insert("Top/Bottom, No Mirror", ImageWidget::TopBottom);
list.insert("Top/Bottom, Mirror Top", ImageWidget::TopBottomMTop);
list.insert("Top/Bottom, Mirror Bottom", ImageWidget::TopBottomMBottom);
list.insert("Top/Bottom, Mirror Both", ImageWidget::TopBottomMBoth);
list.insert("Interlaced, Horizontal", ImageWidget::InterlacedHorizontal);
list.insert("Interlaced, Vertical", ImageWidget::InterlacedVertical);
list.insert("Checkerboard", ImageWidget::Checkerboard);
list.insert("Mono, Left", ImageWidget::MonoLeft);
list.insert("Mono, Right", ImageWidget::MonoRight);
return list;
}
const QMap<QString, ImageWidget::DrawMode> ImageWidget::drawModeNames = initDrawModeList();
<commit_msg>use QElapsedTimer for more accurate draw time output.<commit_after>#include "imagewidget.h"
#include "renderers.h"
#include <QResizeEvent>
#include <QPainter>
#include <QElapsedTimer>
ImageWidget::ImageWidget(QWidget *parent) : QWidget(parent), mode(AnglaphFull), zoom(0.0), swapLR(false), panButtons(Qt::LeftButton | Qt::MidButton),
mouseTimer(this), hBar(Qt::Horizontal, this), vBar(Qt::Vertical, this), continuousPan(true), scrollbarsVisible(true),
maskInterlacedHorizontal(":/masks/interlacedH.pbm"), maskInterlacedVertical(":/masks/interlacedV.pbm"), maskCheckerboard(":/masks/checkerboard.pbm") {
setMouseTracking(true);
recalculatescroolmax();
connect(&hBar, SIGNAL(valueChanged(int)), this, SLOT(update()));
connect(&vBar, SIGNAL(valueChanged(int)), this, SLOT(update()));
mouseTimer.setSingleShot(true);
connect(&mouseTimer, SIGNAL(timeout()), this, SLOT(hideCursor()));
}
void ImageWidget::resizeEvent(QResizeEvent *e){
hBar.resize(e->size().width() - vBar.sizeHint().width(), hBar.sizeHint().height());
hBar.move(0, e->size().height() - hBar.sizeHint().height());
vBar.resize(vBar.sizeHint().width(), e->size().height() - hBar.sizeHint().height());
vBar.move(e->size().width() - vBar.sizeHint().width(), 0);
recalculatescroolmax();
}
void ImageWidget::paintEvent(QPaintEvent *e){
QPainter painter(this);
painter.setBrush(QBrush(Qt::black));
painter.drawRect(e->rect());
if(imgL.isNull() && imgR.isNull()){
painter.setPen(Qt::gray);
QFont font;
font.setPointSize(32);
painter.setFont(font);
painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, tr("No Image Loaded"));
}else if(parentWidget() && !parentWidget()->isFullScreen() && (mode == InterlacedHorizontal || mode == InterlacedVertical || mode == Checkerboard)){
painter.setPen(Qt::gray);
QFont font;
font.setPointSize(24);
painter.setFont(font);
painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, tr("%1 Display Must Be Fullscreen").arg(mode == Checkerboard ? "Checkerboard" : "Interlaced"));
/* keep scrollbars hidden. */
zoom = 0.0f;
recalculatescroolmax();
}else{
QElapsedTimer time;
time.start();
if(swapLR){
draw(pixmapR, pixmapL, painter);
}else{
draw(pixmapL, pixmapR, painter);
}
qDebug("Draw time: %fms", time.nsecsElapsed() * 1.0e-6);
}
}
bool ImageWidget::loadStereoImage(const QString &filename){
QImage img(filename);
imgR = img.copy(0, 0, img.width() / 2, img.height());
imgL = img.copy(img.width() / 2, 0, img.width() / 2, img.height());
pixmapL = QPixmap::fromImage(imgL);
pixmapR = QPixmap::fromImage(imgR);
recalculatescroolmax();
updateAnglaph();
repaint();
return !img.isNull();
}
void ImageWidget::mouseMoveEvent(QMouseEvent *e){
if((e->buttons() & panButtons) && (vBar.maximum() > 0 || hBar.maximum() > 0)){
vBar.setValue(vBar.value() + lastmousepos.y() - e->y());
hBar.setValue(hBar.value() + lastmousepos.x() - e->x());
if(continuousPan){
QPoint warpto = e->pos();
if(e->x() <= 0){
warpto.setX(width() - 3);
}else if(e->x() >= width() - 1){
warpto.setX(2);
}
if(e->y() <= 0){
warpto.setY(height() - 3);
}else if(e->y() >= height() - 1){
warpto.setY(2);
}
if(warpto != e->pos()){
QCursor::setPos(mapToGlobal(warpto));
}
lastmousepos = warpto;
}else{
lastmousepos = e->pos();
}
setCursor(Qt::SizeAllCursor);
}else{
setCursor(Qt::ArrowCursor);
lastmousepos = e->pos();
}
mouseTimer.start(4000);
}
void ImageWidget::mouseReleaseEvent(QMouseEvent *e){
if(panButtons.testFlag(e->button())){
setCursor(Qt::ArrowCursor);
}
}
void ImageWidget::wheelEvent(QWheelEvent *e){
addZoom(e->delta() / 1000.0);
}
void ImageWidget::recalculatescroolmax(){
bool isSidebySide = (mode == SidebySide || mode == SidebySideMLeft || mode == SidebySideMRight || mode == SidebySideMBoth);
bool isTopBottom = (mode == TopBottom || mode == TopBottomMTop || mode == TopBottomMBottom || mode == TopBottomMBoth);
int hmax = qMax(int((imgL.width() << isSidebySide) * zoom - width()) >> (isSidebySide + 1), 0);
hBar.setRange(-hmax, hmax);
int vmax = qMax(int((imgL.height() << isTopBottom) * zoom - height()) >> (isTopBottom + 1), 0);
vBar.setRange(-vmax, vmax);
hBar.setVisible(scrollbarsVisible && hmax != 0);
vBar.setVisible(scrollbarsVisible && vmax != 0);
}
void ImageWidget::setZoom(qreal val){
zoom = val;
recalculatescroolmax();
repaint();
}
void ImageWidget::zoomIn(){
addZoom( 0.1);
}
void ImageWidget::zoomOut(){
addZoom(-0.1);
}
void ImageWidget::addZoom(qreal amount){
if(zoom <= 0.0){
bool isSidebySide = (mode == SidebySide || mode == SidebySideMLeft || mode == SidebySideMRight || mode == SidebySideMBoth);
bool isTopBottom = (mode == TopBottom || mode == TopBottomMTop || mode == TopBottomMBottom || mode == TopBottomMBoth);
zoom = qMin(qreal(width()) / qreal(imgL.width() << isSidebySide), qreal(height()) / qreal(imgL.height() << isTopBottom));
}
qreal zoomorig = zoom;
zoom += amount * zoom;
zoom = qBound(0.2, zoom, 4.0);
recalculatescroolmax();
vBar.setValue(vBar.value() * zoom / zoomorig);
hBar.setValue(hBar.value() * zoom / zoomorig);
repaint();
}
void ImageWidget::enableSwapLR(bool enable){
swapLR = enable;
updateAnglaph();
repaint();
}
void ImageWidget::showScrollbars(bool show){
scrollbarsVisible = show;
recalculatescroolmax();
}
void ImageWidget::enableContinuousPan(bool enable){
continuousPan = enable;
}
void ImageWidget::hideCursor(){
setCursor(Qt::BlankCursor);
}
void ImageWidget::draw(const QPixmap &L, const QPixmap &R, QPainter &painter){
switch(mode){
case AnglaphFull:
case AnglaphHalf:
case AnglaphGreyscale:
drawSingle(anglaph, -hBar.value(), -vBar.value(), painter, zoom);
break;
case SidebySide:
drawSideBySide(L, R, -hBar.value(), -vBar.value(), painter, zoom);
break;
case SidebySideMLeft:
drawSideBySide(L, R, -hBar.value(), -vBar.value(), painter, zoom, true);
break;
case SidebySideMRight:
drawSideBySide(L, R, -hBar.value(), -vBar.value(), painter, zoom, false, true);
break;
case SidebySideMBoth:
drawSideBySide(L, R, -hBar.value(), -vBar.value(), painter, zoom, true, true);
break;
case TopBottom:
drawTopBottom(L, R, -hBar.value(), -vBar.value(), painter, zoom);
break;
case TopBottomMTop:
drawTopBottom(L, R, -hBar.value(), -vBar.value(), painter, zoom, true);
break;
case TopBottomMBottom:
drawTopBottom(L, R, -hBar.value(), -vBar.value(), painter, zoom, false, true);
break;
case TopBottomMBoth:
drawTopBottom(L, R, -hBar.value(), -vBar.value(), painter, zoom, true, true);
break;
case InterlacedHorizontal:
drawInterlaced(L, R, -hBar.value(), -vBar.value(), painter, maskInterlacedHorizontal, zoom);
break;
case InterlacedVertical:
drawInterlaced(L, R, -hBar.value(), -vBar.value(), painter, maskInterlacedVertical, zoom);
break;
case Checkerboard:
drawInterlaced(L, R, -hBar.value(), -vBar.value(), painter, maskCheckerboard, zoom);
break;
case MonoLeft:
drawSingle(L, -hBar.value(), -vBar.value(), painter, zoom);
break;
case MonoRight:
drawSingle(R, -hBar.value(), -vBar.value(), painter, zoom);
break;
}
}
void ImageWidget::setRenderMode(DrawMode m){
mode = m;
recalculatescroolmax();
updateAnglaph();
repaint();
}
void ImageWidget::setPanButtons(Qt::MouseButtons buttons){
panButtons = buttons;
}
void ImageWidget::updateAnglaph(){
const QImage &L = swapLR ? imgR : imgL;
const QImage &R = swapLR ? imgL : imgR;
switch(mode){
case AnglaphFull:
anglaph = QPixmap::fromImage(drawAnglaph(L, R));
break;
case AnglaphHalf:
anglaph = QPixmap::fromImage(drawAnglaphHalf(L, R));
break;
case AnglaphGreyscale:
anglaph = QPixmap::fromImage(drawAnglaphGrey(L, R));
break;
default: break;
}
}
QMap<QString, ImageWidget::DrawMode> initDrawModeList(){
QMap<QString, ImageWidget::DrawMode> list;
list.insert("Anglaph, Full Color", ImageWidget::AnglaphFull);
list.insert("Anglaph, Half Color", ImageWidget::AnglaphHalf);
list.insert("Anglaph, Greyscale", ImageWidget::AnglaphGreyscale);
list.insert("Side by Side, No Mirror", ImageWidget::SidebySide);
list.insert("Side by Side, Mirror Left", ImageWidget::SidebySideMLeft);
list.insert("Side by Side, Mirror Right", ImageWidget::SidebySideMRight);
list.insert("Side by Side, Mirror Both", ImageWidget::SidebySideMBoth);
list.insert("Top/Bottom, No Mirror", ImageWidget::TopBottom);
list.insert("Top/Bottom, Mirror Top", ImageWidget::TopBottomMTop);
list.insert("Top/Bottom, Mirror Bottom", ImageWidget::TopBottomMBottom);
list.insert("Top/Bottom, Mirror Both", ImageWidget::TopBottomMBoth);
list.insert("Interlaced, Horizontal", ImageWidget::InterlacedHorizontal);
list.insert("Interlaced, Vertical", ImageWidget::InterlacedVertical);
list.insert("Checkerboard", ImageWidget::Checkerboard);
list.insert("Mono, Left", ImageWidget::MonoLeft);
list.insert("Mono, Right", ImageWidget::MonoRight);
return list;
}
const QMap<QString, ImageWidget::DrawMode> ImageWidget::drawModeNames = initDrawModeList();
<|endoftext|> |
<commit_before><commit_msg>- Check for the return value of RegQueryValueEx (has to be ERROR_SUCCESS) (the registry was updated at each root.exe startup before)<commit_after><|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/user.h> // PAGE_SIZE
#include "parseArgs/parseArgs.h"
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "au/CommandLine.h" // au::CommandLine
#include "au/Console.h" // au::Console
#include "samson/common/SamsonSetup.h" // samson::SamsonSetup
#include "samson/common/ports.h"
#include "samson/common/coding.h" // samson::FormatHeader
#include "samson/common/samsonVars.h" // SAMSON_ARG_VARS SAMSON_ARGS
#include "samson/module/KVFormat.h" // samson::KVFormat
#include "samson/module/ModulesManager.h" // samson::ModulesManager
#include "samson/common/samsonVersion.h"
#ifdef LINUX
#define KERNEL_SHMMAX "/proc/sys/kernel/shmmax"
#define KERNEL_SHMALL "/proc/sys/kernel/shmall"
#endif
#ifdef OSX
#define KERNEL_SHMMAX "kern.sysv.shmmax"
#define KERNEL_SHMALL "kern.sysv.shmall"
#endif
/* ****************************************************************************
*
* Option variables
*/
SAMSON_ARG_VARS;
bool check;
/* ****************************************************************************
*
* parse arguments
*/
PaArgument paArgs[] =
{
SAMSON_ARGS,
PA_END_OF_ARGS
};
#ifdef LINUX
void sysctl_value(char *param_name, long int *param_value)
{
FILE *fd_param; /* file handle for paramname*/
char *param_value_str = NULL;
fd_param = fopen (param_name, "r");
param_value_str = (char *) malloc(21);
while (fgets(param_value_str, 20, fd_param) != NULL); /* We assume that there are no parameters whose string length > 20 chars */
*param_value=strtol(param_value_str, NULL, 10);
free(param_value_str);
param_value_str = NULL;
fclose(fd_param);
}
#endif
#ifdef OSX
void sysctl_value(char *param_name, long int *param_value)
{
long len = sizeof(&(param_value));
if (sysctlbyname(param_name, param_value, &len, 0, 0) )
{
perror( "sysctlbyname" );
}
}
#endif
int main(int argC, const char *argV[])
{
long int kernel_shmmax = 0;
long int kernel_shmall = 0;
long int page_size = 0;
long int max_memory_size = 0;
long int needed_shmall = 0;
long int num_processes = 0;
long int shared_memory_size_per_buffer = 0;
long int samson_required_mem = 0;
paConfig("usage and exit on any warning", (void*) true);
paConfig("log to screen", (void*) "only errors");
paConfig("log file line format", (void*) "TYPE:DATE:EXEC-AUX/FILE[LINE](p.PID)(t.TID) FUNC: TEXT");
paConfig("screen line format", (void*) "TYPE@TIME EXEC: TEXT");
paConfig("log to file", (void*) true);
paParse(paArgs, argC, (char**) argV, 1, false);
// SamsonSetup init
samson::SamsonSetup::init( samsonHome , samsonWorking );
samson::SamsonSetup::shared()->createWorkingDirectories(); // Create working directories
// Fetch the current SAMSON configuration
std::string num_processes_str = samson::SamsonSetup::shared()->getValueForParameter("general.num_processess");
num_processes = strtol(num_processes_str.c_str(), NULL, 10);
std::string shared_memory_size_per_buffer_str = samson::SamsonSetup::shared()->getValueForParameter("general.shared_memory_size_per_buffer");
shared_memory_size_per_buffer = strtol(shared_memory_size_per_buffer_str.c_str(), NULL, 10);
samson_required_mem = num_processes * shared_memory_size_per_buffer;
#ifdef LINUX
// Fetch the system config
sysctl_value((char *)KERNEL_SHMMAX, &kernel_shmmax);
sysctl_value((char *)KERNEL_SHMALL, &kernel_shmall);
#endif
// max memory allowed shmall * page_size
max_memory_size = kernel_shmall * PAGE_SIZE;
// Check to see if we can allocate all the memory needed
if ( samson_required_mem > max_memory_size )
{
needed_shmall = samson_required_mem / page_size;
printf ("Unable to allocate the needed memory for SAMSON. The system has %ld allocated and we need %ld.\n", max_memory_size, samson_required_mem);
printf ("Set kernel.shmall to %ld using the command 'sysctl -w kernel.shmall=%ld'.\n", needed_shmall, needed_shmall);
}
else
{
printf ("Found enough shared memory for SAMSON\n");
}
// Check to see if the segment size (shmmax) is big enough for each SAMSON buffer
if ( shared_memory_size_per_buffer > kernel_shmmax )
{
printf ("The system shared memory segment size (kernel.shmmax) is too small for samson. The system allows for a maximum size of %ld and we need %ld\n", kernel_shmmax, shared_memory_size_per_buffer );
printf ("Set kernel.shmmax to %ld using the command 'sysctl -w kernel.shmmax=%ld'.\n", shared_memory_size_per_buffer, shared_memory_size_per_buffer );
}
else
{
printf ("The maximum shared memory segment size is sufficent for SAMSON.\n");
}
}
<commit_msg>SAMSON-642 Fix broken compilation in OSX<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/user.h> // PAGE_SIZE
#include "parseArgs/parseArgs.h"
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "au/CommandLine.h" // au::CommandLine
#include "au/Console.h" // au::Console
#include "samson/common/SamsonSetup.h" // samson::SamsonSetup
#include "samson/common/ports.h"
#include "samson/common/coding.h" // samson::FormatHeader
#include "samson/common/samsonVars.h" // SAMSON_ARG_VARS SAMSON_ARGS
#include "samson/module/KVFormat.h" // samson::KVFormat
#include "samson/module/ModulesManager.h" // samson::ModulesManager
#include "samson/common/samsonVersion.h"
#ifdef LINUX
#define KERNEL_SHMMAX "/proc/sys/kernel/shmmax"
#define KERNEL_SHMALL "/proc/sys/kernel/shmall"
#endif
#ifdef OSX
#define KERNEL_SHMMAX "kern.sysv.shmmax"
#define KERNEL_SHMALL "kern.sysv.shmall"
#endif
/* ****************************************************************************
*
* Option variables
*/
SAMSON_ARG_VARS;
bool check;
/* ****************************************************************************
*
* parse arguments
*/
PaArgument paArgs[] =
{
SAMSON_ARGS,
PA_END_OF_ARGS
};
#ifdef LINUX
void sysctl_value(char *param_name, long int *param_value)
{
FILE *fd_param; /* file handle for paramname*/
char *param_value_str = NULL;
fd_param = fopen (param_name, "r");
param_value_str = (char *) malloc(21);
while (fgets(param_value_str, 20, fd_param) != NULL); /* We assume that there are no parameters whose string length > 20 chars */
*param_value=strtol(param_value_str, NULL, 10);
free(param_value_str);
param_value_str = NULL;
fclose(fd_param);
}
#endif
#ifdef OSX
void sysctl_value(char *param_name, long int *param_value)
{
size_t len = sizeof(&(param_value));
if (sysctlbyname(param_name, param_value, &len, 0, 0) )
{
perror( "sysctlbyname" );
}
}
#endif
int main(int argC, const char *argV[])
{
long int kernel_shmmax = 0;
long int kernel_shmall = 0;
long int page_size = 0;
long int max_memory_size = 0;
long int needed_shmall = 0;
long int num_processes = 0;
long int shared_memory_size_per_buffer = 0;
long int samson_required_mem = 0;
paConfig("usage and exit on any warning", (void*) true);
paConfig("log to screen", (void*) "only errors");
paConfig("log file line format", (void*) "TYPE:DATE:EXEC-AUX/FILE[LINE](p.PID)(t.TID) FUNC: TEXT");
paConfig("screen line format", (void*) "TYPE@TIME EXEC: TEXT");
paConfig("log to file", (void*) true);
paParse(paArgs, argC, (char**) argV, 1, false);
// SamsonSetup init
samson::SamsonSetup::init( samsonHome , samsonWorking );
samson::SamsonSetup::shared()->createWorkingDirectories(); // Create working directories
// Fetch the current SAMSON configuration
std::string num_processes_str = samson::SamsonSetup::shared()->getValueForParameter("general.num_processess");
num_processes = strtol(num_processes_str.c_str(), NULL, 10);
std::string shared_memory_size_per_buffer_str = samson::SamsonSetup::shared()->getValueForParameter("general.shared_memory_size_per_buffer");
shared_memory_size_per_buffer = strtol(shared_memory_size_per_buffer_str.c_str(), NULL, 10);
samson_required_mem = num_processes * shared_memory_size_per_buffer;
#ifdef LINUX
// Fetch the system config
sysctl_value((char *)KERNEL_SHMMAX, &kernel_shmmax);
sysctl_value((char *)KERNEL_SHMALL, &kernel_shmall);
#endif
// max memory allowed shmall * page_size
max_memory_size = kernel_shmall * PAGE_SIZE;
// Check to see if we can allocate all the memory needed
if ( samson_required_mem > max_memory_size )
{
needed_shmall = samson_required_mem / page_size;
printf ("Unable to allocate the needed memory for SAMSON. The system has %ld allocated and we need %ld.\n", max_memory_size, samson_required_mem);
printf ("Set kernel.shmall to %ld using the command 'sysctl -w kernel.shmall=%ld'.\n", needed_shmall, needed_shmall);
}
else
{
printf ("Found enough shared memory for SAMSON\n");
}
// Check to see if the segment size (shmmax) is big enough for each SAMSON buffer
if ( shared_memory_size_per_buffer > kernel_shmmax )
{
printf ("The system shared memory segment size (kernel.shmmax) is too small for samson. The system allows for a maximum size of %ld and we need %ld\n", kernel_shmmax, shared_memory_size_per_buffer );
printf ("Set kernel.shmmax to %ld using the command 'sysctl -w kernel.shmmax=%ld'.\n", shared_memory_size_per_buffer, shared_memory_size_per_buffer );
}
else
{
printf ("The maximum shared memory segment size is sufficent for SAMSON.\n");
}
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"
using namespace std;
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() {
return M_PI;
}
double deg2rad(double x) {
return x * pi() / 180;
}
double rad2deg(double x) {
return x * 180 / pi();
}
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_first_of("}");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
double distance(double x1, double y1, double x2, double y2) {
return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
int ClosestWaypoint(double x, double y, vector<double> maps_x,
vector<double> maps_y) {
double closestLen = 100000; //large number
int closestWaypoint = 0;
for (int i = 0; i < maps_x.size(); i++) {
double map_x = maps_x[i];
double map_y = maps_y[i];
double dist = distance(x, y, map_x, map_y);
if (dist < closestLen) {
closestLen = dist;
closestWaypoint = i;
}
}
return closestWaypoint;
}
int NextWaypoint(double x, double y, double theta, vector<double> maps_x,
vector<double> maps_y) {
int closestWaypoint = ClosestWaypoint(x, y, maps_x, maps_y);
double map_x = maps_x[closestWaypoint];
double map_y = maps_y[closestWaypoint];
double heading = atan2((map_y - y), (map_x - x));
double angle = abs(theta - heading);
if (angle > pi() / 4) {
closestWaypoint++;
}
return closestWaypoint;
}
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta,
vector<double> maps_x, vector<double> maps_y) {
int next_wp = NextWaypoint(x, y, theta, maps_x, maps_y);
int prev_wp;
prev_wp = next_wp - 1;
if (next_wp == 0) {
prev_wp = maps_x.size() - 1;
}
double n_x = maps_x[next_wp] - maps_x[prev_wp];
double n_y = maps_y[next_wp] - maps_y[prev_wp];
double x_x = x - maps_x[prev_wp];
double x_y = y - maps_y[prev_wp];
// find the projection of x onto n
double proj_norm = (x_x * n_x + x_y * n_y) / (n_x * n_x + n_y * n_y);
double proj_x = proj_norm * n_x;
double proj_y = proj_norm * n_y;
double frenet_d = distance(x_x, x_y, proj_x, proj_y);
//see if d value is positive or negative by comparing it to a center point
double center_x = 1000 - maps_x[prev_wp];
double center_y = 2000 - maps_y[prev_wp];
double centerToPos = distance(center_x, center_y, x_x, x_y);
double centerToRef = distance(center_x, center_y, proj_x, proj_y);
if (centerToPos <= centerToRef) {
frenet_d *= -1;
}
// calculate s value
double frenet_s = 0;
for (int i = 0; i < prev_wp; i++) {
frenet_s += distance(maps_x[i], maps_y[i], maps_x[i + 1],
maps_y[i + 1]);
}
frenet_s += distance(0, 0, proj_x, proj_y);
return {frenet_s,frenet_d};
}
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, vector<double> maps_s,
vector<double> maps_x, vector<double> maps_y) {
int prev_wp = -1;
while (s > maps_s[prev_wp + 1] && (prev_wp < (int) (maps_s.size() - 1))) {
prev_wp++;
}
int wp2 = (prev_wp + 1) % maps_x.size();
double heading = atan2((maps_y[wp2] - maps_y[prev_wp]),
(maps_x[wp2] - maps_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s - maps_s[prev_wp]);
double seg_x = maps_x[prev_wp] + seg_s * cos(heading);
double seg_y = maps_y[prev_wp] + seg_s * sin(heading);
double perp_heading = heading - pi() / 2;
double x = seg_x + d * cos(perp_heading);
double y = seg_y + d * sin(perp_heading);
return {x,y};
}
int main() {
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
// Waypoint map to read from
string map_file_ = "../data/highway_map.csv";
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
ifstream in_map_(map_file_.c_str(), ifstream::in);
string line;
while (getline(in_map_, line)) {
istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_waypoints_x.push_back(x);
map_waypoints_y.push_back(y);
map_waypoints_s.push_back(s);
map_waypoints_dx.push_back(d_x);
map_waypoints_dy.push_back(d_y);
}
h.onMessage(
[&map_waypoints_x,&map_waypoints_y,&map_waypoints_s,&map_waypoints_dx,&map_waypoints_dy](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
//auto sdata = string(data).substr(0, length);
//cout << sdata << endl;
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side of the road.
auto sensor_fusion = j[1]["sensor_fusion"];
json msgJson;
vector<double> next_x_vals;
vector<double> next_y_vals;
// TODO: define a path made up of (x,y) points that the car will visit sequentially every .02 seconds
double dist_inc = 0.5;
for(int i=0; i<50; ++i) {
// use i+1 instead of i, else the first point will be exactly where the car is at
// and it won't be transitioning
double next_s = car_s + dist_inc * (i + 1);
// we are in the middle lane
// the waypoints are measured from the double yellow lane in the middle of the road
// so we're about 1.5 lanes from where the waypoints are
// Each lane is 4m wide. To stay in the middle of the current lane, d should be 1.5 * 4 = 6
double next_d = 6;
vector<double> xy = getXY(next_s, next_d, map_waypoints_s, map_waypoints_x, map_waypoints_y);
next_x_vals.push_back(xy.at(0));
next_y_vals.push_back(xy.at(1));
}
// END
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
//this_thread::sleep_for(chrono::milliseconds(1000));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the
// program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
<commit_msg>Reduce distance increment to prevent exceeding speed limit<commit_after>#include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"
using namespace std;
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() {
return M_PI;
}
double deg2rad(double x) {
return x * pi() / 180;
}
double rad2deg(double x) {
return x * 180 / pi();
}
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_first_of("}");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
double distance(double x1, double y1, double x2, double y2) {
return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
int ClosestWaypoint(double x, double y, vector<double> maps_x,
vector<double> maps_y) {
double closestLen = 100000; //large number
int closestWaypoint = 0;
for (int i = 0; i < maps_x.size(); i++) {
double map_x = maps_x[i];
double map_y = maps_y[i];
double dist = distance(x, y, map_x, map_y);
if (dist < closestLen) {
closestLen = dist;
closestWaypoint = i;
}
}
return closestWaypoint;
}
int NextWaypoint(double x, double y, double theta, vector<double> maps_x,
vector<double> maps_y) {
int closestWaypoint = ClosestWaypoint(x, y, maps_x, maps_y);
double map_x = maps_x[closestWaypoint];
double map_y = maps_y[closestWaypoint];
double heading = atan2((map_y - y), (map_x - x));
double angle = abs(theta - heading);
if (angle > pi() / 4) {
closestWaypoint++;
}
return closestWaypoint;
}
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta,
vector<double> maps_x, vector<double> maps_y) {
int next_wp = NextWaypoint(x, y, theta, maps_x, maps_y);
int prev_wp;
prev_wp = next_wp - 1;
if (next_wp == 0) {
prev_wp = maps_x.size() - 1;
}
double n_x = maps_x[next_wp] - maps_x[prev_wp];
double n_y = maps_y[next_wp] - maps_y[prev_wp];
double x_x = x - maps_x[prev_wp];
double x_y = y - maps_y[prev_wp];
// find the projection of x onto n
double proj_norm = (x_x * n_x + x_y * n_y) / (n_x * n_x + n_y * n_y);
double proj_x = proj_norm * n_x;
double proj_y = proj_norm * n_y;
double frenet_d = distance(x_x, x_y, proj_x, proj_y);
//see if d value is positive or negative by comparing it to a center point
double center_x = 1000 - maps_x[prev_wp];
double center_y = 2000 - maps_y[prev_wp];
double centerToPos = distance(center_x, center_y, x_x, x_y);
double centerToRef = distance(center_x, center_y, proj_x, proj_y);
if (centerToPos <= centerToRef) {
frenet_d *= -1;
}
// calculate s value
double frenet_s = 0;
for (int i = 0; i < prev_wp; i++) {
frenet_s += distance(maps_x[i], maps_y[i], maps_x[i + 1],
maps_y[i + 1]);
}
frenet_s += distance(0, 0, proj_x, proj_y);
return {frenet_s,frenet_d};
}
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, vector<double> maps_s,
vector<double> maps_x, vector<double> maps_y) {
int prev_wp = -1;
while (s > maps_s[prev_wp + 1] && (prev_wp < (int) (maps_s.size() - 1))) {
prev_wp++;
}
int wp2 = (prev_wp + 1) % maps_x.size();
double heading = atan2((maps_y[wp2] - maps_y[prev_wp]),
(maps_x[wp2] - maps_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s - maps_s[prev_wp]);
double seg_x = maps_x[prev_wp] + seg_s * cos(heading);
double seg_y = maps_y[prev_wp] + seg_s * sin(heading);
double perp_heading = heading - pi() / 2;
double x = seg_x + d * cos(perp_heading);
double y = seg_y + d * sin(perp_heading);
return {x,y};
}
int main() {
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
// Waypoint map to read from
string map_file_ = "../data/highway_map.csv";
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
ifstream in_map_(map_file_.c_str(), ifstream::in);
string line;
while (getline(in_map_, line)) {
istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_waypoints_x.push_back(x);
map_waypoints_y.push_back(y);
map_waypoints_s.push_back(s);
map_waypoints_dx.push_back(d_x);
map_waypoints_dy.push_back(d_y);
}
h.onMessage(
[&map_waypoints_x,&map_waypoints_y,&map_waypoints_s,&map_waypoints_dx,&map_waypoints_dy](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
//auto sdata = string(data).substr(0, length);
//cout << sdata << endl;
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side of the road.
auto sensor_fusion = j[1]["sensor_fusion"];
json msgJson;
vector<double> next_x_vals;
vector<double> next_y_vals;
// TODO: define a path made up of (x,y) points that the car will visit sequentially every .02 seconds
double dist_inc = 0.3;
for(int i=0; i<50; ++i) {
// use i+1 instead of i, else the first point will be exactly where the car is at
// and it won't be transitioning
double next_s = car_s + dist_inc * (i + 1);
// we are in the middle lane
// the waypoints are measured from the double yellow lane in the middle of the road
// so we're about 1.5 lanes from where the waypoints are
// Each lane is 4m wide. To stay in the middle of the current lane, d should be 1.5 * 4 = 6
double next_d = 6;
vector<double> xy = getXY(next_s, next_d, map_waypoints_s, map_waypoints_x, map_waypoints_y);
next_x_vals.push_back(xy.at(0));
next_y_vals.push_back(xy.at(1));
}
// END
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
//this_thread::sleep_for(chrono::milliseconds(1000));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the
// program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "assert.hpp"
#include "Variable.hpp"
#include "Type.hpp"
#include "mtac/LiveVariableAnalysisProblem.hpp"
#include "mtac/Utils.hpp"
using namespace eddic;
typedef mtac::LiveVariableAnalysisProblem::ProblemDomain ProblemDomain;
std::ostream& mtac::operator<<(std::ostream& stream, mtac::LiveVariableValues& value){
stream << "set{";
for(auto& v : value){
if(!v){
stream << "null, ";
} else {
stream << v->name() << ", ";
}
}
return stream << "}";
}
mtac::LiveVariableAnalysisProblem::LiveVariableAnalysisProblem(){
pointer_escaped = std::make_shared<Values>();
}
void mtac::LiveVariableAnalysisProblem::Gather(std::shared_ptr<mtac::Function> function){
for(auto& block : function->getBasicBlocks()){
for(auto& statement : block->statements){
//Passing a variable as param by address escape its liveness
if(auto* ptr = boost::get<std::shared_ptr<mtac::Param>>(&statement)){
auto& param = *ptr;
if(param->address){
if(mtac::isVariable(param->arg)){
escaped_variables.insert(boost::get<std::shared_ptr<Variable>>(param->arg));
}
}
}
//Taking the address of a variable escape its liveness
else if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto& quadruple = *ptr;
if(quadruple->op == mtac::Operator::PASSIGN){
if(quadruple->arg1 && mtac::isVariable(*quadruple->arg1)){
auto var = boost::get<std::shared_ptr<Variable>>(*quadruple->arg1);
escaped_variables.insert(var);
pointer_escaped->insert(var);
}
} else if(quadruple->op == mtac::Operator::DOT_PASSIGN){
if(quadruple->arg2 && mtac::isVariable(*quadruple->arg2)){
auto var = boost::get<std::shared_ptr<Variable>>(*quadruple->arg2);
escaped_variables.insert(var);
pointer_escaped->insert(var);
}
}
}
}
}
}
ProblemDomain mtac::LiveVariableAnalysisProblem::Boundary(std::shared_ptr<mtac::Function> /*function*/){
auto value = default_element();
value.values().pointer_escaped = pointer_escaped;
return value;
}
ProblemDomain mtac::LiveVariableAnalysisProblem::Init(std::shared_ptr<mtac::Function> /*function*/){
auto value = default_element();
value.values().pointer_escaped = pointer_escaped;
return value;
}
ProblemDomain mtac::LiveVariableAnalysisProblem::meet(ProblemDomain& out, ProblemDomain& in){
if(out.top()){
return in;
} else if(in.top()){
return out;
}
typename ProblemDomain::Values values;
ProblemDomain result(values);
result.values().pointer_escaped = pointer_escaped;
for(auto& value : in.values()){
result.values().insert(value);
}
for(auto& value : out.values()){
result.values().insert(value);
}
return result;
}
template<typename Arg, typename Values>
inline void update(Arg& arg, Values& values){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&arg)){
values.insert(*ptr);
}
}
template<typename Arg, typename Values>
inline void update_optional(Arg& arg, Values& values){
if(arg){
update(*arg, values);
}
}
ProblemDomain mtac::LiveVariableAnalysisProblem::transfer(std::shared_ptr<mtac::BasicBlock>/* basic_block*/, mtac::Statement& statement, ProblemDomain& out){
auto in = out;
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto quadruple = *ptr;
if(mtac::erase_result(quadruple->op)){
in.values().erase(quadruple->result);
} else {
in.values().insert(quadruple->result);
}
update_optional((*ptr)->arg1, in.values());
update_optional((*ptr)->arg2, in.values());
} else if(auto* ptr = boost::get<std::shared_ptr<mtac::Param>>(&statement)){
update((*ptr)->arg, in.values());
} else if(auto* ptr = boost::get<std::shared_ptr<mtac::IfFalse>>(&statement)){
update((*ptr)->arg1, in.values());
update_optional((*ptr)->arg2, in.values());
} else if(auto* ptr = boost::get<std::shared_ptr<mtac::If>>(&statement)){
update((*ptr)->arg1, in.values());
update_optional((*ptr)->arg2, in.values());
}
for(auto& escaped_var : escaped_variables){
in.values().insert(escaped_var);
}
return in;
}
bool mtac::LiveVariableAnalysisProblem::optimize(mtac::Statement& /*statement*/, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>>& /*global_results*/){
//This analysis is only made to gather information, not to optimize anything
throw "Unimplemented";
}
<commit_msg>Fix live variable analysis<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "assert.hpp"
#include "Variable.hpp"
#include "Type.hpp"
#include "mtac/LiveVariableAnalysisProblem.hpp"
#include "mtac/Utils.hpp"
using namespace eddic;
typedef mtac::LiveVariableAnalysisProblem::ProblemDomain ProblemDomain;
std::ostream& mtac::operator<<(std::ostream& stream, mtac::LiveVariableValues& value){
stream << "set{";
for(auto& v : value){
if(!v){
stream << "null, ";
} else {
stream << v->name() << ", ";
}
}
return stream << "}";
}
mtac::LiveVariableAnalysisProblem::LiveVariableAnalysisProblem(){
pointer_escaped = std::make_shared<Values>();
}
void mtac::LiveVariableAnalysisProblem::Gather(std::shared_ptr<mtac::Function> function){
for(auto& block : function->getBasicBlocks()){
for(auto& statement : block->statements){
//Passing a variable as param by address escape its liveness
if(auto* ptr = boost::get<std::shared_ptr<mtac::Param>>(&statement)){
auto& param = *ptr;
if(param->address){
if(mtac::isVariable(param->arg)){
auto var = boost::get<std::shared_ptr<Variable>>(param->arg);
escaped_variables.insert(var);
pointer_escaped->insert(var);
}
}
}
//Taking the address of a variable escape its liveness
else if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto& quadruple = *ptr;
if(quadruple->op == mtac::Operator::PASSIGN){
if(quadruple->arg1 && mtac::isVariable(*quadruple->arg1)){
auto var = boost::get<std::shared_ptr<Variable>>(*quadruple->arg1);
escaped_variables.insert(var);
pointer_escaped->insert(var);
}
} else if(quadruple->op == mtac::Operator::DOT_PASSIGN){
if(quadruple->arg2 && mtac::isVariable(*quadruple->arg2)){
auto var = boost::get<std::shared_ptr<Variable>>(*quadruple->arg2);
escaped_variables.insert(var);
pointer_escaped->insert(var);
}
}
}
}
}
}
ProblemDomain mtac::LiveVariableAnalysisProblem::Boundary(std::shared_ptr<mtac::Function> /*function*/){
auto value = default_element();
value.values().pointer_escaped = pointer_escaped;
return value;
}
ProblemDomain mtac::LiveVariableAnalysisProblem::Init(std::shared_ptr<mtac::Function> /*function*/){
auto value = default_element();
value.values().pointer_escaped = pointer_escaped;
return value;
}
ProblemDomain mtac::LiveVariableAnalysisProblem::meet(ProblemDomain& out, ProblemDomain& in){
if(out.top()){
return in;
} else if(in.top()){
return out;
}
typename ProblemDomain::Values values;
ProblemDomain result(values);
result.values().pointer_escaped = pointer_escaped;
for(auto& value : in.values()){
result.values().insert(value);
}
for(auto& value : out.values()){
result.values().insert(value);
}
return result;
}
template<typename Arg, typename Values>
inline void update(Arg& arg, Values& values){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&arg)){
values.insert(*ptr);
}
}
template<typename Arg, typename Values>
inline void update_optional(Arg& arg, Values& values){
if(arg){
update(*arg, values);
}
}
ProblemDomain mtac::LiveVariableAnalysisProblem::transfer(std::shared_ptr<mtac::BasicBlock>/* basic_block*/, mtac::Statement& statement, ProblemDomain& out){
auto in = out;
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto quadruple = *ptr;
if(mtac::erase_result(quadruple->op)){
in.values().erase(quadruple->result);
} else {
in.values().insert(quadruple->result);
}
update_optional((*ptr)->arg1, in.values());
update_optional((*ptr)->arg2, in.values());
} else if(auto* ptr = boost::get<std::shared_ptr<mtac::Param>>(&statement)){
update((*ptr)->arg, in.values());
} else if(auto* ptr = boost::get<std::shared_ptr<mtac::IfFalse>>(&statement)){
update((*ptr)->arg1, in.values());
update_optional((*ptr)->arg2, in.values());
} else if(auto* ptr = boost::get<std::shared_ptr<mtac::If>>(&statement)){
update((*ptr)->arg1, in.values());
update_optional((*ptr)->arg2, in.values());
}
for(auto& escaped_var : escaped_variables){
in.values().insert(escaped_var);
}
return in;
}
bool mtac::LiveVariableAnalysisProblem::optimize(mtac::Statement& /*statement*/, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>>& /*global_results*/){
//This analysis is only made to gather information, not to optimize anything
throw "Unimplemented";
}
<|endoftext|> |
<commit_before>/// \file
/// \ingroup tutorial_roofit
/// \notebook -nodraw
///
/// Extended maximum likelihood fit with alternate range definition
/// for observed number of events.
/// If multiple ranges are used, or only a part of the data is fitted,
/// it is advisable to use a RooAddPdf to extend the model. See tutorial
/// 204a.
///
/// \macro_output
/// \macro_code
///
/// \date 07/2008
/// \author Wouter Verkerke
#include "RooRealVar.h"
#include "RooDataSet.h"
#include "RooGaussian.h"
#include "RooChebychev.h"
#include "RooAddPdf.h"
#include "RooExtendPdf.h"
#include "RooFitResult.h"
#include "TCanvas.h"
#include "TAxis.h"
#include "RooPlot.h"
using namespace RooFit;
void rf204_extrangefit()
{
// S e t u p c o m p o n e n t p d f s
// ---------------------------------------
// Declare observable x
RooRealVar x("x", "x", 0, 10);
// Create two Gaussian PDFs g1(x,mean1,sigma) anf g2(x,mean2,sigma) and their parameters
RooRealVar mean("mean", "mean of gaussians", 5);
RooRealVar sigma1("sigma1", "width of gaussians", 0.5);
RooRealVar sigma2("sigma2", "width of gaussians", 1);
RooGaussian sig1("sig1", "Signal component 1", x, mean, sigma1);
RooGaussian sig2("sig2", "Signal component 2", x, mean, sigma2);
// Build Chebychev polynomial p.d.f.
RooRealVar a0("a0", "a0", 0.5, 0., 1.);
RooRealVar a1("a1", "a1", 0.2, 0., 1.);
RooChebychev bkg("bkg", "Background", x, RooArgSet(a0, a1));
// Sum the signal components into a composite signal p.d.f.
RooRealVar sig1frac("sig1frac", "fraction of component 1 in signal", 0.8, 0., 1.);
RooAddPdf sig("sig", "Signal", RooArgList(sig1, sig2), sig1frac);
// C o n s t r u c t e x t e n d e d c o m p s wi t h r a n g e s p e c
// ------------------------------------------------------------------------------
// Define signal range in which events counts are to be defined
x.setRange("signalRange", 4, 6);
// Associated nsig/nbkg as expected number of events with sig/bkg _in_the_range_ "signalRange"
RooRealVar nsig("nsig", "number of signal events in signalRange", 500, 0., 10000) ;
RooRealVar nbkg("nbkg", "number of background events in signalRange", 500, 0, 10000) ;
// Use AddPdf to extend the model:
RooAddPdf model("model","(g1+g2)+a", RooArgList(bkg,sig), RooArgList(nbkg,nsig)) ;
// Clone these models here because the interpretation of normalisation coefficients changes
// when different ranges are used:
RooAddPdf model2(model);
RooAddPdf model3(model);
// S a m p l e d a t a , f i t m o d e l
// -------------------------------------------
// Generate 1000 events from model so that nsig,nbkg come out to numbers <<500 in fit
RooDataSet *data = model.generate(x, 1000);
auto canv = new TCanvas("Canvas", "Canvas", 1500, 600);
canv->Divide(3,1);
// Fit full range
// -------------------------------------------
canv->cd(1);
// Perform unbinned ML fit to data, full range
RooFitResult* r = model.fitTo(*data,Save()) ;
r->Print() ;
}
<commit_msg>[RF] Remove outdated tutorial.<commit_after><|endoftext|> |
<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2016 cDc <[email protected]>, Pierre MOULON
// 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/.
#include "openMVG/image/image_io.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#define _USE_EIGEN
#include "InterfaceMVS.h"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"
using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::geometry;
using namespace openMVG::image;
using namespace openMVG::sfm;
#include <cstdlib>
#include <string>
bool exportToOpenMVS(
const SfM_Data & sfm_data,
const std::string & sOutFile,
const std::string & sOutDir
)
{
// Create undistorted images directory structure
if (!stlplus::is_folder(sOutDir))
{
stlplus::folder_create(sOutDir);
if (!stlplus::is_folder(sOutDir))
{
std::cerr << "Cannot access to one of the desired output directory" << std::endl;
return false;
}
}
// Export data :
MVS::Interface scene;
size_t nPoses(0);
const uint32_t nViews((uint32_t)sfm_data.GetViews().size());
C_Progress_display my_progress_bar(nViews);
// OpenMVG can have not contiguous index, use a map to create the required OpenMVS contiguous ID index
std::map<openMVG::IndexT, uint32_t> map_intrinsic, map_view;
// define a platform with all the intrinsic group
for (const auto& intrinsic: sfm_data.GetIntrinsics())
{
if (isPinhole(intrinsic.second.get()->getType()))
{
const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(intrinsic.second.get());
if (map_intrinsic.count(intrinsic.first) == 0)
map_intrinsic.insert(std::make_pair(intrinsic.first, scene.platforms.size()));
MVS::Interface::Platform platform;
// add the camera
MVS::Interface::Platform::Camera camera;
camera.K = cam->K();
// sub-pose
camera.R = Mat3::Identity();
camera.C = Vec3::Zero();
platform.cameras.push_back(camera);
scene.platforms.push_back(platform);
}
}
// define images & poses
scene.images.reserve(nViews);
for (const auto& view : sfm_data.GetViews())
{
map_view[view.first] = scene.images.size();
MVS::Interface::Image image;
const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view.second->s_Img_path);
image.name = stlplus::create_filespec(sOutDir, view.second->s_Img_path);
image.platformID = map_intrinsic.at(view.second->id_intrinsic);
MVS::Interface::Platform& platform = scene.platforms[image.platformID];
image.cameraID = 0;
if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()) && stlplus::is_file(srcImage))
{
MVS::Interface::Platform::Pose pose;
image.poseID = platform.poses.size();
const openMVG::geometry::Pose3 poseMVG(sfm_data.GetPoseOrDie(view.second.get()));
pose.R = poseMVG.rotation();
pose.C = poseMVG.center();
// export undistorted images
const openMVG::cameras::IntrinsicBase * cam = sfm_data.GetIntrinsics().at(view.second->id_intrinsic).get();
if (cam->have_disto())
{
// undistort image and save it
Image<openMVG::image::RGBColor> imageRGB, imageRGB_ud;
ReadImage(srcImage.c_str(), &imageRGB);
UndistortImage(imageRGB, cam, imageRGB_ud, BLACK);
WriteImage(image.name.c_str(), imageRGB_ud);
}
else
{
// just copy image
stlplus::file_copy(srcImage, image.name);
}
platform.poses.push_back(pose);
++nPoses;
}
else
{
// image have not valid pose, so set an undefined pose
image.poseID = NO_ID;
// just copy the image
stlplus::file_copy(srcImage, image.name);
}
scene.images.push_back(image);
++my_progress_bar;
}
// define structure
scene.vertices.reserve(sfm_data.GetLandmarks().size());
for (const auto& vertex: sfm_data.GetLandmarks())
{
const Landmark & landmark = vertex.second;
MVS::Interface::Vertex vert;
MVS::Interface::Vertex::ViewArr& views = vert.views;
for (const auto& observation: landmark.obs)
{
const auto it(map_view.find(observation.first));
if (it != map_view.end()) {
MVS::Interface::Vertex::View view;
view.imageID = it->second;
view.confidence = 0;
views.push_back(view);
}
}
if (views.size() < 2)
continue;
std::sort(
views.begin(), views.end(),
[] (const MVS::Interface::Vertex::View& view0, const MVS::Interface::Vertex::View& view1)
{
return view0.imageID < view1.imageID;
}
);
vert.X = landmark.X.cast<float>();
scene.vertices.push_back(vert);
}
// normalize camera intrinsics
for (size_t p=0; p<scene.platforms.size(); ++p)
{
MVS::Interface::Platform& platform = scene.platforms[p];
for (size_t c=0; c<platform.cameras.size(); ++c) {
MVS::Interface::Platform::Camera& camera = platform.cameras[c];
// find one image using this camera
MVS::Interface::Image* pImage(NULL);
for (MVS::Interface::Image& image: scene.images)
{
if (image.platformID == p && image.cameraID == c && image.poseID != NO_ID)
{
pImage = ℑ
break;
}
}
if (pImage == NULL)
{
std::cerr << "error: no image using camera " << c << " of platform " << p << std::endl;
continue;
}
// read image meta-data
ImageHeader imageHeader;
ReadImageHeader(pImage->name.c_str(), &imageHeader);
const double fScale(1.0/std::max(imageHeader.width, imageHeader.height));
camera.K(0, 0) *= fScale;
camera.K(1, 1) *= fScale;
camera.K(0, 2) *= fScale;
camera.K(1, 2) *= fScale;
}
}
// write OpenMVS data
if (!ARCHIVE::SerializeSave(scene, sOutFile))
return false;
std::cout
<< "Scene saved to OpenMVS interface format:\n"
<< "\t" << scene.images.size() << " images (" << nPoses << " calibrated)\n"
<< "\t" << scene.vertices.size() << " Landmarks\n";
return true;
}
int main(int argc, char *argv[])
{
CmdLine cmd;
std::string sSfM_Data_Filename;
std::string sOutFile = "scene.mvs";
std::string sOutDir = "undistorted_images";
cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") );
cmd.add( make_option('o', sOutFile, "outfile") );
cmd.add( make_option('d', sOutDir, "outdir") );
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--sfmdata] filename, the SfM_Data file to convert\n"
<< "[-o|--outfile] OpenMVS scene file\n"
<< "[-d|--outdir] undistorted images path\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
// Read the input SfM scene
SfM_Data sfm_data;
if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) {
std::cerr << std::endl
<< "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
if (exportToOpenMVS(sfm_data, sOutFile, sOutDir))
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
<commit_msg>Fix a tab to spaces.<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2016 cDc <[email protected]>, Pierre MOULON
// 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/.
#include "openMVG/image/image_io.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#define _USE_EIGEN
#include "InterfaceMVS.h"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"
using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::geometry;
using namespace openMVG::image;
using namespace openMVG::sfm;
#include <cstdlib>
#include <string>
bool exportToOpenMVS(
const SfM_Data & sfm_data,
const std::string & sOutFile,
const std::string & sOutDir
)
{
// Create undistorted images directory structure
if (!stlplus::is_folder(sOutDir))
{
stlplus::folder_create(sOutDir);
if (!stlplus::is_folder(sOutDir))
{
std::cerr << "Cannot access to one of the desired output directory" << std::endl;
return false;
}
}
// Export data :
MVS::Interface scene;
size_t nPoses(0);
const uint32_t nViews((uint32_t)sfm_data.GetViews().size());
C_Progress_display my_progress_bar(nViews);
// OpenMVG can have not contiguous index, use a map to create the required OpenMVS contiguous ID index
std::map<openMVG::IndexT, uint32_t> map_intrinsic, map_view;
// define a platform with all the intrinsic group
for (const auto& intrinsic: sfm_data.GetIntrinsics())
{
if (isPinhole(intrinsic.second.get()->getType()))
{
const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(intrinsic.second.get());
if (map_intrinsic.count(intrinsic.first) == 0)
map_intrinsic.insert(std::make_pair(intrinsic.first, scene.platforms.size()));
MVS::Interface::Platform platform;
// add the camera
MVS::Interface::Platform::Camera camera;
camera.K = cam->K();
// sub-pose
camera.R = Mat3::Identity();
camera.C = Vec3::Zero();
platform.cameras.push_back(camera);
scene.platforms.push_back(platform);
}
}
// define images & poses
scene.images.reserve(nViews);
for (const auto& view : sfm_data.GetViews())
{
map_view[view.first] = scene.images.size();
MVS::Interface::Image image;
const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view.second->s_Img_path);
image.name = stlplus::create_filespec(sOutDir, view.second->s_Img_path);
image.platformID = map_intrinsic.at(view.second->id_intrinsic);
MVS::Interface::Platform& platform = scene.platforms[image.platformID];
image.cameraID = 0;
if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()) && stlplus::is_file(srcImage))
{
MVS::Interface::Platform::Pose pose;
image.poseID = platform.poses.size();
const openMVG::geometry::Pose3 poseMVG(sfm_data.GetPoseOrDie(view.second.get()));
pose.R = poseMVG.rotation();
pose.C = poseMVG.center();
// export undistorted images
const openMVG::cameras::IntrinsicBase * cam = sfm_data.GetIntrinsics().at(view.second->id_intrinsic).get();
if (cam->have_disto())
{
// undistort image and save it
Image<openMVG::image::RGBColor> imageRGB, imageRGB_ud;
ReadImage(srcImage.c_str(), &imageRGB);
UndistortImage(imageRGB, cam, imageRGB_ud, BLACK);
WriteImage(image.name.c_str(), imageRGB_ud);
}
else
{
// just copy image
stlplus::file_copy(srcImage, image.name);
}
platform.poses.push_back(pose);
++nPoses;
}
else
{
// image have not valid pose, so set an undefined pose
image.poseID = NO_ID;
// just copy the image
stlplus::file_copy(srcImage, image.name);
}
scene.images.push_back(image);
++my_progress_bar;
}
// define structure
scene.vertices.reserve(sfm_data.GetLandmarks().size());
for (const auto& vertex: sfm_data.GetLandmarks())
{
const Landmark & landmark = vertex.second;
MVS::Interface::Vertex vert;
MVS::Interface::Vertex::ViewArr& views = vert.views;
for (const auto& observation: landmark.obs)
{
const auto it(map_view.find(observation.first));
if (it != map_view.end()) {
MVS::Interface::Vertex::View view;
view.imageID = it->second;
view.confidence = 0;
views.push_back(view);
}
}
if (views.size() < 2)
continue;
std::sort(
views.begin(), views.end(),
[] (const MVS::Interface::Vertex::View& view0, const MVS::Interface::Vertex::View& view1)
{
return view0.imageID < view1.imageID;
}
);
vert.X = landmark.X.cast<float>();
scene.vertices.push_back(vert);
}
// normalize camera intrinsics
for (size_t p=0; p<scene.platforms.size(); ++p)
{
MVS::Interface::Platform& platform = scene.platforms[p];
for (size_t c=0; c<platform.cameras.size(); ++c) {
MVS::Interface::Platform::Camera& camera = platform.cameras[c];
// find one image using this camera
MVS::Interface::Image* pImage(NULL);
for (MVS::Interface::Image& image: scene.images)
{
if (image.platformID == p && image.cameraID == c && image.poseID != NO_ID)
{
pImage = ℑ
break;
}
}
if (pImage == NULL)
{
std::cerr << "error: no image using camera " << c << " of platform " << p << std::endl;
continue;
}
// read image meta-data
ImageHeader imageHeader;
ReadImageHeader(pImage->name.c_str(), &imageHeader);
const double fScale(1.0/std::max(imageHeader.width, imageHeader.height));
camera.K(0, 0) *= fScale;
camera.K(1, 1) *= fScale;
camera.K(0, 2) *= fScale;
camera.K(1, 2) *= fScale;
}
}
// write OpenMVS data
if (!ARCHIVE::SerializeSave(scene, sOutFile))
return false;
std::cout
<< "Scene saved to OpenMVS interface format:\n"
<< "\t" << scene.images.size() << " images (" << nPoses << " calibrated)\n"
<< "\t" << scene.vertices.size() << " Landmarks\n";
return true;
}
int main(int argc, char *argv[])
{
CmdLine cmd;
std::string sSfM_Data_Filename;
std::string sOutFile = "scene.mvs";
std::string sOutDir = "undistorted_images";
cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") );
cmd.add( make_option('o', sOutFile, "outfile") );
cmd.add( make_option('d', sOutDir, "outdir") );
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--sfmdata] filename, the SfM_Data file to convert\n"
<< "[-o|--outfile] OpenMVS scene file\n"
<< "[-d|--outdir] undistorted images path\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
// Read the input SfM scene
SfM_Data sfm_data;
if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) {
std::cerr << std::endl
<< "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
if (exportToOpenMVS(sfm_data, sOutFile, sOutDir))
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>// Copyright 2019 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#include <cinttypes>
#include "pw_boot_armv7m/boot.h"
#include "pw_preprocessor/compiler.h"
#include "pw_sys_io/sys_io.h"
namespace {
// Default core clock. This is technically not a constant, but since this app
// doesn't change the system clock a constant will suffice.
constexpr uint32_t kSystemCoreClock = 16000000;
// Base address for everything peripheral-related on the STM32F4xx.
constexpr uint32_t kPeripheralBaseAddr = 0x40000000u;
// Base address for everything AHB1-related on the STM32F4xx.
constexpr uint32_t kAhb1PeripheralBase = kPeripheralBaseAddr + 0x00020000U;
// Base address for everything APB2-related on the STM32F4xx.
constexpr uint32_t kApb2PeripheralBase = kPeripheralBaseAddr + 0x00010000U;
// Reset/clock configuration block (RCC).
// `reserved` fields are unimplemented features, and are present to ensure
// proper alignment of registers that are in use.
PW_PACKED(struct) RccBlock {
uint32_t reserved1[12];
uint32_t ahb1_config;
uint32_t reserved2[4];
uint32_t apb2_config;
};
// Mask for ahb1_config (AHB1ENR) to enable the "A" GPIO pins.
constexpr uint32_t kGpioAEnable = 0x1u;
// Mask for apb2_config (APB2ENR) to enable USART1.
constexpr uint32_t kUsart1Enable = 0x1u << 4;
// GPIO register block definition.
PW_PACKED(struct) GpioBlock {
uint32_t modes;
uint32_t out_type;
uint32_t out_speed;
uint32_t pull_up_down;
uint32_t input_data;
uint32_t output_data;
uint32_t gpio_bit_set;
uint32_t port_config_lock;
uint32_t alt_low;
uint32_t alt_high;
};
// Constants related to GPIO mode register masks.
constexpr uint32_t kGpioPortModeMask = 0x3u;
constexpr uint32_t kGpio9PortModePos = 18;
constexpr uint32_t kGpio10PortModePos = 20;
constexpr uint32_t kGpioPortModeAlternate = 2;
// Constants related to GPIO port speed register masks.
constexpr uint32_t kGpioPortSpeedMask = 0x3u;
constexpr uint32_t kGpio9PortSpeedPos = 18;
constexpr uint32_t kGpio10PortSpeedPos = 20;
constexpr uint32_t kGpioSpeedVeryHigh = 3;
// Constants related to GPIO pull up/down resistor type masks.
constexpr uint32_t kGpioPullTypeMask = 0x3u;
constexpr uint32_t kGpio9PullTypePos = 18;
constexpr uint32_t kGpio10PullTypePos = 20;
constexpr uint32_t kPullTypePullUp = 1;
// Constants related to GPIO port speed register masks.
constexpr uint32_t kGpioAltModeMask = 0x3u;
constexpr uint32_t kGpio9AltModeHighPos = 4;
constexpr uint32_t kGpio10AltModeHighPos = 8;
// Alternate function for pins A9 and A10 that enable USART1.
constexpr uint8_t kGpioAlternateFunctionUsart1 = 0x07u;
// USART status flags.
constexpr uint32_t kTxRegisterEmpty = 0x1u << 7;
// USART configuration flags for config1 register.
// Note: a large number of configuration flags have been omitted as they default
// to sane values and we don't need to change them.
constexpr uint32_t kReceiveEnable = 0x1 << 2;
constexpr uint32_t kTransmitEnable = 0x1 << 3;
constexpr uint32_t kReadDataReady = 0x1u << 5;
constexpr uint32_t kEnableUsart = 0x1 << 13;
// Layout of memory mapped registers for USART blocks.
PW_PACKED(struct) UsartBlock {
uint32_t status;
// Only the lower 8 bits are valid. Read for RX data, write to TX data.
uint32_t data_register;
uint32_t baud_rate;
uint32_t config1;
uint32_t config2;
uint32_t config3;
uint32_t config4;
};
// Sets the UART baud register using the peripheral clock and target baud rate.
// These calculations are specific to the default oversample by 16 mode.
// TODO(amontanez): Document magic calculations in full UART implementation.
uint32_t CalcBaudRegister(uint32_t clock, uint32_t target_baud) {
uint32_t div_fac = (clock * 25) / (4 * target_baud);
uint32_t mantissa = div_fac / 100;
uint32_t fraction = ((div_fac - mantissa * 100) * 16 + 50) / 100;
return (mantissa << 4) + (fraction & 0xFFu);
}
// Declare a reference to the memory mapped RCC block.
volatile RccBlock& platform_rcc =
*reinterpret_cast<volatile RccBlock*>(kAhb1PeripheralBase + 0x3800U);
// Declare a reference to the 'A' GPIO memory mapped block.
volatile GpioBlock& gpio_a =
*reinterpret_cast<volatile GpioBlock*>(kAhb1PeripheralBase + 0x0000U);
// Declare a reference to the memory mapped block for USART1.
volatile UsartBlock& usart1 =
*reinterpret_cast<volatile UsartBlock*>(kApb2PeripheralBase + 0x1000U);
} // namespace
extern "C" void pw_sys_io_Init() {
// Enable 'A' GIPO clocks.
platform_rcc.ahb1_config |= kGpioAEnable;
// Enable Uart TX pin.
// Output type defaults to push-pull (rather than open/drain).
gpio_a.modes |= kGpioPortModeAlternate << kGpio9PortModePos;
gpio_a.out_speed |= kGpioSpeedVeryHigh << kGpio9PortSpeedPos;
gpio_a.pull_up_down |= kPullTypePullUp << kGpio9PullTypePos;
gpio_a.alt_high |= kGpioAlternateFunctionUsart1 << kGpio9AltModeHighPos;
// Enable Uart RX pin.
// Output type defaults to push-pull (rather than open/drain).
gpio_a.modes |= kGpioPortModeAlternate << kGpio10PortModePos;
gpio_a.out_speed |= kGpioSpeedVeryHigh << kGpio10PortSpeedPos;
gpio_a.pull_up_down |= kPullTypePullUp << kGpio10PullTypePos;
gpio_a.alt_high |= kGpioAlternateFunctionUsart1 << kGpio10AltModeHighPos;
// Initialize USART1. Initialized to 8N1 at the specified baud rate.
platform_rcc.apb2_config |= kUsart1Enable;
// Warning: Normally the baud rate register calculation is based off
// peripheral 2 clock. For this code, the peripheral clock defaults to
// the system core clock so it can be used directly.
usart1.baud_rate = CalcBaudRegister(kSystemCoreClock, /*target_baud=*/115200);
usart1.config1 = kEnableUsart | kReceiveEnable | kTransmitEnable;
}
namespace pw::sys_io {
// Wait for a byte to read on USART1. This blocks until a byte is read. This is
// extremely inefficient as it requires the target to burn CPU cycles polling to
// see if a byte is ready yet.
Status ReadByte(std::byte* dest) {
while (true) {
if (usart1.status & kReadDataReady) {
*dest = static_cast<std::byte>(usart1.data_register);
}
}
return Status::OK;
}
// Send a byte over USART1. Since this blocks on every byte, it's rather
// inefficient. At the default baud rate of 115200, one byte blocks the CPU for
// ~87 micro seconds. This means it takes only 10 bytes to block the CPU for
// 1ms!
Status WriteByte(std::byte b) {
// Wait for TX buffer to be empty. When the buffer is empty, we can write
// a value to be dumped out of UART.
while (!(usart1.status & kTxRegisterEmpty)) {
}
usart1.data_register = static_cast<uint32_t>(b);
return Status::OK;
}
// Writes a string using pw::sys_io, and add newline characters at the end.
StatusWithSize WriteLine(const std::string_view& s) {
size_t chars_written = 0;
StatusWithSize result = WriteBytes(std::as_bytes(std::span(s)));
if (!result.ok()) {
return result;
}
chars_written += result.size();
// Write trailing newline.
result = WriteBytes(std::as_bytes(std::span("\r\n", 2)));
chars_written += result.size();
return StatusWithSize(result.status(), chars_written);
}
} // namespace pw::sys_io
<commit_msg>pw_sys_io: Fix stm32f429i ReadByte()<commit_after>// Copyright 2019 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#include <cinttypes>
#include "pw_boot_armv7m/boot.h"
#include "pw_preprocessor/compiler.h"
#include "pw_sys_io/sys_io.h"
namespace {
// Default core clock. This is technically not a constant, but since this app
// doesn't change the system clock a constant will suffice.
constexpr uint32_t kSystemCoreClock = 16000000;
// Base address for everything peripheral-related on the STM32F4xx.
constexpr uint32_t kPeripheralBaseAddr = 0x40000000u;
// Base address for everything AHB1-related on the STM32F4xx.
constexpr uint32_t kAhb1PeripheralBase = kPeripheralBaseAddr + 0x00020000U;
// Base address for everything APB2-related on the STM32F4xx.
constexpr uint32_t kApb2PeripheralBase = kPeripheralBaseAddr + 0x00010000U;
// Reset/clock configuration block (RCC).
// `reserved` fields are unimplemented features, and are present to ensure
// proper alignment of registers that are in use.
PW_PACKED(struct) RccBlock {
uint32_t reserved1[12];
uint32_t ahb1_config;
uint32_t reserved2[4];
uint32_t apb2_config;
};
// Mask for ahb1_config (AHB1ENR) to enable the "A" GPIO pins.
constexpr uint32_t kGpioAEnable = 0x1u;
// Mask for apb2_config (APB2ENR) to enable USART1.
constexpr uint32_t kUsart1Enable = 0x1u << 4;
// GPIO register block definition.
PW_PACKED(struct) GpioBlock {
uint32_t modes;
uint32_t out_type;
uint32_t out_speed;
uint32_t pull_up_down;
uint32_t input_data;
uint32_t output_data;
uint32_t gpio_bit_set;
uint32_t port_config_lock;
uint32_t alt_low;
uint32_t alt_high;
};
// Constants related to GPIO mode register masks.
constexpr uint32_t kGpioPortModeMask = 0x3u;
constexpr uint32_t kGpio9PortModePos = 18;
constexpr uint32_t kGpio10PortModePos = 20;
constexpr uint32_t kGpioPortModeAlternate = 2;
// Constants related to GPIO port speed register masks.
constexpr uint32_t kGpioPortSpeedMask = 0x3u;
constexpr uint32_t kGpio9PortSpeedPos = 18;
constexpr uint32_t kGpio10PortSpeedPos = 20;
constexpr uint32_t kGpioSpeedVeryHigh = 3;
// Constants related to GPIO pull up/down resistor type masks.
constexpr uint32_t kGpioPullTypeMask = 0x3u;
constexpr uint32_t kGpio9PullTypePos = 18;
constexpr uint32_t kGpio10PullTypePos = 20;
constexpr uint32_t kPullTypePullUp = 1;
// Constants related to GPIO port speed register masks.
constexpr uint32_t kGpioAltModeMask = 0x3u;
constexpr uint32_t kGpio9AltModeHighPos = 4;
constexpr uint32_t kGpio10AltModeHighPos = 8;
// Alternate function for pins A9 and A10 that enable USART1.
constexpr uint8_t kGpioAlternateFunctionUsart1 = 0x07u;
// USART status flags.
constexpr uint32_t kTxRegisterEmpty = 0x1u << 7;
// USART configuration flags for config1 register.
// Note: a large number of configuration flags have been omitted as they default
// to sane values and we don't need to change them.
constexpr uint32_t kReceiveEnable = 0x1 << 2;
constexpr uint32_t kTransmitEnable = 0x1 << 3;
constexpr uint32_t kReadDataReady = 0x1u << 5;
constexpr uint32_t kEnableUsart = 0x1 << 13;
// Layout of memory mapped registers for USART blocks.
PW_PACKED(struct) UsartBlock {
uint32_t status;
// Only the lower 8 bits are valid. Read for RX data, write to TX data.
uint32_t data_register;
uint32_t baud_rate;
uint32_t config1;
uint32_t config2;
uint32_t config3;
uint32_t config4;
};
// Sets the UART baud register using the peripheral clock and target baud rate.
// These calculations are specific to the default oversample by 16 mode.
// TODO(amontanez): Document magic calculations in full UART implementation.
uint32_t CalcBaudRegister(uint32_t clock, uint32_t target_baud) {
uint32_t div_fac = (clock * 25) / (4 * target_baud);
uint32_t mantissa = div_fac / 100;
uint32_t fraction = ((div_fac - mantissa * 100) * 16 + 50) / 100;
return (mantissa << 4) + (fraction & 0xFFu);
}
// Declare a reference to the memory mapped RCC block.
volatile RccBlock& platform_rcc =
*reinterpret_cast<volatile RccBlock*>(kAhb1PeripheralBase + 0x3800U);
// Declare a reference to the 'A' GPIO memory mapped block.
volatile GpioBlock& gpio_a =
*reinterpret_cast<volatile GpioBlock*>(kAhb1PeripheralBase + 0x0000U);
// Declare a reference to the memory mapped block for USART1.
volatile UsartBlock& usart1 =
*reinterpret_cast<volatile UsartBlock*>(kApb2PeripheralBase + 0x1000U);
} // namespace
extern "C" void pw_sys_io_Init() {
// Enable 'A' GIPO clocks.
platform_rcc.ahb1_config |= kGpioAEnable;
// Enable Uart TX pin.
// Output type defaults to push-pull (rather than open/drain).
gpio_a.modes |= kGpioPortModeAlternate << kGpio9PortModePos;
gpio_a.out_speed |= kGpioSpeedVeryHigh << kGpio9PortSpeedPos;
gpio_a.pull_up_down |= kPullTypePullUp << kGpio9PullTypePos;
gpio_a.alt_high |= kGpioAlternateFunctionUsart1 << kGpio9AltModeHighPos;
// Enable Uart RX pin.
// Output type defaults to push-pull (rather than open/drain).
gpio_a.modes |= kGpioPortModeAlternate << kGpio10PortModePos;
gpio_a.out_speed |= kGpioSpeedVeryHigh << kGpio10PortSpeedPos;
gpio_a.pull_up_down |= kPullTypePullUp << kGpio10PullTypePos;
gpio_a.alt_high |= kGpioAlternateFunctionUsart1 << kGpio10AltModeHighPos;
// Initialize USART1. Initialized to 8N1 at the specified baud rate.
platform_rcc.apb2_config |= kUsart1Enable;
// Warning: Normally the baud rate register calculation is based off
// peripheral 2 clock. For this code, the peripheral clock defaults to
// the system core clock so it can be used directly.
usart1.baud_rate = CalcBaudRegister(kSystemCoreClock, /*target_baud=*/115200);
usart1.config1 = kEnableUsart | kReceiveEnable | kTransmitEnable;
}
namespace pw::sys_io {
// Wait for a byte to read on USART1. This blocks until a byte is read. This is
// extremely inefficient as it requires the target to burn CPU cycles polling to
// see if a byte is ready yet.
Status ReadByte(std::byte* dest) {
while (true) {
if (usart1.status & kReadDataReady) {
*dest = static_cast<std::byte>(usart1.data_register);
break;
}
}
return Status::OK;
}
// Send a byte over USART1. Since this blocks on every byte, it's rather
// inefficient. At the default baud rate of 115200, one byte blocks the CPU for
// ~87 micro seconds. This means it takes only 10 bytes to block the CPU for
// 1ms!
Status WriteByte(std::byte b) {
// Wait for TX buffer to be empty. When the buffer is empty, we can write
// a value to be dumped out of UART.
while (!(usart1.status & kTxRegisterEmpty)) {
}
usart1.data_register = static_cast<uint32_t>(b);
return Status::OK;
}
// Writes a string using pw::sys_io, and add newline characters at the end.
StatusWithSize WriteLine(const std::string_view& s) {
size_t chars_written = 0;
StatusWithSize result = WriteBytes(std::as_bytes(std::span(s)));
if (!result.ok()) {
return result;
}
chars_written += result.size();
// Write trailing newline.
result = WriteBytes(std::as_bytes(std::span("\r\n", 2)));
chars_written += result.size();
return StatusWithSize(result.status(), chars_written);
}
} // namespace pw::sys_io
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebKitDLL.h"
#include "WebKit.h"
#include "WebScrollBar.h"
#pragma warning(push, 0)
#include <WebCore/GraphicsContext.h>
#include <WebCore/PlatformMouseEvent.h>
#include <WebCore/PlatformScrollBar.h>
#include <WebCore/ScrollbarTheme.h>
#pragma warning(pop)
using namespace WebCore;
// WebScrollBar ---------------------------------------------------------------------
WebScrollBar::WebScrollBar()
: m_refCount(0)
{
gClassCount++;
gClassNameCount.add("WebScrollBar");
}
WebScrollBar::~WebScrollBar()
{
gClassCount--;
gClassNameCount.remove("WebScrollBar");
}
WebScrollBar* WebScrollBar::createInstance()
{
WebScrollBar* instance = new WebScrollBar();
instance->AddRef();
return instance;
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebScrollBar::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IUnknown*>(this);
else if (IsEqualGUID(riid, IID_IWebScrollBarPrivate))
*ppvObject = static_cast<IWebScrollBarPrivate*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE WebScrollBar::AddRef(void)
{
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE WebScrollBar::Release(void)
{
ULONG newRef = --m_refCount;
if (!newRef)
delete(this);
return newRef;
}
// IWebScrollBarPrivate ------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebScrollBar::init(
/* [in] */ IWebScrollBarDelegatePrivate* delegate,
/* [in] */ OLE_HANDLE containingWindow,
/* [in] */ WebScrollBarOrientation orientation,
/* [in] */ WebScrollBarControlSize controlSize)
{
if (!delegate || !containingWindow)
return E_FAIL;
ScrollbarOrientation webCoreOrientation = (ScrollbarOrientation) orientation;
ScrollbarControlSize webCoreControlSize = (ScrollbarControlSize) controlSize;
m_delegate = delegate;
m_scrollBar = PlatformScrollbar::create(this, webCoreOrientation, webCoreControlSize);
if (!m_scrollBar)
return E_FAIL;
m_scrollBar->setContainingWindow((HWND)(ULONG64)containingWindow);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setEnabled(
/* [in] */ BOOL enabled)
{
m_scrollBar->setEnabled(!!enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setSteps(
/* [in] */ int lineStep,
/* [in] */ int pageStep)
{
m_scrollBar->setSteps(lineStep, pageStep);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setProportion(
/* [in] */ int visibleSize,
/* [in] */ int totalSize)
{
m_scrollBar->setProportion(visibleSize, totalSize);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setRect(
/* [in] */ RECT bounds)
{
IntRect rect(bounds.left, bounds.top, bounds.right-bounds.left, bounds.bottom-bounds.top);
m_scrollBar->setRect(rect);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setValue(
/* [in] */ int value)
{
m_scrollBar->setValue(value);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::value(
/* [retval][out] */ int* value)
{
if (!value)
return E_POINTER;
*value = m_scrollBar->value();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::paint(
/* [in] */ HDC dc,
/* [in] */ RECT damageRect)
{
GraphicsContext context(dc);
IntRect rect(damageRect.left, damageRect.top, damageRect.right-damageRect.left, damageRect.bottom-damageRect.top);
m_scrollBar->paint(&context, rect);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::frameGeometry(
/* [retval][out] */ RECT* bounds)
{
if (!bounds)
return E_POINTER;
IntRect rect = m_scrollBar->frameGeometry();
bounds->left = rect.x();
bounds->right = rect.right();
bounds->top = rect.y();
bounds->bottom = rect.bottom();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::width(
/* [retval][out] */ int* w)
{
if (!w)
return E_POINTER;
*w = m_scrollBar->width();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::height(
/* [retval][out] */ int* h)
{
if (!h)
return E_POINTER;
*h = m_scrollBar->height();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::requestedWidth(
/* [retval][out] */ int* w)
{
if (!w)
return E_POINTER;
*w = m_scrollBar->orientation() == VerticalScrollbar ? ScrollbarTheme::nativeTheme()->scrollbarThickness(m_scrollBar->controlSize()) : -1;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::requestedHeight(
/* [retval][out] */ int* h)
{
if (!h)
return E_POINTER;
*h = m_scrollBar->orientation() == HorizontalScrollbar ? ScrollbarTheme::nativeTheme()->scrollbarThickness(m_scrollBar->controlSize()) : -1;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::handleMouseEvent(
OLE_HANDLE window,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
PlatformMouseEvent mouseEvent((HWND)(ULONG64)window, msg, wParam, lParam);
switch (msg) {
case WM_LBUTTONDOWN:
m_scrollBar->handleMousePressEvent(mouseEvent);
break;
case WM_LBUTTONUP:
m_scrollBar->handleMouseReleaseEvent(mouseEvent);
break;
case WM_MOUSEMOVE:
m_scrollBar->handleMouseMoveEvent(mouseEvent);
break;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::scroll(
WebScrollDirection direction,
WebScrollGranularity granularity,
float multiplier)
{
ScrollDirection webCoreScrollDirection = (ScrollDirection) direction;
ScrollGranularity webCoreGranularity = (ScrollGranularity) granularity;
m_scrollBar->scroll(webCoreScrollDirection, webCoreGranularity, multiplier);
return S_OK;
}
// ScrollbarClient -------------------------------------------------------
void WebScrollBar::valueChanged(Scrollbar* scrollBar)
{
if (m_scrollBar != scrollBar) {
ASSERT(false); // shouldn't happen
return;
}
m_delegate->valueChanged(this);
}
IntRect WebScrollBar::windowClipRect() const
{
HWND sbContainingWindow = m_scrollBar->containingWindow();
RECT clientRect;
::GetClientRect(sbContainingWindow, &clientRect);
return IntRect(clientRect.left, clientRect.top, clientRect.right-clientRect.left, clientRect.bottom-clientRect.top);
}
<commit_msg>Fix Windows bustage.<commit_after>/*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebKitDLL.h"
#include "WebKit.h"
#include "WebScrollBar.h"
#pragma warning(push, 0)
#include <WebCore/GraphicsContext.h>
#include <WebCore/PlatformMouseEvent.h>
#include <WebCore/PlatformScrollBar.h>
#include <WebCore/ScrollbarTheme.h>
#pragma warning(pop)
using namespace WebCore;
// WebScrollBar ---------------------------------------------------------------------
WebScrollBar::WebScrollBar()
: m_refCount(0)
{
gClassCount++;
gClassNameCount.add("WebScrollBar");
}
WebScrollBar::~WebScrollBar()
{
gClassCount--;
gClassNameCount.remove("WebScrollBar");
}
WebScrollBar* WebScrollBar::createInstance()
{
WebScrollBar* instance = new WebScrollBar();
instance->AddRef();
return instance;
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebScrollBar::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IUnknown*>(this);
else if (IsEqualGUID(riid, IID_IWebScrollBarPrivate))
*ppvObject = static_cast<IWebScrollBarPrivate*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE WebScrollBar::AddRef(void)
{
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE WebScrollBar::Release(void)
{
ULONG newRef = --m_refCount;
if (!newRef)
delete(this);
return newRef;
}
// IWebScrollBarPrivate ------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebScrollBar::init(
/* [in] */ IWebScrollBarDelegatePrivate* delegate,
/* [in] */ OLE_HANDLE containingWindow,
/* [in] */ WebScrollBarOrientation orientation,
/* [in] */ WebScrollBarControlSize controlSize)
{
if (!delegate || !containingWindow)
return E_FAIL;
ScrollbarOrientation webCoreOrientation = (ScrollbarOrientation) orientation;
ScrollbarControlSize webCoreControlSize = (ScrollbarControlSize) controlSize;
m_delegate = delegate;
m_scrollBar = PlatformScrollbar::create(this, webCoreOrientation, webCoreControlSize);
if (!m_scrollBar)
return E_FAIL;
m_scrollBar->setContainingWindow((HWND)(ULONG64)containingWindow);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setEnabled(
/* [in] */ BOOL enabled)
{
m_scrollBar->setEnabled(!!enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setSteps(
/* [in] */ int lineStep,
/* [in] */ int pageStep)
{
m_scrollBar->setSteps(lineStep, pageStep);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setProportion(
/* [in] */ int visibleSize,
/* [in] */ int totalSize)
{
m_scrollBar->setProportion(visibleSize, totalSize);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setRect(
/* [in] */ RECT bounds)
{
IntRect rect(bounds.left, bounds.top, bounds.right-bounds.left, bounds.bottom-bounds.top);
m_scrollBar->setFrameGeometry(rect);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::setValue(
/* [in] */ int value)
{
m_scrollBar->setValue(value);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::value(
/* [retval][out] */ int* value)
{
if (!value)
return E_POINTER;
*value = m_scrollBar->value();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::paint(
/* [in] */ HDC dc,
/* [in] */ RECT damageRect)
{
GraphicsContext context(dc);
IntRect rect(damageRect.left, damageRect.top, damageRect.right-damageRect.left, damageRect.bottom-damageRect.top);
m_scrollBar->paint(&context, rect);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::frameGeometry(
/* [retval][out] */ RECT* bounds)
{
if (!bounds)
return E_POINTER;
IntRect rect = m_scrollBar->frameGeometry();
bounds->left = rect.x();
bounds->right = rect.right();
bounds->top = rect.y();
bounds->bottom = rect.bottom();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::width(
/* [retval][out] */ int* w)
{
if (!w)
return E_POINTER;
*w = m_scrollBar->width();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::height(
/* [retval][out] */ int* h)
{
if (!h)
return E_POINTER;
*h = m_scrollBar->height();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::requestedWidth(
/* [retval][out] */ int* w)
{
if (!w)
return E_POINTER;
*w = m_scrollBar->orientation() == VerticalScrollbar ? ScrollbarTheme::nativeTheme()->scrollbarThickness(m_scrollBar->controlSize()) : -1;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::requestedHeight(
/* [retval][out] */ int* h)
{
if (!h)
return E_POINTER;
*h = m_scrollBar->orientation() == HorizontalScrollbar ? ScrollbarTheme::nativeTheme()->scrollbarThickness(m_scrollBar->controlSize()) : -1;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::handleMouseEvent(
OLE_HANDLE window,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
PlatformMouseEvent mouseEvent((HWND)(ULONG64)window, msg, wParam, lParam);
switch (msg) {
case WM_LBUTTONDOWN:
m_scrollBar->handleMousePressEvent(mouseEvent);
break;
case WM_LBUTTONUP:
m_scrollBar->handleMouseReleaseEvent(mouseEvent);
break;
case WM_MOUSEMOVE:
m_scrollBar->handleMouseMoveEvent(mouseEvent);
break;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebScrollBar::scroll(
WebScrollDirection direction,
WebScrollGranularity granularity,
float multiplier)
{
ScrollDirection webCoreScrollDirection = (ScrollDirection) direction;
ScrollGranularity webCoreGranularity = (ScrollGranularity) granularity;
m_scrollBar->scroll(webCoreScrollDirection, webCoreGranularity, multiplier);
return S_OK;
}
// ScrollbarClient -------------------------------------------------------
void WebScrollBar::valueChanged(Scrollbar* scrollBar)
{
if (m_scrollBar != scrollBar) {
ASSERT(false); // shouldn't happen
return;
}
m_delegate->valueChanged(this);
}
IntRect WebScrollBar::windowClipRect() const
{
HWND sbContainingWindow = m_scrollBar->containingWindow();
RECT clientRect;
::GetClientRect(sbContainingWindow, &clientRect);
return IntRect(clientRect.left, clientRect.top, clientRect.right-clientRect.left, clientRect.bottom-clientRect.top);
}
<|endoftext|> |
<commit_before>/*
* #%L
* Bio-Formats plugin for the Insight Toolkit.
* %%
* Copyright (C) 2010 - 2012 Insight Software Consortium, and Open Microscopy
* Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
*
* ----------------------------------------------------------------
* Adapted from the Slicer3 project: http://www.slicer.org/
* http://viewvc.slicer.org/viewcvs.cgi/trunk/Libs/MGHImageIO/
*
* See slicer-license.txt for Slicer3's licensing information.
*
* For more information about the ITK Plugin IO mechanism, see:
* http://www.itk.org/Wiki/Plugin_IO_mechanisms
* #L%
*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkBioFormatsImageIO.h"
#include "itkNrrdImageIO.h"
#include "itkLSMImageIO.h"
#include "itkTimeProbe.h"
#include <vector>
#include <iomanip>
int main(int, char * argv[])
{
itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);
const unsigned int dim = 3;
typedef unsigned char PType;
typedef itk::Image< PType, dim > IType;
// read the input image
typedef itk::ImageFileReader< IType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
itk::BioFormatsImageIO::Pointer io = itk::BioFormatsImageIO::New();
reader->SetImageIO( io );
// update a first time to avoid the effect of the system cache
reader->Update();
// save the image so it can be used by other readers to compare
// typedef itk::ImageFileWriter< IType > WriterType;
// WriterType::Pointer writer = WriterType::New();
// writer->SetInput( reader->GetOutput() );
// writer->SetFileName( "out.tif" );
// writer->Update();
// writer->SetFileName( "out.nrrd" );
// writer->Update();
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName( argv[1] );
itk::BioFormatsImageIO::Pointer io2 = itk::BioFormatsImageIO::New();
reader2->SetImageIO( io2 );
// update a first time to avoid the effect of the system cache
reader2->Update();
// ReaderType::Pointer reader3 = ReaderType::New();
// reader3->SetFileName( "out.tif" );
// itk::TIFFImageIO::Pointer io3 = itk::TIFFImageIO::New();
// reader3->SetImageIO( io3 );
// // update a first time to avoid the effect of the system cache
// reader3->Update();
//
// ReaderType::Pointer reader4 = ReaderType::New();
// reader4->SetFileName( "out.nrrd" );
// itk::NrrdImageIO::Pointer io4 = itk::NrrdImageIO::New();
// reader4->SetImageIO( io4 );
// // update a first time to avoid the effect of the system cache
// reader4->Update();
std::cout << "1IO\txIO\txTIF\txNRRD" << std::endl;
itk::TimeProbe time;
itk::TimeProbe time2;
// itk::TimeProbe time3;
// itk::TimeProbe time4;
for( int i=0; i<10; i++ )
{
reader->Modified();
time.Start();
reader->Update();
time.Stop();
io2 = itk::BioFormatsImageIO::New();
reader2->SetImageIO( io2 );
time2.Start();
reader2->Update();
time2.Stop();
// io3 = itk::TIFFImageIO::New();
// reader3->SetImageIO( io3 );
// time3.Start();
// reader3->Update();
// time3.Stop();
//
// io4 = itk::NrrdImageIO::New();
// reader4->SetImageIO( io4 );
// time4.Start();
// reader4->Update();
// time4.Stop();
std::cout << std::setprecision(3)
<< time.GetMeanTime() << "\t"
<< time2.GetMeanTime() << "\t"
// << time3.GetMeanTime() << "\t"
// << time4.GetMeanTime() << "\t"
<< std::endl;
}
return 0;
}
<commit_msg>bf-itk: GetMeanTime -> GetMean.<commit_after>/*
* #%L
* Bio-Formats plugin for the Insight Toolkit.
* %%
* Copyright (C) 2010 - 2012 Insight Software Consortium, and Open Microscopy
* Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
*
* ----------------------------------------------------------------
* Adapted from the Slicer3 project: http://www.slicer.org/
* http://viewvc.slicer.org/viewcvs.cgi/trunk/Libs/MGHImageIO/
*
* See slicer-license.txt for Slicer3's licensing information.
*
* For more information about the ITK Plugin IO mechanism, see:
* http://www.itk.org/Wiki/Plugin_IO_mechanisms
* #L%
*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkBioFormatsImageIO.h"
#include "itkNrrdImageIO.h"
#include "itkLSMImageIO.h"
#include "itkTimeProbe.h"
#include <vector>
#include <iomanip>
int main(int, char * argv[])
{
itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);
const unsigned int dim = 3;
typedef unsigned char PType;
typedef itk::Image< PType, dim > IType;
// read the input image
typedef itk::ImageFileReader< IType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
itk::BioFormatsImageIO::Pointer io = itk::BioFormatsImageIO::New();
reader->SetImageIO( io );
// update a first time to avoid the effect of the system cache
reader->Update();
// save the image so it can be used by other readers to compare
// typedef itk::ImageFileWriter< IType > WriterType;
// WriterType::Pointer writer = WriterType::New();
// writer->SetInput( reader->GetOutput() );
// writer->SetFileName( "out.tif" );
// writer->Update();
// writer->SetFileName( "out.nrrd" );
// writer->Update();
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName( argv[1] );
itk::BioFormatsImageIO::Pointer io2 = itk::BioFormatsImageIO::New();
reader2->SetImageIO( io2 );
// update a first time to avoid the effect of the system cache
reader2->Update();
// ReaderType::Pointer reader3 = ReaderType::New();
// reader3->SetFileName( "out.tif" );
// itk::TIFFImageIO::Pointer io3 = itk::TIFFImageIO::New();
// reader3->SetImageIO( io3 );
// // update a first time to avoid the effect of the system cache
// reader3->Update();
//
// ReaderType::Pointer reader4 = ReaderType::New();
// reader4->SetFileName( "out.nrrd" );
// itk::NrrdImageIO::Pointer io4 = itk::NrrdImageIO::New();
// reader4->SetImageIO( io4 );
// // update a first time to avoid the effect of the system cache
// reader4->Update();
std::cout << "1IO\txIO\txTIF\txNRRD" << std::endl;
itk::TimeProbe time;
itk::TimeProbe time2;
// itk::TimeProbe time3;
// itk::TimeProbe time4;
for( int i=0; i<10; i++ )
{
reader->Modified();
time.Start();
reader->Update();
time.Stop();
io2 = itk::BioFormatsImageIO::New();
reader2->SetImageIO( io2 );
time2.Start();
reader2->Update();
time2.Stop();
// io3 = itk::TIFFImageIO::New();
// reader3->SetImageIO( io3 );
// time3.Start();
// reader3->Update();
// time3.Stop();
//
// io4 = itk::NrrdImageIO::New();
// reader4->SetImageIO( io4 );
// time4.Start();
// reader4->Update();
// time4.Stop();
std::cout << std::setprecision(3)
<< time.GetMean() << "\t"
<< time2.GetMean() << "\t"
// << time3.GetMean() << "\t"
// << time4.GetMean() << "\t"
<< std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "service/storage_service.hh"
#include "counters.hh"
#include "mutation.hh"
#include "combine.hh"
counter_id counter_id::local()
{
return counter_id(service::get_local_storage_service().get_local_id());
}
std::ostream& operator<<(std::ostream& os, const counter_id& id) {
return os << id.to_uuid();
}
std::ostream& operator<<(std::ostream& os, counter_shard_view csv) {
return os << "{global_shard id: " << csv.id() << " value: " << csv.value()
<< " clock: " << csv.logical_clock() << "}";
}
std::ostream& operator<<(std::ostream& os, counter_cell_view ccv) {
return os << "{counter_cell timestamp: " << ccv.timestamp() << " shards: {" << ::join(", ", ccv.shards()) << "}}";
}
bool counter_cell_view::apply_reversibly(atomic_cell_or_collection& dst, atomic_cell_or_collection& src)
{
// TODO: optimise for single shard existing in the other
// TODO: optimise for no new shards?
auto dst_ac = dst.as_atomic_cell();
auto src_ac = src.as_atomic_cell();
if (!dst_ac.is_live() || !src_ac.is_live()) {
if (dst_ac.is_live() || (!src_ac.is_live() && compare_atomic_cell_for_merge(dst_ac, src_ac) < 0)) {
std::swap(dst, src);
return true;
}
return false;
}
if (dst_ac.is_counter_update() && src_ac.is_counter_update()) {
// FIXME: store deltas just as a normal int64_t and get rid of these calls
// to long_type
auto src_v = value_cast<int64_t>(long_type->deserialize_value(src_ac.value()));
auto dst_v = value_cast<int64_t>(long_type->deserialize_value(dst_ac.value()));
dst = atomic_cell::make_live_counter_update(std::max(dst_ac.timestamp(), src_ac.timestamp()),
long_type->decompose(src_v + dst_v));
return true;
}
assert(!dst_ac.is_counter_update());
assert(!src_ac.is_counter_update());
auto a_shards = counter_cell_view(dst_ac).shards();
auto b_shards = counter_cell_view(src_ac).shards();
counter_cell_builder result;
combine(a_shards.begin(), a_shards.end(), b_shards.begin(), b_shards.end(),
result.inserter(), counter_shard_view::less_compare_by_id(), [] (auto& x, auto& y) {
return x.logical_clock() < y.logical_clock() ? y : x;
});
auto cell = result.build(std::max(dst_ac.timestamp(), src_ac.timestamp()));
src = std::exchange(dst, atomic_cell_or_collection(cell));
return true;
}
void counter_cell_view::revert_apply(atomic_cell_or_collection& dst, atomic_cell_or_collection& src)
{
if (dst.as_atomic_cell().is_counter_update()) {
auto src_v = value_cast<int64_t>(long_type->deserialize_value(src.as_atomic_cell().value()));
auto dst_v = value_cast<int64_t>(long_type->deserialize_value(dst.as_atomic_cell().value()));
dst = atomic_cell::make_live(dst.as_atomic_cell().timestamp(),
long_type->decompose(dst_v - src_v));
} else {
std::swap(dst, src);
}
}
stdx::optional<atomic_cell> counter_cell_view::difference(atomic_cell_view a, atomic_cell_view b)
{
assert(!a.is_counter_update());
assert(!b.is_counter_update());
if (!b.is_live()) {
return { };
} else if (!a.is_live()) {
return a;
}
auto a_shards = counter_cell_view(a).shards();
auto b_shards = counter_cell_view(b).shards();
auto a_it = a_shards.begin();
auto a_end = a_shards.end();
auto b_it = b_shards.begin();
auto b_end = b_shards.end();
counter_cell_builder result;
while (a_it != a_end) {
while (b_it != b_end && (*b_it).id() < (*a_it).id()) {
++b_it;
}
if (b_it == b_end || (*a_it).id() != (*b_it).id() || (*a_it).logical_clock() > (*b_it).logical_clock()) {
result.add_shard(counter_shard(*a_it));
}
++a_it;
}
stdx::optional<atomic_cell> diff;
if (!result.empty()) {
diff = result.build(std::max(a.timestamp(), b.timestamp()));
} else if (a.timestamp() > b.timestamp()) {
diff = atomic_cell::make_live(a.timestamp(), bytes_view());
}
return diff;
}
void transform_counter_updates_to_shards(mutation& m, const mutation* current_state, uint64_t clock_offset) {
// FIXME: allow current_state to be frozen_mutation
auto transform_new_row_to_shards = [clock_offset] (auto& cr) {
cr.row().cells().for_each_cell([clock_offset] (auto, atomic_cell_or_collection& ac_o_c) {
auto acv = ac_o_c.as_atomic_cell();
if (!acv.is_live()) {
return; // continue -- we are in lambda
}
auto delta = value_cast<int64_t>(long_type->deserialize_value(acv.value()));
counter_cell_builder ccb;
ccb.add_shard(counter_shard(counter_id::local(), delta, clock_offset + 1));
ac_o_c = ccb.build(acv.timestamp());
});
};
if (!current_state) {
for (auto& cr : m.partition().clustered_rows()) {
transform_new_row_to_shards(cr);
}
return;
}
clustering_key::less_compare cmp(*m.schema());
auto& cstate = current_state->partition();
auto it = cstate.clustered_rows().begin();
auto end = cstate.clustered_rows().end();
for (auto& cr : m.partition().clustered_rows()) {
while (it != end && cmp(it->key(), cr.key())) {
++it;
}
if (it == end || cmp(cr.key(), it->key())) {
transform_new_row_to_shards(cr);
continue;
}
struct counter_shard_or_tombstone {
stdx::optional<counter_shard> shard;
tombstone tomb;
};
std::deque<std::pair<column_id, counter_shard_or_tombstone>> shards;
it->row().cells().for_each_cell([&] (column_id id, const atomic_cell_or_collection& ac_o_c) {
auto acv = ac_o_c.as_atomic_cell();
if (!acv.is_live()) {
counter_shard_or_tombstone cs_o_t { { },
tombstone(acv.timestamp(), acv.deletion_time()) };
shards.emplace_back(std::make_pair(id, cs_o_t));
return; // continue -- we are in lambda
}
counter_cell_view ccv(acv);
auto cs = ccv.local_shard();
if (!cs) {
return; // continue
}
shards.emplace_back(std::make_pair(id, counter_shard_or_tombstone { counter_shard(*cs), tombstone() }));
});
cr.row().cells().for_each_cell([&] (column_id id, atomic_cell_or_collection& ac_o_c) {
auto acv = ac_o_c.as_atomic_cell();
if (!acv.is_live()) {
return; // continue -- we are in lambda
}
while (!shards.empty() && shards.front().first < id) {
shards.pop_front();
}
auto delta = value_cast<int64_t>(long_type->deserialize_value(acv.value()));
counter_cell_builder ccb;
if (shards.empty() || shards.front().first > id) {
ccb.add_shard(counter_shard(counter_id::local(), delta, clock_offset + 1));
} else if (shards.front().second.tomb.timestamp == api::missing_timestamp) {
auto& cs = *shards.front().second.shard;
cs.update(delta, clock_offset + 1);
ccb.add_shard(cs);
shards.pop_front();
} else {
// We are apply the tombstone that's already there second time.
// It is not necessary but there is no easy way to remove cell
// from a mutation.
tombstone t = shards.front().second.tomb;
ac_o_c = atomic_cell::make_dead(t.timestamp, t.deletion_time);
shards.pop_front();
return; // continue -- we are in lambda
}
ac_o_c = ccb.build(acv.timestamp());
});
}
}
<commit_msg>counters: fix build failure on gcc5<commit_after>/*
* Copyright (C) 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "service/storage_service.hh"
#include "counters.hh"
#include "mutation.hh"
#include "combine.hh"
counter_id counter_id::local()
{
return counter_id(service::get_local_storage_service().get_local_id());
}
std::ostream& operator<<(std::ostream& os, const counter_id& id) {
return os << id.to_uuid();
}
std::ostream& operator<<(std::ostream& os, counter_shard_view csv) {
return os << "{global_shard id: " << csv.id() << " value: " << csv.value()
<< " clock: " << csv.logical_clock() << "}";
}
std::ostream& operator<<(std::ostream& os, counter_cell_view ccv) {
return os << "{counter_cell timestamp: " << ccv.timestamp() << " shards: {" << ::join(", ", ccv.shards()) << "}}";
}
bool counter_cell_view::apply_reversibly(atomic_cell_or_collection& dst, atomic_cell_or_collection& src)
{
// TODO: optimise for single shard existing in the other
// TODO: optimise for no new shards?
auto dst_ac = dst.as_atomic_cell();
auto src_ac = src.as_atomic_cell();
if (!dst_ac.is_live() || !src_ac.is_live()) {
if (dst_ac.is_live() || (!src_ac.is_live() && compare_atomic_cell_for_merge(dst_ac, src_ac) < 0)) {
std::swap(dst, src);
return true;
}
return false;
}
if (dst_ac.is_counter_update() && src_ac.is_counter_update()) {
// FIXME: store deltas just as a normal int64_t and get rid of these calls
// to long_type
auto src_v = value_cast<int64_t>(long_type->deserialize_value(src_ac.value()));
auto dst_v = value_cast<int64_t>(long_type->deserialize_value(dst_ac.value()));
dst = atomic_cell::make_live_counter_update(std::max(dst_ac.timestamp(), src_ac.timestamp()),
long_type->decompose(src_v + dst_v));
return true;
}
assert(!dst_ac.is_counter_update());
assert(!src_ac.is_counter_update());
auto a_shards = counter_cell_view(dst_ac).shards();
auto b_shards = counter_cell_view(src_ac).shards();
counter_cell_builder result;
combine(a_shards.begin(), a_shards.end(), b_shards.begin(), b_shards.end(),
result.inserter(), counter_shard_view::less_compare_by_id(), [] (auto& x, auto& y) {
return x.logical_clock() < y.logical_clock() ? y : x;
});
auto cell = result.build(std::max(dst_ac.timestamp(), src_ac.timestamp()));
src = std::exchange(dst, atomic_cell_or_collection(cell));
return true;
}
void counter_cell_view::revert_apply(atomic_cell_or_collection& dst, atomic_cell_or_collection& src)
{
if (dst.as_atomic_cell().is_counter_update()) {
auto src_v = value_cast<int64_t>(long_type->deserialize_value(src.as_atomic_cell().value()));
auto dst_v = value_cast<int64_t>(long_type->deserialize_value(dst.as_atomic_cell().value()));
dst = atomic_cell::make_live(dst.as_atomic_cell().timestamp(),
long_type->decompose(dst_v - src_v));
} else {
std::swap(dst, src);
}
}
stdx::optional<atomic_cell> counter_cell_view::difference(atomic_cell_view a, atomic_cell_view b)
{
assert(!a.is_counter_update());
assert(!b.is_counter_update());
if (!b.is_live()) {
return { };
} else if (!a.is_live()) {
return atomic_cell(a);
}
auto a_shards = counter_cell_view(a).shards();
auto b_shards = counter_cell_view(b).shards();
auto a_it = a_shards.begin();
auto a_end = a_shards.end();
auto b_it = b_shards.begin();
auto b_end = b_shards.end();
counter_cell_builder result;
while (a_it != a_end) {
while (b_it != b_end && (*b_it).id() < (*a_it).id()) {
++b_it;
}
if (b_it == b_end || (*a_it).id() != (*b_it).id() || (*a_it).logical_clock() > (*b_it).logical_clock()) {
result.add_shard(counter_shard(*a_it));
}
++a_it;
}
stdx::optional<atomic_cell> diff;
if (!result.empty()) {
diff = result.build(std::max(a.timestamp(), b.timestamp()));
} else if (a.timestamp() > b.timestamp()) {
diff = atomic_cell::make_live(a.timestamp(), bytes_view());
}
return diff;
}
void transform_counter_updates_to_shards(mutation& m, const mutation* current_state, uint64_t clock_offset) {
// FIXME: allow current_state to be frozen_mutation
auto transform_new_row_to_shards = [clock_offset] (auto& cr) {
cr.row().cells().for_each_cell([clock_offset] (auto, atomic_cell_or_collection& ac_o_c) {
auto acv = ac_o_c.as_atomic_cell();
if (!acv.is_live()) {
return; // continue -- we are in lambda
}
auto delta = value_cast<int64_t>(long_type->deserialize_value(acv.value()));
counter_cell_builder ccb;
ccb.add_shard(counter_shard(counter_id::local(), delta, clock_offset + 1));
ac_o_c = ccb.build(acv.timestamp());
});
};
if (!current_state) {
for (auto& cr : m.partition().clustered_rows()) {
transform_new_row_to_shards(cr);
}
return;
}
clustering_key::less_compare cmp(*m.schema());
auto& cstate = current_state->partition();
auto it = cstate.clustered_rows().begin();
auto end = cstate.clustered_rows().end();
for (auto& cr : m.partition().clustered_rows()) {
while (it != end && cmp(it->key(), cr.key())) {
++it;
}
if (it == end || cmp(cr.key(), it->key())) {
transform_new_row_to_shards(cr);
continue;
}
struct counter_shard_or_tombstone {
stdx::optional<counter_shard> shard;
tombstone tomb;
};
std::deque<std::pair<column_id, counter_shard_or_tombstone>> shards;
it->row().cells().for_each_cell([&] (column_id id, const atomic_cell_or_collection& ac_o_c) {
auto acv = ac_o_c.as_atomic_cell();
if (!acv.is_live()) {
counter_shard_or_tombstone cs_o_t { { },
tombstone(acv.timestamp(), acv.deletion_time()) };
shards.emplace_back(std::make_pair(id, cs_o_t));
return; // continue -- we are in lambda
}
counter_cell_view ccv(acv);
auto cs = ccv.local_shard();
if (!cs) {
return; // continue
}
shards.emplace_back(std::make_pair(id, counter_shard_or_tombstone { counter_shard(*cs), tombstone() }));
});
cr.row().cells().for_each_cell([&] (column_id id, atomic_cell_or_collection& ac_o_c) {
auto acv = ac_o_c.as_atomic_cell();
if (!acv.is_live()) {
return; // continue -- we are in lambda
}
while (!shards.empty() && shards.front().first < id) {
shards.pop_front();
}
auto delta = value_cast<int64_t>(long_type->deserialize_value(acv.value()));
counter_cell_builder ccb;
if (shards.empty() || shards.front().first > id) {
ccb.add_shard(counter_shard(counter_id::local(), delta, clock_offset + 1));
} else if (shards.front().second.tomb.timestamp == api::missing_timestamp) {
auto& cs = *shards.front().second.shard;
cs.update(delta, clock_offset + 1);
ccb.add_shard(cs);
shards.pop_front();
} else {
// We are apply the tombstone that's already there second time.
// It is not necessary but there is no easy way to remove cell
// from a mutation.
tombstone t = shards.front().second.tomb;
ac_o_c = atomic_cell::make_dead(t.timestamp, t.deletion_time);
shards.pop_front();
return; // continue -- we are in lambda
}
ac_o_c = ccb.build(acv.timestamp());
});
}
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cursespp/Colors.h>
#include <cursespp/Screen.h>
#include <core/library/LocalLibraryConstants.h>
#include <app/query/CategoryTrackListQuery.h>
#include <app/util/Playback.h>
#include "BrowseLayout.h"
using namespace musik::core::library::constants;
#define CATEGORY_WIDTH 25
#define DEFAULT_CATEGORY constants::Track::ARTIST
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::library;
using namespace musik::box;
using namespace cursespp;
BrowseLayout::BrowseLayout(
PlaybackService& playback,
LibraryPtr library)
: LayoutBase()
, playback(playback) {
this->library = library;
this->library->Indexer()->TrackRefreshed.connect(this, &BrowseLayout::OnIndexerProgress);
this->library->Indexer()->SynchronizeEnd.connect(this, &BrowseLayout::OnIndexerProgress);
this->InitializeWindows();
}
BrowseLayout::~BrowseLayout() {
}
void BrowseLayout::Layout() {
size_t cx = this->GetWidth(), cy = this->GetHeight();
if (cx == 0 || cy == 0) {
return;
}
size_t x = this->GetX(), y = this->GetY();
this->MoveAndResize(x, y, cx, cy);
this->categoryList->MoveAndResize(x, y, CATEGORY_WIDTH, cy);
this->trackList->MoveAndResize(
x + CATEGORY_WIDTH, y, cx - CATEGORY_WIDTH, cy);
this->categoryList->SetFocusOrder(0);
this->trackList->SetFocusOrder(1);
}
void BrowseLayout::InitializeWindows() {
this->categoryList.reset(new CategoryListView(this->playback, this->library, DEFAULT_CATEGORY));
this->trackList.reset(new TrackListView(this->playback, this->library));
this->AddWindow(this->categoryList);
this->AddWindow(this->trackList);
this->categoryList->SelectionChanged.connect(
this, &BrowseLayout::OnCategoryViewSelectionChanged);
this->categoryList->Invalidated.connect(
this, &BrowseLayout::OnCategoryViewInvalidated);
this->Layout();
}
void BrowseLayout::ScrollTo(const std::string& fieldType, DBID fieldId) {
this->SetFocus(this->trackList);
this->categoryList->RequeryWithField(fieldType, "", fieldId);
}
IWindowPtr BrowseLayout::GetFocus() {
return this->focused ? this->focused : LayoutBase::GetFocus();
}
void BrowseLayout::OnVisibilityChanged(bool visible) {
LayoutBase::OnVisibilityChanged(visible);
if (visible) {
this->categoryList->Requery();
}
}
void BrowseLayout::OnIndexerProgress() {
this->categoryList->Requery();
}
void BrowseLayout::RequeryTrackList(ListWindow *view) {
if (view == this->categoryList.get()) {
DBID selectedId = this->categoryList->GetSelectedId();
if (selectedId != -1) {
this->trackList->Requery(std::shared_ptr<TrackListQueryBase>(
new CategoryTrackListQuery(
this->library,
this->categoryList->GetFieldName(),
selectedId)));
}
else {
this->trackList->Clear();
}
}
}
void BrowseLayout::OnCategoryViewSelectionChanged(
ListWindow *view, size_t newIndex, size_t oldIndex) {
this->RequeryTrackList(view);
}
void BrowseLayout::OnCategoryViewInvalidated(
ListWindow *view, size_t selectedIndex) {
this->RequeryTrackList(view);
}
bool BrowseLayout::KeyPress(const std::string& key) {
if (key == "^M") { /* enter. play the selection */
playback::Play(this->trackList, this->playback, this->GetFocus());
return true;
}
if (key == "KEY_F(5)") {
this->categoryList->Requery();
return true;
}
else if (key == "M-1") {
this->categoryList->SetFieldName(constants::Track::ARTIST);
return true;
}
else if (key == "M-2") {
this->categoryList->SetFieldName(constants::Track::ALBUM);
return true;
}
else if (key == "M-3") {
this->categoryList->SetFieldName(constants::Track::GENRE);
return true;
}
return LayoutBase::KeyPress(key);
}
<commit_msg>Allow category list width to grow dynamically up to 40 columns.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cursespp/Colors.h>
#include <cursespp/Screen.h>
#include <core/library/LocalLibraryConstants.h>
#include <app/query/CategoryTrackListQuery.h>
#include <app/util/Playback.h>
#include "BrowseLayout.h"
using namespace musik::core::library::constants;
#define DEFAULT_CATEGORY constants::Track::ARTIST
static size_t MAX_CATEGORY_WIDTH = 40;
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::library;
using namespace musik::box;
using namespace cursespp;
BrowseLayout::BrowseLayout(
PlaybackService& playback,
LibraryPtr library)
: LayoutBase()
, playback(playback) {
this->library = library;
this->library->Indexer()->TrackRefreshed.connect(this, &BrowseLayout::OnIndexerProgress);
this->library->Indexer()->SynchronizeEnd.connect(this, &BrowseLayout::OnIndexerProgress);
this->InitializeWindows();
}
BrowseLayout::~BrowseLayout() {
}
void BrowseLayout::Layout() {
size_t cx = this->GetWidth(), cy = this->GetHeight();
if (cx == 0 || cy == 0) {
return;
}
size_t x = this->GetX(), y = this->GetY();
this->MoveAndResize(x, y, cx, cy);
size_t categoryWidth = std::min(MAX_CATEGORY_WIDTH, cx / 4);
this->categoryList->MoveAndResize(x, y, categoryWidth, cy);
this->trackList->MoveAndResize(
x + categoryWidth, y, cx - categoryWidth, cy);
this->categoryList->SetFocusOrder(0);
this->trackList->SetFocusOrder(1);
}
void BrowseLayout::InitializeWindows() {
this->categoryList.reset(new CategoryListView(this->playback, this->library, DEFAULT_CATEGORY));
this->trackList.reset(new TrackListView(this->playback, this->library));
this->AddWindow(this->categoryList);
this->AddWindow(this->trackList);
this->categoryList->SelectionChanged.connect(
this, &BrowseLayout::OnCategoryViewSelectionChanged);
this->categoryList->Invalidated.connect(
this, &BrowseLayout::OnCategoryViewInvalidated);
this->Layout();
}
void BrowseLayout::ScrollTo(const std::string& fieldType, DBID fieldId) {
this->SetFocus(this->trackList);
this->categoryList->RequeryWithField(fieldType, "", fieldId);
}
IWindowPtr BrowseLayout::GetFocus() {
return this->focused ? this->focused : LayoutBase::GetFocus();
}
void BrowseLayout::OnVisibilityChanged(bool visible) {
LayoutBase::OnVisibilityChanged(visible);
if (visible) {
this->categoryList->Requery();
}
}
void BrowseLayout::OnIndexerProgress() {
this->categoryList->Requery();
}
void BrowseLayout::RequeryTrackList(ListWindow *view) {
if (view == this->categoryList.get()) {
DBID selectedId = this->categoryList->GetSelectedId();
if (selectedId != -1) {
this->trackList->Requery(std::shared_ptr<TrackListQueryBase>(
new CategoryTrackListQuery(
this->library,
this->categoryList->GetFieldName(),
selectedId)));
}
else {
this->trackList->Clear();
}
}
}
void BrowseLayout::OnCategoryViewSelectionChanged(
ListWindow *view, size_t newIndex, size_t oldIndex) {
this->RequeryTrackList(view);
}
void BrowseLayout::OnCategoryViewInvalidated(
ListWindow *view, size_t selectedIndex) {
this->RequeryTrackList(view);
}
bool BrowseLayout::KeyPress(const std::string& key) {
if (key == "^M") { /* enter. play the selection */
playback::Play(this->trackList, this->playback, this->GetFocus());
return true;
}
if (key == "KEY_F(5)") {
this->categoryList->Requery();
return true;
}
else if (key == "M-1") {
this->categoryList->SetFieldName(constants::Track::ARTIST);
return true;
}
else if (key == "M-2") {
this->categoryList->SetFieldName(constants::Track::ALBUM);
return true;
}
else if (key == "M-3") {
this->categoryList->SetFieldName(constants::Track::GENRE);
return true;
}
return LayoutBase::KeyPress(key);
}
<|endoftext|> |
<commit_before>/* cbr
* ObjectHostConnectionManager.cpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 cbr nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ObjectHostConnectionManager.hpp"
#include "Options.hpp"
#include "Message.hpp"
#include <sirikata/network/IOService.hpp>
#include <sirikata/network/IOServiceFactory.hpp>
#include <sirikata/network/IOStrand.hpp>
#include <sirikata/network/IOStrandImpl.hpp>
#include <sirikata/network/StreamListenerFactory.hpp>
#include <sirikata/util/PluginManager.hpp>
#include "Statistics.hpp"
#define SPACE_LOG(level,msg) SILOG(space,level,"[SPACE] " << msg)
namespace CBR {
ObjectHostConnectionManager::ConnectionID::ConnectionID()
: conn(NULL)
{
}
ObjectHostConnectionManager::ConnectionID::ConnectionID(ObjectHostConnection* _conn)
: conn(_conn)
{
}
ObjectHostConnectionManager::ConnectionID::ConnectionID(const ConnectionID& rhs)
: conn(rhs.conn)
{
}
ObjectHostConnectionManager::ConnectionID& ObjectHostConnectionManager::ConnectionID::operator=(const ConnectionID& rhs) {
conn = rhs.conn;
return *this;
}
ObjectHostConnectionManager::ObjectHostConnection::ObjectHostConnection(Sirikata::Network::Stream* str)
: socket(str)
{
}
ObjectHostConnectionManager::ObjectHostConnection::~ObjectHostConnection() {
delete socket;
}
ObjectHostConnectionManager::ConnectionID ObjectHostConnectionManager::ObjectHostConnection::conn_id() {
return ConnectionID(this);
}
ObjectHostConnectionManager::ObjectHostConnectionManager(SpaceContext* ctx, const Address4& listen_addr, MessageReceivedCallback cb)
: mContext(ctx),
mIOService( IOServiceFactory::makeIOService() ),
mIOStrand( mIOService->createStrand() ),
mIOWork(NULL),
mIOThread(NULL),
mAcceptor(NULL),
mMessageReceivedCallback(cb)
{
mIOWork = new IOWork( mIOService, "ObjectHostConnectionManager Work" );
mIOThread = new Thread( std::tr1::bind(&IOService::run, mIOService) );
listen(listen_addr);
}
ObjectHostConnectionManager::~ObjectHostConnectionManager() {
delete mAcceptor;
if (mIOWork != NULL)
delete mIOWork;
delete mIOStrand;
IOServiceFactory::destroyIOService(mIOService);
}
bool ObjectHostConnectionManager::send(const ConnectionID& conn_id, CBR::Protocol::Object::ObjectMessage* msg) {
ObjectHostConnection* conn = conn_id.conn;
if (conn == NULL) {
SPACE_LOG(error,"Tried to send over invalid connection.");
return false;
}
// If its not in the connection list we're probably chasing bad pointers
assert( mConnections.find(conn) != mConnections.end() );
String data = serializePBJMessage(*msg);
bool sent = conn->socket->send( Sirikata::MemoryReference(data), Sirikata::Network::ReliableOrdered );
if (sent) {
TIMESTAMP(msg, Trace::SPACE_TO_OH_ENQUEUED);
delete msg;
}
return sent;
}
void ObjectHostConnectionManager::listen(const Address4& listen_addr) {
using std::tr1::placeholders::_1;
using std::tr1::placeholders::_2;
static Sirikata::PluginManager sPluginManager;
static int tcpSstLoaded=(sPluginManager.load(Sirikata::DynamicLibrary::filename("tcpsst")),0);
String oh_stream_lib = GetOption("ohstreamlib")->as<String>();
String oh_stream_options = GetOption("ohstreamoptions")->as<String>();
assert(mAcceptor == NULL);
mAcceptor=Sirikata::Network::StreamListenerFactory::getSingleton()
.getConstructor(oh_stream_lib)
(mIOService,
Sirikata::Network::StreamListenerFactory::getSingleton()
.getOptionParser(oh_stream_lib)
(oh_stream_options));
Sirikata::Network::Address addr(convertAddress4ToSirikata(listen_addr));
mAcceptor->listen(
addr,
//mIOStrand->wrap(
std::tr1::bind(&ObjectHostConnectionManager::handleNewConnection,this,_1,_2)
//) // FIXME can't wrap here yet because of the SetCallbacks parameter -- it requires that we use it immediately
// and wrapping makes this impossible
);
}
void ObjectHostConnectionManager::shutdown() {
// Shut down the listener
mAcceptor->close();
mContext->mainStrand->post(
std::tr1::bind(&ObjectHostConnectionManager::closeAllConnections, this)
);
// Get rid of bogus work which ensures we keep the service running
delete mIOWork;
mIOWork = NULL;
// Wait for the other thread to finish operations
mIOThread->join();
delete mIOThread;
mIOThread = NULL;
}
void ObjectHostConnectionManager::handleNewConnection(Sirikata::Network::Stream* str, Sirikata::Network::Stream::SetCallbacks& set_callbacks) {
using std::tr1::placeholders::_1;
// For some mysterious reason, Sirikata::Network::Stream uses this callback with a NULL stream to indicate
// all streams from a connection are gone and the underlying connection is shutting down. Why we would care
// about this I do not know, but we handle it because it may be used in Sirikata somewhere.
if (str == NULL)
return;
SPACE_LOG(debug,"New object host connection handled");
// Add the new connection to our index, set read callbacks
ObjectHostConnection* conn = new ObjectHostConnection(str);
set_callbacks(
&Sirikata::Network::Stream::ignoreConnectionCallback,
std::tr1::bind(&ObjectHostConnectionManager::handleConnectionRead,
this,
conn,
_1), // FIXME this should be wrapped by mIOStrand, but the return value is a problem
&Sirikata::Network::Stream::ignoreReadySendCallback
);
mContext->mainStrand->post(
std::tr1::bind(&ObjectHostConnectionManager::insertConnection, this, conn)
);
}
Sirikata::Network::Stream::ReceivedResponse ObjectHostConnectionManager::handleConnectionRead(ObjectHostConnection* conn, Sirikata::Network::Chunk& chunk) {
SPACE_LOG(insane, "Handling connection read: " << chunk.size() << " bytes");
CBR::Protocol::Object::ObjectMessage* obj_msg = new CBR::Protocol::Object::ObjectMessage();
bool parse_success = obj_msg->ParseFromArray(chunk.data(),chunk.size());
assert(parse_success == true);
TIMESTAMP(obj_msg, Trace::HANDLE_OBJECT_HOST_MESSAGE);
return mMessageReceivedCallback(conn->conn_id(), obj_msg)?Sirikata::Network::Stream::AcceptedData:Sirikata::Network::Stream::PauseReceive;
}
void ObjectHostConnectionManager::unpauseObjectStream(const ConnectionID&id){
mIOStrand->post(std::tr1::bind(&ObjectHostConnectionManager::unpauseObjectStreamOnIOStrand,this,id));
}
void ObjectHostConnectionManager::unpauseObjectStreamOnIOStrand(const ConnectionID&id){
if (mConnections.find(id.conn)!=mConnections.end())
id.conn->socket->readyRead();
}
void ObjectHostConnectionManager::insertConnection(ObjectHostConnection* conn) {
mConnections.insert(conn);
}
void ObjectHostConnectionManager::closeAllConnections() {
// Close each connection
for(ObjectHostConnectionSet::iterator it = mConnections.begin(); it != mConnections.end(); it++) {
ObjectHostConnection* conn = (*it);
conn->socket->close();
}
}
} // namespace CBR
<commit_msg>More efficient serialization of outbound OH messages.<commit_after>/* cbr
* ObjectHostConnectionManager.cpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 cbr nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ObjectHostConnectionManager.hpp"
#include "Options.hpp"
#include "Message.hpp"
#include <sirikata/network/IOService.hpp>
#include <sirikata/network/IOServiceFactory.hpp>
#include <sirikata/network/IOStrand.hpp>
#include <sirikata/network/IOStrandImpl.hpp>
#include <sirikata/network/StreamListenerFactory.hpp>
#include <sirikata/util/PluginManager.hpp>
#include "Statistics.hpp"
#define SPACE_LOG(level,msg) SILOG(space,level,"[SPACE] " << msg)
namespace CBR {
ObjectHostConnectionManager::ConnectionID::ConnectionID()
: conn(NULL)
{
}
ObjectHostConnectionManager::ConnectionID::ConnectionID(ObjectHostConnection* _conn)
: conn(_conn)
{
}
ObjectHostConnectionManager::ConnectionID::ConnectionID(const ConnectionID& rhs)
: conn(rhs.conn)
{
}
ObjectHostConnectionManager::ConnectionID& ObjectHostConnectionManager::ConnectionID::operator=(const ConnectionID& rhs) {
conn = rhs.conn;
return *this;
}
ObjectHostConnectionManager::ObjectHostConnection::ObjectHostConnection(Sirikata::Network::Stream* str)
: socket(str)
{
}
ObjectHostConnectionManager::ObjectHostConnection::~ObjectHostConnection() {
delete socket;
}
ObjectHostConnectionManager::ConnectionID ObjectHostConnectionManager::ObjectHostConnection::conn_id() {
return ConnectionID(this);
}
ObjectHostConnectionManager::ObjectHostConnectionManager(SpaceContext* ctx, const Address4& listen_addr, MessageReceivedCallback cb)
: mContext(ctx),
mIOService( IOServiceFactory::makeIOService() ),
mIOStrand( mIOService->createStrand() ),
mIOWork(NULL),
mIOThread(NULL),
mAcceptor(NULL),
mMessageReceivedCallback(cb)
{
mIOWork = new IOWork( mIOService, "ObjectHostConnectionManager Work" );
mIOThread = new Thread( std::tr1::bind(&IOService::run, mIOService) );
listen(listen_addr);
}
ObjectHostConnectionManager::~ObjectHostConnectionManager() {
delete mAcceptor;
if (mIOWork != NULL)
delete mIOWork;
delete mIOStrand;
IOServiceFactory::destroyIOService(mIOService);
}
bool ObjectHostConnectionManager::send(const ConnectionID& conn_id, CBR::Protocol::Object::ObjectMessage* msg) {
ObjectHostConnection* conn = conn_id.conn;
if (conn == NULL) {
SPACE_LOG(error,"Tried to send over invalid connection.");
return false;
}
// If its not in the connection list we're probably chasing bad pointers
assert( mConnections.find(conn) != mConnections.end() );
String data;
serializePBJMessage(&data, *msg);
bool sent = conn->socket->send( Sirikata::MemoryReference(data), Sirikata::Network::ReliableOrdered );
if (sent) {
TIMESTAMP(msg, Trace::SPACE_TO_OH_ENQUEUED);
delete msg;
}
return sent;
}
void ObjectHostConnectionManager::listen(const Address4& listen_addr) {
using std::tr1::placeholders::_1;
using std::tr1::placeholders::_2;
static Sirikata::PluginManager sPluginManager;
static int tcpSstLoaded=(sPluginManager.load(Sirikata::DynamicLibrary::filename("tcpsst")),0);
String oh_stream_lib = GetOption("ohstreamlib")->as<String>();
String oh_stream_options = GetOption("ohstreamoptions")->as<String>();
assert(mAcceptor == NULL);
mAcceptor=Sirikata::Network::StreamListenerFactory::getSingleton()
.getConstructor(oh_stream_lib)
(mIOService,
Sirikata::Network::StreamListenerFactory::getSingleton()
.getOptionParser(oh_stream_lib)
(oh_stream_options));
Sirikata::Network::Address addr(convertAddress4ToSirikata(listen_addr));
mAcceptor->listen(
addr,
//mIOStrand->wrap(
std::tr1::bind(&ObjectHostConnectionManager::handleNewConnection,this,_1,_2)
//) // FIXME can't wrap here yet because of the SetCallbacks parameter -- it requires that we use it immediately
// and wrapping makes this impossible
);
}
void ObjectHostConnectionManager::shutdown() {
// Shut down the listener
mAcceptor->close();
mContext->mainStrand->post(
std::tr1::bind(&ObjectHostConnectionManager::closeAllConnections, this)
);
// Get rid of bogus work which ensures we keep the service running
delete mIOWork;
mIOWork = NULL;
// Wait for the other thread to finish operations
mIOThread->join();
delete mIOThread;
mIOThread = NULL;
}
void ObjectHostConnectionManager::handleNewConnection(Sirikata::Network::Stream* str, Sirikata::Network::Stream::SetCallbacks& set_callbacks) {
using std::tr1::placeholders::_1;
// For some mysterious reason, Sirikata::Network::Stream uses this callback with a NULL stream to indicate
// all streams from a connection are gone and the underlying connection is shutting down. Why we would care
// about this I do not know, but we handle it because it may be used in Sirikata somewhere.
if (str == NULL)
return;
SPACE_LOG(debug,"New object host connection handled");
// Add the new connection to our index, set read callbacks
ObjectHostConnection* conn = new ObjectHostConnection(str);
set_callbacks(
&Sirikata::Network::Stream::ignoreConnectionCallback,
std::tr1::bind(&ObjectHostConnectionManager::handleConnectionRead,
this,
conn,
_1), // FIXME this should be wrapped by mIOStrand, but the return value is a problem
&Sirikata::Network::Stream::ignoreReadySendCallback
);
mContext->mainStrand->post(
std::tr1::bind(&ObjectHostConnectionManager::insertConnection, this, conn)
);
}
Sirikata::Network::Stream::ReceivedResponse ObjectHostConnectionManager::handleConnectionRead(ObjectHostConnection* conn, Sirikata::Network::Chunk& chunk) {
SPACE_LOG(insane, "Handling connection read: " << chunk.size() << " bytes");
CBR::Protocol::Object::ObjectMessage* obj_msg = new CBR::Protocol::Object::ObjectMessage();
bool parse_success = obj_msg->ParseFromArray(chunk.data(),chunk.size());
assert(parse_success == true);
TIMESTAMP(obj_msg, Trace::HANDLE_OBJECT_HOST_MESSAGE);
return mMessageReceivedCallback(conn->conn_id(), obj_msg)?Sirikata::Network::Stream::AcceptedData:Sirikata::Network::Stream::PauseReceive;
}
void ObjectHostConnectionManager::unpauseObjectStream(const ConnectionID&id){
mIOStrand->post(std::tr1::bind(&ObjectHostConnectionManager::unpauseObjectStreamOnIOStrand,this,id));
}
void ObjectHostConnectionManager::unpauseObjectStreamOnIOStrand(const ConnectionID&id){
if (mConnections.find(id.conn)!=mConnections.end())
id.conn->socket->readyRead();
}
void ObjectHostConnectionManager::insertConnection(ObjectHostConnection* conn) {
mConnections.insert(conn);
}
void ObjectHostConnectionManager::closeAllConnections() {
// Close each connection
for(ObjectHostConnectionSet::iterator it = mConnections.begin(); it != mConnections.end(); it++) {
ObjectHostConnection* conn = (*it);
conn->socket->close();
}
}
} // namespace CBR
<|endoftext|> |
<commit_before>#include <limits>
#include "Tools/Display/bash_tools.h"
#include "Tools/Math/utils.h"
#include "Decoder_LDPC_BP_flooding.hpp"
// constexpr int C_to_V_max = 15; // saturation value for the LLRs/extrinsics
template <typename B, typename R>
Decoder_LDPC_BP_flooding<B,R>
::Decoder_LDPC_BP_flooding(const int &K, const int &N, const int& n_ite,
const std ::vector<unsigned char> &n_variables_per_parity,
const std ::vector<unsigned char> &n_parities_per_variable,
const std ::vector<unsigned int > &transpose,
const mipp::vector<B > &X_N,
const bool coset,
const std::string name)
: Decoder_SISO<B,R> (K, N, 1, name ),
n_ite (n_ite ),
n_V_nodes (N ), // same as N but more explicit
n_C_nodes (N - K ),
n_branches (transpose.size() ),
coset (coset ),
init_flag (false ),
n_variables_per_parity (n_variables_per_parity ),
n_parities_per_variable(n_parities_per_variable),
transpose (transpose ),
X_N (X_N ),
Y_N (N ),
V_K (K ),
Lp_N (N, -1), // -1 in order to fail when AZCW
C_to_V (this->n_branches, 0),
V_to_C (this->n_branches, 0)
{
assert(N == (int)n_parities_per_variable.size());
assert(K == N - (int) n_variables_per_parity.size());
assert(n_ite > 0);
}
template <typename B, typename R>
Decoder_LDPC_BP_flooding<B,R>
::~Decoder_LDPC_BP_flooding()
{
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::decode(const mipp::vector<R> &sys, const mipp::vector<R> &par, mipp::vector<R> &ext)
{
std::cerr << bold_red("(EE) This decoder does not support this interface.") << std::endl;
std::exit(-1);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::decode(const mipp::vector<R> &Y_N1, mipp::vector<R> &Y_N2)
{
assert(Y_N1.size() == Y_N2.size());
assert(Y_N1.size() == this->Y_N.size());
assert(!this->coset || (this->coset && this->X_N.size() == this->N));
// memory zones initialization
if (this->init_flag)
{
std::fill(this->C_to_V.begin(), this->C_to_V.end(), 0);
this->init_flag = false;
}
// coset pre-processing
if (this->coset)
for (auto i = 0; i < (int)Y_N1.size(); i++)
this->Y_N[i] = this->X_N[i] ? -Y_N1[i] : Y_N1[i];
else
std::copy(Y_N1.begin(), Y_N1.end(), this->Y_N.begin());
// actual decoding
this->BP_decode(this->Y_N);
// prepare for next round by processing extrinsic information
for (auto i = 0; i < (int)Y_N2.size(); i++)
Y_N2[i] = this->Lp_N[i] - this->Y_N[i];
// coset post-processing
if (this->coset)
for (auto i = 0; i < (int)Y_N2.size(); i++)
Y_N2[i] = this->X_N[i] ? -Y_N2[i] : Y_N2[i];
// saturate<R>(Y_N2, (R)-C_to_V_max, (R)C_to_V_max);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::load(const mipp::vector<R>& Y_N)
{
assert(Y_N.size() == this->Y_N.size());
this->Y_N = Y_N;
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::decode()
{
assert(!this->coset || (this->coset && this->X_N.size() == this->N));
// memory zones initialization
if (this->init_flag)
{
std::fill(this->C_to_V.begin(), this->C_to_V.end(), 0);
this->init_flag = false;
}
// coset pre-processing
if (this->coset)
for (auto i = 0; i < (int)this->Y_N.size(); i++)
this->Y_N[i] = this->X_N[i] ? -this->Y_N[i] : this->Y_N[i];
// actual decoding
this->BP_decode(this->Y_N);
// take the hard decision
for (unsigned i = 0; i < this->V_K.size(); i++)
this->V_K[i] = this->Lp_N[i] < 0;
// coset post-processing (coset pre-processing is made in BP_decode method)
if (this->coset)
for (auto i = 0; i < (int)this->V_K.size(); i++)
this->V_K[i] = this->X_N[i] ? !this->V_K[i] : this->V_K[i];
// set the flag so C_to_V structure can be reset to 0 only at the beginning of the loop in iterative decoding
this->init_flag = true;
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::store(mipp::vector<B>& V_K) const
{
assert(V_K.size() == this->V_K.size());
V_K = this->V_K;
}
// BP algorithm
template <typename B, typename R>
bool Decoder_LDPC_BP_flooding<B,R>
::BP_decode(const mipp::vector<R> &Y_N)
{
// actual decoding
auto syndrome = false;
for (auto ite = 0; ite < this->n_ite; ite++)
{
// beginning of the iteration upon all the matrix lines
R *C_to_V_ptr = this->C_to_V.data();
R *V_to_C_ptr = this->V_to_C.data();
for (auto i = 0; i < this->n_V_nodes; i++)
{
// VN node accumulate all the incoming messages
const auto length = this->n_parities_per_variable[i];
auto sum_C_to_V = (R)0;
for (auto j = 0; j < length; j++)
sum_C_to_V += C_to_V_ptr[j];
// update the intern values
const auto temp = Y_N[i] + sum_C_to_V;
// generate the outcoming messages to the CNs
for (auto j = 0; j < length; j++)
V_to_C_ptr[j] = temp - C_to_V_ptr[j];
C_to_V_ptr += length; // jump to the next node
V_to_C_ptr += length; // jump to the next node
}
// specific inner code depending on the selected implementation (min-sum or sum-product for example)
syndrome = this->BP_process();
// make a saturation
// saturate<R>(this->C_to_V, (R)-C_to_V_max, (R)C_to_V_max);
// stop criterion
if (syndrome)
break;
}
// begining of the iteration upon all the matrix lines
R *C_to_V_ptr = this->C_to_V.data();
for (auto i = 0; i < this->n_V_nodes; i++)
{
const auto length = this->n_parities_per_variable[i];
auto sum_C_to_V = (R)0;
for (auto j = 0; j < length; j++)
sum_C_to_V += C_to_V_ptr[j];
// filling the output
this->Lp_N[i] = Y_N[i] + sum_C_to_V;
C_to_V_ptr += length;
}
return syndrome;
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::set_n_frames(const int n_frames)
{
std::clog << bold_yellow("(WW) Modifying the number of frames is not allowed in this decoder.") << std::endl;
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Decoder_LDPC_BP_flooding<B_8,Q_8>;
template class Decoder_LDPC_BP_flooding<B_16,Q_16>;
template class Decoder_LDPC_BP_flooding<B_32,Q_32>;
template class Decoder_LDPC_BP_flooding<B_64,Q_64>;
#else
template class Decoder_LDPC_BP_flooding<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Fix gcc warnings.<commit_after>#include <limits>
#include "Tools/Display/bash_tools.h"
#include "Tools/Math/utils.h"
#include "Decoder_LDPC_BP_flooding.hpp"
// constexpr int C_to_V_max = 15; // saturation value for the LLRs/extrinsics
template <typename B, typename R>
Decoder_LDPC_BP_flooding<B,R>
::Decoder_LDPC_BP_flooding(const int &K, const int &N, const int& n_ite,
const std ::vector<unsigned char> &n_variables_per_parity,
const std ::vector<unsigned char> &n_parities_per_variable,
const std ::vector<unsigned int > &transpose,
const mipp::vector<B > &X_N,
const bool coset,
const std::string name)
: Decoder_SISO<B,R> (K, N, 1, name ),
n_ite (n_ite ),
n_V_nodes (N ), // same as N but more explicit
n_C_nodes (N - K ),
n_branches (transpose.size() ),
coset (coset ),
init_flag (false ),
n_variables_per_parity (n_variables_per_parity ),
n_parities_per_variable(n_parities_per_variable),
transpose (transpose ),
X_N (X_N ),
Y_N (N ),
V_K (K ),
Lp_N (N, -1), // -1 in order to fail when AZCW
C_to_V (this->n_branches, 0),
V_to_C (this->n_branches, 0)
{
assert(N == (int)n_parities_per_variable.size());
assert(K == N - (int) n_variables_per_parity.size());
assert(n_ite > 0);
}
template <typename B, typename R>
Decoder_LDPC_BP_flooding<B,R>
::~Decoder_LDPC_BP_flooding()
{
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::decode(const mipp::vector<R> &sys, const mipp::vector<R> &par, mipp::vector<R> &ext)
{
std::cerr << bold_red("(EE) This decoder does not support this interface.") << std::endl;
std::exit(-1);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::decode(const mipp::vector<R> &Y_N1, mipp::vector<R> &Y_N2)
{
assert(Y_N1.size() == Y_N2.size());
assert(Y_N1.size() == this->Y_N.size());
assert(!this->coset || (this->coset && (int)this->X_N.size() == this->N));
// memory zones initialization
if (this->init_flag)
{
std::fill(this->C_to_V.begin(), this->C_to_V.end(), 0);
this->init_flag = false;
}
// coset pre-processing
if (this->coset)
for (auto i = 0; i < (int)Y_N1.size(); i++)
this->Y_N[i] = this->X_N[i] ? -Y_N1[i] : Y_N1[i];
else
std::copy(Y_N1.begin(), Y_N1.end(), this->Y_N.begin());
// actual decoding
this->BP_decode(this->Y_N);
// prepare for next round by processing extrinsic information
for (auto i = 0; i < (int)Y_N2.size(); i++)
Y_N2[i] = this->Lp_N[i] - this->Y_N[i];
// coset post-processing
if (this->coset)
for (auto i = 0; i < (int)Y_N2.size(); i++)
Y_N2[i] = this->X_N[i] ? -Y_N2[i] : Y_N2[i];
// saturate<R>(Y_N2, (R)-C_to_V_max, (R)C_to_V_max);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::load(const mipp::vector<R>& Y_N)
{
assert(Y_N.size() == this->Y_N.size());
this->Y_N = Y_N;
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::decode()
{
assert(!this->coset || (this->coset && (int)this->X_N.size() == this->N));
// memory zones initialization
if (this->init_flag)
{
std::fill(this->C_to_V.begin(), this->C_to_V.end(), 0);
this->init_flag = false;
}
// coset pre-processing
if (this->coset)
for (auto i = 0; i < (int)this->Y_N.size(); i++)
this->Y_N[i] = this->X_N[i] ? -this->Y_N[i] : this->Y_N[i];
// actual decoding
this->BP_decode(this->Y_N);
// take the hard decision
for (unsigned i = 0; i < this->V_K.size(); i++)
this->V_K[i] = this->Lp_N[i] < 0;
// coset post-processing (coset pre-processing is made in BP_decode method)
if (this->coset)
for (auto i = 0; i < (int)this->V_K.size(); i++)
this->V_K[i] = this->X_N[i] ? !this->V_K[i] : this->V_K[i];
// set the flag so C_to_V structure can be reset to 0 only at the beginning of the loop in iterative decoding
this->init_flag = true;
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::store(mipp::vector<B>& V_K) const
{
assert(V_K.size() == this->V_K.size());
V_K = this->V_K;
}
// BP algorithm
template <typename B, typename R>
bool Decoder_LDPC_BP_flooding<B,R>
::BP_decode(const mipp::vector<R> &Y_N)
{
// actual decoding
auto syndrome = false;
for (auto ite = 0; ite < this->n_ite; ite++)
{
// beginning of the iteration upon all the matrix lines
R *C_to_V_ptr = this->C_to_V.data();
R *V_to_C_ptr = this->V_to_C.data();
for (auto i = 0; i < this->n_V_nodes; i++)
{
// VN node accumulate all the incoming messages
const auto length = this->n_parities_per_variable[i];
auto sum_C_to_V = (R)0;
for (auto j = 0; j < length; j++)
sum_C_to_V += C_to_V_ptr[j];
// update the intern values
const auto temp = Y_N[i] + sum_C_to_V;
// generate the outcoming messages to the CNs
for (auto j = 0; j < length; j++)
V_to_C_ptr[j] = temp - C_to_V_ptr[j];
C_to_V_ptr += length; // jump to the next node
V_to_C_ptr += length; // jump to the next node
}
// specific inner code depending on the selected implementation (min-sum or sum-product for example)
syndrome = this->BP_process();
// make a saturation
// saturate<R>(this->C_to_V, (R)-C_to_V_max, (R)C_to_V_max);
// stop criterion
if (syndrome)
break;
}
// begining of the iteration upon all the matrix lines
R *C_to_V_ptr = this->C_to_V.data();
for (auto i = 0; i < this->n_V_nodes; i++)
{
const auto length = this->n_parities_per_variable[i];
auto sum_C_to_V = (R)0;
for (auto j = 0; j < length; j++)
sum_C_to_V += C_to_V_ptr[j];
// filling the output
this->Lp_N[i] = Y_N[i] + sum_C_to_V;
C_to_V_ptr += length;
}
return syndrome;
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding<B,R>
::set_n_frames(const int n_frames)
{
std::clog << bold_yellow("(WW) Modifying the number of frames is not allowed in this decoder.") << std::endl;
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Decoder_LDPC_BP_flooding<B_8,Q_8>;
template class Decoder_LDPC_BP_flooding<B_16,Q_16>;
template class Decoder_LDPC_BP_flooding<B_32,Q_32>;
template class Decoder_LDPC_BP_flooding<B_64,Q_64>;
#else
template class Decoder_LDPC_BP_flooding<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|> |
<commit_before>//===-- DWARFASTParserSwift.cpp ---------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "DWARFASTParserSwift.h"
#include "DWARFASTParserClang.h"
#include "DWARFCompileUnit.h"
#include "DWARFDIE.h"
#include "DWARFDebugInfo.h"
#include "DWARFDefines.h"
#include "SymbolFileDWARF.h"
#include "swift/AST/ASTContext.h"
#include "swift/Demangling/Demangle.h"
#include "lldb/Core/Module.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SwiftASTContext.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/TypeMap.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
using namespace lldb;
using namespace lldb_private;
DWARFASTParserSwift::DWARFASTParserSwift(SwiftASTContext &ast) : m_ast(ast) {}
DWARFASTParserSwift::~DWARFASTParserSwift() {}
static llvm::StringRef GetTypedefName(const DWARFDIE &die) {
if (die.Tag() != DW_TAG_typedef)
return {};
DWARFDIE type_die = die.GetAttributeValueAsReferenceDIE(DW_AT_type);
if (!type_die.IsValid())
return {};
return llvm::StringRef::withNullAsEmpty(type_die.GetName());
}
lldb::TypeSP DWARFASTParserSwift::ParseTypeFromDWARF(const SymbolContext &sc,
const DWARFDIE &die,
Log *log,
bool *type_is_new_ptr) {
lldb::TypeSP type_sp;
CompilerType compiler_type;
Status error;
Declaration decl;
ConstString mangled_name;
ConstString name;
bool is_clang_type = false;
llvm::Optional<uint64_t> dwarf_byte_size;
DWARFAttributes attributes;
const size_t num_attributes = die.GetAttributes(attributes);
DWARFFormValue type_attr;
if (num_attributes > 0) {
uint32_t i;
for (i = 0; i < num_attributes; ++i) {
const dw_attr_t attr = attributes.AttributeAtIndex(i);
DWARFFormValue form_value;
if (attributes.ExtractFormValueAtIndex(i, form_value)) {
switch (attr) {
case DW_AT_decl_file:
decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
form_value.Unsigned()));
break;
case DW_AT_decl_line:
decl.SetLine(form_value.Unsigned());
break;
case DW_AT_decl_column:
decl.SetColumn(form_value.Unsigned());
break;
case DW_AT_name:
name.SetCString(form_value.AsCString());
break;
case DW_AT_linkage_name:
case DW_AT_MIPS_linkage_name:
mangled_name.SetCString(form_value.AsCString());
break;
case DW_AT_byte_size:
dwarf_byte_size = form_value.Unsigned();
break;
default:
break;
}
}
}
}
if (!mangled_name && name) {
if (name.GetStringRef().equals("$swift.fixedbuffer")) {
DWARFDIE type_die =
die.GetFirstChild().GetAttributeValueAsReferenceDIE(DW_AT_type);
if (auto wrapped_type =
ParseTypeFromDWARF(sc, type_die, log, type_is_new_ptr)) {
// Create a unique pointer for the type + fixed buffer flag.
type_sp.reset(new Type(*wrapped_type));
type_sp->SetSwiftFixedValueBuffer(true);
return type_sp;
}
}
if (SwiftLanguageRuntime::IsSwiftMangledName(name.GetCString()))
mangled_name = name;
else {
const char *type_name_cstr = name.GetCString();
// TODO: remove this once all mangled names are always included for all
// types in DWARF
swift::ModuleDecl *swift_module = m_ast.GetModule(decl.GetFile(), error);
if (swift_module)
compiler_type = m_ast.FindType(type_name_cstr, swift_module);
}
}
if (mangled_name) {
type_sp = m_ast.GetCachedType(mangled_name);
if (type_sp)
return type_sp;
// Try to import the type from one of the loaded Swift modules.
compiler_type = m_ast.GetTypeFromMangledTypename(mangled_name, error);
}
if (!compiler_type &&
swift::Demangle::isObjCSymbol(mangled_name.GetStringRef())) {
// When we failed to look up the type because no .swiftmodule is
// present or it couldn't be read, fall back to presenting objects
// that look like they might be come from Objective-C (or C) as
// Clang types. LLDB's Objective-C part is very robust against
// malformed object pointers, so this isn't very risky.
auto type_system_or_err = sc.module_sp->GetTypeSystemForLanguage(eLanguageTypeObjC);
if (!type_system_or_err) {
llvm::consumeError(type_system_or_err.takeError());
return nullptr;
}
if (auto *clang_ctx = llvm::dyn_cast_or_null<ClangASTContext>(&*type_system_or_err)) {
DWARFASTParserClang *clang_ast_parser =
static_cast<DWARFASTParserClang *>(clang_ctx->GetDWARFParser());
TypeMap clang_types;
GetClangType(die, mangled_name.GetStringRef(), clang_types);
// Import the Clang type into the Clang context.
if (clang_types.GetSize())
if (TypeSP clang_type_sp = clang_types.GetTypeAtIndex(0))
if (clang_type_sp) {
is_clang_type = true;
compiler_type = clang_ast_parser->GetClangASTImporter().CopyType(
*clang_ctx, clang_type_sp->GetForwardCompilerType());
// Swift doesn't know pointers. Convert top-level
// Objective-C object types to object pointers for Clang.
auto clang_type = clang::QualType::getFromOpaquePtr(
compiler_type.GetOpaqueQualType());
if (clang_type->isObjCObjectOrInterfaceType())
compiler_type = compiler_type.GetPointerType();
}
// Fall back to (id), which is not necessarily correct.
if (!compiler_type) {
is_clang_type = true;
compiler_type = clang_ctx->GetBasicType(eBasicTypeObjCClass);
}
}
}
ConstString preferred_name;
if (!compiler_type && name) {
// Handle Archetypes, which are typedefs to RawPointerType.
if (GetTypedefName(die).startswith("$sBp")) {
swift::ASTContext *swift_ast_ctx = m_ast.GetASTContext();
if (!swift_ast_ctx) {
if (log)
log->Printf("Empty Swift AST context while looking up %s.",
name.AsCString());
return {};
}
preferred_name = name;
compiler_type = {swift_ast_ctx->TheRawPointerType};
}
}
switch (die.Tag()) {
case DW_TAG_inlined_subroutine:
case DW_TAG_subprogram:
case DW_TAG_subroutine_type:
if (!compiler_type || !compiler_type.IsFunctionType()) {
// Make sure we at least have some function type. The mangling for
// the "top_level_code" is returning the empty tuple type "()",
// which is not a function type.
compiler_type = m_ast.GetVoidFunctionType();
}
break;
default:
break;
}
if (compiler_type) {
type_sp = TypeSP(new Type(
die.GetID(), die.GetDWARF(),
preferred_name ? preferred_name : compiler_type.GetTypeName(),
is_clang_type ? dwarf_byte_size
: compiler_type.GetByteSize(nullptr),
NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, compiler_type,
is_clang_type ? Type::eResolveStateForward : Type::eResolveStateFull));
// FIXME: This ought to work lazily, too.
if (is_clang_type)
type_sp->GetFullCompilerType();
}
// Cache this type.
if (type_sp && mangled_name &&
SwiftLanguageRuntime::IsSwiftMangledName(mangled_name.GetCString()))
m_ast.SetCachedType(mangled_name, type_sp);
return type_sp;
}
void DWARFASTParserSwift::GetClangType(const DWARFDIE &die,
llvm::StringRef mangled_name,
TypeMap &clang_types) const {
std::vector<CompilerContext> decl_context;
die.GetDeclContext(decl_context);
if (!decl_context.size())
return;
// Typedefs don't have a DW_AT_linkage_name, so their DW_AT_name is the
// mangled. Get the unmangled name.
auto fixup_typedef = [&mangled_name, &decl_context]() {
using namespace swift::Demangle;
Context Ctx;
NodePointer node = Ctx.demangleSymbolAsNode(mangled_name);
if (!node || node->getNumChildren() != 1 ||
node->getKind() != Node::Kind::Global)
return;
node = node->getFirstChild();
if (node->getNumChildren() != 1 ||
node->getKind() != Node::Kind::TypeMangling)
return;
node = node->getFirstChild();
if (node->getNumChildren() != 1 || node->getKind() != Node::Kind::Type)
return;
node = node->getFirstChild();
if (node->getKind() != Node::Kind::TypeAlias)
return;
for (NodePointer child : *node)
if (child->getKind() == Node::Kind::Identifier && child->hasText()) {
decl_context.back().type = CompilerContextKind::Typedef;
decl_context.back().name = ConstString(child->getText());
return;
}
};
fixup_typedef();
auto &sym_file = die.GetCU()->GetSymbolFileDWARF();
sym_file.UpdateExternalModuleListIfNeeded();
CompilerContextKind kinds[] = {decl_context.back().type,
CompilerContextKind::Union,
CompilerContextKind::Enumeration};
// The Swift projection of all Clang type is a struct; search every kind.
for (CompilerContextKind kind : kinds) {
decl_context.back().type = kind;
// Search any modules referenced by DWARF.
for (const auto &name_module : sym_file.getExternalTypeModules()) {
if (!name_module.second)
continue;
SymbolVendor *sym_vendor = name_module.second->GetSymbolVendor();
if (sym_vendor->FindTypes(decl_context, true, clang_types))
return;
}
// Next search the .dSYM the DIE came from, if applicable.
SymbolFileDWARF &sym_file = die.GetCU()->GetSymbolFileDWARF();
if (sym_file.FindTypes(decl_context, true, clang_types))
return;
}
}
Function *DWARFASTParserSwift::ParseFunctionFromDWARF(
lldb_private::CompileUnit &comp_unit, const DWARFDIE &die) {
DWARFRangeList func_ranges;
const char *name = NULL;
const char *mangled = NULL;
int decl_file = 0;
int decl_line = 0;
int decl_column = 0;
int call_file = 0;
int call_line = 0;
int call_column = 0;
DWARFExpression frame_base;
if (die.Tag() != DW_TAG_subprogram)
return NULL;
if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,
decl_column, call_file, call_line, call_column,
&frame_base)) {
// Union of all ranges in the function DIE (if the function is
// discontiguous)
SymbolFileDWARF *dwarf = die.GetDWARF();
AddressRange func_range;
lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);
lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);
if (lowest_func_addr != LLDB_INVALID_ADDRESS &&
lowest_func_addr <= highest_func_addr) {
ModuleSP module_sp(dwarf->GetObjectFile()->GetModule());
func_range.GetBaseAddress().ResolveAddressUsingFileSections(
lowest_func_addr, module_sp->GetSectionList());
if (func_range.GetBaseAddress().IsValid())
func_range.SetByteSize(highest_func_addr - lowest_func_addr);
}
if (func_range.GetBaseAddress().IsValid()) {
Mangled func_name;
if (mangled)
func_name.SetValue(ConstString(mangled), true);
else
func_name.SetValue(ConstString(name), false);
// See if this function can throw. We can't get that from the
// mangled name (even though the information is often there)
// because Swift reserves the right to omit it from the name
// if it doesn't need it. So instead we look for the
// DW_TAG_thrown_type:
bool can_throw = false;
DWARFDebugInfoEntry *child(die.GetFirstChild().GetDIE());
while (child) {
if (child->Tag() == DW_TAG_thrown_type) {
can_throw = true;
break;
}
child = child->GetSibling();
}
FunctionSP func_sp;
std::unique_ptr<Declaration> decl_ap;
if (decl_file != 0 || decl_line != 0 || decl_column != 0)
decl_ap.reset(new Declaration(
comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),
decl_line, decl_column));
if (dwarf->FixupAddress(func_range.GetBaseAddress())) {
const user_id_t func_user_id = die.GetID();
func_sp.reset(new Function(&comp_unit, func_user_id, func_user_id,
func_name, nullptr, func_range,
can_throw)); // first address range
if (func_sp.get() != NULL) {
if (frame_base.IsValid())
func_sp->GetFrameBaseExpression() = frame_base;
comp_unit.AddFunction(func_sp);
return func_sp.get();
}
}
}
}
return NULL;
}
lldb_private::CompilerDeclContext
DWARFASTParserSwift::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {
return CompilerDeclContext();
}
lldb_private::CompilerDeclContext
DWARFASTParserSwift::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {
return CompilerDeclContext();
}
<commit_msg>[SymbolFile] Update after SymbolVendor API change<commit_after>//===-- DWARFASTParserSwift.cpp ---------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "DWARFASTParserSwift.h"
#include "DWARFASTParserClang.h"
#include "DWARFCompileUnit.h"
#include "DWARFDIE.h"
#include "DWARFDebugInfo.h"
#include "DWARFDefines.h"
#include "SymbolFileDWARF.h"
#include "swift/AST/ASTContext.h"
#include "swift/Demangling/Demangle.h"
#include "lldb/Core/Module.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SwiftASTContext.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/TypeMap.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
using namespace lldb;
using namespace lldb_private;
DWARFASTParserSwift::DWARFASTParserSwift(SwiftASTContext &ast) : m_ast(ast) {}
DWARFASTParserSwift::~DWARFASTParserSwift() {}
static llvm::StringRef GetTypedefName(const DWARFDIE &die) {
if (die.Tag() != DW_TAG_typedef)
return {};
DWARFDIE type_die = die.GetAttributeValueAsReferenceDIE(DW_AT_type);
if (!type_die.IsValid())
return {};
return llvm::StringRef::withNullAsEmpty(type_die.GetName());
}
lldb::TypeSP DWARFASTParserSwift::ParseTypeFromDWARF(const SymbolContext &sc,
const DWARFDIE &die,
Log *log,
bool *type_is_new_ptr) {
lldb::TypeSP type_sp;
CompilerType compiler_type;
Status error;
Declaration decl;
ConstString mangled_name;
ConstString name;
bool is_clang_type = false;
llvm::Optional<uint64_t> dwarf_byte_size;
DWARFAttributes attributes;
const size_t num_attributes = die.GetAttributes(attributes);
DWARFFormValue type_attr;
if (num_attributes > 0) {
uint32_t i;
for (i = 0; i < num_attributes; ++i) {
const dw_attr_t attr = attributes.AttributeAtIndex(i);
DWARFFormValue form_value;
if (attributes.ExtractFormValueAtIndex(i, form_value)) {
switch (attr) {
case DW_AT_decl_file:
decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
form_value.Unsigned()));
break;
case DW_AT_decl_line:
decl.SetLine(form_value.Unsigned());
break;
case DW_AT_decl_column:
decl.SetColumn(form_value.Unsigned());
break;
case DW_AT_name:
name.SetCString(form_value.AsCString());
break;
case DW_AT_linkage_name:
case DW_AT_MIPS_linkage_name:
mangled_name.SetCString(form_value.AsCString());
break;
case DW_AT_byte_size:
dwarf_byte_size = form_value.Unsigned();
break;
default:
break;
}
}
}
}
if (!mangled_name && name) {
if (name.GetStringRef().equals("$swift.fixedbuffer")) {
DWARFDIE type_die =
die.GetFirstChild().GetAttributeValueAsReferenceDIE(DW_AT_type);
if (auto wrapped_type =
ParseTypeFromDWARF(sc, type_die, log, type_is_new_ptr)) {
// Create a unique pointer for the type + fixed buffer flag.
type_sp.reset(new Type(*wrapped_type));
type_sp->SetSwiftFixedValueBuffer(true);
return type_sp;
}
}
if (SwiftLanguageRuntime::IsSwiftMangledName(name.GetCString()))
mangled_name = name;
else {
const char *type_name_cstr = name.GetCString();
// TODO: remove this once all mangled names are always included for all
// types in DWARF
swift::ModuleDecl *swift_module = m_ast.GetModule(decl.GetFile(), error);
if (swift_module)
compiler_type = m_ast.FindType(type_name_cstr, swift_module);
}
}
if (mangled_name) {
type_sp = m_ast.GetCachedType(mangled_name);
if (type_sp)
return type_sp;
// Try to import the type from one of the loaded Swift modules.
compiler_type = m_ast.GetTypeFromMangledTypename(mangled_name, error);
}
if (!compiler_type &&
swift::Demangle::isObjCSymbol(mangled_name.GetStringRef())) {
// When we failed to look up the type because no .swiftmodule is
// present or it couldn't be read, fall back to presenting objects
// that look like they might be come from Objective-C (or C) as
// Clang types. LLDB's Objective-C part is very robust against
// malformed object pointers, so this isn't very risky.
auto type_system_or_err = sc.module_sp->GetTypeSystemForLanguage(eLanguageTypeObjC);
if (!type_system_or_err) {
llvm::consumeError(type_system_or_err.takeError());
return nullptr;
}
if (auto *clang_ctx = llvm::dyn_cast_or_null<ClangASTContext>(&*type_system_or_err)) {
DWARFASTParserClang *clang_ast_parser =
static_cast<DWARFASTParserClang *>(clang_ctx->GetDWARFParser());
TypeMap clang_types;
GetClangType(die, mangled_name.GetStringRef(), clang_types);
// Import the Clang type into the Clang context.
if (clang_types.GetSize())
if (TypeSP clang_type_sp = clang_types.GetTypeAtIndex(0))
if (clang_type_sp) {
is_clang_type = true;
compiler_type = clang_ast_parser->GetClangASTImporter().CopyType(
*clang_ctx, clang_type_sp->GetForwardCompilerType());
// Swift doesn't know pointers. Convert top-level
// Objective-C object types to object pointers for Clang.
auto clang_type = clang::QualType::getFromOpaquePtr(
compiler_type.GetOpaqueQualType());
if (clang_type->isObjCObjectOrInterfaceType())
compiler_type = compiler_type.GetPointerType();
}
// Fall back to (id), which is not necessarily correct.
if (!compiler_type) {
is_clang_type = true;
compiler_type = clang_ctx->GetBasicType(eBasicTypeObjCClass);
}
}
}
ConstString preferred_name;
if (!compiler_type && name) {
// Handle Archetypes, which are typedefs to RawPointerType.
if (GetTypedefName(die).startswith("$sBp")) {
swift::ASTContext *swift_ast_ctx = m_ast.GetASTContext();
if (!swift_ast_ctx) {
if (log)
log->Printf("Empty Swift AST context while looking up %s.",
name.AsCString());
return {};
}
preferred_name = name;
compiler_type = {swift_ast_ctx->TheRawPointerType};
}
}
switch (die.Tag()) {
case DW_TAG_inlined_subroutine:
case DW_TAG_subprogram:
case DW_TAG_subroutine_type:
if (!compiler_type || !compiler_type.IsFunctionType()) {
// Make sure we at least have some function type. The mangling for
// the "top_level_code" is returning the empty tuple type "()",
// which is not a function type.
compiler_type = m_ast.GetVoidFunctionType();
}
break;
default:
break;
}
if (compiler_type) {
type_sp = TypeSP(new Type(
die.GetID(), die.GetDWARF(),
preferred_name ? preferred_name : compiler_type.GetTypeName(),
is_clang_type ? dwarf_byte_size
: compiler_type.GetByteSize(nullptr),
NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, compiler_type,
is_clang_type ? Type::eResolveStateForward : Type::eResolveStateFull));
// FIXME: This ought to work lazily, too.
if (is_clang_type)
type_sp->GetFullCompilerType();
}
// Cache this type.
if (type_sp && mangled_name &&
SwiftLanguageRuntime::IsSwiftMangledName(mangled_name.GetCString()))
m_ast.SetCachedType(mangled_name, type_sp);
return type_sp;
}
void DWARFASTParserSwift::GetClangType(const DWARFDIE &die,
llvm::StringRef mangled_name,
TypeMap &clang_types) const {
std::vector<CompilerContext> decl_context;
die.GetDeclContext(decl_context);
if (!decl_context.size())
return;
// Typedefs don't have a DW_AT_linkage_name, so their DW_AT_name is the
// mangled. Get the unmangled name.
auto fixup_typedef = [&mangled_name, &decl_context]() {
using namespace swift::Demangle;
Context Ctx;
NodePointer node = Ctx.demangleSymbolAsNode(mangled_name);
if (!node || node->getNumChildren() != 1 ||
node->getKind() != Node::Kind::Global)
return;
node = node->getFirstChild();
if (node->getNumChildren() != 1 ||
node->getKind() != Node::Kind::TypeMangling)
return;
node = node->getFirstChild();
if (node->getNumChildren() != 1 || node->getKind() != Node::Kind::Type)
return;
node = node->getFirstChild();
if (node->getKind() != Node::Kind::TypeAlias)
return;
for (NodePointer child : *node)
if (child->getKind() == Node::Kind::Identifier && child->hasText()) {
decl_context.back().type = CompilerContextKind::Typedef;
decl_context.back().name = ConstString(child->getText());
return;
}
};
fixup_typedef();
auto &sym_file = die.GetCU()->GetSymbolFileDWARF();
sym_file.UpdateExternalModuleListIfNeeded();
CompilerContextKind kinds[] = {decl_context.back().type,
CompilerContextKind::Union,
CompilerContextKind::Enumeration};
// The Swift projection of all Clang type is a struct; search every kind.
for (CompilerContextKind kind : kinds) {
decl_context.back().type = kind;
// Search any modules referenced by DWARF.
for (const auto &name_module : sym_file.getExternalTypeModules()) {
if (!name_module.second)
continue;
SymbolFile *sym_file = name_module.second->GetSymbolFile();
if (sym_file->FindTypes(decl_context, true, clang_types))
return;
}
// Next search the .dSYM the DIE came from, if applicable.
SymbolFileDWARF &sym_file = die.GetCU()->GetSymbolFileDWARF();
if (sym_file.FindTypes(decl_context, true, clang_types))
return;
}
}
Function *DWARFASTParserSwift::ParseFunctionFromDWARF(
lldb_private::CompileUnit &comp_unit, const DWARFDIE &die) {
DWARFRangeList func_ranges;
const char *name = NULL;
const char *mangled = NULL;
int decl_file = 0;
int decl_line = 0;
int decl_column = 0;
int call_file = 0;
int call_line = 0;
int call_column = 0;
DWARFExpression frame_base;
if (die.Tag() != DW_TAG_subprogram)
return NULL;
if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,
decl_column, call_file, call_line, call_column,
&frame_base)) {
// Union of all ranges in the function DIE (if the function is
// discontiguous)
SymbolFileDWARF *dwarf = die.GetDWARF();
AddressRange func_range;
lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);
lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);
if (lowest_func_addr != LLDB_INVALID_ADDRESS &&
lowest_func_addr <= highest_func_addr) {
ModuleSP module_sp(dwarf->GetObjectFile()->GetModule());
func_range.GetBaseAddress().ResolveAddressUsingFileSections(
lowest_func_addr, module_sp->GetSectionList());
if (func_range.GetBaseAddress().IsValid())
func_range.SetByteSize(highest_func_addr - lowest_func_addr);
}
if (func_range.GetBaseAddress().IsValid()) {
Mangled func_name;
if (mangled)
func_name.SetValue(ConstString(mangled), true);
else
func_name.SetValue(ConstString(name), false);
// See if this function can throw. We can't get that from the
// mangled name (even though the information is often there)
// because Swift reserves the right to omit it from the name
// if it doesn't need it. So instead we look for the
// DW_TAG_thrown_type:
bool can_throw = false;
DWARFDebugInfoEntry *child(die.GetFirstChild().GetDIE());
while (child) {
if (child->Tag() == DW_TAG_thrown_type) {
can_throw = true;
break;
}
child = child->GetSibling();
}
FunctionSP func_sp;
std::unique_ptr<Declaration> decl_ap;
if (decl_file != 0 || decl_line != 0 || decl_column != 0)
decl_ap.reset(new Declaration(
comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),
decl_line, decl_column));
if (dwarf->FixupAddress(func_range.GetBaseAddress())) {
const user_id_t func_user_id = die.GetID();
func_sp.reset(new Function(&comp_unit, func_user_id, func_user_id,
func_name, nullptr, func_range,
can_throw)); // first address range
if (func_sp.get() != NULL) {
if (frame_base.IsValid())
func_sp->GetFrameBaseExpression() = frame_base;
comp_unit.AddFunction(func_sp);
return func_sp.get();
}
}
}
}
return NULL;
}
lldb_private::CompilerDeclContext
DWARFASTParserSwift::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {
return CompilerDeclContext();
}
lldb_private::CompilerDeclContext
DWARFASTParserSwift::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {
return CompilerDeclContext();
}
<|endoftext|> |
<commit_before>/*
==============================================================================
This file was auto-generated!
==============================================================================
*/
#include "MainComponent.h"
//==============================================================================
MainContentComponent::MainContentComponent()
{
setSize (600, 400);
shutterAnimator = new ShutterAnimator(300, 0.5, 1.0);
//slideAnimator = new SlideAnimator(300, 0.5, 1.0);
ValueTree data (Ids::data);
ValueTree node1 (Ids::node);
node1.setProperty (Ids::title, "Item 1", nullptr);
node1.setProperty (Ids::description, "Blah blah", nullptr);
data.addChild (node1, -1, nullptr);
ValueTree node2 (Ids::node);
node2.setProperty (Ids::title, "Item 2", nullptr);
node2.setProperty (Ids::description, "Shutter Animator", nullptr);
data.addChild (node2, -1, nullptr);
ValueTree node3 (Ids::node);
node3.setProperty (Ids::title, "Item 3", nullptr);
node3.setProperty (Ids::description, "Fade Animator", nullptr);
data.addChild (node3, -1, nullptr);
homeComponent = new HomeComponent();
editorComponent = new EditorComponent();
addAndMakeVisible (header = new StackHeaderComponent());
addAndMakeVisible (animatedStack = new AnimatedStackComponent());
shutterAnimator->setStackComponent (animatedStack);
//slideAnimator->setStackComponent (animatedStack);
AnimatedStackHelpers::setStackAnimatorForComponent(shutterAnimator, editorComponent);
animatedStack->setComponentID("Stack");
header->setComponentID("Header");
header->setTargetStack (animatedStack);
header->setInterceptsMouseClicks (false,true);
header->setBounds ("0,0,parent.width,40");
animatedStack->setBounds ("Header.left,Header.bottom,parent.width,parent.height");
//setColour (ListBox::backgroundColourId, Colours::black);
animatedStack->push (homeComponent, true);
animatedStack->push (listBox = new AnimatedListBox (data,
// itemClicked callback function
[this] (int row, ListBox* source, ValueTree node, const MouseEvent &e)
{
Rectangle<int> rowPosition = source->getRowPosition(row, false);
DBG (rowPosition.toString());
DBG (node.toXmlString());
DBG ("row number clicked: " << row);
animatedStack->push (editorComponent, false);
}
), true);
listBox->setBounds (animatedStack->getBounds());
}
MainContentComponent::~MainContentComponent()
{
listBox = nullptr;
homeComponent = nullptr;
editorComponent = nullptr;
animatedStack = nullptr;
}
void MainContentComponent::paint (Graphics& g)
{
g.fillAll (Colours::black);
}
void MainContentComponent::resized()
{
// This is called when the MainContentComponent is resized.
// If you add any child components, this is where you should
// update their positions.
}
<commit_msg>initial position fix, new display bug<commit_after>/*
==============================================================================
This file was auto-generated!
==============================================================================
*/
#include "MainComponent.h"
//==============================================================================
MainContentComponent::MainContentComponent()
{
setSize (600, 400);
shutterAnimator = new ShutterAnimator(300, 0.5, 1.0);
//slideAnimator = new SlideAnimator(300, 0.5, 1.0);
ValueTree data (Ids::data);
ValueTree node1 (Ids::node);
node1.setProperty (Ids::title, "Item 1", nullptr);
node1.setProperty (Ids::description, "Blah blah", nullptr);
data.addChild (node1, -1, nullptr);
ValueTree node2 (Ids::node);
node2.setProperty (Ids::title, "Item 2", nullptr);
node2.setProperty (Ids::description, "Shutter Animator", nullptr);
data.addChild (node2, -1, nullptr);
ValueTree node3 (Ids::node);
node3.setProperty (Ids::title, "Item 3", nullptr);
node3.setProperty (Ids::description, "Fade Animator", nullptr);
data.addChild (node3, -1, nullptr);
homeComponent = new HomeComponent();
editorComponent = new EditorComponent();
addAndMakeVisible (header = new StackHeaderComponent());
addAndMakeVisible (animatedStack = new AnimatedStackComponent());
shutterAnimator->setStackComponent (animatedStack);
//slideAnimator->setStackComponent (animatedStack);
AnimatedStackHelpers::setStackAnimatorForComponent(shutterAnimator, editorComponent);
animatedStack->setComponentID("Stack");
header->setComponentID("Header");
header->setTargetStack (animatedStack);
header->setInterceptsMouseClicks (false,true);
header->setBounds ("0,0,parent.width,40");
animatedStack->setBounds ("Header.left,Header.bottom,parent.width,parent.height");
//setColour (ListBox::backgroundColourId, Colours::black);
animatedStack->push (homeComponent, true);
animatedStack->push (listBox = new AnimatedListBox (data,
// itemClicked callback function
[this] (int row, ListBox* source, ValueTree node, const MouseEvent &e)
{
Rectangle<int> rowPosition = source->getRowPosition(row, false);
DBG (rowPosition.toString());
DBG (node.toXmlString());
DBG ("row number clicked: " << row);
animatedStack->push (editorComponent, false);
}
), true);
listBox->setBounds ("Stack.left,Stack.top,parent.width,parent.height");
}
MainContentComponent::~MainContentComponent()
{
listBox = nullptr;
homeComponent = nullptr;
editorComponent = nullptr;
animatedStack = nullptr;
}
void MainContentComponent::paint (Graphics& g)
{
g.fillAll (Colours::black);
}
void MainContentComponent::resized()
{
// This is called when the MainContentComponent is resized.
// If you add any child components, this is where you should
// update their positions.
}
<|endoftext|> |
<commit_before>#ifndef __STAN__GM__ARGUMENTS__ARGUMENT__PARSER__HPP__
#define __STAN__GM__ARGUMENTS__ARGUMENT__PARSER__HPP__
#include <string>
#include <vector>
#include <fstream>
#include <stan/gm/arguments/argument.hpp>
#include <stan/gm/arguments/arg_method.hpp>
namespace stan {
namespace gm {
class argument_parser {
public:
argument_parser(std::vector<argument*>& valid_args)
: _arguments(valid_args),
_help_flag(false),
_method_flag(false)
{
_arguments.insert(_arguments.begin(), new arg_method());
}
bool parse_args(int argc,
const char* argv[],
std::ostream* out = 0,
std::ostream* err = 0) {
if (argc == 1) {
print_usage(out, argv[0]);
_help_flag |= true;
return true;
}
std::vector<std::string> args;
// Fill in reverse order as parse_args pops from the back
for (int i = argc - 1; i > 0; --i)
args.push_back(std::string(argv[i]));
bool good_arg = true;
bool valid_arg = true;
_help_flag = false;
std::vector<argument*> unset_args = _arguments;
while(good_arg) {
if (args.size() == 0)
break;
good_arg = false;
std::string cat_name = args.back();
// Check for method arguments entered without the method= prefix
if (!_method_flag) {
list_argument* method = dynamic_cast<list_argument*>(_arguments.front());
if (method->valid_value(cat_name)) {
cat_name = "method=" + cat_name;
args.back() = cat_name;
}
}
std::string val_name;
std::string val;
argument::split_arg(cat_name, val_name, val);
if (val_name == "method")
_method_flag = true;
std::vector<argument*>::iterator arg_it;
for (arg_it = unset_args.begin(); arg_it != unset_args.end(); ++arg_it) {
if ( (*arg_it)->name() == cat_name) {
args.pop_back();
valid_arg &= (*arg_it)->parse_args(args, out, err, _help_flag);
good_arg = true;
break;
}
else if ( (*arg_it)->name() == val_name) {
valid_arg &= (*arg_it)->parse_args(args, out, err, _help_flag);
good_arg = true;
break;
}
}
if (good_arg) unset_args.erase(arg_it);
if (cat_name == "help") {
print_usage(out, argv[0]);
_help_flag |= true;
args.clear();
return true;
} else if (cat_name == "help-all") {
print_help(out, true);
_help_flag |= true;
args.clear();
return true;
}
if (!good_arg && err) {
*err << cat_name << " is either mistyped or misplaced." << std::endl;
std::vector<std::string> valid_paths;
for (int i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->find_arg(val_name, "", valid_paths);
}
if (valid_paths.size()) {
*err << "Perhaps you meant one of the following valid configurations?" << std::endl;
for (int i = 0; i < valid_paths.size(); ++i)
std::cout << " " << valid_paths.at(i) << std::endl;
}
}
}
if (_help_flag)
return true;
if (!_method_flag)
*err << "A method must be specified!" << std::endl;
return valid_arg && good_arg && _method_flag;
}
void print(std::ostream* s, const char prefix = '\0') {
if (!s)
return;
for (int i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->print(s, 0, prefix);
}
}
void print_help(std::ostream* s, bool recurse) {
if (!s)
return;
for (int i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->print_help(s, 1, recurse);
}
}
void print_usage(std::ostream* s, const char* executable) {
if (!s)
return;
std::string indent(2, ' ');
int width = 12;
*s << std::left;
*s << "Usage: " << executable << " <arg1> <subarg1_1> ... <subarg1_m>"
<< " ... <arg_n> <subarg_n_1> ... <subarg_n_m>"
<< std::endl << std::endl;
*s << "Begin by selecting amongst the following inference methods"
<< " and diagnostics," << std::endl;
std::vector<argument*>::iterator arg_it = _arguments.begin();
list_argument* method = dynamic_cast<list_argument*>(*arg_it);
for (std::vector<argument*>::iterator value_it = method->values().begin();
value_it != method->values().end(); ++value_it) {
*s << std::setw(width)
<< indent + (*value_it)->name()
<< indent + (*value_it)->description() << std::endl;
}
*s << std::endl;
*s << "Or see help information with" << std::endl;
*s << std::setw(width)
<< indent + "help"
<< indent + "Prints help" << std::endl;
*s << std::setw(width)
<< indent + "help-all"
<< indent + "Prints entire argument tree" << std::endl;
*s << std::endl;
*s << "Additional configuration available by specifying" << std::endl;
++arg_it;
for (; arg_it != _arguments.end(); ++arg_it) {
*s << std::setw(width)
<< indent + (*arg_it)->name()
<< indent + (*arg_it)->description() << std::endl;
}
*s << std::endl;
*s << "See " << executable << " <arg1> [ help | help-all ] "
<< "for details on individual arguments." << std::endl << std::endl;
}
argument* arg(std::string name) {
for (std::vector<argument*>::iterator it = _arguments.begin();
it != _arguments.end(); ++it)
if ( name == (*it)->name() )
return (*it);
return 0;
}
bool help_printed() {
return _help_flag;
}
protected:
std::vector<argument*>& _arguments;
// We can also check for, and warn the user of, deprecated arguments
//std::vector<argument*> deprecated_arguments;
// check_arg_conflict // Ensure non-zero intersection of valid and deprecated arguments
bool _help_flag;
bool _method_flag;
};
} // gm
} // stan
#endif
<commit_msg>Print usage after any help/help-all argument<commit_after>#ifndef __STAN__GM__ARGUMENTS__ARGUMENT__PARSER__HPP__
#define __STAN__GM__ARGUMENTS__ARGUMENT__PARSER__HPP__
#include <string>
#include <vector>
#include <fstream>
#include <stan/gm/arguments/argument.hpp>
#include <stan/gm/arguments/arg_method.hpp>
namespace stan {
namespace gm {
class argument_parser {
public:
argument_parser(std::vector<argument*>& valid_args)
: _arguments(valid_args),
_help_flag(false),
_method_flag(false)
{
_arguments.insert(_arguments.begin(), new arg_method());
}
bool parse_args(int argc,
const char* argv[],
std::ostream* out = 0,
std::ostream* err = 0) {
if (argc == 1) {
print_usage(out, argv[0]);
_help_flag |= true;
return true;
}
std::vector<std::string> args;
// Fill in reverse order as parse_args pops from the back
for (int i = argc - 1; i > 0; --i)
args.push_back(std::string(argv[i]));
bool good_arg = true;
bool valid_arg = true;
_help_flag = false;
std::vector<argument*> unset_args = _arguments;
while(good_arg) {
if (args.size() == 0)
break;
good_arg = false;
std::string cat_name = args.back();
// Check for method arguments entered without the method= prefix
if (!_method_flag) {
list_argument* method = dynamic_cast<list_argument*>(_arguments.front());
if (method->valid_value(cat_name)) {
cat_name = "method=" + cat_name;
args.back() = cat_name;
}
}
std::string val_name;
std::string val;
argument::split_arg(cat_name, val_name, val);
if (val_name == "method")
_method_flag = true;
std::vector<argument*>::iterator arg_it;
for (arg_it = unset_args.begin(); arg_it != unset_args.end(); ++arg_it) {
if ( (*arg_it)->name() == cat_name) {
args.pop_back();
valid_arg &= (*arg_it)->parse_args(args, out, err, _help_flag);
good_arg = true;
break;
}
else if ( (*arg_it)->name() == val_name) {
valid_arg &= (*arg_it)->parse_args(args, out, err, _help_flag);
good_arg = true;
break;
}
}
if (good_arg) unset_args.erase(arg_it);
if (cat_name == "help") {
_help_flag |= true;
args.clear();
} else if (cat_name == "help-all") {
print_help(out, true);
_help_flag |= true;
args.clear();
}
if (_help_flag) {
print_usage(out, argv[0]);
return true;
}
if (!good_arg && err) {
*err << cat_name << " is either mistyped or misplaced." << std::endl;
std::vector<std::string> valid_paths;
for (int i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->find_arg(val_name, "", valid_paths);
}
if (valid_paths.size()) {
*err << "Perhaps you meant one of the following valid configurations?" << std::endl;
for (int i = 0; i < valid_paths.size(); ++i)
std::cout << " " << valid_paths.at(i) << std::endl;
}
}
}
if (_help_flag)
return true;
if (!_method_flag)
*err << "A method must be specified!" << std::endl;
return valid_arg && good_arg && _method_flag;
}
void print(std::ostream* s, const char prefix = '\0') {
if (!s)
return;
for (int i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->print(s, 0, prefix);
}
}
void print_help(std::ostream* s, bool recurse) {
if (!s)
return;
for (int i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->print_help(s, 1, recurse);
}
}
void print_usage(std::ostream* s, const char* executable) {
if (!s)
return;
std::string indent(2, ' ');
int width = 12;
*s << std::left;
*s << "Usage: " << executable << " <arg1> <subarg1_1> ... <subarg1_m>"
<< " ... <arg_n> <subarg_n_1> ... <subarg_n_m>"
<< std::endl << std::endl;
*s << "Begin by selecting amongst the following inference methods"
<< " and diagnostics," << std::endl;
std::vector<argument*>::iterator arg_it = _arguments.begin();
list_argument* method = dynamic_cast<list_argument*>(*arg_it);
for (std::vector<argument*>::iterator value_it = method->values().begin();
value_it != method->values().end(); ++value_it) {
*s << std::setw(width)
<< indent + (*value_it)->name()
<< indent + (*value_it)->description() << std::endl;
}
*s << std::endl;
*s << "Or see help information with" << std::endl;
*s << std::setw(width)
<< indent + "help"
<< indent + "Prints help" << std::endl;
*s << std::setw(width)
<< indent + "help-all"
<< indent + "Prints entire argument tree" << std::endl;
*s << std::endl;
*s << "Additional configuration available by specifying" << std::endl;
++arg_it;
for (; arg_it != _arguments.end(); ++arg_it) {
*s << std::setw(width)
<< indent + (*arg_it)->name()
<< indent + (*arg_it)->description() << std::endl;
}
*s << std::endl;
*s << "See " << executable << " <arg1> [ help | help-all ] "
<< "for details on individual arguments." << std::endl << std::endl;
}
argument* arg(std::string name) {
for (std::vector<argument*>::iterator it = _arguments.begin();
it != _arguments.end(); ++it)
if ( name == (*it)->name() )
return (*it);
return 0;
}
bool help_printed() {
return _help_flag;
}
protected:
std::vector<argument*>& _arguments;
// We can also check for, and warn the user of, deprecated arguments
//std::vector<argument*> deprecated_arguments;
// check_arg_conflict // Ensure non-zero intersection of valid and deprecated arguments
bool _help_flag;
bool _method_flag;
};
} // gm
} // stan
#endif
<|endoftext|> |
<commit_before>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "SimplifyCFG.h"
#include "ControlFlow.h"
#include "DexClass.h"
#include "IRCode.h"
#include "Walkers.h"
void SimplifyCFGPass::run_pass(DexStoresVector& stores,
ConfigFiles& /* unused */,
PassManager& mgr) {
const auto& scope = build_class_scope(stores);
auto total_insns_removed =
walk::parallel::reduce_methods<std::nullptr_t, int64_t, Scope>(
scope,
[](std::nullptr_t, DexMethod* m) {
auto code = m->get_code();
if (code == nullptr) {
return 0l;
}
int64_t before_insns = code->count_opcodes();
// build and linearize the CFG
code->build_cfg(/* editable */ true);
code->clear_cfg();
int64_t after_insns = code->count_opcodes();
return before_insns - after_insns;
},
[](int64_t a, int64_t b) { return a + b; },
[](int) { return nullptr; }, 0);
mgr.set_metric("insns_removed", total_insns_removed);
}
static SimplifyCFGPass s_pass;
<commit_msg>Fix integer casting issues in Mac OSS build<commit_after>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "SimplifyCFG.h"
#include "ControlFlow.h"
#include "DexClass.h"
#include "IRCode.h"
#include "Walkers.h"
void SimplifyCFGPass::run_pass(DexStoresVector& stores,
ConfigFiles& /* unused */,
PassManager& mgr) {
const auto& scope = build_class_scope(stores);
auto total_insns_removed =
walk::parallel::reduce_methods<std::nullptr_t, int64_t, Scope>(
scope,
[](std::nullptr_t, DexMethod* m) -> int64_t {
auto code = m->get_code();
if (code == nullptr) {
return 0;
}
int64_t before_insns = code->count_opcodes();
// build and linearize the CFG
code->build_cfg(/* editable */ true);
code->clear_cfg();
int64_t after_insns = code->count_opcodes();
return before_insns - after_insns;
},
[](int64_t a, int64_t b) { return a + b; },
[](int) { return nullptr; }, 0);
mgr.set_metric("insns_removed", total_insns_removed);
}
static SimplifyCFGPass s_pass;
<|endoftext|> |
<commit_before>/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Adaptivity Example 1 - Solving 1D PDE Using Adaptive Mesh Refinement</h1>
//
// This example demonstrates how to solve a simple 1D problem
// using adaptive mesh refinement. The PDE that is solved is:
// -epsilon*u''(x) + u(x) = 1, on the domain [0,1] with boundary conditions
// u(0) = u(1) = 0 and where epsilon << 1.
//
// The approach used to solve 1D problems in libMesh is virtually identical to
// solving 2D or 3D problems, so in this sense this example represents a good
// starting point for new users. Note that many concepts are used in this
// example which are explained more fully in subsequent examples.
// Libmesh includes
#include "mesh.h"
#include "mesh_generation.h"
#include "edge_edge3.h"
#include "gnuplot_io.h"
#include "equation_systems.h"
#include "linear_implicit_system.h"
#include "fe.h"
#include "quadrature_gauss.h"
#include "sparse_matrix.h"
#include "dof_map.h"
#include "numeric_vector.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "error_vector.h"
#include "kelly_error_estimator.h"
#include "mesh_refinement.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
void assemble_1D(EquationSystems& es, const std::string& system_name);
int main(int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and PETSc)
// that require initialization before use. When the LibMeshInit
// object goes out of scope, other libraries and resources are
// finalized.
LibMeshInit init (argc, argv);
// Skip adaptive examples on a non-adaptive libMesh build
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_assert(false, "--enable-amr");
#else
// Create a new mesh
Mesh mesh;
// Build a 1D mesh with 4 elements from x=0 to x=1, using
// EDGE3 (i.e. quadratic) 1D elements. They are called EDGE3 elements
// because a quadratic element contains 3 nodes.
MeshTools::Generation::build_line(mesh,4,0.,1.,EDGE3);
// Define the equation systems object and the system we are going
// to solve. See Example 2 for more details.
EquationSystems equation_systems(mesh);
LinearImplicitSystem& system = equation_systems.add_system
<LinearImplicitSystem>("1D");
// Add a variable "u" to the system, using second-order approximation
system.add_variable("u",SECOND);
// Give the system a pointer to the matrix assembly function. This
// will be called when needed by the library.
system.attach_assemble_function(assemble_1D);
// Define the mesh refinement object that takes care of adaptively
// refining the mesh.
MeshRefinement mesh_refinement(mesh);
// These parameters determine the proportion of elements that will
// be refined and coarsened. Any element within 30% of the maximum
// error on any element will be refined, and any element within 30%
// of the minimum error on any element might be coarsened
mesh_refinement.refine_fraction() = 0.7;
mesh_refinement.coarsen_fraction() = 0.3;
// We won't refine any element more than 5 times in total
mesh_refinement.max_h_level() = 5;
// Initialize the data structures for the equation system.
equation_systems.init();
// Refinement parameters
const unsigned int max_r_steps = 5; // Refine the mesh 5 times
// Define the refinement loop
for(unsigned int r_step=0; r_step<=max_r_steps; r_step++)
{
// Solve the equation system
equation_systems.get_system("1D").solve();
// We need to ensure that the mesh is not refined on the last iteration
// of this loop, since we do not want to refine the mesh unless we are
// going to solve the equation system for that refined mesh.
if(r_step != max_r_steps)
{
// Objects for error estimation, see Example 10 for more details.
ErrorVector error;
KellyErrorEstimator error_estimator;
// Compute the error for each active element
error_estimator.estimate_error(system, error);
// Flag elements to be refined and coarsened
mesh_refinement.flag_elements_by_error_fraction (error);
// Perform refinement and coarsening
mesh_refinement.refine_and_coarsen_elements();
// Reinitialize the equation_systems object for the newly refined
// mesh. One of the steps in this is project the solution onto the
// new mesh
equation_systems.reinit();
}
}
// Construct gnuplot plotting object, pass in mesh, title of plot
// and boolean to indicate use of grid in plot. The grid is used to
// show the edges of each element in the mesh.
GnuPlotIO plot(mesh,"Example 0", GnuPlotIO::GRID_ON);
// Write out script to be called from within gnuplot:
// Load gnuplot, then type "call 'gnuplot_script'" from gnuplot prompt
plot.write_equation_systems("gnuplot_script",equation_systems);
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
// Define the matrix assembly function for the 1D PDE we are solving
void assemble_1D(EquationSystems& es, const std::string& system_name)
{
#ifdef LIBMESH_ENABLE_AMR
// It is a good idea to check we are solving the correct system
libmesh_assert(system_name == "1D");
// Get a reference to the mesh object
const MeshBase& mesh = es.get_mesh();
// The dimension we are using, i.e. dim==1
const unsigned int dim = mesh.mesh_dimension();
// Get a reference to the system we are solving
LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("1D");
// Get a reference to the DofMap object for this system. The DofMap object
// handles the index translation from node and element numbers to degree of
// freedom numbers. DofMap's are discussed in more detail in future examples.
const DofMap& dof_map = system.get_dof_map();
// Get a constant reference to the Finite Element type for the first
// (and only) variable in the system.
FEType fe_type = dof_map.variable_type(0);
// Build a finite element object of the specified type. The build
// function dynamically allocates memory so we use an AutoPtr in this case.
// An AutoPtr is a pointer that cleans up after itself. See examples 3 and 4
// for more details on AutoPtr.
AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
// Tell the finite element object to use fifth order Gaussian quadrature
QGauss qrule(dim,FIFTH);
fe->attach_quadrature_rule(&qrule);
// Here we define some references to cell-specific data that will be used to
// assemble the linear system.
// The element Jacobian * quadrature weight at each integration point.
const std::vector<Real>& JxW = fe->get_JxW();
// The element shape functions evaluated at the quadrature points.
const std::vector<std::vector<Real> >& phi = fe->get_phi();
// The element shape function gradients evaluated at the quadrature points.
const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi();
// Declare a dense matrix and dense vector to hold the element matrix
// and right-hand-side contribution
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
// This vector will hold the degree of freedom indices for the element.
// These define where in the global system the element degrees of freedom
// get mapped.
std::vector<unsigned int> dof_indices;
// We now loop over all the active elements in the mesh in order to calculate
// the matrix and right-hand-side contribution from each element. Use a
// const_element_iterator to loop over the elements. We make
// el_end const as it is used only for the stopping condition of the loop.
MeshBase::const_element_iterator el = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();
// Note that ++el is preferred to el++ when using loops with iterators
for( ; el != el_end; ++el)
{
// It is convenient to store a pointer to the current element
const Elem* elem = *el;
// Get the degree of freedom indices for the current element.
// These define where in the global matrix and right-hand-side this
// element will contribute to.
dof_map.dof_indices(elem, dof_indices);
// Compute the element-specific data for the current element. This
// involves computing the location of the quadrature points (q_point)
// and the shape functions (phi, dphi) for the current element.
fe->reinit(elem);
// Store the number of local degrees of freedom contained in this element
const int n_dofs = dof_indices.size();
// We resize and zero out Ke and Fe (resize() also clears the matrix and
// vector). In this example, all elements in the mesh are EDGE3's, so
// Ke will always be 3x3, and Fe will always be 3x1. If the mesh contained
// different element types, then the size of Ke and Fe would change.
Ke.resize(n_dofs, n_dofs);
Fe.resize(n_dofs);
// Now loop over quadrature points to handle numerical integration
for(unsigned int qp=0; qp<qrule.n_points(); qp++)
{
// Now build the element matrix and right-hand-side using loops to
// integrate the test functions (i) against the trial functions (j).
for(unsigned int i=0; i<phi.size(); i++)
{
Fe(i) += JxW[qp]*phi[i][qp];
for(unsigned int j=0; j<phi.size(); j++)
{
Ke(i,j) += JxW[qp]*(1.e-3*dphi[i][qp]*dphi[j][qp] +
phi[i][qp]*phi[j][qp]);
}
}
}
// At this point we have completed the matrix and RHS summation. The
// final step is to apply boundary conditions, which in this case are
// simple Dirichlet conditions with u(0) = u(1) = 0.
// Define the penalty parameter used to enforce the BC's
double penalty = 1.e10;
// Loop over the sides of this element. For a 1D element, the "sides"
// are defined as the nodes on each edge of the element, i.e. 1D elements
// have 2 sides.
for(unsigned int s=0; s<elem->n_sides(); s++)
{
// If this element has a NULL neighbor, then it is on the edge of the
// mesh and we need to enforce a boundary condition using the penalty
// method.
if(elem->neighbor(s) == NULL)
{
Ke(s,s) += penalty;
Fe(s) += 0*penalty;
}
}
// This is a function call that is necessary when using adaptive
// mesh refinement. See Example 10 for more details.
dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
// Add Ke and Fe to the global matrix and right-hand-side.
system.matrix->add_matrix(Ke, dof_indices);
system.rhs->add_vector(Fe, dof_indices);
}
#endif // #ifdef LIBMESH_ENABLE_AMR
}
<commit_msg>Allow overriding of initial mesh size, for testing purposes<commit_after>/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Adaptivity Example 1 - Solving 1D PDE Using Adaptive Mesh Refinement</h1>
//
// This example demonstrates how to solve a simple 1D problem
// using adaptive mesh refinement. The PDE that is solved is:
// -epsilon*u''(x) + u(x) = 1, on the domain [0,1] with boundary conditions
// u(0) = u(1) = 0 and where epsilon << 1.
//
// The approach used to solve 1D problems in libMesh is virtually identical to
// solving 2D or 3D problems, so in this sense this example represents a good
// starting point for new users. Note that many concepts are used in this
// example which are explained more fully in subsequent examples.
// Libmesh includes
#include "mesh.h"
#include "mesh_generation.h"
#include "edge_edge3.h"
#include "gnuplot_io.h"
#include "equation_systems.h"
#include "linear_implicit_system.h"
#include "fe.h"
#include "getpot.h"
#include "quadrature_gauss.h"
#include "sparse_matrix.h"
#include "dof_map.h"
#include "numeric_vector.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "error_vector.h"
#include "kelly_error_estimator.h"
#include "mesh_refinement.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
void assemble_1D(EquationSystems& es, const std::string& system_name);
int main(int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and PETSc)
// that require initialization before use. When the LibMeshInit
// object goes out of scope, other libraries and resources are
// finalized.
LibMeshInit init (argc, argv);
// Skip adaptive examples on a non-adaptive libMesh build
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_assert(false, "--enable-amr");
#else
// Create a new mesh
Mesh mesh;
GetPot command_line (argc, argv);
int n = 4;
if ( command_line.search(1, "-n") )
n = command_line.next(n);
// Build a 1D mesh with 4 elements from x=0 to x=1, using
// EDGE3 (i.e. quadratic) 1D elements. They are called EDGE3 elements
// because a quadratic element contains 3 nodes.
MeshTools::Generation::build_line(mesh,n,0.,1.,EDGE3);
// Define the equation systems object and the system we are going
// to solve. See Example 2 for more details.
EquationSystems equation_systems(mesh);
LinearImplicitSystem& system = equation_systems.add_system
<LinearImplicitSystem>("1D");
// Add a variable "u" to the system, using second-order approximation
system.add_variable("u",SECOND);
// Give the system a pointer to the matrix assembly function. This
// will be called when needed by the library.
system.attach_assemble_function(assemble_1D);
// Define the mesh refinement object that takes care of adaptively
// refining the mesh.
MeshRefinement mesh_refinement(mesh);
// These parameters determine the proportion of elements that will
// be refined and coarsened. Any element within 30% of the maximum
// error on any element will be refined, and any element within 30%
// of the minimum error on any element might be coarsened
mesh_refinement.refine_fraction() = 0.7;
mesh_refinement.coarsen_fraction() = 0.3;
// We won't refine any element more than 5 times in total
mesh_refinement.max_h_level() = 5;
// Initialize the data structures for the equation system.
equation_systems.init();
// Refinement parameters
const unsigned int max_r_steps = 5; // Refine the mesh 5 times
// Define the refinement loop
for(unsigned int r_step=0; r_step<=max_r_steps; r_step++)
{
// Solve the equation system
equation_systems.get_system("1D").solve();
// We need to ensure that the mesh is not refined on the last iteration
// of this loop, since we do not want to refine the mesh unless we are
// going to solve the equation system for that refined mesh.
if(r_step != max_r_steps)
{
// Objects for error estimation, see Example 10 for more details.
ErrorVector error;
KellyErrorEstimator error_estimator;
// Compute the error for each active element
error_estimator.estimate_error(system, error);
// Flag elements to be refined and coarsened
mesh_refinement.flag_elements_by_error_fraction (error);
// Perform refinement and coarsening
mesh_refinement.refine_and_coarsen_elements();
// Reinitialize the equation_systems object for the newly refined
// mesh. One of the steps in this is project the solution onto the
// new mesh
equation_systems.reinit();
}
}
// Construct gnuplot plotting object, pass in mesh, title of plot
// and boolean to indicate use of grid in plot. The grid is used to
// show the edges of each element in the mesh.
GnuPlotIO plot(mesh,"Example 0", GnuPlotIO::GRID_ON);
// Write out script to be called from within gnuplot:
// Load gnuplot, then type "call 'gnuplot_script'" from gnuplot prompt
plot.write_equation_systems("gnuplot_script",equation_systems);
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
// Define the matrix assembly function for the 1D PDE we are solving
void assemble_1D(EquationSystems& es, const std::string& system_name)
{
#ifdef LIBMESH_ENABLE_AMR
// It is a good idea to check we are solving the correct system
libmesh_assert(system_name == "1D");
// Get a reference to the mesh object
const MeshBase& mesh = es.get_mesh();
// The dimension we are using, i.e. dim==1
const unsigned int dim = mesh.mesh_dimension();
// Get a reference to the system we are solving
LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("1D");
// Get a reference to the DofMap object for this system. The DofMap object
// handles the index translation from node and element numbers to degree of
// freedom numbers. DofMap's are discussed in more detail in future examples.
const DofMap& dof_map = system.get_dof_map();
// Get a constant reference to the Finite Element type for the first
// (and only) variable in the system.
FEType fe_type = dof_map.variable_type(0);
// Build a finite element object of the specified type. The build
// function dynamically allocates memory so we use an AutoPtr in this case.
// An AutoPtr is a pointer that cleans up after itself. See examples 3 and 4
// for more details on AutoPtr.
AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
// Tell the finite element object to use fifth order Gaussian quadrature
QGauss qrule(dim,FIFTH);
fe->attach_quadrature_rule(&qrule);
// Here we define some references to cell-specific data that will be used to
// assemble the linear system.
// The element Jacobian * quadrature weight at each integration point.
const std::vector<Real>& JxW = fe->get_JxW();
// The element shape functions evaluated at the quadrature points.
const std::vector<std::vector<Real> >& phi = fe->get_phi();
// The element shape function gradients evaluated at the quadrature points.
const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi();
// Declare a dense matrix and dense vector to hold the element matrix
// and right-hand-side contribution
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
// This vector will hold the degree of freedom indices for the element.
// These define where in the global system the element degrees of freedom
// get mapped.
std::vector<unsigned int> dof_indices;
// We now loop over all the active elements in the mesh in order to calculate
// the matrix and right-hand-side contribution from each element. Use a
// const_element_iterator to loop over the elements. We make
// el_end const as it is used only for the stopping condition of the loop.
MeshBase::const_element_iterator el = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();
// Note that ++el is preferred to el++ when using loops with iterators
for( ; el != el_end; ++el)
{
// It is convenient to store a pointer to the current element
const Elem* elem = *el;
// Get the degree of freedom indices for the current element.
// These define where in the global matrix and right-hand-side this
// element will contribute to.
dof_map.dof_indices(elem, dof_indices);
// Compute the element-specific data for the current element. This
// involves computing the location of the quadrature points (q_point)
// and the shape functions (phi, dphi) for the current element.
fe->reinit(elem);
// Store the number of local degrees of freedom contained in this element
const int n_dofs = dof_indices.size();
// We resize and zero out Ke and Fe (resize() also clears the matrix and
// vector). In this example, all elements in the mesh are EDGE3's, so
// Ke will always be 3x3, and Fe will always be 3x1. If the mesh contained
// different element types, then the size of Ke and Fe would change.
Ke.resize(n_dofs, n_dofs);
Fe.resize(n_dofs);
// Now loop over quadrature points to handle numerical integration
for(unsigned int qp=0; qp<qrule.n_points(); qp++)
{
// Now build the element matrix and right-hand-side using loops to
// integrate the test functions (i) against the trial functions (j).
for(unsigned int i=0; i<phi.size(); i++)
{
Fe(i) += JxW[qp]*phi[i][qp];
for(unsigned int j=0; j<phi.size(); j++)
{
Ke(i,j) += JxW[qp]*(1.e-3*dphi[i][qp]*dphi[j][qp] +
phi[i][qp]*phi[j][qp]);
}
}
}
// At this point we have completed the matrix and RHS summation. The
// final step is to apply boundary conditions, which in this case are
// simple Dirichlet conditions with u(0) = u(1) = 0.
// Define the penalty parameter used to enforce the BC's
double penalty = 1.e10;
// Loop over the sides of this element. For a 1D element, the "sides"
// are defined as the nodes on each edge of the element, i.e. 1D elements
// have 2 sides.
for(unsigned int s=0; s<elem->n_sides(); s++)
{
// If this element has a NULL neighbor, then it is on the edge of the
// mesh and we need to enforce a boundary condition using the penalty
// method.
if(elem->neighbor(s) == NULL)
{
Ke(s,s) += penalty;
Fe(s) += 0*penalty;
}
}
// This is a function call that is necessary when using adaptive
// mesh refinement. See Example 10 for more details.
dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
// Add Ke and Fe to the global matrix and right-hand-side.
system.matrix->add_matrix(Ke, dof_indices);
system.rhs->add_vector(Fe, dof_indices);
}
#endif // #ifdef LIBMESH_ENABLE_AMR
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include "server.h"
#define FTP_SERVER "IGBT.local:2121"
static const char* s_http_port = "8000";
static struct mg_serve_http_opts s_http_server_opts;
static void ev_handler(struct mg_connection* nc, int ev, void* ev_data) {
((orchid::server*)nc->user_data)->handler(nc, ev, (struct http_message*)ev_data);
}
orchid::server::server() {
mg_mgr_init(&d_mgr, NULL);
d_nc = mg_bind(&d_mgr, s_http_port, ev_handler);
mg_set_protocol_http_websocket(d_nc);
s_http_server_opts.document_root = s_web_root;
d_nc->user_data = (void*)this;
}
orchid::server::~server() {
mg_mgr_free(&d_mgr);
}
void orchid::server::poll(int rate) {
for(;;) {
mg_mgr_poll(&d_mgr, rate);
}
}
void orchid::server::handler(struct mg_connection* nc, int ev, struct http_message* hm) {
switch(ev) {
case MG_EV_HTTP_REQUEST: {
if(mg_vcmp(&hm->method, "POST") == 0) {
if(mg_vcmp(&hm->uri, "/val") == 0) {
orchid::http post(std::string(hm->body.p, hm->body.len), [&](Json::Value& root) {
std::string ret = "";
try {
d_app.set_value(root);
}
catch(cam_exception& e) {
ret = std::string(e.what());
}
return ret;
});
post(nc);
}
else if(mg_vcmp(&hm->uri, "/capture") == 0) {
orchid::http post(std::string(hm->body.p, hm->body.len), [&](Json::Value& root) {
std::string ret;
try {
if(!d_lastimg)
d_lastimg = d_app.capture(root);
ret = d_lastimg->get_thumb_web();
}
catch(cam_exception& e) {
ret = std::string(e.what());
}
return ret;
});
post(nc);
}
else if(mg_vcmp(&hm->uri, "/save_img") == 0) {
std::unique_ptr<ftplib> ftp = std::make_unique<ftplib>();
std::string ret = "";
auto thumb = std::string(hm->body.p, hm->body.len);
if(!d_lastimg) {
ret = "No img on deck.";
orchid::server::xmit_txt(nc, ret);
break;
}
if(thumb != d_lastimg->get_thumb_web()) {
ret = "Img ID doesn't match img on deck.";
orchid::server::xmit_txt(nc, ret);
break;
}
if(ftp->Connect(FTP_SERVER) == 0) {
ret = "FTP connect failed.";
orchid::server::xmit_txt(nc, ret);
break;
}
if(ftp->Login("pi", "raspberry") == 0) {
ret = "FTP login failed.";
orchid::server::xmit_txt(nc, ret);
break;
}
std::cout << "FTPing: " << d_lastimg->get_img_abs() << " as " << d_lastimg->get_ftp_name() << std::endl;
if(ftp->Put(d_lastimg->get_img_abs().c_str(), d_lastimg->get_ftp_name().c_str(), ftplib::image) == 0) {
ret = "FTP error";
orchid::server::xmit_txt(nc, ret);
ftp->Quit();
break;
}
d_lastimg->delete_img();
d_lastimg.reset();
orchid::server::xmit_txt(nc, ret);
ftp->Quit();
}
else if(mg_vcmp(&hm->uri, "/reject_img") == 0) {
std::string ret = "";
auto thumb = std::string(hm->body.p, hm->body.len);
if(d_lastimg) {
if(thumb != d_lastimg->get_thumb_web()))
ret = "Img ID doesn't match img on deck.";
else {
std::cout << "Deleting: " << d_lastimg->get_img_abs() << std::endl;
ret = d_lastimg->delete_img();
d_lastimg.reset();
}
}
orchid::server::xmit_txt(nc, ret);
}
else
break;
}
else {
if(mg_vcmp(&hm->uri, "/refresh.live") == 0) {
orchid::http get("", [&](Json::Value& root) {
std::string ret;
try {
d_app.init();
ret = d_app.get_tree();
}
catch(cam_exception& e) {
ret = std::string(e.what());
}
return ret;
});
get(nc);
}
else {
mg_serve_http(nc, hm, s_http_server_opts);
}
}
break;
}
default:
break;
}
}
void orchid::server::xmit_txt(struct mg_connection* nc, std::string msg) {
mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n"
"Content-Type: text/plain\r\n\r\n%s",
msg.size(), msg.c_str());
}
orchid::http::http(std::string st, std::function<std::string(Json::Value&)> func) : d_func(func) {
Json::Reader reader;
reader.parse(st, d_root);
}
void orchid::http::operator()(struct mg_connection* nc) {
orchid::server::xmit_txt(nc, d_func(d_root));
}
<commit_msg>Forget to set nullptr as reset condition on unique_img.<commit_after>#include <cstdio>
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include "server.h"
#define FTP_SERVER "IGBT.local:2121"
static const char* s_http_port = "8000";
static struct mg_serve_http_opts s_http_server_opts;
static void ev_handler(struct mg_connection* nc, int ev, void* ev_data) {
((orchid::server*)nc->user_data)->handler(nc, ev, (struct http_message*)ev_data);
}
orchid::server::server() {
mg_mgr_init(&d_mgr, NULL);
d_nc = mg_bind(&d_mgr, s_http_port, ev_handler);
mg_set_protocol_http_websocket(d_nc);
s_http_server_opts.document_root = s_web_root;
d_nc->user_data = (void*)this;
}
orchid::server::~server() {
mg_mgr_free(&d_mgr);
}
void orchid::server::poll(int rate) {
for(;;) {
mg_mgr_poll(&d_mgr, rate);
}
}
void orchid::server::handler(struct mg_connection* nc, int ev, struct http_message* hm) {
switch(ev) {
case MG_EV_HTTP_REQUEST: {
if(mg_vcmp(&hm->method, "POST") == 0) {
if(mg_vcmp(&hm->uri, "/val") == 0) {
orchid::http post(std::string(hm->body.p, hm->body.len), [&](Json::Value& root) {
std::string ret = "";
try {
d_app.set_value(root);
}
catch(cam_exception& e) {
ret = std::string(e.what());
}
return ret;
});
post(nc);
}
else if(mg_vcmp(&hm->uri, "/capture") == 0) {
orchid::http post(std::string(hm->body.p, hm->body.len), [&](Json::Value& root) {
std::string ret;
try {
if(!d_lastimg)
d_lastimg = d_app.capture(root);
ret = d_lastimg->get_thumb_web();
}
catch(cam_exception& e) {
ret = std::string(e.what());
}
return ret;
});
post(nc);
}
else if(mg_vcmp(&hm->uri, "/save_img") == 0) {
std::unique_ptr<ftplib> ftp = std::make_unique<ftplib>();
std::string ret = "";
auto thumb = std::string(hm->body.p, hm->body.len);
if(!d_lastimg) {
ret = "No img on deck.";
orchid::server::xmit_txt(nc, ret);
break;
}
if(thumb != d_lastimg->get_thumb_web()) {
ret = "Img ID doesn't match img on deck.";
orchid::server::xmit_txt(nc, ret);
break;
}
if(ftp->Connect(FTP_SERVER) == 0) {
ret = "FTP connect failed.";
orchid::server::xmit_txt(nc, ret);
break;
}
if(ftp->Login("pi", "raspberry") == 0) {
ret = "FTP login failed.";
orchid::server::xmit_txt(nc, ret);
break;
}
std::cout << "FTPing: " << d_lastimg->get_img_abs() << " as " << d_lastimg->get_ftp_name() << std::endl;
if(ftp->Put(d_lastimg->get_img_abs().c_str(), d_lastimg->get_ftp_name().c_str(), ftplib::image) == 0) {
ret = "FTP error";
orchid::server::xmit_txt(nc, ret);
ftp->Quit();
break;
}
d_lastimg->delete_img();
d_lastimg.reset(nullptr);
orchid::server::xmit_txt(nc, ret);
ftp->Quit();
}
else if(mg_vcmp(&hm->uri, "/reject_img") == 0) {
std::string ret = "";
auto thumb = std::string(hm->body.p, hm->body.len);
if(d_lastimg) {
if(thumb != d_lastimg->get_thumb_web()))
ret = "Img ID doesn't match img on deck.";
else {
std::cout << "Deleting: " << d_lastimg->get_img_abs() << std::endl;
ret = d_lastimg->delete_img();
d_lastimg.reset(nullptr);
}
}
orchid::server::xmit_txt(nc, ret);
}
else
break;
}
else {
if(mg_vcmp(&hm->uri, "/refresh.live") == 0) {
orchid::http get("", [&](Json::Value& root) {
std::string ret;
try {
d_app.init();
ret = d_app.get_tree();
}
catch(cam_exception& e) {
ret = std::string(e.what());
}
return ret;
});
get(nc);
}
else {
mg_serve_http(nc, hm, s_http_server_opts);
}
}
break;
}
default:
break;
}
}
void orchid::server::xmit_txt(struct mg_connection* nc, std::string msg) {
mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n"
"Content-Type: text/plain\r\n\r\n%s",
msg.size(), msg.c_str());
}
orchid::http::http(std::string st, std::function<std::string(Json::Value&)> func) : d_func(func) {
Json::Reader reader;
reader.parse(st, d_root);
}
void orchid::http::operator()(struct mg_connection* nc) {
orchid::server::xmit_txt(nc, d_func(d_root));
}
<|endoftext|> |
<commit_before>#include "remote_access.h"
#include "parameters.h"
#include "slab_allocator.h"
#include "disk_read_thread.h"
#include "file_mapper.h"
const int NUM_PROCESS_COMPLETED_REQS = 8;
/**
* The maximal number of pending IOs is decided by the maximal pending IOs
* allowed on each I/O thread divided by the number of remote_disk_access.
* Thus, the performance isn't decided by the number of remote_disk_access.
*/
int remote_disk_access::get_max_num_pending_ios() const
{
return io_interface::get_max_num_pending_ios() *
io_threads.size() / num_ios.get();
}
void remote_disk_access::notify_completion(io_request *reqs[], int num)
{
#ifdef MEMCHECK
io_request *req_copies = new io_request[num];
#else
io_request req_copies[num];
#endif
for (int i = 0; i < num; i++) {
req_copies[i] = *reqs[i];
assert(req_copies[i].get_io());
}
int ret = complete_queue.add(req_copies, num);
assert(ret == num);
get_thread()->activate();
#ifdef MEMCHECK
delete [] req_copies;
#endif
}
remote_disk_access::remote_disk_access(const std::vector<disk_read_thread *> &remotes,
file_mapper *mapper, thread *t, int max_reqs): io_interface(
// TODO I hope the queue size is large enough.
t), max_disk_cached_reqs(max_reqs), complete_queue(t->get_node_id(),
COMPLETE_QUEUE_SIZE)
{
int node_id = t->get_node_id();
num_ios.inc(1);
this->io_threads = remotes;
// TODO I need to deallocate it later.
msg_allocator = new slab_allocator(IO_MSG_SIZE * sizeof(io_request),
IO_MSG_SIZE * sizeof(io_request) * 1024, INT_MAX, node_id);
senders.resize(remotes.size());
low_prio_senders.resize(remotes.size());
// create a msg sender for each disk read thread.
for (unsigned i = 0; i < remotes.size(); i++) {
senders[i] = request_sender::create(node_id, msg_allocator,
remotes[i]->get_queue());
low_prio_senders[i] = request_sender::create(node_id, msg_allocator,
remotes[i]->get_low_prio_queue());
}
cb = NULL;
this->block_mapper = mapper;
}
remote_disk_access::~remote_disk_access()
{
assert(senders.size() == low_prio_senders.size());
int num_senders = senders.size();
for (int i = 0; i < num_senders; i++) {
request_sender::destroy(senders[i]);
request_sender::destroy(low_prio_senders[i]);
}
}
io_interface *remote_disk_access::clone(thread *t) const
{
// An IO may not be associated to any threads.
assert(t == NULL || t->get_node_id() == this->get_node_id());
num_ios.inc(1);
remote_disk_access *copy = new remote_disk_access(t,
this->max_disk_cached_reqs);
copy->io_threads = this->io_threads;
copy->senders.resize(this->senders.size());
copy->low_prio_senders.resize(this->low_prio_senders.size());
assert(copy->senders.size() == copy->low_prio_senders.size());
for (unsigned i = 0; i < copy->senders.size(); i++) {
copy->senders[i] = request_sender::create(this->get_node_id(),
msg_allocator, this->senders[i]->get_queue());
copy->low_prio_senders[i] = request_sender::create(this->get_node_id(),
msg_allocator, this->low_prio_senders[i]->get_queue());
}
copy->cb = this->cb;
copy->block_mapper = this->block_mapper;
copy->msg_allocator = this->msg_allocator;
return copy;
}
void remote_disk_access::cleanup()
{
process_completed_requests(complete_queue.get_num_entries());
num_ios.dec(1);
for (unsigned i = 0; i < senders.size(); i++) {
senders[i]->flush();
low_prio_senders[i]->flush();
}
int num;
do {
num = 0;
assert(senders.size() == low_prio_senders.size());
for (unsigned i = 0; i < senders.size(); i++) {
num += senders[i]->get_queue()->get_num_entries();
num += low_prio_senders[i]->get_queue()->get_num_entries();
}
/*
* if there are still messages in the queue, wait.
* this might be the best I can do right now
* unless the queues can notify me when they are
* empty.
*/
if (num > 0) {
// Let's wake up all IO threads if there are still
// some low-priority requests that need to be processed.
for (unsigned i = 0; i < io_threads.size(); i++) {
io_threads[i]->activate();
}
usleep(100000);
}
} while (num > 0);
for (unsigned i = 0; i < io_threads.size(); i++)
io_threads[i]->flush_requests();
}
void remote_disk_access::access(io_request *requests, int num,
io_status *status)
{
ASSERT_EQ(get_thread(), thread::get_curr_thread());
num_issued_reqs.inc(num);
bool syncd = false;
for (int i = 0; i < num; i++) {
assert(requests[i].get_size() >= MIN_BLOCK_SIZE);
if (requests[i].is_flush()) {
syncd = true;
continue;
}
else if (requests[i].is_sync()) {
syncd = true;
}
// If the request accesses one RAID block, it's simple.
if (inside_RAID_block(requests[i])) {
off_t pg_off = requests[i].get_offset() / PAGE_SIZE;
int idx = block_mapper->map2file(pg_off);
// The cache inside a sender is extensible, so it can absorb
// all requests.
int ret;
if (requests[i].is_high_prio())
ret = senders[idx]->send_cached(&requests[i]);
else {
ret = low_prio_senders[idx]->send_cached(&requests[i]);
}
assert(ret == 1);
}
else {
// If the request accesses multiple RAID blocks, we have to
// split the request.
// I still use the default memory allocator, but since it is used
// when the request size is large, it should normally be OK.
// TODO I can use slab allocators later.
io_req_extension *ext = new io_req_extension();
io_request *orig = new io_request(ext, 0, 0, NULL, 0);
// global_cached_io doesn't issue requests across a block boundary.
// It can only be application issued requst, so it shouldn't have
// extension.
assert(!requests[i].is_extended_req());
orig->init(requests[i]);
off_t end = orig->get_offset() + orig->get_size();
const off_t RAID_block_size = params.get_RAID_block_size() * PAGE_SIZE;
for (off_t begin = orig->get_offset(); begin < end;
begin = ROUND(begin + RAID_block_size, RAID_block_size)) {
io_req_extension *ext = new io_req_extension();
ext->set_orig(orig);
io_request req(ext, 0, 0, NULL, 0);
int size = ROUND(begin + RAID_block_size, RAID_block_size) - begin;
size = min(size, end - begin);
// It only supports to extract a specified request from
// a single-buffer request.
extract_pages(*orig, begin, size / PAGE_SIZE, req);
req.set_io(this);
assert(inside_RAID_block(req));
// Send a request.
off_t pg_off = req.get_offset() / PAGE_SIZE;
int idx = block_mapper->map2file(pg_off);
// The cache inside a sender is extensible, so it can absorb
// all requests.
int ret;
if (req.is_high_prio())
ret = senders[idx]->send_cached(&req);
else {
ret = low_prio_senders[idx]->send_cached(&req);
}
assert(ret == 1);
}
}
}
int num_remaining = 0;
assert(senders.size() == low_prio_senders.size());
for (unsigned i = 0; i < senders.size(); i++) {
num_remaining += senders[i]->get_num_remaining();
num_remaining += low_prio_senders[i]->get_num_remaining();
}
if (num_remaining > MAX_DISK_CACHED_REQS) {
flush_requests(MAX_DISK_CACHED_REQS);
}
if (syncd)
flush_requests();
if (status)
for (int i = 0; i < num; i++)
status[i] = IO_PENDING;
}
void remote_disk_access::flush_requests()
{
flush_requests(0);
}
int remote_disk_access::process_completed_requests(int num)
{
if (num > 0) {
#ifdef MEMCHECK
io_request *reqs = new io_request[num];
#else
io_request reqs[num];
#endif
int ret = complete_queue.fetch(reqs, num);
process_completed_requests(reqs, ret);
#ifdef MEMCHECK
delete [] reqs;
#endif
return ret;
}
else
return 0;
}
int remote_disk_access::process_completed_requests(io_request reqs[], int num)
{
// There are a few cases for the incoming requests.
// the requests issued by the upper layer IO;
// the requests split by the current IO;
// the requests issued by an application.
io_request *from_upper[num];
io_request *from_app[num];
io_interface *upper_io = NULL;
int num_from_upper = 0;
int num_from_app = 0;
int num_part_reqs = 0;
std::vector<io_request *> completes;
for (int i = 0; i < num; i++) {
assert(reqs[i].get_io());
// The requests issued by the upper layer IO.
if (reqs[i].get_io() != this) {
if (upper_io == NULL)
upper_io = reqs[i].get_io();
else
// They should be from the same upper layer IO.
assert(upper_io == reqs[i].get_io());
from_upper[num_from_upper++] = &reqs[i];
continue;
}
if (reqs[i].get_io() == this && !reqs[i].is_extended_req()) {
from_app[num_from_app++] = &reqs[i];
continue;
}
io_request *orig = reqs[i].get_orig();
io_request *req = &reqs[i];
orig->inc_complete_count();
if (orig->complete_size(req->get_size()))
completes.push_back(orig);
else {
orig->dec_complete_count();
num_part_reqs++;
}
delete req->get_extension();
}
if (num_from_upper > 0) {
assert(upper_io);
upper_io->notify_completion(from_upper, num_from_upper);
}
if (num_from_app > 0 && this->get_callback())
this->get_callback()->invoke(from_app, num_from_app);
for (unsigned i = 0; i < completes.size(); i++) {
io_request *orig = completes[i];
assert(orig->is_extended_req());
io_interface *io = orig->get_io();
// It's from an application.
if (io == this) {
if (io->get_callback())
io->get_callback()->invoke(&orig, 1);
}
else
io->notify_completion(&orig, 1);
orig->dec_complete_count();
orig->wait4unref();
// Now we can delete it.
delete orig->get_extension();
delete orig;
}
num_completed_reqs.inc(num - num_part_reqs);
return num - num_part_reqs;
}
void remote_disk_access::flush_requests(int max_cached)
{
// Now let's flush requests to the queues, but we first try to
// flush requests non-blockingly.
assert(senders.size() == low_prio_senders.size());
int num_senders = senders.size();
for (int i = 0; i < num_senders; i++) {
senders[i]->flush();
low_prio_senders[i]->flush();
assert(senders[i]->get_num_remaining() == 0);
assert(low_prio_senders[i]->get_num_remaining() == 0);
}
for (unsigned i = 0; i < io_threads.size(); i++) {
io_threads[i]->activate();
}
}
int remote_disk_access::get_file_id() const
{
return block_mapper->get_file_id();
}
/**
* We wait for at least the specified number of requests to complete.
*/
int remote_disk_access::wait4complete(int num_to_complete)
{
flush_requests();
int pending = num_pending_ios();
num_to_complete = min(pending, num_to_complete);
process_completed_requests(complete_queue.get_num_entries());
int iters = 0;
while (pending - num_pending_ios() < num_to_complete) {
iters++;
get_thread()->wait();
process_completed_requests(complete_queue.get_num_entries());
}
return pending - num_pending_ios();
}
atomic_integer remote_disk_access::num_ios;
<commit_msg>Replace assert() with ASSERT_x().<commit_after>#include "remote_access.h"
#include "parameters.h"
#include "slab_allocator.h"
#include "disk_read_thread.h"
#include "file_mapper.h"
const int NUM_PROCESS_COMPLETED_REQS = 8;
/**
* The maximal number of pending IOs is decided by the maximal pending IOs
* allowed on each I/O thread divided by the number of remote_disk_access.
* Thus, the performance isn't decided by the number of remote_disk_access.
*/
int remote_disk_access::get_max_num_pending_ios() const
{
return io_interface::get_max_num_pending_ios() *
io_threads.size() / num_ios.get();
}
void remote_disk_access::notify_completion(io_request *reqs[], int num)
{
#ifdef MEMCHECK
io_request *req_copies = new io_request[num];
#else
io_request req_copies[num];
#endif
for (int i = 0; i < num; i++) {
req_copies[i] = *reqs[i];
assert(req_copies[i].get_io());
}
int ret = complete_queue.add(req_copies, num);
assert(ret == num);
get_thread()->activate();
#ifdef MEMCHECK
delete [] req_copies;
#endif
}
remote_disk_access::remote_disk_access(const std::vector<disk_read_thread *> &remotes,
file_mapper *mapper, thread *t, int max_reqs): io_interface(
// TODO I hope the queue size is large enough.
t), max_disk_cached_reqs(max_reqs), complete_queue(t->get_node_id(),
COMPLETE_QUEUE_SIZE)
{
int node_id = t->get_node_id();
num_ios.inc(1);
this->io_threads = remotes;
// TODO I need to deallocate it later.
msg_allocator = new slab_allocator(IO_MSG_SIZE * sizeof(io_request),
IO_MSG_SIZE * sizeof(io_request) * 1024, INT_MAX, node_id);
senders.resize(remotes.size());
low_prio_senders.resize(remotes.size());
// create a msg sender for each disk read thread.
for (unsigned i = 0; i < remotes.size(); i++) {
senders[i] = request_sender::create(node_id, msg_allocator,
remotes[i]->get_queue());
low_prio_senders[i] = request_sender::create(node_id, msg_allocator,
remotes[i]->get_low_prio_queue());
}
cb = NULL;
this->block_mapper = mapper;
}
remote_disk_access::~remote_disk_access()
{
assert(senders.size() == low_prio_senders.size());
int num_senders = senders.size();
for (int i = 0; i < num_senders; i++) {
request_sender::destroy(senders[i]);
request_sender::destroy(low_prio_senders[i]);
}
}
io_interface *remote_disk_access::clone(thread *t) const
{
// An IO may not be associated to any threads.
assert(t == NULL || t->get_node_id() == this->get_node_id());
num_ios.inc(1);
remote_disk_access *copy = new remote_disk_access(t,
this->max_disk_cached_reqs);
copy->io_threads = this->io_threads;
copy->senders.resize(this->senders.size());
copy->low_prio_senders.resize(this->low_prio_senders.size());
assert(copy->senders.size() == copy->low_prio_senders.size());
for (unsigned i = 0; i < copy->senders.size(); i++) {
copy->senders[i] = request_sender::create(this->get_node_id(),
msg_allocator, this->senders[i]->get_queue());
copy->low_prio_senders[i] = request_sender::create(this->get_node_id(),
msg_allocator, this->low_prio_senders[i]->get_queue());
}
copy->cb = this->cb;
copy->block_mapper = this->block_mapper;
copy->msg_allocator = this->msg_allocator;
return copy;
}
void remote_disk_access::cleanup()
{
process_completed_requests(complete_queue.get_num_entries());
num_ios.dec(1);
for (unsigned i = 0; i < senders.size(); i++) {
senders[i]->flush();
low_prio_senders[i]->flush();
}
int num;
do {
num = 0;
assert(senders.size() == low_prio_senders.size());
for (unsigned i = 0; i < senders.size(); i++) {
num += senders[i]->get_queue()->get_num_entries();
num += low_prio_senders[i]->get_queue()->get_num_entries();
}
/*
* if there are still messages in the queue, wait.
* this might be the best I can do right now
* unless the queues can notify me when they are
* empty.
*/
if (num > 0) {
// Let's wake up all IO threads if there are still
// some low-priority requests that need to be processed.
for (unsigned i = 0; i < io_threads.size(); i++) {
io_threads[i]->activate();
}
usleep(100000);
}
} while (num > 0);
for (unsigned i = 0; i < io_threads.size(); i++)
io_threads[i]->flush_requests();
}
void remote_disk_access::access(io_request *requests, int num,
io_status *status)
{
ASSERT_EQ(get_thread(), thread::get_curr_thread());
num_issued_reqs.inc(num);
bool syncd = false;
for (int i = 0; i < num; i++) {
ASSERT_LTEQ(requests[i].get_size(), MIN_BLOCK_SIZE);
if (requests[i].is_flush()) {
syncd = true;
continue;
}
else if (requests[i].is_sync()) {
syncd = true;
}
// If the request accesses one RAID block, it's simple.
if (inside_RAID_block(requests[i])) {
off_t pg_off = requests[i].get_offset() / PAGE_SIZE;
int idx = block_mapper->map2file(pg_off);
// The cache inside a sender is extensible, so it can absorb
// all requests.
int ret;
if (requests[i].is_high_prio())
ret = senders[idx]->send_cached(&requests[i]);
else {
ret = low_prio_senders[idx]->send_cached(&requests[i]);
}
assert(ret == 1);
}
else {
// If the request accesses multiple RAID blocks, we have to
// split the request.
// I still use the default memory allocator, but since it is used
// when the request size is large, it should normally be OK.
// TODO I can use slab allocators later.
io_req_extension *ext = new io_req_extension();
io_request *orig = new io_request(ext, 0, 0, NULL, 0);
// global_cached_io doesn't issue requests across a block boundary.
// It can only be application issued requst, so it shouldn't have
// extension.
assert(!requests[i].is_extended_req());
orig->init(requests[i]);
off_t end = orig->get_offset() + orig->get_size();
const off_t RAID_block_size = params.get_RAID_block_size() * PAGE_SIZE;
for (off_t begin = orig->get_offset(); begin < end;
begin = ROUND(begin + RAID_block_size, RAID_block_size)) {
io_req_extension *ext = new io_req_extension();
ext->set_orig(orig);
io_request req(ext, 0, 0, NULL, 0);
int size = ROUND(begin + RAID_block_size, RAID_block_size) - begin;
size = min(size, end - begin);
// It only supports to extract a specified request from
// a single-buffer request.
extract_pages(*orig, begin, size / PAGE_SIZE, req);
req.set_io(this);
assert(inside_RAID_block(req));
// Send a request.
off_t pg_off = req.get_offset() / PAGE_SIZE;
int idx = block_mapper->map2file(pg_off);
// The cache inside a sender is extensible, so it can absorb
// all requests.
int ret;
if (req.is_high_prio())
ret = senders[idx]->send_cached(&req);
else {
ret = low_prio_senders[idx]->send_cached(&req);
}
assert(ret == 1);
}
}
}
int num_remaining = 0;
assert(senders.size() == low_prio_senders.size());
for (unsigned i = 0; i < senders.size(); i++) {
num_remaining += senders[i]->get_num_remaining();
num_remaining += low_prio_senders[i]->get_num_remaining();
}
if (num_remaining > MAX_DISK_CACHED_REQS) {
flush_requests(MAX_DISK_CACHED_REQS);
}
if (syncd)
flush_requests();
if (status)
for (int i = 0; i < num; i++)
status[i] = IO_PENDING;
}
void remote_disk_access::flush_requests()
{
flush_requests(0);
}
int remote_disk_access::process_completed_requests(int num)
{
if (num > 0) {
#ifdef MEMCHECK
io_request *reqs = new io_request[num];
#else
io_request reqs[num];
#endif
int ret = complete_queue.fetch(reqs, num);
process_completed_requests(reqs, ret);
#ifdef MEMCHECK
delete [] reqs;
#endif
return ret;
}
else
return 0;
}
int remote_disk_access::process_completed_requests(io_request reqs[], int num)
{
// There are a few cases for the incoming requests.
// the requests issued by the upper layer IO;
// the requests split by the current IO;
// the requests issued by an application.
io_request *from_upper[num];
io_request *from_app[num];
io_interface *upper_io = NULL;
int num_from_upper = 0;
int num_from_app = 0;
int num_part_reqs = 0;
std::vector<io_request *> completes;
for (int i = 0; i < num; i++) {
assert(reqs[i].get_io());
// The requests issued by the upper layer IO.
if (reqs[i].get_io() != this) {
if (upper_io == NULL)
upper_io = reqs[i].get_io();
else
// They should be from the same upper layer IO.
assert(upper_io == reqs[i].get_io());
from_upper[num_from_upper++] = &reqs[i];
continue;
}
if (reqs[i].get_io() == this && !reqs[i].is_extended_req()) {
from_app[num_from_app++] = &reqs[i];
continue;
}
io_request *orig = reqs[i].get_orig();
io_request *req = &reqs[i];
orig->inc_complete_count();
if (orig->complete_size(req->get_size()))
completes.push_back(orig);
else {
orig->dec_complete_count();
num_part_reqs++;
}
delete req->get_extension();
}
if (num_from_upper > 0) {
assert(upper_io);
upper_io->notify_completion(from_upper, num_from_upper);
}
if (num_from_app > 0 && this->get_callback())
this->get_callback()->invoke(from_app, num_from_app);
for (unsigned i = 0; i < completes.size(); i++) {
io_request *orig = completes[i];
assert(orig->is_extended_req());
io_interface *io = orig->get_io();
// It's from an application.
if (io == this) {
if (io->get_callback())
io->get_callback()->invoke(&orig, 1);
}
else
io->notify_completion(&orig, 1);
orig->dec_complete_count();
orig->wait4unref();
// Now we can delete it.
delete orig->get_extension();
delete orig;
}
num_completed_reqs.inc(num - num_part_reqs);
return num - num_part_reqs;
}
void remote_disk_access::flush_requests(int max_cached)
{
// Now let's flush requests to the queues, but we first try to
// flush requests non-blockingly.
assert(senders.size() == low_prio_senders.size());
int num_senders = senders.size();
for (int i = 0; i < num_senders; i++) {
senders[i]->flush();
low_prio_senders[i]->flush();
assert(senders[i]->get_num_remaining() == 0);
assert(low_prio_senders[i]->get_num_remaining() == 0);
}
for (unsigned i = 0; i < io_threads.size(); i++) {
io_threads[i]->activate();
}
}
int remote_disk_access::get_file_id() const
{
return block_mapper->get_file_id();
}
/**
* We wait for at least the specified number of requests to complete.
*/
int remote_disk_access::wait4complete(int num_to_complete)
{
flush_requests();
int pending = num_pending_ios();
num_to_complete = min(pending, num_to_complete);
process_completed_requests(complete_queue.get_num_entries());
int iters = 0;
while (pending - num_pending_ios() < num_to_complete) {
iters++;
get_thread()->wait();
process_completed_requests(complete_queue.get_num_entries());
}
return pending - num_pending_ios();
}
atomic_integer remote_disk_access::num_ios;
<|endoftext|> |
<commit_before>/* Stress test for the sequence journal that randomly modifies a
string and compares against modifications of the string.
*/
#undef SEQAN_ENABLE_DEBUG
#define SEQAN_ENABLE_DEBUG 1
#include <cstdlib>
#include <sstream>
#include <string>
#include <seqan/basic.h>
#include <seqan/file.h>
#include <seqan/sequence.h>
#include <seqan/misc/misc_random.h>
#include <seqan/sequence_journal.h>
using namespace seqan;
const unsigned SEED = 42;
const unsigned INITIAL_LENGTH = 10;//1000;//*1000;
const unsigned NUM_CHANGES = 1000*1000;
const unsigned MAX_INSERT = 10000;
#define RAND_CHAR() ('A' + mtRand() % ('Z' - 'A'))
int main(int, char **)
{
// Initialize random number generators with a fixed seed.
std::srand(SEED);
mtRandInit(false);
// Build random reference and host string.
String<char> string;
reserve(string, INITIAL_LENGTH);
String<char> host;
reserve(host, INITIAL_LENGTH);
for (unsigned i = 0; i < INITIAL_LENGTH; ++i) {
char c = RAND_CHAR();
appendValue(string, c);
appendValue(host, c);
}
// Output of initial sequences.
// std::cout << "reference = " << string << std::endl;
// std::cout << "host = " << host << std::endl;
typedef SequenceJournal<String<char>, Unbalanced> TSequenceJournal;
// Construct sequence journal on host.
TSequenceJournal sequenceJournal(host);
// unsigned nextId = 0;
// std::cerr << "digraph {" << std::endl;
// We will use a string stream to test the string result of tmp.
{
std::stringstream tmp;
tmp << sequenceJournal;
// SEQAN_ASSERT_EQ(string, tmp.str());
// std::cout << "string = " << string << std::endl;
// std::cout << "jrnld = " << tmp.str() << std::endl;
// std::cout << " tree = " << sequenceJournal._journalTree << std::endl;
// std::cout << " orig = " << value(sequenceJournal._host) << std::endl;
// std::cout << " buff = " << sequenceJournal._insertionBuffer << std::endl;
// journalTreeToDot(std::cerr, nextId, sequenceJournal._journalTree);
}
size_t expectedLength = length(string);
for (unsigned i = 0; i < NUM_CHANGES; ++i) {
std::cout << "i == " << i << std::endl;
unsigned changeType = mtRand() % 3;
if (changeType == 0) { // edit
if (length(string) == 0)
continue;
unsigned begin = 0;
unsigned end = 0;
while (begin == end) {
begin = mtRand() % length(string);
end = mtRand() % (length(string) + 1);
}
if (begin > end)
std::swap(begin, end);
unsigned len = end - begin;
String<char> buffer;
reserve(buffer, len);
for (unsigned i = 0; i < len; ++i)
appendValue(buffer, RAND_CHAR());
// Perform insert.
// std::cout << "assignInfix(sequenceJournal, " << begin << ", " << end << ", \"" << buffer << "\")" << std::endl;
std::cout << "assignInfix(sequenceJournal, " << begin << ", " << end << ", buffer, len(buffer) == " << length(buffer) << ")" << std::endl;
infix(string, begin, end) = buffer;
// std::cout << "pre assign infix " << length(sequenceJournal) << std::endl;
assignInfix(sequenceJournal, begin, end, buffer);
// std::cout << "post assign infix " << length(sequenceJournal) << std::endl;
} else if (changeType == 1) { // insert
unsigned begin = 0;
unsigned len = 0;
while (len == 0) {
if (length(string) == 0)
begin = 0;
else
begin = mtRand() % length(string);
len = mtRand() % MAX_INSERT + 1;
}
expectedLength += len;
String<char> buffer;
reserve(buffer, len);
for (unsigned i = 0; i < len; ++i)
appendValue(buffer, RAND_CHAR());
// Perform insert.
// std::cout << "insert(sequenceJournal, " << begin << ", \"" << buffer << "\")" << std::endl;
std::cout << "insert(sequenceJournal, " << begin << ", buffer)" << std::endl;
infix(string, begin, begin) = buffer;
insert(sequenceJournal, begin, buffer);
} else if (changeType == 2) { // delete
if (length(string) == 0)
continue;
unsigned begin = 0;
unsigned end = 0;
while (begin == end) {
begin = mtRand() % length(string);
end = mtRand() % (length(string) + 1);
}
if (begin > end)
std::swap(begin, end);
expectedLength -= (end - begin);
// Perform erase.
// std::stringstream tmp;
// tmp << sequenceJournal;
// std::cout << ",---" << std::endl;
// std::cout << "| string = " << string << std::endl;
// std::cout << "| jrnld = " << tmp.str() << std::endl;
// std::cout << "| tree = " << sequenceJournal._journalTree << std::endl;
// std::cout << "| orig = " << value(sequenceJournal._host) << std::endl;
// std::cout << "| buff = " << sequenceJournal._insertionBuffer << std::endl;
std::cout << "erase(sequenceJournal, " << begin << ", " << end << ")" << std::endl;
// std::cout << "`---" << std::endl;
// std::cout << sequenceJournal._journalTree << std::endl;
erase(string, begin, end);
erase(sequenceJournal, begin, end);
// std::cout << sequenceJournal._journalTree << std::endl;
} else {
SEQAN_ASSERT_FAIL("Invalid change type.");
}
{
// Check via stream operator<< into stringstream.
std::stringstream tmp;
tmp << sequenceJournal;
SEQAN_ASSERT_EQ(expectedLength, length(tmp.str()));
SEQAN_ASSERT_EQ(expectedLength, length(string));
SEQAN_ASSERT_EQ(string, tmp.str());
// std::cout << "string = " << string << std::endl << "tmp.str() = " << tmp.str() << std::endl;
// Check via iterator on the journal string.
std::string buffer;
reserve(buffer, length(sequenceJournal));
typedef Iterator<TSequenceJournal, Standard>::Type TIterator;
// std::cout << sequenceJournal._journalTree << std::endl;
for (TIterator it = begin(sequenceJournal), itend = end(sequenceJournal, Standard()); it != itend; ++it) {
appendValue(buffer, *it);
}
// std::cout << "buffer = " << buffer << std::endl;
SEQAN_ASSERT_EQ(expectedLength, length(buffer));
SEQAN_ASSERT_EQ(buffer, tmp.str());
}
{
// Check operator+ and operator+= on sequence journal iterators;
typedef Iterator<TSequenceJournal, Standard>::Type TSequenceJournalIterator;
typedef Iterator<String<char>, Standard>::Type TCharStringIterator;
TSequenceJournalIterator sjIt = begin(sequenceJournal);
TCharStringIterator csIt = begin(string);
size_t remaining = length(sequenceJournal);
while (remaining > 1) {
SEQAN_ASSERT_TRUE(csIt != end(string) - 1);
size_t len = mtRand() % (remaining + 1);
remaining -= len;
if (remaining == 0)
break;
SEQAN_ASSERT_EQ(*(sjIt + len), *(csIt + len));
sjIt += len;
csIt += len;
SEQAN_ASSERT_EQ(*sjIt, *csIt);
}
}
}
// std::cerr << "}" << std::endl;
return 0;
}
<commit_msg>Stress test demo is outdated, see test for sequence_journal.<commit_after><|endoftext|> |
<commit_before>//===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/MustExecute.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/AssemblyAnnotationWriter.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
bool LoopSafetyInfo::headerMayThrow() const {
return HeaderMayThrow;
}
bool LoopSafetyInfo::anyBlockMayThrow() const {
return MayThrow;
}
void LoopSafetyInfo::computeLoopSafetyInfo(Loop *CurLoop) {
assert(CurLoop != nullptr && "CurLoop can't be null");
BasicBlock *Header = CurLoop->getHeader();
// Iterate over header and compute safety info.
HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
MayThrow = HeaderMayThrow;
// Iterate over loop instructions and compute safety info.
// Skip header as it has been computed and stored in HeaderMayThrow.
// The first block in loopinfo.Blocks is guaranteed to be the header.
assert(Header == *CurLoop->getBlocks().begin() &&
"First block must be header");
for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
BBE = CurLoop->block_end();
(BB != BBE) && !MayThrow; ++BB)
MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
// Compute funclet colors if we might sink/hoist in a function with a funclet
// personality routine.
Function *Fn = CurLoop->getHeader()->getParent();
if (Fn->hasPersonalityFn())
if (Constant *PersonalityFn = Fn->getPersonalityFn())
if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
BlockColors = colorEHFunclets(*Fn);
}
/// Return true if we can prove that the given ExitBlock is not reached on the
/// first iteration of the given loop. That is, the backedge of the loop must
/// be executed before the ExitBlock is executed in any dynamic execution trace.
static bool CanProveNotTakenFirstIteration(BasicBlock *ExitBlock,
const DominatorTree *DT,
const Loop *CurLoop) {
auto *CondExitBlock = ExitBlock->getSinglePredecessor();
if (!CondExitBlock)
// expect unique exits
return false;
assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
if (!BI || !BI->isConditional())
return false;
// If condition is constant and false leads to ExitBlock then we always
// execute the true branch.
if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
if (!Cond)
return false;
// todo: this would be a lot more powerful if we used scev, but all the
// plumbing is currently missing to pass a pointer in from the pass
// Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
auto *RHS = Cond->getOperand(1);
if (!LHS || LHS->getParent() != CurLoop->getHeader())
return false;
auto DL = ExitBlock->getModule()->getDataLayout();
auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
IVStart, RHS,
{DL, /*TLI*/ nullptr,
DT, /*AC*/ nullptr, BI});
auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
if (!SimpleCst)
return false;
if (ExitBlock == BI->getSuccessor(0))
return SimpleCst->isZeroValue();
assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
return SimpleCst->isAllOnesValue();
}
/// Returns true if the instruction in a loop is guaranteed to execute at least
/// once.
bool llvm::isGuaranteedToExecute(const Instruction &Inst,
const DominatorTree *DT, const Loop *CurLoop,
const LoopSafetyInfo *SafetyInfo) {
// We have to check to make sure that the instruction dominates all
// of the exit blocks. If it doesn't, then there is a path out of the loop
// which does not execute this instruction, so we can't hoist it.
// If the instruction is in the header block for the loop (which is very
// common), it is always guaranteed to dominate the exit blocks. Since this
// is a common case, and can save some work, check it now.
if (Inst.getParent() == CurLoop->getHeader())
// If there's a throw in the header block, we can't guarantee we'll reach
// Inst unless we can prove that Inst comes before the potential implicit
// exit. At the moment, we use a (cheap) hack for the common case where
// the instruction of interest is the first one in the block.
return !SafetyInfo->headerMayThrow() ||
Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
// Somewhere in this loop there is an instruction which may throw and make us
// exit the loop.
if (SafetyInfo->anyBlockMayThrow())
return false;
// Note: There are two styles of reasoning intermixed below for
// implementation efficiency reasons. They are:
// 1) If we can prove that the instruction dominates all exit blocks, then we
// know the instruction must have executed on *some* iteration before we
// exit. We do not prove *which* iteration the instruction must execute on.
// 2) If we can prove that the instruction dominates the latch and all exits
// which might be taken on the first iteration, we know the instruction must
// execute on the first iteration. This second style allows a conditional
// exit before the instruction of interest which is provably not taken on the
// first iteration. This is a quite common case for range check like
// patterns. TODO: support loops with multiple latches.
const bool InstDominatesLatch =
CurLoop->getLoopLatch() != nullptr &&
DT->dominates(Inst.getParent(), CurLoop->getLoopLatch());
// Get the exit blocks for the current loop.
SmallVector<BasicBlock *, 8> ExitBlocks;
CurLoop->getExitBlocks(ExitBlocks);
// Verify that the block dominates each of the exit blocks of the loop.
for (BasicBlock *ExitBlock : ExitBlocks)
if (!DT->dominates(Inst.getParent(), ExitBlock))
if (!InstDominatesLatch ||
!CanProveNotTakenFirstIteration(ExitBlock, DT, CurLoop))
return false;
// As a degenerate case, if the loop is statically infinite then we haven't
// proven anything since there are no exit blocks.
if (ExitBlocks.empty())
return false;
// FIXME: In general, we have to prove that the loop isn't an infinite loop.
// See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
// just a special case of this.)
return true;
}
namespace {
struct MustExecutePrinter : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
MustExecutePrinter() : FunctionPass(ID) {
initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
}
bool runOnFunction(Function &F) override;
};
}
char MustExecutePrinter::ID = 0;
INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
"Instructions which execute on loop entry", false, true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
"Instructions which execute on loop entry", false, true)
FunctionPass *llvm::createMustExecutePrinter() {
return new MustExecutePrinter();
}
static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
// TODO: merge these two routines. For the moment, we display the best
// result obtained by *either* implementation. This is a bit unfair since no
// caller actually gets the full power at the moment.
LoopSafetyInfo LSI;
LSI.computeLoopSafetyInfo(L);
return isGuaranteedToExecute(I, DT, L, &LSI) ||
isGuaranteedToExecuteForEveryIteration(&I, L);
}
namespace {
/// An assembly annotator class to print must execute information in
/// comments.
class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
public:
MustExecuteAnnotatedWriter(const Function &F,
DominatorTree &DT, LoopInfo &LI) {
for (auto &I: instructions(F)) {
Loop *L = LI.getLoopFor(I.getParent());
while (L) {
if (isMustExecuteIn(I, L, &DT)) {
MustExec[&I].push_back(L);
}
L = L->getParentLoop();
};
}
}
MustExecuteAnnotatedWriter(const Module &M,
DominatorTree &DT, LoopInfo &LI) {
for (auto &F : M)
for (auto &I: instructions(F)) {
Loop *L = LI.getLoopFor(I.getParent());
while (L) {
if (isMustExecuteIn(I, L, &DT)) {
MustExec[&I].push_back(L);
}
L = L->getParentLoop();
};
}
}
void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
if (!MustExec.count(&V))
return;
const auto &Loops = MustExec.lookup(&V);
const auto NumLoops = Loops.size();
if (NumLoops > 1)
OS << " ; (mustexec in " << NumLoops << " loops: ";
else
OS << " ; (mustexec in: ";
bool first = true;
for (const Loop *L : Loops) {
if (!first)
OS << ", ";
first = false;
OS << L->getHeader()->getName();
}
OS << ")";
}
};
} // namespace
bool MustExecutePrinter::runOnFunction(Function &F) {
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
MustExecuteAnnotatedWriter Writer(F, DT, LI);
F.print(dbgs(), &Writer);
return false;
}
<commit_msg>[NFC] Add missing const modifier<commit_after>//===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/MustExecute.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/AssemblyAnnotationWriter.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
bool LoopSafetyInfo::headerMayThrow() const {
return HeaderMayThrow;
}
bool LoopSafetyInfo::anyBlockMayThrow() const {
return MayThrow;
}
void LoopSafetyInfo::computeLoopSafetyInfo(Loop *CurLoop) {
assert(CurLoop != nullptr && "CurLoop can't be null");
BasicBlock *Header = CurLoop->getHeader();
// Iterate over header and compute safety info.
HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
MayThrow = HeaderMayThrow;
// Iterate over loop instructions and compute safety info.
// Skip header as it has been computed and stored in HeaderMayThrow.
// The first block in loopinfo.Blocks is guaranteed to be the header.
assert(Header == *CurLoop->getBlocks().begin() &&
"First block must be header");
for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
BBE = CurLoop->block_end();
(BB != BBE) && !MayThrow; ++BB)
MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
// Compute funclet colors if we might sink/hoist in a function with a funclet
// personality routine.
Function *Fn = CurLoop->getHeader()->getParent();
if (Fn->hasPersonalityFn())
if (Constant *PersonalityFn = Fn->getPersonalityFn())
if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
BlockColors = colorEHFunclets(*Fn);
}
/// Return true if we can prove that the given ExitBlock is not reached on the
/// first iteration of the given loop. That is, the backedge of the loop must
/// be executed before the ExitBlock is executed in any dynamic execution trace.
static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
const DominatorTree *DT,
const Loop *CurLoop) {
auto *CondExitBlock = ExitBlock->getSinglePredecessor();
if (!CondExitBlock)
// expect unique exits
return false;
assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
if (!BI || !BI->isConditional())
return false;
// If condition is constant and false leads to ExitBlock then we always
// execute the true branch.
if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
if (!Cond)
return false;
// todo: this would be a lot more powerful if we used scev, but all the
// plumbing is currently missing to pass a pointer in from the pass
// Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
auto *RHS = Cond->getOperand(1);
if (!LHS || LHS->getParent() != CurLoop->getHeader())
return false;
auto DL = ExitBlock->getModule()->getDataLayout();
auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
IVStart, RHS,
{DL, /*TLI*/ nullptr,
DT, /*AC*/ nullptr, BI});
auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
if (!SimpleCst)
return false;
if (ExitBlock == BI->getSuccessor(0))
return SimpleCst->isZeroValue();
assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
return SimpleCst->isAllOnesValue();
}
/// Returns true if the instruction in a loop is guaranteed to execute at least
/// once.
bool llvm::isGuaranteedToExecute(const Instruction &Inst,
const DominatorTree *DT, const Loop *CurLoop,
const LoopSafetyInfo *SafetyInfo) {
// We have to check to make sure that the instruction dominates all
// of the exit blocks. If it doesn't, then there is a path out of the loop
// which does not execute this instruction, so we can't hoist it.
// If the instruction is in the header block for the loop (which is very
// common), it is always guaranteed to dominate the exit blocks. Since this
// is a common case, and can save some work, check it now.
if (Inst.getParent() == CurLoop->getHeader())
// If there's a throw in the header block, we can't guarantee we'll reach
// Inst unless we can prove that Inst comes before the potential implicit
// exit. At the moment, we use a (cheap) hack for the common case where
// the instruction of interest is the first one in the block.
return !SafetyInfo->headerMayThrow() ||
Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
// Somewhere in this loop there is an instruction which may throw and make us
// exit the loop.
if (SafetyInfo->anyBlockMayThrow())
return false;
// Note: There are two styles of reasoning intermixed below for
// implementation efficiency reasons. They are:
// 1) If we can prove that the instruction dominates all exit blocks, then we
// know the instruction must have executed on *some* iteration before we
// exit. We do not prove *which* iteration the instruction must execute on.
// 2) If we can prove that the instruction dominates the latch and all exits
// which might be taken on the first iteration, we know the instruction must
// execute on the first iteration. This second style allows a conditional
// exit before the instruction of interest which is provably not taken on the
// first iteration. This is a quite common case for range check like
// patterns. TODO: support loops with multiple latches.
const bool InstDominatesLatch =
CurLoop->getLoopLatch() != nullptr &&
DT->dominates(Inst.getParent(), CurLoop->getLoopLatch());
// Get the exit blocks for the current loop.
SmallVector<BasicBlock *, 8> ExitBlocks;
CurLoop->getExitBlocks(ExitBlocks);
// Verify that the block dominates each of the exit blocks of the loop.
for (BasicBlock *ExitBlock : ExitBlocks)
if (!DT->dominates(Inst.getParent(), ExitBlock))
if (!InstDominatesLatch ||
!CanProveNotTakenFirstIteration(ExitBlock, DT, CurLoop))
return false;
// As a degenerate case, if the loop is statically infinite then we haven't
// proven anything since there are no exit blocks.
if (ExitBlocks.empty())
return false;
// FIXME: In general, we have to prove that the loop isn't an infinite loop.
// See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
// just a special case of this.)
return true;
}
namespace {
struct MustExecutePrinter : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
MustExecutePrinter() : FunctionPass(ID) {
initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
}
bool runOnFunction(Function &F) override;
};
}
char MustExecutePrinter::ID = 0;
INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
"Instructions which execute on loop entry", false, true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
"Instructions which execute on loop entry", false, true)
FunctionPass *llvm::createMustExecutePrinter() {
return new MustExecutePrinter();
}
static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
// TODO: merge these two routines. For the moment, we display the best
// result obtained by *either* implementation. This is a bit unfair since no
// caller actually gets the full power at the moment.
LoopSafetyInfo LSI;
LSI.computeLoopSafetyInfo(L);
return isGuaranteedToExecute(I, DT, L, &LSI) ||
isGuaranteedToExecuteForEveryIteration(&I, L);
}
namespace {
/// An assembly annotator class to print must execute information in
/// comments.
class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
public:
MustExecuteAnnotatedWriter(const Function &F,
DominatorTree &DT, LoopInfo &LI) {
for (auto &I: instructions(F)) {
Loop *L = LI.getLoopFor(I.getParent());
while (L) {
if (isMustExecuteIn(I, L, &DT)) {
MustExec[&I].push_back(L);
}
L = L->getParentLoop();
};
}
}
MustExecuteAnnotatedWriter(const Module &M,
DominatorTree &DT, LoopInfo &LI) {
for (auto &F : M)
for (auto &I: instructions(F)) {
Loop *L = LI.getLoopFor(I.getParent());
while (L) {
if (isMustExecuteIn(I, L, &DT)) {
MustExec[&I].push_back(L);
}
L = L->getParentLoop();
};
}
}
void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
if (!MustExec.count(&V))
return;
const auto &Loops = MustExec.lookup(&V);
const auto NumLoops = Loops.size();
if (NumLoops > 1)
OS << " ; (mustexec in " << NumLoops << " loops: ";
else
OS << " ; (mustexec in: ";
bool first = true;
for (const Loop *L : Loops) {
if (!first)
OS << ", ";
first = false;
OS << L->getHeader()->getName();
}
OS << ")";
}
};
} // namespace
bool MustExecutePrinter::runOnFunction(Function &F) {
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
MustExecuteAnnotatedWriter Writer(F, DT, LI);
F.print(dbgs(), &Writer);
return false;
}
<|endoftext|> |
<commit_before>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
// this header must be generated by the build system (may be empty)
#include "caf/detail/build_config.hpp"
// Platform-specific adjustments.
#define CAF_CACHE_LINE_SIZE 64
// Config pararameters defined by the build system (usually CMake):
//
// CAF_ENABLE_RUNTIME_CHECKS:
// - check requirements at runtime
//
// CAF_LOG_LEVEL:
// - denotes the amount of logging, ranging from error messages only (0)
// to complete traces (4)
/// Denotes version of CAF in the format {MAJOR}{MINOR}{PATCH},
/// whereas each number is a two-digit decimal number without
/// leading zeros (e.g. 900 is version 0.9.0).
#define CAF_VERSION 1802
/// Defined to the major version number of CAF.
#define CAF_MAJOR_VERSION (CAF_VERSION / 10000)
/// Defined to the minor version number of CAF.
#define CAF_MINOR_VERSION ((CAF_VERSION / 100) % 100)
/// Defined to the patch version number of CAF.
#define CAF_PATCH_VERSION (CAF_VERSION % 100)
// This compiler-specific block defines:
// - CAF_DEPRECATED to annotate deprecated functions
// - CAF_PUSH_WARNINGS/CAF_POP_WARNINGS to surround "noisy" header includes
// - CAF_ANNOTATE_FALLTHROUGH to suppress warnings in switch/case statements
// - CAF_COMPILER_VERSION to retrieve the compiler version in CAF_VERSION format
// - One of the following:
// + CAF_CLANG
// + CAF_GCC
// + CAF_MSVC
// sets CAF_DEPRECATED, CAF_ANNOTATE_FALLTHROUGH,
// CAF_PUSH_WARNINGS and CAF_POP_WARNINGS
// clang-format off
#if defined(__clang__)
# define CAF_CLANG
# define CAF_LIKELY(x) __builtin_expect((x), 1)
# define CAF_UNLIKELY(x) __builtin_expect((x), 0)
# define CAF_DEPRECATED __attribute__((deprecated))
# define CAF_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))
# define CAF_PUSH_WARNINGS \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wall\"") \
_Pragma("clang diagnostic ignored \"-Wextra\"") \
_Pragma("clang diagnostic ignored \"-Wundef\"") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
_Pragma("clang diagnostic ignored \"-Wdeprecated\"") \
_Pragma("clang diagnostic ignored \"-Wextra-semi\"") \
_Pragma("clang diagnostic ignored \"-Wconversion\"") \
_Pragma("clang diagnostic ignored \"-Wcast-align\"") \
_Pragma("clang diagnostic ignored \"-Wfloat-equal\"") \
_Pragma("clang diagnostic ignored \"-Wswitch-enum\"") \
_Pragma("clang diagnostic ignored \"-Wweak-vtables\"") \
_Pragma("clang diagnostic ignored \"-Wdocumentation\"") \
_Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
_Pragma("clang diagnostic ignored \"-Wsign-conversion\"") \
_Pragma("clang diagnostic ignored \"-Wunused-template\"") \
_Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\"") \
_Pragma("clang diagnostic ignored \"-Wunreachable-code\"") \
_Pragma("clang diagnostic ignored \"-Wdouble-promotion\"") \
_Pragma("clang diagnostic ignored \"-Wc++14-extensions\"") \
_Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \
_Pragma("clang diagnostic ignored \"-Wnested-anon-types\"") \
_Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"") \
_Pragma("clang diagnostic ignored \"-Wconstant-conversion\"") \
_Pragma("clang diagnostic ignored \"-Wimplicit-fallthrough\"") \
_Pragma("clang diagnostic ignored \"-Wused-but-marked-unused\"") \
_Pragma("clang diagnostic ignored \"-Wdisabled-macro-expansion\"")
# define CAF_PUSH_UNUSED_LABEL_WARNING \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wunused-label\"")
# define CAF_PUSH_NON_VIRTUAL_DTOR_WARNING \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wnon-virtual-dtor\"")
# define CAF_PUSH_DEPRECATED_WARNING \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
# define CAF_POP_WARNINGS \
_Pragma("clang diagnostic pop")
# define CAF_ANNOTATE_FALLTHROUGH [[clang::fallthrough]]
# define CAF_COMPILER_VERSION \
(__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#elif defined(__GNUC__)
# define CAF_GCC
# define CAF_LIKELY(x) __builtin_expect((x), 1)
# define CAF_UNLIKELY(x) __builtin_expect((x), 0)
# define CAF_DEPRECATED __attribute__((deprecated))
# define CAF_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))
# define CAF_PUSH_WARNINGS \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wshadow\"") \
_Pragma("GCC diagnostic ignored \"-Wpragmas\"") \
_Pragma("GCC diagnostic ignored \"-Wpedantic\"") \
_Pragma("GCC diagnostic ignored \"-Wcast-qual\"") \
_Pragma("GCC diagnostic ignored \"-Wconversion\"") \
_Pragma("GCC diagnostic ignored \"-Wfloat-equal\"") \
_Pragma("GCC diagnostic ignored \"-Wc++14-extensions\"")
# define CAF_PUSH_UNUSED_LABEL_WARNING \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wunused-label\"")
# define CAF_PUSH_NON_VIRTUAL_DTOR_WARNING \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wnon-virtual-dtor\"")
# define CAF_PUSH_DEPRECATED_WARNING \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
# define CAF_POP_WARNINGS \
_Pragma("GCC diagnostic pop")
# if __GNUC__ >= 7
# define CAF_ANNOTATE_FALLTHROUGH __attribute__((fallthrough))
# else
# define CAF_ANNOTATE_FALLTHROUGH static_cast<void>(0)
# endif
# define CAF_COMPILER_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
// disable thread_local on GCC/macOS due to heap-use-after-free bug:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67135
#elif defined(_MSC_VER)
# define CAF_MSVC
# define CAF_LIKELY(x) x
# define CAF_UNLIKELY(x) x
# define CAF_DEPRECATED
# define CAF_DEPRECATED_MSG(msg)
# define CAF_PUSH_WARNINGS \
__pragma(warning(push))
# define CAF_PUSH_UNUSED_LABEL_WARNING \
__pragma(warning(push)) \
__pragma(warning(disable: 4102))
# define CAF_PUSH_DEPRECATED_WARNING \
__pragma(warning(push))
# define CAF_PUSH_NON_VIRTUAL_DTOR_WARNING \
__pragma(warning(push))
# define CAF_POP_WARNINGS __pragma(warning(pop))
# define CAF_ANNOTATE_FALLTHROUGH static_cast<void>(0)
# define CAF_COMPILER_VERSION _MSC_FULL_VER
# pragma warning( disable : 4624 )
# pragma warning( disable : 4800 )
# pragma warning( disable : 4503 )
# ifndef NOMINMAX
# define NOMINMAX
# endif // NOMINMAX
#else
# define CAF_LIKELY(x) x
# define CAF_UNLIKELY(x) x
# define CAF_DEPRECATED
# define CAF_PUSH_WARNINGS
# define CAF_PUSH_NON_VIRTUAL_DTOR_WARNING
# define CAF_PUSH_DEPRECATED_WARNING
# define CAF_POP_WARNINGS
# define CAF_ANNOTATE_FALLTHROUGH static_cast<void>(0)
#endif
// clang-format on
// This OS-specific block defines one of the following:
// - CAF_MACOS
// - CAF_LINUX
// - CAF_BSD
// - CAF_WINDOWS
// It also defines CAF_POSIX for POSIX-compatible systems
#if defined(__APPLE__)
# include "TargetConditionals.h"
# if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
# define CAF_IOS
# else
# define CAF_MACOS
# if defined(CAF_GCC) && !defined(_GLIBCXX_HAS_GTHREADS)
# define _GLIBCXX_HAS_GTHREADS
# endif
# endif
#elif defined(__ANDROID__)
# define CAF_ANDROID
#elif defined(__linux__)
# define CAF_LINUX
# include <linux/version.h>
# if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 16)
# define CAF_POLL_IMPL
# endif
#elif defined(__FreeBSD__)
# define CAF_BSD
#elif defined(__OpenBSD__)
# define CAF_BSD
#elif defined(__CYGWIN__)
# define CAF_CYGWIN
#elif defined(WIN32) || defined(_WIN32)
# define CAF_WINDOWS
#else
# error Platform and/or compiler not supported
#endif
#if defined(CAF_MACOS) || defined(CAF_LINUX) || defined(CAF_BSD) \
|| defined(CAF_CYGWIN)
# define CAF_POSIX
#endif
#if defined(CAF_WINDOWS) && defined(CAF_CLANG)
// Fix for issue with static_cast<> in objbase.h.
// See: https://github.com/philsquared/Catch/issues/690.
struct IUnknown;
#endif
#include <cstdio>
#include <cstdlib>
// Optionally enable CAF_ASSERT
#ifndef CAF_ENABLE_RUNTIME_CHECKS
# define CAF_ASSERT(unused) static_cast<void>(0)
#elif defined(CAF_WINDOWS) || defined(CAF_BSD)
# define CAF_ASSERT(stmt) \
if (static_cast<bool>(stmt) == false) { \
printf("%s:%u: requirement failed '%s'\n", __FILE__, __LINE__, #stmt); \
::abort(); \
} \
static_cast<void>(0)
#else // defined(CAF_LINUX) || defined(CAF_MACOS)
# include <execinfo.h>
# define CAF_ASSERT(stmt) \
if (static_cast<bool>(stmt) == false) { \
printf("%s:%u: requirement failed '%s'\n", __FILE__, __LINE__, #stmt); \
void* array[20]; \
auto caf_bt_size = ::backtrace(array, 20); \
::backtrace_symbols_fd(array, caf_bt_size, 2); \
::abort(); \
} \
static_cast<void>(0)
#endif
// Convenience macros.
#define CAF_IGNORE_UNUSED(x) static_cast<void>(x)
/// Prints `error` to `stderr` and aborts program execution.
#define CAF_CRITICAL(error) \
do { \
fprintf(stderr, "[FATAL] critical error (%s:%d): %s\n", __FILE__, \
__LINE__, error); \
::abort(); \
} while (false)
/// Prints `error` to `stderr` and aborts program execution.
#define CAF_CRITICAL_FMT(fmt_str, ...) \
do { \
fprintf(stderr, "[FATAL] critical error (%s:%d): " fmt_str "\n", __FILE__, \
__LINE__, __VA_ARGS__); \
::abort(); \
} while (false)
<commit_msg>Change version to 0.18.3<commit_after>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
// this header must be generated by the build system (may be empty)
#include "caf/detail/build_config.hpp"
// Platform-specific adjustments.
#define CAF_CACHE_LINE_SIZE 64
// Config pararameters defined by the build system (usually CMake):
//
// CAF_ENABLE_RUNTIME_CHECKS:
// - check requirements at runtime
//
// CAF_LOG_LEVEL:
// - denotes the amount of logging, ranging from error messages only (0)
// to complete traces (4)
/// Denotes version of CAF in the format {MAJOR}{MINOR}{PATCH},
/// whereas each number is a two-digit decimal number without
/// leading zeros (e.g. 900 is version 0.9.0).
#define CAF_VERSION 1803
/// Defined to the major version number of CAF.
#define CAF_MAJOR_VERSION (CAF_VERSION / 10000)
/// Defined to the minor version number of CAF.
#define CAF_MINOR_VERSION ((CAF_VERSION / 100) % 100)
/// Defined to the patch version number of CAF.
#define CAF_PATCH_VERSION (CAF_VERSION % 100)
// This compiler-specific block defines:
// - CAF_DEPRECATED to annotate deprecated functions
// - CAF_PUSH_WARNINGS/CAF_POP_WARNINGS to surround "noisy" header includes
// - CAF_ANNOTATE_FALLTHROUGH to suppress warnings in switch/case statements
// - CAF_COMPILER_VERSION to retrieve the compiler version in CAF_VERSION format
// - One of the following:
// + CAF_CLANG
// + CAF_GCC
// + CAF_MSVC
// sets CAF_DEPRECATED, CAF_ANNOTATE_FALLTHROUGH,
// CAF_PUSH_WARNINGS and CAF_POP_WARNINGS
// clang-format off
#if defined(__clang__)
# define CAF_CLANG
# define CAF_LIKELY(x) __builtin_expect((x), 1)
# define CAF_UNLIKELY(x) __builtin_expect((x), 0)
# define CAF_DEPRECATED __attribute__((deprecated))
# define CAF_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))
# define CAF_PUSH_WARNINGS \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wall\"") \
_Pragma("clang diagnostic ignored \"-Wextra\"") \
_Pragma("clang diagnostic ignored \"-Wundef\"") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
_Pragma("clang diagnostic ignored \"-Wdeprecated\"") \
_Pragma("clang diagnostic ignored \"-Wextra-semi\"") \
_Pragma("clang diagnostic ignored \"-Wconversion\"") \
_Pragma("clang diagnostic ignored \"-Wcast-align\"") \
_Pragma("clang diagnostic ignored \"-Wfloat-equal\"") \
_Pragma("clang diagnostic ignored \"-Wswitch-enum\"") \
_Pragma("clang diagnostic ignored \"-Wweak-vtables\"") \
_Pragma("clang diagnostic ignored \"-Wdocumentation\"") \
_Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
_Pragma("clang diagnostic ignored \"-Wsign-conversion\"") \
_Pragma("clang diagnostic ignored \"-Wunused-template\"") \
_Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\"") \
_Pragma("clang diagnostic ignored \"-Wunreachable-code\"") \
_Pragma("clang diagnostic ignored \"-Wdouble-promotion\"") \
_Pragma("clang diagnostic ignored \"-Wc++14-extensions\"") \
_Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \
_Pragma("clang diagnostic ignored \"-Wnested-anon-types\"") \
_Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"") \
_Pragma("clang diagnostic ignored \"-Wconstant-conversion\"") \
_Pragma("clang diagnostic ignored \"-Wimplicit-fallthrough\"") \
_Pragma("clang diagnostic ignored \"-Wused-but-marked-unused\"") \
_Pragma("clang diagnostic ignored \"-Wdisabled-macro-expansion\"")
# define CAF_PUSH_UNUSED_LABEL_WARNING \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wunused-label\"")
# define CAF_PUSH_NON_VIRTUAL_DTOR_WARNING \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wnon-virtual-dtor\"")
# define CAF_PUSH_DEPRECATED_WARNING \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
# define CAF_POP_WARNINGS \
_Pragma("clang diagnostic pop")
# define CAF_ANNOTATE_FALLTHROUGH [[clang::fallthrough]]
# define CAF_COMPILER_VERSION \
(__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#elif defined(__GNUC__)
# define CAF_GCC
# define CAF_LIKELY(x) __builtin_expect((x), 1)
# define CAF_UNLIKELY(x) __builtin_expect((x), 0)
# define CAF_DEPRECATED __attribute__((deprecated))
# define CAF_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))
# define CAF_PUSH_WARNINGS \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wshadow\"") \
_Pragma("GCC diagnostic ignored \"-Wpragmas\"") \
_Pragma("GCC diagnostic ignored \"-Wpedantic\"") \
_Pragma("GCC diagnostic ignored \"-Wcast-qual\"") \
_Pragma("GCC diagnostic ignored \"-Wconversion\"") \
_Pragma("GCC diagnostic ignored \"-Wfloat-equal\"") \
_Pragma("GCC diagnostic ignored \"-Wc++14-extensions\"")
# define CAF_PUSH_UNUSED_LABEL_WARNING \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wunused-label\"")
# define CAF_PUSH_NON_VIRTUAL_DTOR_WARNING \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wnon-virtual-dtor\"")
# define CAF_PUSH_DEPRECATED_WARNING \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
# define CAF_POP_WARNINGS \
_Pragma("GCC diagnostic pop")
# if __GNUC__ >= 7
# define CAF_ANNOTATE_FALLTHROUGH __attribute__((fallthrough))
# else
# define CAF_ANNOTATE_FALLTHROUGH static_cast<void>(0)
# endif
# define CAF_COMPILER_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
// disable thread_local on GCC/macOS due to heap-use-after-free bug:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67135
#elif defined(_MSC_VER)
# define CAF_MSVC
# define CAF_LIKELY(x) x
# define CAF_UNLIKELY(x) x
# define CAF_DEPRECATED
# define CAF_DEPRECATED_MSG(msg)
# define CAF_PUSH_WARNINGS \
__pragma(warning(push))
# define CAF_PUSH_UNUSED_LABEL_WARNING \
__pragma(warning(push)) \
__pragma(warning(disable: 4102))
# define CAF_PUSH_DEPRECATED_WARNING \
__pragma(warning(push))
# define CAF_PUSH_NON_VIRTUAL_DTOR_WARNING \
__pragma(warning(push))
# define CAF_POP_WARNINGS __pragma(warning(pop))
# define CAF_ANNOTATE_FALLTHROUGH static_cast<void>(0)
# define CAF_COMPILER_VERSION _MSC_FULL_VER
# pragma warning( disable : 4624 )
# pragma warning( disable : 4800 )
# pragma warning( disable : 4503 )
# ifndef NOMINMAX
# define NOMINMAX
# endif // NOMINMAX
#else
# define CAF_LIKELY(x) x
# define CAF_UNLIKELY(x) x
# define CAF_DEPRECATED
# define CAF_PUSH_WARNINGS
# define CAF_PUSH_NON_VIRTUAL_DTOR_WARNING
# define CAF_PUSH_DEPRECATED_WARNING
# define CAF_POP_WARNINGS
# define CAF_ANNOTATE_FALLTHROUGH static_cast<void>(0)
#endif
// clang-format on
// This OS-specific block defines one of the following:
// - CAF_MACOS
// - CAF_LINUX
// - CAF_BSD
// - CAF_WINDOWS
// It also defines CAF_POSIX for POSIX-compatible systems
#if defined(__APPLE__)
# include "TargetConditionals.h"
# if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
# define CAF_IOS
# else
# define CAF_MACOS
# if defined(CAF_GCC) && !defined(_GLIBCXX_HAS_GTHREADS)
# define _GLIBCXX_HAS_GTHREADS
# endif
# endif
#elif defined(__ANDROID__)
# define CAF_ANDROID
#elif defined(__linux__)
# define CAF_LINUX
# include <linux/version.h>
# if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 16)
# define CAF_POLL_IMPL
# endif
#elif defined(__FreeBSD__)
# define CAF_BSD
#elif defined(__OpenBSD__)
# define CAF_BSD
#elif defined(__CYGWIN__)
# define CAF_CYGWIN
#elif defined(WIN32) || defined(_WIN32)
# define CAF_WINDOWS
#else
# error Platform and/or compiler not supported
#endif
#if defined(CAF_MACOS) || defined(CAF_LINUX) || defined(CAF_BSD) \
|| defined(CAF_CYGWIN)
# define CAF_POSIX
#endif
#if defined(CAF_WINDOWS) && defined(CAF_CLANG)
// Fix for issue with static_cast<> in objbase.h.
// See: https://github.com/philsquared/Catch/issues/690.
struct IUnknown;
#endif
#include <cstdio>
#include <cstdlib>
// Optionally enable CAF_ASSERT
#ifndef CAF_ENABLE_RUNTIME_CHECKS
# define CAF_ASSERT(unused) static_cast<void>(0)
#elif defined(CAF_WINDOWS) || defined(CAF_BSD)
# define CAF_ASSERT(stmt) \
if (static_cast<bool>(stmt) == false) { \
printf("%s:%u: requirement failed '%s'\n", __FILE__, __LINE__, #stmt); \
::abort(); \
} \
static_cast<void>(0)
#else // defined(CAF_LINUX) || defined(CAF_MACOS)
# include <execinfo.h>
# define CAF_ASSERT(stmt) \
if (static_cast<bool>(stmt) == false) { \
printf("%s:%u: requirement failed '%s'\n", __FILE__, __LINE__, #stmt); \
void* array[20]; \
auto caf_bt_size = ::backtrace(array, 20); \
::backtrace_symbols_fd(array, caf_bt_size, 2); \
::abort(); \
} \
static_cast<void>(0)
#endif
// Convenience macros.
#define CAF_IGNORE_UNUSED(x) static_cast<void>(x)
/// Prints `error` to `stderr` and aborts program execution.
#define CAF_CRITICAL(error) \
do { \
fprintf(stderr, "[FATAL] critical error (%s:%d): %s\n", __FILE__, \
__LINE__, error); \
::abort(); \
} while (false)
/// Prints `error` to `stderr` and aborts program execution.
#define CAF_CRITICAL_FMT(fmt_str, ...) \
do { \
fprintf(stderr, "[FATAL] critical error (%s:%d): " fmt_str "\n", __FILE__, \
__LINE__, __VA_ARGS__); \
::abort(); \
} while (false)
<|endoftext|> |
<commit_before>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <sys/time.h>
// Serial includes
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif
#include "mavlink_serial.h"
#include "system_ids.h"
MavlinkSerial::MavlinkSerial() :
SerialPort(),
_command_id(0)
{
printf("default mavlink serial constructor\n");
}
MavlinkSerial::MavlinkSerial(bool verbose) :
SerialPort(verbose),
_command_id(0)
{
// nothing specific to do in this constructor
printf("verbose mavlink serial constructor\n");
}
MavlinkSerial::MavlinkSerial(bool verbose, const char* &uart_name, const int &baudrate) :
SerialPort(verbose, uart_name, baudrate),
_command_id(0)
{
printf("complex mavlink serial constructor\n");
printf("fd = %i\n", fd);
}
MavlinkSerial::~MavlinkSerial() {
// nothing to do in the destructor
// TODO: should probably close the file descriptor...
}
int MavlinkSerial::get_fd() {
printf("get fd = %i\n", fd);
return fd;
}
uint8_t MavlinkSerial::read_serial(mavlink_status_t *lastStatus, mavlink_message_t *message) {
// variables needed for the message reading
uint8_t cp; // not sure
mavlink_status_t status; // current message status
uint8_t msgReceived = false; // whether or not a message was correctly received
// read in from the file
if (read(fd, &cp, 1) > 0) {
// Check if a message could be decoded, return the message in case yes
msgReceived = mavlink_parse_char(MAVLINK_COMM_1, cp, message, &status);
// check the packet drop count to see if there was a packet dropped during this message reading
if (lastStatus->packet_rx_drop_count != status.packet_rx_drop_count) {
// print out some error information containing dropped packet indo
//if (_verbose) printf("ERROR: DROPPED %d PACKETS\n", status.packet_rx_drop_count);
// print out the characters of the packets themselves
if (_verbose) {
unsigned char v=cp;
fprintf(stderr,"%02x ", v);
}
}
// update the last message status
*lastStatus = status;
} else { // means unable to read from the serial device
// print out error as needed
if (_verbose) fprintf(stderr, "ERROR: Could not read from fd %d\n", fd);
}
// return whether or not the message was received
return msgReceived;
}
int MavlinkSerial::write_serial(mavlink_message_t &message) {
if (_verbose) printf("writing to pixhawk...\n");
// buffer needed for mavlink msg and function
char buf[300];
// Send message to buffer
unsigned len = mavlink_msg_to_send_buffer((uint8_t*)buf, &message);
// Write packet via serial link
write(fd, buf, len);
// Wait until all data has been written
tcdrain(fd);
if (_verbose) printf("wrote message of length %u\n", len);
return len;
}
// the mavlink specific functions
void MavlinkSerial::send_tracking_command(const float &north, const float &east, const float &alt) {
// TODO: add altitude as a tracking command input!!! (this is horrible to have it as a default here)
// retrieve the id of the last finished cmd
int nextCmd = _command_id++;
// extract the next north and east commands
float nextNorth = north;
float nextEast = east;
float nextAlt = alt;
printf("sending command %i: N %f\tE %f\tA %f\n", nextCmd, nextNorth, nextEast, nextAlt);
// build the mavlink message
mavlink_tracking_cmd_t tracking_cmd;
tracking_cmd.timestamp_usec = 0;
tracking_cmd.north = nextNorth;
tracking_cmd.east = nextEast;
tracking_cmd.yaw_angle = 270.0;
tracking_cmd.altitude = nextAlt;
tracking_cmd.cmd_id = nextCmd;
tracking_cmd.cmd_type = TRACKING_CMD_TRAVEL;
mavlink_message_t message;
mavlink_msg_tracking_cmd_encode(sysid, compid, &message, &tracking_cmd);
/* printing stuff for debug purposes */
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending next tracking command\n");
}
return;
}
void MavlinkSerial::send_rotate_command(const float direction) {
// retrieve the id of the last finished cmd
int nextCmd = _command_id++;
// build the mavlink message
mavlink_tracking_cmd_t tracking_cmd;
tracking_cmd.timestamp_usec = 0;
tracking_cmd.north = 0.0; // don't travel any distance north
tracking_cmd.east = 0.0; // don't travel any distacne east
tracking_cmd.yaw_angle = direction; // rotate clockwise (NOTE: yaw angle no longer means yaw angle, but rather rotation direction)
tracking_cmd.altitude = 0.0; // will have pixhawk just use current altitude
tracking_cmd.cmd_id = nextCmd;
tracking_cmd.cmd_type = TRACKING_CMD_ROTATE;
mavlink_message_t message;
mavlink_msg_tracking_cmd_encode(sysid, compid, &message, &tracking_cmd);
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending next rotate command\n");
}
return;
}
void MavlinkSerial::send_finish_command() {
// retrieve the id of the last finished cmd
int nextCmd = _command_id++;
// build the mavlink message
mavlink_tracking_cmd_t tracking_cmd;
tracking_cmd.timestamp_usec = 0;
tracking_cmd.north = 0.0;
tracking_cmd.east = 0.0;
tracking_cmd.yaw_angle = 0.0;
tracking_cmd.altitude = 0.0;
tracking_cmd.cmd_id = nextCmd;
tracking_cmd.cmd_type = TRACKING_CMD_FINISH;
mavlink_message_t message;
mavlink_msg_tracking_cmd_encode(sysid, compid, &message, &tracking_cmd);
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending finish command\n");
}
// printf("Sent buffer of length %i\n",len);
return;
}
void MavlinkSerial::send_bearing_cc_message(const double &bearing, const int32_t &lat, const int32_t &lon, const float &alt) {
// build the mavlink message
mavlink_bearing_cc_t bear;
bear.bearing = bearing;
bear.lat = lat;
bear.lon = lon;
bear.alt = alt;
mavlink_message_t message;
mavlink_msg_bearing_cc_encode(sysid, compid, &message, &bear);
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending bearing cc message\n");
}
return;
}
void MavlinkSerial::send_bearing_mle_message(const double &bearing, const int32_t &lat, const int32_t &lon, const float &alt) {
// build the mavlink message
mavlink_bearing_mle_t bear;
bear.bearing = bearing;
bear.lat = lat;
bear.lon = lon;
bear.alt = alt;
mavlink_message_t message;
mavlink_msg_bearing_mle_encode(sysid, compid, &message, &bear);
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending bearing mle message\n");
}
return;
}
void MavlinkSerial::send_rssi_message(const int &rssi, const int &rssi2, const int16_t &heading, const int32_t &lat, const int32_t &lon, const float &alt) {
mavlink_rssi_t rssi_msg;
rssi_msg.rssi_value = rssi;
rssi_msg.rssi_value2 = rssi2;
rssi_msg.heading = (float) heading;
rssi_msg.lat = lat; //lat;
rssi_msg.lon = lon; //lon;
rssi_msg.alt = alt; // alt;
mavlink_message_t message;
mavlink_msg_rssi_encode(sysid, compid, &message, &rssi_msg);
int len = write_serial(message);
if (len > 0 && _verbose) {
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long current_time = 1000000 * tv.tv_sec + tv.tv_usec;
printf("%lu: sending rssi message\n", current_time);
}
return;
}<commit_msg>remove annoying print statements<commit_after>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <sys/time.h>
// Serial includes
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif
#include "mavlink_serial.h"
#include "system_ids.h"
MavlinkSerial::MavlinkSerial() :
SerialPort(),
_command_id(0)
{
printf("default mavlink serial constructor\n");
}
MavlinkSerial::MavlinkSerial(bool verbose) :
SerialPort(verbose),
_command_id(0)
{
// nothing specific to do in this constructor
printf("verbose mavlink serial constructor\n");
}
MavlinkSerial::MavlinkSerial(bool verbose, const char* &uart_name, const int &baudrate) :
SerialPort(verbose, uart_name, baudrate),
_command_id(0)
{
printf("complex mavlink serial constructor\n");
printf("fd = %i\n", fd);
}
MavlinkSerial::~MavlinkSerial() {
// nothing to do in the destructor
// TODO: should probably close the file descriptor...
}
int MavlinkSerial::get_fd() {
printf("get fd = %i\n", fd);
return fd;
}
uint8_t MavlinkSerial::read_serial(mavlink_status_t *lastStatus, mavlink_message_t *message) {
// variables needed for the message reading
uint8_t cp; // not sure
mavlink_status_t status; // current message status
uint8_t msgReceived = false; // whether or not a message was correctly received
// read in from the file
if (read(fd, &cp, 1) > 0) {
// Check if a message could be decoded, return the message in case yes
msgReceived = mavlink_parse_char(MAVLINK_COMM_1, cp, message, &status);
// check the packet drop count to see if there was a packet dropped during this message reading
if (lastStatus->packet_rx_drop_count != status.packet_rx_drop_count) {
// print out some error information containing dropped packet indo
//if (_verbose) printf("ERROR: DROPPED %d PACKETS\n", status.packet_rx_drop_count);
// print out the characters of the packets themselves
/*
if (_verbose) {
unsigned char v=cp;
fprintf(stderr,"%02x ", v);
}
*/
}
// update the last message status
*lastStatus = status;
} else { // means unable to read from the serial device
// print out error as needed
if (_verbose) fprintf(stderr, "ERROR: Could not read from fd %d\n", fd);
}
// return whether or not the message was received
return msgReceived;
}
int MavlinkSerial::write_serial(mavlink_message_t &message) {
if (_verbose) printf("writing to pixhawk...\n");
// buffer needed for mavlink msg and function
char buf[300];
// Send message to buffer
unsigned len = mavlink_msg_to_send_buffer((uint8_t*)buf, &message);
// Write packet via serial link
write(fd, buf, len);
// Wait until all data has been written
tcdrain(fd);
if (_verbose) printf("wrote message of length %u\n", len);
return len;
}
// the mavlink specific functions
void MavlinkSerial::send_tracking_command(const float &north, const float &east, const float &alt) {
// TODO: add altitude as a tracking command input!!! (this is horrible to have it as a default here)
// retrieve the id of the last finished cmd
int nextCmd = _command_id++;
// extract the next north and east commands
float nextNorth = north;
float nextEast = east;
float nextAlt = alt;
printf("sending command %i: N %f\tE %f\tA %f\n", nextCmd, nextNorth, nextEast, nextAlt);
// build the mavlink message
mavlink_tracking_cmd_t tracking_cmd;
tracking_cmd.timestamp_usec = 0;
tracking_cmd.north = nextNorth;
tracking_cmd.east = nextEast;
tracking_cmd.yaw_angle = 270.0;
tracking_cmd.altitude = nextAlt;
tracking_cmd.cmd_id = nextCmd;
tracking_cmd.cmd_type = TRACKING_CMD_TRAVEL;
mavlink_message_t message;
mavlink_msg_tracking_cmd_encode(sysid, compid, &message, &tracking_cmd);
/* printing stuff for debug purposes */
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending next tracking command\n");
}
return;
}
void MavlinkSerial::send_rotate_command(const float direction) {
// retrieve the id of the last finished cmd
int nextCmd = _command_id++;
// build the mavlink message
mavlink_tracking_cmd_t tracking_cmd;
tracking_cmd.timestamp_usec = 0;
tracking_cmd.north = 0.0; // don't travel any distance north
tracking_cmd.east = 0.0; // don't travel any distacne east
tracking_cmd.yaw_angle = direction; // rotate clockwise (NOTE: yaw angle no longer means yaw angle, but rather rotation direction)
tracking_cmd.altitude = 0.0; // will have pixhawk just use current altitude
tracking_cmd.cmd_id = nextCmd;
tracking_cmd.cmd_type = TRACKING_CMD_ROTATE;
mavlink_message_t message;
mavlink_msg_tracking_cmd_encode(sysid, compid, &message, &tracking_cmd);
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending next rotate command\n");
}
return;
}
void MavlinkSerial::send_finish_command() {
// retrieve the id of the last finished cmd
int nextCmd = _command_id++;
// build the mavlink message
mavlink_tracking_cmd_t tracking_cmd;
tracking_cmd.timestamp_usec = 0;
tracking_cmd.north = 0.0;
tracking_cmd.east = 0.0;
tracking_cmd.yaw_angle = 0.0;
tracking_cmd.altitude = 0.0;
tracking_cmd.cmd_id = nextCmd;
tracking_cmd.cmd_type = TRACKING_CMD_FINISH;
mavlink_message_t message;
mavlink_msg_tracking_cmd_encode(sysid, compid, &message, &tracking_cmd);
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending finish command\n");
}
// printf("Sent buffer of length %i\n",len);
return;
}
void MavlinkSerial::send_bearing_cc_message(const double &bearing, const int32_t &lat, const int32_t &lon, const float &alt) {
// build the mavlink message
mavlink_bearing_cc_t bear;
bear.bearing = bearing;
bear.lat = lat;
bear.lon = lon;
bear.alt = alt;
mavlink_message_t message;
mavlink_msg_bearing_cc_encode(sysid, compid, &message, &bear);
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending bearing cc message\n");
}
return;
}
void MavlinkSerial::send_bearing_mle_message(const double &bearing, const int32_t &lat, const int32_t &lon, const float &alt) {
// build the mavlink message
mavlink_bearing_mle_t bear;
bear.bearing = bearing;
bear.lat = lat;
bear.lon = lon;
bear.alt = alt;
mavlink_message_t message;
mavlink_msg_bearing_mle_encode(sysid, compid, &message, &bear);
int len = write_serial(message);
if (len > 0 && _verbose) {
printf("sending bearing mle message\n");
}
return;
}
void MavlinkSerial::send_rssi_message(const int &rssi, const int &rssi2, const int16_t &heading, const int32_t &lat, const int32_t &lon, const float &alt) {
mavlink_rssi_t rssi_msg;
rssi_msg.rssi_value = rssi;
rssi_msg.rssi_value2 = rssi2;
rssi_msg.heading = (float) heading;
rssi_msg.lat = lat; //lat;
rssi_msg.lon = lon; //lon;
rssi_msg.alt = alt; // alt;
mavlink_message_t message;
mavlink_msg_rssi_encode(sysid, compid, &message, &rssi_msg);
int len = write_serial(message);
if (len > 0 && _verbose) {
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long current_time = 1000000 * tv.tv_sec + tv.tv_usec;
printf("%lu: sending rssi message\n", current_time);
}
return;
}<|endoftext|> |
<commit_before>//== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a basic region store model. In this model, we do have field
// sensitivity. But we assume nothing about the heap shape. So recursive data
// structures are largely ignored. Basically we do 1-limiting analysis.
// Parameter pointers are assumed with no aliasing. Pointee objects of
// parameters are created lazily.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/MemRegion.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "clang/Analysis/Analyses/LiveVariables.h"
#include "llvm/ADT/ImmutableMap.h"
#include "llvm/Support/Compiler.h"
using namespace clang;
typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy;
namespace {
class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager {
RegionBindingsTy::Factory RBFactory;
GRStateManager& StateMgr;
MemRegionManager MRMgr;
public:
RegionStoreManager(GRStateManager& mgr)
: StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {}
virtual ~RegionStoreManager() {}
SVal getLValueVar(const GRState* St, const VarDecl* VD);
SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base);
SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D);
SVal Retrieve(Store S, Loc L, QualType T);
Store Bind(Store St, Loc LV, SVal V);
Store getInitialStore();
Store AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal,
unsigned Count);
Loc getVarLoc(const VarDecl* VD) {
return loc::MemRegionVal(MRMgr.getVarRegion(VD));
}
Loc getElementLoc(const VarDecl* VD, SVal Idx);
static inline RegionBindingsTy GetRegionBindings(Store store) {
return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store));
}
};
} // end anonymous namespace
StoreManager* clang::CreateRegionStoreManager(GRStateManager& StMgr) {
// return new RegionStoreManager(StMgr);
return 0; // Uncomment the above line when RegionStoreManager is not abstract.
}
Loc RegionStoreManager::getElementLoc(const VarDecl* VD, SVal Idx) {
MemRegion* R = MRMgr.getVarRegion(VD);
ElementRegion* ER = MRMgr.getElementRegion(Idx, R);
return loc::MemRegionVal(ER);
}
SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) {
return loc::MemRegionVal(MRMgr.getVarRegion(VD));
}
SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D,
SVal Base) {
return UnknownVal();
}
SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base,
const FieldDecl* D) {
if (Base.isUnknownOrUndef())
return Base;
Loc BaseL = cast<Loc>(Base);
const MemRegion* BaseR = 0;
switch (BaseL.getSubKind()) {
case loc::MemRegionKind:
BaseR = cast<loc::MemRegionVal>(BaseL).getRegion();
break;
case loc::SymbolValKind:
BaseR = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(&BaseL)->getSymbol());
break;
case loc::GotoLabelKind:
case loc::FuncValKind:
// These are anormal cases. Flag an undefined value.
return UndefinedVal();
case loc::ConcreteIntKind:
case loc::StringLiteralValKind:
// While these seem funny, this can happen through casts.
// FIXME: What we should return is the field offset. For example,
// add the field offset to the integer value. That way funny things
// like this work properly: &(((struct foo *) 0xa)->f)
return Base;
default:
assert("Unhandled Base.");
return Base;
}
return loc::MemRegionVal(MRMgr.getFieldRegion(D, BaseR));
}
SVal RegionStoreManager::Retrieve(Store S, Loc L, QualType T) {
assert(!isa<UnknownVal>(L) && "location unknown");
assert(!isa<UndefinedVal>(L) && "location undefined");
switch (L.getSubKind()) {
case loc::MemRegionKind: {
const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion();
assert(R && "bad region");
RegionBindingsTy B(static_cast<const RegionBindingsTy::TreeTy*>(S));
RegionBindingsTy::data_type* V = B.lookup(R);
return V ? *V : UnknownVal();
}
case loc::SymbolValKind:
return UnknownVal();
case loc::ConcreteIntKind:
return UndefinedVal(); // As in BasicStoreManager.
case loc::FuncValKind:
return L;
case loc::StringLiteralValKind:
return UnknownVal();
default:
assert(false && "Invalid Location");
break;
}
}
Store RegionStoreManager::Bind(Store store, Loc LV, SVal V) {
assert(LV.getSubKind() == loc::MemRegionKind);
const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion();
if (!R)
return store;
RegionBindingsTy B = GetRegionBindings(store);
return V.isUnknown()
? RBFactory.Remove(B, R).getRoot()
: RBFactory.Add(B, R, V).getRoot();
}
Store RegionStoreManager::getInitialStore() {
typedef LiveVariables::AnalysisDataTy LVDataTy;
LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData();
Store St = RBFactory.GetEmptyMap().getRoot();
for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) {
NamedDecl* ND = const_cast<NamedDecl*>(I->first);
if (VarDecl* VD = dyn_cast<VarDecl>(ND)) {
// Punt on static variables for now.
if (VD->getStorageClass() == VarDecl::Static)
continue;
QualType T = VD->getType();
// Only handle pointers and integers for now.
if (Loc::IsLocType(T) || T->isIntegerType()) {
// Initialize globals and parameters to symbolic values.
// Initialize local variables to undefined.
SVal X = (VD->hasGlobalStorage() || isa<ParmVarDecl>(VD) ||
isa<ImplicitParamDecl>(VD))
? SVal::GetSymbolValue(StateMgr.getSymbolManager(), VD)
: UndefinedVal();
St = Bind(St, getVarLoc(VD), X);
}
}
}
return St;
}
Store RegionStoreManager::AddDecl(Store store,
const VarDecl* VD, Expr* Ex,
SVal InitVal, unsigned Count) {
BasicValueFactory& BasicVals = StateMgr.getBasicVals();
SymbolManager& SymMgr = StateMgr.getSymbolManager();
if (VD->hasGlobalStorage()) {
// Static global variables should not be visited here.
assert(!(VD->getStorageClass() == VarDecl::Static &&
VD->isFileVarDecl()));
// Process static variables.
if (VD->getStorageClass() == VarDecl::Static) {
if (!Ex) {
// Only handle pointer and integer static variables.
QualType T = VD->getType();
if (Loc::IsLocType(T))
store = Bind(store, getVarLoc(VD),
loc::ConcreteInt(BasicVals.getValue(0, T)));
else if (T->isIntegerType())
store = Bind(store, getVarLoc(VD),
loc::ConcreteInt(BasicVals.getValue(0, T)));
else
assert("ignore other types of variables");
} else {
store = Bind(store, getVarLoc(VD), InitVal);
}
}
} else {
// Process local variables.
QualType T = VD->getType();
if (Loc::IsLocType(T) || T->isIntegerType()) {
SVal V = Ex ? InitVal : UndefinedVal();
if (Ex && InitVal.isUnknown()) {
// "Conjured" symbols.
SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count);
V = Loc::IsLocType(Ex->getType())
? cast<SVal>(loc::SymbolVal(Sym))
: cast<SVal>(nonloc::SymbolVal(Sym));
}
store = Bind(store, getVarLoc(VD), V);
} else if (T->isArrayType()) {
// Only handle constant size array.
if (ConstantArrayType* CAT=dyn_cast<ConstantArrayType>(T.getTypePtr())) {
llvm::APInt Size = CAT->getSize();
for (llvm::APInt i = llvm::APInt::getNullValue(Size.getBitWidth());
i != Size; ++i) {
nonloc::ConcreteInt Idx(BasicVals.getValue(llvm::APSInt(i)));
store = Bind(store, getElementLoc(VD, Idx), UndefinedVal());
}
}
} else if (T->isStructureType()) {
// FIXME: Implement struct initialization.
}
}
return store;
}
<commit_msg>Added getLValueElement() to RegionStore. Only handle constant array for now.<commit_after>//== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a basic region store model. In this model, we do have field
// sensitivity. But we assume nothing about the heap shape. So recursive data
// structures are largely ignored. Basically we do 1-limiting analysis.
// Parameter pointers are assumed with no aliasing. Pointee objects of
// parameters are created lazily.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/MemRegion.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "clang/Analysis/Analyses/LiveVariables.h"
#include "llvm/ADT/ImmutableMap.h"
#include "llvm/Support/Compiler.h"
using namespace clang;
typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy;
namespace {
class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager {
RegionBindingsTy::Factory RBFactory;
GRStateManager& StateMgr;
MemRegionManager MRMgr;
public:
RegionStoreManager(GRStateManager& mgr)
: StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {}
virtual ~RegionStoreManager() {}
SVal getLValueVar(const GRState* St, const VarDecl* VD);
SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base);
SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D);
SVal getLValueElement(const GRState* St, SVal Base, SVal Offset);
SVal ArrayToPointer(SVal Array);
SVal Retrieve(Store S, Loc L, QualType T);
Store Bind(Store St, Loc LV, SVal V);
Store getInitialStore();
Store AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal,
unsigned Count);
Loc getVarLoc(const VarDecl* VD) {
return loc::MemRegionVal(MRMgr.getVarRegion(VD));
}
Loc getElementLoc(const VarDecl* VD, SVal Idx);
static inline RegionBindingsTy GetRegionBindings(Store store) {
return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store));
}
};
} // end anonymous namespace
StoreManager* clang::CreateRegionStoreManager(GRStateManager& StMgr) {
// return new RegionStoreManager(StMgr);
return 0; // Uncomment the above line when RegionStoreManager is not abstract.
}
Loc RegionStoreManager::getElementLoc(const VarDecl* VD, SVal Idx) {
MemRegion* R = MRMgr.getVarRegion(VD);
ElementRegion* ER = MRMgr.getElementRegion(Idx, R);
return loc::MemRegionVal(ER);
}
SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) {
return loc::MemRegionVal(MRMgr.getVarRegion(VD));
}
SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D,
SVal Base) {
return UnknownVal();
}
SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base,
const FieldDecl* D) {
if (Base.isUnknownOrUndef())
return Base;
Loc BaseL = cast<Loc>(Base);
const MemRegion* BaseR = 0;
switch (BaseL.getSubKind()) {
case loc::MemRegionKind:
BaseR = cast<loc::MemRegionVal>(BaseL).getRegion();
break;
case loc::SymbolValKind:
BaseR = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(&BaseL)->getSymbol());
break;
case loc::GotoLabelKind:
case loc::FuncValKind:
// These are anormal cases. Flag an undefined value.
return UndefinedVal();
case loc::ConcreteIntKind:
case loc::StringLiteralValKind:
// While these seem funny, this can happen through casts.
// FIXME: What we should return is the field offset. For example,
// add the field offset to the integer value. That way funny things
// like this work properly: &(((struct foo *) 0xa)->f)
return Base;
default:
assert("Unhandled Base.");
return Base;
}
return loc::MemRegionVal(MRMgr.getFieldRegion(D, BaseR));
}
SVal RegionStoreManager::getLValueElement(const GRState* St,
SVal Base, SVal Offset) {
if (Base.isUnknownOrUndef())
return Base;
loc::MemRegionVal& BaseL = cast<loc::MemRegionVal>(Base);
// We expect BaseR is an ElementRegion, not a base VarRegion.
const ElementRegion* ElemR = cast<ElementRegion>(BaseL.getRegion());
SVal Idx = ElemR->getIndex();
nonloc::ConcreteInt *CI1, *CI2;
// Only handle integer indices for now.
if ((CI1 = dyn_cast<nonloc::ConcreteInt>(&Idx)) &&
(CI2 = dyn_cast<nonloc::ConcreteInt>(&Offset))) {
SVal NewIdx = CI1->EvalBinOp(StateMgr.getBasicVals(), BinaryOperator::Add,
*CI2);
return loc::MemRegionVal(MRMgr.getElementRegion(NewIdx,
ElemR->getSuperRegion()));
}
return UnknownVal();
}
// Cast 'pointer to array' to 'pointer to the first element of array'.
SVal RegionStoreManager::ArrayToPointer(SVal Array) {
const MemRegion* ArrayR = cast<loc::MemRegionVal>(&Array)->getRegion();
const VarDecl* D = cast<VarRegion>(ArrayR)->getDecl();
if (const ConstantArrayType* CAT =
dyn_cast<ConstantArrayType>(D->getType().getTypePtr())) {
BasicValueFactory& BasicVals = StateMgr.getBasicVals();
nonloc::ConcreteInt Idx(BasicVals.getValue(0, CAT->getSize().getBitWidth(),
false));
ElementRegion* ER = MRMgr.getElementRegion(Idx, ArrayR);
return loc::MemRegionVal(ER);
}
return Array;
}
SVal RegionStoreManager::Retrieve(Store S, Loc L, QualType T) {
assert(!isa<UnknownVal>(L) && "location unknown");
assert(!isa<UndefinedVal>(L) && "location undefined");
switch (L.getSubKind()) {
case loc::MemRegionKind: {
const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion();
assert(R && "bad region");
RegionBindingsTy B(static_cast<const RegionBindingsTy::TreeTy*>(S));
RegionBindingsTy::data_type* V = B.lookup(R);
return V ? *V : UnknownVal();
}
case loc::SymbolValKind:
return UnknownVal();
case loc::ConcreteIntKind:
return UndefinedVal(); // As in BasicStoreManager.
case loc::FuncValKind:
return L;
case loc::StringLiteralValKind:
return UnknownVal();
default:
assert(false && "Invalid Location");
break;
}
}
Store RegionStoreManager::Bind(Store store, Loc LV, SVal V) {
assert(LV.getSubKind() == loc::MemRegionKind);
const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion();
if (!R)
return store;
RegionBindingsTy B = GetRegionBindings(store);
return V.isUnknown()
? RBFactory.Remove(B, R).getRoot()
: RBFactory.Add(B, R, V).getRoot();
}
Store RegionStoreManager::getInitialStore() {
typedef LiveVariables::AnalysisDataTy LVDataTy;
LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData();
Store St = RBFactory.GetEmptyMap().getRoot();
for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) {
NamedDecl* ND = const_cast<NamedDecl*>(I->first);
if (VarDecl* VD = dyn_cast<VarDecl>(ND)) {
// Punt on static variables for now.
if (VD->getStorageClass() == VarDecl::Static)
continue;
QualType T = VD->getType();
// Only handle pointers and integers for now.
if (Loc::IsLocType(T) || T->isIntegerType()) {
// Initialize globals and parameters to symbolic values.
// Initialize local variables to undefined.
SVal X = (VD->hasGlobalStorage() || isa<ParmVarDecl>(VD) ||
isa<ImplicitParamDecl>(VD))
? SVal::GetSymbolValue(StateMgr.getSymbolManager(), VD)
: UndefinedVal();
St = Bind(St, getVarLoc(VD), X);
}
}
}
return St;
}
Store RegionStoreManager::AddDecl(Store store,
const VarDecl* VD, Expr* Ex,
SVal InitVal, unsigned Count) {
BasicValueFactory& BasicVals = StateMgr.getBasicVals();
SymbolManager& SymMgr = StateMgr.getSymbolManager();
if (VD->hasGlobalStorage()) {
// Static global variables should not be visited here.
assert(!(VD->getStorageClass() == VarDecl::Static &&
VD->isFileVarDecl()));
// Process static variables.
if (VD->getStorageClass() == VarDecl::Static) {
if (!Ex) {
// Only handle pointer and integer static variables.
QualType T = VD->getType();
if (Loc::IsLocType(T))
store = Bind(store, getVarLoc(VD),
loc::ConcreteInt(BasicVals.getValue(0, T)));
else if (T->isIntegerType())
store = Bind(store, getVarLoc(VD),
loc::ConcreteInt(BasicVals.getValue(0, T)));
else
assert("ignore other types of variables");
} else {
store = Bind(store, getVarLoc(VD), InitVal);
}
}
} else {
// Process local variables.
QualType T = VD->getType();
if (Loc::IsLocType(T) || T->isIntegerType()) {
SVal V = Ex ? InitVal : UndefinedVal();
if (Ex && InitVal.isUnknown()) {
// "Conjured" symbols.
SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count);
V = Loc::IsLocType(Ex->getType())
? cast<SVal>(loc::SymbolVal(Sym))
: cast<SVal>(nonloc::SymbolVal(Sym));
}
store = Bind(store, getVarLoc(VD), V);
} else if (T->isArrayType()) {
// Only handle constant size array.
if (ConstantArrayType* CAT=dyn_cast<ConstantArrayType>(T.getTypePtr())) {
llvm::APInt Size = CAT->getSize();
for (llvm::APInt i = llvm::APInt::getNullValue(Size.getBitWidth());
i != Size; ++i) {
nonloc::ConcreteInt Idx(BasicVals.getValue(llvm::APSInt(i)));
store = Bind(store, getElementLoc(VD, Idx), UndefinedVal());
}
}
} else if (T->isStructureType()) {
// FIXME: Implement struct initialization.
}
}
return store;
}
<|endoftext|> |
<commit_before>#include <xcb/xcb.h>
#include <string>
#include <xgl.h>
typedef HWND (*xcbConnectType)();
typedef void (*xcbCreateWindowType)(uint16_t width, uint16_t height);
typedef void (*xcbDestroyWindowType)();
typedef int (*xcbGetMessageType)(MSG * msg);
typedef BOOL (*xcbPeekMessageType)(MSG * msg);
struct xcb_connection_t {
xcb_screen_t screens[1];
xcb_setup_t setup;
HMODULE xcbNvidia;
xcbConnectType xcbConnect;
xcbCreateWindowType xcbCreateWindow;
xcbDestroyWindowType xcbDestroyWindow;
xcbGetMessageType xcbGetMessage;
xcbPeekMessageType xcbPeekMessage;
HWND hwnd;
};
xcb_connection_t * xcb_connect(const char *displayname, int *screenp)
{
std::string xglNvidia = (getenv("XGL_DRIVERS_PATH") == NULL) ? "" : getenv("XGL_DRIVERS_PATH");
xglNvidia += "\\XGL_nvidia.dll";
HMODULE module = LoadLibrary(xglNvidia.c_str());
if (!module) {
std::string xglNulldrv = (getenv("LIBXGL_DRIVERS_PATH") == NULL) ? "" : getenv("LIBXGL_DRIVERS_PATH");
xglNulldrv += "\\xgl_nulldrv.dll";
module = LoadLibrary(xglNulldrv.c_str());
}
if (!module) {
// TODO: Adapted up the following code (copied from "loader.c"):
#define INITIAL_STR_LEN 1024
char *registry_str = (char *) malloc(INITIAL_STR_LEN);
DWORD registry_len = INITIAL_STR_LEN;
DWORD registry_value_type;
LONG registry_return_value;
char *rtn_str = NULL;
size_t rtn_len;
registry_return_value = RegGetValue(HKEY_LOCAL_MACHINE, "Software\\XGL",
"XGL_DRIVERS_PATH",
(RRF_RT_REG_SZ | RRF_ZEROONFAILURE),
®istry_value_type,
(PVOID) registry_str,
®istry_len);
rtn_len = registry_len + 16;
rtn_str = (char *) malloc(rtn_len);
_snprintf(rtn_str, rtn_len, "%s\\%s", registry_str, "xgl_nvidia.dll");
module = LoadLibrary(rtn_str);
}
if (!module) {
return 0;
}
xcb_connection_t * connection = (xcb_connection_t *)calloc(1, sizeof(xcb_connection_t));
connection->xcbNvidia = module;
connection->xcbConnect = (xcbConnectType)GetProcAddress(module, "xcbConnect");
connection->xcbCreateWindow = (xcbCreateWindowType)GetProcAddress(module, "xcbCreateWindow");
connection->xcbDestroyWindow = (xcbDestroyWindowType)GetProcAddress(module, "xcbDestroyWindow");
connection->xcbGetMessage = (xcbGetMessageType)GetProcAddress(module, "xcbGetMessage");
connection->xcbPeekMessage = (xcbPeekMessageType)GetProcAddress(module, "xcbPeekMessage");
if (!connection->xcbConnect) {
return 0;
}
connection->hwnd = connection->xcbConnect();
*screenp = 0;
return static_cast<xcb_connection_t *>(connection);
}
void xcb_disconnect(xcb_connection_t *c)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
FreeLibrary(connection->xcbNvidia);
free(connection);
}
int xcb_flush(xcb_connection_t * c)
{
return 0;
}
static xcb_generic_event_t* TranslateWindowsMsg(MSG * msg)
{
switch (msg->message) {
case WM_PAINT:
{
xcb_generic_event_t * event = (xcb_generic_event_t *)calloc(1, sizeof (xcb_generic_event_t));
event->response_type = XCB_EXPOSE;
return event;
}
break;
case WM_KEYUP:
{
xcb_key_release_event_t * event = (xcb_key_release_event_t *)calloc(1, sizeof (xcb_key_release_event_t));
event->response_type = XCB_KEY_RELEASE;
// TODO: What's the correct mapping?
switch (msg->wParam) {
case VK_ESCAPE:
event->detail = 0x09;
break;
case VK_LEFT:
event->detail = 0x71;
break;
case VK_RIGHT:
event->detail = 0x72;
break;
case VK_SPACE:
event->detail = 0x41;
break;
default:
event->detail = (xcb_keycode_t)msg->wParam;
break;
}
return (xcb_generic_event_t *)event;
}
break;
case WM_DESTROY:
{
xcb_generic_event_t * event = (xcb_generic_event_t *)calloc(1, sizeof (xcb_generic_event_t));
event->response_type = XCB_DESTROY_NOTIFY;
return event;
}
break;
default:
return 0;
}
return 0;
}
xcb_generic_event_t* xcb_wait_for_event(xcb_connection_t * c)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
MSG msg;
int result = connection->xcbGetMessage(&msg);
if (result > 0) {
return TranslateWindowsMsg(&msg);
} else if (result == 0) {
xcb_generic_event_t * event = (xcb_generic_event_t *)calloc(1, sizeof (xcb_generic_event_t));
event->response_type = XCB_DESTROY_NOTIFY;
return event;
}
return 0;
}
xcb_generic_event_t *xcb_poll_for_event(xcb_connection_t *c)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
MSG msg;
if (connection->xcbPeekMessage(&msg)) {
return TranslateWindowsMsg(&msg);
}
return 0;
}
uint32_t xcb_generate_id(xcb_connection_t *c)
{
// This is a MONSTER hack to make XGL_nvidia compatible with both
// the LunarG apps and Dota2.
return (uint32_t)c->hwnd;
}
xcb_void_cookie_t
xcb_create_window(xcb_connection_t *c,
uint8_t depth,
xcb_window_t wid,
xcb_window_t parent,
int16_t x,
int16_t y,
uint16_t width,
uint16_t height,
uint16_t border_width,
uint16_t _class,
xcb_visualid_t visual,
uint32_t value_mask,
const uint32_t *value_list)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
connection->xcbCreateWindow(width, height);
xcb_void_cookie_t cookie = { };
return cookie;
}
xcb_void_cookie_t
xcb_destroy_window(xcb_connection_t *c,
xcb_window_t window)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
connection->xcbDestroyWindow();
xcb_void_cookie_t cookie = { };
return cookie;
}
xcb_intern_atom_cookie_t
xcb_intern_atom(xcb_connection_t *c,
uint8_t only_if_exists,
uint16_t name_len,
const char *name)
{
xcb_intern_atom_cookie_t cookie = { };
return cookie;
}
xcb_intern_atom_reply_t *
xcb_intern_atom_reply(xcb_connection_t *c,
xcb_intern_atom_cookie_t cookie,
xcb_generic_error_t **e)
{
xcb_intern_atom_reply_t * reply = (xcb_intern_atom_reply_t *)calloc(1, sizeof (xcb_intern_atom_reply_t));
return reply;
}
xcb_void_cookie_t
xcb_change_property(xcb_connection_t *c,
uint8_t mode,
xcb_window_t window,
xcb_atom_t property,
xcb_atom_t type,
uint8_t format,
uint32_t data_len,
const void *data)
{
xcb_void_cookie_t cookie = { };
return cookie;
}
xcb_void_cookie_t
xcb_map_window(xcb_connection_t *c,
xcb_window_t window)
{
xcb_void_cookie_t cookie = { };
return cookie;
}
const struct xcb_setup_t* xcb_get_setup(xcb_connection_t * c)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
return &connection->setup;
}
#define OFFSET_OF(_struct_, _member_) \
( \
reinterpret_cast<size_t>(&(reinterpret_cast<_struct_ *>(1)->_member_)) - \
reinterpret_cast<size_t>(reinterpret_cast<_struct_ *>(1)) \
)
/// Returns a pointer to a struct or class based on the pointer to one of
/// its members.
#define STRUCT_PTR_FROM_MEMBER_PTR(_struct_, _member_, _member_ptr_) \
reinterpret_cast<_struct_ *>( \
reinterpret_cast<size_t>(_member_ptr_) - \
OFFSET_OF(_struct_, _member_) \
)
xcb_screen_iterator_t
xcb_setup_roots_iterator(const xcb_setup_t *R)
{
xcb_connection_t * connection = STRUCT_PTR_FROM_MEMBER_PTR(xcb_connection_t, setup, R);
xcb_screen_iterator_t iterator = { };
iterator.data = &connection->screens[0];
return iterator;
}
void
xcb_screen_next(xcb_screen_iterator_t *i)
{
}
xcb_void_cookie_t
xcb_configure_window (xcb_connection_t *c ,
xcb_window_t window ,
uint16_t value_mask ,
const uint32_t *value_list )
{
uint32_t width = 0;
uint32_t height = 0;
size_t index = 0;
for (size_t i = 0; i < sizeof (uint16_t); ++i) {
switch (value_mask & (1 << i)) {
case XCB_CONFIG_WINDOW_WIDTH:
width = value_list[index++];
break;
case XCB_CONFIG_WINDOW_HEIGHT:
height = value_list[index++];
break;
default:
break;
}
}
if (width && height) {
// Resize the window...
}
return xcb_void_cookie_t();
}
<commit_msg>Fix "xcb_nvidia.c" for use of the nulldrv.<commit_after>#include <xcb/xcb.h>
#include <string>
#include <xgl.h>
typedef HWND (*xcbConnectType)();
typedef void (*xcbCreateWindowType)(uint16_t width, uint16_t height);
typedef void (*xcbDestroyWindowType)();
typedef int (*xcbGetMessageType)(MSG * msg);
typedef BOOL (*xcbPeekMessageType)(MSG * msg);
struct xcb_connection_t {
xcb_screen_t screens[1];
xcb_setup_t setup;
HMODULE xcbNvidia;
xcbConnectType xcbConnect;
xcbCreateWindowType xcbCreateWindow;
xcbDestroyWindowType xcbDestroyWindow;
xcbGetMessageType xcbGetMessage;
xcbPeekMessageType xcbPeekMessage;
HWND hwnd;
};
xcb_connection_t * xcb_connect(const char *displayname, int *screenp)
{
std::string xglNvidia = (getenv("XGL_DRIVERS_PATH") == NULL) ? "" : getenv("XGL_DRIVERS_PATH");
xglNvidia += "\\XGL_nvidia.dll";
HMODULE module = LoadLibrary(xglNvidia.c_str());
if (!module) {
std::string xglNulldrv = (getenv("XGL_DRIVERS_PATH") == NULL) ? "" : getenv("XGL_DRIVERS_PATH");
xglNulldrv += "\\xgl_nulldrv.dll";
module = LoadLibrary(xglNulldrv.c_str());
}
if (!module) {
// TODO: Adapted up the following code (copied from "loader.c"):
#define INITIAL_STR_LEN 1024
char *registry_str = (char *) malloc(INITIAL_STR_LEN);
DWORD registry_len = INITIAL_STR_LEN;
DWORD registry_value_type;
LONG registry_return_value;
char *rtn_str = NULL;
size_t rtn_len;
registry_return_value = RegGetValue(HKEY_LOCAL_MACHINE, "Software\\XGL",
"XGL_DRIVERS_PATH",
(RRF_RT_REG_SZ | RRF_ZEROONFAILURE),
®istry_value_type,
(PVOID) registry_str,
®istry_len);
rtn_len = registry_len + 16;
rtn_str = (char *) malloc(rtn_len);
_snprintf(rtn_str, rtn_len, "%s\\%s", registry_str, "xgl_nvidia.dll");
module = LoadLibrary(rtn_str);
}
if (!module) {
return 0;
}
xcb_connection_t * connection = (xcb_connection_t *)calloc(1, sizeof(xcb_connection_t));
connection->xcbNvidia = module;
connection->xcbConnect = (xcbConnectType)GetProcAddress(module, "xcbConnect");
connection->xcbCreateWindow = (xcbCreateWindowType)GetProcAddress(module, "xcbCreateWindow");
connection->xcbDestroyWindow = (xcbDestroyWindowType)GetProcAddress(module, "xcbDestroyWindow");
connection->xcbGetMessage = (xcbGetMessageType)GetProcAddress(module, "xcbGetMessage");
connection->xcbPeekMessage = (xcbPeekMessageType)GetProcAddress(module, "xcbPeekMessage");
if (!connection->xcbConnect) {
return 0;
}
connection->hwnd = connection->xcbConnect();
*screenp = 0;
return static_cast<xcb_connection_t *>(connection);
}
void xcb_disconnect(xcb_connection_t *c)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
FreeLibrary(connection->xcbNvidia);
free(connection);
}
int xcb_flush(xcb_connection_t * c)
{
return 0;
}
static xcb_generic_event_t* TranslateWindowsMsg(MSG * msg)
{
switch (msg->message) {
case WM_PAINT:
{
xcb_generic_event_t * event = (xcb_generic_event_t *)calloc(1, sizeof (xcb_generic_event_t));
event->response_type = XCB_EXPOSE;
return event;
}
break;
case WM_KEYUP:
{
xcb_key_release_event_t * event = (xcb_key_release_event_t *)calloc(1, sizeof (xcb_key_release_event_t));
event->response_type = XCB_KEY_RELEASE;
// TODO: What's the correct mapping?
switch (msg->wParam) {
case VK_ESCAPE:
event->detail = 0x09;
break;
case VK_LEFT:
event->detail = 0x71;
break;
case VK_RIGHT:
event->detail = 0x72;
break;
case VK_SPACE:
event->detail = 0x41;
break;
default:
event->detail = (xcb_keycode_t)msg->wParam;
break;
}
return (xcb_generic_event_t *)event;
}
break;
case WM_DESTROY:
{
xcb_generic_event_t * event = (xcb_generic_event_t *)calloc(1, sizeof (xcb_generic_event_t));
event->response_type = XCB_DESTROY_NOTIFY;
return event;
}
break;
default:
return 0;
}
return 0;
}
xcb_generic_event_t* xcb_wait_for_event(xcb_connection_t * c)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
MSG msg;
int result = connection->xcbGetMessage(&msg);
if (result > 0) {
return TranslateWindowsMsg(&msg);
} else if (result == 0) {
xcb_generic_event_t * event = (xcb_generic_event_t *)calloc(1, sizeof (xcb_generic_event_t));
event->response_type = XCB_DESTROY_NOTIFY;
return event;
}
return 0;
}
xcb_generic_event_t *xcb_poll_for_event(xcb_connection_t *c)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
MSG msg;
if (connection->xcbPeekMessage(&msg)) {
return TranslateWindowsMsg(&msg);
}
return 0;
}
uint32_t xcb_generate_id(xcb_connection_t *c)
{
// This is a MONSTER hack to make XGL_nvidia compatible with both
// the LunarG apps and Dota2.
return (uint32_t)c->hwnd;
}
xcb_void_cookie_t
xcb_create_window(xcb_connection_t *c,
uint8_t depth,
xcb_window_t wid,
xcb_window_t parent,
int16_t x,
int16_t y,
uint16_t width,
uint16_t height,
uint16_t border_width,
uint16_t _class,
xcb_visualid_t visual,
uint32_t value_mask,
const uint32_t *value_list)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
connection->xcbCreateWindow(width, height);
xcb_void_cookie_t cookie = { };
return cookie;
}
xcb_void_cookie_t
xcb_destroy_window(xcb_connection_t *c,
xcb_window_t window)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
connection->xcbDestroyWindow();
xcb_void_cookie_t cookie = { };
return cookie;
}
xcb_intern_atom_cookie_t
xcb_intern_atom(xcb_connection_t *c,
uint8_t only_if_exists,
uint16_t name_len,
const char *name)
{
xcb_intern_atom_cookie_t cookie = { };
return cookie;
}
xcb_intern_atom_reply_t *
xcb_intern_atom_reply(xcb_connection_t *c,
xcb_intern_atom_cookie_t cookie,
xcb_generic_error_t **e)
{
xcb_intern_atom_reply_t * reply = (xcb_intern_atom_reply_t *)calloc(1, sizeof (xcb_intern_atom_reply_t));
return reply;
}
xcb_void_cookie_t
xcb_change_property(xcb_connection_t *c,
uint8_t mode,
xcb_window_t window,
xcb_atom_t property,
xcb_atom_t type,
uint8_t format,
uint32_t data_len,
const void *data)
{
xcb_void_cookie_t cookie = { };
return cookie;
}
xcb_void_cookie_t
xcb_map_window(xcb_connection_t *c,
xcb_window_t window)
{
xcb_void_cookie_t cookie = { };
return cookie;
}
const struct xcb_setup_t* xcb_get_setup(xcb_connection_t * c)
{
xcb_connection_t * connection = static_cast<xcb_connection_t *>(c);
return &connection->setup;
}
#define OFFSET_OF(_struct_, _member_) \
( \
reinterpret_cast<size_t>(&(reinterpret_cast<_struct_ *>(1)->_member_)) - \
reinterpret_cast<size_t>(reinterpret_cast<_struct_ *>(1)) \
)
/// Returns a pointer to a struct or class based on the pointer to one of
/// its members.
#define STRUCT_PTR_FROM_MEMBER_PTR(_struct_, _member_, _member_ptr_) \
reinterpret_cast<_struct_ *>( \
reinterpret_cast<size_t>(_member_ptr_) - \
OFFSET_OF(_struct_, _member_) \
)
xcb_screen_iterator_t
xcb_setup_roots_iterator(const xcb_setup_t *R)
{
xcb_connection_t * connection = STRUCT_PTR_FROM_MEMBER_PTR(xcb_connection_t, setup, R);
xcb_screen_iterator_t iterator = { };
iterator.data = &connection->screens[0];
return iterator;
}
void
xcb_screen_next(xcb_screen_iterator_t *i)
{
}
xcb_void_cookie_t
xcb_configure_window (xcb_connection_t *c ,
xcb_window_t window ,
uint16_t value_mask ,
const uint32_t *value_list )
{
uint32_t width = 0;
uint32_t height = 0;
size_t index = 0;
for (size_t i = 0; i < sizeof (uint16_t); ++i) {
switch (value_mask & (1 << i)) {
case XCB_CONFIG_WINDOW_WIDTH:
width = value_list[index++];
break;
case XCB_CONFIG_WINDOW_HEIGHT:
height = value_list[index++];
break;
default:
break;
}
}
if (width && height) {
// Resize the window...
}
return xcb_void_cookie_t();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/uobject.hxx
#ifndef URBI_UOBJECT_HXX
# define URBI_UOBJECT_HXX
#define URBI_BINDVARS(r, obj, v) UBindVar(obj, v);
#define URBI_BINDFUNCTIONS(r, obj, v) UBindFunction(obj, v);
#define URBI_BINDEVENTS(r, obj, v) UBindEvent(obj, v);
namespace urbi
{
/*----------.
| UObject. |
`----------*/
inline
int
UObject::update()
{
return 0;
}
inline
int
UObject::voidfun()
{
return 0;
}
inline
void
UObject::clean()
{
aver(impl_);
impl_->clean();
}
inline
void
UObject::USetUpdate(ufloat period)
{
aver(impl_);
impl_->setUpdate(period);
}
inline
void
UObject::USync(UVar &v)
{
v.keepSynchronized();
}
inline
bool
UObject::removeTimer(TimerHandle h)
{
return impl_->removeTimer(h);
}
inline
impl::UObjectImpl*
UObject::impl_get()
{
return impl_;
}
inline
libport::ThreadPool::rTaskLock
UObject::getTaskLock(LockMode m, const std::string& what)
{
return getTaskLock(LockSpec(m), what);
}
inline
libport::ThreadPool::rTaskLock
UObject::getTaskLock(LockSpec m, const std::string& what)
{
GD_CATEGORY(UObject);
typedef libport::ThreadPool::rTaskLock rTaskLock;
typedef libport::ThreadPool::TaskLock TaskLock;
// Static in inlined functions are per-module.
static rTaskLock module_lock(new TaskLock);
switch(m.lockMode)
{
case LOCK_NONE:
return 0;
break;
case LOCK_FUNCTION:
{
rTaskLock& res = taskLocks_[what];
if (!res)
{
res = new TaskLock(m.maxQueueSize);
GD_FINFO_TRACE("Creating taskLock for %s with %s: %s", what,
m.maxQueueSize, res.get());
}
return res;
}
break;
case LOCK_INSTANCE:
return taskLock_;
break;
case LOCK_CLASS:
return getClassTaskLock();
break;
case LOCK_MODULE:
return module_lock;
break;
}
return 0;
}
#ifndef NO_UOBJECT_CASTER
inline UObject*
uvalue_caster<UObject*>::operator()(UValue& v)
{
if (v.type != DATA_STRING && v.type != DATA_SLOTNAME)
return 0;
return getUObject(*v.stringValue);
}
inline
UValue& operator,(UValue&a, const UObject* b)
{
if (!b)
a = "nil";
else
a = b->__name;
a.type = DATA_SLOTNAME;
return a;
}
#ifndef NO_ANY_POINTER_CASTER
template<typename T> struct
uvalue_caster<T*> {
T* operator()(UValue& v)
{
UObject* res = uvalue_caster<UObject*>()(v);
return dynamic_cast<T*>(res);
}
};
#endif
#endif
}
#endif // !URBI_UOBJECT_HXX
<commit_msg>Add forgotten include.<commit_after>/*
* Copyright (C) 2009-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/uobject.hxx
#ifndef URBI_UOBJECT_HXX
# define URBI_UOBJECT_HXX
# include <libport/debug.hh>
# define URBI_BINDVARS(r, obj, v) UBindVar(obj, v);
# define URBI_BINDFUNCTIONS(r, obj, v) UBindFunction(obj, v);
# define URBI_BINDEVENTS(r, obj, v) UBindEvent(obj, v);
namespace urbi
{
/*----------.
| UObject. |
`----------*/
inline
int
UObject::update()
{
return 0;
}
inline
int
UObject::voidfun()
{
return 0;
}
inline
void
UObject::clean()
{
aver(impl_);
impl_->clean();
}
inline
void
UObject::USetUpdate(ufloat period)
{
aver(impl_);
impl_->setUpdate(period);
}
inline
void
UObject::USync(UVar &v)
{
v.keepSynchronized();
}
inline
bool
UObject::removeTimer(TimerHandle h)
{
return impl_->removeTimer(h);
}
inline
impl::UObjectImpl*
UObject::impl_get()
{
return impl_;
}
inline
libport::ThreadPool::rTaskLock
UObject::getTaskLock(LockMode m, const std::string& what)
{
return getTaskLock(LockSpec(m), what);
}
inline
libport::ThreadPool::rTaskLock
UObject::getTaskLock(LockSpec m, const std::string& what)
{
GD_CATEGORY(UObject);
typedef libport::ThreadPool::rTaskLock rTaskLock;
typedef libport::ThreadPool::TaskLock TaskLock;
// Static in inlined functions are per-module.
static rTaskLock module_lock(new TaskLock);
switch(m.lockMode)
{
case LOCK_NONE:
return 0;
break;
case LOCK_FUNCTION:
{
rTaskLock& res = taskLocks_[what];
if (!res)
{
res = new TaskLock(m.maxQueueSize);
GD_FINFO_TRACE("Creating taskLock for %s with %s: %s", what,
m.maxQueueSize, res.get());
}
return res;
}
break;
case LOCK_INSTANCE:
return taskLock_;
break;
case LOCK_CLASS:
return getClassTaskLock();
break;
case LOCK_MODULE:
return module_lock;
break;
}
return 0;
}
#ifndef NO_UOBJECT_CASTER
inline UObject*
uvalue_caster<UObject*>::operator()(UValue& v)
{
if (v.type != DATA_STRING && v.type != DATA_SLOTNAME)
return 0;
return getUObject(*v.stringValue);
}
inline
UValue& operator,(UValue&a, const UObject* b)
{
if (!b)
a = "nil";
else
a = b->__name;
a.type = DATA_SLOTNAME;
return a;
}
#ifndef NO_ANY_POINTER_CASTER
template<typename T> struct
uvalue_caster<T*> {
T* operator()(UValue& v)
{
UObject* res = uvalue_caster<UObject*>()(v);
return dynamic_cast<T*>(res);
}
};
#endif
#endif
}
#endif // !URBI_UOBJECT_HXX
<|endoftext|> |
<commit_before>
// Copyright (c) 2015 Pierre MOULON.
// 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/.
#include "image_describer.hpp"
#include "openMVG/features/image_describer_akaze.hpp"
#include "openMVG/features/cctag/CCTAG_describer.hpp"
#include "openMVG/features/openCV/AKAZE_openCV_describer.hpp"
#if OPENMVG_IS_DEFINED(OPENMVG_USE_OCVSIFT)
#include "openMVG/features/openCV/SIFT_openCV_describer.hpp"
#endif //OPENMVG_USE_OCVSIFT
#include "nonFree/sift/SIFT_describer.hpp"
#include "nonFree/sift/SIFT_float_describer.hpp"
#include <exception>
namespace openMVG{
namespace features{
EDESCRIBER_PRESET describerPreset_stringToEnum(const std::string& sPreset)
{
if(sPreset == "LOW")
return LOW_PRESET;
if (sPreset == "MEDIUM")
return MEDIUM_PRESET;
if(sPreset == "NORMAL")
return NORMAL_PRESET;
if (sPreset == "HIGH")
return HIGH_PRESET;
if (sPreset == "ULTRA")
return ULTRA_PRESET;
throw std::invalid_argument("Invalid descriptor preset: " + sPreset);
}
std::string describerPreset_enumToString(const EDESCRIBER_PRESET preset)
{
if(preset == LOW_PRESET)
return "LOW";
if (preset == MEDIUM_PRESET)
return "MEDIUM";
if(preset == NORMAL_PRESET)
return "NORMAL";
if (preset == HIGH_PRESET)
return "HIGH";
if (preset == ULTRA_PRESET)
return "ULTRA";
throw std::invalid_argument("Unrecognized EDESCRIBER_PRESET "+std::to_string(preset));
}
std::ostream& operator<<(std::ostream& os, EDESCRIBER_PRESET p)
{
return os << describerPreset_enumToString(p);
}
std::istream& operator>>(std::istream& in, EDESCRIBER_PRESET& p)
{
std::string token;
in >> token;
p = describerPreset_stringToEnum(token);
return in;
}
std::unique_ptr<Image_describer> createImageDescriber(EImageDescriberType imageDescriberType)
{
std::unique_ptr<Image_describer> describerPtr;
switch(imageDescriberType)
{
case EImageDescriberType::SIFT: describerPtr.reset(new SIFT_Image_describer(SiftParams())); break;
case EImageDescriberType::SIFT_FLOAT: describerPtr.reset(new SIFT_float_describer(SiftParams())); break;
case EImageDescriberType::AKAZE: describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_MSURF))); break;
case EImageDescriberType::AKAZE_MLDB: describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_MLDB))); break;
case EImageDescriberType::AKAZE_LIOP: describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_LIOP))); break;
#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_CCTAG)
case EImageDescriberType::CCTAG3: describerPtr.reset(new CCTAG_Image_describer(3)); break;
case EImageDescriberType::CCTAG4: describerPtr.reset(new CCTAG_Image_describer(4)); break;
#endif //OPENMVG_HAVE_CCTAG
#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_OPENCV)
#if OPENMVG_IS_DEFINED(OPENMVG_USE_OCVSIFT)
case EImageDescriberType::SIFT_OCV: describerPtr.reset(new SIFT_openCV_ImageDescriber()); break;
#endif //OPENMVG_USE_OCVSIFT
case EImageDescriberType::AKAZE_OCV: describerPtr.reset(new AKAZE_openCV_ImageDescriber()); break;
#endif //OPENMVG_HAVE_OPENCV
default: throw std::out_of_range("Invalid imageDescriber enum");
}
assert(describerPtr != nullptr);
return describerPtr;
}
}//namespace features
}//namespace openMVG
<commit_msg>[features] fix : CCTAG_describer include without OPENMVG_HAVE_CCTAG check<commit_after>
// Copyright (c) 2015 Pierre MOULON.
// 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/.
#include "image_describer.hpp"
#include "openMVG/features/image_describer_akaze.hpp"
#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_CCTAG)
#include "openMVG/features/cctag/CCTAG_describer.hpp"
#endif //OPENMVG_HAVE_CCTAG
#include "openMVG/features/openCV/AKAZE_openCV_describer.hpp"
#if OPENMVG_IS_DEFINED(OPENMVG_USE_OCVSIFT)
#include "openMVG/features/openCV/SIFT_openCV_describer.hpp"
#endif //OPENMVG_USE_OCVSIFT
#include "nonFree/sift/SIFT_describer.hpp"
#include "nonFree/sift/SIFT_float_describer.hpp"
#include <exception>
namespace openMVG{
namespace features{
EDESCRIBER_PRESET describerPreset_stringToEnum(const std::string& sPreset)
{
if(sPreset == "LOW")
return LOW_PRESET;
if (sPreset == "MEDIUM")
return MEDIUM_PRESET;
if(sPreset == "NORMAL")
return NORMAL_PRESET;
if (sPreset == "HIGH")
return HIGH_PRESET;
if (sPreset == "ULTRA")
return ULTRA_PRESET;
throw std::invalid_argument("Invalid descriptor preset: " + sPreset);
}
std::string describerPreset_enumToString(const EDESCRIBER_PRESET preset)
{
if(preset == LOW_PRESET)
return "LOW";
if (preset == MEDIUM_PRESET)
return "MEDIUM";
if(preset == NORMAL_PRESET)
return "NORMAL";
if (preset == HIGH_PRESET)
return "HIGH";
if (preset == ULTRA_PRESET)
return "ULTRA";
throw std::invalid_argument("Unrecognized EDESCRIBER_PRESET "+std::to_string(preset));
}
std::ostream& operator<<(std::ostream& os, EDESCRIBER_PRESET p)
{
return os << describerPreset_enumToString(p);
}
std::istream& operator>>(std::istream& in, EDESCRIBER_PRESET& p)
{
std::string token;
in >> token;
p = describerPreset_stringToEnum(token);
return in;
}
std::unique_ptr<Image_describer> createImageDescriber(EImageDescriberType imageDescriberType)
{
std::unique_ptr<Image_describer> describerPtr;
switch(imageDescriberType)
{
case EImageDescriberType::SIFT: describerPtr.reset(new SIFT_Image_describer(SiftParams())); break;
case EImageDescriberType::SIFT_FLOAT: describerPtr.reset(new SIFT_float_describer(SiftParams())); break;
case EImageDescriberType::AKAZE: describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_MSURF))); break;
case EImageDescriberType::AKAZE_MLDB: describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_MLDB))); break;
case EImageDescriberType::AKAZE_LIOP: describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_LIOP))); break;
#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_CCTAG)
case EImageDescriberType::CCTAG3: describerPtr.reset(new CCTAG_Image_describer(3)); break;
case EImageDescriberType::CCTAG4: describerPtr.reset(new CCTAG_Image_describer(4)); break;
#endif //OPENMVG_HAVE_CCTAG
#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_OPENCV)
#if OPENMVG_IS_DEFINED(OPENMVG_USE_OCVSIFT)
case EImageDescriberType::SIFT_OCV: describerPtr.reset(new SIFT_openCV_ImageDescriber()); break;
#endif //OPENMVG_USE_OCVSIFT
case EImageDescriberType::AKAZE_OCV: describerPtr.reset(new AKAZE_openCV_ImageDescriber()); break;
#endif //OPENMVG_HAVE_OPENCV
default: throw std::out_of_range("Invalid imageDescriber enum");
}
assert(describerPtr != nullptr);
return describerPtr;
}
}//namespace features
}//namespace openMVG
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuvalue/ubinary.cc
#include <iostream>
#include <sstream>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <urbi/ubinary.hh>
#include <boost/algorithm/string/replace.hpp>
GD_CATEGORY(UValue);
namespace urbi
{
UBinary::UBinary()
: type(BINARY_NONE)
, allocated_(true)
{
common.data = 0;
common.size = 0;
}
UBinary::UBinary(const UBinary& b, bool copy)
: type(BINARY_NONE)
, allocated_(copy)
{
common.data = 0;
if (copy)
*this = b;
else
{
// Be safe, do not try to guess which is bigger.
image = b.image;
sound = b.sound;
message = b.message;
type = b.type;
}
}
UBinary::UBinary(const UImage& i, bool copy)
: type(BINARY_IMAGE)
, image(i)
, allocated_(copy)
{
if (copy)
{
image.data = static_cast<unsigned char*> (malloc (image.size));
memcpy(image.data, i.data, image.size);
}
}
UBinary::UBinary(const USound& i, bool copy)
: type(BINARY_SOUND)
, sound(i)
, allocated_(copy)
{
if (copy)
{
sound.data = static_cast<char*> (malloc (sound.size));
memcpy(sound.data, i.data, sound.size);
}
}
void
UBinary::clear()
{
if (allocated_)
free(common.data);
}
UBinary::~UBinary()
{
clear();
}
UBinary& UBinary::operator= (const UBinary& b)
{
if (this == &b)
return *this;
clear();
type = b.type;
message = b.message;
common.size = b.common.size;
switch(type)
{
case BINARY_IMAGE:
image = b.image;
break;
case BINARY_SOUND:
sound = b.sound;
break;
case BINARY_NONE:
case BINARY_UNKNOWN:
break;
}
common.data = malloc(common.size);
memcpy(common.data, b.common.data, b.common.size);
return *this;
}
int
UBinary::parse(const char* message, int pos,
const binaries_type& bins,
binaries_type::const_iterator& binpos, bool copy)
{
std::istringstream is(message + pos);
bool ok = parse(is, bins, binpos, copy);
// tellg() might be -1 if we encountered an error.
int endpos = is.tellg();
if (endpos == -1)
endpos = strlen(message) - pos;
return (ok ? 1:-1) * (pos + endpos);
}
namespace
{
/// Return everything up to the next "\n" or "\n\r" or ";", not included.
/// Leave \a i after that delimiter.
/// Return empty string on errors.
static
std::string
headers_get(std::istringstream& i)
{
std::string res;
int c = 0;
while (!i.eof()
&& (c = i.get()) && c != '\n' && c != ';')
res.append(1, c);
if (i.eof())
GD_ERROR("unexpected end of file while parsing UBinary headers");
else
{
// Skip the delimiter.
if (c == '\n')
{
i.ignore();
if (i.peek() == '\r')
i.ignore();
}
else
i.ignore();
}
return res;
}
}
bool
UBinary::parse(std::istringstream& is,
const binaries_type& bins,
binaries_type::const_iterator& binpos, bool copy)
{
// LIBPORT_ECHO("Parsing: {" << is.str() << "}");
if (binpos == bins.end())
{
GD_ERROR("no binary data available");
return false;
}
// Validate size.
size_t psize;
is >> psize;
if (is.fail())
{
GD_FERROR("cannot read bin size: %s (%s)", is.str(), psize);
return false;
}
if (psize != binpos->size)
{
GD_FERROR("bin size inconsistency: %s != %s", psize, binpos->size);
return false;
}
common.size = psize;
if (copy)
{
common.data = malloc(common.size);
memcpy(common.data, binpos->data, common.size);
}
else
{
common.data = binpos->data;
this->allocated_ = false;
}
++binpos;
// Skip spaces.
while (is.peek() == ' ')
is.ignore();
// Get the headers.
message = headers_get(is);
// Analyse the header to decode know UBinary types.
// Header stream.
std::istringstream hs(message);
// Parse the optional type. Don't check hs.fail, since the type
// is optional, in which case t remains empty.
std::string t;
hs >> t;
UImageFormat image_format = parse_image_format(t);
if (image_format != IMAGE_UNKNOWN || t.find("image_")==0)
{
type = BINARY_IMAGE;
image.size = common.size;
// In some cases (jpeg source), image size is not present in headers.
image.width = image.height = 0;
hs >> image.width >> image.height;
image.imageFormat = image_format;
}
else if (t == "raw" || t == "wav")
{
type = BINARY_SOUND;
sound.soundFormat = (t == "raw" ? SOUND_RAW
: t == "wav" ? SOUND_WAV
: SOUND_UNKNOWN);
sound.size = common.size;
hs >> sound.channels
>> sound.rate
>> sound.sampleSize >> sound.sampleFormat;
}
else
{
// GD_FWARN("unknown binary type: %s", t);
type = BINARY_UNKNOWN;
}
return true;
}
void UBinary::buildMessage()
{
message = getMessage();
}
std::string UBinary::getMessage() const
{
switch (type)
{
case BINARY_IMAGE:
return image.headers_();
case BINARY_SOUND:
return sound.headers_();
case BINARY_UNKNOWN:
{
bool warned = false;
std::string res = message;
foreach (char& c, res)
if (c == '\0' || c == '\n' || c == ';')
{
if (!warned++)
GD_FERROR("invalid UBinary header: "
"prohibited `\\n', `\\0' and `;' will be "
"smashed to space: %s",
libport::escape(message));
c = ' ';
}
return res;
}
case BINARY_NONE:
return "";
}
unreachable();
}
std::ostream&
UBinary::print(std::ostream& o) const
{
// Format for the Kernel, which wants ';' as header terminator.
o << "BIN "<< common.size << ' ' << getMessage() << ';';
o.write((char*) common.data, common.size);
return o;
}
std::ostream&
operator<< (std::ostream& o, const UBinary& t)
{
return t.print(o);
}
} // namespace urbi
<commit_msg>UBinary: use parse_sound_format.<commit_after>/*
* Copyright (C) 2009-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuvalue/ubinary.cc
#include <iostream>
#include <sstream>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <urbi/ubinary.hh>
#include <boost/algorithm/string/replace.hpp>
GD_CATEGORY(UValue);
namespace urbi
{
UBinary::UBinary()
: type(BINARY_NONE)
, allocated_(true)
{
common.data = 0;
common.size = 0;
}
UBinary::UBinary(const UBinary& b, bool copy)
: type(BINARY_NONE)
, allocated_(copy)
{
common.data = 0;
if (copy)
*this = b;
else
{
// Be safe, do not try to guess which is bigger.
image = b.image;
sound = b.sound;
message = b.message;
type = b.type;
}
}
UBinary::UBinary(const UImage& i, bool copy)
: type(BINARY_IMAGE)
, image(i)
, allocated_(copy)
{
if (copy)
{
image.data = static_cast<unsigned char*> (malloc (image.size));
memcpy(image.data, i.data, image.size);
}
}
UBinary::UBinary(const USound& i, bool copy)
: type(BINARY_SOUND)
, sound(i)
, allocated_(copy)
{
if (copy)
{
sound.data = static_cast<char*> (malloc (sound.size));
memcpy(sound.data, i.data, sound.size);
}
}
void
UBinary::clear()
{
if (allocated_)
free(common.data);
}
UBinary::~UBinary()
{
clear();
}
UBinary& UBinary::operator= (const UBinary& b)
{
if (this == &b)
return *this;
clear();
type = b.type;
message = b.message;
common.size = b.common.size;
switch(type)
{
case BINARY_IMAGE:
image = b.image;
break;
case BINARY_SOUND:
sound = b.sound;
break;
case BINARY_NONE:
case BINARY_UNKNOWN:
break;
}
common.data = malloc(common.size);
memcpy(common.data, b.common.data, b.common.size);
return *this;
}
int
UBinary::parse(const char* message, int pos,
const binaries_type& bins,
binaries_type::const_iterator& binpos, bool copy)
{
std::istringstream is(message + pos);
bool ok = parse(is, bins, binpos, copy);
// tellg() might be -1 if we encountered an error.
int endpos = is.tellg();
if (endpos == -1)
endpos = strlen(message) - pos;
return (ok ? 1:-1) * (pos + endpos);
}
namespace
{
/// Return everything up to the next "\n" or "\n\r" or ";", not included.
/// Leave \a i after that delimiter.
/// Return empty string on errors.
static
std::string
headers_get(std::istringstream& i)
{
std::string res;
int c = 0;
while (!i.eof()
&& (c = i.get()) && c != '\n' && c != ';')
res.append(1, c);
if (i.eof())
GD_ERROR("unexpected end of file while parsing UBinary headers");
else
{
// Skip the delimiter.
if (c == '\n')
{
i.ignore();
if (i.peek() == '\r')
i.ignore();
}
else
i.ignore();
}
return res;
}
}
bool
UBinary::parse(std::istringstream& is,
const binaries_type& bins,
binaries_type::const_iterator& binpos, bool copy)
{
// LIBPORT_ECHO("Parsing: {" << is.str() << "}");
if (binpos == bins.end())
{
GD_ERROR("no binary data available");
return false;
}
// Validate size.
size_t psize;
is >> psize;
if (is.fail())
{
GD_FERROR("cannot read bin size: %s (%s)", is.str(), psize);
return false;
}
if (psize != binpos->size)
{
GD_FERROR("bin size inconsistency: %s != %s", psize, binpos->size);
return false;
}
common.size = psize;
if (copy)
{
common.data = malloc(common.size);
memcpy(common.data, binpos->data, common.size);
}
else
{
common.data = binpos->data;
this->allocated_ = false;
}
++binpos;
// Skip spaces.
while (is.peek() == ' ')
is.ignore();
// Get the headers.
message = headers_get(is);
// Analyse the header to decode know UBinary types.
// Header stream.
std::istringstream hs(message);
// Parse the optional type. Don't check hs.fail, since the type
// is optional, in which case t remains empty.
std::string t;
hs >> t;
UImageFormat image_format = parse_image_format(t);
if (image_format != IMAGE_UNKNOWN || t.find("image_")==0)
{
type = BINARY_IMAGE;
image.size = common.size;
// In some cases (jpeg source), image size is not present in headers.
image.width = image.height = 0;
hs >> image.width >> image.height;
image.imageFormat = image_format;
}
else if (t == "raw" || t == "wav")
{
type = BINARY_SOUND;
sound.soundFormat = parse_sound_format(t);
sound.size = common.size;
hs >> sound.channels
>> sound.rate
>> sound.sampleSize >> sound.sampleFormat;
}
else
{
// GD_FWARN("unknown binary type: %s", t);
type = BINARY_UNKNOWN;
}
return true;
}
void UBinary::buildMessage()
{
message = getMessage();
}
std::string UBinary::getMessage() const
{
switch (type)
{
case BINARY_IMAGE:
return image.headers_();
case BINARY_SOUND:
return sound.headers_();
case BINARY_UNKNOWN:
{
bool warned = false;
std::string res = message;
foreach (char& c, res)
if (c == '\0' || c == '\n' || c == ';')
{
if (!warned++)
GD_FERROR("invalid UBinary header: "
"prohibited `\\n', `\\0' and `;' will be "
"smashed to space: %s",
libport::escape(message));
c = ' ';
}
return res;
}
case BINARY_NONE:
return "";
}
unreachable();
}
std::ostream&
UBinary::print(std::ostream& o) const
{
// Format for the Kernel, which wants ';' as header terminator.
o << "BIN "<< common.size << ' ' << getMessage() << ';';
o.write((char*) common.data, common.size);
return o;
}
std::ostream&
operator<< (std::ostream& o, const UBinary& t)
{
return t.print(o);
}
} // namespace urbi
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <caf/all.hpp>
#include "vast/detail/assert.hpp"
#include "vast/detail/flat_set.hpp"
#include "vast/detail/string.hpp"
#include "vast/error.hpp"
#include "vast/logger.hpp"
#include "vast/system/archive.hpp"
#include "vast/system/consensus.hpp"
#include "vast/system/tracker.hpp"
using namespace caf;
namespace vast::system {
namespace {
struct terminator_state {
terminator_state(event_based_actor* selfptr) : self(selfptr) {
// nop
}
caf::error reason;
actor parent;
component_state_map components;
std::vector<std::string> victim_stack;
size_t pending_down_messages = 0;
event_based_actor* self;
// Keeps this actor alive until we manually stop it.
strong_actor_ptr anchor;
static inline const char* name = "terminator";
void init(caf::error reason, caf::actor parent,
component_state_map components,
std::vector<std::string> victim_stack) {
VAST_TRACE(VAST_ARG(components), VAST_ARG(victim_stack));
this->anchor = actor_cast<strong_actor_ptr>(self);
this->reason = std::move(reason);
this->parent = std::move(parent);
this->components = std::move(components);
this->victim_stack = std::move(victim_stack);
}
template <class Label>
void kill(const caf::actor& actor, const Label& label) {
VAST_IGNORE_UNUSED(label);
VAST_DEBUG(self, "sends exit_msg to", label);
self->monitor(actor);
self->send_exit(actor, reason);
++pending_down_messages;
}
void kill_next() {
VAST_TRACE("");
do {
if (victim_stack.empty()) {
if (parent == nullptr) {
VAST_DEBUG(self, "stops after stopping all components");
anchor = nullptr;
self->quit();
return;
}
VAST_DEBUG(self, "kills parent and remaining components");
for (auto& component : components)
kill(component.second.actor, component.second.label);
components.clear();
kill(parent, "tracker");
parent = nullptr;
return;
}
auto er = components.equal_range(victim_stack.back());
for (auto i = er.first; i != er.second; ++i)
kill(i->second.actor, i->second.label);
components.erase(er.first, er.second);
victim_stack.pop_back();
} while (pending_down_messages == 0);
}
void got_down_msg() {
VAST_TRACE("");
if (--pending_down_messages == 0)
kill_next();
}
};
behavior terminator(stateful_actor<terminator_state>* self, caf::error reason,
caf::actor parent, component_state_map components,
std::vector<std::string> victim_stack) {
VAST_DEBUG(self, "starts terminator with", victim_stack.size(),
"victims on the stack and", components.size(), "in total");
self->state.init(std::move(reason), std::move(parent), std::move(components),
std::move(victim_stack));
self->state.kill_next();
self->set_down_handler([=](const down_msg&) {
self->state.got_down_msg();
});
return {
[] {
// Dummy message handler to keep the actor alive and kicking.
}
};
}
void register_component(scheduled_actor* self, tracker_state& st,
const std::string& type, const actor& component,
std::string& label) {
using caf::anon_send;
// Save new component.
self->monitor(component);
auto& local = st.registry.components[st.node];
local.emplace(type, component_state{component, label});
// Wire it to existing components.
auto actors = [&](auto key) {
std::vector<actor> result;
auto er = local.equal_range(key);
for (auto i = er.first; i != er.second; ++i)
result.push_back(i->second.actor);
return result;
};
if (type == "exporter") {
for (auto& a : actors("archive"))
anon_send(component, actor_cast<archive_type>(a));
for (auto& a : actors("index"))
anon_send(component, index_atom::value, a);
for (auto& a : actors("sink"))
anon_send(component, sink_atom::value, a);
} else if (type == "importer") {
for (auto& a : actors("consensus"))
anon_send(component, actor_cast<consensus_type>(a));
for (auto& a : actors("archive"))
anon_send(component, actor_cast<archive_type>(a));
for (auto& a : actors("index"))
anon_send(component, index_atom::value, a);
for (auto& a : actors("source"))
anon_send(a, sink_atom::value, component);
} else if (type == "source") {
for (auto& a : actors("importer"))
anon_send(component, sink_atom::value, a);
} else if (type == "sink") {
for (auto& a : actors("exporter"))
anon_send(a, sink_atom::value, component);
}
// Propagate new component to peer.
auto msg = make_message(put_atom::value, st.node, type, component, label);
for (auto& peer : st.registry.components) {
auto& t = peer.second.find("tracker")->second.actor;
if (t != self)
anon_send(t, msg);
}
}
// Checks whether a component can be spawned at most once.
bool is_singleton(const std::string& component) {
static detail::flat_set<std::string> singletons = {"archive", "index",
"consensus"};
return singletons.find(component) != singletons.end();
}
} // namespace <anonymous>
tracker_type::behavior_type
tracker(tracker_type::stateful_pointer<tracker_state> self, std::string node) {
self->state.node = node;
// Insert ourself into the registry.
self->state.registry.components[node].emplace(
"tracker", component_state{actor_cast<actor>(self), "tracker"});
// Insert the accountant into the registry so that it is easy for remote
// actors who query the registry to obtain a reference to the actor.
auto ptr = self->system().registry().get(accountant_atom::value);
VAST_ASSERT(ptr != nullptr);
self->state.registry.components[node].emplace(
"accountant", component_state{actor_cast<actor>(ptr), "accountant"});
self->set_down_handler(
[=](const down_msg& msg) {
auto pred = [&](auto& p) { return p.second.actor == msg.source; };
for (auto& [node, comp_state] : self->state.registry.components) {
auto i = std::find_if(comp_state.begin(), comp_state.end(), pred);
if (i != comp_state.end()) {
if (i->first == "tracker")
self->state.registry.components.erase(node);
else
comp_state.erase(i);
return;
}
}
}
);
self->set_exit_handler(
[=](const exit_msg& msg) {
// Only trap the first exit, regularly shutdown on the next one.
self->set_exit_handler({});
// We shut down the components in the order in which data flows so that
// downstream components can still process in-flight data. Because the
// terminator operates with a stack of components, we specify them in
// reverse order.
self->spawn(terminator, msg.reason, actor_cast<actor>(self),
self->state.registry.components[node],
std::vector<std::string>{"exporter", "index", "archive",
"importer", "source"});
}
);
return {
[=](put_atom, const std::string& type, const actor& component,
std::string& label) -> result<ok_atom> {
VAST_DEBUG(self, "got new", type, '(' << label << ')');
register_component(self, self->state, type, component, label);
return ok_atom::value;
},
[=](try_put_atom, const std::string& type, const actor& component,
std::string& label) -> result<void> {
VAST_DEBUG(self, "got new", type, '(' << label << ')');
auto& st = self->state;
auto& local = st.registry.components[node];
if (is_singleton(type) && local.count(type) > 0)
return make_error(ec::unspecified, "component already exists");
register_component(self, st, type, component, label);
return caf::unit;
},
[=](put_atom, const std::string& name, const std::string& type,
const actor& component, const std::string& label) {
VAST_DEBUG(self, "got PUT from peer", name, "for", type);
auto& components = self->state.registry.components[name];
components.emplace(type, component_state{component, label});
self->monitor(component);
},
[=](get_atom) -> result<registry> {
return self->state.registry;
},
[=](peer_atom, const actor& peer, const std::string& peer_name)
-> typed_response_promise<state_atom, registry> {
auto rp = self->make_response_promise<state_atom, registry>();
if (self->state.registry.components.count(peer_name) > 0) {
VAST_ERROR(self, "peer name already exists", peer_name);
return rp.deliver(make_error(ec::unspecified, "duplicate node name"));
}
VAST_DEBUG(self, "shipping state to new peer", peer_name);
rp.delegate(peer, state_atom::value, self->state.registry);
return rp;
},
[=](state_atom, registry& reg) -> result<ok_atom> {
VAST_DEBUG(self, "got state for", reg.components.size(), "peers");
// Monitor all remote components.
for (auto& peer : reg.components)
for (auto& pair : peer.second)
self->monitor(pair.second.actor);
// Incorporate new state from peer.
std::move(reg.components.begin(), reg.components.end(),
std::inserter(self->state.registry.components,
self->state.registry.components.end()));
// Broadcast our own state to all peers, without expecting a reply.
auto i = self->state.registry.components.find(node);
VAST_ASSERT(i != self->state.registry.components.end());
for (auto& peer : self->state.registry.components) {
auto& t = peer.second.find("tracker")->second.actor;
if (t != self)
self->send(actor_cast<tracker_type>(t), state_atom::value,
component_map_entry{*i});
}
return ok_atom::value;
},
[=](state_atom, component_map_entry& entry) {
VAST_DEBUG(self, "got components from new peer");
for (auto& pair : entry.second)
self->monitor(pair.second.actor);
auto result = self->state.registry.components.insert(std::move(entry));
VAST_ASSERT(result.second);
}
};
}
} // namespace vast::system
<commit_msg>Use smaller guns for testing set membership<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <caf/all.hpp>
#include "vast/detail/assert.hpp"
#include "vast/detail/string.hpp"
#include "vast/error.hpp"
#include "vast/logger.hpp"
#include "vast/system/archive.hpp"
#include "vast/system/consensus.hpp"
#include "vast/system/tracker.hpp"
using namespace caf;
namespace vast::system {
namespace {
struct terminator_state {
terminator_state(event_based_actor* selfptr) : self(selfptr) {
// nop
}
caf::error reason;
actor parent;
component_state_map components;
std::vector<std::string> victim_stack;
size_t pending_down_messages = 0;
event_based_actor* self;
// Keeps this actor alive until we manually stop it.
strong_actor_ptr anchor;
static inline const char* name = "terminator";
void init(caf::error reason, caf::actor parent,
component_state_map components,
std::vector<std::string> victim_stack) {
VAST_TRACE(VAST_ARG(components), VAST_ARG(victim_stack));
this->anchor = actor_cast<strong_actor_ptr>(self);
this->reason = std::move(reason);
this->parent = std::move(parent);
this->components = std::move(components);
this->victim_stack = std::move(victim_stack);
}
template <class Label>
void kill(const caf::actor& actor, const Label& label) {
VAST_IGNORE_UNUSED(label);
VAST_DEBUG(self, "sends exit_msg to", label);
self->monitor(actor);
self->send_exit(actor, reason);
++pending_down_messages;
}
void kill_next() {
VAST_TRACE("");
do {
if (victim_stack.empty()) {
if (parent == nullptr) {
VAST_DEBUG(self, "stops after stopping all components");
anchor = nullptr;
self->quit();
return;
}
VAST_DEBUG(self, "kills parent and remaining components");
for (auto& component : components)
kill(component.second.actor, component.second.label);
components.clear();
kill(parent, "tracker");
parent = nullptr;
return;
}
auto er = components.equal_range(victim_stack.back());
for (auto i = er.first; i != er.second; ++i)
kill(i->second.actor, i->second.label);
components.erase(er.first, er.second);
victim_stack.pop_back();
} while (pending_down_messages == 0);
}
void got_down_msg() {
VAST_TRACE("");
if (--pending_down_messages == 0)
kill_next();
}
};
behavior terminator(stateful_actor<terminator_state>* self, caf::error reason,
caf::actor parent, component_state_map components,
std::vector<std::string> victim_stack) {
VAST_DEBUG(self, "starts terminator with", victim_stack.size(),
"victims on the stack and", components.size(), "in total");
self->state.init(std::move(reason), std::move(parent), std::move(components),
std::move(victim_stack));
self->state.kill_next();
self->set_down_handler([=](const down_msg&) {
self->state.got_down_msg();
});
return {
[] {
// Dummy message handler to keep the actor alive and kicking.
}
};
}
void register_component(scheduled_actor* self, tracker_state& st,
const std::string& type, const actor& component,
std::string& label) {
using caf::anon_send;
// Save new component.
self->monitor(component);
auto& local = st.registry.components[st.node];
local.emplace(type, component_state{component, label});
// Wire it to existing components.
auto actors = [&](auto key) {
std::vector<actor> result;
auto er = local.equal_range(key);
for (auto i = er.first; i != er.second; ++i)
result.push_back(i->second.actor);
return result;
};
if (type == "exporter") {
for (auto& a : actors("archive"))
anon_send(component, actor_cast<archive_type>(a));
for (auto& a : actors("index"))
anon_send(component, index_atom::value, a);
for (auto& a : actors("sink"))
anon_send(component, sink_atom::value, a);
} else if (type == "importer") {
for (auto& a : actors("consensus"))
anon_send(component, actor_cast<consensus_type>(a));
for (auto& a : actors("archive"))
anon_send(component, actor_cast<archive_type>(a));
for (auto& a : actors("index"))
anon_send(component, index_atom::value, a);
for (auto& a : actors("source"))
anon_send(a, sink_atom::value, component);
} else if (type == "source") {
for (auto& a : actors("importer"))
anon_send(component, sink_atom::value, a);
} else if (type == "sink") {
for (auto& a : actors("exporter"))
anon_send(a, sink_atom::value, component);
}
// Propagate new component to peer.
auto msg = make_message(put_atom::value, st.node, type, component, label);
for (auto& peer : st.registry.components) {
auto& t = peer.second.find("tracker")->second.actor;
if (t != self)
anon_send(t, msg);
}
}
// Checks whether a component can be spawned at most once.
bool is_singleton(const std::string& component) {
const char* singletons[] = {"archive", "index", "consensus"};
auto pred = [&](const char* lhs) { return lhs == component; };
return std::any_of(std::begin(singletons), std::end(singletons), pred);
}
} // namespace <anonymous>
tracker_type::behavior_type
tracker(tracker_type::stateful_pointer<tracker_state> self, std::string node) {
self->state.node = node;
// Insert ourself into the registry.
self->state.registry.components[node].emplace(
"tracker", component_state{actor_cast<actor>(self), "tracker"});
// Insert the accountant into the registry so that it is easy for remote
// actors who query the registry to obtain a reference to the actor.
auto ptr = self->system().registry().get(accountant_atom::value);
VAST_ASSERT(ptr != nullptr);
self->state.registry.components[node].emplace(
"accountant", component_state{actor_cast<actor>(ptr), "accountant"});
self->set_down_handler(
[=](const down_msg& msg) {
auto pred = [&](auto& p) { return p.second.actor == msg.source; };
for (auto& [node, comp_state] : self->state.registry.components) {
auto i = std::find_if(comp_state.begin(), comp_state.end(), pred);
if (i != comp_state.end()) {
if (i->first == "tracker")
self->state.registry.components.erase(node);
else
comp_state.erase(i);
return;
}
}
}
);
self->set_exit_handler(
[=](const exit_msg& msg) {
// Only trap the first exit, regularly shutdown on the next one.
self->set_exit_handler({});
// We shut down the components in the order in which data flows so that
// downstream components can still process in-flight data. Because the
// terminator operates with a stack of components, we specify them in
// reverse order.
self->spawn(terminator, msg.reason, actor_cast<actor>(self),
self->state.registry.components[node],
std::vector<std::string>{"exporter", "index", "archive",
"importer", "source"});
}
);
return {
[=](put_atom, const std::string& type, const actor& component,
std::string& label) -> result<ok_atom> {
VAST_DEBUG(self, "got new", type, '(' << label << ')');
register_component(self, self->state, type, component, label);
return ok_atom::value;
},
[=](try_put_atom, const std::string& type, const actor& component,
std::string& label) -> result<void> {
VAST_DEBUG(self, "got new", type, '(' << label << ')');
auto& st = self->state;
auto& local = st.registry.components[node];
if (is_singleton(type) && local.count(type) > 0)
return make_error(ec::unspecified, "component already exists");
register_component(self, st, type, component, label);
return caf::unit;
},
[=](put_atom, const std::string& name, const std::string& type,
const actor& component, const std::string& label) {
VAST_DEBUG(self, "got PUT from peer", name, "for", type);
auto& components = self->state.registry.components[name];
components.emplace(type, component_state{component, label});
self->monitor(component);
},
[=](get_atom) -> result<registry> {
return self->state.registry;
},
[=](peer_atom, const actor& peer, const std::string& peer_name)
-> typed_response_promise<state_atom, registry> {
auto rp = self->make_response_promise<state_atom, registry>();
if (self->state.registry.components.count(peer_name) > 0) {
VAST_ERROR(self, "peer name already exists", peer_name);
return rp.deliver(make_error(ec::unspecified, "duplicate node name"));
}
VAST_DEBUG(self, "shipping state to new peer", peer_name);
rp.delegate(peer, state_atom::value, self->state.registry);
return rp;
},
[=](state_atom, registry& reg) -> result<ok_atom> {
VAST_DEBUG(self, "got state for", reg.components.size(), "peers");
// Monitor all remote components.
for (auto& peer : reg.components)
for (auto& pair : peer.second)
self->monitor(pair.second.actor);
// Incorporate new state from peer.
std::move(reg.components.begin(), reg.components.end(),
std::inserter(self->state.registry.components,
self->state.registry.components.end()));
// Broadcast our own state to all peers, without expecting a reply.
auto i = self->state.registry.components.find(node);
VAST_ASSERT(i != self->state.registry.components.end());
for (auto& peer : self->state.registry.components) {
auto& t = peer.second.find("tracker")->second.actor;
if (t != self)
self->send(actor_cast<tracker_type>(t), state_atom::value,
component_map_entry{*i});
}
return ok_atom::value;
},
[=](state_atom, component_map_entry& entry) {
VAST_DEBUG(self, "got components from new peer");
for (auto& pair : entry.second)
self->monitor(pair.second.actor);
auto result = self->state.registry.components.insert(std::move(entry));
VAST_ASSERT(result.second);
}
};
}
} // namespace vast::system
<|endoftext|> |
<commit_before>/*
* server.cpp
*
* Created on: Mar 29, 2017
* Author: patrick
*/
#include "Server.h"
using namespace std;
const string DIR_NAME = "server";
const string FILE_NAME = "test.txt";
Server::Server() {
}
void Server::connect(string* response) {
*response = "ACK";
is_connected = true;
return;
}
bool Server::does_file_exist(string filename) {
if (filename == FILE_NAME) {
return true;
}
return false;
}
ifstream Server::get_file(string filename, string * response) {
try {
ifstream file((DIR_NAME + "/" + filename).c_str(), std::ios::binary);
*response = "ACK";
return file;
}
catch (std::exception& e) {
return ifstream();
}
}
bool Server::connection_established() {
return is_connected;
}
<commit_msg>Delete Server.cpp<commit_after><|endoftext|> |
<commit_before>#include "ANIMITEM.H"
#include <LIBGTE.H>
#include "GTEREG.H"
void mmPushMatrix(int* fp)//81C0C(<)
{
mLoadMatrix((int*)fp[20]);
}
void mLoadMatrix(int* a0)
{
}
void stash_the_info(int meshp/*a0*/, int* fp)//81750
{
int* at;
at = (int*)fp[17];
((int*)at)[0] = meshp;
at[1] = R11 | (R12 << 16);
at[2] = R13 | (R21 << 16);
at[3] = R22 | (R23 << 16);
at[4] = R31 | (R32 << 16);
at[5] = R33;
at[6] = TRX;
at[7] = TRY;
at[8] = TRZ;
at += 9;
fp[19]++;
fp[17] = (int)at;
}
int GetBounds(int t0, int a2, int a3, int t1, int t2, int v0, int a0, int a1, int t3, int t4, int t5)//8139C
{
if (t0 < a2)
{
a2 = t0;
}
//loc_813AC
if (t0 >= a3)
{
a3 = t0;
}
//loc_813B8
if (t1 < a2)
{
a2 = t1;
}
//loc_813C4
if (t1 >= a3)
{
a3 = t1;
}
if (t2 < a2)
{
a3 = t2;
}
//loc_813DC
t0 <<= 16;
if (t2 >= a3)
{
a3 = t2;
}
//loc_813E8
t1 <<= 16;
t2 <<= 16;
if (t0 < a0)
{
a0 = t0;
}
if (t0 >= a1)
{
a1 = t0;
}
if (t1 < a0)
{
a0 = t1;
}
if (t1 >= a1)
{
a1 = t1;
}
if (t2 < a0)
{
a0 = t2;
}
if (t2 >= a1)
{
a1 = t2;
}
if (t3 < 0x5000)
{
v0 = 1;
}
if (t4 < 0x5000)
{
v0 = 1;
}
if (t5 < 0x5000)
{
v0 = 1;
}
return v0;
}
int mClipBoundingBox2(short* bounds, int* sp /*fp*/)//811FC
{
int t0 = TRZ - 20480;
int t3;
int t1;
int t4;
int t2;
int t7;
int v0 = 0;
int at;
int t9;
int t8;
int a0;
int a1;
int a2;
int t5;
int a3;
if (t0 < 0)
{
t0 = bounds[0];
t3 = bounds[1];
t1 = bounds[2];
t4 = bounds[3];
t2 = bounds[4];
t7 = bounds[5];
t1 <<= 16;
t4 <<= 16;
at = t0 | t1;
VX0 = at & 0xFFFF;
VY0 = at >> 16;
VZ0 = t2;
at = t3 | t1;
VX1 = at & 0xFFFF;
VY1 = at >> 16;
VZ1 = t2;
at = t0 | t4;
VX2 = at & 0xFFFF;
VY2 = at >> 16;
VZ2 = t2;
docop2(0x280030);
t9 = t3 | t4;
t8 = t2;
a0 = 0x7FFFFFFF;
a1 = 0x81000000;
a2 = a0;
t0 = SXY0;
t1 = SXY1;
t2 = SXY2;
t3 = SZ1;
t4 = SZ2;
t5 = SZ3;
VZ0 = t7;
VZ1 = t7;
VZ2 = t7;
a3 = a1;
docop2(0x280030);
t3 -= 33;
t4 -= 33;
t5 -= 33;
v0 = 0;
v0 = GetBounds(t0, a2, a3, t1, t2, v0, a0, a1, t3, t4, t5);
t0 = SXY0;
t1 = SXY1;
t2 = SXY2;
t3 = SZ1;
t4 = SZ2;
t5 = SZ3;
VX0 = (t9 & 0xFFFF);
VY0 = (t9 >> 16) & 0xFFFF;
VZ0 = t8;
VX1 = (t9 & 0xFFFF);
VY1 = (t9 >> 16) & 0xFFFF;
t2 -= 0x21;
docop2(0x280030);
t4 -= 0x21;
t5 -= 0x21;
v0 = GetBounds(t0, a2, a3, t1, t2, v0, a0, a1, t3, t4, t5);
t0 = SXY0;
t1 = SXY1;
t3 = SZ1;
t4 = SZ2;
t3 -= 0x21;
t4 -= 0x21;
t2 = t1;
t5 = t4;
v0 = GetBounds(t0, at, a3, t1, t2, v0, a0, a1, t3, t4, t5);
t0 = ((short*)sp)[73];
t1 = ((short*)sp)[75];
t2 = ((short*)sp)[72];
t3 = ((short*)sp)[74];
a0 >>= 16;
a1 >>= 16;
a2 >>= 16;
a3 >>= 16;
if (v0 == 0 || t0 < a0 || t1 < a2 || a1 < t2 || a3 < t3)
{
return 0;
}
if (v0 < 9 || a0 < t2 || a2 < t3 || t0 < a1 || t1 < a3)
{
return -1;
}
return 1;
}
return v0;
}
<commit_msg>[Specific-PSXPC_N] Implement mLoadMatrix<commit_after>#include "ANIMITEM.H"
#include <LIBGTE.H>
#include "GTEREG.H"
void mmPushMatrix(int* fp)//81C0C(<)
{
mLoadMatrix((int*)fp[20], fp);
}
void mLoadMatrix(int* a0, int* fp)//81C18(<)
{
R11 = (a0[0] & 0xFFFF);
R12 = (a0[0] >> 16) & 0xFFFF;
R13 = (a0[1] & 0xFFFF);
R21 = (a0[1] >> 16) & 0xFFFF;
R22 = (a0[2] & 0xFFFF);
R23 = (a0[2] >> 16) & 0xFFFF;
R31 = (a0[3] & 0xFFFF);
R32 = (a0[3] >> 16) & 0xFFFF;
R33 = (a0[4] & 0xFFFF);
TRX = a0[5];
TRY = a0[6];
TRZ = a0[7];
fp[50] = (int)a0;
}
void stash_the_info(int meshp/*a0*/, int* fp)//81750
{
int* at;
at = (int*)fp[17];
((int*)at)[0] = meshp;
at[1] = R11 | (R12 << 16);
at[2] = R13 | (R21 << 16);
at[3] = R22 | (R23 << 16);
at[4] = R31 | (R32 << 16);
at[5] = R33;
at[6] = TRX;
at[7] = TRY;
at[8] = TRZ;
at += 9;
fp[19]++;
fp[17] = (int)at;
}
int GetBounds(int t0, int a2, int a3, int t1, int t2, int v0, int a0, int a1, int t3, int t4, int t5)//8139C
{
if (t0 < a2)
{
a2 = t0;
}
//loc_813AC
if (t0 >= a3)
{
a3 = t0;
}
//loc_813B8
if (t1 < a2)
{
a2 = t1;
}
//loc_813C4
if (t1 >= a3)
{
a3 = t1;
}
if (t2 < a2)
{
a3 = t2;
}
//loc_813DC
t0 <<= 16;
if (t2 >= a3)
{
a3 = t2;
}
//loc_813E8
t1 <<= 16;
t2 <<= 16;
if (t0 < a0)
{
a0 = t0;
}
if (t0 >= a1)
{
a1 = t0;
}
if (t1 < a0)
{
a0 = t1;
}
if (t1 >= a1)
{
a1 = t1;
}
if (t2 < a0)
{
a0 = t2;
}
if (t2 >= a1)
{
a1 = t2;
}
if (t3 < 0x5000)
{
v0 = 1;
}
if (t4 < 0x5000)
{
v0 = 1;
}
if (t5 < 0x5000)
{
v0 = 1;
}
return v0;
}
int mClipBoundingBox2(short* bounds, int* sp /*fp*/)//811FC
{
int t0 = TRZ - 20480;
int t3;
int t1;
int t4;
int t2;
int t7;
int v0 = 0;
int at;
int t9;
int t8;
int a0;
int a1;
int a2;
int t5;
int a3;
if (t0 < 0)
{
t0 = bounds[0];
t3 = bounds[1];
t1 = bounds[2];
t4 = bounds[3];
t2 = bounds[4];
t7 = bounds[5];
t1 <<= 16;
t4 <<= 16;
at = t0 | t1;
VX0 = at & 0xFFFF;
VY0 = at >> 16;
VZ0 = t2;
at = t3 | t1;
VX1 = at & 0xFFFF;
VY1 = at >> 16;
VZ1 = t2;
at = t0 | t4;
VX2 = at & 0xFFFF;
VY2 = at >> 16;
VZ2 = t2;
docop2(0x280030);
t9 = t3 | t4;
t8 = t2;
a0 = 0x7FFFFFFF;
a1 = 0x81000000;
a2 = a0;
t0 = SXY0;
t1 = SXY1;
t2 = SXY2;
t3 = SZ1;
t4 = SZ2;
t5 = SZ3;
VZ0 = t7;
VZ1 = t7;
VZ2 = t7;
a3 = a1;
docop2(0x280030);
t3 -= 33;
t4 -= 33;
t5 -= 33;
v0 = 0;
v0 = GetBounds(t0, a2, a3, t1, t2, v0, a0, a1, t3, t4, t5);
t0 = SXY0;
t1 = SXY1;
t2 = SXY2;
t3 = SZ1;
t4 = SZ2;
t5 = SZ3;
VX0 = (t9 & 0xFFFF);
VY0 = (t9 >> 16) & 0xFFFF;
VZ0 = t8;
VX1 = (t9 & 0xFFFF);
VY1 = (t9 >> 16) & 0xFFFF;
t2 -= 0x21;
docop2(0x280030);
t4 -= 0x21;
t5 -= 0x21;
v0 = GetBounds(t0, a2, a3, t1, t2, v0, a0, a1, t3, t4, t5);
t0 = SXY0;
t1 = SXY1;
t3 = SZ1;
t4 = SZ2;
t3 -= 0x21;
t4 -= 0x21;
t2 = t1;
t5 = t4;
v0 = GetBounds(t0, at, a3, t1, t2, v0, a0, a1, t3, t4, t5);
t0 = ((short*)sp)[73];
t1 = ((short*)sp)[75];
t2 = ((short*)sp)[72];
t3 = ((short*)sp)[74];
a0 >>= 16;
a1 >>= 16;
a2 >>= 16;
a3 >>= 16;
if (v0 == 0 || t0 < a0 || t1 < a2 || a1 < t2 || a3 < t3)
{
return 0;
}
if (v0 < 9 || a0 < t2 || a2 < t3 || t0 < a1 || t1 < a3)
{
return -1;
}
return 1;
}
return v0;
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "paxos/serialization.hpp"
TEST(SerializationUnitTest, testDecreeIsSerializableAndDeserializable)
{
Decree expected(Replica("an_author_1"), 1, "the_decree_contents", DecreeType::UserDecree), actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<Decree>(string_obj);
ASSERT_EQ(expected.author.hostname, actual.author.hostname);
ASSERT_EQ(expected.author.port, actual.author.port);
ASSERT_EQ(expected.content, actual.content);
ASSERT_EQ(expected.number, actual.number);
}
TEST(SerializationUnitTest, testReplicaIsSerializableAndDeserializable)
{
Replica expected("hostname", 123), actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<Replica>(string_obj);
ASSERT_EQ(expected.hostname, actual.hostname);
ASSERT_EQ(expected.port, actual.port);
}
TEST(SerializationUnitTest, testMessageIsSerializableAndDeserializable)
{
Message expected(
Decree(Replica("author-hostname", 0), 1, "the_decree_contents", DecreeType::UserDecree),
Replica("hostname-A", 111),
Replica("hostname-B", 111),
MessageType::PrepareMessage),
actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<Message>(string_obj);
ASSERT_EQ(expected.decree.author.hostname, actual.decree.author.hostname);
ASSERT_EQ(expected.decree.author.port, actual.decree.author.port);
ASSERT_EQ(expected.decree.number, actual.decree.number);
ASSERT_EQ(expected.decree.content, actual.decree.content);
ASSERT_EQ(expected.from.hostname, actual.from.hostname);
ASSERT_EQ(expected.from.port, actual.from.port);
ASSERT_EQ(expected.to.hostname, actual.to.hostname);
ASSERT_EQ(expected.to.port, actual.to.port);
ASSERT_EQ(expected.type, actual.type);
}
TEST(SerializationUnitTest, testBootstrapFileIsSerializableAndDeserializable)
{
BootstrapFile expected(
"the_filename",
"content of the bootstrap file."),
actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<BootstrapFile>(string_obj);
ASSERT_EQ(expected.name, actual.name);
ASSERT_EQ(expected.content, actual.content);
}
TEST(SerializationUnitTest, testSerializationWithPaddedFluffOnTheEndOfTheBuffer)
{
Decree expected(Replica("an_author_1", 0), 1, "the_decree_contents", DecreeType::UserDecree), actual;
actual = Deserialize<Decree>(
"22 serialization::archive 11 0 0 0 0 11 an_author_1 "
"0 1 0 19 the_decree_contents THIS IS FLUFF!!!"
);
ASSERT_EQ(expected.author.hostname, actual.author.hostname);
ASSERT_EQ(expected.author.port, actual.author.port);
ASSERT_EQ(expected.content, actual.content);
ASSERT_EQ(expected.number, actual.number);
}
TEST(SerializationUnitTest, testSerializationWithUniversalReferenceValues)
{
Decree expected(Replica("an_author_1", 0), 1, "the_decree_contents", DecreeType::UserDecree), actual;
std::string string_obj = Serialize(Decree(Replica("an_author_1", 0), 1, "the_decree_contents", DecreeType::UserDecree));
actual = Deserialize<Decree>(string_obj);
ASSERT_EQ(expected.author.hostname, actual.author.hostname);
ASSERT_EQ(expected.author.port, actual.author.port);
ASSERT_EQ(expected.content, actual.content);
ASSERT_EQ(expected.number, actual.number);
}
<commit_msg>Add unittest system decree serialization<commit_after>#include "gtest/gtest.h"
#include "paxos/serialization.hpp"
TEST(SerializationUnitTest, testDecreeIsSerializableAndDeserializable)
{
Decree expected(Replica("an_author_1"), 1, "the_decree_contents", DecreeType::UserDecree), actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<Decree>(string_obj);
ASSERT_EQ(expected.author.hostname, actual.author.hostname);
ASSERT_EQ(expected.author.port, actual.author.port);
ASSERT_EQ(expected.content, actual.content);
ASSERT_EQ(expected.number, actual.number);
}
TEST(SerializationUnitTest, testSystemDecreeIsSerializableAndDeserializable)
{
int number = 3;
SystemOperation operation = SystemOperation::AddReplica;
std::string content("system decree contents");
SystemDecree expected(operation, number, content), actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<SystemDecree>(string_obj);
ASSERT_EQ(expected.operation, actual.operation);
ASSERT_EQ(expected.number, actual.number);
ASSERT_EQ(expected.content, actual.content);
}
TEST(SerializationUnitTest, testReplicaIsSerializableAndDeserializable)
{
Replica expected("hostname", 123), actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<Replica>(string_obj);
ASSERT_EQ(expected.hostname, actual.hostname);
ASSERT_EQ(expected.port, actual.port);
}
TEST(SerializationUnitTest, testMessageIsSerializableAndDeserializable)
{
Message expected(
Decree(Replica("author-hostname", 0), 1, "the_decree_contents", DecreeType::UserDecree),
Replica("hostname-A", 111),
Replica("hostname-B", 111),
MessageType::PrepareMessage),
actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<Message>(string_obj);
ASSERT_EQ(expected.decree.author.hostname, actual.decree.author.hostname);
ASSERT_EQ(expected.decree.author.port, actual.decree.author.port);
ASSERT_EQ(expected.decree.number, actual.decree.number);
ASSERT_EQ(expected.decree.content, actual.decree.content);
ASSERT_EQ(expected.from.hostname, actual.from.hostname);
ASSERT_EQ(expected.from.port, actual.from.port);
ASSERT_EQ(expected.to.hostname, actual.to.hostname);
ASSERT_EQ(expected.to.port, actual.to.port);
ASSERT_EQ(expected.type, actual.type);
}
TEST(SerializationUnitTest, testBootstrapFileIsSerializableAndDeserializable)
{
BootstrapFile expected(
"the_filename",
"content of the bootstrap file."),
actual;
std::string string_obj = Serialize(expected);
actual = Deserialize<BootstrapFile>(string_obj);
ASSERT_EQ(expected.name, actual.name);
ASSERT_EQ(expected.content, actual.content);
}
TEST(SerializationUnitTest, testSerializationWithPaddedFluffOnTheEndOfTheBuffer)
{
Decree expected(Replica("an_author_1", 0), 1, "the_decree_contents", DecreeType::UserDecree), actual;
actual = Deserialize<Decree>(
"22 serialization::archive 11 0 0 0 0 11 an_author_1 "
"0 1 0 19 the_decree_contents THIS IS FLUFF!!!"
);
ASSERT_EQ(expected.author.hostname, actual.author.hostname);
ASSERT_EQ(expected.author.port, actual.author.port);
ASSERT_EQ(expected.content, actual.content);
ASSERT_EQ(expected.number, actual.number);
}
TEST(SerializationUnitTest, testSerializationWithUniversalReferenceValues)
{
Decree expected(Replica("an_author_1", 0), 1, "the_decree_contents", DecreeType::UserDecree), actual;
std::string string_obj = Serialize(Decree(Replica("an_author_1", 0), 1, "the_decree_contents", DecreeType::UserDecree));
actual = Deserialize<Decree>(string_obj);
ASSERT_EQ(expected.author.hostname, actual.author.hostname);
ASSERT_EQ(expected.author.port, actual.author.port);
ASSERT_EQ(expected.content, actual.content);
ASSERT_EQ(expected.number, actual.number);
}
<|endoftext|> |
<commit_before>/*
* EndEffectorTrajectory.hpp
*
* Created on: Mar 16, 2016
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#pragma once
// Free Gait
#include "free_gait_core/TypeDefs.hpp"
#include "free_gait_core/leg_motion/EndEffectorMotionBase.hpp"
// Curves
#include <curves/PolynomialSplineVectorSpaceCurve.hpp>
// STD
#include <string>
#include <memory>
namespace free_gait {
class EndEffectorTrajectory : public EndEffectorMotionBase
{
public:
typedef typename curves::PolynomialSplineQuinticVector3Curve::ValueType ValueType;
typedef typename curves::PolynomialSplineQuinticVector3Curve::DerivativeType DerivativeType;
typedef typename curves::Time Time;
EndEffectorTrajectory(LimbEnum limb);
virtual ~EndEffectorTrajectory();
/*!
* Deep copy clone.
* @return a clone of this class.
*/
std::unique_ptr<LegMotionBase> clone() const;
/*!
* Update the trajectory with the foot start position.
* Do this to avoid jumps of the swing leg.
* @param startPosition the start position of the foot in the trajectoryFrameId_ frame.
* @return true if successful, false otherwise.
*/
void updateStartPosition(const Position& startPosition);
const ControlSetup getControlSetup() const;
bool prepareComputation(const State& state, const Step& step, const AdapterBase& adapter);
bool needsComputation() const;
bool isComputed() const;
/*!
* Evaluate the swing foot position at a given swing phase value.
* @param phase the swing phase value.
* @return the position of the foot on the swing trajectory.
*/
const Position evaluatePosition(const double time) const;
/*!
* Returns the total duration of the trajectory.
* @return the duration.
*/
double getDuration() const;
/*!
* Return the target (end position) of the swing profile.
* @return the target.
*/
const Position getTargetPosition() const;
const std::string& getFrameId(const ControlLevel& controlLevel) const;
bool isIgnoreContact() const;
bool isIgnoreForPoseAdaptation() const;
friend std::ostream& operator << (std::ostream& out, const EndEffectorTrajectory& endEffectorTrajectory);
friend class StepCompleter;
friend class StepRosConverter;
private:
void generateStraightKnots(std::vector<ValueType>& values) const;
void generateTriangleKnots(std::vector<ValueType>& values) const;
void generateSquareKnots(std::vector<ValueType>& values) const;
void computeTiming(const std::vector<ValueType>& values, std::vector<Time>& times) const;
bool ignoreContact_;
bool ignoreForPoseAdaptation_;
ControlSetup controlSetup_;
//! Knots.
std::unordered_map<ControlLevel, std::string, EnumClassHash> frameIds_;
std::vector<Time> times_;
std::unordered_map<ControlLevel, std::vector<ValueType>, EnumClassHash> values_;
double duration_;
//! Foot trajectory.
curves::PolynomialSplineQuinticVector3Curve trajectory_;
//! If trajectory is updated.
bool isComputed_;
};
} /* namespace */
<commit_msg>Update EndEffectorTrajectory.hpp<commit_after>/*
* EndEffectorTrajectory.hpp
*
* Created on: Mar 16, 2016
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#pragma once
// Free Gait
#include "free_gait_core/TypeDefs.hpp"
#include "free_gait_core/leg_motion/EndEffectorMotionBase.hpp"
// Curves
#include <curves/PolynomialSplineVectorSpaceCurve.hpp>
// STD
#include <string>
#include <memory>
namespace free_gait {
class EndEffectorTrajectory : public EndEffectorMotionBase
{
public:
typedef typename curves::PolynomialSplineQuinticVector3Curve::ValueType ValueType;
typedef typename curves::PolynomialSplineQuinticVector3Curve::DerivativeType DerivativeType;
typedef typename curves::Time Time;
EndEffectorTrajectory(LimbEnum limb);
virtual ~EndEffectorTrajectory();
/*!
* Deep copy clone.
* @return a clone of this class.
*/
std::unique_ptr<LegMotionBase> clone() const;
/*!
* Update the trajectory with the foot start position.
* Do this to avoid jumps of the swing leg.
* @param startPosition the start position of the foot in the trajectoryFrameId_ frame.
* @return true if successful, false otherwise.
*/
void updateStartPosition(const Position& startPosition);
const ControlSetup getControlSetup() const;
bool prepareComputation(const State& state, const Step& step, const AdapterBase& adapter);
bool needsComputation() const;
bool isComputed() const;
/*!
* Evaluate the swing foot position at a given swing phase value.
* @param phase the swing phase value.
* @return the position of the foot on the swing trajectory.
*/
const Position evaluatePosition(const double time) const;
void addTime(Time time);
void addValue(const ControlLevel& controlLevel, const ValueType value);
/*!
* Returns the total duration of the trajectory.
* @return the duration.
*/
double getDuration() const;
/*!
* Return the target (end position) of the swing profile.
* @return the target.
*/
const Position getTargetPosition() const;
void setFrameId(const ControlLevel& controlLevel, const std::string& frameId);
const std::string& getFrameId(const ControlLevel& controlLevel) const;
void setIgnoreContact(bool ignoreContact);
bool isIgnoreContact() const;
bool isIgnoreForPoseAdaptation() const;
friend std::ostream& operator << (std::ostream& out, const EndEffectorTrajectory& endEffectorTrajectory);
friend class StepCompleter;
friend class StepRosConverter;
private:
void generateStraightKnots(std::vector<ValueType>& values) const;
void generateTriangleKnots(std::vector<ValueType>& values) const;
void generateSquareKnots(std::vector<ValueType>& values) const;
void computeTiming(const std::vector<ValueType>& values, std::vector<Time>& times) const;
bool ignoreContact_;
bool ignoreForPoseAdaptation_;
ControlSetup controlSetup_;
//! Knots.
std::unordered_map<ControlLevel, std::string, EnumClassHash> frameIds_;
std::vector<Time> times_;
std::unordered_map<ControlLevel, std::vector<ValueType>, EnumClassHash> values_;
double duration_;
//! Foot trajectory.
curves::PolynomialSplineQuinticVector3Curve trajectory_;
//! If trajectory is updated.
bool isComputed_;
};
} /* namespace */
<|endoftext|> |
<commit_before>// Copyright 2018 The Flutter 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 "flutter/shell/platform/android/platform_message_response_android.h"
#include "flutter/shell/platform/android/platform_view_android_jni.h"
#include "lib/fxl/functional/make_copyable.h"
namespace shell {
PlatformMessageResponseAndroid::PlatformMessageResponseAndroid(
int response_id,
fml::jni::JavaObjectWeakGlobalRef weak_java_object,
fxl::RefPtr<fxl::TaskRunner> platform_task_runner)
: response_id_(response_id),
weak_java_object_(weak_java_object),
platform_task_runner_(std::move(platform_task_runner)) {}
// |blink::PlatformMessageResponse|
void PlatformMessageResponseAndroid::Complete(std::vector<uint8_t> data) {
platform_task_runner_->PostTask(
fxl::MakeCopyable([response = response_id_, //
weak_java_object = weak_java_object_, //
data = std::move(data) //
]() {
// We are on the platform thread. Attempt to get the strong reference to
// the Java object.
auto env = fml::jni::AttachCurrentThread();
auto java_object = weak_java_object.get(env);
if (java_object.is_null()) {
// The Java object was collected before this message response got to
// it. Drop the response on the floor.
return;
}
if (data.size() == 0) {
// If the data is empty, there is no reason to create a Java byte
// array. Make the response now with a nullptr now.
FlutterViewHandlePlatformMessageResponse(env, java_object.obj(),
response, nullptr);
}
// Convert the vector to a Java byte array.
fml::jni::ScopedJavaLocalRef<jbyteArray> data_array(
env, env->NewByteArray(data.size()));
env->SetByteArrayRegion(data_array.obj(), 0, data.size(),
reinterpret_cast<const jbyte*>(data.data()));
// Make the response call into Java.
FlutterViewHandlePlatformMessageResponse(env, java_object.obj(),
response, data_array.obj());
}));
}
// |blink::PlatformMessageResponse|
void PlatformMessageResponseAndroid::CompleteEmpty() {
Complete(std::vector<uint8_t>{});
}
} // namespace shell
<commit_msg>Fix Android platform channels (#5025)<commit_after>// Copyright 2018 The Flutter 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 "flutter/shell/platform/android/platform_message_response_android.h"
#include "flutter/shell/platform/android/platform_view_android_jni.h"
#include "lib/fxl/functional/make_copyable.h"
namespace shell {
PlatformMessageResponseAndroid::PlatformMessageResponseAndroid(
int response_id,
fml::jni::JavaObjectWeakGlobalRef weak_java_object,
fxl::RefPtr<fxl::TaskRunner> platform_task_runner)
: response_id_(response_id),
weak_java_object_(weak_java_object),
platform_task_runner_(std::move(platform_task_runner)) {}
// |blink::PlatformMessageResponse|
void PlatformMessageResponseAndroid::Complete(std::vector<uint8_t> data) {
platform_task_runner_->PostTask(
fxl::MakeCopyable([response = response_id_, //
weak_java_object = weak_java_object_, //
data = std::move(data) //
]() {
// We are on the platform thread. Attempt to get the strong reference to
// the Java object.
auto env = fml::jni::AttachCurrentThread();
auto java_object = weak_java_object.get(env);
if (java_object.is_null()) {
// The Java object was collected before this message response got to
// it. Drop the response on the floor.
return;
}
// Convert the vector to a Java byte array.
fml::jni::ScopedJavaLocalRef<jbyteArray> data_array(
env, env->NewByteArray(data.size()));
env->SetByteArrayRegion(data_array.obj(), 0, data.size(),
reinterpret_cast<const jbyte*>(data.data()));
// Make the response call into Java.
FlutterViewHandlePlatformMessageResponse(env, java_object.obj(),
response, data_array.obj());
}));
}
// |blink::PlatformMessageResponse|
void PlatformMessageResponseAndroid::CompleteEmpty() {
platform_task_runner_->PostTask(
fxl::MakeCopyable([response = response_id_, //
weak_java_object = weak_java_object_ //
]() {
// We are on the platform thread. Attempt to get the strong reference to
// the Java object.
auto env = fml::jni::AttachCurrentThread();
auto java_object = weak_java_object.get(env);
if (java_object.is_null()) {
// The Java object was collected before this message response got to
// it. Drop the response on the floor.
return;
}
// Make the response call into Java.
FlutterViewHandlePlatformMessageResponse(env, java_object.obj(),
response, nullptr);
}));
}
} // namespace shell
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "otbClampImageFilter.h"
#include "otbClampVectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float), m_RAMValue(0)
{
this->SetName("Output Image");
this->SetKey("out");
}
OutputImageParameter::~OutputImageParameter()
{
}
void OutputImageParameter::InitializeWriters()
{
m_UInt8Writer = UInt8WriterType::New();
m_Int16Writer = Int16WriterType::New();
m_UInt16Writer = UInt16WriterType::New();
m_Int32Writer = Int32WriterType::New();
m_UInt32Writer = UInt32WriterType::New();
m_FloatWriter = FloatWriterType::New();
m_DoubleWriter = DoubleWriterType::New();
m_VectorUInt8Writer = VectorUInt8WriterType::New();
m_VectorInt16Writer = VectorInt16WriterType::New();
m_VectorUInt16Writer = VectorUInt16WriterType::New();
m_VectorInt32Writer = VectorInt32WriterType::New();
m_VectorUInt32Writer = VectorUInt32WriterType::New();
m_VectorFloatWriter = VectorFloatWriterType::New();
m_VectorDoubleWriter = VectorDoubleWriterType::New();
m_RGBUInt8Writer = RGBUInt8WriterType::New();
m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
}
#define otbClampAndWriteImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef otb::ClampImageFilter<InputImageType, OutputImageType> ClampFilterType; \
typename ClampFilterType::Pointer clampFilter = ClampFilterType::New(); \
clampFilter->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName( this->GetFileName() ); \
writer->SetInput(clampFilter->GetOutput()); \
writer->SetAutomaticAdaptativeStreaming(m_RAMValue); \
writer->Update(); \
}
#define otbClampAndWriteVectorImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef otb::ClampVectorImageFilter<InputImageType, OutputImageType> ClampFilterType; \
typename ClampFilterType::Pointer clampFilter = ClampFilterType::New(); \
clampFilter->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName(this->GetFileName() ); \
writer->SetInput(clampFilter->GetOutput()); \
writer->SetAutomaticAdaptativeStreaming(m_RAMValue); \
writer->Update(); \
}
template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_uint8:
{
otbClampAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbClampAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
break;
}
case ImagePixelType_uint16:
{
otbClampAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbClampAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
break;
}
case ImagePixelType_uint32:
{
otbClampAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
break;
}
case ImagePixelType_float:
{
otbClampAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
break;
}
case ImagePixelType_double:
{
otbClampAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
break;
}
}
}
template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_uint8:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
break;
}
case ImagePixelType_double:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
break;
}
}
}
template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
{
if( m_PixelType == ImagePixelType_uint8 )
{
m_RGBAUInt8Writer->SetFileName( this->GetFileName() );
m_RGBAUInt8Writer->SetInput(dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()) );
m_RGBAUInt8Writer->SetAutomaticAdaptativeStreaming(m_RAMValue);
m_RGBAUInt8Writer->Update();
}
else
itkExceptionMacro("Unknown PixelType for RGBA Image. Only uint8 is supported.");
}
template <class TInputRGBImageType>
void
OutputImageParameter::SwitchRGBImageWrite()
{
if( m_PixelType == ImagePixelType_uint8 )
{
m_RGBUInt8Writer->SetFileName( this->GetFileName() );
m_RGBUInt8Writer->SetInput(dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()) );
m_RGBUInt8Writer->SetAutomaticAdaptativeStreaming(m_RAMValue);
m_RGBUInt8Writer->Update();
}
else
itkExceptionMacro("Unknown PixelType for RGB Image. Only uint8 is supported.");
}
void
OutputImageParameter::Write()
{
m_Image->UpdateOutputInformation();
if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt8ImageType>();
}
else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int16ImageType>();
}
else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt16ImageType>();
}
else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int32ImageType>();
}
else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt32ImageType>();
}
else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<FloatImageType>();
}
else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<DoubleImageType>();
}
else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt8VectorImageType>();
}
else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int16VectorImageType>();
}
else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt16VectorImageType>();
}
else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int32VectorImageType>();
}
else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt32VectorImageType>();
}
else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<FloatVectorImageType>();
}
else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<DoubleVectorImageType>();
}
else if (dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()))
{
SwitchRGBImageWrite<UInt8RGBImageType>();
}
else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt8RGBAImageType>();
}
else
{
itkExceptionMacro("Unknown image type");
}
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
int type = 0;
// 0 : image
// 1 : VectorImage
// 2 : RGBAImage
// 3 : RGBImage
itk::ProcessObject* writer = 0;
if (dynamic_cast<UInt8VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<Int16VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<UInt16VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<Int32VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<UInt32VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<FloatVectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<DoubleVectorImageType*> (m_Image.GetPointer()))
{
type = 1;
}
else
if (dynamic_cast<UInt8RGBAImageType*> (m_Image.GetPointer()))
{
type = 2;
writer = m_RGBAUInt8Writer;
itkWarningMacro("UInt8RGBAImageType will be saved in UInt8 format.");
return writer;
}
else
if (dynamic_cast<UInt8RGBImageType*> (m_Image.GetPointer()))
{
type = 3;
writer = m_RGBUInt8Writer;
itkWarningMacro("UInt8RGBImageType will be saved in UInt8 format.");
return writer;
}
switch (GetPixelType())
{
case ImagePixelType_uint8:
{
if (type == 1)
writer = m_VectorUInt8Writer;
else
if (type == 0)
writer = m_UInt8Writer;
else
if (type == 2)
writer = m_RGBAUInt8Writer;
else writer = m_RGBUInt8Writer;
break;
}
case ImagePixelType_int16:
{
if (type == 1)
writer = m_VectorInt16Writer;
else
if (type == 0) writer = m_Int16Writer;
break;
}
case ImagePixelType_uint16:
{
if (type == 1)
writer = m_VectorUInt16Writer;
else
if (type == 0) writer = m_UInt16Writer;
break;
}
case ImagePixelType_int32:
{
if (type == 1)
writer = m_VectorInt32Writer;
else
if (type == 0) writer = m_Int32Writer;
break;
}
case ImagePixelType_uint32:
{
if (type == 1)
writer = m_VectorUInt32Writer;
else
if (type == 0) writer = m_UInt32Writer;
break;
}
case ImagePixelType_float:
{
if (type == 1)
writer = m_VectorFloatWriter;
else
if (type == 0) writer = m_FloatWriter;
break;
}
case ImagePixelType_double:
{
if (type == 1)
writer = m_VectorDoubleWriter;
else
if (type == 0) writer = m_DoubleWriter;
break;
}
}
if (0 == writer)
{
itkExceptionMacro("Unknown Writer type.");
}
return writer;
}
OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter::HasValue() const
{
std::string filename(this->GetFileName());
return !filename.empty();
}
}
}
<commit_msg>COV: Fixing coverity issue 1221603 (logically dead code)<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "otbClampImageFilter.h"
#include "otbClampVectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float), m_RAMValue(0)
{
this->SetName("Output Image");
this->SetKey("out");
}
OutputImageParameter::~OutputImageParameter()
{
}
void OutputImageParameter::InitializeWriters()
{
m_UInt8Writer = UInt8WriterType::New();
m_Int16Writer = Int16WriterType::New();
m_UInt16Writer = UInt16WriterType::New();
m_Int32Writer = Int32WriterType::New();
m_UInt32Writer = UInt32WriterType::New();
m_FloatWriter = FloatWriterType::New();
m_DoubleWriter = DoubleWriterType::New();
m_VectorUInt8Writer = VectorUInt8WriterType::New();
m_VectorInt16Writer = VectorInt16WriterType::New();
m_VectorUInt16Writer = VectorUInt16WriterType::New();
m_VectorInt32Writer = VectorInt32WriterType::New();
m_VectorUInt32Writer = VectorUInt32WriterType::New();
m_VectorFloatWriter = VectorFloatWriterType::New();
m_VectorDoubleWriter = VectorDoubleWriterType::New();
m_RGBUInt8Writer = RGBUInt8WriterType::New();
m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
}
#define otbClampAndWriteImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef otb::ClampImageFilter<InputImageType, OutputImageType> ClampFilterType; \
typename ClampFilterType::Pointer clampFilter = ClampFilterType::New(); \
clampFilter->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName( this->GetFileName() ); \
writer->SetInput(clampFilter->GetOutput()); \
writer->SetAutomaticAdaptativeStreaming(m_RAMValue); \
writer->Update(); \
}
#define otbClampAndWriteVectorImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef otb::ClampVectorImageFilter<InputImageType, OutputImageType> ClampFilterType; \
typename ClampFilterType::Pointer clampFilter = ClampFilterType::New(); \
clampFilter->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName(this->GetFileName() ); \
writer->SetInput(clampFilter->GetOutput()); \
writer->SetAutomaticAdaptativeStreaming(m_RAMValue); \
writer->Update(); \
}
template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_uint8:
{
otbClampAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbClampAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
break;
}
case ImagePixelType_uint16:
{
otbClampAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbClampAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
break;
}
case ImagePixelType_uint32:
{
otbClampAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
break;
}
case ImagePixelType_float:
{
otbClampAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
break;
}
case ImagePixelType_double:
{
otbClampAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
break;
}
}
}
template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_uint8:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
break;
}
case ImagePixelType_double:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
break;
}
}
}
template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
{
if( m_PixelType == ImagePixelType_uint8 )
{
m_RGBAUInt8Writer->SetFileName( this->GetFileName() );
m_RGBAUInt8Writer->SetInput(dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()) );
m_RGBAUInt8Writer->SetAutomaticAdaptativeStreaming(m_RAMValue);
m_RGBAUInt8Writer->Update();
}
else
itkExceptionMacro("Unknown PixelType for RGBA Image. Only uint8 is supported.");
}
template <class TInputRGBImageType>
void
OutputImageParameter::SwitchRGBImageWrite()
{
if( m_PixelType == ImagePixelType_uint8 )
{
m_RGBUInt8Writer->SetFileName( this->GetFileName() );
m_RGBUInt8Writer->SetInput(dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()) );
m_RGBUInt8Writer->SetAutomaticAdaptativeStreaming(m_RAMValue);
m_RGBUInt8Writer->Update();
}
else
itkExceptionMacro("Unknown PixelType for RGB Image. Only uint8 is supported.");
}
void
OutputImageParameter::Write()
{
m_Image->UpdateOutputInformation();
if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt8ImageType>();
}
else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int16ImageType>();
}
else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt16ImageType>();
}
else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int32ImageType>();
}
else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt32ImageType>();
}
else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<FloatImageType>();
}
else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<DoubleImageType>();
}
else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt8VectorImageType>();
}
else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int16VectorImageType>();
}
else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt16VectorImageType>();
}
else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int32VectorImageType>();
}
else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt32VectorImageType>();
}
else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<FloatVectorImageType>();
}
else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<DoubleVectorImageType>();
}
else if (dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()))
{
SwitchRGBImageWrite<UInt8RGBImageType>();
}
else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt8RGBAImageType>();
}
else
{
itkExceptionMacro("Unknown image type");
}
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
int type = 0;
// 0 : image
// 1 : VectorImage
// 2 : RGBAImage
// 3 : RGBImage
itk::ProcessObject* writer = 0;
if (dynamic_cast<UInt8VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<Int16VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<UInt16VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<Int32VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<UInt32VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<FloatVectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<DoubleVectorImageType*> (m_Image.GetPointer()))
{
type = 1;
}
else
if (dynamic_cast<UInt8RGBAImageType*> (m_Image.GetPointer()))
{
type = 2;
writer = m_RGBAUInt8Writer;
itkWarningMacro("UInt8RGBAImageType will be saved in UInt8 format.");
return writer;
}
else
if (dynamic_cast<UInt8RGBImageType*> (m_Image.GetPointer()))
{
type = 3;
writer = m_RGBUInt8Writer;
itkWarningMacro("UInt8RGBImageType will be saved in UInt8 format.");
return writer;
}
switch (GetPixelType())
{
case ImagePixelType_uint8:
{
switch(type)
{
case 0:
writer = m_UInt8Writer;
break;
case 1:
writer = m_VectorUInt8Writer;
break;
case 2:
writer = m_RGBAUInt8Writer;
break;
default:
writer = m_RGBUInt8Writer;
break;
}
break;
}
case ImagePixelType_int16:
{
if (type == 1)
writer = m_VectorInt16Writer;
else
if (type == 0) writer = m_Int16Writer;
break;
}
case ImagePixelType_uint16:
{
if (type == 1)
writer = m_VectorUInt16Writer;
else
if (type == 0) writer = m_UInt16Writer;
break;
}
case ImagePixelType_int32:
{
if (type == 1)
writer = m_VectorInt32Writer;
else
if (type == 0) writer = m_Int32Writer;
break;
}
case ImagePixelType_uint32:
{
if (type == 1)
writer = m_VectorUInt32Writer;
else
if (type == 0) writer = m_UInt32Writer;
break;
}
case ImagePixelType_float:
{
if (type == 1)
writer = m_VectorFloatWriter;
else
if (type == 0) writer = m_FloatWriter;
break;
}
case ImagePixelType_double:
{
if (type == 1)
writer = m_VectorDoubleWriter;
else
if (type == 0) writer = m_DoubleWriter;
break;
}
}
if (0 == writer)
{
itkExceptionMacro("Unknown Writer type.");
}
return writer;
}
OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter::HasValue() const
{
std::string filename(this->GetFileName());
return !filename.empty();
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
/*===========================================================================*/
/*===============================[ Includes ]================================*/
/*===========================================================================*/
#include "otbOGRLayerWrapper.h"
#include <cassert>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include "ogrsf_frmts.h" // OGRDataSource & OGRLayer
/*===========================================================================*/
/*======================[ Construction & Destruction ]=======================*/
/*===========================================================================*/
namespace { // Anonymous namespace
/**\ingroup Geometry
* Deleter for \c boost::shared_ptr<> that doesn't delete.
* This is required for \c OGRLayer s that belong to \c OGRDataSource.
* \internal
*/
struct LeaveAloneDeleter
{
void operator()(OGRLayer*) const {}
};
} // Anonymous namespace
otb::ogr::Layer::Layer(OGRLayer* layer)
: m_Layer(layer, LeaveAloneDeleter())
{
}
otb::ogr::Layer::Layer(OGRLayer* layer, OGRDataSource* sourceInChargeOfLifeTime)
: m_Layer(layer, boost::bind(&OGRDataSource::ReleaseResultSet, sourceInChargeOfLifeTime, _1))
{
assert(layer && "A null OGRlayer cannot belong to an OGRDataSource" );
// OGR always refuses "delete 0". *sigh*
}
/*===========================================================================*/
/*===============================[ Features ]================================*/
/*===========================================================================*/
int otb::ogr::Layer::GetFeatureCount(bool doForceComputation) const
{
assert(m_Layer);
return m_Layer->GetFeatureCount(doForceComputation);
}
otb::ogr::Feature otb::ogr::Layer::GetNextFeature()
{
assert(m_Layer && "OGRLayer not initialized");
return m_Layer->GetNextFeature();
}
otb::ogr::Layer::iterator otb::ogr::Layer::begin()
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->ResetReading();
return iterator(*this);
}
otb::ogr::Layer::const_iterator otb::ogr::Layer::cbegin() const
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->ResetReading();
return const_iterator(*const_cast <Layer*>(this));
}
void otb::ogr::Layer::CreateFeature(Feature feature)
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->CreateFeature(&feature.ogr());
}
void otb::ogr::Layer::DeleteFeature(long nFID)
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->DeleteFeature(nFID);
}
otb::ogr::Feature otb::ogr::Layer::GetFeature(long nFID)
{
assert(m_Layer && "OGRLayer not initialized");
const Feature feat = m_Layer->GetFeature(nFID);
return feat;
}
void otb::ogr::Layer::SetFeature(Feature feature)
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->SetFeature(&feature.ogr());
}
/*===========================================================================*/
/*=================================[ Misc ]==================================*/
/*===========================================================================*/
std::string otb::ogr::Layer::GetName() const
{
assert(m_Layer && "null layer");
#if GDAL_VERSION_NUM >= 1800
return m_Layer->GetName();
#else
return GetLayerDefn().GetName();
#endif
}
OGRLayer & otb::ogr::Layer::ogr()
{
assert(m_Layer && "OGRLayer not initialized");
return *m_Layer;
}
void otb::ogr::Layer::PrintSelf(std::ostream& os, itk::Indent indent) const
{
os << indent << "+";
if (m_Layer) // in case for odd reason the layer that should exist can't be found
{
os << "Layer <" << GetName() << ">\n";
indent = indent.GetNextIndent();
BOOST_FOREACH(Feature f, *this)
{
f.PrintSelf(os, indent);
}
// boost::for_each( // for each feature
// *this,
// boost::bind(&Feature::PrintSelf, _1, boost::ref(os), indent.GetNextIndent()));
}
else
{
os << "null Layer\n";
}
}
/*===========================================================================*/
/*============================[ Spatial Filter ]=============================*/
/*===========================================================================*/
OGRGeometry const* otb::ogr::Layer::GetSpatialFilter() const
{
assert(m_Layer && "OGRLayer not initialized");
OGRGeometry* spatialFilter = m_Layer->GetSpatialFilter();
return spatialFilter;
}
void otb::ogr::Layer::SetSpatialFilter(OGRGeometry const* spatialFilter)
{
assert(m_Layer && "OGRLayer not initialized");
// const_cast because OGR is not 100% const-correct
m_Layer->SetSpatialFilter(const_cast <OGRGeometry*>(spatialFilter));
}
/*===========================================================================*/
/*==========================[ Feature Definition ]===========================*/
/*===========================================================================*/
OGRFeatureDefn & otb::ogr::Layer::GetLayerDefn() const
{
assert(m_Layer && "OGRLayer not initialized");
return *const_cast <OGRLayer*>(m_Layer.get())->GetLayerDefn();
}
void otb::ogr::Layer::CreateField(
OGRFieldDefn const& field, bool bApproxOK/* = true */)
{
assert(m_Layer && "OGRLayer not initialized");
const OGRErr res = m_Layer->CreateField(const_cast <OGRFieldDefn*>(&field), bApproxOK);
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot create a new field in the layer <"<<GetName()<<">.");
}
}
void otb::ogr::Layer::DeleteField(size_t fieldIndex)
{
assert(m_Layer && "OGRLayer not initialized");
#if GDAL_VERSION_NUM < 1900
itkGenericExceptionMacro("OGRLayer::AlterFieldDefn is not supported by OGR v"
<< GDAL_VERSION << ". Upgrade to a version >= 1.9.0, and recompile OTB.")
#else
const OGRErr res = m_Layer->DeleteField(int(fieldIndex));
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot delete the "<<fieldIndex << "th field in the layer <"
<<GetName() <<">.");
}
#endif
}
void otb::ogr::Layer::AlterFieldDefn(
size_t fieldIndex, OGRFieldDefn& newFieldDefn, int nFlags)
{
assert(m_Layer && "OGRLayer not initialized");
#if GDAL_VERSION_NUM < 1900
itkGenericExceptionMacro("OGRLayer::AlterFieldDefn is not supported by OGR v"
<< GDAL_VERSION << ". Upgrade to a version >= 1.9.0, and recompile OTB.")
#else
const OGRErr res = m_Layer->AlterFieldDefn(int(fieldIndex), &newFieldDefn, nFlags);
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot alter the "<<fieldIndex << "th field in the layer <"
<<GetName() <<">.");
}
#endif
}
void otb::ogr::Layer::ReorderField(size_t oldPos, size_t newPos)
{
assert(m_Layer && "OGRLayer not initialized");
#if GDAL_VERSION_NUM < 1900
itkGenericExceptionMacro("OGRLayer::ReorderField is not supported by OGR v"
<< GDAL_VERSION << ". Upgrade to a version >= 1.9.0, and recompile OTB.")
#else
const OGRErr res = m_Layer->ReorderField(int(oldPos), int(newPos));
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot move the "<<oldPos << "th field to the "
<< newPos << "th position in the layer <" <<GetName() <<">.");
}
#endif
}
void otb::ogr::Layer::ReorderFields(int * map)
{
assert(m_Layer && "OGRLayer not initialized");
#if GDAL_VERSION_NUM < 1900
itkGenericExceptionMacro("OGRLayer::ReorderField is not supported by OGR v"
<< GDAL_VERSION << ". Upgrade to a version >= 1.9.0, and recompile OTB.")
#else
const OGRErr res = m_Layer->ReorderFields(map);
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot reorder the fields of the layer <"
<<GetName() <<">.");
}
#endif
}
<commit_msg>COMP: OTB-134/OGR now uses the official GDAL_VERSION_NUM #define<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
/*===========================================================================*/
/*===============================[ Includes ]================================*/
/*===========================================================================*/
#include "otbOGRLayerWrapper.h"
#include <cassert>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include "ogrsf_frmts.h" // OGRDataSource & OGRLayer
/*===========================================================================*/
/*======================[ Construction & Destruction ]=======================*/
/*===========================================================================*/
namespace { // Anonymous namespace
/**\ingroup Geometry
* Deleter for \c boost::shared_ptr<> that doesn't delete.
* This is required for \c OGRLayer s that belong to \c OGRDataSource.
* \internal
*/
struct LeaveAloneDeleter
{
void operator()(OGRLayer*) const {}
};
} // Anonymous namespace
otb::ogr::Layer::Layer(OGRLayer* layer)
: m_Layer(layer, LeaveAloneDeleter())
{
}
otb::ogr::Layer::Layer(OGRLayer* layer, OGRDataSource* sourceInChargeOfLifeTime)
: m_Layer(layer, boost::bind(&OGRDataSource::ReleaseResultSet, sourceInChargeOfLifeTime, _1))
{
assert(layer && "A null OGRlayer cannot belong to an OGRDataSource" );
// OGR always refuses "delete 0". *sigh*
}
/*===========================================================================*/
/*===============================[ Features ]================================*/
/*===========================================================================*/
int otb::ogr::Layer::GetFeatureCount(bool doForceComputation) const
{
assert(m_Layer);
return m_Layer->GetFeatureCount(doForceComputation);
}
otb::ogr::Feature otb::ogr::Layer::GetNextFeature()
{
assert(m_Layer && "OGRLayer not initialized");
return m_Layer->GetNextFeature();
}
otb::ogr::Layer::iterator otb::ogr::Layer::begin()
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->ResetReading();
return iterator(*this);
}
otb::ogr::Layer::const_iterator otb::ogr::Layer::cbegin() const
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->ResetReading();
return const_iterator(*const_cast <Layer*>(this));
}
void otb::ogr::Layer::CreateFeature(Feature feature)
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->CreateFeature(&feature.ogr());
}
void otb::ogr::Layer::DeleteFeature(long nFID)
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->DeleteFeature(nFID);
}
otb::ogr::Feature otb::ogr::Layer::GetFeature(long nFID)
{
assert(m_Layer && "OGRLayer not initialized");
const Feature feat = m_Layer->GetFeature(nFID);
return feat;
}
void otb::ogr::Layer::SetFeature(Feature feature)
{
assert(m_Layer && "OGRLayer not initialized");
m_Layer->SetFeature(&feature.ogr());
}
/*===========================================================================*/
/*=================================[ Misc ]==================================*/
/*===========================================================================*/
std::string otb::ogr::Layer::GetName() const
{
assert(m_Layer && "null layer");
#if GDAL_VERSION_NUM >= 1800
return m_Layer->GetName();
#else
return GetLayerDefn().GetName();
#endif
}
OGRLayer & otb::ogr::Layer::ogr()
{
assert(m_Layer && "OGRLayer not initialized");
return *m_Layer;
}
void otb::ogr::Layer::PrintSelf(std::ostream& os, itk::Indent indent) const
{
os << indent << "+";
if (m_Layer) // in case for odd reason the layer that should exist can't be found
{
os << "Layer <" << GetName() << ">\n";
indent = indent.GetNextIndent();
BOOST_FOREACH(Feature f, *this)
{
f.PrintSelf(os, indent);
}
// boost::for_each( // for each feature
// *this,
// boost::bind(&Feature::PrintSelf, _1, boost::ref(os), indent.GetNextIndent()));
}
else
{
os << "null Layer\n";
}
}
/*===========================================================================*/
/*============================[ Spatial Filter ]=============================*/
/*===========================================================================*/
OGRGeometry const* otb::ogr::Layer::GetSpatialFilter() const
{
assert(m_Layer && "OGRLayer not initialized");
OGRGeometry* spatialFilter = m_Layer->GetSpatialFilter();
return spatialFilter;
}
void otb::ogr::Layer::SetSpatialFilter(OGRGeometry const* spatialFilter)
{
assert(m_Layer && "OGRLayer not initialized");
// const_cast because OGR is not 100% const-correct
m_Layer->SetSpatialFilter(const_cast <OGRGeometry*>(spatialFilter));
}
/*===========================================================================*/
/*==========================[ Feature Definition ]===========================*/
/*===========================================================================*/
OGRFeatureDefn & otb::ogr::Layer::GetLayerDefn() const
{
assert(m_Layer && "OGRLayer not initialized");
return *const_cast <OGRLayer*>(m_Layer.get())->GetLayerDefn();
}
void otb::ogr::Layer::CreateField(
OGRFieldDefn const& field, bool bApproxOK/* = true */)
{
assert(m_Layer && "OGRLayer not initialized");
const OGRErr res = m_Layer->CreateField(const_cast <OGRFieldDefn*>(&field), bApproxOK);
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot create a new field in the layer <"<<GetName()<<">.");
}
}
void otb::ogr::Layer::DeleteField(size_t fieldIndex)
{
assert(m_Layer && "OGRLayer not initialized");
#if GDAL_VERSION_NUM < 1900
itkGenericExceptionMacro("OGRLayer::AlterFieldDefn is not supported by OGR v"
<< GDAL_VERSION_NUM << ". Upgrade to a version >= 1.9.0, and recompile OTB.")
#else
const OGRErr res = m_Layer->DeleteField(int(fieldIndex));
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot delete the "<<fieldIndex << "th field in the layer <"
<<GetName() <<">.");
}
#endif
}
void otb::ogr::Layer::AlterFieldDefn(
size_t fieldIndex, OGRFieldDefn& newFieldDefn, int nFlags)
{
assert(m_Layer && "OGRLayer not initialized");
#if GDAL_VERSION_NUM < 1900
itkGenericExceptionMacro("OGRLayer::AlterFieldDefn is not supported by OGR v"
<< GDAL_VERSION_NUM << ". Upgrade to a version >= 1.9.0, and recompile OTB.")
#else
const OGRErr res = m_Layer->AlterFieldDefn(int(fieldIndex), &newFieldDefn, nFlags);
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot alter the "<<fieldIndex << "th field in the layer <"
<<GetName() <<">.");
}
#endif
}
void otb::ogr::Layer::ReorderField(size_t oldPos, size_t newPos)
{
assert(m_Layer && "OGRLayer not initialized");
#if GDAL_VERSION_NUM < 1900
itkGenericExceptionMacro("OGRLayer::ReorderField is not supported by OGR v"
<< GDAL_VERSION_NUM << ". Upgrade to a version >= 1.9.0, and recompile OTB.")
#else
const OGRErr res = m_Layer->ReorderField(int(oldPos), int(newPos));
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot move the "<<oldPos << "th field to the "
<< newPos << "th position in the layer <" <<GetName() <<">.");
}
#endif
}
void otb::ogr::Layer::ReorderFields(int * map)
{
assert(m_Layer && "OGRLayer not initialized");
#if GDAL_VERSION_NUM < 1900
itkGenericExceptionMacro("OGRLayer::ReorderField is not supported by OGR v"
<< GDAL_VERSION_NUM << ". Upgrade to a version >= 1.9.0, and recompile OTB.")
#else
const OGRErr res = m_Layer->ReorderFields(map);
if (res != OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot reorder the fields of the layer <"
<<GetName() <<">.");
}
#endif
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: plugcon.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-01-20 12:58:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _PLUGCON_HXX
#define _PLUGCON_HXX
#include <stdarg.h>
#include <string.h>
#include <list>
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _MEDIATOR_HXX
#include <plugin/unx/mediator.hxx>
#endif
#if defined SOLARIS
#define USE_MOTIF
#endif
#define Window XLIB_Window
#define Font XLIB_Font
#define KeyCode XLIB_KeyCode
#define Time XLIB_Time
#define Cursor XLIB_Cursor
#define Region XLIB_Region
#define String XLIB_String
#define Boolean XLIB_Boolean
#define XPointer XLIB_XPointer
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Shell.h>
#include <X11/IntrinsicP.h> /* Intrinsics Definitions*/
#include <X11/StringDefs.h> /* Standard Name-String definitions*/
#if defined USE_MOTIF
#include <Xm/DrawingA.h>
#else
#include <X11/Xaw/Label.h>
#endif
#include <X11/Xatom.h>
#define XP_UNIX
#define MOZ_X11
#include <stdio.h>
#ifdef SYSTEM_MOZILLA
#define OJI
#define MOZ_X11
#include <npupp.h>
#include <npapi.h>
#else
#ifndef _NPAPI_H_
#include <npupp.h>
#include <npapi.h>
#endif
#endif
#undef Window
#undef Font
#undef KeyCode
#undef Time
#undef Cursor
#undef String
#undef Region
#undef Boolean
#undef XPointer
class ConnectorInstance
{
public:
NPP instance;
NPWindow window;
NPSetWindowCallbackStruct ws_info;
char* pMimeType;
void* pShell;
void* pWidget;
void* pForm;
int nArg;
char** argn;
char** argv;
char* pArgnBuf;
char* pArgvBuf;
NPSavedData aData;
ConnectorInstance( NPP inst, char* type,
int args, char* pargnbuf, ULONG nargnbytes,
char* pargvbuf, ULONG nargvbytes,
char* savedata, ULONG savebytes );
~ConnectorInstance();
};
class PluginConnector;
DECLARE_LIST( NPStreamList, NPStream* );
DECLARE_LIST( InstanceList, ConnectorInstance* );
DECLARE_LIST( PluginConnectorList, PluginConnector* );
class PluginConnector : public Mediator
{
protected:
NAMESPACE_VOS(OMutex) m_aUserEventMutex;
static PluginConnectorList allConnectors;
DECL_LINK( NewMessageHdl, Mediator* );
DECL_LINK( WorkOnNewMessageHdl, Mediator* );
NPStreamList m_aNPWrapStreams;
InstanceList m_aInstances;
ULONG FillBuffer( char*&, char*, ULONG, va_list );
public:
PluginConnector( int nSocket );
~PluginConnector();
virtual MediatorMessage* WaitForAnswer( ULONG nMessageID );
MediatorMessage* Transact( char*, ULONG, ... );
MediatorMessage* Transact( UINT32, ... );
void Respond( ULONG nID, char*, ULONG, ... );
ULONG Send( UINT32, ... );
static const UINT32 UnknownStreamID = 0xffffffff;
static const UINT32 UnknownNPPID = 0xffffffff;
UINT32 GetStreamID( NPStream* pStream );
UINT32 GetNPPID( NPP );
NPStreamList& getStreamList() { return m_aNPWrapStreams; }
NPError GetNPError( MediatorMessage* pMes )
{
NPError* pErr = (NPError*)pMes->GetBytes();
NPError aErr = *pErr;
delete [] pErr;
return aErr;
}
void CallWorkHandler()
{
LINK( this, PluginConnector, WorkOnNewMessageHdl ).
Call( (Mediator*)this );
}
};
enum CommandAtoms
{
eNPN_GetURL,
eNPN_GetURLNotify,
eNPN_DestroyStream,
eNPN_NewStream,
eNPN_PostURLNotify,
eNPN_PostURL,
eNPN_RequestRead,
eNPN_Status,
eNPN_Version,
eNPN_Write,
eNPN_UserAgent,
eNPP_DestroyStream,
eNPP_Destroy,
eNPP_DestroyPhase2,
eNPP_NewStream,
eNPP_New,
eNPP_SetWindow,
eNPP_StreamAsFile,
eNPP_URLNotify,
eNPP_WriteReady,
eNPP_Write,
eNPP_GetMIMEDescription,
eNPP_Initialize,
eNPP_Shutdown,
eMaxCommand
};
char* GetCommandName( CommandAtoms );
#define POST_STRING( x ) x ? x : const_cast<char*>(""), x ? strlen(x) : 1
#endif // _PLUGCON_HXX
<commit_msg>INTEGRATION: CWS cmcfixes29 (1.9.202); FILE MERGED 2006/11/24 10:33:04 cmc 1.9.202.1: #i64463# optionally disable Xaw for the extensions plugin in favour of direct Xt<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: plugcon.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2006-12-01 14:18:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _PLUGCON_HXX
#define _PLUGCON_HXX
#include <stdarg.h>
#include <string.h>
#include <list>
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _MEDIATOR_HXX
#include <plugin/unx/mediator.hxx>
#endif
#if defined SOLARIS
#define USE_MOTIF
#endif
#define Window XLIB_Window
#define Font XLIB_Font
#define KeyCode XLIB_KeyCode
#define Time XLIB_Time
#define Cursor XLIB_Cursor
#define Region XLIB_Region
#define String XLIB_String
#define Boolean XLIB_Boolean
#define XPointer XLIB_XPointer
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Shell.h>
#include <X11/IntrinsicP.h> /* Intrinsics Definitions*/
#include <X11/StringDefs.h> /* Standard Name-String definitions*/
#if defined USE_MOTIF
#include <Xm/DrawingA.h>
#else
# if defined DISABLE_XAW
# include <X11/Composite.h>
# else
# include <X11/Xaw/Label.h>
# endif
#endif
#include <X11/Xatom.h>
#define XP_UNIX
#define MOZ_X11
#include <stdio.h>
#ifdef SYSTEM_MOZILLA
#define OJI
#define MOZ_X11
#include <npupp.h>
#include <npapi.h>
#else
#ifndef _NPAPI_H_
#include <npupp.h>
#include <npapi.h>
#endif
#endif
#undef Window
#undef Font
#undef KeyCode
#undef Time
#undef Cursor
#undef String
#undef Region
#undef Boolean
#undef XPointer
class ConnectorInstance
{
public:
NPP instance;
NPWindow window;
NPSetWindowCallbackStruct ws_info;
char* pMimeType;
void* pShell;
void* pWidget;
void* pForm;
int nArg;
char** argn;
char** argv;
char* pArgnBuf;
char* pArgvBuf;
NPSavedData aData;
ConnectorInstance( NPP inst, char* type,
int args, char* pargnbuf, ULONG nargnbytes,
char* pargvbuf, ULONG nargvbytes,
char* savedata, ULONG savebytes );
~ConnectorInstance();
};
class PluginConnector;
DECLARE_LIST( NPStreamList, NPStream* );
DECLARE_LIST( InstanceList, ConnectorInstance* );
DECLARE_LIST( PluginConnectorList, PluginConnector* );
class PluginConnector : public Mediator
{
protected:
NAMESPACE_VOS(OMutex) m_aUserEventMutex;
static PluginConnectorList allConnectors;
DECL_LINK( NewMessageHdl, Mediator* );
DECL_LINK( WorkOnNewMessageHdl, Mediator* );
NPStreamList m_aNPWrapStreams;
InstanceList m_aInstances;
ULONG FillBuffer( char*&, char*, ULONG, va_list );
public:
PluginConnector( int nSocket );
~PluginConnector();
virtual MediatorMessage* WaitForAnswer( ULONG nMessageID );
MediatorMessage* Transact( char*, ULONG, ... );
MediatorMessage* Transact( UINT32, ... );
void Respond( ULONG nID, char*, ULONG, ... );
ULONG Send( UINT32, ... );
static const UINT32 UnknownStreamID = 0xffffffff;
static const UINT32 UnknownNPPID = 0xffffffff;
UINT32 GetStreamID( NPStream* pStream );
UINT32 GetNPPID( NPP );
NPStreamList& getStreamList() { return m_aNPWrapStreams; }
NPError GetNPError( MediatorMessage* pMes )
{
NPError* pErr = (NPError*)pMes->GetBytes();
NPError aErr = *pErr;
delete [] pErr;
return aErr;
}
void CallWorkHandler()
{
LINK( this, PluginConnector, WorkOnNewMessageHdl ).
Call( (Mediator*)this );
}
};
enum CommandAtoms
{
eNPN_GetURL,
eNPN_GetURLNotify,
eNPN_DestroyStream,
eNPN_NewStream,
eNPN_PostURLNotify,
eNPN_PostURL,
eNPN_RequestRead,
eNPN_Status,
eNPN_Version,
eNPN_Write,
eNPN_UserAgent,
eNPP_DestroyStream,
eNPP_Destroy,
eNPP_DestroyPhase2,
eNPP_NewStream,
eNPP_New,
eNPP_SetWindow,
eNPP_StreamAsFile,
eNPP_URLNotify,
eNPP_WriteReady,
eNPP_Write,
eNPP_GetMIMEDescription,
eNPP_Initialize,
eNPP_Shutdown,
eMaxCommand
};
char* GetCommandName( CommandAtoms );
#define POST_STRING( x ) x ? x : const_cast<char*>(""), x ? strlen(x) : 1
#endif // _PLUGCON_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xsdvalidationhelper.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2006-03-14 11:35:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONHELPER_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONHELPER_HXX
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_EFORMSHELPER_HXX
#include "eformshelper.hxx"
#endif
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_XSDDATATYPES_HXX
#include "xsddatatypes.hxx"
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_XSD_XDATATYPE_HPP_
#include <com/sun/star/xsd/XDataType.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
/** === end UNO includes === **/
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
//........................................................................
namespace pcr
{
//........................................................................
class XSDDataType;
//====================================================================
//= XSDValidationHelper
//====================================================================
class XSDValidationHelper : public EFormsHelper
{
private:
bool m_bInspectingFormattedField;
public:
bool isInspectingFormattedField() const { return m_bInspectingFormattedField; }
public:
XSDValidationHelper(
::osl::Mutex& _rMutex,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxIntrospectee,
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument
);
/** retrieves the names of all XForms models in the document the control lives in
*/
void getAvailableDataTypeNames( ::std::vector< ::rtl::OUString >& /* [out] */ _rNames ) const SAL_THROW(());
/** retrieves a particular data type given by name
*/
::rtl::Reference< XSDDataType >
getDataTypeByName( const ::rtl::OUString& _rName ) const SAL_THROW(());
/** retrieves the DataType instance which the control model is currently validated against
If there is a binding set at our control model, which at the same time acts as validator,
and if this validator is bound to an XDataType, then this data type is retrieved here.
*/
::rtl::Reference< XSDDataType >
getValidatingDataType( ) const SAL_THROW(());
/** retrieves the name of the data type which the control model is currently validated against
@seealso getValidatingDataType
*/
::rtl::OUString
getValidatingDataTypeName( ) const SAL_THROW(());
/** binds the validator to a new data type
To be called with an active binding only.
*/
void setValidatingDataTypeByName( const ::rtl::OUString& _rName ) const SAL_THROW(());
/** removes the data type given by name from the data type repository
*/
bool removeDataTypeFromRepository( const ::rtl::OUString& _rName ) const SAL_THROW(());
/** creates a new data type, which is a clone of an existing data type
*/
bool cloneDataType( const ::rtl::Reference< XSDDataType >& _pDataType, const ::rtl::OUString& _rNewName ) const SAL_THROW(());
/** retrieves the name of the basic data type which has the given class
*/
::rtl::OUString
getBasicTypeNameForClass( sal_Int16 _eClass ) const SAL_THROW(());
/** copy a data type from one model to another
If a data type with the given name already exists in the target model, then nothing
happens. In particular, the facets of the data type are not copied.
*/
void copyDataType( const ::rtl::OUString& _rFromModel, const ::rtl::OUString& _rToModel,
const ::rtl::OUString& _rDataTypeName ) const SAL_THROW(());
/** finds (and sets) a default format for the formatted field we're inspecting,
according to the current data type the control value is evaluated against
*/
void findDefaultFormatForIntrospectee() SAL_THROW(());
private:
/** retrieves the data type repository associated with the current model
*/
::com::sun::star::uno::Reference< ::com::sun::star::xforms::XDataTypeRepository >
getDataTypeRepository() const SAL_THROW((::com::sun::star::uno::Exception));
/** retrieves the data type repository associated with any model
*/
::com::sun::star::uno::Reference< ::com::sun::star::xforms::XDataTypeRepository >
getDataTypeRepository( const ::rtl::OUString& _rModelName ) const SAL_THROW((::com::sun::star::uno::Exception));
/** retrieves the data type object for the given name
*/
::com::sun::star::uno::Reference< ::com::sun::star::xsd::XDataType >
getDataType( const ::rtl::OUString& _rName ) const
SAL_THROW((::com::sun::star::uno::Exception));
/** retrieves the name of the basic data type which has the given class, in the given repository
*/
::rtl::OUString
getBasicTypeNameForClass(
sal_Int16 _nClass,
::com::sun::star::uno::Reference< ::com::sun::star::xforms::XDataTypeRepository > _rxRepository
) const SAL_THROW(());
};
//........................................................................
} // namespace pcr
//........................................................................
#endif // EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONHELPER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.380); FILE MERGED 2008/04/01 15:15:22 thb 1.5.380.3: #i85898# Stripping all external header guards 2008/04/01 12:29:56 thb 1.5.380.2: #i85898# Stripping all external header guards 2008/03/31 12:31:58 rt 1.5.380.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xsdvalidationhelper.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_XSDVALIDATIONHELPER_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONHELPER_HXX
#include "eformshelper.hxx"
#include "xsddatatypes.hxx"
/** === begin UNO includes === **/
#include <com/sun/star/xsd/XDataType.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
/** === end UNO includes === **/
#include <rtl/ref.hxx>
//........................................................................
namespace pcr
{
//........................................................................
class XSDDataType;
//====================================================================
//= XSDValidationHelper
//====================================================================
class XSDValidationHelper : public EFormsHelper
{
private:
bool m_bInspectingFormattedField;
public:
bool isInspectingFormattedField() const { return m_bInspectingFormattedField; }
public:
XSDValidationHelper(
::osl::Mutex& _rMutex,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxIntrospectee,
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument
);
/** retrieves the names of all XForms models in the document the control lives in
*/
void getAvailableDataTypeNames( ::std::vector< ::rtl::OUString >& /* [out] */ _rNames ) const SAL_THROW(());
/** retrieves a particular data type given by name
*/
::rtl::Reference< XSDDataType >
getDataTypeByName( const ::rtl::OUString& _rName ) const SAL_THROW(());
/** retrieves the DataType instance which the control model is currently validated against
If there is a binding set at our control model, which at the same time acts as validator,
and if this validator is bound to an XDataType, then this data type is retrieved here.
*/
::rtl::Reference< XSDDataType >
getValidatingDataType( ) const SAL_THROW(());
/** retrieves the name of the data type which the control model is currently validated against
@seealso getValidatingDataType
*/
::rtl::OUString
getValidatingDataTypeName( ) const SAL_THROW(());
/** binds the validator to a new data type
To be called with an active binding only.
*/
void setValidatingDataTypeByName( const ::rtl::OUString& _rName ) const SAL_THROW(());
/** removes the data type given by name from the data type repository
*/
bool removeDataTypeFromRepository( const ::rtl::OUString& _rName ) const SAL_THROW(());
/** creates a new data type, which is a clone of an existing data type
*/
bool cloneDataType( const ::rtl::Reference< XSDDataType >& _pDataType, const ::rtl::OUString& _rNewName ) const SAL_THROW(());
/** retrieves the name of the basic data type which has the given class
*/
::rtl::OUString
getBasicTypeNameForClass( sal_Int16 _eClass ) const SAL_THROW(());
/** copy a data type from one model to another
If a data type with the given name already exists in the target model, then nothing
happens. In particular, the facets of the data type are not copied.
*/
void copyDataType( const ::rtl::OUString& _rFromModel, const ::rtl::OUString& _rToModel,
const ::rtl::OUString& _rDataTypeName ) const SAL_THROW(());
/** finds (and sets) a default format for the formatted field we're inspecting,
according to the current data type the control value is evaluated against
*/
void findDefaultFormatForIntrospectee() SAL_THROW(());
private:
/** retrieves the data type repository associated with the current model
*/
::com::sun::star::uno::Reference< ::com::sun::star::xforms::XDataTypeRepository >
getDataTypeRepository() const SAL_THROW((::com::sun::star::uno::Exception));
/** retrieves the data type repository associated with any model
*/
::com::sun::star::uno::Reference< ::com::sun::star::xforms::XDataTypeRepository >
getDataTypeRepository( const ::rtl::OUString& _rModelName ) const SAL_THROW((::com::sun::star::uno::Exception));
/** retrieves the data type object for the given name
*/
::com::sun::star::uno::Reference< ::com::sun::star::xsd::XDataType >
getDataType( const ::rtl::OUString& _rName ) const
SAL_THROW((::com::sun::star::uno::Exception));
/** retrieves the name of the basic data type which has the given class, in the given repository
*/
::rtl::OUString
getBasicTypeNameForClass(
sal_Int16 _nClass,
::com::sun::star::uno::Reference< ::com::sun::star::xforms::XDataTypeRepository > _rxRepository
) const SAL_THROW(());
};
//........................................................................
} // namespace pcr
//........................................................................
#endif // EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONHELPER_HXX
<|endoftext|> |
<commit_before>#pragma once
#include <eosio/chain/transaction.hpp>
namespace eosio { namespace chain {
struct pending_cycle_state : cycle_trace {
set<scope_name> read_scopes;
map<scope_name,uint32_t> write_scope_to_shard;
/**
* @return the shard number this transation goes in or (-1) if it
* cannot go on any shard due to conflict
*/
uint32_t schedule( const transaction& trx ) {
uint32_t current_shard = -1;
for( const auto& ws : trx.write_scope ) {
if( read_scopes.find(ws) != read_scopes.end() )
return -1;
auto itr = write_scope_to_shard.find(ws);
if( itr != write_scope_to_shard.end() ) {
if( current_shard == -1 ) {
current_shard = itr->second;
continue;
}
if( current_shard != itr->second )
return -1; /// conflict detected
}
}
for( const auto& rs : trx.read_scope )
{
auto itr = write_scope_to_shard.find(rs);
if( itr != write_scope_to_shard.end() ) {
if( current_shard == -1 ) {
current_shard = itr->second;
continue;
}
if( current_shard != itr->second )
return -1; /// schedule conflict
current_shard = itr->second;
}
}
if( current_shard == -1 ) {
shards.resize( shards.size()+1 );
current_shard = shards.size() - 1;
for( auto ws : trx.write_scope )
{
shards.back().write_scopes.insert( ws );
write_scope_to_shard[ws] = current_shard;
}
for( auto rs : trx.read_scope )
read_scopes.insert(rs);
}
return current_shard;
} /// schedule
struct pending_shard {
set<scope_name> write_scopes;
};
vector<pending_shard> shards;
};
} } /// eosio::chain
<commit_msg>fixed bug that caused scopes not to be recorded properly during scheduling<commit_after>#pragma once
#include <eosio/chain/transaction.hpp>
namespace eosio { namespace chain {
struct pending_cycle_state : cycle_trace {
set<scope_name> read_scopes;
map<scope_name,uint32_t> write_scope_to_shard;
/**
* @return the shard number this transation goes in or (-1) if it
* cannot go on any shard due to conflict
*/
uint32_t schedule( const transaction& trx ) {
uint32_t current_shard = -1;
for( const auto& ws : trx.write_scope ) {
if( read_scopes.find(ws) != read_scopes.end() )
return -1;
auto itr = write_scope_to_shard.find(ws);
if( itr != write_scope_to_shard.end() ) {
if( current_shard == -1 ) {
current_shard = itr->second;
continue;
}
if( current_shard != itr->second )
return -1; /// conflict detected
}
}
for( const auto& rs : trx.read_scope )
{
auto itr = write_scope_to_shard.find(rs);
if( itr != write_scope_to_shard.end() ) {
if( current_shard == -1 ) {
current_shard = itr->second;
continue;
}
if( current_shard != itr->second )
return -1; /// schedule conflict
current_shard = itr->second;
}
}
if( current_shard == -1 ) {
shards.resize( shards.size()+1 );
current_shard = shards.size() - 1;
}
for( auto ws : trx.write_scope )
{
shards.back().write_scopes.insert( ws );
write_scope_to_shard[ws] = current_shard;
}
for( auto rs : trx.read_scope )
read_scopes.insert(rs);
return current_shard;
} /// schedule
struct pending_shard {
set<scope_name> write_scopes;
};
vector<pending_shard> shards;
};
} } /// eosio::chain
<|endoftext|> |
<commit_before>/* $Id: middlewareSubscriptionTests.cpp,v 1.1.2.5 2012/12/17 15:46:04 matthewmulhern Exp $
*
* OpenMAMA: The open middleware agnostic messaging API
* Copyright (C) 2011 NYSE Technologies, Inc.
*
* 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 "mama/mama.h"
#include "MainUnitTestC.h"
#include <iostream>
#include "bridge.h"
#include "mama/types.h"
using std::cout;
using std::endl;
static void onCreate (mamaSubscription subscription, void* closure);
static void onError(mamaSubscription subscription,
mama_status status,
void* platformError,
const char* subject,
void* closure);
static void onQuality(mamaSubscription subsc,
mamaQuality quality,
const char* symbol,
short cause,
const void* platformInfo,
void* closure);
static void onMsg(mamaSubscription subscription,
mamaMsg msg,
void* closure,
void* itemClosure);
static void onGap(mamaSubscription subsc, void* closure);
static void onRecapRequest(mamaSubscription subsc, void* closure);
static void onDestroy(mamaSubscription subsc, void* closure);
class MiddlewareSubscriptionTests : public ::testing::Test
{
protected:
MiddlewareSubscriptionTests(void);
virtual ~MiddlewareSubscriptionTests(void);
virtual void SetUp(void);
virtual void TearDown(void);
mamaBridge mBridge;
mamaTransport tport;
const char* tportName;
subscriptionBridge subscriber;
mamaSource source;
const char* sourceName;
const char* symbol;
mamaQueue queue;
void* closure;
mamaSubscription parent;
mamaMsgCallbacks callbacks;
};
MiddlewareSubscriptionTests::MiddlewareSubscriptionTests(void)
: tport (NULL),
tportName ("test_tport"),
source (NULL),
sourceName ("src"),
symbol ("SYM"),
queue (NULL),
closure (NULL)
{
mama_loadBridge (&mBridge, getMiddleware());
mamaQueue_create(&queue, mBridge);
}
MiddlewareSubscriptionTests::~MiddlewareSubscriptionTests(void)
{
mamaQueue_destroy (queue);
}
void MiddlewareSubscriptionTests::SetUp(void)
{
mamaTransport_allocate (&tport);
mamaTransport_create (tport, tportName, mBridge);
mamaSource_create(&source);
mamaSource_setId(source, "SRC");
mamaSource_setTransport(source, tport);
mamaSource_setSymbolNamespace(source, "NASDAQ");
callbacks.onCreate = onCreate;
callbacks.onError = onError;
callbacks.onQuality = onQuality;
callbacks.onMsg = onMsg;
callbacks.onGap = onGap;
callbacks.onRecapRequest = onRecapRequest;
callbacks.onDestroy = onDestroy;
}
void MiddlewareSubscriptionTests::TearDown(void)
{
mamaTransport_destroy (tport);
}
static void onCreate (mamaSubscription subscription,
void* closure)
{
}
static void onError(mamaSubscription subscription,
mama_status status,
void* platformError,
const char* subject,
void* closure)
{
}
static void onQuality(mamaSubscription subsc,
mamaQuality quality,
const char* symbol,
short cause,
const void* platformInfo,
void* closure)
{
}
static void onMsg(mamaSubscription subscription,
mamaMsg msg,
void* closure,
void* itemClosure)
{
}
static void onGap(mamaSubscription subsc, void* closure)
{
}
static void onRecapRequest(mamaSubscription subsc, void* closure)
{
}
static void onDestroy(mamaSubscription subsc, void* closure)
{
}
/*===================================================================
= mamaSubscription bridge functions =
====================================================================*/
/* TODO:
* Discuss the validity of these tests - ultimately we double create
* subscriptions, which I would assume isn't supposed to be expected behaviour.
*/
TEST_F (MiddlewareSubscriptionTests, DISABLED_createDestroy)
/* cores*/
{
mamaSubscription_allocate(&parent);
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_destroy(parent));
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_deallocate(parent));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidResult)
{
ASSERT_EQ(MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionCreate(NULL, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidTport)
{
ASSERT_EQ(MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
NULL, queue, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidSourceName)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, NULL, symbol,
tport, queue, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidSymbol)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, NULL,
tport, queue, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidQueue)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, NULL, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidParent)
{
ASSERT_EQ(MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
NULL, closure));
}
/* TEST COMMENTED OUT BECAUSE mamaMsgCallbacks CAN'T BE CAST AS NULL!
TEST_F (MiddlewareSubscriptionTests, createInvalidCallbacks)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, NULL,
parent, closure));
}
*/
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidResult)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(NULL, sourceName, symbol,
tport, queue, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidSource)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, NULL, symbol,
tport, queue, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidSymbol)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, NULL,
tport, queue, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidTport)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,
NULL, queue, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidQueue)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,
tport, NULL, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidParent)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,
tport, queue, callbacks,
NULL, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
/* COMMENTED OUT BECAUSE mamaMsg Callbacks CAN'T BE CAST AS NULL
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidCallbacks)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,
tport, queue, NULL,
parent, closure));
}
*/
TEST_F (MiddlewareSubscriptionTests, mute)
{
mamaSubscription_allocate(&parent);
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
ASSERT_EQ (MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionMute(subscriber));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
}
TEST_F (MiddlewareSubscriptionTests, muteInvalid)
{
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionMute(NULL));
}
TEST_F (MiddlewareSubscriptionTests, destroyInvalid)
{
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionDestroy(NULL));
}
TEST_F (MiddlewareSubscriptionTests, isValid)
{
int res = NULL;
mamaSubscription_allocate(&parent);
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
res = mBridge->bridgeMamaSubscriptionIsValid(subscriber);
ASSERT_TRUE(res != NULL);
}
TEST_F (MiddlewareSubscriptionTests, isValidInvalid)
{
int res = NULL;
res = mBridge->bridgeMamaSubscriptionIsValid(NULL);
ASSERT_TRUE(res == 0);
}
TEST_F (MiddlewareSubscriptionTests, hasWildcards)
{
int res = NULL;
res = mBridge->bridgeMamaSubscriptionHasWildcards(NULL);
ASSERT_TRUE(res == 0);
}
TEST_F (MiddlewareSubscriptionTests, getPlatformError)
{
void* error = NOT_NULL;
mama_status status = MAMA_STATUS_OK;
mamaSubscription_allocate(&parent);
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ (MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
status = mBridge->bridgeMamaSubscriptionGetPlatformError(subscriber, &error);
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, getPlatformErrorInvalidError)
{
mama_status status = mBridge->bridgeMamaSubscriptionGetPlatformError(subscriber,
NULL);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
status);
}
TEST_F (MiddlewareSubscriptionTests, getPlatformErrorInvalidSubBridge)
{
void* error = NOT_NULL;
mama_status status = mBridge->bridgeMamaSubscriptionGetPlatformError(NULL,
&error);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
status);
}
TEST_F (MiddlewareSubscriptionTests, isTportDisconnected)
{
int res = NULL;
mamaSubscription_allocate(&parent);
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
res=mBridge->bridgeMamaSubscriptionIsTportDisconnected(subscriber);
ASSERT_TRUE(res != NULL);
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
}
TEST_F (MiddlewareSubscriptionTests, isTportDisconnectedInvalid)
{
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionIsTportDisconnected(NULL));
}
TEST_F (MiddlewareSubscriptionTests, setTopicClosure)
{
void* newClosure = NOT_NULL;
mama_status status = MAMA_STATUS_OK;
mamaSubscription_allocate(&parent);
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
status = mBridge->bridgeMamaSubscriptionSetTopicClosure(subscriber,newClosure);
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ (MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, setTopicClosureInvalidSubBridge)
{
void* closure = NOT_NULL;
mama_status status = mBridge->bridgeMamaSubscriptionSetTopicClosure(NULL,
closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
status);
}
TEST_F (MiddlewareSubscriptionTests, muteCurrentTopic)
{
mamaSubscription_allocate(&parent);
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
ASSERT_EQ (MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionMuteCurrentTopic(subscriber));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
}
TEST_F (MiddlewareSubscriptionTests, muteCurrentTopicInvalid)
{
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionMuteCurrentTopic(NULL));
}
<commit_msg>Subscription Allocate is not being called prior to the create so the qpid bridge checks for null on the MamaSubscription and fails.<commit_after>/* $Id: middlewareSubscriptionTests.cpp,v 1.1.2.5 2012/12/17 15:46:04 matthewmulhern Exp $
*
* OpenMAMA: The open middleware agnostic messaging API
* Copyright (C) 2011 NYSE Technologies, Inc.
*
* 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 "mama/mama.h"
#include "MainUnitTestC.h"
#include <iostream>
#include "bridge.h"
#include "mama/types.h"
using std::cout;
using std::endl;
static void onCreate (mamaSubscription subscription, void* closure);
static void onError(mamaSubscription subscription,
mama_status status,
void* platformError,
const char* subject,
void* closure);
static void onQuality(mamaSubscription subsc,
mamaQuality quality,
const char* symbol,
short cause,
const void* platformInfo,
void* closure);
static void onMsg(mamaSubscription subscription,
mamaMsg msg,
void* closure,
void* itemClosure);
static void onGap(mamaSubscription subsc, void* closure);
static void onRecapRequest(mamaSubscription subsc, void* closure);
static void onDestroy(mamaSubscription subsc, void* closure);
class MiddlewareSubscriptionTests : public ::testing::Test
{
protected:
MiddlewareSubscriptionTests(void);
virtual ~MiddlewareSubscriptionTests(void);
virtual void SetUp(void);
virtual void TearDown(void);
mamaBridge mBridge;
mamaTransport tport;
const char* tportName;
subscriptionBridge subscriber;
mamaSource source;
const char* sourceName;
const char* symbol;
mamaQueue queue;
void* closure;
mamaSubscription parent;
mamaMsgCallbacks callbacks;
};
MiddlewareSubscriptionTests::MiddlewareSubscriptionTests(void)
: tport (NULL),
tportName ("test_tport"),
source (NULL),
sourceName ("src"),
symbol ("SYM"),
queue (NULL),
closure (NULL)
{
mama_loadBridge (&mBridge, getMiddleware());
mamaQueue_create(&queue, mBridge);
}
MiddlewareSubscriptionTests::~MiddlewareSubscriptionTests(void)
{
mamaQueue_destroy (queue);
}
void MiddlewareSubscriptionTests::SetUp(void)
{
mamaTransport_allocate (&tport);
mamaTransport_create (tport, tportName, mBridge);
mamaSource_create(&source);
mamaSource_setId(source, "SRC");
mamaSource_setTransport(source, tport);
mamaSource_setSymbolNamespace(source, "NASDAQ");
mamaSubscription_allocate(&parent);
callbacks.onCreate = onCreate;
callbacks.onError = onError;
callbacks.onQuality = onQuality;
callbacks.onMsg = onMsg;
callbacks.onGap = onGap;
callbacks.onRecapRequest = onRecapRequest;
callbacks.onDestroy = onDestroy;
}
void MiddlewareSubscriptionTests::TearDown(void)
{
mamaTransport_destroy (tport);
mamaSubscription_deallocate(parent);
}
static void onCreate (mamaSubscription subscription,
void* closure)
{
}
static void onError(mamaSubscription subscription,
mama_status status,
void* platformError,
const char* subject,
void* closure)
{
}
static void onQuality(mamaSubscription subsc,
mamaQuality quality,
const char* symbol,
short cause,
const void* platformInfo,
void* closure)
{
}
static void onMsg(mamaSubscription subscription,
mamaMsg msg,
void* closure,
void* itemClosure)
{
}
static void onGap(mamaSubscription subsc, void* closure)
{
}
static void onRecapRequest(mamaSubscription subsc, void* closure)
{
}
static void onDestroy(mamaSubscription subsc, void* closure)
{
}
/*===================================================================
= mamaSubscription bridge functions =
====================================================================*/
/* TODO:
* Discuss the validity of these tests - ultimately we double create
* subscriptions, which I would assume isn't supposed to be expected behaviour.
*/
TEST_F (MiddlewareSubscriptionTests, DISABLED_createDestroy)
/* cores*/
{
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_destroy(parent));
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_deallocate(parent));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidResult)
{
ASSERT_EQ(MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionCreate(NULL, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidTport)
{
ASSERT_EQ(MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
NULL, queue, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidSourceName)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, NULL, symbol,
tport, queue, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidSymbol)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, NULL,
tport, queue, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidQueue)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, NULL, callbacks,
parent, closure));
}
TEST_F (MiddlewareSubscriptionTests, createInvalidParent)
{
ASSERT_EQ(MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
NULL, closure));
}
/* TEST COMMENTED OUT BECAUSE mamaMsgCallbacks CAN'T BE CAST AS NULL!
TEST_F (MiddlewareSubscriptionTests, createInvalidCallbacks)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, NULL,
parent, closure));
}
*/
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidResult)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(NULL, sourceName, symbol,
tport, queue, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidSource)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, NULL, symbol,
tport, queue, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidSymbol)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, NULL,
tport, queue, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidTport)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,
NULL, queue, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidQueue)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,
tport, NULL, callbacks,
parent, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidParent)
{
mama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,
tport, queue, callbacks,
NULL, closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
/* COMMENTED OUT BECAUSE mamaMsg Callbacks CAN'T BE CAST AS NULL
TEST_F (MiddlewareSubscriptionTests, createWildCardInvalidCallbacks)
{
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,
tport, queue, NULL,
parent, closure));
}
*/
TEST_F (MiddlewareSubscriptionTests, mute)
{
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
ASSERT_EQ (MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionMute(subscriber));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
}
TEST_F (MiddlewareSubscriptionTests, muteInvalid)
{
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionMute(NULL));
}
TEST_F (MiddlewareSubscriptionTests, destroyInvalid)
{
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionDestroy(NULL));
}
TEST_F (MiddlewareSubscriptionTests, isValid)
{
int res = NULL;
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
res = mBridge->bridgeMamaSubscriptionIsValid(subscriber);
ASSERT_TRUE(res != NULL);
}
TEST_F (MiddlewareSubscriptionTests, isValidInvalid)
{
int res = NULL;
res = mBridge->bridgeMamaSubscriptionIsValid(NULL);
ASSERT_TRUE(res == 0);
}
TEST_F (MiddlewareSubscriptionTests, hasWildcards)
{
int res = NULL;
res = mBridge->bridgeMamaSubscriptionHasWildcards(NULL);
ASSERT_TRUE(res == 0);
}
TEST_F (MiddlewareSubscriptionTests, getPlatformError)
{
void* error = NOT_NULL;
mama_status status = MAMA_STATUS_OK;
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ (MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
status = mBridge->bridgeMamaSubscriptionGetPlatformError(subscriber, &error);
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ(MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, getPlatformErrorInvalidError)
{
mama_status status = mBridge->bridgeMamaSubscriptionGetPlatformError(subscriber,
NULL);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
status);
}
TEST_F (MiddlewareSubscriptionTests, getPlatformErrorInvalidSubBridge)
{
void* error = NOT_NULL;
mama_status status = mBridge->bridgeMamaSubscriptionGetPlatformError(NULL,
&error);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
status);
}
TEST_F (MiddlewareSubscriptionTests, isTportDisconnected)
{
int res = NULL;
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
res=mBridge->bridgeMamaSubscriptionIsTportDisconnected(subscriber);
ASSERT_TRUE(res != NULL);
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
}
TEST_F (MiddlewareSubscriptionTests, isTportDisconnectedInvalid)
{
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionIsTportDisconnected(NULL));
}
TEST_F (MiddlewareSubscriptionTests, setTopicClosure)
{
void* newClosure = NOT_NULL;
mama_status status = MAMA_STATUS_OK;
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
status = mBridge->bridgeMamaSubscriptionSetTopicClosure(subscriber,newClosure);
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ (MAMA_STATUS_OK,
status);
}
TEST_F (MiddlewareSubscriptionTests, setTopicClosureInvalidSubBridge)
{
void* closure = NOT_NULL;
mama_status status = mBridge->bridgeMamaSubscriptionSetTopicClosure(NULL,
closure);
CHECK_NON_IMPLEMENTED_OPTIONAL(status);
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
status);
}
TEST_F (MiddlewareSubscriptionTests, muteCurrentTopic)
{
ASSERT_EQ(MAMA_STATUS_OK,
mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,
tport, queue, callbacks,
parent, closure));
ASSERT_EQ (MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionMuteCurrentTopic(subscriber));
ASSERT_EQ(MAMA_STATUS_OK,
mBridge->bridgeMamaSubscriptionDestroy(subscriber));
}
TEST_F (MiddlewareSubscriptionTests, muteCurrentTopicInvalid)
{
ASSERT_EQ (MAMA_STATUS_NULL_ARG,
mBridge->bridgeMamaSubscriptionMuteCurrentTopic(NULL));
}
<|endoftext|> |
<commit_before>#include "source/extensions/filters/http/cache/cache_headers_utils.h"
#include <array>
#include <chrono>
#include <string>
#include "envoy/http/header_map.h"
#include "source/common/http/header_map_impl.h"
#include "source/common/http/header_utility.h"
#include "source/extensions/filters/http/cache/cache_custom_headers.h"
#include "absl/algorithm/container.h"
#include "absl/container/btree_set.h"
#include "absl/strings/ascii.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace Cache {
// Utility functions used in RequestCacheControl & ResponseCacheControl.
namespace {
// A directive with an invalid duration is ignored, the RFC does not specify a behavior:
// https://httpwg.org/specs/rfc7234.html#delta-seconds
OptionalDuration parseDuration(absl::string_view s) {
OptionalDuration duration;
// Strip quotation marks if any.
if (s.size() > 1 && s.front() == '"' && s.back() == '"') {
s = s.substr(1, s.size() - 2);
}
long num;
if (absl::SimpleAtoi(s, &num) && num >= 0) {
// s is a valid string of digits representing a positive number.
duration = Seconds(num);
}
return duration;
}
inline std::pair<absl::string_view, absl::string_view>
separateDirectiveAndArgument(absl::string_view full_directive) {
return absl::StrSplit(absl::StripAsciiWhitespace(full_directive), absl::MaxSplits('=', 1));
}
} // namespace
// The grammar for This Cache-Control header value should be:
// Cache-Control = 1#cache-directive
// cache-directive = token [ "=" ( token / quoted-string ) ]
// token = 1*tchar
// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+"
// / "-" / "." / "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
// quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
// qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text
// obs-text = %x80-FF
// quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
// VCHAR = %x21-7E ; visible (printing) characters
// Multiple directives are comma separated according to:
// https://httpwg.org/specs/rfc7234.html#collected.abnf
RequestCacheControl::RequestCacheControl(absl::string_view cache_control_header) {
const std::vector<absl::string_view> directives = absl::StrSplit(cache_control_header, ',');
for (auto full_directive : directives) {
absl::string_view directive, argument;
std::tie(directive, argument) = separateDirectiveAndArgument(full_directive);
if (directive == "no-cache") {
must_validate_ = true;
} else if (directive == "no-store") {
no_store_ = true;
} else if (directive == "no-transform") {
no_transform_ = true;
} else if (directive == "only-if-cached") {
only_if_cached_ = true;
} else if (directive == "max-age") {
max_age_ = parseDuration(argument);
} else if (directive == "min-fresh") {
min_fresh_ = parseDuration(argument);
} else if (directive == "max-stale") {
max_stale_ = argument.empty() ? SystemTime::duration::max() : parseDuration(argument);
}
}
}
ResponseCacheControl::ResponseCacheControl(absl::string_view cache_control_header) {
const std::vector<absl::string_view> directives = absl::StrSplit(cache_control_header, ',');
for (auto full_directive : directives) {
absl::string_view directive, argument;
std::tie(directive, argument) = separateDirectiveAndArgument(full_directive);
if (directive == "no-cache") {
// If no-cache directive has arguments they are ignored - not handled.
must_validate_ = true;
} else if (directive == "must-revalidate" || directive == "proxy-revalidate") {
no_stale_ = true;
} else if (directive == "no-store" || directive == "private") {
// If private directive has arguments they are ignored - not handled.
no_store_ = true;
} else if (directive == "no-transform") {
no_transform_ = true;
} else if (directive == "public") {
is_public_ = true;
} else if (directive == "s-maxage") {
max_age_ = parseDuration(argument);
} else if (!max_age_.has_value() && directive == "max-age") {
max_age_ = parseDuration(argument);
}
}
}
bool operator==(const RequestCacheControl& lhs, const RequestCacheControl& rhs) {
return (lhs.must_validate_ == rhs.must_validate_) && (lhs.no_store_ == rhs.no_store_) &&
(lhs.no_transform_ == rhs.no_transform_) && (lhs.only_if_cached_ == rhs.only_if_cached_) &&
(lhs.max_age_ == rhs.max_age_) && (lhs.min_fresh_ == rhs.min_fresh_) &&
(lhs.max_stale_ == rhs.max_stale_);
}
bool operator==(const ResponseCacheControl& lhs, const ResponseCacheControl& rhs) {
return (lhs.must_validate_ == rhs.must_validate_) && (lhs.no_store_ == rhs.no_store_) &&
(lhs.no_transform_ == rhs.no_transform_) && (lhs.no_stale_ == rhs.no_stale_) &&
(lhs.is_public_ == rhs.is_public_) && (lhs.max_age_ == rhs.max_age_);
}
SystemTime CacheHeadersUtils::httpTime(const Http::HeaderEntry* header_entry) {
if (!header_entry) {
return {};
}
absl::Time time;
const std::string input(header_entry->value().getStringView());
// Acceptable Date/Time Formats per:
// https://tools.ietf.org/html/rfc7231#section-7.1.1.1
//
// Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate.
// Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format.
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format.
static const char* rfc7231_date_formats[] = {"%a, %d %b %Y %H:%M:%S GMT",
"%A, %d-%b-%y %H:%M:%S GMT", "%a %b %e %H:%M:%S %Y"};
for (const std::string& format : rfc7231_date_formats) {
if (absl::ParseTime(format, input, &time, nullptr)) {
return ToChronoTime(time);
}
}
return {};
}
Seconds CacheHeadersUtils::calculateAge(const Http::ResponseHeaderMap& response_headers,
const SystemTime response_time, const SystemTime now) {
// Age headers calculations follow: https://httpwg.org/specs/rfc7234.html#age.calculations
const SystemTime date_value = CacheHeadersUtils::httpTime(response_headers.Date());
long age_value;
const absl::string_view age_header = response_headers.getInlineValue(CacheCustomHeaders::age());
if (!absl::SimpleAtoi(age_header, &age_value)) {
age_value = 0;
}
const SystemTime::duration apparent_age =
std::max(SystemTime::duration(0), response_time - date_value);
// Assumption: response_delay is negligible -> corrected_age_value = age_value.
const SystemTime::duration corrected_age_value = Seconds(age_value);
const SystemTime::duration corrected_initial_age = std::max(apparent_age, corrected_age_value);
// Calculate current_age:
const SystemTime::duration resident_time = now - response_time;
const SystemTime::duration current_age = corrected_initial_age + resident_time;
return std::chrono::duration_cast<Seconds>(current_age);
}
absl::optional<uint64_t> CacheHeadersUtils::readAndRemoveLeadingDigits(absl::string_view& str) {
uint64_t val = 0;
uint32_t bytes_consumed = 0;
for (const char cur : str) {
if (!absl::ascii_isdigit(cur)) {
break;
}
uint64_t new_val = (val * 10) + (cur - '0');
if (new_val / 8 < val) {
// Overflow occurred
return absl::nullopt;
}
val = new_val;
++bytes_consumed;
}
if (bytes_consumed) {
// Consume some digits
str.remove_prefix(bytes_consumed);
return val;
}
return absl::nullopt;
}
void CacheHeadersUtils::getAllMatchingHeaderNames(
const Http::HeaderMap& headers, const std::vector<Matchers::StringMatcherPtr>& ruleset,
absl::flat_hash_set<absl::string_view>& out) {
headers.iterate([&ruleset, &out](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
absl::string_view header_name = header.key().getStringView();
for (const auto& rule : ruleset) {
if (rule->match(header_name)) {
out.emplace(header_name);
break;
}
}
return Http::HeaderMap::Iterate::Continue;
});
}
std::vector<absl::string_view>
CacheHeadersUtils::parseCommaDelimitedHeader(const Http::HeaderMap::GetResult& entry) {
std::vector<absl::string_view> values;
for (size_t i = 0; i < entry.size(); ++i) {
for (absl::string_view s : absl::StrSplit(entry[i]->value().getStringView(), ',')) {
if (s.empty()) {
continue;
}
values.emplace_back(absl::StripAsciiWhitespace(s));
}
}
return values;
}
VaryAllowList::VaryAllowList(
const Protobuf::RepeatedPtrField<envoy::type::matcher::v3::StringMatcher>& allow_list) {
for (const auto& rule : allow_list) {
allow_list_.emplace_back(
std::make_unique<Matchers::StringMatcherImpl<envoy::type::matcher::v3::StringMatcher>>(
rule));
}
}
bool VaryAllowList::allowsValue(const absl::string_view vary_value) const {
for (const auto& rule : allow_list_) {
if (rule->match(vary_value)) {
return true;
}
}
return false;
}
bool VaryAllowList::allowsHeaders(const Http::ResponseHeaderMap& headers) const {
if (!VaryHeaderUtils::hasVary(headers)) {
return true;
}
std::vector<absl::string_view> varied_headers =
CacheHeadersUtils::parseCommaDelimitedHeader(headers.get(Http::CustomHeaders::get().Vary));
for (absl::string_view& header : varied_headers) {
bool valid = false;
// "Vary: *" should never be cached per:
// https://tools.ietf.org/html/rfc7231#section-7.1.4
if (header == "*") {
return false;
}
if (allowsValue(header)) {
valid = true;
}
if (!valid) {
return false;
}
}
return true;
}
bool VaryHeaderUtils::hasVary(const Http::ResponseHeaderMap& headers) {
// TODO(mattklein123): Support multiple vary headers and/or just make the vary header inline.
const auto vary_header = headers.get(Http::CustomHeaders::get().Vary);
return !vary_header.empty() && !vary_header[0]->value().empty();
}
absl::btree_set<absl::string_view>
VaryHeaderUtils::getVaryValues(const Http::ResponseHeaderMap& headers) {
Http::HeaderMap::GetResult vary_headers = headers.get(Http::CustomHeaders::get().Vary);
if (vary_headers.empty()) {
return {};
}
std::vector<absl::string_view> values =
CacheHeadersUtils::parseCommaDelimitedHeader(vary_headers);
return absl::btree_set<absl::string_view>(values.begin(), values.end());
}
namespace {
// The separator characters are used to create the vary-key, and must be characters that are
// invalid to be inside values and header names. The chosen characters are invalid per:
// https://tools.ietf.org/html/rfc2616#section-4.2.
// Used to separate the values of different headers.
constexpr absl::string_view headerSeparator = "\n";
// Used to separate multiple values of a same header.
constexpr absl::string_view inValueSeparator = "\r";
}; // namespace
absl::optional<std::string>
VaryHeaderUtils::createVaryIdentifier(const VaryAllowList& allow_list,
const absl::btree_set<absl::string_view>& vary_header_values,
const Http::RequestHeaderMap& request_headers) {
std::string vary_identifier = "vary-id\n";
if (vary_header_values.empty()) {
return vary_identifier;
}
for (const absl::string_view& value : vary_header_values) {
if (value.empty()) {
// Empty headers are ignored.
continue;
}
if (!allow_list.allowsValue(value)) {
// The backend tried to vary on a header that we don't allow, so return
// absl::nullopt to indicate we are unable to cache this request. This
// also may occur if the allow list has changed since an item was cached,
// rendering the cached vary value invalid.
return absl::nullopt;
}
// TODO(cbdm): Can add some bucketing logic here based on header. For
// example, we could normalize the values for accept-language by making all
// of {en-CA, en-GB, en-US} into "en". This way we would not need to store
// multiple versions of the same payload, and any of those values would find
// the payload in the requested language. Another example would be to bucket
// UserAgent values into android/ios/desktop;
// UserAgent::initializeFromHeaders tries to do that normalization and could
// be used as an inspiration for some bucketing configuration. The config
// should enable and control the bucketing wanted.
const auto all_values = Http::HeaderUtility::getAllOfHeaderAsString(
request_headers, Http::LowerCaseString(std::string(value)), inValueSeparator);
absl::StrAppend(&vary_identifier, value, inValueSeparator,
all_values.result().has_value() ? all_values.result().value() : "",
headerSeparator);
}
return vary_identifier;
}
} // namespace Cache
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
<commit_msg>cache: clean up string-array declaration to avoid temp std::string conversion during lookup, and eliminate warning (#19366)<commit_after>#include "source/extensions/filters/http/cache/cache_headers_utils.h"
#include <array>
#include <chrono>
#include <string>
#include "envoy/http/header_map.h"
#include "source/common/http/header_map_impl.h"
#include "source/common/http/header_utility.h"
#include "source/extensions/filters/http/cache/cache_custom_headers.h"
#include "absl/algorithm/container.h"
#include "absl/container/btree_set.h"
#include "absl/strings/ascii.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace Cache {
// Utility functions used in RequestCacheControl & ResponseCacheControl.
namespace {
// A directive with an invalid duration is ignored, the RFC does not specify a behavior:
// https://httpwg.org/specs/rfc7234.html#delta-seconds
OptionalDuration parseDuration(absl::string_view s) {
OptionalDuration duration;
// Strip quotation marks if any.
if (s.size() > 1 && s.front() == '"' && s.back() == '"') {
s = s.substr(1, s.size() - 2);
}
long num;
if (absl::SimpleAtoi(s, &num) && num >= 0) {
// s is a valid string of digits representing a positive number.
duration = Seconds(num);
}
return duration;
}
inline std::pair<absl::string_view, absl::string_view>
separateDirectiveAndArgument(absl::string_view full_directive) {
return absl::StrSplit(absl::StripAsciiWhitespace(full_directive), absl::MaxSplits('=', 1));
}
} // namespace
// The grammar for This Cache-Control header value should be:
// Cache-Control = 1#cache-directive
// cache-directive = token [ "=" ( token / quoted-string ) ]
// token = 1*tchar
// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+"
// / "-" / "." / "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
// quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
// qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text
// obs-text = %x80-FF
// quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
// VCHAR = %x21-7E ; visible (printing) characters
// Multiple directives are comma separated according to:
// https://httpwg.org/specs/rfc7234.html#collected.abnf
RequestCacheControl::RequestCacheControl(absl::string_view cache_control_header) {
const std::vector<absl::string_view> directives = absl::StrSplit(cache_control_header, ',');
for (auto full_directive : directives) {
absl::string_view directive, argument;
std::tie(directive, argument) = separateDirectiveAndArgument(full_directive);
if (directive == "no-cache") {
must_validate_ = true;
} else if (directive == "no-store") {
no_store_ = true;
} else if (directive == "no-transform") {
no_transform_ = true;
} else if (directive == "only-if-cached") {
only_if_cached_ = true;
} else if (directive == "max-age") {
max_age_ = parseDuration(argument);
} else if (directive == "min-fresh") {
min_fresh_ = parseDuration(argument);
} else if (directive == "max-stale") {
max_stale_ = argument.empty() ? SystemTime::duration::max() : parseDuration(argument);
}
}
}
ResponseCacheControl::ResponseCacheControl(absl::string_view cache_control_header) {
const std::vector<absl::string_view> directives = absl::StrSplit(cache_control_header, ',');
for (auto full_directive : directives) {
absl::string_view directive, argument;
std::tie(directive, argument) = separateDirectiveAndArgument(full_directive);
if (directive == "no-cache") {
// If no-cache directive has arguments they are ignored - not handled.
must_validate_ = true;
} else if (directive == "must-revalidate" || directive == "proxy-revalidate") {
no_stale_ = true;
} else if (directive == "no-store" || directive == "private") {
// If private directive has arguments they are ignored - not handled.
no_store_ = true;
} else if (directive == "no-transform") {
no_transform_ = true;
} else if (directive == "public") {
is_public_ = true;
} else if (directive == "s-maxage") {
max_age_ = parseDuration(argument);
} else if (!max_age_.has_value() && directive == "max-age") {
max_age_ = parseDuration(argument);
}
}
}
bool operator==(const RequestCacheControl& lhs, const RequestCacheControl& rhs) {
return (lhs.must_validate_ == rhs.must_validate_) && (lhs.no_store_ == rhs.no_store_) &&
(lhs.no_transform_ == rhs.no_transform_) && (lhs.only_if_cached_ == rhs.only_if_cached_) &&
(lhs.max_age_ == rhs.max_age_) && (lhs.min_fresh_ == rhs.min_fresh_) &&
(lhs.max_stale_ == rhs.max_stale_);
}
bool operator==(const ResponseCacheControl& lhs, const ResponseCacheControl& rhs) {
return (lhs.must_validate_ == rhs.must_validate_) && (lhs.no_store_ == rhs.no_store_) &&
(lhs.no_transform_ == rhs.no_transform_) && (lhs.no_stale_ == rhs.no_stale_) &&
(lhs.is_public_ == rhs.is_public_) && (lhs.max_age_ == rhs.max_age_);
}
SystemTime CacheHeadersUtils::httpTime(const Http::HeaderEntry* header_entry) {
if (!header_entry) {
return {};
}
absl::Time time;
const absl::string_view input(header_entry->value().getStringView());
// Acceptable Date/Time Formats per:
// https://tools.ietf.org/html/rfc7231#section-7.1.1.1
//
// Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate.
// Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format.
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format.
static constexpr absl::string_view rfc7231_date_formats[] = {
"%a, %d %b %Y %H:%M:%S GMT", "%A, %d-%b-%y %H:%M:%S GMT", "%a %b %e %H:%M:%S %Y"};
for (absl::string_view format : rfc7231_date_formats) {
if (absl::ParseTime(format, input, &time, nullptr)) {
return ToChronoTime(time);
}
}
return {};
}
Seconds CacheHeadersUtils::calculateAge(const Http::ResponseHeaderMap& response_headers,
const SystemTime response_time, const SystemTime now) {
// Age headers calculations follow: https://httpwg.org/specs/rfc7234.html#age.calculations
const SystemTime date_value = CacheHeadersUtils::httpTime(response_headers.Date());
long age_value;
const absl::string_view age_header = response_headers.getInlineValue(CacheCustomHeaders::age());
if (!absl::SimpleAtoi(age_header, &age_value)) {
age_value = 0;
}
const SystemTime::duration apparent_age =
std::max(SystemTime::duration(0), response_time - date_value);
// Assumption: response_delay is negligible -> corrected_age_value = age_value.
const SystemTime::duration corrected_age_value = Seconds(age_value);
const SystemTime::duration corrected_initial_age = std::max(apparent_age, corrected_age_value);
// Calculate current_age:
const SystemTime::duration resident_time = now - response_time;
const SystemTime::duration current_age = corrected_initial_age + resident_time;
return std::chrono::duration_cast<Seconds>(current_age);
}
absl::optional<uint64_t> CacheHeadersUtils::readAndRemoveLeadingDigits(absl::string_view& str) {
uint64_t val = 0;
uint32_t bytes_consumed = 0;
for (const char cur : str) {
if (!absl::ascii_isdigit(cur)) {
break;
}
uint64_t new_val = (val * 10) + (cur - '0');
if (new_val / 8 < val) {
// Overflow occurred
return absl::nullopt;
}
val = new_val;
++bytes_consumed;
}
if (bytes_consumed) {
// Consume some digits
str.remove_prefix(bytes_consumed);
return val;
}
return absl::nullopt;
}
void CacheHeadersUtils::getAllMatchingHeaderNames(
const Http::HeaderMap& headers, const std::vector<Matchers::StringMatcherPtr>& ruleset,
absl::flat_hash_set<absl::string_view>& out) {
headers.iterate([&ruleset, &out](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
absl::string_view header_name = header.key().getStringView();
for (const auto& rule : ruleset) {
if (rule->match(header_name)) {
out.emplace(header_name);
break;
}
}
return Http::HeaderMap::Iterate::Continue;
});
}
std::vector<absl::string_view>
CacheHeadersUtils::parseCommaDelimitedHeader(const Http::HeaderMap::GetResult& entry) {
std::vector<absl::string_view> values;
for (size_t i = 0; i < entry.size(); ++i) {
for (absl::string_view s : absl::StrSplit(entry[i]->value().getStringView(), ',')) {
if (s.empty()) {
continue;
}
values.emplace_back(absl::StripAsciiWhitespace(s));
}
}
return values;
}
VaryAllowList::VaryAllowList(
const Protobuf::RepeatedPtrField<envoy::type::matcher::v3::StringMatcher>& allow_list) {
for (const auto& rule : allow_list) {
allow_list_.emplace_back(
std::make_unique<Matchers::StringMatcherImpl<envoy::type::matcher::v3::StringMatcher>>(
rule));
}
}
bool VaryAllowList::allowsValue(const absl::string_view vary_value) const {
for (const auto& rule : allow_list_) {
if (rule->match(vary_value)) {
return true;
}
}
return false;
}
bool VaryAllowList::allowsHeaders(const Http::ResponseHeaderMap& headers) const {
if (!VaryHeaderUtils::hasVary(headers)) {
return true;
}
std::vector<absl::string_view> varied_headers =
CacheHeadersUtils::parseCommaDelimitedHeader(headers.get(Http::CustomHeaders::get().Vary));
for (absl::string_view& header : varied_headers) {
bool valid = false;
// "Vary: *" should never be cached per:
// https://tools.ietf.org/html/rfc7231#section-7.1.4
if (header == "*") {
return false;
}
if (allowsValue(header)) {
valid = true;
}
if (!valid) {
return false;
}
}
return true;
}
bool VaryHeaderUtils::hasVary(const Http::ResponseHeaderMap& headers) {
// TODO(mattklein123): Support multiple vary headers and/or just make the vary header inline.
const auto vary_header = headers.get(Http::CustomHeaders::get().Vary);
return !vary_header.empty() && !vary_header[0]->value().empty();
}
absl::btree_set<absl::string_view>
VaryHeaderUtils::getVaryValues(const Http::ResponseHeaderMap& headers) {
Http::HeaderMap::GetResult vary_headers = headers.get(Http::CustomHeaders::get().Vary);
if (vary_headers.empty()) {
return {};
}
std::vector<absl::string_view> values =
CacheHeadersUtils::parseCommaDelimitedHeader(vary_headers);
return absl::btree_set<absl::string_view>(values.begin(), values.end());
}
namespace {
// The separator characters are used to create the vary-key, and must be characters that are
// invalid to be inside values and header names. The chosen characters are invalid per:
// https://tools.ietf.org/html/rfc2616#section-4.2.
// Used to separate the values of different headers.
constexpr absl::string_view headerSeparator = "\n";
// Used to separate multiple values of a same header.
constexpr absl::string_view inValueSeparator = "\r";
}; // namespace
absl::optional<std::string>
VaryHeaderUtils::createVaryIdentifier(const VaryAllowList& allow_list,
const absl::btree_set<absl::string_view>& vary_header_values,
const Http::RequestHeaderMap& request_headers) {
std::string vary_identifier = "vary-id\n";
if (vary_header_values.empty()) {
return vary_identifier;
}
for (const absl::string_view& value : vary_header_values) {
if (value.empty()) {
// Empty headers are ignored.
continue;
}
if (!allow_list.allowsValue(value)) {
// The backend tried to vary on a header that we don't allow, so return
// absl::nullopt to indicate we are unable to cache this request. This
// also may occur if the allow list has changed since an item was cached,
// rendering the cached vary value invalid.
return absl::nullopt;
}
// TODO(cbdm): Can add some bucketing logic here based on header. For
// example, we could normalize the values for accept-language by making all
// of {en-CA, en-GB, en-US} into "en". This way we would not need to store
// multiple versions of the same payload, and any of those values would find
// the payload in the requested language. Another example would be to bucket
// UserAgent values into android/ios/desktop;
// UserAgent::initializeFromHeaders tries to do that normalization and could
// be used as an inspiration for some bucketing configuration. The config
// should enable and control the bucketing wanted.
const auto all_values = Http::HeaderUtility::getAllOfHeaderAsString(
request_headers, Http::LowerCaseString(std::string(value)), inValueSeparator);
absl::StrAppend(&vary_identifier, value, inValueSeparator,
all_values.result().has_value() ? all_values.result().value() : "",
headerSeparator);
}
return vary_identifier;
}
} // namespace Cache
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Antonio Recuero
// =============================================================================
//
// Unit test for ANCF beam element (continuum-based). This unit test uses published
// data to verify the implementation of the internal forces of the ANCFbeamelement.
// For more information, refer to Nachbagauer, Gruber, and Gerstmayr, "Structural and
// continuum mechanics approaches for a 3D shear deformable ANCF beam finite element:
// Application to static and linearized dynamic examples", Journal of Computational
// and Nonlinear Dynamics, April 2013, Vol. 8/021004. Table 1 therein.
// =============================================================================
#include <cstdio>
#include <cmath>
#include "chrono/physics/ChSystem.h"
#include "chrono/solver/ChSolverMINRES.h"
#include "chrono_fea/ChElementBeamANCF.h"
#include "chrono_fea/ChMesh.h"
#ifdef CHRONO_MKL
#include "chrono_mkl/ChSolverMKL.h"
#endif
bool use_mkl = true;
const double u_y_Ref = 8.091623235e-4;
const double u_x_Ref = 1.944145290e-7;
const double rel_Tol = 1e-7;
using namespace chrono;
using namespace chrono::fea;
int main(int argc, char* argv[]) {
// Create a Chrono::Engine physical system
ChSystem my_system;
// Create a mesh, that is a container for groups of elements and
// their referenced nodes.
auto my_mesh = std::make_shared<ChMesh>();
my_system.Set_G_acc(ChVector<>(0, -9.81, 0.0));
const double beam_h = 0.5; // Beam height (y)
const double beam_w = 0.1; // Beam width (z)
const double beam_l = 2.0; // Beam length
unsigned int NElem = 4; // Number of finite elements
double rho = 2000.0; // Beam material density
const double E_mod = 2.07e11; // Beam modulus of elasticity
const double nu_rat = 0.3; // Beam material Poisson ratio
const double k1 = 10 * (1 + nu_rat) / (12 + 11 * nu_rat); // Timoshenko coefficient
const double k2 = k1; // Timoshenko coefficient
auto m_beamMaterial = std::make_shared<ChMaterialBeamANCF>(rho, E_mod, nu_rat, k1, k2);
// Create the end nodes
auto hnodeancf1 = std::make_shared<ChNodeFEAxyzDD>(ChVector<>(0, 0, 0.0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancf2 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 4, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancf3 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 2, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancf4 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(3.0 * beam_l / 4, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancf5 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
// Create the middle nodes
auto hnodeancfm1 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 8, 0, 0.0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancfm2 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(3 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancfm3 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(5 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancfm4 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(7 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
hnodeancf1->SetFixed(true); // Fix ALL coordinates of first (clamped) node
my_mesh->AddNode(hnodeancf1);
my_mesh->AddNode(hnodeancf2);
my_mesh->AddNode(hnodeancf3);
my_mesh->AddNode(hnodeancf4);
my_mesh->AddNode(hnodeancf5);
my_mesh->AddNode(hnodeancfm1);
my_mesh->AddNode(hnodeancfm2);
my_mesh->AddNode(hnodeancfm3);
my_mesh->AddNode(hnodeancfm4);
// Create the element 1
auto belementancf1 = std::make_shared<ChElementBeamANCF>();
belementancf1->SetNodes(hnodeancf1, hnodeancf2, hnodeancfm1);
belementancf1->SetDimensions(beam_l / 4, beam_h, beam_w);
belementancf1->SetMaterial(m_beamMaterial);
belementancf1->SetAlphaDamp(0.0004);
belementancf1->SetGravityOn(false);
belementancf1->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect
my_mesh->AddElement(belementancf1);
// Create the element 2
auto belementancf2 = std::make_shared<ChElementBeamANCF>();
belementancf2->SetNodes(hnodeancf2, hnodeancf3, hnodeancfm2);
belementancf2->SetDimensions(beam_l / 4, beam_h, beam_w);
belementancf2->SetMaterial(m_beamMaterial);
belementancf2->SetAlphaDamp(0.0004);
belementancf2->SetGravityOn(false);
belementancf2->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect
my_mesh->AddElement(belementancf2);
// Create the element 3
auto belementancf3 = std::make_shared<ChElementBeamANCF>();
belementancf3->SetNodes(hnodeancf3, hnodeancf4, hnodeancfm3);
belementancf3->SetDimensions(beam_l / 4, beam_h, beam_w);
belementancf3->SetMaterial(m_beamMaterial);
belementancf3->SetAlphaDamp(0.0004);
belementancf3->SetGravityOn(false);
belementancf3->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect
my_mesh->AddElement(belementancf3);
// Create the element 4
auto belementancf4 = std::make_shared<ChElementBeamANCF>();
belementancf4->SetNodes(hnodeancf4, hnodeancf5, hnodeancfm4);
belementancf4->SetDimensions(beam_l / 4, beam_h, beam_w);
belementancf4->SetMaterial(m_beamMaterial);
belementancf4->SetAlphaDamp(0.0004);
belementancf4->SetGravityOn(false);
belementancf4->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect
my_mesh->AddElement(belementancf4);
// Cancel automatic gravity
my_mesh->SetAutomaticGravity(false);
// Remember to add the mesh to the system
my_system.Add(my_mesh);
// Setup solver
if (true) {
#ifdef CHRONO_MKL
ChSolverMKL<>* mkl_solver_stab = new ChSolverMKL<>;
ChSolverMKL<>* mkl_solver_speed = new ChSolverMKL<>;
my_system.ChangeSolverStab(mkl_solver_stab);
my_system.ChangeSolverSpeed(mkl_solver_speed);
mkl_solver_speed->SetSparsityPatternLock(false);
mkl_solver_stab->SetSparsityPatternLock(false);
mkl_solver_speed->SetVerbose(false);
#endif
} else {
my_system.SetSolverType(ChSystem::SOLVER_MINRES);
ChSolverMINRES* msolver = (ChSolverMINRES*)my_system.GetSolverSpeed();
msolver->SetDiagonalPreconditioning(true);
my_system.SetSolverWarmStarting(true);
my_system.SetMaxItersSolverSpeed(100);
my_system.SetMaxItersSolverStab(100);
my_system.SetTolForce(1e-09);
}
// Setup integrator
my_system.SetIntegrationType(ChSystem::INT_HHT);
auto mystepper = std::static_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper());
mystepper->SetAlpha(-0.2);
mystepper->SetMaxiters(10);
mystepper->SetAbsTolerances(1e-10);
mystepper->SetMode(ChTimestepperHHT::POSITION);
mystepper->SetScaling(false);
mystepper->SetVerbose(true);
mystepper->SetModifiedNewton(false);
// Mark completion of system construction
my_system.SetupInitial();
unsigned int num_steps = 50;
double time_Step = 0.01;
std::cout << std::fixed << std::setprecision(12);
for (unsigned int it = 0; it < num_steps; it++) {
// std::cout << "Position of the tip: " << hnodeancf5->GetPos().y << " m. \n";
// std::cout << "Long. Position of the tip: " << hnodeancf5->GetPos().x << " m. \n";
// std::cout << "Lat. Position of the tip: " << hnodeancf5->GetPos().z << " m. \n";
hnodeancf5->SetForce(ChVector<>(0, -5e5 * std::pow(0.5, 3), 0));
my_system.DoStepDynamics(time_Step);
}
double error_y = (hnodeancf5->GetPos().y + u_y_Ref) / u_y_Ref;
double error_x = (hnodeancf5->GetPos().x + u_x_Ref - 2.0) / u_x_Ref;
if (ChMax(error_x, error_y) > rel_Tol) {
return 1;
}
std::cout << "Position of the tip: " << hnodeancf5->GetPos().y << " m. \n";
std::cout << "Long. Position of the tip: " << hnodeancf5->GetPos().x << " m. \n";
std::cout << "Lat. Position of the tip: " << hnodeancf5->GetPos().z << " m. \n";
return 0;
}
<commit_msg>Use mkl only if available in ANCF beam unit test<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Antonio Recuero
// =============================================================================
//
// Unit test for ANCF beam element (continuum-based). This unit test uses published
// data to verify the implementation of the internal forces of the ANCFbeamelement.
// For more information, refer to Nachbagauer, Gruber, and Gerstmayr, "Structural and
// continuum mechanics approaches for a 3D shear deformable ANCF beam finite element:
// Application to static and linearized dynamic examples", Journal of Computational
// and Nonlinear Dynamics, April 2013, Vol. 8/021004. Table 1 therein.
// =============================================================================
#include <cstdio>
#include <cmath>
#include "chrono/physics/ChSystem.h"
#include "chrono/solver/ChSolverMINRES.h"
#include "chrono_fea/ChElementBeamANCF.h"
#include "chrono_fea/ChMesh.h"
#ifdef CHRONO_MKL
#include "chrono_mkl/ChSolverMKL.h"
#endif
bool use_mkl = true;
const double u_y_Ref = 8.091623235e-4;
const double u_x_Ref = 1.944145290e-7;
const double rel_Tol = 1e-7;
using namespace chrono;
using namespace chrono::fea;
int main(int argc, char* argv[]) {
// Create a Chrono::Engine physical system
ChSystem my_system;
// Create a mesh, that is a container for groups of elements and
// their referenced nodes.
auto my_mesh = std::make_shared<ChMesh>();
my_system.Set_G_acc(ChVector<>(0, -9.81, 0.0));
const double beam_h = 0.5; // Beam height (y)
const double beam_w = 0.1; // Beam width (z)
const double beam_l = 2.0; // Beam length
unsigned int NElem = 4; // Number of finite elements
double rho = 2000.0; // Beam material density
const double E_mod = 2.07e11; // Beam modulus of elasticity
const double nu_rat = 0.3; // Beam material Poisson ratio
const double k1 = 10 * (1 + nu_rat) / (12 + 11 * nu_rat); // Timoshenko coefficient
const double k2 = k1; // Timoshenko coefficient
auto m_beamMaterial = std::make_shared<ChMaterialBeamANCF>(rho, E_mod, nu_rat, k1, k2);
// Create the end nodes
auto hnodeancf1 = std::make_shared<ChNodeFEAxyzDD>(ChVector<>(0, 0, 0.0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancf2 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 4, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancf3 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 2, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancf4 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(3.0 * beam_l / 4, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancf5 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
// Create the middle nodes
auto hnodeancfm1 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 8, 0, 0.0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancfm2 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(3 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancfm3 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(5 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
auto hnodeancfm4 =
std::make_shared<ChNodeFEAxyzDD>(ChVector<>(7 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1));
hnodeancf1->SetFixed(true); // Fix ALL coordinates of first (clamped) node
my_mesh->AddNode(hnodeancf1);
my_mesh->AddNode(hnodeancf2);
my_mesh->AddNode(hnodeancf3);
my_mesh->AddNode(hnodeancf4);
my_mesh->AddNode(hnodeancf5);
my_mesh->AddNode(hnodeancfm1);
my_mesh->AddNode(hnodeancfm2);
my_mesh->AddNode(hnodeancfm3);
my_mesh->AddNode(hnodeancfm4);
// Create the element 1
auto belementancf1 = std::make_shared<ChElementBeamANCF>();
belementancf1->SetNodes(hnodeancf1, hnodeancf2, hnodeancfm1);
belementancf1->SetDimensions(beam_l / 4, beam_h, beam_w);
belementancf1->SetMaterial(m_beamMaterial);
belementancf1->SetAlphaDamp(0.0004);
belementancf1->SetGravityOn(false);
belementancf1->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect
my_mesh->AddElement(belementancf1);
// Create the element 2
auto belementancf2 = std::make_shared<ChElementBeamANCF>();
belementancf2->SetNodes(hnodeancf2, hnodeancf3, hnodeancfm2);
belementancf2->SetDimensions(beam_l / 4, beam_h, beam_w);
belementancf2->SetMaterial(m_beamMaterial);
belementancf2->SetAlphaDamp(0.0004);
belementancf2->SetGravityOn(false);
belementancf2->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect
my_mesh->AddElement(belementancf2);
// Create the element 3
auto belementancf3 = std::make_shared<ChElementBeamANCF>();
belementancf3->SetNodes(hnodeancf3, hnodeancf4, hnodeancfm3);
belementancf3->SetDimensions(beam_l / 4, beam_h, beam_w);
belementancf3->SetMaterial(m_beamMaterial);
belementancf3->SetAlphaDamp(0.0004);
belementancf3->SetGravityOn(false);
belementancf3->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect
my_mesh->AddElement(belementancf3);
// Create the element 4
auto belementancf4 = std::make_shared<ChElementBeamANCF>();
belementancf4->SetNodes(hnodeancf4, hnodeancf5, hnodeancfm4);
belementancf4->SetDimensions(beam_l / 4, beam_h, beam_w);
belementancf4->SetMaterial(m_beamMaterial);
belementancf4->SetAlphaDamp(0.0004);
belementancf4->SetGravityOn(false);
belementancf4->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect
my_mesh->AddElement(belementancf4);
// Cancel automatic gravity
my_mesh->SetAutomaticGravity(false);
// Remember to add the mesh to the system
my_system.Add(my_mesh);
#ifndef CHRONO_MKL
use_mkl = false;
#endif
// Setup solver
if (use_mkl) {
#ifdef CHRONO_MKL
ChSolverMKL<>* mkl_solver_stab = new ChSolverMKL<>;
ChSolverMKL<>* mkl_solver_speed = new ChSolverMKL<>;
my_system.ChangeSolverStab(mkl_solver_stab);
my_system.ChangeSolverSpeed(mkl_solver_speed);
mkl_solver_speed->SetSparsityPatternLock(false);
mkl_solver_stab->SetSparsityPatternLock(false);
mkl_solver_speed->SetVerbose(false);
#endif
} else {
my_system.SetSolverType(ChSystem::SOLVER_MINRES);
ChSolverMINRES* msolver = (ChSolverMINRES*)my_system.GetSolverSpeed();
msolver->SetDiagonalPreconditioning(true);
my_system.SetSolverWarmStarting(true);
my_system.SetMaxItersSolverSpeed(100);
my_system.SetMaxItersSolverStab(100);
my_system.SetTolForce(1e-09);
}
// Setup integrator
my_system.SetIntegrationType(ChSystem::INT_HHT);
auto mystepper = std::static_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper());
mystepper->SetAlpha(-0.2);
mystepper->SetMaxiters(10);
mystepper->SetAbsTolerances(1e-10);
mystepper->SetMode(ChTimestepperHHT::POSITION);
mystepper->SetScaling(false);
mystepper->SetVerbose(true);
mystepper->SetModifiedNewton(false);
// Mark completion of system construction
my_system.SetupInitial();
unsigned int num_steps = 50;
double time_Step = 0.01;
std::cout << std::fixed << std::setprecision(12);
for (unsigned int it = 0; it < num_steps; it++) {
// std::cout << "Position of the tip: " << hnodeancf5->GetPos().y << " m. \n";
// std::cout << "Long. Position of the tip: " << hnodeancf5->GetPos().x << " m. \n";
// std::cout << "Lat. Position of the tip: " << hnodeancf5->GetPos().z << " m. \n";
hnodeancf5->SetForce(ChVector<>(0, -5e5 * std::pow(0.5, 3), 0));
my_system.DoStepDynamics(time_Step);
}
double error_y = (hnodeancf5->GetPos().y + u_y_Ref) / u_y_Ref;
double error_x = (hnodeancf5->GetPos().x + u_x_Ref - 2.0) / u_x_Ref;
if (ChMax(error_x, error_y) > rel_Tol) {
return 1;
}
std::cout << "Position of the tip: " << hnodeancf5->GetPos().y << " m. \n";
std::cout << "Long. Position of the tip: " << hnodeancf5->GetPos().x << " m. \n";
std::cout << "Lat. Position of the tip: " << hnodeancf5->GetPos().z << " m. \n";
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: uielementfactorymanager.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:08:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
#define __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
#include <list>
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUIELEMENTFACTORY_HPP_
#include <com/sun/star/ui/XUIElementFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUIELEMENTFACTORYREGISTRATION_HPP_
#include <com/sun/star/ui/XUIElementFactoryRegistration.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include "com/sun/star/frame/XModuleManager.hpp"
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace framework
{
class ConfigurationAccess_UIElementFactoryManager;
class UIElementFactoryManager : public com::sun::star::lang::XTypeProvider ,
public com::sun::star::lang::XServiceInfo ,
public ::com::sun::star::ui::XUIElementFactory ,
public ::com::sun::star::ui::XUIElementFactoryRegistration ,
private ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
UIElementFactoryManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
virtual ~UIElementFactoryManager();
// XInterface, XTypeProvider, XServiceInfo
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XUIElementFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIElement > SAL_CALL createUIElement( const ::rtl::OUString& ResourceURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& Args ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
// XUIElementFactoryRegistration
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getRegisteredFactories( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIElementFactory > SAL_CALL getFactory( const ::rtl::OUString& ResourceURL, const ::rtl::OUString& ModuleIdentifier ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL registerFactory( const ::rtl::OUString& aType, const ::rtl::OUString& aName, const ::rtl::OUString& aModuleIdentifier, const ::rtl::OUString& aFactoryImplementationName ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deregisterFactory( const ::rtl::OUString& aType, const ::rtl::OUString& aName, const ::rtl::OUString& aModuleIdentifier ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);
private:
void RetrieveTypeNameFromResourceURL( const ::rtl::OUString& aResourceURL, rtl::OUString& aType, rtl::OUString& aName );
sal_Bool m_bConfigRead;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModuleManager > m_xModuleManager;
ConfigurationAccess_UIElementFactoryManager* m_pConfigAccess;
};
} // namespace framework
#endif // __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.6.318); FILE MERGED 2008/04/01 15:18:30 thb 1.6.318.3: #i85898# Stripping all external header guards 2008/04/01 10:57:59 thb 1.6.318.2: #i85898# Stripping all external header guards 2008/03/28 15:34:59 rt 1.6.318.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: uielementfactorymanager.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 __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
#define __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
#include <list>
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#include <threadhelp/threadhelpbase.hxx>
#include <macros/generic.hxx>
#include <macros/xinterface.hxx>
#include <macros/xtypeprovider.hxx>
#include <macros/xserviceinfo.hxx>
#include <stdtypes.h>
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/ui/XUIElementFactory.hpp>
#include <com/sun/star/ui/XUIElementFactoryRegistration.hpp>
#include "com/sun/star/frame/XModuleManager.hpp"
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#include <cppuhelper/weak.hxx>
#include <rtl/ustring.hxx>
namespace framework
{
class ConfigurationAccess_UIElementFactoryManager;
class UIElementFactoryManager : public com::sun::star::lang::XTypeProvider ,
public com::sun::star::lang::XServiceInfo ,
public ::com::sun::star::ui::XUIElementFactory ,
public ::com::sun::star::ui::XUIElementFactoryRegistration ,
private ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
UIElementFactoryManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
virtual ~UIElementFactoryManager();
// XInterface, XTypeProvider, XServiceInfo
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XUIElementFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIElement > SAL_CALL createUIElement( const ::rtl::OUString& ResourceURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& Args ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
// XUIElementFactoryRegistration
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getRegisteredFactories( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIElementFactory > SAL_CALL getFactory( const ::rtl::OUString& ResourceURL, const ::rtl::OUString& ModuleIdentifier ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL registerFactory( const ::rtl::OUString& aType, const ::rtl::OUString& aName, const ::rtl::OUString& aModuleIdentifier, const ::rtl::OUString& aFactoryImplementationName ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deregisterFactory( const ::rtl::OUString& aType, const ::rtl::OUString& aName, const ::rtl::OUString& aModuleIdentifier ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);
private:
void RetrieveTypeNameFromResourceURL( const ::rtl::OUString& aResourceURL, rtl::OUString& aType, rtl::OUString& aName );
sal_Bool m_bConfigRead;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModuleManager > m_xModuleManager;
ConfigurationAccess_UIElementFactoryManager* m_pConfigAccess;
};
} // namespace framework
#endif // __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep14/call_mss_memdiag.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 */
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <isteps/hwpisteperror.H>
#include <initservice/isteps_trace.H>
#include <targeting/common/utilFilter.H>
#include <diag/attn/attn.H>
#include <diag/mdia/mdia.H>
#include <targeting/common/targetservice.H>
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
namespace ISTEP_14
{
void* call_mss_memdiag (void* io_pArgs)
{
errlHndl_t l_errl = NULL;
IStepError l_stepError;
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_mss_memdiag entry");
TARGETING::Target* masterproc = nullptr;
TARGETING::targetService().masterProcChipTargetHandle(masterproc);
#ifdef CONFIG_IPLTIME_CHECKSTOP_ANALYSIS
// @TODO-RTC: 155065
// update firdata inputs for OCC
l_errl = HBOCC::loadHostDataToSRAM(masterproc,
PRDF::ALL_PROC_MEM_MASTER_CORE);
assert(l_errl==NULL,
"Error returned from call to HBOCC::loadHostDataToSRAM");
#endif
TARGETING::TargetHandleList l_targetList;
TARGETING::TYPE targetType;
// we need to check the model of the master proc
// if it is Cumulus then we will use TYPE_MBA for targetType
// else it is Nimbus so then we will use TYPE_MCBIST for targetType
if ( TARGETING::MODEL_CUMULUS ==
masterproc->getAttr<TARGETING::ATTR_MODEL>() )
{
targetType = TARGETING::TYPE_MBA;
}
else
{
targetType = TARGETING::TYPE_MCBIST;
}
getAllChiplets(l_targetList, targetType);
do
{
l_errl = ATTN::startService();
if( NULL != l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ATTN startService failed");
break;
}
l_errl = MDIA::runStep(l_targetList);
if( NULL != l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MDIA subStep failed");
break;
}
l_errl = ATTN::stopService();
if( NULL != l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ATTN stopService failed");
break;
}
}while( 0 );
if( NULL != l_errl )
{
// Create IStep error log and cross reference to error that occurred
l_stepError.addErrorDetails(l_errl);
// Commit Error
errlCommit(l_errl, HWPF_COMP_ID);
}
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_mss_memdiag exit");
// end task, returning any errorlogs to IStepDisp
return l_stepError.getErrorHandle();
}
};
<commit_msg>Disable memdiags<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep14/call_mss_memdiag.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 */
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <isteps/hwpisteperror.H>
#include <initservice/isteps_trace.H>
#include <targeting/common/utilFilter.H>
#include <diag/attn/attn.H>
#include <diag/mdia/mdia.H>
#include <targeting/common/targetservice.H>
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
namespace ISTEP_14
{
void* call_mss_memdiag (void* io_pArgs)
{
errlHndl_t l_errl = NULL;
IStepError l_stepError;
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_mss_memdiag entry");
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"!!!Skipping memdiags until it works!!!");
return NULL;
TARGETING::Target* masterproc = nullptr;
TARGETING::targetService().masterProcChipTargetHandle(masterproc);
#ifdef CONFIG_IPLTIME_CHECKSTOP_ANALYSIS
// @TODO-RTC: 155065
// update firdata inputs for OCC
l_errl = HBOCC::loadHostDataToSRAM(masterproc,
PRDF::ALL_PROC_MEM_MASTER_CORE);
assert(l_errl==NULL,
"Error returned from call to HBOCC::loadHostDataToSRAM");
#endif
TARGETING::TargetHandleList l_targetList;
TARGETING::TYPE targetType;
// we need to check the model of the master proc
// if it is Cumulus then we will use TYPE_MBA for targetType
// else it is Nimbus so then we will use TYPE_MCBIST for targetType
if ( TARGETING::MODEL_CUMULUS ==
masterproc->getAttr<TARGETING::ATTR_MODEL>() )
{
targetType = TARGETING::TYPE_MBA;
}
else
{
targetType = TARGETING::TYPE_MCBIST;
}
getAllChiplets(l_targetList, targetType);
do
{
l_errl = ATTN::startService();
if( NULL != l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ATTN startService failed");
break;
}
l_errl = MDIA::runStep(l_targetList);
if( NULL != l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MDIA subStep failed");
break;
}
l_errl = ATTN::stopService();
if( NULL != l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ATTN stopService failed");
break;
}
}while( 0 );
if( NULL != l_errl )
{
// Create IStep error log and cross reference to error that occurred
l_stepError.addErrorDetails(l_errl);
// Commit Error
errlCommit(l_errl, HWPF_COMP_ID);
}
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_mss_memdiag exit");
// end task, returning any errorlogs to IStepDisp
return l_stepError.getErrorHandle();
}
};
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MoosePreconditioner.h"
#include "FEProblem.h"
template<>
InputParameters validParams<MoosePreconditioner>()
{
InputParameters params = validParams<MooseObject>();
params.addPrivateParam<FEProblem *>("_fe_problem");
params.addPrivateParam<std::string>("built_by_action", "add_preconditioning");
return params;
}
MoosePreconditioner::MoosePreconditioner(const std::string & name, InputParameters params) :
MooseObject(name, params),
_fe_problem(*getParam<FEProblem *>("_fe_problem"))
{
}
MoosePreconditioner::~MoosePreconditioner()
{
}
void
MoosePreconditioner::copyVarValues(MeshBase & mesh,
const unsigned int from_system, const unsigned int from_var, const NumericVector<Number> & from_vector,
const unsigned int to_system, const unsigned int to_var, NumericVector<Number> & to_vector)
{
MeshBase::node_iterator it = mesh.local_nodes_begin();
MeshBase::node_iterator it_end = mesh.local_nodes_end();
for(;it!=it_end;++it)
{
Node * node = *it;
unsigned int n_comp = node->n_comp(from_system, from_var);
mooseAssert(node->n_comp(from_system, from_var) == node->n_comp(to_system, to_var), "Number of components does not match in each system in PBP");
for(unsigned int i=0; i<n_comp; i++)
{
unsigned int from_dof = node->dof_number(from_system,from_var,i);
unsigned int to_dof = node->dof_number(to_system,to_var,i);
to_vector.set(to_dof,from_vector(from_dof));
}
}
}
<commit_msg>yaqis patch for CopyVarValues closes #1592<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MoosePreconditioner.h"
#include "FEProblem.h"
template<>
InputParameters validParams<MoosePreconditioner>()
{
InputParameters params = validParams<MooseObject>();
params.addPrivateParam<FEProblem *>("_fe_problem");
params.addPrivateParam<std::string>("built_by_action", "add_preconditioning");
return params;
}
MoosePreconditioner::MoosePreconditioner(const std::string & name, InputParameters params) :
MooseObject(name, params),
_fe_problem(*getParam<FEProblem *>("_fe_problem"))
{
}
MoosePreconditioner::~MoosePreconditioner()
{
}
void
MoosePreconditioner::copyVarValues(MeshBase & mesh,
const unsigned int from_system, const unsigned int from_var, const NumericVector<Number> & from_vector,
const unsigned int to_system, const unsigned int to_var, NumericVector<Number> & to_vector)
{
{
MeshBase::node_iterator it = mesh.local_nodes_begin();
MeshBase::node_iterator it_end = mesh.local_nodes_end();
for(;it!=it_end;++it)
{
Node * node = *it;
unsigned int n_comp = node->n_comp(from_system, from_var);
mooseAssert(node->n_comp(from_system, from_var) == node->n_comp(to_system, to_var),
"Number of components does not match in each system");
for(unsigned int i=0; i<n_comp; i++)
{
unsigned int from_dof = node->dof_number(from_system,from_var,i);
unsigned int to_dof = node->dof_number(to_system,to_var,i);
to_vector.set(to_dof,from_vector(from_dof));
}
}
}
{
MeshBase::element_iterator it = mesh.local_elements_begin();
MeshBase::element_iterator it_end = mesh.local_elements_end();
for(;it!=it_end;++it)
{
Elem * elem = *it;
unsigned int n_comp = elem->n_comp(from_system, from_var);
mooseAssert(elem->n_comp(from_system, from_var) == elem->n_comp(to_system, to_var),
"Number of components does not match in each system");
for(unsigned int i=0; i<n_comp; i++)
{
unsigned int from_dof = elem->dof_number(from_system,from_var,i);
unsigned int to_dof = elem->dof_number(to_system,to_var,i);
to_vector.set(to_dof,from_vector(from_dof));
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef PLUGINS_HPP
#define PLUGINS_HPP
#include <plugin.hpp>
#include <vector>
#include <string>
#include <kdb>
class Plugins
{
protected:
std::vector<Plugin *> plugins;
kdb::KeySet ret;
std::vector <std::string> alreadyProvided;
int nrStoragePlugins;
int nrResolverPlugins;
public:
Plugins () :
plugins (10),
nrStoragePlugins (0),
nrResolverPlugins (0)
{}
void addProvided (Plugin &plugin);
void checkProvided (Plugin &plugin);
void checkStorage (Plugin &plugin);
void checkResolver (Plugin &plugin);
void checkInfo (Plugin &plugin);
};
class GetPlugins : public Plugins
{
public:
/**
* Returns true if GetPlugins are valid afterwards.
*
* Will throw an exception if plugin could not
* be added.
*/
void tryPlugin (Plugin &plugin);
void addPlugin (Plugin &plugin);
bool validated ();
void serialize (kdb::Key &baseKey, kdb::KeySet &ret);
};
class SetPlugins : public Plugins
{
public:
void tryPlugin (Plugin &plugin);
void addPlugin (Plugin &plugin);
bool validated ();
void serialize (kdb::Key &baseKey, kdb::KeySet &ret);
};
class ErrorPlugins : public Plugins
{
public:
void tryPlugin (Plugin &plugin);
void addPlugin (Plugin &plugin);
bool validated ();
void serialize (kdb::Key &baseKey, kdb::KeySet &ret);
};
#endif
<commit_msg>use private inheritance<commit_after>#ifndef PLUGINS_HPP
#define PLUGINS_HPP
#include <plugin.hpp>
#include <vector>
#include <string>
#include <kdb>
class Plugins
{
protected:
std::vector<Plugin *> plugins;
kdb::KeySet ret;
std::vector <std::string> alreadyProvided;
int nrStoragePlugins;
int nrResolverPlugins;
public:
Plugins () :
plugins (10),
nrStoragePlugins (0),
nrResolverPlugins (0)
{}
void addProvided (Plugin &plugin);
void checkProvided (Plugin &plugin);
void checkStorage (Plugin &plugin);
void checkResolver (Plugin &plugin);
void checkInfo (Plugin &plugin);
};
class GetPlugins : private Plugins
{
public:
/**
* Returns true if GetPlugins are valid afterwards.
*
* Will throw an exception if plugin could not
* be added.
*/
void tryPlugin (Plugin &plugin);
void addPlugin (Plugin &plugin);
bool validated ();
void serialize (kdb::Key &baseKey, kdb::KeySet &ret);
};
class SetPlugins : private Plugins
{
public:
void tryPlugin (Plugin &plugin);
void addPlugin (Plugin &plugin);
bool validated ();
void serialize (kdb::Key &baseKey, kdb::KeySet &ret);
};
class ErrorPlugins : private Plugins
{
public:
void tryPlugin (Plugin &plugin);
void addPlugin (Plugin &plugin);
bool validated ();
void serialize (kdb::Key &baseKey, kdb::KeySet &ret);
};
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2013, Howard Butler ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <algorithm>
#include <pdal/kernel/Info.hpp>
#include <pdal/KDIndex.hpp>
#include <pdal/PipelineWriter.hpp>
namespace pdal
{
namespace kernel
{
Info::Info(int argc, const char* argv[])
: Application(argc, argv, "info")
, m_inputFile("")
, m_showStats(false)
, m_showSchema(false)
, m_showStage(false)
, m_showMetadata(false)
, m_showSDOPCMetadata(false)
, m_computeBoundary(false)
, m_useXML(false)
, m_useJSON(false)
, m_useREST(true)
, m_QueryDistance(0.0)
, m_numPointsToWrite(0)
, m_showSample(false)
{}
void Info::validateSwitches()
{
const bool got_something =
m_showStats ||
m_showSchema ||
m_showMetadata ||
m_showSDOPCMetadata ||
m_computeBoundary ||
m_showStage ||
m_QueryPoint.size() > 0 ||
m_pointIndexes.size() > 0;
if (!got_something)
{
m_showStats = true;
m_computeBoundary = true;
m_showSchema = true;
}
}
void Info::addSwitches()
{
namespace po = boost::program_options;
po::options_description* file_options =
new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile)->default_value(""),
"input file name")
;
addSwitchSet(file_options);
po::options_description* processing_options =
new po::options_description("processing options");
processing_options->add_options()
("point,p", po::value<std::string >(&m_pointIndexes), "point to dump")
("query", po::value< std::string>(&m_QueryPoint),
"A 2d or 3d point query point")
("distance", po::value< double>(&m_QueryDistance), "A query distance")
("stats",
po::value<bool>(&m_showStats)->zero_tokens()->implicit_value(true),
"dump stats on all points (reads entire dataset)")
("boundary",
po::value<bool>(&m_computeBoundary)->zero_tokens()->implicit_value(true),
"compute a hexagonal hull/boundary of dataset")
("count", po::value<uint64_t>(&m_numPointsToWrite)->default_value(0),
"How many points should we write?")
("dimensions", po::value<std::string >(&m_Dimensions),
"dump stats on all points (reads entire dataset)")
("schema",
po::value<bool>(&m_showSchema)->zero_tokens()->implicit_value(true),
"dump the schema")
("metadata,m",
po::value<bool>(&m_showMetadata)->zero_tokens()->implicit_value(true),
"dump the metadata")
("sdo_pc",
po::value<bool>(&m_showSDOPCMetadata)->zero_tokens()->
implicit_value(true),
"dump the SDO_PC Oracle Metadata")
("stage,r",
po::value<bool>(&m_showStage)->zero_tokens()->implicit_value(true),
"dump the stage info")
("pipeline-serialization",
po::value<std::string>(&m_pipelineFile)->default_value(""), "")
("xml", po::value<bool>(&m_useXML)->zero_tokens()->implicit_value(true),
"dump XML")
("json",
po::value<bool>(&m_useJSON)->zero_tokens()->implicit_value(true),
"dump JSON")
("sample",
po::value<bool>(&m_showSample)->zero_tokens()->implicit_value(true),
"randomly sample dimension for stats")
("seed", po::value<uint32_t>(&m_seed)->default_value(0),
"Seed value for random sample")
("sample_size",
po::value<uint32_t>(&m_sample_size)->default_value(1000),
"Sample size for random sample")
;
addSwitchSet(processing_options);
addPositionalSwitch("input", 1);
}
// Support for parsing point numbers. Points can be specified singly or as
// dash-separated ranges. i.e. 6-7,8,19-20
namespace {
using namespace std;
vector<string> tokenize(const string s, char c)
{
string::const_iterator begin;
string::const_iterator end;
vector<string> strings;
begin = s.begin();
while (true)
{
end = find(begin, s.end(), c);
strings.push_back(string(begin, end));
if (end == s.end())
break;
begin = end + 1;
}
return strings;
}
uint32_t parseInt(const string& s)
{
try
{
return boost::lexical_cast<uint32_t>(s);
}
catch (boost::bad_lexical_cast)
{
throw app_runtime_error(string("Invalid integer: ") + s);
}
}
void addSingle(const string& s, vector<uint32_t>& points)
{
points.push_back(parseInt(s));
}
void addRange(const string& begin, const string& end,
vector<uint32_t>& points)
{
uint32_t low = parseInt(begin);
uint32_t high = parseInt(end);
if (low > high)
throw app_runtime_error(string("Range invalid: ") + begin + "-" + end);
while (low <= high)
points.push_back(low++);
}
vector<boost::uint32_t> getListOfPoints(std::string p)
{
vector<boost::uint32_t> output;
//Remove whitespace from string with awful remove/erase idiom.
p.erase(remove_if(p.begin(), p.end(), ::isspace), p.end());
vector<string> ranges = tokenize(p, ',');
for (string s : ranges)
{
vector<string> limits = tokenize(s, '-');
if (limits.size() == 1)
addSingle(limits[0], output);
else if (limits.size() == 2)
addRange(limits[0], limits[1], output);
else
throw app_runtime_error(string("Invalid point range: ") + s);
}
return output;
}
} //namespace
void Info::dumpPoints(PointBufferPtr buf) const
{
PointBufferPtr outbuf = buf->makeNew();
std::vector<uint32_t> points = getListOfPoints(m_pointIndexes);
for (size_t i = 0; i < points.size(); ++i)
{
PointId id = (PointId)points[i];
if (id < buf->size())
outbuf->appendPoint(*buf, id);
}
boost::property_tree::ptree buffer_tree = pdal::utils::toPTree(*outbuf);
for (size_t i = 0; i < outbuf->size(); ++i)
{
std::string name = (std::string)"point " +
boost::lexical_cast<std::string>(points[i]);
std::string key = boost::lexical_cast<std::string>(i);
m_tree->add_child(name, buffer_tree.get_child(key));
}
}
void Info::dumpStats()
{
PipelineWriter* writer = NULL;
if (m_pipelineFile.size() > 0)
writer = new pdal::PipelineWriter(*m_manager);
MetadataNode statsNode("stats");
statsNode.add(m_manager->getMetadata());
boost::property_tree::ptree stats;
std::stringstream strm;
strm << statsNode.toJSON();
boost::property_tree::read_json(strm, stats);
m_tree->add_child("stats", stats);
if (m_pipelineFile.size() > 0)
writer->writePipeline(m_pipelineFile);
delete writer;
}
void Info::dump(PointContext ctx, PointBufferPtr buf)
{
if (m_showStats)
dumpStats();
if (m_pointIndexes.size())
dumpPoints(buf);
if (m_showSchema)
{
boost::property_tree::ptree schema;
std::string json; //= ctx.dimsJson();
std::stringstream strm;
strm << json;
boost::property_tree::read_json(strm, schema);
m_tree->add_child("schema", schema);
}
if (m_showSDOPCMetadata)
{
boost::property_tree::ptree metadata =
m_manager->getStage()->serializePipeline();
boost::property_tree::ptree output;
m_tree->add_child("stage", output);
}
if (m_QueryPoint.size())
dumpQuery(buf);
}
void Info::dumpQuery(PointBufferPtr buf) const
{
#define SEPARATORS ",| "
boost::char_separator<char> sep(SEPARATORS);
tokenizer tokens(m_QueryPoint, sep);
std::vector<double> values;
for (tokenizer::iterator t = tokens.begin(); t != tokens.end(); ++t)
values.push_back(boost::lexical_cast<double>(*t));
if (values.size() != 2 && values.size() != 3)
throw app_runtime_error("--points must be two or three values");
bool is3d = (values.size() >= 3);
double x = values[0];
double y = values[1];
double z = is3d ? values[2] : 0.0;
PointBufferPtr outbuf = buf->makeNew();
KDIndex kdi(*buf);
kdi.build(is3d);
std::vector<size_t> ids = kdi.neighbors(x, y, z, 0.0, buf->size());
for (auto i = ids.begin(); i != ids.end(); ++i)
outbuf->appendPoint(*buf, *i);
boost::property_tree::ptree tree = pdal::utils::toPTree(*outbuf);
m_tree->add_child("point", tree);
}
void Info::dumpSDO_PCMetadata(PointContext ctx, const Stage& stage) const
{
std::ostream& ostr = std::cout;
// std::string xml = pdal::Schema::to_xml(*ctx.schema(), stage.getMetadata());
// ostr << xml;
}
void Info::dumpMetadata(PointContext ctx, const Stage& stage) const
{
boost::property_tree::ptree tree = stage.serializePipeline();
std::ostream& ostr = std::cout;
if (m_useXML)
write_xml(ostr, tree);
else
write_json(ostr, tree);
}
int Info::execute()
{
Options readerOptions;
{
if (m_usestdin)
m_inputFile = "STDIN";
readerOptions.add<std::string>("filename", m_inputFile);
readerOptions.add<bool>("debug", isDebug());
readerOptions.add<uint32_t>("verbose", getVerboseLevel());
}
m_manager = std::unique_ptr<PipelineManager>(
AppSupport::makePipeline(readerOptions));
if (m_seed != 0)
{
Option seed_option("seed", m_seed, "seed value");
m_options.add(seed_option);
}
m_options.add("sample_size", m_sample_size,
"sample size for random sample");
m_options.add("exact_count", "Classification",
"use exact counts for classification stats");
m_options.add("exact_count", "ReturnNumber",
"use exact counts for ReturnNumber stats");
m_options.add("exact_count", "NumberOfReturns",
"use exact counts for ReturnNumber stats");
m_options.add("do_sample", m_showSample, "Don't do sampling");
if (m_Dimensions.size())
m_options.add("dimensions", m_Dimensions,
"Use explicit list of dimensions");
Options options = m_options + readerOptions;
Stage* stage = m_manager->getStage();
if (m_showStats)
stage = m_manager->addFilter("filters.stats", stage, options);
if (m_computeBoundary)
stage = m_manager->addFilter("filters.hexbin", stage, options);
m_tree = std::unique_ptr<boost::property_tree::ptree>(
new boost::property_tree::ptree);
std::ostream& ostr = std::cout;
m_manager->execute();
PointBufferSet pbSet = m_manager->buffers();
assert(pbSet.size() == 1);
dump(m_manager->context(), *pbSet.begin());
//
// if (m_showStats)
// dumpStats(ctx, *dynamic_cast<pdal::filters::Stats*>(filter), manager);
// if (m_showSchema)
// dumpSchema(ctx);
// if (m_showMetadata)
// dumpMetadata(ctx, *filter);
// if (m_showStage)
// dumpStage(*filter);
// if (m_showSDOPCMetadata)
// dumpSDO_PCMetadata(ctx, *filter);
//
// if (m_QueryPoint.size())
// dumpQuery(ctx, *filter);
if (m_useXML)
write_xml(ostr, *m_tree);
else
write_json(ostr, *m_tree);
return 0;
}
}} // pdal::kernel
<commit_msg>Update method used to get dimensions.<commit_after>/******************************************************************************
* Copyright (c) 2013, Howard Butler ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <algorithm>
#include <pdal/kernel/Info.hpp>
#include <pdal/KDIndex.hpp>
#include <pdal/PipelineWriter.hpp>
namespace pdal
{
namespace kernel
{
Info::Info(int argc, const char* argv[])
: Application(argc, argv, "info")
, m_inputFile("")
, m_showStats(false)
, m_showSchema(false)
, m_showStage(false)
, m_showMetadata(false)
, m_showSDOPCMetadata(false)
, m_computeBoundary(false)
, m_useXML(false)
, m_useJSON(false)
, m_useREST(true)
, m_QueryDistance(0.0)
, m_numPointsToWrite(0)
, m_showSample(false)
{}
void Info::validateSwitches()
{
const bool got_something =
m_showStats ||
m_showSchema ||
m_showMetadata ||
m_showSDOPCMetadata ||
m_computeBoundary ||
m_showStage ||
m_QueryPoint.size() > 0 ||
m_pointIndexes.size() > 0;
if (!got_something)
{
m_showStats = true;
m_computeBoundary = true;
m_showSchema = true;
}
}
void Info::addSwitches()
{
namespace po = boost::program_options;
po::options_description* file_options =
new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile)->default_value(""),
"input file name")
;
addSwitchSet(file_options);
po::options_description* processing_options =
new po::options_description("processing options");
processing_options->add_options()
("point,p", po::value<std::string >(&m_pointIndexes), "point to dump")
("query", po::value< std::string>(&m_QueryPoint),
"A 2d or 3d point query point")
("distance", po::value< double>(&m_QueryDistance), "A query distance")
("stats",
po::value<bool>(&m_showStats)->zero_tokens()->implicit_value(true),
"dump stats on all points (reads entire dataset)")
("boundary",
po::value<bool>(&m_computeBoundary)->zero_tokens()->implicit_value(true),
"compute a hexagonal hull/boundary of dataset")
("count", po::value<uint64_t>(&m_numPointsToWrite)->default_value(0),
"How many points should we write?")
("dimensions", po::value<std::string >(&m_Dimensions),
"dump stats on all points (reads entire dataset)")
("schema",
po::value<bool>(&m_showSchema)->zero_tokens()->implicit_value(true),
"dump the schema")
("metadata,m",
po::value<bool>(&m_showMetadata)->zero_tokens()->implicit_value(true),
"dump the metadata")
("sdo_pc",
po::value<bool>(&m_showSDOPCMetadata)->zero_tokens()->
implicit_value(true),
"dump the SDO_PC Oracle Metadata")
("stage,r",
po::value<bool>(&m_showStage)->zero_tokens()->implicit_value(true),
"dump the stage info")
("pipeline-serialization",
po::value<std::string>(&m_pipelineFile)->default_value(""), "")
("xml", po::value<bool>(&m_useXML)->zero_tokens()->implicit_value(true),
"dump XML")
("json",
po::value<bool>(&m_useJSON)->zero_tokens()->implicit_value(true),
"dump JSON")
("sample",
po::value<bool>(&m_showSample)->zero_tokens()->implicit_value(true),
"randomly sample dimension for stats")
("seed", po::value<uint32_t>(&m_seed)->default_value(0),
"Seed value for random sample")
("sample_size",
po::value<uint32_t>(&m_sample_size)->default_value(1000),
"Sample size for random sample")
;
addSwitchSet(processing_options);
addPositionalSwitch("input", 1);
}
// Support for parsing point numbers. Points can be specified singly or as
// dash-separated ranges. i.e. 6-7,8,19-20
namespace {
using namespace std;
vector<string> tokenize(const string s, char c)
{
string::const_iterator begin;
string::const_iterator end;
vector<string> strings;
begin = s.begin();
while (true)
{
end = find(begin, s.end(), c);
strings.push_back(string(begin, end));
if (end == s.end())
break;
begin = end + 1;
}
return strings;
}
uint32_t parseInt(const string& s)
{
try
{
return boost::lexical_cast<uint32_t>(s);
}
catch (boost::bad_lexical_cast)
{
throw app_runtime_error(string("Invalid integer: ") + s);
}
}
void addSingle(const string& s, vector<uint32_t>& points)
{
points.push_back(parseInt(s));
}
void addRange(const string& begin, const string& end,
vector<uint32_t>& points)
{
uint32_t low = parseInt(begin);
uint32_t high = parseInt(end);
if (low > high)
throw app_runtime_error(string("Range invalid: ") + begin + "-" + end);
while (low <= high)
points.push_back(low++);
}
vector<boost::uint32_t> getListOfPoints(std::string p)
{
vector<boost::uint32_t> output;
//Remove whitespace from string with awful remove/erase idiom.
p.erase(remove_if(p.begin(), p.end(), ::isspace), p.end());
vector<string> ranges = tokenize(p, ',');
for (string s : ranges)
{
vector<string> limits = tokenize(s, '-');
if (limits.size() == 1)
addSingle(limits[0], output);
else if (limits.size() == 2)
addRange(limits[0], limits[1], output);
else
throw app_runtime_error(string("Invalid point range: ") + s);
}
return output;
}
} //namespace
void Info::dumpPoints(PointBufferPtr buf) const
{
PointBufferPtr outbuf = buf->makeNew();
std::vector<uint32_t> points = getListOfPoints(m_pointIndexes);
for (size_t i = 0; i < points.size(); ++i)
{
PointId id = (PointId)points[i];
if (id < buf->size())
outbuf->appendPoint(*buf, id);
}
boost::property_tree::ptree buffer_tree = pdal::utils::toPTree(*outbuf);
for (size_t i = 0; i < outbuf->size(); ++i)
{
std::string name = (std::string)"point " +
boost::lexical_cast<std::string>(points[i]);
std::string key = boost::lexical_cast<std::string>(i);
m_tree->add_child(name, buffer_tree.get_child(key));
}
}
void Info::dumpStats()
{
PipelineWriter* writer = NULL;
if (m_pipelineFile.size() > 0)
writer = new pdal::PipelineWriter(*m_manager);
MetadataNode statsNode("stats");
statsNode.add(m_manager->getMetadata());
boost::property_tree::ptree stats;
std::stringstream strm;
strm << statsNode.toJSON();
boost::property_tree::read_json(strm, stats);
m_tree->add_child("stats", stats);
if (m_pipelineFile.size() > 0)
writer->writePipeline(m_pipelineFile);
delete writer;
}
void Info::dump(PointContext ctx, PointBufferPtr buf)
{
if (m_showStats)
{
dumpStats();
}
if (m_pointIndexes.size())
{
dumpPoints(buf);
}
if (m_showSchema)
{
boost::property_tree::ptree dims(pdal::utils::toPTree(ctx));
m_tree->add_child("schema", dims);
}
if (m_showSDOPCMetadata)
{
boost::property_tree::ptree metadata =
m_manager->getStage()->serializePipeline();
boost::property_tree::ptree output;
m_tree->add_child("stage", output);
}
if (m_QueryPoint.size())
{
dumpQuery(buf);
}
}
void Info::dumpQuery(PointBufferPtr buf) const
{
#define SEPARATORS ",| "
boost::char_separator<char> sep(SEPARATORS);
tokenizer tokens(m_QueryPoint, sep);
std::vector<double> values;
for (tokenizer::iterator t = tokens.begin(); t != tokens.end(); ++t)
values.push_back(boost::lexical_cast<double>(*t));
if (values.size() != 2 && values.size() != 3)
throw app_runtime_error("--points must be two or three values");
bool is3d = (values.size() >= 3);
double x = values[0];
double y = values[1];
double z = is3d ? values[2] : 0.0;
PointBufferPtr outbuf = buf->makeNew();
KDIndex kdi(*buf);
kdi.build(is3d);
std::vector<size_t> ids = kdi.neighbors(x, y, z, 0.0, buf->size());
for (auto i = ids.begin(); i != ids.end(); ++i)
outbuf->appendPoint(*buf, *i);
boost::property_tree::ptree tree = pdal::utils::toPTree(*outbuf);
m_tree->add_child("point", tree);
}
void Info::dumpSDO_PCMetadata(PointContext ctx, const Stage& stage) const
{
std::ostream& ostr = std::cout;
// std::string xml = pdal::Schema::to_xml(*ctx.schema(), stage.getMetadata());
// ostr << xml;
}
void Info::dumpMetadata(PointContext ctx, const Stage& stage) const
{
boost::property_tree::ptree tree = stage.serializePipeline();
std::ostream& ostr = std::cout;
if (m_useXML)
write_xml(ostr, tree);
else
write_json(ostr, tree);
}
int Info::execute()
{
Options readerOptions;
{
if (m_usestdin)
m_inputFile = "STDIN";
readerOptions.add<std::string>("filename", m_inputFile);
readerOptions.add<bool>("debug", isDebug());
readerOptions.add<uint32_t>("verbose", getVerboseLevel());
}
m_manager = std::unique_ptr<PipelineManager>(
AppSupport::makePipeline(readerOptions));
if (m_seed != 0)
{
Option seed_option("seed", m_seed, "seed value");
m_options.add(seed_option);
}
m_options.add("sample_size", m_sample_size,
"sample size for random sample");
m_options.add("exact_count", "Classification",
"use exact counts for classification stats");
m_options.add("exact_count", "ReturnNumber",
"use exact counts for ReturnNumber stats");
m_options.add("exact_count", "NumberOfReturns",
"use exact counts for ReturnNumber stats");
m_options.add("do_sample", m_showSample, "Don't do sampling");
if (m_Dimensions.size())
m_options.add("dimensions", m_Dimensions,
"Use explicit list of dimensions");
Options options = m_options + readerOptions;
Stage* stage = m_manager->getStage();
if (m_showStats)
stage = m_manager->addFilter("filters.stats", stage, options);
if (m_computeBoundary)
stage = m_manager->addFilter("filters.hexbin", stage, options);
m_tree = std::unique_ptr<boost::property_tree::ptree>(
new boost::property_tree::ptree);
std::ostream& ostr = std::cout;
m_manager->execute();
PointBufferSet pbSet = m_manager->buffers();
assert(pbSet.size() == 1);
dump(m_manager->context(), *pbSet.begin());
//
// if (m_showStats)
// dumpStats(ctx, *dynamic_cast<pdal::filters::Stats*>(filter), manager);
// if (m_showSchema)
// dumpSchema(ctx);
// if (m_showMetadata)
// dumpMetadata(ctx, *filter);
// if (m_showStage)
// dumpStage(*filter);
// if (m_showSDOPCMetadata)
// dumpSDO_PCMetadata(ctx, *filter);
//
// if (m_QueryPoint.size())
// dumpQuery(ctx, *filter);
if (m_useXML)
write_xml(ostr, *m_tree);
else
write_json(ostr, *m_tree);
return 0;
}
}} // pdal::kernel
<|endoftext|> |
<commit_before>#include "keytar.h"
#include <gnome-keyring.h>
namespace keytar {
namespace {
const GnomeKeyringPasswordSchema kGnomeSchema = {
GNOME_KEYRING_ITEM_GENERIC_SECRET, {
{ "service", GNOME_KEYRING_ATTRIBUTE_TYPE_STRING },
{ "account", GNOME_KEYRING_ATTRIBUTE_TYPE_STRING },
{ NULL }
}
};
} // namespace
bool AddPassword(const std::string& service,
const std::string& account,
const std::string& password) {
return gnome_keyring_store_password_sync(
&kGnomeSchema,
NULL, // Default keyring.
(service + "/" + account).c_str(), // Display name.
password.c_str(),
"service", service.c_str(),
"account", account.c_str(),
NULL) == GNOME_KEYRING_RESULT_OK;
}
bool GetPassword(const std::string& service,
const std::string& account,
std::string* password) {
gchar* raw_passwords;
GnomeKeyringResult result = gnome_keyring_find_password_sync(
&kGnomeSchema,
&raw_passwords,
"service", service.c_str(),
"account", account.c_str(),
NULL);
if (result != GNOME_KEYRING_RESULT_OK)
return false;
if (raw_passwords != NULL)
*password = raw_passwords;
gnome_keyring_free_password(raw_passwords);
return true;
}
bool DeletePassword(const std::string& service, const std::string& account) {
return gnome_keyring_delete_password_sync(
&kGnomeSchema,
"service", service.c_str(),
"account", account.c_str(),
NULL) == GNOME_KEYRING_RESULT_OK;
}
bool FindPassword(const std::string& service, std::string* password) {
gchar* raw_passwords;
GnomeKeyringResult result = gnome_keyring_find_password_sync(
&kGnomeSchema,
&raw_passwords,
"service", service.c_str(),
NULL);
if (result != GNOME_KEYRING_RESULT_OK)
return false;
if (raw_passwords != NULL)
*password = raw_passwords;
gnome_keyring_free_password(raw_passwords);
return true;
}
} // namespace keytar
<commit_msg>Print error message.<commit_after>#include "keytar.h"
#include <gnome-keyring.h>
#include <stdio.h>
namespace keytar {
namespace {
const GnomeKeyringPasswordSchema kGnomeSchema = {
GNOME_KEYRING_ITEM_GENERIC_SECRET, {
{ "service", GNOME_KEYRING_ATTRIBUTE_TYPE_STRING },
{ "account", GNOME_KEYRING_ATTRIBUTE_TYPE_STRING },
{ NULL }
}
};
void PrintError(const gchar* where, GnomeKeyringResult result) {
if (result != GNOME_KEYRING_RESULT_OK)
fprintf(stderr, "%s: %s\n", where, gnome_keyring_result_to_message(result));
}
} // namespace
bool AddPassword(const std::string& service,
const std::string& account,
const std::string& password) {
GnomeKeyringResult result = gnome_keyring_store_password_sync(
&kGnomeSchema,
NULL, // Default keyring.
(service + "/" + account).c_str(), // Display name.
password.c_str(),
"service", service.c_str(),
"account", account.c_str(),
NULL);
PrintError("AddPassword", result);
return result == GNOME_KEYRING_RESULT_OK;
}
bool GetPassword(const std::string& service,
const std::string& account,
std::string* password) {
gchar* raw_passwords;
GnomeKeyringResult result = gnome_keyring_find_password_sync(
&kGnomeSchema,
&raw_passwords,
"service", service.c_str(),
"account", account.c_str(),
NULL);
PrintError("GetPassword", result);
if (result != GNOME_KEYRING_RESULT_OK)
return false;
if (raw_passwords != NULL)
*password = raw_passwords;
gnome_keyring_free_password(raw_passwords);
return true;
}
bool DeletePassword(const std::string& service, const std::string& account) {
return gnome_keyring_delete_password_sync(
&kGnomeSchema,
"service", service.c_str(),
"account", account.c_str(),
NULL) == GNOME_KEYRING_RESULT_OK;
}
bool FindPassword(const std::string& service, std::string* password) {
gchar* raw_passwords;
GnomeKeyringResult result = gnome_keyring_find_password_sync(
&kGnomeSchema,
&raw_passwords,
"service", service.c_str(),
NULL);
PrintError("FindPassword", result);
if (result != GNOME_KEYRING_RESULT_OK)
return false;
if (raw_passwords != NULL)
*password = raw_passwords;
gnome_keyring_free_password(raw_passwords);
return true;
}
} // namespace keytar
<|endoftext|> |
<commit_before>//== MemRegion.cpp - Abstract memory regions for static analysis --*- C++ -*--//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines MemRegion and its subclasses. MemRegion defines a
// partially-typed abstraction of memory useful for path-sensitive dataflow
// analyses.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/raw_ostream.h"
#include "clang/Analysis/PathSensitive/MemRegion.h"
using namespace clang;
//===----------------------------------------------------------------------===//
// Basic methods.
//===----------------------------------------------------------------------===//
MemRegion::~MemRegion() {}
bool SubRegion::isSubRegionOf(const MemRegion* R) const {
const MemRegion* r = getSuperRegion();
while (r != 0) {
if (r == R)
return true;
if (const SubRegion* sr = dyn_cast<SubRegion>(r))
r = sr->getSuperRegion();
else
break;
}
return false;
}
MemRegionManager* SubRegion::getMemRegionManager() const {
const SubRegion* r = this;
do {
const MemRegion *superRegion = r->getSuperRegion();
if (const SubRegion *sr = dyn_cast<SubRegion>(superRegion)) {
r = sr;
continue;
}
return superRegion->getMemRegionManager();
} while (1);
}
void MemSpaceRegion::Profile(llvm::FoldingSetNodeID& ID) const {
ID.AddInteger((unsigned)getKind());
}
void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
const StringLiteral* Str,
const MemRegion* superRegion) {
ID.AddInteger((unsigned) StringRegionKind);
ID.AddPointer(Str);
ID.AddPointer(superRegion);
}
void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
const Expr* Ex, unsigned cnt,
const MemRegion *) {
ID.AddInteger((unsigned) AllocaRegionKind);
ID.AddPointer(Ex);
ID.AddInteger(cnt);
}
void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
ProfileRegion(ID, Ex, Cnt, superRegion);
}
void TypedViewRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, QualType T,
const MemRegion* superRegion) {
ID.AddInteger((unsigned) TypedViewRegionKind);
ID.Add(T);
ID.AddPointer(superRegion);
}
void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
}
void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
const CompoundLiteralExpr* CL,
const MemRegion* superRegion) {
ID.AddInteger((unsigned) CompoundLiteralRegionKind);
ID.AddPointer(CL);
ID.AddPointer(superRegion);
}
void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl* D,
const MemRegion* superRegion, Kind k) {
ID.AddInteger((unsigned) k);
ID.AddPointer(D);
ID.AddPointer(superRegion);
}
void DeclRegion::Profile(llvm::FoldingSetNodeID& ID) const {
DeclRegion::ProfileRegion(ID, D, superRegion, getKind());
}
void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
const MemRegion *sreg) {
ID.AddInteger((unsigned) MemRegion::SymbolicRegionKind);
ID.Add(sym);
ID.AddPointer(sreg);
}
void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
}
void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
QualType ElementType, SVal Idx,
const MemRegion* superRegion) {
ID.AddInteger(MemRegion::ElementRegionKind);
ID.Add(ElementType);
ID.AddPointer(superRegion);
Idx.Profile(ID);
}
void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
}
void CodeTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const void* data,
QualType t, const MemRegion*) {
ID.AddInteger(MemRegion::CodeTextRegionKind);
ID.AddPointer(data);
ID.Add(t);
}
void CodeTextRegion::Profile(llvm::FoldingSetNodeID& ID) const {
CodeTextRegion::ProfileRegion(ID, Data, LocationType, superRegion);
}
//===----------------------------------------------------------------------===//
// Region pretty-printing.
//===----------------------------------------------------------------------===//
void MemRegion::dump() const {
dumpToStream(llvm::errs());
}
std::string MemRegion::getString() const {
std::string s;
llvm::raw_string_ostream os(s);
dumpToStream(os);
return os.str();
}
void MemRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "<Unknown Region>";
}
void AllocaRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "alloca{" << (void*) Ex << ',' << Cnt << '}';
}
void CodeTextRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "code{";
if (isDeclared())
os << getDecl()->getDeclName().getAsString();
else
os << '$' << getSymbol();
os << '}';
}
void CompoundLiteralRegion::dumpToStream(llvm::raw_ostream& os) const {
// FIXME: More elaborate pretty-printing.
os << "{ " << (void*) CL << " }";
}
void ElementRegion::dumpToStream(llvm::raw_ostream& os) const {
os << superRegion << '['; Index.print(os); os << ']';
}
void FieldRegion::dumpToStream(llvm::raw_ostream& os) const {
os << superRegion << "->" << getDecl()->getNameAsString();
}
void StringRegion::dumpToStream(llvm::raw_ostream& os) const {
LangOptions LO; // FIXME.
Str->printPretty(os, 0, PrintingPolicy(LO));
}
void SymbolicRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "SymRegion-" << sym;
}
void TypedViewRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "typed_view{" << LValueType.getAsString() << ','
<< getSuperRegion() << '}';
}
void VarRegion::dumpToStream(llvm::raw_ostream& os) const {
os << cast<VarDecl>(D)->getNameAsString();
}
//===----------------------------------------------------------------------===//
// MemRegionManager methods.
//===----------------------------------------------------------------------===//
MemSpaceRegion* MemRegionManager::LazyAllocate(MemSpaceRegion*& region) {
if (!region) {
region = (MemSpaceRegion*) A.Allocate<MemSpaceRegion>();
new (region) MemSpaceRegion(this);
}
return region;
}
MemSpaceRegion* MemRegionManager::getStackRegion() {
return LazyAllocate(stack);
}
MemSpaceRegion* MemRegionManager::getStackArgumentsRegion() {
return LazyAllocate(stackArguments);
}
MemSpaceRegion* MemRegionManager::getGlobalsRegion() {
return LazyAllocate(globals);
}
MemSpaceRegion* MemRegionManager::getHeapRegion() {
return LazyAllocate(heap);
}
MemSpaceRegion* MemRegionManager::getUnknownRegion() {
return LazyAllocate(unknown);
}
MemSpaceRegion* MemRegionManager::getCodeRegion() {
return LazyAllocate(code);
}
//===----------------------------------------------------------------------===//
// Constructing regions.
//===----------------------------------------------------------------------===//
StringRegion* MemRegionManager::getStringRegion(const StringLiteral* Str) {
return getRegion<StringRegion>(Str);
}
VarRegion* MemRegionManager::getVarRegion(const VarDecl* d) {
return getRegion<VarRegion>(d);
}
CompoundLiteralRegion*
MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr* CL) {
return getRegion<CompoundLiteralRegion>(CL);
}
ElementRegion*
MemRegionManager::getElementRegion(QualType elementType, SVal Idx,
const MemRegion* superRegion, ASTContext& Ctx){
QualType T = Ctx.getCanonicalType(elementType);
llvm::FoldingSetNodeID ID;
ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
void* InsertPos;
MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
ElementRegion* R = cast_or_null<ElementRegion>(data);
if (!R) {
R = (ElementRegion*) A.Allocate<ElementRegion>();
new (R) ElementRegion(T, Idx, superRegion);
Regions.InsertNode(R, InsertPos);
}
return R;
}
CodeTextRegion* MemRegionManager::getCodeTextRegion(const FunctionDecl* fd,
QualType t) {
return getRegion<CodeTextRegion>(fd, t);
}
CodeTextRegion* MemRegionManager::getCodeTextRegion(SymbolRef sym, QualType t) {
return getRegion<CodeTextRegion>(sym, t);
}
/// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
SymbolicRegion* MemRegionManager::getSymbolicRegion(SymbolRef sym) {
return getRegion<SymbolicRegion>(sym);
}
FieldRegion* MemRegionManager::getFieldRegion(const FieldDecl* d,
const MemRegion* superRegion) {
return getSubRegion<FieldRegion>(d, superRegion);
}
ObjCIvarRegion*
MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl* d,
const MemRegion* superRegion) {
return getSubRegion<ObjCIvarRegion>(d, superRegion);
}
ObjCObjectRegion*
MemRegionManager::getObjCObjectRegion(const ObjCInterfaceDecl* d,
const MemRegion* superRegion) {
return getSubRegion<ObjCObjectRegion>(d, superRegion);
}
TypedViewRegion*
MemRegionManager::getTypedViewRegion(QualType t, const MemRegion* superRegion) {
return getSubRegion<TypedViewRegion>(t, superRegion);
}
AllocaRegion* MemRegionManager::getAllocaRegion(const Expr* E, unsigned cnt) {
return getRegion<AllocaRegion>(E, cnt);
}
const MemSpaceRegion *MemRegion::getMemorySpace() const {
const MemRegion *R = this;
const SubRegion* SR = dyn_cast<SubRegion>(this);
while (SR) {
R = SR->getSuperRegion();
SR = dyn_cast<SubRegion>(R);
}
return dyn_cast<MemSpaceRegion>(R);
}
bool MemRegion::hasStackStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace()) {
MemRegionManager *Mgr = getMemRegionManager();
return MS == Mgr->getStackRegion() || MS == Mgr->getStackArgumentsRegion();
}
return false;
}
bool MemRegion::hasHeapStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace())
return MS == getMemRegionManager()->getHeapRegion();
return false;
}
bool MemRegion::hasHeapOrStackStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace()) {
MemRegionManager *Mgr = getMemRegionManager();
return MS == Mgr->getHeapRegion()
|| MS == Mgr->getStackRegion()
|| MS == Mgr->getStackArgumentsRegion();
}
return false;
}
bool MemRegion::hasGlobalsStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace())
return MS == getMemRegionManager()->getGlobalsRegion();
return false;
}
bool MemRegion::hasParametersStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace())
return MS == getMemRegionManager()->getStackArgumentsRegion();
return false;
}
bool MemRegion::hasGlobalsOrParametersStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace()) {
MemRegionManager *Mgr = getMemRegionManager();
return MS == Mgr->getGlobalsRegion()
|| MS == Mgr->getStackArgumentsRegion();
}
return false;
}
//===----------------------------------------------------------------------===//
// View handling.
//===----------------------------------------------------------------------===//
const MemRegion *TypedViewRegion::removeViews() const {
const SubRegion *SR = this;
const MemRegion *R = SR;
while (SR && isa<TypedViewRegion>(SR)) {
R = SR->getSuperRegion();
SR = dyn_cast<SubRegion>(R);
}
return R;
}
<commit_msg>When pretty-printing symbolic regions, use '{' ... '}' to indicate the symbol used for the region (makes it easier to read for nested regions).<commit_after>//== MemRegion.cpp - Abstract memory regions for static analysis --*- C++ -*--//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines MemRegion and its subclasses. MemRegion defines a
// partially-typed abstraction of memory useful for path-sensitive dataflow
// analyses.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/raw_ostream.h"
#include "clang/Analysis/PathSensitive/MemRegion.h"
using namespace clang;
//===----------------------------------------------------------------------===//
// Basic methods.
//===----------------------------------------------------------------------===//
MemRegion::~MemRegion() {}
bool SubRegion::isSubRegionOf(const MemRegion* R) const {
const MemRegion* r = getSuperRegion();
while (r != 0) {
if (r == R)
return true;
if (const SubRegion* sr = dyn_cast<SubRegion>(r))
r = sr->getSuperRegion();
else
break;
}
return false;
}
MemRegionManager* SubRegion::getMemRegionManager() const {
const SubRegion* r = this;
do {
const MemRegion *superRegion = r->getSuperRegion();
if (const SubRegion *sr = dyn_cast<SubRegion>(superRegion)) {
r = sr;
continue;
}
return superRegion->getMemRegionManager();
} while (1);
}
void MemSpaceRegion::Profile(llvm::FoldingSetNodeID& ID) const {
ID.AddInteger((unsigned)getKind());
}
void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
const StringLiteral* Str,
const MemRegion* superRegion) {
ID.AddInteger((unsigned) StringRegionKind);
ID.AddPointer(Str);
ID.AddPointer(superRegion);
}
void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
const Expr* Ex, unsigned cnt,
const MemRegion *) {
ID.AddInteger((unsigned) AllocaRegionKind);
ID.AddPointer(Ex);
ID.AddInteger(cnt);
}
void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
ProfileRegion(ID, Ex, Cnt, superRegion);
}
void TypedViewRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, QualType T,
const MemRegion* superRegion) {
ID.AddInteger((unsigned) TypedViewRegionKind);
ID.Add(T);
ID.AddPointer(superRegion);
}
void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
}
void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
const CompoundLiteralExpr* CL,
const MemRegion* superRegion) {
ID.AddInteger((unsigned) CompoundLiteralRegionKind);
ID.AddPointer(CL);
ID.AddPointer(superRegion);
}
void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl* D,
const MemRegion* superRegion, Kind k) {
ID.AddInteger((unsigned) k);
ID.AddPointer(D);
ID.AddPointer(superRegion);
}
void DeclRegion::Profile(llvm::FoldingSetNodeID& ID) const {
DeclRegion::ProfileRegion(ID, D, superRegion, getKind());
}
void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
const MemRegion *sreg) {
ID.AddInteger((unsigned) MemRegion::SymbolicRegionKind);
ID.Add(sym);
ID.AddPointer(sreg);
}
void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
}
void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
QualType ElementType, SVal Idx,
const MemRegion* superRegion) {
ID.AddInteger(MemRegion::ElementRegionKind);
ID.Add(ElementType);
ID.AddPointer(superRegion);
Idx.Profile(ID);
}
void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
}
void CodeTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const void* data,
QualType t, const MemRegion*) {
ID.AddInteger(MemRegion::CodeTextRegionKind);
ID.AddPointer(data);
ID.Add(t);
}
void CodeTextRegion::Profile(llvm::FoldingSetNodeID& ID) const {
CodeTextRegion::ProfileRegion(ID, Data, LocationType, superRegion);
}
//===----------------------------------------------------------------------===//
// Region pretty-printing.
//===----------------------------------------------------------------------===//
void MemRegion::dump() const {
dumpToStream(llvm::errs());
}
std::string MemRegion::getString() const {
std::string s;
llvm::raw_string_ostream os(s);
dumpToStream(os);
return os.str();
}
void MemRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "<Unknown Region>";
}
void AllocaRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "alloca{" << (void*) Ex << ',' << Cnt << '}';
}
void CodeTextRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "code{";
if (isDeclared())
os << getDecl()->getDeclName().getAsString();
else
os << '$' << getSymbol();
os << '}';
}
void CompoundLiteralRegion::dumpToStream(llvm::raw_ostream& os) const {
// FIXME: More elaborate pretty-printing.
os << "{ " << (void*) CL << " }";
}
void ElementRegion::dumpToStream(llvm::raw_ostream& os) const {
os << superRegion << '['; Index.print(os); os << ']';
}
void FieldRegion::dumpToStream(llvm::raw_ostream& os) const {
os << superRegion << "->" << getDecl()->getNameAsString();
}
void StringRegion::dumpToStream(llvm::raw_ostream& os) const {
LangOptions LO; // FIXME.
Str->printPretty(os, 0, PrintingPolicy(LO));
}
void SymbolicRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "SymRegion{" << sym << '}';
}
void TypedViewRegion::dumpToStream(llvm::raw_ostream& os) const {
os << "typed_view{" << LValueType.getAsString() << ','
<< getSuperRegion() << '}';
}
void VarRegion::dumpToStream(llvm::raw_ostream& os) const {
os << cast<VarDecl>(D)->getNameAsString();
}
//===----------------------------------------------------------------------===//
// MemRegionManager methods.
//===----------------------------------------------------------------------===//
MemSpaceRegion* MemRegionManager::LazyAllocate(MemSpaceRegion*& region) {
if (!region) {
region = (MemSpaceRegion*) A.Allocate<MemSpaceRegion>();
new (region) MemSpaceRegion(this);
}
return region;
}
MemSpaceRegion* MemRegionManager::getStackRegion() {
return LazyAllocate(stack);
}
MemSpaceRegion* MemRegionManager::getStackArgumentsRegion() {
return LazyAllocate(stackArguments);
}
MemSpaceRegion* MemRegionManager::getGlobalsRegion() {
return LazyAllocate(globals);
}
MemSpaceRegion* MemRegionManager::getHeapRegion() {
return LazyAllocate(heap);
}
MemSpaceRegion* MemRegionManager::getUnknownRegion() {
return LazyAllocate(unknown);
}
MemSpaceRegion* MemRegionManager::getCodeRegion() {
return LazyAllocate(code);
}
//===----------------------------------------------------------------------===//
// Constructing regions.
//===----------------------------------------------------------------------===//
StringRegion* MemRegionManager::getStringRegion(const StringLiteral* Str) {
return getRegion<StringRegion>(Str);
}
VarRegion* MemRegionManager::getVarRegion(const VarDecl* d) {
return getRegion<VarRegion>(d);
}
CompoundLiteralRegion*
MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr* CL) {
return getRegion<CompoundLiteralRegion>(CL);
}
ElementRegion*
MemRegionManager::getElementRegion(QualType elementType, SVal Idx,
const MemRegion* superRegion, ASTContext& Ctx){
QualType T = Ctx.getCanonicalType(elementType);
llvm::FoldingSetNodeID ID;
ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
void* InsertPos;
MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
ElementRegion* R = cast_or_null<ElementRegion>(data);
if (!R) {
R = (ElementRegion*) A.Allocate<ElementRegion>();
new (R) ElementRegion(T, Idx, superRegion);
Regions.InsertNode(R, InsertPos);
}
return R;
}
CodeTextRegion* MemRegionManager::getCodeTextRegion(const FunctionDecl* fd,
QualType t) {
return getRegion<CodeTextRegion>(fd, t);
}
CodeTextRegion* MemRegionManager::getCodeTextRegion(SymbolRef sym, QualType t) {
return getRegion<CodeTextRegion>(sym, t);
}
/// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
SymbolicRegion* MemRegionManager::getSymbolicRegion(SymbolRef sym) {
return getRegion<SymbolicRegion>(sym);
}
FieldRegion* MemRegionManager::getFieldRegion(const FieldDecl* d,
const MemRegion* superRegion) {
return getSubRegion<FieldRegion>(d, superRegion);
}
ObjCIvarRegion*
MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl* d,
const MemRegion* superRegion) {
return getSubRegion<ObjCIvarRegion>(d, superRegion);
}
ObjCObjectRegion*
MemRegionManager::getObjCObjectRegion(const ObjCInterfaceDecl* d,
const MemRegion* superRegion) {
return getSubRegion<ObjCObjectRegion>(d, superRegion);
}
TypedViewRegion*
MemRegionManager::getTypedViewRegion(QualType t, const MemRegion* superRegion) {
return getSubRegion<TypedViewRegion>(t, superRegion);
}
AllocaRegion* MemRegionManager::getAllocaRegion(const Expr* E, unsigned cnt) {
return getRegion<AllocaRegion>(E, cnt);
}
const MemSpaceRegion *MemRegion::getMemorySpace() const {
const MemRegion *R = this;
const SubRegion* SR = dyn_cast<SubRegion>(this);
while (SR) {
R = SR->getSuperRegion();
SR = dyn_cast<SubRegion>(R);
}
return dyn_cast<MemSpaceRegion>(R);
}
bool MemRegion::hasStackStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace()) {
MemRegionManager *Mgr = getMemRegionManager();
return MS == Mgr->getStackRegion() || MS == Mgr->getStackArgumentsRegion();
}
return false;
}
bool MemRegion::hasHeapStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace())
return MS == getMemRegionManager()->getHeapRegion();
return false;
}
bool MemRegion::hasHeapOrStackStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace()) {
MemRegionManager *Mgr = getMemRegionManager();
return MS == Mgr->getHeapRegion()
|| MS == Mgr->getStackRegion()
|| MS == Mgr->getStackArgumentsRegion();
}
return false;
}
bool MemRegion::hasGlobalsStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace())
return MS == getMemRegionManager()->getGlobalsRegion();
return false;
}
bool MemRegion::hasParametersStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace())
return MS == getMemRegionManager()->getStackArgumentsRegion();
return false;
}
bool MemRegion::hasGlobalsOrParametersStorage() const {
if (const MemSpaceRegion *MS = getMemorySpace()) {
MemRegionManager *Mgr = getMemRegionManager();
return MS == Mgr->getGlobalsRegion()
|| MS == Mgr->getStackArgumentsRegion();
}
return false;
}
//===----------------------------------------------------------------------===//
// View handling.
//===----------------------------------------------------------------------===//
const MemRegion *TypedViewRegion::removeViews() const {
const SubRegion *SR = this;
const MemRegion *R = SR;
while (SR && isa<TypedViewRegion>(SR)) {
R = SR->getSuperRegion();
SR = dyn_cast<SubRegion>(R);
}
return R;
}
<|endoftext|> |
<commit_before>/* cis_splice_effects_identifier.cc -- 'cis-splice-effects identify' methods
Copyright (c) 2015, The Griffith Lab
Author: Avinash Ramu <[email protected]>
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 <stdexcept>
#include <set>
#include "common.h"
#include "cis_splice_effects_identifier.h"
#include "junctions_annotator.h"
#include "junctions_extractor.h"
#include "variants_annotator.h"
//Usage for this tool
void CisSpliceEffectsIdentifier::usage(ostream& out) {
out << "\nUsage:\t\t"
<< "regtools cis-splice-effects identify [options] variants.vcf"
<< " alignments.bam ref.fa annotations.gtf";
out << "\nOptions:";
out << "\t" << "-o STR Output file containing the aberrant splice junctions. [STDOUT]";
out << "\n\t\t" << "-v STR Output file containing variants annotated as splice relevant (VCF format).";
out << "\n\t\t" << "-w INT \tWindow size in b.p to identify splicing events in. "
<< "\n\t\t\t" << "The tool identifies events in variant.start +/- w basepairs."
<< "\n\t\t\t" << "Default behaviour is to look at the window between previous and next exons.";
out << "\n";
}
//Return stream to write output to
void CisSpliceEffectsIdentifier::close_ostream() {
if(ofs_.is_open())
ofs_.close();
}
//Return stream to write output to
//If output file is not empty, attempt to open
//If output file is empty, set to cout
void CisSpliceEffectsIdentifier::set_ostream() {
if(output_file_ == "NA") {
common::copy_stream(cout, ofs_);
return;
}
ofs_.open(output_file_.c_str());
if(!ofs_.is_open())
throw runtime_error("Unable to open " +
output_file_);
if(output_junctions_bed_ != "NA") {
ofs_junctions_bed_.open(output_junctions_bed_.c_str());
if(!ofs_junctions_bed_.is_open())
throw runtime_error("Unable to open " +
output_junctions_bed_);
}
}
//Do QC on files
void CisSpliceEffectsIdentifier::file_qc() {
if(vcf_ == "NA" || bam_ == "NA" ||
ref_ == "NA" || gtf_ == "NA") {
usage(std::cout);
throw runtime_error("\nError parsing inputs!(2)\n");
}
if(!common::file_exists(vcf_) || !common::file_exists(bam_) ||
!common::file_exists(ref_) || !common::file_exists(gtf_)) {
throw runtime_error("\nPlease make sure input files exist.\n");
}
}
//Parse command line options
void CisSpliceEffectsIdentifier::parse_options(int argc, char* argv[]) {
optind = 1; //Reset before parsing again.
stringstream help_ss;
char c;
while((c = getopt(argc, argv, "o:w:v:j:h")) != -1) {
switch(c) {
case 'o':
output_file_ = string(optarg);
break;
case 'w':
window_size_ = atoi(optarg);
break;
case 'v':
annotated_variant_file_ = string(optarg);
break;
case 'j':
output_junctions_bed_ = string(optarg);
break;
case 'h':
usage(help_ss);
throw common::cmdline_help_exception(help_ss.str());
default:
usage(std::cerr);
throw runtime_error("\nError parsing inputs!(1)");
}
}
if(argc - optind >= 4) {
vcf_ = string(argv[optind++]);
bam_ = string(argv[optind++]);
ref_ = string(argv[optind++]);
gtf_ = string(argv[optind++]);
}
if(optind < argc ||
vcf_ == "NA" ||
bam_ == "NA" ||
ref_ == "NA" ||
gtf_ == "NA"){
usage(std::cerr);
throw runtime_error("\nError parsing inputs!(2)\n");
}
file_qc();
cerr << "\nVariant file: " << vcf_;
cerr << "\nAlignment file: " << bam_;
cerr << "\nReference fasta file: " << ref_;
cerr << "\nAnnotation file: " << gtf_;
if(window_size_ != 0) {
cerr << "\nWindow size: " << window_size_;
}
if(output_file_ != "NA")
cerr << "\nOutput file: " << output_file_;
if(output_junctions_bed_ != "NA")
cerr << "\nOutput junctions BED file: " << output_junctions_bed_;
if(annotated_variant_file_ != "NA") {
cerr << "\nAnnotated variants file: " << annotated_variant_file_;
write_annotated_variants_ = true;
}
cerr << endl;
}
//Call the junctions annotator
void CisSpliceEffectsIdentifier::annotate_junctions(const GtfParser& gp1) {
JunctionsAnnotator ja1(ref_, gp1);
ja1.set_gtf_parser(gp1);
set_ostream();
//Annotate the junctions in the set and write to file
AnnotatedJunction::print_header(ofs_);
int i = 0;
//This is ugly, waiting to start using C++11/14
for (set<Junction>::iterator j1 = unique_junctions_.begin(); j1 != unique_junctions_.end(); j1++) {
Junction j = *j1;
AnnotatedJunction line(j);
ja1.get_splice_site(line);
ja1.annotate_junction_with_gtf(line);
if(line.anchor != "DA") {
if(output_junctions_bed_ != "NA") {
j.name = get_junction_name(++i);
j.print(ofs_junctions_bed_);
}
line.print(ofs_);
}
}
close_ostream();
}
//get name for the junction
string CisSpliceEffectsIdentifier::get_junction_name(int i) {
stringstream name_ss;
name_ss << "JUNC" << setfill('0') << setw(8) << i;
return name_ss.str();
}
//The workhorse
void CisSpliceEffectsIdentifier::identify() {
//GTF parser object
GtfParser gp1(gtf_);
gp1.load();
//variant annotator
VariantsAnnotator va(vcf_, gtf_, annotated_variant_file_);
va.open_vcf_in();
if(write_annotated_variants_)
va.open_vcf_out();
va.set_gtf_parser(gp1);
//Annotate each variant and pay attention to splicing related ones
while(va.read_next_record()) {
AnnotatedVariant v1 = va.annotate_record_with_transcripts();
if(v1.annotation != non_splice_region_annotation_string) {
string region_start = window_size_ ? common::num_to_str(v1.start - window_size_) :
common::num_to_str(v1.cis_effect_start);
string region_end = window_size_ ? common::num_to_str(v1.end + window_size_) :
common::num_to_str(v1.cis_effect_end);
string variant_region = v1.chrom + ":" + region_start + "-" + region_end;
cerr << "\n\nVariant " << v1;
cerr << "Variant region is " << variant_region;
if(write_annotated_variants_)
va.write_annotation_output(v1);
//Extract junctions near this variant
JunctionsExtractor je1(bam_, variant_region);
je1.identify_junctions_from_BAM();
vector<Junction> junctions = je1.get_all_junctions();
//Add all the junctions to the unique set
for (size_t i = 0; i < junctions.size(); i++) {
if(window_size_ == 0) {
if(junctions[i].start >= v1.cis_effect_start &&
junctions[i].end <= v1.cis_effect_end) {
unique_junctions_.insert(junctions[i]);
}
continue;
}
if(common::coordinate_diff(junctions[i].start, v1.start) < window_size_ &&
common::coordinate_diff(junctions[i].end, v1.start) <= window_size_) {
unique_junctions_.insert(junctions[i]);
}
}
}
}
annotate_junctions(gp1);
}
<commit_msg>Update csei usage<commit_after>/* cis_splice_effects_identifier.cc -- 'cis-splice-effects identify' methods
Copyright (c) 2015, The Griffith Lab
Author: Avinash Ramu <[email protected]>
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 <stdexcept>
#include <set>
#include "common.h"
#include "cis_splice_effects_identifier.h"
#include "junctions_annotator.h"
#include "junctions_extractor.h"
#include "variants_annotator.h"
//Usage for this tool
void CisSpliceEffectsIdentifier::usage(ostream& out) {
out << "\nUsage:\t\t"
<< "regtools cis-splice-effects identify [options] variants.vcf"
<< " alignments.bam ref.fa annotations.gtf";
out << "\nOptions:";
out << "\t" << "-o STR Output file containing the aberrant splice junctions with annotations. [STDOUT]";
out << "\n\t\t" << "-v STR Output file containing variants annotated as splice relevant (VCF format).";
out << "\n\t\t" << "-w INT\tWindow size in b.p to identify splicing events in. "
<< "\n\t\t\t" << "The tool identifies events in variant.start +/- w basepairs."
<< "\n\t\t\t" << "Default behaviour is to look at the window between previous and next exons.";
out << "\n\t\t" << "-j STR Output file containing the aberrant junctions in BED12 format.";
out << "\n";
}
//Return stream to write output to
void CisSpliceEffectsIdentifier::close_ostream() {
if(ofs_.is_open())
ofs_.close();
}
//Return stream to write output to
//If output file is not empty, attempt to open
//If output file is empty, set to cout
void CisSpliceEffectsIdentifier::set_ostream() {
if(output_file_ == "NA") {
common::copy_stream(cout, ofs_);
return;
}
ofs_.open(output_file_.c_str());
if(!ofs_.is_open())
throw runtime_error("Unable to open " +
output_file_);
if(output_junctions_bed_ != "NA") {
ofs_junctions_bed_.open(output_junctions_bed_.c_str());
if(!ofs_junctions_bed_.is_open())
throw runtime_error("Unable to open " +
output_junctions_bed_);
}
}
//Do QC on files
void CisSpliceEffectsIdentifier::file_qc() {
if(vcf_ == "NA" || bam_ == "NA" ||
ref_ == "NA" || gtf_ == "NA") {
usage(std::cout);
throw runtime_error("\nError parsing inputs!(2)\n");
}
if(!common::file_exists(vcf_) || !common::file_exists(bam_) ||
!common::file_exists(ref_) || !common::file_exists(gtf_)) {
throw runtime_error("\nPlease make sure input files exist.\n");
}
}
//Parse command line options
void CisSpliceEffectsIdentifier::parse_options(int argc, char* argv[]) {
optind = 1; //Reset before parsing again.
stringstream help_ss;
char c;
while((c = getopt(argc, argv, "o:w:v:j:h")) != -1) {
switch(c) {
case 'o':
output_file_ = string(optarg);
break;
case 'w':
window_size_ = atoi(optarg);
break;
case 'v':
annotated_variant_file_ = string(optarg);
break;
case 'j':
output_junctions_bed_ = string(optarg);
break;
case 'h':
usage(help_ss);
throw common::cmdline_help_exception(help_ss.str());
default:
usage(std::cerr);
throw runtime_error("\nError parsing inputs!(1)");
}
}
if(argc - optind >= 4) {
vcf_ = string(argv[optind++]);
bam_ = string(argv[optind++]);
ref_ = string(argv[optind++]);
gtf_ = string(argv[optind++]);
}
if(optind < argc ||
vcf_ == "NA" ||
bam_ == "NA" ||
ref_ == "NA" ||
gtf_ == "NA"){
usage(std::cerr);
throw runtime_error("\nError parsing inputs!(2)\n");
}
file_qc();
cerr << "\nVariant file: " << vcf_;
cerr << "\nAlignment file: " << bam_;
cerr << "\nReference fasta file: " << ref_;
cerr << "\nAnnotation file: " << gtf_;
if(window_size_ != 0) {
cerr << "\nWindow size: " << window_size_;
}
if(output_file_ != "NA")
cerr << "\nOutput file: " << output_file_;
if(output_junctions_bed_ != "NA")
cerr << "\nOutput junctions BED file: " << output_junctions_bed_;
if(annotated_variant_file_ != "NA") {
cerr << "\nAnnotated variants file: " << annotated_variant_file_;
write_annotated_variants_ = true;
}
cerr << endl;
}
//Call the junctions annotator
void CisSpliceEffectsIdentifier::annotate_junctions(const GtfParser& gp1) {
JunctionsAnnotator ja1(ref_, gp1);
ja1.set_gtf_parser(gp1);
set_ostream();
//Annotate the junctions in the set and write to file
AnnotatedJunction::print_header(ofs_);
int i = 0;
//This is ugly, waiting to start using C++11/14
for (set<Junction>::iterator j1 = unique_junctions_.begin(); j1 != unique_junctions_.end(); j1++) {
Junction j = *j1;
AnnotatedJunction line(j);
ja1.get_splice_site(line);
ja1.annotate_junction_with_gtf(line);
if(line.anchor != "DA") {
if(output_junctions_bed_ != "NA") {
j.name = get_junction_name(++i);
j.print(ofs_junctions_bed_);
}
line.print(ofs_);
}
}
close_ostream();
}
//get name for the junction
string CisSpliceEffectsIdentifier::get_junction_name(int i) {
stringstream name_ss;
name_ss << "JUNC" << setfill('0') << setw(8) << i;
return name_ss.str();
}
//The workhorse
void CisSpliceEffectsIdentifier::identify() {
//GTF parser object
GtfParser gp1(gtf_);
gp1.load();
//variant annotator
VariantsAnnotator va(vcf_, gtf_, annotated_variant_file_);
va.open_vcf_in();
if(write_annotated_variants_)
va.open_vcf_out();
va.set_gtf_parser(gp1);
//Annotate each variant and pay attention to splicing related ones
while(va.read_next_record()) {
AnnotatedVariant v1 = va.annotate_record_with_transcripts();
if(v1.annotation != non_splice_region_annotation_string) {
string region_start = window_size_ ? common::num_to_str(v1.start - window_size_) :
common::num_to_str(v1.cis_effect_start);
string region_end = window_size_ ? common::num_to_str(v1.end + window_size_) :
common::num_to_str(v1.cis_effect_end);
string variant_region = v1.chrom + ":" + region_start + "-" + region_end;
cerr << "\n\nVariant " << v1;
cerr << "Variant region is " << variant_region;
if(write_annotated_variants_)
va.write_annotation_output(v1);
//Extract junctions near this variant
JunctionsExtractor je1(bam_, variant_region);
je1.identify_junctions_from_BAM();
vector<Junction> junctions = je1.get_all_junctions();
//Add all the junctions to the unique set
for (size_t i = 0; i < junctions.size(); i++) {
if(window_size_ == 0) {
if(junctions[i].start >= v1.cis_effect_start &&
junctions[i].end <= v1.cis_effect_end) {
unique_junctions_.insert(junctions[i]);
}
continue;
}
if(common::coordinate_diff(junctions[i].start, v1.start) < window_size_ &&
common::coordinate_diff(junctions[i].end, v1.start) <= window_size_) {
unique_junctions_.insert(junctions[i]);
}
}
}
}
annotate_junctions(gp1);
}
<|endoftext|> |
<commit_before>#include <QtCore/QCoreApplication>
#include <QFile>
#include <QtDebug>
#include "qblowfish.h"
// Random key generated at http://www.random.org/bytes/
#define KEY_HEX "ea462947a76af8a50dba0ad01455c8c3"
int main(int argc, char *argv[])
{
Q_UNUSED(argc);
Q_UNUSED(argv);
QBlowfish bf(QByteArray::fromHex(KEY_HEX));
// Encrypt string
bf.setPaddingEnabled(true); // Enable padding to be able to encrypt an arbitrary length of bytes
QString clearText("Balderdash");
QByteArray cipherText = bf.encrypted(clearText.toUtf8());
qDebug() << "Encrypted ba (hex):" << cipherText.toHex();
// Encrypt a file
QFile clearFile("clearText.txt");
if (!clearFile.open(QFile::ReadOnly)) {
qFatal("Could not open clearText.txt for reading");
}
QFile encryptedFile("encrypted.dat");
if (!encryptedFile.open(QFile::WriteOnly)) {
qFatal("Could not open encrypted.dat for writing");
}
qint64 encryptedBytesWritten = 0;
while (!clearFile.atEnd()) {
QByteArray data = clearFile.read(8); // Let's process the file in 8-byte blocks (can use any multiple of 8)
bf.setPaddingEnabled((clearFile.size() - encryptedBytesWritten) <= 8); // Enable padding for the last block only
QByteArray encryptedData = bf.encrypted(data);
Q_ASSERT(encryptedData.size() == 8);
qint64 bytesWritten = encryptedFile.write(encryptedData);
encryptedBytesWritten += bytesWritten;
}
encryptedFile.close();
clearFile.close();
qDebug() << "Encrypted data written to encrypted.dat";
// Decrypt string
bf.setPaddingEnabled(true);
QByteArray decryptedBa = bf.decrypted(cipherText);
QString decryptedString = QString::fromUtf8(decryptedBa.constData(), decryptedBa.size());
qDebug() << "Decrypted string:" << decryptedString;
// Decrypt file
bf.setPaddingEnabled(false);
QFile encryptedFile2("encrypted.dat");
if (!encryptedFile2.open(QFile::ReadOnly)) {
qFatal("Could not open encrypted.dat for reading");
}
QFile decryptedFile("decrypted.txt");
if (!decryptedFile.open(QFile::WriteOnly)) {
qFatal("Could not open decrypted.txt for writing");
}
qint64 decryptedBytesWritten = 0;
while (!encryptedFile2.atEnd()) {
QByteArray data = encryptedFile2.read(8); // Let's process the file in 8-byte blocks (can use any multiple of 8)
bf.setPaddingEnabled((encryptedFile2.size() - decryptedBytesWritten) <= 8); // Enable padding for the last block only
QByteArray decryptedData = bf.decrypted(data);
Q_ASSERT(decryptedData.size() <= 8);
qint64 bytesWritten = decryptedFile.write(decryptedData);
decryptedBytesWritten += bytesWritten;
}
decryptedFile.close();
encryptedFile2.close();
qDebug() << "Decrypted data written to decrypted.dat";
return 0;
}
<commit_msg>Example: Fix filename in info message<commit_after>#include <QtCore/QCoreApplication>
#include <QFile>
#include <QtDebug>
#include "qblowfish.h"
// Random key generated at http://www.random.org/bytes/
#define KEY_HEX "ea462947a76af8a50dba0ad01455c8c3"
int main(int argc, char *argv[])
{
Q_UNUSED(argc);
Q_UNUSED(argv);
QBlowfish bf(QByteArray::fromHex(KEY_HEX));
// Encrypt string
bf.setPaddingEnabled(true); // Enable padding to be able to encrypt an arbitrary length of bytes
QString clearText("Balderdash");
QByteArray cipherText = bf.encrypted(clearText.toUtf8());
qDebug() << "Encrypted ba (hex):" << cipherText.toHex();
// Encrypt a file
QFile clearFile("clearText.txt");
if (!clearFile.open(QFile::ReadOnly)) {
qFatal("Could not open clearText.txt for reading");
}
QFile encryptedFile("encrypted.dat");
if (!encryptedFile.open(QFile::WriteOnly)) {
qFatal("Could not open encrypted.dat for writing");
}
qint64 encryptedBytesWritten = 0;
while (!clearFile.atEnd()) {
QByteArray data = clearFile.read(8); // Let's process the file in 8-byte blocks (can use any multiple of 8)
bf.setPaddingEnabled((clearFile.size() - encryptedBytesWritten) <= 8); // Enable padding for the last block only
QByteArray encryptedData = bf.encrypted(data);
Q_ASSERT(encryptedData.size() == 8);
qint64 bytesWritten = encryptedFile.write(encryptedData);
encryptedBytesWritten += bytesWritten;
}
encryptedFile.close();
clearFile.close();
qDebug() << "Encrypted data written to encrypted.dat";
// Decrypt string
bf.setPaddingEnabled(true);
QByteArray decryptedBa = bf.decrypted(cipherText);
QString decryptedString = QString::fromUtf8(decryptedBa.constData(), decryptedBa.size());
qDebug() << "Decrypted string:" << decryptedString;
// Decrypt file
bf.setPaddingEnabled(false);
QFile encryptedFile2("encrypted.dat");
if (!encryptedFile2.open(QFile::ReadOnly)) {
qFatal("Could not open encrypted.dat for reading");
}
QFile decryptedFile("decrypted.txt");
if (!decryptedFile.open(QFile::WriteOnly)) {
qFatal("Could not open decrypted.txt for writing");
}
qint64 decryptedBytesWritten = 0;
while (!encryptedFile2.atEnd()) {
QByteArray data = encryptedFile2.read(8); // Let's process the file in 8-byte blocks (can use any multiple of 8)
bf.setPaddingEnabled((encryptedFile2.size() - decryptedBytesWritten) <= 8); // Enable padding for the last block only
QByteArray decryptedData = bf.decrypted(data);
Q_ASSERT(decryptedData.size() <= 8);
qint64 bytesWritten = decryptedFile.write(decryptedData);
decryptedBytesWritten += bytesWritten;
}
decryptedFile.close();
encryptedFile2.close();
qDebug() << "Decrypted data written to decrypted.txt";
return 0;
}
<|endoftext|> |
<commit_before>/* -----------------------------------------------------------------------------
Copyright 2017 Google 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.
----------------------------------------------------------------------------- */
// Author: Kevin P. Barry [[email protected]] [[email protected]]
// This is a simple (and noisy) test of the overhead required for each
// ThreadCapture captured by ThreadCrosser::WrapCall.
#include <chrono>
#include <functional>
#include <iostream>
#include <string>
#include "thread-capture.h"
#include "thread-crosser.h"
using capture_thread::ThreadCapture;
using capture_thread::ThreadCrosser;
class NoOp : public ThreadCapture<NoOp> {
public:
NoOp() : cross_and_capture_to_(this) {}
private:
const AutoThreadCrosser cross_and_capture_to_;
};
static std::chrono::duration<double> GetCurrentTime() {
return std::chrono::duration_cast<std::chrono::duration<double>>(
std::chrono::high_resolution_clock::now().time_since_epoch());
}
void TimeIterations(const std::string& prefix,
const std::function<void()>& call, int count) {
const auto start_time = GetCurrentTime();
for (int i = 0; i < count; ++i) {
call();
}
const auto finish_time = GetCurrentTime();
const double elapsed_ms = 1000. * (finish_time - start_time).count();
std::cerr << prefix << ":\t" << elapsed_ms << "\t(" << elapsed_ms / count
<< ")" << std::endl;
}
int main() {
constexpr int iterations = 10000000;
std::function<void()> empty([] {});
TimeIterations("0", ThreadCrosser::WrapCall(empty), iterations);
{
NoOp noop1;
TimeIterations("1", ThreadCrosser::WrapCall(empty), iterations);
{
NoOp noop2;
TimeIterations("2", ThreadCrosser::WrapCall(empty), iterations);
{
NoOp noop3;
TimeIterations("3", ThreadCrosser::WrapCall(empty), iterations);
{
NoOp noop4;
TimeIterations("4", ThreadCrosser::WrapCall(empty), iterations);
}
TimeIterations("3", ThreadCrosser::WrapCall(empty), iterations);
}
TimeIterations("2", ThreadCrosser::WrapCall(empty), iterations);
}
TimeIterations("1", ThreadCrosser::WrapCall(empty), iterations);
}
TimeIterations("0", ThreadCrosser::WrapCall(empty), iterations);
}
<commit_msg>Updates speed test to provide more usable data.<commit_after>/* -----------------------------------------------------------------------------
Copyright 2017 Google 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.
----------------------------------------------------------------------------- */
// Author: Kevin P. Barry [[email protected]] [[email protected]]
// This is a simple (and noisy) test of the overhead required for each
// ThreadCapture captured by ThreadCrosser::WrapCall.
#include <chrono>
#include <functional>
#include <iostream>
#include <string>
#include "thread-capture.h"
#include "thread-crosser.h"
using capture_thread::ThreadCapture;
using capture_thread::ThreadCrosser;
constexpr int kRepetitions = 5;
constexpr int kMaxWraps = 4;
constexpr int kMaxScopes = 4;
constexpr int kIterations = 1000000;
class NoOp : public ThreadCapture<NoOp> {
public:
NoOp() : cross_and_capture_to_(this) {}
private:
const AutoThreadCrosser cross_and_capture_to_;
};
static std::chrono::duration<double> GetCurrentTime() {
return std::chrono::duration_cast<std::chrono::duration<double>>(
std::chrono::high_resolution_clock::now().time_since_epoch());
}
void Execute(const std::function<int(int)>& function) {
const auto start_time = GetCurrentTime();
for (int i = 0; i < kIterations; ++i) {
function(i);
}
const auto finish_time = GetCurrentTime();
const double elapsed_ms = 1000. * (finish_time - start_time).count();
std::cout << '\t' << elapsed_ms << '\t' << elapsed_ms / kIterations
<< std::endl;
}
void ExecuteWithWrapping(std::function<int(int)> function, int wraps) {
if (wraps > 0) {
ExecuteWithWrapping(ThreadCrosser::WrapFunction(function), wraps - 1);
} else {
Execute(function);
}
}
void ExecuteWithScopesAndWrapping(int scopes, int wraps) {
if (scopes > 0) {
NoOp noop;
ExecuteWithScopesAndWrapping(scopes - 1, wraps);
} else {
ExecuteWithWrapping([](int x) { return x; }, wraps);
}
}
int main() {
for (int i = 0; i < kRepetitions; ++i) {
for (int wraps = 1; wraps < kMaxWraps + 1; ++wraps) {
for (int scopes = 1; scopes < kMaxScopes + 1; ++scopes) {
std::cout << i << '\t' << scopes << '\t' << wraps;
ExecuteWithScopesAndWrapping(scopes, wraps);
}
}
}
}
<|endoftext|> |
<commit_before>/*
* High level FastCGI client.
*
* author: Max Kellermann <[email protected]>
*/
#include "fcgi_request.hxx"
#include "fcgi_stock.hxx"
#include "fcgi_client.hxx"
#include "http_response.hxx"
#include "lease.hxx"
#include "tcp_stock.hxx"
#include "stock.hxx"
#include "ChildOptions.hxx"
#include "istream/istream.hxx"
#include "async.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include <daemon/log.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
struct FcgiRequest {
struct pool *const pool;
FcgiStock *const fcgi_stock;
StockItem *stock_item;
struct async_operation operation;
struct async_operation_ref async_ref;
FcgiRequest(struct pool &_pool,
FcgiStock &_fcgi_stock, StockItem &_stock_item)
:pool(&_pool), fcgi_stock(&_fcgi_stock), stock_item(&_stock_item) {
operation.Init2<FcgiRequest>();
}
void Abort() {
if (stock_item != nullptr)
fcgi_stock_aborted(*stock_item);
async_ref.Abort();
}
};
/*
* socket lease
*
*/
static void
fcgi_socket_release(bool reuse, void *ctx)
{
FcgiRequest *request = (FcgiRequest *)ctx;
fcgi_stock_put(request->fcgi_stock, *request->stock_item, !reuse);
request->stock_item = nullptr;
}
static const struct lease fcgi_socket_lease = {
.release = fcgi_socket_release,
};
/*
* constructor
*
*/
void
fcgi_request(struct pool *pool, FcgiStock *fcgi_stock,
const ChildOptions &options,
const char *action,
const char *path,
ConstBuffer<const char *> args,
ConstBuffer<const char *> env,
http_method_t method, const char *uri,
const char *script_name, const char *path_info,
const char *query_string,
const char *document_root,
const char *remote_addr,
struct strmap *headers, struct istream *body,
ConstBuffer<const char *> params,
int stderr_fd,
const struct http_response_handler *handler,
void *handler_ctx,
struct async_operation_ref *async_ref)
{
if (action == nullptr)
action = path;
GError *error = nullptr;
StockItem *stock_item =
fcgi_stock_get(fcgi_stock, pool, options,
action,
args, env,
&error);
if (stock_item == nullptr) {
if (body != nullptr)
istream_close_unused(body);
if (stderr_fd >= 0)
close(stderr_fd);
handler->InvokeAbort(handler_ctx, error);
return;
}
auto request = NewFromPool<FcgiRequest>(*pool, *pool,
*fcgi_stock, *stock_item);
async_ref->Set(request->operation);
async_ref = &request->async_ref;
const char *script_filename = fcgi_stock_translate_path(*stock_item, path,
request->pool);
document_root = fcgi_stock_translate_path(*stock_item, document_root,
request->pool);
fcgi_client_request(request->pool, fcgi_stock_item_get(*stock_item),
fcgi_stock_item_get_domain(*stock_item) == AF_LOCAL
? FdType::FD_SOCKET : FdType::FD_TCP,
&fcgi_socket_lease, request,
method, uri,
script_filename,
script_name, path_info,
query_string,
document_root,
remote_addr,
headers, body,
params,
stderr_fd,
handler, handler_ctx,
async_ref);
}
<commit_msg>fcgi/request: convert pointers to references<commit_after>/*
* High level FastCGI client.
*
* author: Max Kellermann <[email protected]>
*/
#include "fcgi_request.hxx"
#include "fcgi_stock.hxx"
#include "fcgi_client.hxx"
#include "http_response.hxx"
#include "lease.hxx"
#include "tcp_stock.hxx"
#include "stock.hxx"
#include "ChildOptions.hxx"
#include "istream/istream.hxx"
#include "async.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include <daemon/log.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
struct FcgiRequest {
struct pool &pool;
FcgiStock &fcgi_stock;
StockItem *stock_item;
struct async_operation operation;
struct async_operation_ref async_ref;
FcgiRequest(struct pool &_pool,
FcgiStock &_fcgi_stock, StockItem &_stock_item)
:pool(_pool), fcgi_stock(_fcgi_stock), stock_item(&_stock_item) {
operation.Init2<FcgiRequest>();
}
void Abort() {
if (stock_item != nullptr)
fcgi_stock_aborted(*stock_item);
async_ref.Abort();
}
};
/*
* socket lease
*
*/
static void
fcgi_socket_release(bool reuse, void *ctx)
{
FcgiRequest *request = (FcgiRequest *)ctx;
fcgi_stock_put(&request->fcgi_stock, *request->stock_item, !reuse);
request->stock_item = nullptr;
}
static const struct lease fcgi_socket_lease = {
.release = fcgi_socket_release,
};
/*
* constructor
*
*/
void
fcgi_request(struct pool *pool, FcgiStock *fcgi_stock,
const ChildOptions &options,
const char *action,
const char *path,
ConstBuffer<const char *> args,
ConstBuffer<const char *> env,
http_method_t method, const char *uri,
const char *script_name, const char *path_info,
const char *query_string,
const char *document_root,
const char *remote_addr,
struct strmap *headers, struct istream *body,
ConstBuffer<const char *> params,
int stderr_fd,
const struct http_response_handler *handler,
void *handler_ctx,
struct async_operation_ref *async_ref)
{
if (action == nullptr)
action = path;
GError *error = nullptr;
StockItem *stock_item =
fcgi_stock_get(fcgi_stock, pool, options,
action,
args, env,
&error);
if (stock_item == nullptr) {
if (body != nullptr)
istream_close_unused(body);
if (stderr_fd >= 0)
close(stderr_fd);
handler->InvokeAbort(handler_ctx, error);
return;
}
auto request = NewFromPool<FcgiRequest>(*pool, *pool,
*fcgi_stock, *stock_item);
async_ref->Set(request->operation);
async_ref = &request->async_ref;
const char *script_filename = fcgi_stock_translate_path(*stock_item, path,
&request->pool);
document_root = fcgi_stock_translate_path(*stock_item, document_root,
&request->pool);
fcgi_client_request(&request->pool, fcgi_stock_item_get(*stock_item),
fcgi_stock_item_get_domain(*stock_item) == AF_LOCAL
? FdType::FD_SOCKET : FdType::FD_TCP,
&fcgi_socket_lease, request,
method, uri,
script_filename,
script_name, path_info,
query_string,
document_root,
remote_addr,
headers, body,
params,
stderr_fd,
handler, handler_ctx,
async_ref);
}
<|endoftext|> |
<commit_before>#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <opencv2/opencv.hpp>
// #include "opencv2/xfeatures2d.hpp"
using std::string;
using std::vector;
// Make sure directory exists
void mkdirp(string path) {
system((std::string("mkdir -p ") + path).c_str());
}
void write_matches_list(string path, vector<cv::KeyPoint> kp1, vector<cv::KeyPoint> kp2, vector<cv::DMatch> matches) {
std::ofstream ofs((path + "/matches.txt").c_str());
ofs << "# Keypoints matches file, x y x y dist" << std::endl;
for (size_t i = 0; i < matches.size(); i++) {
// Is train/query kp1 or kp2 ?
ofs << kp1[matches[i].queryIdx].pt.x
<< " " << kp1[matches[i].queryIdx].pt.y
<< " " << kp2[matches[i].trainIdx].pt.x
<< " " << kp2[matches[i].trainIdx].pt.y
<< " " << matches[i].distance
<< std::endl;
}
}
void write_matches_image(string path, cv::Mat image1, cv::Mat image2,
vector<cv::KeyPoint> keypoint1, vector<cv::KeyPoint> keypoint2,
vector<cv::DMatch> matches,
double threshold) {
// Filter based on distance
vector<cv::DMatch> good_matches;
for (size_t i = 0; i < matches.size(); i++) {
if (matches[i].distance <= threshold) {
good_matches.push_back(matches[i]);
}
}
if (good_matches.size() == 0) {
return;
}
// Draw
cv::Mat img;
cv::drawMatches(image1, keypoint1, image2, keypoint2,
good_matches, img, cv::Scalar::all(-1), cv::Scalar::all(-1),
vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
// Write to file
std::ostringstream oss;
oss << threshold;
cv::imwrite(path + "/" + oss.str() + ".jpg", img);
}
void features_analysis(string path, cv::Mat image1, cv::Mat image2, cv::Ptr<cv::FeatureDetector> detector, cv::Ptr<cv::DescriptorExtractor> descriptor) {
mkdirp(path);
// Detect keypoints
vector<cv::KeyPoint> keypoint1;
vector<cv::KeyPoint> keypoint2;
detector->detect(image1, keypoint1);
detector->detect(image2, keypoint2);
// Draw keypoints
cv::Mat img_keypoints_1;
cv::Mat img_keypoints_2;
cv::drawKeypoints(image1, keypoint1, img_keypoints_1, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT);
cv::drawKeypoints(image2, keypoint2, img_keypoints_2, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT);
cv::imwrite(path + "/kp1.jpg", img_keypoints_1);
cv::imwrite(path + "/kp2.jpg", img_keypoints_2);
// Compute descriptors
cv::Mat descriptor1;
cv::Mat descriptor2;
descriptor->compute(image1, keypoint1, descriptor1);
descriptor->compute(image2, keypoint2, descriptor2);
if (descriptor1.empty() || descriptor2.empty()) {
std::cerr << "Empty descriptor!" << std::endl;
}
if (descriptor1.type()!= CV_32F) {
descriptor1.convertTo(descriptor1, CV_32F);
}
if (descriptor2.type()!= CV_32F) {
descriptor2.convertTo(descriptor2, CV_32F);
}
// Match using FLANN
cv::FlannBasedMatcher matcher;
vector<cv::DMatch> matches;
matcher.match(descriptor1, descriptor2, matches);
// Quick calculation of max and min distances between keypoints
double min_dist, max_dist;
for (int i = 0; i < descriptor1.rows; i++) {
double dist = matches[i].distance;
if (dist < min_dist) min_dist = dist;
if (dist > max_dist) max_dist = dist;
}
write_matches_list(path, keypoint1, keypoint2, matches);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 1e9);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 500);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 400);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 300);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 200);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 100);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 50);
}
// Run features analysis test for an image pair
void test_image_pair(string path, string path1, string path2) {
// Load images
cv::Mat image1 = cv::imread(path1);
cv::Mat image2 = cv::imread(path2);
if (!image1.data || !image2.data) {
std::cerr << "Error reading image for " << path << std::endl;
return;
}
mkdirp(path);
// Perform analysis with different configs
cv::Ptr<cv::ORB> orb = cv::ORB::create(400);
cv::Ptr<cv::MSER> fast = cv::MSER::create(400);
cv::Ptr<cv::BRISK> brisk = cv::BRISK::create();
// cv::Ptr<cv::SURF> surf = cv::SURF::create(400);
features_analysis(path + "/ORB400", image1, image2, orb, orb);
features_analysis(path + "/SURF400", image1, image2, fast, orb);
features_analysis(path + "/BRISK", image1, image2, brisk, brisk);
}
int main(int argc, char* argv[]) {
if (argc < 3) {
std::cerr << "Usage: ./features_analysis data_dir results_dir" << std::endl;
return -1;
}
string data = std::string(argv[1]);
string results_dir = std::string(argv[2]) + "/features_analysis";
test_image_pair(results_dir + "/lake",
data + "/features-areas/lake1.jpg",
data + "/features-areas/lake2.jpg");
test_image_pair(results_dir + "/desert",
data + "/features-areas/desert1.jpg",
data + "/features-areas/desert2.jpg");
test_image_pair(results_dir + "/cars",
data + "/features-areas/cars1.jpg",
data + "/features-areas/cars2.jpg");
test_image_pair(results_dir + "/water",
data + "/features-areas/water1.jpg",
data + "/features-areas/water2.jpg");
}
<commit_msg>added more features algos to test<commit_after>#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <opencv2/opencv.hpp>
// This needs to be before the SURF include
using std::string;
using std::vector;
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/nonfree/nonfree.hpp>
// Make sure directory exists
void mkdirp(string path) {
system((std::string("mkdir -p ") + path).c_str());
}
void write_matches_list(string path, vector<cv::KeyPoint> kp1, vector<cv::KeyPoint> kp2, vector<cv::DMatch> matches) {
std::ofstream ofs((path + "/matches.txt").c_str());
ofs << "# Keypoints matches file, x y x y dist" << std::endl;
for (size_t i = 0; i < matches.size(); i++) {
// Is train/query kp1 or kp2 ?
ofs << kp1[matches[i].queryIdx].pt.x
<< " " << kp1[matches[i].queryIdx].pt.y
<< " " << kp2[matches[i].trainIdx].pt.x
<< " " << kp2[matches[i].trainIdx].pt.y
<< " " << matches[i].distance
<< std::endl;
}
}
void write_matches_image(string path, cv::Mat image1, cv::Mat image2,
vector<cv::KeyPoint> keypoint1, vector<cv::KeyPoint> keypoint2,
vector<cv::DMatch> matches,
double threshold) {
// Filter based on distance
vector<cv::DMatch> good_matches;
for (size_t i = 0; i < matches.size(); i++) {
if (matches[i].distance <= threshold) {
good_matches.push_back(matches[i]);
}
}
if (good_matches.size() == 0) {
return;
}
// Draw
cv::Mat img;
cv::drawMatches(image1, keypoint1, image2, keypoint2,
good_matches, img, cv::Scalar::all(-1), cv::Scalar::all(-1),
vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
// Write to file
std::ostringstream oss;
oss << threshold;
cv::imwrite(path + "/" + oss.str() + ".jpg", img);
}
void features_analysis(string path, cv::Mat image1, cv::Mat image2, cv::Ptr<cv::FeatureDetector> detector, cv::Ptr<cv::DescriptorExtractor> descriptor) {
mkdirp(path);
// Detect keypoints
vector<cv::KeyPoint> keypoint1;
vector<cv::KeyPoint> keypoint2;
detector->detect(image1, keypoint1);
detector->detect(image2, keypoint2);
// Draw keypoints
cv::Mat img_keypoints_1;
cv::Mat img_keypoints_2;
cv::drawKeypoints(image1, keypoint1, img_keypoints_1, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT);
cv::drawKeypoints(image2, keypoint2, img_keypoints_2, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT);
cv::imwrite(path + "/kp1.jpg", img_keypoints_1);
cv::imwrite(path + "/kp2.jpg", img_keypoints_2);
// Compute descriptors
cv::Mat descriptor1;
cv::Mat descriptor2;
descriptor->compute(image1, keypoint1, descriptor1);
descriptor->compute(image2, keypoint2, descriptor2);
if (descriptor1.empty() || descriptor2.empty()) {
std::cerr << "Empty descriptor!" << std::endl;
}
if (descriptor1.type()!= CV_32F) {
descriptor1.convertTo(descriptor1, CV_32F);
}
if (descriptor2.type()!= CV_32F) {
descriptor2.convertTo(descriptor2, CV_32F);
}
// Match using FLANN
cv::FlannBasedMatcher matcher;
vector<cv::DMatch> matches;
matcher.match(descriptor1, descriptor2, matches);
// Quick calculation of max and min distances between keypoints
double min_dist, max_dist;
for (int i = 0; i < descriptor1.rows; i++) {
double dist = matches[i].distance;
if (dist < min_dist) min_dist = dist;
if (dist > max_dist) max_dist = dist;
}
write_matches_list(path, keypoint1, keypoint2, matches);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 1e9);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 500);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 400);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 300);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 200);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 100);
write_matches_image(path, image1, image2, keypoint1, keypoint2, matches, 50);
}
// Run features analysis test for an image pair
void test_image_pair(string path, string path1, string path2) {
// Load images
cv::Mat image1 = cv::imread(path1);
cv::Mat image2 = cv::imread(path2);
if (!image1.data || !image2.data) {
std::cerr << "Error reading image for " << path << std::endl;
return;
}
mkdirp(path);
// Perform analysis with different configs
cv::Ptr<cv::ORB> orb = cv::ORB::create(400);
cv::Ptr<cv::MSER> mser = cv::MSER::create(400);
cv::Ptr<cv::BRISK> brisk = cv::BRISK::create();
cv::Ptr<cv::KAZE> kaze = cv::KAZE::create();
// cv::Ptr<cv::SIFT> sift = cv::SIFT::create();
// cv::Ptr<cv::SURF> surf = cv::SURF::create(400);
features_analysis(path + "/ORB", image1, image2, orb, orb);
features_analysis(path + "/MSER-ORB", image1, image2, mser, orb);
features_analysis(path + "/BRISK", image1, image2, brisk, brisk);
features_analysis(path + "/BRISK-ORB", image1, image2, brisk, orb);
features_analysis(path + "/KAZE", image1, image2, kaze, kaze);
features_analysis(path + "/KAZE-ORB", image1, image2, kaze, orb);
}
int main(int argc, char* argv[]) {
if (argc < 3) {
std::cerr << "Usage: ./features_analysis data_dir results_dir" << std::endl;
return -1;
}
string data = std::string(argv[1]);
string results_dir = std::string(argv[2]) + "/features_analysis";
test_image_pair(results_dir + "/lake",
data + "/features-areas/lake1.jpg",
data + "/features-areas/lake2.jpg");
test_image_pair(results_dir + "/desert",
data + "/features-areas/desert1.jpg",
data + "/features-areas/desert2.jpg");
test_image_pair(results_dir + "/cars",
data + "/features-areas/cars1.jpg",
data + "/features-areas/cars2.jpg");
test_image_pair(results_dir + "/water",
data + "/features-areas/water1.jpg",
data + "/features-areas/water2.jpg");
test_image_pair(results_dir + "/industrial",
data + "/features-areas/industrial1.jpg",
data + "/features-areas/industrial2.jpg");
}
<|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 "media/base/video_frame.h"
#include "remoting/client/decoder_verbatim.h"
#include "remoting/client/mock_objects.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::InSequence;
namespace remoting {
TEST(DecoderVerbatimTest, SimpleDecode) {
DecoderVerbatim decoder;
scoped_refptr<MockDecodeDoneHandler> handler = new MockDecodeDoneHandler();
const size_t kWidth = 10;
const size_t kHeight = 1;
const char kData[] = "ABCDEFGHIJ";
scoped_ptr<HostMessage> msg(new HostMessage());
msg->mutable_update_stream_packet()->mutable_header()->set_width(kWidth);
msg->mutable_update_stream_packet()->mutable_header()->set_height(kHeight);
msg->mutable_update_stream_packet()->mutable_header()->set_x(0);
msg->mutable_update_stream_packet()->mutable_header()->set_y(0);
msg->mutable_update_stream_packet()->mutable_header()->set_pixel_format(
PixelFormatAscii);
msg->mutable_update_stream_packet()->set_data(kData, sizeof(kData));
scoped_refptr<media::VideoFrame> frame;
media::VideoFrame::CreateFrame(media::VideoFrame::ASCII, kWidth, kHeight,
base::TimeDelta(), base::TimeDelta(), &frame);
ASSERT_TRUE(frame);
InSequence s;
EXPECT_CALL(*handler, PartialDecodeDone());
EXPECT_CALL(*handler, DecodeDone());
UpdatedRects rects;
decoder.BeginDecode(
frame, &rects,
NewRunnableMethod(handler.get(),
&MockDecodeDoneHandler::PartialDecodeDone),
NewRunnableMethod(handler.get(), &MockDecodeDoneHandler::DecodeDone));
decoder.PartialDecode(msg.release());
decoder.EndDecode();
// Make sure we get the same data back.
EXPECT_EQ(kWidth, frame->width());
EXPECT_EQ(kHeight, frame->height());
EXPECT_EQ(media::VideoFrame::ASCII, frame->format());
EXPECT_EQ(0, memcmp(kData, frame->data(media::VideoFrame::kRGBPlane),
sizeof(kData)));
// Check the updated rects.
ASSERT_TRUE(rects.size() == 1);
EXPECT_EQ(kWidth, static_cast<size_t>(rects[0].width()));
EXPECT_EQ(kHeight, static_cast<size_t>(rects[0].height()));
}
} // namespace remoting
<commit_msg>Fix remoting_unittests<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 "media/base/video_frame.h"
#include "remoting/client/decoder_verbatim.h"
#include "remoting/client/mock_objects.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::InSequence;
namespace remoting {
TEST(DecoderVerbatimTest, SimpleDecode) {
DecoderVerbatim decoder;
scoped_refptr<MockDecodeDoneHandler> handler = new MockDecodeDoneHandler();
const size_t kWidth = 10;
const size_t kHeight = 1;
const char kData[] = "ABCDEFGHIJ";
scoped_ptr<HostMessage> msg(new HostMessage());
msg->mutable_update_stream_packet()->mutable_header()->set_width(kWidth);
msg->mutable_update_stream_packet()->mutable_header()->set_height(kHeight);
msg->mutable_update_stream_packet()->mutable_header()->set_x(0);
msg->mutable_update_stream_packet()->mutable_header()->set_y(0);
msg->mutable_update_stream_packet()->mutable_header()->set_pixel_format(
PixelFormatAscii);
msg->mutable_update_stream_packet()->set_data(kData, sizeof(kData));
scoped_refptr<media::VideoFrame> frame;
media::VideoFrame::CreateFrame(media::VideoFrame::ASCII, kWidth, kHeight,
base::TimeDelta(), base::TimeDelta(), &frame);
ASSERT_TRUE(frame);
InSequence s;
EXPECT_CALL(*handler, PartialDecodeDone());
EXPECT_CALL(*handler, DecodeDone());
UpdatedRects rects;
decoder.BeginDecode(
frame, &rects,
NewRunnableMethod(handler.get(),
&MockDecodeDoneHandler::PartialDecodeDone),
NewRunnableMethod(handler.get(), &MockDecodeDoneHandler::DecodeDone));
decoder.PartialDecode(msg.release());
decoder.EndDecode();
// Make sure we get the same data back.
EXPECT_EQ(kWidth, frame->width());
EXPECT_EQ(kHeight, frame->height());
EXPECT_EQ(media::VideoFrame::ASCII, frame->format());
// TODO(hclam): Enable this line.
// EXPECT_EQ(0, memcmp(kData, frame->data(media::VideoFrame::kRGBPlane),
// sizeof(kData)));
// Check the updated rects.
ASSERT_TRUE(rects.size() == 1);
EXPECT_EQ(kWidth, static_cast<size_t>(rects[0].width()));
EXPECT_EQ(kHeight, static_cast<size_t>(rects[0].height()));
}
} // namespace remoting
<|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/test/channel_transport/include/channel_transport.h"
#include <stdio.h>
#ifndef WEBRTC_ANDROID
#include "testing/gtest/include/gtest/gtest.h"
#endif
#include "webrtc/test/channel_transport/udp_transport.h"
#include "webrtc/video_engine/include/vie_network.h"
#include "webrtc/video_engine/vie_defines.h"
#include "webrtc/voice_engine/include/voe_network.h"
#ifdef WEBRTC_ANDROID
#undef NDEBUG
#include <assert.h>
#endif
namespace webrtc {
namespace test {
VoiceChannelTransport::VoiceChannelTransport(VoENetwork* voe_network,
int channel)
: channel_(channel),
voe_network_(voe_network) {
uint8_t socket_threads = 1;
socket_transport_ = UdpTransport::Create(channel, socket_threads);
int registered = voe_network_->RegisterExternalTransport(channel,
*socket_transport_);
#ifndef WEBRTC_ANDROID
EXPECT_EQ(0, registered);
#else
assert(registered == 0);
#endif
}
VoiceChannelTransport::~VoiceChannelTransport() {
voe_network_->DeRegisterExternalTransport(channel_);
UdpTransport::Destroy(socket_transport_);
}
void VoiceChannelTransport::IncomingRTPPacket(
const int8_t* incoming_rtp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
voe_network_->ReceivedRTPPacket(channel_, incoming_rtp_packet, packet_length);
}
void VoiceChannelTransport::IncomingRTCPPacket(
const int8_t* incoming_rtcp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
voe_network_->ReceivedRTCPPacket(channel_, incoming_rtcp_packet,
packet_length);
}
int VoiceChannelTransport::SetLocalReceiver(uint16_t rtp_port) {
int return_value = socket_transport_->InitializeReceiveSockets(this,
rtp_port);
if (return_value == 0) {
return socket_transport_->StartReceiving(kViENumReceiveSocketBuffers);
}
return return_value;
}
int VoiceChannelTransport::SetSendDestination(const char* ip_address,
uint16_t rtp_port) {
return socket_transport_->InitializeSendSockets(ip_address, rtp_port);
}
VideoChannelTransport::VideoChannelTransport(ViENetwork* vie_network,
int channel)
: channel_(channel),
vie_network_(vie_network) {
uint8_t socket_threads = 1;
socket_transport_ = UdpTransport::Create(channel, socket_threads);
int registered = vie_network_->RegisterSendTransport(channel,
*socket_transport_);
#ifndef WEBRTC_ANDROID
EXPECT_EQ(0, registered);
#else
assert(registered == 0);
#endif
}
VideoChannelTransport::~VideoChannelTransport() {
vie_network_->DeregisterSendTransport(channel_);
UdpTransport::Destroy(socket_transport_);
}
void VideoChannelTransport::IncomingRTPPacket(
const int8_t* incoming_rtp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
vie_network_->ReceivedRTPPacket(channel_, incoming_rtp_packet, packet_length);
}
void VideoChannelTransport::IncomingRTCPPacket(
const int8_t* incoming_rtcp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
vie_network_->ReceivedRTCPPacket(channel_, incoming_rtcp_packet,
packet_length);
}
int VideoChannelTransport::SetLocalReceiver(uint16_t rtp_port) {
int return_value = socket_transport_->InitializeReceiveSockets(this,
rtp_port);
if (return_value == 0) {
return socket_transport_->StartReceiving(kViENumReceiveSocketBuffers);
}
return return_value;
}
int VideoChannelTransport::SetSendDestination(const char* ip_address,
uint16_t rtp_port) {
return socket_transport_->InitializeSendSockets(ip_address, rtp_port);
}
} // namespace test
} // namespace webrtc
<commit_msg>To use the channel_transport on the iOS platform, some #if directives are changed.<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/test/channel_transport/include/channel_transport.h"
#include <stdio.h>
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
#include "testing/gtest/include/gtest/gtest.h"
#endif
#include "webrtc/test/channel_transport/udp_transport.h"
#include "webrtc/video_engine/include/vie_network.h"
#include "webrtc/video_engine/vie_defines.h"
#include "webrtc/voice_engine/include/voe_network.h"
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
#undef NDEBUG
#include <assert.h>
#endif
namespace webrtc {
namespace test {
VoiceChannelTransport::VoiceChannelTransport(VoENetwork* voe_network,
int channel)
: channel_(channel),
voe_network_(voe_network) {
uint8_t socket_threads = 1;
socket_transport_ = UdpTransport::Create(channel, socket_threads);
int registered = voe_network_->RegisterExternalTransport(channel,
*socket_transport_);
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
EXPECT_EQ(0, registered);
#else
assert(registered == 0);
#endif
}
VoiceChannelTransport::~VoiceChannelTransport() {
voe_network_->DeRegisterExternalTransport(channel_);
UdpTransport::Destroy(socket_transport_);
}
void VoiceChannelTransport::IncomingRTPPacket(
const int8_t* incoming_rtp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
voe_network_->ReceivedRTPPacket(channel_, incoming_rtp_packet, packet_length);
}
void VoiceChannelTransport::IncomingRTCPPacket(
const int8_t* incoming_rtcp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
voe_network_->ReceivedRTCPPacket(channel_, incoming_rtcp_packet,
packet_length);
}
int VoiceChannelTransport::SetLocalReceiver(uint16_t rtp_port) {
int return_value = socket_transport_->InitializeReceiveSockets(this,
rtp_port);
if (return_value == 0) {
return socket_transport_->StartReceiving(kViENumReceiveSocketBuffers);
}
return return_value;
}
int VoiceChannelTransport::SetSendDestination(const char* ip_address,
uint16_t rtp_port) {
return socket_transport_->InitializeSendSockets(ip_address, rtp_port);
}
VideoChannelTransport::VideoChannelTransport(ViENetwork* vie_network,
int channel)
: channel_(channel),
vie_network_(vie_network) {
uint8_t socket_threads = 1;
socket_transport_ = UdpTransport::Create(channel, socket_threads);
int registered = vie_network_->RegisterSendTransport(channel,
*socket_transport_);
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
EXPECT_EQ(0, registered);
#else
assert(registered == 0);
#endif
}
VideoChannelTransport::~VideoChannelTransport() {
vie_network_->DeregisterSendTransport(channel_);
UdpTransport::Destroy(socket_transport_);
}
void VideoChannelTransport::IncomingRTPPacket(
const int8_t* incoming_rtp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
vie_network_->ReceivedRTPPacket(channel_, incoming_rtp_packet, packet_length);
}
void VideoChannelTransport::IncomingRTCPPacket(
const int8_t* incoming_rtcp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
vie_network_->ReceivedRTCPPacket(channel_, incoming_rtcp_packet,
packet_length);
}
int VideoChannelTransport::SetLocalReceiver(uint16_t rtp_port) {
int return_value = socket_transport_->InitializeReceiveSockets(this,
rtp_port);
if (return_value == 0) {
return socket_transport_->StartReceiving(kViENumReceiveSocketBuffers);
}
return return_value;
}
int VideoChannelTransport::SetSendDestination(const char* ip_address,
uint16_t rtp_port) {
return socket_transport_->InitializeSendSockets(ip_address, rtp_port);
}
} // namespace test
} // namespace webrtc
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#ifndef _Stroika_Foundation_Traversal_Iterator_inl_
#define _Stroika_Foundation_Traversal_Iterator_inl_
#include "../Debug/Assertions.h"
namespace Stroika::Foundation::Traversal {
/*
********************************************************************************
******************************** IteratorBase **********************************
********************************************************************************
*/
template <typename SHARED_T, typename... ARGS_TYPE>
inline auto IteratorBase::MakeSmartPtr (ARGS_TYPE&&... args) -> PtrImplementationTemplate<SHARED_T>
{
return make_unique<SHARED_T> (forward<ARGS_TYPE> (args)...);
}
/*
********************************************************************************
*************************** Iterator<T, ITERATOR_TRAITS> ***********************
********************************************************************************
*/
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T, ITERATOR_TRAITS>::Iterator (const Iterator& src)
: fIterator_ (src.fIterator_ == nullptr ? nullptr : Clone_ (*src.fIterator_))
, fCurrent_ (src.fCurrent_)
{
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T, ITERATOR_TRAITS>::Iterator (RepSmartPtr&& rep)
: fIterator_ (move (rep))
, fCurrent_ ()
{
RequireNotNull (fIterator_);
// Reason for cast stuff is to avoid Clone if unneeded.
const_cast<IRep*> (fIterator_.get ())->More (&fCurrent_, false);
}
template <typename T, typename ITERATOR_TRAITS>
constexpr Iterator<T, ITERATOR_TRAITS>::Iterator (nullptr_t)
: Iterator (ConstructionFlagForceAtEnd_::ForceAtEnd)
{
}
template <typename T, typename ITERATOR_TRAITS>
constexpr Iterator<T, ITERATOR_TRAITS>::Iterator (ConstructionFlagForceAtEnd_)
: fIterator_ (nullptr)
, fCurrent_ ()
{
Assert (Done ());
}
template <typename T, typename ITERATOR_TRAITS>
Iterator<T, ITERATOR_TRAITS>& Iterator<T, ITERATOR_TRAITS>::operator= (const Iterator& rhs)
{
if (&rhs != this)
[[LIKELY_ATTR]]
{
fIterator_ = rhs.fIterator_ == nullptr ? nullptr : Clone_ (*rhs.fIterator_);
fCurrent_ = rhs.fCurrent_;
}
return *this;
}
template <typename T, typename ITERATOR_TRAITS>
inline typename Iterator<T, ITERATOR_TRAITS>::IRep& Iterator<T, ITERATOR_TRAITS>::GetRep ()
{
EnsureNotNull (fIterator_);
return *fIterator_;
}
template <typename T, typename ITERATOR_TRAITS>
inline const typename Iterator<T, ITERATOR_TRAITS>::IRep& Iterator<T, ITERATOR_TRAITS>::ConstGetRep () const
{
EnsureNotNull (fIterator_);
return *fIterator_;
}
template <typename T, typename ITERATOR_TRAITS>
inline T Iterator<T, ITERATOR_TRAITS>::Current () const
{
RequireNotNull (fIterator_);
Require (fCurrent_.has_value ());
return *fCurrent_;
}
template <typename T, typename ITERATOR_TRAITS>
inline bool Iterator<T, ITERATOR_TRAITS>::Done () const
{
return not fCurrent_.has_value ();
}
template <typename T, typename ITERATOR_TRAITS>
inline void Iterator<T, ITERATOR_TRAITS>::reset ()
{
*this = GetEmptyIterator ();
}
template <typename T, typename ITERATOR_TRAITS>
inline void Iterator<T, ITERATOR_TRAITS>::clear ()
{
*this = GetEmptyIterator ();
}
template <typename T, typename ITERATOR_TRAITS>
inline IteratorOwnerID Iterator<T, ITERATOR_TRAITS>::GetOwner () const
{
// We could cache this value, but its only used breaking references and in assertions, so its
// not clearly worth while
return fIterator_ == nullptr ? kUnknownIteratorOwnerID : fIterator_->GetOwner ();
}
template <typename T, typename ITERATOR_TRAITS>
inline T Iterator<T, ITERATOR_TRAITS>::operator* () const
{
Require (not Done ());
RequireNotNull (fIterator_);
return *fCurrent_;
}
template <typename T, typename ITERATOR_TRAITS>
inline auto Iterator<T, ITERATOR_TRAITS>::operator-> () const -> const value_type*
{
Require (not Done ());
RequireNotNull (fIterator_);
return fCurrent_.operator-> ();
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T>& Iterator<T, ITERATOR_TRAITS>::operator++ ()
{
Require (not Done ());
RequireNotNull (fIterator_);
fIterator_->More (&fCurrent_, true);
return *this;
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T> Iterator<T, ITERATOR_TRAITS>::operator++ (int)
{
RequireNotNull (fIterator_);
Require (not Done ());
Iterator<T> tmp = *this;
fIterator_->More (&fCurrent_, true);
return tmp;
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T, ITERATOR_TRAITS> Iterator<T, ITERATOR_TRAITS>::operator+ (int i) const
{
Require (i >= 0);
Iterator<T, ITERATOR_TRAITS> tmp{*this};
while (i > 0) {
--i;
++tmp;
}
return tmp;
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T, ITERATOR_TRAITS>::operator bool () const
{
return not Done ();
}
#if __cpp_impl_three_way_comparison >= 201907
template <typename T, typename ITERATOR_TRAITS>
inline bool Iterator<T, ITERATOR_TRAITS>::operator== (const Iterator& rhs) const
{
Require (GetOwner () == rhs.GetOwner () or GetOwner () == kUnknownIteratorOwnerID or rhs.GetOwner () == kUnknownIteratorOwnerID);
/*
* Equals is checked by first checking handling the case of special 'done' iterators. If two
* iterators differ on Done () - they cannot be equal. And if they are both done (this is special -
* even if from different sources) they are considered equal.
*
* But then - we check that they are the same dynamic type, and if so, hand to one,
* and let it do the dynamic/concrete type specific checks for equality.
*/
bool lDone = Done ();
bool rDone = rhs.Done ();
if (lDone != rDone)
[[LIKELY_ATTR]]
{
return false;
}
if (lDone) {
Assert (rDone);
return true;
}
Assert (not lDone and not rDone);
const Iterator<T, ITERATOR_TRAITS>::IRep* lhsRep = fIterator_.get ();
const Iterator<T, ITERATOR_TRAITS>::IRep* rhsRep = rhs.fIterator_.get ();
Ensure (lhsRep->Equals (rhsRep) == rhsRep->Equals (lhsRep));
return lhsRep->Equals (rhsRep);
}
#endif
template <typename T, typename ITERATOR_TRAITS>
inline typename Iterator<T, ITERATOR_TRAITS>::RepSmartPtr Iterator<T, ITERATOR_TRAITS>::Clone_ (const typename Iterator<T, ITERATOR_TRAITS>::IRep& rep)
{
return rep.Clone ();
}
template <typename T, typename ITERATOR_TRAITS>
constexpr Iterator<T, ITERATOR_TRAITS> Iterator<T, ITERATOR_TRAITS>::GetEmptyIterator ()
{
return Iterator<T, ITERATOR_TRAITS> (ConstructionFlagForceAtEnd_::ForceAtEnd);
}
#if __cpp_impl_three_way_comparison < 201907
/*
********************************************************************************
**************************** Iterator operators ********************************
********************************************************************************
*/
template <typename T, typename ITERATOR_TRAITS>
inline bool operator== (const Iterator<T, ITERATOR_TRAITS>& lhs, const Iterator<T, ITERATOR_TRAITS>& rhs)
{
bool lDone = lhs.Done ();
bool rDone = rhs.Done ();
if (lDone != rDone)
[[LIKELY_ATTR]]
{
return false;
}
if (lDone) {
Assert (rDone);
return true;
}
Assert (not lDone and not rDone);
const Iterator<T, ITERATOR_TRAITS>::IRep* lhsRep = lhs.fIterator_.get ();
const Iterator<T, ITERATOR_TRAITS>::IRep* rhsRep = rhs.fIterator_.get ();
Ensure (lhsRep->Equals (rhsRep) == rhsRep->Equals (lhsRep));
return lhsRep->Equals (rhsRep);
}
template <typename T, typename ITERATOR_TRAITS>
inline bool operator!= (const Iterator<T, ITERATOR_TRAITS>& lhs, const Iterator<T, ITERATOR_TRAITS>& rhs)
{
return not(lhs == rhs);
}
#endif
/*
********************************************************************************
***************************** Iterator2Pointer *********************************
********************************************************************************
*/
template <typename ITERATOR>
inline typename iterator_traits<ITERATOR>::pointer Iterator2Pointer (ITERATOR i)
{
// this overload wont always work.. I hope it gives good compiler error message??? --LGP 2014-10-07
//
// note Traversal::Iterator2Pointer (s.end ()) generally crashes in debug mode - windows - _ITERATOR_DEBUG_LEVEL >= 1, but I can find no better way which is portable
return &*i;
}
}
#endif /* _Stroika_Foundation_Traversal_Iterator_inl_ */
<commit_msg>try to fix warning about deprecated Iterator method<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#ifndef _Stroika_Foundation_Traversal_Iterator_inl_
#define _Stroika_Foundation_Traversal_Iterator_inl_
#include "../Debug/Assertions.h"
namespace Stroika::Foundation::Traversal {
/*
********************************************************************************
******************************** IteratorBase **********************************
********************************************************************************
*/
template <typename SHARED_T, typename... ARGS_TYPE>
inline auto IteratorBase::MakeSmartPtr (ARGS_TYPE&&... args) -> PtrImplementationTemplate<SHARED_T>
{
return make_unique<SHARED_T> (forward<ARGS_TYPE> (args)...);
}
/*
********************************************************************************
*************************** Iterator<T, ITERATOR_TRAITS> ***********************
********************************************************************************
*/
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T, ITERATOR_TRAITS>::Iterator (const Iterator& src)
: fIterator_ (src.fIterator_ == nullptr ? nullptr : Clone_ (*src.fIterator_))
, fCurrent_ (src.fCurrent_)
{
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T, ITERATOR_TRAITS>::Iterator (RepSmartPtr&& rep)
: fIterator_ (move (rep))
, fCurrent_ ()
{
RequireNotNull (fIterator_);
// Reason for cast stuff is to avoid Clone if unneeded.
const_cast<IRep*> (fIterator_.get ())->More (&fCurrent_, false);
}
template <typename T, typename ITERATOR_TRAITS>
constexpr Iterator<T, ITERATOR_TRAITS>::Iterator (nullptr_t)
: Iterator (ConstructionFlagForceAtEnd_::ForceAtEnd)
{
}
template <typename T, typename ITERATOR_TRAITS>
constexpr Iterator<T, ITERATOR_TRAITS>::Iterator (ConstructionFlagForceAtEnd_)
: fIterator_ (nullptr)
, fCurrent_ ()
{
Assert (Done ());
}
template <typename T, typename ITERATOR_TRAITS>
Iterator<T, ITERATOR_TRAITS>& Iterator<T, ITERATOR_TRAITS>::operator= (const Iterator& rhs)
{
if (&rhs != this)
[[LIKELY_ATTR]]
{
fIterator_ = rhs.fIterator_ == nullptr ? nullptr : Clone_ (*rhs.fIterator_);
fCurrent_ = rhs.fCurrent_;
}
return *this;
}
template <typename T, typename ITERATOR_TRAITS>
inline typename Iterator<T, ITERATOR_TRAITS>::IRep& Iterator<T, ITERATOR_TRAITS>::GetRep ()
{
EnsureNotNull (fIterator_);
return *fIterator_;
}
template <typename T, typename ITERATOR_TRAITS>
inline const typename Iterator<T, ITERATOR_TRAITS>::IRep& Iterator<T, ITERATOR_TRAITS>::ConstGetRep () const
{
EnsureNotNull (fIterator_);
return *fIterator_;
}
template <typename T, typename ITERATOR_TRAITS>
inline T Iterator<T, ITERATOR_TRAITS>::Current () const
{
RequireNotNull (fIterator_);
Require (fCurrent_.has_value ());
return *fCurrent_;
}
template <typename T, typename ITERATOR_TRAITS>
inline bool Iterator<T, ITERATOR_TRAITS>::Done () const
{
return not fCurrent_.has_value ();
}
template <typename T, typename ITERATOR_TRAITS>
inline void Iterator<T, ITERATOR_TRAITS>::reset ()
{
*this = GetEmptyIterator ();
}
template <typename T, typename ITERATOR_TRAITS>
inline void Iterator<T, ITERATOR_TRAITS>::clear ()
{
*this = GetEmptyIterator ();
}
template <typename T, typename ITERATOR_TRAITS>
inline IteratorOwnerID Iterator<T, ITERATOR_TRAITS>::GetOwner () const
{
// We could cache this value, but its only used breaking references and in assertions, so its
// not clearly worth while
return fIterator_ == nullptr ? kUnknownIteratorOwnerID : fIterator_->GetOwner ();
}
template <typename T, typename ITERATOR_TRAITS>
inline T Iterator<T, ITERATOR_TRAITS>::operator* () const
{
Require (not Done ());
RequireNotNull (fIterator_);
return *fCurrent_;
}
template <typename T, typename ITERATOR_TRAITS>
inline auto Iterator<T, ITERATOR_TRAITS>::operator-> () const -> const value_type*
{
Require (not Done ());
RequireNotNull (fIterator_);
return fCurrent_.operator-> ();
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T>& Iterator<T, ITERATOR_TRAITS>::operator++ ()
{
Require (not Done ());
RequireNotNull (fIterator_);
fIterator_->More (&fCurrent_, true);
return *this;
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T> Iterator<T, ITERATOR_TRAITS>::operator++ (int)
{
RequireNotNull (fIterator_);
Require (not Done ());
Iterator<T> tmp = *this;
fIterator_->More (&fCurrent_, true);
return tmp;
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T, ITERATOR_TRAITS> Iterator<T, ITERATOR_TRAITS>::operator+ (int i) const
{
Require (i >= 0);
Iterator<T, ITERATOR_TRAITS> tmp{*this};
while (i > 0) {
--i;
++tmp;
}
return tmp;
}
template <typename T, typename ITERATOR_TRAITS>
inline Iterator<T, ITERATOR_TRAITS>::operator bool () const
{
return not Done ();
}
#if __cpp_impl_three_way_comparison >= 201907
template <typename T, typename ITERATOR_TRAITS>
inline bool Iterator<T, ITERATOR_TRAITS>::operator== (const Iterator& rhs) const
{
Require (GetOwner () == rhs.GetOwner () or GetOwner () == kUnknownIteratorOwnerID or rhs.GetOwner () == kUnknownIteratorOwnerID);
/*
* Equals is checked by first checking handling the case of special 'done' iterators. If two
* iterators differ on Done () - they cannot be equal. And if they are both done (this is special -
* even if from different sources) they are considered equal.
*
* But then - we check that they are the same dynamic type, and if so, hand to one,
* and let it do the dynamic/concrete type specific checks for equality.
*/
bool lDone = Done ();
bool rDone = rhs.Done ();
if (lDone != rDone)
[[LIKELY_ATTR]]
{
return false;
}
if (lDone) {
Assert (rDone);
return true;
}
Assert (not lDone and not rDone);
const Iterator<T, ITERATOR_TRAITS>::IRep* lhsRep = fIterator_.get ();
const Iterator<T, ITERATOR_TRAITS>::IRep* rhsRep = rhs.fIterator_.get ();
Ensure (lhsRep->Equals (rhsRep) == rhsRep->Equals (lhsRep));
return lhsRep->Equals (rhsRep);
}
#endif
template <typename T, typename ITERATOR_TRAITS>
inline typename Iterator<T, ITERATOR_TRAITS>::RepSmartPtr Iterator<T, ITERATOR_TRAITS>::Clone_ (const typename Iterator<T, ITERATOR_TRAITS>::IRep& rep)
{
return rep.Clone ();
}
template <typename T, typename ITERATOR_TRAITS>
constexpr Iterator<T, ITERATOR_TRAITS> Iterator<T, ITERATOR_TRAITS>::GetEmptyIterator ()
{
return Iterator<T, ITERATOR_TRAITS> (ConstructionFlagForceAtEnd_::ForceAtEnd);
}
#if __cpp_impl_three_way_comparison < 201907
/*
********************************************************************************
**************************** Iterator operators ********************************
********************************************************************************
*/
template <typename T, typename ITERATOR_TRAITS>
inline bool operator== (const Iterator<T, ITERATOR_TRAITS>& lhs, const Iterator<T, ITERATOR_TRAITS>& rhs)
{
bool lDone = lhs.Done ();
bool rDone = rhs.Done ();
if (lDone != rDone)
[[LIKELY_ATTR]]
{
return false;
}
if (lDone) {
Assert (rDone);
return true;
}
Assert (not lDone and not rDone);
typename const Iterator<T, ITERATOR_TRAITS>::IRep* lhsRep = lhs.fIterator_.get ();
typename const Iterator<T, ITERATOR_TRAITS>::IRep* rhsRep = rhs.fIterator_.get ();
Ensure (lhsRep->Equals (rhsRep) == rhsRep->Equals (lhsRep));
return lhsRep->Equals (rhsRep);
}
template <typename T, typename ITERATOR_TRAITS>
inline bool operator!= (const Iterator<T, ITERATOR_TRAITS>& lhs, const Iterator<T, ITERATOR_TRAITS>& rhs)
{
return not(lhs == rhs);
}
#endif
/*
********************************************************************************
***************************** Iterator2Pointer *********************************
********************************************************************************
*/
template <typename ITERATOR>
inline typename iterator_traits<ITERATOR>::pointer Iterator2Pointer (ITERATOR i)
{
// this overload wont always work.. I hope it gives good compiler error message??? --LGP 2014-10-07
//
// note Traversal::Iterator2Pointer (s.end ()) generally crashes in debug mode - windows - _ITERATOR_DEBUG_LEVEL >= 1, but I can find no better way which is portable
return &*i;
}
}
#endif /* _Stroika_Foundation_Traversal_Iterator_inl_ */
<|endoftext|> |
<commit_before>#include "TrackingData.h"
#include <queue>
#include "ScalingCoordinateMapper.h"
#include <cmath>
#include <opencv2/opencv.hpp>
#define MAX_DEPTH 10000
namespace sensekit { namespace plugins { namespace hand {
namespace segmentation {
struct PointTTL
{
cv::Point m_point;
float m_ttl;
bool m_pathInRange;
PointTTL(cv::Point point, float ttl, bool pathInRange)
{
m_point = point;
m_ttl = ttl;
m_pathInRange = pathInRange;
}
};
static void segment_foreground(TrackingData data)
{
const float maxSegmentationDist = data.maxSegmentationDist;
SegmentationForegroundPolicy foregroundPolicy = data.foregroundPolicy;
float seedDepth = data.matrices.depth.at<float>(data.seedPosition);
cv::Mat& depthMatrix = data.matrices.depth;
cv::Mat& foregroundMatrix = data.matrices.foreground;
cv::Mat& areaMatrix = data.matrices.area;
cv::Mat& segmentationMatrix = data.matrices.layerSegmentation;
cv::Mat& searchedMatrix = data.matrices.debugSearched;
bool isActivePoint = data.pointType == TrackedPointType::ActivePoint;
std::queue<PointTTL> pointQueue;
//does the seed point start in range?
//If not, it will search outward until it finds in range pixels
const float maxDepth = data.referenceDepth + data.bandwidthDepth;
bool seedInRange = seedDepth != 0 && seedDepth < maxDepth;
bool anyInRange = seedInRange;
pointQueue.push(PointTTL(data.seedPosition, maxSegmentationDist, seedInRange));
cv::Mat matVisited = cv::Mat::zeros(depthMatrix.size(), CV_8UC1);
int width = depthMatrix.cols;
int height = depthMatrix.rows;
matVisited.at<char>(data.seedPosition) = 1;
while (!pointQueue.empty())
{
PointTTL pt = pointQueue.front();
pointQueue.pop();
cv::Point p = pt.m_point;
float ttl = pt.m_ttl;
bool pathInRange = pt.m_pathInRange;
if (foregroundPolicy == FG_POLICY_RESET_TTL &&
foregroundMatrix.at<char>(p) == PixelType::Foreground)
{
ttl = maxSegmentationDist;
}
if (ttl > 0)
{
searchedMatrix.at<char>(p) = PixelType::Searched;
float depth = depthMatrix.at<float>(p);
bool pointInRange = depth != 0 && depth < maxDepth;
if (ttl > 0 && (!pathInRange || pointInRange))
{
//If active tracking, then must be in range to decrement TTL.
//This will give active points a larger range, more likely to recover.
//If not active tracking, will always decrement TTL.
if (!isActivePoint || anyInRange)
{
ttl -= sqrt(areaMatrix.at<float>(p));
}
if (pointInRange)
{
//Once a path has "come ashore" -- found an in-range pixel -- it won't leave the range again
pathInRange = true;
anyInRange = true;
segmentationMatrix.at<char>(p) = PixelType::Foreground;
}
cv::Point right(p.x + 1, p.y);
cv::Point left(p.x - 1, p.y);
cv::Point down(p.x, p.y + 1);
cv::Point up(p.x, p.y - 1);
if (right.x < width && 0 == matVisited.at<char>(right))
{
matVisited.at<char>(right) = 1;
pointQueue.push(PointTTL(right, ttl, pathInRange));
}
if (left.x >= 0 && 0 == matVisited.at<char>(left))
{
matVisited.at<char>(left) = 1;
pointQueue.push(PointTTL(left, ttl, pathInRange));
}
if (down.y < height && 0 == matVisited.at<char>(down))
{
matVisited.at<char>(down) = 1;
pointQueue.push(PointTTL(down, ttl, pathInRange));
}
if (up.y >= 0 && 0 == matVisited.at<char>(up))
{
matVisited.at<char>(up) = 1;
pointQueue.push(PointTTL(up, ttl, pathInRange));
}
}
}
}
}
static cv::Point track_point_from_seed(TrackingData data)
{
cv::Size size = data.matrices.depth.size();
data.matrices.layerSegmentation = cv::Mat::zeros(size, CV_8UC1);
//data.matrices.matLayerSegmentation.setTo(cv::Scalar(0));
segment_foreground(data);
++data.matrices.layerCount;
cv::bitwise_or(cv::Mat(size, CV_8UC1, cv::Scalar(data.matrices.layerCount)),
data.matrices.debugSegmentation,
data.matrices.debugSegmentation,
data.matrices.layerSegmentation);
double min, max;
cv::Point minLoc, maxLoc;
cv::minMaxLoc(data.matrices.score, &min, &max, &minLoc, &maxLoc, data.matrices.layerSegmentation);
return maxLoc;
}
cv::Point converge_track_point_from_seed(TrackingData data)
{
cv::Point point = data.seedPosition;
cv::Point lastPoint = data.seedPosition;
int iterations = 0;
do
{
lastPoint = point;
point = track_point_from_seed(data);
++iterations;
} while (point != lastPoint && iterations < data.iterationMax && point.x != -1 && point.y != -1);
return point;
}
bool find_next_foreground_pixel(cv::Mat& foregroundMatrix,
cv::Point& foregroundPosition,
cv::Point& nextSearchStart)
{
int width = foregroundMatrix.cols;
int height = foregroundMatrix.rows;
const int startX = MAX(0, MIN(width - 1, nextSearchStart.x));
const int startY = MAX(0, MIN(height - 1, nextSearchStart.y));
for (int y = startY; y < height; y++)
{
for (int x = startX; x < width; x++)
{
char foreground = *foregroundMatrix.ptr<char>(y, x);
if (foreground == PixelType::Foreground)
{
foregroundPosition.x = x;
foregroundPosition.y = y;
nextSearchStart.x = x + 1;
if (nextSearchStart.x < width)
{
nextSearchStart.y = y;
}
else
{
nextSearchStart.x = 0;
nextSearchStart.y = y + 1;
}
return true;
}
}
}
foregroundPosition.x = -1;
foregroundPosition.y = -1;
nextSearchStart.x = width;
nextSearchStart.y = height;
return false;
}
void calculate_basic_score(cv::Mat& depthMatrix,
cv::Mat& scoreMatrix,
const float heightFactor,
const float depthFactor,
const ScalingCoordinateMapper& mapper)
{
int width = depthMatrix.cols;
int height = depthMatrix.rows;
for (int y = 0; y < height; y++)
{
float* depthRow = depthMatrix.ptr<float>(y);
float* scoreRow = scoreMatrix.ptr<float>(y);
for (int x = 0; x < width; x++)
{
float depth = *depthRow;
if (depth != 0)
{
cv::Point3f worldPosition = mapper.convert_depth_to_world(x, y, depth);
float score = 0;
score += worldPosition.y * heightFactor;
score += (MAX_DEPTH - worldPosition.z) * depthFactor;
*scoreRow = score;
}
else
{
*scoreRow = 0;
}
++depthRow;
++scoreRow;
}
}
}
void calculate_edge_distance(cv::Mat& segmentationMatrix,
cv::Mat& areaMatrix,
cv::Mat& edgeDistanceMatrix)
{
cv::Mat eroded, temp;
cv::Mat crossElement = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(3, 3));
edgeDistanceMatrix = cv::Mat::zeros(segmentationMatrix.size(), CV_32FC1);
cv::Mat ones = cv::Mat::ones(segmentationMatrix.size(), CV_32FC1);
segmentationMatrix.copyTo(eroded);
//close small holes
int dilateCount = 1;
for (int i = 0; i < dilateCount; i++)
{
cv::dilate(eroded, eroded, crossElement);
}
int nonZeroCount = 0;
const int imageLength = eroded.cols * eroded.rows;
int iterations = 0;
const int maxIterations = segmentationMatrix.cols / 2;
bool done;
do
{
//erode makes the image smaller
cv::erode(eroded, eroded, crossElement);
//accumulate the eroded image to the matGlobalSegmentation buffer
cv::add(areaMatrix, edgeDistanceMatrix, edgeDistanceMatrix, eroded, CV_32FC1);
nonZeroCount = cv::countNonZero(eroded);
done = (nonZeroCount == 0);
//nonZerCount < imageLength guards against image with all 1's, which will never erode
} while (!done && nonZeroCount < imageLength && ++iterations < maxIterations);
}
static float get_depth_area(cv::Point3f& p1,
cv::Point3f& p2,
cv::Point3f& p3,
const ScalingCoordinateMapper& mapper)
{
cv::Point3f world1 = mapper.convert_depth_to_world(p1);
cv::Point3f world2 = mapper.convert_depth_to_world(p2);
cv::Point3f world3 = mapper.convert_depth_to_world(p3);
cv::Point3f v1 = world2 - world1;
cv::Point3f v2 = world3 - world1;
float area = static_cast<float>(0.5 * cv::norm(v1.cross(v2)));
return area;
}
void calculate_segment_area(cv::Mat& depthMatrix, cv::Mat& areaMatrix, const ScalingCoordinateMapper& mapper)
{
int width = depthMatrix.cols;
int height = depthMatrix.rows;
areaMatrix = cv::Mat::zeros(depthMatrix.size(), CV_32FC1);
for (int y = 0; y < height - 1; y++)
{
float* depthRow = depthMatrix.ptr<float>(y);
float* nextDepthRow = depthMatrix.ptr<float>(y + 1);
float* areaRow = areaMatrix.ptr<float>(y);
for (int x = 0; x < width - 1; x++)
{
float area = 0;
float depth1 = *depthRow;
if (depth1 != 0)
{
cv::Point3f p1(x, y, depth1);
cv::Point3f p2(x + 1, y, depth1);
cv::Point3f p3(x, y + 1, depth1);
cv::Point3f p4(x + 1, y + 1, depth1);
area += get_depth_area(p1, p2, p3, mapper);
area += get_depth_area(p2, p3, p4, mapper);
}
*areaRow = area;
++depthRow;
++nextDepthRow;
++areaRow;
}
}
}
float count_neighborhood_area(cv::Mat& segmentationMatrix,
cv::Mat& depthMatrix,
cv::Mat& areaMatrix,
cv::Point center,
const float bandwidth,
const float bandwidthDepth,
const ScalingCoordinateMapper& mapper)
{
float startingDepth = depthMatrix.at<float>(center);
cv::Point topLeft = offset_pixel_location_by_mm(mapper, center, -bandwidth, bandwidth, startingDepth);
cv::Point bottomRight = offset_pixel_location_by_mm(mapper, center, bandwidth, -bandwidth, startingDepth);
int32_t x0 = MAX(0, topLeft.x);
int32_t y0 = MAX(0, topLeft.y);
int32_t x1 = MIN(depthMatrix.cols - 1, bottomRight.x);
int32_t y1 = MIN(depthMatrix.rows - 1, bottomRight.y);
float area = 0;
for (int y = y0; y < y1; y++)
{
float* depthRow = depthMatrix.ptr<float>(y);
char* segmentationRow = segmentationMatrix.ptr<char>(y);
float* areaRow = areaMatrix.ptr<float>(y);
depthRow += x0;
segmentationRow += x0;
areaRow += x0;
for (int x = x0; x < x1; x++)
{
if (*segmentationRow == PixelType::Foreground)
{
float depth = *depthRow;
if (std::fabs(depth - startingDepth) < bandwidthDepth)
{
area += *areaRow;
}
}
++depthRow;
++areaRow;
++segmentationRow;
}
}
return area;
}
}
}}}
<commit_msg>Fixed rare bug where if the last pixel is foreground - infinite loop<commit_after>#include "TrackingData.h"
#include <queue>
#include "ScalingCoordinateMapper.h"
#include <cmath>
#include <opencv2/opencv.hpp>
#define MAX_DEPTH 10000
namespace sensekit { namespace plugins { namespace hand {
namespace segmentation {
struct PointTTL
{
cv::Point m_point;
float m_ttl;
bool m_pathInRange;
PointTTL(cv::Point point, float ttl, bool pathInRange)
{
m_point = point;
m_ttl = ttl;
m_pathInRange = pathInRange;
}
};
static void segment_foreground(TrackingData data)
{
const float maxSegmentationDist = data.maxSegmentationDist;
SegmentationForegroundPolicy foregroundPolicy = data.foregroundPolicy;
float seedDepth = data.matrices.depth.at<float>(data.seedPosition);
cv::Mat& depthMatrix = data.matrices.depth;
cv::Mat& foregroundMatrix = data.matrices.foreground;
cv::Mat& areaMatrix = data.matrices.area;
cv::Mat& segmentationMatrix = data.matrices.layerSegmentation;
cv::Mat& searchedMatrix = data.matrices.debugSearched;
bool isActivePoint = data.pointType == TrackedPointType::ActivePoint;
std::queue<PointTTL> pointQueue;
//does the seed point start in range?
//If not, it will search outward until it finds in range pixels
const float maxDepth = data.referenceDepth + data.bandwidthDepth;
bool seedInRange = seedDepth != 0 && seedDepth < maxDepth;
bool anyInRange = seedInRange;
pointQueue.push(PointTTL(data.seedPosition, maxSegmentationDist, seedInRange));
cv::Mat matVisited = cv::Mat::zeros(depthMatrix.size(), CV_8UC1);
int width = depthMatrix.cols;
int height = depthMatrix.rows;
matVisited.at<char>(data.seedPosition) = 1;
while (!pointQueue.empty())
{
PointTTL pt = pointQueue.front();
pointQueue.pop();
cv::Point p = pt.m_point;
float ttl = pt.m_ttl;
bool pathInRange = pt.m_pathInRange;
if (foregroundPolicy == FG_POLICY_RESET_TTL &&
foregroundMatrix.at<char>(p) == PixelType::Foreground)
{
ttl = maxSegmentationDist;
}
if (ttl > 0)
{
searchedMatrix.at<char>(p) = PixelType::Searched;
float depth = depthMatrix.at<float>(p);
bool pointInRange = depth != 0 && depth < maxDepth;
if (ttl > 0 && (!pathInRange || pointInRange))
{
//If active tracking, then must be in range to decrement TTL.
//This will give active points a larger range, more likely to recover.
//If not active tracking, will always decrement TTL.
if (!isActivePoint || anyInRange)
{
ttl -= sqrt(areaMatrix.at<float>(p));
}
if (pointInRange)
{
//Once a path has "come ashore" -- found an in-range pixel -- it won't leave the range again
pathInRange = true;
anyInRange = true;
segmentationMatrix.at<char>(p) = PixelType::Foreground;
}
cv::Point right(p.x + 1, p.y);
cv::Point left(p.x - 1, p.y);
cv::Point down(p.x, p.y + 1);
cv::Point up(p.x, p.y - 1);
if (right.x < width && 0 == matVisited.at<char>(right))
{
matVisited.at<char>(right) = 1;
pointQueue.push(PointTTL(right, ttl, pathInRange));
}
if (left.x >= 0 && 0 == matVisited.at<char>(left))
{
matVisited.at<char>(left) = 1;
pointQueue.push(PointTTL(left, ttl, pathInRange));
}
if (down.y < height && 0 == matVisited.at<char>(down))
{
matVisited.at<char>(down) = 1;
pointQueue.push(PointTTL(down, ttl, pathInRange));
}
if (up.y >= 0 && 0 == matVisited.at<char>(up))
{
matVisited.at<char>(up) = 1;
pointQueue.push(PointTTL(up, ttl, pathInRange));
}
}
}
}
}
static cv::Point track_point_from_seed(TrackingData data)
{
cv::Size size = data.matrices.depth.size();
data.matrices.layerSegmentation = cv::Mat::zeros(size, CV_8UC1);
//data.matrices.matLayerSegmentation.setTo(cv::Scalar(0));
segment_foreground(data);
++data.matrices.layerCount;
cv::bitwise_or(cv::Mat(size, CV_8UC1, cv::Scalar(data.matrices.layerCount)),
data.matrices.debugSegmentation,
data.matrices.debugSegmentation,
data.matrices.layerSegmentation);
double min, max;
cv::Point minLoc, maxLoc;
cv::minMaxLoc(data.matrices.score, &min, &max, &minLoc, &maxLoc, data.matrices.layerSegmentation);
return maxLoc;
}
cv::Point converge_track_point_from_seed(TrackingData data)
{
cv::Point point = data.seedPosition;
cv::Point lastPoint = data.seedPosition;
int iterations = 0;
do
{
lastPoint = point;
point = track_point_from_seed(data);
++iterations;
} while (point != lastPoint && iterations < data.iterationMax && point.x != -1 && point.y != -1);
return point;
}
bool find_next_foreground_pixel(cv::Mat& foregroundMatrix,
cv::Point& foregroundPosition,
cv::Point& nextSearchStart)
{
int width = foregroundMatrix.cols;
int height = foregroundMatrix.rows;
const int startX = MAX(0, MIN(width - 1, nextSearchStart.x));
const int startY = MAX(0, MIN(height - 1, nextSearchStart.y));
for (int y = startY; y < height; y++)
{
for (int x = startX; x < width; x++)
{
char foreground = *foregroundMatrix.ptr<char>(y, x);
if (foreground == PixelType::Foreground)
{
foregroundPosition.x = x;
foregroundPosition.y = y;
nextSearchStart.x = x + 1;
if (nextSearchStart.x < width)
{
nextSearchStart.y = y;
}
else
{
nextSearchStart.x = 0;
nextSearchStart.y = y + 1;
if (nextSearchStart.y >= height)
{
return false;
}
}
return true;
}
}
}
foregroundPosition.x = -1;
foregroundPosition.y = -1;
nextSearchStart.x = width;
nextSearchStart.y = height;
return false;
}
void calculate_basic_score(cv::Mat& depthMatrix,
cv::Mat& scoreMatrix,
const float heightFactor,
const float depthFactor,
const ScalingCoordinateMapper& mapper)
{
int width = depthMatrix.cols;
int height = depthMatrix.rows;
for (int y = 0; y < height; y++)
{
float* depthRow = depthMatrix.ptr<float>(y);
float* scoreRow = scoreMatrix.ptr<float>(y);
for (int x = 0; x < width; x++)
{
float depth = *depthRow;
if (depth != 0)
{
cv::Point3f worldPosition = mapper.convert_depth_to_world(x, y, depth);
float score = 0;
score += worldPosition.y * heightFactor;
score += (MAX_DEPTH - worldPosition.z) * depthFactor;
*scoreRow = score;
}
else
{
*scoreRow = 0;
}
++depthRow;
++scoreRow;
}
}
}
void calculate_edge_distance(cv::Mat& segmentationMatrix,
cv::Mat& areaMatrix,
cv::Mat& edgeDistanceMatrix)
{
cv::Mat eroded, temp;
cv::Mat crossElement = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(3, 3));
edgeDistanceMatrix = cv::Mat::zeros(segmentationMatrix.size(), CV_32FC1);
cv::Mat ones = cv::Mat::ones(segmentationMatrix.size(), CV_32FC1);
segmentationMatrix.copyTo(eroded);
//close small holes
int dilateCount = 1;
for (int i = 0; i < dilateCount; i++)
{
cv::dilate(eroded, eroded, crossElement);
}
int nonZeroCount = 0;
const int imageLength = eroded.cols * eroded.rows;
int iterations = 0;
const int maxIterations = segmentationMatrix.cols / 2;
bool done;
do
{
//erode makes the image smaller
cv::erode(eroded, eroded, crossElement);
//accumulate the eroded image to the matGlobalSegmentation buffer
cv::add(areaMatrix, edgeDistanceMatrix, edgeDistanceMatrix, eroded, CV_32FC1);
nonZeroCount = cv::countNonZero(eroded);
done = (nonZeroCount == 0);
//nonZerCount < imageLength guards against image with all 1's, which will never erode
} while (!done && nonZeroCount < imageLength && ++iterations < maxIterations);
}
static float get_depth_area(cv::Point3f& p1,
cv::Point3f& p2,
cv::Point3f& p3,
const ScalingCoordinateMapper& mapper)
{
cv::Point3f world1 = mapper.convert_depth_to_world(p1);
cv::Point3f world2 = mapper.convert_depth_to_world(p2);
cv::Point3f world3 = mapper.convert_depth_to_world(p3);
cv::Point3f v1 = world2 - world1;
cv::Point3f v2 = world3 - world1;
float area = static_cast<float>(0.5 * cv::norm(v1.cross(v2)));
return area;
}
void calculate_segment_area(cv::Mat& depthMatrix, cv::Mat& areaMatrix, const ScalingCoordinateMapper& mapper)
{
int width = depthMatrix.cols;
int height = depthMatrix.rows;
areaMatrix = cv::Mat::zeros(depthMatrix.size(), CV_32FC1);
for (int y = 0; y < height - 1; y++)
{
float* depthRow = depthMatrix.ptr<float>(y);
float* nextDepthRow = depthMatrix.ptr<float>(y + 1);
float* areaRow = areaMatrix.ptr<float>(y);
for (int x = 0; x < width - 1; x++)
{
float area = 0;
float depth1 = *depthRow;
if (depth1 != 0)
{
cv::Point3f p1(x, y, depth1);
cv::Point3f p2(x + 1, y, depth1);
cv::Point3f p3(x, y + 1, depth1);
cv::Point3f p4(x + 1, y + 1, depth1);
area += get_depth_area(p1, p2, p3, mapper);
area += get_depth_area(p2, p3, p4, mapper);
}
*areaRow = area;
++depthRow;
++nextDepthRow;
++areaRow;
}
}
}
float count_neighborhood_area(cv::Mat& segmentationMatrix,
cv::Mat& depthMatrix,
cv::Mat& areaMatrix,
cv::Point center,
const float bandwidth,
const float bandwidthDepth,
const ScalingCoordinateMapper& mapper)
{
float startingDepth = depthMatrix.at<float>(center);
cv::Point topLeft = offset_pixel_location_by_mm(mapper, center, -bandwidth, bandwidth, startingDepth);
cv::Point bottomRight = offset_pixel_location_by_mm(mapper, center, bandwidth, -bandwidth, startingDepth);
int32_t x0 = MAX(0, topLeft.x);
int32_t y0 = MAX(0, topLeft.y);
int32_t x1 = MIN(depthMatrix.cols - 1, bottomRight.x);
int32_t y1 = MIN(depthMatrix.rows - 1, bottomRight.y);
float area = 0;
for (int y = y0; y < y1; y++)
{
float* depthRow = depthMatrix.ptr<float>(y);
char* segmentationRow = segmentationMatrix.ptr<char>(y);
float* areaRow = areaMatrix.ptr<float>(y);
depthRow += x0;
segmentationRow += x0;
areaRow += x0;
for (int x = x0; x < x1; x++)
{
if (*segmentationRow == PixelType::Foreground)
{
float depth = *depthRow;
if (std::fabs(depth - startingDepth) < bandwidthDepth)
{
area += *areaRow;
}
}
++depthRow;
++areaRow;
++segmentationRow;
}
}
return area;
}
}
}}}
<|endoftext|> |
<commit_before>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_FUCHSIA)
#include "bin/extensions.h"
#include <dlfcn.h>
#include <fcntl.h>
#include <lib/fdio/io.h>
#include <zircon/dlfcn.h>
#include "platform/assert.h"
namespace dart {
namespace bin {
const char* kVmSnapshotDataSymbolName = "_kDartVmSnapshotData";
const char* kVmSnapshotInstructionsSymbolName = "_kDartVmSnapshotInstructions";
const char* kIsolateSnapshotDataSymbolName = "_kDartIsolateSnapshotData";
const char* kIsolateSnapshotInstructionsSymbolName =
"_kDartIsolateSnapshotInstructions";
void* Extensions::LoadExtensionLibrary(const char* library_file) {
int fd = open(library_file, O_RDONLY);
if (fd < 0) {
return NULL;
}
zx_handle_t vmo;
zx_status_t status = fdio_get_vmo_clone(fd, &vmo);
close(fd);
if (status != ZX_OK) {
return NULL;
}
return dlopen_vmo(vmo, RTLD_LAZY);
}
void* Extensions::ResolveSymbol(void* lib_handle, const char* symbol) {
dlerror();
return dlsym(lib_handle, symbol);
}
void Extensions::UnloadLibrary(void* lib_handle) {
dlerror();
int result = dlclose(lib_handle);
ASSERT(result == 0);
}
Dart_Handle Extensions::GetError() {
const char* err_str = dlerror();
if (err_str != NULL) {
return Dart_NewApiError(err_str);
}
return Dart_Null();
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_FUCHSIA)
<commit_msg>[fuchsia] Just use dlopen like on other OSes<commit_after>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_FUCHSIA)
#include "bin/extensions.h"
#include <dlfcn.h>
#include <fcntl.h>
#include <lib/fdio/io.h>
#include <zircon/dlfcn.h>
#include "platform/assert.h"
namespace dart {
namespace bin {
const char* kVmSnapshotDataSymbolName = "_kDartVmSnapshotData";
const char* kVmSnapshotInstructionsSymbolName = "_kDartVmSnapshotInstructions";
const char* kIsolateSnapshotDataSymbolName = "_kDartIsolateSnapshotData";
const char* kIsolateSnapshotInstructionsSymbolName =
"_kDartIsolateSnapshotInstructions";
void* Extensions::LoadExtensionLibrary(const char* library_file) {
return dlopen(library_file, RTLD_LAZY);
}
void* Extensions::ResolveSymbol(void* lib_handle, const char* symbol) {
dlerror();
return dlsym(lib_handle, symbol);
}
void Extensions::UnloadLibrary(void* lib_handle) {
dlerror();
int result = dlclose(lib_handle);
ASSERT(result == 0);
}
Dart_Handle Extensions::GetError() {
const char* err_str = dlerror();
if (err_str != NULL) {
return Dart_NewApiError(err_str);
}
return Dart_Null();
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_FUCHSIA)
<|endoftext|> |
<commit_before>#include "block.h"
#include <QtCore/QDebug>
#include "../robotsBlockParser.h"
using namespace qReal;
using namespace interpreters::robots::details;
using namespace blocks;
Block::Block()
: mNextBlock(NULL)
, mGraphicalModelApi(NULL)
, mLogicalModelApi(NULL)
, mBlocksTable(NULL)
, mGraphicalId(Id())
, mParser(NULL)
, mState(idle)
, mErrorReporter(NULL)
{
connect(this, SIGNAL(done(blocks::Block*const)), this, SLOT(finishedRunning()));
}
void Block::init(Id const &graphicalId
, GraphicalModelAssistInterface const &graphicalModelApi
, LogicalModelAssistInterface const &logicalModelApi
, BlocksTable &blocksTable
, ErrorReporterInterface * const errorReporter
, RobotsBlockParser * const parser)
{
mGraphicalId = graphicalId;
mGraphicalModelApi = &graphicalModelApi;
mLogicalModelApi = &logicalModelApi;
mBlocksTable = &blocksTable;
mErrorReporter = errorReporter;
mParser = parser;
additionalInit();
}
bool Block::initNextBlocks()
{
if (id() == Id() || id() == Id::rootId()) {
error(tr("Control flow break detected, stopping"));
return false;
}
IdList const links = mGraphicalModelApi->graphicalRepoApi().outgoingLinks(id());
if (links.count() > 1) {
error(tr("Too many outgoing links"));
return false;
}
if (links.count() == 0) {
error(tr("No outgoing links, please connect this block to something or use Final Node to end program"));
return false;
}
if (links.count() == 1) {
Id const nextBlockId = mGraphicalModelApi->graphicalRepoApi().otherEntityFromLink(links[0], id());
if (nextBlockId == Id()) {
error(tr("Outgoing link is not connected"));
return false;
}
mNextBlock = mBlocksTable->block(nextBlockId);
}
return true;
}
Id const Block::id() const
{
return mGraphicalId;
}
void Block::interpret()
{
if ((mState == running) || (mState == failed)) {
return;
}
mState = running;
bool result = initNextBlocks();
if (result) {
run();
}
}
void Block::setFailedStatus()
{
mState = failed;
}
void Block::setIdleStatus()
{
mState = idle;
}
void Block::finishedRunning()
{
mState = idle;
}
QVariant Block::property(QString const &propertyName) const
{
return property(id(), propertyName);
}
QString Block::stringProperty(QString const &propertyName) const
{
return stringProperty(id(), propertyName);
}
int Block::intProperty(QString const &propertyName) const
{
return intProperty(id(), propertyName);
}
bool Block::boolProperty(QString const &propertyName) const
{
return boolProperty(id(), propertyName);
}
QVariant Block::property(Id const &id, QString const &propertyName) const
{
Id const logicalId = mGraphicalModelApi->logicalId(id);
return mLogicalModelApi->propertyByRoleName(logicalId, propertyName);
}
QString Block::stringProperty(Id const &id, QString const &propertyName) const
{
return property(id, propertyName).toString();
}
int Block::intProperty(Id const &id, QString const &propertyName) const
{
return property(id, propertyName).toInt();
}
bool Block::boolProperty(Id const &id, QString const &propertyName) const
{
return property(id, propertyName).toBool();
}
void Block::error(QString const &message)
{
mErrorReporter->addError(message, id());
emit failure();
}
QList<Block::SensorPortPair> Block::usedSensors() const
{
return QList<SensorPortPair>();
}
QVariant Block::evaluate(const QString &propertyName)
{
int position = 0;
QVariant value = mParser->standartBlockParseProcess(stringProperty(propertyName), position, mGraphicalId).property("Number");
if (mParser->hasErrors()) {
mParser->deselect();
emit failure();
}
return value;
}
void Block::stopActiveTimerInBlock()
{
}
<commit_msg>Nicer error reporing about control flow break<commit_after>#include "block.h"
#include <QtCore/QDebug>
#include "../robotsBlockParser.h"
using namespace qReal;
using namespace interpreters::robots::details;
using namespace blocks;
Block::Block()
: mNextBlock(NULL)
, mGraphicalModelApi(NULL)
, mLogicalModelApi(NULL)
, mBlocksTable(NULL)
, mGraphicalId(Id())
, mParser(NULL)
, mState(idle)
, mErrorReporter(NULL)
{
connect(this, SIGNAL(done(blocks::Block*const)), this, SLOT(finishedRunning()));
}
void Block::init(Id const &graphicalId
, GraphicalModelAssistInterface const &graphicalModelApi
, LogicalModelAssistInterface const &logicalModelApi
, BlocksTable &blocksTable
, ErrorReporterInterface * const errorReporter
, RobotsBlockParser * const parser)
{
mGraphicalId = graphicalId;
mGraphicalModelApi = &graphicalModelApi;
mLogicalModelApi = &logicalModelApi;
mBlocksTable = &blocksTable;
mErrorReporter = errorReporter;
mParser = parser;
additionalInit();
}
bool Block::initNextBlocks()
{
if (id() == Id() || id() == Id::rootId()) {
error(tr("Control flow break detected, stopping"));
return false;
}
IdList const links = mGraphicalModelApi->graphicalRepoApi().outgoingLinks(id());
if (links.count() > 1) {
error(tr("Too many outgoing links"));
return false;
}
if (links.count() == 0) {
error(tr("No outgoing links, please connect this block to something or use Final Node to end program"));
return false;
}
if (links.count() == 1) {
Id const nextBlockId = mGraphicalModelApi->graphicalRepoApi().otherEntityFromLink(links[0], id());
if (nextBlockId == Id() || nextBlockId == Id::rootId()) {
error(tr("Outgoing link is not connected"));
return false;
}
mNextBlock = mBlocksTable->block(nextBlockId);
}
return true;
}
Id const Block::id() const
{
return mGraphicalId;
}
void Block::interpret()
{
if ((mState == running) || (mState == failed)) {
return;
}
mState = running;
bool result = initNextBlocks();
if (result) {
run();
}
}
void Block::setFailedStatus()
{
mState = failed;
}
void Block::setIdleStatus()
{
mState = idle;
}
void Block::finishedRunning()
{
mState = idle;
}
QVariant Block::property(QString const &propertyName) const
{
return property(id(), propertyName);
}
QString Block::stringProperty(QString const &propertyName) const
{
return stringProperty(id(), propertyName);
}
int Block::intProperty(QString const &propertyName) const
{
return intProperty(id(), propertyName);
}
bool Block::boolProperty(QString const &propertyName) const
{
return boolProperty(id(), propertyName);
}
QVariant Block::property(Id const &id, QString const &propertyName) const
{
Id const logicalId = mGraphicalModelApi->logicalId(id);
return mLogicalModelApi->propertyByRoleName(logicalId, propertyName);
}
QString Block::stringProperty(Id const &id, QString const &propertyName) const
{
return property(id, propertyName).toString();
}
int Block::intProperty(Id const &id, QString const &propertyName) const
{
return property(id, propertyName).toInt();
}
bool Block::boolProperty(Id const &id, QString const &propertyName) const
{
return property(id, propertyName).toBool();
}
void Block::error(QString const &message)
{
mErrorReporter->addError(message, id());
emit failure();
}
QList<Block::SensorPortPair> Block::usedSensors() const
{
return QList<SensorPortPair>();
}
QVariant Block::evaluate(const QString &propertyName)
{
int position = 0;
QVariant value = mParser->standartBlockParseProcess(stringProperty(propertyName), position, mGraphicalId).property("Number");
if (mParser->hasErrors()) {
mParser->deselect();
emit failure();
}
return value;
}
void Block::stopActiveTimerInBlock()
{
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexHex.cxx
** Lexer for Motorola S-Record.
**
** Written by Markus Heidelberg
**/
// Copyright 1998-2001 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
/*
* Motorola S-Record file format
* ===============================
*
* Each record (line) is built as follows:
*
* field digits states
*
* +----------+
* | start | 1 ('S') SCE_SREC_RECSTART
* +----------+
* | type | 1 SCE_SREC_RECTYPE
* +----------+
* | count | 2 SCE_SREC_BYTECOUNT, SCE_SREC_BYTECOUNT_WRONG
* +----------+
* | address | 4/6/8 SCE_SREC_NOADDRESS, SCE_SREC_DATAADDRESS, SCE_SREC_RECCOUNT, SCE_SREC_STARTADDRESS, (SCE_SREC_ADDRESSFIELD_UNKNOWN)
* +----------+
* | data | 0..504/502/500 SCE_SREC_DATA_ODD, SCE_SREC_DATA_EVEN, (SCE_SREC_DATA_UNKNOWN)
* +----------+
* | checksum | 2 SCE_SREC_CHECKSUM, SCE_SREC_CHECKSUM_WRONG
* +----------+
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// prototypes for general helper functions
static inline bool IsNewline(const int ch);
static int GetHexaChar(char hd1, char hd2);
static int GetHexaChar(unsigned int pos, Accessor &styler);
static bool ForwardWithinLine(StyleContext &sc, int nb = 1);
// prototypes for file format specific helper functions
static unsigned int GetSrecRecStartPosition(unsigned int pos, Accessor &styler);
static int GetSrecByteCount(unsigned int recStartPos, Accessor &styler);
static int CountSrecByteCount(unsigned int recStartPos, Accessor &styler);
static int GetSrecAddressFieldSize(unsigned int recStartPos, Accessor &styler);
static int GetSrecAddressFieldType(unsigned int recStartPos, Accessor &styler);
static int GetSrecChecksum(unsigned int recStartPos, Accessor &styler);
static int CalcSrecChecksum(unsigned int recStartPos, Accessor &styler);
static inline bool IsNewline(const int ch)
{
return (ch == '\n' || ch == '\r');
}
static int GetHexaChar(char hd1, char hd2)
{
int hexValue = 0;
if (hd1 >= '0' && hd1 <= '9') {
hexValue += 16 * (hd1 - '0');
} else if (hd1 >= 'A' && hd1 <= 'F') {
hexValue += 16 * (hd1 - 'A' + 10);
} else if (hd1 >= 'a' && hd1 <= 'f') {
hexValue += 16 * (hd1 - 'a' + 10);
} else {
return -1;
}
if (hd2 >= '0' && hd2 <= '9') {
hexValue += hd2 - '0';
} else if (hd2 >= 'A' && hd2 <= 'F') {
hexValue += hd2 - 'A' + 10;
} else if (hd2 >= 'a' && hd2 <= 'f') {
hexValue += hd2 - 'a' + 10;
} else {
return -1;
}
return hexValue;
}
static int GetHexaChar(unsigned int pos, Accessor &styler)
{
char highNibble, lowNibble;
highNibble = styler.SafeGetCharAt(pos);
lowNibble = styler.SafeGetCharAt(pos + 1);
return GetHexaChar(highNibble, lowNibble);
}
// Forward <nb> characters, but abort (and return false) if hitting the line
// end. Return true if forwarding within the line was possible.
// Avoids influence on highlighting of the subsequent line if the current line
// is malformed (too short).
static bool ForwardWithinLine(StyleContext &sc, int nb)
{
for (int i = 0; i < nb; i++) {
if (sc.atLineEnd) {
// line is too short
sc.SetState(SCE_SREC_DEFAULT);
sc.Forward();
return false;
} else {
sc.Forward();
}
}
return true;
}
// Get the position of the record "start" field (first character in line) in
// the record around position <pos>.
static unsigned int GetSrecRecStartPosition(unsigned int pos, Accessor &styler)
{
while (styler.SafeGetCharAt(pos) != 'S') {
pos--;
}
return pos;
}
// Get the value of the "byte count" field, it counts the number of bytes in
// the subsequent fields ("address", "data" and "checksum" fields).
static int GetSrecByteCount(unsigned int recStartPos, Accessor &styler)
{
int val;
val = GetHexaChar(recStartPos + 2, styler);
if (val < 0) {
val = 0;
}
return val;
}
// Count the number of digit pairs for the "address", "data" and "checksum"
// fields in this record. Has to be equal to the "byte count" field value.
// If the record is too short, a negative count may be returned.
static int CountSrecByteCount(unsigned int recStartPos, Accessor &styler)
{
int cnt;
unsigned int pos;
pos = recStartPos;
while (!IsNewline(styler.SafeGetCharAt(pos, '\n'))) {
pos++;
}
// number of digits in this line minus number of digits of uncounted fields
cnt = static_cast<int>(pos - recStartPos) - 4;
// Prepare round up if odd (digit pair incomplete), this way the byte
// count is considered to be valid if the checksum is incomplete.
if (cnt >= 0) {
cnt++;
}
// digit pairs
cnt /= 2;
return cnt;
}
// Get the size of the "address" field.
static int GetSrecAddressFieldSize(unsigned int recStartPos, Accessor &styler)
{
switch (styler.SafeGetCharAt(recStartPos + 1)) {
case '0':
case '1':
case '5':
case '9':
return 2; // 16 bit
case '2':
case '6':
case '8':
return 3; // 24 bit
case '3':
case '7':
return 4; // 32 bit
default:
return 0;
}
}
// Get the type of the "address" field content.
static int GetSrecAddressFieldType(unsigned int recStartPos, Accessor &styler)
{
switch (styler.SafeGetCharAt(recStartPos + 1)) {
case '0':
return SCE_SREC_NOADDRESS;
case '1':
case '2':
case '3':
return SCE_SREC_DATAADDRESS;
case '5':
case '6':
return SCE_SREC_RECCOUNT;
case '7':
case '8':
case '9':
return SCE_SREC_STARTADDRESS;
default: // handle possible format extension in the future
return SCE_SREC_ADDRESSFIELD_UNKNOWN;
}
}
// Get the value of the "checksum" field.
static int GetSrecChecksum(unsigned int recStartPos, Accessor &styler)
{
int byteCount;
byteCount = GetSrecByteCount(recStartPos, styler);
return GetHexaChar(recStartPos + 2 + byteCount * 2, styler);
}
// Calculate the checksum of the record.
static int CalcSrecChecksum(unsigned int recStartPos, Accessor &styler)
{
int byteCount;
unsigned int cs = 0;
byteCount = GetSrecByteCount(recStartPos, styler);
// sum over "byte count", "address" and "data" fields (6..510 digits)
for (unsigned int pos = recStartPos + 2; pos < recStartPos + 2 + byteCount * 2; pos += 2) {
int val = GetHexaChar(pos, styler);
if (val < 0) {
return val;
}
cs += val;
}
// low byte of one's complement
return (~cs) & 0xFF;
}
static void ColouriseSrecDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler)
{
StyleContext sc(startPos, length, initStyle, styler);
while (sc.More()) {
unsigned int recStartPos;
int byteCount, addrFieldSize, addrFieldType, dataFieldSize;
int cs1, cs2;
switch (sc.state) {
case SCE_SREC_DEFAULT:
if (sc.atLineStart && sc.Match('S')) {
sc.SetState(SCE_SREC_RECSTART);
}
ForwardWithinLine(sc);
break;
case SCE_SREC_RECSTART:
sc.SetState(SCE_SREC_RECTYPE);
ForwardWithinLine(sc);
break;
case SCE_SREC_RECTYPE:
recStartPos = sc.currentPos - 2;
byteCount = GetSrecByteCount(recStartPos, styler);
if (byteCount == CountSrecByteCount(recStartPos, styler)) {
sc.SetState(SCE_SREC_BYTECOUNT);
} else {
sc.SetState(SCE_SREC_BYTECOUNT_WRONG);
}
ForwardWithinLine(sc, 2);
break;
case SCE_SREC_BYTECOUNT:
case SCE_SREC_BYTECOUNT_WRONG:
recStartPos = sc.currentPos - 4;
addrFieldSize = GetSrecAddressFieldSize(recStartPos, styler);
addrFieldType = GetSrecAddressFieldType(recStartPos, styler);
sc.SetState(addrFieldType);
ForwardWithinLine(sc, addrFieldSize * 2);
break;
case SCE_SREC_NOADDRESS:
case SCE_SREC_DATAADDRESS:
case SCE_SREC_RECCOUNT:
case SCE_SREC_STARTADDRESS:
case SCE_SREC_ADDRESSFIELD_UNKNOWN:
recStartPos = GetSrecRecStartPosition(sc.currentPos, styler);
byteCount = GetSrecByteCount(recStartPos, styler);
addrFieldSize = GetSrecAddressFieldSize(recStartPos, styler);
dataFieldSize = byteCount - addrFieldSize - 1; // -1 for checksum field
if (sc.state == SCE_SREC_ADDRESSFIELD_UNKNOWN) {
sc.SetState(SCE_SREC_DATA_UNKNOWN);
ForwardWithinLine(sc, dataFieldSize * 2);
break;
}
sc.SetState(SCE_SREC_DATA_ODD);
for (int i = 0; i < dataFieldSize * 2; i++) {
if ((i & 0x3) == 0) {
sc.SetState(SCE_SREC_DATA_ODD);
} else if ((i & 0x3) == 2) {
sc.SetState(SCE_SREC_DATA_EVEN);
}
if (!ForwardWithinLine(sc)) {
break;
}
}
break;
case SCE_SREC_DATA_ODD:
case SCE_SREC_DATA_EVEN:
case SCE_SREC_DATA_UNKNOWN:
recStartPos = GetSrecRecStartPosition(sc.currentPos, styler);
cs1 = CalcSrecChecksum(recStartPos, styler);
cs2 = GetSrecChecksum(recStartPos, styler);
if (cs1 != cs2 || cs1 < 0 || cs2 < 0) {
sc.SetState(SCE_SREC_CHECKSUM_WRONG);
} else {
sc.SetState(SCE_SREC_CHECKSUM);
}
ForwardWithinLine(sc, 2);
break;
case SCE_SREC_CHECKSUM:
case SCE_SREC_CHECKSUM_WRONG:
// record finished
sc.SetState(SCE_SREC_DEFAULT);
ForwardWithinLine(sc);
break;
}
}
sc.Complete();
}
LexerModule lmSrec(SCLEX_SREC, ColouriseSrecDoc, "srec", 0, NULL);
<commit_msg>S-Record lexer: extract reusable parts of helper functions CalcChecksum() takes a parameter to decide between one's or two's complement. The variable "cs" has been changed to "signed int" to simplifiy calculation of the two's complement with signed arithmetic instead of using bitwise operations, which would cause "overflow" warnings in Coverity without additional "& 0xFF" masking.<commit_after>// Scintilla source code edit control
/** @file LexHex.cxx
** Lexer for Motorola S-Record.
**
** Written by Markus Heidelberg
**/
// Copyright 1998-2001 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
/*
* Motorola S-Record file format
* ===============================
*
* Each record (line) is built as follows:
*
* field digits states
*
* +----------+
* | start | 1 ('S') SCE_SREC_RECSTART
* +----------+
* | type | 1 SCE_SREC_RECTYPE
* +----------+
* | count | 2 SCE_SREC_BYTECOUNT, SCE_SREC_BYTECOUNT_WRONG
* +----------+
* | address | 4/6/8 SCE_SREC_NOADDRESS, SCE_SREC_DATAADDRESS, SCE_SREC_RECCOUNT, SCE_SREC_STARTADDRESS, (SCE_SREC_ADDRESSFIELD_UNKNOWN)
* +----------+
* | data | 0..504/502/500 SCE_SREC_DATA_ODD, SCE_SREC_DATA_EVEN, (SCE_SREC_DATA_UNKNOWN)
* +----------+
* | checksum | 2 SCE_SREC_CHECKSUM, SCE_SREC_CHECKSUM_WRONG
* +----------+
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// prototypes for general helper functions
static inline bool IsNewline(const int ch);
static int GetHexaChar(char hd1, char hd2);
static int GetHexaChar(unsigned int pos, Accessor &styler);
static bool ForwardWithinLine(StyleContext &sc, int nb = 1);
static int CountByteCount(unsigned int startPos, int uncountedDigits, Accessor &styler);
static int CalcChecksum(unsigned int startPos, int cnt, bool twosCompl, Accessor &styler);
// prototypes for file format specific helper functions
static unsigned int GetSrecRecStartPosition(unsigned int pos, Accessor &styler);
static int GetSrecByteCount(unsigned int recStartPos, Accessor &styler);
static int CountSrecByteCount(unsigned int recStartPos, Accessor &styler);
static int GetSrecAddressFieldSize(unsigned int recStartPos, Accessor &styler);
static int GetSrecAddressFieldType(unsigned int recStartPos, Accessor &styler);
static int GetSrecChecksum(unsigned int recStartPos, Accessor &styler);
static int CalcSrecChecksum(unsigned int recStartPos, Accessor &styler);
static inline bool IsNewline(const int ch)
{
return (ch == '\n' || ch == '\r');
}
static int GetHexaChar(char hd1, char hd2)
{
int hexValue = 0;
if (hd1 >= '0' && hd1 <= '9') {
hexValue += 16 * (hd1 - '0');
} else if (hd1 >= 'A' && hd1 <= 'F') {
hexValue += 16 * (hd1 - 'A' + 10);
} else if (hd1 >= 'a' && hd1 <= 'f') {
hexValue += 16 * (hd1 - 'a' + 10);
} else {
return -1;
}
if (hd2 >= '0' && hd2 <= '9') {
hexValue += hd2 - '0';
} else if (hd2 >= 'A' && hd2 <= 'F') {
hexValue += hd2 - 'A' + 10;
} else if (hd2 >= 'a' && hd2 <= 'f') {
hexValue += hd2 - 'a' + 10;
} else {
return -1;
}
return hexValue;
}
static int GetHexaChar(unsigned int pos, Accessor &styler)
{
char highNibble, lowNibble;
highNibble = styler.SafeGetCharAt(pos);
lowNibble = styler.SafeGetCharAt(pos + 1);
return GetHexaChar(highNibble, lowNibble);
}
// Forward <nb> characters, but abort (and return false) if hitting the line
// end. Return true if forwarding within the line was possible.
// Avoids influence on highlighting of the subsequent line if the current line
// is malformed (too short).
static bool ForwardWithinLine(StyleContext &sc, int nb)
{
for (int i = 0; i < nb; i++) {
if (sc.atLineEnd) {
// line is too short
sc.SetState(SCE_SREC_DEFAULT);
sc.Forward();
return false;
} else {
sc.Forward();
}
}
return true;
}
// Count the number of digit pairs from <startPos> till end of record, ignoring
// <uncountedDigits> digits.
// If the record is too short, a negative count may be returned.
static int CountByteCount(unsigned int startPos, int uncountedDigits, Accessor &styler)
{
int cnt;
unsigned int pos;
pos = startPos;
while (!IsNewline(styler.SafeGetCharAt(pos, '\n'))) {
pos++;
}
// number of digits in this line minus number of digits of uncounted fields
cnt = static_cast<int>(pos - startPos) - uncountedDigits;
// Prepare round up if odd (digit pair incomplete), this way the byte
// count is considered to be valid if the checksum is incomplete.
if (cnt >= 0) {
cnt++;
}
// digit pairs
cnt /= 2;
return cnt;
}
// Calculate the checksum of the record.
// <startPos> is the position of the first character of the starting digit
// pair, <cnt> is the number of digit pairs.
static int CalcChecksum(unsigned int startPos, int cnt, bool twosCompl, Accessor &styler)
{
int cs = 0;
for (unsigned int pos = startPos; pos < startPos + cnt; pos += 2) {
int val = GetHexaChar(pos, styler);
if (val < 0) {
return val;
}
// overflow does not matter
cs += val;
}
if (twosCompl) {
// low byte of two's complement
return -cs & 0xFF;
} else {
// low byte of one's complement
return ~cs & 0xFF;
}
}
// Get the position of the record "start" field (first character in line) in
// the record around position <pos>.
static unsigned int GetSrecRecStartPosition(unsigned int pos, Accessor &styler)
{
while (styler.SafeGetCharAt(pos) != 'S') {
pos--;
}
return pos;
}
// Get the value of the "byte count" field, it counts the number of bytes in
// the subsequent fields ("address", "data" and "checksum" fields).
static int GetSrecByteCount(unsigned int recStartPos, Accessor &styler)
{
int val;
val = GetHexaChar(recStartPos + 2, styler);
if (val < 0) {
val = 0;
}
return val;
}
// Count the number of digit pairs for the "address", "data" and "checksum"
// fields in this record. Has to be equal to the "byte count" field value.
// If the record is too short, a negative count may be returned.
static int CountSrecByteCount(unsigned int recStartPos, Accessor &styler)
{
return CountByteCount(recStartPos, 4, styler);
}
// Get the size of the "address" field.
static int GetSrecAddressFieldSize(unsigned int recStartPos, Accessor &styler)
{
switch (styler.SafeGetCharAt(recStartPos + 1)) {
case '0':
case '1':
case '5':
case '9':
return 2; // 16 bit
case '2':
case '6':
case '8':
return 3; // 24 bit
case '3':
case '7':
return 4; // 32 bit
default:
return 0;
}
}
// Get the type of the "address" field content.
static int GetSrecAddressFieldType(unsigned int recStartPos, Accessor &styler)
{
switch (styler.SafeGetCharAt(recStartPos + 1)) {
case '0':
return SCE_SREC_NOADDRESS;
case '1':
case '2':
case '3':
return SCE_SREC_DATAADDRESS;
case '5':
case '6':
return SCE_SREC_RECCOUNT;
case '7':
case '8':
case '9':
return SCE_SREC_STARTADDRESS;
default: // handle possible format extension in the future
return SCE_SREC_ADDRESSFIELD_UNKNOWN;
}
}
// Get the value of the "checksum" field.
static int GetSrecChecksum(unsigned int recStartPos, Accessor &styler)
{
int byteCount;
byteCount = GetSrecByteCount(recStartPos, styler);
return GetHexaChar(recStartPos + 2 + byteCount * 2, styler);
}
// Calculate the checksum of the record.
static int CalcSrecChecksum(unsigned int recStartPos, Accessor &styler)
{
int byteCount;
byteCount = GetSrecByteCount(recStartPos, styler);
// sum over "byte count", "address" and "data" fields (6..510 digits)
return CalcChecksum(recStartPos + 2, byteCount * 2, false, styler);
}
static void ColouriseSrecDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler)
{
StyleContext sc(startPos, length, initStyle, styler);
while (sc.More()) {
unsigned int recStartPos;
int byteCount, addrFieldSize, addrFieldType, dataFieldSize;
int cs1, cs2;
switch (sc.state) {
case SCE_SREC_DEFAULT:
if (sc.atLineStart && sc.Match('S')) {
sc.SetState(SCE_SREC_RECSTART);
}
ForwardWithinLine(sc);
break;
case SCE_SREC_RECSTART:
sc.SetState(SCE_SREC_RECTYPE);
ForwardWithinLine(sc);
break;
case SCE_SREC_RECTYPE:
recStartPos = sc.currentPos - 2;
byteCount = GetSrecByteCount(recStartPos, styler);
if (byteCount == CountSrecByteCount(recStartPos, styler)) {
sc.SetState(SCE_SREC_BYTECOUNT);
} else {
sc.SetState(SCE_SREC_BYTECOUNT_WRONG);
}
ForwardWithinLine(sc, 2);
break;
case SCE_SREC_BYTECOUNT:
case SCE_SREC_BYTECOUNT_WRONG:
recStartPos = sc.currentPos - 4;
addrFieldSize = GetSrecAddressFieldSize(recStartPos, styler);
addrFieldType = GetSrecAddressFieldType(recStartPos, styler);
sc.SetState(addrFieldType);
ForwardWithinLine(sc, addrFieldSize * 2);
break;
case SCE_SREC_NOADDRESS:
case SCE_SREC_DATAADDRESS:
case SCE_SREC_RECCOUNT:
case SCE_SREC_STARTADDRESS:
case SCE_SREC_ADDRESSFIELD_UNKNOWN:
recStartPos = GetSrecRecStartPosition(sc.currentPos, styler);
byteCount = GetSrecByteCount(recStartPos, styler);
addrFieldSize = GetSrecAddressFieldSize(recStartPos, styler);
dataFieldSize = byteCount - addrFieldSize - 1; // -1 for checksum field
if (sc.state == SCE_SREC_ADDRESSFIELD_UNKNOWN) {
sc.SetState(SCE_SREC_DATA_UNKNOWN);
ForwardWithinLine(sc, dataFieldSize * 2);
break;
}
sc.SetState(SCE_SREC_DATA_ODD);
for (int i = 0; i < dataFieldSize * 2; i++) {
if ((i & 0x3) == 0) {
sc.SetState(SCE_SREC_DATA_ODD);
} else if ((i & 0x3) == 2) {
sc.SetState(SCE_SREC_DATA_EVEN);
}
if (!ForwardWithinLine(sc)) {
break;
}
}
break;
case SCE_SREC_DATA_ODD:
case SCE_SREC_DATA_EVEN:
case SCE_SREC_DATA_UNKNOWN:
recStartPos = GetSrecRecStartPosition(sc.currentPos, styler);
cs1 = CalcSrecChecksum(recStartPos, styler);
cs2 = GetSrecChecksum(recStartPos, styler);
if (cs1 != cs2 || cs1 < 0 || cs2 < 0) {
sc.SetState(SCE_SREC_CHECKSUM_WRONG);
} else {
sc.SetState(SCE_SREC_CHECKSUM);
}
ForwardWithinLine(sc, 2);
break;
case SCE_SREC_CHECKSUM:
case SCE_SREC_CHECKSUM_WRONG:
// record finished
sc.SetState(SCE_SREC_DEFAULT);
ForwardWithinLine(sc);
break;
}
}
sc.Complete();
}
LexerModule lmSrec(SCLEX_SREC, ColouriseSrecDoc, "srec", 0, NULL);
<|endoftext|> |
<commit_before>/* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
#include "build/Protocol/Client.pb.h"
#include "Core/Time.h"
#include "RPC/Buffer.h"
#include "RPC/ProtoBuf.h"
#include "RPC/ServerRPC.h"
#include "Server/RaftConsensus.h"
#include "Server/ClientService.h"
#include "Server/Globals.h"
#include "Server/StateMachine.h"
namespace LogCabin {
namespace Server {
ClientService::ClientService(Globals& globals)
: globals(globals)
{
}
ClientService::~ClientService()
{
}
void
ClientService::handleRPC(RPC::ServerRPC rpc)
{
using Protocol::Client::OpCode;
// TODO(ongaro): If this is not the current cluster leader, need to
// redirect the client.
// Call the appropriate RPC handler based on the request's opCode.
switch (rpc.getOpCode()) {
case OpCode::GET_SUPPORTED_RPC_VERSIONS:
getSupportedRPCVersions(std::move(rpc));
break;
case OpCode::GET_CONFIGURATION:
getConfiguration(std::move(rpc));
break;
case OpCode::SET_CONFIGURATION:
setConfiguration(std::move(rpc));
break;
case OpCode::OPEN_SESSION:
openSession(std::move(rpc));
break;
case OpCode::READ_ONLY_TREE:
readOnlyTreeRPC(std::move(rpc));
break;
case OpCode::READ_WRITE_TREE:
readWriteTreeRPC(std::move(rpc));
break;
default:
rpc.rejectInvalidRequest();
}
}
std::string
ClientService::getName() const
{
return "ClientService";
}
/**
* Place this at the top of each RPC handler. Afterwards, 'request' will refer
* to the protocol buffer for the request with all required fields set.
* 'response' will be an empty protocol buffer for you to fill in the response.
*/
#define PRELUDE(rpcClass) \
Protocol::Client::rpcClass::Request request; \
Protocol::Client::rpcClass::Response response; \
if (!rpc.getRequest(request)) \
return;
////////// RPC handlers //////////
void
ClientService::getSupportedRPCVersions(RPC::ServerRPC rpc)
{
PRELUDE(GetSupportedRPCVersions);
response.set_min_version(1);
response.set_max_version(1);
rpc.reply(response);
}
typedef RaftConsensus::ClientResult Result;
typedef Protocol::Client::Command Command;
typedef Protocol::Client::CommandResponse CommandResponse;
std::pair<Result, uint64_t>
ClientService::submit(RPC::ServerRPC& rpc,
const google::protobuf::Message& command)
{
// TODO(ongaro): Switch from string to binary format. This is probably
// really slow to serialize.
std::string cmdStr = Core::ProtoBuf::dumpString(command);
std::pair<Result, uint64_t> result = globals.raft->replicate(cmdStr);
if (result.first == Result::RETRY || result.first == Result::NOT_LEADER) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::NOT_LEADER);
std::string leaderHint = globals.raft->getLeaderHint();
if (!leaderHint.empty())
error.set_leader_hint(leaderHint);
rpc.returnError(error);
}
return result;
}
Result
ClientService::catchUpStateMachine(RPC::ServerRPC& rpc)
{
std::pair<Result, uint64_t> result = globals.raft->getLastCommittedId();
if (result.first == Result::RETRY || result.first == Result::NOT_LEADER) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::NOT_LEADER);
std::string leaderHint = globals.raft->getLeaderHint();
if (!leaderHint.empty())
error.set_leader_hint(leaderHint);
rpc.returnError(error);
return result.first;
}
globals.stateMachine->wait(result.second);
return result.first;
}
bool
ClientService::getResponse(RPC::ServerRPC& rpc,
uint64_t entryId,
const Protocol::Client::ExactlyOnceRPCInfo& rpcInfo,
Protocol::Client::CommandResponse& response)
{
globals.stateMachine->wait(entryId);
bool ok = globals.stateMachine->getResponse(rpcInfo, response);
if (!ok) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::SESSION_EXPIRED);
rpc.returnError(error);
return false;
}
return true;
}
void
ClientService::openSession(RPC::ServerRPC rpc)
{
PRELUDE(OpenSession);
Command command;
command.set_nanoseconds_since_epoch(Core::Time::getTimeNanos());
*command.mutable_open_session() = request;
std::pair<Result, uint64_t> result = submit(rpc, command);
if (result.first != Result::SUCCESS)
return;
response.set_client_id(result.second);
rpc.reply(response);
}
void
ClientService::getConfiguration(RPC::ServerRPC rpc)
{
PRELUDE(GetConfiguration);
Protocol::Raft::SimpleConfiguration configuration;
uint64_t id;
Result result = globals.raft->getConfiguration(configuration, id);
if (result == Result::RETRY || result == Result::NOT_LEADER) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::NOT_LEADER);
std::string leaderHint = globals.raft->getLeaderHint();
if (!leaderHint.empty())
error.set_leader_hint(leaderHint);
rpc.returnError(error);
return;
}
response.set_id(id);
for (auto it = configuration.servers().begin();
it != configuration.servers().end();
++it) {
Protocol::Client::Server* server = response.add_servers();
server->set_server_id(it->server_id());
server->set_address(it->address());
}
rpc.reply(response);
}
void
ClientService::setConfiguration(RPC::ServerRPC rpc)
{
PRELUDE(SetConfiguration);
Protocol::Raft::SimpleConfiguration newConfiguration;
for (auto it = request.new_servers().begin();
it != request.new_servers().end();
++it) {
Protocol::Raft::Server* s = newConfiguration.add_servers();
s->set_server_id(it->server_id());
s->set_address(it->address());
}
Result result = globals.raft->setConfiguration(
request.old_id(),
newConfiguration);
if (result == Result::SUCCESS) {
response.mutable_ok();
} else if (result == Result::RETRY || result == Result::NOT_LEADER) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::NOT_LEADER);
std::string leaderHint = globals.raft->getLeaderHint();
if (!leaderHint.empty())
error.set_leader_hint(leaderHint);
rpc.returnError(error);
return;
} else if (result == Result::FAIL) {
// TODO(ongaro): can't distinguish changed from bad
response.mutable_configuration_changed();
}
rpc.reply(response);
}
void
ClientService::readOnlyTreeRPC(RPC::ServerRPC rpc)
{
PRELUDE(ReadOnlyTree);
if (catchUpStateMachine(rpc) != Result::SUCCESS)
return;
globals.stateMachine->readOnlyTreeRPC(request, response);
rpc.reply(response);
}
void
ClientService::readWriteTreeRPC(RPC::ServerRPC rpc)
{
PRELUDE(ReadWriteTree);
Command command;
command.set_nanoseconds_since_epoch(Core::Time::getTimeNanos());
*command.mutable_tree() = request;
std::pair<Result, uint64_t> result = submit(rpc, command);
if (result.first != Result::SUCCESS)
return;
CommandResponse commandResponse;
if (!getResponse(rpc, result.second, request.exactly_once(),
commandResponse)) {
return;
}
rpc.reply(commandResponse.tree());
}
} // namespace LogCabin::Server
} // namespace LogCabin
<commit_msg>Remove stale TODO<commit_after>/* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
#include "build/Protocol/Client.pb.h"
#include "Core/Time.h"
#include "RPC/Buffer.h"
#include "RPC/ProtoBuf.h"
#include "RPC/ServerRPC.h"
#include "Server/RaftConsensus.h"
#include "Server/ClientService.h"
#include "Server/Globals.h"
#include "Server/StateMachine.h"
namespace LogCabin {
namespace Server {
ClientService::ClientService(Globals& globals)
: globals(globals)
{
}
ClientService::~ClientService()
{
}
void
ClientService::handleRPC(RPC::ServerRPC rpc)
{
using Protocol::Client::OpCode;
// Call the appropriate RPC handler based on the request's opCode.
switch (rpc.getOpCode()) {
case OpCode::GET_SUPPORTED_RPC_VERSIONS:
getSupportedRPCVersions(std::move(rpc));
break;
case OpCode::GET_CONFIGURATION:
getConfiguration(std::move(rpc));
break;
case OpCode::SET_CONFIGURATION:
setConfiguration(std::move(rpc));
break;
case OpCode::OPEN_SESSION:
openSession(std::move(rpc));
break;
case OpCode::READ_ONLY_TREE:
readOnlyTreeRPC(std::move(rpc));
break;
case OpCode::READ_WRITE_TREE:
readWriteTreeRPC(std::move(rpc));
break;
default:
rpc.rejectInvalidRequest();
}
}
std::string
ClientService::getName() const
{
return "ClientService";
}
/**
* Place this at the top of each RPC handler. Afterwards, 'request' will refer
* to the protocol buffer for the request with all required fields set.
* 'response' will be an empty protocol buffer for you to fill in the response.
*/
#define PRELUDE(rpcClass) \
Protocol::Client::rpcClass::Request request; \
Protocol::Client::rpcClass::Response response; \
if (!rpc.getRequest(request)) \
return;
////////// RPC handlers //////////
void
ClientService::getSupportedRPCVersions(RPC::ServerRPC rpc)
{
PRELUDE(GetSupportedRPCVersions);
response.set_min_version(1);
response.set_max_version(1);
rpc.reply(response);
}
typedef RaftConsensus::ClientResult Result;
typedef Protocol::Client::Command Command;
typedef Protocol::Client::CommandResponse CommandResponse;
std::pair<Result, uint64_t>
ClientService::submit(RPC::ServerRPC& rpc,
const google::protobuf::Message& command)
{
// TODO(ongaro): Switch from string to binary format. This is probably
// really slow to serialize.
std::string cmdStr = Core::ProtoBuf::dumpString(command);
std::pair<Result, uint64_t> result = globals.raft->replicate(cmdStr);
if (result.first == Result::RETRY || result.first == Result::NOT_LEADER) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::NOT_LEADER);
std::string leaderHint = globals.raft->getLeaderHint();
if (!leaderHint.empty())
error.set_leader_hint(leaderHint);
rpc.returnError(error);
}
return result;
}
Result
ClientService::catchUpStateMachine(RPC::ServerRPC& rpc)
{
std::pair<Result, uint64_t> result = globals.raft->getLastCommittedId();
if (result.first == Result::RETRY || result.first == Result::NOT_LEADER) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::NOT_LEADER);
std::string leaderHint = globals.raft->getLeaderHint();
if (!leaderHint.empty())
error.set_leader_hint(leaderHint);
rpc.returnError(error);
return result.first;
}
globals.stateMachine->wait(result.second);
return result.first;
}
bool
ClientService::getResponse(RPC::ServerRPC& rpc,
uint64_t entryId,
const Protocol::Client::ExactlyOnceRPCInfo& rpcInfo,
Protocol::Client::CommandResponse& response)
{
globals.stateMachine->wait(entryId);
bool ok = globals.stateMachine->getResponse(rpcInfo, response);
if (!ok) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::SESSION_EXPIRED);
rpc.returnError(error);
return false;
}
return true;
}
void
ClientService::openSession(RPC::ServerRPC rpc)
{
PRELUDE(OpenSession);
Command command;
command.set_nanoseconds_since_epoch(Core::Time::getTimeNanos());
*command.mutable_open_session() = request;
std::pair<Result, uint64_t> result = submit(rpc, command);
if (result.first != Result::SUCCESS)
return;
response.set_client_id(result.second);
rpc.reply(response);
}
void
ClientService::getConfiguration(RPC::ServerRPC rpc)
{
PRELUDE(GetConfiguration);
Protocol::Raft::SimpleConfiguration configuration;
uint64_t id;
Result result = globals.raft->getConfiguration(configuration, id);
if (result == Result::RETRY || result == Result::NOT_LEADER) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::NOT_LEADER);
std::string leaderHint = globals.raft->getLeaderHint();
if (!leaderHint.empty())
error.set_leader_hint(leaderHint);
rpc.returnError(error);
return;
}
response.set_id(id);
for (auto it = configuration.servers().begin();
it != configuration.servers().end();
++it) {
Protocol::Client::Server* server = response.add_servers();
server->set_server_id(it->server_id());
server->set_address(it->address());
}
rpc.reply(response);
}
void
ClientService::setConfiguration(RPC::ServerRPC rpc)
{
PRELUDE(SetConfiguration);
Protocol::Raft::SimpleConfiguration newConfiguration;
for (auto it = request.new_servers().begin();
it != request.new_servers().end();
++it) {
Protocol::Raft::Server* s = newConfiguration.add_servers();
s->set_server_id(it->server_id());
s->set_address(it->address());
}
Result result = globals.raft->setConfiguration(
request.old_id(),
newConfiguration);
if (result == Result::SUCCESS) {
response.mutable_ok();
} else if (result == Result::RETRY || result == Result::NOT_LEADER) {
Protocol::Client::Error error;
error.set_error_code(Protocol::Client::Error::NOT_LEADER);
std::string leaderHint = globals.raft->getLeaderHint();
if (!leaderHint.empty())
error.set_leader_hint(leaderHint);
rpc.returnError(error);
return;
} else if (result == Result::FAIL) {
// TODO(ongaro): can't distinguish changed from bad
response.mutable_configuration_changed();
}
rpc.reply(response);
}
void
ClientService::readOnlyTreeRPC(RPC::ServerRPC rpc)
{
PRELUDE(ReadOnlyTree);
if (catchUpStateMachine(rpc) != Result::SUCCESS)
return;
globals.stateMachine->readOnlyTreeRPC(request, response);
rpc.reply(response);
}
void
ClientService::readWriteTreeRPC(RPC::ServerRPC rpc)
{
PRELUDE(ReadWriteTree);
Command command;
command.set_nanoseconds_since_epoch(Core::Time::getTimeNanos());
*command.mutable_tree() = request;
std::pair<Result, uint64_t> result = submit(rpc, command);
if (result.first != Result::SUCCESS)
return;
CommandResponse commandResponse;
if (!getResponse(rpc, result.second, request.exactly_once(),
commandResponse)) {
return;
}
rpc.reply(commandResponse.tree());
}
} // namespace LogCabin::Server
} // namespace LogCabin
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexTCL.cxx
** Lexer for TCL language.
**/
// Copyright 1998-2001 by Andre Arpin <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '_' || ch ==':' || ch=='.'); // : name space separator
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 || (ch ==':' || isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(IsADigit(ch, 0x10) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+');
}
static void ColouriseTCLDoc(unsigned int startPos, int length, int , WordList *keywordlists[], Accessor &styler) {
#define isComment(s) (s==SCE_TCL_COMMENT || s==SCE_TCL_COMMENTLINE || s==SCE_TCL_COMMENT_BOX || s==SCE_TCL_BLOCK_COMMENT)
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool commentLevel = false;
bool subBrace = false; // substitution begin with a brace ${.....}
enum tLineState {LS_DEFAULT, LS_OPEN_COMMENT, LS_OPEN_DOUBLE_QUOTE, LS_COMMENT_BOX, LS_MASK_STATE = 0xf,
LS_COMMAND_EXPECTED = 16, LS_BRACE_ONLY = 32 } lineState = LS_DEFAULT;
bool prevSlash = false;
int currentLevel = 0;
bool expected = 0;
bool subParen = 0;
int currentLine = styler.GetLine(startPos);
if (currentLine > 0)
currentLine--;
length += startPos - styler.LineStart(currentLine);
// make sure lines overlap
startPos = styler.LineStart(currentLine);
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
WordList &keywords9 = *keywordlists[8];
if (currentLine > 0) {
int ls = styler.GetLineState(currentLine - 1);
lineState = tLineState(ls & LS_MASK_STATE);
expected = LS_COMMAND_EXPECTED == tLineState(ls & LS_COMMAND_EXPECTED);
subBrace = LS_BRACE_ONLY == tLineState(ls & LS_BRACE_ONLY);
currentLevel = styler.LevelAt(currentLine - 1) >> 17;
commentLevel = (styler.LevelAt(currentLine - 1) >> 16) & 1;
} else
styler.SetLevel(0, SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG);
bool visibleChars = false;
int previousLevel = currentLevel;
StyleContext sc(startPos, length, SCE_TCL_DEFAULT, styler);
for (; ; sc.Forward()) {
next:
if (sc.ch=='\r' && sc.chNext == '\n') // only ignore \r on PC process on the mac
continue;
bool atEnd = !sc.More(); // make sure we coloured the last word
if (lineState != LS_DEFAULT) {
sc.SetState(SCE_TCL_DEFAULT);
if (lineState == LS_OPEN_COMMENT)
sc.SetState(SCE_TCL_COMMENTLINE);
else if (lineState == LS_OPEN_DOUBLE_QUOTE)
sc.SetState(SCE_TCL_IN_QUOTE);
else if (lineState == LS_COMMENT_BOX && (sc.ch == '#' || (sc.ch == ' ' && sc.chNext=='#')))
sc.SetState(SCE_TCL_COMMENT_BOX);
lineState = LS_DEFAULT;
}
if (subBrace) { // ${ overrides every thing even \ except }
if (sc.ch == '}') {
subBrace = false;
sc.SetState(SCE_TCL_OPERATOR);
sc.ForwardSetState(SCE_TCL_DEFAULT);
goto next;
}
else
sc.SetState(SCE_TCL_SUB_BRACE);
if (!sc.atLineEnd)
continue;
} else if (sc.state == SCE_TCL_DEFAULT || sc.state ==SCE_TCL_OPERATOR) {
expected &= isspacechar(static_cast<unsigned char>(sc.ch)) || IsAWordStart(sc.ch) || sc.ch =='#';
} else if (sc.state == SCE_TCL_SUBSTITUTION) {
switch(sc.ch) {
case '(':
subParen=true;
sc.SetState(SCE_TCL_OPERATOR);
sc.ForwardSetState(SCE_TCL_SUBSTITUTION);
continue;
case ')':
sc.SetState(SCE_TCL_OPERATOR);
subParen=false;
continue;
case '$':
continue;
case ',':
sc.SetState(SCE_TCL_OPERATOR);
if (subParen)
sc.ForwardSetState(SCE_TCL_SUBSTITUTION);
continue;
default :
// maybe spaces should be allowed ???
if (!IsAWordChar(sc.ch)) { // probably the code is wrong
sc.SetState(SCE_TCL_DEFAULT);
subParen = 0;
}
break;
}
} else if (isComment(sc.state)) {
} else if (!IsAWordChar(sc.ch)) {
if ((sc.state == SCE_TCL_IDENTIFIER && expected) || sc.state == SCE_TCL_MODIFIER) {
char w[100];
char *s=w;
sc.GetCurrent(w, sizeof(w));
if (w[strlen(w)-1]=='\r')
w[strlen(w)-1]=0;
while(*s == ':') // ignore leading : like in ::set a 10
++s;
bool quote = sc.state == SCE_TCL_IN_QUOTE;
if (commentLevel || expected) {
if (keywords.InList(s)) {
sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD4);
} else if (sc.GetRelative(-static_cast<int>(strlen(s))-1) == '{' &&
keywords5.InList(s) && sc.ch == '}') { // {keyword} exactly no spaces
sc.ChangeState(SCE_TCL_EXPAND);
}
if (keywords6.InList(s)) {
sc.ChangeState(SCE_TCL_WORD5);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_TCL_WORD6);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_TCL_WORD7);
} else if (keywords9.InList(s)) {
sc.ChangeState(SCE_TCL_WORD8);
}
}
expected = false;
sc.SetState(quote ? SCE_TCL_IN_QUOTE : SCE_TCL_DEFAULT);
} else if (sc.state == SCE_TCL_MODIFIER || sc.state == SCE_TCL_IDENTIFIER) {
sc.SetState(SCE_TCL_DEFAULT);
}
}
if (atEnd)
break;
if (sc.atLineEnd) {
lineState = LS_DEFAULT;
currentLine = styler.GetLine(sc.currentPos);
if (foldComment && sc.state!=SCE_TCL_COMMENT && isComment(sc.state)) {
if (currentLevel == 0) {
++currentLevel;
commentLevel = true;
}
} else {
if (visibleChars && commentLevel) {
--currentLevel;
--previousLevel;
commentLevel = false;
}
}
int flag = 0;
if (!visibleChars)
flag = SC_FOLDLEVELWHITEFLAG;
if (currentLevel > previousLevel)
flag = SC_FOLDLEVELHEADERFLAG;
styler.SetLevel(currentLine, flag + previousLevel + SC_FOLDLEVELBASE + (currentLevel << 17) + (commentLevel << 16));
// Update the line state, so it can be seen by next line
if (sc.state == SCE_TCL_IN_QUOTE)
lineState = LS_OPEN_DOUBLE_QUOTE;
else {
if (prevSlash) {
if (isComment(sc.state))
lineState = LS_OPEN_COMMENT;
} else if (sc.state == SCE_TCL_COMMENT_BOX)
lineState = LS_COMMENT_BOX;
}
styler.SetLineState(currentLine,
(subBrace ? LS_BRACE_ONLY : 0) |
(expected ? LS_COMMAND_EXPECTED : 0) | lineState);
if (lineState == LS_COMMENT_BOX)
sc.ForwardSetState(SCE_TCL_COMMENT_BOX);
else if (lineState == LS_OPEN_DOUBLE_QUOTE)
sc.ForwardSetState(SCE_TCL_IN_QUOTE);
else
sc.ForwardSetState(SCE_TCL_DEFAULT);
prevSlash = false;
previousLevel = currentLevel;
goto next;
}
if (prevSlash) {
prevSlash = false;
if (sc.ch == '#' && IsANumberChar(sc.chNext))
sc.ForwardSetState(SCE_TCL_NUMBER);
continue;
}
prevSlash = sc.ch == '\\';
if (isComment(sc.state))
continue;
if (sc.atLineStart) {
visibleChars = false;
if (sc.state!=SCE_TCL_IN_QUOTE && !isComment(sc.state))
{
sc.SetState(SCE_TCL_DEFAULT);
expected = IsAWordStart(sc.ch)|| isspacechar(static_cast<unsigned char>(sc.ch));
}
}
switch (sc.state) {
case SCE_TCL_NUMBER:
if (!IsANumberChar(sc.ch))
sc.SetState(SCE_TCL_DEFAULT);
break;
case SCE_TCL_IN_QUOTE:
if (sc.ch == '"') {
sc.ForwardSetState(SCE_TCL_DEFAULT);
visibleChars = true; // necessary if a " is the first and only character on a line
goto next;
} else if (sc.ch == '[' || sc.ch == ']' || sc.ch == '$') {
sc.SetState(SCE_TCL_OPERATOR);
expected = sc.ch == '[';
sc.ForwardSetState(SCE_TCL_IN_QUOTE);
goto next;
}
continue;
case SCE_TCL_OPERATOR:
sc.SetState(SCE_TCL_DEFAULT);
break;
}
if (sc.ch == '#') {
if (visibleChars) {
if (sc.state != SCE_TCL_IN_QUOTE && expected)
sc.SetState(SCE_TCL_COMMENT);
} else {
sc.SetState(SCE_TCL_COMMENTLINE);
if (sc.chNext == '~')
sc.SetState(SCE_TCL_BLOCK_COMMENT);
if (sc.atLineStart && (sc.chNext == '#' || sc.chNext == '-'))
sc.SetState(SCE_TCL_COMMENT_BOX);
}
}
if (!isspacechar(static_cast<unsigned char>(sc.ch))) {
visibleChars = true;
}
if (sc.ch == '\\') {
prevSlash = true;
continue;
}
// Determine if a new state should be entered.
if (sc.state == SCE_TCL_DEFAULT) {
if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_TCL_IDENTIFIER);
} else if (IsADigit(sc.ch) && !IsAWordChar(sc.chPrev)) {
sc.SetState(SCE_TCL_NUMBER);
} else {
switch (sc.ch) {
case '\"':
sc.SetState(SCE_TCL_IN_QUOTE);
break;
case '{':
sc.SetState(SCE_TCL_OPERATOR);
expected = true;
++currentLevel;
break;
case '}':
sc.SetState(SCE_TCL_OPERATOR);
expected = true;
--currentLevel;
break;
case '[':
expected = true;
case ']':
case '(':
case ')':
sc.SetState(SCE_TCL_OPERATOR);
break;
case ';':
expected = true;
break;
case '$':
subParen = 0;
if (sc.chNext != '{') {
sc.SetState(SCE_TCL_SUBSTITUTION);
}
else {
sc.SetState(SCE_TCL_OPERATOR); // $
sc.Forward(); // {
sc.ForwardSetState(SCE_TCL_SUB_BRACE);
subBrace = true;
}
break;
case '#':
if ((isspacechar(static_cast<unsigned char>(sc.chPrev))||
isoperator(static_cast<char>(sc.chPrev))) && IsADigit(sc.chNext,0x10))
sc.SetState(SCE_TCL_NUMBER);
break;
case '-':
sc.SetState(IsADigit(sc.chNext)? SCE_TCL_NUMBER: SCE_TCL_MODIFIER);
break;
default:
if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_TCL_OPERATOR);
}
}
}
}
}
sc.Complete();
}
static const char * const tclWordListDesc[] = {
"TCL Keywords",
"TK Keywords",
"iTCL Keywords",
"tkCommands",
"expand"
"user1",
"user2",
"user3",
"user4",
0
};
// this code supports folding in the colourizer
LexerModule lmTCL(SCLEX_TCL, ColouriseTCLDoc, "tcl", 0, tclWordListDesc);
<commit_msg>Add missing comma.<commit_after>// Scintilla source code edit control
/** @file LexTCL.cxx
** Lexer for TCL language.
**/
// Copyright 1998-2001 by Andre Arpin <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '_' || ch ==':' || ch=='.'); // : name space separator
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 || (ch ==':' || isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(IsADigit(ch, 0x10) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+');
}
static void ColouriseTCLDoc(unsigned int startPos, int length, int , WordList *keywordlists[], Accessor &styler) {
#define isComment(s) (s==SCE_TCL_COMMENT || s==SCE_TCL_COMMENTLINE || s==SCE_TCL_COMMENT_BOX || s==SCE_TCL_BLOCK_COMMENT)
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool commentLevel = false;
bool subBrace = false; // substitution begin with a brace ${.....}
enum tLineState {LS_DEFAULT, LS_OPEN_COMMENT, LS_OPEN_DOUBLE_QUOTE, LS_COMMENT_BOX, LS_MASK_STATE = 0xf,
LS_COMMAND_EXPECTED = 16, LS_BRACE_ONLY = 32 } lineState = LS_DEFAULT;
bool prevSlash = false;
int currentLevel = 0;
bool expected = 0;
bool subParen = 0;
int currentLine = styler.GetLine(startPos);
if (currentLine > 0)
currentLine--;
length += startPos - styler.LineStart(currentLine);
// make sure lines overlap
startPos = styler.LineStart(currentLine);
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
WordList &keywords9 = *keywordlists[8];
if (currentLine > 0) {
int ls = styler.GetLineState(currentLine - 1);
lineState = tLineState(ls & LS_MASK_STATE);
expected = LS_COMMAND_EXPECTED == tLineState(ls & LS_COMMAND_EXPECTED);
subBrace = LS_BRACE_ONLY == tLineState(ls & LS_BRACE_ONLY);
currentLevel = styler.LevelAt(currentLine - 1) >> 17;
commentLevel = (styler.LevelAt(currentLine - 1) >> 16) & 1;
} else
styler.SetLevel(0, SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG);
bool visibleChars = false;
int previousLevel = currentLevel;
StyleContext sc(startPos, length, SCE_TCL_DEFAULT, styler);
for (; ; sc.Forward()) {
next:
if (sc.ch=='\r' && sc.chNext == '\n') // only ignore \r on PC process on the mac
continue;
bool atEnd = !sc.More(); // make sure we coloured the last word
if (lineState != LS_DEFAULT) {
sc.SetState(SCE_TCL_DEFAULT);
if (lineState == LS_OPEN_COMMENT)
sc.SetState(SCE_TCL_COMMENTLINE);
else if (lineState == LS_OPEN_DOUBLE_QUOTE)
sc.SetState(SCE_TCL_IN_QUOTE);
else if (lineState == LS_COMMENT_BOX && (sc.ch == '#' || (sc.ch == ' ' && sc.chNext=='#')))
sc.SetState(SCE_TCL_COMMENT_BOX);
lineState = LS_DEFAULT;
}
if (subBrace) { // ${ overrides every thing even \ except }
if (sc.ch == '}') {
subBrace = false;
sc.SetState(SCE_TCL_OPERATOR);
sc.ForwardSetState(SCE_TCL_DEFAULT);
goto next;
}
else
sc.SetState(SCE_TCL_SUB_BRACE);
if (!sc.atLineEnd)
continue;
} else if (sc.state == SCE_TCL_DEFAULT || sc.state ==SCE_TCL_OPERATOR) {
expected &= isspacechar(static_cast<unsigned char>(sc.ch)) || IsAWordStart(sc.ch) || sc.ch =='#';
} else if (sc.state == SCE_TCL_SUBSTITUTION) {
switch(sc.ch) {
case '(':
subParen=true;
sc.SetState(SCE_TCL_OPERATOR);
sc.ForwardSetState(SCE_TCL_SUBSTITUTION);
continue;
case ')':
sc.SetState(SCE_TCL_OPERATOR);
subParen=false;
continue;
case '$':
continue;
case ',':
sc.SetState(SCE_TCL_OPERATOR);
if (subParen)
sc.ForwardSetState(SCE_TCL_SUBSTITUTION);
continue;
default :
// maybe spaces should be allowed ???
if (!IsAWordChar(sc.ch)) { // probably the code is wrong
sc.SetState(SCE_TCL_DEFAULT);
subParen = 0;
}
break;
}
} else if (isComment(sc.state)) {
} else if (!IsAWordChar(sc.ch)) {
if ((sc.state == SCE_TCL_IDENTIFIER && expected) || sc.state == SCE_TCL_MODIFIER) {
char w[100];
char *s=w;
sc.GetCurrent(w, sizeof(w));
if (w[strlen(w)-1]=='\r')
w[strlen(w)-1]=0;
while(*s == ':') // ignore leading : like in ::set a 10
++s;
bool quote = sc.state == SCE_TCL_IN_QUOTE;
if (commentLevel || expected) {
if (keywords.InList(s)) {
sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD4);
} else if (sc.GetRelative(-static_cast<int>(strlen(s))-1) == '{' &&
keywords5.InList(s) && sc.ch == '}') { // {keyword} exactly no spaces
sc.ChangeState(SCE_TCL_EXPAND);
}
if (keywords6.InList(s)) {
sc.ChangeState(SCE_TCL_WORD5);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_TCL_WORD6);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_TCL_WORD7);
} else if (keywords9.InList(s)) {
sc.ChangeState(SCE_TCL_WORD8);
}
}
expected = false;
sc.SetState(quote ? SCE_TCL_IN_QUOTE : SCE_TCL_DEFAULT);
} else if (sc.state == SCE_TCL_MODIFIER || sc.state == SCE_TCL_IDENTIFIER) {
sc.SetState(SCE_TCL_DEFAULT);
}
}
if (atEnd)
break;
if (sc.atLineEnd) {
lineState = LS_DEFAULT;
currentLine = styler.GetLine(sc.currentPos);
if (foldComment && sc.state!=SCE_TCL_COMMENT && isComment(sc.state)) {
if (currentLevel == 0) {
++currentLevel;
commentLevel = true;
}
} else {
if (visibleChars && commentLevel) {
--currentLevel;
--previousLevel;
commentLevel = false;
}
}
int flag = 0;
if (!visibleChars)
flag = SC_FOLDLEVELWHITEFLAG;
if (currentLevel > previousLevel)
flag = SC_FOLDLEVELHEADERFLAG;
styler.SetLevel(currentLine, flag + previousLevel + SC_FOLDLEVELBASE + (currentLevel << 17) + (commentLevel << 16));
// Update the line state, so it can be seen by next line
if (sc.state == SCE_TCL_IN_QUOTE)
lineState = LS_OPEN_DOUBLE_QUOTE;
else {
if (prevSlash) {
if (isComment(sc.state))
lineState = LS_OPEN_COMMENT;
} else if (sc.state == SCE_TCL_COMMENT_BOX)
lineState = LS_COMMENT_BOX;
}
styler.SetLineState(currentLine,
(subBrace ? LS_BRACE_ONLY : 0) |
(expected ? LS_COMMAND_EXPECTED : 0) | lineState);
if (lineState == LS_COMMENT_BOX)
sc.ForwardSetState(SCE_TCL_COMMENT_BOX);
else if (lineState == LS_OPEN_DOUBLE_QUOTE)
sc.ForwardSetState(SCE_TCL_IN_QUOTE);
else
sc.ForwardSetState(SCE_TCL_DEFAULT);
prevSlash = false;
previousLevel = currentLevel;
goto next;
}
if (prevSlash) {
prevSlash = false;
if (sc.ch == '#' && IsANumberChar(sc.chNext))
sc.ForwardSetState(SCE_TCL_NUMBER);
continue;
}
prevSlash = sc.ch == '\\';
if (isComment(sc.state))
continue;
if (sc.atLineStart) {
visibleChars = false;
if (sc.state!=SCE_TCL_IN_QUOTE && !isComment(sc.state))
{
sc.SetState(SCE_TCL_DEFAULT);
expected = IsAWordStart(sc.ch)|| isspacechar(static_cast<unsigned char>(sc.ch));
}
}
switch (sc.state) {
case SCE_TCL_NUMBER:
if (!IsANumberChar(sc.ch))
sc.SetState(SCE_TCL_DEFAULT);
break;
case SCE_TCL_IN_QUOTE:
if (sc.ch == '"') {
sc.ForwardSetState(SCE_TCL_DEFAULT);
visibleChars = true; // necessary if a " is the first and only character on a line
goto next;
} else if (sc.ch == '[' || sc.ch == ']' || sc.ch == '$') {
sc.SetState(SCE_TCL_OPERATOR);
expected = sc.ch == '[';
sc.ForwardSetState(SCE_TCL_IN_QUOTE);
goto next;
}
continue;
case SCE_TCL_OPERATOR:
sc.SetState(SCE_TCL_DEFAULT);
break;
}
if (sc.ch == '#') {
if (visibleChars) {
if (sc.state != SCE_TCL_IN_QUOTE && expected)
sc.SetState(SCE_TCL_COMMENT);
} else {
sc.SetState(SCE_TCL_COMMENTLINE);
if (sc.chNext == '~')
sc.SetState(SCE_TCL_BLOCK_COMMENT);
if (sc.atLineStart && (sc.chNext == '#' || sc.chNext == '-'))
sc.SetState(SCE_TCL_COMMENT_BOX);
}
}
if (!isspacechar(static_cast<unsigned char>(sc.ch))) {
visibleChars = true;
}
if (sc.ch == '\\') {
prevSlash = true;
continue;
}
// Determine if a new state should be entered.
if (sc.state == SCE_TCL_DEFAULT) {
if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_TCL_IDENTIFIER);
} else if (IsADigit(sc.ch) && !IsAWordChar(sc.chPrev)) {
sc.SetState(SCE_TCL_NUMBER);
} else {
switch (sc.ch) {
case '\"':
sc.SetState(SCE_TCL_IN_QUOTE);
break;
case '{':
sc.SetState(SCE_TCL_OPERATOR);
expected = true;
++currentLevel;
break;
case '}':
sc.SetState(SCE_TCL_OPERATOR);
expected = true;
--currentLevel;
break;
case '[':
expected = true;
case ']':
case '(':
case ')':
sc.SetState(SCE_TCL_OPERATOR);
break;
case ';':
expected = true;
break;
case '$':
subParen = 0;
if (sc.chNext != '{') {
sc.SetState(SCE_TCL_SUBSTITUTION);
}
else {
sc.SetState(SCE_TCL_OPERATOR); // $
sc.Forward(); // {
sc.ForwardSetState(SCE_TCL_SUB_BRACE);
subBrace = true;
}
break;
case '#':
if ((isspacechar(static_cast<unsigned char>(sc.chPrev))||
isoperator(static_cast<char>(sc.chPrev))) && IsADigit(sc.chNext,0x10))
sc.SetState(SCE_TCL_NUMBER);
break;
case '-':
sc.SetState(IsADigit(sc.chNext)? SCE_TCL_NUMBER: SCE_TCL_MODIFIER);
break;
default:
if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_TCL_OPERATOR);
}
}
}
}
}
sc.Complete();
}
static const char * const tclWordListDesc[] = {
"TCL Keywords",
"TK Keywords",
"iTCL Keywords",
"tkCommands",
"expand",
"user1",
"user2",
"user3",
"user4",
0
};
// this code supports folding in the colourizer
LexerModule lmTCL(SCLEX_TCL, ColouriseTCLDoc, "tcl", 0, tclWordListDesc);
<|endoftext|> |
<commit_before><commit_msg>build<commit_after><|endoftext|> |
<commit_before><commit_msg>Fix assertion failure.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: b3dhommatrix.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: thb $ $Date: 2004-02-16 17:03:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX
#define _BGFX_MATRIX_B3DHOMMATRIX_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
namespace basegfx
{
// predeclaration
class B3DTuple;
// forward declaration
class Impl3DHomMatrix;
class B3DHomMatrix
{
private:
Impl3DHomMatrix* mpM;
void implPrepareChange();
public:
B3DHomMatrix();
B3DHomMatrix(const B3DHomMatrix& rMat);
~B3DHomMatrix();
double get(sal_uInt16 nRow, sal_uInt16 nColumn) const;
void set(sal_uInt16 nRow, sal_uInt16 nColumn, double fValue);
bool isIdentity() const;
/// Reset to the identity matrix
void identity();
bool isInvertible() const;
/// Invert the matrix (if possible)
bool invert();
bool isNormalized() const;
/// Normalize (i.e. force w=1) the matrix
void normalize();
/// Calc the matrix determinant
double determinant() const;
/// Calc the matrix trace
double trace() const;
/// Transpose the matrix
void transpose();
/// Rotation
void rotate(double fAngleX,double fAngleY,double fAngleZ);
/// Translation
void translate(double fX, double fY, double fZ);
/// Scaling
void scale(double fX, double fY, double fZ);
// Shearing-Matrices
void shearXY(double fSx, double fSy);
void shearYZ(double fSy, double fSz);
void shearXZ(double fSx, double fSz);
// Projection matrices, used for converting between eye and
// clip coordinates
void frustum(double fLeft = -1.0, double fRight = 1.0,
double fBottom = -1.0, double fTop = 1.0,
double fNear = 0.001, double fFar = 1.0);
void ortho(double fLeft = -1.0, double fRight = 1.0,
double fBottom = -1.0, double fTop = 1.0,
double fNear = 0.0, double fFar = 1.0);
// addition, subtraction
B3DHomMatrix& operator+=(const B3DHomMatrix& rMat);
B3DHomMatrix& operator-=(const B3DHomMatrix& rMat);
// comparison
bool operator==(const B3DHomMatrix& rMat) const;
bool operator!=(const B3DHomMatrix& rMat) const;
// multiplication, division by constant value
B3DHomMatrix& operator*=(double fValue);
B3DHomMatrix& operator/=(double fValue);
// matrix multiplication (from the left)
B3DHomMatrix& operator*=(const B3DHomMatrix& rMat);
// assignment operator
B3DHomMatrix& operator=(const B3DHomMatrix& rMat);
// decomposition
bool decompose(B3DTuple& rScale, B3DTuple& rTranslate, B3DTuple& rRotate, B3DTuple& rShear) const;
};
// addition, subtraction
inline B3DHomMatrix operator+(const B3DHomMatrix& rMatA, const B3DHomMatrix& rMatB)
{
B3DHomMatrix aSum(rMatA);
aSum += rMatB;
return aSum;
}
inline B3DHomMatrix operator-(const B3DHomMatrix& rMatA, const B3DHomMatrix& rMatB)
{
B3DHomMatrix aDiv(rMatA);
aDiv -= rMatB;
return aDiv;
}
// multiplication, division by constant value
inline B3DHomMatrix operator*(const B3DHomMatrix& rMat, double fValue)
{
B3DHomMatrix aNew(rMat);
aNew *= fValue;
return aNew;
}
inline B3DHomMatrix operator/(const B3DHomMatrix& rMat, double fValue)
{
B3DHomMatrix aNew(rMat);
aNew *= 1.0 / fValue;
return aNew;
}
inline B3DHomMatrix operator*(const B3DHomMatrix& rMatA, const B3DHomMatrix& rMatB)
{
B3DHomMatrix aMul(rMatB);
aMul *= rMatA;
return aMul;
}
} // end of namespace basegfx
#endif /* _BGFX_MATRIX_B3DHOMMATRIX_HXX */
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.62); FILE MERGED 2005/09/05 17:38:19 rt 1.6.62.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b3dhommatrix.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:25:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX
#define _BGFX_MATRIX_B3DHOMMATRIX_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
namespace basegfx
{
// predeclaration
class B3DTuple;
// forward declaration
class Impl3DHomMatrix;
class B3DHomMatrix
{
private:
Impl3DHomMatrix* mpM;
void implPrepareChange();
public:
B3DHomMatrix();
B3DHomMatrix(const B3DHomMatrix& rMat);
~B3DHomMatrix();
double get(sal_uInt16 nRow, sal_uInt16 nColumn) const;
void set(sal_uInt16 nRow, sal_uInt16 nColumn, double fValue);
bool isIdentity() const;
/// Reset to the identity matrix
void identity();
bool isInvertible() const;
/// Invert the matrix (if possible)
bool invert();
bool isNormalized() const;
/// Normalize (i.e. force w=1) the matrix
void normalize();
/// Calc the matrix determinant
double determinant() const;
/// Calc the matrix trace
double trace() const;
/// Transpose the matrix
void transpose();
/// Rotation
void rotate(double fAngleX,double fAngleY,double fAngleZ);
/// Translation
void translate(double fX, double fY, double fZ);
/// Scaling
void scale(double fX, double fY, double fZ);
// Shearing-Matrices
void shearXY(double fSx, double fSy);
void shearYZ(double fSy, double fSz);
void shearXZ(double fSx, double fSz);
// Projection matrices, used for converting between eye and
// clip coordinates
void frustum(double fLeft = -1.0, double fRight = 1.0,
double fBottom = -1.0, double fTop = 1.0,
double fNear = 0.001, double fFar = 1.0);
void ortho(double fLeft = -1.0, double fRight = 1.0,
double fBottom = -1.0, double fTop = 1.0,
double fNear = 0.0, double fFar = 1.0);
// addition, subtraction
B3DHomMatrix& operator+=(const B3DHomMatrix& rMat);
B3DHomMatrix& operator-=(const B3DHomMatrix& rMat);
// comparison
bool operator==(const B3DHomMatrix& rMat) const;
bool operator!=(const B3DHomMatrix& rMat) const;
// multiplication, division by constant value
B3DHomMatrix& operator*=(double fValue);
B3DHomMatrix& operator/=(double fValue);
// matrix multiplication (from the left)
B3DHomMatrix& operator*=(const B3DHomMatrix& rMat);
// assignment operator
B3DHomMatrix& operator=(const B3DHomMatrix& rMat);
// decomposition
bool decompose(B3DTuple& rScale, B3DTuple& rTranslate, B3DTuple& rRotate, B3DTuple& rShear) const;
};
// addition, subtraction
inline B3DHomMatrix operator+(const B3DHomMatrix& rMatA, const B3DHomMatrix& rMatB)
{
B3DHomMatrix aSum(rMatA);
aSum += rMatB;
return aSum;
}
inline B3DHomMatrix operator-(const B3DHomMatrix& rMatA, const B3DHomMatrix& rMatB)
{
B3DHomMatrix aDiv(rMatA);
aDiv -= rMatB;
return aDiv;
}
// multiplication, division by constant value
inline B3DHomMatrix operator*(const B3DHomMatrix& rMat, double fValue)
{
B3DHomMatrix aNew(rMat);
aNew *= fValue;
return aNew;
}
inline B3DHomMatrix operator/(const B3DHomMatrix& rMat, double fValue)
{
B3DHomMatrix aNew(rMat);
aNew *= 1.0 / fValue;
return aNew;
}
inline B3DHomMatrix operator*(const B3DHomMatrix& rMatA, const B3DHomMatrix& rMatB)
{
B3DHomMatrix aMul(rMatB);
aMul *= rMatA;
return aMul;
}
} // end of namespace basegfx
#endif /* _BGFX_MATRIX_B3DHOMMATRIX_HXX */
<|endoftext|> |
<commit_before>AliAnalysisTaskHFE* ConfigHFECalstandard_PbPb(Bool_t useMC){
//
// HFE standard task configuration
//
AliHFEcuts *hfecuts = new AliHFEcuts("hfeCuts","HFE Standard Cuts for EMCal");
hfecuts->CreateStandardCuts();
hfecuts->SetMinNClustersTPC(120);
hfecuts->SetMinRatioTPCclusters(0.6);
hfecuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable);
//hfecuts->SetMinNClustersITS(4);
hfecuts->SetMinNClustersITS(3);
hfecuts->SetCutITSpixel(AliHFEextraCuts::kAny);
hfecuts->SetCheckITSLayerStatus(kFALSE);
//hfecuts->UnsetVertexRequirement();
hfecuts->SetMaxImpactParam(3.,3.);
hfecuts->SetMaxImpactParam(3.,3.);
hfecuts->SetPtRange(0.5,60.0);
hfecuts->SetVertexRange(10.);
//hfecuts->SetMaxChi2perClusterITS(36);
//hfecuts->SetSigmaToVertex(10);
//hfecuts->SetTOFPIDStep(kTRUE);
//hfecuts->SetTOFMISMATCHStep(kTRUE);
//hfecuts->SetTPCPIDCleanUpStep(kTRUE);
hfecuts->SetQAOn();
//hfecuts->SetMinNTrackletsTRD(5);
AliAnalysisTaskHFE *task = new AliAnalysisTaskHFE("HFEanalysisStandardEMCal");
task->SetHFECuts(hfecuts);
task->SetPbPbAnalysis(kTRUE);
//task->SetRemovePileUp(kTRUE);
task->GetPIDQAManager()->SetHighResolutionHistos();
// Define Variables
AliHFEvarManager *vm = task->GetVarManager();
//vm->AddVariable("pt");
//vm->AddVariable("eta");
const Double_t ptbinning[50] = {1., 1.1, 1.2, 1.3, 1.4,
1.5, 1.75, 2., 2.25, 2.5,
2.75, 3., 3.5, 4., 4.5,
5., 5.5, 6., 7., 8.,
9., 10., 11., 12., 13.,
14., 15., 16., 17., 18.,
20., 22., 24., 26., 28.,
30., 32., 34., 36., 38.,
40., 45., 50., 55., 60.,
65., 70., 80., 90., 100};
const Double_t etabinning[17] = {-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8};
vm->AddVariable("pt", 49, ptbinning);
vm->AddVariable("eta", 16, etabinning);
vm->AddVariable("phi");
vm->AddVariable("charge");
vm->AddVariable("source");
vm->AddVariable("centrality");
/*
if(!useMC){
for(Int_t a=0;a<12;a++)
{
TF1 *hBackground = new TF1("hadronicBackgroundFunction","TMath::Exp([0]/x + [1])", 0., 20.);
hBackground->SetParameter(0, -43.87);
hBackground->SetParameter(1, 2.85);
task->SetBackGroundFactorsFunction(hBackground,a);
}
}
*/
// Define PID
AliHFEpid *pid = task->GetPID();
if(useMC) pid->SetHasMCData(kTRUE);
pid->AddDetector("EMCAL", 1);
pid->AddDetector("TPC", 0);
// pid->ConfigureTPCrejection();
if(!useMC){
Double_t params_centr_0_5[1];
Double_t params_centr_5_10[1];
Double_t params_centr_10_20[1];
Double_t params_centr_20_30[1];
Double_t params_centr_per[1];
//params_centr_0_5[0]=0.16; // cut tuned for 0-10%
//params_centr_5_10[0]=0.16; // cut tuned for 0-10%
//params_centr_10_20[0]=0.29;
//params_centr_20_30[0]=0.38;
//params_centr_per[0]=0.44;
params_centr_0_5[0]=-1.5; // cut tuned for 0-10%
params_centr_5_10[0]=-1.5; // cut tuned for 0-10%
params_centr_10_20[0]=-1.5;
params_centr_20_30[0]=-1.5;
params_centr_per[0]=-1.5;
char *cutmodel;
cutmodel="pol0";
for(Int_t a=0;a<11;a++)
{
if(a>3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_per,3.0);
if(a==0) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_0_5,3.0); // 0-5%
if(a==1) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_5_10,3.0); // 5-10%
if(a==2) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_10_20,3.0); // 10-20%
if(a==3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_20_30,3.0); // 20-30%
}
}
// V0 tagged tracks
AliHFEcuts *v0trackCuts = new AliHFEcuts("V0trackCuts", "Track Cuts for tagged track Analysis");
v0trackCuts->CreateStandardCuts();
v0trackCuts->SetMinNClustersTPC(120);
v0trackCuts->SetMinRatioTPCclusters(0.6);
v0trackCuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable);
v0trackCuts->SetMinNClustersITS(1);
v0trackCuts->SetCutITSpixel(AliHFEextraCuts::kAny);
v0trackCuts->SetCheckITSLayerStatus(kFALSE);
v0trackCuts->UnsetVertexRequirement();
//v0trackCuts->SetMaxChi2perClusterITS(36);
//hfecuts->SetSigmaToVertex(10);
v0trackCuts->SetTOFPIDStep(kTRUE);
// v0trackCuts->SetTOFMISMATCHStep(kTRUE);
//v0trackCuts->SetTPCPIDCleanUpStep(kTRUE);
v0trackCuts->SetQAOn();
task->SwitchOnPlugin(AliAnalysisTaskHFE::kTaggedTrackAnalysis);
task->SetTaggedTrackCuts(v0trackCuts);
task->SetCleanTaggedTrack(kFALSE);
// change E/p cuts
AliHFEpidEMCAL *emcpid = pid->AliHFEpid::GetDetPID(AliHFEpid::kEMCALpid);
emcpid->SetEoPMax(1.2);
emcpid->SetEoPMim(0.85);
// QA
task->SetQAOn(AliAnalysisTaskHFE::kPIDqa);
// task->SetFillSignalOnly(kFALSE); // for DE pluging for MC
task->SetQAOn(AliAnalysisTaskHFE::kMCqa);
//task->SwitchOnPlugin(AliAnalysisTaskHFE::kIsElecBackGround);
//task->SwitchOnPlugin(AliAnalysisTaskHFE::kSecVtx);
task->SwitchOnPlugin(AliAnalysisTaskHFE::kDEstep);
printf("*************************************\n");
printf("Configuring standard Task:\n");
task->Print();
pid->PrintStatus();
printf("*************************************\n");
return task;
}
<commit_msg>add a parameter for TPC cluster cut<commit_after>AliAnalysisTaskHFE* ConfigHFECalstandard_PbPb(Bool_t useMC, int TPCclust){
//
// HFE standard task configuration
//
cout << "==== TPC cluster cut" << TPCclust << endl;
AliHFEcuts *hfecuts = new AliHFEcuts("hfeCuts","HFE Standard Cuts for EMCal");
hfecuts->CreateStandardCuts();
//hfecuts->SetMinNClustersTPC(120);
hfecuts->SetMinNClustersTPC(TPCclust);
hfecuts->SetMinRatioTPCclusters(0.6);
hfecuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable);
//hfecuts->SetMinNClustersITS(4);
hfecuts->SetMinNClustersITS(3);
hfecuts->SetCutITSpixel(AliHFEextraCuts::kAny);
hfecuts->SetCheckITSLayerStatus(kFALSE);
//hfecuts->UnsetVertexRequirement();
hfecuts->SetMaxImpactParam(3.,3.);
hfecuts->SetMaxImpactParam(3.,3.);
hfecuts->SetPtRange(0.5,60.0);
hfecuts->SetVertexRange(10.);
//hfecuts->SetMaxChi2perClusterITS(36);
//hfecuts->SetSigmaToVertex(10);
//hfecuts->SetTOFPIDStep(kTRUE);
//hfecuts->SetTOFMISMATCHStep(kTRUE);
//hfecuts->SetTPCPIDCleanUpStep(kTRUE);
hfecuts->SetQAOn();
//hfecuts->SetMinNTrackletsTRD(5);
AliAnalysisTaskHFE *task = new AliAnalysisTaskHFE("HFEanalysisStandardEMCal");
task->SetHFECuts(hfecuts);
task->SetPbPbAnalysis(kTRUE);
//task->SetRemovePileUp(kTRUE);
task->GetPIDQAManager()->SetHighResolutionHistos();
// Define Variables
AliHFEvarManager *vm = task->GetVarManager();
//vm->AddVariable("pt");
//vm->AddVariable("eta");
const Double_t ptbinning[50] = {1., 1.1, 1.2, 1.3, 1.4,
1.5, 1.75, 2., 2.25, 2.5,
2.75, 3., 3.5, 4., 4.5,
5., 5.5, 6., 7., 8.,
9., 10., 11., 12., 13.,
14., 15., 16., 17., 18.,
20., 22., 24., 26., 28.,
30., 32., 34., 36., 38.,
40., 45., 50., 55., 60.,
65., 70., 80., 90., 100};
const Double_t etabinning[17] = {-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8};
vm->AddVariable("pt", 49, ptbinning);
vm->AddVariable("eta", 16, etabinning);
vm->AddVariable("phi");
vm->AddVariable("charge");
vm->AddVariable("source");
vm->AddVariable("centrality");
/*
if(!useMC){
for(Int_t a=0;a<12;a++)
{
TF1 *hBackground = new TF1("hadronicBackgroundFunction","TMath::Exp([0]/x + [1])", 0., 20.);
hBackground->SetParameter(0, -43.87);
hBackground->SetParameter(1, 2.85);
task->SetBackGroundFactorsFunction(hBackground,a);
}
}
*/
// Define PID
AliHFEpid *pid = task->GetPID();
if(useMC) pid->SetHasMCData(kTRUE);
pid->AddDetector("EMCAL", 1);
pid->AddDetector("TPC", 0);
// pid->ConfigureTPCrejection();
if(!useMC){
Double_t params_centr_0_5[1];
Double_t params_centr_5_10[1];
Double_t params_centr_10_20[1];
Double_t params_centr_20_30[1];
Double_t params_centr_per[1];
//params_centr_0_5[0]=0.16; // cut tuned for 0-10%
//params_centr_5_10[0]=0.16; // cut tuned for 0-10%
//params_centr_10_20[0]=0.29;
//params_centr_20_30[0]=0.38;
//params_centr_per[0]=0.44;
params_centr_0_5[0]=-1.5; // cut tuned for 0-10%
params_centr_5_10[0]=-1.5; // cut tuned for 0-10%
params_centr_10_20[0]=-1.5;
params_centr_20_30[0]=-1.5;
params_centr_per[0]=-1.5;
char *cutmodel;
cutmodel="pol0";
for(Int_t a=0;a<11;a++)
{
if(a>3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_per,3.0);
if(a==0) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_0_5,3.0); // 0-5%
if(a==1) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_5_10,3.0); // 5-10%
if(a==2) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_10_20,3.0); // 10-20%
if(a==3) pid->ConfigureTPCcentralityCut(a,cutmodel,params_centr_20_30,3.0); // 20-30%
}
}
// V0 tagged tracks
AliHFEcuts *v0trackCuts = new AliHFEcuts("V0trackCuts", "Track Cuts for tagged track Analysis");
v0trackCuts->CreateStandardCuts();
//v0trackCuts->SetMinNClustersTPC(120);
v0trackCuts->SetMinNClustersTPC(TPCclust);
v0trackCuts->SetMinRatioTPCclusters(0.6);
v0trackCuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable);
v0trackCuts->SetMinNClustersITS(1);
v0trackCuts->SetCutITSpixel(AliHFEextraCuts::kAny);
v0trackCuts->SetCheckITSLayerStatus(kFALSE);
v0trackCuts->UnsetVertexRequirement();
//v0trackCuts->SetMaxChi2perClusterITS(36);
//hfecuts->SetSigmaToVertex(10);
v0trackCuts->SetTOFPIDStep(kTRUE);
// v0trackCuts->SetTOFMISMATCHStep(kTRUE);
//v0trackCuts->SetTPCPIDCleanUpStep(kTRUE);
v0trackCuts->SetQAOn();
task->SwitchOnPlugin(AliAnalysisTaskHFE::kTaggedTrackAnalysis);
task->SetTaggedTrackCuts(v0trackCuts);
task->SetCleanTaggedTrack(kFALSE);
// change E/p cuts
AliHFEpidEMCAL *emcpid = pid->AliHFEpid::GetDetPID(AliHFEpid::kEMCALpid);
emcpid->SetEoPMax(1.2);
emcpid->SetEoPMim(0.85);
// QA
task->SetQAOn(AliAnalysisTaskHFE::kPIDqa);
// task->SetFillSignalOnly(kFALSE); // for DE pluging for MC
task->SetQAOn(AliAnalysisTaskHFE::kMCqa);
//task->SwitchOnPlugin(AliAnalysisTaskHFE::kIsElecBackGround);
//task->SwitchOnPlugin(AliAnalysisTaskHFE::kSecVtx);
task->SwitchOnPlugin(AliAnalysisTaskHFE::kDEstep);
printf("*************************************\n");
printf("Configuring standard Task:\n");
task->Print();
pid->PrintStatus();
printf("*************************************\n");
return task;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 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 COPYING 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.
*/
#include "common.h"
// implementation header
#include "CacheManager.h"
// system headers
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32
# include <unistd.h>
#endif
// common headers
#include "md5.h"
#include "bzfio.h"
#include "TextUtils.h"
#include "FileManager.h"
#include "StateDatabase.h"
#include "DirectoryNames.h"
// function prototypes
static bool fileExists(const std::string& name);
static void removeDirs(const std::string& path);
static void removeNewlines(char* c);
static std::string partialEncoding(const std::string& string);
static bool compareUsedDate(const CacheManager::CacheRecord& a,
const CacheManager::CacheRecord& b);
CacheManager CACHEMGR;
CacheManager::CacheManager()
{
indexName = getCacheDirName();
indexName += "CacheIndex.txt";
return;
}
CacheManager::~CacheManager()
{
return;
}
bool CacheManager::isCacheFileType(const std::string name) const
{
if (strncasecmp(name.c_str(), "http://", 7) == 0) {
return true;
}
if (strncasecmp(name.c_str(), "ftp://", 6) == 0) {
return true;
}
return false;
}
std::string CacheManager::getLocalName(const std::string name) const
{
std::string local = "";
if (strncasecmp(name.c_str(), "http://", 7) == 0) {
local = getCacheDirName() + "http/";
local += partialEncoding(name.substr(7));
}
else if (strncasecmp(name.c_str(), "ftp://", 6) == 0) {
local = getCacheDirName() + "ftp/";
local += partialEncoding(name.substr(6));
}
#ifdef _WIN32
std::replace(local.begin(), local.end(), '/', '\\');
#endif
return local;
}
bool CacheManager::findURL(const std::string& url, CacheRecord& record)
{
int pos = findRecord(url);
if (pos >= 0) {
CacheRecord* rec = &records[pos];
rec->usedDate = time(NULL); // update the timestamp
record = *rec;
return true;
}
return false;
}
bool CacheManager::addFile(CacheRecord& record, const void* data)
{
if (((data == NULL) && (record.size != 0)) || (record.url.size() <= 0)) {
return false;
}
record.name = getLocalName(record.url);
std::ostream* out = FILEMGR.createDataOutStream(record.name);
if (out == NULL) {
return false;
}
bool replacement = false;
CacheRecord* rec = &record;
int pos = findRecord(record.url);
if (pos >= 0) {
records[pos] = record;
rec = &records[pos];
replacement = true;
}
out->write((char*)data, rec->size);
rec->usedDate = time(NULL); // update the timestamp
MD5 md5;
md5.update((unsigned char *)data, rec->size);
md5.finalize();
rec->key = md5.hexdigest();
if (!replacement) {
records.push_back(*rec);
}
delete out;
return true;
}
int CacheManager::findRecord(const std::string& url)
{
for (unsigned int i = 0; i < records.size(); i++) {
CacheRecord* rec = &(records[i]);
if (url == rec->url) {
return i;
}
}
return -1;
}
bool CacheManager::loadIndex()
{
records.clear();
FILE* file = fopen(indexName.c_str(), "r");
if (file == NULL) {
return false;
}
char buffer[1024];
while (fgets(buffer, 1024, file) != NULL) {
removeNewlines(buffer);
if ((buffer[0] == '\0') || (buffer[0] == '#')) {
continue;
}
CacheRecord rec;
rec.url = buffer;
rec.name = getLocalName(rec.url);
if (fgets(buffer, 1024, file) == NULL) {
break;
} else {
removeNewlines(buffer);
}
std::string line = buffer;
std::vector<std::string> tokens = TextUtils::tokenize(line, " ");
if (tokens.size() != 4) {
DEBUG1("loadCacheIndex (bad line): %s\n", buffer);
continue;
}
rec.size = strtoul(tokens[0].c_str(), NULL, 10);
rec.date = strtoul(tokens[1].c_str(), NULL, 10);
rec.usedDate = strtoul(tokens[2].c_str(), NULL, 10);
rec.key = tokens[3];
if (fileExists(rec.name)) {
records.push_back(rec);
}
}
fclose(file);
return true;
}
bool CacheManager::saveIndex()
{
std::sort(records.begin(), records.end(), compareUsedDate);
std::string tmpIndexName = indexName + ".tmp";
FILE* file = fopen(tmpIndexName.c_str(), "w");
if (file == NULL) {
return false;
}
for (unsigned int i = 0; i < records.size(); i++) {
const CacheRecord& rec = records[i];
fprintf(file, "%s\n%u %lu %lu %s\n\n", rec.url.c_str(),
rec.size, rec.date, rec.usedDate, rec.key.c_str());
}
fclose(file);
return (rename(tmpIndexName.c_str(), indexName.c_str()) == 0);
}
void CacheManager::limitCacheSize()
{
int maxSize = BZDB.evalInt("maxCacheMB") * 1024 * 1024;
if (maxSize < 0) {
maxSize = 0;
}
int currentSize = 0;
for (unsigned int i = 0; i < records.size(); i++) {
currentSize += records[i].size;
}
std::sort(records.begin(), records.end(), compareUsedDate);
while ((currentSize > maxSize) && (records.size() > 0)) {
CacheManager::CacheRecord& rec = records.back();
currentSize -= rec.size;
remove(rec.name.c_str());
removeDirs(rec.name);
records.pop_back();
}
return;
}
std::vector<CacheManager::CacheRecord> CacheManager::getCacheList() const
{
return records;
}
static bool fileExists (const std::string& name)
{
struct stat buf;
#ifndef _WIN32
return (stat(name.c_str(), &buf) == 0);
#else
// Windows sucks yet again, if there is a trailing "\"
// at the end of the filename, _stat will return -1.
std::string dirname = name;
while (dirname.find_last_of('\\') == (dirname.size() - 1)) {
dirname.resize(dirname.size() - 1);
}
return (_stat(dirname.c_str(), (struct _stat *) &buf) == 0);
#endif
}
static void removeDirs(const std::string& path)
{
unsigned int minLen = (unsigned int)getConfigDirName().size();
std::string tmp = path;
while (tmp.size() > minLen) {
#ifndef _WIN32
unsigned int i = (unsigned int)tmp.find_last_of('/');
#else
unsigned int i = (unsigned int)tmp.find_last_of('\\');
#endif
tmp = tmp.substr(0, i);
if (remove(tmp.c_str()) != 0) {
break;
}
}
return;
}
static void removeNewlines(char* c)
{
while (*c != '\0') {
if ((*c == '\n') || (*c == '\r')) {
*c = '\0';
}
c++;
}
return;
}
static std::string partialEncoding(const std::string& string)
{
// URL encoding removes the '/' and '.', which is
// not acceptable. It is nice to have the directory
// structure, and to be able to point and click your
// way through it to view ".png"s.
std::string tmp;
char hex[5];
for (unsigned int i = 0; i < string.size(); i++) {
const char c = string[i];
if (TextUtils::isWhitespace(c)) {
tmp += "%20";
}
else if ((c == '%') || (c == '*') || (c == '?') ||
(c == ':') || (c == '"') || (c == '\\')) {
tmp += '%';
sprintf(hex, "%-2.2X", c);
tmp += hex;
}
else {
tmp += c;
}
}
return tmp;
}
static bool compareUsedDate(const CacheManager::CacheRecord& a,
const CacheManager::CacheRecord& b)
{
// oldest last
return (a.usedDate > b.usedDate);
}
/*
* Local Variables: ***
* mode:C ***
* tab-width: 8 ***
* c-basic-offset: 2 ***
* indent-tabs-mode: t ***
* End: ***
* ex: shiftwidth=2 tabstop=8
*/
<commit_msg>cache files are binary files for winnies<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 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 COPYING 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.
*/
#include "common.h"
// implementation header
#include "CacheManager.h"
// system headers
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32
# include <unistd.h>
#endif
// common headers
#include "md5.h"
#include "bzfio.h"
#include "TextUtils.h"
#include "FileManager.h"
#include "StateDatabase.h"
#include "DirectoryNames.h"
// function prototypes
static bool fileExists(const std::string& name);
static void removeDirs(const std::string& path);
static void removeNewlines(char* c);
static std::string partialEncoding(const std::string& string);
static bool compareUsedDate(const CacheManager::CacheRecord& a,
const CacheManager::CacheRecord& b);
CacheManager CACHEMGR;
CacheManager::CacheManager()
{
indexName = getCacheDirName();
indexName += "CacheIndex.txt";
return;
}
CacheManager::~CacheManager()
{
return;
}
bool CacheManager::isCacheFileType(const std::string name) const
{
if (strncasecmp(name.c_str(), "http://", 7) == 0) {
return true;
}
if (strncasecmp(name.c_str(), "ftp://", 6) == 0) {
return true;
}
return false;
}
std::string CacheManager::getLocalName(const std::string name) const
{
std::string local = "";
if (strncasecmp(name.c_str(), "http://", 7) == 0) {
local = getCacheDirName() + "http/";
local += partialEncoding(name.substr(7));
}
else if (strncasecmp(name.c_str(), "ftp://", 6) == 0) {
local = getCacheDirName() + "ftp/";
local += partialEncoding(name.substr(6));
}
#ifdef _WIN32
std::replace(local.begin(), local.end(), '/', '\\');
#endif
return local;
}
bool CacheManager::findURL(const std::string& url, CacheRecord& record)
{
int pos = findRecord(url);
if (pos >= 0) {
CacheRecord* rec = &records[pos];
rec->usedDate = time(NULL); // update the timestamp
record = *rec;
return true;
}
return false;
}
bool CacheManager::addFile(CacheRecord& record, const void* data)
{
if (((data == NULL) && (record.size != 0)) || (record.url.size() <= 0)) {
return false;
}
record.name = getLocalName(record.url);
std::ostream* out = FILEMGR.createDataOutStream(record.name, true /* binary*/);
if (out == NULL) {
return false;
}
bool replacement = false;
CacheRecord* rec = &record;
int pos = findRecord(record.url);
if (pos >= 0) {
records[pos] = record;
rec = &records[pos];
replacement = true;
}
out->write((char*)data, rec->size);
rec->usedDate = time(NULL); // update the timestamp
MD5 md5;
md5.update((unsigned char *)data, rec->size);
md5.finalize();
rec->key = md5.hexdigest();
if (!replacement) {
records.push_back(*rec);
}
delete out;
return true;
}
int CacheManager::findRecord(const std::string& url)
{
for (unsigned int i = 0; i < records.size(); i++) {
CacheRecord* rec = &(records[i]);
if (url == rec->url) {
return i;
}
}
return -1;
}
bool CacheManager::loadIndex()
{
records.clear();
FILE* file = fopen(indexName.c_str(), "r");
if (file == NULL) {
return false;
}
char buffer[1024];
while (fgets(buffer, 1024, file) != NULL) {
removeNewlines(buffer);
if ((buffer[0] == '\0') || (buffer[0] == '#')) {
continue;
}
CacheRecord rec;
rec.url = buffer;
rec.name = getLocalName(rec.url);
if (fgets(buffer, 1024, file) == NULL) {
break;
} else {
removeNewlines(buffer);
}
std::string line = buffer;
std::vector<std::string> tokens = TextUtils::tokenize(line, " ");
if (tokens.size() != 4) {
DEBUG1("loadCacheIndex (bad line): %s\n", buffer);
continue;
}
rec.size = strtoul(tokens[0].c_str(), NULL, 10);
rec.date = strtoul(tokens[1].c_str(), NULL, 10);
rec.usedDate = strtoul(tokens[2].c_str(), NULL, 10);
rec.key = tokens[3];
if (fileExists(rec.name)) {
records.push_back(rec);
}
}
fclose(file);
return true;
}
bool CacheManager::saveIndex()
{
std::sort(records.begin(), records.end(), compareUsedDate);
std::string tmpIndexName = indexName + ".tmp";
FILE* file = fopen(tmpIndexName.c_str(), "w");
if (file == NULL) {
return false;
}
for (unsigned int i = 0; i < records.size(); i++) {
const CacheRecord& rec = records[i];
fprintf(file, "%s\n%u %lu %lu %s\n\n", rec.url.c_str(),
rec.size, rec.date, rec.usedDate, rec.key.c_str());
}
fclose(file);
return (rename(tmpIndexName.c_str(), indexName.c_str()) == 0);
}
void CacheManager::limitCacheSize()
{
int maxSize = BZDB.evalInt("maxCacheMB") * 1024 * 1024;
if (maxSize < 0) {
maxSize = 0;
}
int currentSize = 0;
for (unsigned int i = 0; i < records.size(); i++) {
currentSize += records[i].size;
}
std::sort(records.begin(), records.end(), compareUsedDate);
while ((currentSize > maxSize) && (records.size() > 0)) {
CacheManager::CacheRecord& rec = records.back();
currentSize -= rec.size;
remove(rec.name.c_str());
removeDirs(rec.name);
records.pop_back();
}
return;
}
std::vector<CacheManager::CacheRecord> CacheManager::getCacheList() const
{
return records;
}
static bool fileExists (const std::string& name)
{
struct stat buf;
#ifndef _WIN32
return (stat(name.c_str(), &buf) == 0);
#else
// Windows sucks yet again, if there is a trailing "\"
// at the end of the filename, _stat will return -1.
std::string dirname = name;
while (dirname.find_last_of('\\') == (dirname.size() - 1)) {
dirname.resize(dirname.size() - 1);
}
return (_stat(dirname.c_str(), (struct _stat *) &buf) == 0);
#endif
}
static void removeDirs(const std::string& path)
{
unsigned int minLen = (unsigned int)getConfigDirName().size();
std::string tmp = path;
while (tmp.size() > minLen) {
#ifndef _WIN32
unsigned int i = (unsigned int)tmp.find_last_of('/');
#else
unsigned int i = (unsigned int)tmp.find_last_of('\\');
#endif
tmp = tmp.substr(0, i);
if (remove(tmp.c_str()) != 0) {
break;
}
}
return;
}
static void removeNewlines(char* c)
{
while (*c != '\0') {
if ((*c == '\n') || (*c == '\r')) {
*c = '\0';
}
c++;
}
return;
}
static std::string partialEncoding(const std::string& string)
{
// URL encoding removes the '/' and '.', which is
// not acceptable. It is nice to have the directory
// structure, and to be able to point and click your
// way through it to view ".png"s.
std::string tmp;
char hex[5];
for (unsigned int i = 0; i < string.size(); i++) {
const char c = string[i];
if (TextUtils::isWhitespace(c)) {
tmp += "%20";
}
else if ((c == '%') || (c == '*') || (c == '?') ||
(c == ':') || (c == '"') || (c == '\\')) {
tmp += '%';
sprintf(hex, "%-2.2X", c);
tmp += hex;
}
else {
tmp += c;
}
}
return tmp;
}
static bool compareUsedDate(const CacheManager::CacheRecord& a,
const CacheManager::CacheRecord& b)
{
// oldest last
return (a.usedDate > b.usedDate);
}
/*
* Local Variables: ***
* mode:C ***
* tab-width: 8 ***
* c-basic-offset: 2 ***
* indent-tabs-mode: t ***
* End: ***
* ex: shiftwidth=2 tabstop=8
*/
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/seq.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] 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 seq.C
/// @brief Subroutines for the PHY SEQ registers
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <lib/phy/seq.H>
#include <generic/memory/lib/utils/scom.H>
#include <generic/memory/lib/utils/c_str.H>
#include <lib/utils/bit_count.H>
#include <lib/eff_config/timing.H>
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;
namespace mss
{
namespace seq
{
///
/// @brief PHY SEQ register exponent helper
/// PHY SEQ fields is used as exponent of 2, to calculate the number of MEMINTCLKO clock cycles.
/// For example, if TMOD_CYCLES[0:3] = 5, the internal timers use the value 2^5 = 32 MEMINTCLKO
/// clock cycles. The maximum value per nibble is ‘A’h. This helper takes a calculated value and returns
/// the 'best' exponent.
/// @param[in] i_value a value for which to make an exponent
/// @return uint64_t right-aligned value to stick in the field
///
uint64_t exp_helper( const uint64_t i_value )
{
// PHY exponents don't make much sense above this value so we short circuit if possible.
constexpr uint64_t MAX_EXP = 0xA;
if (i_value >= (1 << MAX_EXP))
{
return 0xA;
}
// If the user passes in 0, let it past.
if (i_value == 0)
{
return 0;
}
// Find the first bit set. The subtraction from 63 switches from a left-count to a right-count (e.g., 0 (left most
// bit) is really bit 63 if you start on the right.)
const uint64_t l_first_bit = 63 - first_bit_set(i_value);
// If the input is greater than 2^first bit, add one to the first_bit so 2^first_bit >= input
// (round up)
return l_first_bit + (uint64_t(1 << l_first_bit) < i_value ? 1 : 0);
}
///
/// @brief reset SEQ_TIMING0
/// @param[in] i_target fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode reset_timing0( const fapi2::Target<TARGET_TYPE_MCA>& i_target )
{
typedef seqTraits<TARGET_TYPE_MCA> TT;
fapi2::buffer<uint64_t> l_data;
// Table 5-324. SEQ Memory Timing Parameter 0 Register Bit Definition
// TMOD_CYCLES max(tMRD, tMOD)
// TRCD_CYCLES tRCD
// TRP_CYCLES tRP
// TRFC_CYCLES tRFC
uint64_t l_tmod_cycles = 0;
uint8_t l_trcd = 0;
uint8_t l_trp = 0;
uint16_t l_trfc_max = 0;
l_tmod_cycles = exp_helper( std::max(mss::tmrd(), mss::tmod(i_target)) );
l_data.insertFromRight<TT::TMOD_CYCLES, TT::TMOD_CYCLES_LEN>(l_tmod_cycles);
FAPI_TRY( mss::eff_dram_trcd(i_target, l_trcd) );
l_data.insertFromRight<TT::TRCD_CYCLES, TT::TRCD_CYCLES_LEN>( exp_helper(l_trcd) );
FAPI_TRY( mss::eff_dram_trp(i_target, l_trp) );
l_data.insertFromRight<TT::TRP_CYCLES, TT::TRP_CYCLES_LEN>( exp_helper(l_trp) );
// It's not really clear what to put here. We can have DIMM with different tRFC as they
// don't have to be the same (3DS v. SDP for example.) So we'll take the maximum trfc we
// find on the DIMM connected to this port.
for (const auto& d : mss::find_targets<TARGET_TYPE_DIMM>(i_target))
{
// tRFC is for non-3DS, tRFC_slr for 3DS is to the same logical rank,
// and tRFC_dlr is to different logical ranks. Unclear which to use.
uint16_t l_trfc = 0;
uint8_t l_trfc_dlr = 0;
// tRFC (or tRFC_slr) will retrieve a value for 3DS or non-3DS
// tRFC_dlr is only set for 3DS (should be 0 otherwise)
// so we opt to take the more aggressive timing,
// means less chance of data being corrupted
FAPI_TRY( mss::eff_dram_trfc(d, l_trfc) );
FAPI_TRY( mss::eff_dram_trfc_dlr(d, l_trfc_dlr) );
{
// cast needed for template deduction of std::max()
// HB doesn't support using std::min() with initializer lists
const uint16_t l_trfc_3ds_min = std::min(l_trfc, static_cast<uint16_t>(l_trfc_dlr));
l_trfc_max = std::min( l_trfc_3ds_min, l_trfc_max);
}
}
l_data.insertFromRight<TT::TRFC_CYCLES, TT::TRFC_CYCLES_LEN>( exp_helper(l_trfc_max) );
FAPI_TRY( mss::putScom(i_target, TT::SEQ_TIMING0_REG, l_data) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief reset SEQ_TIMING1
/// @param[in] i_target fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode reset_timing1( const fapi2::Target<TARGET_TYPE_MCA>& i_target )
{
typedef seqTraits<TARGET_TYPE_MCA> TT;
fapi2::buffer<uint64_t> l_data;
// Table 5-325. SEQ Memory Timing Parameter 1 Register
// TZQINIT_CYCLES max(tZQINIT,tZQOPER)
// TZQCS_CYCLES tZQCS
// TWLDQSEN_CYCLES tWLDQSEN
// TWRMRD_CYCLES tWLMRD
uint64_t l_tzqint = std::max( mss::tzqinit(), mss::tzqoper() );
l_data.insertFromRight<TT::TZQINIT_CYCLES, TT::TZQINIT_CYCLES_LEN>( exp_helper(l_tzqint) );
l_data.insertFromRight<TT::TZQCS_CYCLES, TT::TZQCS_CYCLES_LEN>( exp_helper(mss::tzqcs()) );
l_data.insertFromRight<TT::TWLDQSEN_CYCLES, TT::TWLDQSEN_CYCLES_LEN>( exp_helper(mss::twldqsen()) );
l_data.insertFromRight<TT::TWRMRD_CYCLES, TT::TWRMRD_CYCLES_LEN>( exp_helper(mss::twlmrd()) );
return mss::putScom(i_target, TT::SEQ_TIMING1_REG, l_data);
}
///
/// @brief reset SEQ_TIMING2
/// @param[in] i_target fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode reset_timing2( const fapi2::Target<TARGET_TYPE_MCA>& i_target )
{
typedef seqTraits<TARGET_TYPE_MCA> TT;
// Reset value of SEQ_TIMING2 is lucky 7's - we'll fix up the first nibble with ODT info
fapi2::buffer<uint64_t> l_data(0x7777);
// Table 5-327. SEQ Memory Timing Parameter 2 Register
// TODTLON_OFF_CYCLES max(ODTLon, ODTLoff)
uint8_t l_odtlon = 0;
uint8_t l_odtloff = 0;
uint64_t l_odt = 0;
FAPI_TRY( mss::max_dodt_on(i_target, l_odtlon) );
FAPI_TRY( mss::max_dodt_off(i_target, l_odtloff) );
l_odt = std::max( l_odtlon, l_odtloff );
l_data.insertFromRight<TT::TODTLON_OFF_CYCLES, TT::TODTLON_OFF_CYCLES_LEN>( exp_helper(l_odt) );
FAPI_TRY( mss::putScom(i_target, TT::SEQ_TIMING2_REG, l_data) );
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace seq
} // close namespace mss
<commit_msg>L3 support for ddr_phy_reset, termination_control<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/seq.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] 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 seq.C
/// @brief Subroutines for the PHY SEQ registers
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <lib/phy/seq.H>
#include <generic/memory/lib/utils/scom.H>
#include <generic/memory/lib/utils/c_str.H>
#include <lib/utils/bit_count.H>
#include <lib/eff_config/timing.H>
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;
namespace mss
{
namespace seq
{
///
/// @brief PHY SEQ register exponent helper
/// PHY SEQ fields is used as exponent of 2, to calculate the number of MEMINTCLKO clock cycles.
/// For example, if TMOD_CYCLES[0:3] = 5, the internal timers use the value 2^5 = 32 MEMINTCLKO
/// clock cycles. The maximum value per nibble is ‘A’h. This helper takes a calculated value and returns
/// the 'best' exponent.
/// @param[in] i_value a value for which to make an exponent
/// @return uint64_t right-aligned value to stick in the field
///
uint64_t exp_helper( const uint64_t i_value )
{
// PHY exponents don't make much sense above this value so we short circuit if possible.
constexpr uint64_t MAX_EXP = 0xA;
if (i_value >= (1 << MAX_EXP))
{
return 0xA;
}
// If the user passes in 0, let it past.
if (i_value == 0)
{
return 0;
}
// Find the first bit set. The subtraction from 63 switches from a left-count to a right-count (e.g., 0 (left most
// bit) is really bit 63 if you start on the right.)
const uint64_t l_first_bit = 63 - first_bit_set(i_value);
// If the input is greater than 2^first bit, add one to the first_bit so 2^first_bit >= input
// (round up)
return l_first_bit + (uint64_t(1 << l_first_bit) < i_value ? 1 : 0);
}
///
/// @brief reset SEQ_TIMING0
/// @param[in] i_target fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode reset_timing0( const fapi2::Target<TARGET_TYPE_MCA>& i_target )
{
typedef seqTraits<TARGET_TYPE_MCA> TT;
fapi2::buffer<uint64_t> l_data;
// Table 5-324. SEQ Memory Timing Parameter 0 Register Bit Definition
// TMOD_CYCLES max(tMRD, tMOD)
// TRCD_CYCLES tRCD
// TRP_CYCLES tRP
// TRFC_CYCLES tRFC
uint64_t l_tmod_cycles = 0;
uint8_t l_trcd = 0;
uint8_t l_trp = 0;
uint16_t l_trfc_max = 0;
l_tmod_cycles = exp_helper( std::max(mss::tmrd(), mss::tmod(i_target)) );
l_data.insertFromRight<TT::TMOD_CYCLES, TT::TMOD_CYCLES_LEN>(l_tmod_cycles);
FAPI_TRY( mss::eff_dram_trcd(i_target, l_trcd) );
l_data.insertFromRight<TT::TRCD_CYCLES, TT::TRCD_CYCLES_LEN>( exp_helper(l_trcd) );
FAPI_TRY( mss::eff_dram_trp(i_target, l_trp) );
l_data.insertFromRight<TT::TRP_CYCLES, TT::TRP_CYCLES_LEN>( exp_helper(l_trp) );
// It's not really clear what to put here. We can have DIMM with different tRFC as they
// don't have to be the same (3DS v. SDP for example.) So we'll take the maximum trfc we
// find on the DIMM connected to this port.
for (const auto& d : mss::find_targets<TARGET_TYPE_DIMM>(i_target))
{
// tRFC is for non-3DS, tRFC_slr for 3DS is to the same logical rank,
// and tRFC_dlr is to different logical ranks. Unclear which to use.
uint16_t l_trfc = 0;
uint8_t l_trfc_dlr = 0;
// tRFC (or tRFC_slr) will retrieve a value for 3DS or non-3DS
// tRFC_dlr is only set for 3DS (should be 0 otherwise)
// so we opt to take the more aggressive timing,
// means less chance of data being corrupted
FAPI_TRY( mss::eff_dram_trfc(d, l_trfc) );
FAPI_TRY( mss::eff_dram_trfc_dlr(d, l_trfc_dlr) );
{
// cast needed for template deduction of std::max()
// HB doesn't support using std::min() with initializer lists
const uint16_t l_trfc_3ds_min = std::min(l_trfc, static_cast<uint16_t>(l_trfc_dlr));
l_trfc_max = std::min( l_trfc_3ds_min, l_trfc_max);
}
}
l_data.insertFromRight<TT::TRFC_CYCLES, TT::TRFC_CYCLES_LEN>( exp_helper(l_trfc_max) );
FAPI_TRY( mss::putScom(i_target, TT::SEQ_TIMING0_REG, l_data) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief reset SEQ_TIMING1
/// @param[in] i_target fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode reset_timing1( const fapi2::Target<TARGET_TYPE_MCA>& i_target )
{
typedef seqTraits<TARGET_TYPE_MCA> TT;
fapi2::buffer<uint64_t> l_data;
// Table 5-325. SEQ Memory Timing Parameter 1 Register
// TZQINIT_CYCLES max(tZQINIT,tZQOPER)
// TZQCS_CYCLES tZQCS
// TWLDQSEN_CYCLES tWLDQSEN
// TWRMRD_CYCLES tWLMRD
uint64_t l_tzqint = std::max( mss::tzqinit(), mss::tzqoper() );
l_data.insertFromRight<TT::TZQINIT_CYCLES, TT::TZQINIT_CYCLES_LEN>( exp_helper(l_tzqint) );
l_data.insertFromRight<TT::TZQCS_CYCLES, TT::TZQCS_CYCLES_LEN>( exp_helper(mss::tzqcs()) );
l_data.insertFromRight<TT::TWLDQSEN_CYCLES, TT::TWLDQSEN_CYCLES_LEN>( exp_helper(mss::twldqsen()) );
l_data.insertFromRight<TT::TWRMRD_CYCLES, TT::TWRMRD_CYCLES_LEN>( exp_helper(mss::twlmrd()) );
return mss::putScom(i_target, TT::SEQ_TIMING1_REG, l_data);
}
///
/// @brief reset SEQ_TIMING2
/// @param[in] i_target fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode reset_timing2( const fapi2::Target<TARGET_TYPE_MCA>& i_target )
{
typedef seqTraits<TARGET_TYPE_MCA> TT;
// Reset value of SEQ_TIMING2 is lucky 7's - we'll fix up the first nibble with ODT info
fapi2::buffer<uint64_t> l_data(0x7777);
// Table 5-327. SEQ Memory Timing Parameter 2 Register
// TODTLON_OFF_CYCLES max(ODTLon, ODTLoff)
uint8_t l_odtlon = 0;
uint8_t l_odtloff = 0;
uint64_t l_odt = 0;
FAPI_TRY( mss::max_dodt_on(i_target, l_odtlon) );
FAPI_TRY( mss::max_dodt_off(i_target, l_odtloff) );
l_odt = std::max( l_odtlon, l_odtloff );
l_data.insertFromRight<TT::TODTLON_OFF_CYCLES, TT::TODTLON_OFF_CYCLES_LEN>( exp_helper(l_odt) );
FAPI_TRY( mss::putScom(i_target, TT::SEQ_TIMING2_REG, l_data) );
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace seq
} // close namespace mss
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] 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_mss_freq.C
/// @brief Calculate and save off DIMM frequencies
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP FW Owner: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include <p9_mss_freq.H>
// std lib
#include <map>
// fapi2
#include <fapi2.H>
// mss lib
#include <generic/memory/lib/spd/common/ddr4/spd_decoder_ddr4.H>
#include <lib/spd/spd_factory.H>
#include <lib/freq/cas_latency.H>
#include <generic/memory/lib/utils/c_str.H>
#include <lib/freq/cycle_time.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/utils/count_dimm.H>
#include <lib/utils/index.H>
#include <lib/shared/mss_const.H>
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::FAPI2_RC_SUCCESS;
extern "C"
{
///
/// @brief Calculate and save off DIMM frequencies
/// @param[in] i_target, the controller (e.g., MCS)
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_freq( const fapi2::Target<TARGET_TYPE_MCS>& i_target )
{
// TODO RTC:161701 p9_mss_freq needs to be re-worked to work per-MC as it's hard
// (if not impossible) to know the appropriate freq if we don't have information
// for both MCS. Setting one to max freq doesn't work in the case of 0 DIMM as
// there is no check for other freq's and we end up setting the chosen freq to
// the default.
// So for now, iterate over all the MCBIST. This isn't great as we do this work
// twice for every MC. However, attribute access is cheap so this will suffice for
// the time being.
std::vector<uint64_t> l_min_dimm_freq(mss::MCS_PER_MC, 0);
std::vector<uint64_t> l_desired_cas_latency(mss::MCS_PER_MC, 0);
const auto& l_mcbist = mss::find_target<TARGET_TYPE_MCBIST>(i_target);
// If there are no DIMM, we can just get out.
if (mss::count_dimm(l_mcbist) == 0)
{
FAPI_INF("Seeing no DIMM on %s, no freq to set", mss::c_str(l_mcbist));
return FAPI2_RC_SUCCESS;
}
for (const auto& l_mcs : mss::find_targets<TARGET_TYPE_MCS>(l_mcbist))
{
const auto l_index = mss::index(l_mcs);
// Get cached decoder
std::vector< std::shared_ptr<mss::spd::decoder> > l_factory_caches;
FAPI_TRY( mss::spd::populate_decoder_caches(l_mcs, l_factory_caches),
"%s. Failed to populate decoder cache", mss::c_str(i_target) );
{
// instantiation of class that calculates CL algorithm
fapi2::ReturnCode l_rc;
mss::cas_latency l_cas_latency( l_mcs, l_factory_caches, l_rc );
FAPI_TRY( l_rc, "%s. Failed to initialize cas_latency ctor", mss::c_str(i_target) );
if(l_cas_latency.iv_dimm_list_empty)
{
// Cannot fail out for an empty DIMM configuration, so default values are set
FAPI_INF("%s. DIMM list is empty! Setting default values for CAS latency and DIMM speed.",
mss::c_str(i_target) );
}
else
{
// We set this to a non-0 so we avoid divide-by-zero errors in the conversions which
// go from clocks to time (and vice versa.) We have other bugs if there was really
// no MT/s determined and there really is a DIMM installed, so this is ok.
// We pick the maximum frequency supported by the system as the default.
l_min_dimm_freq[l_index] = fapi2::ENUM_ATTR_MSS_FREQ_MT2666;
uint64_t l_tCKmin = 0;
// Find CAS latency using JEDEC algorithm
FAPI_TRY( l_cas_latency.find_cl(l_desired_cas_latency[l_index],
l_tCKmin) );
FAPI_INF("%s. Result from CL algorithm, CL (nck): %d, tCK (ps): %d",
mss::c_str(i_target), l_desired_cas_latency[l_index], l_tCKmin);
// Find dimm transfer speed from selected tCK
FAPI_TRY( mss::ps_to_freq(l_tCKmin, l_min_dimm_freq[l_index]),
"%s. Failed ps_to_freq()", mss::c_str(i_target) );
FAPI_INF("DIMM speed from selected tCK (ps): %d for %s", l_min_dimm_freq[l_index], mss::c_str(l_mcs));
FAPI_TRY(mss::select_supported_freq(l_mcs, l_min_dimm_freq[l_index]),
"Failed select_supported_freq() for %s", mss::c_str(l_mcs));
FAPI_INF("%s. Selected DIMM speed from supported speeds: %d",
mss::c_str(i_target), l_min_dimm_freq[l_index]);
}// end else
} // close scope
FAPI_TRY(mss::set_CL_attr(l_mcs, l_desired_cas_latency[l_index] ),
"%s. Failed set_CL_attr()", mss::c_str(i_target) );
} // close for each mcs
FAPI_TRY(mss::set_freq_attrs(l_mcbist, l_min_dimm_freq),
"%s. Failed set_freq_attrs()", mss::c_str(i_target) );
fapi_try_exit:
return fapi2::current_err;
}// p9_mss_freq
}// extern C
<commit_msg>Move index API to generic/memory folder<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] 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_mss_freq.C
/// @brief Calculate and save off DIMM frequencies
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP FW Owner: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include <p9_mss_freq.H>
// std lib
#include <map>
// fapi2
#include <fapi2.H>
// mss lib
#include <generic/memory/lib/spd/common/ddr4/spd_decoder_ddr4.H>
#include <lib/spd/spd_factory.H>
#include <lib/freq/cas_latency.H>
#include <generic/memory/lib/utils/c_str.H>
#include <lib/freq/cycle_time.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/utils/count_dimm.H>
#include <generic/memory/lib/utils/index.H>
#include <lib/shared/mss_const.H>
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::FAPI2_RC_SUCCESS;
extern "C"
{
///
/// @brief Calculate and save off DIMM frequencies
/// @param[in] i_target, the controller (e.g., MCS)
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_freq( const fapi2::Target<TARGET_TYPE_MCS>& i_target )
{
// TODO RTC:161701 p9_mss_freq needs to be re-worked to work per-MC as it's hard
// (if not impossible) to know the appropriate freq if we don't have information
// for both MCS. Setting one to max freq doesn't work in the case of 0 DIMM as
// there is no check for other freq's and we end up setting the chosen freq to
// the default.
// So for now, iterate over all the MCBIST. This isn't great as we do this work
// twice for every MC. However, attribute access is cheap so this will suffice for
// the time being.
std::vector<uint64_t> l_min_dimm_freq(mss::MCS_PER_MC, 0);
std::vector<uint64_t> l_desired_cas_latency(mss::MCS_PER_MC, 0);
const auto& l_mcbist = mss::find_target<TARGET_TYPE_MCBIST>(i_target);
// If there are no DIMM, we can just get out.
if (mss::count_dimm(l_mcbist) == 0)
{
FAPI_INF("Seeing no DIMM on %s, no freq to set", mss::c_str(l_mcbist));
return FAPI2_RC_SUCCESS;
}
for (const auto& l_mcs : mss::find_targets<TARGET_TYPE_MCS>(l_mcbist))
{
const auto l_index = mss::index(l_mcs);
// Get cached decoder
std::vector< std::shared_ptr<mss::spd::decoder> > l_factory_caches;
FAPI_TRY( mss::spd::populate_decoder_caches(l_mcs, l_factory_caches),
"%s. Failed to populate decoder cache", mss::c_str(i_target) );
{
// instantiation of class that calculates CL algorithm
fapi2::ReturnCode l_rc;
mss::cas_latency l_cas_latency( l_mcs, l_factory_caches, l_rc );
FAPI_TRY( l_rc, "%s. Failed to initialize cas_latency ctor", mss::c_str(i_target) );
if(l_cas_latency.iv_dimm_list_empty)
{
// Cannot fail out for an empty DIMM configuration, so default values are set
FAPI_INF("%s. DIMM list is empty! Setting default values for CAS latency and DIMM speed.",
mss::c_str(i_target) );
}
else
{
// We set this to a non-0 so we avoid divide-by-zero errors in the conversions which
// go from clocks to time (and vice versa.) We have other bugs if there was really
// no MT/s determined and there really is a DIMM installed, so this is ok.
// We pick the maximum frequency supported by the system as the default.
l_min_dimm_freq[l_index] = fapi2::ENUM_ATTR_MSS_FREQ_MT2666;
uint64_t l_tCKmin = 0;
// Find CAS latency using JEDEC algorithm
FAPI_TRY( l_cas_latency.find_cl(l_desired_cas_latency[l_index],
l_tCKmin) );
FAPI_INF("%s. Result from CL algorithm, CL (nck): %d, tCK (ps): %d",
mss::c_str(i_target), l_desired_cas_latency[l_index], l_tCKmin);
// Find dimm transfer speed from selected tCK
FAPI_TRY( mss::ps_to_freq(l_tCKmin, l_min_dimm_freq[l_index]),
"%s. Failed ps_to_freq()", mss::c_str(i_target) );
FAPI_INF("DIMM speed from selected tCK (ps): %d for %s", l_min_dimm_freq[l_index], mss::c_str(l_mcs));
FAPI_TRY(mss::select_supported_freq(l_mcs, l_min_dimm_freq[l_index]),
"Failed select_supported_freq() for %s", mss::c_str(l_mcs));
FAPI_INF("%s. Selected DIMM speed from supported speeds: %d",
mss::c_str(i_target), l_min_dimm_freq[l_index]);
}// end else
} // close scope
FAPI_TRY(mss::set_CL_attr(l_mcs, l_desired_cas_latency[l_index] ),
"%s. Failed set_CL_attr()", mss::c_str(i_target) );
} // close for each mcs
FAPI_TRY(mss::set_freq_attrs(l_mcbist, l_min_dimm_freq),
"%s. Failed set_freq_attrs()", mss::c_str(i_target) );
fapi_try_exit:
return fapi2::current_err;
}// p9_mss_freq
}// extern C
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/side.h"
#include "libmesh/cell_pyramid14.h"
#include "libmesh/edge_edge3.h"
#include "libmesh/face_tri6.h"
#include "libmesh/face_quad9.h"
namespace libMesh
{
// ------------------------------------------------------------
// Pyramid14 class static member initializations
const unsigned int Pyramid14::side_nodes_map[5][9] =
{
{0, 1, 4, 5, 10, 9, 99, 99, 99}, // Side 0 (front)
{1, 2, 4, 6, 11, 10, 99, 99, 99}, // Side 1 (right)
{2, 3, 4, 7, 12, 11, 99, 99, 99}, // Side 2 (back)
{3, 0, 4, 8, 9, 12, 99, 99, 99}, // Side 3 (left)
{0, 3, 2, 1, 8, 7, 6, 5, 13} // Side 4 (base)
};
const unsigned int Pyramid14::edge_nodes_map[8][3] =
{
{0, 1, 5}, // Edge 0
{1, 2, 6}, // Edge 1
{2, 3, 7}, // Edge 2
{0, 3, 8}, // Edge 3
{0, 4, 9}, // Edge 4
{1, 4, 10}, // Edge 5
{2, 4, 11}, // Edge 6
{3, 4, 12} // Edge 7
};
// ------------------------------------------------------------
// Pyramid14 class member functions
bool Pyramid14::is_vertex(const unsigned int i) const
{
if (i < 5)
return true;
return false;
}
bool Pyramid14::is_edge(const unsigned int i) const
{
if (i < 5)
return false;
if (i == 13)
return false;
return true;
}
bool Pyramid14::is_face(const unsigned int i) const
{
if (i == 13)
return true;
return false;
}
bool Pyramid14::is_node_on_side(const unsigned int n,
const unsigned int s) const
{
libmesh_assert_less (s, n_sides());
for (unsigned int i = 0; i != 4; ++i)
if (side_nodes_map[s][i] == n)
return true;
return false;
}
bool Pyramid14::is_node_on_edge(const unsigned int n,
const unsigned int e) const
{
libmesh_assert_less (e, n_edges());
for (unsigned int i = 0; i != 2; ++i)
if (edge_nodes_map[e][i] == n)
return true;
return false;
}
bool Pyramid14::has_affine_map() const
{
// TODO: If the base is a parallelogram and all the triangular faces are planar,
// the map should be linear, but I need to test this theory...
return false;
}
AutoPtr<Elem> Pyramid14::build_side (const unsigned int i, bool proxy) const
{
libmesh_assert_less (i, this->n_sides());
if (proxy)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
{
AutoPtr<Elem> face(new Side<Tri6,Pyramid14>(this,i));
return face;
}
case 4:
{
AutoPtr<Elem> face(new Side<Quad9,Pyramid14>(this,i));
return face;
}
default:
{
libmesh_error();
}
}
}
else
{
// Create NULL pointer to be initialized, returned later.
AutoPtr<Elem> face(NULL);
switch (i)
{
case 0: // triangular face 1
{
face.reset(new Tri6);
face->set_node(0) = this->get_node(0);
face->set_node(1) = this->get_node(1);
face->set_node(2) = this->get_node(4);
face->set_node(3) = this->get_node(5);
face->set_node(4) = this->get_node(10);
face->set_node(5) = this->get_node(9);
break;
}
case 1: // triangular face 2
{
face.reset(new Tri6);
face->set_node(0) = this->get_node(1);
face->set_node(1) = this->get_node(2);
face->set_node(2) = this->get_node(4);
face->set_node(3) = this->get_node(6);
face->set_node(4) = this->get_node(11);
face->set_node(5) = this->get_node(10);
break;
}
case 2: // triangular face 3
{
face.reset(new Tri6);
face->set_node(0) = this->get_node(2);
face->set_node(1) = this->get_node(3);
face->set_node(2) = this->get_node(4);
face->set_node(3) = this->get_node(7);
face->set_node(4) = this->get_node(12);
face->set_node(5) = this->get_node(11);
break;
}
case 3: // triangular face 4
{
face.reset(new Tri6);
face->set_node(0) = this->get_node(3);
face->set_node(1) = this->get_node(0);
face->set_node(2) = this->get_node(4);
face->set_node(3) = this->get_node(8);
face->set_node(4) = this->get_node(9);
face->set_node(5) = this->get_node(12);
break;
}
case 4: // the quad face at z=0
{
face.reset(new Quad9);
face->set_node(0) = this->get_node(0);
face->set_node(1) = this->get_node(3);
face->set_node(2) = this->get_node(2);
face->set_node(3) = this->get_node(1);
face->set_node(4) = this->get_node(8);
face->set_node(5) = this->get_node(7);
face->set_node(6) = this->get_node(6);
face->set_node(7) = this->get_node(5);
face->set_node(8) = this->get_node(13);
break;
}
default:
{
libmesh_error();
}
}
face->subdomain_id() = this->subdomain_id();
return face;
}
// We'll never get here.
libmesh_error();
AutoPtr<Elem> ap(NULL); return ap;
}
AutoPtr<Elem> Pyramid14::build_edge (const unsigned int i) const
{
libmesh_assert_less (i, this->n_edges());
return AutoPtr<Elem>(new SideEdge<Edge3,Pyramid14>(this,i));
}
void Pyramid14::connectivity(const unsigned int libmesh_dbg_var(sc),
const IOPackage iop,
std::vector<dof_id_type>& conn) const
{
libmesh_assert(_nodes);
libmesh_assert_less (sc, this->n_sub_elem());
libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);
switch (iop)
{
case TECPLOT:
{
// FIXME
conn.resize(8);
conn[0] = this->node(0)+1;
conn[1] = this->node(1)+1;
conn[2] = this->node(2)+1;
conn[3] = this->node(3)+1;
conn[4] = this->node(4)+1;
conn[5] = this->node(4)+1;
conn[6] = this->node(4)+1;
conn[7] = this->node(4)+1;
return;
}
case VTK:
{
// FIXME
conn.resize(5);
conn[0] = this->node(3);
conn[1] = this->node(2);
conn[2] = this->node(1);
conn[3] = this->node(0);
conn[4] = this->node(4);
return;
}
default:
libmesh_error();
}
libmesh_error();
}
unsigned int Pyramid14::n_second_order_adjacent_vertices (const unsigned int n) const
{
switch (n)
{
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
return 2;
case 13:
return 4;
default:
libmesh_error();
}
// We'll never get here
libmesh_error();
return static_cast<unsigned int>(-1);
}
unsigned short int Pyramid14::second_order_adjacent_vertex (const unsigned int n,
const unsigned int v) const
{
libmesh_assert_greater_equal (n, this->n_vertices());
libmesh_assert_less (n, this->n_nodes());
switch (n)
{
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
{
libmesh_assert_less (v, 2);
// This is the analog of the static, const arrays
// {Hex,Prism,Tet10}::_second_order_adjacent_vertices
// defined in the respective source files... possibly treat
// this similarly once the Pyramid13 has been added?
unsigned short node_list[8][2] =
{
{0,1},
{1,2},
{2,3},
{0,3},
{0,4},
{1,4},
{2,4},
{3,4}
};
return node_list[n-5][v];
}
// mid-face node on bottom
case 13:
{
libmesh_assert_less (v, 4);
// The vertex nodes surrounding node 13 are 0, 1, 2, and 3.
// Thus, the v'th node is simply = v.
return v;
}
default:
{
// We can't handle this n, throw an error!
libmesh_error();
}
}
// We'll never get here
libmesh_error();
return static_cast<unsigned short int>(-1);
}
} // namespace libMesh
<commit_msg>Fixing is_node_on_{side,edge} for Pyramid14.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/side.h"
#include "libmesh/cell_pyramid14.h"
#include "libmesh/edge_edge3.h"
#include "libmesh/face_tri6.h"
#include "libmesh/face_quad9.h"
namespace libMesh
{
// ------------------------------------------------------------
// Pyramid14 class static member initializations
const unsigned int Pyramid14::side_nodes_map[5][9] =
{
{0, 1, 4, 5, 10, 9, 99, 99, 99}, // Side 0 (front)
{1, 2, 4, 6, 11, 10, 99, 99, 99}, // Side 1 (right)
{2, 3, 4, 7, 12, 11, 99, 99, 99}, // Side 2 (back)
{3, 0, 4, 8, 9, 12, 99, 99, 99}, // Side 3 (left)
{0, 3, 2, 1, 8, 7, 6, 5, 13} // Side 4 (base)
};
const unsigned int Pyramid14::edge_nodes_map[8][3] =
{
{0, 1, 5}, // Edge 0
{1, 2, 6}, // Edge 1
{2, 3, 7}, // Edge 2
{0, 3, 8}, // Edge 3
{0, 4, 9}, // Edge 4
{1, 4, 10}, // Edge 5
{2, 4, 11}, // Edge 6
{3, 4, 12} // Edge 7
};
// ------------------------------------------------------------
// Pyramid14 class member functions
bool Pyramid14::is_vertex(const unsigned int i) const
{
if (i < 5)
return true;
return false;
}
bool Pyramid14::is_edge(const unsigned int i) const
{
if (i < 5)
return false;
if (i == 13)
return false;
return true;
}
bool Pyramid14::is_face(const unsigned int i) const
{
if (i == 13)
return true;
return false;
}
bool Pyramid14::is_node_on_side(const unsigned int n,
const unsigned int s) const
{
libmesh_assert_less (s, n_sides());
for (unsigned int i = 0; i != 9; ++i)
if (side_nodes_map[s][i] == n)
return true;
return false;
}
bool Pyramid14::is_node_on_edge(const unsigned int n,
const unsigned int e) const
{
libmesh_assert_less (e, n_edges());
for (unsigned int i = 0; i != 3; ++i)
if (edge_nodes_map[e][i] == n)
return true;
return false;
}
bool Pyramid14::has_affine_map() const
{
// TODO: If the base is a parallelogram and all the triangular faces are planar,
// the map should be linear, but I need to test this theory...
return false;
}
AutoPtr<Elem> Pyramid14::build_side (const unsigned int i, bool proxy) const
{
libmesh_assert_less (i, this->n_sides());
if (proxy)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
{
AutoPtr<Elem> face(new Side<Tri6,Pyramid14>(this,i));
return face;
}
case 4:
{
AutoPtr<Elem> face(new Side<Quad9,Pyramid14>(this,i));
return face;
}
default:
{
libmesh_error();
}
}
}
else
{
// Create NULL pointer to be initialized, returned later.
AutoPtr<Elem> face(NULL);
switch (i)
{
case 0: // triangular face 1
{
face.reset(new Tri6);
face->set_node(0) = this->get_node(0);
face->set_node(1) = this->get_node(1);
face->set_node(2) = this->get_node(4);
face->set_node(3) = this->get_node(5);
face->set_node(4) = this->get_node(10);
face->set_node(5) = this->get_node(9);
break;
}
case 1: // triangular face 2
{
face.reset(new Tri6);
face->set_node(0) = this->get_node(1);
face->set_node(1) = this->get_node(2);
face->set_node(2) = this->get_node(4);
face->set_node(3) = this->get_node(6);
face->set_node(4) = this->get_node(11);
face->set_node(5) = this->get_node(10);
break;
}
case 2: // triangular face 3
{
face.reset(new Tri6);
face->set_node(0) = this->get_node(2);
face->set_node(1) = this->get_node(3);
face->set_node(2) = this->get_node(4);
face->set_node(3) = this->get_node(7);
face->set_node(4) = this->get_node(12);
face->set_node(5) = this->get_node(11);
break;
}
case 3: // triangular face 4
{
face.reset(new Tri6);
face->set_node(0) = this->get_node(3);
face->set_node(1) = this->get_node(0);
face->set_node(2) = this->get_node(4);
face->set_node(3) = this->get_node(8);
face->set_node(4) = this->get_node(9);
face->set_node(5) = this->get_node(12);
break;
}
case 4: // the quad face at z=0
{
face.reset(new Quad9);
face->set_node(0) = this->get_node(0);
face->set_node(1) = this->get_node(3);
face->set_node(2) = this->get_node(2);
face->set_node(3) = this->get_node(1);
face->set_node(4) = this->get_node(8);
face->set_node(5) = this->get_node(7);
face->set_node(6) = this->get_node(6);
face->set_node(7) = this->get_node(5);
face->set_node(8) = this->get_node(13);
break;
}
default:
{
libmesh_error();
}
}
face->subdomain_id() = this->subdomain_id();
return face;
}
// We'll never get here.
libmesh_error();
AutoPtr<Elem> ap(NULL); return ap;
}
AutoPtr<Elem> Pyramid14::build_edge (const unsigned int i) const
{
libmesh_assert_less (i, this->n_edges());
return AutoPtr<Elem>(new SideEdge<Edge3,Pyramid14>(this,i));
}
void Pyramid14::connectivity(const unsigned int libmesh_dbg_var(sc),
const IOPackage iop,
std::vector<dof_id_type>& conn) const
{
libmesh_assert(_nodes);
libmesh_assert_less (sc, this->n_sub_elem());
libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);
switch (iop)
{
case TECPLOT:
{
// FIXME
conn.resize(8);
conn[0] = this->node(0)+1;
conn[1] = this->node(1)+1;
conn[2] = this->node(2)+1;
conn[3] = this->node(3)+1;
conn[4] = this->node(4)+1;
conn[5] = this->node(4)+1;
conn[6] = this->node(4)+1;
conn[7] = this->node(4)+1;
return;
}
case VTK:
{
// FIXME
conn.resize(5);
conn[0] = this->node(3);
conn[1] = this->node(2);
conn[2] = this->node(1);
conn[3] = this->node(0);
conn[4] = this->node(4);
return;
}
default:
libmesh_error();
}
libmesh_error();
}
unsigned int Pyramid14::n_second_order_adjacent_vertices (const unsigned int n) const
{
switch (n)
{
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
return 2;
case 13:
return 4;
default:
libmesh_error();
}
// We'll never get here
libmesh_error();
return static_cast<unsigned int>(-1);
}
unsigned short int Pyramid14::second_order_adjacent_vertex (const unsigned int n,
const unsigned int v) const
{
libmesh_assert_greater_equal (n, this->n_vertices());
libmesh_assert_less (n, this->n_nodes());
switch (n)
{
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
{
libmesh_assert_less (v, 2);
// This is the analog of the static, const arrays
// {Hex,Prism,Tet10}::_second_order_adjacent_vertices
// defined in the respective source files... possibly treat
// this similarly once the Pyramid13 has been added?
unsigned short node_list[8][2] =
{
{0,1},
{1,2},
{2,3},
{0,3},
{0,4},
{1,4},
{2,4},
{3,4}
};
return node_list[n-5][v];
}
// mid-face node on bottom
case 13:
{
libmesh_assert_less (v, 4);
// The vertex nodes surrounding node 13 are 0, 1, 2, and 3.
// Thus, the v'th node is simply = v.
return v;
}
default:
{
// We can't handle this n, throw an error!
libmesh_error();
}
}
// We'll never get here
libmesh_error();
return static_cast<unsigned short int>(-1);
}
} // namespace libMesh
<|endoftext|> |
<commit_before>#ifndef MTL_STREAM_CALLER_MAPPER_CHANNEL_PROXY
#define MTL_STREAM_CALLER_MAPPER_CHANNEL_PROXY
#include "../stream_channel.hpp"
#include <cassert>
namespace mtl
{
template<typename Stream, typename FunctionID = std::string>
class function_mapper_channel_proxy : public stream_channel<Stream>
{
public:
using request_id_type = uint32_t;
using ProxyCallback = std::function<void(Stream& ss)>;
using RequestMap = std::map<request_id_type, ProxyCallback>;
Stream create_stream()
{
Stream arg;
arg << _magic_number;
arg << _magic_number;
return arg;
}
void proxy_call(Stream& arg, const ProxyCallback& callback)
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto id = _last_id++;
//replacing header in stream - stream should be created by us in create_stream
//so we are replacing first _magic_number
{
auto pp = arg.tellp();
arg.seekp(0);
arg << id;
arg.seekp(pp);
}
_requests[id] = callback;
send_stream(arg);
}
void received_stream(Stream& ss) override
{
request_id_type id;
ss >> id;
request_id_type number;
ss >> number;
if (number != _magic_number)
{
assert(false);
return;
}
ProxyCallback callback;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto it = _requests.find(id);
if (it == _requests.end())
return;
callback = it->second;
_requests.erase(it);
}
callback(ss);
}
protected:
constexpr static request_id_type _magic_number = 0xFF003200;
request_id_type _last_id = 1;
std::recursive_mutex _mutex;
RequestMap _requests;
};
template<typename Stream, typename FunctionID = std::string>
class function_mapper_channel_proxy_receiver : public stream_channel<Stream>
{
public:
using request_id_type = uint32_t;
using ProxyCallback = std::function<void(Stream& ss)>;
void received_stream(Stream& ss) override
{
request_id_type id;
ss >> id;
request_id_type number;
ss >> number;
if (number != _magic_number)
{
assert(false);
return;
}
Stream out;
out << id;
out << _magic_number;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_mapper.call_from_stream_out(ss, out);
}
send_stream(out);
}
auto& mapper() { return _mapper; }
protected:
using mapper_type = function_mapper<Stream, FunctionID>;
constexpr static request_id_type _magic_number = 0xFF003200;
std::recursive_mutex _mutex;
mapper_type _mapper;
};
}
#endif<commit_msg>added exception handling<commit_after>#ifndef MTL_STREAM_CALLER_MAPPER_CHANNEL_PROXY
#define MTL_STREAM_CALLER_MAPPER_CHANNEL_PROXY
#include "../stream_channel.hpp"
#include <cassert>
namespace mtl
{
template<typename Stream, typename FunctionID = std::string>
class function_mapper_channel_proxy : public stream_channel<Stream>
{
public:
using request_id_type = uint32_t;
using ProxyCallback = std::function<void(Stream& ss)>;
using RequestMap = std::map<request_id_type, ProxyCallback>;
enum class ResponseType : uint8_t
{
valid = 0,
std_exception,
generic_exception
};
Stream create_stream()
{
Stream arg;
arg << _magic_number;
arg << _magic_number;
return arg;
}
void proxy_call(Stream& arg, const ProxyCallback& callback)
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto id = _last_id++;
//replacing header in stream - stream should be created by us in create_stream
//so we are replacing first _magic_number
{
auto pp = arg.tellp();
arg.seekp(0);
arg << id;
arg.seekp(pp);
}
_requests[id] = callback;
send_stream(arg);
}
void received_stream(Stream& ss) override
{
request_id_type id;
ss >> id;
request_id_type number;
ss >> number;
if (number != _magic_number)
{
assert(false);
return;
}
ResponseType type = ResponseType::valid;
ss >> (uint8_t&)type;
ProxyCallback callback;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto it = _requests.find(id);
if (it == _requests.end())
return;
callback = it->second;
_requests.erase(it);
}
if (type == ResponseType::valid)
{
callback(ss);
return;
}
std::string exc_message;
ss >> exc_message;
//TODO send this error to callback
assert(false);
}
protected:
constexpr static request_id_type _magic_number = 0xFF003200;
request_id_type _last_id = 1;
std::recursive_mutex _mutex;
RequestMap _requests;
};
template<typename Stream, typename FunctionID = std::string>
class function_mapper_channel_proxy_receiver : public stream_channel<Stream>
{
public:
using ResponseType = typename function_mapper_channel_proxy<Stream, FunctionID>::ResponseType;
using request_id_type = uint32_t;
using ProxyCallback = std::function<void(Stream& ss)>;
void received_stream(Stream& ss) override
{
request_id_type id;
ss >> id;
request_id_type number;
ss >> number;
if (number != _magic_number)
{
assert(false);
return;
}
ResponseType type = ResponseType::valid;
std::string exc_message;
Stream out;
try
{
out << id;
out << _magic_number;
out << (uint8_t)type;
std::lock_guard<std::recursive_mutex> lock(_mutex);
_mapper.call_from_stream_out(ss, out);
}
catch (std::exception& exc)
{
type = ResponseType::std_exception;
exc_message = exc.what();
}
catch (...)
{
type = ResponseType::generic_exception;
}
static_assert(sizeof(uint8_t) == sizeof(ResponseType), "ResponseType is not what we expect");
if (type != ResponseType::valid)
{
Stream exc_out;
exc_out << id;
exc_out << _magic_number;
exc_out << (uint8_t)type;
exc_out << exc_message;
send_stream(exc_out);
return;
}
send_stream(out);
}
auto& mapper() { return _mapper; }
protected:
using mapper_type = function_mapper<Stream, FunctionID>;
constexpr static request_id_type _magic_number = 0xFF003200;
std::recursive_mutex _mutex;
mapper_type _mapper;
};
}
#endif<|endoftext|> |
<commit_before>//
// The MIT License (MIT)
//
// Copyright (c) 2017 Tag Games Limited
//
// 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.
//
#ifdef CS_TARGETPLATFORM_RPI
#include <CSBackend/Platform/RPi/Networking/Http/HttpRequestSystem.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Threading/TaskScheduler.h>
#include <curl/curl.h>
namespace CSBackend
{
namespace RPi
{
CS_DEFINE_NAMEDTYPE(HttpRequestSystem);
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::OnInit() noexcept
{
curl_global_init(CURL_GLOBAL_SSL);
}
//--------------------------------------------------------------------------------------------------
bool HttpRequestSystem::IsA(ChilliSource::InterfaceIDType interfaceId) const noexcept
{
return interfaceId == ChilliSource::HttpRequestSystem::InterfaceID || interfaceId == HttpRequestSystem::InterfaceID;
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& url, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
return MakeRequest(HttpRequest::Type::k_get, url, "", ChilliSource::ParamDictionary(), delegate, timeoutSecs);
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& url, const ChilliSource::ParamDictionary& headers, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
return MakeRequest(HttpRequest::Type::k_get, url, "", headers, delegate, timeoutSecs);
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakePostRequest(const std::string& url, const std::string& body, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
return MakeRequest(HttpRequest::Type::k_post, url, body, ChilliSource::ParamDictionary(), delegate, timeoutSecs);
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakePostRequest(const std::string& url, const std::string& body, const ChilliSource::ParamDictionary& headers, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
return MakeRequest(HttpRequest::Type::k_post, url, body, headers, delegate, timeoutSecs);
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakeRequest(HttpRequest::Type type, const std::string& url, const std::string& body, const ChilliSource::ParamDictionary& headers, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
CS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread");
CS_ASSERT(delegate != nullptr, "Cannot make an http request with a null delegate");
CS_ASSERT(url.empty() == false, "Cannot make an http request to a blank url");
//TODO: Persistent connections. Don't close the connection but instead check if the next request is to the same server
//and reuse it. If not then close the connection and open a new one
auto curl = curl_easy_init();
HttpRequest* httpRequest = new HttpRequest(type, url, body, headers, timeoutSecs, curl, GetMaxBufferSize(), delegate);
m_curls.emplace(httpRequest, curl);
m_requests.push_back(httpRequest);
return httpRequest;
}
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::CancelAllRequests() noexcept
{
CS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread");
for(auto request : m_requests)
{
request->Cancel();
}
}
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::CheckReachability(const ReachabilityResultDelegate& delegate) const noexcept
{
//TODO: RPi: Add reachability check
CS_ASSERT(delegate, "The reachability delegate should not be null.");
delegate(true);
}
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::OnUpdate(f32 timeSinceLastUpdate) noexcept
{
//We should do this in two loops incase anyone tries to insert into the requests from the completion callback
for (u32 i=0; i<m_requests.size(); ++i)
{
m_requests[i]->Update(timeSinceLastUpdate);
}
for (auto it = m_requests.begin(); it != m_requests.end(); /*No increment*/)
{
if((*it)->HasCompleted())
{
//...and remove the completed request
auto curlIt = m_curls.find(*it);
curl_easy_cleanup(curlIt->second);
m_curls.erase(curlIt);
CS_SAFEDELETE(*it);
it = m_requests.erase(it);
}
else
{
++it;
}
}
}
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::OnDestroy() noexcept
{
CancelAllRequests();
HttpRequest::Shutdown();
for (auto it = m_requests.begin(); it != m_requests.end(); ++it)
{
CS_SAFEDELETE(*it);
}
m_requests.clear();
m_requests.shrink_to_fit();
for(auto& curl : m_curls)
{
curl_easy_cleanup(curl.second);
}
curl_global_cleanup();
}
}
}
#endif
<commit_msg>Adding warning for unimplemented check reachability<commit_after>//
// The MIT License (MIT)
//
// Copyright (c) 2017 Tag Games Limited
//
// 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.
//
#ifdef CS_TARGETPLATFORM_RPI
#include <CSBackend/Platform/RPi/Networking/Http/HttpRequestSystem.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Threading/TaskScheduler.h>
#include <curl/curl.h>
namespace CSBackend
{
namespace RPi
{
CS_DEFINE_NAMEDTYPE(HttpRequestSystem);
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::OnInit() noexcept
{
curl_global_init(CURL_GLOBAL_SSL);
}
//--------------------------------------------------------------------------------------------------
bool HttpRequestSystem::IsA(ChilliSource::InterfaceIDType interfaceId) const noexcept
{
return interfaceId == ChilliSource::HttpRequestSystem::InterfaceID || interfaceId == HttpRequestSystem::InterfaceID;
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& url, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
return MakeRequest(HttpRequest::Type::k_get, url, "", ChilliSource::ParamDictionary(), delegate, timeoutSecs);
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& url, const ChilliSource::ParamDictionary& headers, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
return MakeRequest(HttpRequest::Type::k_get, url, "", headers, delegate, timeoutSecs);
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakePostRequest(const std::string& url, const std::string& body, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
return MakeRequest(HttpRequest::Type::k_post, url, body, ChilliSource::ParamDictionary(), delegate, timeoutSecs);
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakePostRequest(const std::string& url, const std::string& body, const ChilliSource::ParamDictionary& headers, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
return MakeRequest(HttpRequest::Type::k_post, url, body, headers, delegate, timeoutSecs);
}
//--------------------------------------------------------------------------------------------------
HttpRequest* HttpRequestSystem::MakeRequest(HttpRequest::Type type, const std::string& url, const std::string& body, const ChilliSource::ParamDictionary& headers, const HttpRequest::Delegate& delegate, u32 timeoutSecs) noexcept
{
CS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread");
CS_ASSERT(delegate != nullptr, "Cannot make an http request with a null delegate");
CS_ASSERT(url.empty() == false, "Cannot make an http request to a blank url");
//TODO: Persistent connections. Don't close the connection but instead check if the next request is to the same server
//and reuse it. If not then close the connection and open a new one
auto curl = curl_easy_init();
HttpRequest* httpRequest = new HttpRequest(type, url, body, headers, timeoutSecs, curl, GetMaxBufferSize(), delegate);
m_curls.emplace(httpRequest, curl);
m_requests.push_back(httpRequest);
return httpRequest;
}
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::CancelAllRequests() noexcept
{
CS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread");
for(auto request : m_requests)
{
request->Cancel();
}
}
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::CheckReachability(const ReachabilityResultDelegate& delegate) const noexcept
{
//TODO: RPi: Add reachability check
CS_ASSERT(delegate, "The reachability delegate should not be null.");
CS_LOG_WARNING("CheckReachability: Not implemented on Raspberry Pi");
delegate(true);
}
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::OnUpdate(f32 timeSinceLastUpdate) noexcept
{
//We should do this in two loops incase anyone tries to insert into the requests from the completion callback
for (u32 i=0; i<m_requests.size(); ++i)
{
m_requests[i]->Update(timeSinceLastUpdate);
}
for (auto it = m_requests.begin(); it != m_requests.end(); /*No increment*/)
{
if((*it)->HasCompleted())
{
//...and remove the completed request
auto curlIt = m_curls.find(*it);
curl_easy_cleanup(curlIt->second);
m_curls.erase(curlIt);
CS_SAFEDELETE(*it);
it = m_requests.erase(it);
}
else
{
++it;
}
}
}
//--------------------------------------------------------------------------------------------------
void HttpRequestSystem::OnDestroy() noexcept
{
CancelAllRequests();
HttpRequest::Shutdown();
for (auto it = m_requests.begin(); it != m_requests.end(); ++it)
{
CS_SAFEDELETE(*it);
}
m_requests.clear();
m_requests.shrink_to_fit();
for(auto& curl : m_curls)
{
curl_easy_cleanup(curl.second);
}
curl_global_cleanup();
}
}
}
#endif
<|endoftext|> |
<commit_before>//
// Copyright (c) 2008-2014 the Urho3D project.
//
// 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 "Camera.h"
#include "CoreEvents.h"
#include "Engine.h"
#include "Font.h"
#include "Graphics.h"
#include "Input.h"
#include "Octree.h"
#include "Renderer.h"
#include "ResourceCache.h"
#include "Scene.h"
#include "Text.h"
#include "Urho2DSpriterAnimation.h"
#include "XAnimatedSprite2D.h"
#include "XAnimation2D.h"
#include "XAnimationSet2D.h"
#include "Zone.h"
#include "DebugNew.h"
static const char* animationNames[] =
{
"idle",
"run",
"attack",
"hit",
"dead",
"dead2",
"dead3",
};
DEFINE_APPLICATION_MAIN(Urho2DSpriterAnimation)
Urho2DSpriterAnimation::Urho2DSpriterAnimation(Context* context) :
Sample(context),
animationIndex_(0)
{
}
void Urho2DSpriterAnimation::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void Urho2DSpriterAnimation::CreateScene()
{
scene_ = new Scene(context_);
scene_->CreateComponent<Octree>();
// Create camera node
cameraNode_ = scene_->CreateChild("Camera");
// Set camera's position
cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));
Camera* camera = cameraNode_->CreateComponent<Camera>();
camera->SetOrthographic(true);
Graphics* graphics = GetSubsystem<Graphics>();
camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
ResourceCache* cache = GetSubsystem<ResourceCache>();
XAnimationSet2D* animationSet = cache->GetResource<XAnimationSet2D>("Urho2D/imp/imp.scml");
if (!animationSet)
return;
spriteNode_ = scene_->CreateChild("SpriterAnimation");
spriteNode_->SetPosition(Vector3(-1.4f, 2.0f, -1.0f));
XAnimatedSprite2D* animatedSprite = spriteNode_->CreateComponent<XAnimatedSprite2D>();
animatedSprite->SetAnimation(animationSet, animationNames[animationIndex_]);
}
void Urho2DSpriterAnimation::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use mouse click to play next animation,\n Use WASD keys to move, use PageUp PageDown keys to zoom.");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void Urho2DSpriterAnimation::SetupViewport()
{
Renderer* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void Urho2DSpriterAnimation::MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (GetSubsystem<UI>()->GetFocusElement())
return;
Input* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 4.0f;
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input->GetKeyDown('W'))
cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
if (input->GetKeyDown('S'))
cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
if (input->GetKeyDown('A'))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown('D'))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_PAGEUP))
{
Camera* camera = cameraNode_->GetComponent<Camera>();
camera->SetZoom(camera->GetZoom() * 1.01f);
}
if (input->GetKeyDown(KEY_PAGEDOWN))
{
Camera* camera = cameraNode_->GetComponent<Camera>();
camera->SetZoom(camera->GetZoom() * 0.99f);
}
}
void Urho2DSpriterAnimation::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, HANDLER(Urho2DSpriterAnimation, HandleUpdate));
SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(Urho2DSpriterAnimation, HandleMouseButtonDown));
// Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent(E_SCENEUPDATE);
}
void Urho2DSpriterAnimation::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
void Urho2DSpriterAnimation::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
{
XAnimatedSprite2D* animatedSprite = spriteNode_->GetComponent<XAnimatedSprite2D>();
animationIndex_ = (animationIndex_ + 1) % 7;
animatedSprite->SetAnimation(animationNames[animationIndex_]);
}
<commit_msg>Fixed text format.[ci skip]<commit_after>//
// Copyright (c) 2008-2014 the Urho3D project.
//
// 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 "Camera.h"
#include "CoreEvents.h"
#include "Engine.h"
#include "Font.h"
#include "Graphics.h"
#include "Input.h"
#include "Octree.h"
#include "Renderer.h"
#include "ResourceCache.h"
#include "Scene.h"
#include "Text.h"
#include "Urho2DSpriterAnimation.h"
#include "XAnimatedSprite2D.h"
#include "XAnimation2D.h"
#include "XAnimationSet2D.h"
#include "Zone.h"
#include "DebugNew.h"
static const char* animationNames[] =
{
"idle",
"run",
"attack",
"hit",
"dead",
"dead2",
"dead3",
};
DEFINE_APPLICATION_MAIN(Urho2DSpriterAnimation)
Urho2DSpriterAnimation::Urho2DSpriterAnimation(Context* context) :
Sample(context),
animationIndex_(0)
{
}
void Urho2DSpriterAnimation::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void Urho2DSpriterAnimation::CreateScene()
{
scene_ = new Scene(context_);
scene_->CreateComponent<Octree>();
// Create camera node
cameraNode_ = scene_->CreateChild("Camera");
// Set camera's position
cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));
Camera* camera = cameraNode_->CreateComponent<Camera>();
camera->SetOrthographic(true);
Graphics* graphics = GetSubsystem<Graphics>();
camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
ResourceCache* cache = GetSubsystem<ResourceCache>();
XAnimationSet2D* animationSet = cache->GetResource<XAnimationSet2D>("Urho2D/imp/imp.scml");
if (!animationSet)
return;
spriteNode_ = scene_->CreateChild("SpriterAnimation");
spriteNode_->SetPosition(Vector3(-1.4f, 2.0f, -1.0f));
XAnimatedSprite2D* animatedSprite = spriteNode_->CreateComponent<XAnimatedSprite2D>();
animatedSprite->SetAnimation(animationSet, animationNames[animationIndex_]);
}
void Urho2DSpriterAnimation::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use mouse click to play next animation, \nUse WASD keys to move, use PageUp PageDown keys to zoom.");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void Urho2DSpriterAnimation::SetupViewport()
{
Renderer* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void Urho2DSpriterAnimation::MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (GetSubsystem<UI>()->GetFocusElement())
return;
Input* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 4.0f;
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input->GetKeyDown('W'))
cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
if (input->GetKeyDown('S'))
cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
if (input->GetKeyDown('A'))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown('D'))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_PAGEUP))
{
Camera* camera = cameraNode_->GetComponent<Camera>();
camera->SetZoom(camera->GetZoom() * 1.01f);
}
if (input->GetKeyDown(KEY_PAGEDOWN))
{
Camera* camera = cameraNode_->GetComponent<Camera>();
camera->SetZoom(camera->GetZoom() * 0.99f);
}
}
void Urho2DSpriterAnimation::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, HANDLER(Urho2DSpriterAnimation, HandleUpdate));
SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(Urho2DSpriterAnimation, HandleMouseButtonDown));
// Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent(E_SCENEUPDATE);
}
void Urho2DSpriterAnimation::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
void Urho2DSpriterAnimation::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
{
XAnimatedSprite2D* animatedSprite = spriteNode_->GetComponent<XAnimatedSprite2D>();
animationIndex_ = (animationIndex_ + 1) % 7;
animatedSprite->SetAnimation(animationNames[animationIndex_]);
}
<|endoftext|> |
<commit_before>#include "sani/platform/graphics/graphics_precompiled.hpp"
#include "sani/platform/graphics/graphics_device.hpp"
#include "sani/graphics/renderables/renderable.hpp"
#include "sani/graphics/setups/render_setups.hpp"
#include "sani/resource/texture2d.hpp"
#include "sani/graphics/renderer.hpp"
namespace sani {
namespace graphics {
#define INITIAL_BUFFER_ELEMENTS_COUNT 32768
/*
RenderBatch class
Represents a part of the rendering process.
Can contain one or more elements that will be
rendered.
*/
class RenderBatch {
public:
// First vertex position.
uint32 verticesBegin;
// Last vertex position.
uint32 verticesEnd;
// First vertex index position.
uint32 indicesBegin;
// Last vertex index position.
uint32 indicesEnd;
// Element this batch can be used to render.
const RenderElementData* elementsData;
// Statee elements.
RenderState renderState;
VertexMode vertexMode;
RenderMode renderMode;
// TODO: add these
/*
Effect* effect;
Texture2D* texture;
*/
RenderBatch() : verticesBegin(0),
verticesEnd(0),
indicesBegin(0),
indicesEnd(0),
elementsData(nullptr) {
}
void resetBatch() {
verticesBegin = 0;
verticesEnd = 0;
indicesBegin = 0;
indicesEnd = 0;
elementsData = nullptr;
}
~RenderBatch() {
}
};
// For starters, reserve 128kb worth of vertex memory (32768 float32 elements).
// Keep the buffer usage as dynamic (memory as the limit).
Renderer::Renderer(GraphicsDevice& graphicsDevice) : graphicsDevice(graphicsDevice),
vertices(INITIAL_BUFFER_ELEMENTS_COUNT, BufferSizing::Dynamic),
indices(INITIAL_BUFFER_ELEMENTS_COUNT, BufferSizing::Dynamic),
verticesSize(INITIAL_BUFFER_ELEMENTS_COUNT),
indicesSize(INITIAL_BUFFER_ELEMENTS_COUNT),
renderBatch(nullptr),
renderBatchesCount(0),
renderSetup(nullptr),
vertexBuffer(0),
indexBuffer(0) {
renderBatches.resize(32);
}
void Renderer::generateRenderSetups() {
renderSetups = new RenderSetup*[RENDER_STATES_COUNT];
renderSetups[static_cast<uint32>(RenderState::Waiting)] = nullptr;
renderSetups[static_cast<uint32>(RenderState::Polygons)] = new PolygonRenderSetup(&graphicsDevice);
renderSetups[static_cast<uint32>(RenderState::TexturedPolygons)] = new TexturedPolygonRenderSetup(&graphicsDevice);
}
void Renderer::generateBuffers() {
graphicsDevice.generateBuffer(vertexBuffer);
graphicsDevice.bindBuffer(vertexBuffer, BufferType::ArrayBuffer);
graphicsDevice.generateBuffer(indexBuffer);
graphicsDevice.bindBuffer(indexBuffer, BufferType::ElementArrayBuffer);
graphicsDevice.setBufferData(BufferType::ArrayBuffer,
vertices.getSize() * sizeof(float32),
vertices.data(),
BufferUsage::Stream);
graphicsDevice.setBufferData(BufferType::ElementArrayBuffer,
indices.getSize() * sizeof(uint32),
indices.data(),
BufferUsage::Stream);
}
void Renderer::updateVertexBufferSize() {
// Rebind buffer if it's size has changed.
if (verticesSize != vertices.getSize()) {
graphicsDevice.bindBuffer(vertexBuffer, BufferType::ArrayBuffer);
graphicsDevice.setBufferData(BufferType::ArrayBuffer,
vertices.getSize() * sizeof(float32),
vertices.data(),
BufferUsage::Stream);
verticesSize = vertices.getSize();
}
}
void Renderer::updateIndexBufferSize() {
if (indicesSize != indices.getSize()) {
graphicsDevice.bindBuffer(indexBuffer, BufferType::ElementArrayBuffer);
graphicsDevice.setBufferData(BufferType::ElementArrayBuffer,
indices.getSize() * sizeof(uint32),
indices.data(),
BufferUsage::Stream);
indicesSize = indices.getSize();
}
}
void Renderer::applyVertexOffset() {
// No need to add offset.
if (renderBatchesCount <= 1) return;
const RenderBatch* last = &renderBatches[renderBatchesCount - 1];
// No need to add offset, same vertex elements count.
if (last->elementsData->vertexElements == renderBatch->elementsData->vertexElements) return;
// From less elements to more.
// Offset = vtxElemes - vetxElemsMod.
const uint32 vertexElementsCount = renderBatch->elementsData->vertexElements;
const uint32 vertexElementsModulo = vertices.getElementsCount() % vertexElementsCount;
const uint32 vertexElementsOffset = vertexElementsCount - vertexElementsModulo;
vertices.offset(vertexElementsOffset);
}
void Renderer::swapRenderSetup(const RenderState renderState) {
const uint32 index = static_cast<uint32>(renderState);
renderSetup = renderSetups[index];
}
void Renderer::initializeBatch(const RenderElementData* const renderElementData) {
renderBatch->elementsData = renderElementData;
/*
TODO: add texturing.
*/
renderBatch->indicesBegin = indices.getElementsCount();
renderBatch->indicesEnd = renderBatch->indicesBegin + renderElementData->indices;
renderBatch->renderState = RenderState::Polygons;
renderBatch->vertexMode = renderElementData->indices == 0 ? VertexMode::NoIndexing : VertexMode::Indexed;
renderBatch->renderMode = renderElementData->renderMode;
// Add possible vertex elements offset for this batch element.
applyVertexOffset();
const uint32 vertexElementsCount = vertices.getElementsCount();
const uint32 vertexOffset = vertexElementsCount > 0 ? 1 : 0;
renderBatch->verticesBegin = vertexElementsCount / renderElementData->vertexElements;
renderBatch->verticesEnd = renderBatch->verticesBegin;
}
void Renderer::swapBatch() {
renderBatch = &renderBatches[renderBatchesCount];
renderBatch->resetBatch();
renderBatchesCount++;
if (renderBatchesCount == renderBatches.size()) renderBatches.reserve(renderBatches.size() * 2);
}
void Renderer::applyToBatch(const RenderElementData* const renderElementData) {
// Add one to keep the indexes as zero based.
const uint32 verticesCount = (renderElementData->last + 1) - renderElementData->first;
renderBatch->verticesEnd += verticesCount;
renderBatch->indicesEnd += renderElementData->indices;
}
void Renderer::batchElement(const RenderElementData* const renderElementData) {
if (renderBatch->elementsData == nullptr) {
initializeBatch(renderElementData);
}
if (renderElementData->renderMode == RenderMode::TriangleFan || renderElementData->renderMode == RenderMode::LineLoop) {
swapBatch();
initializeBatch(renderElementData);
} else if (renderElementData->groupIdentifier != renderBatch->elementsData->groupIdentifier) {
// Check if we can batch this element to some recent batch.
// If we can't just create new batch.
//if (renderBatchesCount >= 1 && (renderBatchesCount < elementCounter)) {
// const uint32 batchesBegin = renderBatchesCount - elementCounter;
//
// uint32 i = batchesBegin;
// while (i < renderBatchesCount) {
// RenderBatch* const recentRenderBatch = &renderBatches[i];
// if (recentRenderBatch->elementsData->groupIdentifier == renderElementData->groupIdentifier) {
// RenderBatch* const temp = renderBatch;
// renderBatch = recentRenderBatch;
// applyToBatch(renderElementData);
// renderBatch = temp;
// return;
// }
// }
//} else {
// Can't batch to other batches, a new batch is required.
swapBatch();
initializeBatch(renderElementData);
/*}*/
}
applyToBatch(renderElementData);
}
void Renderer::copyVertexData(const RenderElementData* const renderElementData, const RenderData* const renderData) {
const uint32 elementVertexElementsCount = renderElementData->vertexElements;
const uint32 vertexElementOffset = renderElementData->offset;
const uint32 first = renderElementData->first;
const uint32 last = renderElementData->last + 1; // Add one to keep the index as zero-based.
const uint32 firstVertexElement = first * (elementVertexElementsCount + vertexElementOffset);
const uint32 lastVertexElement = last * (elementVertexElementsCount + vertexElementOffset);
const uint32 vertexElementsCount = lastVertexElement - firstVertexElement;
const uint32 verticesCount = last - first;
const float32* const vertexElementsData = reinterpret_cast<const float32* const>(renderData->vertices.data());
uint32 vertexElementPointer = firstVertexElement;
if (vertexElementOffset != 0) {
uint32 vertexElementPointer = firstVertexElement;
for (uint32 i = 0; i < verticesCount; i++) {
vertices.push(&vertexElementsData[vertexElementPointer], elementVertexElementsCount);
vertexElementPointer += elementVertexElementsCount + vertexElementOffset;
}
} else {
vertices.push(&vertexElementsData[firstVertexElement], vertexElementsCount);
}
}
void Renderer::copyIndexData(const RenderElementData* const renderElementData, const RenderData* const renderData) {
const uint32 indicesCount = renderElementData->indices;
const uint32* indicesData = reinterpret_cast<const uint32* const>(renderData->vertexIndices.data());
indices.push(indicesData, indicesCount);
}
void Renderer::flushRenderBatch(const RenderBatch* const renderBatch) {
if (renderSetup != nullptr) renderSetup->clear();
const RenderState renderState = renderBatch->renderState;
swapRenderSetup(renderState);
renderSetup->setVertexElementsCount(renderBatch->elementsData->vertexElements);
renderSetup->use();
const VertexMode vertexMode = renderBatch->vertexMode;
const RenderMode renderMode = renderBatch->renderMode;
if (vertexMode == VertexMode::NoIndexing) {
graphicsDevice.drawArrays(renderMode, renderBatch->verticesBegin, renderBatch->verticesEnd);
} else {
const uint32 indicesCount = renderBatch->indicesEnd - renderBatch->indicesBegin;
graphicsDevice.drawElements(renderMode, PrimitiveType::UInt, indicesCount, renderBatch->indicesBegin);
}
}
void Renderer::updateBufferDatas() {
updateVertexBufferSize();
updateIndexBufferSize();
graphicsDevice.bindBuffer(vertexBuffer, BufferType::ArrayBuffer);
graphicsDevice.setBufferSubData(BufferType::ArrayBuffer,
0,
vertices.getElementsCount() * sizeof(float32),
vertices.data());
graphicsDevice.bindBuffer(indexBuffer, BufferType::ElementArrayBuffer);
graphicsDevice.setBufferSubData(BufferType::ElementArrayBuffer,
0,
indices.getElementsCount() * sizeof(uint32),
indices.data());
}
bool Renderer::initialize() {
generateRenderSetups();
generateBuffers();
return graphicsDevice.hasErrors();
}
void Renderer::beginRendering(const math::Mat4f& transform) {
renderBatchesCount = 0;
renderBatch = nullptr;
vertices.resetBufferPointer();
indices.resetBufferPointer();
swapBatch();
}
void Renderer::render(const Renderable* const renderable) {
elementsCount = renderable->renderData.renderElementsCount;
for (elementCounter = 0; elementCounter < elementsCount; elementCounter++) {
const uint32 renderElementIndex = renderable->renderData.renderElementIndices[elementCounter];
const RenderElementData* const renderElementData = &renderable->renderData.renderElements[renderElementIndex];
batchElement(renderElementData);
copyVertexData(renderElementData, &renderable->renderData);
copyIndexData(renderElementData, &renderable->renderData);
}
}
void Renderer::endRendering() {
updateBufferDatas();
for (uint32 i = 0; i < renderBatchesCount; i++) flushRenderBatch(&renderBatches[i]);
}
Renderer::~Renderer() {
for (uint32 i = 0; i < RENDER_STATES_COUNT; i++) delete renderSetups[i];
delete[] renderSetups;
}
}
}<commit_msg>Return bab's moti<commit_after>#include "sani/platform/graphics/graphics_precompiled.hpp"
#include "sani/platform/graphics/graphics_device.hpp"
#include "sani/graphics/renderables/renderable.hpp"
#include "sani/graphics/setups/render_setups.hpp"
#include "sani/resource/texture2d.hpp"
#include "sani/graphics/renderer.hpp"
namespace sani {
namespace graphics {
#define INITIAL_BUFFER_ELEMENTS_COUNT 32768
/*
RenderBatch class
Represents a part of the rendering process.
Can contain one or more elements that will be
rendered.
*/
class RenderBatch {
public:
// First vertex position.
uint32 verticesBegin;
// Last vertex position.
uint32 verticesEnd;
// First vertex index position.
uint32 indicesBegin;
// Last vertex index position.
uint32 indicesEnd;
// Element this batch can be used to render.
const RenderElementData* elementsData;
// Statee elements.
RenderState renderState;
VertexMode vertexMode;
RenderMode renderMode;
// TODO: add these
/*
Effect* effect;
Texture2D* texture;
*/
RenderBatch() : verticesBegin(0),
verticesEnd(0),
indicesBegin(0),
indicesEnd(0),
elementsData(nullptr) {
}
void resetBatch() {
verticesBegin = 0;
verticesEnd = 0;
indicesBegin = 0;
indicesEnd = 0;
elementsData = nullptr;
}
~RenderBatch() {
}
};
// For starters, reserve 128kb worth of vertex memory (32768 float32 elements).
// Keep the buffer usage as dynamic (memory as the limit).
Renderer::Renderer(GraphicsDevice& graphicsDevice) : graphicsDevice(graphicsDevice),
vertices(INITIAL_BUFFER_ELEMENTS_COUNT, BufferSizing::Dynamic),
indices(INITIAL_BUFFER_ELEMENTS_COUNT, BufferSizing::Dynamic),
verticesSize(INITIAL_BUFFER_ELEMENTS_COUNT),
indicesSize(INITIAL_BUFFER_ELEMENTS_COUNT),
renderBatch(nullptr),
renderBatchesCount(0),
renderSetup(nullptr),
vertexBuffer(0),
indexBuffer(0) {
renderBatches.resize(32);
}
void Renderer::generateRenderSetups() {
renderSetups = new RenderSetup*[RENDER_STATES_COUNT];
renderSetups[static_cast<uint32>(RenderState::Waiting)] = nullptr;
renderSetups[static_cast<uint32>(RenderState::Polygons)] = new PolygonRenderSetup(&graphicsDevice);
renderSetups[static_cast<uint32>(RenderState::TexturedPolygons)] = new TexturedPolygonRenderSetup(&graphicsDevice);
}
void Renderer::generateBuffers() {
graphicsDevice.generateBuffer(vertexBuffer);
graphicsDevice.bindBuffer(vertexBuffer, BufferType::ArrayBuffer);
graphicsDevice.generateBuffer(indexBuffer);
graphicsDevice.bindBuffer(indexBuffer, BufferType::ElementArrayBuffer);
graphicsDevice.setBufferData(BufferType::ArrayBuffer,
vertices.getSize() * sizeof(float32),
vertices.data(),
BufferUsage::Stream);
graphicsDevice.setBufferData(BufferType::ElementArrayBuffer,
indices.getSize() * sizeof(uint32),
indices.data(),
BufferUsage::Stream);
}
void Renderer::updateVertexBufferSize() {
// Rebind buffer if it's size has changed.
if (verticesSize != vertices.getSize()) {
graphicsDevice.bindBuffer(vertexBuffer, BufferType::ArrayBuffer);
graphicsDevice.setBufferData(BufferType::ArrayBuffer,
vertices.getSize() * sizeof(float32),
vertices.data(),
BufferUsage::Stream);
verticesSize = vertices.getSize();
}
}
void Renderer::updateIndexBufferSize() {
if (indicesSize != indices.getSize()) {
graphicsDevice.bindBuffer(indexBuffer, BufferType::ElementArrayBuffer);
graphicsDevice.setBufferData(BufferType::ElementArrayBuffer,
indices.getSize() * sizeof(uint32),
indices.data(),
BufferUsage::Stream);
indicesSize = indices.getSize();
}
}
void Renderer::applyVertexOffset() {
// No need to add offset.
if (renderBatchesCount <= 1) return;
const RenderBatch* last = &renderBatches[renderBatchesCount - 1];
// No need to add offset, same vertex elements count.
if (last->elementsData->vertexElements == renderBatch->elementsData->vertexElements) return;
// From less elements to more.
// Offset = vtxElemes - vetxElemsMod.
const uint32 vertexElementsCount = renderBatch->elementsData->vertexElements;
const uint32 vertexElementsModulo = vertices.getElementsCount() % vertexElementsCount;
const uint32 vertexElementsOffset = vertexElementsCount - vertexElementsModulo;
vertices.offset(vertexElementsOffset);
}
void Renderer::swapRenderSetup(const RenderState renderState) {
const uint32 index = static_cast<uint32>(renderState);
renderSetup = renderSetups[index];
}
void Renderer::initializeBatch(const RenderElementData* const renderElementData) {
renderBatch->elementsData = renderElementData;
/*
TODO: add texturing.
*/
renderBatch->indicesBegin = indices.getElementsCount();
renderBatch->indicesEnd = renderBatch->indicesBegin + renderElementData->indices;
renderBatch->renderState = RenderState::Polygons;
renderBatch->vertexMode = renderElementData->indices == 0 ? VertexMode::NoIndexing : VertexMode::Indexed;
renderBatch->renderMode = renderElementData->renderMode;
// Add possible vertex elements offset for this batch element.
applyVertexOffset();
const uint32 vertexElementsCount = vertices.getElementsCount();
const uint32 vertexOffset = vertexElementsCount > 0 ? 1 : 0;
renderBatch->verticesBegin = vertexElementsCount / renderElementData->vertexElements;
renderBatch->verticesEnd = renderBatch->verticesBegin;
}
void Renderer::swapBatch() {
renderBatch = &renderBatches[renderBatchesCount];
renderBatch->resetBatch();
renderBatchesCount++;
if (renderBatchesCount == renderBatches.size()) renderBatches.reserve(renderBatches.size() * 2);
}
void Renderer::applyToBatch(const RenderElementData* const renderElementData) {
// Add one to keep the indexes as zero based.
const uint32 verticesCount = (renderElementData->last + 1) - renderElementData->first;
renderBatch->verticesEnd += verticesCount;
renderBatch->indicesEnd += renderElementData->indices;
}
void Renderer::batchElement(const RenderElementData* const renderElementData) {
if (renderBatch->elementsData == nullptr) {
initializeBatch(renderElementData);
}
if (renderElementData->renderMode == RenderMode::TriangleFan || renderElementData->renderMode == RenderMode::LineLoop) {
swapBatch();
initializeBatch(renderElementData);
} else if (renderElementData->groupIdentifier != renderBatch->elementsData->groupIdentifier) {
// Check if we can batch this element to some recent batch.
// If we can't just create new batch.
//if (renderBatchesCount >= 1 && (renderBatchesCount < elementCounter)) {
// const uint32 batchesBegin = renderBatchesCount - elementCounter;
//
// uint32 i = batchesBegin;
// while (i < renderBatchesCount) {
// RenderBatch* const recentRenderBatch = &renderBatches[i];
// if (recentRenderBatch->elementsData->groupIdentifier == renderElementData->groupIdentifier) {
// RenderBatch* const temp = renderBatch;
// renderBatch = recentRenderBatch;
// applyToBatch(renderElementData);
// renderBatch = temp;
// return;
// }
// }
//} else {
// Can't batch to other batches, a new batch is required.
swapBatch();
initializeBatch(renderElementData);
/*}*/
}
applyToBatch(renderElementData);
}
void Renderer::copyVertexData(const RenderElementData* const renderElementData, const RenderData* const renderData) {
const uint32 elementVertexElementsCount = renderElementData->vertexElements;
const uint32 vertexElementOffset = renderElementData->offset;
const uint32 first = renderElementData->first;
const uint32 last = renderElementData->last + 1; // Add one to keep the index as zero-based.
const uint32 firstVertexElement = first * (elementVertexElementsCount + vertexElementOffset);
const uint32 lastVertexElement = last * (elementVertexElementsCount + vertexElementOffset);
const uint32 vertexElementsCount = lastVertexElement - firstVertexElement;
const uint32 verticesCount = last - first;
const float32* const vertexElementsData = reinterpret_cast<const float32* const>(renderData->vertices.data());
uint32 vertexElementPointer = firstVertexElement;
if (vertexElementOffset != 0) {
uint32 vertexElementPointer = firstVertexElement;
for (uint32 i = 0; i < verticesCount; i++) {
vertices.push(&vertexElementsData[vertexElementPointer], elementVertexElementsCount);
vertexElementPointer += elementVertexElementsCount + vertexElementOffset;
}
} else {
vertices.push(&vertexElementsData[firstVertexElement], vertexElementsCount);
}
}
void Renderer::copyIndexData(const RenderElementData* const renderElementData, const RenderData* const renderData) {
const uint32 indicesCount = renderElementData->indices;
const uint32* indicesData = reinterpret_cast<const uint32* const>(renderData->vertexIndices.data());
indices.push(indicesData, indicesCount);
}
void Renderer::flushRenderBatch(const RenderBatch* const renderBatch) {
if (renderSetup != nullptr) renderSetup->clear();
const RenderState renderState = renderBatch->renderState;
swapRenderSetup(renderState);
renderSetup->setVertexElementsCount(renderBatch->elementsData->vertexElements);
renderSetup->use();
const VertexMode vertexMode = renderBatch->vertexMode;
const RenderMode renderMode = renderBatch->renderMode;
if (vertexMode == VertexMode::NoIndexing) {
graphicsDevice.drawArrays(renderMode, renderBatch->verticesBegin, renderBatch->verticesEnd - renderBatch->verticesBegin);
} else {
const uint32 indicesCount = renderBatch->indicesEnd - renderBatch->indicesBegin;
graphicsDevice.drawElements(renderMode, PrimitiveType::UInt, indicesCount, renderBatch->indicesBegin);
}
}
void Renderer::updateBufferDatas() {
updateVertexBufferSize();
updateIndexBufferSize();
graphicsDevice.bindBuffer(vertexBuffer, BufferType::ArrayBuffer);
graphicsDevice.setBufferSubData(BufferType::ArrayBuffer,
0,
vertices.getElementsCount() * sizeof(float32),
vertices.data());
graphicsDevice.bindBuffer(indexBuffer, BufferType::ElementArrayBuffer);
graphicsDevice.setBufferSubData(BufferType::ElementArrayBuffer,
0,
indices.getElementsCount() * sizeof(uint32),
indices.data());
}
bool Renderer::initialize() {
generateRenderSetups();
generateBuffers();
return graphicsDevice.hasErrors();
}
void Renderer::beginRendering(const math::Mat4f& transform) {
renderBatchesCount = 0;
renderBatch = nullptr;
vertices.resetBufferPointer();
indices.resetBufferPointer();
swapBatch();
}
void Renderer::render(const Renderable* const renderable) {
elementsCount = renderable->renderData.renderElementsCount;
for (elementCounter = 0; elementCounter < elementsCount; elementCounter++) {
const uint32 renderElementIndex = renderable->renderData.renderElementIndices[elementCounter];
const RenderElementData* const renderElementData = &renderable->renderData.renderElements[renderElementIndex];
batchElement(renderElementData);
copyVertexData(renderElementData, &renderable->renderData);
copyIndexData(renderElementData, &renderable->renderData);
}
}
void Renderer::endRendering() {
updateBufferDatas();
for (uint32 i = 0; i < renderBatchesCount; i++) flushRenderBatch(&renderBatches[i]);
}
Renderer::~Renderer() {
for (uint32 i = 0; i < RENDER_STATES_COUNT; i++) delete renderSetups[i];
delete[] renderSetups;
}
}
}<|endoftext|> |
<commit_before>// Copyright (c) 2014-2020 The Gridcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "main.h"
#include "gridcoin/backup.h"
#include "gridcoin/contract/contract.h"
#include "gridcoin/gridcoin.h"
#include "gridcoin/quorum.h"
#include "gridcoin/researcher.h"
#include "gridcoin/support/block_finder.h"
#include "gridcoin/tally.h"
#include "gridcoin/upgrade.h"
#include "init.h"
#include "scheduler.h"
#include "ui_interface.h"
using namespace GRC;
extern bool fExplorer;
extern unsigned int nScraperSleep;
extern unsigned int nActiveBeforeSB;
extern bool fScraperActive;
void Scraper(bool bSingleShot = false);
void ScraperSubscriber();
namespace {
//!
//! \brief Initialize the service that creates and validate superblocks.
//!
//! \param pindexBest Block index of the tip of the chain.
//!
void InitializeSuperblockQuorum(const CBlockIndex* pindexBest)
{
if (IsV9Enabled(pindexBest->nHeight)) {
LogPrintf("Gridcoin: Loading superblock cache...");
uiInterface.InitMessage(_("Loading superblock cache..."));
Quorum::LoadSuperblockIndex(pindexBest);
}
}
//!
//! \brief Initialize the service that tracks research rewards.
//!
//! \param pindexBest Block index of the tip of the chain.
//!
//! \return \c false if a problem occurs while loading the stored accrual state.
//!
bool InitializeResearchRewardAccounting(CBlockIndex* pindexBest)
{
LogPrintf("Gridcoin: initializing research reward accounting...");
uiInterface.InitMessage(_("Initializing research reward accounting..."));
const int64_t start_height = Params().GetConsensus().ResearchAgeHeight;
if (!Tally::Initialize(BlockFinder().FindByHeight(start_height))) {
return error("Failed to initialize tally.");
}
if (pindexBest->nVersion <= 10) {
LogPrint(BCLog::LogFlags::TALLY, "Gridcoin: loading network averages...");
uiInterface.InitMessage(_("Loading Network Averages..."));
Tally::LegacyRecount(Tally::FindLegacyTrigger(pindexBest));
}
return true;
}
//!
//! \brief Reload historical contract state from the blockchain.
//!
//! \param pindexBest Block index of the tip of the chain.
//!
void InitializeContracts(const CBlockIndex* pindexBest)
{
LogPrintf("Gridcoin: replaying contracts...");
uiInterface.InitMessage(_("Replaying contracts..."));
ReplayContracts(pindexBest);
}
//!
//! \brief Set up the user's CPID for participation in the research reward
//! protocol.
//!
void InitializeResearcherContext()
{
LogPrintf("Gridcoin: initializing local researcher context...");
uiInterface.InitMessage(_("Initializing local researcher context..."));
Researcher::Initialize();
if (!pwalletMain->IsLocked()) {
Researcher::Get()->ImportBeaconKeysFromConfig(pwalletMain);
}
}
//!
//! \brief Run the scraper thread.
//!
//! \param parg Unused.
//!
void ThreadScraper(void* parg)
{
LogPrint(BCLog::LogFlags::NOISY, "ThreadSraper starting");
try {
fScraperActive = true;
Scraper(false);
} catch (std::exception& e) {
fScraperActive = false;
PrintException(&e, "ThreadScraper()");
} catch(boost::thread_interrupted&) {
fScraperActive = false;
LogPrintf("ThreadScraper exited (interrupt)");
return;
} catch (...) {
fScraperActive = false;
PrintException(nullptr, "ThreadScraper()");
}
fScraperActive = false;
LogPrintf("ThreadScraper exited");
}
//!
//! \brief Run the scraper subscriber thread.
//!
//! \param parg Unused.
//!
void ThreadScraperSubscriber(void* parg)
{
LogPrint(BCLog::LogFlags::NOISY, "ThreadScraperSubscriber starting");
try {
ScraperSubscriber();
} catch (std::exception& e) {
PrintException(&e, "ThreadScraperSubscriber()");
} catch(boost::thread_interrupted&) {
LogPrintf("ThreadScraperSubscriber exited (interrupt)");
return;
} catch (...) {
PrintException(nullptr, "ThreadScraperSubscriber()");
}
LogPrintf("ThreadScraperSubscriber exited");
}
//!
//! \brief Configure and initialize the scraper system.
//!
//! \param threads Used to start the scraper housekeeping threads.
//!
void InitializeScraper(ThreadHandlerPtr threads)
{
// Default to 300 sec (5 min), clamp to 60 minimum, 600 maximum - converted to milliseconds.
nScraperSleep = std::min<int64_t>(std::max<int64_t>(GetArg("-scrapersleep", 300), 60), 600) * 1000;
// Default to 7200 sec (4 hrs), clamp to 300 minimum, 86400 maximum (meaning active all of the time).
nActiveBeforeSB = std::min<int64_t>(std::max<int64_t>(GetArg("-activebeforesb", 14400), 300), 86400);
// Run the scraper or subscriber housekeeping thread, but not both. The
// subscriber housekeeping thread checks if the flag for the scraper thread
// is true, and basically becomes a no-op, but it is silly to run it if the
// scraper thread is running. The scraper thread does all of the same
// housekeeping functions as the subscriber housekeeping thread.
//
// For example. gridcoinresearch(d) with no args will run the subscriber
// but not the scraper.
// gridcoinresearch(d) -scraper will run the scraper but not the subscriber.
if (GetBoolArg("-scraper", false)) {
LogPrintf("Gridcoin: scraper enabled");
if (!threads->createThread(ThreadScraper, nullptr, "ThreadScraper")) {
LogPrintf("ERROR: createThread(ThreadScraper) failed");
}
} else {
LogPrintf("Gridcoin: scraper disabled");
LogPrintf("Gridcoin: scraper subscriber housekeeping thread enabled");
if (!threads->createThread(ThreadScraperSubscriber, nullptr, "ScraperSubscriber")) {
LogPrintf("ERROR: createThread(ScraperSubscriber) failed");
}
}
}
//!
//! \brief Enable explorer functionality for the scraper if requested.
//!
void InitializeExplorerFeatures()
{
fExplorer = GetBoolArg("-scraper", false) && GetBoolArg("-explorer", false);
}
//!
//! \brief Set up the background job that creates backup files.
//!
//! \param scheduler Scheduler instance to register jobs with.
//!
void ScheduleBackups(CScheduler& scheduler)
{
if (!BackupsEnabled()) {
return;
}
// Run the backup job at a rate of 4x the configured backup interval
// in case the wallet becomes busy when the job runs. This job skips
// a cycle when it encounters lock contention or when a cycle occurs
// sooner than the requested interval:
//
scheduler.scheduleEvery(RunBackupJob, GetBackupInterval() * 1000 / 4);
// Run the backup job on start-up in case the wallet started after a
// long period of downtime. Some usage patterns may cause the wallet
// to start and shutdown frequently without producing a backup if we
// only create backups from the scheduler cycles. This is a no-op if
// the wallet contains a stored backup timestamp later than the next
// scheduled backup interval:
//
scheduler.scheduleFromNow(RunBackupJob, 60 * 1000);
}
//!
//! \brief Set up the background job that checks for new Gridcoin versions.
//!
//! \param scheduler Scheduler instance to register jobs with.
//!
void ScheduleUpdateChecks(CScheduler& scheduler)
{
if (fTestNet) {
LogPrintf("Gridcoin: update checks disabled for testnet");
return;
}
if (GetBoolArg("-disableupdatecheck", false)) {
LogPrintf("Gridcoin: update checks disabled by configuration");
return;
}
int64_t hours = GetArg("-updatecheckinterval", 5 * 24);
if (hours < 1) {
LogPrintf("ERROR: invalid -updatecheckinterval: %s. Using default...",
GetArg("-updatecheckinterval", ""));
hours = 24;
}
LogPrintf("Gridcoin: checking for updates every %" PRId64 " hours", hours);
scheduler.scheduleEvery([]{
g_UpdateChecker->CheckForLatestUpdate();
}, hours * 60 * 60 * 1000);
// Schedule a start-up check one minute from now:
scheduler.scheduleFromNow([]{
g_UpdateChecker->CheckForLatestUpdate();
}, 60 * 1000);
}
} // Anonymous namespace
// -----------------------------------------------------------------------------
// Global Variables
// -----------------------------------------------------------------------------
std::unique_ptr<Upgrade> g_UpdateChecker;
bool fSnapshotRequest = false;
// -----------------------------------------------------------------------------
// Functions
// -----------------------------------------------------------------------------
bool GRC::Initialize(ThreadHandlerPtr threads, CBlockIndex* pindexBest)
{
LogPrintf("Gridcoin: initializing...");
InitializeSuperblockQuorum(pindexBest);
if (!InitializeResearchRewardAccounting(pindexBest)) {
return false;
}
InitializeContracts(pindexBest);
InitializeResearcherContext();
InitializeScraper(threads);
InitializeExplorerFeatures();
return true;
}
void GRC::ScheduleBackgroundJobs(CScheduler& scheduler)
{
// Primitive, but this is what the scraper does in the scraper housekeeping
// loop. It checks to see if the logs need to be archived by default every
// 5 mins. Note that passing false to the archive function means that if we
// have not crossed over the day boundary, it does nothing, so this is a
// very inexpensive call. Also if -logarchivedaily is set to false, then
// this will be a no-op.
scheduler.scheduleEvery([]{
fs::path plogfile_out;
LogInstance().archive(false, plogfile_out);
}, 300 * 1000);
scheduler.scheduleEvery(Researcher::RunRenewBeaconJob, 4 * 60 * 60 * 1000);
ScheduleBackups(scheduler);
ScheduleUpdateChecks(scheduler);
}
<commit_msg>Reimplement block index sanity check as a background job<commit_after>// Copyright (c) 2014-2020 The Gridcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "main.h"
#include "gridcoin/backup.h"
#include "gridcoin/contract/contract.h"
#include "gridcoin/gridcoin.h"
#include "gridcoin/quorum.h"
#include "gridcoin/researcher.h"
#include "gridcoin/support/block_finder.h"
#include "gridcoin/tally.h"
#include "gridcoin/upgrade.h"
#include "init.h"
#include "scheduler.h"
#include "ui_interface.h"
using namespace GRC;
extern bool fExplorer;
extern unsigned int nScraperSleep;
extern unsigned int nActiveBeforeSB;
extern bool fScraperActive;
void Scraper(bool bSingleShot = false);
void ScraperSubscriber();
namespace {
//!
//! \brief Initialize the service that creates and validate superblocks.
//!
//! \param pindexBest Block index of the tip of the chain.
//!
void InitializeSuperblockQuorum(const CBlockIndex* pindexBest)
{
if (IsV9Enabled(pindexBest->nHeight)) {
LogPrintf("Gridcoin: Loading superblock cache...");
uiInterface.InitMessage(_("Loading superblock cache..."));
Quorum::LoadSuperblockIndex(pindexBest);
}
}
//!
//! \brief Initialize the service that tracks research rewards.
//!
//! \param pindexBest Block index of the tip of the chain.
//!
//! \return \c false if a problem occurs while loading the stored accrual state.
//!
bool InitializeResearchRewardAccounting(CBlockIndex* pindexBest)
{
LogPrintf("Gridcoin: initializing research reward accounting...");
uiInterface.InitMessage(_("Initializing research reward accounting..."));
const int64_t start_height = Params().GetConsensus().ResearchAgeHeight;
if (!Tally::Initialize(BlockFinder().FindByHeight(start_height))) {
return error("Failed to initialize tally.");
}
if (pindexBest->nVersion <= 10) {
LogPrint(BCLog::LogFlags::TALLY, "Gridcoin: loading network averages...");
uiInterface.InitMessage(_("Loading Network Averages..."));
Tally::LegacyRecount(Tally::FindLegacyTrigger(pindexBest));
}
return true;
}
//!
//! \brief Reload historical contract state from the blockchain.
//!
//! \param pindexBest Block index of the tip of the chain.
//!
void InitializeContracts(const CBlockIndex* pindexBest)
{
LogPrintf("Gridcoin: replaying contracts...");
uiInterface.InitMessage(_("Replaying contracts..."));
ReplayContracts(pindexBest);
}
//!
//! \brief Set up the user's CPID for participation in the research reward
//! protocol.
//!
void InitializeResearcherContext()
{
LogPrintf("Gridcoin: initializing local researcher context...");
uiInterface.InitMessage(_("Initializing local researcher context..."));
Researcher::Initialize();
if (!pwalletMain->IsLocked()) {
Researcher::Get()->ImportBeaconKeysFromConfig(pwalletMain);
}
}
//!
//! \brief Run the scraper thread.
//!
//! \param parg Unused.
//!
void ThreadScraper(void* parg)
{
LogPrint(BCLog::LogFlags::NOISY, "ThreadSraper starting");
try {
fScraperActive = true;
Scraper(false);
} catch (std::exception& e) {
fScraperActive = false;
PrintException(&e, "ThreadScraper()");
} catch(boost::thread_interrupted&) {
fScraperActive = false;
LogPrintf("ThreadScraper exited (interrupt)");
return;
} catch (...) {
fScraperActive = false;
PrintException(nullptr, "ThreadScraper()");
}
fScraperActive = false;
LogPrintf("ThreadScraper exited");
}
//!
//! \brief Run the scraper subscriber thread.
//!
//! \param parg Unused.
//!
void ThreadScraperSubscriber(void* parg)
{
LogPrint(BCLog::LogFlags::NOISY, "ThreadScraperSubscriber starting");
try {
ScraperSubscriber();
} catch (std::exception& e) {
PrintException(&e, "ThreadScraperSubscriber()");
} catch(boost::thread_interrupted&) {
LogPrintf("ThreadScraperSubscriber exited (interrupt)");
return;
} catch (...) {
PrintException(nullptr, "ThreadScraperSubscriber()");
}
LogPrintf("ThreadScraperSubscriber exited");
}
//!
//! \brief Configure and initialize the scraper system.
//!
//! \param threads Used to start the scraper housekeeping threads.
//!
void InitializeScraper(ThreadHandlerPtr threads)
{
// Default to 300 sec (5 min), clamp to 60 minimum, 600 maximum - converted to milliseconds.
nScraperSleep = std::min<int64_t>(std::max<int64_t>(GetArg("-scrapersleep", 300), 60), 600) * 1000;
// Default to 7200 sec (4 hrs), clamp to 300 minimum, 86400 maximum (meaning active all of the time).
nActiveBeforeSB = std::min<int64_t>(std::max<int64_t>(GetArg("-activebeforesb", 14400), 300), 86400);
// Run the scraper or subscriber housekeeping thread, but not both. The
// subscriber housekeeping thread checks if the flag for the scraper thread
// is true, and basically becomes a no-op, but it is silly to run it if the
// scraper thread is running. The scraper thread does all of the same
// housekeeping functions as the subscriber housekeeping thread.
//
// For example. gridcoinresearch(d) with no args will run the subscriber
// but not the scraper.
// gridcoinresearch(d) -scraper will run the scraper but not the subscriber.
if (GetBoolArg("-scraper", false)) {
LogPrintf("Gridcoin: scraper enabled");
if (!threads->createThread(ThreadScraper, nullptr, "ThreadScraper")) {
LogPrintf("ERROR: createThread(ThreadScraper) failed");
}
} else {
LogPrintf("Gridcoin: scraper disabled");
LogPrintf("Gridcoin: scraper subscriber housekeeping thread enabled");
if (!threads->createThread(ThreadScraperSubscriber, nullptr, "ScraperSubscriber")) {
LogPrintf("ERROR: createThread(ScraperSubscriber) failed");
}
}
}
//!
//! \brief Enable explorer functionality for the scraper if requested.
//!
void InitializeExplorerFeatures()
{
fExplorer = GetBoolArg("-scraper", false) && GetBoolArg("-explorer", false);
}
//!
//! \brief Check the block index for unusual entries.
//!
//! This runs a simple check on the entries in the block index to determine
//! whether the index contains invalid state caused by an unclean shutdown.
//! This condition was originally detected by an assertion in a routine for
//! stake modifier checksum verification. Because Gridcoin removed modifier
//! checksums and checkpoints, we reinstate that assertion here as a formal
//! inspection.
//!
//! This function checks that no block index entries contain a null pointer
//! to a previous block. The symptom may indicate a deeper problem that can
//! be resolved by tuning disk synchronization in LevelDB. Until then, this
//! heuristic has proven itself to be effective for identifying a corrupted
//! database.
//!
void CheckBlockIndexJob()
{
LogPrintf("Gridcoin: checking block index...");
bool corrupted = false;
if (pindexGenesisBlock) {
LOCK(cs_main);
for (const auto& index_pair : mapBlockIndex) {
const CBlockIndex* const pindex = index_pair.second;
if (!pindex || !(pindex->pprev || pindex == pindexGenesisBlock)) {
corrupted = true;
break;
}
}
}
if (!corrupted) {
LogPrintf("Gridcoin: block index is clean");
return;
}
// This prints a message to the log and stderr on headless:
uiInterface.ThreadSafeMessageBox(
_("WARNING: Blockchain data may be corrupt.\n\n"
"Gridcoin detected bad index entries. This may occur because of an "
"unexpected exit or power failure.\n\n"
"Please exit Gridcoin, open the data directory, and delete:\n"
" - the blk****.dat files\n"
" - the txleveldb folder\n\n"
"Your wallet will re-download the blockchain. Your balance may "
"appear incorrect until the synchronization finishes.\n" ),
"Gridcoin",
CClientUIInterface::OK | CClientUIInterface::MODAL);
}
//!
//! \brief Set up the background job that creates backup files.
//!
//! \param scheduler Scheduler instance to register jobs with.
//!
void ScheduleBackups(CScheduler& scheduler)
{
if (!BackupsEnabled()) {
return;
}
// Run the backup job at a rate of 4x the configured backup interval
// in case the wallet becomes busy when the job runs. This job skips
// a cycle when it encounters lock contention or when a cycle occurs
// sooner than the requested interval:
//
scheduler.scheduleEvery(RunBackupJob, GetBackupInterval() * 1000 / 4);
// Run the backup job on start-up in case the wallet started after a
// long period of downtime. Some usage patterns may cause the wallet
// to start and shutdown frequently without producing a backup if we
// only create backups from the scheduler cycles. This is a no-op if
// the wallet contains a stored backup timestamp later than the next
// scheduled backup interval:
//
scheduler.scheduleFromNow(RunBackupJob, 60 * 1000);
}
//!
//! \brief Set up the background job that checks for new Gridcoin versions.
//!
//! \param scheduler Scheduler instance to register jobs with.
//!
void ScheduleUpdateChecks(CScheduler& scheduler)
{
if (fTestNet) {
LogPrintf("Gridcoin: update checks disabled for testnet");
return;
}
if (GetBoolArg("-disableupdatecheck", false)) {
LogPrintf("Gridcoin: update checks disabled by configuration");
return;
}
int64_t hours = GetArg("-updatecheckinterval", 5 * 24);
if (hours < 1) {
LogPrintf("ERROR: invalid -updatecheckinterval: %s. Using default...",
GetArg("-updatecheckinterval", ""));
hours = 24;
}
LogPrintf("Gridcoin: checking for updates every %" PRId64 " hours", hours);
scheduler.scheduleEvery([]{
g_UpdateChecker->CheckForLatestUpdate();
}, hours * 60 * 60 * 1000);
// Schedule a start-up check one minute from now:
scheduler.scheduleFromNow([]{
g_UpdateChecker->CheckForLatestUpdate();
}, 60 * 1000);
}
} // Anonymous namespace
// -----------------------------------------------------------------------------
// Global Variables
// -----------------------------------------------------------------------------
std::unique_ptr<Upgrade> g_UpdateChecker;
bool fSnapshotRequest = false;
// -----------------------------------------------------------------------------
// Functions
// -----------------------------------------------------------------------------
bool GRC::Initialize(ThreadHandlerPtr threads, CBlockIndex* pindexBest)
{
LogPrintf("Gridcoin: initializing...");
InitializeSuperblockQuorum(pindexBest);
if (!InitializeResearchRewardAccounting(pindexBest)) {
return false;
}
InitializeContracts(pindexBest);
InitializeResearcherContext();
InitializeScraper(threads);
InitializeExplorerFeatures();
return true;
}
void GRC::ScheduleBackgroundJobs(CScheduler& scheduler)
{
scheduler.schedule(CheckBlockIndexJob);
// Primitive, but this is what the scraper does in the scraper housekeeping
// loop. It checks to see if the logs need to be archived by default every
// 5 mins. Note that passing false to the archive function means that if we
// have not crossed over the day boundary, it does nothing, so this is a
// very inexpensive call. Also if -logarchivedaily is set to false, then
// this will be a no-op.
scheduler.scheduleEvery([]{
fs::path plogfile_out;
LogInstance().archive(false, plogfile_out);
}, 300 * 1000);
scheduler.scheduleEvery(Researcher::RunRenewBeaconJob, 4 * 60 * 60 * 1000);
ScheduleBackups(scheduler);
ScheduleUpdateChecks(scheduler);
}
<|endoftext|> |
<commit_before>//
// $Id$
//
#include "AVGOGLSurface.h"
#include "AVGPlayer.h"
#include "AVGLogger.h"
#include "AVGException.h"
#include "AVGPoint.h"
#include "OGLHelper.h"
#include <paintlib/plstdpch.h>
#include <paintlib/plrect.h>
#include <paintlib/planybmp.h>
#include <paintlib/plsubbmp.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
#include <sstream>
using namespace std;
int AVGOGLSurface::s_TextureMode = 0;
int AVGOGLSurface::s_MaxTexSize = 0;
AVGOGLSurface::AVGOGLSurface()
: m_bBound(false),
m_pBmp(0),
m_pSubBmp(0)
{
// Do an NVIDIA texture support query if it hasn't happened already.
getTextureMode();
}
AVGOGLSurface::~AVGOGLSurface()
{
discardBmp();
if (m_bBound) {
unbind();
}
}
void AVGOGLSurface::create(int Width, int Height, int bpp,
bool bHasAlpha)
{
discardBmp();
if (m_bBound) {
unbind();
}
m_pBmp = new PLAnyBmp;
dynamic_cast<PLAnyBmp*>(m_pBmp)->Create(Width, Height, bpp,
bHasAlpha, false);
m_pSubBmp = 0;
}
PLBmpBase* AVGOGLSurface::getBmp()
{
return m_pBmp;
}
void AVGOGLSurface::createFromBits(int Width, int Height, int bpp,
bool bHasAlpha, PLBYTE* pBits, int Stride)
{
if (m_bBound &&
(!m_pSubBmp ||
Width != m_pBmp->GetWidth() || Height != m_pBmp->GetHeight() ||
bpp != m_pBmp->GetBitsPerPixel() || bHasAlpha != m_pBmp->HasAlpha()))
{
unbind();
}
if (!m_pSubBmp) {
discardBmp();
m_pBmp = new PLSubBmp;
m_pSubBmp = dynamic_cast<PLSubBmp*>(m_pBmp);
}
m_pSubBmp->Create(Width, Height, bpp, bHasAlpha, pBits, Stride);
}
void AVGOGLSurface::discardBmp()
{
if (m_pBmp) {
delete m_pBmp;
m_pBmp = 0;
}
}
int nextpow2(int n) {
double d = ::log(n)/::log(2);
return int(pow(2, ceil(d)));
}
string getGlModeString(int Mode)
{
switch (Mode) {
case GL_ALPHA:
return "GL_ALPHA";
case GL_RGB:
return "GL_RGB";
case GL_RGBA:
return "GL_RGBA";
case GL_BGR:
return "GL_BGR";
case GL_BGRA:
return "GL_BGRA";
default:
return "UNKNOWN";
}
}
void AVGOGLSurface::bind()
{
if (m_bBound) {
rebind();
} else {
int DestMode = getDestMode();
int SrcMode = getSrcMode();
int Width = m_pBmp->GetWidth();
int Height = m_pBmp->GetHeight();
m_Tiles.clear();
vector<TextureTile> v;
if (Width > s_MaxTexSize || Height > s_MaxTexSize) {
m_TileSize = PLPoint(s_MaxTexSize/2, s_MaxTexSize/2);
} else {
if (getTextureMode() == GL_TEXTURE_2D) {
if ((Width > 256 && nextpow2(Width) > Width*1.3) ||
(Height > 256 && nextpow2(Height) > Height*1.3))
{
m_TileSize = PLPoint(nextpow2(Width)/2, nextpow2(Height)/2);
} else {
m_TileSize = PLPoint(nextpow2(Width), nextpow2(Height));
}
} else {
m_TileSize = PLPoint(Width, Height);
}
}
int NumHorizTextures = int(ceil(float(Width)/m_TileSize.x));
int NumVertTextures = int(ceil(float(Height)/m_TileSize.y));
glPixelStorei(GL_UNPACK_ROW_LENGTH, Width);
for (int y=0; y<NumVertTextures; y++) {
m_Tiles.push_back(v);
for (int x=0; x<NumHorizTextures; x++) {
PLPoint CurSize = m_TileSize;
if (y == NumVertTextures-1) {
CurSize.y = Height-y*m_TileSize.y;
}
if (x == NumHorizTextures-1) {
CurSize.x = Width-x*m_TileSize.x;
}
PLRect CurExtent(x*m_TileSize.x, y*m_TileSize.y,
x*m_TileSize.x+CurSize.x, y*m_TileSize.y+CurSize.y);
TextureTile Tile;
Tile.m_Extent = CurExtent;
Tile.m_TexWidth = CurSize.x;
Tile.m_TexHeight = CurSize.y;
if (getTextureMode() == GL_TEXTURE_2D) {
Tile.m_TexWidth = nextpow2(CurSize.x);
Tile.m_TexHeight = nextpow2(CurSize.y);
}
glGenTextures(1, &Tile.m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bindOneTexture: glGenTextures()");
m_Tiles[y].push_back(Tile);
glBindTexture(s_TextureMode, Tile.m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bindOneTexture: glBindTexture()");
glTexParameteri(s_TextureMode,
GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(s_TextureMode,
GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(s_TextureMode, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(s_TextureMode, GL_TEXTURE_WRAP_T, GL_CLAMP);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bind: glTexParameteri()");
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bind: glPixelStorei()");
glTexImage2D(s_TextureMode, 0,
DestMode, Tile.m_TexWidth, Tile.m_TexHeight, 0,
SrcMode, GL_UNSIGNED_BYTE, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bind: glTexImage2D()");
PLBYTE * pStartPos =
m_pBmp->GetLineArray()[Tile.m_Extent.tl.y]
+ Tile.m_Extent.tl.x*m_pBmp->GetBitsPerPixel()/8;
glTexSubImage2D(s_TextureMode, 0, 0, 0,
Tile.m_Extent.Width(), Tile.m_Extent.Height(),
SrcMode, GL_UNSIGNED_BYTE, pStartPos);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bind: glTexSubImage2D()");
}
}
m_bBound = true;
}
}
void AVGOGLSurface::unbind()
{
if (m_bBound) {
for (int y=0; y<m_Tiles.size(); y++) {
for (int x=0; x<m_Tiles[y].size(); x++) {
glDeleteTextures(1, &m_Tiles[y][x].m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::unbind: glDeleteTextures()");
}
}
m_Tiles.clear();
}
m_bBound = false;
}
void AVGOGLSurface::rebind()
{
for (int y=0; y<m_Tiles.size(); y++) {
for (int x=0; x<m_Tiles[y].size(); x++) {
glBindTexture(s_TextureMode, m_Tiles[y][x].m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::rebind: glBindTexture()");
TextureTile Tile = m_Tiles[y][x];
PLBYTE * pStartPos =
m_pBmp->GetLineArray()[Tile.m_Extent.tl.y]
+ Tile.m_Extent.tl.x*m_pBmp->GetBitsPerPixel()/8;
glTexSubImage2D(s_TextureMode, 0, 0, 0,
Tile.m_Extent.Width(), Tile.m_Extent.Height(),
getSrcMode(), GL_UNSIGNED_BYTE, pStartPos);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::rebind: glTexSubImage2D()");
}
}
}
void AVGOGLSurface::blt(const AVGDRect* pDestRect, double opacity,
double angle, const AVGDPoint& pivot)
{
bltTexture(pDestRect, angle, pivot);
}
int AVGOGLSurface::getTextureMode()
{
if (s_TextureMode == 0) {
// TODO: Change to GL_TEXTURE_RECTANGLE_EXT so we don't depend on
// proprietary NVidia stuff
if (!queryOGLExtension("GL_NV_texture_rectangle")) {
s_TextureMode = GL_TEXTURE_RECTANGLE_NV;
AVG_TRACE(AVGPlayer::DEBUG_CONFIG,
"Using NVidia texture rectangle extension.");
} else {
s_TextureMode = GL_TEXTURE_2D;
AVG_TRACE(AVGPlayer::DEBUG_CONFIG,
"Using power of 2 textures.");
}
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &s_MaxTexSize);
AVG_TRACE(AVGPlayer::DEBUG_CONFIG,
"Max. texture size is " << s_MaxTexSize);
}
return s_TextureMode;
}
void AVGOGLSurface::bltTexture(const AVGDRect* pDestRect,
double angle, const AVGDPoint& pivot)
{
AVGDPoint center(pDestRect->tl.x+pivot.x,
pDestRect->tl.y+pivot.y);
glPushMatrix();
glTranslated(center.x, center.y, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "bltTexture: glTranslated");
glRotated(angle, 0, 0, 1);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "bltTexture: glRotated");
glTranslated(-center.x, -center.y, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "bltTexture: glTranslated");
for (int y=0; y<m_Tiles.size(); y++) {
for (int x=0; x<m_Tiles[y].size(); x++) {
TextureTile& CurTile = m_Tiles[y][x];
AVGDRect TileDestRect;
TileDestRect.tl.x = pDestRect->tl.x+
(float(pDestRect->Width())*m_TileSize.x*x)
/ m_pBmp->GetWidth();
TileDestRect.tl.y = pDestRect->tl.y+
(float(pDestRect->Height())*m_TileSize.y*y)
/ m_pBmp->GetHeight();
TileDestRect.br.x = TileDestRect.tl.x+
(float(pDestRect->Width())*CurTile.m_Extent.Width())
/ m_pBmp->GetWidth();
TileDestRect.br.y = TileDestRect.tl.y+
(float(pDestRect->Height())*CurTile.m_Extent.Height())
/ m_pBmp->GetHeight();
bltTile(CurTile, TileDestRect);
}
}
AVG_TRACE(AVGPlayer::DEBUG_BLTS, "(" << pDestRect->tl.x << ", "
<< pDestRect->tl.y << ")" << ", width:" << pDestRect->Width()
<< ", height: " << pDestRect->Height());
glPopMatrix();
}
int AVGOGLSurface::bltTile(const TextureTile& Tile,
const AVGDRect& DestRect)
{
double TexWidth;
double TexHeight;
if (getTextureMode() == GL_TEXTURE_2D) {
TexWidth = double(Tile.m_Extent.Width())/Tile.m_TexWidth;
TexHeight = double(Tile.m_Extent.Height())/Tile.m_TexHeight;
} else {
TexWidth = Tile.m_TexWidth;
TexHeight = Tile.m_TexHeight;
}
glBindTexture(s_TextureMode, Tile.m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGSDLDisplayEngine::blta8: glBindTexture()");
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0);
glVertex3d (DestRect.tl.x, DestRect.tl.y, 0.0);
glTexCoord2d(TexWidth, 0.0);
glVertex3d (DestRect.br.x, DestRect.tl.y, 0.0);
glTexCoord2d(TexWidth, TexHeight);
glVertex3d (DestRect.br.x, DestRect.br.y, 0.0);
glTexCoord2d(0.0, TexHeight);
glVertex3d (DestRect.tl.x, DestRect.br.y, 0.0);
glEnd();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGSDLDisplayEngine::bltTexture: glEnd()");
}
int AVGOGLSurface::getDestMode()
{
int bpp = m_pBmp->GetBitsPerPixel();
switch (bpp) {
case 8:
return GL_ALPHA;
break;
case 24:
return GL_RGB;
break;
case 32:
if (m_pBmp->HasAlpha()) {
return GL_RGBA;
} else {
return GL_RGB;
}
break;
default:
AVG_TRACE(AVGPlayer::DEBUG_ERROR, "Unsupported bpp " <<
bpp << " in AVGOGLSurface::bind()");
}
}
int AVGOGLSurface::getSrcMode()
{
switch (m_pBmp->GetBitsPerPixel()) {
case 8:
return GL_ALPHA;
case 24:
return GL_RGB;
case 32:
return GL_RGBA;
default:
AVG_TRACE(AVGPlayer::DEBUG_ERROR, "Unsupported bpp " <<
m_pBmp->GetBitsPerPixel() <<
" in AVGOGLSurface::getSrcMode()");
}
}
<commit_msg>oops.<commit_after>//
// $Id$
//
#include "AVGOGLSurface.h"
#include "AVGPlayer.h"
#include "AVGLogger.h"
#include "AVGException.h"
#include "AVGPoint.h"
#include "OGLHelper.h"
#include <paintlib/plstdpch.h>
#include <paintlib/plrect.h>
#include <paintlib/planybmp.h>
#include <paintlib/plsubbmp.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
#include <sstream>
using namespace std;
int AVGOGLSurface::s_TextureMode = 0;
int AVGOGLSurface::s_MaxTexSize = 0;
AVGOGLSurface::AVGOGLSurface()
: m_bBound(false),
m_pBmp(0),
m_pSubBmp(0)
{
// Do an NVIDIA texture support query if it hasn't happened already.
getTextureMode();
}
AVGOGLSurface::~AVGOGLSurface()
{
discardBmp();
if (m_bBound) {
unbind();
}
}
void AVGOGLSurface::create(int Width, int Height, int bpp,
bool bHasAlpha)
{
discardBmp();
if (m_bBound) {
unbind();
}
m_pBmp = new PLAnyBmp;
dynamic_cast<PLAnyBmp*>(m_pBmp)->Create(Width, Height, bpp,
bHasAlpha, false);
m_pSubBmp = 0;
}
PLBmpBase* AVGOGLSurface::getBmp()
{
return m_pBmp;
}
void AVGOGLSurface::createFromBits(int Width, int Height, int bpp,
bool bHasAlpha, PLBYTE* pBits, int Stride)
{
if (m_bBound &&
(!m_pSubBmp ||
Width != m_pBmp->GetWidth() || Height != m_pBmp->GetHeight() ||
bpp != m_pBmp->GetBitsPerPixel() || bHasAlpha != m_pBmp->HasAlpha()))
{
unbind();
}
if (!m_pSubBmp) {
discardBmp();
m_pBmp = new PLSubBmp;
m_pSubBmp = dynamic_cast<PLSubBmp*>(m_pBmp);
}
m_pSubBmp->Create(Width, Height, bpp, bHasAlpha, pBits, Stride);
}
void AVGOGLSurface::discardBmp()
{
if (m_pBmp) {
delete m_pBmp;
m_pBmp = 0;
}
}
int nextpow2(int n) {
double d = ::log(n)/::log(2);
return int(pow(2, ceil(d)));
}
string getGlModeString(int Mode)
{
switch (Mode) {
case GL_ALPHA:
return "GL_ALPHA";
case GL_RGB:
return "GL_RGB";
case GL_RGBA:
return "GL_RGBA";
case GL_BGR:
return "GL_BGR";
case GL_BGRA:
return "GL_BGRA";
default:
return "UNKNOWN";
}
}
void AVGOGLSurface::bind()
{
if (m_bBound) {
rebind();
} else {
int DestMode = getDestMode();
int SrcMode = getSrcMode();
int Width = m_pBmp->GetWidth();
int Height = m_pBmp->GetHeight();
m_Tiles.clear();
vector<TextureTile> v;
if (Width > s_MaxTexSize || Height > s_MaxTexSize) {
m_TileSize = PLPoint(s_MaxTexSize/2, s_MaxTexSize/2);
} else {
if (getTextureMode() == GL_TEXTURE_2D) {
if ((Width > 256 && nextpow2(Width) > Width*1.3) ||
(Height > 256 && nextpow2(Height) > Height*1.3))
{
m_TileSize = PLPoint(nextpow2(Width)/2, nextpow2(Height)/2);
} else {
m_TileSize = PLPoint(nextpow2(Width), nextpow2(Height));
}
} else {
m_TileSize = PLPoint(Width, Height);
}
}
int NumHorizTextures = int(ceil(float(Width)/m_TileSize.x));
int NumVertTextures = int(ceil(float(Height)/m_TileSize.y));
glPixelStorei(GL_UNPACK_ROW_LENGTH, Width);
for (int y=0; y<NumVertTextures; y++) {
m_Tiles.push_back(v);
for (int x=0; x<NumHorizTextures; x++) {
PLPoint CurSize = m_TileSize;
if (y == NumVertTextures-1) {
CurSize.y = Height-y*m_TileSize.y;
}
if (x == NumHorizTextures-1) {
CurSize.x = Width-x*m_TileSize.x;
}
PLRect CurExtent(x*m_TileSize.x, y*m_TileSize.y,
x*m_TileSize.x+CurSize.x, y*m_TileSize.y+CurSize.y);
TextureTile Tile;
Tile.m_Extent = CurExtent;
Tile.m_TexWidth = CurSize.x;
Tile.m_TexHeight = CurSize.y;
if (getTextureMode() == GL_TEXTURE_2D) {
Tile.m_TexWidth = nextpow2(CurSize.x);
Tile.m_TexHeight = nextpow2(CurSize.y);
}
glGenTextures(1, &Tile.m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bindOneTexture: glGenTextures()");
m_Tiles[y].push_back(Tile);
glBindTexture(s_TextureMode, Tile.m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bindOneTexture: glBindTexture()");
glTexParameteri(s_TextureMode,
GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(s_TextureMode,
GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(s_TextureMode, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(s_TextureMode, GL_TEXTURE_WRAP_T, GL_CLAMP);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bind: glTexParameteri()");
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bind: glPixelStorei()");
glTexImage2D(s_TextureMode, 0,
DestMode, Tile.m_TexWidth, Tile.m_TexHeight, 0,
SrcMode, GL_UNSIGNED_BYTE, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bind: glTexImage2D()");
PLBYTE * pStartPos =
m_pBmp->GetLineArray()[Tile.m_Extent.tl.y]
+ Tile.m_Extent.tl.x*m_pBmp->GetBitsPerPixel()/8;
glTexSubImage2D(s_TextureMode, 0, 0, 0,
Tile.m_Extent.Width(), Tile.m_Extent.Height(),
SrcMode, GL_UNSIGNED_BYTE, pStartPos);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::bind: glTexSubImage2D()");
}
}
m_bBound = true;
}
}
void AVGOGLSurface::unbind()
{
if (m_bBound) {
for (int y=0; y<m_Tiles.size(); y++) {
for (int x=0; x<m_Tiles[y].size(); x++) {
glDeleteTextures(1, &m_Tiles[y][x].m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::unbind: glDeleteTextures()");
}
}
m_Tiles.clear();
}
m_bBound = false;
}
void AVGOGLSurface::rebind()
{
for (int y=0; y<m_Tiles.size(); y++) {
for (int x=0; x<m_Tiles[y].size(); x++) {
glBindTexture(s_TextureMode, m_Tiles[y][x].m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::rebind: glBindTexture()");
TextureTile Tile = m_Tiles[y][x];
PLBYTE * pStartPos =
m_pBmp->GetLineArray()[Tile.m_Extent.tl.y]
+ Tile.m_Extent.tl.x*m_pBmp->GetBitsPerPixel()/8;
glTexSubImage2D(s_TextureMode, 0, 0, 0,
Tile.m_Extent.Width(), Tile.m_Extent.Height(),
getSrcMode(), GL_UNSIGNED_BYTE, pStartPos);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGOGLSurface::rebind: glTexSubImage2D()");
}
}
}
void AVGOGLSurface::blt(const AVGDRect* pDestRect, double opacity,
double angle, const AVGDPoint& pivot)
{
bltTexture(pDestRect, angle, pivot);
}
int AVGOGLSurface::getTextureMode()
{
if (s_TextureMode == 0) {
// TODO: Change to GL_TEXTURE_RECTANGLE_EXT so we don't depend on
// proprietary NVidia stuff
if (queryOGLExtension("GL_NV_texture_rectangle")) {
s_TextureMode = GL_TEXTURE_RECTANGLE_NV;
AVG_TRACE(AVGPlayer::DEBUG_CONFIG,
"Using NVidia texture rectangle extension.");
} else {
s_TextureMode = GL_TEXTURE_2D;
AVG_TRACE(AVGPlayer::DEBUG_CONFIG,
"Using power of 2 textures.");
}
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &s_MaxTexSize);
AVG_TRACE(AVGPlayer::DEBUG_CONFIG,
"Max. texture size is " << s_MaxTexSize);
}
return s_TextureMode;
}
void AVGOGLSurface::bltTexture(const AVGDRect* pDestRect,
double angle, const AVGDPoint& pivot)
{
AVGDPoint center(pDestRect->tl.x+pivot.x,
pDestRect->tl.y+pivot.y);
glPushMatrix();
glTranslated(center.x, center.y, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "bltTexture: glTranslated");
glRotated(angle, 0, 0, 1);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "bltTexture: glRotated");
glTranslated(-center.x, -center.y, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "bltTexture: glTranslated");
for (int y=0; y<m_Tiles.size(); y++) {
for (int x=0; x<m_Tiles[y].size(); x++) {
TextureTile& CurTile = m_Tiles[y][x];
AVGDRect TileDestRect;
TileDestRect.tl.x = pDestRect->tl.x+
(float(pDestRect->Width())*m_TileSize.x*x)
/ m_pBmp->GetWidth();
TileDestRect.tl.y = pDestRect->tl.y+
(float(pDestRect->Height())*m_TileSize.y*y)
/ m_pBmp->GetHeight();
TileDestRect.br.x = TileDestRect.tl.x+
(float(pDestRect->Width())*CurTile.m_Extent.Width())
/ m_pBmp->GetWidth();
TileDestRect.br.y = TileDestRect.tl.y+
(float(pDestRect->Height())*CurTile.m_Extent.Height())
/ m_pBmp->GetHeight();
bltTile(CurTile, TileDestRect);
}
}
AVG_TRACE(AVGPlayer::DEBUG_BLTS, "(" << pDestRect->tl.x << ", "
<< pDestRect->tl.y << ")" << ", width:" << pDestRect->Width()
<< ", height: " << pDestRect->Height());
glPopMatrix();
}
int AVGOGLSurface::bltTile(const TextureTile& Tile,
const AVGDRect& DestRect)
{
double TexWidth;
double TexHeight;
if (getTextureMode() == GL_TEXTURE_2D) {
TexWidth = double(Tile.m_Extent.Width())/Tile.m_TexWidth;
TexHeight = double(Tile.m_Extent.Height())/Tile.m_TexHeight;
} else {
TexWidth = Tile.m_TexWidth;
TexHeight = Tile.m_TexHeight;
}
glBindTexture(s_TextureMode, Tile.m_TexID);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGSDLDisplayEngine::blta8: glBindTexture()");
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0);
glVertex3d (DestRect.tl.x, DestRect.tl.y, 0.0);
glTexCoord2d(TexWidth, 0.0);
glVertex3d (DestRect.br.x, DestRect.tl.y, 0.0);
glTexCoord2d(TexWidth, TexHeight);
glVertex3d (DestRect.br.x, DestRect.br.y, 0.0);
glTexCoord2d(0.0, TexHeight);
glVertex3d (DestRect.tl.x, DestRect.br.y, 0.0);
glEnd();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"AVGSDLDisplayEngine::bltTexture: glEnd()");
}
int AVGOGLSurface::getDestMode()
{
int bpp = m_pBmp->GetBitsPerPixel();
switch (bpp) {
case 8:
return GL_ALPHA;
break;
case 24:
return GL_RGB;
break;
case 32:
if (m_pBmp->HasAlpha()) {
return GL_RGBA;
} else {
return GL_RGB;
}
break;
default:
AVG_TRACE(AVGPlayer::DEBUG_ERROR, "Unsupported bpp " <<
bpp << " in AVGOGLSurface::bind()");
}
}
int AVGOGLSurface::getSrcMode()
{
switch (m_pBmp->GetBitsPerPixel()) {
case 8:
return GL_ALPHA;
case 24:
return GL_RGB;
case 32:
return GL_RGBA;
default:
AVG_TRACE(AVGPlayer::DEBUG_ERROR, "Unsupported bpp " <<
m_pBmp->GetBitsPerPixel() <<
" in AVGOGLSurface::getSrcMode()");
}
}
<|endoftext|> |
<commit_before>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <[email protected]>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include "AbstractImage.h"
#include <Utility/Assert.h>
namespace Magnum {
std::size_t AbstractImage::pixelSize(Format format, Type type) {
std::size_t size = 0;
switch(type) {
case Type::UnsignedByte:
#ifndef MAGNUM_TARGET_GLES2
case Type::Byte:
#endif
size = 1; break;
case Type::UnsignedShort:
#ifndef MAGNUM_TARGET_GLES2
case Type::Short:
#endif
case Type::HalfFloat:
size = 2; break;
case Type::UnsignedInt:
#ifndef MAGNUM_TARGET_GLES2
case Type::Int:
#endif
case Type::Float:
size = 4; break;
#ifndef MAGNUM_TARGET_GLES
case Type::UnsignedByte332:
case Type::UnsignedByte233Rev:
return 1;
#endif
case Type::UnsignedShort565:
#ifndef MAGNUM_TARGET_GLES
case Type::UnsignedShort565Rev:
#endif
case Type::UnsignedShort4444:
case Type::UnsignedShort4444Rev:
case Type::UnsignedShort5551:
case Type::UnsignedShort1555Rev:
return 2;
#ifndef MAGNUM_TARGET_GLES
case Type::UnsignedInt8888:
case Type::UnsignedInt8888Rev:
case Type::UnsignedInt1010102:
#endif
case Type::UnsignedInt2101010Rev:
#ifndef MAGNUM_TARGET_GLES2
case Type::UnsignedInt10F11F11FRev:
case Type::UnsignedInt5999Rev:
#endif
case Type::UnsignedInt248:
return 4;
#ifndef MAGNUM_TARGET_GLES2
case Type::Float32UnsignedInt248Rev:
return 8;
#endif
}
switch(format) {
case Format::Red:
#ifndef MAGNUM_TARGET_GLES2
case Format::RedInteger:
#endif
#ifndef MAGNUM_TARGET_GLES
case Format::Green:
case Format::Blue:
case Format::GreenInteger:
case Format::BlueInteger:
#endif
return 1*size;
case Format::RG:
#ifndef MAGNUM_TARGET_GLES2
case Format::RGInteger:
#endif
return 2*size;
case Format::RGB:
#ifndef MAGNUM_TARGET_GLES2
case Format::RGBInteger:
#endif
#ifndef MAGNUM_TARGET_GLES
case Format::BGR:
case Format::BGRInteger:
#endif
return 3*size;
case Format::RGBA:
#ifndef MAGNUM_TARGET_GLES2
case Format::RGBAInteger:
#endif
case Format::BGRA:
#ifndef MAGNUM_TARGET_GLES2
case Format::BGRAInteger:
#endif
return 4*size;
/* Handled above */
case Format::DepthComponent:
case Format::StencilIndex:
case Format::DepthStencil:
CORRADE_INTERNAL_ASSERT(false);
}
return 0;
}
}
<commit_msg>Assert when improper pixel type is passed to AbstractImage::pixelSize().<commit_after>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <[email protected]>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include "AbstractImage.h"
#include <Utility/Assert.h>
namespace Magnum {
std::size_t AbstractImage::pixelSize(Format format, Type type) {
std::size_t size = 0;
switch(type) {
case Type::UnsignedByte:
#ifndef MAGNUM_TARGET_GLES2
case Type::Byte:
#endif
size = 1; break;
case Type::UnsignedShort:
#ifndef MAGNUM_TARGET_GLES2
case Type::Short:
#endif
case Type::HalfFloat:
size = 2; break;
case Type::UnsignedInt:
#ifndef MAGNUM_TARGET_GLES2
case Type::Int:
#endif
case Type::Float:
size = 4; break;
#ifndef MAGNUM_TARGET_GLES
case Type::UnsignedByte332:
case Type::UnsignedByte233Rev:
return 1;
#endif
case Type::UnsignedShort565:
#ifndef MAGNUM_TARGET_GLES
case Type::UnsignedShort565Rev:
#endif
case Type::UnsignedShort4444:
case Type::UnsignedShort4444Rev:
case Type::UnsignedShort5551:
case Type::UnsignedShort1555Rev:
return 2;
#ifndef MAGNUM_TARGET_GLES
case Type::UnsignedInt8888:
case Type::UnsignedInt8888Rev:
case Type::UnsignedInt1010102:
#endif
case Type::UnsignedInt2101010Rev:
#ifndef MAGNUM_TARGET_GLES2
case Type::UnsignedInt10F11F11FRev:
case Type::UnsignedInt5999Rev:
#endif
case Type::UnsignedInt248:
return 4;
#ifndef MAGNUM_TARGET_GLES2
case Type::Float32UnsignedInt248Rev:
return 8;
#endif
}
switch(format) {
case Format::Red:
#ifndef MAGNUM_TARGET_GLES2
case Format::RedInteger:
#endif
#ifndef MAGNUM_TARGET_GLES
case Format::Green:
case Format::Blue:
case Format::GreenInteger:
case Format::BlueInteger:
#endif
return 1*size;
case Format::RG:
#ifndef MAGNUM_TARGET_GLES2
case Format::RGInteger:
#endif
return 2*size;
case Format::RGB:
#ifndef MAGNUM_TARGET_GLES2
case Format::RGBInteger:
#endif
#ifndef MAGNUM_TARGET_GLES
case Format::BGR:
case Format::BGRInteger:
#endif
return 3*size;
case Format::RGBA:
#ifndef MAGNUM_TARGET_GLES2
case Format::RGBAInteger:
#endif
case Format::BGRA:
#ifndef MAGNUM_TARGET_GLES2
case Format::BGRAInteger:
#endif
return 4*size;
/* Handled above */
case Format::DepthComponent:
case Format::StencilIndex:
case Format::DepthStencil:
CORRADE_INTERNAL_ASSERT(false);
}
CORRADE_INTERNAL_ASSERT(false);
return 0;
}
}
<|endoftext|> |
<commit_before>/*
* AbstractState.cpp
*
* Created on: 21 Dec 2013
* Author: jowr
*/
#include "math.h"
#include "AbstractState.h"
#include "Backends/REFPROP/REFPROPBackend.h"
#include "Backends/Helmholtz/HelmholtzEOSBackend.h"
#include "Backends/Incompressible/IncompressibleBackend.h"
#include "Backends/Helmholtz/Fluids/FluidLibrary.h"
namespace CoolProp {
AbstractState * AbstractState::factory(const std::string &backend, const std::string &fluid_string)
{
static std::string HEOS_string = "HEOS";
if (!backend.compare("HEOS"))
{
if (fluid_string.find('&') == std::string::npos){
return new HelmholtzEOSBackend(&get_fluid(fluid_string));
}
else{
// Split at the '&'
std::vector<std::string> components = strsplit(fluid_string,'&');
return new HelmholtzEOSMixtureBackend(components);
}
}
else if (!backend.compare("REFPROP"))
{
if (fluid_string.find('&') == std::string::npos){
return new REFPROPBackend(fluid_string);
}
else{
// Split at the '&'
std::vector<std::string> components = strsplit(fluid_string,'&');
return new REFPROPMixtureBackend(components);
}
}
else if (!backend.compare("INCOMP"))
{
return new IncompressibleBackend(fluid_string);
}
else if (!backend.compare("BRINE"))
{
throw ValueError("BRINE backend not yet implemented");
}
else if (!backend.compare("TREND"))
{
throw ValueError("TREND backend not yet implemented");
}
else if (!backend.compare("?"))
{
std::size_t idel = fluid_string.find("::");
// Backend has not been specified, and we have to figure out what the backend is by parsing the string
if (idel == std::string::npos) // No '::' found, no backend specified, try HEOS, otherwise a failure
{
// Figure out what backend to use
return factory(HEOS_string, fluid_string);
}
else
{
// Split string at the '::' into two std::string, call again
return factory(std::string(fluid_string.begin(), fluid_string.begin() + idel), std::string(fluid_string.begin()+idel+2, fluid_string.end()));
}
}
else
{
throw ValueError(format("Invalid backend name [%s] to factory function",backend.c_str()));
}
}
bool AbstractState::clear() {
// Reset all instances of CachedElement and overwrite
// the internal double values with -_HUGE
this->_fluid_type = FLUID_TYPE_UNDEFINED;
this->_phase = iphase_unknown;
this->_forceSinglePhase = false;
this->_forceTwoPhase = false;
this->_R = _HUGE;
/// Ancillary curve values
this->_rhoLanc.clear();
this->_rhoVanc.clear();
this->_pVanc.clear();
this->_pLanc.clear();
this->_TVanc.clear();
this->_TLanc.clear();
this->_critical.T = -_HUGE;
this->_critical.hmolar = -_HUGE;
this->_critical.p = -_HUGE;
this->_critical.rhomolar = -_HUGE;
this->_critical.smolar = -_HUGE;
this->_reducing.T = -_HUGE;
this->_reducing.hmolar = -_HUGE;
this->_reducing.p = -_HUGE;
this->_reducing.rhomolar = -_HUGE;
this->_reducing.smolar = -_HUGE;
/// Bulk values
this->_rhomolar = -_HUGE;
this->_T = -_HUGE;
this->_p = -_HUGE;
this->_Q = -_HUGE;
this->_tau.clear();
this->_delta.clear();
this->_umolar.clear();
this->_cpmolar.clear();
this->_cvmolar.clear();
this->_speed_sound.clear();
this->_hmolar.clear();
this->_smolar.clear();
this->_logp.clear();
this->_logrhomolar.clear();
///// Smoothing values
//this->rhospline = -_HUGE;
//this->dsplinedp = -_HUGE;
//this->dsplinedh = -_HUGE;
/// Cached low-level elements for in-place calculation of other properties
this->_alpha0.clear();
this->_dalpha0_dTau.clear();
this->_dalpha0_dDelta.clear();
this->_d2alpha0_dTau2.clear();
this->_d2alpha0_dDelta_dTau.clear();
this->_d2alpha0_dDelta2.clear();
this->_d3alpha0_dTau3.clear();
this->_d3alpha0_dDelta_dTau2.clear();
this->_d3alpha0_dDelta2_dTau.clear();
this->_d3alpha0_dDelta3.clear();
this->_alphar.clear();
this->_dalphar_dTau.clear();
this->_dalphar_dDelta.clear();
this->_d2alphar_dTau2.clear();
this->_d2alphar_dDelta_dTau.clear();
this->_d2alphar_dDelta2.clear();
this->_d3alphar_dTau3.clear();
this->_d3alphar_dDelta_dTau2.clear();
this->_d3alphar_dDelta2_dTau.clear();
this->_d3alphar_dDelta3.clear();
this->_dalphar_dDelta_lim.clear();
this->_d2alphar_dDelta2_lim.clear();
this->_d2alphar_dDelta_dTau_lim.clear();
this->_d3alphar_dDelta2_dTau_lim.clear();
return true;
}
double AbstractState::keyed_output(int key)
{
switch (key)
{
case iQ:
return Q();
case iT:
return T();
case iP:
return p();
case iDmolar:
return rhomolar();
case iDmass:
return rhomass();
case iHmolar:
return hmolar();
case iHmass:
return hmass();
case iSmolar:
return smolar();
case iSmass:
return smass();
case iUmolar:
return umolar();
case iUmass:
return umass();
case iCvmolar:
return cvmolar();
case iCvmass:
return cvmass();
case iCpmolar:
return cpmolar();
case iCpmass:
return cpmass();
case imolar_mass:
return molar_mass();
case iT_reducing:
return get_reducing().T;
case irhomolar_reducing:
return get_reducing().rhomolar;
case ispeed_sound:
return speed_sound();
//case iT_critical:
// return get_critical().T;
//case irhomolar_critical:
// return get_critical().rhomolar; // TODO
case ialpha0:
return alpha0();
case idalpha0_ddelta_consttau:
return dalpha0_dDelta();
case idalpha0_dtau_constdelta:
return dalpha0_dTau();
case iBvirial:
return Bvirial();
case idBvirial_dT:
return dBvirial_dT();
case iCvirial:
return Cvirial();
case idCvirial_dT:
return dCvirial_dT();
case iisothermal_compressibility:
return isothermal_compressibility();
case iviscosity:
return viscosity();
case iconductivity:
return conductivity();
default:
throw ValueError(format("This input [%d: \"%s\"] is not valid for keyed_output",key,get_parameter_information(key,"short").c_str()));
}
}
double AbstractState::tau(void){
if (!_tau) _tau = calc_reciprocal_reduced_temperature();
return _tau;
}
double AbstractState::delta(void){
if (!_delta) _delta = calc_reduced_density();
return _delta;
}
double AbstractState::Tmax(void){
return calc_Tmax();
}
double AbstractState::Ttriple(void){
return calc_Ttriple();
}
double AbstractState::pmax(void){
return calc_pmax();
}
double AbstractState::T_critical(void){
return calc_T_critical();
}
double AbstractState::p_critical(void){
return calc_p_critical();
}
double AbstractState::rhomolar_critical(void){
return calc_rhomolar_critical();
}
double AbstractState::hmolar(void){
if (!_hmolar) _hmolar = calc_hmolar();
return _hmolar;
}
double AbstractState::smolar(void){
if (!_smolar) _smolar = calc_smolar();
return _smolar;
}
double AbstractState::umolar(void){
if (!_umolar) _umolar = calc_umolar();
return _umolar;
}
double AbstractState::cpmolar(void){
if (!_cpmolar) _cpmolar = calc_cpmolar();
return _cpmolar;
}
double AbstractState::cvmolar(void){
if (!_cvmolar) _cvmolar = calc_cvmolar();
return _cvmolar;
}
double AbstractState::speed_sound(void){
if (!_speed_sound) _speed_sound = calc_speed_sound();
return _speed_sound;
}
double AbstractState::viscosity(void){
if (!_viscosity) _viscosity = calc_viscosity();
return _viscosity;
}
double AbstractState::conductivity(void){
if (!_conductivity) _conductivity = calc_conductivity();
return _conductivity;
}
double AbstractState::surface_tension(void){
if (!_surface_tension) _surface_tension = calc_surface_tension();
return _surface_tension;
}
double AbstractState::molar_mass(void){
if (!_molar_mass) _molar_mass = calc_molar_mass();
return _molar_mass;
}
double AbstractState::gas_constant(void){
if (!_gas_constant) _gas_constant = calc_gas_constant();
return _gas_constant;
}
double AbstractState::fugacity_coefficient(int i){
// TODO: Cache the fug. coeff for each component
return calc_fugacity_coefficient(i);
}
void AbstractState::build_phase_envelope(const std::string &type)
{
calc_phase_envelope(type);
}
double AbstractState::isothermal_compressibility(void){
return 1.0/_rhomolar*first_partial_deriv(iDmolar, iP, iT);
}
double AbstractState::isobaric_expansion_coefficient(void){
return -1.0/pow(_rhomolar,2)*first_partial_deriv(iDmolar, iT, iP);
}
double AbstractState::Bvirial(void){ return calc_Bvirial(); }
double AbstractState::Cvirial(void){ return calc_Cvirial(); }
double AbstractState::dBvirial_dT(void){ return calc_dBvirial_dT(); }
double AbstractState::dCvirial_dT(void){ return calc_dCvirial_dT(); }
// // ----------------------------------------
// // Smoothing functions for density
// // ----------------------------------------
// /// A smoothed version of the derivative using a spline curve in the region of x=0 to x=xend
// virtual double AbstractState::drhodh_constp_smoothed(double xend);
// /// A smoothed version of the derivative using a spline curve in the region of x=0 to x=xend
// virtual double AbstractState::drhodp_consth_smoothed(double xend);
// /// Density corresponding to the smoothed derivatives in the region of x=0 to x=xend
// virtual void AbstractState::rho_smoothed(double xend, double *rho_spline, double *dsplinedh, double *dsplinedp);
} /* namespace CoolProp */
#ifdef ENABLE_CATCH
#include "catch.hpp"
TEST_CASE("Check AbstractState","[AbstractState]")
{
SECTION("bad backend")
{
CHECK_THROWS(std::tr1::shared_ptr<CoolProp::AbstractState> Water(CoolProp::AbstractState::factory("DEFINITELY_A_BAD_BACKEND", "Water")));
}
}
#endif
<commit_msg>Removed std::tr1 from AbstractState<commit_after>/*
* AbstractState.cpp
*
* Created on: 21 Dec 2013
* Author: jowr
*/
#include "math.h"
#include "AbstractState.h"
#include "Backends/REFPROP/REFPROPBackend.h"
#include "Backends/Helmholtz/HelmholtzEOSBackend.h"
#include "Backends/Incompressible/IncompressibleBackend.h"
#include "Backends/Helmholtz/Fluids/FluidLibrary.h"
namespace CoolProp {
AbstractState * AbstractState::factory(const std::string &backend, const std::string &fluid_string)
{
static std::string HEOS_string = "HEOS";
if (!backend.compare("HEOS"))
{
if (fluid_string.find('&') == std::string::npos){
return new HelmholtzEOSBackend(&get_fluid(fluid_string));
}
else{
// Split at the '&'
std::vector<std::string> components = strsplit(fluid_string,'&');
return new HelmholtzEOSMixtureBackend(components);
}
}
else if (!backend.compare("REFPROP"))
{
if (fluid_string.find('&') == std::string::npos){
return new REFPROPBackend(fluid_string);
}
else{
// Split at the '&'
std::vector<std::string> components = strsplit(fluid_string,'&');
return new REFPROPMixtureBackend(components);
}
}
else if (!backend.compare("INCOMP"))
{
return new IncompressibleBackend(fluid_string);
}
else if (!backend.compare("BRINE"))
{
throw ValueError("BRINE backend not yet implemented");
}
else if (!backend.compare("TREND"))
{
throw ValueError("TREND backend not yet implemented");
}
else if (!backend.compare("?"))
{
std::size_t idel = fluid_string.find("::");
// Backend has not been specified, and we have to figure out what the backend is by parsing the string
if (idel == std::string::npos) // No '::' found, no backend specified, try HEOS, otherwise a failure
{
// Figure out what backend to use
return factory(HEOS_string, fluid_string);
}
else
{
// Split string at the '::' into two std::string, call again
return factory(std::string(fluid_string.begin(), fluid_string.begin() + idel), std::string(fluid_string.begin()+idel+2, fluid_string.end()));
}
}
else
{
throw ValueError(format("Invalid backend name [%s] to factory function",backend.c_str()));
}
}
bool AbstractState::clear() {
// Reset all instances of CachedElement and overwrite
// the internal double values with -_HUGE
this->_fluid_type = FLUID_TYPE_UNDEFINED;
this->_phase = iphase_unknown;
this->_forceSinglePhase = false;
this->_forceTwoPhase = false;
this->_R = _HUGE;
/// Ancillary curve values
this->_rhoLanc.clear();
this->_rhoVanc.clear();
this->_pVanc.clear();
this->_pLanc.clear();
this->_TVanc.clear();
this->_TLanc.clear();
this->_critical.T = -_HUGE;
this->_critical.hmolar = -_HUGE;
this->_critical.p = -_HUGE;
this->_critical.rhomolar = -_HUGE;
this->_critical.smolar = -_HUGE;
this->_reducing.T = -_HUGE;
this->_reducing.hmolar = -_HUGE;
this->_reducing.p = -_HUGE;
this->_reducing.rhomolar = -_HUGE;
this->_reducing.smolar = -_HUGE;
/// Bulk values
this->_rhomolar = -_HUGE;
this->_T = -_HUGE;
this->_p = -_HUGE;
this->_Q = -_HUGE;
this->_tau.clear();
this->_delta.clear();
this->_umolar.clear();
this->_cpmolar.clear();
this->_cvmolar.clear();
this->_speed_sound.clear();
this->_hmolar.clear();
this->_smolar.clear();
this->_logp.clear();
this->_logrhomolar.clear();
///// Smoothing values
//this->rhospline = -_HUGE;
//this->dsplinedp = -_HUGE;
//this->dsplinedh = -_HUGE;
/// Cached low-level elements for in-place calculation of other properties
this->_alpha0.clear();
this->_dalpha0_dTau.clear();
this->_dalpha0_dDelta.clear();
this->_d2alpha0_dTau2.clear();
this->_d2alpha0_dDelta_dTau.clear();
this->_d2alpha0_dDelta2.clear();
this->_d3alpha0_dTau3.clear();
this->_d3alpha0_dDelta_dTau2.clear();
this->_d3alpha0_dDelta2_dTau.clear();
this->_d3alpha0_dDelta3.clear();
this->_alphar.clear();
this->_dalphar_dTau.clear();
this->_dalphar_dDelta.clear();
this->_d2alphar_dTau2.clear();
this->_d2alphar_dDelta_dTau.clear();
this->_d2alphar_dDelta2.clear();
this->_d3alphar_dTau3.clear();
this->_d3alphar_dDelta_dTau2.clear();
this->_d3alphar_dDelta2_dTau.clear();
this->_d3alphar_dDelta3.clear();
this->_dalphar_dDelta_lim.clear();
this->_d2alphar_dDelta2_lim.clear();
this->_d2alphar_dDelta_dTau_lim.clear();
this->_d3alphar_dDelta2_dTau_lim.clear();
return true;
}
double AbstractState::keyed_output(int key)
{
switch (key)
{
case iQ:
return Q();
case iT:
return T();
case iP:
return p();
case iDmolar:
return rhomolar();
case iDmass:
return rhomass();
case iHmolar:
return hmolar();
case iHmass:
return hmass();
case iSmolar:
return smolar();
case iSmass:
return smass();
case iUmolar:
return umolar();
case iUmass:
return umass();
case iCvmolar:
return cvmolar();
case iCvmass:
return cvmass();
case iCpmolar:
return cpmolar();
case iCpmass:
return cpmass();
case imolar_mass:
return molar_mass();
case iT_reducing:
return get_reducing().T;
case irhomolar_reducing:
return get_reducing().rhomolar;
case ispeed_sound:
return speed_sound();
//case iT_critical:
// return get_critical().T;
//case irhomolar_critical:
// return get_critical().rhomolar; // TODO
case ialpha0:
return alpha0();
case idalpha0_ddelta_consttau:
return dalpha0_dDelta();
case idalpha0_dtau_constdelta:
return dalpha0_dTau();
case iBvirial:
return Bvirial();
case idBvirial_dT:
return dBvirial_dT();
case iCvirial:
return Cvirial();
case idCvirial_dT:
return dCvirial_dT();
case iisothermal_compressibility:
return isothermal_compressibility();
case iviscosity:
return viscosity();
case iconductivity:
return conductivity();
default:
throw ValueError(format("This input [%d: \"%s\"] is not valid for keyed_output",key,get_parameter_information(key,"short").c_str()));
}
}
double AbstractState::tau(void){
if (!_tau) _tau = calc_reciprocal_reduced_temperature();
return _tau;
}
double AbstractState::delta(void){
if (!_delta) _delta = calc_reduced_density();
return _delta;
}
double AbstractState::Tmax(void){
return calc_Tmax();
}
double AbstractState::Ttriple(void){
return calc_Ttriple();
}
double AbstractState::pmax(void){
return calc_pmax();
}
double AbstractState::T_critical(void){
return calc_T_critical();
}
double AbstractState::p_critical(void){
return calc_p_critical();
}
double AbstractState::rhomolar_critical(void){
return calc_rhomolar_critical();
}
double AbstractState::hmolar(void){
if (!_hmolar) _hmolar = calc_hmolar();
return _hmolar;
}
double AbstractState::smolar(void){
if (!_smolar) _smolar = calc_smolar();
return _smolar;
}
double AbstractState::umolar(void){
if (!_umolar) _umolar = calc_umolar();
return _umolar;
}
double AbstractState::cpmolar(void){
if (!_cpmolar) _cpmolar = calc_cpmolar();
return _cpmolar;
}
double AbstractState::cvmolar(void){
if (!_cvmolar) _cvmolar = calc_cvmolar();
return _cvmolar;
}
double AbstractState::speed_sound(void){
if (!_speed_sound) _speed_sound = calc_speed_sound();
return _speed_sound;
}
double AbstractState::viscosity(void){
if (!_viscosity) _viscosity = calc_viscosity();
return _viscosity;
}
double AbstractState::conductivity(void){
if (!_conductivity) _conductivity = calc_conductivity();
return _conductivity;
}
double AbstractState::surface_tension(void){
if (!_surface_tension) _surface_tension = calc_surface_tension();
return _surface_tension;
}
double AbstractState::molar_mass(void){
if (!_molar_mass) _molar_mass = calc_molar_mass();
return _molar_mass;
}
double AbstractState::gas_constant(void){
if (!_gas_constant) _gas_constant = calc_gas_constant();
return _gas_constant;
}
double AbstractState::fugacity_coefficient(int i){
// TODO: Cache the fug. coeff for each component
return calc_fugacity_coefficient(i);
}
void AbstractState::build_phase_envelope(const std::string &type)
{
calc_phase_envelope(type);
}
double AbstractState::isothermal_compressibility(void){
return 1.0/_rhomolar*first_partial_deriv(iDmolar, iP, iT);
}
double AbstractState::isobaric_expansion_coefficient(void){
return -1.0/pow(_rhomolar,2)*first_partial_deriv(iDmolar, iT, iP);
}
double AbstractState::Bvirial(void){ return calc_Bvirial(); }
double AbstractState::Cvirial(void){ return calc_Cvirial(); }
double AbstractState::dBvirial_dT(void){ return calc_dBvirial_dT(); }
double AbstractState::dCvirial_dT(void){ return calc_dCvirial_dT(); }
// // ----------------------------------------
// // Smoothing functions for density
// // ----------------------------------------
// /// A smoothed version of the derivative using a spline curve in the region of x=0 to x=xend
// virtual double AbstractState::drhodh_constp_smoothed(double xend);
// /// A smoothed version of the derivative using a spline curve in the region of x=0 to x=xend
// virtual double AbstractState::drhodp_consth_smoothed(double xend);
// /// Density corresponding to the smoothed derivatives in the region of x=0 to x=xend
// virtual void AbstractState::rho_smoothed(double xend, double *rho_spline, double *dsplinedh, double *dsplinedp);
} /* namespace CoolProp */
#ifdef ENABLE_CATCH
#include "catch.hpp"
TEST_CASE("Check AbstractState","[AbstractState]")
{
SECTION("bad backend")
{
CHECK_THROWS(shared_ptr<CoolProp::AbstractState> Water(CoolProp::AbstractState::factory("DEFINITELY_A_BAD_BACKEND", "Water")));
}
}
#endif
<|endoftext|> |
<commit_before>//===- lib/Linker/LinkLibraries.cpp - Link LLVM libraries -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencerand is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains routines to handle finding libraries and linking them in.
//
//===----------------------------------------------------------------------===//
#include "llvm/Linker.h"
#include "llvm/Module.h"
using namespace llvm;
/// LinkInLibrary - links one library into the HeadModule
bool
Linker::LinkInLibrary(const std::string& Lib)
{
// Determine where this library lives.
sys::Path Pathname = FindLib(Lib);
if (Pathname.isEmpty())
return warning("Cannot find library '" + Lib + "'");
// If its an archive, try to link it in
if (Pathname.isArchive()) {
if (LinkInArchive(Pathname)) {
return error("Cannot link archive '" + Pathname.toString() + "'");
}
} else {
return warning("Supposed library '" + Lib + "' isn't a library.");
}
return false;
}
/// LinkLibraries - takes the specified library files and links them into the
/// main bytecode object file.
///
/// Inputs:
/// Libraries - The list of libraries to link into the module.
///
/// Return value:
/// FALSE - No error.
/// TRUE - Error.
///
bool
Linker::LinkInLibraries(const std::vector<std::string> &Libraries) {
// Process the set of libraries we've been provided
for (unsigned i = 0; i < Libraries.size(); ++i) {
if (LinkInLibrary(Libraries[i]))
return true;
}
// At this point we have processed all the libraries provided to us. Since
// we have an aggregated module at this point, the dependent libraries in
// that module should also be aggregated with duplicates eliminated. This is
// now the time to process the dependent libraries to resolve any remaining
// symbols.
const Module::LibraryListType& DepLibs = Composite->getLibraries();
for (Module::LibraryListType::const_iterator I = DepLibs.begin(),
E = DepLibs.end(); I != E; ++I) {
if (LinkInLibrary(*I))
return true;
}
return false;
}
<commit_msg>Add missing space in a comment.<commit_after>//===- lib/Linker/LinkLibraries.cpp - Link LLVM libraries -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains routines to handle finding libraries and linking them in.
//
//===----------------------------------------------------------------------===//
#include "llvm/Linker.h"
#include "llvm/Module.h"
using namespace llvm;
/// LinkInLibrary - links one library into the HeadModule
bool
Linker::LinkInLibrary(const std::string& Lib)
{
// Determine where this library lives.
sys::Path Pathname = FindLib(Lib);
if (Pathname.isEmpty())
return warning("Cannot find library '" + Lib + "'");
// If its an archive, try to link it in
if (Pathname.isArchive()) {
if (LinkInArchive(Pathname)) {
return error("Cannot link archive '" + Pathname.toString() + "'");
}
} else {
return warning("Supposed library '" + Lib + "' isn't a library.");
}
return false;
}
/// LinkLibraries - takes the specified library files and links them into the
/// main bytecode object file.
///
/// Inputs:
/// Libraries - The list of libraries to link into the module.
///
/// Return value:
/// FALSE - No error.
/// TRUE - Error.
///
bool
Linker::LinkInLibraries(const std::vector<std::string> &Libraries) {
// Process the set of libraries we've been provided
for (unsigned i = 0; i < Libraries.size(); ++i) {
if (LinkInLibrary(Libraries[i]))
return true;
}
// At this point we have processed all the libraries provided to us. Since
// we have an aggregated module at this point, the dependent libraries in
// that module should also be aggregated with duplicates eliminated. This is
// now the time to process the dependent libraries to resolve any remaining
// symbols.
const Module::LibraryListType& DepLibs = Composite->getLibraries();
for (Module::LibraryListType::const_iterator I = DepLibs.begin(),
E = DepLibs.end(); I != E; ++I) {
if (LinkInLibrary(*I))
return true;
}
return false;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_HYPERGEOMETRIC_2F2_HPP
#define STAN_MATH_PRIM_FUN_HYPERGEOMETRIC_2F2_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/hypergeometric_pFq.hpp>
namespace stan {
namespace math {
/**
* Returns the generalised hypergeometric function applied to the
* input arguments:
* \f$_2F_2(a_1,a_2;b_1,b_2;z)\f$
*
* See 'grad_pFq.hpp' for the derivatives wrt each parameter
*
* @param[in] a Vector of 'a' arguments to function
* @param[in] b Vector of 'b' arguments to function
* @param[in] z Scalar z argument
* @return Generalised hypergeometric function
*/
template <typename Ta, typename Tb, typename Tz,
require_all_eigen_t<Ta, Tb>* = nullptr,
require_stan_scalar_t<Tz>* = nullptr>
double hypergeometric_2F2(const Ta& a, const Tb& b, const Tz& z) {
return hypergeometric_pFq(a, b, z);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Add size check to 2F2<commit_after>#ifndef STAN_MATH_PRIM_FUN_HYPERGEOMETRIC_2F2_HPP
#define STAN_MATH_PRIM_FUN_HYPERGEOMETRIC_2F2_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/hypergeometric_pFq.hpp>
namespace stan {
namespace math {
/**
* Returns the generalised hypergeometric function applied to the
* input arguments:
* \f$_2F_2(a_1,a_2;b_1,b_2;z)\f$
*
* See 'grad_pFq.hpp' for the derivatives wrt each parameter
*
* @param[in] a Vector of 'a' arguments to function
* @param[in] b Vector of 'b' arguments to function
* @param[in] z Scalar z argument
* @return Generalised hypergeometric function
*/
template <typename Ta, typename Tb, typename Tz,
require_all_eigen_t<Ta, Tb>* = nullptr,
require_stan_scalar_t<Tz>* = nullptr>
double hypergeometric_2F2(const Ta& a, const Tb& b, const Tz& z) {
if (a.size() != 2 || b.size() != 2) {
std::stringstream msg;
msg << "Inputs to hypergeometric 2F2 do not contain two values"
<< "a: " << a_ref << ", b: " << b_ref;
throw std::domain_error(msg.str());
}
return hypergeometric_pFq(a, b, z);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>#include "Crown.h"
#include <cstdlib>
#include <iostream>
#include <GL/glew.h>
using namespace Crown;
class WndCtrl: public KeyboardListener
{
public:
WndCtrl()
{
GetDevice()->GetInputManager()->RegisterKeyboardListener(this);
}
virtual void KeyReleased(const KeyboardEvent& event)
{
if (event.key == KC_ESCAPE)
{
GetDevice()->StopRunning();
}
}
};
class FruitInfo: public WithProperties
{
public:
FruitInfo(Str name, float price):
mName(name), mPrice(price)
{
AddProperty(new StrProperty("fruitName", &mName));
AddProperty(new FloatProperty("fruitPrice", &mPrice));
}
virtual ~FruitInfo()
{
}
Str ToStr() const
{
return mName;
}
public:
Str mName;
float mPrice;
};
class AllWindowsContext: public WindowContext
{
public:
AllWindowsContext(WindowsManager* windowsManager):
WindowContext(windowsManager)
{
mFruitsList = new List<Generic>();
mFruitsList->Append(new FruitInfo("Pear", 1.38f));
mFruitsList->Append(new FruitInfo("Apple", 2.41f));
mFruitsList->Append(new FruitInfo("Peach", 1.89f));
mFruitsList->Append(new FruitInfo("Tomato???", 0.87f));
mFruitsList->Append(new FruitInfo("Orange", 1.40f));
mFruitsList->Append(new FruitInfo("Pineapple", 2.15f));
//AddProperty(new GenericListProperty("FruitsList", &mFruitsList));
RegisterAction("IncreaseFruitPrice", CreateDelegate(this, &AllWindowsContext::IncreaseFruitPrice));
RegisterAction("DecreaseFruitPrice", CreateDelegate(this, &AllWindowsContext::DecreaseFruitPrice));
}
virtual ~AllWindowsContext()
{
for(int i=0; i<mFruitsList->GetSize(); i++)
{
FruitInfo* fruitInfo = mFruitsList->GetElement(i).asType<FruitInfo>();
delete fruitInfo;
}
}
void OnLoad()
{
lwFruits = (ListView*)(GetAssociatedWindow()->FindChildByName("lwFruits"));
}
void IncreaseFruitPrice(Widget* src, List<Str>* /*args*/)
{
FruitPriceApplyDeltaToSelected(+1.0f);
}
void DecreaseFruitPrice(Widget* src, List<Str>* /*args*/)
{
FruitPriceApplyDeltaToSelected(-1.0f);
}
void FruitPriceApplyDeltaToSelected(float delta)
{
int selectedIndex = lwFruits->GetSelectedIndex();
if (selectedIndex != -1)
{
FruitInfo* fruitInfo;
mFruitsList->GetElement(selectedIndex).asType(&fruitInfo);
fruitInfo->SetPropertyValue("fruitPrice", fruitInfo->mPrice + delta);
}
}
private:
ListView* lwFruits;
List<Generic>* mFruitsList;
};
class MainScene: public Scene, public WeakReferenced
{
public:
MainScene(Crown::uint windowWidth, Crown::uint windowHeight)
{
}
virtual ~MainScene()
{
}
void LoadXWMLAndLogResponse(Str xwmlFile)
{
XWMLReader xwml;
Window* window;
Filesystem* fs = GetFilesystem();
FilesystemEntry info;
// if (!fs->GetInfo(xwmlFile, info))
// {
// MessageWindow* mw = new MessageWindow(mWindowsManager, "Load XWML", "Could not find file '" + xwmlFile + "'", MWR_OK, NULL);
// mWindowsManager->DoModalWindow(mw);
// return;
// }
window = xwml.LoadFile(xwmlFile, mWindowsManager, new AllWindowsContext(mWindowsManager));
if (window == NULL)
Log::E("Could not load XWML file '" + info.osPath + "'");
else
Log::I("Successfully loaded XWML file '" + info.osPath + "'");
}
virtual void OnLoad()
{
Scene::OnLoad();
Renderer* renderer = GetDevice()->GetRenderer();
renderer->SetClearColor(Color4(0.6f, 0.6f, 0.6f, 1.0f));
mWindowsManager = new WindowsManager(this);
mWindowsManager->RegisterAction("LoadXWMLFromFilepath", CreateDelegate(this, &MainScene::LoadXWMLFromFilepath));
//LoadXWMLAndLogResponse("res/window.xml", wm);
//LoadXWMLAndLogResponse("res/window_listview.xml", wm);
LoadXWMLAndLogResponse("res/window_loader.xml");
}
void LoadXWMLFromFilepath(Widget* src, List<Str>* /*args*/)
{
Window* window = src->GetWindow();
TextBox* tbXWMLFilepath = (TextBox*)window->FindChildByName("tbXWMLFilepath");
if (tbXWMLFilepath == NULL)
{
Log::E("LoadXWMLFromFilepath action: Could not find TextBox 'tbXWMLFilepath'");
return;
}
LoadXWMLAndLogResponse(tbXWMLFilepath->GetText());
}
virtual void RenderScene()
{
GetDevice()->GetRenderer()->_SetBackfaceCulling(false);
mWindowsManager->Render();
GetDevice()->GetRenderer()->_SetBackfaceCulling(true);
}
private:
WindowsManager* mWindowsManager;
};
int main(int argc, char** argv)
{
int wndW = 1024;
int wndH = 768;
if (argc == 3)
{
wndW = atoi(argv[1]);
wndH = atoi(argv[2]);
}
Device* mDevice = GetDevice();
if (!mDevice->Init(wndW, wndH, 32, false))
{
return 0;
}
WndCtrl ctrl;
MainScene* mainScene = new MainScene(wndW, wndH);
GetDevice()->GetSceneManager()->SelectNextScene(mainScene);
mDevice->GetMainWindow()->SetTitle("Crown Engine v0.1 - XWMLReader Test");
while (mDevice->IsRunning())
{
mDevice->Frame();
}
mDevice->Shutdown();
return 0;
}
<commit_msg>Delete xwmlreader sample<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* [ Copyright (C) 2011 Markus Mohrhard <[email protected]> (initial developer) ]
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <test/unoapi_test.hxx>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <com/sun/star/sheet/XCellRangesQuery.hpp>
#include <com/sun/star/sheet/XSheetCellRanges.hpp>
#include <com/sun/star/table/CellAddress.hpp>
#include <com/sun/star/sheet/CellFlags.hpp>
using namespace com::sun::star;
namespace ScCellRangeObj {
class ScXCellRangesQuery : public UnoApiTest
{
public:
ScXCellRangesQuery();
uno::Reference<sheet::XCellRangesQuery> init();
void setRowVisible(bool bVisible);
//Testcases
void testQueryColumnDifference();
void testQueryContentDifference();
void testQueryEmptyCells();
void testQueryFormulaCells();
void testQueryIntersection();
void testQueryRowDifference();
void testQueryVisibleCells();
CPPUNIT_TEST_SUITE(ScXCellRangesQuery);
CPPUNIT_TEST(testQueryColumnDifference);
CPPUNIT_TEST(testQueryContentDifference);
CPPUNIT_TEST(testQueryEmptyCells);
//looks broken
//CPPUNIT_TEST(testQueryFormulaCells);
CPPUNIT_TEST(testQueryIntersection);
CPPUNIT_TEST(testQueryRowDifference);
CPPUNIT_TEST_SUITE_END();
};
ScXCellRangesQuery::ScXCellRangesQuery()
{
}
uno::Reference<sheet::XCellRangesQuery> ScXCellRangesQuery::init()
{
rtl::OUString aFileURL;
const rtl::OUString aFileBase(RTL_CONSTASCII_USTRINGPARAM("xcellrangesquery.ods"));
createFileURL(aFileBase, aFileURL);
std::cout << rtl::OUStringToOString(aFileURL, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
uno::Reference< lang::XComponent > xComponent = loadFromDesktop(aFileURL);
uno::Reference< sheet::XSpreadsheetDocument> xDoc (xComponent, UNO_QUERY_THROW);
uno::Reference< container::XIndexAccess > xIndex (xDoc->getSheets(), UNO_QUERY_THROW);
uno::Reference< sheet::XSpreadsheet > xSheet( xIndex->getByIndex(0), UNO_QUERY_THROW);
CPPUNIT_ASSERT_MESSAGE("Could not create interface of type XSpreadsheet", xSheet.is());
uno::Reference<sheet::XCellRangesQuery> xReturn(xSheet->getCellRangeByPosition(0,0,3,4), UNO_QUERY_THROW);
CPPUNIT_ASSERT_MESSAGE("Could not create object of type XCellRangesQuery", xReturn.is());
return xReturn;
}
void ScXCellRangesQuery::testQueryColumnDifference()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.B1:C1,Sheet1.B3:C5"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryColumnDifferences(table::CellAddress(0, 1, 1));
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryColumnDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryColumnDifference", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryContentDifference()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.B2:B3"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryContentCells(sheet::CellFlags::VALUE);
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryContentDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryContentDifference", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryEmptyCells()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A1:A5,Sheet1.B1:C1,Sheet1.B5,Sheet1.C3:C5,Sheet1.D1:D5"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryEmptyCells();
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryEmptyCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryEmptyCells", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryFormulaCells()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.C2"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryFormulaCells(sheet::CellFlags::FORMULA);
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryFormulaCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryIntersection()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.D4:D5"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryIntersection(table::CellRangeAddress(0,3,3,7,7));
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryIntersection: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryRowDifference()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A2:A4,Sheet1.C2:D4"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryRowDifferences(table::CellAddress(0,1,1));
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryRowDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryVisibleCells()
{
setRowVisible(false);
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A2"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryVisibleCells();
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryVisibleCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}
void ScXCellRangesQuery::setRowVisible(bool bVisible)
{
}
CPPUNIT_TEST_SUITE_REGISTRATION(ScXCellRangesQuery);
CPPUNIT_PLUGIN_IMPLEMENT();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>only load the testfile once and after that reuse the already loaded file<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* [ Copyright (C) 2011 Markus Mohrhard <[email protected]> (initial developer) ]
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <test/unoapi_test.hxx>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <com/sun/star/sheet/XCellRangesQuery.hpp>
#include <com/sun/star/sheet/XSheetCellRanges.hpp>
#include <com/sun/star/table/CellAddress.hpp>
#include <com/sun/star/sheet/CellFlags.hpp>
using namespace com::sun::star;
namespace ScCellRangeObj {
class ScXCellRangesQuery : public UnoApiTest
{
public:
ScXCellRangesQuery();
uno::Reference<sheet::XCellRangesQuery> init();
void setRowVisible(bool bVisible);
//Testcases
void testQueryColumnDifference();
void testQueryContentDifference();
void testQueryEmptyCells();
void testQueryFormulaCells();
void testQueryIntersection();
void testQueryRowDifference();
void testQueryVisibleCells();
CPPUNIT_TEST_SUITE(ScXCellRangesQuery);
CPPUNIT_TEST(testQueryColumnDifference);
CPPUNIT_TEST(testQueryContentDifference);
CPPUNIT_TEST(testQueryEmptyCells);
//looks broken
//CPPUNIT_TEST(testQueryFormulaCells);
CPPUNIT_TEST(testQueryIntersection);
CPPUNIT_TEST(testQueryRowDifference);
CPPUNIT_TEST_SUITE_END();
};
ScXCellRangesQuery::ScXCellRangesQuery()
{
}
uno::Reference<sheet::XCellRangesQuery> ScXCellRangesQuery::init()
{
rtl::OUString aFileURL;
const rtl::OUString aFileBase(RTL_CONSTASCII_USTRINGPARAM("xcellrangesquery.ods"));
createFileURL(aFileBase, aFileURL);
std::cout << rtl::OUStringToOString(aFileURL, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
static uno::Reference< lang::XComponent > xComponent;
if( !xComponent.is())
xComponent = loadFromDesktop(aFileURL);
uno::Reference< sheet::XSpreadsheetDocument> xDoc (xComponent, UNO_QUERY_THROW);
uno::Reference< container::XIndexAccess > xIndex (xDoc->getSheets(), UNO_QUERY_THROW);
uno::Reference< sheet::XSpreadsheet > xSheet( xIndex->getByIndex(0), UNO_QUERY_THROW);
CPPUNIT_ASSERT_MESSAGE("Could not create interface of type XSpreadsheet", xSheet.is());
uno::Reference<sheet::XCellRangesQuery> xReturn(xSheet->getCellRangeByPosition(0,0,3,4), UNO_QUERY_THROW);
CPPUNIT_ASSERT_MESSAGE("Could not create object of type XCellRangesQuery", xReturn.is());
return xReturn;
}
void ScXCellRangesQuery::testQueryColumnDifference()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.B1:C1,Sheet1.B3:C5"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryColumnDifferences(table::CellAddress(0, 1, 1));
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryColumnDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryColumnDifference", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryContentDifference()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.B2:B3"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryContentCells(sheet::CellFlags::VALUE);
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryContentDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryContentDifference", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryEmptyCells()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A1:A5,Sheet1.B1:C1,Sheet1.B5,Sheet1.C3:C5,Sheet1.D1:D5"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryEmptyCells();
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryEmptyCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryEmptyCells", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryFormulaCells()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.C2"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryFormulaCells(sheet::CellFlags::FORMULA);
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryFormulaCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryIntersection()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.D4:D5"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryIntersection(table::CellRangeAddress(0,3,3,7,7));
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryIntersection: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryRowDifference()
{
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A2:A4,Sheet1.C2:D4"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryRowDifferences(table::CellAddress(0,1,1));
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryRowDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}
void ScXCellRangesQuery::testQueryVisibleCells()
{
setRowVisible(false);
rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A2"));
uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryVisibleCells();
rtl::OUString aResult = xRanges->getRangeAddressesAsString();
std::cout << "testQueryVisibleCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}
void ScXCellRangesQuery::setRowVisible(bool bVisible)
{
}
CPPUNIT_TEST_SUITE_REGISTRATION(ScXCellRangesQuery);
CPPUNIT_PLUGIN_IMPLEMENT();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file stochastic_gradient_descent.hpp
* \brief Stochastic Gradient Descent (SGD) Implementation for neural networks
*
* This implementations supports fully-connected layers, convolutional layers,
* RBM layers, CRBM layers, transform layers and pooling layers.
*/
#pragma once
#include "cpp_utils/static_if.hpp"
#include "dll/util/batch.hpp"
#include "dll/util/checks.hpp" // For NaN checks
#include "dll/trainer/sgd_context.hpp" //Context for SGD
namespace dll {
template <typename DBN>
struct sgd_trainer {
using dbn_t = DBN;
using weight = typename dbn_t::weight;
using this_type = sgd_trainer<dbn_t>;
static constexpr const auto layers = dbn_t::layers;
static constexpr const auto batch_size = dbn_t::batch_size;
bool ae_training = false;
dbn_t& dbn;
/*!
* \brief Indicates if the model is being trained as an auto-encoder (true) or not (false)
*/
void set_autoencoder(bool ae){
this->ae_training = ae;;
}
template<std::size_t Layer, typename Enable = void>
struct input_layer_t {
static constexpr const std::size_t L = Layer;
};
template<std::size_t Layer>
struct input_layer_t<Layer, std::enable_if_t< decay_layer_traits<typename dbn_t::template layer_type<Layer>>::is_transform_layer() >> {
static constexpr const std::size_t L = input_layer_t<Layer + 1>::L;
};
// Some Transform layers need to inherit dimensions from back
template<typename L1, typename L2, cpp_enable_if(decay_layer_traits<L1>::is_transform_layer())>
static void inherit_from_back(L1& l1, L2& l2){
auto& ctx1 = l1.template get_sgd_context<dbn_t>();
auto& ctx2 = l2.template get_sgd_context<dbn_t>();
if (ctx1.errors.size() == 0) {
ctx1.output = ctx2.input;
ctx1.errors = ctx2.input;
ctx1.input = ctx2.input;
}
}
template<typename L1, typename L2, cpp_disable_if(decay_layer_traits<L1>::is_transform_layer())>
static void inherit_from_back(L1& /*l1*/, L2& /*l2*/){ }
// Some Transform layers need to inherit dimensions from back
template<typename L1, typename L2, cpp_enable_if(decay_layer_traits<L2>::is_transform_layer())>
static void inherit_from_front(L1& l1, L2& l2){
auto& ctx1 = l1.template get_sgd_context<dbn_t>();
auto& ctx2 = l2.template get_sgd_context<dbn_t>();
if (ctx2.errors.size() == 0) {
ctx2.output = ctx1.output;
ctx2.errors = ctx1.output;
ctx2.input = ctx1.output;
}
}
template<typename L1, typename L2, cpp_disable_if(decay_layer_traits<L2>::is_transform_layer())>
static void inherit_from_front(L1& /*l1*/, L2& /*l2*/){ }
explicit sgd_trainer(dbn_t& dbn) : dbn(dbn) {
// Initialize all the SGD contexts
dbn.for_each_layer([](auto& layer) {
layer.template init_sgd_context<dbn_t>();
});
// Inherit dimensions from back
dbn.for_each_layer_rpair([](auto& l1, auto& l2) {
constexpr bool l1_transform = decay_layer_traits<decltype(l1)>::is_transform_layer();
constexpr bool l2_transform = decay_layer_traits<decltype(l2)>::is_transform_layer();
if (l1_transform && (!l2_transform || l2.template get_sgd_context<dbn_t>().errors.size())) {
this_type::inherit_from_back(l1, l2);
}
});
// Inherit dimensions from front
dbn.for_each_layer_pair([](auto& l1, auto& l2) {
constexpr bool l2_transform = decay_layer_traits<decltype(l2)>::is_transform_layer();
if (l2_transform) {
this_type::inherit_from_front(l1, l2);
}
});
}
void init_training(std::size_t) {}
template <typename D, typename It>
void copy_inputs(D& dest, It first, It last) {
std::size_t i = 0;
while (first != last) {
dest(i++) = *first++;
}
}
template <typename D, typename It, cpp_enable_if(etl::decay_traits<D>::dimensions() == 2)>
void copy_labels(D& dest, It first, It last) {
//TODO How does that work in auto encoder mode ?
std::size_t i = 0;
while (first != last) {
for (std::size_t l = 0; l < etl::dim<1>(dest); ++l) {
dest(i, l) = (*first)[l];
}
++i;
++first;
}
}
template <typename D, typename It, cpp_enable_if(etl::decay_traits<D>::dimensions() == 4)>
void copy_labels(D& dest, It first, It last) {
//TODO How does that work in auto encoder mode ?
std::size_t i = 0;
while (first != last) {
dest(i++) = *first++;
}
}
// TODO: There are way too many copies going in this function
template <typename T, typename L, typename InputTransformer>
std::pair<double, double> train_batch(std::size_t /*epoch*/, const dll::batch<T>& data_batch, const dll::batch<L>& label_batch, InputTransformer input_transformer) {
dll::auto_timer timer("sgd::train_batch");
// Ensure that the data batch and the label batch are of the same size
cpp_assert(data_batch.size() == label_batch.size(), "Invalid sizes");
auto n = label_batch.size();
decltype(auto) input_layer = dbn.template layer_get<input_layer_t<0>::L>();
decltype(auto) input_ctx = input_layer.template get_sgd_context<dbn_t>();
decltype(auto) first_layer = dbn.template layer_get<0>();
decltype(auto) first_ctx = first_layer.template get_sgd_context<dbn_t>();
decltype(auto) last_layer = dbn.template layer_get<layers - 1>();
decltype(auto) last_ctx = last_layer.template get_sgd_context<dbn_t>();
// Prepare initial inputs and final outputs (labels)
auto inputs = input_ctx.input;
auto labels = last_ctx.output;
//Copy inputs and labels into suitable data structure
copy_inputs(inputs, data_batch.begin(), data_batch.end());
copy_labels(labels, label_batch.begin(), label_batch.end());
auto tilde_inputs = inputs;
for(size_t i = 0; i < etl::dim<0>(tilde_inputs); ++i){
input_transformer(tilde_inputs(i));
}
//Feedforward pass
{
dll::auto_timer timer("sgd::forward");
first_ctx.input = tilde_inputs;
first_layer.batch_activate_hidden(first_ctx.output, first_ctx.input);
dbn.for_each_layer_pair([](auto& layer_1, auto& layer_2) {
auto& ctx1 = layer_1.template get_sgd_context<dbn_t>();
auto& ctx2 = layer_2.template get_sgd_context<dbn_t>();
ctx2.input = ctx1.output;
layer_2.batch_activate_hidden(ctx2.output, ctx2.input);
});
}
//Compute the errors of the last layer
last_ctx.errors = labels - last_ctx.output;
// Backpropagate the error
{
dll::auto_timer timer("sgd::backward");
dbn.for_each_layer_rpair([](auto& r1, auto& r2) {
auto& ctx1 = r1.template get_sgd_context<dbn_t>();
auto& ctx2 = r2.template get_sgd_context<dbn_t>();
r2.adapt_errors(ctx2);
r2.backward_batch(ctx1.errors, ctx2);
});
first_layer.adapt_errors(first_ctx);
}
// Compute and apply the gradients
{
dll::auto_timer timer("sgd::grad");
dbn.for_each_layer([this, n](auto& layer) {
// Compute the gradients
layer.compute_gradients(layer.template get_sgd_context<dbn_t>());
// Apply the gradients
this->apply_gradients(layer, n);
});
}
// Compute error and loss
double error = 0.0;
double loss = 0.0;
{
dll::auto_timer timer("sgd::error");
error = etl::mean(etl::abs(labels - last_ctx.output));
if (ae_training) {
// Reconstruction Cross-Entropy Loss
loss = -etl::sum((labels >> etl::log(last_ctx.output)) + ((1.0 - labels) >> etl::log(1 - last_ctx.output))) / (double)n;
} else {
// Cross-Entropy Loss
loss = -etl::sum(etl::log(last_ctx.output) >> labels) / (double)n;
}
}
return std::make_pair(error, loss);
}
template <typename L, cpp_enable_if(decay_layer_traits<L>::is_neural_layer())>
void apply_gradients(L& layer, std::size_t n) {
auto& context = layer.template get_sgd_context<dbn_t>();
//Update the gradients
this->update_grad(layer.w, context.w_grad, w_decay(dbn_traits<dbn_t>::decay()), 0.0);
this->update_grad(layer.b, context.b_grad, b_decay(dbn_traits<dbn_t>::decay()), 0.0);
//Update with momentum and learning rate
if (dbn_traits<dbn_t>::has_momentum()) {
auto momentum = dbn.momentum;
auto eps = dbn.learning_rate;
context.w_inc = momentum * context.w_inc + (eps / n) * context.w_grad;
context.b_inc = momentum * context.b_inc + (eps / n) * context.b_grad;
layer.w += context.w_inc;
layer.b += context.b_inc;
} else {
auto eps = dbn.learning_rate;
layer.w += (eps / n) * context.w_grad;
layer.b += (eps / n) * context.b_grad;
}
nan_check_deep(layer.w);
nan_check_deep(layer.b);
}
template <typename L, cpp_disable_if(decay_layer_traits<L>::is_neural_layer())>
void apply_gradients(L&, std::size_t) {
//Pooling and transform layers have no weights, therefore no
//gradients
}
template <typename V, typename G>
void update_grad(const V& value, G& grad, decay_type decay, double penalty) {
if (decay == decay_type::L1) {
grad = grad - dbn.l1_weight_cost * abs(value) - penalty;
} else if (decay == decay_type::L2) {
grad = grad - dbn.l2_weight_cost * value - penalty;
} else if (decay == decay_type::L1L2) {
grad = grad - dbn.l1_weight_cost * abs(value) - dbn.l2_weight_cost * value - penalty;
} else {
grad = grad - penalty;
}
}
static std::string name() {
return "Stochastic Gradient Descent";
}
};
} //end of dll namespace
<commit_msg>New performance timer<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file stochastic_gradient_descent.hpp
* \brief Stochastic Gradient Descent (SGD) Implementation for neural networks
*
* This implementations supports fully-connected layers, convolutional layers,
* RBM layers, CRBM layers, transform layers and pooling layers.
*/
#pragma once
#include "cpp_utils/static_if.hpp"
#include "dll/util/batch.hpp"
#include "dll/util/checks.hpp" // For NaN checks
#include "dll/trainer/sgd_context.hpp" //Context for SGD
namespace dll {
template <typename DBN>
struct sgd_trainer {
using dbn_t = DBN;
using weight = typename dbn_t::weight;
using this_type = sgd_trainer<dbn_t>;
static constexpr const auto layers = dbn_t::layers;
static constexpr const auto batch_size = dbn_t::batch_size;
bool ae_training = false;
dbn_t& dbn;
/*!
* \brief Indicates if the model is being trained as an auto-encoder (true) or not (false)
*/
void set_autoencoder(bool ae){
this->ae_training = ae;;
}
template<std::size_t Layer, typename Enable = void>
struct input_layer_t {
static constexpr const std::size_t L = Layer;
};
template<std::size_t Layer>
struct input_layer_t<Layer, std::enable_if_t< decay_layer_traits<typename dbn_t::template layer_type<Layer>>::is_transform_layer() >> {
static constexpr const std::size_t L = input_layer_t<Layer + 1>::L;
};
// Some Transform layers need to inherit dimensions from back
template<typename L1, typename L2, cpp_enable_if(decay_layer_traits<L1>::is_transform_layer())>
static void inherit_from_back(L1& l1, L2& l2){
auto& ctx1 = l1.template get_sgd_context<dbn_t>();
auto& ctx2 = l2.template get_sgd_context<dbn_t>();
if (ctx1.errors.size() == 0) {
ctx1.output = ctx2.input;
ctx1.errors = ctx2.input;
ctx1.input = ctx2.input;
}
}
template<typename L1, typename L2, cpp_disable_if(decay_layer_traits<L1>::is_transform_layer())>
static void inherit_from_back(L1& /*l1*/, L2& /*l2*/){ }
// Some Transform layers need to inherit dimensions from back
template<typename L1, typename L2, cpp_enable_if(decay_layer_traits<L2>::is_transform_layer())>
static void inherit_from_front(L1& l1, L2& l2){
auto& ctx1 = l1.template get_sgd_context<dbn_t>();
auto& ctx2 = l2.template get_sgd_context<dbn_t>();
if (ctx2.errors.size() == 0) {
ctx2.output = ctx1.output;
ctx2.errors = ctx1.output;
ctx2.input = ctx1.output;
}
}
template<typename L1, typename L2, cpp_disable_if(decay_layer_traits<L2>::is_transform_layer())>
static void inherit_from_front(L1& /*l1*/, L2& /*l2*/){ }
explicit sgd_trainer(dbn_t& dbn) : dbn(dbn) {
// Initialize all the SGD contexts
dbn.for_each_layer([](auto& layer) {
layer.template init_sgd_context<dbn_t>();
});
// Inherit dimensions from back
dbn.for_each_layer_rpair([](auto& l1, auto& l2) {
constexpr bool l1_transform = decay_layer_traits<decltype(l1)>::is_transform_layer();
constexpr bool l2_transform = decay_layer_traits<decltype(l2)>::is_transform_layer();
if (l1_transform && (!l2_transform || l2.template get_sgd_context<dbn_t>().errors.size())) {
this_type::inherit_from_back(l1, l2);
}
});
// Inherit dimensions from front
dbn.for_each_layer_pair([](auto& l1, auto& l2) {
constexpr bool l2_transform = decay_layer_traits<decltype(l2)>::is_transform_layer();
if (l2_transform) {
this_type::inherit_from_front(l1, l2);
}
});
}
void init_training(std::size_t) {}
template <typename D, typename It>
void copy_inputs(D& dest, It first, It last) {
std::size_t i = 0;
while (first != last) {
dest(i++) = *first++;
}
}
template <typename D, typename It, cpp_enable_if(etl::decay_traits<D>::dimensions() == 2)>
void copy_labels(D& dest, It first, It last) {
//TODO How does that work in auto encoder mode ?
std::size_t i = 0;
while (first != last) {
for (std::size_t l = 0; l < etl::dim<1>(dest); ++l) {
dest(i, l) = (*first)[l];
}
++i;
++first;
}
}
template <typename D, typename It, cpp_enable_if(etl::decay_traits<D>::dimensions() == 4)>
void copy_labels(D& dest, It first, It last) {
//TODO How does that work in auto encoder mode ?
std::size_t i = 0;
while (first != last) {
dest(i++) = *first++;
}
}
// TODO: There are way too many copies going in this function
template <typename T, typename L, typename InputTransformer>
std::pair<double, double> train_batch(std::size_t /*epoch*/, const dll::batch<T>& data_batch, const dll::batch<L>& label_batch, InputTransformer input_transformer) {
dll::auto_timer timer("sgd::train_batch");
// Ensure that the data batch and the label batch are of the same size
cpp_assert(data_batch.size() == label_batch.size(), "Invalid sizes");
auto n = label_batch.size();
decltype(auto) input_layer = dbn.template layer_get<input_layer_t<0>::L>();
decltype(auto) input_ctx = input_layer.template get_sgd_context<dbn_t>();
decltype(auto) first_layer = dbn.template layer_get<0>();
decltype(auto) first_ctx = first_layer.template get_sgd_context<dbn_t>();
decltype(auto) last_layer = dbn.template layer_get<layers - 1>();
decltype(auto) last_ctx = last_layer.template get_sgd_context<dbn_t>();
// Prepare initial inputs and final outputs (labels)
auto inputs = input_ctx.input;
auto labels = last_ctx.output;
//Copy inputs and labels into suitable data structure
copy_inputs(inputs, data_batch.begin(), data_batch.end());
copy_labels(labels, label_batch.begin(), label_batch.end());
auto tilde_inputs = inputs;
for(size_t i = 0; i < etl::dim<0>(tilde_inputs); ++i){
input_transformer(tilde_inputs(i));
}
//Feedforward pass
{
dll::auto_timer timer("sgd::forward");
first_ctx.input = tilde_inputs;
first_layer.batch_activate_hidden(first_ctx.output, first_ctx.input);
dbn.for_each_layer_pair([](auto& layer_1, auto& layer_2) {
auto& ctx1 = layer_1.template get_sgd_context<dbn_t>();
auto& ctx2 = layer_2.template get_sgd_context<dbn_t>();
ctx2.input = ctx1.output;
layer_2.batch_activate_hidden(ctx2.output, ctx2.input);
});
}
//Compute the errors of the last layer
last_ctx.errors = labels - last_ctx.output;
// Backpropagate the error
{
dll::auto_timer timer("sgd::backward");
dbn.for_each_layer_rpair([](auto& r1, auto& r2) {
auto& ctx1 = r1.template get_sgd_context<dbn_t>();
auto& ctx2 = r2.template get_sgd_context<dbn_t>();
r2.adapt_errors(ctx2);
r2.backward_batch(ctx1.errors, ctx2);
});
first_layer.adapt_errors(first_ctx);
}
// Compute and apply the gradients
{
dll::auto_timer timer("sgd::grad");
dbn.for_each_layer([this, n](auto& layer) {
// Compute the gradients
layer.compute_gradients(layer.template get_sgd_context<dbn_t>());
// Apply the gradients
this->apply_gradients(layer, n);
});
}
// Compute error and loss
double error = 0.0;
double loss = 0.0;
{
dll::auto_timer timer("sgd::error");
error = etl::mean(etl::abs(labels - last_ctx.output));
if (ae_training) {
// Reconstruction Cross-Entropy Loss
loss = -etl::sum((labels >> etl::log(last_ctx.output)) + ((1.0 - labels) >> etl::log(1 - last_ctx.output))) / (double)n;
} else {
// Cross-Entropy Loss
loss = -etl::sum(etl::log(last_ctx.output) >> labels) / (double)n;
}
}
return std::make_pair(error, loss);
}
template <typename L, cpp_enable_if(decay_layer_traits<L>::is_neural_layer())>
void apply_gradients(L& layer, std::size_t n) {
dll::auto_timer timer("sgd::apply_grad");
auto& context = layer.template get_sgd_context<dbn_t>();
//Update the gradients
this->update_grad(layer.w, context.w_grad, w_decay(dbn_traits<dbn_t>::decay()), 0.0);
this->update_grad(layer.b, context.b_grad, b_decay(dbn_traits<dbn_t>::decay()), 0.0);
//Update with momentum and learning rate
if (dbn_traits<dbn_t>::has_momentum()) {
auto momentum = dbn.momentum;
auto eps = dbn.learning_rate;
context.w_inc = momentum * context.w_inc + (eps / n) * context.w_grad;
context.b_inc = momentum * context.b_inc + (eps / n) * context.b_grad;
layer.w += context.w_inc;
layer.b += context.b_inc;
} else {
auto eps = dbn.learning_rate;
layer.w += (eps / n) * context.w_grad;
layer.b += (eps / n) * context.b_grad;
}
nan_check_deep(layer.w);
nan_check_deep(layer.b);
}
template <typename L, cpp_disable_if(decay_layer_traits<L>::is_neural_layer())>
void apply_gradients(L&, std::size_t) {
//Pooling and transform layers have no weights, therefore no
//gradients
}
template <typename V, typename G>
void update_grad(const V& value, G& grad, decay_type decay, double penalty) {
if (decay == decay_type::L1) {
grad = grad - dbn.l1_weight_cost * abs(value) - penalty;
} else if (decay == decay_type::L2) {
grad = grad - dbn.l2_weight_cost * value - penalty;
} else if (decay == decay_type::L1L2) {
grad = grad - dbn.l1_weight_cost * abs(value) - dbn.l2_weight_cost * value - penalty;
} else {
grad = grad - penalty;
}
}
static std::string name() {
return "Stochastic Gradient Descent";
}
};
} //end of dll namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2017, Joseph Mirabel
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio 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
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>.
#ifndef HPP_PINOCCHIO_LIEGROUP_CARTESIAN_PRODUCT_OPERATION_HH
#define HPP_PINOCCHIO_LIEGROUP_CARTESIAN_PRODUCT_OPERATION_HH
#include <pinocchio/multibody/liegroup/cartesian-product.hpp>
#include <hpp/util/exception-factory.hh>
namespace hpp {
namespace pinocchio {
namespace liegroup {
template<typename LieGroup1, typename LieGroup2>
struct CartesianProductOperation : public se3::CartesianProductOperation<LieGroup1, LieGroup2>
{
enum {
BoundSize = LieGroup1::BoundSize + LieGroup2::BoundSize,
NR = LieGroup1::BoundSize + LieGroup2::BoundSize,
NT = LieGroup1::BoundSize + LieGroup2::BoundSize
};
typedef se3::CartesianProductOperation<LieGroup1, LieGroup2> Base;
template <class ConfigL_t, class ConfigR_t>
static double squaredDistance(
const Eigen::MatrixBase<ConfigL_t> & q0,
const Eigen::MatrixBase<ConfigR_t> & q1)
{
return Base::squaredDistance(q0, q1);
}
template <class ConfigL_t, class ConfigR_t>
static double squaredDistance(
const Eigen::MatrixBase<ConfigL_t> & q0,
const Eigen::MatrixBase<ConfigR_t> & q1,
const typename ConfigL_t::Scalar& w)
{
return LieGroup1::squaredDistance(q0.template head<LieGroup1::NQ>(), q1.template head<LieGroup1::NQ>(), w)
+ LieGroup2::squaredDistance(q0.template tail<LieGroup2::NQ>(), q1.template tail<LieGroup2::NQ>(), w);
}
template <class ConfigIn_t, class ConfigOut_t>
static void setBound(
const Eigen::MatrixBase<ConfigIn_t > & bound,
const Eigen::MatrixBase<ConfigOut_t> & out)
{
EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(ConfigOut_t, Base::ConfigVector_t)
ConfigOut_t& oout = const_cast<Eigen::MatrixBase<ConfigOut_t>&> (out).derived();
if (bound.size() == BoundSize) {
if (LieGroup1::BoundSize > 0)
LieGroup1::setBound(bound.template head<LieGroup1::BoundSize>(),
oout. template head<LieGroup1::NQ >());
if (LieGroup2::BoundSize > 0)
LieGroup2::setBound(bound.template tail<LieGroup2::BoundSize>(),
oout. template tail<LieGroup2::NQ >());
} else if (bound.size() == Base::NQ) {
LieGroup1::setBound(bound.template head<LieGroup1::NQ>(),
oout. template head<LieGroup1::NQ>());
LieGroup2::setBound(bound.template tail<LieGroup2::NQ>(),
oout. template tail<LieGroup2::NQ>());
} else {
HPP_THROW(std::invalid_argument,
"Expected vector of size " << BoundSize << " or " << Base::NQ
<< ", got size " << bound.size());
}
}
template <class JacobianIn_t, class JacobianOut_t>
static void getRotationSubJacobian(
const Eigen::MatrixBase<JacobianIn_t > & Jin,
const Eigen::MatrixBase<JacobianOut_t> & Jout)
{
JacobianOut_t& J = const_cast<Eigen::MatrixBase<JacobianOut_t>&> (Jout).derived();
if (LieGroup1::NR > 0)
LieGroup1::getRotationSubJacobian(Jin.template leftCols<LieGroup1::NV>(),
J .template leftCols<LieGroup1::NR>());
if (LieGroup2::NR > 0)
LieGroup2::getRotationSubJacobian(Jin.template rightCols<LieGroup2::NV>(),
J .template rightCols<LieGroup2::NR>());
}
template <class ConfigIn_t>
static bool isNormalized(const Eigen::MatrixBase<ConfigIn_t > & q, const value_type& eps)
{
EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(ConfigIn_t , Base::ConfigVector_t);
return LieGroup1::isNormalized(q.template head<LieGroup1::NQ>(), eps)
&& LieGroup2::isNormalized(q.template tail<LieGroup2::NQ>(), eps);
}
}; // struct CartesianProductOperation
} // namespace liegroup
} // namespace pinocchio
} // namespace hpp
#endif // HPP_PINOCCHIO_LIEGROUP_CARTESIAN_PRODUCT_OPERATION_HH
<commit_msg>Fix CartesianProductOperation<commit_after>// Copyright (c) 2017, Joseph Mirabel
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio 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
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>.
#ifndef HPP_PINOCCHIO_LIEGROUP_CARTESIAN_PRODUCT_OPERATION_HH
#define HPP_PINOCCHIO_LIEGROUP_CARTESIAN_PRODUCT_OPERATION_HH
#include <pinocchio/multibody/liegroup/cartesian-product.hpp>
#include <hpp/util/exception-factory.hh>
namespace hpp {
namespace pinocchio {
namespace liegroup {
template<typename LieGroup1, typename LieGroup2>
struct CartesianProductOperation : public se3::CartesianProductOperation<LieGroup1, LieGroup2>
{
enum {
BoundSize = LieGroup1::BoundSize + LieGroup2::BoundSize,
NR = LieGroup1::NR + LieGroup2::NR,
NT = LieGroup1::NT + LieGroup2::NT
};
typedef se3::CartesianProductOperation<LieGroup1, LieGroup2> Base;
template <class ConfigL_t, class ConfigR_t>
static double squaredDistance(
const Eigen::MatrixBase<ConfigL_t> & q0,
const Eigen::MatrixBase<ConfigR_t> & q1)
{
return Base::squaredDistance(q0, q1);
}
template <class ConfigL_t, class ConfigR_t>
static double squaredDistance(
const Eigen::MatrixBase<ConfigL_t> & q0,
const Eigen::MatrixBase<ConfigR_t> & q1,
const typename ConfigL_t::Scalar& w)
{
return LieGroup1::squaredDistance(q0.template head<LieGroup1::NQ>(), q1.template head<LieGroup1::NQ>(), w)
+ LieGroup2::squaredDistance(q0.template tail<LieGroup2::NQ>(), q1.template tail<LieGroup2::NQ>(), w);
}
template <class ConfigIn_t, class ConfigOut_t>
static void setBound(
const Eigen::MatrixBase<ConfigIn_t > & bound,
const Eigen::MatrixBase<ConfigOut_t> & out)
{
EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(ConfigOut_t, Base::ConfigVector_t)
ConfigOut_t& oout = const_cast<Eigen::MatrixBase<ConfigOut_t>&> (out).derived();
if (bound.size() == BoundSize) {
if (LieGroup1::BoundSize > 0)
LieGroup1::setBound(bound.template head<LieGroup1::BoundSize>(),
oout. template head<LieGroup1::NQ >());
if (LieGroup2::BoundSize > 0)
LieGroup2::setBound(bound.template tail<LieGroup2::BoundSize>(),
oout. template tail<LieGroup2::NQ >());
} else if (bound.size() == Base::NQ) {
LieGroup1::setBound(bound.template head<LieGroup1::NQ>(),
oout. template head<LieGroup1::NQ>());
LieGroup2::setBound(bound.template tail<LieGroup2::NQ>(),
oout. template tail<LieGroup2::NQ>());
} else {
HPP_THROW(std::invalid_argument,
"Expected vector of size " << BoundSize << " or " << Base::NQ
<< ", got size " << bound.size());
}
}
template <class JacobianIn_t, class JacobianOut_t>
static void getRotationSubJacobian(
const Eigen::MatrixBase<JacobianIn_t > & Jin,
const Eigen::MatrixBase<JacobianOut_t> & Jout)
{
JacobianOut_t& J = const_cast<Eigen::MatrixBase<JacobianOut_t>&> (Jout).derived();
if (LieGroup1::NR > 0)
LieGroup1::getRotationSubJacobian(Jin.template leftCols<LieGroup1::NV>(),
J .template leftCols<LieGroup1::NR>());
if (LieGroup2::NR > 0)
LieGroup2::getRotationSubJacobian(Jin.template rightCols<LieGroup2::NV>(),
J .template rightCols<LieGroup2::NR>());
}
template <class ConfigIn_t>
static bool isNormalized(const Eigen::MatrixBase<ConfigIn_t > & q, const value_type& eps)
{
EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(ConfigIn_t , Base::ConfigVector_t);
return LieGroup1::isNormalized(q.template head<LieGroup1::NQ>(), eps)
&& LieGroup2::isNormalized(q.template tail<LieGroup2::NQ>(), eps);
}
}; // struct CartesianProductOperation
} // namespace liegroup
} // namespace pinocchio
} // namespace hpp
#endif // HPP_PINOCCHIO_LIEGROUP_CARTESIAN_PRODUCT_OPERATION_HH
<|endoftext|> |
<commit_before>#include <stdio.h>
#include "Halide.h"
#include <atomic>
using namespace Halide;
// Check that assertion failures free allocations appropriately
std::atomic<int> malloc_count = 0;
std::atomic<int> free_count = 0;
void *my_malloc(void *user_context, size_t x) {
malloc_count++;
void *orig = malloc(x+32);
void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
((void **)ptr)[-1] = orig;
return ptr;
}
void my_free(void *user_context, void *ptr) {
free_count++;
free(((void**)ptr)[-1]);
}
bool error_occurred = false;
void my_error_handler(void *user_context, const char *) {
error_occurred = true;
}
int main(int argc, char **argv) {
Func f, g, h;
Var x;
f(x) = x;
f.compute_root();
g(x) = f(x)+1;
g.compute_root();
h(x) = g(x)+1;
// This should fail an assertion at runtime after f has been allocated
int g_size = 100000;
g.bound(x, 0, g_size);
h.set_custom_allocator(my_malloc, my_free);
h.set_error_handler(my_error_handler);
Image<int> im = h.realize(g_size+100);
printf("%d %d\n", (int)malloc_count, (int)free_count);
assert(error_occurred && (int)malloc_count == (int)free_count);
printf("Success!\n");
return 0;
}
<commit_msg>Can't statically initialize atomic ints, apparently.<commit_after>#include <stdio.h>
#include "Halide.h"
#include <atomic>
using namespace Halide;
// Check that assertion failures free allocations appropriately
std::atomic<int> malloc_count;
std::atomic<int> free_count;
void *my_malloc(void *user_context, size_t x) {
malloc_count++;
void *orig = malloc(x+32);
void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
((void **)ptr)[-1] = orig;
return ptr;
}
void my_free(void *user_context, void *ptr) {
free_count++;
free(((void**)ptr)[-1]);
}
bool error_occurred = false;
void my_error_handler(void *user_context, const char *) {
error_occurred = true;
}
int main(int argc, char **argv) {
Func f, g, h;
Var x;
malloc_count = 0;
free_count = 0;
f(x) = x;
f.compute_root();
g(x) = f(x)+1;
g.compute_root();
h(x) = g(x)+1;
// This should fail an assertion at runtime after f has been allocated
int g_size = 100000;
g.bound(x, 0, g_size);
h.set_custom_allocator(my_malloc, my_free);
h.set_error_handler(my_error_handler);
Image<int> im = h.realize(g_size+100);
printf("%d %d\n", (int)malloc_count, (int)free_count);
assert(error_occurred && (int)malloc_count == (int)free_count);
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: drawsh2.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: nn $ $Date: 2002-05-16 13:09:13 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#include "scitems.hxx"
#include <svx/eeitem.hxx>
#include <svx/sizeitem.hxx>
#include <svx/svdpagv.hxx>
#include <svx/xdef.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/ptitem.hxx>
#include <svtools/whiter.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdouno.hxx>
#include "drawsh.hxx"
#include "drawview.hxx"
#include "viewdata.hxx"
#include "sc.hrc"
#include "tabvwsh.hxx"
USHORT ScGetFontWorkId(); // in drtxtob
//------------------------------------------------------------------
ScDrawShell::ScDrawShell( ScViewData* pData ) :
SfxShell(pData->GetViewShell()),
pViewData( pData )
{
SetPool( &pViewData->GetScDrawView()->GetModel()->GetItemPool() );
SetUndoManager( pViewData->GetSfxDocShell()->GetUndoManager() );
SetHelpId( HID_SCSHELL_DRAWSH );
SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Drawing")));
}
ScDrawShell::~ScDrawShell()
{
}
void ScDrawShell::GetState( SfxItemSet& rSet ) // Zustaende / Toggles
{
ScDrawView* pView = pViewData->GetScDrawView();
SdrDragMode eMode = pView->GetDragMode();
rSet.Put( SfxBoolItem( SID_OBJECT_ROTATE, eMode == SDRDRAG_ROTATE ) );
rSet.Put( SfxBoolItem( SID_OBJECT_MIRROR, eMode == SDRDRAG_MIRROR ) );
rSet.Put( SfxBoolItem( SID_BEZIER_EDIT, !pView->IsFrameDragSingles() ) );
USHORT nFWId = ScGetFontWorkId();
SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame();
rSet.Put(SfxBoolItem(SID_FONTWORK, pViewFrm->HasChildWindow(nFWId)));
switch( pView->GetAnchor() )
{
case SCA_PAGE:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, TRUE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, FALSE ) );
break;
case SCA_CELL:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, FALSE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, TRUE ) );
break;
default:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, FALSE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, FALSE ) );
break;
}
}
void ScDrawShell::GetDrawFuncState( SfxItemSet& rSet ) // Funktionen disablen
{
ScDrawView* pView = pViewData->GetScDrawView();
const SdrMarkList& rMarkList = pView->GetMarkList();
ULONG nMarkCount = rMarkList.GetMarkCount();
if ( nMarkCount <= 1 || !pView->IsGroupPossible() )
rSet.DisableItem( SID_GROUP );
if ( nMarkCount == 0 || !pView->IsUnGroupPossible() )
rSet.DisableItem( SID_UNGROUP );
if ( nMarkCount != 1 || !pView->IsGroupEnterPossible() )
rSet.DisableItem( SID_ENTER_GROUP );
if ( !pView->IsGroupEntered() )
rSet.DisableItem( SID_LEAVE_GROUP );
if (!pView->IsMirrorAllowed(TRUE,TRUE))
{
rSet.DisableItem( SID_MIRROR_HORIZONTAL );
rSet.DisableItem( SID_MIRROR_VERTICAL );
}
if ( nMarkCount <= 1 ) // nichts oder nur ein Objekt selektiert
{
// Ausrichtung
rSet.DisableItem( SID_OBJECT_ALIGN_LEFT ); // keine Ausrichtung an der Seite
rSet.DisableItem( SID_OBJECT_ALIGN_CENTER );
rSet.DisableItem( SID_OBJECT_ALIGN_RIGHT );
rSet.DisableItem( SID_OBJECT_ALIGN_UP );
rSet.DisableItem( SID_OBJECT_ALIGN_MIDDLE );
rSet.DisableItem( SID_OBJECT_ALIGN_DOWN );
}
if ( !nMarkCount || pView->HasMarkedControl() )
{
// Layer von Controls darf nicht veraendert werden
rSet.DisableItem( SID_OBJECT_HEAVEN );
rSet.DisableItem( SID_OBJECT_HELL );
}
else
{
if(AreAllObjectsOnLayer(SC_LAYER_FRONT,rMarkList))
{
rSet.DisableItem( SID_OBJECT_HEAVEN );
}
else if(AreAllObjectsOnLayer(SC_LAYER_BACK,rMarkList))
{
rSet.DisableItem( SID_OBJECT_HELL );
}
}
BOOL bCanRename = FALSE;
if ( nMarkCount == 1 )
{
UINT16 nObjType = rMarkList.GetMark( 0 )->GetObj()->GetObjIdentifier();
if ( nObjType == OBJ_OLE2 || nObjType == OBJ_GRAF || nObjType == OBJ_GRUP )
bCanRename = TRUE;
}
if ( !bCanRename )
rSet.DisableItem( SID_RENAME_OBJECT );
if ( !nMarkCount ) // nichts selektiert
{
// Anordnung
rSet.DisableItem( SID_FRAME_UP );
rSet.DisableItem( SID_FRAME_DOWN );
rSet.DisableItem( SID_FRAME_TO_TOP );
rSet.DisableItem( SID_FRAME_TO_BOTTOM );
// Clipboard / loeschen
rSet.DisableItem( SID_DELETE );
rSet.DisableItem( SID_DELETE_CONTENTS );
rSet.DisableItem( SID_CUT );
rSet.DisableItem( SID_COPY );
// sonstiges
rSet.DisableItem( SID_ANCHOR_TOGGLE );
rSet.DisableItem( SID_ORIGINALSIZE );
rSet.DisableItem( SID_ATTR_TRANSFORM );
}
if ( rSet.GetItemState( SID_ENABLE_HYPHENATION ) != SFX_ITEM_UNKNOWN )
{
SfxItemSet aAttrs( pView->GetModel()->GetItemPool() );
pView->GetAttributes( aAttrs );
if( aAttrs.GetItemState( EE_PARA_HYPHENATE ) >= SFX_ITEM_AVAILABLE )
{
BOOL bValue = ( (const SfxBoolItem&) aAttrs.Get( EE_PARA_HYPHENATE ) ).GetValue();
rSet.Put( SfxBoolItem( SID_ENABLE_HYPHENATION, bValue ) );
}
}
}
//
// Attribute fuer Drawing-Objekte
//
void ScDrawShell::GetDrawAttrState( SfxItemSet& rSet )
{
Point aMousePos = pViewData->GetMousePosPixel();
Window* pWindow = pViewData->GetActiveWin();
ScDrawView* pDrView = pViewData->GetScDrawView();
Point aPos = pWindow->PixelToLogic(aMousePos);
BOOL bHasMarked = pDrView->HasMarkedObj();
if( bHasMarked )
{
rSet.Put( pDrView->GetAttrFromMarked(FALSE) );
// Wenn die View selektierte Objekte besitzt, muessen entspr. Items
// von SFX_ITEM_DEFAULT (_ON) auf SFX_ITEM_DISABLED geaendert werden
SfxWhichIter aIter( rSet, XATTR_LINE_FIRST, XATTR_FILL_LAST );
USHORT nWhich = aIter.FirstWhich();
while( nWhich )
{
if( SFX_ITEM_DEFAULT == rSet.GetItemState( nWhich ) )
rSet.DisableItem( nWhich );
nWhich = aIter.NextWhich();
}
}
else
rSet.Put( pDrView->GetDefaultAttr() );
// Position- und Groesse-Items
if ( pDrView->IsAction() )
{
Rectangle aRect;
pDrView->TakeActionRect( aRect );
if ( aRect.IsEmpty() )
rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
else
{
pDrView->GetPageViewPvNum(0)->LogicToPagePos(aRect);
rSet.Put( SfxPointItem( SID_ATTR_POSITION, aRect.TopLeft() ) );
rSet.Put( SvxSizeItem( SID_ATTR_SIZE,
Size( aRect.Right() - aRect.Left(),
aRect.Bottom() - aRect.Top() ) ) );
}
}
else
{
rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
if ( bHasMarked )
{
Rectangle aRect = pDrView->GetAllMarkedRect();
pDrView->GetPageViewPvNum(0)->LogicToPagePos(aRect);
rSet.Put( SvxSizeItem( SID_ATTR_SIZE,
Size( aRect.Right() - aRect.Left(),
aRect.Bottom() - aRect.Top()) ) );
}
else
rSet.Put( SvxSizeItem( SID_ATTR_SIZE, Size( 0, 0 ) ) );
}
}
void ScDrawShell::GetAttrFuncState(SfxItemSet &rSet)
{
// Dialoge fuer Draw-Attribute disablen, wenn noetig
ScDrawView* pDrView = pViewData->GetScDrawView();
SfxItemSet aViewSet = pDrView->GetAttrFromMarked(FALSE);
if ( aViewSet.GetItemState( XATTR_LINESTYLE ) == SFX_ITEM_DEFAULT )
{
rSet.DisableItem( SID_ATTRIBUTES_LINE );
rSet.DisableItem( SID_ATTR_LINEEND_STYLE ); // Tbx-Controller
}
if ( aViewSet.GetItemState( XATTR_FILLSTYLE ) == SFX_ITEM_DEFAULT )
rSet.DisableItem( SID_ATTRIBUTES_AREA );
}
BOOL ScDrawShell::AreAllObjectsOnLayer(USHORT nLayerNo,const SdrMarkList& rMark)
{
BOOL bResult=TRUE;
ULONG nCount = rMark.GetMarkCount();
for (ULONG i=0; i<nCount; i++)
{
SdrObject* pObj = rMark.GetMark(i)->GetObj();
if ( !pObj->ISA(SdrUnoObj) )
{
if(nLayerNo!=pObj->GetLayer())
{
bResult=FALSE;
break;
}
}
}
return bResult;
}
<commit_msg>#91929#; disable original size entry if not possible<commit_after>/*************************************************************************
*
* $RCSfile: drawsh2.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: sab $ $Date: 2002-11-11 13:40:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#include "scitems.hxx"
#include <svx/eeitem.hxx>
#include <svx/sizeitem.hxx>
#include <svx/svdpagv.hxx>
#include <svx/xdef.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/ptitem.hxx>
#include <svtools/whiter.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdouno.hxx>
#include "drawsh.hxx"
#include "drawview.hxx"
#include "viewdata.hxx"
#include "sc.hrc"
#include "tabvwsh.hxx"
#ifndef _IPOBJ_HXX
#include <so3/ipobj.hxx>
#endif
#ifndef _SVDOOLE2_HXX
#include <svx/svdoole2.hxx>
#endif
USHORT ScGetFontWorkId(); // in drtxtob
//------------------------------------------------------------------
ScDrawShell::ScDrawShell( ScViewData* pData ) :
SfxShell(pData->GetViewShell()),
pViewData( pData )
{
SetPool( &pViewData->GetScDrawView()->GetModel()->GetItemPool() );
SetUndoManager( pViewData->GetSfxDocShell()->GetUndoManager() );
SetHelpId( HID_SCSHELL_DRAWSH );
SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Drawing")));
}
ScDrawShell::~ScDrawShell()
{
}
void ScDrawShell::GetState( SfxItemSet& rSet ) // Zustaende / Toggles
{
ScDrawView* pView = pViewData->GetScDrawView();
SdrDragMode eMode = pView->GetDragMode();
rSet.Put( SfxBoolItem( SID_OBJECT_ROTATE, eMode == SDRDRAG_ROTATE ) );
rSet.Put( SfxBoolItem( SID_OBJECT_MIRROR, eMode == SDRDRAG_MIRROR ) );
rSet.Put( SfxBoolItem( SID_BEZIER_EDIT, !pView->IsFrameDragSingles() ) );
USHORT nFWId = ScGetFontWorkId();
SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame();
rSet.Put(SfxBoolItem(SID_FONTWORK, pViewFrm->HasChildWindow(nFWId)));
switch( pView->GetAnchor() )
{
case SCA_PAGE:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, TRUE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, FALSE ) );
break;
case SCA_CELL:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, FALSE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, TRUE ) );
break;
default:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, FALSE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, FALSE ) );
break;
}
}
void ScDrawShell::GetDrawFuncState( SfxItemSet& rSet ) // Funktionen disablen
{
ScDrawView* pView = pViewData->GetScDrawView();
const SdrMarkList& rMarkList = pView->GetMarkList();
ULONG nMarkCount = rMarkList.GetMarkCount();
if ( nMarkCount <= 1 || !pView->IsGroupPossible() )
rSet.DisableItem( SID_GROUP );
if ( nMarkCount == 0 || !pView->IsUnGroupPossible() )
rSet.DisableItem( SID_UNGROUP );
if ( nMarkCount != 1 || !pView->IsGroupEnterPossible() )
rSet.DisableItem( SID_ENTER_GROUP );
if ( !pView->IsGroupEntered() )
rSet.DisableItem( SID_LEAVE_GROUP );
if (!pView->IsMirrorAllowed(TRUE,TRUE))
{
rSet.DisableItem( SID_MIRROR_HORIZONTAL );
rSet.DisableItem( SID_MIRROR_VERTICAL );
}
if ( nMarkCount <= 1 ) // nichts oder nur ein Objekt selektiert
{
// Ausrichtung
rSet.DisableItem( SID_OBJECT_ALIGN_LEFT ); // keine Ausrichtung an der Seite
rSet.DisableItem( SID_OBJECT_ALIGN_CENTER );
rSet.DisableItem( SID_OBJECT_ALIGN_RIGHT );
rSet.DisableItem( SID_OBJECT_ALIGN_UP );
rSet.DisableItem( SID_OBJECT_ALIGN_MIDDLE );
rSet.DisableItem( SID_OBJECT_ALIGN_DOWN );
}
if ( !nMarkCount || pView->HasMarkedControl() )
{
// Layer von Controls darf nicht veraendert werden
rSet.DisableItem( SID_OBJECT_HEAVEN );
rSet.DisableItem( SID_OBJECT_HELL );
}
else
{
if(AreAllObjectsOnLayer(SC_LAYER_FRONT,rMarkList))
{
rSet.DisableItem( SID_OBJECT_HEAVEN );
}
else if(AreAllObjectsOnLayer(SC_LAYER_BACK,rMarkList))
{
rSet.DisableItem( SID_OBJECT_HELL );
}
}
BOOL bCanRename = FALSE;
if ( nMarkCount == 1 )
{
UINT16 nObjType = rMarkList.GetMark( 0 )->GetObj()->GetObjIdentifier();
if ( nObjType == OBJ_OLE2 || nObjType == OBJ_GRAF || nObjType == OBJ_GRUP )
bCanRename = TRUE;
// #91929#; don't show original size entry if not possible
if ( nObjType == OBJ_OLE2 )
{
SdrOle2Obj* pOleObj = static_cast<SdrOle2Obj*>(rMarkList.GetMark( 0 )->GetObj());
if (pOleObj && ((pOleObj->GetObjRef()->GetMiscStatus() & SVOBJ_MISCSTATUS_SERVERRESIZE) == SVOBJ_MISCSTATUS_SERVERRESIZE))
rSet.DisableItem(SID_ORIGINALSIZE);
}
}
if ( !bCanRename )
rSet.DisableItem( SID_RENAME_OBJECT );
if ( !nMarkCount ) // nichts selektiert
{
// Anordnung
rSet.DisableItem( SID_FRAME_UP );
rSet.DisableItem( SID_FRAME_DOWN );
rSet.DisableItem( SID_FRAME_TO_TOP );
rSet.DisableItem( SID_FRAME_TO_BOTTOM );
// Clipboard / loeschen
rSet.DisableItem( SID_DELETE );
rSet.DisableItem( SID_DELETE_CONTENTS );
rSet.DisableItem( SID_CUT );
rSet.DisableItem( SID_COPY );
// sonstiges
rSet.DisableItem( SID_ANCHOR_TOGGLE );
rSet.DisableItem( SID_ORIGINALSIZE );
rSet.DisableItem( SID_ATTR_TRANSFORM );
}
if ( rSet.GetItemState( SID_ENABLE_HYPHENATION ) != SFX_ITEM_UNKNOWN )
{
SfxItemSet aAttrs( pView->GetModel()->GetItemPool() );
pView->GetAttributes( aAttrs );
if( aAttrs.GetItemState( EE_PARA_HYPHENATE ) >= SFX_ITEM_AVAILABLE )
{
BOOL bValue = ( (const SfxBoolItem&) aAttrs.Get( EE_PARA_HYPHENATE ) ).GetValue();
rSet.Put( SfxBoolItem( SID_ENABLE_HYPHENATION, bValue ) );
}
}
}
//
// Attribute fuer Drawing-Objekte
//
void ScDrawShell::GetDrawAttrState( SfxItemSet& rSet )
{
Point aMousePos = pViewData->GetMousePosPixel();
Window* pWindow = pViewData->GetActiveWin();
ScDrawView* pDrView = pViewData->GetScDrawView();
Point aPos = pWindow->PixelToLogic(aMousePos);
BOOL bHasMarked = pDrView->HasMarkedObj();
if( bHasMarked )
{
rSet.Put( pDrView->GetAttrFromMarked(FALSE) );
// Wenn die View selektierte Objekte besitzt, muessen entspr. Items
// von SFX_ITEM_DEFAULT (_ON) auf SFX_ITEM_DISABLED geaendert werden
SfxWhichIter aIter( rSet, XATTR_LINE_FIRST, XATTR_FILL_LAST );
USHORT nWhich = aIter.FirstWhich();
while( nWhich )
{
if( SFX_ITEM_DEFAULT == rSet.GetItemState( nWhich ) )
rSet.DisableItem( nWhich );
nWhich = aIter.NextWhich();
}
}
else
rSet.Put( pDrView->GetDefaultAttr() );
// Position- und Groesse-Items
if ( pDrView->IsAction() )
{
Rectangle aRect;
pDrView->TakeActionRect( aRect );
if ( aRect.IsEmpty() )
rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
else
{
pDrView->GetPageViewPvNum(0)->LogicToPagePos(aRect);
rSet.Put( SfxPointItem( SID_ATTR_POSITION, aRect.TopLeft() ) );
rSet.Put( SvxSizeItem( SID_ATTR_SIZE,
Size( aRect.Right() - aRect.Left(),
aRect.Bottom() - aRect.Top() ) ) );
}
}
else
{
rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
if ( bHasMarked )
{
Rectangle aRect = pDrView->GetAllMarkedRect();
pDrView->GetPageViewPvNum(0)->LogicToPagePos(aRect);
rSet.Put( SvxSizeItem( SID_ATTR_SIZE,
Size( aRect.Right() - aRect.Left(),
aRect.Bottom() - aRect.Top()) ) );
}
else
rSet.Put( SvxSizeItem( SID_ATTR_SIZE, Size( 0, 0 ) ) );
}
}
void ScDrawShell::GetAttrFuncState(SfxItemSet &rSet)
{
// Dialoge fuer Draw-Attribute disablen, wenn noetig
ScDrawView* pDrView = pViewData->GetScDrawView();
SfxItemSet aViewSet = pDrView->GetAttrFromMarked(FALSE);
if ( aViewSet.GetItemState( XATTR_LINESTYLE ) == SFX_ITEM_DEFAULT )
{
rSet.DisableItem( SID_ATTRIBUTES_LINE );
rSet.DisableItem( SID_ATTR_LINEEND_STYLE ); // Tbx-Controller
}
if ( aViewSet.GetItemState( XATTR_FILLSTYLE ) == SFX_ITEM_DEFAULT )
rSet.DisableItem( SID_ATTRIBUTES_AREA );
}
BOOL ScDrawShell::AreAllObjectsOnLayer(USHORT nLayerNo,const SdrMarkList& rMark)
{
BOOL bResult=TRUE;
ULONG nCount = rMark.GetMarkCount();
for (ULONG i=0; i<nCount; i++)
{
SdrObject* pObj = rMark.GetMark(i)->GetObj();
if ( !pObj->ISA(SdrUnoObj) )
{
if(nLayerNo!=pObj->GetLayer())
{
bResult=FALSE;
break;
}
}
}
return bResult;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: spelldialog.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-02-21 13:54:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_SPELLDIALOG_HXX
#include "spelldialog.hxx"
#endif
#include <sfx2/app.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <svx/svxids.hrc>
#include <svx/editstat.hxx>
#include <svx/editview.hxx>
#include <svx/unolingu.hxx>
#ifndef SC_SELECTIONSTATE_HXX
#include "selectionstate.hxx"
#endif
#include "spelleng.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"
#include "scmod.hxx"
#include "editable.hxx"
#include "undoblk.hxx"
// ============================================================================
SFX_IMPL_CHILDWINDOW( ScSpellDialogChildWindow, SID_SPELL_DIALOG )
ScSpellDialogChildWindow::ScSpellDialogChildWindow( Window* pParent, USHORT nId,
SfxBindings* pBindings, SfxChildWinInfo* pInfo ) :
::svx::SpellDialogChildWindow( pParent, nId, pBindings, pInfo ),
mpViewShell( 0 ),
mpViewData( 0 ),
mpDocShell( 0 ),
mpDoc( 0 ),
mbNeedNextObj( false ),
mbOldIdleDisabled( false )
{
Init();
}
ScSpellDialogChildWindow::~ScSpellDialogChildWindow()
{
Reset();
}
SfxChildWinInfo ScSpellDialogChildWindow::GetInfo() const
{
return ::svx::SpellDialogChildWindow::GetInfo();
}
void ScSpellDialogChildWindow::InvalidateSpellDialog()
{
::svx::SpellDialogChildWindow::InvalidateSpellDialog();
}
// protected ------------------------------------------------------------------
::svx::SpellPortions ScSpellDialogChildWindow::GetNextWrongSentence()
{
::svx::SpellPortions aPortions;
if( mxEngine.get() && mpViewData )
{
if( EditView* pEditView = mpViewData->GetSpellingView() )
{
// edit engine handles cell iteration internally
do
{
if( mbNeedNextObj )
mxEngine->SpellNextDocument();
mbNeedNextObj = !mxEngine->IsFinished() && !mxEngine->SpellSentence( *pEditView, aPortions );
}
while( mbNeedNextObj );
}
// finished? - close the spelling dialog
if( mxEngine->IsFinished() )
GetBindings().GetDispatcher()->Execute( SID_SPELL_DIALOG, SFX_CALLMODE_ASYNCHRON );
}
return aPortions;
}
void ScSpellDialogChildWindow::ApplyChangedSentence( const ::svx::SpellPortions& rChanged )
{
if( mxEngine.get() && mpViewData )
if( EditView* pEditView = mpViewData->GetSpellingView() )
mxEngine->ApplyChangedSentence( *pEditView, rChanged );
}
void ScSpellDialogChildWindow::GetFocus()
{
if( IsSelectionChanged() )
{
Reset();
InvalidateSpellDialog();
Init();
}
}
void ScSpellDialogChildWindow::LoseFocus()
{
}
// private --------------------------------------------------------------------
void ScSpellDialogChildWindow::Reset()
{
if( mpViewShell && (mpViewShell == PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) )
{
if( mxEngine.get() && mxEngine->IsAnyModified() )
{
const ScAddress& rCursor = mxOldSel->GetCellCursor();
SCTAB nTab = rCursor.Tab();
SCCOL nOldCol = rCursor.Col();
SCROW nOldRow = rCursor.Row();
SCCOL nNewCol = mpViewData->GetCurX();
SCROW nNewRow = mpViewData->GetCurY();
mpDocShell->GetUndoManager()->AddUndoAction( new ScUndoConversion(
mpDocShell, mpViewData->GetMarkData(),
nOldCol, nOldRow, nTab, mxUndoDoc.release(),
nNewCol, nNewRow, nTab, mxRedoDoc.release(),
ScConversionParam( SC_CONVERSION_SPELLCHECK ) ) );
mpDoc->SetDirty();
mpDocShell->SetDocumentModified();
}
mpViewData->SetSpellingView( 0 );
mpViewShell->KillEditView( TRUE );
mpDocShell->PostPaintGridAll();
mpViewShell->UpdateInputHandler();
mpDoc->DisableIdle( mbOldIdleDisabled );
}
mxEngine.reset();
mxUndoDoc.reset();
mxRedoDoc.reset();
mxOldSel.reset();
mpViewShell = 0;
mpViewData = 0;
mpDocShell = 0;
mpDoc = 0;
mbNeedNextObj = false;
mbOldIdleDisabled = false;
}
void ScSpellDialogChildWindow::Init()
{
if( mpViewShell )
return;
if( (mpViewShell = PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) == 0 )
return;
mpViewData = mpViewShell->GetViewData();
// exit edit mode - TODO support spelling in edit mode
if( mpViewData->HasEditView( mpViewData->GetActivePart() ) )
SC_MOD()->InputEnterHandler();
mxOldSel.reset( new ScSelectionState( *mpViewData ) );
mpDocShell = mpViewData->GetDocShell();
mpDoc = mpDocShell->GetDocument();
const ScAddress& rCursor = mxOldSel->GetCellCursor();
SCCOL nCol = rCursor.Col();
SCROW nRow = rCursor.Row();
SCTAB nTab = rCursor.Tab();
ScMarkData& rMarkData = mpViewData->GetMarkData();
rMarkData.MarkToMulti();
switch( mxOldSel->GetSelectionType() )
{
case SC_SELECTTYPE_NONE:
case SC_SELECTTYPE_SHEET:
{
// test if there is something editable
ScEditableTester aTester( mpDoc, rMarkData );
if( !aTester.IsEditable() )
{
mpViewShell->ErrorMessage( aTester.GetMessageId() );
return;
}
}
break;
// edit mode exited, see TODO above
// case SC_SELECTTYPE_EDITCELL:
// break;
default:
DBG_ERRORFILE( "ScSpellDialogChildWindow::Init - unknown selection type" );
}
mbOldIdleDisabled = mpDoc->IsIdleDisabled();
mpDoc->DisableIdle( TRUE ); // #42726# stop online spelling
// *** create Undo/Redo documents *** -------------------------------------
mxUndoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
mxUndoDoc->InitUndo( mpDoc, nTab, nTab );
mxRedoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
mxRedoDoc->InitUndo( mpDoc, nTab, nTab );
if ( rMarkData.GetSelectCount() > 1 )
{
SCTAB nTabCount = mpDoc->GetTableCount();
for( SCTAB nOtherTab = 0; nOtherTab < nTabCount; ++nOtherTab )
{
if( rMarkData.GetTableSelect( nOtherTab ) && (nOtherTab != nTab) )
{
mxUndoDoc->AddUndoTab( nOtherTab, nOtherTab );
mxRedoDoc->AddUndoTab( nOtherTab, nOtherTab );
}
}
}
// *** create and init the edit engine *** --------------------------------
mxEngine.reset( new ScSpellingEngine(
mpDoc->GetEnginePool(), *mpViewData, mxUndoDoc.get(), mxRedoDoc.get(), LinguMgr::GetSpellChecker() ) );
mxEngine->SetRefDevice( mpViewData->GetActiveWin() );
mpViewShell->MakeEditView( mxEngine.get(), nCol, nRow );
EditView* pEditView = mpViewData->GetEditView( mpViewData->GetActivePart() );
mpViewData->SetSpellingView( pEditView );
Rectangle aRect( Point( 0, 0 ), Point( 0, 0 ) );
pEditView->SetOutputArea( aRect );
mxEngine->SetControlWord( EE_CNTRL_USECHARATTRIBS );
mxEngine->EnableUndo( FALSE );
mxEngine->SetPaperSize( aRect.GetSize() );
mxEngine->SetText( EMPTY_STRING );
mxEngine->ClearModifyFlag();
mbNeedNextObj = true;
}
bool ScSpellDialogChildWindow::IsSelectionChanged()
{
if( !mxOldSel.get() || !mpViewShell || (mpViewShell != PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) )
return true;
if( EditView* pEditView = mpViewData->GetSpellingView() )
if( pEditView->GetEditEngine() != mxEngine.get() )
return true;
ScSelectionState aNewSel( *mpViewData );
return mxOldSel->GetSheetSelection() != aNewSel.GetSheetSelection();
}
// ============================================================================
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.146); FILE MERGED 2005/09/05 15:09:40 rt 1.3.146.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: spelldialog.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:05:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_SPELLDIALOG_HXX
#include "spelldialog.hxx"
#endif
#include <sfx2/app.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <svx/svxids.hrc>
#include <svx/editstat.hxx>
#include <svx/editview.hxx>
#include <svx/unolingu.hxx>
#ifndef SC_SELECTIONSTATE_HXX
#include "selectionstate.hxx"
#endif
#include "spelleng.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"
#include "scmod.hxx"
#include "editable.hxx"
#include "undoblk.hxx"
// ============================================================================
SFX_IMPL_CHILDWINDOW( ScSpellDialogChildWindow, SID_SPELL_DIALOG )
ScSpellDialogChildWindow::ScSpellDialogChildWindow( Window* pParent, USHORT nId,
SfxBindings* pBindings, SfxChildWinInfo* pInfo ) :
::svx::SpellDialogChildWindow( pParent, nId, pBindings, pInfo ),
mpViewShell( 0 ),
mpViewData( 0 ),
mpDocShell( 0 ),
mpDoc( 0 ),
mbNeedNextObj( false ),
mbOldIdleDisabled( false )
{
Init();
}
ScSpellDialogChildWindow::~ScSpellDialogChildWindow()
{
Reset();
}
SfxChildWinInfo ScSpellDialogChildWindow::GetInfo() const
{
return ::svx::SpellDialogChildWindow::GetInfo();
}
void ScSpellDialogChildWindow::InvalidateSpellDialog()
{
::svx::SpellDialogChildWindow::InvalidateSpellDialog();
}
// protected ------------------------------------------------------------------
::svx::SpellPortions ScSpellDialogChildWindow::GetNextWrongSentence()
{
::svx::SpellPortions aPortions;
if( mxEngine.get() && mpViewData )
{
if( EditView* pEditView = mpViewData->GetSpellingView() )
{
// edit engine handles cell iteration internally
do
{
if( mbNeedNextObj )
mxEngine->SpellNextDocument();
mbNeedNextObj = !mxEngine->IsFinished() && !mxEngine->SpellSentence( *pEditView, aPortions );
}
while( mbNeedNextObj );
}
// finished? - close the spelling dialog
if( mxEngine->IsFinished() )
GetBindings().GetDispatcher()->Execute( SID_SPELL_DIALOG, SFX_CALLMODE_ASYNCHRON );
}
return aPortions;
}
void ScSpellDialogChildWindow::ApplyChangedSentence( const ::svx::SpellPortions& rChanged )
{
if( mxEngine.get() && mpViewData )
if( EditView* pEditView = mpViewData->GetSpellingView() )
mxEngine->ApplyChangedSentence( *pEditView, rChanged );
}
void ScSpellDialogChildWindow::GetFocus()
{
if( IsSelectionChanged() )
{
Reset();
InvalidateSpellDialog();
Init();
}
}
void ScSpellDialogChildWindow::LoseFocus()
{
}
// private --------------------------------------------------------------------
void ScSpellDialogChildWindow::Reset()
{
if( mpViewShell && (mpViewShell == PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) )
{
if( mxEngine.get() && mxEngine->IsAnyModified() )
{
const ScAddress& rCursor = mxOldSel->GetCellCursor();
SCTAB nTab = rCursor.Tab();
SCCOL nOldCol = rCursor.Col();
SCROW nOldRow = rCursor.Row();
SCCOL nNewCol = mpViewData->GetCurX();
SCROW nNewRow = mpViewData->GetCurY();
mpDocShell->GetUndoManager()->AddUndoAction( new ScUndoConversion(
mpDocShell, mpViewData->GetMarkData(),
nOldCol, nOldRow, nTab, mxUndoDoc.release(),
nNewCol, nNewRow, nTab, mxRedoDoc.release(),
ScConversionParam( SC_CONVERSION_SPELLCHECK ) ) );
mpDoc->SetDirty();
mpDocShell->SetDocumentModified();
}
mpViewData->SetSpellingView( 0 );
mpViewShell->KillEditView( TRUE );
mpDocShell->PostPaintGridAll();
mpViewShell->UpdateInputHandler();
mpDoc->DisableIdle( mbOldIdleDisabled );
}
mxEngine.reset();
mxUndoDoc.reset();
mxRedoDoc.reset();
mxOldSel.reset();
mpViewShell = 0;
mpViewData = 0;
mpDocShell = 0;
mpDoc = 0;
mbNeedNextObj = false;
mbOldIdleDisabled = false;
}
void ScSpellDialogChildWindow::Init()
{
if( mpViewShell )
return;
if( (mpViewShell = PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) == 0 )
return;
mpViewData = mpViewShell->GetViewData();
// exit edit mode - TODO support spelling in edit mode
if( mpViewData->HasEditView( mpViewData->GetActivePart() ) )
SC_MOD()->InputEnterHandler();
mxOldSel.reset( new ScSelectionState( *mpViewData ) );
mpDocShell = mpViewData->GetDocShell();
mpDoc = mpDocShell->GetDocument();
const ScAddress& rCursor = mxOldSel->GetCellCursor();
SCCOL nCol = rCursor.Col();
SCROW nRow = rCursor.Row();
SCTAB nTab = rCursor.Tab();
ScMarkData& rMarkData = mpViewData->GetMarkData();
rMarkData.MarkToMulti();
switch( mxOldSel->GetSelectionType() )
{
case SC_SELECTTYPE_NONE:
case SC_SELECTTYPE_SHEET:
{
// test if there is something editable
ScEditableTester aTester( mpDoc, rMarkData );
if( !aTester.IsEditable() )
{
mpViewShell->ErrorMessage( aTester.GetMessageId() );
return;
}
}
break;
// edit mode exited, see TODO above
// case SC_SELECTTYPE_EDITCELL:
// break;
default:
DBG_ERRORFILE( "ScSpellDialogChildWindow::Init - unknown selection type" );
}
mbOldIdleDisabled = mpDoc->IsIdleDisabled();
mpDoc->DisableIdle( TRUE ); // #42726# stop online spelling
// *** create Undo/Redo documents *** -------------------------------------
mxUndoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
mxUndoDoc->InitUndo( mpDoc, nTab, nTab );
mxRedoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
mxRedoDoc->InitUndo( mpDoc, nTab, nTab );
if ( rMarkData.GetSelectCount() > 1 )
{
SCTAB nTabCount = mpDoc->GetTableCount();
for( SCTAB nOtherTab = 0; nOtherTab < nTabCount; ++nOtherTab )
{
if( rMarkData.GetTableSelect( nOtherTab ) && (nOtherTab != nTab) )
{
mxUndoDoc->AddUndoTab( nOtherTab, nOtherTab );
mxRedoDoc->AddUndoTab( nOtherTab, nOtherTab );
}
}
}
// *** create and init the edit engine *** --------------------------------
mxEngine.reset( new ScSpellingEngine(
mpDoc->GetEnginePool(), *mpViewData, mxUndoDoc.get(), mxRedoDoc.get(), LinguMgr::GetSpellChecker() ) );
mxEngine->SetRefDevice( mpViewData->GetActiveWin() );
mpViewShell->MakeEditView( mxEngine.get(), nCol, nRow );
EditView* pEditView = mpViewData->GetEditView( mpViewData->GetActivePart() );
mpViewData->SetSpellingView( pEditView );
Rectangle aRect( Point( 0, 0 ), Point( 0, 0 ) );
pEditView->SetOutputArea( aRect );
mxEngine->SetControlWord( EE_CNTRL_USECHARATTRIBS );
mxEngine->EnableUndo( FALSE );
mxEngine->SetPaperSize( aRect.GetSize() );
mxEngine->SetText( EMPTY_STRING );
mxEngine->ClearModifyFlag();
mbNeedNextObj = true;
}
bool ScSpellDialogChildWindow::IsSelectionChanged()
{
if( !mxOldSel.get() || !mpViewShell || (mpViewShell != PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) )
return true;
if( EditView* pEditView = mpViewData->GetSpellingView() )
if( pEditView->GetEditEngine() != mxEngine.get() )
return true;
ScSelectionState aNewSel( *mpViewData );
return mxOldSel->GetSheetSelection() != aNewSel.GetSheetSelection();
}
// ============================================================================
<|endoftext|> |
<commit_before>#include <iostream> // std::cout ...
#include "logMsg.h" // lmInit, LM_*
#include "coreTracelevels.h" // LMT_*
#include "Message.h" // Message
#include "Macros.h" // EXIT, ...
#include "Packet.h" // ss::Packet
#include "Network.h" // NetworkInterface
#include "Endpoint.h" // Endpoint
#include "CommandLine.h" // CommandLine
#include "ProcessAssistant.h" // ProcessAssistant
#include "SamsonWorker.h" // Own interfce
#include "EndpointMgr.h" // ss::EndpointMgr
#include "SamsonSetup.h" // ss::SamsonSetup
#include "Format.h" // au::Format
#include "MemoryManager.h" // ss::SharedMemory
#include "FileManager.h" // ss::FileManager
namespace ss {
/* ****************************************************************************
*
* Constructor
*/
SamsonWorker::SamsonWorker(char* controller, char* alias, unsigned short port, int workers, int endpoints) : taskManager(this) , dataBuffer(this), loadDataManager(this)
{
this->controller = controller;
this->alias = alias;
this->port = port;
this->workers = workers;
this->endpoints = endpoints;
// Define the number of process
num_processes = SamsonSetup::shared()->num_processes;
srand( (unsigned int) time(NULL) );
}
/* ****************************************************************************
*
* endpointMgrSet -
*/
void SamsonWorker::endpointMgrSet(ss::EndpointMgr* _epMgr)
{
epMgr = _epMgr;
// epMgr->init(Endpoint::Worker, alias.c_str(), port, controller.c_str());
// epMgr->packetReceiverSet(this);
}
/* ****************************************************************************
*
* networkSet -
*/
void SamsonWorker::networkSet(NetworkInterface* network)
{
this->network = network;
network->setPacketReceiverInterface(this);
network->init(Endpoint::Worker, alias.c_str(), port, controller.c_str());
// Get my id as worker
myWorkerId = network->getWorkerFromIdentifier(network->getMyidentifier());
this->workers = network->getNumWorkers();
// This is only necessary when running multiple samsonworkers as separated process in the same machine
// MemoryManager::shared()->setOtherSharedMemoryAsMarked( myWorkerId , workers );
}
/* ****************************************************************************
*
* run -
*/
void SamsonWorker::run()
{
workerStatus(&status);
// //////////////////////////////////////////////////////////////////////
//
// Create one ProcessAssistant per core
//
if (num_processes == -1)
LM_X(1, ("Invalid number of cores. Please edit /opt/samson/setup.txt"));
LM_T(LMT_WINIT, ("initializing %d process assistants", num_processes));
processAssistant = (ProcessAssistant**) calloc(num_processes, sizeof(ProcessAssistant*));
if (processAssistant == NULL)
LM_XP(1, ("calloc(%d, %d)", num_processes, sizeof(ProcessAssistant*)));
int coreId;
for (coreId = 0; coreId < num_processes ; coreId++)
{
// Fake id to debig locally multiple workers
int fake_core_id = myWorkerId * workers + coreId;
processAssistant[coreId] = new ProcessAssistant(fake_core_id, this);
}
LM_T(LMT_WINIT, ("Got %d process assistants", coreId));
// assert(epMgr);
// epMgr->run();
assert(network);
network->run();
}
#if 0
void SamsonWorker::sendWorkerStatus()
{
Packet *p = new Packet();
network::WorkerStatus* w = p->message.mutable_worker_status();
// Fill with all data related to data
data.fillWorkerStatus(w);
// Fill to all data related with task manager
taskManager.fillWorkerStatus(w);
network->send(this, network->controllerGetIdentifier(), Message::WorkerStatus, NULL, 0, p);
}
#endif
int SamsonWorker::receive(int fromId, Message::MessageCode msgCode, Packet* packet)
{
if (msgCode == Message::StatusRequest)
{
Packet* p = new Packet();
network::StatusResponse *response = p->message.mutable_status_response();
response->set_title( "Worker " + au::Format::string( network->getWorkerFromIdentifier( network->getMyidentifier() ) ) );
response->set_senderid( packet->message.status_request().senderid() ) ;
response->set_response( getStatus( packet->message.status_request().command() ) );
network->send(this, network->controllerGetIdentifier() , Message::StatusResponse, p);
return 0;
}
if (msgCode == Message::WorkerTask)
{
// A packet with a particular command is received (controller expect to send a confirmation message)
LM_T(LMT_TASK, ("Got a WorkerTask message"));
// add task to the task manager
taskManager.addTask( packet->message.worker_task() );
return 0;
}
// Load data files to be latter confirmed to controller
if (msgCode == Message::UploadData)
{
std::ostringstream fileName;
fileName << "/tmp/file_"<< getpid() << "_" << rand() << rand(); // Just to test
loadDataManager.addUploadItem(fromId, packet->message.upload_data(), packet->message.delilah_id() , packet->buffer );
return 0;
}
// Download data files
if (msgCode == Message::DownloadData)
{
loadDataManager.addDownloadItem(fromId, packet->message.download_data() , packet->message.delilah_id() );
return 0;
}
/**
Data packets go directly to the DataBuffer to be joined and flushed to disk
DataManager is notifyed when created a new file or finish everything
*/
if( msgCode == Message::WorkerDataExchange )
{
// New data packet for a particular queue inside a particular task environment
size_t task_id = packet->message.data().task_id();
network::Queue queue = packet->message.data().queue();
dataBuffer.addBuffer(task_id, queue, packet->buffer );
return 0;
}
/**
Data Close message is sent to notify that no more data will be generated
We have to wait for "N" messages ( one per worker )
*/
if( msgCode == Message::WorkerDataExchangeClose )
{
size_t task_id = packet->message.data_close().task_id();
dataBuffer.finishWorker( task_id );
return 0;
}
return 0;
}
std::string SamsonWorker::getStatus(std::string command)
{
std::ostringstream output;
output << "** Memory: " << MemoryManager::shared()->getStatus() << std::endl;
output << "** TaskManager:\n";
output << taskManager.getStatus();
output << "** ProcessAssistants: (" << num_processes << " process):\n";
for (int i = 0 ; i < num_processes ; i++)
output << "\t" << processAssistant[i]->getStatus() << std::endl;
output << "** DataBuffer:\n";
output << dataBuffer.getStatus();
output << "** LoadManager:\n";
output << loadDataManager.getStatus();
output << "** File Manager:\n";
output << FileManager::shared()->getStatus();
output << "** Network status:\n";
output << network->getState("");
return output.str();
}
}
<commit_msg>traces<commit_after>#include <iostream> // std::cout ...
#include "logMsg.h" // lmInit, LM_*
#include "coreTracelevels.h" // LMT_*
#include "Message.h" // Message
#include "Macros.h" // EXIT, ...
#include "Packet.h" // ss::Packet
#include "Network.h" // NetworkInterface
#include "Endpoint.h" // Endpoint
#include "CommandLine.h" // CommandLine
#include "ProcessAssistant.h" // ProcessAssistant
#include "SamsonWorker.h" // Own interfce
#include "EndpointMgr.h" // ss::EndpointMgr
#include "SamsonSetup.h" // ss::SamsonSetup
#include "Format.h" // au::Format
#include "MemoryManager.h" // ss::SharedMemory
#include "FileManager.h" // ss::FileManager
namespace ss {
/* ****************************************************************************
*
* Constructor
*/
SamsonWorker::SamsonWorker(char* controller, char* alias, unsigned short port, int workers, int endpoints) : taskManager(this) , dataBuffer(this), loadDataManager(this)
{
this->controller = controller;
this->alias = alias;
this->port = port;
this->workers = workers;
this->endpoints = endpoints;
// Define the number of process
num_processes = SamsonSetup::shared()->num_processes;
srand( (unsigned int) time(NULL) );
}
/* ****************************************************************************
*
* endpointMgrSet -
*/
void SamsonWorker::endpointMgrSet(ss::EndpointMgr* _epMgr)
{
epMgr = _epMgr;
// epMgr->init(Endpoint::Worker, alias.c_str(), port, controller.c_str());
// epMgr->packetReceiverSet(this);
}
/* ****************************************************************************
*
* networkSet -
*/
void SamsonWorker::networkSet(NetworkInterface* network)
{
this->network = network;
network->setPacketReceiverInterface(this);
network->init(Endpoint::Worker, alias.c_str(), port, controller.c_str());
// Get my id as worker
myWorkerId = network->getWorkerFromIdentifier(network->getMyidentifier());
this->workers = network->getNumWorkers();
// This is only necessary when running multiple samsonworkers as separated process in the same machine
// MemoryManager::shared()->setOtherSharedMemoryAsMarked( myWorkerId , workers );
}
/* ****************************************************************************
*
* run -
*/
void SamsonWorker::run()
{
workerStatus(&status);
// //////////////////////////////////////////////////////////////////////
//
// Create one ProcessAssistant per core
//
if (num_processes == -1)
LM_X(1, ("Invalid number of cores. Please edit /opt/samson/setup.txt"));
LM_T(LMT_WINIT, ("initializing %d process assistants", num_processes));
processAssistant = (ProcessAssistant**) calloc(num_processes, sizeof(ProcessAssistant*));
if (processAssistant == NULL)
LM_XP(1, ("calloc(%d, %d)", num_processes, sizeof(ProcessAssistant*)));
int coreId;
for (coreId = 0; coreId < num_processes ; coreId++)
{
// Fake id to debig locally multiple workers
int fake_core_id = myWorkerId * workers + coreId;
processAssistant[coreId] = new ProcessAssistant(fake_core_id, this);
}
LM_T(LMT_WINIT, ("Got %d process assistants", coreId));
// assert(epMgr);
// epMgr->run();
assert(network);
network->run();
}
#if 0
void SamsonWorker::sendWorkerStatus()
{
Packet *p = new Packet();
network::WorkerStatus* w = p->message.mutable_worker_status();
// Fill with all data related to data
data.fillWorkerStatus(w);
// Fill to all data related with task manager
taskManager.fillWorkerStatus(w);
network->send(this, network->controllerGetIdentifier(), Message::WorkerStatus, NULL, 0, p);
}
#endif
int SamsonWorker::receive(int fromId, Message::MessageCode msgCode, Packet* packet)
{
if (msgCode == Message::StatusRequest)
{
LM_M(("Here"));
Packet* p = new Packet();
LM_M(("Here"));
network::StatusResponse *response = p->message.mutable_status_response();
LM_M(("Here"));
response->set_title( "Worker " + au::Format::string( network->getWorkerFromIdentifier( network->getMyidentifier() ) ) );
LM_M(("Here"));
response->set_senderid( packet->message.status_request().senderid() ) ;
LM_M(("Here"));
response->set_response( getStatus( packet->message.status_request().command() ) );
LM_M(("Here"));
network->send(this, network->controllerGetIdentifier() , Message::StatusResponse, p);
LM_M(("Here"));
return 0;
}
if (msgCode == Message::WorkerTask)
{
// A packet with a particular command is received (controller expect to send a confirmation message)
LM_T(LMT_TASK, ("Got a WorkerTask message"));
// add task to the task manager
taskManager.addTask( packet->message.worker_task() );
return 0;
}
// Load data files to be latter confirmed to controller
if (msgCode == Message::UploadData)
{
std::ostringstream fileName;
fileName << "/tmp/file_"<< getpid() << "_" << rand() << rand(); // Just to test
loadDataManager.addUploadItem(fromId, packet->message.upload_data(), packet->message.delilah_id() , packet->buffer );
return 0;
}
// Download data files
if (msgCode == Message::DownloadData)
{
loadDataManager.addDownloadItem(fromId, packet->message.download_data() , packet->message.delilah_id() );
return 0;
}
/**
Data packets go directly to the DataBuffer to be joined and flushed to disk
DataManager is notifyed when created a new file or finish everything
*/
if( msgCode == Message::WorkerDataExchange )
{
// New data packet for a particular queue inside a particular task environment
size_t task_id = packet->message.data().task_id();
network::Queue queue = packet->message.data().queue();
dataBuffer.addBuffer(task_id, queue, packet->buffer );
return 0;
}
/**
Data Close message is sent to notify that no more data will be generated
We have to wait for "N" messages ( one per worker )
*/
if( msgCode == Message::WorkerDataExchangeClose )
{
size_t task_id = packet->message.data_close().task_id();
dataBuffer.finishWorker( task_id );
return 0;
}
return 0;
}
std::string SamsonWorker::getStatus(std::string command)
{
std::ostringstream output;
output << "** Memory: " << MemoryManager::shared()->getStatus() << std::endl;
output << "** TaskManager:\n";
output << taskManager.getStatus();
output << "** ProcessAssistants: (" << num_processes << " process):\n";
for (int i = 0 ; i < num_processes ; i++)
output << "\t" << processAssistant[i]->getStatus() << std::endl;
output << "** DataBuffer:\n";
output << dataBuffer.getStatus();
output << "** LoadManager:\n";
output << loadDataManager.getStatus();
output << "** File Manager:\n";
output << FileManager::shared()->getStatus();
output << "** Network status:\n";
output << network->getState("");
return output.str();
}
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef NDK_COMPONENTS_CONSTRAINTCOMPONENT2D_HPP
#define NDK_COMPONENTS_CONSTRAINTCOMPONENT2D_HPP
#include <NDK/Component.hpp>
#include <Nazara/Physics2D/Constraint2D.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <vector>
#include <memory>
namespace Ndk
{
class NDK_API ConstraintComponent2D : public Component<ConstraintComponent2D>
{
public:
ConstraintComponent2D() = default;
ConstraintComponent2D(const ConstraintComponent2D& joint) = default;
ConstraintComponent2D(ConstraintComponent2D&& joint) = default;
template<typename T, typename... Args> inline Nz::ObjectRef<T> CreateConstraint(const Ndk::EntityHandle first, const Ndk::EntityHandle second, Args&&... args);
static ComponentIndex componentIndex;
private:
std::vector<Nz::Constraint2DRef> m_constraints;
};
}
#include <NDK/Components/ConstraintComponent2D.inl>
#endif// NDK_COMPONENTS_CONSTRAINTCOMPONENT2D_HPP
<commit_msg>Fix compilation for good<commit_after>#pragma once
#ifndef NDK_COMPONENTS_CONSTRAINTCOMPONENT2D_HPP
#define NDK_COMPONENTS_CONSTRAINTCOMPONENT2D_HPP
#include <NDK/Component.hpp>
#include <Nazara/Physics2D/Constraint2D.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <vector>
#include <memory>
namespace Ndk
{
class NDK_API ConstraintComponent2D : public Component<ConstraintComponent2D>
{
public:
ConstraintComponent2D() = default;
ConstraintComponent2D(const ConstraintComponent2D& joint) = default;
ConstraintComponent2D(ConstraintComponent2D&& joint) = default;
template<typename T, typename... Args> inline Nz::ObjectRef<T> CreateConstraint(const Ndk::EntityHandle& first, const Ndk::EntityHandle& second, Args&&... args);
static ComponentIndex componentIndex;
private:
std::vector<Nz::Constraint2DRef> m_constraints;
};
}
#include <NDK/Components/ConstraintComponent2D.inl>
#endif// NDK_COMPONENTS_CONSTRAINTCOMPONENT2D_HPP
<|endoftext|> |
<commit_before>#include "ShaderMacro.h"
using namespace Rendering::Shader;
ShaderMacro::ShaderMacro() : _name(""), _definition("")
{
}
ShaderMacro::ShaderMacro(const std::string& name, const std::string& definition)
: _name(name), _definition(definition)
{
}<commit_msg>Delete ShaderMacro.cpp<commit_after><|endoftext|> |
<commit_before>//
// C++ Implementation: conferencetask
//
// Description:
//
//
// Author: SUSE AG (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "conferencetask.h"
ConferenceTask::ConferenceTask( Task* parent )
: EventTask( parent )
{
// register all the events that this task monitors
registerEvent( EventTransfer::ConferenceClosed );
registerEvent( EventTransfer::ConferenceJoined );
registerEvent( EventTransfer::ConferenceLeft );
registerEvent( EventTransfer::ReceiveMessage );
registerEvent( EventTransfer::UserTyping );
registerEvent( EventTransfer::UserNotTyping );
registerEvent( EventTransfer::ConferenceInvite );
registerEvent( EventTransfer::ConferenceInviteNotify );
registerEvent( EventTransfer::ConferenceReject );
registerEvent( EventTransfer::ReceiveAutoReply );
}
ConferenceTask::~ConferenceTask()
{
}
void dumpConferenceEvent( ConferenceEvent & evt )
{
qDebug( "Conference Event - guid: %s user: %s timestamp: %i:%i:%i flags: %08x\n",
evt.guid.ascii(), evt.user.ascii(), evt.timeStamp.hour(), evt.timeStamp.minute(), evt.timeStamp.second(), evt.flags );
}
bool ConferenceTask::take( Transfer * transfer )
{
EventTransfer * incomingEvent;
if ( forMe( transfer, incomingEvent ) )
{
qDebug( "Got a status change!" );
QDataStream din( incomingEvent->payload(), IO_ReadOnly);
din.setByteOrder( QDataStream::LittleEndian );
ConferenceEvent event;
event.timeStamp = incomingEvent->timeStamp();
event.user = incomingEvent->source();
event.flags = 0;
// read the conference guid
uint val;
char* rawData;
din.readBytes( rawData, val );
if ( val ) // val is 0 if there is no status text
event.guid = QString::fromUtf8( rawData, val );
//else
// set error protocolError
Message m;
switch ( incomingEvent->event() )
{
case EventTransfer::ConferenceClosed:
qDebug( "ConferenceClosed" );
dumpConferenceEvent( event );
emit closed( event );
break;
case EventTransfer::ConferenceJoined:
event.flags = readFlags( din );
qDebug( "ConferenceJoined" );
dumpConferenceEvent( event );
emit joined( event );
break;
case EventTransfer::ConferenceLeft:
event.flags = readFlags( din );
qDebug( "ConferenceLeft" );
dumpConferenceEvent( event );
emit left( event );
break;
case EventTransfer::ReceiveMessage:
event.flags = readFlags( din );
m = readMessage( din );
qDebug( "ReceiveMessage" );
dumpConferenceEvent( event );
qDebug( "message: %s\n", m.ascii() );
emit message( event, m );
break;
case EventTransfer::UserTyping:
qDebug( "UserTyping" );
dumpConferenceEvent( event );
emit typing( event );
break;
case EventTransfer::UserNotTyping:
qDebug( "UserNotTyping" );
dumpConferenceEvent( event );
emit notTyping( event );
break;
case EventTransfer::ConferenceInvite:
m = readMessage( din );
qDebug( "ConferenceInvite" );
dumpConferenceEvent( event );
qDebug( "message: %s\n", m.ascii() );
emit invited( event, m );
break;
case EventTransfer::ConferenceInviteNotify:
qDebug( "ConferenceInviteNotify" );
dumpConferenceEvent( event );
emit otherInvited( event );
break;
case EventTransfer::ConferenceReject:
qDebug( "ConferenceReject" );
dumpConferenceEvent( event );
emit invitationRejected( event );
break;
case EventTransfer::ReceiveAutoReply:
event.flags = readFlags( din );
m = readMessage( din );
qDebug( "ReceiveAutoReply" );
dumpConferenceEvent( event );
qDebug( "message: %s\n", m.ascii() );
emit autoReply( event, m );
break;
default:
qDebug( "WARNING: didn't handle registered event %i, on conference %s\n", incomingEvent->event(), event.guid.ascii() );
}
return true;
}
return false;
}
Q_UINT32 ConferenceTask::readFlags( QDataStream & din )
{
Q_UINT32 flags;
/*if ( din.atEnd()
; //set error
else*/
din >> flags;
return flags;
}
QString ConferenceTask::readMessage( QDataStream & din )
{
QString message;
uint val;
char* rawData;
din.readBytes( rawData, val );
if ( val ) // val is 0 if there is no status text
message = QString::fromUtf8( rawData, val );
// else
// seterror
return message;
}
#include "conferencetask.moc"
<commit_msg>Error handling for conference tasks<commit_after>//
// C++ Implementation: conferencetask
//
// Description:
//
//
// Author: SUSE AG (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "conferencetask.h"
ConferenceTask::ConferenceTask( Task* parent )
: EventTask( parent )
{
// register all the events that this task monitors
registerEvent( EventTransfer::ConferenceClosed );
registerEvent( EventTransfer::ConferenceJoined );
registerEvent( EventTransfer::ConferenceLeft );
registerEvent( EventTransfer::ReceiveMessage );
registerEvent( EventTransfer::UserTyping );
registerEvent( EventTransfer::UserNotTyping );
registerEvent( EventTransfer::ConferenceInvite );
registerEvent( EventTransfer::ConferenceInviteNotify );
registerEvent( EventTransfer::ConferenceReject );
registerEvent( EventTransfer::ReceiveAutoReply );
}
ConferenceTask::~ConferenceTask()
{
}
void dumpConferenceEvent( ConferenceEvent & evt )
{
qDebug( "Conference Event - guid: %s user: %s timestamp: %i:%i:%i flags: %08x\n",
evt.guid.ascii(), evt.user.ascii(), evt.timeStamp.hour(), evt.timeStamp.minute(), evt.timeStamp.second(), evt.flags );
}
bool ConferenceTask::take( Transfer * transfer )
{
EventTransfer * incomingEvent;
if ( forMe( transfer, incomingEvent ) )
{
qDebug( "Got a status change!" );
QDataStream din( incomingEvent->payload(), IO_ReadOnly);
din.setByteOrder( QDataStream::LittleEndian );
ConferenceEvent event;
event.timeStamp = incomingEvent->timeStamp();
event.user = incomingEvent->source();
event.flags = 0;
// read the conference guid
uint val;
char* rawData;
din.readBytes( rawData, val );
if ( val ) // val is 0 if there is no status text
event.guid = QString::fromUtf8( rawData, val );
//else
// set error protocolError
Message m;
switch ( incomingEvent->event() )
{
case EventTransfer::ConferenceClosed:
qDebug( "ConferenceClosed" );
dumpConferenceEvent( event );
emit closed( event );
break;
case EventTransfer::ConferenceJoined:
event.flags = readFlags( din );
qDebug( "ConferenceJoined" );
dumpConferenceEvent( event );
emit joined( event );
break;
case EventTransfer::ConferenceLeft:
event.flags = readFlags( din );
qDebug( "ConferenceLeft" );
dumpConferenceEvent( event );
emit left( event );
break;
case EventTransfer::ReceiveMessage:
event.flags = readFlags( din );
m = readMessage( din );
qDebug( "ReceiveMessage" );
dumpConferenceEvent( event );
qDebug( "message: %s\n", m.ascii() );
emit message( event, m );
break;
case EventTransfer::UserTyping:
qDebug( "UserTyping" );
dumpConferenceEvent( event );
emit typing( event );
break;
case EventTransfer::UserNotTyping:
qDebug( "UserNotTyping" );
dumpConferenceEvent( event );
emit notTyping( event );
break;
case EventTransfer::ConferenceInvite:
m = readMessage( din );
qDebug( "ConferenceInvite" );
dumpConferenceEvent( event );
qDebug( "message: %s\n", m.ascii() );
emit invited( event, m );
break;
case EventTransfer::ConferenceInviteNotify:
qDebug( "ConferenceInviteNotify" );
dumpConferenceEvent( event );
emit otherInvited( event );
break;
case EventTransfer::ConferenceReject:
qDebug( "ConferenceReject" );
dumpConferenceEvent( event );
emit invitationRejected( event );
break;
case EventTransfer::ReceiveAutoReply:
event.flags = readFlags( din );
m = readMessage( din );
qDebug( "ReceiveAutoReply" );
dumpConferenceEvent( event );
qDebug( "message: %s\n", m.ascii() );
emit autoReply( event, m );
break;
default:
qDebug( "WARNING: didn't handle registered event %i, on conference %s\n", incomingEvent->event(), event.guid.ascii() );
}
return true;
}
return false;
}
Q_UINT32 ConferenceTask::readFlags( QDataStream & din )
{
Q_UINT32 flags;
if ( din.atEnd() )
{
setError( GroupWise::Protocol );
return 0;
}
else
{
din >> flags;
return flags;
}
}
QString ConferenceTask::readMessage( QDataStream & din )
{
QString message;
uint val;
char* rawData;
din.readBytes( rawData, val );
if ( val ) // val is 0 if there is no status text
message = QString::fromUtf8( rawData, val );
else
setError( GroupWise::Protocol );
return message;
}
#include "conferencetask.moc"
<|endoftext|> |
<commit_before>/**
Copyright (c) 2013, Philip Deegan.
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 Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_TEST_HPP_
#define _KUL_TEST_HPP_
#include "kul/os.hpp"
#include "kul/cli.hpp"
#include "kul/ipc.hpp"
#include "kul/log.hpp"
#include "kul/math.hpp"
#include "kul/proc.hpp"
#include "kul/time.hpp"
#include "kul/signal.hpp"
#include "kul/string.hpp"
#include "kul/wstring.hpp"
#include "kul/threads.hpp"
#include <iomanip>
namespace kul {
class TestThreadObject{
private:
int i;
public:
TestThreadObject() : i(0){}
void print(){ KLOG(INF) << "i = " << i;}
friend class kul::ThreadCopy<TestThreadObject>;
friend class kul::ThreadRef<TestThreadObject>;
protected:
void operator()(){
KLOG(INF) << "THREAD RUNNING";
i++;
KLOG(INF) << "THREAD FINISHED";
}
public:
void operator()() const {
KLOG(INF) << "CONST THREAD RUNNING";
KLOG(INF) << "CONST THREAD FINISHED";
}
};
class TestThreadQueueObject{
protected:
int i;
Mutex& mutex;
public:
TestThreadQueueObject(Mutex& mutex) : i(0), mutex(mutex){}
void operator()(){
kul::ScopeLock lock(mutex);
KLOG(INF) << "THREAD RUNNING";
i++;
KLOG(INF) << "THREAD FINISHED";
}
void print(){ KLOG(INF) << "i = " << i;}
};
class TestThreadQueueQObject : public TestThreadQueueObject{
private:
std::queue<int>& q;
public:
TestThreadQueueQObject(Mutex& mutex, std::queue<int>& q) : TestThreadQueueObject(mutex), q(q){}
void operator()(){
kul::ScopeLock lock(mutex);
KLOG(INF) << "THREAD RUNNING";
i++;
q.pop();
KLOG(INF) << "THREAD FINISHED";
}
void print(){ KLOG(INF) << "i = " << i;}
};
class TestIPCServer : public kul::ipc::Server{
public:
TestIPCServer() : kul::ipc::Server("uuid", 1){} // UUID CHECKS ONCE
void handle(const std::string& s){
KLOG(INF) << "TestIPCServer " << s;
}
void operator()(){
listen();
}
};
class TestIPC{
public:
void run(){
TestIPCServer ipc;
kul::Ref<TestIPCServer> ref(ipc);
kul::Thread t(ref);
t.run();
kul::this_thread::sleep(1000);
kul::ipc::Client("uuid").send("TestIPCClient");
t.join();
}
};
class Catch{
public:
void print(const int16_t& s){
KOUT(NON) << "SEGMENTATION FAULT INTERCEPTED";
KOUT(NON) << "PRINT STACKTRACE";
}
};
class Test{
private:
const std::string s;
public:
Test() : s("LAMBDAS ALLOWED IN SIGNAL"){
Catch c;
kul::Signal sig; // Windows: each thread requires own handler, static singleton otherwise so only ever one.
sig.segv(std::bind(&Catch::print, std::ref(c), std::placeholders::_1)); // Vector of functions to call before exiting - CAUTION! KEEP SIMPLE!
sig.segv([this](int16_t){ KOUT(NON) << s; }); // Allows lamda notation
KERR << "KERR";
KOUT(NON) << "KOUT(NON)";
KOUT(INF) << "KOUT(INF)";
KOUT(ERR) << "KOUT(ERR)";
KOUT(DBG) << "KOUT(DBG)";
KLOG(INF) << "KLOG(INF)";
KLOG(ERR) << "KLOG(ERR)";
KLOG(DBG) << "KLOG(DBG)";
KOUT(NON) << kul::Dir::SEP();
KOUT(NON) << kul::env::SEP();
KOUT(NON) << kul::env::CWD();
KOUT(NON) << kul::os::userDir().path();
KLOG(INF) << kul::os::userAppDir("maiken").path();
for(const kul::Dir& d : kul::Dir(kul::env::CWD()).dirs())
for(const kul::File& f : d.files())
KOUT(NON) << d.join(f.name()); // or f.full()
try{
kul::Process("echo").arg("Hello").arg("World").start();
}catch(const kul::proc::Exception& e){
KERR << e.debug()<< " : " << typeid(e).name();
KERR << "Error expected on windows without echo on path";
}
for(const std::string& arg : kul::cli::asArgs("/path/to \"words in quotes\" words\\ not\\ in\\ quotes end"))
KOUT(NON) << "ARG: " << arg;
for(const std::string& arg : kul::String::split("split - by - char - dash", '-'))
KOUT(NON) << "BIT: " << arg;
for(const std::string& arg : kul::String::split("split - by - string - dash", "-"))
KOUT(NON) << "BIT: " << arg;
for(const std::string& arg : kul::String::escSplit("split \\- by - char - dash with escape backslash", '-'))
KOUT(NON) << "BIT: " << arg;
kul::hash::map::S2S sparse;
sparse.insert("LEFT", "RIGHT");
kul::dense::hash::map::S2S dense;
dense.setEmptyKey(""); // unique non occuring key
dense.insert("LEFT", "RIGHT");
kul::File file("./write_access");
if(file && !file.rm()) KERR << "CANNOT DELETE FILE " << file;
if(!file && !file.mk()) KERR << "CANNOT CREATE FILE " << file;
if(file && !file.rm()) KERR << "CANNOT DELETE FILE " << file;
KOUT(NON) << "kul::Now::MILLIS(); " << kul::Now::MILLIS();
KOUT(NON) << "kul::Now::MICROS(); " << kul::Now::MICROS();
KOUT(NON) << "kul::Now::NANOS(); " << kul::Now::NANOS();
KOUT(NON) << "kul::DateTime::NOW(); " << kul::DateTime::NOW();
KOUT(NON) << "CPU CORES: " << kul::cpu::cores();
KOUT(NON) << "MAX THREADS: " << kul::cpu::threads();
TestThreadObject tto1;
kul::Ref<TestThreadObject> ref(tto1);
kul::Thread th(ref);
th.detach();
th.join();
tto1.print();
th.join();
tto1.print();
TestThreadObject tto2;
kul::Ref<const TestThreadObject> cref(tto2);
kul::Thread th2(cref);
th2.detach();
th2.join();
tto2.print();
TestThreadObject tto3;
kul::Thread th1(tto3);
th1.detach();
th1.join();
tto3.print();
kul::Mutex mutex;
{
{
kul::ScopeLock lock(mutex);
}
kul::ScopeLock lock(mutex);
}
KOUT(NON) << "LAUNCHING THREAD POOL";
TestThreadQueueObject ttpo1(mutex);
kul::Ref<TestThreadQueueObject> ref2(ttpo1);
kul::ThreadQueue tp1(ref2);
tp1.setMax(4);
tp1.detach();
tp1.join();
ttpo1.print();
std::queue<int> q;
for(int i = 0; i < 10; i++) q.push(i);
KOUT(NON) << "LAUNCHING PREDICATED THREAD POOL";
TestThreadQueueQObject ttpo2(mutex, q);
kul::Ref<TestThreadQueueQObject> ref3(ttpo2);
kul::PredicatedThreadQueue<std::queue<int> > tp2(ref3, q);
tp2.setMax(kul::cpu::threads());
tp2.detach();
tp2.join();
ttpo2.print();
TestIPC().run();
KOUT(NON) << kul::math::abs(-1);
KOUT(NON) << kul::math::root(16);
KOUT(NON) << kul::math::root(64, 3);
KOUT(NON) << std::setprecision(16) << kul::math::root<double>(64, 6);
KOUT(NON) << kul::math::root(64, 6, 8);
KOUT(NON) << kul::math::root(64, 6, 3, 3);
// kul::math::root(root of, nth root(default 2), iterations(default 6), starting guess(default ignored));
KOUT(NON) << std::setprecision(6) << kul::math::root(2, 2); // float implicit
KOUT(NON) << std::setprecision(16) << kul::math::root<double>(2, 3);
KOUT(NON) << kul::math::pow(-2, 0); // float implicit
KOUT(NON) << kul::math::pow(2, 5);
KOUT(NON) << kul::math::pow(2, -5);
KOUT(NON) << kul::math::pow<double>(2.2974, 5);
KOUT(NON) << kul::math::pow(2, 6);
KOUT(NON);
KOUT(NON) << "SEG FAULTING MAIN THREAD!";
KOUT(NON) << "NON ZERO EXIT CODE EXPECTED";
KOUT(NON) << "FOR FULL DEBUG INFO BUILD WITH:";
KOUT(NON) << "\tWINDOWS cl: -Z7 / link: -DEBUG";
KOUT(NON) << "\tLINUX gcc: -g";
*(int *) 0 = 0; // First seg fault always exits after handling
}
};
}
#endif /* _KUL_TEST_HPP_ */
<commit_msg>cleaner<commit_after>/**
Copyright (c) 2013, Philip Deegan.
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 Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_TEST_HPP_
#define _KUL_TEST_HPP_
#include "kul/os.hpp"
#include "kul/cli.hpp"
#include "kul/ipc.hpp"
#include "kul/log.hpp"
#include "kul/math.hpp"
#include "kul/proc.hpp"
#include "kul/time.hpp"
#include "kul/signal.hpp"
#include "kul/string.hpp"
#include "kul/wstring.hpp"
#include "kul/threads.hpp"
#include <iomanip>
namespace kul {
class TestThreadObject{
private:
int i = 0;
public:
void print(){ KLOG(INF) << "i = " << i;}
friend class kul::ThreadCopy<TestThreadObject>;
friend class kul::ThreadRef<TestThreadObject>;
protected:
void operator()(){
KLOG(INF) << "THREAD RUNNING";
i++;
KLOG(INF) << "THREAD FINISHED";
}
public:
void operator()() const {
KLOG(INF) << "CONST THREAD RUNNING";
KLOG(INF) << "CONST THREAD FINISHED";
}
};
class TestThreadQueueObject{
protected:
int i = 0;
Mutex& mutex;
public:
TestThreadQueueObject(Mutex& mutex) : mutex(mutex){}
void operator()(){
kul::ScopeLock lock(mutex);
KLOG(INF) << "THREAD RUNNING";
i++;
KLOG(INF) << "THREAD FINISHED";
}
void print(){ KLOG(INF) << "i = " << i;}
};
class TestThreadQueueQObject : public TestThreadQueueObject{
private:
std::queue<int>& q;
public:
TestThreadQueueQObject(Mutex& mutex, std::queue<int>& q) : TestThreadQueueObject(mutex), q(q){}
void operator()(){
kul::ScopeLock lock(mutex);
KLOG(INF) << "THREAD RUNNING";
i++;
q.pop();
KLOG(INF) << "THREAD FINISHED";
}
void print(){ KLOG(INF) << "i = " << i;}
};
class TestIPCServer : public kul::ipc::Server{
public:
TestIPCServer() : kul::ipc::Server("uuid", 1){} // UUID CHECKS ONCE
void handle(const std::string& s){
KLOG(INF) << "TestIPCServer " << s;
}
void operator()(){
listen();
}
};
class TestIPC{
public:
void run(){
TestIPCServer ipc;
kul::Ref<TestIPCServer> ref(ipc);
kul::Thread t(ref);
t.run();
kul::this_thread::sleep(1000);
kul::ipc::Client("uuid").send("TestIPCClient");
t.join();
}
};
class Catch{
public:
void print(const int16_t& s){
KOUT(NON) << "SEGMENTATION FAULT INTERCEPTED";
KOUT(NON) << "PRINT STACKTRACE";
}
};
class Test{
private:
const std::string s;
public:
Test() : s("LAMBDAS ALLOWED IN SIGNAL"){
Catch c;
kul::Signal sig; // Windows: each thread requires own handler, static singleton otherwise so only ever one.
sig.segv(std::bind(&Catch::print, std::ref(c), std::placeholders::_1)); // Vector of functions to call before exiting - CAUTION! KEEP SIMPLE!
sig.segv([this](int16_t){ KOUT(NON) << s; }); // Allows lamda notation
KERR << "KERR";
KOUT(NON) << "KOUT(NON)";
KOUT(INF) << "KOUT(INF)";
KOUT(ERR) << "KOUT(ERR)";
KOUT(DBG) << "KOUT(DBG)";
KLOG(INF) << "KLOG(INF)";
KLOG(ERR) << "KLOG(ERR)";
KLOG(DBG) << "KLOG(DBG)";
KOUT(NON) << kul::Dir::SEP();
KOUT(NON) << kul::env::SEP();
KOUT(NON) << kul::env::CWD();
KOUT(NON) << kul::os::userDir().path();
KLOG(INF) << kul::os::userAppDir("maiken").path();
for(const kul::Dir& d : kul::Dir(kul::env::CWD()).dirs())
for(const kul::File& f : d.files())
KOUT(NON) << d.join(f.name()); // or f.full()
try{
kul::Process("echo").arg("Hello").arg("World").start();
}catch(const kul::proc::Exception& e){
KERR << e.debug()<< " : " << typeid(e).name();
KERR << "Error expected on windows without echo on path";
}
for(const std::string& arg : kul::cli::asArgs("/path/to \"words in quotes\" words\\ not\\ in\\ quotes end"))
KOUT(NON) << "ARG: " << arg;
for(const std::string& arg : kul::String::split("split - by - char - dash", '-'))
KOUT(NON) << "BIT: " << arg;
for(const std::string& arg : kul::String::split("split - by - string - dash", "-"))
KOUT(NON) << "BIT: " << arg;
for(const std::string& arg : kul::String::escSplit("split \\- by - char - dash with escape backslash", '-'))
KOUT(NON) << "BIT: " << arg;
kul::hash::map::S2S sparse;
sparse.insert("LEFT", "RIGHT");
kul::dense::hash::map::S2S dense;
dense.setEmptyKey(""); // unique non occuring key
dense.insert("LEFT", "RIGHT");
kul::File file("./write_access");
if(file && !file.rm()) KERR << "CANNOT DELETE FILE " << file;
if(!file && !file.mk()) KERR << "CANNOT CREATE FILE " << file;
if(file && !file.rm()) KERR << "CANNOT DELETE FILE " << file;
KOUT(NON) << "kul::Now::MILLIS(); " << kul::Now::MILLIS();
KOUT(NON) << "kul::Now::MICROS(); " << kul::Now::MICROS();
KOUT(NON) << "kul::Now::NANOS(); " << kul::Now::NANOS();
KOUT(NON) << "kul::DateTime::NOW(); " << kul::DateTime::NOW();
KOUT(NON) << "CPU CORES: " << kul::cpu::cores();
KOUT(NON) << "MAX THREADS: " << kul::cpu::threads();
TestThreadObject tto1;
kul::Ref<TestThreadObject> ref(tto1);
kul::Thread th(ref);
th.detach();
th.join();
tto1.print();
th.join();
tto1.print();
TestThreadObject tto2;
kul::Ref<const TestThreadObject> cref(tto2);
kul::Thread th2(cref);
th2.detach();
th2.join();
tto2.print();
TestThreadObject tto3;
kul::Thread th1(tto3);
th1.detach();
th1.join();
tto3.print();
kul::Mutex mutex;
{
{
kul::ScopeLock lock(mutex);
}
kul::ScopeLock lock(mutex);
}
KOUT(NON) << "LAUNCHING THREAD POOL";
TestThreadQueueObject ttpo1(mutex);
kul::Ref<TestThreadQueueObject> ref2(ttpo1);
kul::ThreadQueue tp1(ref2);
tp1.setMax(4);
tp1.detach();
tp1.join();
ttpo1.print();
std::queue<int> q;
for(int i = 0; i < 10; i++) q.push(i);
KOUT(NON) << "LAUNCHING PREDICATED THREAD POOL";
TestThreadQueueQObject ttpo2(mutex, q);
kul::Ref<TestThreadQueueQObject> ref3(ttpo2);
kul::PredicatedThreadQueue<std::queue<int> > tp2(ref3, q);
tp2.setMax(kul::cpu::threads());
tp2.detach();
tp2.join();
ttpo2.print();
TestIPC().run();
KOUT(NON) << kul::math::abs(-1);
KOUT(NON) << kul::math::root(16);
KOUT(NON) << kul::math::root(64, 3);
KOUT(NON) << std::setprecision(16) << kul::math::root<double>(64, 6);
KOUT(NON) << kul::math::root(64, 6, 8);
KOUT(NON) << kul::math::root(64, 6, 3, 3);
// kul::math::root(root of, nth root(default 2), iterations(default 6), starting guess(default ignored));
KOUT(NON) << std::setprecision(6) << kul::math::root(2, 2); // float implicit
KOUT(NON) << std::setprecision(16) << kul::math::root<double>(2, 3);
KOUT(NON) << kul::math::pow(-2, 0); // float implicit
KOUT(NON) << kul::math::pow(2, 5);
KOUT(NON) << kul::math::pow(2, -5);
KOUT(NON) << kul::math::pow<double>(2.2974, 5);
KOUT(NON) << kul::math::pow(2, 6);
KOUT(NON);
KOUT(NON) << "SEG FAULTING MAIN THREAD!";
KOUT(NON) << "NON ZERO EXIT CODE EXPECTED";
KOUT(NON) << "FOR FULL DEBUG INFO BUILD WITH:";
KOUT(NON) << "\tWINDOWS cl: -Z7 / link: -DEBUG";
KOUT(NON) << "\tLINUX gcc: -g";
*(int *) 0 = 0; // First seg fault always exits after handling
}
};
}
#endif /* _KUL_TEST_HPP_ */
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
#define RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
#include <rectojump/global/common.hpp>
#include <mlk/graphics/graphics_utl.h>
#include <SFML/Graphics.hpp>
namespace rj
{
class gradient_rect : public sf::Drawable
{
vec2f m_position{0.f, 0.f};
vec2f m_size;
sf::VertexArray m_verts{sf::Quads};
sf::Color m_startcolor;
sf::Color m_endcolor;
std::size_t m_num_gradient_points;
float m_step_ratio;
public:
gradient_rect(const vec2f& size = {0.f, 0.f}, const sf::Color& startcolor = {255, 255, 255},
const sf::Color& endcolor = {255, 255, 255}, std::size_t gradient_points = 1) :
m_size{size},
m_startcolor{startcolor},
m_endcolor{endcolor},
m_num_gradient_points{gradient_points},
m_step_ratio{1.f / m_num_gradient_points}
{this->recalculate();}
void set_size(const vec2f& size) noexcept
{m_size = size; this->recalculate();}
void set_position(const vec2f& pos) noexcept
{m_position = pos; this->recalculate();}
void set_startcolor(const sf::Color& color) noexcept
{m_startcolor = color; this->recalculate();}
void set_endcolor(const sf::Color& color) noexcept
{m_endcolor = color; this->recalculate();}
void set_gradient_points(std::size_t num) noexcept
{m_num_gradient_points = num; this->recalculate();}
void move(const vec2f& offset) noexcept
{this->set_position(m_position + offset);}
const vec2f& get_size() const noexcept
{return m_size;}
const vec2f& get_position() const noexcept
{return m_position;}
const sf::Color& get_startcolor() const noexcept
{return m_startcolor;}
const sf::Color& get_endcolor() const noexcept
{return m_endcolor;}
std::size_t num_gradient_points() const noexcept
{return m_num_gradient_points;}
private:
void recalculate() noexcept
{
m_verts.clear();
auto single_size(m_size.y / m_num_gradient_points);
auto pos_y(m_position.y);
auto current_ratio(0.f);
for(auto i(0); i < m_num_gradient_points; ++i)
{
auto current_color(mlk::gcs::color_diff(m_startcolor, m_endcolor, current_ratio));
m_verts.append({{m_position.x, pos_y + single_size}, current_color});
m_verts.append({{m_position.x, pos_y}, current_color});
m_verts.append({{m_size.x + m_position.x, pos_y}, current_color});
m_verts.append({{m_size.x + m_position.x, pos_y + single_size}, current_color});
pos_y += single_size;
current_ratio += m_step_ratio;
}
}
void draw(sf::RenderTarget& target, sf::RenderStates states) const override
{target.draw(m_verts, states);}
};
}
#endif // RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
<commit_msg>gradient_rect: fixed recalculation<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
#define RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
#include <rectojump/global/common.hpp>
#include <mlk/graphics/graphics_utl.h>
#include <SFML/Graphics.hpp>
namespace rj
{
class gradient_rect : public sf::Drawable
{
vec2f m_position{0.f, 0.f};
vec2f m_size;
sf::VertexArray m_verts{sf::Quads};
sf::Color m_startcolor;
sf::Color m_endcolor;
std::size_t m_num_gradient_points;
float m_step_ratio;
public:
gradient_rect(const vec2f& size = {0.f, 0.f}, const sf::Color& startcolor = {255, 255, 255},
const sf::Color& endcolor = {255, 255, 255}, std::size_t gradient_points = 1) :
m_size{size},
m_startcolor{startcolor},
m_endcolor{endcolor},
m_num_gradient_points{gradient_points},
m_step_ratio{1.f / m_num_gradient_points}
{this->recalculate();}
void set_size(const vec2f& size) noexcept
{m_size = size; this->recalculate();}
void set_position(const vec2f& pos) noexcept
{m_position = pos; this->recalculate();}
void set_startcolor(const sf::Color& color) noexcept
{m_startcolor = color; this->recalculate();}
void set_endcolor(const sf::Color& color) noexcept
{m_endcolor = color; this->recalculate();}
void set_gradient_points(std::size_t num) noexcept
{m_num_gradient_points = num; this->recalculate();}
void move(const vec2f& offset) noexcept
{this->set_position(m_position + offset);}
const vec2f& get_size() const noexcept
{return m_size;}
const vec2f& get_position() const noexcept
{return m_position;}
const sf::Color& get_startcolor() const noexcept
{return m_startcolor;}
const sf::Color& get_endcolor() const noexcept
{return m_endcolor;}
std::size_t num_gradient_points() const noexcept
{return m_num_gradient_points;}
private:
void recalculate() noexcept
{
m_verts.clear();
m_step_ratio = 1.f / m_num_gradient_points;
auto single_size(m_size.y / m_num_gradient_points);
auto pos_y(m_position.y);
auto current_ratio(0.f);
for(auto i(0); i < m_num_gradient_points; ++i)
{
auto current_color(mlk::gcs::color_diff(m_startcolor, m_endcolor, current_ratio));
m_verts.append({{m_position.x, pos_y + single_size}, current_color});
m_verts.append({{m_position.x, pos_y}, current_color});
m_verts.append({{m_size.x + m_position.x, pos_y}, current_color});
m_verts.append({{m_size.x + m_position.x, pos_y + single_size}, current_color});
pos_y += single_size;
current_ratio += m_step_ratio;
}
}
void draw(sf::RenderTarget& target, sf::RenderStates states) const override
{target.draw(m_verts, states);}
};
}
#endif // RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "content/public/common/content_switches.h"
#include "xwalk/extensions/common/xwalk_extension.h"
#include "xwalk/extensions/common/xwalk_extension_server.h"
#include "xwalk/runtime/common/xwalk_runtime_features.h"
#include "xwalk/runtime/extension/runtime_extension.h"
#include "xwalk/sysapps/raw_socket/raw_socket_extension.h"
#include "ui/gl/gl_switches.h"
#include "content/browser/device_orientation/device_inertial_sensor_service.h"
#include "xwalk/application/browser/installer/tizen/package_installer.h"
#include "xwalk/sysapps/device_capabilities/device_capabilities_extension.h"
#include "xwalk/tizen/mobile/sensor/tizen_data_fetcher_shared_memory.h"
namespace xwalk {
XWalkBrowserMainPartsTizen::XWalkBrowserMainPartsTizen(
const content::MainFunctionParams& parameters)
: XWalkBrowserMainParts(parameters) {
}
void XWalkBrowserMainPartsTizen::PreMainMessageLoopStart() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);
const char* gl_name;
if (base::PathExists(base::FilePath("/usr/lib/xwalk/libosmesa.so")))
gl_name = gfx::kGLImplementationOSMesaName;
else if (base::PathExists(base::FilePath("/usr/lib/libGL.so")))
gl_name = gfx::kGLImplementationDesktopName;
else
gl_name = gfx::kGLImplementationEGLName;
command_line->AppendSwitchASCII(switches::kUseGL, gl_name);
XWalkBrowserMainParts::PreMainMessageLoopStart();
}
void XWalkBrowserMainPartsTizen::PreMainMessageLoopRun() {
if (content::DeviceInertialSensorService* sensor_service =
content::DeviceInertialSensorService::GetInstance()) {
// As the data fetcher of sensors is implemented outside of Chromium, we
// need to make it available to Chromium by "abusing" the test framework.
// TODO(zliang7): Find a decent way to inject our sensor fetcher for Tizen.
sensor_service->SetDataFetcherForTests(new TizenDataFetcherSharedMemory());
}
XWalkBrowserMainParts::PreMainMessageLoopRun();
}
void
XWalkBrowserMainPartsTizen::RegisterInternalExtensionsInExtensionThreadServer(
extensions::XWalkExtensionServer* server) {
CHECK(server);
if (XWalkRuntimeFeatures::isDeviceCapabilitiesAPIEnabled()) {
server->RegisterExtension(scoped_ptr<extensions::XWalkExtension>(
new sysapps::DeviceCapabilitiesExtension(runtime_registry_.get())));
}
if (XWalkRuntimeFeatures::isRawSocketsAPIEnabled()) {
server->RegisterExtension(scoped_ptr<extensions::XWalkExtension>(
new sysapps::RawSocketExtension()));
}
}
} // namespace xwalk
<commit_msg>[Tizen][Temp] Enforce device scale factor value to '2.0' on Tizen<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "content/public/common/content_switches.h"
#include "xwalk/extensions/common/xwalk_extension.h"
#include "xwalk/extensions/common/xwalk_extension_server.h"
#include "xwalk/runtime/common/xwalk_runtime_features.h"
#include "xwalk/runtime/extension/runtime_extension.h"
#include "xwalk/sysapps/raw_socket/raw_socket_extension.h"
#include "ui/gl/gl_switches.h"
#include "ui/gfx/switches.h"
#include "content/browser/device_orientation/device_inertial_sensor_service.h"
#include "xwalk/application/browser/installer/tizen/package_installer.h"
#include "xwalk/sysapps/device_capabilities/device_capabilities_extension.h"
#include "xwalk/tizen/mobile/sensor/tizen_data_fetcher_shared_memory.h"
namespace xwalk {
XWalkBrowserMainPartsTizen::XWalkBrowserMainPartsTizen(
const content::MainFunctionParams& parameters)
: XWalkBrowserMainParts(parameters) {
}
void XWalkBrowserMainPartsTizen::PreMainMessageLoopStart() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);
const char* gl_name;
if (base::PathExists(base::FilePath("/usr/lib/xwalk/libosmesa.so")))
gl_name = gfx::kGLImplementationOSMesaName;
else if (base::PathExists(base::FilePath("/usr/lib/libGL.so")))
gl_name = gfx::kGLImplementationDesktopName;
else
gl_name = gfx::kGLImplementationEGLName;
command_line->AppendSwitchASCII(switches::kUseGL, gl_name);
// Workaround to provide viewport meta tag proper behavior on Tizen.
// FIXME: Must be removed when Chromium r235967 is in place.
command_line->AppendSwitchASCII(switches::kForceDeviceScaleFactor, "2.0");
XWalkBrowserMainParts::PreMainMessageLoopStart();
}
void XWalkBrowserMainPartsTizen::PreMainMessageLoopRun() {
if (content::DeviceInertialSensorService* sensor_service =
content::DeviceInertialSensorService::GetInstance()) {
// As the data fetcher of sensors is implemented outside of Chromium, we
// need to make it available to Chromium by "abusing" the test framework.
// TODO(zliang7): Find a decent way to inject our sensor fetcher for Tizen.
sensor_service->SetDataFetcherForTests(new TizenDataFetcherSharedMemory());
}
XWalkBrowserMainParts::PreMainMessageLoopRun();
}
void
XWalkBrowserMainPartsTizen::RegisterInternalExtensionsInExtensionThreadServer(
extensions::XWalkExtensionServer* server) {
CHECK(server);
if (XWalkRuntimeFeatures::isDeviceCapabilitiesAPIEnabled()) {
server->RegisterExtension(scoped_ptr<extensions::XWalkExtension>(
new sysapps::DeviceCapabilitiesExtension(runtime_registry_.get())));
}
if (XWalkRuntimeFeatures::isRawSocketsAPIEnabled()) {
server->RegisterExtension(scoped_ptr<extensions::XWalkExtension>(
new sysapps::RawSocketExtension()));
}
}
} // namespace xwalk
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.