text
stringlengths 54
60.6k
|
---|
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_TENSOR_OPPS_HPP_
#define GUARD_MIOPEN_TENSOR_OPPS_HPP_
#include <miopen/common.hpp>
#include <miopen/datatype.hpp>
#include <miopen/handle.hpp>
#include <miopen/miopen.h>
#include <miopen/object.hpp>
#include <vector>
namespace miopen {
void ScaleTensor(Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, const int offset = 0);
void SetTensor(Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, const int offset = 0);
void OpTensor(Handle& handle,
miopenTensorOp_t tensorOp,
const void* alpha0,
const TensorDescriptor& aTensorDesc,
ConstData_t ATensor,
const void* alpha1,
const TensorDescriptor& bTensorDesc,
ConstData_t BTensor,
const void* beta,
const TensorDescriptor& cTensorDesc,
Data_t CTensor,
size_t Aoffset = 0,
size_t Boffset = 0,
size_t Coffset = 0);
void CopyTensor(Handle& handle,
const TensorDescriptor& srcDesc,
ConstData_t src,
const TensorDescriptor& destDesc,
Data_t dest,
int srcOffset = 0,
int destOffset = 0);
} // namespace miopen
#endif // GUARD_MIOPEN_TENSOR_OPPS_HPP_
<commit_msg>fix clang-tidy errors<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_TENSOR_OPPS_HPP_
#define GUARD_MIOPEN_TENSOR_OPPS_HPP_
#include <miopen/common.hpp>
#include <miopen/datatype.hpp>
#include <miopen/handle.hpp>
#include <miopen/miopen.h>
#include <miopen/object.hpp>
#include <vector>
namespace miopen {
void ScaleTensor(Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, int offset = 0);
void SetTensor(Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, int offset = 0);
void OpTensor(Handle& handle,
miopenTensorOp_t tensorOp,
const void* alpha0,
const TensorDescriptor& aTensorDesc,
ConstData_t ATensor,
const void* alpha1,
const TensorDescriptor& bTensorDesc,
ConstData_t BTensor,
const void* beta,
const TensorDescriptor& cTensorDesc,
Data_t CTensor,
size_t Aoffset = 0,
size_t Boffset = 0,
size_t Coffset = 0);
void CopyTensor(Handle& handle,
const TensorDescriptor& srcDesc,
ConstData_t src,
const TensorDescriptor& dstDesc,
Data_t dst,
int srcOffset = 0,
int dstOffset = 0);
} // namespace miopen
#endif // GUARD_MIOPEN_TENSOR_OPPS_HPP_
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/content_settings/content_settings_notification_provider.h"
#include "base/string_util.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "googleurl/src/gurl.h"
namespace {
const ContentSetting kDefaultSetting = CONTENT_SETTING_ASK;
} // namespace
namespace content_settings {
// ////////////////////////////////////////////////////////////////////////////
// NotificationProvider
//
// static
void NotificationProvider::RegisterUserPrefs(PrefService* user_prefs) {
if (!user_prefs->FindPreference(prefs::kDesktopNotificationAllowedOrigins))
user_prefs->RegisterListPref(prefs::kDesktopNotificationAllowedOrigins);
if (!user_prefs->FindPreference(prefs::kDesktopNotificationDeniedOrigins))
user_prefs->RegisterListPref(prefs::kDesktopNotificationDeniedOrigins);
}
// TODO(markusheintz): Re-factoring in progress. Do not move or touch the
// following two static methods as you might cause trouble. Thanks!
// static
ContentSettingsPattern NotificationProvider::ToContentSettingsPattern(
const GURL& origin) {
// Fix empty GURLs.
if (origin.spec().empty()) {
std::string pattern_spec(chrome::kFileScheme);
pattern_spec += chrome::kStandardSchemeSeparator;
return ContentSettingsPattern(pattern_spec);
}
return ContentSettingsPattern::FromURLNoWildcard(origin);
}
// static
GURL NotificationProvider::ToGURL(const ContentSettingsPattern& pattern) {
std::string pattern_spec(pattern.AsString());
if (pattern_spec.empty() ||
StartsWithASCII(pattern_spec,
std::string(ContentSettingsPattern::kDomainWildcard),
true)) {
NOTREACHED();
}
std::string url_spec("");
if (StartsWithASCII(pattern_spec, std::string(chrome::kFileScheme), false)) {
url_spec += pattern_spec;
} else if (!pattern.scheme().empty()) {
url_spec += pattern.scheme();
url_spec += chrome::kStandardSchemeSeparator;
url_spec += pattern_spec;
}
LOG(ERROR) << " url_spec=" << url_spec;
return GURL(url_spec);
}
NotificationProvider::NotificationProvider(
Profile* profile)
: profile_(profile) {
prefs_registrar_.Init(profile_->GetPrefs());
StartObserving();
}
NotificationProvider::~NotificationProvider() {
StopObserving();
}
bool NotificationProvider::ContentSettingsTypeIsManaged(
ContentSettingsType content_type) {
return false;
}
ContentSetting NotificationProvider::GetContentSetting(
const GURL& requesting_url,
const GURL& embedding_url,
ContentSettingsType content_type,
const ResourceIdentifier& resource_identifier) const {
if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
return CONTENT_SETTING_DEFAULT;
return GetContentSetting(requesting_url);
}
void NotificationProvider::SetContentSetting(
const ContentSettingsPattern& requesting_url_pattern,
const ContentSettingsPattern& embedding_url_pattern,
ContentSettingsType content_type,
const ResourceIdentifier& resource_identifier,
ContentSetting content_setting) {
if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
return;
GURL origin = ToGURL(requesting_url_pattern);
if (CONTENT_SETTING_ALLOW == content_setting) {
GrantPermission(origin);
} else if (CONTENT_SETTING_BLOCK == content_setting) {
DenyPermission(origin);
} else if (CONTENT_SETTING_DEFAULT == content_setting) {
ContentSetting current_setting = GetContentSetting(origin);
if (CONTENT_SETTING_ALLOW == current_setting) {
ResetAllowedOrigin(origin);
} else if (CONTENT_SETTING_BLOCK == current_setting) {
ResetBlockedOrigin(origin);
} else {
NOTREACHED();
}
} else {
NOTREACHED();
}
}
void NotificationProvider::GetAllContentSettingsRules(
ContentSettingsType content_type,
const ResourceIdentifier& resource_identifier,
Rules* content_setting_rules) const {
if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
return;
std::vector<GURL> allowed_origins = GetAllowedOrigins();
std::vector<GURL> denied_origins = GetBlockedOrigins();
for (std::vector<GURL>::iterator url = allowed_origins.begin();
url != allowed_origins.end();
++url) {
ContentSettingsPattern pattern =
ContentSettingsPattern::FromURLNoWildcard(*url);
content_setting_rules->push_back(Rule(
pattern,
pattern,
CONTENT_SETTING_ALLOW));
}
for (std::vector<GURL>::iterator url = denied_origins.begin();
url != denied_origins.end();
++url) {
ContentSettingsPattern pattern =
ContentSettingsPattern::FromURLNoWildcard(*url);
content_setting_rules->push_back(Rule(
pattern,
pattern,
CONTENT_SETTING_BLOCK));
}
}
void NotificationProvider::ClearAllContentSettingsRules(
ContentSettingsType content_type) {
if (content_type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
ResetAllOrigins();
}
void NotificationProvider::ResetToDefaults() {
ResetAllOrigins();
}
void NotificationProvider::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (NotificationType::PREF_CHANGED == type) {
const std::string& name = *Details<std::string>(details).ptr();
OnPrefsChanged(name);
} else if (NotificationType::PROFILE_DESTROYED == type) {
StopObserving();
}
}
/////////////////////////////////////////////////////////////////////
// Private
//
void NotificationProvider::StartObserving() {
if (!profile_->IsOffTheRecord()) {
prefs_registrar_.Add(prefs::kDesktopNotificationDefaultContentSetting,
this);
prefs_registrar_.Add(prefs::kDesktopNotificationAllowedOrigins, this);
prefs_registrar_.Add(prefs::kDesktopNotificationDeniedOrigins, this);
notification_registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
NotificationService::AllSources());
}
notification_registrar_.Add(this, NotificationType::PROFILE_DESTROYED,
Source<Profile>(profile_));
}
void NotificationProvider::StopObserving() {
if (!profile_->IsOffTheRecord()) {
prefs_registrar_.RemoveAll();
}
notification_registrar_.RemoveAll();
}
void NotificationProvider::OnPrefsChanged(const std::string& pref_name) {
if (pref_name == prefs::kDesktopNotificationAllowedOrigins) {
NotifySettingsChange();
} else if (pref_name == prefs::kDesktopNotificationDeniedOrigins) {
NotifySettingsChange();
}
}
void NotificationProvider::NotifySettingsChange() {
// TODO(markusheintz): Re-factoring work in progress: Replace the
// DESKTOP_NOTIFICATION_SETTINGS_CHANGED with a CONTENT_SETTINGS_CHANGED
// notification, and use the HostContentSettingsMap as source once this
// content settings provider in integrated in the HostContentSetttingsMap.
NotificationService::current()->Notify(
NotificationType::DESKTOP_NOTIFICATION_SETTINGS_CHANGED,
Source<DesktopNotificationService>(
profile_->GetDesktopNotificationService()),
NotificationService::NoDetails());
}
std::vector<GURL> NotificationProvider::GetAllowedOrigins() const {
std::vector<GURL> allowed_origins;
PrefService* prefs = profile_->GetPrefs();
const ListValue* allowed_sites =
prefs->GetList(prefs::kDesktopNotificationAllowedOrigins);
if (allowed_sites) {
// TODO(markusheintz): Remove dependency to PrefsCache
NotificationsPrefsCache::ListValueToGurlVector(*allowed_sites,
&allowed_origins);
}
return allowed_origins;
}
std::vector<GURL> NotificationProvider::GetBlockedOrigins() const {
std::vector<GURL> denied_origins;
PrefService* prefs = profile_->GetPrefs();
const ListValue* denied_sites =
prefs->GetList(prefs::kDesktopNotificationDeniedOrigins);
if (denied_sites) {
// TODO(markusheintz): Remove dependency to PrefsCache
NotificationsPrefsCache::ListValueToGurlVector(*denied_sites,
&denied_origins);
}
return denied_origins;
}
void NotificationProvider::GrantPermission(const GURL& origin) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
PersistPermissionChange(origin, true);
NotifySettingsChange();
}
void NotificationProvider::DenyPermission(const GURL& origin) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
PersistPermissionChange(origin, false);
NotifySettingsChange();
}
void NotificationProvider::PersistPermissionChange(
const GURL& origin, bool is_allowed) {
// Don't persist changes when off the record.
if (profile_->IsOffTheRecord())
return;
PrefService* prefs = profile_->GetPrefs();
// |Observe()| updates the whole permission set in the cache, but only a
// single origin has changed. Hence, callers of this method manually
// schedule a task to update the prefs cache, and the prefs observer is
// disabled while the update runs.
StopObserving();
bool allowed_changed = false;
bool denied_changed = false;
ListValue* allowed_sites =
prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
ListValue* denied_sites =
prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
{
// |value| is passed to the preferences list, or deleted.
StringValue* value = new StringValue(origin.spec());
// Remove from one list and add to the other.
if (is_allowed) {
// Remove from the denied list.
if (denied_sites->Remove(*value) != -1)
denied_changed = true;
// Add to the allowed list.
if (allowed_sites->AppendIfNotPresent(value))
allowed_changed = true;
} else {
// Remove from the allowed list.
if (allowed_sites->Remove(*value) != -1)
allowed_changed = true;
// Add to the denied list.
if (denied_sites->AppendIfNotPresent(value))
denied_changed = true;
}
}
// Persist the pref if anthing changed, but only send updates for the
// list that changed.
if (allowed_changed || denied_changed) {
if (allowed_changed) {
ScopedUserPrefUpdate update_allowed(
prefs, prefs::kDesktopNotificationAllowedOrigins);
}
if (denied_changed) {
ScopedUserPrefUpdate updateDenied(
prefs, prefs::kDesktopNotificationDeniedOrigins);
}
prefs->ScheduleSavePersistentPrefs();
}
StartObserving();
}
ContentSetting NotificationProvider::GetContentSetting(
const GURL& origin) const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (profile_->IsOffTheRecord())
return kDefaultSetting;
std::vector<GURL> allowed_origins(GetAllowedOrigins());
if (std::find(allowed_origins.begin(), allowed_origins.end(), origin) !=
allowed_origins.end())
return CONTENT_SETTING_ALLOW;
std::vector<GURL> denied_origins(GetBlockedOrigins());
if (std::find(denied_origins.begin(), denied_origins.end(), origin) !=
denied_origins.end())
return CONTENT_SETTING_BLOCK;
return CONTENT_SETTING_DEFAULT;
}
void NotificationProvider::ResetAllowedOrigin(const GURL& origin) {
if (profile_->IsOffTheRecord())
return;
// Since this isn't called often, let the normal observer behavior update the
// cache in this case.
PrefService* prefs = profile_->GetPrefs();
ListValue* allowed_sites =
prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
{
StringValue value(origin.spec());
int removed_index = allowed_sites->Remove(value);
DCHECK_NE(-1, removed_index) << origin << " was not allowed";
ScopedUserPrefUpdate update_allowed(
prefs, prefs::kDesktopNotificationAllowedOrigins);
}
prefs->ScheduleSavePersistentPrefs();
}
void NotificationProvider::ResetBlockedOrigin(const GURL& origin) {
if (profile_->IsOffTheRecord())
return;
// Since this isn't called often, let the normal observer behavior update the
// cache in this case.
PrefService* prefs = profile_->GetPrefs();
ListValue* denied_sites =
prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
{
StringValue value(origin.spec());
int removed_index = denied_sites->Remove(value);
DCHECK_NE(-1, removed_index) << origin << " was not blocked";
ScopedUserPrefUpdate update_allowed(
prefs, prefs::kDesktopNotificationDeniedOrigins);
}
prefs->ScheduleSavePersistentPrefs();
}
void NotificationProvider::ResetAllOrigins() {
PrefService* prefs = profile_->GetPrefs();
prefs->ClearPref(prefs::kDesktopNotificationAllowedOrigins);
prefs->ClearPref(prefs::kDesktopNotificationDeniedOrigins);
}
} // namespace content_settings
<commit_msg>Remove unnecessary LOG statement.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/content_settings/content_settings_notification_provider.h"
#include "base/string_util.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "googleurl/src/gurl.h"
namespace {
const ContentSetting kDefaultSetting = CONTENT_SETTING_ASK;
} // namespace
namespace content_settings {
// ////////////////////////////////////////////////////////////////////////////
// NotificationProvider
//
// static
void NotificationProvider::RegisterUserPrefs(PrefService* user_prefs) {
if (!user_prefs->FindPreference(prefs::kDesktopNotificationAllowedOrigins))
user_prefs->RegisterListPref(prefs::kDesktopNotificationAllowedOrigins);
if (!user_prefs->FindPreference(prefs::kDesktopNotificationDeniedOrigins))
user_prefs->RegisterListPref(prefs::kDesktopNotificationDeniedOrigins);
}
// TODO(markusheintz): Re-factoring in progress. Do not move or touch the
// following two static methods as you might cause trouble. Thanks!
// static
ContentSettingsPattern NotificationProvider::ToContentSettingsPattern(
const GURL& origin) {
// Fix empty GURLs.
if (origin.spec().empty()) {
std::string pattern_spec(chrome::kFileScheme);
pattern_spec += chrome::kStandardSchemeSeparator;
return ContentSettingsPattern(pattern_spec);
}
return ContentSettingsPattern::FromURLNoWildcard(origin);
}
// static
GURL NotificationProvider::ToGURL(const ContentSettingsPattern& pattern) {
std::string pattern_spec(pattern.AsString());
if (pattern_spec.empty() ||
StartsWithASCII(pattern_spec,
std::string(ContentSettingsPattern::kDomainWildcard),
true)) {
NOTREACHED();
}
std::string url_spec("");
if (StartsWithASCII(pattern_spec, std::string(chrome::kFileScheme), false)) {
url_spec += pattern_spec;
} else if (!pattern.scheme().empty()) {
url_spec += pattern.scheme();
url_spec += chrome::kStandardSchemeSeparator;
url_spec += pattern_spec;
}
return GURL(url_spec);
}
NotificationProvider::NotificationProvider(
Profile* profile)
: profile_(profile) {
prefs_registrar_.Init(profile_->GetPrefs());
StartObserving();
}
NotificationProvider::~NotificationProvider() {
StopObserving();
}
bool NotificationProvider::ContentSettingsTypeIsManaged(
ContentSettingsType content_type) {
return false;
}
ContentSetting NotificationProvider::GetContentSetting(
const GURL& requesting_url,
const GURL& embedding_url,
ContentSettingsType content_type,
const ResourceIdentifier& resource_identifier) const {
if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
return CONTENT_SETTING_DEFAULT;
return GetContentSetting(requesting_url);
}
void NotificationProvider::SetContentSetting(
const ContentSettingsPattern& requesting_url_pattern,
const ContentSettingsPattern& embedding_url_pattern,
ContentSettingsType content_type,
const ResourceIdentifier& resource_identifier,
ContentSetting content_setting) {
if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
return;
GURL origin = ToGURL(requesting_url_pattern);
if (CONTENT_SETTING_ALLOW == content_setting) {
GrantPermission(origin);
} else if (CONTENT_SETTING_BLOCK == content_setting) {
DenyPermission(origin);
} else if (CONTENT_SETTING_DEFAULT == content_setting) {
ContentSetting current_setting = GetContentSetting(origin);
if (CONTENT_SETTING_ALLOW == current_setting) {
ResetAllowedOrigin(origin);
} else if (CONTENT_SETTING_BLOCK == current_setting) {
ResetBlockedOrigin(origin);
} else {
NOTREACHED();
}
} else {
NOTREACHED();
}
}
void NotificationProvider::GetAllContentSettingsRules(
ContentSettingsType content_type,
const ResourceIdentifier& resource_identifier,
Rules* content_setting_rules) const {
if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
return;
std::vector<GURL> allowed_origins = GetAllowedOrigins();
std::vector<GURL> denied_origins = GetBlockedOrigins();
for (std::vector<GURL>::iterator url = allowed_origins.begin();
url != allowed_origins.end();
++url) {
ContentSettingsPattern pattern =
ContentSettingsPattern::FromURLNoWildcard(*url);
content_setting_rules->push_back(Rule(
pattern,
pattern,
CONTENT_SETTING_ALLOW));
}
for (std::vector<GURL>::iterator url = denied_origins.begin();
url != denied_origins.end();
++url) {
ContentSettingsPattern pattern =
ContentSettingsPattern::FromURLNoWildcard(*url);
content_setting_rules->push_back(Rule(
pattern,
pattern,
CONTENT_SETTING_BLOCK));
}
}
void NotificationProvider::ClearAllContentSettingsRules(
ContentSettingsType content_type) {
if (content_type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
ResetAllOrigins();
}
void NotificationProvider::ResetToDefaults() {
ResetAllOrigins();
}
void NotificationProvider::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (NotificationType::PREF_CHANGED == type) {
const std::string& name = *Details<std::string>(details).ptr();
OnPrefsChanged(name);
} else if (NotificationType::PROFILE_DESTROYED == type) {
StopObserving();
}
}
/////////////////////////////////////////////////////////////////////
// Private
//
void NotificationProvider::StartObserving() {
if (!profile_->IsOffTheRecord()) {
prefs_registrar_.Add(prefs::kDesktopNotificationDefaultContentSetting,
this);
prefs_registrar_.Add(prefs::kDesktopNotificationAllowedOrigins, this);
prefs_registrar_.Add(prefs::kDesktopNotificationDeniedOrigins, this);
notification_registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
NotificationService::AllSources());
}
notification_registrar_.Add(this, NotificationType::PROFILE_DESTROYED,
Source<Profile>(profile_));
}
void NotificationProvider::StopObserving() {
if (!profile_->IsOffTheRecord()) {
prefs_registrar_.RemoveAll();
}
notification_registrar_.RemoveAll();
}
void NotificationProvider::OnPrefsChanged(const std::string& pref_name) {
if (pref_name == prefs::kDesktopNotificationAllowedOrigins) {
NotifySettingsChange();
} else if (pref_name == prefs::kDesktopNotificationDeniedOrigins) {
NotifySettingsChange();
}
}
void NotificationProvider::NotifySettingsChange() {
// TODO(markusheintz): Re-factoring work in progress: Replace the
// DESKTOP_NOTIFICATION_SETTINGS_CHANGED with a CONTENT_SETTINGS_CHANGED
// notification, and use the HostContentSettingsMap as source once this
// content settings provider in integrated in the HostContentSetttingsMap.
NotificationService::current()->Notify(
NotificationType::DESKTOP_NOTIFICATION_SETTINGS_CHANGED,
Source<DesktopNotificationService>(
profile_->GetDesktopNotificationService()),
NotificationService::NoDetails());
}
std::vector<GURL> NotificationProvider::GetAllowedOrigins() const {
std::vector<GURL> allowed_origins;
PrefService* prefs = profile_->GetPrefs();
const ListValue* allowed_sites =
prefs->GetList(prefs::kDesktopNotificationAllowedOrigins);
if (allowed_sites) {
// TODO(markusheintz): Remove dependency to PrefsCache
NotificationsPrefsCache::ListValueToGurlVector(*allowed_sites,
&allowed_origins);
}
return allowed_origins;
}
std::vector<GURL> NotificationProvider::GetBlockedOrigins() const {
std::vector<GURL> denied_origins;
PrefService* prefs = profile_->GetPrefs();
const ListValue* denied_sites =
prefs->GetList(prefs::kDesktopNotificationDeniedOrigins);
if (denied_sites) {
// TODO(markusheintz): Remove dependency to PrefsCache
NotificationsPrefsCache::ListValueToGurlVector(*denied_sites,
&denied_origins);
}
return denied_origins;
}
void NotificationProvider::GrantPermission(const GURL& origin) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
PersistPermissionChange(origin, true);
NotifySettingsChange();
}
void NotificationProvider::DenyPermission(const GURL& origin) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
PersistPermissionChange(origin, false);
NotifySettingsChange();
}
void NotificationProvider::PersistPermissionChange(
const GURL& origin, bool is_allowed) {
// Don't persist changes when off the record.
if (profile_->IsOffTheRecord())
return;
PrefService* prefs = profile_->GetPrefs();
// |Observe()| updates the whole permission set in the cache, but only a
// single origin has changed. Hence, callers of this method manually
// schedule a task to update the prefs cache, and the prefs observer is
// disabled while the update runs.
StopObserving();
bool allowed_changed = false;
bool denied_changed = false;
ListValue* allowed_sites =
prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
ListValue* denied_sites =
prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
{
// |value| is passed to the preferences list, or deleted.
StringValue* value = new StringValue(origin.spec());
// Remove from one list and add to the other.
if (is_allowed) {
// Remove from the denied list.
if (denied_sites->Remove(*value) != -1)
denied_changed = true;
// Add to the allowed list.
if (allowed_sites->AppendIfNotPresent(value))
allowed_changed = true;
} else {
// Remove from the allowed list.
if (allowed_sites->Remove(*value) != -1)
allowed_changed = true;
// Add to the denied list.
if (denied_sites->AppendIfNotPresent(value))
denied_changed = true;
}
}
// Persist the pref if anthing changed, but only send updates for the
// list that changed.
if (allowed_changed || denied_changed) {
if (allowed_changed) {
ScopedUserPrefUpdate update_allowed(
prefs, prefs::kDesktopNotificationAllowedOrigins);
}
if (denied_changed) {
ScopedUserPrefUpdate updateDenied(
prefs, prefs::kDesktopNotificationDeniedOrigins);
}
prefs->ScheduleSavePersistentPrefs();
}
StartObserving();
}
ContentSetting NotificationProvider::GetContentSetting(
const GURL& origin) const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (profile_->IsOffTheRecord())
return kDefaultSetting;
std::vector<GURL> allowed_origins(GetAllowedOrigins());
if (std::find(allowed_origins.begin(), allowed_origins.end(), origin) !=
allowed_origins.end())
return CONTENT_SETTING_ALLOW;
std::vector<GURL> denied_origins(GetBlockedOrigins());
if (std::find(denied_origins.begin(), denied_origins.end(), origin) !=
denied_origins.end())
return CONTENT_SETTING_BLOCK;
return CONTENT_SETTING_DEFAULT;
}
void NotificationProvider::ResetAllowedOrigin(const GURL& origin) {
if (profile_->IsOffTheRecord())
return;
// Since this isn't called often, let the normal observer behavior update the
// cache in this case.
PrefService* prefs = profile_->GetPrefs();
ListValue* allowed_sites =
prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
{
StringValue value(origin.spec());
int removed_index = allowed_sites->Remove(value);
DCHECK_NE(-1, removed_index) << origin << " was not allowed";
ScopedUserPrefUpdate update_allowed(
prefs, prefs::kDesktopNotificationAllowedOrigins);
}
prefs->ScheduleSavePersistentPrefs();
}
void NotificationProvider::ResetBlockedOrigin(const GURL& origin) {
if (profile_->IsOffTheRecord())
return;
// Since this isn't called often, let the normal observer behavior update the
// cache in this case.
PrefService* prefs = profile_->GetPrefs();
ListValue* denied_sites =
prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
{
StringValue value(origin.spec());
int removed_index = denied_sites->Remove(value);
DCHECK_NE(-1, removed_index) << origin << " was not blocked";
ScopedUserPrefUpdate update_allowed(
prefs, prefs::kDesktopNotificationDeniedOrigins);
}
prefs->ScheduleSavePersistentPrefs();
}
void NotificationProvider::ResetAllOrigins() {
PrefService* prefs = profile_->GetPrefs();
prefs->ClearPref(prefs::kDesktopNotificationAllowedOrigins);
prefs->ClearPref(prefs::kDesktopNotificationDeniedOrigins);
}
} // namespace content_settings
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/ref_counted.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
class RenderViewHostManagerTest : public InProcessBrowserTest {
public:
RenderViewHostManagerTest() {
EnableDOMAutomation();
}
static bool GetFilePathWithHostAndPortReplacement(
const std::string& original_file_path,
const net::HostPortPair& host_port_pair,
std::string* replacement_path) {
std::vector<net::TestServer::StringPair> replacement_text;
replacement_text.push_back(
make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
return net::TestServer::GetFilePathWithReplacements(
original_file_path, replacement_text, replacement_path);
}
};
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
SwapProcessWithRelNoreferrerAndTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server_.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer + target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have a new SiteInstance.
scoped_refptr<SiteInstance> noref_blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server_.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyRelNoreferrer) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server_.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in same tab.
EXPECT_EQ(1, browser()->tab_count());
EXPECT_EQ(0, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> noref_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, noref_site_instance);
}
// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
#defne MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload
#endif // defined(OS_WIN)
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
MAYBE_ChromeURLAfterDownload) {
GURL downloads_url("chrome://downloads");
GURL extensions_url("chrome://extensions");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
ui_test_utils::NavigateToURL(browser(), extensions_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool domui_responded = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.domAutomationController.send(window.domui_responded_);",
&domui_responded));
EXPECT_TRUE(domui_responded);
}
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::BROWSER_CLOSED:
MessageLoopForUI::current()->Quit();
break;
}
}
private:
NotificationRegistrar registrar_;
};
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_BrowserCloseAfterDownload) {
GURL downloads_url("chrome://downloads");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
ASSERT_TRUE(file_util::PathExists(zip_download));
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.onunload = function() { var do_nothing = 0; }; "
L"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
browser()->CloseWindow();
BrowserClosedObserver wait_for_close(browser());
}
<commit_msg>Disable RenderViewHostManagerTest.DontSwapProcessWithOnlyTargetBlank<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/ref_counted.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
class RenderViewHostManagerTest : public InProcessBrowserTest {
public:
RenderViewHostManagerTest() {
EnableDOMAutomation();
}
static bool GetFilePathWithHostAndPortReplacement(
const std::string& original_file_path,
const net::HostPortPair& host_port_pair,
std::string* replacement_path) {
std::vector<net::TestServer::StringPair> replacement_text;
replacement_text.push_back(
make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
return net::TestServer::GetFilePathWithReplacements(
original_file_path, replacement_text, replacement_path);
}
};
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
SwapProcessWithRelNoreferrerAndTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server_.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer + target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have a new SiteInstance.
scoped_refptr<SiteInstance> noref_blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
// Disabled, http://crbug.com/67532.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_DontSwapProcessWithOnlyTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server_.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyRelNoreferrer) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server_.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in same tab.
EXPECT_EQ(1, browser()->tab_count());
EXPECT_EQ(0, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> noref_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, noref_site_instance);
}
// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
#defne MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload
#endif // defined(OS_WIN)
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
MAYBE_ChromeURLAfterDownload) {
GURL downloads_url("chrome://downloads");
GURL extensions_url("chrome://extensions");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
ui_test_utils::NavigateToURL(browser(), extensions_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool domui_responded = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.domAutomationController.send(window.domui_responded_);",
&domui_responded));
EXPECT_TRUE(domui_responded);
}
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::BROWSER_CLOSED:
MessageLoopForUI::current()->Quit();
break;
}
}
private:
NotificationRegistrar registrar_;
};
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_BrowserCloseAfterDownload) {
GURL downloads_url("chrome://downloads");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
ASSERT_TRUE(file_util::PathExists(zip_download));
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.onunload = function() { var do_nothing = 0; }; "
L"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
browser()->CloseWindow();
BrowserClosedObserver wait_for_close(browser());
}
<|endoftext|> |
<commit_before>/*
Resembla
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "flag_feature_aggregator.hpp"
#include <algorithm>
#include <iostream>
namespace resembla {
Feature::real_type FlagFeatureAggregatorImpl::operator()(Feature::real_type a, Feature::real_type b) const
{
auto c = (std::abs(a) + std::abs(b) - 3.0 * std::abs(a - b)) / 2.0;
#ifdef DEBUG
std::cerr << "flag-type feature: a=" << a << ", b=" << b << ", c=" << c << std::endl;
#endif
return std::min(std::max(c, -1.0), 1.0);
}
}
<commit_msg>include header<commit_after>/*
Resembla
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "flag_feature_aggregator.hpp"
#include <cmath>
#include <algorithm>
#ifdef DEBUG
#include <iostream>
#endif
namespace resembla {
Feature::real_type FlagFeatureAggregatorImpl::operator()(Feature::real_type a, Feature::real_type b) const
{
auto c = (std::abs(a) + std::abs(b) - 3.0 * std::abs(a - b)) / 2.0;
#ifdef DEBUG
std::cerr << "flag-type feature: a=" << a << ", b=" << b << ", c=" << c << std::endl;
#endif
return std::min(std::max(c, -1.0), 1.0);
}
}
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2012 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
#include "event.hh"
#include "transaction.hh"
#include "common.hh"
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_tagarg.h>
using namespace ::std;
MsgSip::MsgSip(msg_t *msg, sip_t *sip) {
LOGD("New MsgSip %p", this);
mMsg = msg_copy(msg);
mSip = sip_object(mMsg);
mHome = msg_home(mMsg);
}
MsgSip::MsgSip(const MsgSip &msgSip) {
LOGD("New MsgSip %p", this);
mMsg = msg_copy(msgSip.mMsg);
mSip = sip_object(mMsg);
mHome = msg_home(mMsg);
}
void MsgSip::log(const char *fmt, ...) {
if (IS_LOGD) {
size_t msg_size;
char *header = NULL;
char *buf = NULL;
if (fmt) {
va_list args;
va_start(args, fmt);
header = su_vsprintf(mHome, fmt, args);
va_end(args);
}
buf = msg_as_string(mHome, mMsg, NULL, 0, &msg_size);
LOGD("%s%s%s", (header) ? header : "", (header) ? "\n" : "", buf);
}
}
MsgSip::~MsgSip() {
LOGD("Destroy MsgSip %p", this);
msg_destroy(mMsg);
}
SipEvent::SipEvent(const shared_ptr<MsgSip> msgSip) :
mCurrModule(NULL), mMsgSip(msgSip), mState(STARTED) {
LOGD("New SipEvent %p", this);
}
SipEvent::SipEvent(const SipEvent &sipEvent) :
mCurrModule(sipEvent.mCurrModule), mMsgSip(sipEvent.mMsgSip), mIncomingAgent(sipEvent.mIncomingAgent), mOutgoingAgent(sipEvent.mOutgoingAgent), mState(sipEvent.mState) {
LOGD("New SipEvent %p", this);
}
SipEvent::~SipEvent() {
LOGD("Destroy SipEvent %p", this);
}
void SipEvent::terminateProcessing() {
LOGD("Terminate SipEvent %p", this);
if (mState == STARTED || mState == SUSPENDED) {
mState = TERMINATED;
} else {
LOGA("Can't terminateProcessing: wrong state");
}
}
void SipEvent::suspendProcessing() {
LOGD("Suspend SipEvent %p", this);
if (mState == STARTED) {
mState = SUSPENDED;
} else {
LOGA("Can't suspendProcessing: wrong state");
}
}
void SipEvent::restartProcessing() {
LOGD("Restart SipEvent %p", this);
if (mState == SUSPENDED) {
mState = STARTED;
} else {
LOGA("Can't restartProcessing: wrong state");
}
}
shared_ptr<IncomingTransaction> SipEvent::createIncomingTransaction() {
shared_ptr<IncomingTransaction> transaction = dynamic_pointer_cast<IncomingTransaction>(mIncomingAgent);
if (transaction == NULL) {
transaction = shared_ptr<IncomingTransaction>(new IncomingTransaction(mIncomingAgent->getAgent()));
transaction->handle(mMsgSip);
mIncomingAgent = transaction;
}
return transaction;
}
shared_ptr<OutgoingTransaction> SipEvent::createOutgoingTransaction() {
shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(mOutgoingAgent);
if (transaction == NULL) {
transaction = shared_ptr<OutgoingTransaction>(new OutgoingTransaction(mOutgoingAgent->getAgent()));
mOutgoingAgent = transaction;
}
return transaction;
}
RequestSipEvent::RequestSipEvent(const shared_ptr<IncomingAgent> &incomingAgent, const shared_ptr<MsgSip> &msgSip) :
SipEvent(msgSip) {
mIncomingAgent = incomingAgent;
mOutgoingAgent = incomingAgent->getAgent()->shared_from_this();
}
RequestSipEvent::RequestSipEvent(const shared_ptr<SipEvent> &sipEvent) :
SipEvent(*sipEvent) {
}
void RequestSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
if (mOutgoingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Request SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
}
ta_list ta;
ta_start(ta, tag, value);
mOutgoingAgent->send(msg, u, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Request SIP message is not send");
}
terminateProcessing();
}
void RequestSipEvent::send(const shared_ptr<MsgSip> &msg) {
if (mOutgoingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Request SIP message:");
}
mOutgoingAgent->send(msg);
} else {
LOGD("The Request SIP message is not send");
}
terminateProcessing();
}
void RequestSipEvent::reply(const shared_ptr<MsgSip> &msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
LOGD("Replying Request SIP message: %i %s\n\n", status, phrase);
}
ta_list ta;
ta_start(ta, tag, value);
mIncomingAgent->reply(msg, status, phrase, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Request SIP message is not reply");
}
terminateProcessing();
}
void RequestSipEvent::setIncomingAgent(const shared_ptr<IncomingAgent> &agent) {
LOGA("Can't change incoming agent in request sip event");
}
RequestSipEvent::~RequestSipEvent() {
}
ResponseSipEvent::ResponseSipEvent(const shared_ptr<OutgoingAgent> &outgoingAgent, const shared_ptr<MsgSip> &msgSip) :
SipEvent(msgSip) {
mOutgoingAgent = outgoingAgent;
mIncomingAgent = outgoingAgent->getAgent()->shared_from_this();
}
ResponseSipEvent::ResponseSipEvent(const shared_ptr<SipEvent> &sipEvent) :
SipEvent(*sipEvent) {
}
void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Response SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
}
ta_list ta;
ta_start(ta, tag, value);
mIncomingAgent->send(msg, u, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Response SIP message is not send");
}
terminateProcessing();
}
void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Response SIP message:");
}
mIncomingAgent->send(msg);
} else {
LOGD("The Response SIP message is not send");
}
terminateProcessing();
}
void ResponseSipEvent::reply(const shared_ptr<MsgSip> &msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
LOGA("Can't reply to an response sip event");
}
void ResponseSipEvent::setOutgoingAgent(const shared_ptr<OutgoingAgent> &agent) {
LOGA("Can't change outgoing agent in response sip event");
}
ResponseSipEvent::~ResponseSipEvent() {
}
<commit_msg>cleanup traces<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2012 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
#include "event.hh"
#include "transaction.hh"
#include "common.hh"
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_tagarg.h>
using namespace ::std;
MsgSip::MsgSip(msg_t *msg, sip_t *sip) {
//LOGD("New MsgSip %p", this);
mMsg = msg_copy(msg);
mSip = sip_object(mMsg);
mHome = msg_home(mMsg);
}
MsgSip::MsgSip(const MsgSip &msgSip) {
//LOGD("New MsgSip %p", this);
mMsg = msg_copy(msgSip.mMsg);
mSip = sip_object(mMsg);
mHome = msg_home(mMsg);
}
void MsgSip::log(const char *fmt, ...) {
if (IS_LOGD) {
size_t msg_size;
char *header = NULL;
char *buf = NULL;
if (fmt) {
va_list args;
va_start(args, fmt);
header = su_vsprintf(mHome, fmt, args);
va_end(args);
}
buf = msg_as_string(mHome, mMsg, NULL, 0, &msg_size);
LOGD("%s%s%s", (header) ? header : "", (header) ? "\n" : "", buf);
}
}
MsgSip::~MsgSip() {
//LOGD("Destroy MsgSip %p", this);
msg_destroy(mMsg);
}
SipEvent::SipEvent(const shared_ptr<MsgSip> msgSip) :
mCurrModule(NULL), mMsgSip(msgSip), mState(STARTED) {
LOGD("New SipEvent %p", this);
}
SipEvent::SipEvent(const SipEvent &sipEvent) :
mCurrModule(sipEvent.mCurrModule), mMsgSip(sipEvent.mMsgSip), mIncomingAgent(sipEvent.mIncomingAgent), mOutgoingAgent(sipEvent.mOutgoingAgent), mState(sipEvent.mState) {
LOGD("New SipEvent %p", this);
}
SipEvent::~SipEvent() {
//LOGD("Destroy SipEvent %p", this);
}
void SipEvent::terminateProcessing() {
LOGD("Terminate SipEvent %p", this);
if (mState == STARTED || mState == SUSPENDED) {
mState = TERMINATED;
} else {
LOGA("Can't terminateProcessing: wrong state");
}
}
void SipEvent::suspendProcessing() {
LOGD("Suspend SipEvent %p", this);
if (mState == STARTED) {
mState = SUSPENDED;
} else {
LOGA("Can't suspendProcessing: wrong state");
}
}
void SipEvent::restartProcessing() {
LOGD("Restart SipEvent %p", this);
if (mState == SUSPENDED) {
mState = STARTED;
} else {
LOGA("Can't restartProcessing: wrong state");
}
}
shared_ptr<IncomingTransaction> SipEvent::createIncomingTransaction() {
shared_ptr<IncomingTransaction> transaction = dynamic_pointer_cast<IncomingTransaction>(mIncomingAgent);
if (transaction == NULL) {
transaction = shared_ptr<IncomingTransaction>(new IncomingTransaction(mIncomingAgent->getAgent()));
transaction->handle(mMsgSip);
mIncomingAgent = transaction;
}
return transaction;
}
shared_ptr<OutgoingTransaction> SipEvent::createOutgoingTransaction() {
shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(mOutgoingAgent);
if (transaction == NULL) {
transaction = shared_ptr<OutgoingTransaction>(new OutgoingTransaction(mOutgoingAgent->getAgent()));
mOutgoingAgent = transaction;
}
return transaction;
}
RequestSipEvent::RequestSipEvent(const shared_ptr<IncomingAgent> &incomingAgent, const shared_ptr<MsgSip> &msgSip) :
SipEvent(msgSip) {
mIncomingAgent = incomingAgent;
mOutgoingAgent = incomingAgent->getAgent()->shared_from_this();
}
RequestSipEvent::RequestSipEvent(const shared_ptr<SipEvent> &sipEvent) :
SipEvent(*sipEvent) {
}
void RequestSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
if (mOutgoingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Request SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
}
ta_list ta;
ta_start(ta, tag, value);
mOutgoingAgent->send(msg, u, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Request SIP message is not send");
}
terminateProcessing();
}
void RequestSipEvent::send(const shared_ptr<MsgSip> &msg) {
if (mOutgoingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Request SIP message:");
}
mOutgoingAgent->send(msg);
} else {
LOGD("The Request SIP message is not send");
}
terminateProcessing();
}
void RequestSipEvent::reply(const shared_ptr<MsgSip> &msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
LOGD("Replying Request SIP message: %i %s\n\n", status, phrase);
}
ta_list ta;
ta_start(ta, tag, value);
mIncomingAgent->reply(msg, status, phrase, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Request SIP message is not reply");
}
terminateProcessing();
}
void RequestSipEvent::setIncomingAgent(const shared_ptr<IncomingAgent> &agent) {
LOGA("Can't change incoming agent in request sip event");
}
RequestSipEvent::~RequestSipEvent() {
}
ResponseSipEvent::ResponseSipEvent(const shared_ptr<OutgoingAgent> &outgoingAgent, const shared_ptr<MsgSip> &msgSip) :
SipEvent(msgSip) {
mOutgoingAgent = outgoingAgent;
mIncomingAgent = outgoingAgent->getAgent()->shared_from_this();
}
ResponseSipEvent::ResponseSipEvent(const shared_ptr<SipEvent> &sipEvent) :
SipEvent(*sipEvent) {
}
void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Response SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
}
ta_list ta;
ta_start(ta, tag, value);
mIncomingAgent->send(msg, u, ta_tags(ta));
ta_end(ta);
} else {
LOGD("The Response SIP message is not send");
}
terminateProcessing();
}
void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg) {
if (mIncomingAgent != NULL) {
if (IS_LOGD) {
msg->log("Sending Response SIP message:");
}
mIncomingAgent->send(msg);
} else {
LOGD("The Response SIP message is not send");
}
terminateProcessing();
}
void ResponseSipEvent::reply(const shared_ptr<MsgSip> &msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
LOGA("Can't reply to an response sip event");
}
void ResponseSipEvent::setOutgoingAgent(const shared_ptr<OutgoingAgent> &agent) {
LOGA("Can't change outgoing agent in response sip event");
}
ResponseSipEvent::~ResponseSipEvent() {
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* 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
*
* "@(#) $Id: bulkDataNTStream.cpp,v 1.21 2011/09/28 16:43:42 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2011-04-19 created
*/
#include "bulkDataNTStream.h"
#include <iostream>
using namespace ACS_BD_Errors;
using namespace ACSErrTypeCommon;
using namespace ACS_DDS_Errors;
using namespace AcsBulkdata;
BulkDataNTStream::BulkDataNTStream(const char* name, const StreamConfiguration &cfg) :
streamName_m(name), configuration_m(cfg), factory_m(0), participant_m(0)
{
AUTO_TRACE(__PRETTY_FUNCTION__);
try
{
createDDSFactory();
createDDSParticipant(); //should be somewhere else in initialize or createStream
}catch(const ACSErr::ACSbaseExImpl &e)
{
if (factory_m!=0)
DDS::DomainParticipantFactory::finalize_instance();
StreamCreateProblemExImpl ex (e, __FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setStreamName(name);
throw ex;
}//try-catch
}//BulkDataNTStream
BulkDataNTStream::~BulkDataNTStream()
{
AUTO_TRACE(__PRETTY_FUNCTION__);
destroyDDSParticipant();
DDS::DomainParticipantFactory::finalize_instance();
}//~BulkDataNTStream
void BulkDataNTStream::createDDSFactory()
{
AUTO_TRACE(__PRETTY_FUNCTION__);
DDS::ReturnCode_t ret;
DDS::DomainParticipantFactoryQos factory_qos;
factory_m = DDS::DomainParticipantFactory::get_instance();
// needed by RTI only
ret = factory_m->get_qos(factory_qos);
if (ret!=DDS::RETCODE_OK)
{
DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDDSTypeCode(ret);
ex.setQoS("factory_m->get_qos");
throw ex;
}//if
factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
// if both values are true (default) we prevent that default values are taken from default places
factory_qos.profile.ignore_user_profile = configuration_m.ignoreUserProfileQoS;
factory_qos.profile.ignore_environment_profile = configuration_m.ignoreEnvironmentProfileQoS;
if (configuration_m.stringProfileQoS.length()>0)
{
factory_qos.profile.string_profile.ensure_length(1,1);
factory_qos.profile.string_profile[0] = DDS_String_dup(configuration_m.stringProfileQoS.c_str());
}//if
if (configuration_m.urlProfileQoS.length()>0)
{
factory_qos.profile.url_profile.ensure_length(1,1);
factory_qos.profile.url_profile[0] = DDS_String_dup(configuration_m.urlProfileQoS.c_str());
}//if
ret = factory_m->set_qos(factory_qos);
if (ret!=DDS::RETCODE_OK)
{
DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDDSTypeCode(ret);
ex.setQoS("factory_m->set_qos");
throw ex;
}//if
//RTI logging
NDDSConfigLogger::get_instance()->set_verbosity_by_category(
NDDS_CONFIG_LOG_CATEGORY_API,
(NDDS_Config_LogVerbosity)(configuration_m.DDSLogVerbosity));
}//createDDSFactory
void BulkDataNTStream::createDDSParticipant()
{
AUTO_TRACE(__PRETTY_FUNCTION__);
DDS::ReturnCode_t ret;
DDS::DomainParticipantQos participant_qos;
int domainID=0; //TBD: where to get domain ID
if (factory_m==NULL)
{
NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setVariable("factory_m");
throw ex;
}
if (participant_m!=NULL)
{
printf("participant already created\n");
return;
}
ret = factory_m->get_participant_qos_from_profile(participant_qos, configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str());
if (ret!=DDS::RETCODE_OK)
{
DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDDSTypeCode(ret);
ex.setQoS("get_participant_qos_from_profile");
throw ex;
}//if
participant_m =factory_m->create_participant(domainID, participant_qos, NULL, DDS::STATUS_MASK_NONE );
if (participant_m==NULL)
{
DDSParticipantCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDomainID(domainID);
throw ex;
}
ret = participant_m->enable();
}//createDDSParticipant
void BulkDataNTStream::destroyDDSParticipant()
{
DDS::ReturnCode_t ret;
AUTO_TRACE(__PRETTY_FUNCTION__);
ret = factory_m->delete_participant(participant_m);
if (ret != DDS_RETCODE_OK)
{
DDSParticipantDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.log();
}//if
}//destroyDDSParticipant
<commit_msg>added error handling for enable participant<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* 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
*
* "@(#) $Id: bulkDataNTStream.cpp,v 1.22 2011/11/25 09:07:13 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2011-04-19 created
*/
#include "bulkDataNTStream.h"
#include <iostream>
using namespace ACS_BD_Errors;
using namespace ACSErrTypeCommon;
using namespace ACS_DDS_Errors;
using namespace AcsBulkdata;
BulkDataNTStream::BulkDataNTStream(const char* name, const StreamConfiguration &cfg) :
streamName_m(name), configuration_m(cfg), factory_m(0), participant_m(0)
{
AUTO_TRACE(__PRETTY_FUNCTION__);
try
{
createDDSFactory();
createDDSParticipant(); //should be somewhere else in initialize or createStream
}catch(const ACSErr::ACSbaseExImpl &e)
{
if (factory_m!=0)
DDS::DomainParticipantFactory::finalize_instance();
StreamCreateProblemExImpl ex (e, __FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setStreamName(name);
throw ex;
}//try-catch
}//BulkDataNTStream
BulkDataNTStream::~BulkDataNTStream()
{
AUTO_TRACE(__PRETTY_FUNCTION__);
destroyDDSParticipant();
DDS::DomainParticipantFactory::finalize_instance();
}//~BulkDataNTStream
void BulkDataNTStream::createDDSFactory()
{
AUTO_TRACE(__PRETTY_FUNCTION__);
DDS::ReturnCode_t ret;
DDS::DomainParticipantFactoryQos factory_qos;
factory_m = DDS::DomainParticipantFactory::get_instance();
// needed by RTI only
ret = factory_m->get_qos(factory_qos);
if (ret!=DDS::RETCODE_OK)
{
DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDDSTypeCode(ret);
ex.setQoS("factory_m->get_qos");
throw ex;
}//if
factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
// if both values are true (default) we prevent that default values are taken from default places
factory_qos.profile.ignore_user_profile = configuration_m.ignoreUserProfileQoS;
factory_qos.profile.ignore_environment_profile = configuration_m.ignoreEnvironmentProfileQoS;
if (configuration_m.stringProfileQoS.length()>0)
{
factory_qos.profile.string_profile.ensure_length(1,1);
factory_qos.profile.string_profile[0] = DDS_String_dup(configuration_m.stringProfileQoS.c_str());
}//if
if (configuration_m.urlProfileQoS.length()>0)
{
factory_qos.profile.url_profile.ensure_length(1,1);
factory_qos.profile.url_profile[0] = DDS_String_dup(configuration_m.urlProfileQoS.c_str());
}//if
ret = factory_m->set_qos(factory_qos);
if (ret!=DDS::RETCODE_OK)
{
DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDDSTypeCode(ret);
ex.setQoS("factory_m->set_qos");
throw ex;
}//if
//RTI logging
NDDSConfigLogger::get_instance()->set_verbosity_by_category(
NDDS_CONFIG_LOG_CATEGORY_API,
(NDDS_Config_LogVerbosity)(configuration_m.DDSLogVerbosity));
}//createDDSFactory
void BulkDataNTStream::createDDSParticipant()
{
AUTO_TRACE(__PRETTY_FUNCTION__);
DDS::ReturnCode_t ret;
DDS::DomainParticipantQos participant_qos;
int domainID=0; //TBD: where to get domain ID
if (factory_m==NULL)
{
NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setVariable("factory_m");
throw ex;
}
if (participant_m!=NULL)
{
printf("participant already created\n");
return;
}
ret = factory_m->get_participant_qos_from_profile(participant_qos, configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str());
if (ret!=DDS::RETCODE_OK)
{
DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDDSTypeCode(ret);
ex.setQoS("get_participant_qos_from_profile");
throw ex;
}//if
participant_m =factory_m->create_participant(domainID, participant_qos, NULL, DDS::STATUS_MASK_NONE );
if (participant_m==NULL)
{
DDSParticipantCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDomainID(domainID);
throw ex;
}
ret = participant_m->enable();
if (ret!=DDS::RETCODE_OK)
{
DDSParticipantEnableProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.setDDSTypeCode(ret);
ex.setDomainID(domainID);
throw ex;
}//if
}//createDDSParticipant
void BulkDataNTStream::destroyDDSParticipant()
{
DDS::ReturnCode_t ret;
AUTO_TRACE(__PRETTY_FUNCTION__);
ret = factory_m->delete_participant(participant_m);
if (ret != DDS_RETCODE_OK)
{
DDSParticipantDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
ex.log();
}//if
}//destroyDDSParticipant
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>
using namespace std;
//___ERROR LIST___
//test exit after commands
//test semi-colons before/after commands
//Prompt multi-prints when space-separated garbage is entered
//Test with whitespace before/inbetween/after commands
//Test touch with large, small, and symbol commands
int main(int argc, char*argv[]){
bool isRunning = true;
while(isRunning){
cout << "$"; //Prints the Prompt
string input;
getline(cin, input);
if(input == "exit"){ //Exit Check
cout << "Exiting rshell..." << endl;
return 0;
}
int cnt = 0;//where cnt used to be - FIXME
char * tokInput = new char[input.size() + 1];
copy(input.begin(), input.end(), tokInput);//tokInput now = input
tokInput[input.size()] = '\0'; //Null terminates array
char* token = strtok(tokInput, "-;|&\""); //parses rawInput
while(token != NULL){//Tokenization
cout << "token: " << token << endl;//output - FIXME
/*if(*token == '#'){
strcpy(argv[cnt], "\0"); //null terminates argv
token = NULL;
}*/
argv[cnt] = token;//places tokens into argv
// strcat(argv[cnt], "\0");//adds null char to argv
token = strtok(NULL, "-;|&\" "); //looks for connectors
cnt++; //increment count
}
//strcat(argv[cnt], "\0");//Null terminates argv[]
for(int i = 0; i < cnt; i++){ //prints all values of argv[] - FIXME
cout << "argv[" << i << "]: " << argv[i] << endl;
}
int pid = fork();//forks the process
if(pid == 0){ //child process
//if(execvp(argv[0], &argv[0]) == -1){ - Old
if(execvp(argv[0], argv) == -1){
perror("execvp failure");
}
exit(1);
}else{ //parent
if(-1 == wait(NULL)){
perror("wait() failure");
}
}
}//end isRunning loop
return 0;
}
<commit_msg>New exec.cpp, now tokenizes properly and handles comments<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>
using namespace std;
int main(int argc, char*argv[]){
bool isOn = true; //Keeps track of whether rshell is still running
string usrInput;
while(isOn){
cout << "$ "; //Prints prompt
getline(cin, usrInput);
char* inputCpy = new char[usrInput.length() + 1]; //pointer for input string
strcpy(inputCpy, usrInput.c_str()); //token now holds c-string copy of input
char* token = strtok(inputCpy, " ;"); //removes semicolons
unsigned cnt = 0; //counter for slots in argv[]
while(token != NULL){
cout << token << endl;//Fixme - remove later
if(*token == '#'){ //Handles comments
token = NULL;
}else{ //Default scenario
argv[cnt] = token;
token = strtok(NULL, " ;");
cnt++;
}
}
for(unsigned i = 0; i < cnt; i++){
cout << "Argv[" << i << "]: " << argv[i] << endl; //Fixme - remove later
}
}
return 0;
}
//---------------------OLD CODE BELOW THIS LINE---------------------
//___ERROR LIST___
//test exit after commands
//test semi-colons before/after commands
//Prompt multi-prints when space-separated garbage is entered
//Test with whitespace before/inbetween/after commands
//Test touch with large, small, and symbol commands
//Must work with &&'s and ||'s as connectors
/*
int main(int argc, char*argv[]){
bool isRunning = true;
while(isRunning){
cout << "$"; //Prints the Prompt
string input;
getline(cin, input);
if(input == "exit"){ //Exit Check
cout << "Exiting rshell..." << endl;
return 0;
}
int cnt = 0;
char * tokInput = new char[input.size() + 1];
copy(input.begin(), input.end(), tokInput);//tokInput now = input
tokInput[input.size()] = '\0'; //Null terminates array
char* token = strtok(tokInput, ";"); //parses rawInput
char* arr[] = strtok(tokInput, ";");
while(token != NULL){//Tokenization
cout << "token: " << token << endl;//output - FIXME
//if(*token == '#'){
//strcpy(argv[cnt], "\0"); //null terminates argv
//token = NULL;
}
argv[cnt] = token;//places tokenized strings into argv
strcat(argv[cnt], "\0");//adds null char to strings in argv
token = strtok(NULL, " "); //looks for connectors
cnt++; //increment count
}
//strcat(argv[cnt], "\0");//Null terminates argv[]
for(int i = 0; i < cnt; i++){ //prints all values of argv[] - FIXME
cout << "argv[" << i << "]: " << argv[i] << endl;
}
int pid = fork();//forks the process
if(pid == 0){ //child process
//if(execvp(argv[0], &argv[0]) == -1){ - Old
if(execvp(argv[0], argv) == -1){
perror("execvp failure");
}
exit(1);
}else{ //parent
if(-1 == wait(NULL)){
perror("wait() failure");
}
}
}//end isRunning loop
return 0;
}
*/
<|endoftext|> |
<commit_before>// BriocheBot
// The MIT License(MIT)
//
// Copyright(c) 2015 Abricot Soinou <[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.
///////////////////////////////////////////////
//
// Current mode: Database migration
// Will migrate everything from the old players
// to the new viewers-models
//
///////////////////////////////////////////////
#include "models/viewers.h"
#include "models/viewer.h"
#include "models/streamer.h"
#include "models/moderator.h"
#include "utils/redis.h"
#include "utils/utils.h"
// Extra program, used to do some extra things
int main()
{
the_viewers.load();
// Connect to redis
Redis::Connection connection("127.0.0.1", 6379);
// Json reader we'll use
Json::Reader reader;
printf("Getting all keys...\n\n");
// Get all the keys we have in redis
Redis::Reply reply = connection.execute("KEYS *");
printf("Got all keys, scanning keys...\n");
// If we got an array
if (reply.type == Redis::Reply::Array)
{
int count = the_viewers.max_id();
// For each key
for (auto i = reply.elements.begin(); i != reply.elements.end(); i++)
{
// Get this element
Redis::Reply element = *i;
printf(" Scanning key \"%s\"...\n", element.string.c_str());
// Get the element value
int value = atoi(element.string.c_str());
// We got 0
if (value == 0)
// Not valid
printf(" Key is not valid, skipping\n\n");
// We got a number
else
{
// Valid
printf(" Key is a streamer, getting data...\n", value);
// Get the streamer
Redis::Reply streamer = connection.execute(Utils::string_format("GET %d", value));
// Reply is a string
if (streamer.type == Redis::Reply::String)
{
printf(" Got data, creating streamer...\n");
// Json we'll need
Json::Value json;
// Parse the json
reader.parse(streamer.string, json);
// If the streamer already exists, skip
if (the_viewers.exists(json["twitch_username"].asString()))
printf(" Streamer already exists, skipping\n\n");
// If the streamer doesn't already exists
else
{
// Create a new streamer
Streamer* new_streamer = nullptr;
// If this streamer was an admin
if (json["admin"].asBool())
{
// Create a new moderator
Moderator* moderator = new Moderator();
// Set his privileges
moderator->set_privileges(1);
// Pass it to our viewer
new_streamer = moderator;
}
// Else
else
// Just create a new streamer
new_streamer = new Streamer();
// Set streamer data
new_streamer->set_id(count++);
new_streamer->set_twitch_username(json["twitch_username"].asString());
new_streamer->set_osu_username(json["osu_username"].asString());
new_streamer->set_osu_skin_link(json["osu_skin"].asString());
printf(" Streamer created, adding him...\n");
// Insert the streamer
new_streamer->insert();
printf(" Streamer added!\n\n");
}
}
}
}
}
return 0;
}
<commit_msg>Little mistake<commit_after>// BriocheBot
// The MIT License(MIT)
//
// Copyright(c) 2015 Abricot Soinou <[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.
///////////////////////////////////////////////
//
// Current mode: Database migration
// Will migrate everything from the old players
// to the new viewers-models
//
///////////////////////////////////////////////
#include "models/viewers.h"
#include "models/viewer.h"
#include "models/streamer.h"
#include "models/moderator.h"
#include "utils/redis.h"
#include "utils/utils.h"
// Extra program, used to do some extra things
int main()
{
the_viewers.load();
// Connect to redis
Redis::Connection connection("127.0.0.1", 6379);
// Json reader we'll use
Json::Reader reader;
printf("Getting all keys...\n\n");
// Get all the keys we have in redis
Redis::Reply reply = connection.execute("KEYS *");
printf("Got all keys, scanning keys...\n");
// If we got an array
if (reply.type == Redis::Reply::Array)
{
int count = the_viewers.max_id();
// For each key
for (auto i = reply.elements.begin(); i != reply.elements.end(); i++)
{
// Get this element
Redis::Reply element = *i;
printf(" Scanning key \"%s\"...\n", element.string.c_str());
// Get the element value
int value = atoi(element.string.c_str());
// We got 0
if (value == 0)
// Not valid
printf(" Key is not valid, skipping\n\n");
// We got a number
else
{
// Valid
printf(" Key is a streamer, getting data...\n");
// Get the streamer
Redis::Reply streamer = connection.execute(Utils::string_format("GET %d", value));
// Reply is a string
if (streamer.type == Redis::Reply::String)
{
printf(" Got data, creating streamer...\n");
// Json we'll need
Json::Value json;
// Parse the json
reader.parse(streamer.string, json);
// If the streamer already exists, skip
if (the_viewers.exists(json["twitch_username"].asString()))
printf(" Streamer already exists, skipping\n\n");
// If the streamer doesn't already exists
else
{
// Create a new streamer
Streamer* new_streamer = nullptr;
// If this streamer was an admin
if (json["admin"].asBool())
{
// Create a new moderator
Moderator* moderator = new Moderator();
// Set his privileges
moderator->set_privileges(1);
// Pass it to our viewer
new_streamer = moderator;
}
// Else
else
// Just create a new streamer
new_streamer = new Streamer();
// Set streamer data
new_streamer->set_id(count++);
new_streamer->set_twitch_username(json["twitch_username"].asString());
new_streamer->set_osu_username(json["osu_username"].asString());
new_streamer->set_osu_skin_link(json["osu_skin"].asString());
printf(" Streamer created, adding him...\n");
// Insert the streamer
new_streamer->insert();
printf(" Streamer added!\n\n");
}
}
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>#define FUSE_USE_VERSION 26
#include "FBGraph.h"
#include "FBQuery.h"
#include "Util.h"
#include <boost/filesystem.hpp>
#include <fuse.h>
#include "json_spirit.h"
#include <cerrno>
#include <ctime>
#include <cstring>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <system_error>
static const std::string LOGIN_ERROR = "You are not logged in, so the program cannot fetch your profile. Terminating.";
static const std::string LOGIN_SUCCESS = "You are now logged into Facebook.";
static const std::string PERMISSION_CHECK_ERROR = "Could not determine app permissions.";
static const std::string POST_FILE_NAME = "post";
static inline FBGraph* get_fb_graph() {
return static_cast<FBGraph*>(fuse_get_context()->private_data);
}
static inline std::string dirname(const std::string &path) {
boost::filesystem::path p(path);
return p.parent_path().string();
}
static inline std::string basename(const std::string &path) {
return boost::filesystem::basename(path);
}
static inline std::set<std::string> get_endpoints() {
return {
"albums",
"friends",
"status",
};
}
static inline std::string get_node_from_path(const std::string &path) {
std::string p(path);
std::string node;
if (basename(p) == POST_FILE_NAME) {
p = dirname(p);
}
if (dirname(p) == "/") {
node = "me";
} else {
std::string friend_name = basename(dirname(p));
node = get_fb_graph()->get_uid_from_name(friend_name);
}
return node;
}
static int fbfs_getattr(const char* cpath, struct stat *stbuf) {
std::string path(cpath);
std::error_condition result;
std::memset(stbuf, 0, sizeof(struct stat));
if (path == "/") {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
return 0;
}
if (basename(dirname(path)) == "friends") {
// This is a directory representing a friend
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
return 0;
}
if (basename(path) == POST_FILE_NAME) {
stbuf->st_mode = S_IFREG | 0200;
stbuf->st_size = 0;
return 0;
}
std::set<std::string> endpoints = get_endpoints();
if (endpoints.count(basename(path))) {
// This is an endpoint
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
} else if (endpoints.count(basename(dirname(path)))) {
// This is a file inside an endpoint
stbuf->st_mode = S_IFREG | 0400;
if (basename(dirname(path)) == "status") {
// Store the date in the file
FBQuery query(basename(path));
query.add_parameter("date_format", "U");
query.add_parameter("fields", "message,updated_time");
json_spirit::mObject status_response = get_fb_graph()->get(query);
if (status_response.count("error")) {
result = std::errc::no_such_file_or_directory;
return -result.value();
}
const time_t updated_time = status_response.at("updated_time").get_int();
timespec time;
time.tv_sec = updated_time;
stbuf->st_mtim = time;
stbuf->st_size = status_response.at("message").get_str().length();
} else if (basename(dirname(path)) == "albums") {
// This is an album
stbuf->st_mode = S_IFDIR | 0755;
return 0;
}
} else {
result = std::errc::no_such_file_or_directory;
return -result.value();
}
return 0;
}
static int fbfs_readdir(const char *cpath, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi) {
(void)offset;
(void)fi;
std::string path(cpath);
std::error_condition result;
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
std::set<std::string> endpoints = get_endpoints();
std::set<std::string> friends = get_fb_graph()->get_friends();
if (path == "/" || friends.count(basename(path))) {
for (auto endpoint : endpoints) {
filler(buf, endpoint.c_str(), NULL, 0);
}
} else if (endpoints.count(basename(path))) {
// Request the user's friends
FBQuery query("me", "friends");
json_spirit::mObject friend_response = get_fb_graph()->get(query);
json_spirit::mArray friends_list = friend_response.at("data").get_array();
std::string node = get_node_from_path(path);
if (basename(path) == "friends") {
if (dirname(path) == "/") {
for (auto friend_obj : friends_list) {
std::string name = friend_obj.get_obj().at("name").get_str();
filler(buf, name.c_str(), NULL, 0);
}
} else {
// We are in a friends directory. We should either make the
// folder read-only, or a symlink to the user's friends.
// TODO: Implement
}
} else if (basename(path) == "status") {
FBQuery query(node, "statuses");
query.add_parameter("date_format", "U");
query.add_parameter("fields", "updated_time,message,id");
json_spirit::mObject status_response = get_fb_graph()->get(query);
json_spirit::mArray statuses = status_response.at("data").get_array();
if (dirname(path) == "/") {
filler(buf, POST_FILE_NAME.c_str(), NULL, 0);
}
for (auto& status : statuses) {
if (!status.get_obj().count("message")) {
// The status doesn't have a message
continue;
}
std::string id = status.get_obj().at("id").get_str();
filler(buf, id.c_str(), NULL, 0);
}
} else if (basename(path) == "albums") {
FBQuery query(node, "albums");
json_spirit::mObject albums_response = get_fb_graph()->get(query);
json_spirit::mArray albums = albums_response.at("data").get_array();
for (auto& album : albums) {
std::string album_name = album.get_obj().at("name").get_str();
filler(buf, album_name.c_str(), NULL, 0);
}
}
}
return 0;
}
static int fbfs_open(const char *cpath, struct fuse_file_info *fi) {
std::string path(cpath);
std::error_condition result;
std::set<std::string> endpoints = get_endpoints();
std::string parent_folder = basename(dirname(path));
if (fi->flags & O_RDONLY) {
result = std::errc::permission_denied;
return -result.value();
}
return 0;
}
static int fbfs_truncate(const char *cpath, off_t size) {
(void)cpath;
(void)size;
return 0;
}
static int fbfs_write(const char *cpath, const char *buf, size_t size,
off_t offset, struct fuse_file_info *fi) {
(void)fi;
std::error_condition result;
std::string path(cpath);
std::set<std::string> endpoints = get_endpoints();
if (endpoints.count(basename(dirname(path)))) {
// We are in an endpoint directory, so we are able to write the file
const char *start = buf + offset;
std::string data(start, size);
// Determine which endpoint we are in
std::string endpoint = basename(dirname(path));
if (endpoint == "status") {
// TODO: Allow writes to friend's walls as well. Unfortunately, it
// is not possible to post directly using the Facebook API.
// Instead, we will have to open a feed dialog.
// https://developers.facebook.com/docs/sharing/reference/feed-dialog
FBQuery query("me", "feed");
query.add_parameter("message", data);
json_spirit::mObject response = get_fb_graph()->post(query);
if (response.count("error")) {
result = std::errc::operation_not_permitted;
std::cerr << response.at("error").get_obj().at("message").get_str();
return -result.value();
}
return data.size();
}
}
return 0;
}
static int fbfs_read(const char *cpath, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi) {
(void)fi;
std::string path(cpath);
std::error_condition result;
FBQuery query(basename(path));
query.add_parameter("fields", "message");
json_spirit::mObject status_response = get_fb_graph()->get(query);
std::string message = status_response.at("message").get_str();
if (static_cast<unsigned>(offset) < message.length()) {
if (offset + size > message.length()) {
size = message.length() - offset;
}
std::memcpy(buf, message.c_str() + offset, size);
} else {
size = 0;
}
return size;
}
static void* fbfs_init(struct fuse_conn_info *ci) {
(void)ci;
FBGraph *fb_graph = new FBGraph();
// We will ask for both user and friend variants of these permissions.
// Refer to https://developers.facebook.com/docs/facebook-login/permissions
// to see what each permission requests.
std::vector<std::string> permissions = {
"status",
};
std::vector<std::string> extended_permissions = {
"publish_actions",
};
fb_graph->login(permissions, extended_permissions);
if (!fb_graph->is_logged_in()) {
std::cout << LOGIN_ERROR << std::endl;
std::exit(EXIT_SUCCESS);
}
std::cout << LOGIN_SUCCESS << std::endl;
return fb_graph;
}
static void fbfs_destroy(void *private_data) {
delete static_cast<FBGraph*>(private_data);
}
static struct fuse_operations fbfs_oper;
void initialize_operations(fuse_operations& operations) {
std::memset(static_cast<void*>(&operations), 0, sizeof(operations));
operations.getattr = fbfs_getattr;
operations.readdir = fbfs_readdir;
operations.open = fbfs_open;
operations.read = fbfs_read;
operations.init = fbfs_init;
operations.destroy = fbfs_destroy;
operations.truncate = fbfs_truncate;
operations.write = fbfs_write;
}
void call_fusermount() {
std::system("fusermount -u testdir");
}
int main(int argc, char *argv[]) {
umask(0);
std::atexit(call_fusermount);
initialize_operations(fbfs_oper);
return fuse_main(argc, argv, &fbfs_oper, NULL);
}
<commit_msg>move error handling into own function<commit_after>#define FUSE_USE_VERSION 26
#include "FBGraph.h"
#include "FBQuery.h"
#include "Util.h"
#include <boost/filesystem.hpp>
#include <fuse.h>
#include "json_spirit.h"
#include <cerrno>
#include <ctime>
#include <cstring>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <system_error>
static const std::string LOGIN_ERROR = "You are not logged in, so the program cannot fetch your profile. Terminating.";
static const std::string LOGIN_SUCCESS = "You are now logged into Facebook.";
static const std::string PERMISSION_CHECK_ERROR = "Could not determine app permissions.";
static const std::string POST_FILE_NAME = "post";
static inline FBGraph* get_fb_graph() {
return static_cast<FBGraph*>(fuse_get_context()->private_data);
}
static inline std::string dirname(const std::string &path) {
boost::filesystem::path p(path);
return p.parent_path().string();
}
static inline std::string basename(const std::string &path) {
return boost::filesystem::basename(path);
}
static inline std::set<std::string> get_endpoints() {
return {
"albums",
"friends",
"status",
};
}
static inline std::error_condition handle_error(const json_spirit::mObject response) {
json_spirit::mObject error = response.at("error").get_obj();
std::cerr << error.at("message").get_str() << std::endl;
if (error.at("type").get_str() == "OAuthException") {
if (error.at("code").get_int() == 803) {
return std::errc::no_such_file_or_directory;
}
return std::errc::permission_denied;
}
return std::errc::operation_not_permitted;
}
static inline std::string get_node_from_path(const std::string &path) {
std::string p(path);
std::string node;
if (basename(p) == POST_FILE_NAME) {
p = dirname(p);
}
if (dirname(p) == "/") {
node = "me";
} else {
std::string friend_name = basename(dirname(p));
node = get_fb_graph()->get_uid_from_name(friend_name);
}
return node;
}
static int fbfs_getattr(const char* cpath, struct stat *stbuf) {
std::string path(cpath);
std::error_condition result;
std::memset(stbuf, 0, sizeof(struct stat));
if (path == "/") {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
return 0;
}
if (basename(dirname(path)) == "friends") {
// This is a directory representing a friend
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
return 0;
}
if (basename(path) == POST_FILE_NAME) {
stbuf->st_mode = S_IFREG | 0200;
stbuf->st_size = 0;
return 0;
}
std::set<std::string> endpoints = get_endpoints();
if (endpoints.count(basename(path))) {
// This is an endpoint
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
} else if (endpoints.count(basename(dirname(path)))) {
// This is a file inside an endpoint
stbuf->st_mode = S_IFREG | 0400;
if (basename(dirname(path)) == "status") {
// Store the date in the file
FBQuery query(basename(path));
query.add_parameter("date_format", "U");
query.add_parameter("fields", "message,updated_time");
json_spirit::mObject status_response = get_fb_graph()->get(query);
if (status_response.count("error")) {
result = handle_error(status_response);
return -result.value();
}
const time_t updated_time = status_response.at("updated_time").get_int();
timespec time;
time.tv_sec = updated_time;
stbuf->st_mtim = time;
stbuf->st_size = status_response.at("message").get_str().length();
} else if (basename(dirname(path)) == "albums") {
// This is an album
stbuf->st_mode = S_IFDIR | 0755;
return 0;
}
} else {
result = std::errc::no_such_file_or_directory;
return -result.value();
}
return 0;
}
static int fbfs_readdir(const char *cpath, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi) {
(void)offset;
(void)fi;
std::string path(cpath);
std::error_condition result;
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
std::set<std::string> endpoints = get_endpoints();
std::set<std::string> friends = get_fb_graph()->get_friends();
if (path == "/" || friends.count(basename(path))) {
for (auto endpoint : endpoints) {
filler(buf, endpoint.c_str(), NULL, 0);
}
} else if (endpoints.count(basename(path))) {
// Request the user's friends
FBQuery query("me", "friends");
json_spirit::mObject friend_response = get_fb_graph()->get(query);
json_spirit::mArray friends_list = friend_response.at("data").get_array();
std::string node = get_node_from_path(path);
if (basename(path) == "friends") {
if (dirname(path) == "/") {
for (auto friend_obj : friends_list) {
std::string name = friend_obj.get_obj().at("name").get_str();
filler(buf, name.c_str(), NULL, 0);
}
} else {
// We are in a friends directory. We should either make the
// folder read-only, or a symlink to the user's friends.
// TODO: Implement
}
} else if (basename(path) == "status") {
FBQuery query(node, "statuses");
query.add_parameter("date_format", "U");
query.add_parameter("fields", "updated_time,message,id");
json_spirit::mObject status_response = get_fb_graph()->get(query);
json_spirit::mArray statuses = status_response.at("data").get_array();
if (dirname(path) == "/") {
filler(buf, POST_FILE_NAME.c_str(), NULL, 0);
}
for (auto& status : statuses) {
if (!status.get_obj().count("message")) {
// The status doesn't have a message
continue;
}
std::string id = status.get_obj().at("id").get_str();
filler(buf, id.c_str(), NULL, 0);
}
} else if (basename(path) == "albums") {
FBQuery query(node, "albums");
json_spirit::mObject albums_response = get_fb_graph()->get(query);
json_spirit::mArray albums = albums_response.at("data").get_array();
for (auto& album : albums) {
std::string album_name = album.get_obj().at("name").get_str();
filler(buf, album_name.c_str(), NULL, 0);
}
}
}
return 0;
}
static int fbfs_open(const char *cpath, struct fuse_file_info *fi) {
std::string path(cpath);
std::error_condition result;
std::set<std::string> endpoints = get_endpoints();
std::string parent_folder = basename(dirname(path));
if (fi->flags & O_RDONLY) {
result = std::errc::permission_denied;
return -result.value();
}
return 0;
}
static int fbfs_truncate(const char *cpath, off_t size) {
(void)cpath;
(void)size;
return 0;
}
static int fbfs_write(const char *cpath, const char *buf, size_t size,
off_t offset, struct fuse_file_info *fi) {
(void)fi;
std::error_condition result;
std::string path(cpath);
std::set<std::string> endpoints = get_endpoints();
if (endpoints.count(basename(dirname(path)))) {
// We are in an endpoint directory, so we are able to write the file
const char *start = buf + offset;
std::string data(start, size);
// Determine which endpoint we are in
std::string endpoint = basename(dirname(path));
if (endpoint == "status") {
// TODO: Allow writes to friend's walls as well. Unfortunately, it
// is not possible to post directly using the Facebook API.
// Instead, we will have to open a feed dialog.
// https://developers.facebook.com/docs/sharing/reference/feed-dialog
FBQuery query("me", "feed");
query.add_parameter("message", data);
json_spirit::mObject response = get_fb_graph()->post(query);
if (response.count("error")) {
result = handle_error(response);
return -result.value();
}
return data.size();
}
}
return 0;
}
static int fbfs_read(const char *cpath, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi) {
(void)fi;
std::string path(cpath);
std::error_condition result;
FBQuery query(basename(path));
query.add_parameter("fields", "message");
json_spirit::mObject status_response = get_fb_graph()->get(query);
std::string message = status_response.at("message").get_str();
if (static_cast<unsigned>(offset) < message.length()) {
if (offset + size > message.length()) {
size = message.length() - offset;
}
std::memcpy(buf, message.c_str() + offset, size);
} else {
size = 0;
}
return size;
}
static void* fbfs_init(struct fuse_conn_info *ci) {
(void)ci;
FBGraph *fb_graph = new FBGraph();
// We will ask for both user and friend variants of these permissions.
// Refer to https://developers.facebook.com/docs/facebook-login/permissions
// to see what each permission requests.
std::vector<std::string> permissions = {
"status",
};
std::vector<std::string> extended_permissions = {
"publish_actions",
};
fb_graph->login(permissions, extended_permissions);
if (!fb_graph->is_logged_in()) {
std::cout << LOGIN_ERROR << std::endl;
std::exit(EXIT_SUCCESS);
}
std::cout << LOGIN_SUCCESS << std::endl;
return fb_graph;
}
static void fbfs_destroy(void *private_data) {
delete static_cast<FBGraph*>(private_data);
}
static struct fuse_operations fbfs_oper;
void initialize_operations(fuse_operations& operations) {
std::memset(static_cast<void*>(&operations), 0, sizeof(operations));
operations.getattr = fbfs_getattr;
operations.readdir = fbfs_readdir;
operations.open = fbfs_open;
operations.read = fbfs_read;
operations.init = fbfs_init;
operations.destroy = fbfs_destroy;
operations.truncate = fbfs_truncate;
operations.write = fbfs_write;
}
void call_fusermount() {
std::system("fusermount -u testdir");
}
int main(int argc, char *argv[]) {
umask(0);
std::atexit(call_fusermount);
initialize_operations(fbfs_oper);
return fuse_main(argc, argv, &fbfs_oper, NULL);
}
<|endoftext|> |
<commit_before>// -*-c++-*-
/*
* $Id$
*
* DirectX file converter for OpenSceneGraph.
* Copyright (c)2002 Ulrich Hertlein <[email protected]>
*
* 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
*/
#include "directx.h"
#include <osg/TexEnv>
#include <osg/CullFace>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Image>
#include <osg/Texture2D>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/FileNameUtils>
#include <assert.h>
/**
* OpenSceneGraph plugin wrapper/converter.
*/
class ReaderWriterDirectX : public osgDB::ReaderWriter
{
public:
ReaderWriterDirectX() { }
virtual const char* className() {
return "DirectX Reader/Writer";
}
virtual bool acceptsExtension(const std::string& extension) {
return osgDB::equalCaseInsensitive(extension,"x") ? true : false;
}
virtual ReadResult readNode(const std::string& fileName,
const osgDB::ReaderWriter::Options* options);
private:
osg::Geode* convertFromDX(DX::Object& obj, bool flipTexture, float creaseAngle);
};
// Register with Registry to instantiate the above reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterDirectX> g_readerWriter_DirectX_Proxy;
// Read node
osgDB::ReaderWriter::ReadResult ReaderWriterDirectX::readNode(const std::string& fileName,
const osgDB::ReaderWriter::Options* options)
{
std::string ext = osgDB::getLowerCaseFileExtension(fileName);
if (!acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
osg::notify(osg::INFO) << "ReaderWriterDirectX::readNode(" << fileName.c_str() << ")\n";
// Load DirectX mesh
DX::Object obj;
if (obj.load(fileName.c_str())) {
// Options?
bool flipTexture = true;
float creaseAngle = 80.0f;
if (options) {
const std::string option = options->getOptionString();
if (option.find("flipTexture") != std::string::npos)
flipTexture = false;
if (option.find("creaseAngle") != std::string::npos) {
// TODO
}
}
// Convert to osg::Geode
osg::Geode* geode = convertFromDX(obj, flipTexture, creaseAngle);
if (!geode)
return ReadResult::FILE_NOT_HANDLED;
return geode;
}
return ReadResult::FILE_NOT_HANDLED;
}
// Convert DirectX mesh to osg::Geode
osg::Geode* ReaderWriterDirectX::convertFromDX(DX::Object& obj,
bool flipTexture, float creaseAngle)
{
// Fetch mesh
const DX::Mesh* mesh = obj.getMesh();
if (!mesh)
return NULL;
const DX::MeshMaterialList* meshMaterial = obj.getMeshMaterialList();
if (!meshMaterial)
return NULL;
const DX::MeshNormals* meshNormals = obj.getMeshNormals();
if (!meshNormals) {
obj.generateNormals(creaseAngle);
meshNormals = obj.getMeshNormals();
}
if (!meshNormals)
return NULL;
const DX::MeshTextureCoords* meshTexCoords = obj.getMeshTextureCoords();
if (!meshTexCoords)
return NULL;
/*
* - MeshMaterialList contains a list of Material and a per-face
* information with Material is to be applied to which face.
* - Mesh contains a list of Vertices and a per-face information
* which vertices (three or four) belong to this face.
* - MeshNormals contains a list of Normals and a per-face information
* which normal is used by which vertex.
* - MeshTextureCoords contains a list of per-vertex texture coordinates.
*
* - Uses left-hand CS with Y-up, Z-into
* obj_x -> osg_x
* obj_y -> osg_z
* obj_z -> osg_y
*
* - Polys are CW oriented
*/
std::vector<osg::Geometry*> geomList;
unsigned int i;
for (i = 0; i < meshMaterial->material.size(); i++) {
const DX::Material& mtl = meshMaterial->material[i];
osg::StateSet* state = new osg::StateSet;
// Material
osg::Material* material = new osg::Material;
state->setAttributeAndModes(material);
float alpha = mtl.faceColor.alpha;
osg::Vec4 ambient(mtl.faceColor.red,
mtl.faceColor.green,
mtl.faceColor.blue,
alpha);
material->setAmbient(osg::Material::FRONT, ambient);
material->setDiffuse(osg::Material::FRONT, ambient);
material->setShininess(osg::Material::FRONT, mtl.power);
osg::Vec4 specular(mtl.specularColor.red,
mtl.specularColor.green,
mtl.specularColor.blue, alpha);
material->setSpecular(osg::Material::FRONT, specular);
osg::Vec4 emissive(mtl.emissiveColor.red,
mtl.emissiveColor.green,
mtl.emissiveColor.blue, alpha);
material->setEmission(osg::Material::FRONT, emissive);
// Transparency? Set render hint & blending
if (alpha < 1.0f) {
state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
state->setMode(GL_BLEND, osg::StateAttribute::ON);
}
else
state->setMode(GL_BLEND, osg::StateAttribute::OFF);
unsigned int textureCount = mtl.texture.size();
for (unsigned int j = 0; j < textureCount; j++) {
// Load image
osg::Image* image = osgDB::readImageFile(mtl.texture[j]);
if (!image)
continue;
// Texture
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT);
texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::REPEAT);
state->setTextureAttributeAndModes(j, texture);
}
// Geometry
osg::Geometry* geom = new osg::Geometry;
geomList.push_back(geom);
geom->setStateSet(state);
// Arrays to hold vertices, normals, and texcoords.
geom->setVertexArray(new osg::Vec3Array);
geom->setNormalArray(new osg::Vec3Array);
geom->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
if (textureCount) {
// All texture units share the same array
osg::Vec2Array* texCoords = new osg::Vec2Array;
for (unsigned int j = 0; j < textureCount; j++)
geom->setTexCoordArray(j, texCoords);
}
geom->addPrimitiveSet(new osg::DrawArrayLengths(osg::PrimitiveSet::POLYGON));
}
if (mesh->faces.size() != meshMaterial->faceIndices.size())
{
osg::notify(osg::FATAL)<<"Error: internal error in DirectX .x loader,"<<std::endl;
osg::notify(osg::FATAL)<<" mesh->faces.size() == meshMaterial->faceIndices.size()"<<std::endl;
return NULL;
}
// Add faces to Geometry
for (i = 0; i < meshMaterial->faceIndices.size(); i++) {
// Geometry for Material
unsigned int mi = meshMaterial->faceIndices[i];
osg::Geometry* geom = geomList[mi];
// #pts of this face
unsigned int np = mesh->faces[i].size();
((osg::DrawArrayLengths*) geom->getPrimitiveSet(0))->push_back(np);
assert(np == meshNormals->faceNormals[i].size());
osg::Vec3Array* vertexArray = (osg::Vec3Array*) geom->getVertexArray();
osg::Vec3Array* normalArray = (osg::Vec3Array*) geom->getNormalArray();
osg::Vec2Array* texCoordArray = (osg::Vec2Array*) geom->getTexCoordArray(0);
// Add vertices, normals, texcoords
for (unsigned int j = 0; j < np; j++) {
// Convert CW to CCW order
unsigned int jj = (j > 0 ? np - j : j);
// Vertices
unsigned int vi = mesh->faces[i][jj];
if (vertexArray) {
// Transform Xleft/Yup/Zinto to Xleft/Yinto/Zup
const DX::Vector& v = mesh->vertices[vi];
vertexArray->push_back(osg::Vec3(v.x,v.z,v.y));
}
// Normals
unsigned int ni = meshNormals->faceNormals[i][jj];
if (normalArray) {
// Transform Xleft/Yup/Zinto to Xleft/Yinto/Zup
const DX::Vector& n = meshNormals->normals[ni];
normalArray->push_back(osg::Vec3(n.x,n.z,n.y));
}
// TexCoords
if (texCoordArray) {
const DX::Coords2d& tc = (*meshTexCoords)[vi];
osg::Vec2 uv;
if (flipTexture)
uv.set(tc.u, 1.0f - tc.v); // Image is upside down
else
uv.set(tc.u, tc.v);
texCoordArray->push_back(uv);
}
}
}
// Add non-empty nodes to Geode
osg::Geode* geode = new osg::Geode;
for (i = 0; i < geomList.size(); i++) {
osg::Geometry* geom = geomList[i];
if (((osg::Vec3Array*) geom->getVertexArray())->size())
geode->addDrawable(geom);
}
// Back-face culling
osg::StateSet* state = new osg::StateSet;
geode->setStateSet(state);
osg::CullFace* cullFace = new osg::CullFace;
cullFace->setMode(osg::CullFace::BACK);
state->setAttributeAndModes(cullFace);
return geode;
}
<commit_msg>Updates from Ulrich for sharing of textures.<commit_after>// -*-c++-*-
/*
* $Id$
*
* DirectX file converter for OpenSceneGraph.
* Copyright (c)2002 Ulrich Hertlein <[email protected]>
*
* 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
*/
#include "directx.h"
#include <osg/TexEnv>
#include <osg/CullFace>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Image>
#include <osg/Texture2D>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/FileNameUtils>
#include <assert.h>
#include <map>
/**
* OpenSceneGraph plugin wrapper/converter.
*/
class ReaderWriterDirectX : public osgDB::ReaderWriter
{
public:
ReaderWriterDirectX() { }
virtual const char* className() {
return "DirectX Reader/Writer";
}
virtual bool acceptsExtension(const std::string& extension) {
return osgDB::equalCaseInsensitive(extension,"x") ? true : false;
}
virtual ReadResult readNode(const std::string& fileName,
const osgDB::ReaderWriter::Options* options);
private:
osg::Geode* convertFromDX(DX::Object& obj, bool flipTexture, float creaseAngle);
};
// Register with Registry to instantiate the above reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterDirectX> g_readerWriter_DirectX_Proxy;
// Read node
osgDB::ReaderWriter::ReadResult ReaderWriterDirectX::readNode(const std::string& fileName,
const osgDB::ReaderWriter::Options* options)
{
std::string ext = osgDB::getLowerCaseFileExtension(fileName);
if (!acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
osg::notify(osg::INFO) << "ReaderWriterDirectX::readNode(" << fileName.c_str() << ")\n";
// Load DirectX mesh
DX::Object obj;
if (obj.load(fileName.c_str())) {
// Options?
bool flipTexture = true;
float creaseAngle = 80.0f;
if (options) {
const std::string option = options->getOptionString();
if (option.find("flipTexture") != std::string::npos)
flipTexture = false;
if (option.find("creaseAngle") != std::string::npos) {
// TODO
}
}
// Convert to osg::Geode
osg::Geode* geode = convertFromDX(obj, flipTexture, creaseAngle);
if (!geode)
return ReadResult::FILE_NOT_HANDLED;
return geode;
}
return ReadResult::FILE_NOT_HANDLED;
}
// Convert DirectX mesh to osg::Geode
osg::Geode* ReaderWriterDirectX::convertFromDX(DX::Object& obj,
bool flipTexture, float creaseAngle)
{
// Fetch mesh
const DX::Mesh* mesh = obj.getMesh();
if (!mesh)
return NULL;
const DX::MeshMaterialList* meshMaterial = obj.getMeshMaterialList();
if (!meshMaterial)
return NULL;
const DX::MeshNormals* meshNormals = obj.getMeshNormals();
if (!meshNormals) {
obj.generateNormals(creaseAngle);
meshNormals = obj.getMeshNormals();
}
if (!meshNormals)
return NULL;
const DX::MeshTextureCoords* meshTexCoords = obj.getMeshTextureCoords();
if (!meshTexCoords)
return NULL;
/*
* - MeshMaterialList contains a list of Material and a per-face
* information with Material is to be applied to which face.
* - Mesh contains a list of Vertices and a per-face information
* which vertices (three or four) belong to this face.
* - MeshNormals contains a list of Normals and a per-face information
* which normal is used by which vertex.
* - MeshTextureCoords contains a list of per-vertex texture coordinates.
*
* - Uses left-hand CS with Y-up, Z-into
* obj_x -> osg_x
* obj_y -> osg_z
* obj_z -> osg_y
*
* - Polys are CW oriented
*/
std::vector<osg::Geometry*> geomList;
// Texture-for-Image map
std::map<std::string, osg::Texture2D*> texForImage;
unsigned int i;
for (i = 0; i < meshMaterial->material.size(); i++) {
const DX::Material& mtl = meshMaterial->material[i];
osg::StateSet* state = new osg::StateSet;
// Material
osg::Material* material = new osg::Material;
state->setAttributeAndModes(material);
float alpha = mtl.faceColor.alpha;
osg::Vec4 ambient(mtl.faceColor.red,
mtl.faceColor.green,
mtl.faceColor.blue,
alpha);
material->setAmbient(osg::Material::FRONT, ambient);
material->setDiffuse(osg::Material::FRONT, ambient);
material->setShininess(osg::Material::FRONT, mtl.power);
osg::Vec4 specular(mtl.specularColor.red,
mtl.specularColor.green,
mtl.specularColor.blue, alpha);
material->setSpecular(osg::Material::FRONT, specular);
osg::Vec4 emissive(mtl.emissiveColor.red,
mtl.emissiveColor.green,
mtl.emissiveColor.blue, alpha);
material->setEmission(osg::Material::FRONT, emissive);
// Transparency? Set render hint & blending
if (alpha < 1.0f) {
state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
state->setMode(GL_BLEND, osg::StateAttribute::ON);
}
else
state->setMode(GL_BLEND, osg::StateAttribute::OFF);
unsigned int textureCount = mtl.texture.size();
for (unsigned int j = 0; j < textureCount; j++) {
// Share image/texture pairs
osg::Texture2D* texture = texForImage[mtl.texture[j]];
if (!texture) {
osg::Image* image = osgDB::readImageFile(mtl.texture[j]);
if (!image)
continue;
// Texture
texture = new osg::Texture2D;
texForImage[mtl.texture[j]] = texture;
texture->setImage(image);
texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT);
texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::REPEAT);
}
state->setTextureAttributeAndModes(j, texture);
}
// Geometry
osg::Geometry* geom = new osg::Geometry;
geomList.push_back(geom);
geom->setStateSet(state);
// Arrays to hold vertices, normals, and texcoords.
geom->setVertexArray(new osg::Vec3Array);
geom->setNormalArray(new osg::Vec3Array);
geom->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
if (textureCount) {
// All texture units share the same array
osg::Vec2Array* texCoords = new osg::Vec2Array;
for (unsigned int j = 0; j < textureCount; j++)
geom->setTexCoordArray(j, texCoords);
}
geom->addPrimitiveSet(new osg::DrawArrayLengths(osg::PrimitiveSet::POLYGON));
}
if (mesh->faces.size() != meshMaterial->faceIndices.size())
{
osg::notify(osg::FATAL)<<"Error: internal error in DirectX .x loader,"<<std::endl;
osg::notify(osg::FATAL)<<" mesh->faces.size() == meshMaterial->faceIndices.size()"<<std::endl;
return NULL;
}
// Add faces to Geometry
for (i = 0; i < meshMaterial->faceIndices.size(); i++) {
// Geometry for Material
unsigned int mi = meshMaterial->faceIndices[i];
osg::Geometry* geom = geomList[mi];
// #pts of this face
unsigned int np = mesh->faces[i].size();
((osg::DrawArrayLengths*) geom->getPrimitiveSet(0))->push_back(np);
assert(np == meshNormals->faceNormals[i].size());
osg::Vec3Array* vertexArray = (osg::Vec3Array*) geom->getVertexArray();
osg::Vec3Array* normalArray = (osg::Vec3Array*) geom->getNormalArray();
osg::Vec2Array* texCoordArray = (osg::Vec2Array*) geom->getTexCoordArray(0);
// Add vertices, normals, texcoords
for (unsigned int j = 0; j < np; j++) {
// Convert CW to CCW order
unsigned int jj = (j > 0 ? np - j : j);
// Vertices
unsigned int vi = mesh->faces[i][jj];
if (vertexArray) {
// Transform Xleft/Yup/Zinto to Xleft/Yinto/Zup
const DX::Vector& v = mesh->vertices[vi];
vertexArray->push_back(osg::Vec3(v.x,v.z,v.y));
}
// Normals
unsigned int ni = meshNormals->faceNormals[i][jj];
if (normalArray) {
// Transform Xleft/Yup/Zinto to Xleft/Yinto/Zup
const DX::Vector& n = meshNormals->normals[ni];
normalArray->push_back(osg::Vec3(n.x,n.z,n.y));
}
// TexCoords
if (texCoordArray) {
const DX::Coords2d& tc = (*meshTexCoords)[vi];
osg::Vec2 uv;
if (flipTexture)
uv.set(tc.u, 1.0f - tc.v); // Image is upside down
else
uv.set(tc.u, tc.v);
texCoordArray->push_back(uv);
}
}
}
// Add non-empty nodes to Geode
osg::Geode* geode = new osg::Geode;
for (i = 0; i < geomList.size(); i++) {
osg::Geometry* geom = geomList[i];
if (((osg::Vec3Array*) geom->getVertexArray())->size())
geode->addDrawable(geom);
}
// Back-face culling
osg::StateSet* state = new osg::StateSet;
geode->setStateSet(state);
osg::CullFace* cullFace = new osg::CullFace;
cullFace->setMode(osg::CullFace::BACK);
state->setAttributeAndModes(cullFace);
return geode;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsvgiohandler.h"
#ifndef QT_NO_SVGRENDERER
#include "qsvgrenderer.h"
#include "qimage.h"
#include "qpixmap.h"
#include "qpainter.h"
#include "qvariant.h"
#include "qdebug.h"
QT_BEGIN_NAMESPACE
class QSvgIOHandlerPrivate
{
public:
QSvgIOHandlerPrivate()
: r(new QSvgRenderer()), loaded(false)
{}
~QSvgIOHandlerPrivate()
{
delete r;
}
bool load(QIODevice *device);
QSvgRenderer *r;
QSize defaultSize;
QSize currentSize;
bool loaded;
};
bool QSvgIOHandlerPrivate::load(QIODevice *device)
{
if (loaded)
return true;
if (r->load(device->readAll())) {
defaultSize = QSize(r->viewBox().width(), r->viewBox().height());
if (currentSize.isEmpty())
currentSize = defaultSize;
}
loaded = r->isValid();
return loaded;
}
QSvgIOHandler::QSvgIOHandler()
: d(new QSvgIOHandlerPrivate())
{
}
QSvgIOHandler::~QSvgIOHandler()
{
delete d;
}
bool QSvgIOHandler::canRead() const
{
QByteArray contents = device()->peek(80);
return contents.contains("<svg");
}
QByteArray QSvgIOHandler::name() const
{
return "svg";
}
bool QSvgIOHandler::read(QImage *image)
{
if (d->load(device())) {
*image = QImage(d->currentSize, QImage::Format_ARGB32_Premultiplied);
if (!d->currentSize.isEmpty()) {
image->fill(0x00000000);
QPainter p(image);
d->r->render(&p);
p.end();
}
return true;
}
return false;
}
QVariant QSvgIOHandler::option(ImageOption option) const
{
switch(option) {
case ImageFormat:
return QImage::Format_ARGB32_Premultiplied;
break;
case Size:
d->load(device());
return d->defaultSize;
break;
case ScaledSize:
return d->currentSize;
break;
default:
break;
}
return QVariant();
}
void QSvgIOHandler::setOption(ImageOption option, const QVariant & value)
{
switch(option) {
case Size:
d->defaultSize = value.toSize();
d->currentSize = value.toSize();
break;
case ScaledSize:
d->currentSize = value.toSize();
break;
default:
break;
}
}
bool QSvgIOHandler::supportsOption(ImageOption option) const
{
switch(option)
{
case ImageFormat:
case Size:
case ScaledSize:
return true;
default:
break;
}
return false;
}
bool QSvgIOHandler::canRead(QIODevice *device)
{
QByteArray contents = device->peek(80);
return contents.contains("<svg");
}
QT_END_NAMESPACE
#endif // QT_NO_SVGRENDERER
<commit_msg>Fixed a validation problem in QSvgIOHandler::canRead().<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsvgiohandler.h"
#ifndef QT_NO_SVGRENDERER
#include "qsvgrenderer.h"
#include "qimage.h"
#include "qpixmap.h"
#include "qpainter.h"
#include "qvariant.h"
#include "qdebug.h"
QT_BEGIN_NAMESPACE
class QSvgIOHandlerPrivate
{
public:
QSvgIOHandlerPrivate()
: r(new QSvgRenderer()), loaded(false)
{}
~QSvgIOHandlerPrivate()
{
delete r;
}
bool load(QIODevice *device);
static bool findSvgTag(QIODevice *device);
QSvgRenderer *r;
QSize defaultSize;
QSize currentSize;
bool loaded;
};
bool QSvgIOHandlerPrivate::load(QIODevice *device)
{
if (loaded)
return true;
if (r->load(device->readAll())) {
defaultSize = QSize(r->viewBox().width(), r->viewBox().height());
if (currentSize.isEmpty())
currentSize = defaultSize;
}
loaded = r->isValid();
return loaded;
}
bool QSvgIOHandlerPrivate::findSvgTag(QIODevice *device)
{
qint64 pos = device->pos();
device->seek(0);
char buffer[256];
const char svg_tag[] = "<svg";
while (1) {
int size = device->read(buffer, 256);
for (int i=0; i<size - 5; ++i) {
if (!memcmp(buffer + i, svg_tag, 4)) {
if (buffer[i+4] == ' ' || buffer[i+4] == '\t'
|| buffer[i+4] == '\n' || buffer[i+4] == '\r')
{
device->seek(pos);
return true;
}
}
}
if (device->atEnd())
break;
device->seek(device->pos()-4);
}
device->seek(pos);
return false;
}
QSvgIOHandler::QSvgIOHandler()
: d(new QSvgIOHandlerPrivate())
{
}
QSvgIOHandler::~QSvgIOHandler()
{
delete d;
}
bool QSvgIOHandler::canRead() const
{
return QSvgIOHandlerPrivate::findSvgTag(device());
}
QByteArray QSvgIOHandler::name() const
{
return "svg";
}
bool QSvgIOHandler::read(QImage *image)
{
if (d->load(device())) {
*image = QImage(d->currentSize, QImage::Format_ARGB32_Premultiplied);
if (!d->currentSize.isEmpty()) {
image->fill(0x00000000);
QPainter p(image);
d->r->render(&p);
p.end();
}
return true;
}
return false;
}
QVariant QSvgIOHandler::option(ImageOption option) const
{
switch(option) {
case ImageFormat:
return QImage::Format_ARGB32_Premultiplied;
break;
case Size:
d->load(device());
return d->defaultSize;
break;
case ScaledSize:
return d->currentSize;
break;
default:
break;
}
return QVariant();
}
void QSvgIOHandler::setOption(ImageOption option, const QVariant & value)
{
switch(option) {
case Size:
d->defaultSize = value.toSize();
d->currentSize = value.toSize();
break;
case ScaledSize:
d->currentSize = value.toSize();
break;
default:
break;
}
}
bool QSvgIOHandler::supportsOption(ImageOption option) const
{
switch(option)
{
case ImageFormat:
case Size:
case ScaledSize:
return true;
default:
break;
}
return false;
}
bool QSvgIOHandler::canRead(QIODevice *device)
{
return QSvgIOHandlerPrivate::findSvgTag(device);
}
QT_END_NAMESPACE
#endif // QT_NO_SVGRENDERER
<|endoftext|> |
<commit_before>// set a very long point contact so that the field is almost the same as a
// coaxial detector. We then compare the field in the middle part of z with the
// analytic result of a true coaxial detector field
{
// calculate potential for point contact 2D
GeFiCa::PointContactRZ *ppc = new GeFiCa::PointContactRZ(1036,506);
ppc->RUpperBound=3.45;
ppc->RLowerBound=-3.45;
ppc->ZUpperBound=5.05;
ppc->PointBegin=-0.135;
ppc->PointEnd=0.135;
ppc->PointDepth=5.05;
ppc->MaxIterations=1e6;
ppc->Precision=1e-8;
ppc->Csor=1.996;
ppc->V0=2500*GeFiCa::volt;
ppc->V1=0*GeFiCa::volt;
ppc->Impurity="-0.318e10+0*y";
ppc->CalculateField(GeFiCa::kSOR2);
ppc->SaveField("pc2d.root");
// calculate potential for true coaxial 1D analyitically
GeFiCa::TrueCoaxial1D *tc1d = new GeFiCa::TrueCoaxial1D(499);
tc1d->V0=0*GeFiCa::volt;
tc1d->V1=2500*GeFiCa::volt;
tc1d->InnerRadius=0.13;
tc1d->OuterRadius=3.45;
tc1d->Impurity="-0.318e10";
tc1d->CalculateField(GeFiCa::kAnalytic);
tc1d->SaveField("tca.root");
// compare
TChain *t1 = new TChain("t");
t1->Add("pc2d.root");
t1->Draw("p:c1","c2>2.5 && c2<2.51 && c1>0.13");
double *p1 = t->GetV1();
double *r1 = t->GetV2();
TChain *t2 = new TChain("t");
t2->Add("tca.root");
t2->Draw("p:c1");
double *p2 = t->GetV1();
double *r2 = t->GetV2();
const int n = t2->GetSelectedRows();
double p[n]={0};
for (int i=0; i<n; i++) p[i] = p1[i] - p2[i];
TGraph *g = new TGraph(n,r1,p);
g->Draw("ap");
g->GetYaxis()->SetRangeUser(-1e-9,1e-9);
}
<commit_msg>changed PointContactRZ setting names<commit_after>// set a very long point contact so that the field is almost the same as a
// coaxial detector. We then compare the field in the middle part of z with the
// analytic result of a true coaxial detector field
{
// calculate potential for point contact 2D
GeFiCa::PointContactRZ *ppc = new GeFiCa::PointContactRZ(1036,506);
ppc->Radius=3.45;
ppc->ZUpperBound=5.05;
ppc->PointR=0.135;
ppc->PointDepth=5.05;
ppc->MaxIterations=1e6;
ppc->Precision=1e-8;
ppc->Csor=1.996;
ppc->V0=2500*GeFiCa::volt;
ppc->V1=0*GeFiCa::volt;
ppc->Impurity="-0.318e10+0*y";
ppc->CalculateField(GeFiCa::kSOR2);
ppc->SaveField("pc2d.root");
// calculate potential for true coaxial 1D analyitically
GeFiCa::TrueCoaxial1D *tc1d = new GeFiCa::TrueCoaxial1D(499);
tc1d->V0=0*GeFiCa::volt;
tc1d->V1=2500*GeFiCa::volt;
tc1d->InnerRadius=0.13;
tc1d->OuterRadius=3.45;
tc1d->Impurity="-0.318e10";
tc1d->CalculateField(GeFiCa::kAnalytic);
tc1d->SaveField("tca.root");
// compare
TChain *t1 = new TChain("t");
t1->Add("pc2d.root");
t1->Draw("p:c1","c2>2.5 && c2<2.51 && c1>0.13");
double *p1 = t->GetV1();
double *r1 = t->GetV2();
TChain *t2 = new TChain("t");
t2->Add("tca.root");
t2->Draw("p:c1");
double *p2 = t->GetV1();
double *r2 = t->GetV2();
const int n = t2->GetSelectedRows();
double p[n]={0};
for (int i=0; i<n; i++) p[i] = p1[i] - p2[i];
TGraph *g = new TGraph(n,r1,p);
g->Draw("ap");
g->GetYaxis()->SetRangeUser(-1e-9,1e-9);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/config.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef TORRENT_WINDOWS
// windows part
#include "libtorrent/utf8.hpp"
#include <windows.h>
#include <winioctl.h>
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// posix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
#ifdef TORRENT_WINDOWS
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
#ifdef TORRENT_WINDOWS
const file::open_mode file::in(GENERIC_READ);
const file::open_mode file::out(GENERIC_WRITE);
const file::seek_mode file::begin(FILE_BEGIN);
const file::seek_mode file::end(FILE_END);
#else
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(SEEK_SET);
const file::seek_mode file::end(SEEK_END);
#endif
file::file()
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{}
file::file(fs::path const& path, open_mode mode, error_code& ec)
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{
open(path, mode, ec);
}
file::~file()
{
close();
}
bool file::open(fs::path const& path, open_mode mode, error_code& ec)
{
close();
#ifdef TORRENT_WINDOWS
#ifdef UNICODE
std::wstring file_path(safe_convert(path.native_file_string()));
#else
std::string file_path = utf8_native(path.native_file_string());
#endif
m_file_handle = CreateFile(
file_path.c_str()
, mode.m_mask
, FILE_SHARE_READ
, 0
, (mode & out)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
if (m_file_handle == INVALID_HANDLE_VALUE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
// try to make the file sparse if supported
if (mode & out)
{
DWORD temp;
::DeviceIoControl(m_file_handle, FSCTL_SET_SPARSE, 0, 0
, 0, 0, &temp, 0);
}
#else
// rely on default umask to filter x and w permissions
// for group and others
int permissions = S_IRUSR | S_IWUSR
| S_IRGRP | S_IWGRP
| S_IROTH | S_IWOTH;
m_fd = ::open(path.native_file_string().c_str()
, map_open_mode(mode.m_mask), permissions);
if (m_fd == -1)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
#ifndef NDEBUG
m_open_mode = mode;
#endif
TORRENT_ASSERT(is_open());
return true;
}
bool file::is_open() const
{
#ifdef TORRENT_WINDOWS
return m_file_handle != INVALID_HANDLE_VALUE;
#else
return m_fd != -1;
#endif
}
void file::close()
{
#ifdef TORRENT_WINDOWS
if (m_file_handle == INVALID_HANDLE_VALUE) return;
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
#else
if (m_fd == -1) return;
::close(m_fd);
m_fd = -1;
#endif
#ifndef NDEBUG
m_open_mode = 0;
#endif
}
size_type file::read(char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & in) == in);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
TORRENT_ASSERT(DWORD(num_bytes) == num_bytes);
DWORD ret = 0;
if (num_bytes != 0)
{
if (ReadFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::read(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & out) == out);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
DWORD ret = 0;
if (num_bytes != 0)
{
if (WriteFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::write(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
bool file::set_size(size_type s, error_code& ec)
{
TORRENT_ASSERT(is_open());
TORRENT_ASSERT(s >= 0);
#ifdef TORRENT_WINDOWS
size_type pos = tell(ec);
if (ec) return false;
seek(s, begin, ec);
if (ec) return false;
if (::SetEndOfFile(m_file_handle) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
#else
if (ftruncate(m_fd, s) < 0)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
return true;
}
size_type file::seek(size_type offset, seek_mode m, error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = offset;
if (SetFilePointerEx(m_file_handle, offs, &offs, m.m_val) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret = lseek(m_fd, offset, m.m_val);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
size_type file::tell(error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (SetFilePointerEx(m_file_handle, offs, &offs
, FILE_CURRENT) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret;
ret = lseek(m_fd, 0, SEEK_CUR);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
}
<commit_msg>fixed typecast typo in file.cpp<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/config.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef TORRENT_WINDOWS
// windows part
#include "libtorrent/utf8.hpp"
#include <windows.h>
#include <winioctl.h>
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// posix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
#ifdef TORRENT_WINDOWS
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == std::size_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
#ifdef TORRENT_WINDOWS
const file::open_mode file::in(GENERIC_READ);
const file::open_mode file::out(GENERIC_WRITE);
const file::seek_mode file::begin(FILE_BEGIN);
const file::seek_mode file::end(FILE_END);
#else
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(SEEK_SET);
const file::seek_mode file::end(SEEK_END);
#endif
file::file()
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{}
file::file(fs::path const& path, open_mode mode, error_code& ec)
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{
open(path, mode, ec);
}
file::~file()
{
close();
}
bool file::open(fs::path const& path, open_mode mode, error_code& ec)
{
close();
#ifdef TORRENT_WINDOWS
#ifdef UNICODE
std::wstring file_path(safe_convert(path.native_file_string()));
#else
std::string file_path = utf8_native(path.native_file_string());
#endif
m_file_handle = CreateFile(
file_path.c_str()
, mode.m_mask
, FILE_SHARE_READ
, 0
, (mode & out)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
if (m_file_handle == INVALID_HANDLE_VALUE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
// try to make the file sparse if supported
if (mode & out)
{
DWORD temp;
::DeviceIoControl(m_file_handle, FSCTL_SET_SPARSE, 0, 0
, 0, 0, &temp, 0);
}
#else
// rely on default umask to filter x and w permissions
// for group and others
int permissions = S_IRUSR | S_IWUSR
| S_IRGRP | S_IWGRP
| S_IROTH | S_IWOTH;
m_fd = ::open(path.native_file_string().c_str()
, map_open_mode(mode.m_mask), permissions);
if (m_fd == -1)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
#ifndef NDEBUG
m_open_mode = mode;
#endif
TORRENT_ASSERT(is_open());
return true;
}
bool file::is_open() const
{
#ifdef TORRENT_WINDOWS
return m_file_handle != INVALID_HANDLE_VALUE;
#else
return m_fd != -1;
#endif
}
void file::close()
{
#ifdef TORRENT_WINDOWS
if (m_file_handle == INVALID_HANDLE_VALUE) return;
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
#else
if (m_fd == -1) return;
::close(m_fd);
m_fd = -1;
#endif
#ifndef NDEBUG
m_open_mode = 0;
#endif
}
size_type file::read(char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & in) == in);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
TORRENT_ASSERT(DWORD(num_bytes) == num_bytes);
DWORD ret = 0;
if (num_bytes != 0)
{
if (ReadFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::read(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & out) == out);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
DWORD ret = 0;
if (num_bytes != 0)
{
if (WriteFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::write(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
bool file::set_size(size_type s, error_code& ec)
{
TORRENT_ASSERT(is_open());
TORRENT_ASSERT(s >= 0);
#ifdef TORRENT_WINDOWS
size_type pos = tell(ec);
if (ec) return false;
seek(s, begin, ec);
if (ec) return false;
if (::SetEndOfFile(m_file_handle) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
#else
if (ftruncate(m_fd, s) < 0)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
return true;
}
size_type file::seek(size_type offset, seek_mode m, error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = offset;
if (SetFilePointerEx(m_file_handle, offs, &offs, m.m_val) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret = lseek(m_fd, offset, m.m_val);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
size_type file::tell(error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (SetFilePointerEx(m_file_handle, offs, &offs
, FILE_CURRENT) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret;
ret = lseek(m_fd, 0, SEEK_CUR);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
}
<|endoftext|> |
<commit_before>#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/channel.h>
#include <io/pipe.h>
#include <io/splice.h>
/*
* A Splice passes data unidirectionall between StreamChannels across a Pipe.
*/
Splice::Splice(StreamChannel *source, Pipe *pipe, StreamChannel *sink)
: log_("/splice"),
source_(source),
pipe_(pipe),
sink_(sink),
callback_(NULL),
callback_action_(NULL),
read_eos_(false),
read_action_(NULL),
input_action_(NULL),
output_action_(NULL),
write_action_(NULL),
shutdown_action_(NULL)
{
ASSERT(source_ != NULL);
ASSERT(pipe_ != NULL);
ASSERT(sink_ != NULL);
}
Splice::~Splice()
{
ASSERT(callback_ == NULL);
ASSERT(callback_action_ == NULL);
ASSERT(read_action_ == NULL);
ASSERT(input_action_ == NULL);
ASSERT(output_action_ == NULL);
ASSERT(write_action_ == NULL);
ASSERT(shutdown_action_ == NULL);
}
Action *
Splice::start(EventCallback *cb)
{
ASSERT(callback_ == NULL && callback_action_ == NULL);
callback_ = cb;
EventCallback *scb = callback(this, &Splice::read_complete);
read_action_ = source_->read(0, scb);
EventCallback *pcb = callback(this, &Splice::output_complete);
output_action_ = pipe_->output(pcb);
return (cancellation(this, &Splice::cancel));
}
void
Splice::cancel(void)
{
if (callback_ != NULL) {
delete callback_;
callback_ = NULL;
ASSERT(callback_action_ == NULL);
if (read_action_ != NULL) {
read_action_->cancel();
read_action_ = NULL;
}
if (input_action_ != NULL) {
input_action_->cancel();
input_action_ = NULL;
}
if (output_action_ != NULL) {
output_action_->cancel();
output_action_ = NULL;
}
if (write_action_ != NULL) {
write_action_->cancel();
write_action_ = NULL;
}
if (shutdown_action_ != NULL) {
shutdown_action_->cancel();
shutdown_action_ = NULL;
}
} else {
ASSERT(callback_action_ != NULL);
callback_action_->cancel();
callback_action_ = NULL;
}
}
void
Splice::complete(Event e)
{
ASSERT(callback_ != NULL);
ASSERT(callback_action_ == NULL);
if (read_action_ != NULL) {
read_action_->cancel();
read_action_ = NULL;
}
if (input_action_ != NULL) {
input_action_->cancel();
input_action_ = NULL;
}
if (output_action_ != NULL) {
output_action_->cancel();
output_action_ = NULL;
}
if (write_action_ != NULL) {
write_action_->cancel();
write_action_ = NULL;
}
callback_->param(e);
callback_action_ = EventSystem::instance()->schedule(callback_);
callback_ = NULL;
}
void
Splice::read_complete(Event e)
{
read_action_->cancel();
read_action_ = NULL;
ASSERT(!read_eos_);
switch (e.type_) {
case Event::Done:
case Event::EOS:
break;
default:
DEBUG(log_) << "Unexpected event: " << e;
complete(e);
return;
}
if (e.buffer_.empty()) {
ASSERT(e.type_ == Event::EOS);
read_eos_ = true;
}
ASSERT(input_action_ == NULL);
EventCallback *cb = callback(this, &Splice::input_complete);
input_action_ = pipe_->input(&e.buffer_, cb);
}
void
Splice::input_complete(Event e)
{
input_action_->cancel();
input_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
DEBUG(log_) << "Unexpected event: " << e;
complete(e);
return;
}
ASSERT(read_action_ == NULL);
if (!read_eos_) {
EventCallback *cb = callback(this, &Splice::read_complete);
read_action_ = source_->read(0, cb);
}
}
void
Splice::output_complete(Event e)
{
output_action_->cancel();
output_action_ = NULL;
switch (e.type_) {
case Event::Done:
case Event::EOS:
break;
default:
DEBUG(log_) << "Unexpected event: " << e;
complete(e);
return;
}
if (e.type_ == Event::EOS && e.buffer_.empty()) {
EventCallback *cb = callback(this, &Splice::shutdown_complete);
shutdown_action_ = sink_->shutdown(false, true, cb);
return;
}
ASSERT(write_action_ == NULL);
EventCallback *cb = callback(this, &Splice::write_complete);
write_action_ = sink_->write(&e.buffer_, cb);
}
void
Splice::write_complete(Event e)
{
write_action_->cancel();
write_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
DEBUG(log_) << "Unexpected event: " << e;
complete(e);
return;
}
ASSERT(output_action_ == NULL);
EventCallback *cb = callback(this, &Splice::output_complete);
output_action_ = pipe_->output(cb);
}
void
Splice::shutdown_complete(Event e)
{
shutdown_action_->cancel();
shutdown_action_ = NULL;
switch (e.type_) {
case Event::Done:
case Event::Error:
break;
default:
HALT(log_) << "Unexpected event: " << e;
return;
}
if (e.type_ == Event::Error)
DEBUG(log_) << "Could not shut down write channel.";
complete(Event::EOS);
}
<commit_msg>Clean up shutdown actions when the splice is finished, too.<commit_after>#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/channel.h>
#include <io/pipe.h>
#include <io/splice.h>
/*
* A Splice passes data unidirectionall between StreamChannels across a Pipe.
*/
Splice::Splice(StreamChannel *source, Pipe *pipe, StreamChannel *sink)
: log_("/splice"),
source_(source),
pipe_(pipe),
sink_(sink),
callback_(NULL),
callback_action_(NULL),
read_eos_(false),
read_action_(NULL),
input_action_(NULL),
output_action_(NULL),
write_action_(NULL),
shutdown_action_(NULL)
{
ASSERT(source_ != NULL);
ASSERT(pipe_ != NULL);
ASSERT(sink_ != NULL);
}
Splice::~Splice()
{
ASSERT(callback_ == NULL);
ASSERT(callback_action_ == NULL);
ASSERT(read_action_ == NULL);
ASSERT(input_action_ == NULL);
ASSERT(output_action_ == NULL);
ASSERT(write_action_ == NULL);
ASSERT(shutdown_action_ == NULL);
}
Action *
Splice::start(EventCallback *cb)
{
ASSERT(callback_ == NULL && callback_action_ == NULL);
callback_ = cb;
EventCallback *scb = callback(this, &Splice::read_complete);
read_action_ = source_->read(0, scb);
EventCallback *pcb = callback(this, &Splice::output_complete);
output_action_ = pipe_->output(pcb);
return (cancellation(this, &Splice::cancel));
}
void
Splice::cancel(void)
{
if (callback_ != NULL) {
delete callback_;
callback_ = NULL;
ASSERT(callback_action_ == NULL);
if (read_action_ != NULL) {
read_action_->cancel();
read_action_ = NULL;
}
if (input_action_ != NULL) {
input_action_->cancel();
input_action_ = NULL;
}
if (output_action_ != NULL) {
output_action_->cancel();
output_action_ = NULL;
}
if (write_action_ != NULL) {
write_action_->cancel();
write_action_ = NULL;
}
if (shutdown_action_ != NULL) {
shutdown_action_->cancel();
shutdown_action_ = NULL;
}
} else {
ASSERT(callback_action_ != NULL);
callback_action_->cancel();
callback_action_ = NULL;
}
}
void
Splice::complete(Event e)
{
ASSERT(callback_ != NULL);
ASSERT(callback_action_ == NULL);
if (read_action_ != NULL) {
read_action_->cancel();
read_action_ = NULL;
}
if (input_action_ != NULL) {
input_action_->cancel();
input_action_ = NULL;
}
if (output_action_ != NULL) {
output_action_->cancel();
output_action_ = NULL;
}
if (write_action_ != NULL) {
write_action_->cancel();
write_action_ = NULL;
}
if (shutdown_action_ != NULL) {
shutdown_action_->cancel();
shutdown_action_ = NULL;
}
callback_->param(e);
callback_action_ = EventSystem::instance()->schedule(callback_);
callback_ = NULL;
}
void
Splice::read_complete(Event e)
{
read_action_->cancel();
read_action_ = NULL;
ASSERT(!read_eos_);
switch (e.type_) {
case Event::Done:
case Event::EOS:
break;
default:
DEBUG(log_) << "Unexpected event: " << e;
complete(e);
return;
}
if (e.buffer_.empty()) {
ASSERT(e.type_ == Event::EOS);
read_eos_ = true;
}
ASSERT(input_action_ == NULL);
EventCallback *cb = callback(this, &Splice::input_complete);
input_action_ = pipe_->input(&e.buffer_, cb);
}
void
Splice::input_complete(Event e)
{
input_action_->cancel();
input_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
DEBUG(log_) << "Unexpected event: " << e;
complete(e);
return;
}
ASSERT(read_action_ == NULL);
if (!read_eos_) {
EventCallback *cb = callback(this, &Splice::read_complete);
read_action_ = source_->read(0, cb);
}
}
void
Splice::output_complete(Event e)
{
output_action_->cancel();
output_action_ = NULL;
switch (e.type_) {
case Event::Done:
case Event::EOS:
break;
default:
DEBUG(log_) << "Unexpected event: " << e;
complete(e);
return;
}
if (e.type_ == Event::EOS && e.buffer_.empty()) {
EventCallback *cb = callback(this, &Splice::shutdown_complete);
shutdown_action_ = sink_->shutdown(false, true, cb);
return;
}
ASSERT(write_action_ == NULL);
EventCallback *cb = callback(this, &Splice::write_complete);
write_action_ = sink_->write(&e.buffer_, cb);
}
void
Splice::write_complete(Event e)
{
write_action_->cancel();
write_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
DEBUG(log_) << "Unexpected event: " << e;
complete(e);
return;
}
ASSERT(output_action_ == NULL);
EventCallback *cb = callback(this, &Splice::output_complete);
output_action_ = pipe_->output(cb);
}
void
Splice::shutdown_complete(Event e)
{
shutdown_action_->cancel();
shutdown_action_ = NULL;
switch (e.type_) {
case Event::Done:
case Event::Error:
break;
default:
HALT(log_) << "Unexpected event: " << e;
return;
}
if (e.type_ == Event::Error)
DEBUG(log_) << "Could not shut down write channel.";
complete(Event::EOS);
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <QtCore/QSocketNotifier>
#include <QtCore/QTimer>
#include <QtCore/QThread>
#include <QtCore/QWaitCondition>
#include "virtualserialdevice.h"
namespace SymbianUtils {
class VirtualSerialDevicePrivate
{
public:
int portHandle;
QSocketNotifier* readNotifier;
QSocketNotifier* writeUnblockedNotifier;
};
void VirtualSerialDevice::platInit()
{
d = new VirtualSerialDevicePrivate;
d->portHandle = -1;
d->readNotifier = NULL;
d->writeUnblockedNotifier = NULL;
connect(this, SIGNAL(AsyncCall_emitBytesWrittenIfNeeded(qint64)), this, SIGNAL(bytesWritten(qint64)), Qt::QueuedConnection);
}
bool VirtualSerialDevice::open(OpenMode mode)
{
if (isOpen()) return true;
d->portHandle = ::open(portName.toAscii().constData(), O_RDWR | O_NONBLOCK | O_NOCTTY);
if (d->portHandle == -1) {
setErrorString(QString("Posix error %1 opening %2").arg(errno).arg(portName));
return false;
}
d->readNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Read);
connect(d->readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead()));
d->writeUnblockedNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Write);
d->writeUnblockedNotifier->setEnabled(false);
connect(d->writeUnblockedNotifier, SIGNAL(activated(int)), this, SLOT(writeHasUnblocked(int)));
bool ok = QIODevice::open(mode);
if (!ok) close();
return ok;
}
void VirtualSerialDevice::platClose()
{
delete d->readNotifier;
d->readNotifier = NULL;
delete d->writeUnblockedNotifier;
d->writeUnblockedNotifier = NULL;
::close(d->portHandle);
d->portHandle = -1;
}
VirtualSerialDevice::~VirtualSerialDevice()
{
close();
delete d;
}
qint64 VirtualSerialDevice::bytesAvailable() const
{
QMutexLocker locker(&lock);
if (!isOpen()) return 0;
int avail = 0;
if (ioctl(d->portHandle, FIONREAD, &avail) == -1) {
return 0;
}
return (qint64)avail + QIODevice::bytesAvailable();
}
qint64 VirtualSerialDevice::readData(char *data, qint64 maxSize)
{
QMutexLocker locker(&lock);
int result = ::read(d->portHandle, data, maxSize);
if (result == -1 && errno == EAGAIN)
result = 0; // To Qt, 0 here means nothing ready right now, and -1 is reserved for permanent errors
return result;
}
qint64 VirtualSerialDevice::writeData(const char *data, qint64 maxSize)
{
QMutexLocker locker(&lock);
qint64 bytesWritten;
bool needToWait = tryFlushPendingBuffers(locker, EmitBytesWrittenAsync);
if (!needToWait) {
needToWait = tryWrite(data, maxSize, bytesWritten);
if (needToWait && bytesWritten > 0) {
// Wrote some of the buffer, adjust pointers to point to the remainder that needs queueing
data += bytesWritten;
maxSize -= bytesWritten;
}
}
if (needToWait) {
pendingWrites.append(QByteArray(data, maxSize));
d->writeUnblockedNotifier->setEnabled(true);
// Now wait for the writeUnblocked signal or for a call to waitForBytesWritten
return bytesWritten + maxSize;
} else {
//emitBytesWrittenIfNeeded(locker, bytesWritten);
// Can't emit bytesWritten directly from writeData - means clients end up recursing
emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten);
return bytesWritten;
}
}
/* Returns true if EAGAIN encountered.
* if error occurred (other than EAGAIN) returns -1 in bytesWritten
* lock must be held. Doesn't emit signals or set notifiers.
*/
bool VirtualSerialDevice::tryWrite(const char *data, qint64 maxSize, qint64& bytesWritten)
{
// Must be locked
bytesWritten = 0;
while (maxSize > 0) {
int result = ::write(d->portHandle, data, maxSize);
if (result == -1) {
if (errno == EAGAIN)
return true; // Need to wait
setErrorString(QString("Posix error %1 from write to %2").arg(errno).arg(portName));
bytesWritten = -1;
return false;
} else {
if (result == 0)
qWarning("Zero bytes written to port!");
bytesWritten += result;
maxSize -= result;
data += result;
}
}
return false; // If we reach here we've successfully written all the data without blocking
}
/* Returns true if EAGAIN encountered. Emits (or queues) bytesWritten for any buffers written.
* If stopAfterWritingOneBuffer is true, return immediately if a single buffer is written, rather than
* attempting to drain the whole queue.
* Doesn't modify notifier.
*/
bool VirtualSerialDevice::tryFlushPendingBuffers(QMutexLocker& locker, FlushPendingOptions flags)
{
while (pendingWrites.count() > 0) {
// Try writing everything we've got, until we hit EAGAIN
const QByteArray& data = pendingWrites[0];
qint64 bytesWritten;
bool needToWait = tryWrite(data.constData(), data.size(), bytesWritten);
if (needToWait) {
if (bytesWritten > 0) {
// We wrote some of the data, update the pending queue
QByteArray remainder = data.mid(bytesWritten);
pendingWrites.removeFirst();
pendingWrites.insert(0, remainder);
}
return needToWait;
} else {
pendingWrites.removeFirst();
if (flags & EmitBytesWrittenAsync) {
emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten);
} else {
emitBytesWrittenIfNeeded(locker, bytesWritten);
}
if (flags & StopAfterWritingOneBuffer) return false;
// Otherwise go round loop again
}
}
return false; // no EAGAIN encountered
}
void VirtualSerialDevice::writeHasUnblocked(int fileHandle)
{
Q_ASSERT(fileHandle == d->portHandle);
(void)fileHandle; // Compiler shutter-upper
d->writeUnblockedNotifier->setEnabled(false);
QMutexLocker locker(&lock);
bool needToWait = tryFlushPendingBuffers(locker);
if (needToWait) d->writeUnblockedNotifier->setEnabled(true);
}
// Copy of qt_safe_select from /qt/src/corelib/kernel/qeventdispatcher_unix.cpp
// But without the timeout correction
int safe_select(int nfds, fd_set *fdread, fd_set *fdwrite, fd_set *fdexcept,
const struct timeval *orig_timeout)
{
if (!orig_timeout) {
// no timeout -> block forever
register int ret;
do {
ret = select(nfds, fdread, fdwrite, fdexcept, 0);
} while (ret == -1 && errno == EINTR);
return ret;
}
timeval timeout = *orig_timeout;
int ret;
forever {
ret = ::select(nfds, fdread, fdwrite, fdexcept, &timeout);
if (ret != -1 || errno != EINTR)
return ret;
}
}
bool VirtualSerialDevice::waitForBytesWritten(int msecs)
{
QMutexLocker locker(&lock);
if (pendingWrites.count() == 0) return false;
if (QThread::currentThread() != thread()) {
// Wait for signal from main thread
unsigned long timeout = msecs;
if (msecs == -1) timeout = ULONG_MAX;
if (waiterForBytesWritten == NULL)
waiterForBytesWritten = new QWaitCondition;
return waiterForBytesWritten->wait(&lock, timeout);
}
d->writeUnblockedNotifier->setEnabled(false);
forever {
fd_set writeSet;
FD_ZERO(&writeSet);
FD_SET(d->portHandle, &writeSet);
struct timeval timeout;
if (msecs != -1) {
timeout.tv_sec = msecs / 1000;
timeout.tv_usec = (msecs % 1000) * 1000;
}
int ret = safe_select(d->portHandle+1, NULL, &writeSet, NULL, msecs == -1 ? NULL : &timeout);
if (ret == 0) {
// Timeout
return false;
} else if (ret < 0) {
setErrorString(QString("Posix error %1 returned from select in waitForBytesWritten").arg(errno));
return false;
} else {
bool needToWait = tryFlushPendingBuffers(locker, StopAfterWritingOneBuffer);
if (needToWait) {
// go round the select again
} else {
return true;
}
}
}
}
void VirtualSerialDevice::flush()
{
while (waitForBytesWritten(-1)) { /* loop */ }
tcflush(d->portHandle, TCIOFLUSH);
}
bool VirtualSerialDevice::waitForReadyRead(int msecs)
{
return QIODevice::waitForReadyRead(msecs); //TODO
}
} // namespace SymbianUtils
<commit_msg>Symbian: Fix for CODA serial problem on unix<commit_after>#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <QtCore/QSocketNotifier>
#include <QtCore/QTimer>
#include <QtCore/QThread>
#include <QtCore/QWaitCondition>
#include "virtualserialdevice.h"
namespace SymbianUtils {
class VirtualSerialDevicePrivate
{
public:
int portHandle;
QSocketNotifier* readNotifier;
QSocketNotifier* writeUnblockedNotifier;
};
void VirtualSerialDevice::platInit()
{
d = new VirtualSerialDevicePrivate;
d->portHandle = -1;
d->readNotifier = NULL;
d->writeUnblockedNotifier = NULL;
connect(this, SIGNAL(AsyncCall_emitBytesWrittenIfNeeded(qint64)), this, SIGNAL(bytesWritten(qint64)), Qt::QueuedConnection);
}
bool VirtualSerialDevice::open(OpenMode mode)
{
if (isOpen()) return true;
d->portHandle = ::open(portName.toAscii().constData(), O_RDWR | O_NONBLOCK | O_NOCTTY);
if (d->portHandle == -1) {
setErrorString(QString("Posix error %1 opening %2").arg(errno).arg(portName));
return false;
}
struct termios termInfo;
if (tcgetattr(d->portHandle, &termInfo) < 0) {
setErrorString(QString::fromLatin1("Unable to retrieve terminal settings: %1 %2").arg(errno).arg(QString::fromAscii(strerror(errno))));
close();
return false;
}
cfmakeraw(&termInfo);
// Turn off terminal echo as not get messages back, among other things
termInfo.c_cflag |= CREAD|CLOCAL;
termInfo.c_cc[VTIME] = 0;
termInfo.c_lflag &= (~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
termInfo.c_iflag &= (~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY|IXON|IXOFF));
termInfo.c_oflag &= (~OPOST);
termInfo.c_cc[VMIN] = 0;
termInfo.c_cc[VINTR] = _POSIX_VDISABLE;
termInfo.c_cc[VQUIT] = _POSIX_VDISABLE;
termInfo.c_cc[VSTART] = _POSIX_VDISABLE;
termInfo.c_cc[VSTOP] = _POSIX_VDISABLE;
termInfo.c_cc[VSUSP] = _POSIX_VDISABLE;
if (tcsetattr(d->portHandle, TCSAFLUSH, &termInfo) < 0) {
setErrorString(QString::fromLatin1("Unable to apply terminal settings: %1 %2").arg(errno).arg(QString::fromAscii(strerror(errno))));
close();
return false;
}
d->readNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Read);
connect(d->readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead()));
d->writeUnblockedNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Write);
d->writeUnblockedNotifier->setEnabled(false);
connect(d->writeUnblockedNotifier, SIGNAL(activated(int)), this, SLOT(writeHasUnblocked(int)));
bool ok = QIODevice::open(mode | QIODevice::Unbuffered);
if (!ok) close();
return ok;
}
void VirtualSerialDevice::platClose()
{
delete d->readNotifier;
d->readNotifier = NULL;
delete d->writeUnblockedNotifier;
d->writeUnblockedNotifier = NULL;
::close(d->portHandle);
d->portHandle = -1;
}
VirtualSerialDevice::~VirtualSerialDevice()
{
close();
delete d;
}
qint64 VirtualSerialDevice::bytesAvailable() const
{
QMutexLocker locker(&lock);
if (!isOpen()) return 0;
int avail = 0;
if (ioctl(d->portHandle, FIONREAD, &avail) == -1) {
return 0;
}
return (qint64)avail + QIODevice::bytesAvailable();
}
qint64 VirtualSerialDevice::readData(char *data, qint64 maxSize)
{
QMutexLocker locker(&lock);
int result = ::read(d->portHandle, data, maxSize);
if (result == -1 && errno == EAGAIN)
result = 0; // To Qt, 0 here means nothing ready right now, and -1 is reserved for permanent errors
return result;
}
qint64 VirtualSerialDevice::writeData(const char *data, qint64 maxSize)
{
QMutexLocker locker(&lock);
qint64 bytesWritten;
bool needToWait = tryFlushPendingBuffers(locker, EmitBytesWrittenAsync);
if (!needToWait) {
needToWait = tryWrite(data, maxSize, bytesWritten);
if (needToWait && bytesWritten > 0) {
// Wrote some of the buffer, adjust pointers to point to the remainder that needs queueing
data += bytesWritten;
maxSize -= bytesWritten;
}
}
if (needToWait) {
pendingWrites.append(QByteArray(data, maxSize));
d->writeUnblockedNotifier->setEnabled(true);
// Now wait for the writeUnblocked signal or for a call to waitForBytesWritten
return bytesWritten + maxSize;
} else {
//emitBytesWrittenIfNeeded(locker, bytesWritten);
// Can't emit bytesWritten directly from writeData - means clients end up recursing
emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten);
return bytesWritten;
}
}
/* Returns true if EAGAIN encountered.
* if error occurred (other than EAGAIN) returns -1 in bytesWritten
* lock must be held. Doesn't emit signals or set notifiers.
*/
bool VirtualSerialDevice::tryWrite(const char *data, qint64 maxSize, qint64& bytesWritten)
{
// Must be locked
bytesWritten = 0;
while (maxSize > 0) {
int result = ::write(d->portHandle, data, maxSize);
if (result == -1) {
if (errno == EAGAIN)
return true; // Need to wait
setErrorString(QString("Posix error %1 from write to %2").arg(errno).arg(portName));
bytesWritten = -1;
return false;
} else {
if (result == 0)
qWarning("Zero bytes written to port!");
bytesWritten += result;
maxSize -= result;
data += result;
}
}
return false; // If we reach here we've successfully written all the data without blocking
}
/* Returns true if EAGAIN encountered. Emits (or queues) bytesWritten for any buffers written.
* If stopAfterWritingOneBuffer is true, return immediately if a single buffer is written, rather than
* attempting to drain the whole queue.
* Doesn't modify notifier.
*/
bool VirtualSerialDevice::tryFlushPendingBuffers(QMutexLocker& locker, FlushPendingOptions flags)
{
while (pendingWrites.count() > 0) {
// Try writing everything we've got, until we hit EAGAIN
const QByteArray& data = pendingWrites[0];
qint64 bytesWritten;
bool needToWait = tryWrite(data.constData(), data.size(), bytesWritten);
if (needToWait) {
if (bytesWritten > 0) {
// We wrote some of the data, update the pending queue
QByteArray remainder = data.mid(bytesWritten);
pendingWrites.removeFirst();
pendingWrites.insert(0, remainder);
}
return needToWait;
} else {
pendingWrites.removeFirst();
if (flags & EmitBytesWrittenAsync) {
emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten);
} else {
emitBytesWrittenIfNeeded(locker, bytesWritten);
}
if (flags & StopAfterWritingOneBuffer) return false;
// Otherwise go round loop again
}
}
return false; // no EAGAIN encountered
}
void VirtualSerialDevice::writeHasUnblocked(int fileHandle)
{
Q_ASSERT(fileHandle == d->portHandle);
(void)fileHandle; // Compiler shutter-upper
d->writeUnblockedNotifier->setEnabled(false);
QMutexLocker locker(&lock);
bool needToWait = tryFlushPendingBuffers(locker);
if (needToWait) d->writeUnblockedNotifier->setEnabled(true);
}
// Copy of qt_safe_select from /qt/src/corelib/kernel/qeventdispatcher_unix.cpp
// But without the timeout correction
int safe_select(int nfds, fd_set *fdread, fd_set *fdwrite, fd_set *fdexcept,
const struct timeval *orig_timeout)
{
if (!orig_timeout) {
// no timeout -> block forever
register int ret;
do {
ret = select(nfds, fdread, fdwrite, fdexcept, 0);
} while (ret == -1 && errno == EINTR);
return ret;
}
timeval timeout = *orig_timeout;
int ret;
forever {
ret = ::select(nfds, fdread, fdwrite, fdexcept, &timeout);
if (ret != -1 || errno != EINTR)
return ret;
}
}
bool VirtualSerialDevice::waitForBytesWritten(int msecs)
{
QMutexLocker locker(&lock);
if (pendingWrites.count() == 0) return false;
if (QThread::currentThread() != thread()) {
// Wait for signal from main thread
unsigned long timeout = msecs;
if (msecs == -1) timeout = ULONG_MAX;
if (waiterForBytesWritten == NULL)
waiterForBytesWritten = new QWaitCondition;
return waiterForBytesWritten->wait(&lock, timeout);
}
d->writeUnblockedNotifier->setEnabled(false);
forever {
fd_set writeSet;
FD_ZERO(&writeSet);
FD_SET(d->portHandle, &writeSet);
struct timeval timeout;
if (msecs != -1) {
timeout.tv_sec = msecs / 1000;
timeout.tv_usec = (msecs % 1000) * 1000;
}
int ret = safe_select(d->portHandle+1, NULL, &writeSet, NULL, msecs == -1 ? NULL : &timeout);
if (ret == 0) {
// Timeout
return false;
} else if (ret < 0) {
setErrorString(QString("Posix error %1 returned from select in waitForBytesWritten").arg(errno));
return false;
} else {
bool needToWait = tryFlushPendingBuffers(locker, StopAfterWritingOneBuffer);
if (needToWait) {
// go round the select again
} else {
return true;
}
}
}
}
void VirtualSerialDevice::flush()
{
while (waitForBytesWritten(-1)) { /* loop */ }
tcflush(d->portHandle, TCIOFLUSH);
}
bool VirtualSerialDevice::waitForReadyRead(int msecs)
{
return QIODevice::waitForReadyRead(msecs); //TODO
}
} // namespace SymbianUtils
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkOptimizerParameters.h"
#include "itkIntTypes.h"
#include "itkTestingMacros.h"
using namespace itk;
template< typename TValueType >
bool runTestByType()
{
bool passed = true;
OptimizerParameters<TValueType> params;
params.SetSize(10);
params.Fill(1.23);
std::cout << "GetSize: " << params.GetSize() << std::endl;
/* Test different ctors */
//Construct by size
SizeValueType dim = 20;
OptimizerParameters<TValueType> paramsSize(dim);
if( paramsSize.GetSize() != dim )
{
std::cerr << "Constructor with dimension failed. Expected size of "
<< dim << ", but got " << paramsSize.GetSize() << "." << std::endl;
passed = false;
}
//Copy constructor
{
OptimizerParameters<TValueType> paramsCopy( params );
for( SizeValueType i=0; i < params.GetSize(); i++ )
{
if( params[i] != paramsCopy[i] )
{
std::cerr << "Copy constructor failed. " << std::endl;
passed = false;
}
}
}
//Constructor from array
Array<TValueType> array(dim);
for( SizeValueType i=0; i<dim; i++ )
{ array[i]=i*3.19; }
{
OptimizerParameters<TValueType> paramsCopy( array );
for( SizeValueType i=0; i < params.GetSize(); i++ )
{
if( array[i] != paramsCopy[i] )
{
std::cerr << "Constructor from Array failed. " << std::endl;
passed = false;
}
}
}
/* Test assignment operators from different types */
//Assign from Array
OptimizerParameters<TValueType> paramsArray;
paramsArray = array;
for( SizeValueType i=0; i < array.GetSize(); i++ )
{
if( paramsArray[i] != array[i] )
{
std::cerr << "Copy from Array via assignment failed. " << std::endl;
passed = false;
}
}
//Assign from VnlVector
vnl_vector<TValueType> vector(dim);
for( SizeValueType i=0; i<dim; i++ )
{ vector[i]=i*0.123; }
{
OptimizerParameters<TValueType> paramsVnl;
paramsVnl = vector;
for( SizeValueType i=0; i < paramsVnl.GetSize(); i++ )
{
if( vector[i] != paramsVnl[i] )
{
std::cerr << "Assignment from VnlVector failed. " << std::endl;
passed = false;
}
}
}
/* Test MoveDataPointer to point to different memory block */
TValueType block[10] = {10,9,8,7,6,5,4,3,2,1};
params.MoveDataPointer( block );
for( int i=0; i < 10; i++)
{
if( params[i] != 10-i )
{
std::cerr << "Failed reading memory after MoveDataPointer." << std::endl
<< "Expected: " << 10-i << ", got: " << params[i] << std::endl;
passed = false;
}
}
/* Test SetParametersObject. Should throw exception with default helper. */
typename LightObject::Pointer dummyObj = LightObject::New();
TRY_EXPECT_EXCEPTION( params.SetParametersObject( dummyObj.GetPointer() ) );
/* Test with null helper and expect exception */
params.SetHelper( NULL );
TRY_EXPECT_EXCEPTION( params.MoveDataPointer( block ) );
TRY_EXPECT_EXCEPTION( params.SetParametersObject( dummyObj.GetPointer() ) );
/* Test copy operator */
OptimizerParameters<TValueType> params1(4);
OptimizerParameters<TValueType> params2(4);
params1.Fill(1.23);
params2 = params1;
for( SizeValueType i=0; i < params1.GetSize(); i++ )
{
if( params1[i] != params2[i] )
{
std::cerr << "Copy operator failed:" << std::endl
<< "params1 " << params1 << std::endl
<< "params2 " << params2 << std::endl;
passed = false;
break;
}
}
/* Exercise set helper */
typedef typename OptimizerParameters<TValueType>::OptimizerParametersHelperType HelperType;
HelperType * helper = new HelperType;
params1.SetHelper( helper );
return passed;
}
int itkOptimizerParametersTest(int, char *[])
{
bool passed = true;
/* Test double type */
if( runTestByType<double>() == false )
{
passed = false;
}
/* Test float type */
if( runTestByType<float>() == false )
{
passed = false;
}
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>COMP: Tests should not have "using namespace itk".<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkOptimizerParameters.h"
#include "itkIntTypes.h"
#include "itkTestingMacros.h"
template< typename TValueType >
bool runTestByType()
{
bool passed = true;
itk::OptimizerParameters<TValueType> params;
params.SetSize(10);
params.Fill(1.23);
std::cout << "GetSize: " << params.GetSize() << std::endl;
/* Test different ctors */
//Construct by size
itk::SizeValueType dim = 20;
itk::OptimizerParameters<TValueType> paramsSize(dim);
if( paramsSize.GetSize() != dim )
{
std::cerr << "Constructor with dimension failed. Expected size of "
<< dim << ", but got " << paramsSize.GetSize() << "." << std::endl;
passed = false;
}
//Copy constructor
{
itk::OptimizerParameters<TValueType> paramsCopy( params );
for( itk::SizeValueType i=0; i < params.GetSize(); i++ )
{
if( params[i] != paramsCopy[i] )
{
std::cerr << "Copy constructor failed. " << std::endl;
passed = false;
}
}
}
//Constructor from array
itk::Array<TValueType> array(dim);
for( itk::SizeValueType i=0; i<dim; i++ )
{ array[i]=i*3.19; }
{
itk::OptimizerParameters<TValueType> paramsCopy( array );
for( itk::SizeValueType i=0; i < params.GetSize(); i++ )
{
if( array[i] != paramsCopy[i] )
{
std::cerr << "Constructor from Array failed. " << std::endl;
passed = false;
}
}
}
/* Test assignment operators from different types */
//Assign from Array
itk::OptimizerParameters<TValueType> paramsArray;
paramsArray = array;
for( itk::SizeValueType i=0; i < array.GetSize(); i++ )
{
if( paramsArray[i] != array[i] )
{
std::cerr << "Copy from Array via assignment failed. " << std::endl;
passed = false;
}
}
//Assign from VnlVector
vnl_vector<TValueType> vector(dim);
for( itk::SizeValueType i=0; i<dim; i++ )
{ vector[i]=i*0.123; }
{
itk::OptimizerParameters<TValueType> paramsVnl;
paramsVnl = vector;
for( itk::SizeValueType i=0; i < paramsVnl.GetSize(); i++ )
{
if( vector[i] != paramsVnl[i] )
{
std::cerr << "Assignment from VnlVector failed. " << std::endl;
passed = false;
}
}
}
/* Test MoveDataPointer to point to different memory block */
TValueType block[10] = {10,9,8,7,6,5,4,3,2,1};
params.MoveDataPointer( block );
for( int i=0; i < 10; i++)
{
if( params[i] != 10-i )
{
std::cerr << "Failed reading memory after MoveDataPointer." << std::endl
<< "Expected: " << 10-i << ", got: " << params[i] << std::endl;
passed = false;
}
}
/* Test SetParametersObject. Should throw exception with default helper. */
typename itk::LightObject::Pointer dummyObj = itk::LightObject::New();
TRY_EXPECT_EXCEPTION( params.SetParametersObject( dummyObj.GetPointer() ) );
/* Test with null helper and expect exception */
params.SetHelper( NULL );
TRY_EXPECT_EXCEPTION( params.MoveDataPointer( block ) );
TRY_EXPECT_EXCEPTION( params.SetParametersObject( dummyObj.GetPointer() ) );
/* Test copy operator */
itk::OptimizerParameters<TValueType> params1(4);
itk::OptimizerParameters<TValueType> params2(4);
params1.Fill(1.23);
params2 = params1;
for( itk::SizeValueType i=0; i < params1.GetSize(); i++ )
{
if( params1[i] != params2[i] )
{
std::cerr << "Copy operator failed:" << std::endl
<< "params1 " << params1 << std::endl
<< "params2 " << params2 << std::endl;
passed = false;
break;
}
}
/* Exercise set helper */
typedef typename itk::OptimizerParameters<TValueType>::OptimizerParametersHelperType HelperType;
HelperType * helper = new HelperType;
params1.SetHelper( helper );
return passed;
}
int itkOptimizerParametersTest(int, char *[])
{
bool passed = true;
/* Test double type */
if( runTestByType<double>() == false )
{
passed = false;
}
/* Test float type */
if( runTestByType<float>() == false )
{
passed = false;
}
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbPointSetExtractROI_hxx
#define otbPointSetExtractROI_hxx
#include "otbPointSetExtractROI.h"
#include "itkMacro.h"
namespace otb
{
/**
*
*/
template <class TInputPointSet, class TOutputPointSet>
PointSetExtractROI<TInputPointSet, TOutputPointSet>
::PointSetExtractROI()
{
}
/**
*
*/
template <class TInputPointSet, class TOutputPointSet>
void
PointSetExtractROI<TInputPointSet, TOutputPointSet>
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
/**
* This method causes the filter to generate its output.
*/
template <class TInputPointSet, class TOutputPointSet>
void
PointSetExtractROI<TInputPointSet, TOutputPointSet>
::GenerateData(void)
{
typedef typename TInputPointSet::PointsContainer InputPointsContainer;
typedef typename TInputPointSet::PointsContainerPointer InputPointsContainerPointer;
typedef typename TOutputPointSet::PointsContainerPointer OutputPointsContainerPointer;
typedef typename TInputPointSet::PointDataContainerPointer InputPointDataContainerPointer;
typedef typename TOutputPointSet::PointDataContainerPointer OutputPointDataContainerPointer;
InputPointSetPointer inputPointSet = this->GetInput();
OutputPointSetPointer outputPointSet = this->GetOutput();
if (!inputPointSet)
{
itkExceptionMacro(<< "Missing Input PointSet");
}
if (!outputPointSet)
{
itkExceptionMacro(<< "Missing Output PointSet");
}
outputPointSet->SetBufferedRegion(outputPointSet->GetRequestedRegion()); //TODO update outputRegion
InputPointsContainerPointer inPoints = inputPointSet->GetPoints();
InputPointDataContainerPointer inData = inputPointSet->GetPointData();
OutputPointsContainerPointer outPoints = outputPointSet->GetPoints();
OutputPointDataContainerPointer outData = outputPointSet->GetPointData();
typename InputPointsContainer::ConstIterator inputPoint = inPoints->Begin();
// Commented cause using iterator on the pointSetData crash
// Use a direct access to pointSet Data instead to avoid segfault
//typename InputPointDataContainer::ConstIterator inputData = inData->Begin();
//if (inData.IsNotNull())
// {
// inputData = inData->Begin();
// }
while (inputPoint != inPoints->End())
{
typename InputPointsContainer::Element point = inputPoint.Value();
if ((((point[0] >= m_StartX) && (point[0] < m_StartX + m_SizeX))
|| ((point[0] <= m_StartX) && (point[0] > m_StartX + m_SizeX))) //cover the case when size<0
&& (((point[1] >= m_StartY) && (point[1] < m_StartY + m_SizeY))
|| ((point[1] <= m_StartY) && (point[1] > m_StartY + m_SizeY))))
{
// Add the point
outPoints->push_back(point);
// Get & Add the data
typename InputPointSetType::PixelType data;
inputPointSet->GetPointData(inputPoint.Index(), &data);
outData->push_back(data/*inputData.Value()*/);
}
++inputPoint;
//++inputData;
}
}
} // end namespace otb
#endif
<commit_msg>BUG: fix unitialized member variable<commit_after>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbPointSetExtractROI_hxx
#define otbPointSetExtractROI_hxx
#include "otbPointSetExtractROI.h"
#include "itkMacro.h"
namespace otb
{
/**
*
*/
template <class TInputPointSet, class TOutputPointSet>
PointSetExtractROI<TInputPointSet, TOutputPointSet>
::PointSetExtractROI() : m_SizeX(0), m_StartY(0), m_SizeX(0), m_SizeY(0)
{
}
/**
*
*/
template <class TInputPointSet, class TOutputPointSet>
void
PointSetExtractROI<TInputPointSet, TOutputPointSet>
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
/**
* This method causes the filter to generate its output.
*/
template <class TInputPointSet, class TOutputPointSet>
void
PointSetExtractROI<TInputPointSet, TOutputPointSet>
::GenerateData(void)
{
typedef typename TInputPointSet::PointsContainer InputPointsContainer;
typedef typename TInputPointSet::PointsContainerPointer InputPointsContainerPointer;
typedef typename TOutputPointSet::PointsContainerPointer OutputPointsContainerPointer;
typedef typename TInputPointSet::PointDataContainerPointer InputPointDataContainerPointer;
typedef typename TOutputPointSet::PointDataContainerPointer OutputPointDataContainerPointer;
InputPointSetPointer inputPointSet = this->GetInput();
OutputPointSetPointer outputPointSet = this->GetOutput();
if (!inputPointSet)
{
itkExceptionMacro(<< "Missing Input PointSet");
}
if (!outputPointSet)
{
itkExceptionMacro(<< "Missing Output PointSet");
}
outputPointSet->SetBufferedRegion(outputPointSet->GetRequestedRegion()); //TODO update outputRegion
InputPointsContainerPointer inPoints = inputPointSet->GetPoints();
InputPointDataContainerPointer inData = inputPointSet->GetPointData();
OutputPointsContainerPointer outPoints = outputPointSet->GetPoints();
OutputPointDataContainerPointer outData = outputPointSet->GetPointData();
typename InputPointsContainer::ConstIterator inputPoint = inPoints->Begin();
// Commented cause using iterator on the pointSetData crash
// Use a direct access to pointSet Data instead to avoid segfault
//typename InputPointDataContainer::ConstIterator inputData = inData->Begin();
//if (inData.IsNotNull())
// {
// inputData = inData->Begin();
// }
while (inputPoint != inPoints->End())
{
typename InputPointsContainer::Element point = inputPoint.Value();
if ((((point[0] >= m_StartX) && (point[0] < m_StartX + m_SizeX))
|| ((point[0] <= m_StartX) && (point[0] > m_StartX + m_SizeX))) //cover the case when size<0
&& (((point[1] >= m_StartY) && (point[1] < m_StartY + m_SizeY))
|| ((point[1] <= m_StartY) && (point[1] > m_StartY + m_SizeY))))
{
// Add the point
outPoints->push_back(point);
// Get & Add the data
typename InputPointSetType::PixelType data;
inputPointSet->GetPointData(inputPoint.Index(), &data);
outData->push_back(data/*inputData.Value()*/);
}
++inputPoint;
//++inputData;
}
}
} // end namespace otb
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkMovieGeneratorOpenCV.h"
//#include <GL/gl.h>
#include "mitkgl.h"
#include <iostream>
mitk::MovieGeneratorOpenCV::MovieGeneratorOpenCV()
{
m_initialized = false;
m_aviWriter = NULL;
m_dwRate = 20;
m_FourCCCodec = NULL;
m_RemoveColouredFrame = true;
}
void mitk::MovieGeneratorOpenCV::SetFileName( const char *fileName )
{
m_sFile = fileName;
}
void mitk::MovieGeneratorOpenCV::SetFrameRate(int rate)
{
m_dwRate = rate;
}
void mitk::MovieGeneratorOpenCV::SetRemoveColouredFrame(bool RemoveColouredFrame)
{
m_RemoveColouredFrame = RemoveColouredFrame;
}
bool mitk::MovieGeneratorOpenCV::InitGenerator()
{
m_width = m_renderer->GetRenderWindow()->GetSize()[0]; // changed from glGetIntegerv( GL_VIEWPORT, viewport );
m_height = m_renderer->GetRenderWindow()->GetSize()[1]; // due to sometimes strange dimensions
if(m_RemoveColouredFrame)
{
m_width -= 10; //remove colored boarders around renderwindows
m_height -= 10;
}
m_width -= m_width % 4; // some video codecs have prerequisites to the image dimensions
m_height -= m_height % 4;
m_currentFrame = cvCreateImage(cvSize(m_width,m_height),8,3); // creating image with widget size, 8 bit per pixel and 3 channel r,g,b
m_currentFrame->origin = 1; // avoid building a video with bottom up
/*
m_sFile = Name of the output video file.
CV_FOURCC = 4-character code of codec used to compress the frames. For example, CV_FOURCC('P','I','M','1') is MPEG-1 codec,
CV_FOURCC('M','J','P','G') is motion-jpeg codec etc.
CV_FOURCC('P','I','M','1') = MPEG-1 codec
CV_FOURCC('M','J','P','G') = motion-jpeg codec (does not work well)
CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
CV_FOURCC('U', '2', '6', '3') = H263 codec
CV_FOURCC('I', '2', '6', '3') = H263I codec
CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec
List of FOURCC codes is available at http://msdn2.microsoft.com/en-us/library/ms867195.aspx
Under Win32 it is possible to pass -1 in order to choose compression
method and additional compression parameters from dialog.
m_dwRate = Framerate of the created video stream.
frame_size Size of video frames. InitGenerator
1 = If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames
(the flag is currently supported on Windows only).*/
if(m_FourCCCodec != NULL)
{
#ifdef WIN32
m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC(m_FourCCCodec[0],m_FourCCCodec[1],m_FourCCCodec[2],
m_FourCCCodec[3]),m_dwRate,cvSize(m_width,m_height),1); //initializing video writer
#else
m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC(m_FourCCCodec[0],m_FourCCCodec[1],m_FourCCCodec[2],
m_FourCCCodec[3]),m_dwRate,cvSize(m_width,m_height)); //initializing video writer
#endif
}
else
{
#ifdef WIN32
m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),-1,m_dwRate,cvSize(m_width,m_height),1); //initializing video writer
#else
m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC('X','V','I','D'),m_dwRate,cvSize(m_width,m_height)); //initializing video writer
#endif
}
if(!m_aviWriter)
{
std::cout << "errors initializing video writer...correct video file path? on linux: ffmpeg must be included in OpenCV.";
return false;
}
return true;
}
bool mitk::MovieGeneratorOpenCV::AddFrame( void *data )
{
//cvSetImageData(m_currentFrame,data,m_width*3);
memcpy(m_currentFrame->imageData,data,m_width*m_height*3);
cvWriteFrame(m_aviWriter,m_currentFrame);
return true;
}
bool mitk::MovieGeneratorOpenCV::TerminateGenerator()
{
if (m_aviWriter)
{
cvReleaseVideoWriter(&m_aviWriter);
}
return true;
}
<commit_msg>COMP: fixed mitkGL.h path bug<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkMovieGeneratorOpenCV.h"
//#include <GL/gl.h>
#include "mitkGL.h"
#include <iostream>
mitk::MovieGeneratorOpenCV::MovieGeneratorOpenCV()
{
m_initialized = false;
m_aviWriter = NULL;
m_dwRate = 20;
m_FourCCCodec = NULL;
m_RemoveColouredFrame = true;
}
void mitk::MovieGeneratorOpenCV::SetFileName( const char *fileName )
{
m_sFile = fileName;
}
void mitk::MovieGeneratorOpenCV::SetFrameRate(int rate)
{
m_dwRate = rate;
}
void mitk::MovieGeneratorOpenCV::SetRemoveColouredFrame(bool RemoveColouredFrame)
{
m_RemoveColouredFrame = RemoveColouredFrame;
}
bool mitk::MovieGeneratorOpenCV::InitGenerator()
{
m_width = m_renderer->GetRenderWindow()->GetSize()[0]; // changed from glGetIntegerv( GL_VIEWPORT, viewport );
m_height = m_renderer->GetRenderWindow()->GetSize()[1]; // due to sometimes strange dimensions
if(m_RemoveColouredFrame)
{
m_width -= 10; //remove colored boarders around renderwindows
m_height -= 10;
}
m_width -= m_width % 4; // some video codecs have prerequisites to the image dimensions
m_height -= m_height % 4;
m_currentFrame = cvCreateImage(cvSize(m_width,m_height),8,3); // creating image with widget size, 8 bit per pixel and 3 channel r,g,b
m_currentFrame->origin = 1; // avoid building a video with bottom up
/*
m_sFile = Name of the output video file.
CV_FOURCC = 4-character code of codec used to compress the frames. For example, CV_FOURCC('P','I','M','1') is MPEG-1 codec,
CV_FOURCC('M','J','P','G') is motion-jpeg codec etc.
CV_FOURCC('P','I','M','1') = MPEG-1 codec
CV_FOURCC('M','J','P','G') = motion-jpeg codec (does not work well)
CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
CV_FOURCC('U', '2', '6', '3') = H263 codec
CV_FOURCC('I', '2', '6', '3') = H263I codec
CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec
List of FOURCC codes is available at http://msdn2.microsoft.com/en-us/library/ms867195.aspx
Under Win32 it is possible to pass -1 in order to choose compression
method and additional compression parameters from dialog.
m_dwRate = Framerate of the created video stream.
frame_size Size of video frames. InitGenerator
1 = If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames
(the flag is currently supported on Windows only).*/
if(m_FourCCCodec != NULL)
{
#ifdef WIN32
m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC(m_FourCCCodec[0],m_FourCCCodec[1],m_FourCCCodec[2],
m_FourCCCodec[3]),m_dwRate,cvSize(m_width,m_height),1); //initializing video writer
#else
m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC(m_FourCCCodec[0],m_FourCCCodec[1],m_FourCCCodec[2],
m_FourCCCodec[3]),m_dwRate,cvSize(m_width,m_height)); //initializing video writer
#endif
}
else
{
#ifdef WIN32
m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),-1,m_dwRate,cvSize(m_width,m_height),1); //initializing video writer
#else
m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC('X','V','I','D'),m_dwRate,cvSize(m_width,m_height)); //initializing video writer
#endif
}
if(!m_aviWriter)
{
std::cout << "errors initializing video writer...correct video file path? on linux: ffmpeg must be included in OpenCV.";
return false;
}
return true;
}
bool mitk::MovieGeneratorOpenCV::AddFrame( void *data )
{
//cvSetImageData(m_currentFrame,data,m_width*3);
memcpy(m_currentFrame->imageData,data,m_width*m_height*3);
cvWriteFrame(m_aviWriter,m_currentFrame);
return true;
}
bool mitk::MovieGeneratorOpenCV::TerminateGenerator()
{
if (m_aviWriter)
{
cvReleaseVideoWriter(&m_aviWriter);
}
return true;
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkSetRegionTool.h"
#include "mitkToolManager.h"
#include "mitkOverwriteSliceImageFilter.h"
#include "ipSegmentation.h"
#include "mitkBaseRenderer.h"
#include "mitkImageDataItem.h"
#include "mitkOverwriteDirectedPlaneImageFilter.h"
mitk::SetRegionTool::SetRegionTool(int paintingPixelValue)
:FeedbackContourTool("PressMoveReleaseWithCTRLInversion"),
m_PaintingPixelValue(paintingPixelValue),
m_FillContour(false),
m_StatusFillWholeSlice(false)
{
// great magic numbers
CONNECT_ACTION( 80, OnMousePressed );
//CONNECT_ACTION( 90, OnMouseMoved );
CONNECT_ACTION( 42, OnMouseReleased );
CONNECT_ACTION( 49014, OnInvertLogic );
}
mitk::SetRegionTool::~SetRegionTool()
{
}
void mitk::SetRegionTool::Activated()
{
Superclass::Activated();
}
void mitk::SetRegionTool::Deactivated()
{
Superclass::Deactivated();
}
bool mitk::SetRegionTool::OnMousePressed (Action* action, const StateEvent* stateEvent)
{
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return false;
m_LastEventSender = positionEvent->GetSender();
m_LastEventSlice = m_LastEventSender->GetSlice();
if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;
// 1. Get the working image
Image::Pointer workingSlice = FeedbackContourTool::GetAffectedWorkingSlice( positionEvent );
if ( workingSlice.IsNull() ) return false; // can't do anything without the segmentation
// if click was outside the image, don't continue
const Geometry3D* sliceGeometry = workingSlice->GetGeometry();
itk::Index<2> projectedPointIn2D;
sliceGeometry->WorldToIndex( positionEvent->GetWorldPosition(), projectedPointIn2D );
if ( !sliceGeometry->IsIndexInside( projectedPointIn2D ) )
{
MITK_ERROR << "point apparently not inside segmentation slice" << std::endl;
return false; // can't use that as a seed point
}
// Convert to ipMITKSegmentationTYPE (because ipMITKSegmentationGetContour8N relys on that data type)
itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage;
CastToItkImage( workingSlice, correctPixelTypeImage );
assert (correctPixelTypeImage.IsNotNull() );
// possible bug in CastToItkImage ?
// direction maxtrix is wrong/broken/not working after CastToItkImage, leading to a failed assertion in
// mitk/Core/DataStructures/mitkSlicedGeometry3D.cpp, 479:
// virtual void mitk::SlicedGeometry3D::SetSpacing(const mitk::Vector3D&): Assertion `aSpacing[0]>0 && aSpacing[1]>0 && aSpacing[2]>0' failed
// solution here: we overwrite it with an unity matrix
itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection;
imageDirection.SetIdentity();
correctPixelTypeImage->SetDirection(imageDirection);
Image::Pointer temporarySlice = Image::New();
// temporarySlice = ImportItkImage( correctPixelTypeImage );
CastToMitkImage( correctPixelTypeImage, temporarySlice );
// check index positions
mitkIpPicDescriptor* originalPicSlice = mitkIpPicNew();
CastToIpPicDescriptor( temporarySlice, originalPicSlice );
int m_SeedPointMemoryOffset = projectedPointIn2D[1] * originalPicSlice->n[0] + projectedPointIn2D[0];
if ( m_SeedPointMemoryOffset >= static_cast<int>( originalPicSlice->n[0] * originalPicSlice->n[1] ) ||
m_SeedPointMemoryOffset < 0 )
{
MITK_ERROR << "Memory offset calculation if mitk::SetRegionTool has some serious flaw! Aborting.." << std::endl;
return false;
}
// 2. Determine the contour that surronds the selected "piece of the image"
// find a contour seed point
unsigned int oneContourOffset = static_cast<unsigned int>( m_SeedPointMemoryOffset ); // safe because of earlier check if m_SeedPointMemoryOffset < 0
/**
* The logic of finding a starting point for the contour is the following:
*
* - If the initial seed point is 0, we are either inside a hole or outside of every segmentation.
* We move to the right until we hit a 1, which must be part of a contour.
*
* - If the initial seed point is 1, then ...
* we now do the same (running to the right) until we hit a 1
*
* In both cases the found contour point is used to extract a contour and
* then a test is applied to find out if the initial seed point is contained
* in the contour. If this is the case, filling should be applied, otherwise
* nothing is done.
*/
unsigned int size = originalPicSlice->n[0] * originalPicSlice->n[1];
/*
unsigned int rowSize = originalPicSlice->n[0];
*/
ipMITKSegmentationTYPE* data = static_cast<ipMITKSegmentationTYPE*>(originalPicSlice->data);
if ( data[oneContourOffset] == 0 ) // initial seed 0
{
for ( ; oneContourOffset < size; ++oneContourOffset )
{
if ( data[oneContourOffset] > 0 ) break;
}
}
else if ( data[oneContourOffset] == 1 ) // initial seed 1
{
unsigned int lastValidPixel = size-1; // initialization, will be changed lateron
bool inSeg = true; // inside segmentation?
for ( ; oneContourOffset < size; ++oneContourOffset )
{
if ( ( data[oneContourOffset] == 0 ) && inSeg ) // pixel 0 and inside-flag set: this happens at the first pixel outside a filled region
{
inSeg = false;
lastValidPixel = oneContourOffset - 1; // store the last pixel position inside a filled region
break;
}
else // pixel 1, inside-flag doesn't matter: this happens while we are inside a filled region
{
inSeg = true; // first iteration lands here
}
}
oneContourOffset = lastValidPixel;
}
else
{
MITK_ERROR << "Fill/Erase was never intended to work with other than binary images." << std::endl;
m_FillContour = false;
return false;
}
if (oneContourOffset == size) // nothing found until end of slice
{
m_FillContour = false;
return false;
}
int numberOfContourPoints( 0 );
int newBufferSize( 0 );
//MITK_INFO << "getting contour from offset " << oneContourOffset << " ("<<oneContourOffset%originalPicSlice->n[0]<<","<<oneContourOffset/originalPicSlice->n[0]<<")"<<std::endl;
float* contourPoints = ipMITKSegmentationGetContour8N( originalPicSlice, oneContourOffset, numberOfContourPoints, newBufferSize ); // memory allocated with malloc
//MITK_INFO << "contourPoints " << contourPoints << " (N="<<numberOfContourPoints<<")"<<std::endl;
assert(contourPoints == NULL || numberOfContourPoints > 0);
bool cursorInsideContour = ipMITKSegmentationIsInsideContour( contourPoints, numberOfContourPoints, projectedPointIn2D[0], projectedPointIn2D[1]);
// decide if contour should be filled or not
m_FillContour = cursorInsideContour;
if (m_FillContour)
{
// copy point from float* to mitk::Contour
ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New();
contourInImageIndexCoordinates->Initialize();
Point3D newPoint;
for (int index = 0; index < numberOfContourPoints; ++index)
{
newPoint[0] = contourPoints[ 2 * index + 0 ] - 0.5;
newPoint[1] = contourPoints[ 2 * index + 1] - 0.5;
newPoint[2] = 0;
contourInImageIndexCoordinates->AddVertex(newPoint);
}
m_SegmentationContourInWorldCoordinates = FeedbackContourTool::BackProjectContourFrom2DSlice( workingSlice->GetGeometry(), contourInImageIndexCoordinates, true ); // true, correct the result from ipMITKSegmentationGetContour8N
// 3. Show the contour
FeedbackContourTool::SetFeedbackContour( *m_SegmentationContourInWorldCoordinates );
FeedbackContourTool::SetFeedbackContourVisible(true);
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
// always generate a second contour, containing the whole image (used when CTRL is pressed)
{
// copy point from float* to mitk::Contour
ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New();
contourInImageIndexCoordinates->Initialize();
Point3D newPoint;
newPoint[0] = 0; newPoint[1] = 0; newPoint[2] = 0.0;
contourInImageIndexCoordinates->AddVertex( newPoint );
newPoint[0] = originalPicSlice->n[0]; newPoint[1] = 0; newPoint[2] = 0.0;
contourInImageIndexCoordinates->AddVertex( newPoint );
newPoint[0] = originalPicSlice->n[0]; newPoint[1] = originalPicSlice->n[1]; newPoint[2] = 0.0;
contourInImageIndexCoordinates->AddVertex( newPoint );
newPoint[0] = 0; newPoint[1] = originalPicSlice->n[1]; newPoint[2] = 0.0;
contourInImageIndexCoordinates->AddVertex( newPoint );
m_WholeImageContourInWorldCoordinates = FeedbackContourTool::BackProjectContourFrom2DSlice( workingSlice->GetGeometry(), contourInImageIndexCoordinates, true ); // true, correct the result from ipMITKSegmentationGetContour8N
// 3. Show the contour
FeedbackContourTool::SetFeedbackContour( *m_SegmentationContourInWorldCoordinates );
FeedbackContourTool::SetFeedbackContourVisible(true);
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
free(contourPoints);
return true;
}
bool mitk::SetRegionTool::OnMouseReleased(Action* action, const StateEvent* stateEvent)
{
// 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's working image corresponds to that
FeedbackContourTool::SetFeedbackContourVisible(false);
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return false;
assert( positionEvent->GetSender()->GetRenderWindow() );
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
if (!m_FillContour && !m_StatusFillWholeSlice) return true;
if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;
DataNode* workingNode( m_ToolManager->GetWorkingData(0) );
if (!workingNode) return false;
Image* image = dynamic_cast<Image*>(workingNode->GetData());
const PlaneGeometry* planeGeometry( dynamic_cast<const PlaneGeometry*> (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) );
if ( !image || !planeGeometry ) return false;
Image::Pointer slice = FeedbackContourTool::GetAffectedImageSliceAs2DImage( positionEvent, image );
if ( slice.IsNull() )
{
MITK_ERROR << "Unable to extract slice." << std::endl;
return false;
}
ContourModel* feedbackContour( FeedbackContourTool::GetFeedbackContour() );
ContourModel::Pointer projectedContour = FeedbackContourTool::ProjectContourTo2DSlice( slice, feedbackContour, false, false ); // false: don't add 0.5 (done by FillContourInSlice)
// false: don't constrain the contour to the image's inside
if (projectedContour.IsNull()) return false;
FeedbackContourTool::FillContourInSlice( projectedContour, slice, m_PaintingPixelValue );
this->WriteBackSegmentationResult(positionEvent, slice);
m_WholeImageContourInWorldCoordinates = NULL;
m_SegmentationContourInWorldCoordinates = NULL;
return true;
}
/**
Called when the CTRL key is pressed. Will change the painting pixel value from 0 to 1 or from 1 to 0.
*/
bool mitk::SetRegionTool::OnInvertLogic(Action* action, const StateEvent* stateEvent)
{
if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return false;
if (m_StatusFillWholeSlice)
{
// use contour extracted from image data
if (m_SegmentationContourInWorldCoordinates.IsNotNull())
FeedbackContourTool::SetFeedbackContour( *m_SegmentationContourInWorldCoordinates );
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
else
{
// use some artificial contour
if (m_WholeImageContourInWorldCoordinates.IsNotNull())
FeedbackContourTool::SetFeedbackContour( *m_WholeImageContourInWorldCoordinates );
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
m_StatusFillWholeSlice = !m_StatusFillWholeSlice;
return true;
}
<commit_msg>4D contour support for SetRegionTool.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkSetRegionTool.h"
#include "mitkToolManager.h"
#include "mitkOverwriteSliceImageFilter.h"
#include "ipSegmentation.h"
#include "mitkBaseRenderer.h"
#include "mitkImageDataItem.h"
#include "mitkOverwriteDirectedPlaneImageFilter.h"
mitk::SetRegionTool::SetRegionTool(int paintingPixelValue)
:FeedbackContourTool("PressMoveReleaseWithCTRLInversion"),
m_PaintingPixelValue(paintingPixelValue),
m_FillContour(false),
m_StatusFillWholeSlice(false)
{
// great magic numbers
CONNECT_ACTION( 80, OnMousePressed );
//CONNECT_ACTION( 90, OnMouseMoved );
CONNECT_ACTION( 42, OnMouseReleased );
CONNECT_ACTION( 49014, OnInvertLogic );
}
mitk::SetRegionTool::~SetRegionTool()
{
}
void mitk::SetRegionTool::Activated()
{
Superclass::Activated();
}
void mitk::SetRegionTool::Deactivated()
{
Superclass::Deactivated();
}
bool mitk::SetRegionTool::OnMousePressed (Action* action, const StateEvent* stateEvent)
{
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return false;
m_LastEventSender = positionEvent->GetSender();
m_LastEventSlice = m_LastEventSender->GetSlice();
int timeStep = positionEvent->GetSender()->GetTimeStep();
if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;
// 1. Get the working image
Image::Pointer workingSlice = FeedbackContourTool::GetAffectedWorkingSlice( positionEvent );
if ( workingSlice.IsNull() ) return false; // can't do anything without the segmentation
// if click was outside the image, don't continue
const Geometry3D* sliceGeometry = workingSlice->GetGeometry();
itk::Index<2> projectedPointIn2D;
sliceGeometry->WorldToIndex( positionEvent->GetWorldPosition(), projectedPointIn2D );
if ( !sliceGeometry->IsIndexInside( projectedPointIn2D ) )
{
MITK_ERROR << "point apparently not inside segmentation slice" << std::endl;
return false; // can't use that as a seed point
}
// Convert to ipMITKSegmentationTYPE (because ipMITKSegmentationGetContour8N relys on that data type)
itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage;
CastToItkImage( workingSlice, correctPixelTypeImage );
assert (correctPixelTypeImage.IsNotNull() );
// possible bug in CastToItkImage ?
// direction maxtrix is wrong/broken/not working after CastToItkImage, leading to a failed assertion in
// mitk/Core/DataStructures/mitkSlicedGeometry3D.cpp, 479:
// virtual void mitk::SlicedGeometry3D::SetSpacing(const mitk::Vector3D&): Assertion `aSpacing[0]>0 && aSpacing[1]>0 && aSpacing[2]>0' failed
// solution here: we overwrite it with an unity matrix
itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection;
imageDirection.SetIdentity();
correctPixelTypeImage->SetDirection(imageDirection);
Image::Pointer temporarySlice = Image::New();
// temporarySlice = ImportItkImage( correctPixelTypeImage );
CastToMitkImage( correctPixelTypeImage, temporarySlice );
// check index positions
mitkIpPicDescriptor* originalPicSlice = mitkIpPicNew();
CastToIpPicDescriptor( temporarySlice, originalPicSlice );
int m_SeedPointMemoryOffset = projectedPointIn2D[1] * originalPicSlice->n[0] + projectedPointIn2D[0];
if ( m_SeedPointMemoryOffset >= static_cast<int>( originalPicSlice->n[0] * originalPicSlice->n[1] ) ||
m_SeedPointMemoryOffset < 0 )
{
MITK_ERROR << "Memory offset calculation if mitk::SetRegionTool has some serious flaw! Aborting.." << std::endl;
return false;
}
// 2. Determine the contour that surronds the selected "piece of the image"
// find a contour seed point
unsigned int oneContourOffset = static_cast<unsigned int>( m_SeedPointMemoryOffset ); // safe because of earlier check if m_SeedPointMemoryOffset < 0
/**
* The logic of finding a starting point for the contour is the following:
*
* - If the initial seed point is 0, we are either inside a hole or outside of every segmentation.
* We move to the right until we hit a 1, which must be part of a contour.
*
* - If the initial seed point is 1, then ...
* we now do the same (running to the right) until we hit a 1
*
* In both cases the found contour point is used to extract a contour and
* then a test is applied to find out if the initial seed point is contained
* in the contour. If this is the case, filling should be applied, otherwise
* nothing is done.
*/
unsigned int size = originalPicSlice->n[0] * originalPicSlice->n[1];
/*
unsigned int rowSize = originalPicSlice->n[0];
*/
ipMITKSegmentationTYPE* data = static_cast<ipMITKSegmentationTYPE*>(originalPicSlice->data);
if ( data[oneContourOffset] == 0 ) // initial seed 0
{
for ( ; oneContourOffset < size; ++oneContourOffset )
{
if ( data[oneContourOffset] > 0 ) break;
}
}
else if ( data[oneContourOffset] == 1 ) // initial seed 1
{
unsigned int lastValidPixel = size-1; // initialization, will be changed lateron
bool inSeg = true; // inside segmentation?
for ( ; oneContourOffset < size; ++oneContourOffset )
{
if ( ( data[oneContourOffset] == 0 ) && inSeg ) // pixel 0 and inside-flag set: this happens at the first pixel outside a filled region
{
inSeg = false;
lastValidPixel = oneContourOffset - 1; // store the last pixel position inside a filled region
break;
}
else // pixel 1, inside-flag doesn't matter: this happens while we are inside a filled region
{
inSeg = true; // first iteration lands here
}
}
oneContourOffset = lastValidPixel;
}
else
{
MITK_ERROR << "Fill/Erase was never intended to work with other than binary images." << std::endl;
m_FillContour = false;
return false;
}
if (oneContourOffset == size) // nothing found until end of slice
{
m_FillContour = false;
return false;
}
int numberOfContourPoints( 0 );
int newBufferSize( 0 );
//MITK_INFO << "getting contour from offset " << oneContourOffset << " ("<<oneContourOffset%originalPicSlice->n[0]<<","<<oneContourOffset/originalPicSlice->n[0]<<")"<<std::endl;
float* contourPoints = ipMITKSegmentationGetContour8N( originalPicSlice, oneContourOffset, numberOfContourPoints, newBufferSize ); // memory allocated with malloc
//MITK_INFO << "contourPoints " << contourPoints << " (N="<<numberOfContourPoints<<")"<<std::endl;
assert(contourPoints == NULL || numberOfContourPoints > 0);
bool cursorInsideContour = ipMITKSegmentationIsInsideContour( contourPoints, numberOfContourPoints, projectedPointIn2D[0], projectedPointIn2D[1]);
// decide if contour should be filled or not
m_FillContour = cursorInsideContour;
if (m_FillContour)
{
// copy point from float* to mitk::Contour
ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New();
contourInImageIndexCoordinates->Expand(timeStep + 1);
contourInImageIndexCoordinates->SetIsClosed(true, timeStep);
Point3D newPoint;
for (int index = 0; index < numberOfContourPoints; ++index)
{
newPoint[0] = contourPoints[ 2 * index + 0 ] - 0.5;
newPoint[1] = contourPoints[ 2 * index + 1] - 0.5;
newPoint[2] = 0;
contourInImageIndexCoordinates->AddVertex(newPoint, timeStep);
}
m_SegmentationContourInWorldCoordinates = FeedbackContourTool::BackProjectContourFrom2DSlice( workingSlice->GetGeometry(), contourInImageIndexCoordinates, true ); // true, correct the result from ipMITKSegmentationGetContour8N
// 3. Show the contour
FeedbackContourTool::SetFeedbackContour( *m_SegmentationContourInWorldCoordinates );
FeedbackContourTool::SetFeedbackContourVisible(true);
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
// always generate a second contour, containing the whole image (used when CTRL is pressed)
{
// copy point from float* to mitk::Contour
ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New();
contourInImageIndexCoordinates->Expand(timeStep + 1);
contourInImageIndexCoordinates->SetIsClosed(true, timeStep);
Point3D newPoint;
newPoint[0] = 0; newPoint[1] = 0; newPoint[2] = 0.0;
contourInImageIndexCoordinates->AddVertex( newPoint, timeStep );
newPoint[0] = originalPicSlice->n[0]; newPoint[1] = 0; newPoint[2] = 0.0;
contourInImageIndexCoordinates->AddVertex( newPoint, timeStep );
newPoint[0] = originalPicSlice->n[0]; newPoint[1] = originalPicSlice->n[1]; newPoint[2] = 0.0;
contourInImageIndexCoordinates->AddVertex( newPoint, timeStep );
newPoint[0] = 0; newPoint[1] = originalPicSlice->n[1]; newPoint[2] = 0.0;
contourInImageIndexCoordinates->AddVertex( newPoint, timeStep );
m_WholeImageContourInWorldCoordinates = FeedbackContourTool::BackProjectContourFrom2DSlice( workingSlice->GetGeometry(), contourInImageIndexCoordinates, true ); // true, correct the result from ipMITKSegmentationGetContour8N
// 3. Show the contour
FeedbackContourTool::SetFeedbackContour( *m_SegmentationContourInWorldCoordinates );
FeedbackContourTool::SetFeedbackContourVisible(true);
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
free(contourPoints);
return true;
}
bool mitk::SetRegionTool::OnMouseReleased(Action* action, const StateEvent* stateEvent)
{
// 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's working image corresponds to that
FeedbackContourTool::SetFeedbackContourVisible(false);
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return false;
assert( positionEvent->GetSender()->GetRenderWindow() );
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
int timeStep = positionEvent->GetSender()->GetTimeStep();
if (!m_FillContour && !m_StatusFillWholeSlice) return true;
if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;
DataNode* workingNode( m_ToolManager->GetWorkingData(0) );
if (!workingNode) return false;
Image* image = dynamic_cast<Image*>(workingNode->GetData());
const PlaneGeometry* planeGeometry( dynamic_cast<const PlaneGeometry*> (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) );
if ( !image || !planeGeometry ) return false;
Image::Pointer slice = FeedbackContourTool::GetAffectedImageSliceAs2DImage( positionEvent, image );
if ( slice.IsNull() )
{
MITK_ERROR << "Unable to extract slice." << std::endl;
return false;
}
ContourModel* feedbackContour( FeedbackContourTool::GetFeedbackContour() );
ContourModel::Pointer projectedContour = FeedbackContourTool::ProjectContourTo2DSlice( slice, feedbackContour, false, false ); // false: don't add 0.5 (done by FillContourInSlice)
// false: don't constrain the contour to the image's inside
if (projectedContour.IsNull()) return false;
FeedbackContourTool::FillContourInSlice( projectedContour, timeStep, slice, m_PaintingPixelValue );
this->WriteBackSegmentationResult(positionEvent, slice);
m_WholeImageContourInWorldCoordinates = NULL;
m_SegmentationContourInWorldCoordinates = NULL;
return true;
}
/**
Called when the CTRL key is pressed. Will change the painting pixel value from 0 to 1 or from 1 to 0.
*/
bool mitk::SetRegionTool::OnInvertLogic(Action* action, const StateEvent* stateEvent)
{
if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return false;
if (m_StatusFillWholeSlice)
{
// use contour extracted from image data
if (m_SegmentationContourInWorldCoordinates.IsNotNull())
FeedbackContourTool::SetFeedbackContour( *m_SegmentationContourInWorldCoordinates );
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
else
{
// use some artificial contour
if (m_WholeImageContourInWorldCoordinates.IsNotNull())
FeedbackContourTool::SetFeedbackContour( *m_WholeImageContourInWorldCoordinates );
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
m_StatusFillWholeSlice = !m_StatusFillWholeSlice;
return true;
}
<|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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
#include <iostream>
#include <iomanip>
#include "otbCommandLineArgumentParser.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbMapProjections.h"
#include "otbOrthoRectificationFilter.h"
#include "otbImage.h"
#include "otbMacro.h"
#include "itkExceptionObject.h"
#include "itkMacro.h"
#include "itkTransform.h"
#include "init/ossimInit.h"
template<typename TMapProjection>
int generic_main_carto_geo(TMapProjection* mapProjection, otb::CommandLineArgumentParseResult* parseResult)
{
try
{
typedef TMapProjection MapProjectionType;
typename MapProjectionType::InputPointType cartoPoint;
typename MapProjectionType::OutputPointType geoPoint;
cartoPoint[0]=parseResult->GetParameterDouble("--XCarto");
cartoPoint[1]=parseResult->GetParameterDouble("--YCarto");
geoPoint = mapProjection->TransformPoint(cartoPoint);
if(!parseResult->IsOptionPresent("--OTBTesting"))
{
std::cout << std::setprecision(10) << "Cartographic Point (x , y) : (" << cartoPoint[0] << "," << cartoPoint[1] << ")" << std::endl;
std::cout << std::setprecision(10) << "Geographic Point (Lat,Lon) : (" << geoPoint[1] << "," << geoPoint[0] << ")" << std::endl;
}
else
{
std::string outputTestFileName = parseResult->GetParameterString("--OTBTesting",0);
ofstream outputTestFile;
outputTestFile.open(outputTestFileName.c_str());
outputTestFile << std::setprecision(10) << "Cartographic Point (x , y) : (" << cartoPoint[0] << "," << cartoPoint[1] << ")" << std::endl;
outputTestFile << std::setprecision(10) << "Geographic Point (Lat,Lon) : (" << geoPoint[1] << "," << geoPoint[0] << ")" << std::endl;
outputTestFile.close();
}
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject raised !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Unknown exception raised !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}//Fin main()
int main(int argc, char* argv[])
{
try
{
ossimInit::instance()->initialize(argc, argv);
// Parse command line parameters
typedef otb::CommandLineArgumentParser ParserType;
ParserType::Pointer parser = ParserType::New();
parser->SetProgramDescription("Cartographic to geographic coordinates conversion");
parser->AddOption("--XCarto","X cartographic value of desired point","-x");
parser->AddOption("--YCarto","Y cartographic value of desired point","-y");
parser->AddOptionNParams("--MapProjectionType","Type (UTM/LAMBERT/LAMBERT2/LAMBERT93/SINUS/ECKERT4/TRANSMERCATOR/MOLLWEID/SVY21) and parameters of map projection used","-mapProj");
typedef otb::CommandLineArgumentParseResult ParserResultType;
ParserResultType::Pointer parseResult = ParserResultType::New();
try
{
parser->ParseCommandLine(argc,argv,parseResult);
}
catch( itk::ExceptionObject & err )
{
std::string descriptionException = err.GetDescription();
if(descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos)
{
std::cout << "WARNING : output file pixels are converted in 'unsigned char'" << std::endl;
return EXIT_SUCCESS;
}
if(descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos)
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
// Code
std::string typeMap = parseResult->GetParameterString("--MapProjectionType",0);
int nbParams = parseResult->GetNumberOfParameters("--MapProjectionType");
nbParams--;
if ((typeMap == "UTM")&&(nbParams==2))
{
int numZone = parseResult->GetParameterUInt("--MapProjectionType",1);
char hemisphere = parseResult->GetParameterChar("--MapProjectionType",2);
typedef otb::UtmInverseProjection UtmProjectionType;
UtmProjectionType::Pointer utmProjection = UtmProjectionType::New();
utmProjection->SetZone(numZone);
utmProjection->SetHemisphere(hemisphere);
return generic_main_carto_geo<UtmProjectionType>(utmProjection, parseResult);
}
else
{
std::vector<double> parameters ;
for (int i=1; i<nbParams+1; i++)
{
parameters.push_back(parseResult->GetParameterDouble("--MapProjectionType",i));
}
if ((typeMap == "LAMBERT")&&(nbParams==4))
{
typedef otb::LambertConformalConicInverseProjection LambertProjectionType;
LambertProjectionType::Pointer lambertProjection = LambertProjectionType::New();
lambertProjection->SetParameters(parameters[0],parameters[1],parameters[2],parameters[3]);
return generic_main_carto_geo<LambertProjectionType>(lambertProjection, parseResult);
}
else if ((typeMap == "LAMBERT2")&&(nbParams==0))
{
typedef otb::Lambert2EtenduInverseProjection Lambert2ProjectionType;
Lambert2ProjectionType::Pointer lambert2Projection = Lambert2ProjectionType::New();
return generic_main_carto_geo<Lambert2ProjectionType>(lambert2Projection, parseResult);
}
else if ((typeMap == "LAMBERT93")&&(nbParams==0))
{
typedef otb::Lambert93InverseProjection Lambert93ProjectionType;
Lambert93ProjectionType::Pointer lambert93Projection = Lambert93ProjectionType::New();
return generic_main_carto_geo<Lambert93ProjectionType>(lambert93Projection, parseResult);
}
else if ((typeMap == "SINUS")&&(nbParams==2))
{
typedef otb::SinusoidalInverseProjection SinusoidalProjectionType;
SinusoidalProjectionType::Pointer sinusoidalProjection = SinusoidalProjectionType::New();
sinusoidalProjection->SetParameters(parameters[0],parameters[1]);
return generic_main_carto_geo<SinusoidalProjectionType>(sinusoidalProjection, parseResult);
}
else if ((typeMap == "ECKERT4")&&(nbParams==2))
{
typedef otb::Eckert4InverseProjection Eckert4ProjectionType;
Eckert4ProjectionType::Pointer eckert4Projection = Eckert4ProjectionType::New();
eckert4Projection->SetParameters(parameters[0],parameters[1]);
return generic_main_carto_geo<Eckert4ProjectionType>(eckert4Projection, parseResult);
}
else if ((typeMap == "TRANSMERCATOR")&&(nbParams==3))
{
typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;
TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();
transMercatorProjection->SetParameters(parameters[0],parameters[1],parameters[2]);
return generic_main_carto_geo<TransMercatorProjectionType>(transMercatorProjection, parseResult);
}
else if ((typeMap == "MOLLWEID")&&(nbParams==2))
{
typedef otb::MollweidInverseProjection MollweidProjectionType;
MollweidProjectionType::Pointer mollweidProjection = MollweidProjectionType::New();
mollweidProjection->SetParameters(parameters[0],parameters[1]);
return generic_main_carto_geo<MollweidProjectionType>(mollweidProjection, parseResult);
}
else if ((typeMap == "SVY21")&&(nbParams==0))
{
typedef otb::SVY21InverseProjection SVY21ProjectionType;
SVY21ProjectionType::Pointer svy21Projection = SVY21ProjectionType::New();
return generic_main_carto_geo<SVY21ProjectionType>(svy21Projection, parseResult);
}
else
{
itkGenericExceptionMacro(<< "TypeMap not recognized, choose one with (parameters) : UTM(2), LAMBERT(4), LAMBERT2(0), LAMBERT2(93), SINUS(2), ECKERT4(2), TRANSMERCATOR(3), MOLLWEID(2), SVY21(0)");
}
}
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject raised !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Unknown exception raised !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>STYLE: tab replaced by 2 spaces<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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
#include <iostream>
#include <iomanip>
#include "otbCommandLineArgumentParser.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbMapProjections.h"
#include "otbOrthoRectificationFilter.h"
#include "otbImage.h"
#include "otbMacro.h"
#include "itkExceptionObject.h"
#include "itkMacro.h"
#include "itkTransform.h"
#include "init/ossimInit.h"
template<typename TMapProjection>
int generic_main_carto_geo(TMapProjection* mapProjection, otb::CommandLineArgumentParseResult* parseResult)
{
try
{
typedef TMapProjection MapProjectionType;
typename MapProjectionType::InputPointType cartoPoint;
typename MapProjectionType::OutputPointType geoPoint;
cartoPoint[0]=parseResult->GetParameterDouble("--XCarto");
cartoPoint[1]=parseResult->GetParameterDouble("--YCarto");
geoPoint = mapProjection->TransformPoint(cartoPoint);
if(!parseResult->IsOptionPresent("--OTBTesting"))
{
std::cout << std::setprecision(10) << "Cartographic Point (x , y) : (" << cartoPoint[0] << "," << cartoPoint[1] << ")" << std::endl;
std::cout << std::setprecision(10) << "Geographic Point (Lat,Lon) : (" << geoPoint[1] << "," << geoPoint[0] << ")" << std::endl;
}
else
{
std::string outputTestFileName = parseResult->GetParameterString("--OTBTesting",0);
ofstream outputTestFile;
outputTestFile.open(outputTestFileName.c_str());
outputTestFile << std::setprecision(10) << "Cartographic Point (x , y) : (" << cartoPoint[0] << "," << cartoPoint[1] << ")" << std::endl;
outputTestFile << std::setprecision(10) << "Geographic Point (Lat,Lon) : (" << geoPoint[1] << "," << geoPoint[0] << ")" << std::endl;
outputTestFile.close();
}
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject raised !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Unknown exception raised !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}//Fin main()
int main(int argc, char* argv[])
{
try
{
ossimInit::instance()->initialize(argc, argv);
// Parse command line parameters
typedef otb::CommandLineArgumentParser ParserType;
ParserType::Pointer parser = ParserType::New();
parser->SetProgramDescription("Cartographic to geographic coordinates conversion");
parser->AddOption("--XCarto","X cartographic value of desired point","-x");
parser->AddOption("--YCarto","Y cartographic value of desired point","-y");
parser->AddOptionNParams("--MapProjectionType","Type (UTM/LAMBERT/LAMBERT2/LAMBERT93/SINUS/ECKERT4/TRANSMERCATOR/MOLLWEID/SVY21) and parameters of map projection used","-mapProj");
typedef otb::CommandLineArgumentParseResult ParserResultType;
ParserResultType::Pointer parseResult = ParserResultType::New();
try
{
parser->ParseCommandLine(argc,argv,parseResult);
}
catch( itk::ExceptionObject & err )
{
std::string descriptionException = err.GetDescription();
if(descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos)
{
std::cout << "WARNING : output file pixels are converted in 'unsigned char'" << std::endl;
return EXIT_SUCCESS;
}
if(descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos)
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
// Code
std::string typeMap = parseResult->GetParameterString("--MapProjectionType",0);
int nbParams = parseResult->GetNumberOfParameters("--MapProjectionType");
nbParams--;
if ((typeMap == "UTM")&&(nbParams==2))
{
int numZone = parseResult->GetParameterUInt("--MapProjectionType",1);
char hemisphere = parseResult->GetParameterChar("--MapProjectionType",2);
typedef otb::UtmInverseProjection UtmProjectionType;
UtmProjectionType::Pointer utmProjection = UtmProjectionType::New();
utmProjection->SetZone(numZone);
utmProjection->SetHemisphere(hemisphere);
return generic_main_carto_geo<UtmProjectionType>(utmProjection, parseResult);
}
else
{
std::vector<double> parameters ;
for (int i=1; i<nbParams+1; i++)
{
parameters.push_back(parseResult->GetParameterDouble("--MapProjectionType",i));
}
if ((typeMap == "LAMBERT")&&(nbParams==4))
{
typedef otb::LambertConformalConicInverseProjection LambertProjectionType;
LambertProjectionType::Pointer lambertProjection = LambertProjectionType::New();
lambertProjection->SetParameters(parameters[0],parameters[1],parameters[2],parameters[3]);
return generic_main_carto_geo<LambertProjectionType>(lambertProjection, parseResult);
}
else if ((typeMap == "LAMBERT2")&&(nbParams==0))
{
typedef otb::Lambert2EtenduInverseProjection Lambert2ProjectionType;
Lambert2ProjectionType::Pointer lambert2Projection = Lambert2ProjectionType::New();
return generic_main_carto_geo<Lambert2ProjectionType>(lambert2Projection, parseResult);
}
else if ((typeMap == "LAMBERT93")&&(nbParams==0))
{
typedef otb::Lambert93InverseProjection Lambert93ProjectionType;
Lambert93ProjectionType::Pointer lambert93Projection = Lambert93ProjectionType::New();
return generic_main_carto_geo<Lambert93ProjectionType>(lambert93Projection, parseResult);
}
else if ((typeMap == "SINUS")&&(nbParams==2))
{
typedef otb::SinusoidalInverseProjection SinusoidalProjectionType;
SinusoidalProjectionType::Pointer sinusoidalProjection = SinusoidalProjectionType::New();
sinusoidalProjection->SetParameters(parameters[0],parameters[1]);
return generic_main_carto_geo<SinusoidalProjectionType>(sinusoidalProjection, parseResult);
}
else if ((typeMap == "ECKERT4")&&(nbParams==2))
{
typedef otb::Eckert4InverseProjection Eckert4ProjectionType;
Eckert4ProjectionType::Pointer eckert4Projection = Eckert4ProjectionType::New();
eckert4Projection->SetParameters(parameters[0],parameters[1]);
return generic_main_carto_geo<Eckert4ProjectionType>(eckert4Projection, parseResult);
}
else if ((typeMap == "TRANSMERCATOR")&&(nbParams==3))
{
typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;
TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();
transMercatorProjection->SetParameters(parameters[0],parameters[1],parameters[2]);
return generic_main_carto_geo<TransMercatorProjectionType>(transMercatorProjection, parseResult);
}
else if ((typeMap == "MOLLWEID")&&(nbParams==2))
{
typedef otb::MollweidInverseProjection MollweidProjectionType;
MollweidProjectionType::Pointer mollweidProjection = MollweidProjectionType::New();
mollweidProjection->SetParameters(parameters[0],parameters[1]);
return generic_main_carto_geo<MollweidProjectionType>(mollweidProjection, parseResult);
}
else if ((typeMap == "SVY21")&&(nbParams==0))
{
typedef otb::SVY21InverseProjection SVY21ProjectionType;
SVY21ProjectionType::Pointer svy21Projection = SVY21ProjectionType::New();
return generic_main_carto_geo<SVY21ProjectionType>(svy21Projection, parseResult);
}
else
{
itkGenericExceptionMacro(<< "TypeMap not recognized, choose one with (parameters) : UTM(2), LAMBERT(4), LAMBERT2(0), LAMBERT2(93), SINUS(2), ECKERT4(2), TRANSMERCATOR(3), MOLLWEID(2), SVY21(0)");
}
}
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject raised !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Unknown exception raised !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "time.h"
#include <strstream>
#include <RegisterWindow.h>
#include <FL/fl_file_chooser.H>
RegisterWindow::RegisterWindow()
{
m_FixedImageViewer = ImageViewerType::New() ;
m_MovingImageViewer = ImageViewerType::New() ;
m_RegisteredImageViewer = ImageViewerType::New() ;
m_MixedChannelViewer = MixedChannelViewerType::New() ;
m_FixedImageViewer->SetLabel( "Fixed Image" ) ;
m_MovingImageViewer->SetLabel( "Moving Image" ) ;
m_RegisteredImageViewer->SetLabel( "Registered Image" ) ;
m_MixedChannelViewer->SetLabel( "Mixed Channel View" ) ;
m_DebugViewer = ImageViewerType::New() ;
m_DebugViewer->SetLabel( "Debug" ) ;
m_ChannelSources[0] = fixed ;
m_ChannelSources[1] = registered ;
m_ChannelSources[2] = none ;
m_FixedImageViewer->imageViewer->
SetSelectionCallBack((void*) this,
RegisterWindow::SelectionCallBackWrapper) ;
buStartRegistration->deactivate() ;
buSaveRegisteredImage->deactivate() ;
buShowDisplay->deactivate() ;
lsDisplay->deactivate() ;
menuFixedImageDisplay->deactivate() ;
menuMovingImageDisplay->deactivate() ;
menuRegisteredImageDisplay->deactivate() ;
menuMixedChannel->deactivate() ;
m_IterationObserver = IterationObserverType::New();
m_IterationObserver->SetOptimizer( m_Registrator->GetOptimizer() );
m_IterationObserver->SetBrowser( iterationsBrowser );
this->ShowStatus("Let's start by loading an image...");
}
RegisterWindow::~RegisterWindow()
{
}
void RegisterWindow::LoadMovingImage(void)
{
const char * filename =
fl_file_chooser("Moving Image filename","*.*","");
if( !filename )
{
return;
}
m_MovingImageFileName = filename ;
this->ShowStatus("Loading moving image file...");
try
{
RegisterApplication::LoadMovingImage();
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
return;
}
if (m_FixedImage != 0 && m_MovingImage != 0)
{
buStartRegistration->activate() ;
}
lsDisplay->activate() ;
buShowDisplay->activate() ;
menuMovingImageDisplay->activate() ;
this->ShowStatus("Moving Image Loaded");
}
void RegisterWindow::LoadFixedImage(void)
{
const char * filename =
fl_file_chooser("Fixed Image filename","*.*","");
if( !filename )
{
return;
}
m_FixedImageFileName = filename ;
this->ShowStatus("Loading fixed image file...");
try
{
RegisterApplication::LoadFixedImage();
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
return;
}
m_TempBox.X1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[0] ;
m_TempBox.Y1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[1] ;
m_TempBox.X2 = m_TempBox.X1 +
m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
m_TempBox.Y2 = m_TempBox.Y1 +
m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;
outSelectedRegionBeginX->value(m_TempBox.X1) ;
outSelectedRegionBeginY->value(m_TempBox.Y1) ;
outSelectedRegionEndX->value(m_TempBox.X2) ;
outSelectedRegionEndY->value(m_TempBox.Y2) ;
m_FixedImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;
lsDisplay->activate() ;
buShowDisplay->activate() ;
menuFixedImageDisplay->activate() ;
if (m_FixedImage != 0 && m_MovingImage != 0)
{
buStartRegistration->activate() ;
}
this->ShowStatus("Fixed Image Loaded");
}
void RegisterWindow::Show()
{
winMain->show() ;
}
void RegisterWindow::Hide()
{
winMain->hide();
m_FixedImageViewer->Hide();
m_MovingImageViewer->Hide();
m_RegisteredImageViewer->Hide();
m_MixedChannelViewer->Hide() ;
}
void RegisterWindow::Quit(void)
{
this->Hide() ;
}
void RegisterWindow::ShowStatus(const char * text)
{
outStatus->value( text );
Fl::check();
}
void RegisterWindow::ShowFixedImage(void)
{
if( !m_FixedImageLoaded )
{
return;
}
m_FixedImageViewer->SetImage( m_FixedImage );
m_FixedImageViewer->Show();
}
void RegisterWindow::ShowMovingImage(void)
{
if( !m_MovingImageLoaded )
{
return;
}
m_MovingImageViewer->SetImage( m_MovingImage );
m_MovingImageViewer->Show();
if (m_FixedImage != 0)
{
m_TempBox.X1 = (int) outSelectedRegionBeginX->value() ;
m_TempBox.Y1 = (int) outSelectedRegionBeginY->value() ;
m_TempBox.X2 = (int) outSelectedRegionEndX->value() ;
m_TempBox.Y2 = (int) outSelectedRegionEndY->value() ;
m_MovingImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;
}
}
void RegisterWindow::ShowRegisteredImage(void)
{
if( !m_RegisteredImageAvailable )
{
return;
}
m_RegisteredImageViewer->SetImage( m_RegisteredImage );
m_RegisteredImageViewer->Show();
}
void RegisterWindow::ShowMixedChannel(void)
{
if( !m_RegisteredImageAvailable )
{
return;
}
int sizeX = m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
int sizeY = m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;
if (m_ChannelSources[0] == fixed)
{
m_MixedChannelViewer->SetRedChannel( m_FixedImage) ;
}
else if (m_ChannelSources[0] == registered)
{
m_MixedChannelViewer->SetRedChannel( m_RegisteredImage ) ;
}
else
{
m_MixedChannelViewer->FillChannel(0, 0, sizeX, sizeY) ;
}
if (m_ChannelSources[1] == fixed)
{
m_MixedChannelViewer->SetGreenChannel( m_FixedImage) ;
}
else if (m_ChannelSources[1] == registered)
{
m_MixedChannelViewer->SetGreenChannel( m_RegisteredImage ) ;
}
else
{
m_MixedChannelViewer->FillChannel(1, 0, sizeX, sizeY) ;
}
if (m_ChannelSources[2] == fixed)
{
m_MixedChannelViewer->SetBlueChannel( m_FixedImage) ;
}
else if (m_ChannelSources[2] == registered)
{
m_MixedChannelViewer->SetBlueChannel( m_RegisteredImage ) ;
}
else
{
m_MixedChannelViewer->FillChannel(2, 0, sizeX, sizeY) ;
}
m_MixedChannelViewer->Show();
}
void RegisterWindow::Execute(void)
{
iterationsWindow->show();
Fl::check();
clock_t time_begin ;
clock_t time_end ;
this->ShowStatus("Registering Moving Image against Fixed Image ...");
grpControls->deactivate() ;
this->UpdateParameters() ;
time_begin = clock() ;
RegisterApplication::Execute();
time_end = clock() ;
menuRegisteredImageDisplay->activate() ;
menuMixedChannel->activate() ;
buSaveRegisteredImage->activate() ;
grpControls->activate() ;
std::ostrstream message ;
message
<< "Registration done in " <<
double(time_end - time_begin) / CLOCKS_PER_SEC << "seconds."
<< std::endl ;
message << "angle = "
<< m_Registrator->GetTransformParameters()[0] << ", x offset = "
<< m_Registrator->GetTransformParameters()[1] << ", y offset = "
<< m_Registrator->GetTransformParameters()[2] << std::ends;
this->ShowStatus(message.str());
// m_MovingImage->SetRequestedRegion(m_SelectedRegion) ;
// m_DebugViewer->SetImage(m_MovingImage) ;
// m_DebugViewer->Show() ;
// m_MovingImage->SetRequestedRegionToLargestPossibleRegion() ;
}
void RegisterWindow::UpdateParameters(void)
{
m_RegionBegin.resize(ImageDimension) ;
m_RegionEnd.resize(ImageDimension) ;
m_RegionBegin[0] = (int) outSelectedRegionBeginX->value() ;
m_RegionBegin[1] = (int) outSelectedRegionBeginY->value() ;
m_RegionEnd[0] = (int) outSelectedRegionEndX->value() ;
m_RegionEnd[1] = (int) outSelectedRegionEndY->value() ;
int i ;
// crop images from original image using selected region
for (i = 0 ; i < ImageDimension ; i++)
{
if (m_RegionEnd[i] > m_RegionBegin[i])
{
m_SelectedSize[i] = m_RegionEnd[i] - m_RegionBegin[i] ;
m_SelectedIndex[i] = m_RegionBegin[i] ;
}
else
{
m_SelectedSize[i] = m_RegionBegin[i] - m_RegionEnd[i] ;
m_SelectedIndex[i] = m_RegionEnd[i] ;
}
}
m_SelectedRegion.SetIndex(m_SelectedIndex) ;
m_SelectedRegion.SetSize(m_SelectedSize) ;
}
void RegisterWindow::ShowAdvancedOptionsWindow()
{
winAdvancedOptions->show() ;
inTranslationScale->value(m_TranslationScale) ;
inRotationScale->value(m_RotationScale) ;
inLearningRate->value(m_LearningRate) ;
inNumberOfIterations->value(m_NumberOfIterations) ;
if (m_ChannelSources[0] == fixed)
{
buRedFixedImage->setonly() ;
}
else if (m_ChannelSources[0] == registered)
{
buRedRegisteredImage->setonly() ;
}
else
{
buRedNone->setonly() ;
}
if (m_ChannelSources[1] == fixed)
{
buGreenFixedImage->setonly() ;
}
else if (m_ChannelSources[1] == registered)
{
buGreenRegisteredImage->setonly() ;
}
else
{
buGreenNone->setonly() ;
}
if (m_ChannelSources[2] == fixed)
{
buBlueFixedImage->setonly() ;
}
else if (m_ChannelSources[2] == registered)
{
buBlueRegisteredImage->setonly() ;
}
else
{
buBlueNone->setonly() ;
}
}
void RegisterWindow::UpdateAdvancedOptions(void)
{
m_TranslationScale = inTranslationScale->value() ;
m_RotationScale = inRotationScale->value() ;
m_LearningRate = inLearningRate->value() ;
m_NumberOfIterations = (int) inNumberOfIterations->value() ;
if (buRedFixedImage->value() == 1)
{
m_ChannelSources[0] = fixed ;
}
else if (buRedRegisteredImage->value() == 1)
{
m_ChannelSources[0] = registered ;
}
else
{
m_ChannelSources[0] = none ;
}
if (buGreenFixedImage->value() == 1)
{
m_ChannelSources[1] = fixed ;
}
else if (buGreenRegisteredImage->value() == 1)
{
m_ChannelSources[1] = registered ;
}
else
{
m_ChannelSources[1] = none ;
}
if (buBlueFixedImage->value() == 1)
{
m_ChannelSources[2] = fixed ;
}
else if (buBlueRegisteredImage->value() == 1)
{
m_ChannelSources[2] = registered ;
}
else
{
m_ChannelSources[2] = none ;
}
winAdvancedOptions->hide() ;
}
void RegisterWindow::CloseAdvancedOptionsWindow(void)
{
winAdvancedOptions->hide() ;
}
void RegisterWindow::SaveRegisteredImage( void )
{
const char * filename =
fl_file_chooser("Registered Image filename","*.*","");
if( !filename )
{
return;
}
this->ShowStatus("Saving registered image file...");
try
{
RegisterApplication::SaveRegisteredImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems saving file format");
return;
}
this->ShowStatus("Registered Image Saved");
}
void RegisterWindow
::SelectionCallBackWrapper(void* ptrSelf,
fltk::Image2DViewerWindow::SelectionBoxType* box)
{
RegisterWindow* self = (RegisterWindow*) ptrSelf ;
self->UpdateSelectedRegion(box) ;
}
void RegisterWindow
::UpdateSelectedRegion(fltk::Image2DViewerWindow::SelectionBoxType* box)
{
outSelectedRegionBeginX->value(box->X1) ;
outSelectedRegionBeginY->value(box->Y1) ;
outSelectedRegionEndX->value(box->X2) ;
outSelectedRegionEndY->value(box->Y2) ;
m_MovingImageViewer->imageViewer->SetSelectionBox(box) ;
}
<commit_msg>BUG: old library strstream is replaced by sstream<commit_after>#include "time.h"
#include <sstream>
#include <RegisterWindow.h>
#include <FL/fl_file_chooser.H>
RegisterWindow::RegisterWindow()
{
m_FixedImageViewer = ImageViewerType::New() ;
m_MovingImageViewer = ImageViewerType::New() ;
m_RegisteredImageViewer = ImageViewerType::New() ;
m_MixedChannelViewer = MixedChannelViewerType::New() ;
m_FixedImageViewer->SetLabel( "Fixed Image" ) ;
m_MovingImageViewer->SetLabel( "Moving Image" ) ;
m_RegisteredImageViewer->SetLabel( "Registered Image" ) ;
m_MixedChannelViewer->SetLabel( "Mixed Channel View" ) ;
m_DebugViewer = ImageViewerType::New() ;
m_DebugViewer->SetLabel( "Debug" ) ;
m_ChannelSources[0] = fixed ;
m_ChannelSources[1] = registered ;
m_ChannelSources[2] = none ;
m_FixedImageViewer->imageViewer->
SetSelectionCallBack((void*) this,
RegisterWindow::SelectionCallBackWrapper) ;
buStartRegistration->deactivate() ;
buSaveRegisteredImage->deactivate() ;
buShowDisplay->deactivate() ;
lsDisplay->deactivate() ;
menuFixedImageDisplay->deactivate() ;
menuMovingImageDisplay->deactivate() ;
menuRegisteredImageDisplay->deactivate() ;
menuMixedChannel->deactivate() ;
m_IterationObserver = IterationObserverType::New();
m_IterationObserver->SetOptimizer( m_Registrator->GetOptimizer() );
m_IterationObserver->SetBrowser( iterationsBrowser );
this->ShowStatus("Let's start by loading an image...");
}
RegisterWindow::~RegisterWindow()
{
}
void RegisterWindow::LoadMovingImage(void)
{
const char * filename =
fl_file_chooser("Moving Image filename","*.*","");
if( !filename )
{
return;
}
m_MovingImageFileName = filename ;
this->ShowStatus("Loading moving image file...");
try
{
RegisterApplication::LoadMovingImage();
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
return;
}
if (m_FixedImage != 0 && m_MovingImage != 0)
{
buStartRegistration->activate() ;
}
lsDisplay->activate() ;
buShowDisplay->activate() ;
menuMovingImageDisplay->activate() ;
this->ShowStatus("Moving Image Loaded");
}
void RegisterWindow::LoadFixedImage(void)
{
const char * filename =
fl_file_chooser("Fixed Image filename","*.*","");
if( !filename )
{
return;
}
m_FixedImageFileName = filename ;
this->ShowStatus("Loading fixed image file...");
try
{
RegisterApplication::LoadFixedImage();
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
return;
}
m_TempBox.X1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[0] ;
m_TempBox.Y1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[1] ;
m_TempBox.X2 = m_TempBox.X1 +
m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
m_TempBox.Y2 = m_TempBox.Y1 +
m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;
outSelectedRegionBeginX->value(m_TempBox.X1) ;
outSelectedRegionBeginY->value(m_TempBox.Y1) ;
outSelectedRegionEndX->value(m_TempBox.X2) ;
outSelectedRegionEndY->value(m_TempBox.Y2) ;
m_FixedImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;
lsDisplay->activate() ;
buShowDisplay->activate() ;
menuFixedImageDisplay->activate() ;
if (m_FixedImage != 0 && m_MovingImage != 0)
{
buStartRegistration->activate() ;
}
this->ShowStatus("Fixed Image Loaded");
}
void RegisterWindow::Show()
{
winMain->show() ;
}
void RegisterWindow::Hide()
{
winMain->hide();
m_FixedImageViewer->Hide();
m_MovingImageViewer->Hide();
m_RegisteredImageViewer->Hide();
m_MixedChannelViewer->Hide() ;
}
void RegisterWindow::Quit(void)
{
this->Hide() ;
}
void RegisterWindow::ShowStatus(const char * text)
{
outStatus->value( text );
Fl::check();
}
void RegisterWindow::ShowFixedImage(void)
{
if( !m_FixedImageLoaded )
{
return;
}
m_FixedImageViewer->SetImage( m_FixedImage );
m_FixedImageViewer->Show();
}
void RegisterWindow::ShowMovingImage(void)
{
if( !m_MovingImageLoaded )
{
return;
}
m_MovingImageViewer->SetImage( m_MovingImage );
m_MovingImageViewer->Show();
if (m_FixedImage != 0)
{
m_TempBox.X1 = (int) outSelectedRegionBeginX->value() ;
m_TempBox.Y1 = (int) outSelectedRegionBeginY->value() ;
m_TempBox.X2 = (int) outSelectedRegionEndX->value() ;
m_TempBox.Y2 = (int) outSelectedRegionEndY->value() ;
m_MovingImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;
}
}
void RegisterWindow::ShowRegisteredImage(void)
{
if( !m_RegisteredImageAvailable )
{
return;
}
m_RegisteredImageViewer->SetImage( m_RegisteredImage );
m_RegisteredImageViewer->Show();
}
void RegisterWindow::ShowMixedChannel(void)
{
if( !m_RegisteredImageAvailable )
{
return;
}
int sizeX = m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
int sizeY = m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;
if (m_ChannelSources[0] == fixed)
{
m_MixedChannelViewer->SetRedChannel( m_FixedImage) ;
}
else if (m_ChannelSources[0] == registered)
{
m_MixedChannelViewer->SetRedChannel( m_RegisteredImage ) ;
}
else
{
m_MixedChannelViewer->FillChannel(0, 0, sizeX, sizeY) ;
}
if (m_ChannelSources[1] == fixed)
{
m_MixedChannelViewer->SetGreenChannel( m_FixedImage) ;
}
else if (m_ChannelSources[1] == registered)
{
m_MixedChannelViewer->SetGreenChannel( m_RegisteredImage ) ;
}
else
{
m_MixedChannelViewer->FillChannel(1, 0, sizeX, sizeY) ;
}
if (m_ChannelSources[2] == fixed)
{
m_MixedChannelViewer->SetBlueChannel( m_FixedImage) ;
}
else if (m_ChannelSources[2] == registered)
{
m_MixedChannelViewer->SetBlueChannel( m_RegisteredImage ) ;
}
else
{
m_MixedChannelViewer->FillChannel(2, 0, sizeX, sizeY) ;
}
m_MixedChannelViewer->Show();
}
void RegisterWindow::Execute(void)
{
iterationsWindow->show();
Fl::check();
clock_t time_begin ;
clock_t time_end ;
this->ShowStatus("Registering Moving Image against Fixed Image ...");
grpControls->deactivate() ;
this->UpdateParameters() ;
time_begin = clock() ;
RegisterApplication::Execute();
time_end = clock() ;
menuRegisteredImageDisplay->activate() ;
menuMixedChannel->activate() ;
buSaveRegisteredImage->activate() ;
grpControls->activate() ;
std::ostrstream message ;
message
<< "Registration done in " <<
double(time_end - time_begin) / CLOCKS_PER_SEC << "seconds."
<< std::endl ;
message << "angle = "
<< m_Registrator->GetTransformParameters()[0] << ", x offset = "
<< m_Registrator->GetTransformParameters()[1] << ", y offset = "
<< m_Registrator->GetTransformParameters()[2] << std::ends;
this->ShowStatus(message.str());
// m_MovingImage->SetRequestedRegion(m_SelectedRegion) ;
// m_DebugViewer->SetImage(m_MovingImage) ;
// m_DebugViewer->Show() ;
// m_MovingImage->SetRequestedRegionToLargestPossibleRegion() ;
}
void RegisterWindow::UpdateParameters(void)
{
m_RegionBegin.resize(ImageDimension) ;
m_RegionEnd.resize(ImageDimension) ;
m_RegionBegin[0] = (int) outSelectedRegionBeginX->value() ;
m_RegionBegin[1] = (int) outSelectedRegionBeginY->value() ;
m_RegionEnd[0] = (int) outSelectedRegionEndX->value() ;
m_RegionEnd[1] = (int) outSelectedRegionEndY->value() ;
int i ;
// crop images from original image using selected region
for (i = 0 ; i < ImageDimension ; i++)
{
if (m_RegionEnd[i] > m_RegionBegin[i])
{
m_SelectedSize[i] = m_RegionEnd[i] - m_RegionBegin[i] ;
m_SelectedIndex[i] = m_RegionBegin[i] ;
}
else
{
m_SelectedSize[i] = m_RegionBegin[i] - m_RegionEnd[i] ;
m_SelectedIndex[i] = m_RegionEnd[i] ;
}
}
m_SelectedRegion.SetIndex(m_SelectedIndex) ;
m_SelectedRegion.SetSize(m_SelectedSize) ;
}
void RegisterWindow::ShowAdvancedOptionsWindow()
{
winAdvancedOptions->show() ;
inTranslationScale->value(m_TranslationScale) ;
inRotationScale->value(m_RotationScale) ;
inLearningRate->value(m_LearningRate) ;
inNumberOfIterations->value(m_NumberOfIterations) ;
if (m_ChannelSources[0] == fixed)
{
buRedFixedImage->setonly() ;
}
else if (m_ChannelSources[0] == registered)
{
buRedRegisteredImage->setonly() ;
}
else
{
buRedNone->setonly() ;
}
if (m_ChannelSources[1] == fixed)
{
buGreenFixedImage->setonly() ;
}
else if (m_ChannelSources[1] == registered)
{
buGreenRegisteredImage->setonly() ;
}
else
{
buGreenNone->setonly() ;
}
if (m_ChannelSources[2] == fixed)
{
buBlueFixedImage->setonly() ;
}
else if (m_ChannelSources[2] == registered)
{
buBlueRegisteredImage->setonly() ;
}
else
{
buBlueNone->setonly() ;
}
}
void RegisterWindow::UpdateAdvancedOptions(void)
{
m_TranslationScale = inTranslationScale->value() ;
m_RotationScale = inRotationScale->value() ;
m_LearningRate = inLearningRate->value() ;
m_NumberOfIterations = (int) inNumberOfIterations->value() ;
if (buRedFixedImage->value() == 1)
{
m_ChannelSources[0] = fixed ;
}
else if (buRedRegisteredImage->value() == 1)
{
m_ChannelSources[0] = registered ;
}
else
{
m_ChannelSources[0] = none ;
}
if (buGreenFixedImage->value() == 1)
{
m_ChannelSources[1] = fixed ;
}
else if (buGreenRegisteredImage->value() == 1)
{
m_ChannelSources[1] = registered ;
}
else
{
m_ChannelSources[1] = none ;
}
if (buBlueFixedImage->value() == 1)
{
m_ChannelSources[2] = fixed ;
}
else if (buBlueRegisteredImage->value() == 1)
{
m_ChannelSources[2] = registered ;
}
else
{
m_ChannelSources[2] = none ;
}
winAdvancedOptions->hide() ;
}
void RegisterWindow::CloseAdvancedOptionsWindow(void)
{
winAdvancedOptions->hide() ;
}
void RegisterWindow::SaveRegisteredImage( void )
{
const char * filename =
fl_file_chooser("Registered Image filename","*.*","");
if( !filename )
{
return;
}
this->ShowStatus("Saving registered image file...");
try
{
RegisterApplication::SaveRegisteredImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems saving file format");
return;
}
this->ShowStatus("Registered Image Saved");
}
void RegisterWindow
::SelectionCallBackWrapper(void* ptrSelf,
fltk::Image2DViewerWindow::SelectionBoxType* box)
{
RegisterWindow* self = (RegisterWindow*) ptrSelf ;
self->UpdateSelectedRegion(box) ;
}
void RegisterWindow
::UpdateSelectedRegion(fltk::Image2DViewerWindow::SelectionBoxType* box)
{
outSelectedRegionBeginX->value(box->X1) ;
outSelectedRegionBeginY->value(box->Y1) ;
outSelectedRegionEndX->value(box->X2) ;
outSelectedRegionEndY->value(box->Y2) ;
m_MovingImageViewer->imageViewer->SetSelectionBox(box) ;
}
<|endoftext|> |
<commit_before>/******************************************************************************
font.cpp
SDL-based Font Rendering API
Copyright (c) 2013 Jeffrey Carpenter
******************************************************************************/
#include "font.h"
Font::Font ( void )
{
#ifdef DEBUG_FONT_OBJ
std::cout << "Font::Font (): " << "Hello, world!" << "\n" << std::endl;
#endif
this->font = NULL;
if ( TTF_Init () == -1 )
{
#ifdef DEBUG_FONT
std::cout << "ERR in Font::Font (): " << TTF_GetError() << std::endl;
#endif
exit ( EXIT_FAILURE ); // TODO: Reconsider
}
this->text_color = { 0, 0, 0 };
this->coords = { 0, 0, 0, 0 };
}
Font::~Font ( void )
{
#ifdef DEBUG_FONT_OBJ
std::cout << "Font::~Font (): " << "Goodbye cruel world!" << "\n" << std::endl;
#endif
if ( this->font != NULL )
{
TTF_CloseFont ( this->font );
this->font = NULL;
}
TTF_Quit ();
}
unsigned int Font::GetTextWidth ( void )
{
return this->coords.w;
}
unsigned int Font::GetTextHeight ( void )
{
return this->coords.h;
}
std::string Font::GetTextBuffer ( void )
{
return this->text_buffer;
}
void Font::SetTextBuffer ( std::string text )
{
signed int width, height = 0;
/*
TODO: Finish ERR checks:
if ( text.length() > 0 )
*/
if ( TTF_SizeText ( this->font, text.c_str(), &width, &height ) != -1 )
{
this->coords.w = width;
this->coords.h = height;
this->text_buffer = text;
}
}
SDL_Color Font::GetTextColor ( void )
{
return this->text_color;
}
void Font::SetTextColor ( unsigned r, unsigned g, unsigned b )
{
this->text_color.r = r;
this->text_color.g = g;
this->text_color.b = b;
}
bool Font::LoadTTF ( std::string filename, unsigned int font_size )
{
this->font = TTF_OpenFont ( filename.c_str(), font_size );
if ( this->font == NULL )
{
#ifdef DEBUG_FONT
std::cout << "ERR: " << TTF_GetError() << std::endl;
#endif
return false;
}
return true;
}
bool Font::DrawText ( Gfx *engine, unsigned int x, unsigned int y )
{
SDL_Surface *video_buffer = NULL;
this->coords.x = x;
this->coords.y = y;
if ( this->GetTextBuffer().c_str() != NULL )
{
video_buffer = TTF_RenderText_Solid ( this->font, this->GetTextBuffer().c_str(), this->text_color );
}
else
{
std::cout << "ERR in Font::DrawText(): " << SDL_GetError() << std::endl;
SDL_FreeSurface ( video_buffer );
video_buffer = NULL;
return false;
}
if ( video_buffer != NULL )
{
if ( engine->DrawSurface ( video_buffer, x, y ) == false )
{
std::cout << "ERR in Font::DrawText(): " << SDL_GetError() << std::endl;
}
SDL_FreeSurface ( video_buffer );
video_buffer = NULL;
return false;
}
SDL_FreeSurface ( video_buffer );
video_buffer = NULL;
return true;
}
<commit_msg>Compile Time ERR Fix<commit_after>/******************************************************************************
font.cpp
SDL-based Font Rendering API
Copyright (c) 2013 Jeffrey Carpenter
******************************************************************************/
#include "font.h"
Font::Font ( void )
{
#ifdef DEBUG_FONT_OBJ
std::cout << "Font::Font (): " << "Hello, world!" << "\n" << std::endl;
#endif
this->font = NULL;
if ( TTF_Init () == -1 )
{
#ifdef DEBUG_FONT
std::cout << "ERR in Font::Font (): " << TTF_GetError() << std::endl;
#endif
exit ( EXIT_FAILURE ); // TODO: Reconsider
}
}
Font::~Font ( void )
{
#ifdef DEBUG_FONT_OBJ
std::cout << "Font::~Font (): " << "Goodbye cruel world!" << "\n" << std::endl;
#endif
if ( this->font != NULL )
{
TTF_CloseFont ( this->font );
this->font = NULL;
}
TTF_Quit ();
}
unsigned int Font::GetTextWidth ( void )
{
return this->coords.w;
}
unsigned int Font::GetTextHeight ( void )
{
return this->coords.h;
}
std::string Font::GetTextBuffer ( void )
{
return this->text_buffer;
}
void Font::SetTextBuffer ( std::string text )
{
signed int width, height = 0;
/*
TODO: Finish ERR checks:
if ( text.length() > 0 )
*/
if ( TTF_SizeText ( this->font, text.c_str(), &width, &height ) != -1 )
{
this->coords.w = width;
this->coords.h = height;
this->text_buffer = text;
}
}
SDL_Color Font::GetTextColor ( void )
{
return this->text_color;
}
void Font::SetTextColor ( unsigned r, unsigned g, unsigned b )
{
this->text_color.r = r;
this->text_color.g = g;
this->text_color.b = b;
}
bool Font::LoadTTF ( std::string filename, unsigned int font_size )
{
this->font = TTF_OpenFont ( filename.c_str(), font_size );
if ( this->font == NULL )
{
#ifdef DEBUG_FONT
std::cout << "ERR: " << TTF_GetError() << std::endl;
#endif
return false;
}
return true;
}
bool Font::DrawText ( Gfx *engine, unsigned int x, unsigned int y )
{
SDL_Surface *video_buffer = NULL;
this->coords.x = x;
this->coords.y = y;
if ( this->GetTextBuffer().c_str() != NULL )
{
video_buffer = TTF_RenderText_Solid ( this->font, this->GetTextBuffer().c_str(), this->text_color );
}
else
{
std::cout << "ERR in Font::DrawText(): " << SDL_GetError() << std::endl;
SDL_FreeSurface ( video_buffer );
video_buffer = NULL;
return false;
}
if ( video_buffer != NULL )
{
if ( engine->DrawSurface ( video_buffer, x, y ) == false )
{
std::cout << "ERR in Font::DrawText(): " << SDL_GetError() << std::endl;
}
SDL_FreeSurface ( video_buffer );
video_buffer = NULL;
return false;
}
SDL_FreeSurface ( video_buffer );
video_buffer = NULL;
return true;
}
<|endoftext|> |
<commit_before>/*
* GPIO handler for Dragonboard
* Author: Kenny Yokoyama & Mike Lara
*/
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "ros/ros.h"
#include "std_msgs/Int32.h"
#define GPIO_EXPORT_PATH "/sys/class/gpio/export"
#define GPIO_UNEXPORT_PATH "/sys/class/gpio/unexport"
#define GPIO_DIR_PATH "/sys/class/gpio/gpio%d/direction"
#define GPIO_VALUE_PATH "/sys/class/gpio/gpio%d/value"
#define GPIO_HIGH 1
#define GPIO_LOW 0
#define GPIO_IN "in"
#define GPIO_OUT "out"
enum GPIO_PINS { GPIO_1=6, GPIO_2=7, GPIO_3=206, GPIO_4=207,
GPIO_5=186, GPIO_6=189, GPIO_7=22, GPIO_8=23};
int PIN_VALUES[5];
class GPIOPin
{
private:
// Mike:
int hwPinId;
int fileDesc;
public:
GPIOPin(GPIO_PINS pin, const char* pinIO);
~GPIOPin();
// Kenny:
void setPin(int state);
// Mike:
void writeFile(int value);
};
GPIOPin::GPIOPin(GPIO_PINS pin, const char* pinIO)
{
char path[256];
hwPinId = pin;
// setup export
fileDesc = open(GPIO_EXPORT_PATH, O_WRONLY);
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), "%d", hwPinId);
write(fileDesc, path, strlen(path));
close(fileDesc);
// setup signal direction
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), GPIO_DIR_PATH, hwPinId);
fileDesc = open(path, O_WRONLY);
write(fileDesc, pinIO, sizeof(const char*));
close(fileDesc);
// open descriptor to value
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), GPIO_VALUE_PATH, hwPinId);
fileDesc = open(path, O_RDWR);
}
GPIOPin::~GPIOPin()
{
close(fileDesc);
//fileDesc = open(GPIO_EXPORT_PATH, O_WRONLY);
//write(fileDesc, hwPinId, sizeof(hwPinId));
//close(fileDesc);
}
void GPIOPin::setPin(int state)
{
char buffer[4];
memset(buffer, 0, sizeof(buffer));
snprintf(buffer, sizeof(buffer), "%d", state);
ROS_INFO("Setting pin %d to %s", hwPinId, buffer);
lseek(fileDesc, 0, SEEK_SET);
write(fileDesc, buffer, strlen(buffer));
}
void pinCallback(const std_msgs::Int32::ConstPtr& msg)
{
memset(PIN_VALUES, GPIO_LOW, sizeof(PIN_VALUES));
if (!(msg->data < 0 || msg->data > sizeof(PIN_VALUES)/sizeof(int))) {
PIN_VALUES[msg->data] = GPIO_HIGH;
ROS_INFO("%d is now on", msg->data);
}
}
// Mike:
int main (int argc, char *argv[])
{
ros::init(argc, argv, "gpio_controller");
ros::NodeHandle n;
ros::Subscriber gpio_sub = n.subscribe<std_msgs::Int32>("/gpio_ctl", 10, &pinCallback);
ros::Rate loop_rate(1);
memset(PIN_VALUES, GPIO_LOW, sizeof(PIN_VALUES));
// create pins
GPIOPin pin1(GPIO_1, GPIO_OUT);
GPIOPin pin2(GPIO_2, GPIO_OUT);
GPIOPin pin3(GPIO_3, GPIO_OUT);
GPIOPin pin4(GPIO_4, GPIO_OUT);
GPIOPin pin7(GPIO_7, GPIO_OUT);
while (ros::ok()) {
pin1.setPin(PIN_VALUES[0]);
pin2.setPin(PIN_VALUES[1]);
pin3.setPin(PIN_VALUES[2]);
pin4.setPin(PIN_VALUES[3]);
pin7.setPin(PIN_VALUES[4]);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<commit_msg>Updated GPIO code. Corrected the LED lightup order<commit_after>/*
* GPIO handler for Dragonboard
* Author: Kenny Yokoyama & Mike Lara
*/
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "ros/ros.h"
#include "std_msgs/Int32.h"
#define GPIO_EXPORT_PATH "/sys/class/gpio/export"
#define GPIO_UNEXPORT_PATH "/sys/class/gpio/unexport"
#define GPIO_DIR_PATH "/sys/class/gpio/gpio%d/direction"
#define GPIO_VALUE_PATH "/sys/class/gpio/gpio%d/value"
#define GPIO_HIGH 1
#define GPIO_LOW 0
#define GPIO_IN "in"
#define GPIO_OUT "out"
enum GPIO_PINS { GPIO_1=6, GPIO_2=7, GPIO_3=206, GPIO_4=207,
GPIO_5=186, GPIO_6=189, GPIO_7=22, GPIO_8=23};
int PIN_VALUES[5];
class GPIOPin
{
private:
// Mike:
int hwPinId;
int fileDesc;
public:
GPIOPin(GPIO_PINS pin, const char* pinIO);
~GPIOPin();
// Kenny:
void setPin(int state);
// Mike:
void writeFile(int value);
};
GPIOPin::GPIOPin(GPIO_PINS pin, const char* pinIO)
{
char path[256];
hwPinId = pin;
// setup export
fileDesc = open(GPIO_EXPORT_PATH, O_WRONLY);
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), "%d", hwPinId);
write(fileDesc, path, strlen(path));
close(fileDesc);
// setup signal direction
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), GPIO_DIR_PATH, hwPinId);
fileDesc = open(path, O_WRONLY);
write(fileDesc, pinIO, sizeof(const char*));
close(fileDesc);
// open descriptor to value
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), GPIO_VALUE_PATH, hwPinId);
fileDesc = open(path, O_RDWR);
}
GPIOPin::~GPIOPin()
{
close(fileDesc);
//fileDesc = open(GPIO_EXPORT_PATH, O_WRONLY);
//write(fileDesc, hwPinId, sizeof(hwPinId));
//close(fileDesc);
}
void GPIOPin::setPin(int state)
{
char buffer[4];
memset(buffer, 0, sizeof(buffer));
snprintf(buffer, sizeof(buffer), "%d", state);
ROS_INFO("Setting pin %d to %s", hwPinId, buffer);
lseek(fileDesc, 0, SEEK_SET);
write(fileDesc, buffer, strlen(buffer));
}
void pinCallback(const std_msgs::Int32::ConstPtr& msg)
{
memset(PIN_VALUES, GPIO_LOW, sizeof(PIN_VALUES));
if (!(msg->data < 0 || msg->data > sizeof(PIN_VALUES)/sizeof(int))) {
PIN_VALUES[msg->data] = GPIO_HIGH;
ROS_INFO("%d is now on", msg->data);
}
}
// Mike:
int main (int argc, char *argv[])
{
ros::init(argc, argv, "gpio_controller");
ros::NodeHandle n;
ros::Subscriber gpio_sub = n.subscribe<std_msgs::Int32>("/gpio_ctl", 10, &pinCallback);
ros::Rate loop_rate(1);
memset(PIN_VALUES, GPIO_LOW, sizeof(PIN_VALUES));
// create pins
GPIOPin pin1(GPIO_1, GPIO_OUT);
GPIOPin pin2(GPIO_2, GPIO_OUT);
GPIOPin pin3(GPIO_3, GPIO_OUT);
GPIOPin pin4(GPIO_4, GPIO_OUT);
GPIOPin pin7(GPIO_7, GPIO_OUT);
while (ros::ok()) {
pin1.setPin(PIN_VALUES[1]);
pin2.setPin(PIN_VALUES[0]);
pin3.setPin(PIN_VALUES[3]);
pin4.setPin(PIN_VALUES[2]);
pin7.setPin(PIN_VALUES[4]);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<|endoftext|> |
<commit_before>//! @file
//! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>.
#pragma once
#include "coordinates.hpp"
#include "reg.hpp"
#include "utility/reference.hpp"
#include <array>
#include <iostream>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <unordered_set>
namespace ql {
struct light_source;
//! An rhomboid section of hexes in a region.
struct section {
//! Generates a new section.
//! @param region_id The ID of the region containing this section.
//! @param coords The coordinates of the section within its region.
section(id region_id, section_hex::point coords);
//! The hex coordinates of this section within its region's sections.
auto section_coords() const;
//! The coordinates of this section's center tile.
auto center_coords() const -> tile_hex::point;
//! A map in this section of tile coordinates to occupying entities.
auto entity_id_map() const -> std::unordered_map<tile_hex::point, id> const&;
//! The ID of the entity at @p tile_coords or nullopt if there is none.
auto entity_id_at(tile_hex::point tile_coords) const -> std::optional<id>;
//! Tries to add the given entity to the section. Returns true on success or false if there is already an entity
//! at the entity's coordinates.
[[nodiscard]] auto try_add(id being_id) -> bool;
//! Removes the being at the given region tile coordinates, if present.
auto remove_at(tile_hex::point coords) -> void;
//! Removes the entity with ID @p entity_id from this section, if present.
auto remove(id entity_id) -> void;
//! The ID of the tile at @p coords in this section.
//! @note Behavior is undefined if @p coords is not within this section.
auto tile_id_at(tile_hex::point coords) const -> id;
private:
//! A q-major array of tiles, representing a rhomboid section of tiles centered on this section's hex coordinates.
std::array<std::array<id, section_diameter.value>, section_diameter.value> _tile_ids;
std::unordered_map<tile_hex::point, id> _entity_id_map;
//! The hex coordinates of this section within its region.
section_hex::point _coords;
//! The array indices of the tile at @p coords.
//! @note Behavior is undefined if @p coords is not within this section.
auto indices(tile_hex::point coords) const -> std::tuple<size_t, size_t>;
};
}
<commit_msg>Removed unused includes.<commit_after>//! @file
//! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>.
#pragma once
#include "coordinates.hpp"
#include "reg.hpp"
#include "utility/reference.hpp"
#include <array>
#include <optional>
#include <unordered_map>
namespace ql {
struct light_source;
//! An rhomboid section of hexes in a region.
struct section {
//! Generates a new section.
//! @param region_id The ID of the region containing this section.
//! @param coords The coordinates of the section within its region.
section(id region_id, section_hex::point coords);
//! The hex coordinates of this section within its region's sections.
auto section_coords() const;
//! The coordinates of this section's center tile.
auto center_coords() const -> tile_hex::point;
//! A map in this section of tile coordinates to occupying entities.
auto entity_id_map() const -> std::unordered_map<tile_hex::point, id> const&;
//! The ID of the entity at @p tile_coords or nullopt if there is none.
auto entity_id_at(tile_hex::point tile_coords) const -> std::optional<id>;
//! Tries to add the given entity to the section. Returns true on success or false if there is already an entity
//! at the entity's coordinates.
[[nodiscard]] auto try_add(id being_id) -> bool;
//! Removes the being at the given region tile coordinates, if present.
auto remove_at(tile_hex::point coords) -> void;
//! Removes the entity with ID @p entity_id from this section, if present.
auto remove(id entity_id) -> void;
//! The ID of the tile at @p coords in this section.
//! @note Behavior is undefined if @p coords is not within this section.
auto tile_id_at(tile_hex::point coords) const -> id;
private:
//! A q-major array of tiles, representing a rhomboid section of tiles centered on this section's hex coordinates.
std::array<std::array<id, section_diameter.value>, section_diameter.value> _tile_ids;
std::unordered_map<tile_hex::point, id> _entity_id_map;
//! The hex coordinates of this section within its region.
section_hex::point _coords;
//! The array indices of the tile at @p coords.
//! @note Behavior is undefined if @p coords is not within this section.
auto indices(tile_hex::point coords) const -> std::tuple<size_t, size_t>;
};
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or 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 DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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 "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct EquivStructWorker
{
Module *module;
SigMap sigmap;
SigMap equiv_bits;
bool mode_nortl;
int merge_count;
dict<IdString, pool<IdString>> cells_by_type;
void handle_cell_pair(Cell *cell_a, Cell *cell_b)
{
if (cell_a->parameters != cell_b->parameters)
return;
bool merge_this_cells = false;
vector<SigSpec> inputs_a, inputs_b;
for (auto &port_a : cell_a->connections())
{
SigSpec bits_a = equiv_bits(port_a.second);
SigSpec bits_b = equiv_bits(cell_b->getPort(port_a.first));
if (GetSize(bits_a) != GetSize(bits_b))
return;
if (cell_a->output(port_a.first)) {
for (int i = 0; i < GetSize(bits_a); i++)
if (bits_a[i] == bits_b[i])
merge_this_cells = true;
} else {
SigSpec diff_bits_a, diff_bits_b;
for (int i = 0; i < GetSize(bits_a); i++)
if (bits_a[i] != bits_b[i]) {
diff_bits_a.append(bits_a[i]);
diff_bits_b.append(bits_b[i]);
}
if (!diff_bits_a.empty()) {
inputs_a.push_back(diff_bits_a);
inputs_b.push_back(diff_bits_b);
}
}
}
if (merge_this_cells)
{
SigMap merged_map;
log(" Merging cells %s and %s.\n", log_id(cell_a), log_id(cell_b));
merge_count++;
for (int i = 0; i < GetSize(inputs_a); i++) {
SigSpec &sig_a = inputs_a[i], &sig_b = inputs_b[i];
SigSpec sig_y = module->addWire(NEW_ID, GetSize(sig_a));
log(" A: %s, B: %s, Y: %s\n", log_signal(sig_a), log_signal(sig_b), log_signal(sig_y));
module->addEquiv(NEW_ID, sig_a, sig_b, sig_y);
merged_map.add(sig_a, sig_y);
merged_map.add(sig_b, sig_y);
}
std::vector<IdString> outport_names, inport_names;
for (auto &port_a : cell_a->connections())
if (cell_a->output(port_a.first))
outport_names.push_back(port_a.first);
else
inport_names.push_back(port_a.first);
for (auto &pn : inport_names)
cell_a->setPort(pn, merged_map(equiv_bits(cell_a->getPort(pn))));
for (auto &pn : outport_names) {
SigSpec sig_a = cell_a->getPort(pn);
SigSpec sig_b = cell_b->getPort(pn);
module->connect(sig_b, sig_a);
sigmap.add(sig_b, sig_a);
equiv_bits.add(sig_b, sig_a);
}
module->remove(cell_b);
}
}
EquivStructWorker(Module *module, bool mode_nortl) :
module(module), sigmap(module), equiv_bits(module), mode_nortl(mode_nortl), merge_count(0)
{
log(" Starting new iteration.\n");
for (auto cell : module->selected_cells())
if (cell->type == "$equiv") {
equiv_bits.add(sigmap(cell->getPort("\\A")), sigmap(cell->getPort("\\B")));
} else
if (module->design->selected(module, cell)) {
if (!mode_nortl || module->design->module(cell->type))
cells_by_type[cell->type].insert(cell->name);
}
for (auto &it : cells_by_type)
{
if (it.second.size() <= 1)
continue;
log(" Merging %s cells..\n", log_id(it.first));
// FIXME: O(n^2)
for (auto cell_name_a : it.second)
for (auto cell_name_b : it.second)
if (cell_name_a < cell_name_b) {
Cell *cell_a = module->cell(cell_name_a);
Cell *cell_b = module->cell(cell_name_b);
if (cell_a && cell_b)
handle_cell_pair(cell_a, cell_b);
}
}
}
};
struct EquivStructPass : public Pass {
EquivStructPass() : Pass("equiv_struct", "structural equivalence checking") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" equiv_struct [options] [selection]\n");
log("\n");
log("This command adds additional $equiv cells based on the assumption that the\n");
log("gold and gate circuit are structurally equivalent. Note that this can introduce\n");
log("bad $equiv cells in cases where the netlists are not structurally equivalent,\n");
log("for example when analyzing circuits with cells with commutative inputs.\n");
log("\n");
log(" -nortl\n");
log(" only operate on 'blackbox' cells and hierarchical module instantiations\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, Design *design)
{
bool mode_nortl = false;
log_header("Executing EQUIV_STRUCT pass.\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-bb") {
mode_nortl = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto module : design->selected_modules()) {
log("Running equiv_struct on module %s:", log_id(module));
while (1) {
EquivStructWorker worker(module, mode_nortl);
if (worker.merge_count == 0)
break;
}
}
}
} EquivStructPass;
PRIVATE_NAMESPACE_END
<commit_msg>Improvements in equiv_struct<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or 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 DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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 "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct EquivStructWorker
{
Module *module;
SigMap sigmap;
SigMap equiv_bits;
bool mode_icells;
int merge_count;
dict<IdString, pool<IdString>> cells_by_type;
void handle_cell_pair(Cell *cell_a, Cell *cell_b)
{
if (cell_a->parameters != cell_b->parameters)
return;
bool merge_this_cells = false;
bool found_diff_inputs = false;
vector<SigSpec> inputs_a, inputs_b;
for (auto &port_a : cell_a->connections())
{
SigSpec bits_a = equiv_bits(port_a.second);
SigSpec bits_b = equiv_bits(cell_b->getPort(port_a.first));
if (GetSize(bits_a) != GetSize(bits_b))
return;
if (cell_a->output(port_a.first)) {
for (int i = 0; i < GetSize(bits_a); i++)
if (bits_a[i] == bits_b[i])
merge_this_cells = true;
} else {
SigSpec diff_bits_a, diff_bits_b;
for (int i = 0; i < GetSize(bits_a); i++)
if (bits_a[i] != bits_b[i]) {
diff_bits_a.append(bits_a[i]);
diff_bits_b.append(bits_b[i]);
}
if (!diff_bits_a.empty()) {
inputs_a.push_back(diff_bits_a);
inputs_b.push_back(diff_bits_b);
found_diff_inputs = true;
}
}
}
if (!found_diff_inputs)
merge_this_cells = true;
if (merge_this_cells)
{
SigMap merged_map;
log(" Merging cells %s and %s.\n", log_id(cell_a), log_id(cell_b));
merge_count++;
for (int i = 0; i < GetSize(inputs_a); i++) {
SigSpec &sig_a = inputs_a[i], &sig_b = inputs_b[i];
SigSpec sig_y = module->addWire(NEW_ID, GetSize(sig_a));
log(" A: %s, B: %s, Y: %s\n", log_signal(sig_a), log_signal(sig_b), log_signal(sig_y));
module->addEquiv(NEW_ID, sig_a, sig_b, sig_y);
merged_map.add(sig_a, sig_y);
merged_map.add(sig_b, sig_y);
}
std::vector<IdString> outport_names, inport_names;
for (auto &port_a : cell_a->connections())
if (cell_a->output(port_a.first))
outport_names.push_back(port_a.first);
else
inport_names.push_back(port_a.first);
for (auto &pn : inport_names)
cell_a->setPort(pn, merged_map(equiv_bits(cell_a->getPort(pn))));
for (auto &pn : outport_names) {
SigSpec sig_a = cell_a->getPort(pn);
SigSpec sig_b = cell_b->getPort(pn);
module->connect(sig_b, sig_a);
sigmap.add(sig_b, sig_a);
equiv_bits.add(sig_b, sig_a);
}
module->remove(cell_b);
}
}
EquivStructWorker(Module *module, bool mode_icells) :
module(module), sigmap(module), equiv_bits(module), mode_icells(mode_icells), merge_count(0)
{
log(" Starting new iteration.\n");
for (auto cell : module->selected_cells())
if (cell->type == "$equiv") {
equiv_bits.add(sigmap(cell->getPort("\\A")), sigmap(cell->getPort("\\B")));
} else
if (module->design->selected(module, cell)) {
if (mode_icells || module->design->module(cell->type))
cells_by_type[cell->type].insert(cell->name);
}
for (auto &it : cells_by_type)
{
if (it.second.size() <= 1)
continue;
log(" Merging %s cells..\n", log_id(it.first));
// FIXME: O(n^2)
for (auto cell_name_a : it.second)
for (auto cell_name_b : it.second)
if (cell_name_a < cell_name_b) {
Cell *cell_a = module->cell(cell_name_a);
Cell *cell_b = module->cell(cell_name_b);
if (cell_a && cell_b)
handle_cell_pair(cell_a, cell_b);
}
}
}
};
struct EquivStructPass : public Pass {
EquivStructPass() : Pass("equiv_struct", "structural equivalence checking") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" equiv_struct [options] [selection]\n");
log("\n");
log("This command adds additional $equiv cells based on the assumption that the\n");
log("gold and gate circuit are structurally equivalent. Note that this can introduce\n");
log("bad $equiv cells in cases where the netlists are not structurally equivalent,\n");
log("for example when analyzing circuits with cells with commutative inputs. This\n");
log("command will also de-duplicate gates.\n");
log("\n");
log(" -icells\n");
log(" by default, the internal RTL and gate cell types are ignored. add\n");
log(" this option to also process those cell types with this command.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, Design *design)
{
bool mode_icells = false;
log_header("Executing EQUIV_STRUCT pass.\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-icells") {
mode_icells = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto module : design->selected_modules()) {
log("Running equiv_struct on module %s:", log_id(module));
while (1) {
EquivStructWorker worker(module, mode_icells);
if (worker.merge_count == 0)
break;
}
}
}
} EquivStructPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>AliAnalysisTask *AddTask_slehner_ElectronEfficiency(Bool_t hasITS = kTRUE,
Int_t trackCut=1,
Int_t evCut=1,
TString directoryBaseName = "slehner",
Char_t* outputFileName="LMEE_output.root",
Bool_t deactivateTree=kFALSE, // enabling this has priority over 'writeTree'! (needed for LEGO trains)
TString resolutionfile = "" //Resolution_pp_16l_eta.root
)
{
//get the current analysis manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
if(!mgr){
Error("AddTask_slehner_ElectronEfficiency", "No analysis manager found.");
return 0;
}
//Base Directory for GRID / LEGO Train
TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
TString configLMEECutLib("LMEECutLib_slehner.C");
TString configLMEECutLibPath(configBasePath+configLMEECutLib);
std::cout << "Configpath: " << configFilePath << std::endl;
//LOAD CUTLIB
if(gSystem->Exec(Form("ls %s", configLMEECutLibPath.Data()))==0){
std::cout << "loading LMEECutLib: " << configLMEECutLibPath.Data() << std::endl;
gROOT->LoadMacro(configLMEECutLibPath.Data());
}
else{
std::cout << "LMEECutLib not found: " << configLMEECutLibPath.Data() << std::endl;
return 0; // if return is not called, the job will fail instead of running wihout this task... (good for local tests, bad for train)
}
//Do we have an MC handler?
Bool_t hasMC = (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler() != 0x0);
std::cout << "hasMC = " << hasMC << std::endl;
LMEECutLib* cutlib = new LMEECutLib();
AliAnalysisTaskMLTreeMaker *task = new AliAnalysisTaskMLTreeMaker(taskname);
task->SelectCollisionCandidates(AliVEvent::kINT7);
task->SetTrackCuts(cutlib->GetTrackSelectionAna(trackCut));
task->SetEventCuts(cutlib->GetEventCuts(evCut));
mgr->AddTask(taskESD);
TString outputFileName = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *coutESD = mgr->CreateContainer("output", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
mgr->ConnectInput(taskESD, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskESD, 1, coutESD);
return taskESD;
}
<commit_msg>rename function<commit_after>AliAnalysisTask *AddTask_slehner_TreeMakeWCutLib(Bool_t hasITS = kTRUE,
Int_t trackCut=1,
Int_t evCut=1,
TString directoryBaseName = "slehner",
Char_t* outputFileName="LMEE_output.root",
Bool_t deactivateTree=kFALSE, // enabling this has priority over 'writeTree'! (needed for LEGO trains)
TString resolutionfile = "" //Resolution_pp_16l_eta.root
)
{
//get the current analysis manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
if(!mgr){
Error("AddTask_slehner_TreeMakeWCutLib", "No analysis manager found.");
return 0;
}
//Base Directory for GRID / LEGO Train
TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
TString configLMEECutLib("LMEECutLib_slehner.C");
TString configLMEECutLibPath(configBasePath+configLMEECutLib);
std::cout << "Configpath: " << configFilePath << std::endl;
//LOAD CUTLIB
if(gSystem->Exec(Form("ls %s", configLMEECutLibPath.Data()))==0){
std::cout << "loading LMEECutLib: " << configLMEECutLibPath.Data() << std::endl;
gROOT->LoadMacro(configLMEECutLibPath.Data());
}
else{
std::cout << "LMEECutLib not found: " << configLMEECutLibPath.Data() << std::endl;
return 0; // if return is not called, the job will fail instead of running wihout this task... (good for local tests, bad for train)
}
//Do we have an MC handler?
Bool_t hasMC = (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler() != 0x0);
std::cout << "hasMC = " << hasMC << std::endl;
LMEECutLib* cutlib = new LMEECutLib();
AliAnalysisTaskMLTreeMaker *task = new AliAnalysisTaskMLTreeMaker(taskname);
task->SelectCollisionCandidates(AliVEvent::kINT7);
task->SetTrackCuts(cutlib->GetTrackSelectionAna(trackCut));
task->SetEventCuts(cutlib->GetEventCuts(evCut));
mgr->AddTask(taskESD);
TString outputFileName = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *coutESD = mgr->CreateContainer("output", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
mgr->ConnectInput(taskESD, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskESD, 1, coutESD);
return taskESD;
}
<|endoftext|> |
<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TMath.h>
#include <TROOT.h>
#include <Riostream.h>
#include <TCanvas.h>
#include <TString.h>
#include <TFile.h>
#include <TList.h>
#include <TH1F.h>
#include <TH1D.h>
#include <TF2.h>
#include <TFitResult.h>
#include <TFitResultPtr.h>
#include <TH2F.h>
#include <TH3F.h>
#endif
Double_t xbins[]={
0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,
1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,
2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,
4.5,5.0,5.5,6.5,8.0,10.0,12.0
};
Int_t nb=sizeof(xbins)/sizeof(Double_t);
Int_t nb1=nb-1;
TFile *fAss;
TFile *fGen;
TFile *fRaw;
void Generated();
void Efficiencies(Float_t cMin, Float_t cMax, TString centr);
void RawYields(Float_t cMin, Float_t cMax, TString centr);
void Spectra(TString centr);
void SpectraV0CutVariations(Float_t cMin, Float_t cMax, TString centr) {
fRaw=TFile::Open((centr+"/AliV0CutVariations.root").Data());
fAss=TFile::Open((centr+"/AliV0CutVariationsMC.root").Data());
fGen=TFile::Open("Generated.root");
if (!fGen) {
Generated();
fGen=TFile::Open("Generated.root");
}
Efficiencies(cMin,cMax,centr);
RawYields(cMin,cMax,centr);
Spectra(centr);
fAss->Close();
fGen->Close();
fRaw->Close();
}
TH1 *GetEfficiency(Float_t, Float_t, const Char_t *, const Char_t *);
void Efficiencies(Float_t cmin, Float_t cmax, TString centr) {
TString name;
TH1 *effK0s=
GetEfficiency(cmin, cmax, "fK0sAs","f3dHistPrimRawPtVsYVsMultK0Short");
name="eff_K0s_";
name+=centr;
effK0s->SetName(name.Data());
TH1 *effLambda=
GetEfficiency(cmin, cmax, "fLambdaAs","f3dHistPrimRawPtVsYVsMultLambda");
name="eff_Lambda_";
name+=centr;
effLambda->SetName(name.Data());
TH1 *effLambdaBar=
GetEfficiency(cmin,cmax,"fLambdaBarAs","f3dHistPrimRawPtVsYVsMultAntiLambda");
name="eff_LambdaBar_";
name+=centr;
effLambdaBar->SetName(name.Data());
TFile *f=TFile::Open("SpectraFromTrees.root","update");
effK0s->Write();
effLambda->Write();
effLambdaBar->Write();
f->Close();
}
TH1 *GetEfficiency(Float_t cMin, Float_t cMax,
const Char_t *chis, const Char_t *znam) {
// Numerator
fAss->cd();
TH2F *f2d=(TH2F*)gDirectory->Get(chis); f2d->Sumw2();
TH1D *hAs=f2d->ProjectionX("hAs",0,-1,"e");
// Denominator
fGen->cd();
TH3F *f3d = (TH3F*)gDirectory->Get(znam);
f3d->Sumw2();
TH1D *fpt = f3d->ProjectionX("fpt",
f3d->GetYaxis()->FindBin(-0.5+1e-2),
f3d->GetYaxis()->FindBin(+0.5-1e-2),
f3d->GetZaxis()->FindBin(cMin),
f3d->GetZaxis()->FindBin(cMax)
);
TH1 *hMc=fpt->Rebin(nb1,"hMc",xbins);
//Efficiency
TH1 *eff = (TH1*)hAs->Clone();
eff->Divide(hAs,hMc,1,1,"b");
return eff;
}
void RawYields(Float_t cMin, Float_t cMax, TString centr) {
TString name;
TH2F *f2d=0;
//+++ Number of events for normalisation
TFile *file=TFile::Open("Merged.root");
TList *v0list=(TList *)gFile->Get("PWGLFExtractV0_PP/clistV0");
TH1F *fMult=(TH1F*)v0list->FindObject("fHistMultiplicity");
Int_t i1=fMult->GetXaxis()->FindBin(cMin+1e-2);
Int_t i2=fMult->GetXaxis()->FindBin(cMax+1e-2);
Float_t nEvents=fMult->Integral(i1,i2);
file->Close();
fRaw->cd();
name="raw_K0s_";
name+=centr;
f2d=(TH2F*)gDirectory->Get("fK0sSi"); f2d->Sumw2();
TH1D *rawK0s=f2d->ProjectionX(name,0,-1,"e");
rawK0s->Scale(1/nEvents,"width");
name="raw_Lambda_";
name+=centr;
f2d=(TH2F*)gDirectory->Get("fLambdaSi"); f2d->Sumw2();
TH1D *rawLambda=f2d->ProjectionX(name,0,-1,"e");
rawLambda->Scale(1/nEvents,"width");
name="raw_LambdaBar_";
name+=centr;
f2d=(TH2F*)gDirectory->Get("fLambdaBarSi"); f2d->Sumw2();
TH1D *rawLambdaBar=f2d->ProjectionX(name,0,-1,"e");
rawLambdaBar->Scale(1/nEvents,"width");
TFile *f=TFile::Open("SpectraFromTrees.root","update");
rawK0s->Write();
rawLambda->Write();
rawLambdaBar->Write();
f->Close();
}
void Spectra(TString centr) {
TString name;
TH1 *eff=0;
TH1D *raw=0;
TH1D *spe=0;
TFile *f=TFile::Open("SpectraFromTrees.root","update");
name="eff_K0s_";
name+=centr;
eff = (TH1*)gDirectory->Get(name.Data());
name="raw_K0s_";
name+=centr;
raw = (TH1D*)gDirectory->Get(name.Data());
spe = new TH1D(*raw);
spe->Divide(eff);
name="K0s_";
name+=centr;
spe->SetName(name.Data());
spe->Write();
name="eff_Lambda_";
name+=centr;
eff = (TH1*)gDirectory->Get(name.Data());
name="raw_Lambda_";
name+=centr;
raw = (TH1D*)gDirectory->Get(name.Data());
spe = new TH1D(*raw);
spe->Divide(eff);
name="Lambda_";
name+=centr;
spe->SetName(name.Data());
spe->Write();
name="eff_LambdaBar_";
name+=centr;
eff = (TH1*)gDirectory->Get(name.Data());
name="raw_LambdaBar_";
name+=centr;
raw = (TH1D*)gDirectory->Get(name.Data());
spe = new TH1D(*raw);
spe->Divide(eff);
name="LambdaBar_";
name+=centr;
spe->SetName(name.Data());
spe->Write();
f->Close();
}
void Generated() {
TList *v0listMC=0;
TH3F *h3=0;
//
TFile::Open("LHC11a10b_plus/Merged.root");
v0listMC=(TList *)gFile->Get("PWGLFExtractPerformanceV0_PP_MC/clistV0MC");
TH3F *k0s =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
TH3F *k0s_nonInj =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjK0Short");
TH3F *lam =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
TH3F *lam_nonInj =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjLambda");
TH3F *alam =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
TH3F *alam_nonInj =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjAntiLambda");
//
TFile::Open("LHC11a10b_bis/Merged.root");
v0listMC=(TList *)gFile->Get("PWGLFExtractPerformanceV0_PP_MC/clistV0MC");
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
k0s->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjK0Short");
k0s_nonInj->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
lam->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjLambda");
lam_nonInj->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
alam->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjAntiLambda");
alam_nonInj->Add(h3);
//
TFile::Open("LHC11a10a_bis/Merged.root");
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
k0s_nonInj->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
lam_nonInj->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
alam_nonInj->Add(h3);
TFile *f=TFile::Open("Generated.root","new");
k0s->Write(); k0s_nonInj->Write();
lam->Write(); lam_nonInj->Write();
alam->Write(); alam_nonInj->Write();
f->Close();
}
<commit_msg>More convenient file names<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TMath.h>
#include <TROOT.h>
#include <Riostream.h>
#include <TCanvas.h>
#include <TString.h>
#include <TFile.h>
#include <TList.h>
#include <TH1F.h>
#include <TH1D.h>
#include <TF2.h>
#include <TFitResult.h>
#include <TFitResultPtr.h>
#include <TH2F.h>
#include <TH3F.h>
#endif
Double_t xbins[]={
0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,
1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,
2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,
4.5,5.0,5.5,6.5,8.0,10.0,12.0
};
Int_t nb=sizeof(xbins)/sizeof(Double_t);
Int_t nb1=nb-1;
TFile *fAss;
TFile *fGen;
TFile *fRaw;
void Generated();
void Efficiencies(Float_t cMin, Float_t cMax, TString centr);
void RawYields(Float_t cMin, Float_t cMax, TString centr);
void Spectra(TString centr);
void SpectraV0CutVariations(Float_t cMin, Float_t cMax, TString centr) {
fRaw=TFile::Open((centr+"/AliV0CutVariations.root").Data());
fAss=TFile::Open((centr+"/AliV0CutVariationsMC.root").Data());
fGen=TFile::Open("Generated.root");
if (!fGen) {
Generated();
fGen=TFile::Open("Generated.root");
}
Efficiencies(cMin,cMax,centr);
RawYields(cMin,cMax,centr);
Spectra(centr);
fAss->Close();
fGen->Close();
fRaw->Close();
}
TH1 *GetEfficiency(Float_t, Float_t, const Char_t *, const Char_t *);
void Efficiencies(Float_t cmin, Float_t cmax, TString centr) {
TString name;
TH1 *effK0s=
GetEfficiency(cmin, cmax, "fK0sAs","f3dHistPrimRawPtVsYVsMultK0Short");
name="eff_K0s_";
name+=centr;
effK0s->SetName(name.Data());
TH1 *effLambda=
GetEfficiency(cmin, cmax, "fLambdaAs","f3dHistPrimRawPtVsYVsMultLambda");
name="eff_Lambda_";
name+=centr;
effLambda->SetName(name.Data());
TH1 *effLambdaBar=
GetEfficiency(cmin,cmax,"fLambdaBarAs","f3dHistPrimRawPtVsYVsMultAntiLambda");
name="eff_LambdaBar_";
name+=centr;
effLambdaBar->SetName(name.Data());
TFile *f=TFile::Open("SpectraV0CutVariations.root","update");
effK0s->Write();
effLambda->Write();
effLambdaBar->Write();
f->Close();
}
TH1 *GetEfficiency(Float_t cMin, Float_t cMax,
const Char_t *chis, const Char_t *znam) {
// Numerator
fAss->cd();
TH2F *f2d=(TH2F*)gDirectory->Get(chis); f2d->Sumw2();
TH1D *hAs=f2d->ProjectionX("hAs",0,-1,"e");
// Denominator
fGen->cd();
TH3F *f3d = (TH3F*)gDirectory->Get(znam);
f3d->Sumw2();
TH1D *fpt = f3d->ProjectionX("fpt",
f3d->GetYaxis()->FindBin(-0.5+1e-2),
f3d->GetYaxis()->FindBin(+0.5-1e-2),
f3d->GetZaxis()->FindBin(cMin),
f3d->GetZaxis()->FindBin(cMax)
);
TH1 *hMc=fpt->Rebin(nb1,"hMc",xbins);
//Efficiency
TH1 *eff = (TH1*)hAs->Clone();
eff->Divide(hAs,hMc,1,1,"b");
return eff;
}
void RawYields(Float_t cMin, Float_t cMax, TString centr) {
TString name;
TH2F *f2d=0;
//+++ Number of events for normalisation
TFile *file=TFile::Open("LHC10h_pass2/Merged.root");
TList *v0list=(TList *)gFile->Get("PWGLFExtractV0_PP/clistV0");
TH1F *fMult=(TH1F*)v0list->FindObject("fHistMultiplicity");
Int_t i1=fMult->GetXaxis()->FindBin(cMin+1e-2);
Int_t i2=fMult->GetXaxis()->FindBin(cMax+1e-2);
Float_t nEvents=fMult->Integral(i1,i2);
file->Close();
fRaw->cd();
name="raw_K0s_";
name+=centr;
f2d=(TH2F*)gDirectory->Get("fK0sSi"); f2d->Sumw2();
TH1D *rawK0s=f2d->ProjectionX(name,0,-1,"e");
rawK0s->Scale(1/nEvents,"width");
name="raw_Lambda_";
name+=centr;
f2d=(TH2F*)gDirectory->Get("fLambdaSi"); f2d->Sumw2();
TH1D *rawLambda=f2d->ProjectionX(name,0,-1,"e");
rawLambda->Scale(1/nEvents,"width");
name="raw_LambdaBar_";
name+=centr;
f2d=(TH2F*)gDirectory->Get("fLambdaBarSi"); f2d->Sumw2();
TH1D *rawLambdaBar=f2d->ProjectionX(name,0,-1,"e");
rawLambdaBar->Scale(1/nEvents,"width");
TFile *f=TFile::Open("SpectraV0CutVariations.root","update");
rawK0s->Write();
rawLambda->Write();
rawLambdaBar->Write();
f->Close();
}
void Spectra(TString centr) {
TString name;
TH1 *eff=0;
TH1D *raw=0;
TH1D *spe=0;
TFile *f=TFile::Open("SpectraV0CutVariations.root","update");
name="eff_K0s_";
name+=centr;
eff = (TH1*)gDirectory->Get(name.Data());
name="raw_K0s_";
name+=centr;
raw = (TH1D*)gDirectory->Get(name.Data());
spe = new TH1D(*raw);
spe->Divide(eff);
name="K0s_";
name+=centr;
spe->SetName(name.Data());
spe->Write();
name="eff_Lambda_";
name+=centr;
eff = (TH1*)gDirectory->Get(name.Data());
name="raw_Lambda_";
name+=centr;
raw = (TH1D*)gDirectory->Get(name.Data());
spe = new TH1D(*raw);
spe->Divide(eff);
name="Lambda_";
name+=centr;
spe->SetName(name.Data());
spe->Write();
name="eff_LambdaBar_";
name+=centr;
eff = (TH1*)gDirectory->Get(name.Data());
name="raw_LambdaBar_";
name+=centr;
raw = (TH1D*)gDirectory->Get(name.Data());
spe = new TH1D(*raw);
spe->Divide(eff);
name="LambdaBar_";
name+=centr;
spe->SetName(name.Data());
spe->Write();
f->Close();
}
void Generated() {
TList *v0listMC=0;
TH3F *h3=0;
//
TFile::Open("LHC11a10b_plus/Merged.root");
v0listMC=(TList *)gFile->Get("PWGLFExtractPerformanceV0_PP_MC/clistV0MC");
TH3F *k0s =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
TH3F *k0s_nonInj =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjK0Short");
TH3F *lam =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
TH3F *lam_nonInj =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjLambda");
TH3F *alam =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
TH3F *alam_nonInj =
(TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjAntiLambda");
//
TFile::Open("LHC11a10b_bis/Merged.root");
v0listMC=(TList *)gFile->Get("PWGLFExtractPerformanceV0_PP_MC/clistV0MC");
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
k0s->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjK0Short");
k0s_nonInj->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
lam->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjLambda");
lam_nonInj->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
alam->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjAntiLambda");
alam_nonInj->Add(h3);
//
TFile::Open("LHC11a10a_bis/Merged.root");
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
k0s_nonInj->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
lam_nonInj->Add(h3);
h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
alam_nonInj->Add(h3);
TFile *f=TFile::Open("Generated.root","new");
k0s->Write(); k0s_nonInj->Write();
lam->Write(); lam_nonInj->Write();
alam->Write(); alam_nonInj->Write();
f->Close();
}
<|endoftext|> |
<commit_before>#include <limits>
#include <boost/math/special_functions/fpclassify.hpp>
#include <stan/agrad/rev/functions/abs.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
TEST(AgradRev,abs_var) {
AVAR a = 0.68;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(0.68, f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(1.0, g[0]);
}
TEST(AgradRev,abs_var_2) {
AVAR a = -0.68;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(0.68, f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(-1.0, g[0]);
}
TEST(AgradRev,abs_var_3) {
AVAR a = 0.0;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(0.0, f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_EQ(1U,g.size());
EXPECT_FLOAT_EQ(0.0, g[0]);
}
TEST(AgradRev,abs_inf) {
double inf = std::numeric_limits<double>::infinity();
AVAR a = inf;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(inf,f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(1.0,g[0]);
}
TEST(AgradRev,abs_neg_inf) {
double inf = std::numeric_limits<double>::infinity();
AVAR a = -inf;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(inf,f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(-1.0,g[0]);
}
TEST(AgradRev,abs_NaN) {
AVAR a = std::numeric_limits<double>::quiet_NaN();
AVAR f = abs(a);
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_TRUE(boost::math::isnan(f.val()));
ASSERT_EQ(1U,g.size());
EXPECT_TRUE(boost::math::isnan(g[0]));
}
<commit_msg>update nan test for agrad/rev/abs<commit_after>#include <limits>
#include <stan/agrad/rev/functions/abs.hpp>
#include <test/unit/agrad/util.hpp>
#include <test/unit-agrad-rev/nan_util.hpp>
#include <gtest/gtest.h>
TEST(AgradRev,abs_var) {
AVAR a = 0.68;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(0.68, f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(1.0, g[0]);
}
TEST(AgradRev,abs_var_2) {
AVAR a = -0.68;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(0.68, f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(-1.0, g[0]);
}
TEST(AgradRev,abs_var_3) {
AVAR a = 0.0;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(0.0, f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_EQ(1U,g.size());
EXPECT_FLOAT_EQ(0.0, g[0]);
}
TEST(AgradRev,abs_inf) {
double inf = std::numeric_limits<double>::infinity();
AVAR a = inf;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(inf,f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(1.0,g[0]);
}
TEST(AgradRev,abs_neg_inf) {
double inf = std::numeric_limits<double>::infinity();
AVAR a = -inf;
AVAR f = abs(a);
EXPECT_FLOAT_EQ(inf,f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(-1.0,g[0]);
}
struct abs_fun {
template <typename T0>
inline T0
operator()(const T0& arg1) const {
return abs(arg1);
}
};
TEST(AgradRev,abs_NaN) {
abs_fun abs_;
test_nan(abs_,false,true);
}
<|endoftext|> |
<commit_before>#include "RhoFile.h"
#include "common/StringConverter.h"
namespace rho{
namespace common{
class CFileInputStream : public InputStream
{
CRhoFile& m_oFile;
public:
CFileInputStream(CRhoFile& oFile) : m_oFile(oFile){}
virtual int available(){ return m_oFile.size(); }
virtual int read(){ return m_oFile.readByte(); }
virtual int read(void* buffer, int bufOffset, int bytesToRead){ return m_oFile.readData(buffer, bufOffset, bytesToRead); }
virtual void reset(){ m_oFile.movePosToStart(); }
};
bool CRhoFile::isOpened(){
return m_file!=0;
}
bool CRhoFile::open( const char* szFilePath, EOpenModes eMode ){
m_strPath = szFilePath;
if ( eMode == OpenForAppend || eMode == OpenForReadWrite ){
m_file = fopen(szFilePath,"r+b");
if ( eMode == OpenForAppend )
movePosToEnd();
if ( !m_file && !isFileExist(szFilePath) )
m_file = fopen(szFilePath,"wb");
}else if ( eMode == OpenReadOnly )
m_file = fopen(szFilePath,"rb");
else if ( eMode == OpenForWrite )
m_file = fopen(szFilePath,"wb");
return isOpened();
}
unsigned int CRhoFile::write( const void* data, unsigned int len ){
if ( !isOpened() )
return 0;
return static_cast<unsigned int>( fwrite(data,1, len, m_file) );
}
int CRhoFile::readByte()
{
unsigned char buf[1];
int nSize = fread(buf, 1, 1, m_file);
return nSize > 0 ? buf[0] : -1;
}
int CRhoFile::readData(void* buffer, int bufOffset, int bytesToRead)
{
int nSize = fread(((char*)buffer)+bufOffset, 1, bytesToRead, m_file);
return nSize > 0 ? nSize : -1;
}
void CRhoFile::readString(String& strData){
if ( !isOpened() )
return;
int nSize = size();
strData.resize(nSize);
nSize = fread(&strData[0], 1, nSize, m_file);
strData[nSize] = 0;
}
void CRhoFile::readStringW(StringW& strTextW)
{
if ( !isOpened() )
return;
int nSize = size();
char* buf = (char*)malloc(nSize+1);
nSize = fread(buf, 1, nSize, m_file);
buf[nSize] = 0;
common::convertToStringW(buf,strTextW);
free(buf);
}
InputStream* CRhoFile::getInputStream()
{
if ( m_pInputStream )
delete m_pInputStream;
m_pInputStream = new CFileInputStream(*this);
return m_pInputStream;
}
void CRhoFile::flush(){
if ( !isOpened() )
return;
fflush(m_file);
}
void CRhoFile::close(){
if ( !isOpened() )
return;
if ( m_pInputStream )
delete m_pInputStream;
m_pInputStream = 0;
fclose(m_file);
m_file = 0;
}
void CRhoFile::movePosToStart(){
if ( !isOpened() )
return;
fseek(m_file,0,SEEK_SET);
}
void CRhoFile::movePosToEnd(){
if ( !isOpened() )
return;
fseek(m_file,0,SEEK_END);
}
void CRhoFile::setPosTo(int nPos){
if ( !isOpened() || nPos < 0 )
return;
fseek(m_file,nPos,SEEK_SET);
}
unsigned int CRhoFile::size(){
if ( !isOpened() )
return 0;
return getFileSize( m_strPath.c_str() );
}
bool CRhoFile::isFileExist( const char* szFilePath ){
struct stat st;
memset(&st,0, sizeof(st));
return stat(szFilePath, &st) == 0;
}
unsigned int CRhoFile::getFileSize( const char* szFilePath ){
struct stat st;
memset(&st,0, sizeof(st));
int rc = stat(szFilePath, &st);
if ( rc == 0 && st.st_size > 0 )
return st.st_size;
return 0;
}
void CRhoFile::loadTextFile(const char* szFilePath, String& strFile)
{
common::CRhoFile oFile;
if ( oFile.open( szFilePath, common::CRhoFile::OpenReadOnly) )
oFile.readString(strFile);
}
void CRhoFile::deleteFile( const char* szFilePath ){
#if defined(OS_WINDOWS) || defined(OS_WINCE)
StringW wFileName;
common::convertToStringW(szFilePath,wFileName);
DeleteFile(wFileName.c_str());
#else
remove(szFilePath);
#endif
}
void CRhoFile::deleteFilesInFolder(const char* szFolderPath)
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
StringW wFolderName;
common::convertToStringW(szFolderPath,wFolderName);
StringW wFolderMask = wFolderName + L"/*";
WIN32_FIND_DATAW FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
hFind = FindFirstFileW(wFolderMask.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
return;
while (FindNextFileW(hFind, &FindFileData) != 0)
{
if ( FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY )
continue;
StringW wFileName = wFolderName + L"/" + FindFileData.cFileName;
DeleteFileW(wFileName.c_str());
}
FindClose(hFind);
#else
delete_files_in_folder(szFolderPath);
#endif
}
#if defined(OS_WINDOWS) || defined(OS_WINCE)
extern "C" int _mkdir(const char * dir);
#endif
/*static*/ void CRhoFile::createFolder(const char* szFolderPath)
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
_mkdir(szFolderPath);
#else
mkdir(szFolderPath, S_IRWXU);
#endif
}
/*static*/ void CRhoFile::renameFile( const char* szOldFilePath, const char* szNewFilePath )
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
StringW wNewFileName, wOldFileName;
common::convertToStringW(szNewFilePath,wNewFileName);
common::convertToStringW(szOldFilePath,wOldFileName);
BOOL res = MoveFileW( wOldFileName.c_str(), wNewFileName.c_str());
#else
rename( szOldFilePath, szNewFilePath );
#endif
}
}
}
<commit_msg>fix append file issue<commit_after>#include "RhoFile.h"
#include "common/StringConverter.h"
namespace rho{
namespace common{
class CFileInputStream : public InputStream
{
CRhoFile& m_oFile;
public:
CFileInputStream(CRhoFile& oFile) : m_oFile(oFile){}
virtual int available(){ return m_oFile.size(); }
virtual int read(){ return m_oFile.readByte(); }
virtual int read(void* buffer, int bufOffset, int bytesToRead){ return m_oFile.readData(buffer, bufOffset, bytesToRead); }
virtual void reset(){ m_oFile.movePosToStart(); }
};
bool CRhoFile::isOpened(){
return m_file!=0;
}
bool CRhoFile::open( const char* szFilePath, EOpenModes eMode ){
m_strPath = szFilePath;
if ( eMode == OpenForAppend || eMode == OpenForReadWrite ){
m_file = fopen(szFilePath,"r+b");
if ( !m_file && !isFileExist(szFilePath) )
m_file = fopen(szFilePath,"wb");
if ( eMode == OpenForAppend )
movePosToEnd();
}else if ( eMode == OpenReadOnly )
m_file = fopen(szFilePath,"rb");
else if ( eMode == OpenForWrite )
m_file = fopen(szFilePath,"wb");
return isOpened();
}
unsigned int CRhoFile::write( const void* data, unsigned int len ){
if ( !isOpened() )
return 0;
return static_cast<unsigned int>( fwrite(data,1, len, m_file) );
}
int CRhoFile::readByte()
{
unsigned char buf[1];
int nSize = fread(buf, 1, 1, m_file);
return nSize > 0 ? buf[0] : -1;
}
int CRhoFile::readData(void* buffer, int bufOffset, int bytesToRead)
{
int nSize = fread(((char*)buffer)+bufOffset, 1, bytesToRead, m_file);
return nSize > 0 ? nSize : -1;
}
void CRhoFile::readString(String& strData){
if ( !isOpened() )
return;
int nSize = size();
strData.resize(nSize);
nSize = fread(&strData[0], 1, nSize, m_file);
strData[nSize] = 0;
}
void CRhoFile::readStringW(StringW& strTextW)
{
if ( !isOpened() )
return;
int nSize = size();
char* buf = (char*)malloc(nSize+1);
nSize = fread(buf, 1, nSize, m_file);
buf[nSize] = 0;
common::convertToStringW(buf,strTextW);
free(buf);
}
InputStream* CRhoFile::getInputStream()
{
if ( m_pInputStream )
delete m_pInputStream;
m_pInputStream = new CFileInputStream(*this);
return m_pInputStream;
}
void CRhoFile::flush(){
if ( !isOpened() )
return;
fflush(m_file);
}
void CRhoFile::close(){
if ( !isOpened() )
return;
if ( m_pInputStream )
delete m_pInputStream;
m_pInputStream = 0;
fclose(m_file);
m_file = 0;
}
void CRhoFile::movePosToStart(){
if ( !isOpened() )
return;
fseek(m_file,0,SEEK_SET);
}
void CRhoFile::movePosToEnd(){
if ( !isOpened() )
return;
int nRes = fseek(m_file,0,SEEK_END);
fpos_t pos = 0;
int nRes2 = fgetpos(m_file, &pos );
if ( !nRes2 )
nRes2 = 0;
}
void CRhoFile::setPosTo(int nPos){
if ( !isOpened() || nPos < 0 )
return;
fseek(m_file,nPos,SEEK_SET);
}
unsigned int CRhoFile::size(){
if ( !isOpened() )
return 0;
return getFileSize( m_strPath.c_str() );
}
bool CRhoFile::isFileExist( const char* szFilePath ){
struct stat st;
memset(&st,0, sizeof(st));
return stat(szFilePath, &st) == 0;
}
unsigned int CRhoFile::getFileSize( const char* szFilePath ){
struct stat st;
memset(&st,0, sizeof(st));
int rc = stat(szFilePath, &st);
if ( rc == 0 && st.st_size > 0 )
return st.st_size;
return 0;
}
void CRhoFile::loadTextFile(const char* szFilePath, String& strFile)
{
common::CRhoFile oFile;
if ( oFile.open( szFilePath, common::CRhoFile::OpenReadOnly) )
oFile.readString(strFile);
}
void CRhoFile::deleteFile( const char* szFilePath ){
#if defined(OS_WINDOWS) || defined(OS_WINCE)
StringW wFileName;
common::convertToStringW(szFilePath,wFileName);
DeleteFile(wFileName.c_str());
#else
remove(szFilePath);
#endif
}
void CRhoFile::deleteFilesInFolder(const char* szFolderPath)
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
StringW wFolderName;
common::convertToStringW(szFolderPath,wFolderName);
StringW wFolderMask = wFolderName + L"/*";
WIN32_FIND_DATAW FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
hFind = FindFirstFileW(wFolderMask.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
return;
while (FindNextFileW(hFind, &FindFileData) != 0)
{
if ( FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY )
continue;
StringW wFileName = wFolderName + L"/" + FindFileData.cFileName;
DeleteFileW(wFileName.c_str());
}
FindClose(hFind);
#else
delete_files_in_folder(szFolderPath);
#endif
}
#if defined(OS_WINDOWS) || defined(OS_WINCE)
extern "C" int _mkdir(const char * dir);
#endif
/*static*/ void CRhoFile::createFolder(const char* szFolderPath)
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
_mkdir(szFolderPath);
#else
mkdir(szFolderPath, S_IRWXU);
#endif
}
/*static*/ void CRhoFile::renameFile( const char* szOldFilePath, const char* szNewFilePath )
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
StringW wNewFileName, wOldFileName;
common::convertToStringW(szNewFilePath,wNewFileName);
common::convertToStringW(szOldFilePath,wOldFileName);
BOOL res = MoveFileW( wOldFileName.c_str(), wNewFileName.c_str());
#else
rename( szOldFilePath, szNewFilePath );
#endif
}
}
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
* $Id$
*/
#ifndef PCL_SURFACE_IMPL_SURFEL_SMOOTHING_H_
#define PCL_SURFACE_IMPL_SURFEL_SMOOTHING_H_
#include "pcl/surface/surfel_smoothing.h"
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/kdtree/organized_data.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SurfelSmoothing<PointT, PointNT>::initCompute ()
{
if (!PCLBase<PointT>::initCompute ())
return false;
if (!normals_)
{
PCL_ERROR ("SurfelSmoothing: normal cloud not set\n");
return false;
}
if (input_->points.size () != normals_->points.size ())
{
PCL_ERROR ("SurfelSmoothing: number of input points different from the number of given normals\n");
return false;
}
// Initialize the spatial locator
if (!tree_)
{
if (input_->isOrganized ())
tree_.reset (new pcl::OrganizedDataIndex<PointT> ());
else
tree_.reset (new pcl::KdTreeFLANN<PointT> (false));
}
// create internal copies of the input - these will be modified
interm_cloud_ = PointCloudInPtr (new PointCloudIn (*input_));
interm_normals_ = NormalCloudPtr (new NormalCloud (*normals_));
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> float
pcl::SurfelSmoothing<PointT, PointNT>::smoothCloudIteration (PointCloudInPtr &output_positions,
NormalCloudPtr &output_normals)
{
PCL_INFO ("SurfelSmoothing: cloud smoothing iteration starting ...\n");
output_positions = PointCloudInPtr (new PointCloudIn);
output_positions->points.resize (interm_cloud_->points.size ());
output_normals = NormalCloudPtr (new NormalCloud);
output_normals->points.resize (interm_cloud_->points.size ());
std::vector<int> nn_indices;
std::vector<float> nn_distances;
std::vector<float> diffs (interm_cloud_->points.size ());
float total_residual = 0.0f;
for (size_t i = 0; i < interm_cloud_->points.size (); ++i)
{
Eigen::Vector4f smoothed_point = Eigen::Vector4f::Zero ();
Eigen::Vector4f smoothed_normal = Eigen::Vector4f::Zero ();
// get neighbors
// @todo using 5x the scale for searching instead of all the points to avoid O(N^2)
tree_->radiusSearch (interm_cloud_->points[i], 5*scale_, nn_indices, nn_distances);
// PCL_INFO ("NN: %u\n", nn_indices.size ());
float theta_normalization_factor = 0.0;
std::vector<float> theta (nn_indices.size ());
for (size_t nn_index_i = 0; nn_index_i < nn_indices.size (); ++nn_index_i)
{
float dist = pcl::squaredEuclideanDistance (interm_cloud_->points[i], input_->points[nn_indices[nn_index_i]]);//interm_cloud_->points[nn_indices[nn_index_i]]);
float theta_i = exp ( (-1) * dist / scale_squared_);
theta_normalization_factor += theta_i;
smoothed_normal += theta_i * interm_normals_->points[nn_indices[nn_index_i]].getNormalVector4fMap ();
theta[nn_index_i] = theta_i;
}
smoothed_normal /= theta_normalization_factor;
smoothed_normal(3) = 0.0f;
smoothed_normal.normalize ();
// find minimum along the normal
float e_residual;
smoothed_point = interm_cloud_->points[i].getVector4fMap ();
while (1)
{
e_residual = 0.0f;
smoothed_point(3) = 0.0f;
for (size_t nn_index_i = 0; nn_index_i < nn_indices.size (); ++nn_index_i)
{
Eigen::Vector4f neighbor = input_->points[nn_indices[nn_index_i]].getVector4fMap ();//interm_cloud_->points[nn_indices[nn_index_i]].getVector4fMap ();
neighbor(3) = 0.0f;
float dot_product = smoothed_normal.dot (neighbor - smoothed_point);
e_residual += theta[nn_index_i] * dot_product;// * dot_product;
}
e_residual /= theta_normalization_factor;
if (e_residual < 1e-5) break;
smoothed_point = smoothed_point + e_residual * smoothed_normal;
}
total_residual += e_residual;
output_positions->points[i].getVector4fMap () = smoothed_point;
output_normals->points[i].getNormalVector4fMap () = normals_->points[i].getNormalVector4fMap ();//smoothed_normal;
// Calculate difference
// diffs[i] = smoothed_normal.dot (smoothed_point - interm_cloud_->points[i].getVector4fMap ());
}
std::cerr << "Total residual after iteration: " << total_residual << std::endl;
PCL_INFO("SurfelSmoothing done iteration\n");
return total_residual;
}
template <typename PointT, typename PointNT> void
pcl::SurfelSmoothing<PointT, PointNT>::smoothPoint (size_t &point_index,
PointT &output_point,
PointNT &output_normal)
{
Eigen::Vector4f average_normal = Eigen::Vector4f::Zero ();
Eigen::Vector4f result_point = input_->points[point_index].getVector4fMap ();
result_point(3) = 0.0f;
// @todo parameter
float error_residual_threshold_ = 1e-9;
float error_residual = error_residual_threshold_ + 1;
float last_error_residual = error_residual + 100;
std::vector<int> nn_indices;
std::vector<float> nn_distances;
int big_iterations = 0;
int max_big_iterations = 500;
while (fabs (error_residual) < fabs (last_error_residual) -error_residual_threshold_ &&
big_iterations < max_big_iterations)
{
average_normal = Eigen::Vector4f::Zero ();
big_iterations ++;
// PCL_INFO ("%f ", error_residual);
PointT aux_point; aux_point.x = result_point(0); aux_point.y = result_point(1); aux_point.z = result_point(2);
tree_->radiusSearch (aux_point, 5*scale_, nn_indices, nn_distances);
float theta_normalization_factor = 0.0;
std::vector<float> theta (nn_indices.size ());
for (size_t nn_index_i = 0; nn_index_i < nn_indices.size (); ++nn_index_i)
{
float dist = nn_distances[nn_index_i];
float theta_i = exp ( (-1) * dist / scale_squared_);
theta_normalization_factor += theta_i;
average_normal += theta_i * normals_->points[nn_indices[nn_index_i]].getNormalVector4fMap ();
theta[nn_index_i] = theta_i;
}
average_normal /= theta_normalization_factor;
average_normal(3) = 0.0f;
average_normal.normalize ();
// find minimum along the normal
float e_residual_along_normal;
int small_iterations = 0;
int max_small_iterations = 10;
while (small_iterations < max_small_iterations)
{
small_iterations ++;
e_residual_along_normal = 0.0f;
for (size_t nn_index_i = 0; nn_index_i < nn_indices.size (); ++nn_index_i)
{
Eigen::Vector4f neighbor = input_->points[nn_indices[nn_index_i]].getVector4fMap ();
neighbor(3) = 0.0f;
float dot_product = average_normal.dot (neighbor - result_point);
e_residual_along_normal += theta[nn_index_i] * dot_product;
}
e_residual_along_normal /= theta_normalization_factor;
if (e_residual_along_normal < 1e-8) break;
result_point = result_point + e_residual_along_normal * average_normal;
}
if (small_iterations == max_small_iterations)
PCL_INFO ("passed the number of small iterations %d\n", small_iterations);
last_error_residual = error_residual;
error_residual = e_residual_along_normal;
PCL_INFO ("last %f current %f\n", last_error_residual, error_residual);
}
output_point.x = result_point(0);
output_point.y = result_point(1);
output_point.z = result_point(2);
output_normal = normals_->points[point_index];
if (big_iterations == max_big_iterations)
PCL_INFO ("passed the number of BIG iterations: %d\n", big_iterations);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SurfelSmoothing<PointT, PointNT>::computeSmoothedCloud (PointCloudInPtr &output_positions,
NormalCloudPtr &output_normals)
{
if (!initCompute ())
{
PCL_ERROR ("[pcl::SurfelSmoothing::computeSmoothedCloud]: SurfelSmoothing not initialized properly, skipping computeSmoothedCloud ().\n");
return;
}
tree_->setInputCloud (input_);
output_positions->points.resize (input_->points.size ());
output_normals->points.resize (input_->points.size ());
for (size_t i = 0; i < input_->points.size (); ++i)
{
smoothPoint (i, output_positions->points[i], output_normals->points[i]);
}
/*
// @todo make this a parameter
size_t min_iterations = 0;
size_t max_iterations = 200;
float last_residual = std::numeric_limits<float>::max (), residual;
for (size_t iteration = 0; iteration < max_iterations; ++iteration)
{
PCL_INFO ("Surfel smoothing iteration %u\n", iteration);
residual = smoothCloudIteration (output_positions, output_normals);
if (fabs (residual) > fabs (last_residual) -1e-8 && iteration > min_iterations) break;
// if (fabs (residual) < 0.23) break;
interm_cloud_ = output_positions;
interm_normals_ = output_normals;
last_residual = residual;
}*/
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SurfelSmoothing<PointT, PointNT>::extractSalientFeaturesBetweenScales (PointCloudInPtr &cloud2,
NormalCloudPtr &cloud2_normals,
boost::shared_ptr<std::vector<int> > &output_features)
{
if (interm_cloud_->points.size () != cloud2->points.size () ||
cloud2->points.size () != cloud2_normals->points.size ())
{
PCL_ERROR ("[pcl::SurfelSmoothing::extractSalientFeaturesBetweenScales]: Number of points in the clouds does not match.\n");
return;
}
std::vector<float> diffs (cloud2->points.size ());
for (size_t i = 0; i < cloud2->points.size (); ++i)
diffs[i] = cloud2_normals->points[i].getNormalVector4fMap ().dot (cloud2->points[i].getVector4fMap () -
interm_cloud_->points[i].getVector4fMap ());
std::vector<int> nn_indices;
std::vector<float> nn_distances;
output_features->resize (cloud2->points.size ());
for (size_t point_i = 0; point_i < cloud2->points.size (); ++point_i)
{
// Get neighbors
tree_->radiusSearch (point_i, scale_, nn_indices, nn_distances);
bool largest = true;
bool smallest = true;
for (std::vector<int>::iterator nn_index_it = nn_indices.begin (); nn_index_it != nn_indices.end (); ++nn_index_it)
{
if (diffs[point_i] < diffs[*nn_index_it])
largest = false;
else
smallest = false;
}
if (largest == true || smallest == true)
(*output_features)[point_i] = point_i;
}
}
#define PCL_INSTANTIATE_SurfelSmoothing(PointT,PointNT) template class PCL_EXPORTS pcl::SurfelSmoothing<PointT, PointNT>;
#endif /* PCL_SURFACE_IMPL_SURFEL_SMOOTHING_H_ */
<commit_msg>surfel smoothing mods<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
* $Id$
*/
#ifndef PCL_SURFACE_IMPL_SURFEL_SMOOTHING_H_
#define PCL_SURFACE_IMPL_SURFEL_SMOOTHING_H_
#include "pcl/surface/surfel_smoothing.h"
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/kdtree/organized_data.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SurfelSmoothing<PointT, PointNT>::initCompute ()
{
if (!PCLBase<PointT>::initCompute ())
return false;
if (!normals_)
{
PCL_ERROR ("SurfelSmoothing: normal cloud not set\n");
return false;
}
if (input_->points.size () != normals_->points.size ())
{
PCL_ERROR ("SurfelSmoothing: number of input points different from the number of given normals\n");
return false;
}
// Initialize the spatial locator
if (!tree_)
{
if (input_->isOrganized ())
tree_.reset (new pcl::OrganizedDataIndex<PointT> ());
else
tree_.reset (new pcl::KdTreeFLANN<PointT> (false));
}
// create internal copies of the input - these will be modified
interm_cloud_ = PointCloudInPtr (new PointCloudIn (*input_));
interm_normals_ = NormalCloudPtr (new NormalCloud (*normals_));
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> float
pcl::SurfelSmoothing<PointT, PointNT>::smoothCloudIteration (PointCloudInPtr &output_positions,
NormalCloudPtr &output_normals)
{
// PCL_INFO ("SurfelSmoothing: cloud smoothing iteration starting ...\n");
output_positions = PointCloudInPtr (new PointCloudIn);
output_positions->points.resize (interm_cloud_->points.size ());
output_normals = NormalCloudPtr (new NormalCloud);
output_normals->points.resize (interm_cloud_->points.size ());
std::vector<int> nn_indices;
std::vector<float> nn_distances;
std::vector<float> diffs (interm_cloud_->points.size ());
float total_residual = 0.0f;
for (size_t i = 0; i < interm_cloud_->points.size (); ++i)
{
Eigen::Vector4f smoothed_point = Eigen::Vector4f::Zero ();
Eigen::Vector4f smoothed_normal = Eigen::Vector4f::Zero ();
// get neighbors
// @todo using 5x the scale for searching instead of all the points to avoid O(N^2)
tree_->radiusSearch (interm_cloud_->points[i], 5*scale_, nn_indices, nn_distances);
float theta_normalization_factor = 0.0;
std::vector<float> theta (nn_indices.size ());
for (size_t nn_index_i = 0; nn_index_i < nn_indices.size (); ++nn_index_i)
{
float dist = pcl::squaredEuclideanDistance (interm_cloud_->points[i], input_->points[nn_indices[nn_index_i]]);//interm_cloud_->points[nn_indices[nn_index_i]]);
float theta_i = exp ( (-1) * dist / scale_squared_);
theta_normalization_factor += theta_i;
smoothed_normal += theta_i * interm_normals_->points[nn_indices[nn_index_i]].getNormalVector4fMap ();
theta[nn_index_i] = theta_i;
}
smoothed_normal /= theta_normalization_factor;
smoothed_normal(3) = 0.0f;
smoothed_normal.normalize ();
// find minimum along the normal
float e_residual;
smoothed_point = interm_cloud_->points[i].getVector4fMap ();
while (1)
{
e_residual = 0.0f;
smoothed_point(3) = 0.0f;
for (size_t nn_index_i = 0; nn_index_i < nn_indices.size (); ++nn_index_i)
{
Eigen::Vector4f neighbor = input_->points[nn_indices[nn_index_i]].getVector4fMap ();//interm_cloud_->points[nn_indices[nn_index_i]].getVector4fMap ();
neighbor(3) = 0.0f;
float dot_product = smoothed_normal.dot (neighbor - smoothed_point);
e_residual += theta[nn_index_i] * dot_product;// * dot_product;
}
e_residual /= theta_normalization_factor;
if (e_residual < 1e-5) break;
smoothed_point = smoothed_point + e_residual * smoothed_normal;
}
total_residual += e_residual;
output_positions->points[i].getVector4fMap () = smoothed_point;
output_normals->points[i].getNormalVector4fMap () = normals_->points[i].getNormalVector4fMap ();//smoothed_normal;
}
// std::cerr << "Total residual after iteration: " << total_residual << std::endl;
// PCL_INFO("SurfelSmoothing done iteration\n");
return total_residual;
}
template <typename PointT, typename PointNT> void
pcl::SurfelSmoothing<PointT, PointNT>::smoothPoint (size_t &point_index,
PointT &output_point,
PointNT &output_normal)
{
Eigen::Vector4f average_normal = Eigen::Vector4f::Zero ();
Eigen::Vector4f result_point = input_->points[point_index].getVector4fMap ();
result_point(3) = 0.0f;
// @todo parameter
float error_residual_threshold_ = 1e-3;
float error_residual = error_residual_threshold_ + 1;
float last_error_residual = error_residual + 100;
std::vector<int> nn_indices;
std::vector<float> nn_distances;
int big_iterations = 0;
int max_big_iterations = 500;
while (fabs (error_residual) < fabs (last_error_residual) -error_residual_threshold_ &&
big_iterations < max_big_iterations)
{
average_normal = Eigen::Vector4f::Zero ();
big_iterations ++;
PointT aux_point; aux_point.x = result_point(0); aux_point.y = result_point(1); aux_point.z = result_point(2);
tree_->radiusSearch (aux_point, 5*scale_, nn_indices, nn_distances);
float theta_normalization_factor = 0.0;
std::vector<float> theta (nn_indices.size ());
for (size_t nn_index_i = 0; nn_index_i < nn_indices.size (); ++nn_index_i)
{
float dist = nn_distances[nn_index_i];
float theta_i = exp ( (-1) * dist / scale_squared_);
theta_normalization_factor += theta_i;
average_normal += theta_i * normals_->points[nn_indices[nn_index_i]].getNormalVector4fMap ();
theta[nn_index_i] = theta_i;
}
average_normal /= theta_normalization_factor;
average_normal(3) = 0.0f;
average_normal.normalize ();
// find minimum along the normal
float e_residual_along_normal = 2, last_e_residual_along_normal = 3;
int small_iterations = 0;
int max_small_iterations = 10;
while ( fabs (e_residual_along_normal) < fabs (last_e_residual_along_normal) &&
small_iterations < max_small_iterations)
{
small_iterations ++;
e_residual_along_normal = 0.0f;
for (size_t nn_index_i = 0; nn_index_i < nn_indices.size (); ++nn_index_i)
{
Eigen::Vector4f neighbor = input_->points[nn_indices[nn_index_i]].getVector4fMap ();
neighbor(3) = 0.0f;
float dot_product = average_normal.dot (neighbor - result_point);
e_residual_along_normal += theta[nn_index_i] * dot_product;
}
e_residual_along_normal /= theta_normalization_factor;
if (e_residual_along_normal < 1e-3) break;
result_point = result_point + e_residual_along_normal * average_normal;
}
// if (small_iterations == max_small_iterations)
// PCL_INFO ("passed the number of small iterations %d\n", small_iterations);
last_error_residual = error_residual;
error_residual = e_residual_along_normal;
// PCL_INFO ("last %f current %f\n", last_error_residual, error_residual);
}
output_point.x = result_point(0);
output_point.y = result_point(1);
output_point.z = result_point(2);
output_normal = normals_->points[point_index];
if (big_iterations == max_big_iterations)
PCL_DEBUG ("[pcl::SurfelSmoothing::smoothPoint] Passed the number of BIG iterations: %d\n", big_iterations);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SurfelSmoothing<PointT, PointNT>::computeSmoothedCloud (PointCloudInPtr &output_positions,
NormalCloudPtr &output_normals)
{
if (!initCompute ())
{
PCL_ERROR ("[pcl::SurfelSmoothing::computeSmoothedCloud]: SurfelSmoothing not initialized properly, skipping computeSmoothedCloud ().\n");
return;
}
tree_->setInputCloud (input_);
output_positions->header = input_->header;
output_positions->height = input_->height;
output_positions->width = input_->width;
output_normals->header = input_->header;
output_normals->height = input_->height;
output_normals->width = input_->width;
output_positions->points.resize (input_->points.size ());
output_normals->points.resize (input_->points.size ());
for (size_t i = 0; i < input_->points.size (); ++i)
{
smoothPoint (i, output_positions->points[i], output_normals->points[i]);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SurfelSmoothing<PointT, PointNT>::extractSalientFeaturesBetweenScales (PointCloudInPtr &cloud2,
NormalCloudPtr &cloud2_normals,
boost::shared_ptr<std::vector<int> > &output_features)
{
if (interm_cloud_->points.size () != cloud2->points.size () ||
cloud2->points.size () != cloud2_normals->points.size ())
{
PCL_ERROR ("[pcl::SurfelSmoothing::extractSalientFeaturesBetweenScales]: Number of points in the clouds does not match.\n");
return;
}
std::vector<float> diffs (cloud2->points.size ());
for (size_t i = 0; i < cloud2->points.size (); ++i)
diffs[i] = cloud2_normals->points[i].getNormalVector4fMap ().dot (cloud2->points[i].getVector4fMap () -
interm_cloud_->points[i].getVector4fMap ());
std::vector<int> nn_indices;
std::vector<float> nn_distances;
output_features->resize (cloud2->points.size ());
for (size_t point_i = 0; point_i < cloud2->points.size (); ++point_i)
{
// Get neighbors
tree_->radiusSearch (point_i, scale_, nn_indices, nn_distances);
bool largest = true;
bool smallest = true;
for (std::vector<int>::iterator nn_index_it = nn_indices.begin (); nn_index_it != nn_indices.end (); ++nn_index_it)
{
if (diffs[point_i] < diffs[*nn_index_it])
largest = false;
else
smallest = false;
}
if (largest == true || smallest == true)
(*output_features)[point_i] = point_i;
}
}
#define PCL_INSTANTIATE_SurfelSmoothing(PointT,PointNT) template class PCL_EXPORTS pcl::SurfelSmoothing<PointT, PointNT>;
#endif /* PCL_SURFACE_IMPL_SURFEL_SMOOTHING_H_ */
<|endoftext|> |
<commit_before>/*
* Copyright 2010-2012 PathScale, 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* guard.cc: Functions for thread-safe static initialisation.
*
* Static values in C++ can be initialised lazily their first use. This file
* contains functions that are used to ensure that two threads attempting to
* initialize the same static do not call the constructor twice. This is
* important because constructors can have side effects, so calling the
* constructor twice may be very bad.
*
* Statics that require initialisation are protected by a 64-bit value. Any
* platform that can do 32-bit atomic test and set operations can use this
* value as a low-overhead lock. Because statics (in most sane code) are
* accessed far more times than they are initialised, this lock implementation
* is heavily optimised towards the case where the static has already been
* initialised.
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
#include "atomic.h"
// Older GCC doesn't define __LITTLE_ENDIAN__
#ifndef __LITTLE_ENDIAN__
// If __BYTE_ORDER__ is defined, use that instead
# ifdef __BYTE_ORDER__
# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define __LITTLE_ENDIAN__
# endif
// x86 and ARM are the most common little-endian CPUs, so let's have a
// special case for them (ARM is already special cased). Assume everything
// else is big endian.
# elif defined(__x86_64) || defined(__i386)
# define __LITTLE_ENDIAN__
# endif
#endif
/*
* The least significant bit of the guard variable indicates that the object
* has been initialised, the most significant bit is used for a spinlock.
*/
#ifdef __arm__
// ARM ABI - 32-bit guards.
typedef uint32_t guard_t;
typedef uint32_t lock_t;
static const uint32_t LOCKED = static_cast<guard_t>(1) << 31;
static const uint32_t INITIALISED = 1;
#define LOCK_PART(guard) (guard)
#define INIT_PART(guard) (guard)
#elif defined(_LP64)
typedef uint64_t guard_t;
typedef uint64_t lock_t;
# if defined(__LITTLE_ENDIAN__)
static const guard_t LOCKED = static_cast<guard_t>(1) << 63;
static const guard_t INITIALISED = 1;
# else
static const guard_t LOCKED = 1;
static const guard_t INITIALISED = static_cast<guard_t>(1) << 56;
# endif
#define LOCK_PART(guard) (guard)
#define INIT_PART(guard) (guard)
#else
# if defined(__LITTLE_ENDIAN__)
typedef struct {
uint32_t init_half;
uint32_t lock_half;
} guard_t;
typedef uint32_t lock_t;
static const uint32_t LOCKED = static_cast<lock_t>(1) << 31;
static const uint32_t INITIALISED = 1;
# else
typedef struct {
uint32_t init_half;
uint32_t lock_half;
} guard_t;
static_assert(sizeof(guard_t) == sizeof(uint64_t), "");
static const uint32_t LOCKED = 1;
static const uint32_t INITIALISED = static_cast<lock_t>(1) << 24;
# endif
#define LOCK_PART(guard) (&(guard)->lock_half)
#define INIT_PART(guard) (&(guard)->init_half)
#endif
static const lock_t INITIAL = 0;
/**
* Acquires a lock on a guard, returning 0 if the object has already been
* initialised, and 1 if it has not. If the object is already constructed then
* this function just needs to read a byte from memory and return.
*/
extern "C" int __cxa_guard_acquire(volatile guard_t *guard_object)
{
lock_t old, dst;
// Not an atomic read, doesn't establish a happens-before relationship, but
// if one is already established and we end up seeing an initialised state
// then it's a fast path, otherwise we'll do something more expensive than
// this test anyway...
if (INITIALISED == *INIT_PART(guard_object))
return 0;
// Spin trying to do the initialisation
for (;;)
{
// Loop trying to move the value of the guard from 0 (not
// locked, not initialised) to the locked-uninitialised
// position.
if (INIT_PART(guard_object) == LOCK_PART(guard_object))
dst = INITIALISED;
else
dst = LOCKED;
old = __sync_val_compare_and_swap(LOCK_PART(guard_object),
INITIAL, dst);
if (old == INITIAL) {
// Lock obtained. If lock and init bit are
// in separate words, check for init race.
if (INIT_PART(guard_object) == LOCK_PART(guard_object))
return 1;
if (INITIALISED != *INIT_PART(guard_object))
return 1;
// No need for a memory barrier here,
// see first comment.
*LOCK_PART(guard_object) = INITIAL;
return 0;
}
// If lock and init bit are in the same word, check again
// if we are done.
if (INIT_PART(guard_object) == LOCK_PART(guard_object) &&
old == INITIALISED)
return 0;
assert(old == LOCKED);
// Another thread holds the lock.
// If lock and init bit are in different words, check
// if we are done before yielding and looping.
if (INIT_PART(guard_object) != LOCK_PART(guard_object) &&
INITIALISED == *INIT_PART(guard_object))
return 0;
sched_yield();
}
}
/**
* Releases the lock without marking the object as initialised. This function
* is called if initialising a static causes an exception to be thrown.
*/
extern "C" void __cxa_guard_abort(volatile guard_t *guard_object)
{
__attribute__((unused))
bool reset = __sync_bool_compare_and_swap(LOCK_PART(guard_object),
LOCKED, INITIAL);
assert(reset);
}
/**
* Releases the guard and marks the object as initialised. This function is
* called after successful initialisation of a static.
*/
extern "C" void __cxa_guard_release(volatile guard_t *guard_object)
{
lock_t old;
if (INIT_PART(guard_object) == LOCK_PART(guard_object))
old = LOCKED;
else
old = INITIAL;
__attribute__((unused))
bool reset = __sync_bool_compare_and_swap(INIT_PART(guard_object),
old, INITIALISED);
assert(reset);
if (INIT_PART(guard_object) != LOCK_PART(guard_object))
*LOCK_PART(guard_object) = INITIAL;
}
<commit_msg>Revert the LP64 part of the last commit, thinking error.<commit_after>/*
* Copyright 2010-2012 PathScale, 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* guard.cc: Functions for thread-safe static initialisation.
*
* Static values in C++ can be initialised lazily their first use. This file
* contains functions that are used to ensure that two threads attempting to
* initialize the same static do not call the constructor twice. This is
* important because constructors can have side effects, so calling the
* constructor twice may be very bad.
*
* Statics that require initialisation are protected by a 64-bit value. Any
* platform that can do 32-bit atomic test and set operations can use this
* value as a low-overhead lock. Because statics (in most sane code) are
* accessed far more times than they are initialised, this lock implementation
* is heavily optimised towards the case where the static has already been
* initialised.
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
#include "atomic.h"
// Older GCC doesn't define __LITTLE_ENDIAN__
#ifndef __LITTLE_ENDIAN__
// If __BYTE_ORDER__ is defined, use that instead
# ifdef __BYTE_ORDER__
# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define __LITTLE_ENDIAN__
# endif
// x86 and ARM are the most common little-endian CPUs, so let's have a
// special case for them (ARM is already special cased). Assume everything
// else is big endian.
# elif defined(__x86_64) || defined(__i386)
# define __LITTLE_ENDIAN__
# endif
#endif
/*
* The least significant bit of the guard variable indicates that the object
* has been initialised, the most significant bit is used for a spinlock.
*/
#ifdef __arm__
// ARM ABI - 32-bit guards.
typedef uint32_t guard_t;
typedef uint32_t lock_t;
static const uint32_t LOCKED = static_cast<guard_t>(1) << 31;
static const uint32_t INITIALISED = 1;
#define LOCK_PART(guard) (guard)
#define INIT_PART(guard) (guard)
#elif defined(_LP64)
typedef uint64_t guard_t;
typedef uint64_t lock_t;
# if defined(__LITTLE_ENDIAN__)
static const guard_t LOCKED = static_cast<guard_t>(1) << 63;
static const guard_t INITIALISED = 1;
# else
static const guard_t LOCKED = 1;
static const guard_t INITIALISED = static_cast<guard_t>(1) << 56;
# endif
#define LOCK_PART(guard) (guard)
#define INIT_PART(guard) (guard)
#else
# if defined(__LITTLE_ENDIAN__)
typedef struct {
uint32_t init_half;
uint32_t lock_half;
} guard_t;
typedef uint32_t lock_t;
static const uint32_t LOCKED = static_cast<lock_t>(1) << 31;
static const uint32_t INITIALISED = 1;
# else
typedef struct {
uint32_t init_half;
uint32_t lock_half;
} guard_t;
static_assert(sizeof(guard_t) == sizeof(uint64_t), "");
static const uint32_t LOCKED = 1;
static const uint32_t INITIALISED = static_cast<lock_t>(1) << 24;
# endif
#define LOCK_PART(guard) (&(guard)->lock_half)
#define INIT_PART(guard) (&(guard)->init_half)
#endif
static const lock_t INITIAL = 0;
/**
* Acquires a lock on a guard, returning 0 if the object has already been
* initialised, and 1 if it has not. If the object is already constructed then
* this function just needs to read a byte from memory and return.
*/
extern "C" int __cxa_guard_acquire(volatile guard_t *guard_object)
{
lock_t old;
// Not an atomic read, doesn't establish a happens-before relationship, but
// if one is already established and we end up seeing an initialised state
// then it's a fast path, otherwise we'll do something more expensive than
// this test anyway...
if (INITIALISED == *INIT_PART(guard_object))
return 0;
// Spin trying to do the initialisation
for (;;)
{
// Loop trying to move the value of the guard from 0 (not
// locked, not initialised) to the locked-uninitialised
// position.
old = __sync_val_compare_and_swap(LOCK_PART(guard_object),
INITIAL, LOCKED);
if (old == INITIAL) {
// Lock obtained. If lock and init bit are
// in separate words, check for init race.
if (INIT_PART(guard_object) == LOCK_PART(guard_object))
return 1;
if (INITIALISED != *INIT_PART(guard_object))
return 1;
// No need for a memory barrier here,
// see first comment.
*LOCK_PART(guard_object) = INITIAL;
return 0;
}
// If lock and init bit are in the same word, check again
// if we are done.
if (INIT_PART(guard_object) == LOCK_PART(guard_object) &&
old == INITIALISED)
return 0;
assert(old == LOCKED);
// Another thread holds the lock.
// If lock and init bit are in different words, check
// if we are done before yielding and looping.
if (INIT_PART(guard_object) != LOCK_PART(guard_object) &&
INITIALISED == *INIT_PART(guard_object))
return 0;
sched_yield();
}
}
/**
* Releases the lock without marking the object as initialised. This function
* is called if initialising a static causes an exception to be thrown.
*/
extern "C" void __cxa_guard_abort(volatile guard_t *guard_object)
{
__attribute__((unused))
bool reset = __sync_bool_compare_and_swap(LOCK_PART(guard_object),
LOCKED, INITIAL);
assert(reset);
}
/**
* Releases the guard and marks the object as initialised. This function is
* called after successful initialisation of a static.
*/
extern "C" void __cxa_guard_release(volatile guard_t *guard_object)
{
lock_t old;
if (INIT_PART(guard_object) == LOCK_PART(guard_object))
old = LOCKED;
else
old = INITIAL;
__attribute__((unused))
bool reset = __sync_bool_compare_and_swap(INIT_PART(guard_object),
old, INITIALISED);
assert(reset);
if (INIT_PART(guard_object) != LOCK_PART(guard_object))
*LOCK_PART(guard_object) = INITIAL;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 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 "EncodeDecodeTest.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "audio_coding_module.h"
#include "common_types.h"
#include "gtest/gtest.h"
#include "trace.h"
#include "testsupport/fileutils.h"
#include "utility.h"
namespace webrtc {
TestPacketization::TestPacketization(RTPStream *rtpStream,
WebRtc_UWord16 frequency)
: _rtpStream(rtpStream),
_frequency(frequency),
_seqNo(0) {
}
TestPacketization::~TestPacketization() { }
WebRtc_Word32 TestPacketization::SendData(
const FrameType /* frameType */,
const WebRtc_UWord8 payloadType,
const WebRtc_UWord32 timeStamp,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadSize,
const RTPFragmentationHeader* /* fragmentation */) {
_rtpStream->Write(payloadType, timeStamp, _seqNo++, payloadData, payloadSize,
_frequency);
return 1;
}
Sender::Sender()
: _acm(NULL),
_pcmFile(),
_audioFrame(),
_payloadSize(0),
_timeStamp(0),
_packetization(NULL) {
}
void Sender::Setup(AudioCodingModule *acm, RTPStream *rtpStream) {
acm->InitializeSender();
struct CodecInst sendCodec;
int noOfCodecs = acm->NumberOfCodecs();
int codecNo;
if (testMode == 1) {
// Set the codec, input file, and parameters for the current test.
codecNo = codeId;
// Use same input file for now.
char fileName[] = "./data/audio_coding/testfile32kHz.pcm";
_pcmFile.Open(fileName, 32000, "rb");
} else if (testMode == 0) {
// Set the codec, input file, and parameters for the current test.
codecNo = codeId;
acm->Codec(codecNo, sendCodec);
// Use same input file for now.
char fileName[] = "./data/audio_coding/testfile32kHz.pcm";
_pcmFile.Open(fileName, 32000, "rb");
} else {
printf("List of supported codec.\n");
for (int n = 0; n < noOfCodecs; n++) {
acm->Codec(n, sendCodec);
printf("%d %s\n", n, sendCodec.plname);
}
printf("Choose your codec:");
ASSERT_GT(scanf("%d", &codecNo), 0);
char fileName[] = "./data/audio_coding/testfile32kHz.pcm";
_pcmFile.Open(fileName, 32000, "rb");
}
acm->Codec(codecNo, sendCodec);
if (!strcmp(sendCodec.plname, "CELT")) {
sendCodec.channels = 1;
}
acm->RegisterSendCodec(sendCodec);
_packetization = new TestPacketization(rtpStream, sendCodec.plfreq);
if (acm->RegisterTransportCallback(_packetization) < 0) {
printf("Registering Transport Callback failed, for run: codecId: %d: --\n",
codeId);
}
_acm = acm;
}
void Sender::Teardown() {
_pcmFile.Close();
delete _packetization;
}
bool Sender::Add10MsData() {
if (!_pcmFile.EndOfFile()) {
_pcmFile.Read10MsData(_audioFrame);
WebRtc_Word32 ok = _acm->Add10MsData(_audioFrame);
if (ok != 0) {
printf("Error calling Add10MsData: for run: codecId: %d\n", codeId);
exit(1);
}
return true;
}
return false;
}
bool Sender::Process() {
WebRtc_Word32 ok = _acm->Process();
if (ok < 0) {
printf("Error calling Add10MsData: for run: codecId: %d\n", codeId);
exit(1);
}
return true;
}
void Sender::Run() {
while (true) {
if (!Add10MsData()) {
break;
}
if (!Process()) { // This could be done in a processing thread
break;
}
}
}
Receiver::Receiver()
: _playoutLengthSmpls(WEBRTC_10MS_PCM_AUDIO),
_payloadSizeBytes(MAX_INCOMING_PAYLOAD) {
}
void Receiver::Setup(AudioCodingModule *acm, RTPStream *rtpStream) {
struct CodecInst recvCodec;
int noOfCodecs;
acm->InitializeReceiver();
noOfCodecs = acm->NumberOfCodecs();
for (int i = 0; i < noOfCodecs; i++) {
acm->Codec((WebRtc_UWord8) i, recvCodec);
if (acm->RegisterReceiveCodec(recvCodec) != 0) {
printf("Unable to register codec: for run: codecId: %d\n", codeId);
exit(1);
}
}
char filename[128];
_rtpStream = rtpStream;
int playSampFreq;
if (testMode == 1) {
playSampFreq=recvCodec.plfreq;
//output file for current run
sprintf(filename,"%s/out%dFile.pcm", webrtc::test::OutputPath().c_str(),
codeId);
_pcmFile.Open(filename, recvCodec.plfreq, "wb+");
} else if (testMode == 0) {
playSampFreq=32000;
//output file for current run
sprintf(filename, "%s/encodeDecode_out%d.pcm",
webrtc::test::OutputPath().c_str(), codeId);
_pcmFile.Open(filename, 32000/*recvCodec.plfreq*/, "wb+");
} else {
printf("\nValid output frequencies:\n");
printf("8000\n16000\n32000\n-1,");
printf("which means output freq equal to received signal freq");
printf("\n\nChoose output sampling frequency: ");
ASSERT_GT(scanf("%d", &playSampFreq), 0);
sprintf(filename, "%s/outFile.pcm", webrtc::test::OutputPath().c_str());
_pcmFile.Open(filename, 32000, "wb+");
}
_realPayloadSizeBytes = 0;
_playoutBuffer = new WebRtc_Word16[WEBRTC_10MS_PCM_AUDIO];
_frequency = playSampFreq;
_acm = acm;
_firstTime = true;
}
void Receiver::Teardown() {
delete [] _playoutBuffer;
_pcmFile.Close();
if (testMode > 1)
Trace::ReturnTrace();
}
bool Receiver::IncomingPacket() {
if (!_rtpStream->EndOfFile()) {
if (_firstTime) {
_firstTime = false;
_realPayloadSizeBytes = _rtpStream->Read(&_rtpInfo, _incomingPayload,
_payloadSizeBytes, &_nextTime);
if (_realPayloadSizeBytes == 0) {
if (_rtpStream->EndOfFile()) {
_firstTime = true;
return true;
} else {
printf("Error in reading incoming payload.\n");
return false;
}
}
}
WebRtc_Word32 ok = _acm->IncomingPacket(_incomingPayload,
_realPayloadSizeBytes, _rtpInfo);
if (ok != 0) {
printf("Error when inserting packet to ACM, for run: codecId: %d\n",
codeId);
}
_realPayloadSizeBytes = _rtpStream->Read(&_rtpInfo, _incomingPayload,
_payloadSizeBytes, &_nextTime);
if (_realPayloadSizeBytes == 0 && _rtpStream->EndOfFile()) {
_firstTime = true;
}
}
return true;
}
bool Receiver::PlayoutData() {
AudioFrame audioFrame;
if (_acm->PlayoutData10Ms(_frequency, audioFrame) != 0) {
printf("Error when calling PlayoutData10Ms, for run: codecId: %d\n",
codeId);
exit(1);
}
if (_playoutLengthSmpls == 0) {
return false;
}
_pcmFile.Write10MsData(audioFrame.data_,
audioFrame.samples_per_channel_);
return true;
}
void Receiver::Run() {
WebRtc_UWord8 counter500Ms = 50;
WebRtc_UWord32 clock = 0;
while (counter500Ms > 0) {
if (clock == 0 || clock >= _nextTime) {
IncomingPacket();
if (clock == 0) {
clock = _nextTime;
}
}
if ((clock % 10) == 0) {
if (!PlayoutData()) {
clock++;
continue;
}
}
if (_rtpStream->EndOfFile()) {
counter500Ms--;
}
clock++;
}
}
EncodeDecodeTest::EncodeDecodeTest() {
_testMode = 2;
Trace::CreateTrace();
Trace::SetTraceFile("acm_encdec_test.txt");
}
EncodeDecodeTest::EncodeDecodeTest(int testMode) {
//testMode == 0 for autotest
//testMode == 1 for testing all codecs/parameters
//testMode > 1 for specific user-input test (as it was used before)
_testMode = testMode;
if(_testMode != 0) {
Trace::CreateTrace();
Trace::SetTraceFile("acm_encdec_test.txt");
}
}
void EncodeDecodeTest::Perform() {
if (_testMode == 0) {
printf("Running Encode/Decode Test");
WEBRTC_TRACE(webrtc::kTraceStateInfo, webrtc::kTraceAudioCoding, -1,
"---------- EncodeDecodeTest ----------");
}
int numCodecs = 1;
int codePars[3]; // Frequency, packet size, rate.
int numPars[52]; // Number of codec parameters sets (freq, pacsize, rate)
// to test, for a given codec.
codePars[0] = 0;
codePars[1] = 0;
codePars[2] = 0;
AudioCodingModule *acmTmp = AudioCodingModule::Create(0);
struct CodecInst sendCodecTmp;
numCodecs = acmTmp->NumberOfCodecs();
AudioCodingModule::Destroy(acmTmp);
if (_testMode == 1) {
printf("List of supported codec.\n");
}
if (_testMode != 2) {
for (int n = 0; n < numCodecs; n++) {
acmTmp->Codec(n, sendCodecTmp);
if (STR_CASE_CMP(sendCodecTmp.plname, "telephone-event") == 0) {
numPars[n] = 0;
} else if (STR_CASE_CMP(sendCodecTmp.plname, "cn") == 0) {
numPars[n] = 0;
} else if (STR_CASE_CMP(sendCodecTmp.plname, "red") == 0) {
numPars[n] = 0;
} else if (sendCodecTmp.channels == 2) {
numPars[n] = 0;
} else {
numPars[n] = 1;
if (_testMode == 1) {
printf("%d %s\n", n, sendCodecTmp.plname);
}
}
}
} else {
numCodecs = 1;
numPars[0] = 1;
}
_receiver.testMode = _testMode;
// Loop over all mono codecs:
for (int codeId = 0; codeId < numCodecs; codeId++) {
// Only encode using real mono encoders, not telephone-event and cng.
for (int loopPars = 1; loopPars <= numPars[codeId]; loopPars++) {
if (_testMode == 1) {
printf("\n");
printf("***FOR RUN: codeId: %d\n", codeId);
printf("\n");
} else if (_testMode == 0) {
printf(".");
}
EncodeToFile(1, codeId, codePars, _testMode);
AudioCodingModule *acm = AudioCodingModule::Create(10);
RTPFile rtpFile;
std::string fileName = webrtc::test::OutputPath() + "outFile.rtp";
rtpFile.Open(fileName.c_str(), "rb");
_receiver.codeId = codeId;
rtpFile.ReadHeader();
_receiver.Setup(acm, &rtpFile);
_receiver.Run();
_receiver.Teardown();
rtpFile.Close();
AudioCodingModule::Destroy(acm);
if (_testMode == 1) {
printf("***COMPLETED RUN FOR: codecID: %d ***\n", codeId);
}
}
}
if (_testMode == 0) {
printf("Done!\n");
}
if (_testMode == 1)
Trace::ReturnTrace();
}
void EncodeDecodeTest::EncodeToFile(int fileType, int codeId, int* codePars,
int testMode) {
AudioCodingModule *acm = AudioCodingModule::Create(0);
RTPFile rtpFile;
std::string fileName = webrtc::test::OutputPath() + "outFile.rtp";
rtpFile.Open(fileName.c_str(), "wb+");
rtpFile.WriteHeader();
//for auto_test and logging
_sender.testMode = testMode;
_sender.codeId = codeId;
_sender.Setup(acm, &rtpFile);
struct CodecInst sendCodecInst;
if (acm->SendCodec(sendCodecInst) >= 0) {
_sender.Run();
}
_sender.Teardown();
rtpFile.Close();
AudioCodingModule::Destroy(acm);
}
} // namespace webrtc
<commit_msg>ACM: Too short char vector<commit_after>/*
* Copyright (c) 2012 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 "EncodeDecodeTest.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "audio_coding_module.h"
#include "common_types.h"
#include "gtest/gtest.h"
#include "trace.h"
#include "testsupport/fileutils.h"
#include "utility.h"
namespace webrtc {
TestPacketization::TestPacketization(RTPStream *rtpStream,
WebRtc_UWord16 frequency)
: _rtpStream(rtpStream),
_frequency(frequency),
_seqNo(0) {
}
TestPacketization::~TestPacketization() { }
WebRtc_Word32 TestPacketization::SendData(
const FrameType /* frameType */,
const WebRtc_UWord8 payloadType,
const WebRtc_UWord32 timeStamp,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadSize,
const RTPFragmentationHeader* /* fragmentation */) {
_rtpStream->Write(payloadType, timeStamp, _seqNo++, payloadData, payloadSize,
_frequency);
return 1;
}
Sender::Sender()
: _acm(NULL),
_pcmFile(),
_audioFrame(),
_payloadSize(0),
_timeStamp(0),
_packetization(NULL) {
}
void Sender::Setup(AudioCodingModule *acm, RTPStream *rtpStream) {
acm->InitializeSender();
struct CodecInst sendCodec;
int noOfCodecs = acm->NumberOfCodecs();
int codecNo;
if (testMode == 1) {
// Set the codec, input file, and parameters for the current test.
codecNo = codeId;
// Use same input file for now.
char fileName[] = "./data/audio_coding/testfile32kHz.pcm";
_pcmFile.Open(fileName, 32000, "rb");
} else if (testMode == 0) {
// Set the codec, input file, and parameters for the current test.
codecNo = codeId;
acm->Codec(codecNo, sendCodec);
// Use same input file for now.
char fileName[] = "./data/audio_coding/testfile32kHz.pcm";
_pcmFile.Open(fileName, 32000, "rb");
} else {
printf("List of supported codec.\n");
for (int n = 0; n < noOfCodecs; n++) {
acm->Codec(n, sendCodec);
printf("%d %s\n", n, sendCodec.plname);
}
printf("Choose your codec:");
ASSERT_GT(scanf("%d", &codecNo), 0);
char fileName[] = "./data/audio_coding/testfile32kHz.pcm";
_pcmFile.Open(fileName, 32000, "rb");
}
acm->Codec(codecNo, sendCodec);
if (!strcmp(sendCodec.plname, "CELT")) {
sendCodec.channels = 1;
}
acm->RegisterSendCodec(sendCodec);
_packetization = new TestPacketization(rtpStream, sendCodec.plfreq);
if (acm->RegisterTransportCallback(_packetization) < 0) {
printf("Registering Transport Callback failed, for run: codecId: %d: --\n",
codeId);
}
_acm = acm;
}
void Sender::Teardown() {
_pcmFile.Close();
delete _packetization;
}
bool Sender::Add10MsData() {
if (!_pcmFile.EndOfFile()) {
_pcmFile.Read10MsData(_audioFrame);
WebRtc_Word32 ok = _acm->Add10MsData(_audioFrame);
if (ok != 0) {
printf("Error calling Add10MsData: for run: codecId: %d\n", codeId);
exit(1);
}
return true;
}
return false;
}
bool Sender::Process() {
WebRtc_Word32 ok = _acm->Process();
if (ok < 0) {
printf("Error calling Add10MsData: for run: codecId: %d\n", codeId);
exit(1);
}
return true;
}
void Sender::Run() {
while (true) {
if (!Add10MsData()) {
break;
}
if (!Process()) { // This could be done in a processing thread
break;
}
}
}
Receiver::Receiver()
: _playoutLengthSmpls(WEBRTC_10MS_PCM_AUDIO),
_payloadSizeBytes(MAX_INCOMING_PAYLOAD) {
}
void Receiver::Setup(AudioCodingModule *acm, RTPStream *rtpStream) {
struct CodecInst recvCodec;
int noOfCodecs;
acm->InitializeReceiver();
noOfCodecs = acm->NumberOfCodecs();
for (int i = 0; i < noOfCodecs; i++) {
acm->Codec((WebRtc_UWord8) i, recvCodec);
if (acm->RegisterReceiveCodec(recvCodec) != 0) {
printf("Unable to register codec: for run: codecId: %d\n", codeId);
exit(1);
}
}
char filename[256];
_rtpStream = rtpStream;
int playSampFreq;
if (testMode == 1) {
playSampFreq=recvCodec.plfreq;
//output file for current run
sprintf(filename,"%s/out%dFile.pcm", webrtc::test::OutputPath().c_str(),
codeId);
_pcmFile.Open(filename, recvCodec.plfreq, "wb+");
} else if (testMode == 0) {
playSampFreq=32000;
//output file for current run
sprintf(filename, "%s/encodeDecode_out%d.pcm",
webrtc::test::OutputPath().c_str(), codeId);
_pcmFile.Open(filename, 32000/*recvCodec.plfreq*/, "wb+");
} else {
printf("\nValid output frequencies:\n");
printf("8000\n16000\n32000\n-1,");
printf("which means output freq equal to received signal freq");
printf("\n\nChoose output sampling frequency: ");
ASSERT_GT(scanf("%d", &playSampFreq), 0);
sprintf(filename, "%s/outFile.pcm", webrtc::test::OutputPath().c_str());
_pcmFile.Open(filename, 32000, "wb+");
}
_realPayloadSizeBytes = 0;
_playoutBuffer = new WebRtc_Word16[WEBRTC_10MS_PCM_AUDIO];
_frequency = playSampFreq;
_acm = acm;
_firstTime = true;
}
void Receiver::Teardown() {
delete [] _playoutBuffer;
_pcmFile.Close();
if (testMode > 1)
Trace::ReturnTrace();
}
bool Receiver::IncomingPacket() {
if (!_rtpStream->EndOfFile()) {
if (_firstTime) {
_firstTime = false;
_realPayloadSizeBytes = _rtpStream->Read(&_rtpInfo, _incomingPayload,
_payloadSizeBytes, &_nextTime);
if (_realPayloadSizeBytes == 0) {
if (_rtpStream->EndOfFile()) {
_firstTime = true;
return true;
} else {
printf("Error in reading incoming payload.\n");
return false;
}
}
}
WebRtc_Word32 ok = _acm->IncomingPacket(_incomingPayload,
_realPayloadSizeBytes, _rtpInfo);
if (ok != 0) {
printf("Error when inserting packet to ACM, for run: codecId: %d\n",
codeId);
}
_realPayloadSizeBytes = _rtpStream->Read(&_rtpInfo, _incomingPayload,
_payloadSizeBytes, &_nextTime);
if (_realPayloadSizeBytes == 0 && _rtpStream->EndOfFile()) {
_firstTime = true;
}
}
return true;
}
bool Receiver::PlayoutData() {
AudioFrame audioFrame;
if (_acm->PlayoutData10Ms(_frequency, audioFrame) != 0) {
printf("Error when calling PlayoutData10Ms, for run: codecId: %d\n",
codeId);
exit(1);
}
if (_playoutLengthSmpls == 0) {
return false;
}
_pcmFile.Write10MsData(audioFrame.data_,
audioFrame.samples_per_channel_);
return true;
}
void Receiver::Run() {
WebRtc_UWord8 counter500Ms = 50;
WebRtc_UWord32 clock = 0;
while (counter500Ms > 0) {
if (clock == 0 || clock >= _nextTime) {
IncomingPacket();
if (clock == 0) {
clock = _nextTime;
}
}
if ((clock % 10) == 0) {
if (!PlayoutData()) {
clock++;
continue;
}
}
if (_rtpStream->EndOfFile()) {
counter500Ms--;
}
clock++;
}
}
EncodeDecodeTest::EncodeDecodeTest() {
_testMode = 2;
Trace::CreateTrace();
Trace::SetTraceFile("acm_encdec_test.txt");
}
EncodeDecodeTest::EncodeDecodeTest(int testMode) {
//testMode == 0 for autotest
//testMode == 1 for testing all codecs/parameters
//testMode > 1 for specific user-input test (as it was used before)
_testMode = testMode;
if(_testMode != 0) {
Trace::CreateTrace();
Trace::SetTraceFile("acm_encdec_test.txt");
}
}
void EncodeDecodeTest::Perform() {
if (_testMode == 0) {
printf("Running Encode/Decode Test");
WEBRTC_TRACE(webrtc::kTraceStateInfo, webrtc::kTraceAudioCoding, -1,
"---------- EncodeDecodeTest ----------");
}
int numCodecs = 1;
int codePars[3]; // Frequency, packet size, rate.
int numPars[52]; // Number of codec parameters sets (freq, pacsize, rate)
// to test, for a given codec.
codePars[0] = 0;
codePars[1] = 0;
codePars[2] = 0;
AudioCodingModule* acm = AudioCodingModule::Create(0);
struct CodecInst sendCodecTmp;
numCodecs = acm->NumberOfCodecs();
if (_testMode == 1) {
printf("List of supported codec.\n");
}
if (_testMode != 2) {
for (int n = 0; n < numCodecs; n++) {
acm->Codec(n, sendCodecTmp);
if (STR_CASE_CMP(sendCodecTmp.plname, "telephone-event") == 0) {
numPars[n] = 0;
} else if (STR_CASE_CMP(sendCodecTmp.plname, "cn") == 0) {
numPars[n] = 0;
} else if (STR_CASE_CMP(sendCodecTmp.plname, "red") == 0) {
numPars[n] = 0;
} else if (sendCodecTmp.channels == 2) {
numPars[n] = 0;
} else {
numPars[n] = 1;
if (_testMode == 1) {
printf("%d %s\n", n, sendCodecTmp.plname);
}
}
}
} else {
numCodecs = 1;
numPars[0] = 1;
}
_receiver.testMode = _testMode;
// Loop over all mono codecs:
for (int codeId = 0; codeId < numCodecs; codeId++) {
// Only encode using real mono encoders, not telephone-event and cng.
for (int loopPars = 1; loopPars <= numPars[codeId]; loopPars++) {
if (_testMode == 1) {
printf("\n");
printf("***FOR RUN: codeId: %d\n", codeId);
printf("\n");
} else if (_testMode == 0) {
printf(".");
}
EncodeToFile(1, codeId, codePars, _testMode);
RTPFile rtpFile;
std::string fileName = webrtc::test::OutputPath() + "outFile.rtp";
rtpFile.Open(fileName.c_str(), "rb");
_receiver.codeId = codeId;
rtpFile.ReadHeader();
_receiver.Setup(acm, &rtpFile);
_receiver.Run();
_receiver.Teardown();
rtpFile.Close();
if (_testMode == 1) {
printf("***COMPLETED RUN FOR: codecID: %d ***\n", codeId);
}
}
}
AudioCodingModule::Destroy(acm);
if (_testMode == 0) {
printf("Done!\n");
}
if (_testMode == 1)
Trace::ReturnTrace();
}
void EncodeDecodeTest::EncodeToFile(int fileType, int codeId, int* codePars,
int testMode) {
AudioCodingModule* acm = AudioCodingModule::Create(1);
RTPFile rtpFile;
std::string fileName = webrtc::test::OutputPath() + "outFile.rtp";
rtpFile.Open(fileName.c_str(), "wb+");
rtpFile.WriteHeader();
//for auto_test and logging
_sender.testMode = testMode;
_sender.codeId = codeId;
_sender.Setup(acm, &rtpFile);
struct CodecInst sendCodecInst;
if (acm->SendCodec(sendCodecInst) >= 0) {
_sender.Run();
}
_sender.Teardown();
rtpFile.Close();
AudioCodingModule::Destroy(acm);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#include "PFCRFFMaterial.h"
template<>
InputParameters validParams<PFCRFFMaterial>()
{
InputParameters params = validParams<Material>();
params.addRequiredParam<unsigned int>("num_L", "specifies the number of complex L variables will be solved for");
return params;
}
PFCRFFMaterial::PFCRFFMaterial(const std::string & name,
InputParameters parameters) :
Material(name, parameters),
_M(declareProperty<Real>("M")),
_alpha_R_0(declareProperty<Real>("alpha_R_0")),
_alpha_I_0(declareProperty<Real>("alpha_I_0")),
_A_R_0(declareProperty<Real>("A_R_0")),
_A_I_0(declareProperty<Real>("A_I_0")),
_alpha_R_1(declareProperty<Real>("alpha_R_1")),
_alpha_I_1(declareProperty<Real>("alpha_I_1")),
_A_R_1(declareProperty<Real>("A_R_1")),
_A_I_1(declareProperty<Real>("A_I_1")),
_alpha_R_2(declareProperty<Real>("alpha_R_2")),
_alpha_I_2(declareProperty<Real>("alpha_I_2")),
_A_R_2(declareProperty<Real>("A_R_2")),
_A_I_2(declareProperty<Real>("A_I_2")),
_alpha_R_3(declareProperty<Real>("alpha_R_3")),
_alpha_I_3(declareProperty<Real>("alpha_I_3")),
_A_R_3(declareProperty<Real>("A_R_3")),
_A_I_3(declareProperty<Real>("A_I_3")),
_alpha_R_4(declareProperty<Real>("alpha_R_4")),
_alpha_I_4(declareProperty<Real>("alpha_I_4")),
_A_R_4(declareProperty<Real>("A_R_4")),
_A_I_4(declareProperty<Real>("A_I_4")),
_num_L(getParam<unsigned int>("num_L"))
{
}
void
PFCRFFMaterial::computeQpProperties()
{
// Mobility
_M[_qp] = 1.0;
// Alpha and A constants
if (_num_L == 3)
{
// alpha constants
_alpha_R_0[_qp] = 2.429134088464706;
_alpha_I_0[_qp] = 0.0;
_alpha_R_1[_qp] = 18.943264072194637;
_alpha_I_1[_qp] = 9.349446845430961;
_alpha_R_2[_qp] = 3.972333899872749;
_alpha_I_2[_qp] = 6.499130135847140;
// A constants
_A_R_0[_qp] = -63.1;
_A_I_0[_qp] = 9.910190130869531e-15;
_A_R_1[_qp] = 10.501019149026910;
_A_I_1[_qp] = 2.363585467971611;
_A_R_2[_qp] = 34.212475550666770;
_A_I_2[_qp] = -42.274652746496530;
}
else if (_num_L == 5)
{
// alpha constants
_alpha_R_0[_qp] = 2.429134088464706;
_alpha_I_0[_qp] = 0.0;
_alpha_R_1[_qp] = -3.972333899872749;
_alpha_I_1[_qp] = 6.499130135847140;
_alpha_R_2[_qp] = -3.972333899872749;
_alpha_I_2[_qp] = -6.499130135847140;
_alpha_R_3[_qp] = -18.943264072194637;
_alpha_I_3[_qp] = 9.349446845430961;
_alpha_R_4[_qp] = -18.943264072194637;
_alpha_I_4[_qp] = -9.349446845430961;
// A constants
_A_R_0[_qp] = -1.282478656880326e02;
_A_I_0[_qp] = 9.910190130869531e-15;
_A_R_1[_qp] = 34.212475550662354;
_A_I_1[_qp] = 42.274652746493430;
_A_R_2[_qp] = 34.212475550666770;
_A_I_2[_qp] = -42.274652746496530;
_A_R_3[_qp] = 10.501019149011636;
_A_I_3[_qp] = -2.363585468012575;
_A_R_4[_qp] = 10.501019149026910;
_A_I_4[_qp] = 2.363585467971611;
}
}
/*
_alpha_R_0[_qp] = 2.412;
_alpha_I_0[_qp] = 0.0;
_alpha_R_1[_qp] = -18.62;
_alpha_I_1[_qp] = 9.968;
_alpha_R_2[_qp] = -51.8;
_alpha_I_2[_qp] = -18.58;
_alpha_R_3[_qp] = -104.6;
_alpha_I_3[_qp] = -19.21;
_alpha_R_4[_qp] = -3.88;
_alpha_I_4[_qp] = 6.545;
// A constants
_A_R_0[_qp] = -63.1;
_A_I_0[_qp] = 0.0;
_A_R_1[_qp] = 12.52;
_A_I_1[_qp] = -3.607;
_A_R_2[_qp] = 3.88;
_A_I_2[_qp] = 0.7762;
_A_R_3[_qp] = 0.9984;
_A_I_3[_qp] = 0.1591;
_A_R_4[_qp] = 36.7;
_A_I_4[_qp] = 42.66;
else if (_num_L == 5)
{
// alpha constants
_alpha_R_0[_qp] = 2.4887266073084095552303551812656223773956298828125;
_alpha_I_0[_qp] = 0.0;
_alpha_R_1[_qp] = -19.2733746470461682065433706156909465789794921875;
_alpha_I_1[_qp] = -9.18277447910810451503493823111057281494140625;
_alpha_R_2[_qp] = -19.2733746470461682065433706156909465789794921875;
_alpha_I_2[_qp] = 9.18277447910810451503493823111057281494140625;
_alpha_R_3[_qp] = -3.8695517424123173633176975272363051772117614746094;
_alpha_I_3[_qp] = 6.7955256217773678528715208813082426786422729492188;
_alpha_R_4[_qp] = -3.8695517424123173633176975272363051772117614746094;
_alpha_I_4[_qp] = -6.7955256217773678528715208813082426786422729492188;
// A constants
_A_R_0[_qp] = -133.2927098034036816898151300847530364990234375;
_A_I_0[_qp] = 0.0;
_A_R_1[_qp] = 10.728194854990965367846911249216645956039428710938;
_A_I_1[_qp] = 2.5027746492227604946378960448782891035079956054688;
_A_R_2[_qp] = 10.728194854990965367846911249216645956039428710938;
_A_I_2[_qp] = -2.5027746492227604946378960448782891035079956054688;
_A_R_3[_qp] = 35.9742594324134188354946672916412353515625;
_A_I_3[_qp] = 45.6070815722133602321264334022998809814453125;
_A_R_4[_qp] = 35.9742594324134188354946672916412353515625;
_A_I_4[_qp] = -45.6070815722133602321264334022998809814453125;
}
*/
<commit_msg>New parameters for 3rd RFF PFC model (#109)<commit_after>#include "PFCRFFMaterial.h"
template<>
InputParameters validParams<PFCRFFMaterial>()
{
InputParameters params = validParams<Material>();
params.addRequiredParam<unsigned int>("num_L", "specifies the number of complex L variables will be solved for");
return params;
}
PFCRFFMaterial::PFCRFFMaterial(const std::string & name,
InputParameters parameters) :
Material(name, parameters),
_M(declareProperty<Real>("M")),
_alpha_R_0(declareProperty<Real>("alpha_R_0")),
_alpha_I_0(declareProperty<Real>("alpha_I_0")),
_A_R_0(declareProperty<Real>("A_R_0")),
_A_I_0(declareProperty<Real>("A_I_0")),
_alpha_R_1(declareProperty<Real>("alpha_R_1")),
_alpha_I_1(declareProperty<Real>("alpha_I_1")),
_A_R_1(declareProperty<Real>("A_R_1")),
_A_I_1(declareProperty<Real>("A_I_1")),
_alpha_R_2(declareProperty<Real>("alpha_R_2")),
_alpha_I_2(declareProperty<Real>("alpha_I_2")),
_A_R_2(declareProperty<Real>("A_R_2")),
_A_I_2(declareProperty<Real>("A_I_2")),
_alpha_R_3(declareProperty<Real>("alpha_R_3")),
_alpha_I_3(declareProperty<Real>("alpha_I_3")),
_A_R_3(declareProperty<Real>("A_R_3")),
_A_I_3(declareProperty<Real>("A_I_3")),
_alpha_R_4(declareProperty<Real>("alpha_R_4")),
_alpha_I_4(declareProperty<Real>("alpha_I_4")),
_A_R_4(declareProperty<Real>("A_R_4")),
_A_I_4(declareProperty<Real>("A_I_4")),
_num_L(getParam<unsigned int>("num_L"))
{
}
void
PFCRFFMaterial::computeQpProperties()
{
// Mobility
_M[_qp] = 1.0;
// Alpha and A constants
if (_num_L == 3)
{
// alpha constants
_alpha_R_0[_qp] = 2.352788316033853;
_alpha_I_0[_qp] = 0.0;
_alpha_R_1[_qp] = -4.371217046300305;
_alpha_I_1[_qp] = 6.153993830413678;
_alpha_R_2[_qp] = -4.371217046300305;
_alpha_I_2[_qp] = -6.153993830413678;
// A constants
_A_R_0[_qp] = -1.254832460194660e2;
_A_I_0[_qp] = 4.141043034348927e-15;
_A_R_1[_qp] = 24.798843718179786;
_A_I_1[_qp] = 37.678064436502760;
_A_R_2[_qp] = 24.798843718179786;
_A_I_2[_qp] = -37.678064436502760;
}
else if (_num_L == 5)
{
// alpha constants
_alpha_R_0[_qp] = 2.429134088464706;
_alpha_I_0[_qp] = 0.0;
_alpha_R_1[_qp] = -3.972333899872749;
_alpha_I_1[_qp] = 6.499130135847140;
_alpha_R_2[_qp] = -3.972333899872749;
_alpha_I_2[_qp] = -6.499130135847140;
_alpha_R_3[_qp] = -18.943264072194637;
_alpha_I_3[_qp] = 9.349446845430961;
_alpha_R_4[_qp] = -18.943264072194637;
_alpha_I_4[_qp] = -9.349446845430961;
// A constants
_A_R_0[_qp] = -1.282478656880326e02;
_A_I_0[_qp] = 9.910190130869531e-15;
_A_R_1[_qp] = 34.212475550662354;
_A_I_1[_qp] = 42.274652746493430;
_A_R_2[_qp] = 34.212475550666770;
_A_I_2[_qp] = -42.274652746496530;
_A_R_3[_qp] = 10.501019149011636;
_A_I_3[_qp] = -2.363585468012575;
_A_R_4[_qp] = 10.501019149026910;
_A_I_4[_qp] = 2.363585467971611;
}
}
/*
_alpha_R_0[_qp] = 2.412;
_alpha_I_0[_qp] = 0.0;
_alpha_R_1[_qp] = -18.62;
_alpha_I_1[_qp] = 9.968;
_alpha_R_2[_qp] = -51.8;
_alpha_I_2[_qp] = -18.58;
_alpha_R_3[_qp] = -104.6;
_alpha_I_3[_qp] = -19.21;
_alpha_R_4[_qp] = -3.88;
_alpha_I_4[_qp] = 6.545;
// A constants
_A_R_0[_qp] = -63.1;
_A_I_0[_qp] = 0.0;
_A_R_1[_qp] = 12.52;
_A_I_1[_qp] = -3.607;
_A_R_2[_qp] = 3.88;
_A_I_2[_qp] = 0.7762;
_A_R_3[_qp] = 0.9984;
_A_I_3[_qp] = 0.1591;
_A_R_4[_qp] = 36.7;
_A_I_4[_qp] = 42.66;
else if (_num_L == 5)
{
// alpha constants
_alpha_R_0[_qp] = 2.4887266073084095552303551812656223773956298828125;
_alpha_I_0[_qp] = 0.0;
_alpha_R_1[_qp] = -19.2733746470461682065433706156909465789794921875;
_alpha_I_1[_qp] = -9.18277447910810451503493823111057281494140625;
_alpha_R_2[_qp] = -19.2733746470461682065433706156909465789794921875;
_alpha_I_2[_qp] = 9.18277447910810451503493823111057281494140625;
_alpha_R_3[_qp] = -3.8695517424123173633176975272363051772117614746094;
_alpha_I_3[_qp] = 6.7955256217773678528715208813082426786422729492188;
_alpha_R_4[_qp] = -3.8695517424123173633176975272363051772117614746094;
_alpha_I_4[_qp] = -6.7955256217773678528715208813082426786422729492188;
// A constants
_A_R_0[_qp] = -133.2927098034036816898151300847530364990234375;
_A_I_0[_qp] = 0.0;
_A_R_1[_qp] = 10.728194854990965367846911249216645956039428710938;
_A_I_1[_qp] = 2.5027746492227604946378960448782891035079956054688;
_A_R_2[_qp] = 10.728194854990965367846911249216645956039428710938;
_A_I_2[_qp] = -2.5027746492227604946378960448782891035079956054688;
_A_R_3[_qp] = 35.9742594324134188354946672916412353515625;
_A_I_3[_qp] = 45.6070815722133602321264334022998809814453125;
_A_R_4[_qp] = 35.9742594324134188354946672916412353515625;
_A_I_4[_qp] = -45.6070815722133602321264334022998809814453125;
}
*/
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <modules/plottinggl/processors/colorscalelegend.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo ColorScaleLegend::processorInfo_{
"org.inviwo.ColorScaleLegend", // Class identifier
"Color Scale Legend", // Display name
"Drawing", // Category
CodeState::Experimental, // Code state
Tags::GL, // Tags
};
const ProcessorInfo ColorScaleLegend::getProcessorInfo() const { return processorInfo_; }
ColorScaleLegend::ColorScaleLegend()
: Processor()
, inport_("inport")
, outport_("outport")
, volumeInport_("volumeInport")
, isotfComposite_("isotfComposite", "TF & Isovalues")
, positioning_("positioning", "Positioning & Size")
, style_("style", "Style")
, legendPlacement_("legendPlacement", "Legend Placement",
{{"top", "Top", 0},
{"right", "Right", 1},
{"bottom", "Bottom", 2},
{"left", "Left", 3},
{"custom", "Custom", 4}},
1)
, rotation_("legendRotation", "Legend Rotation",
{{"degree0", "0 degrees", 0},
{"degree90", "90 degrees", 1},
{"degree180", "180 degrees", 2},
{"degree270", "270 degrees", 3}},
1)
, position_("position", "Position", vec2(0.5f), vec2(0.0f), vec2(1.0f))
, margin_("margin", "Margin (in pixels)", 25, 0, 100)
, legendSize_("legendSize", "Legend Size", vec2(200, 25), vec2(50, 10), vec2(400, 50))
, title_("title", "Legend Title", "Legend Title")
, color_("color", "Color", vec4(0, 0, 0, 1))
, fontSize_("fontSize", "Font Size", 14, 8, 36)
, backgroundStyle_("backgroundStyle", "Background",
{{"noBackground", "No background", BackgroundStyle::NoBackground},
{"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}},
0)
, checkerBoardSize_("checkerBoardSize", "Checker Board Size", 5, 1, 20)
, borderWidth_("borderWidth", "Border Width", 2, 0, 10)
, shader_("img_texturequad.vert", "legend.frag")
, axis_("axis", "Scale Axis")
, axisRenderer_(axis_) {
shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });
inport_.setOptional(true);
volumeInport_.setOptional(true);
addPort(inport_);
addPort(outport_);
addPort(volumeInport_);
addProperty(isotfComposite_);
// legend position
positioning_.addProperty(legendPlacement_);
positioning_.addProperty(rotation_);
rotation_.setVisible(false);
positioning_.addProperty(position_);
position_.setVisible(false);
positioning_.addProperty(margin_);
positioning_.addProperty(legendSize_);
addProperty(positioning_);
// legend style
style_.addProperty(title_);
style_.addProperty(color_);
color_.setSemantics(PropertySemantics::Color);
style_.addProperty(fontSize_);
style_.addProperty(backgroundStyle_);
style_.addProperty(checkerBoardSize_);
style_.addProperty(borderWidth_);
checkerBoardSize_.setVisible(false);
addProperty(style_);
addProperty(axis_);
rotation_.onChange([&]() { setLegendRotation(); });
title_.onChange([&]() { axis_.caption_.title_.set(title_.get()); });
fontSize_.onChange([&]() {
// the caption should be bigger than labels
axis_.caption_.font_.fontSize_.set(fontSize_.get() + 2);
axis_.labels_.font_.fontSize_.set(fontSize_.get());
});
color_.onChange([&]() {
axis_.color_.set(color_.get());
axis_.caption_.color_.set(color_.get());
axis_.labels_.color_.set(color_.get());
axis_.ticks_.majorTicks_.color_.set(color_.get());
axis_.ticks_.minorTicks_.color_.set(color_.get());
});
legendPlacement_.onChange([&]() {
if (legendPlacement_.get() == 4) {
rotation_.setVisible(true);
position_.setVisible(true);
} else {
rotation_.setVisible(false);
position_.setVisible(false);
}
});
backgroundStyle_.onChange([&]() {
switch (backgroundStyle_.get()) {
default:
case BackgroundStyle::NoBackground:
checkerBoardSize_.setVisible(false);
break;
case BackgroundStyle::CheckerBoard:
checkerBoardSize_.setVisible(true);
break;
}
});
}
void ColorScaleLegend::initializeResources() {
// set initial axis parameters
axis_.width_ = 0;
axis_.caption_.title_.set(title_.get());
axis_.caption_.setChecked(true);
axis_.labels_.font_.fontFace_.set(axis_.caption_.font_.fontFace_.get());
axis_.caption_.offset_.set(8);
fontSize_.propertyModified();
shader_.build();
}
vec2 ColorScaleLegend::getRealSize() {
vec2 size = legendSize_.get();
if (rotation_.get() % 2 == 0) return size;
return vec2(size.y, size.x);
}
// this function handles the legend rotation and updates the axis thereafter
void ColorScaleLegend::setAxisPosition() {
float ticsWidth = ceil(axis_.ticks_.majorTicks_.tickWidth_.get());
auto borderWidth = borderWidth_.get();
switch (rotation_.get()) {
default:
case 0: // 0 degrees rotation (top)
axisStart_ = bottomLeft_ + ivec2(ticsWidth / 2, 0) - ivec2(borderWidth);
axisEnd_ = bottomRight_ - ivec2(ticsWidth / 2, 0) + ivec2(borderWidth, -borderWidth);
axis_.orientation_.set(plot::AxisProperty::Orientation::Horizontal);
axis_.placement_.set(plot::AxisProperty::Placement::Outside);
break;
case 1: // 90 degrees rotation (right)
axisStart_ = bottomLeft_ + ivec2(0, ticsWidth / 2) - ivec2(borderWidth);
axisEnd_ = topLeft_ - ivec2(0, ticsWidth / 2) + ivec2(-borderWidth, borderWidth);
axis_.orientation_.set(plot::AxisProperty::Orientation::Vertical);
axis_.placement_.set(plot::AxisProperty::Placement::Outside);
break;
case 2: // 180 degrees rotation (bottom)
axisStart_ = topLeft_ + ivec2(ticsWidth / 2, 0) + ivec2(-borderWidth, borderWidth);
axisEnd_ = topRight_ - ivec2(ticsWidth / 2, 0) + ivec2(borderWidth);
axis_.orientation_.set(plot::AxisProperty::Orientation::Horizontal);
axis_.placement_.set(plot::AxisProperty::Placement::Inside);
break;
case 3: // 270 degrees rotation (left)
axisStart_ = bottomRight_ + ivec2(0, ticsWidth / 2) + ivec2(borderWidth, -borderWidth);
axisEnd_ = topRight_ - ivec2(0, ticsWidth / 2) + ivec2(borderWidth);
axis_.orientation_.set(plot::AxisProperty::Orientation::Vertical);
axis_.placement_.set(plot::AxisProperty::Placement::Inside);
break;
}
}
// set the boundaries of the position so that the legend is always inside the output canvas
void ColorScaleLegend::updatePositionBoundaries() {
auto legendSize = getRealSize();
auto dim = outport_.getDimensions();
vec2 normalizedMin(((float)legendSize.x / 2) / dim.x, ((float)legendSize.y / 2) / dim.y);
vec2 normalizedMax(1.0 - normalizedMin.x, 1.0 - normalizedMin.y);
vec2 normalizedMargin((float)margin_.get() / dim.x, (float)margin_.get() / dim.y);
position_.setMinValue(
vec2(normalizedMin.x + normalizedMargin.x, normalizedMin.y + normalizedMargin.y));
position_.setMaxValue(
vec2(normalizedMax.x - normalizedMargin.x, normalizedMax.y - normalizedMargin.y));
}
void ColorScaleLegend::setLegendPosition() {
switch (legendPlacement_.get()) {
default:
break;
case 0:
position_.set(vec2(0.5, 1));
break;
case 1:
position_.set(vec2(1, 0.5));
break;
case 2:
position_.set(vec2(0.5, 0));
break;
case 3:
position_.set(vec2(0, 0.5));
break;
}
}
void ColorScaleLegend::setLegendRotation() {
if (legendPlacement_.get() != 4) rotation_.set(legendPlacement_.get());
// update the legend size boundaries
if (rotation_.get() % 2 == 0) {
auto maxLength = outport_.getDimensions().x - margin_.get() * 2;
legendSize_.setMaxValue(vec2(maxLength, legendSize_.getMaxValue().y));
} else {
auto maxLength = outport_.getDimensions().x - margin_.get() * 2;
legendSize_.setMaxValue(vec2(maxLength, legendSize_.getMaxValue().y));
}
}
void ColorScaleLegend::process() {
// draw cached overlay on top of the input image
if (inport_.isReady()) {
utilgl::activateTargetAndCopySource(outport_, inport_);
} else {
utilgl::activateAndClearTarget(outport_);
}
setLegendRotation();
updatePositionBoundaries();
setLegendPosition();
ivec2 dimensions = outport_.getDimensions();
vec2 position = position_.get();
ivec2 legendSize = getRealSize();
auto borderWidth = borderWidth_.get();
// define the legend corners
bottomLeft_ = vec2(position.x * dimensions.x - (legendSize.x / 2.0),
position.y * dimensions.y - (legendSize.y / 2.0));
bottomRight_ = vec2(bottomLeft_.x + legendSize.x, bottomLeft_.y);
topLeft_ = vec2(bottomLeft_.x, bottomLeft_.y + legendSize.y);
topRight_ = vec2(bottomRight_.x, topLeft_.y);
// update the legend range if a volume is connected to inport
if (volumeInport_.isChanged() && volumeInport_.isConnected()) {
axis_.setRange(volumeInport_.getData()->dataMap_.dataRange);
} else if (!volumeInport_.isConnected()) {
axis_.setRange(vec2(0, 1));
}
setAxisPosition();
axisRenderer_.render(dimensions, axisStart_, axisEnd_);
utilgl::DepthFuncState depthFunc(GL_ALWAYS);
utilgl::BlendModeState blending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
TextureUnit colorUnit;
shader_.activate();
shader_.setUniform("color_", colorUnit.getUnitNumber());
shader_.setUniform("dimensions_", dimensions);
shader_.setUniform("position_", position);
shader_.setUniform("legendSize_", legendSize);
shader_.setUniform("borderColor_", color_.get());
shader_.setUniform("backgroundAlpha_", (int)backgroundStyle_.get());
shader_.setUniform("checkerBoardSize_", (int)checkerBoardSize_.get());
shader_.setUniform("rotationTF_", rotation_.get());
utilgl::bindTexture(isotfComposite_.tf_, colorUnit);
utilgl::ViewportState viewport(bottomLeft_.x - borderWidth, bottomLeft_.y - borderWidth,
legendSize.x + (borderWidth * 2),
legendSize.y + (borderWidth * 2));
utilgl::singleDrawImagePlaneRect();
shader_.deactivate();
TextureUnit::setZeroUnit();
utilgl::deactivateCurrentTarget();
}
} // namespace inviwo
<commit_msg>PlottingGL: Added a missing include to colorscalelegend.cpp<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <modules/plottinggl/processors/colorscalelegend.h>
#include <modules/opengl/texture/textureutils.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo ColorScaleLegend::processorInfo_{
"org.inviwo.ColorScaleLegend", // Class identifier
"Color Scale Legend", // Display name
"Drawing", // Category
CodeState::Experimental, // Code state
Tags::GL, // Tags
};
const ProcessorInfo ColorScaleLegend::getProcessorInfo() const { return processorInfo_; }
ColorScaleLegend::ColorScaleLegend()
: Processor()
, inport_("inport")
, outport_("outport")
, volumeInport_("volumeInport")
, isotfComposite_("isotfComposite", "TF & Isovalues")
, positioning_("positioning", "Positioning & Size")
, style_("style", "Style")
, legendPlacement_("legendPlacement", "Legend Placement",
{{"top", "Top", 0},
{"right", "Right", 1},
{"bottom", "Bottom", 2},
{"left", "Left", 3},
{"custom", "Custom", 4}},
1)
, rotation_("legendRotation", "Legend Rotation",
{{"degree0", "0 degrees", 0},
{"degree90", "90 degrees", 1},
{"degree180", "180 degrees", 2},
{"degree270", "270 degrees", 3}},
1)
, position_("position", "Position", vec2(0.5f), vec2(0.0f), vec2(1.0f))
, margin_("margin", "Margin (in pixels)", 25, 0, 100)
, legendSize_("legendSize", "Legend Size", vec2(200, 25), vec2(50, 10), vec2(400, 50))
, title_("title", "Legend Title", "Legend Title")
, color_("color", "Color", vec4(0, 0, 0, 1))
, fontSize_("fontSize", "Font Size", 14, 8, 36)
, backgroundStyle_("backgroundStyle", "Background",
{{"noBackground", "No background", BackgroundStyle::NoBackground},
{"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}},
0)
, checkerBoardSize_("checkerBoardSize", "Checker Board Size", 5, 1, 20)
, borderWidth_("borderWidth", "Border Width", 2, 0, 10)
, shader_("img_texturequad.vert", "legend.frag")
, axis_("axis", "Scale Axis")
, axisRenderer_(axis_) {
shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });
inport_.setOptional(true);
volumeInport_.setOptional(true);
addPort(inport_);
addPort(outport_);
addPort(volumeInport_);
addProperty(isotfComposite_);
// legend position
positioning_.addProperty(legendPlacement_);
positioning_.addProperty(rotation_);
rotation_.setVisible(false);
positioning_.addProperty(position_);
position_.setVisible(false);
positioning_.addProperty(margin_);
positioning_.addProperty(legendSize_);
addProperty(positioning_);
// legend style
style_.addProperty(title_);
style_.addProperty(color_);
color_.setSemantics(PropertySemantics::Color);
style_.addProperty(fontSize_);
style_.addProperty(backgroundStyle_);
style_.addProperty(checkerBoardSize_);
style_.addProperty(borderWidth_);
checkerBoardSize_.setVisible(false);
addProperty(style_);
addProperty(axis_);
rotation_.onChange([&]() { setLegendRotation(); });
title_.onChange([&]() { axis_.caption_.title_.set(title_.get()); });
fontSize_.onChange([&]() {
// the caption should be bigger than labels
axis_.caption_.font_.fontSize_.set(fontSize_.get() + 2);
axis_.labels_.font_.fontSize_.set(fontSize_.get());
});
color_.onChange([&]() {
axis_.color_.set(color_.get());
axis_.caption_.color_.set(color_.get());
axis_.labels_.color_.set(color_.get());
axis_.ticks_.majorTicks_.color_.set(color_.get());
axis_.ticks_.minorTicks_.color_.set(color_.get());
});
legendPlacement_.onChange([&]() {
if (legendPlacement_.get() == 4) {
rotation_.setVisible(true);
position_.setVisible(true);
} else {
rotation_.setVisible(false);
position_.setVisible(false);
}
});
backgroundStyle_.onChange([&]() {
switch (backgroundStyle_.get()) {
default:
case BackgroundStyle::NoBackground:
checkerBoardSize_.setVisible(false);
break;
case BackgroundStyle::CheckerBoard:
checkerBoardSize_.setVisible(true);
break;
}
});
}
void ColorScaleLegend::initializeResources() {
// set initial axis parameters
axis_.width_ = 0;
axis_.caption_.title_.set(title_.get());
axis_.caption_.setChecked(true);
axis_.labels_.font_.fontFace_.set(axis_.caption_.font_.fontFace_.get());
axis_.caption_.offset_.set(8);
fontSize_.propertyModified();
shader_.build();
}
vec2 ColorScaleLegend::getRealSize() {
vec2 size = legendSize_.get();
if (rotation_.get() % 2 == 0) return size;
return vec2(size.y, size.x);
}
// this function handles the legend rotation and updates the axis thereafter
void ColorScaleLegend::setAxisPosition() {
float ticsWidth = ceil(axis_.ticks_.majorTicks_.tickWidth_.get());
auto borderWidth = borderWidth_.get();
switch (rotation_.get()) {
default:
case 0: // 0 degrees rotation (top)
axisStart_ = bottomLeft_ + ivec2(ticsWidth / 2, 0) - ivec2(borderWidth);
axisEnd_ = bottomRight_ - ivec2(ticsWidth / 2, 0) + ivec2(borderWidth, -borderWidth);
axis_.orientation_.set(plot::AxisProperty::Orientation::Horizontal);
axis_.placement_.set(plot::AxisProperty::Placement::Outside);
break;
case 1: // 90 degrees rotation (right)
axisStart_ = bottomLeft_ + ivec2(0, ticsWidth / 2) - ivec2(borderWidth);
axisEnd_ = topLeft_ - ivec2(0, ticsWidth / 2) + ivec2(-borderWidth, borderWidth);
axis_.orientation_.set(plot::AxisProperty::Orientation::Vertical);
axis_.placement_.set(plot::AxisProperty::Placement::Outside);
break;
case 2: // 180 degrees rotation (bottom)
axisStart_ = topLeft_ + ivec2(ticsWidth / 2, 0) + ivec2(-borderWidth, borderWidth);
axisEnd_ = topRight_ - ivec2(ticsWidth / 2, 0) + ivec2(borderWidth);
axis_.orientation_.set(plot::AxisProperty::Orientation::Horizontal);
axis_.placement_.set(plot::AxisProperty::Placement::Inside);
break;
case 3: // 270 degrees rotation (left)
axisStart_ = bottomRight_ + ivec2(0, ticsWidth / 2) + ivec2(borderWidth, -borderWidth);
axisEnd_ = topRight_ - ivec2(0, ticsWidth / 2) + ivec2(borderWidth);
axis_.orientation_.set(plot::AxisProperty::Orientation::Vertical);
axis_.placement_.set(plot::AxisProperty::Placement::Inside);
break;
}
}
// set the boundaries of the position so that the legend is always inside the output canvas
void ColorScaleLegend::updatePositionBoundaries() {
auto legendSize = getRealSize();
auto dim = outport_.getDimensions();
vec2 normalizedMin(((float)legendSize.x / 2) / dim.x, ((float)legendSize.y / 2) / dim.y);
vec2 normalizedMax(1.0 - normalizedMin.x, 1.0 - normalizedMin.y);
vec2 normalizedMargin((float)margin_.get() / dim.x, (float)margin_.get() / dim.y);
position_.setMinValue(
vec2(normalizedMin.x + normalizedMargin.x, normalizedMin.y + normalizedMargin.y));
position_.setMaxValue(
vec2(normalizedMax.x - normalizedMargin.x, normalizedMax.y - normalizedMargin.y));
}
void ColorScaleLegend::setLegendPosition() {
switch (legendPlacement_.get()) {
default:
break;
case 0:
position_.set(vec2(0.5, 1));
break;
case 1:
position_.set(vec2(1, 0.5));
break;
case 2:
position_.set(vec2(0.5, 0));
break;
case 3:
position_.set(vec2(0, 0.5));
break;
}
}
void ColorScaleLegend::setLegendRotation() {
if (legendPlacement_.get() != 4) rotation_.set(legendPlacement_.get());
// update the legend size boundaries
if (rotation_.get() % 2 == 0) {
auto maxLength = outport_.getDimensions().x - margin_.get() * 2;
legendSize_.setMaxValue(vec2(maxLength, legendSize_.getMaxValue().y));
} else {
auto maxLength = outport_.getDimensions().x - margin_.get() * 2;
legendSize_.setMaxValue(vec2(maxLength, legendSize_.getMaxValue().y));
}
}
void ColorScaleLegend::process() {
// draw cached overlay on top of the input image
if (inport_.isReady()) {
utilgl::activateTargetAndCopySource(outport_, inport_);
} else {
utilgl::activateAndClearTarget(outport_);
}
setLegendRotation();
updatePositionBoundaries();
setLegendPosition();
ivec2 dimensions = outport_.getDimensions();
vec2 position = position_.get();
ivec2 legendSize = getRealSize();
auto borderWidth = borderWidth_.get();
// define the legend corners
bottomLeft_ = vec2(position.x * dimensions.x - (legendSize.x / 2.0),
position.y * dimensions.y - (legendSize.y / 2.0));
bottomRight_ = vec2(bottomLeft_.x + legendSize.x, bottomLeft_.y);
topLeft_ = vec2(bottomLeft_.x, bottomLeft_.y + legendSize.y);
topRight_ = vec2(bottomRight_.x, topLeft_.y);
// update the legend range if a volume is connected to inport
if (volumeInport_.isChanged() && volumeInport_.isConnected()) {
axis_.setRange(volumeInport_.getData()->dataMap_.dataRange);
} else if (!volumeInport_.isConnected()) {
axis_.setRange(vec2(0, 1));
}
setAxisPosition();
axisRenderer_.render(dimensions, axisStart_, axisEnd_);
utilgl::DepthFuncState depthFunc(GL_ALWAYS);
utilgl::BlendModeState blending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
TextureUnit colorUnit;
shader_.activate();
shader_.setUniform("color_", colorUnit.getUnitNumber());
shader_.setUniform("dimensions_", dimensions);
shader_.setUniform("position_", position);
shader_.setUniform("legendSize_", legendSize);
shader_.setUniform("borderColor_", color_.get());
shader_.setUniform("backgroundAlpha_", (int)backgroundStyle_.get());
shader_.setUniform("checkerBoardSize_", (int)checkerBoardSize_.get());
shader_.setUniform("rotationTF_", rotation_.get());
utilgl::bindTexture(isotfComposite_.tf_, colorUnit);
utilgl::ViewportState viewport(bottomLeft_.x - borderWidth, bottomLeft_.y - borderWidth,
legendSize.x + (borderWidth * 2),
legendSize.y + (borderWidth * 2));
utilgl::singleDrawImagePlaneRect();
shader_.deactivate();
TextureUnit::setZeroUnit();
utilgl::deactivateCurrentTarget();
}
} // namespace inviwo
<|endoftext|> |
<commit_before>// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %t
// RUN: rm -rf %T/coverage-maybe-open-file
// RUN: mkdir -p %T/coverage-maybe-open-file && cd %T/coverage-maybe-open-file
// RUN: %env_asan_opts=coverage=1 %run %t | FileCheck %s --check-prefix=CHECK-success
// RUN: %env_asan_opts=coverage=0 %run %t | FileCheck %s --check-prefix=CHECK-fail
// RUN: [ "$(cat test.sancov.packed)" == "test" ]
// RUN: cd .. && rm -rf %T/coverage-maybe-open-file
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sanitizer/coverage_interface.h>
// FIXME: the code below might not work on Windows.
int main(int argc, char **argv) {
int fd = __sanitizer_maybe_open_cov_file("test");
if (fd > 0) {
printf("SUCCESS\n");
const char s[] = "test\n";
write(fd, s, strlen(s));
close(fd);
} else {
printf("FAIL\n");
}
}
// CHECK-success: SUCCESS
// CHECK-fail: FAIL
<commit_msg>Use FileCheck instead of [.<commit_after>// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %t
// RUN: rm -rf %T/coverage-maybe-open-file
// RUN: mkdir -p %T/coverage-maybe-open-file && cd %T/coverage-maybe-open-file
// RUN: %env_asan_opts=coverage=1 %run %t | FileCheck %s --check-prefix=CHECK-success
// RUN: %env_asan_opts=coverage=0 %run %t | FileCheck %s --check-prefix=CHECK-fail
// RUN: FileCheck %s < test.sancov.packed -implicit-check-not={{.}} --check-prefix=CHECK-test
// RUN: cd .. && rm -rf %T/coverage-maybe-open-file
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sanitizer/coverage_interface.h>
// FIXME: the code below might not work on Windows.
int main(int argc, char **argv) {
int fd = __sanitizer_maybe_open_cov_file("test");
if (fd > 0) {
printf("SUCCESS\n");
const char s[] = "test\n";
write(fd, s, strlen(s));
close(fd);
} else {
printf("FAIL\n");
}
}
// CHECK-success: SUCCESS
// CHECK-fail: FAIL
// CHECK-test: {{^}}test{{$}}
<|endoftext|> |
<commit_before>// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <stdio.h>
char bigchunk[1 << 30];
int main() {
printf("Hello, world!\n");
scanf("%s", bigchunk);
// CHECK-NOT: Hello, world!
// CHECK: Shadow memory range interleaves with an existing memory mapping.
// CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range.
// CHECK: Dumping process modules:
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}kernel32.dll
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll
}
<commit_msg>[asan] Remove CHECK line for kernel32.dll<commit_after>// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <stdio.h>
char bigchunk[1 << 30];
int main() {
printf("Hello, world!\n");
scanf("%s", bigchunk);
// CHECK-NOT: Hello, world!
// CHECK: Shadow memory range interleaves with an existing memory mapping.
// CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range.
// CHECK: Dumping process modules:
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll
}
<|endoftext|> |
<commit_before>#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
#include <iostream>
#include <iomanip>
#include <TClass.h>
#include <TDataMember.h>
#include <TDataType.h>
#include <TFile.h>
#include <TKey.h>
#include <TMemberInspector.h>
#include <TStreamerElement.h>
#include <TVirtualStreamerInfo.h>
#include <TROOT.h>
using namespace ROOT;
class MyInspector: public TMemberInspector
{
private:
unsigned tabs;
public:
MyInspector(): tabs(0)
{
}
void Inspect(TClass* klass, const char* parent, const char* name, const void* addr)
{
std::string indent(tabs, '\t');
TDataType* memberType = NULL;
TString memberTypeName;
TString memberFullTypeName;
TString memberName;
TString memberValueAsStr;
Bool_t isPointer;
if (TDataMember* member = klass->GetDataMember(name)) {
memberTypeName = member->GetTypeName();
memberFullTypeName = member->GetFullTypeName();
memberType = member->GetDataType(); // Only for basic types
memberName = member->GetName();
isPointer = member->IsaPointer();
}
else if (!klass->IsLoaded()) {
// The class hasn't been loaded
TVirtualStreamerInfo* info = klass->GetStreamerInfo();
if (!info) return;
const char* cursor = name;
while ((*cursor) == '*') ++cursor;
TString elname(cursor);
Ssiz_t pos = elname.Index("[");
if (pos != kNPOS)
elname.Remove(pos);
TStreamerElement* element = static_cast<TStreamerElement*>(info->GetElements()->FindObject(elname.Data()));
if (!element) return;
memberFullTypeName = element->GetTypeName();
memberType = gROOT->GetType(memberTypeName);
memberName = element->GetName();
isPointer = element->IsaPointer() || element->GetType() == TVirtualStreamerInfo::kCharStar;
memberTypeName = memberFullTypeName;
}
else {
return;
}
TClass* dataClass = NULL;
if (isPointer) {
char buffer[32];
snprintf(buffer, sizeof(buffer), "0x%lx", (off64_t)addr);
memberValueAsStr = buffer;
}
else if(memberType) {
memberValueAsStr = memberType->AsString((void*)addr);
}
else {
char buffer[32];
dataClass = TClass::GetClass(memberFullTypeName);
if (dataClass == TString::Class()) {
TString* str = (TString*)addr;
memberValueAsStr = *str;
dataClass = NULL;
}
else {
snprintf(buffer, sizeof(buffer), "-> 0x%lx", (off64_t)addr);
memberValueAsStr = buffer;
}
}
std::cout << indent << std::setw(20) << memberFullTypeName << " "
<< klass->GetName() << "::" << memberName << " = " << memberValueAsStr
<< std::endl;
}
void Inspect(const TDirectory* dir)
{
std::string indent(tabs, '\t');
Int_t nelements = dir->GetNkeys();
std::cout << indent << nelements << " elements" << std::endl;
TList* keys = dir->GetListOfKeys();
for (Int_t i = 0; i < nelements; ++i) {
TKey* key = static_cast<TKey*>(keys->At(i));
std::cout << indent << key->GetName() << std::endl;
++tabs;
key->ReadObj()->ShowMembers(*this);
--tabs;
}
}
void Inspect(const TCollection* collection)
{
std::string indent(tabs, '\t');
std::cout << indent << "Collection!" << std::endl;
}
};
int main(int argc, char** argv)
{
if (argc < 2) {
std::cerr << "Expecting a file name as a parameter" << std::endl;
return -1;
}
boost::shared_ptr<TFile> f(new TFile(argv[1]));
MyInspector inspector;
// Call inspect on the file
inspector.Inspect(f.get());
return 0;
}
<commit_msg>Removed Inspect(CollectioN)<commit_after>#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
#include <iostream>
#include <iomanip>
#include <TClass.h>
#include <TDataMember.h>
#include <TDataType.h>
#include <TFile.h>
#include <TKey.h>
#include <TMemberInspector.h>
#include <TStreamerElement.h>
#include <TVirtualStreamerInfo.h>
#include <TROOT.h>
using namespace ROOT;
class MyInspector: public TMemberInspector
{
private:
unsigned tabs;
public:
MyInspector(): tabs(0)
{
}
void Inspect(TClass* klass, const char* parent, const char* name, const void* addr)
{
std::string indent(tabs, '\t');
TDataType* memberType = NULL;
TString memberTypeName;
TString memberFullTypeName;
TString memberName;
TString memberValueAsStr;
Bool_t isPointer;
if (TDataMember* member = klass->GetDataMember(name)) {
memberTypeName = member->GetTypeName();
memberFullTypeName = member->GetFullTypeName();
memberType = member->GetDataType(); // Only for basic types
memberName = member->GetName();
isPointer = member->IsaPointer();
}
else if (!klass->IsLoaded()) {
// The class hasn't been loaded
TVirtualStreamerInfo* info = klass->GetStreamerInfo();
if (!info) return;
const char* cursor = name;
while ((*cursor) == '*') ++cursor;
TString elname(cursor);
Ssiz_t pos = elname.Index("[");
if (pos != kNPOS)
elname.Remove(pos);
TStreamerElement* element = static_cast<TStreamerElement*>(info->GetElements()->FindObject(elname.Data()));
if (!element) return;
memberFullTypeName = element->GetTypeName();
memberType = gROOT->GetType(memberTypeName);
memberName = element->GetName();
isPointer = element->IsaPointer() || element->GetType() == TVirtualStreamerInfo::kCharStar;
memberTypeName = memberFullTypeName;
}
else {
return;
}
TClass* dataClass = NULL;
if (isPointer) {
char buffer[32];
snprintf(buffer, sizeof(buffer), "0x%lx", (off64_t)addr);
memberValueAsStr = buffer;
}
else if(memberType) {
memberValueAsStr = memberType->AsString((void*)addr);
}
else {
char buffer[32];
dataClass = TClass::GetClass(memberFullTypeName);
if (dataClass == TString::Class()) {
TString* str = (TString*)addr;
memberValueAsStr = *str;
dataClass = NULL;
}
else {
snprintf(buffer, sizeof(buffer), "-> 0x%lx", (off64_t)addr);
memberValueAsStr = buffer;
}
}
std::cout << indent << std::setw(20) << memberFullTypeName << " "
<< klass->GetName() << "::" << memberName << " = " << memberValueAsStr
<< std::endl;
}
void Inspect(const TDirectory* dir)
{
std::string indent(tabs, '\t');
Int_t nelements = dir->GetNkeys();
std::cout << indent << nelements << " elements" << std::endl;
TList* keys = dir->GetListOfKeys();
for (Int_t i = 0; i < nelements; ++i) {
TKey* key = static_cast<TKey*>(keys->At(i));
std::cout << indent << key->GetName() << std::endl;
++tabs;
key->ReadObj()->ShowMembers(*this);
--tabs;
}
}
};
int main(int argc, char** argv)
{
if (argc < 2) {
std::cerr << "Expecting a file name as a parameter" << std::endl;
return -1;
}
boost::shared_ptr<TFile> f(new TFile(argv[1]));
MyInspector inspector;
// Call inspect on the file
inspector.Inspect(f.get());
return 0;
}
<|endoftext|> |
<commit_before>#include "ics3/ics3.hpp"
#include "core.hpp"
#include "ics3/angle.hpp"
#include "ics3/eeprom.hpp"
#include "ics3/parameter.hpp"
#include "ics3/id.hpp"
ics::ICS3::ICS3(const char* path, ICSBaudrate baudrate) throw(std::invalid_argument, std::runtime_error)
: core(Core::getReference(path, static_cast<speed_t>(baudrate)))
{
}
ics::Angle ics::ICS3::move(const ID &id, Angle angle) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(3), rx(6);
uint16_t send = angle.getRaw();
tx[0] = 0x80 | id.get();
tx[1] = 0x7F & (send >> 7);
tx[2] = 0x7F & send;
try {
core.communicate(tx, rx);
} catch (std::runtime_error e) {
throw e;
}
uint16_t receive = (rx[4] << 7) | rx[5];
try {
angle.setRaw(receive);
} catch (std::invalid_argument) {
throw std::runtime_error("Receive angle error");
}
return angle;
}
ics::Parameter ics::ICS3::get(const ID &id, Parameter param) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(2), rx(5);
tx[0] = 0xA0 | id.get();
tx[1] = param.getSc();
try {
core.communicate(tx, rx);
} catch (std::runtime_error e) {
throw e;
}
param.set(rx[4]);
return param;
}
void ics::ICS3::set(const ID &id, const Parameter ¶m) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(3), rx(6);
tx[0] = 0xC0 | id.get();
tx[1] = param.getSc();
tx[2] = param.get();
try {
core.communicate(tx, rx);
} catch (std::runtime_error e) {
throw e;
}
}
ics::Eeprom ics::ICS3::getRom(const ID &id) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(2), rx(68);
tx[0] = 0xA0 | id.get();
tx[1] = 0;
try {
core.communicate(tx, rx);
} catch (std::runtime_error e) {
throw e;
}
Eeprom rom;
std::copy(rx.begin() + 2, rx.end(), rom.data.begin());
return rom;
}
void ics::ICS3::setRom(const ID &id, const Eeprom &rom) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(66), rx(68);
tx[0] = 0xC0 | id.get();
tx[2] = 0;
std::copy(rom.data.begin(), rom.data.end(), tx.begin() + 2);
try {
core.communicate(tx, rx);
} catch (std::runtime_error e) {
throw e;
}
}
<commit_msg>Update ics3.cpp<commit_after>#include "ics3/ics3.hpp"
#include "core.hpp"
#include "ics3/angle.hpp"
#include "ics3/eeprom.hpp"
#include "ics3/parameter.hpp"
#include "ics3/id.hpp"
ics::ICS3::ICS3(const char* path, ICSBaudrate baudrate) throw(std::invalid_argument, std::runtime_error)
: core(Core::getReference(path, static_cast<speed_t>(baudrate)))
{}
ics::Angle ics::ICS3::move(const ID& id, Angle angle) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(3), rx(6);
uint16_t send = angle.getRaw();
tx[0] = 0x80 | id.get();
tx[1] = 0x7F & (send >> 7);
tx[2] = 0x7F & send;
try {
core.communicate(tx, rx);
} catch (std::runtime_error& e) {
throw;
}
uint16_t receive = (rx[4] << 7) | rx[5];
try {
angle.setRaw(receive);
} catch (std::invalid_argument& e) {
throw std::runtime_error("Receive angle error");
}
return angle;
}
ics::Parameter ics::ICS3::get(const ID& id, Parameter param) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(2), rx(5);
tx[0] = 0xA0 | id.get();
tx[1] = param.getSc();
try {
core.communicate(tx, rx);
} catch (std::runtime_error& e) {
throw;
}
param.set(rx[4]);
return param;
}
void ics::ICS3::set(const ID& id, const Parameter& param) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(3), rx(6);
tx[0] = 0xC0 | id.get();
tx[1] = param.getSc();
tx[2] = param.get();
try {
core.communicate(tx, rx);
} catch (std::runtime_error& e) {
throw;
}
}
ics::Eeprom ics::ICS3::getRom(const ID& id) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(2), rx(68);
tx[0] = 0xA0 | id.get();
tx[1] = 0;
try {
core.communicate(tx, rx);
} catch (std::runtime_error& e) {
throw;
}
Eeprom rom;
std::copy(rx.begin() + 2, rx.end(), rom.data.begin());
return rom;
}
void ics::ICS3::setRom(const ID& id, const Eeprom& rom) const throw(std::runtime_error) {
static std::vector<unsigned char> tx(66), rx(68);
tx[0] = 0xC0 | id.get();
tx[2] = 0;
std::copy(rom.data.begin(), rom.data.end(), tx.begin() + 2);
try {
core.communicate(tx, rx);
} catch (std::runtime_error& e) {
throw;
}
}
<|endoftext|> |
<commit_before>// Copyright 2019, Institute for Artificial Intelligence - University of Bremen
// Author: Andrei Haidu (http://haidu.eu)
#include "Events/SLSlicingEventHandler.h"
#include "SLEntitiesManager.h"
#include "Tags.h"
#if SL_WITH_SLICING
#include "SlicingBladeComponent.h"
#endif // SL_WITH_SLICING
// UUtils
#include "Ids.h"
// Set parent
void FSLSlicingEventHandler::Init(UObject* InParent)
{
if (!bIsInit)
{
// Make sure the mappings singleton is initialized (the handler uses it)
if (!FSLEntitiesManager::GetInstance()->IsInit())
{
FSLEntitiesManager::GetInstance()->Init(InParent->GetWorld());
}
#if SL_WITH_SLICING
// Check if parent is of right type
Parent = Cast<USlicingBladeComponent>(InParent);
#endif // SL_WITH_SLICING
if (Parent)
{
// Mark as initialized
bIsInit = true;
}
}
}
// Bind to input delegates
void FSLSlicingEventHandler::Start()
{
if (!bIsStarted && bIsInit)
{
#if SL_WITH_SLICING
// Subscribe to the forwarded semantically annotated Slicing broadcasts
Parent->OnBeginSlicing.AddRaw(this, &FSLSlicingEventHandler::OnSLSlicingBegin);
Parent->OnEndSlicingFail.AddRaw(this, &FSLSlicingEventHandler::OnSLSlicingEndFail);
Parent->OnEndSlicingSuccess.AddRaw(this, &FSLSlicingEventHandler::OnSLSlicingEndSuccess);
Parent->OnObjectCreation.AddRaw(this, &FSLSlicingEventHandler::OnSLObjectCreation);
Parent->OnObjectDestruction.AddRaw(this, &FSLSlicingEventHandler::OnSLObjectDestruction);
#endif // SL_WITH_SLICING
// Mark as started
bIsStarted = true;
}
}
// Terminate listener, finish and publish remaining events
void FSLSlicingEventHandler::Finish(float EndTime, bool bForced)
{
if (!bIsFinished && (bIsInit || bIsStarted))
{
FSLSlicingEventHandler::FinishAllEvents(EndTime);
// TODO use dynamic delegates to be able to unbind from them
// https://docs.unrealengine.com/en-us/Programming/UnrealArchitecture/Delegates/Dynamic
// this would mean that the handler will need to inherit from UObject
// Mark finished
bIsStarted = false;
bIsInit = false;
bIsFinished = true;
}
}
// Start new Slicing event
void FSLSlicingEventHandler::AddNewEvent(const FSLEntity& PerformedBy, const FSLEntity& DeviceUsed, const FSLEntity& ObjectActedOn, float StartTime)
{
// Start a semantic Slicing event
TSharedPtr<FSLSlicingEvent> Event = MakeShareable(new FSLSlicingEvent(
FIds::NewGuidInBase64Url(), StartTime,
FIds::PairEncodeCantor(PerformedBy.Obj->GetUniqueID(), ObjectActedOn.Obj->GetUniqueID()),
PerformedBy, DeviceUsed, ObjectActedOn));
// Add event to the pending array
StartedEvents.Emplace(Event);
}
// Publish finished event
bool FSLSlicingEventHandler::FinishEvent(UObject* ObjectActedOn, bool taskSuccess, float EndTime, const FSLEntity& OutputsCreated = FSLEntity::FSLEntity())
{
// Use iterator to be able to remove the entry from the array
for (auto EventItr(StartedEvents.CreateIterator()); EventItr; ++EventItr)
{
// It is enough to compare against the other id when searching
if ((*EventItr)->ObjectActedOn.Obj == ObjectActedOn)
{
// Set end time and publish event
(*EventItr)->End = EndTime;
(*EventItr)->TaskSuccess = taskSuccess;
(*EventItr)->OutputsCreated = OutputsCreated;
OnSemanticEvent.ExecuteIfBound(*EventItr);
// Remove event from the pending list
EventItr.RemoveCurrent();
return true;
}
}
return false;
}
// Terminate and publish pending events (this usually is called at end play)
void FSLSlicingEventHandler::FinishAllEvents(float EndTime)
{
// Finish events
for (auto& Ev : StartedEvents)
{
// Set end time and publish event
Ev->End = EndTime;
OnSemanticEvent.ExecuteIfBound(Ev);
}
StartedEvents.Empty();
}
// Event called when a semantic Slicing event begins
void FSLSlicingEventHandler::OnSLSlicingBegin(UObject* PerformedBy, UObject* DeviceUsed, UObject* ObjectActedOn, float Time)
{
// Check that the objects are semantically annotated
FSLEntity PerformedByEntity = FSLEntitiesManager::GetInstance()->GetEntity(PerformedBy);
FSLEntity DeviceUsedEntity = FSLEntitiesManager::GetInstance()->GetEntity(DeviceUsed);
FSLEntity CutEntity = FSLEntitiesManager::GetInstance()->GetEntity(ObjectActedOn);
if (PerformedByEntity.IsSet()
&& CutEntity.IsSet()
&& DeviceUsedEntity.IsSet())
{
FSLSlicingEventHandler::AddNewEvent(PerformedByEntity, DeviceUsedEntity, CutEntity, Time);
}
}
// Event called when a semantic Slicing event ends
void FSLSlicingEventHandler::OnSLSlicingEndFail(UObject* PerformedBy, UObject* ObjectActedOn, float Time)
{
FSLEntity PerformedByEntity = FSLEntitiesManager::GetInstance()->GetEntity(PerformedBy);
FSLEntity CutEntity = FSLEntitiesManager::GetInstance()->GetEntity(ObjectActedOn);
if (PerformedByEntity.IsSet()
&& CutEntity.IsSet())
{
FSLSlicingEventHandler::FinishEvent(ObjectActedOn, false, Time);
}
}
// Event called when a semantic Slicing event ends
void FSLSlicingEventHandler::OnSLSlicingEndSuccess(UObject* PerformedBy, UObject* ObjectActedOn, UObject* OutputsCreated, float Time)
{
FSLEntity PerformedByEntity = FSLEntitiesManager::GetInstance()->GetEntity(PerformedBy);
FSLEntity CutEntity = FSLEntitiesManager::GetInstance()->GetEntity(ObjectActedOn);
FSLEntity OutputsCreatedEntity = FSLEntitiesManager::GetInstance()->GetEntity(OutputsCreated);
if (PerformedByEntity.IsSet()
&& CutEntity.IsSet()
&& OutputsCreatedEntity.IsSet())
{
FSLSlicingEventHandler::FinishEvent(ObjectActedOn, true, Time, OutputsCreatedEntity);
}
}
// Event called when new objects are created
void FSLSlicingEventHandler::OnSLObjectCreation(UObject* TransformedObject, UObject* NewSlice, float Time)
{
// Only create Id for new Slice and use same old ID for Original object
FString IdValue = FIds::NewGuidInBase64() + "_";
IdValue.Append(FTags::GetValue(TransformedObject, "SemLog", "Id"));
FTags::AddKeyValuePair(NewSlice, "SemLog", "Id", IdValue, true);
if (FSLEntitiesManager::GetInstance()->AddObject(TransformedObject) &&
FSLEntitiesManager::GetInstance()->AddObject(NewSlice))
{
UE_LOG(LogTemp, Error, TEXT(">>Items Have been Created"));
}
}
// Event called when an object is destroyed
void FSLSlicingEventHandler::OnSLObjectDestruction(UObject* ObjectActedOn, float Time)
{
FSLEntity OtherItem = FSLEntitiesManager::GetInstance()->GetEntity(ObjectActedOn);
if (OtherItem.IsSet())
{
FSLEntitiesManager::GetInstance()->RemoveEntity(ObjectActedOn);
}
}
<commit_msg>Changing the default parameter behavior: the ctor can be called without giving the name of the struct<commit_after>// Copyright 2019, Institute for Artificial Intelligence - University of Bremen
// Author: Andrei Haidu (http://haidu.eu)
#include "Events/SLSlicingEventHandler.h"
#include "SLEntitiesManager.h"
#include "Tags.h"
#if SL_WITH_SLICING
#include "SlicingBladeComponent.h"
#endif // SL_WITH_SLICING
// UUtils
#include "Ids.h"
// Set parent
void FSLSlicingEventHandler::Init(UObject* InParent)
{
if (!bIsInit)
{
// Make sure the mappings singleton is initialized (the handler uses it)
if (!FSLEntitiesManager::GetInstance()->IsInit())
{
FSLEntitiesManager::GetInstance()->Init(InParent->GetWorld());
}
#if SL_WITH_SLICING
// Check if parent is of right type
Parent = Cast<USlicingBladeComponent>(InParent);
#endif // SL_WITH_SLICING
if (Parent)
{
// Mark as initialized
bIsInit = true;
}
}
}
// Bind to input delegates
void FSLSlicingEventHandler::Start()
{
if (!bIsStarted && bIsInit)
{
#if SL_WITH_SLICING
// Subscribe to the forwarded semantically annotated Slicing broadcasts
Parent->OnBeginSlicing.AddRaw(this, &FSLSlicingEventHandler::OnSLSlicingBegin);
Parent->OnEndSlicingFail.AddRaw(this, &FSLSlicingEventHandler::OnSLSlicingEndFail);
Parent->OnEndSlicingSuccess.AddRaw(this, &FSLSlicingEventHandler::OnSLSlicingEndSuccess);
Parent->OnObjectCreation.AddRaw(this, &FSLSlicingEventHandler::OnSLObjectCreation);
Parent->OnObjectDestruction.AddRaw(this, &FSLSlicingEventHandler::OnSLObjectDestruction);
#endif // SL_WITH_SLICING
// Mark as started
bIsStarted = true;
}
}
// Terminate listener, finish and publish remaining events
void FSLSlicingEventHandler::Finish(float EndTime, bool bForced)
{
if (!bIsFinished && (bIsInit || bIsStarted))
{
FSLSlicingEventHandler::FinishAllEvents(EndTime);
// TODO use dynamic delegates to be able to unbind from them
// https://docs.unrealengine.com/en-us/Programming/UnrealArchitecture/Delegates/Dynamic
// this would mean that the handler will need to inherit from UObject
// Mark finished
bIsStarted = false;
bIsInit = false;
bIsFinished = true;
}
}
// Start new Slicing event
void FSLSlicingEventHandler::AddNewEvent(const FSLEntity& PerformedBy, const FSLEntity& DeviceUsed, const FSLEntity& ObjectActedOn, float StartTime)
{
// Start a semantic Slicing event
TSharedPtr<FSLSlicingEvent> Event = MakeShareable(new FSLSlicingEvent(
FIds::NewGuidInBase64Url(), StartTime,
FIds::PairEncodeCantor(PerformedBy.Obj->GetUniqueID(), ObjectActedOn.Obj->GetUniqueID()),
PerformedBy, DeviceUsed, ObjectActedOn));
// Add event to the pending array
StartedEvents.Emplace(Event);
}
// Publish finished event
bool FSLSlicingEventHandler::FinishEvent(UObject* ObjectActedOn, bool taskSuccess, float EndTime, const FSLEntity& OutputsCreated = FSLEntity())
{
// Use iterator to be able to remove the entry from the array
for (auto EventItr(StartedEvents.CreateIterator()); EventItr; ++EventItr)
{
// It is enough to compare against the other id when searching
if ((*EventItr)->ObjectActedOn.Obj == ObjectActedOn)
{
// Set end time and publish event
(*EventItr)->End = EndTime;
(*EventItr)->TaskSuccess = taskSuccess;
(*EventItr)->OutputsCreated = OutputsCreated;
OnSemanticEvent.ExecuteIfBound(*EventItr);
// Remove event from the pending list
EventItr.RemoveCurrent();
return true;
}
}
return false;
}
// Terminate and publish pending events (this usually is called at end play)
void FSLSlicingEventHandler::FinishAllEvents(float EndTime)
{
// Finish events
for (auto& Ev : StartedEvents)
{
// Set end time and publish event
Ev->End = EndTime;
OnSemanticEvent.ExecuteIfBound(Ev);
}
StartedEvents.Empty();
}
// Event called when a semantic Slicing event begins
void FSLSlicingEventHandler::OnSLSlicingBegin(UObject* PerformedBy, UObject* DeviceUsed, UObject* ObjectActedOn, float Time)
{
// Check that the objects are semantically annotated
FSLEntity PerformedByEntity = FSLEntitiesManager::GetInstance()->GetEntity(PerformedBy);
FSLEntity DeviceUsedEntity = FSLEntitiesManager::GetInstance()->GetEntity(DeviceUsed);
FSLEntity CutEntity = FSLEntitiesManager::GetInstance()->GetEntity(ObjectActedOn);
if (PerformedByEntity.IsSet()
&& CutEntity.IsSet()
&& DeviceUsedEntity.IsSet())
{
FSLSlicingEventHandler::AddNewEvent(PerformedByEntity, DeviceUsedEntity, CutEntity, Time);
}
}
// Event called when a semantic Slicing event ends
void FSLSlicingEventHandler::OnSLSlicingEndFail(UObject* PerformedBy, UObject* ObjectActedOn, float Time)
{
FSLEntity PerformedByEntity = FSLEntitiesManager::GetInstance()->GetEntity(PerformedBy);
FSLEntity CutEntity = FSLEntitiesManager::GetInstance()->GetEntity(ObjectActedOn);
if (PerformedByEntity.IsSet()
&& CutEntity.IsSet())
{
FSLSlicingEventHandler::FinishEvent(ObjectActedOn, false, Time);
}
}
// Event called when a semantic Slicing event ends
void FSLSlicingEventHandler::OnSLSlicingEndSuccess(UObject* PerformedBy, UObject* ObjectActedOn, UObject* OutputsCreated, float Time)
{
FSLEntity PerformedByEntity = FSLEntitiesManager::GetInstance()->GetEntity(PerformedBy);
FSLEntity CutEntity = FSLEntitiesManager::GetInstance()->GetEntity(ObjectActedOn);
FSLEntity OutputsCreatedEntity = FSLEntitiesManager::GetInstance()->GetEntity(OutputsCreated);
if (PerformedByEntity.IsSet()
&& CutEntity.IsSet()
&& OutputsCreatedEntity.IsSet())
{
FSLSlicingEventHandler::FinishEvent(ObjectActedOn, true, Time, OutputsCreatedEntity);
}
}
// Event called when new objects are created
void FSLSlicingEventHandler::OnSLObjectCreation(UObject* TransformedObject, UObject* NewSlice, float Time)
{
// Only create Id for new Slice and use same old ID for Original object
FString IdValue = FIds::NewGuidInBase64() + "_";
IdValue.Append(FTags::GetValue(TransformedObject, "SemLog", "Id"));
FTags::AddKeyValuePair(NewSlice, "SemLog", "Id", IdValue, true);
if (FSLEntitiesManager::GetInstance()->AddObject(TransformedObject) &&
FSLEntitiesManager::GetInstance()->AddObject(NewSlice))
{
UE_LOG(LogTemp, Error, TEXT(">>Items Have been Created"));
}
}
// Event called when an object is destroyed
void FSLSlicingEventHandler::OnSLObjectDestruction(UObject* ObjectActedOn, float Time)
{
FSLEntity OtherItem = FSLEntitiesManager::GetInstance()->GetEntity(ObjectActedOn);
if (OtherItem.IsSet())
{
FSLEntitiesManager::GetInstance()->RemoveEntity(ObjectActedOn);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAcosImageFilter.h"
#include "itkAdaptImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkAnisotropicDiffusionFunction.h"
#include "itkAnisotropicDiffusionImageFilter.h"
#include "itkAsinImageFilter.h"
#include "itkAtan2ImageFilter.h"
#include "itkAtanImageFilter.h"
#include "itkBinaryDilateImageFilter.txx"
#include "itkBinaryErodeImageFilter.txx"
#include "itkBinaryFunctorImageFilter.txx"
#include "itkBinaryMagnitudeImageFilter.h"
#include "itkBinaryThresholdImageFilter.txx"
#include "itkBinomialBlurImageFilter.txx"
#include "itkBloxBoundaryPointToCoreAtomImageFilter.txx"
#include "itkCannyEdgeDetectionImageFilter.txx"
#include "itkCastImageFilter.h"
#include "itkChangeInformationImageFilter.txx"
#include "itkConfidenceConnectedImageFilter.txx"
#include "itkConnectedThresholdImageFilter.txx"
#include "itkConstantPadImageFilter.txx"
#include "itkCosImageFilter.h"
#include "itkCropImageFilter.txx"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureNDAnisotropicDiffusionFunction.txx"
#include "itkDanielssonDistanceMapImageFilter.txx"
#include "itkDerivativeImageFilter.txx"
#include "itkDifferenceOfGaussiansGradientImageFilter.txx"
#include "itkDiscreteGaussianImageFilter.txx"
#include "itkDivideImageFilter.h"
#include "itkEdgePotentialImageFilter.h"
#include "itkEigenAnalysis2DImageFilter.txx"
#include "itkExpImageFilter.h"
#include "itkExpandImageFilter.txx"
#include "itkExtractImageFilter.txx"
#include "itkExtractImageFilterRegionCopier.h"
#include "itkFileIOToImageFilter.txx"
#include "itkFlipImageFilter.txx"
#include "itkGaussianImageSource.txx"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkGradientImageFilter.txx"
#include "itkGradientImageToBloxBoundaryPointImageFilter.txx"
#include "itkGradientMagnitudeImageFilter.txx"
#include "itkGradientNDAnisotropicDiffusionFunction.txx"
#include "itkGradientRecursiveGaussianImageFilter.txx"
#include "itkGradientToMagnitudeImageFilter.txx"
#include "itkGrayscaleDilateImageFilter.txx"
#include "itkGrayscaleErodeImageFilter.txx"
#include "itkGrayscaleFunctionDilateImageFilter.txx"
#include "itkGrayscaleFunctionErodeImageFilter.txx"
#include "itkHardConnectedComponentImageFilter.txx"
#include "itkImageToMeshFilter.txx"
#include "itkImageToParametricSpaceFilter.txx"
#include "itkImportImageFilter.txx"
#include "itkInteriorExteriorMeshFilter.txx"
#include "itkIsolatedConnectedImageFilter.txx"
#include "itkJoinImageFilter.h"
#include "itkLaplacianImageFilter.txx"
#include "itkLog10ImageFilter.h"
#include "itkLogImageFilter.h"
#include "itkMeanImageFilter.txx"
#include "itkMedianImageFilter.txx"
#include "itkMinimumMaximumImageCalculator.txx"
#include "itkMinimumMaximumImageFilter.txx"
#include "itkMirrorPadImageFilter.txx"
#include "itkMorphologyImageFilter.txx"
#include "itkMultiplyImageFilter.h"
#include "itkNaryAddImageFilter.h"
#include "itkNaryFunctorImageFilter.txx"
#include "itkNeighborhoodConnectedImageFilter.txx"
#include "itkNeighborhoodOperatorImageFilter.txx"
#include "itkNonThreadedShrinkImageFilter.txx"
#include "itkNormalizeImageFilter.txx"
#include "itkPadImageFilter.txx"
#include "itkParametricSpaceToImageSpaceMeshFilter.txx"
#include "itkPermuteAxesImageFilter.txx"
#include "itkPlaheImageFilter.txx"
#include "itkRandomImageSource.txx"
#include "itkRecursiveGaussianImageFilter.txx"
#include "itkRecursiveSeparableImageFilter.txx"
#include "itkReflectImageFilter.txx"
#include "itkReflectiveImageRegionIterator.txx"
#include "itkResampleImageFilter.txx"
#include "itkRescaleIntensityImageFilter.txx"
#include "itkScalarAnisotropicDiffusionFunction.txx"
#include "itkShiftScaleImageFilter.txx"
#include "itkShrinkImageFilter.txx"
#include "itkSimilarityIndexImageFilter.txx"
#include "itkSinImageFilter.h"
#include "itkSobelEdgeDetectionImageFilter.txx"
#include "itkSparseFieldLevelSetImageFilter.txx"
#include "itkSparseLevelSetNode.h"
#include "itkSpatialFunctionImageEvaluatorFilter.txx"
#include "itkSqrtImageFilter.h"
#include "itkStatisticsImageFilter.txx"
#include "itkStreamingImageFilter.txx"
#include "itkSubtractImageFilter.h"
#include "itkTanImageFilter.h"
#include "itkTernaryAddImageFilter.h"
#include "itkTernaryFunctorImageFilter.txx"
#include "itkTernaryMagnitudeImageFilter.h"
#include "itkTernaryMagnitudeSquaredImageFilter.h"
#include "itkThresholdImageFilter.txx"
#include "itkTransformMeshFilter.txx"
#include "itkTwoOutputExampleImageFilter.txx"
#include "itkUnaryFunctorImageFilter.txx"
#include "itkVTKImageExport.txx"
#include "itkVTKImageExportBase.h"
#include "itkVTKImageImport.txx"
#include "itkVectorAnisotropicDiffusionFunction.txx"
#include "itkVectorCastImageFilter.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkVectorCurvatureNDAnisotropicDiffusionFunction.txx"
#include "itkVectorExpandImageFilter.txx"
#include "itkVectorGradientAnisotropicDiffusionImageFilter.h"
#include "itkVectorGradientNDAnisotropicDiffusionFunction.txx"
#include "itkVectorNeighborhoodOperatorImageFilter.txx"
#include "itkWarpImageFilter.txx"
#include "itkWrapPadImageFilter.txx"
#include "itkZeroCrossingBasedEdgeDetectionImageFilter.txx"
#include "itkZeroCrossingImageFilter.txx"
int main ( int argc, char* argv )
{
return 0;
}
<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAcosImageFilter.h"
#include "itkAdaptImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkAnisotropicDiffusionFunction.h"
#include "itkAnisotropicDiffusionImageFilter.h"
#include "itkAsinImageFilter.h"
#include "itkAtan2ImageFilter.h"
#include "itkAtanImageFilter.h"
#include "itkBinaryDilateImageFilter.txx"
#include "itkBinaryErodeImageFilter.txx"
#include "itkBinaryFunctorImageFilter.txx"
#include "itkBinaryMagnitudeImageFilter.h"
#include "itkBinaryThresholdImageFilter.txx"
#include "itkBinomialBlurImageFilter.txx"
#include "itkBloxBoundaryPointToCoreAtomImageFilter.txx"
#include "itkCannyEdgeDetectionImageFilter.txx"
#include "itkCastImageFilter.h"
#include "itkChangeInformationImageFilter.txx"
#include "itkConfidenceConnectedImageFilter.txx"
#include "itkConnectedThresholdImageFilter.txx"
#include "itkConstantPadImageFilter.txx"
#include "itkCosImageFilter.h"
#include "itkCropImageFilter.txx"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureNDAnisotropicDiffusionFunction.txx"
#include "itkDanielssonDistanceMapImageFilter.txx"
#include "itkDerivativeImageFilter.txx"
#include "itkDifferenceOfGaussiansGradientImageFilter.txx"
#include "itkDirectedHausdorffDistanceImageFilter.txx"
#include "itkDiscreteGaussianImageFilter.txx"
#include "itkDivideImageFilter.h"
#include "itkEdgePotentialImageFilter.h"
#include "itkEigenAnalysis2DImageFilter.txx"
#include "itkExpImageFilter.h"
#include "itkExpandImageFilter.txx"
#include "itkExtractImageFilter.txx"
#include "itkExtractImageFilterRegionCopier.h"
#include "itkFileIOToImageFilter.txx"
#include "itkFlipImageFilter.txx"
#include "itkGaussianImageSource.txx"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkGradientImageFilter.txx"
#include "itkGradientImageToBloxBoundaryPointImageFilter.txx"
#include "itkGradientMagnitudeImageFilter.txx"
#include "itkGradientNDAnisotropicDiffusionFunction.txx"
#include "itkGradientRecursiveGaussianImageFilter.txx"
#include "itkGradientToMagnitudeImageFilter.txx"
#include "itkGrayscaleDilateImageFilter.txx"
#include "itkGrayscaleErodeImageFilter.txx"
#include "itkGrayscaleFunctionDilateImageFilter.txx"
#include "itkGrayscaleFunctionErodeImageFilter.txx"
#include "itkHardConnectedComponentImageFilter.txx"
#include "itkHausdorffDistanceImageFilter.txx"
#include "itkImageToMeshFilter.txx"
#include "itkImageToParametricSpaceFilter.txx"
#include "itkImportImageFilter.txx"
#include "itkInteriorExteriorMeshFilter.txx"
#include "itkIsolatedConnectedImageFilter.txx"
#include "itkJoinImageFilter.h"
#include "itkLaplacianImageFilter.txx"
#include "itkLog10ImageFilter.h"
#include "itkLogImageFilter.h"
#include "itkMeanImageFilter.txx"
#include "itkMedianImageFilter.txx"
#include "itkMinimumMaximumImageCalculator.txx"
#include "itkMinimumMaximumImageFilter.txx"
#include "itkMirrorPadImageFilter.txx"
#include "itkMorphologyImageFilter.txx"
#include "itkMultiplyImageFilter.h"
#include "itkNaryAddImageFilter.h"
#include "itkNaryFunctorImageFilter.txx"
#include "itkNeighborhoodConnectedImageFilter.txx"
#include "itkNeighborhoodOperatorImageFilter.txx"
#include "itkNonThreadedShrinkImageFilter.txx"
#include "itkNormalizeImageFilter.txx"
#include "itkPadImageFilter.txx"
#include "itkParametricSpaceToImageSpaceMeshFilter.txx"
#include "itkPermuteAxesImageFilter.txx"
#include "itkPlaheImageFilter.txx"
#include "itkRandomImageSource.txx"
#include "itkRecursiveGaussianImageFilter.txx"
#include "itkRecursiveSeparableImageFilter.txx"
#include "itkReflectImageFilter.txx"
#include "itkReflectiveImageRegionIterator.txx"
#include "itkResampleImageFilter.txx"
#include "itkRescaleIntensityImageFilter.txx"
#include "itkScalarAnisotropicDiffusionFunction.txx"
#include "itkShiftScaleImageFilter.txx"
#include "itkShrinkImageFilter.txx"
#include "itkSimilarityIndexImageFilter.txx"
#include "itkSinImageFilter.h"
#include "itkSobelEdgeDetectionImageFilter.txx"
#include "itkSparseFieldLevelSetImageFilter.txx"
#include "itkSparseLevelSetNode.h"
#include "itkSpatialFunctionImageEvaluatorFilter.txx"
#include "itkSqrtImageFilter.h"
#include "itkStatisticsImageFilter.txx"
#include "itkStreamingImageFilter.txx"
#include "itkSubtractImageFilter.h"
#include "itkTanImageFilter.h"
#include "itkTernaryAddImageFilter.h"
#include "itkTernaryFunctorImageFilter.txx"
#include "itkTernaryMagnitudeImageFilter.h"
#include "itkTernaryMagnitudeSquaredImageFilter.h"
#include "itkThresholdImageFilter.txx"
#include "itkTransformMeshFilter.txx"
#include "itkTwoOutputExampleImageFilter.txx"
#include "itkUnaryFunctorImageFilter.txx"
#include "itkVTKImageExport.txx"
#include "itkVTKImageExportBase.h"
#include "itkVTKImageImport.txx"
#include "itkVectorAnisotropicDiffusionFunction.txx"
#include "itkVectorCastImageFilter.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkVectorCurvatureNDAnisotropicDiffusionFunction.txx"
#include "itkVectorExpandImageFilter.txx"
#include "itkVectorGradientAnisotropicDiffusionImageFilter.h"
#include "itkVectorGradientNDAnisotropicDiffusionFunction.txx"
#include "itkVectorNeighborhoodOperatorImageFilter.txx"
#include "itkWarpImageFilter.txx"
#include "itkWrapPadImageFilter.txx"
#include "itkZeroCrossingBasedEdgeDetectionImageFilter.txx"
#include "itkZeroCrossingImageFilter.txx"
int main ( int argc, char* argv )
{
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Include <stdlib.h> for the declarations of memcpy, malloc, free. This is needed for the "chromium-rel-linux-jaunty" builder.<commit_after><|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#pragma once
#ifndef OPENCV_CUDEV_UTIL_SATURATE_CAST_HPP
#define OPENCV_CUDEV_UTIL_SATURATE_CAST_HPP
#include "../common.hpp"
#if __CUDACC_VER_MAJOR__ >= 9
#include <cuda_fp16.h>
#endif
namespace cv { namespace cudev {
//! @addtogroup cudev
//! @{
template <typename T> __device__ __forceinline__ T saturate_cast(uchar v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(schar v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(ushort v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(short v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(uint v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(int v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(float v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(double v) { return T(v); }
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(schar v)
{
uint res = 0;
int vi = v;
asm("cvt.sat.u8.s8 %0, %1;" : "=r"(res) : "r"(vi));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(short v)
{
uint res = 0;
asm("cvt.sat.u8.s16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(ushort v)
{
uint res = 0;
asm("cvt.sat.u8.u16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(int v)
{
uint res = 0;
asm("cvt.sat.u8.s32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(uint v)
{
uint res = 0;
asm("cvt.sat.u8.u32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(float v)
{
uint res = 0;
asm("cvt.rni.sat.u8.f32 %0, %1;" : "=r"(res) : "f"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(double v)
{
uint res = 0;
asm("cvt.rni.sat.u8.f64 %0, %1;" : "=r"(res) : "d"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(uchar v)
{
uint res = 0;
uint vi = v;
asm("cvt.sat.s8.u8 %0, %1;" : "=r"(res) : "r"(vi));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(short v)
{
uint res = 0;
asm("cvt.sat.s8.s16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(ushort v)
{
uint res = 0;
asm("cvt.sat.s8.u16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(int v)
{
uint res = 0;
asm("cvt.sat.s8.s32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(uint v)
{
uint res = 0;
asm("cvt.sat.s8.u32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(float v)
{
uint res = 0;
asm("cvt.rni.sat.s8.f32 %0, %1;" : "=r"(res) : "f"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(double v)
{
uint res = 0;
asm("cvt.rni.sat.s8.f64 %0, %1;" : "=r"(res) : "d"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(schar v)
{
ushort res = 0;
int vi = v;
asm("cvt.sat.u16.s8 %0, %1;" : "=h"(res) : "r"(vi));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(short v)
{
ushort res = 0;
asm("cvt.sat.u16.s16 %0, %1;" : "=h"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(int v)
{
ushort res = 0;
asm("cvt.sat.u16.s32 %0, %1;" : "=h"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(uint v)
{
ushort res = 0;
asm("cvt.sat.u16.u32 %0, %1;" : "=h"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(float v)
{
ushort res = 0;
asm("cvt.rni.sat.u16.f32 %0, %1;" : "=h"(res) : "f"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(double v)
{
ushort res = 0;
asm("cvt.rni.sat.u16.f64 %0, %1;" : "=h"(res) : "d"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(ushort v)
{
short res = 0;
asm("cvt.sat.s16.u16 %0, %1;" : "=h"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(int v)
{
short res = 0;
asm("cvt.sat.s16.s32 %0, %1;" : "=h"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(uint v)
{
short res = 0;
asm("cvt.sat.s16.u32 %0, %1;" : "=h"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(float v)
{
short res = 0;
asm("cvt.rni.sat.s16.f32 %0, %1;" : "=h"(res) : "f"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(double v)
{
short res = 0;
asm("cvt.rni.sat.s16.f64 %0, %1;" : "=h"(res) : "d"(v));
return res;
}
template <> __device__ __forceinline__ int saturate_cast<int>(uint v)
{
int res = 0;
asm("cvt.sat.s32.u32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ int saturate_cast<int>(float v)
{
return __float2int_rn(v);
}
template <> __device__ __forceinline__ int saturate_cast<int>(double v)
{
#if CV_CUDEV_ARCH >= 130
return __double2int_rn(v);
#else
return saturate_cast<int>((float) v);
#endif
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(schar v)
{
uint res = 0;
int vi = v;
asm("cvt.sat.u32.s8 %0, %1;" : "=r"(res) : "r"(vi));
return res;
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(short v)
{
uint res = 0;
asm("cvt.sat.u32.s16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(int v)
{
uint res = 0;
asm("cvt.sat.u32.s32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(float v)
{
return __float2uint_rn(v);
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(double v)
{
#if CV_CUDEV_ARCH >= 130
return __double2uint_rn(v);
#else
return saturate_cast<uint>((float) v);
#endif
}
template <typename T, typename D> __device__ __forceinline__ D cast_fp16(T v);
template <> __device__ __forceinline__ float cast_fp16<short, float>(short v)
{
#if __CUDACC_VER_MAJOR__ >= 9
return float(*(__half*)&v);
#else
return __half2float(v);
#endif
}
template <> __device__ __forceinline__ short cast_fp16<float, short>(float v)
{
#if __CUDACC_VER_MAJOR__ >= 9
__half h(v);
return *(short*)&v;
#else
return (short)__float2half_rn(v);
#endif
}
//! @}
}}
#endif
<commit_msg>fix CvFp16Test failure<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#pragma once
#ifndef OPENCV_CUDEV_UTIL_SATURATE_CAST_HPP
#define OPENCV_CUDEV_UTIL_SATURATE_CAST_HPP
#include "../common.hpp"
#if __CUDACC_VER_MAJOR__ >= 9
#include <cuda_fp16.h>
#endif
namespace cv { namespace cudev {
//! @addtogroup cudev
//! @{
template <typename T> __device__ __forceinline__ T saturate_cast(uchar v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(schar v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(ushort v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(short v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(uint v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(int v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(float v) { return T(v); }
template <typename T> __device__ __forceinline__ T saturate_cast(double v) { return T(v); }
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(schar v)
{
uint res = 0;
int vi = v;
asm("cvt.sat.u8.s8 %0, %1;" : "=r"(res) : "r"(vi));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(short v)
{
uint res = 0;
asm("cvt.sat.u8.s16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(ushort v)
{
uint res = 0;
asm("cvt.sat.u8.u16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(int v)
{
uint res = 0;
asm("cvt.sat.u8.s32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(uint v)
{
uint res = 0;
asm("cvt.sat.u8.u32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(float v)
{
uint res = 0;
asm("cvt.rni.sat.u8.f32 %0, %1;" : "=r"(res) : "f"(v));
return res;
}
template <> __device__ __forceinline__ uchar saturate_cast<uchar>(double v)
{
uint res = 0;
asm("cvt.rni.sat.u8.f64 %0, %1;" : "=r"(res) : "d"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(uchar v)
{
uint res = 0;
uint vi = v;
asm("cvt.sat.s8.u8 %0, %1;" : "=r"(res) : "r"(vi));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(short v)
{
uint res = 0;
asm("cvt.sat.s8.s16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(ushort v)
{
uint res = 0;
asm("cvt.sat.s8.u16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(int v)
{
uint res = 0;
asm("cvt.sat.s8.s32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(uint v)
{
uint res = 0;
asm("cvt.sat.s8.u32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(float v)
{
uint res = 0;
asm("cvt.rni.sat.s8.f32 %0, %1;" : "=r"(res) : "f"(v));
return res;
}
template <> __device__ __forceinline__ schar saturate_cast<schar>(double v)
{
uint res = 0;
asm("cvt.rni.sat.s8.f64 %0, %1;" : "=r"(res) : "d"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(schar v)
{
ushort res = 0;
int vi = v;
asm("cvt.sat.u16.s8 %0, %1;" : "=h"(res) : "r"(vi));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(short v)
{
ushort res = 0;
asm("cvt.sat.u16.s16 %0, %1;" : "=h"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(int v)
{
ushort res = 0;
asm("cvt.sat.u16.s32 %0, %1;" : "=h"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(uint v)
{
ushort res = 0;
asm("cvt.sat.u16.u32 %0, %1;" : "=h"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(float v)
{
ushort res = 0;
asm("cvt.rni.sat.u16.f32 %0, %1;" : "=h"(res) : "f"(v));
return res;
}
template <> __device__ __forceinline__ ushort saturate_cast<ushort>(double v)
{
ushort res = 0;
asm("cvt.rni.sat.u16.f64 %0, %1;" : "=h"(res) : "d"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(ushort v)
{
short res = 0;
asm("cvt.sat.s16.u16 %0, %1;" : "=h"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(int v)
{
short res = 0;
asm("cvt.sat.s16.s32 %0, %1;" : "=h"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(uint v)
{
short res = 0;
asm("cvt.sat.s16.u32 %0, %1;" : "=h"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(float v)
{
short res = 0;
asm("cvt.rni.sat.s16.f32 %0, %1;" : "=h"(res) : "f"(v));
return res;
}
template <> __device__ __forceinline__ short saturate_cast<short>(double v)
{
short res = 0;
asm("cvt.rni.sat.s16.f64 %0, %1;" : "=h"(res) : "d"(v));
return res;
}
template <> __device__ __forceinline__ int saturate_cast<int>(uint v)
{
int res = 0;
asm("cvt.sat.s32.u32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ int saturate_cast<int>(float v)
{
return __float2int_rn(v);
}
template <> __device__ __forceinline__ int saturate_cast<int>(double v)
{
#if CV_CUDEV_ARCH >= 130
return __double2int_rn(v);
#else
return saturate_cast<int>((float) v);
#endif
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(schar v)
{
uint res = 0;
int vi = v;
asm("cvt.sat.u32.s8 %0, %1;" : "=r"(res) : "r"(vi));
return res;
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(short v)
{
uint res = 0;
asm("cvt.sat.u32.s16 %0, %1;" : "=r"(res) : "h"(v));
return res;
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(int v)
{
uint res = 0;
asm("cvt.sat.u32.s32 %0, %1;" : "=r"(res) : "r"(v));
return res;
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(float v)
{
return __float2uint_rn(v);
}
template <> __device__ __forceinline__ uint saturate_cast<uint>(double v)
{
#if CV_CUDEV_ARCH >= 130
return __double2uint_rn(v);
#else
return saturate_cast<uint>((float) v);
#endif
}
template <typename T, typename D> __device__ __forceinline__ D cast_fp16(T v);
template <> __device__ __forceinline__ float cast_fp16<short, float>(short v)
{
#if __CUDACC_VER_MAJOR__ >= 9
return float(*(__half*)&v);
#else
return __half2float(v);
#endif
}
template <> __device__ __forceinline__ short cast_fp16<float, short>(float v)
{
#if __CUDACC_VER_MAJOR__ >= 9
__half h(v);
return *(short*)&h;
#else
return (short)__float2half_rn(v);
#endif
}
//! @}
}}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/curvecp/messenger.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/curvecp/protocol.h"
// Basic protocol design:
//
// OnTimeout: Called when the timeout timer pops.
// - call SendMessage()
// - call RecvMessage()
//
// OnSendTimer: Called when the send-timer pops.
// - call SendMessage()
// - call RecvMessage()
//
// OnMessage: Called when a message arrived from the packet layer
// - add the message to the receive queue
// - call RecvMessage()
//
// Write: Called by application to write data to remote
// - add the data to the send_buffer
// - call SendMessage()
//
// SendMessage: Called to Send a message to the remote
// - msg = first message to retransmit where retransmit timer popped
// - if msg == NULL
// - msg = create a new message from the send buffer
// - if msg != NULL
// - send message to the packet layer
// - setTimer(OnSendTimer, send_rate);
//
// RecvMessage: Called to process a Received message from the remote
// - calculate RTT
// - calculate Send Rate
// - acknowledge data from received message
// - resetTimeout
// - timeout = now + rtt_timeout
// - if currrent_timeout > timeout
// setTimer(OnTimeout, timeout)
namespace net {
// Maximum number of write blocks.
static const size_t kMaxWriteQueueMessages = 128;
// Size of the send buffer.
static const size_t kSendBufferSize = (128 * 1024);
// Size of the receive buffer.
static const size_t kReceiveBufferSize = (128 * 1024);
Messenger::Messenger(Packetizer* packetizer)
: packetizer_(packetizer),
send_buffer_(kSendBufferSize),
send_complete_callback_(NULL),
receive_complete_callback_(NULL),
pending_receive_length_(0),
send_message_in_progress_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(
send_message_callback_(this, &Messenger::OnSendMessageComplete)),
ALLOW_THIS_IN_INITIALIZER_LIST(factory_(this)) {
}
Messenger::~Messenger() {
}
int Messenger::Read(IOBuffer* buf, int buf_len, CompletionCallback* callback) {
DCHECK(CalledOnValidThread());
DCHECK(!receive_complete_callback_);
if (!received_list_.bytes_available()) {
receive_complete_callback_ = callback;
pending_receive_ = buf;
pending_receive_length_ = buf_len;
return ERR_IO_PENDING;
}
int bytes_read = InternalRead(buf, buf_len);
DCHECK_LT(0, bytes_read);
return bytes_read;
}
int Messenger::Write(IOBuffer* buf, int buf_len, CompletionCallback* callback) {
DCHECK(CalledOnValidThread());
DCHECK(!pending_send_.get()); // Already a write pending!
DCHECK(!send_complete_callback_);
DCHECK_LT(0, buf_len);
int len = send_buffer_.write(buf->data(), buf_len);
if (!send_timer_.IsRunning())
send_timer_.Start(base::TimeDelta(), this, &Messenger::OnSendTimer);
if (len)
return len;
// We couldn't add data to the send buffer, so block the application.
pending_send_ = buf;
pending_send_length_ = buf_len;
send_complete_callback_ = callback;
return ERR_IO_PENDING;
}
void Messenger::OnConnection(ConnectionKey key) {
LOG(ERROR) << "Client Connect: " << key.ToString();
key_ = key;
}
void Messenger::OnClose(Packetizer* packetizer, ConnectionKey key) {
LOG(ERROR) << "Got Close!";
}
void Messenger::OnMessage(Packetizer* packetizer,
ConnectionKey key,
unsigned char* msg,
size_t length) {
DCHECK(key == key_);
// Do basic message sanity checking.
if (length < sizeof(Message))
return;
if (length > static_cast<size_t>(kMaxMessageLength))
return;
// Add message to received queue.
scoped_refptr<IOBufferWithSize> buffer(new IOBufferWithSize(length));
memcpy(buffer->data(), msg, length);
read_queue_.push_back(buffer);
// Process a single received message
RecvMessage();
}
int Messenger::InternalRead(IOBuffer* buffer, int buffer_length) {
return received_list_.ReadBytes(buffer, buffer_length);
}
IOBufferWithSize* Messenger::CreateBufferFromSendQueue() {
DCHECK_LT(0, send_buffer_.length());
int length = std::min(packetizer_->max_message_payload(),
send_buffer_.length());
IOBufferWithSize* rv = new IOBufferWithSize(length);
int bytes = send_buffer_.read(rv->data(), length);
DCHECK_EQ(bytes, length);
// We consumed data, check to see if someone is waiting to write more data.
if (send_complete_callback_) {
DCHECK(pending_send_.get());
int len = send_buffer_.write(pending_send_->data(), pending_send_length_);
if (len) {
pending_send_ = NULL;
CompletionCallback* callback = send_complete_callback_;
send_complete_callback_ = NULL;
callback->Run(len);
}
}
return rv;
}
void Messenger::OnSendMessageComplete(int result) {
DCHECK_NE(ERR_IO_PENDING, result);
send_message_in_progress_ = false;
if (result <= 0) {
// TODO(mbelshe): Handle error.
NOTIMPLEMENTED();
}
// If the send timer fired while we were waiting for this send to complete,
// we need to manually run the timer now.
if (!send_timer_.IsRunning())
OnSendTimer();
if (!send_timeout_timer_.IsRunning()) {
LOG(ERROR) << "RttTimeout is " << rtt_.rtt_timeout();
base::TimeDelta delay =
base::TimeDelta::FromMicroseconds(rtt_.rtt_timeout());
send_timeout_timer_.Start(delay, this, &Messenger::OnTimeout);
}
}
void Messenger::OnTimeout() {
LOG(ERROR) << "OnTimeout fired";
int64 position = sent_list_.FindPositionOfOldestSentBlock();
// XXXMB - need to verify that we really need to retransmit...
if (position >= 0) {
rtt_.OnTimeout(); // adjust our send rate.
LOG(ERROR) << "OnTimeout retransmitting: " << position;
SendMessage(position);
} else {
DCHECK_EQ(0u, sent_list_.size());
}
RecvMessage();
received_list_.LogBlockList();
}
void Messenger::OnSendTimer() {
LOG(ERROR) << "OnSendTimer!";
DCHECK(!send_timer_.IsRunning());
// If the send buffer is empty, then we don't need to keep firing.
if (!send_buffer_.length()) {
LOG(ERROR) << "OnSendTimer: send_buffer empty";
return;
}
// Set the next send timer.
LOG(ERROR) << "SendRate is: " << rtt_.send_rate() << "us";
send_timer_.Start(base::TimeDelta::FromMicroseconds(rtt_.send_rate()),
this,
&Messenger::OnSendTimer);
// Create a block from the send_buffer.
if (!sent_list_.is_full()) {
scoped_refptr<IOBufferWithSize> buffer = CreateBufferFromSendQueue();
int64 position = sent_list_.CreateBlock(buffer.get());
DCHECK_LE(0, position);
SendMessage(position);
}
RecvMessage(); // Try to process an incoming message
}
void Messenger::SendMessage(int64 position) {
LOG(ERROR) << "SendMessage (position=" << position << ")";
if (send_message_in_progress_)
return; // We're still waiting for the last write to complete.
IOBufferWithSize* data = sent_list_.FindBlockByPosition(position);
DCHECK(data != NULL);
size_t message_size = sizeof(Message) + data->size();
size_t padded_size = (message_size + 15) & 0xfffffff0;
scoped_refptr<IOBufferWithSize> message(new IOBufferWithSize(padded_size));
Message* header = reinterpret_cast<Message*>(message->data());
memset(header, 0, sizeof(Message));
uint64 id = sent_list_.GetNewMessageId();
uint32_pack(header->message_id, id);
// TODO(mbelshe): Needs to carry EOF flags
uint16_pack(header->size.val, data->size());
uint64_pack(header->position, position);
// TODO(mbelshe): Fill in rest of the header fields.
// needs to have the block-position. He tags each chunk with an
// absolute offset into the data stream.
// Copy the contents of the message into the Message frame.
memcpy(message->data() + sizeof(Message), data->data(), data->size());
sent_list_.MarkBlockSent(position, id);
int rv = packetizer_->SendMessage(key_,
message->data(),
padded_size,
&send_message_callback_);
if (rv == ERR_IO_PENDING) {
send_message_in_progress_ = true;
return;
}
// UDP must write all or none.
DCHECK_EQ(padded_size, static_cast<size_t>(rv));
OnSendMessageComplete(rv);
}
void Messenger::RecvMessage() {
if (!read_queue_.size())
return;
scoped_refptr<IOBufferWithSize> message(read_queue_.front());
read_queue_.pop_front();
Message* header = reinterpret_cast<Message*>(message->data());
uint16 body_length = uint16_unpack(header->size.val);
if (body_length < 0)
return;
if (body_length > kMaxMessageLength)
return;
if (body_length > message->size())
return;
uint32 message_id = uint32_unpack(header->message_id);
if (message_id) {
LOG(ERROR) << "RecvMessage Message id: " << message_id
<< ", " << body_length << " bytes";
} else {
LOG(ERROR) << "RecvMessage ACK ";
}
// See if this message has information for recomputing RTT.
uint32 response_to_msg = uint32_unpack(header->last_message_received);
base::TimeTicks last_sent_time = sent_list_.FindLastSendTime(response_to_msg);
if (!last_sent_time.is_null()) {
int rtt = (base::TimeTicks::Now() - last_sent_time).InMicroseconds();
DCHECK_LE(0, rtt);
LOG(ERROR) << "RTT was: " << rtt << "us";
rtt_.OnMessage(rtt);
}
// Handle acknowledgements
uint64 start_byte = 0;
uint64 stop_byte = uint64_unpack(header->acknowledge_1);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_1);
stop_byte = start_byte + uint16_unpack(header->acknowledge_2);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_2);
stop_byte = start_byte + uint16_unpack(header->acknowledge_3);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_3);
stop_byte = start_byte + uint16_unpack(header->acknowledge_4);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_4);
stop_byte = start_byte + uint16_unpack(header->acknowledge_5);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_5);
stop_byte = start_byte + uint16_unpack(header->acknowledge_6);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
if (!header->is_ack()) {
// Add to our received block list
uint64 position = uint64_unpack(header->position);
scoped_refptr<IOBuffer> buffer(new IOBuffer(body_length));
memcpy(buffer->data(), message->data() + sizeof(Message), body_length);
received_list_.AddBlock(position, buffer, body_length);
SendAck(message_id);
}
// If we have data available, and a read is pending, notify the callback.
if (received_list_.bytes_available() && receive_complete_callback_) {
// Pass the data up to the caller.
int bytes_read = InternalRead(pending_receive_, pending_receive_length_);
CompletionCallback* callback = receive_complete_callback_;
receive_complete_callback_ = NULL;
callback->Run(bytes_read);
}
}
void Messenger::SendAck(uint32 last_message_received) {
scoped_refptr<IOBuffer> buffer(new IOBuffer(sizeof(Message)));
memset(buffer->data(), 0, sizeof(Message));
Message* message = reinterpret_cast<Message*>(buffer->data());
uint32_pack(message->last_message_received, last_message_received);
uint64_pack(message->acknowledge_1, received_list_.bytes_received());
LOG(ERROR) << "SendAck " << received_list_.bytes_received();
// TODO(mbelshe): fill in remainder of selective acknowledgements
// TODO(mbelshe): Fix this - it is totally possible to have a send message
// in progress here...
DCHECK(!send_message_in_progress_);
int rv = packetizer_->SendMessage(key_,
buffer->data(),
sizeof(Message),
&send_message_callback_);
// TODO(mbelshe): Fix me! Deal with the error cases
DCHECK(rv == sizeof(Message));
}
} // namespace net
<commit_msg>Remove unnecessary check which was invalid anyway.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/curvecp/messenger.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/curvecp/protocol.h"
// Basic protocol design:
//
// OnTimeout: Called when the timeout timer pops.
// - call SendMessage()
// - call RecvMessage()
//
// OnSendTimer: Called when the send-timer pops.
// - call SendMessage()
// - call RecvMessage()
//
// OnMessage: Called when a message arrived from the packet layer
// - add the message to the receive queue
// - call RecvMessage()
//
// Write: Called by application to write data to remote
// - add the data to the send_buffer
// - call SendMessage()
//
// SendMessage: Called to Send a message to the remote
// - msg = first message to retransmit where retransmit timer popped
// - if msg == NULL
// - msg = create a new message from the send buffer
// - if msg != NULL
// - send message to the packet layer
// - setTimer(OnSendTimer, send_rate);
//
// RecvMessage: Called to process a Received message from the remote
// - calculate RTT
// - calculate Send Rate
// - acknowledge data from received message
// - resetTimeout
// - timeout = now + rtt_timeout
// - if currrent_timeout > timeout
// setTimer(OnTimeout, timeout)
namespace net {
// Maximum number of write blocks.
static const size_t kMaxWriteQueueMessages = 128;
// Size of the send buffer.
static const size_t kSendBufferSize = (128 * 1024);
// Size of the receive buffer.
static const size_t kReceiveBufferSize = (128 * 1024);
Messenger::Messenger(Packetizer* packetizer)
: packetizer_(packetizer),
send_buffer_(kSendBufferSize),
send_complete_callback_(NULL),
receive_complete_callback_(NULL),
pending_receive_length_(0),
send_message_in_progress_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(
send_message_callback_(this, &Messenger::OnSendMessageComplete)),
ALLOW_THIS_IN_INITIALIZER_LIST(factory_(this)) {
}
Messenger::~Messenger() {
}
int Messenger::Read(IOBuffer* buf, int buf_len, CompletionCallback* callback) {
DCHECK(CalledOnValidThread());
DCHECK(!receive_complete_callback_);
if (!received_list_.bytes_available()) {
receive_complete_callback_ = callback;
pending_receive_ = buf;
pending_receive_length_ = buf_len;
return ERR_IO_PENDING;
}
int bytes_read = InternalRead(buf, buf_len);
DCHECK_LT(0, bytes_read);
return bytes_read;
}
int Messenger::Write(IOBuffer* buf, int buf_len, CompletionCallback* callback) {
DCHECK(CalledOnValidThread());
DCHECK(!pending_send_.get()); // Already a write pending!
DCHECK(!send_complete_callback_);
DCHECK_LT(0, buf_len);
int len = send_buffer_.write(buf->data(), buf_len);
if (!send_timer_.IsRunning())
send_timer_.Start(base::TimeDelta(), this, &Messenger::OnSendTimer);
if (len)
return len;
// We couldn't add data to the send buffer, so block the application.
pending_send_ = buf;
pending_send_length_ = buf_len;
send_complete_callback_ = callback;
return ERR_IO_PENDING;
}
void Messenger::OnConnection(ConnectionKey key) {
LOG(ERROR) << "Client Connect: " << key.ToString();
key_ = key;
}
void Messenger::OnClose(Packetizer* packetizer, ConnectionKey key) {
LOG(ERROR) << "Got Close!";
}
void Messenger::OnMessage(Packetizer* packetizer,
ConnectionKey key,
unsigned char* msg,
size_t length) {
DCHECK(key == key_);
// Do basic message sanity checking.
if (length < sizeof(Message))
return;
if (length > static_cast<size_t>(kMaxMessageLength))
return;
// Add message to received queue.
scoped_refptr<IOBufferWithSize> buffer(new IOBufferWithSize(length));
memcpy(buffer->data(), msg, length);
read_queue_.push_back(buffer);
// Process a single received message
RecvMessage();
}
int Messenger::InternalRead(IOBuffer* buffer, int buffer_length) {
return received_list_.ReadBytes(buffer, buffer_length);
}
IOBufferWithSize* Messenger::CreateBufferFromSendQueue() {
DCHECK_LT(0, send_buffer_.length());
int length = std::min(packetizer_->max_message_payload(),
send_buffer_.length());
IOBufferWithSize* rv = new IOBufferWithSize(length);
int bytes = send_buffer_.read(rv->data(), length);
DCHECK_EQ(bytes, length);
// We consumed data, check to see if someone is waiting to write more data.
if (send_complete_callback_) {
DCHECK(pending_send_.get());
int len = send_buffer_.write(pending_send_->data(), pending_send_length_);
if (len) {
pending_send_ = NULL;
CompletionCallback* callback = send_complete_callback_;
send_complete_callback_ = NULL;
callback->Run(len);
}
}
return rv;
}
void Messenger::OnSendMessageComplete(int result) {
DCHECK_NE(ERR_IO_PENDING, result);
send_message_in_progress_ = false;
if (result <= 0) {
// TODO(mbelshe): Handle error.
NOTIMPLEMENTED();
}
// If the send timer fired while we were waiting for this send to complete,
// we need to manually run the timer now.
if (!send_timer_.IsRunning())
OnSendTimer();
if (!send_timeout_timer_.IsRunning()) {
LOG(ERROR) << "RttTimeout is " << rtt_.rtt_timeout();
base::TimeDelta delay =
base::TimeDelta::FromMicroseconds(rtt_.rtt_timeout());
send_timeout_timer_.Start(delay, this, &Messenger::OnTimeout);
}
}
void Messenger::OnTimeout() {
LOG(ERROR) << "OnTimeout fired";
int64 position = sent_list_.FindPositionOfOldestSentBlock();
// XXXMB - need to verify that we really need to retransmit...
if (position >= 0) {
rtt_.OnTimeout(); // adjust our send rate.
LOG(ERROR) << "OnTimeout retransmitting: " << position;
SendMessage(position);
} else {
DCHECK_EQ(0u, sent_list_.size());
}
RecvMessage();
received_list_.LogBlockList();
}
void Messenger::OnSendTimer() {
LOG(ERROR) << "OnSendTimer!";
DCHECK(!send_timer_.IsRunning());
// If the send buffer is empty, then we don't need to keep firing.
if (!send_buffer_.length()) {
LOG(ERROR) << "OnSendTimer: send_buffer empty";
return;
}
// Set the next send timer.
LOG(ERROR) << "SendRate is: " << rtt_.send_rate() << "us";
send_timer_.Start(base::TimeDelta::FromMicroseconds(rtt_.send_rate()),
this,
&Messenger::OnSendTimer);
// Create a block from the send_buffer.
if (!sent_list_.is_full()) {
scoped_refptr<IOBufferWithSize> buffer = CreateBufferFromSendQueue();
int64 position = sent_list_.CreateBlock(buffer.get());
DCHECK_LE(0, position);
SendMessage(position);
}
RecvMessage(); // Try to process an incoming message
}
void Messenger::SendMessage(int64 position) {
LOG(ERROR) << "SendMessage (position=" << position << ")";
if (send_message_in_progress_)
return; // We're still waiting for the last write to complete.
IOBufferWithSize* data = sent_list_.FindBlockByPosition(position);
DCHECK(data != NULL);
size_t message_size = sizeof(Message) + data->size();
size_t padded_size = (message_size + 15) & 0xfffffff0;
scoped_refptr<IOBufferWithSize> message(new IOBufferWithSize(padded_size));
Message* header = reinterpret_cast<Message*>(message->data());
memset(header, 0, sizeof(Message));
uint64 id = sent_list_.GetNewMessageId();
uint32_pack(header->message_id, id);
// TODO(mbelshe): Needs to carry EOF flags
uint16_pack(header->size.val, data->size());
uint64_pack(header->position, position);
// TODO(mbelshe): Fill in rest of the header fields.
// needs to have the block-position. He tags each chunk with an
// absolute offset into the data stream.
// Copy the contents of the message into the Message frame.
memcpy(message->data() + sizeof(Message), data->data(), data->size());
sent_list_.MarkBlockSent(position, id);
int rv = packetizer_->SendMessage(key_,
message->data(),
padded_size,
&send_message_callback_);
if (rv == ERR_IO_PENDING) {
send_message_in_progress_ = true;
return;
}
// UDP must write all or none.
DCHECK_EQ(padded_size, static_cast<size_t>(rv));
OnSendMessageComplete(rv);
}
void Messenger::RecvMessage() {
if (!read_queue_.size())
return;
scoped_refptr<IOBufferWithSize> message(read_queue_.front());
read_queue_.pop_front();
Message* header = reinterpret_cast<Message*>(message->data());
uint16 body_length = uint16_unpack(header->size.val);
if (body_length > kMaxMessageLength)
return;
if (body_length > message->size())
return;
uint32 message_id = uint32_unpack(header->message_id);
if (message_id) {
LOG(ERROR) << "RecvMessage Message id: " << message_id
<< ", " << body_length << " bytes";
} else {
LOG(ERROR) << "RecvMessage ACK ";
}
// See if this message has information for recomputing RTT.
uint32 response_to_msg = uint32_unpack(header->last_message_received);
base::TimeTicks last_sent_time = sent_list_.FindLastSendTime(response_to_msg);
if (!last_sent_time.is_null()) {
int rtt = (base::TimeTicks::Now() - last_sent_time).InMicroseconds();
DCHECK_LE(0, rtt);
LOG(ERROR) << "RTT was: " << rtt << "us";
rtt_.OnMessage(rtt);
}
// Handle acknowledgements
uint64 start_byte = 0;
uint64 stop_byte = uint64_unpack(header->acknowledge_1);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_1);
stop_byte = start_byte + uint16_unpack(header->acknowledge_2);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_2);
stop_byte = start_byte + uint16_unpack(header->acknowledge_3);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_3);
stop_byte = start_byte + uint16_unpack(header->acknowledge_4);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_4);
stop_byte = start_byte + uint16_unpack(header->acknowledge_5);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
start_byte = stop_byte + uint16_unpack(header->gap_5);
stop_byte = start_byte + uint16_unpack(header->acknowledge_6);
sent_list_.AcknowledgeBlocks(start_byte, stop_byte);
if (!header->is_ack()) {
// Add to our received block list
uint64 position = uint64_unpack(header->position);
scoped_refptr<IOBuffer> buffer(new IOBuffer(body_length));
memcpy(buffer->data(), message->data() + sizeof(Message), body_length);
received_list_.AddBlock(position, buffer, body_length);
SendAck(message_id);
}
// If we have data available, and a read is pending, notify the callback.
if (received_list_.bytes_available() && receive_complete_callback_) {
// Pass the data up to the caller.
int bytes_read = InternalRead(pending_receive_, pending_receive_length_);
CompletionCallback* callback = receive_complete_callback_;
receive_complete_callback_ = NULL;
callback->Run(bytes_read);
}
}
void Messenger::SendAck(uint32 last_message_received) {
scoped_refptr<IOBuffer> buffer(new IOBuffer(sizeof(Message)));
memset(buffer->data(), 0, sizeof(Message));
Message* message = reinterpret_cast<Message*>(buffer->data());
uint32_pack(message->last_message_received, last_message_received);
uint64_pack(message->acknowledge_1, received_list_.bytes_received());
LOG(ERROR) << "SendAck " << received_list_.bytes_received();
// TODO(mbelshe): fill in remainder of selective acknowledgements
// TODO(mbelshe): Fix this - it is totally possible to have a send message
// in progress here...
DCHECK(!send_message_in_progress_);
int rv = packetizer_->SendMessage(key_,
buffer->data(),
sizeof(Message),
&send_message_callback_);
// TODO(mbelshe): Fix me! Deal with the error cases
DCHECK(rv == sizeof(Message));
}
} // namespace net
<|endoftext|> |
<commit_before><commit_msg>Make SpdySession::GetSSLInfo work when the SpdySession is constructed using SpdySession::InitializeWithSocket. The is_secure_ member needs to be set to true.<commit_after><|endoftext|> |
<commit_before>#include "Vajra/Engine/Components/DerivedComponents/Camera/Camera.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/GameObject/GameObject.h"
#include "Vajra/Engine/Lighting/ShadowMap.h"
#include "Vajra/Engine/RenderScene/RenderScene.h"
#include "Vajra/Engine/SceneGraph/RenderLists.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Framework/DeviceUtils/DeviceProperties/DeviceProperties.h"
#include "Vajra/Utilities/OpenGLIncludes.h"
static GLuint g_depth_fbo_id;
#ifdef PLATFORM_IOS
static GLint g_default_fbo;
#define SCREEN_FRAME_BUFFER g_default_fbo
#else
#define SCREEN_FRAME_BUFFER 0
#endif
#ifdef PLATFORM_IOS
#define MULTISAMPLING_ENABLED 1
#else
#define MULTISAMPLING_ENABLED 0
#endif
#if MULTISAMPLING_ENABLED
//Buffer definitions for the MSAA
GLuint msaaFramebuffer,
msaaRenderBuffer,
msaaDepthBuffer;
#endif
GLuint renderBuffer;
void RenderScene::SetupStuff() {
GLCALL(glEnable, GL_DEPTH_TEST);
#ifdef PLATFORM_IOS
GLCALL(glGetIntegerv, GL_FRAMEBUFFER_BINDING, &g_default_fbo);
#endif
// Create a frame buffer object:
GLCALL(glGenFramebuffers, 1, &g_depth_fbo_id);
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, g_depth_fbo_id);
// Create a render buffer
GLCALL(glGenRenderbuffers, 1, &renderBuffer);
GLCALL(glBindRenderbuffer, GL_RENDERBUFFER, renderBuffer);
unsigned int depthMap_width, depthMap_height;
ENGINE->GetShadowMap()->GetDepthMapResolution(depthMap_width, depthMap_height);
// Create a depth texture:
GLCALL(glGenTextures, 1, &ENGINE->GetShadowMap()->depthTexture);
GLCALL(glActiveTexture, GL_TEXTURE2);
GLCALL(glBindTexture, GL_TEXTURE_2D, ENGINE->GetShadowMap()->depthTexture);
GLCALL(glTexImage2D, GL_TEXTURE_2D, 0, GL_RGBA, depthMap_width, depthMap_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
//
GLCALL(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
GLCALL(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLCALL(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
GLCALL(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GLCALL(glFramebufferTexture2D, GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ENGINE->GetShadowMap()->depthTexture, 0);
// Allocate 16-bit depth buffer
GLCALL(glRenderbufferStorage, GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, depthMap_width, depthMap_height);
// Attach the render buffer as depth buffer - will be ignored
GLCALL(glFramebufferRenderbuffer, GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderBuffer);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { // GLCALL
ASSERT(0, "Framebuffer OK");
}
#if MULTISAMPLING_ENABLED
//Generate our MSAA Frame and Render buffers
glGenFramebuffers(1, &msaaFramebuffer);
glGenRenderbuffers(1, &msaaRenderBuffer);
//Bind our MSAA buffers
glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer);
glBindRenderbuffer(GL_RENDERBUFFER, msaaRenderBuffer);
unsigned int numSamples = 4;
// Generate the msaaDepthBuffer.
// numSamples will be the number of pixels that the MSAA buffer will use in order to make one pixel on the render buffer.
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, numSamples, GL_RGB5_A1, FRAMEWORK->GetDeviceProperties()->GetWidthPixels(), FRAMEWORK->GetDeviceProperties()->GetHeightPixels());
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msaaRenderBuffer);
glGenRenderbuffers(1, &msaaDepthBuffer);
//Bind the msaa depth buffer.
glBindRenderbuffer(GL_RENDERBUFFER, msaaDepthBuffer);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, numSamples, GL_DEPTH_COMPONENT16, FRAMEWORK->GetDeviceProperties()->GetWidthPixels() , FRAMEWORK->GetDeviceProperties()->GetHeightPixels());
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, msaaDepthBuffer);
#endif
}
void RenderScene::CleanupStuff() {
// TODO [Implement] Call this from somewhere:
// Free up the frame buffer object:
GLCALL(glDeleteFramebuffers, 1, &g_depth_fbo_id);
}
void RenderScene::RenderScene(RenderLists* renderLists, Camera* camera) {
#ifdef PLATFORM_IOS
GLCALL(glGetIntegerv, GL_FRAMEBUFFER_BINDING, &g_default_fbo);
#endif
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, SCREEN_FRAME_BUFFER /* default window framebuffer */);
renderLists->Draw(camera, false, DISTANCE_FROM_CAMERA_COMPARE_TYPE_ortho_z);
}
void RenderScene::RenderScene(RenderLists* renderLists, Camera* camera,
DirectionalLight* directionalLight,
std::vector<DirectionalLight*> additionalLights) {
#ifdef PLATFORM_IOS
GLCALL(glGetIntegerv, GL_FRAMEBUFFER_BINDING, &g_default_fbo);
#endif
std::vector<DirectionalLight*> emptyVector;
{
// Switch off blend for depth pass:
GLCALL(glDisable, GL_BLEND);
Camera* depthCamera = ENGINE->GetShadowMap()->GetDepthCamera();
#if defined(DRAWING_DEPTH_BUFFER_CONTENTS)
GLCALL(glViewport, 0, 0, FRAMEWORK->GetDeviceProperties()->GetWidthPixels(), FRAMEWORK->GetDeviceProperties()->GetHeightPixels());
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, SCREEN_FRAME_BUFFER /* default window framebuffer */);
#else
/*
* Draw to the depth buffer:
*/
unsigned int depthMap_width, depthMap_height;
ENGINE->GetShadowMap()->GetDepthMapResolution(depthMap_width, depthMap_height);
//
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, g_depth_fbo_id);
GLCALL(glViewport, 0, 0, depthMap_width, depthMap_height);
GLCALL(glClear, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
#endif
// Depth pass draw:
ENGINE->GetSceneGraph3D()->SetMainCameraId(depthCamera->GetObject()->GetId());
renderLists->Draw(depthCamera, nullptr /* no lights in depth pass */, emptyVector /* no lights in depth pass */, true, DISTANCE_FROM_CAMERA_COMPARE_TYPE_perspective);
// Switch blend back on:
GLCALL(glEnable, GL_BLEND);
}
#if MULTISAMPLING_ENABLED
glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
#endif
{
#if !defined(DRAWING_DEPTH_BUFFER_CONTENTS)
/*
* Draw again, this time to the screen:
*/
ENGINE->GetSceneGraph3D()->SetMainCameraId(camera->GetObject()->GetId());
#if !MULTISAMPLING_ENABLED
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, SCREEN_FRAME_BUFFER /* default window framebuffer */);
#endif
GLCALL(glViewport, 0, 0, FRAMEWORK->GetDeviceProperties()->GetWidthPixels(), FRAMEWORK->GetDeviceProperties()->GetHeightPixels());
renderLists->Draw(camera, directionalLight, additionalLights, false, DISTANCE_FROM_CAMERA_COMPARE_TYPE_perspective);
#endif
}
#if MULTISAMPLING_ENABLED
// Apple (and the khronos group) encourages you to discard depth
// render buffer contents whenever is possible
// GLenum attachments[] = {GL_DEPTH_ATTACHMENT};
// glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments);
//Bind both MSAA and View FrameBuffers.
glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, msaaFramebuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, SCREEN_FRAME_BUFFER);
// Call a resolve to combine both buffers
glResolveMultisampleFramebufferAPPLE();
// Present final image to screen
glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
// [context presentRenderbuffer:GL_RENDERBUFFER];
#endif
}
<commit_msg>Discard framebuffer attachments when they are not needed.<commit_after>#include "Vajra/Engine/Components/DerivedComponents/Camera/Camera.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/GameObject/GameObject.h"
#include "Vajra/Engine/Lighting/ShadowMap.h"
#include "Vajra/Engine/RenderScene/RenderScene.h"
#include "Vajra/Engine/SceneGraph/RenderLists.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Framework/DeviceUtils/DeviceProperties/DeviceProperties.h"
#include "Vajra/Utilities/OpenGLIncludes.h"
static GLuint g_depth_fbo_id;
#ifdef PLATFORM_IOS
static GLint g_default_fbo;
#define SCREEN_FRAME_BUFFER g_default_fbo
#else
#define SCREEN_FRAME_BUFFER 0
#endif
#ifdef PLATFORM_IOS
#define MULTISAMPLING_ENABLED 1
#else
#define MULTISAMPLING_ENABLED 0
#endif
#if MULTISAMPLING_ENABLED
//Buffer definitions for the MSAA
GLuint msaaFramebuffer,
msaaRenderBuffer,
msaaDepthBuffer;
#endif
GLuint renderBuffer;
void RenderScene::SetupStuff() {
GLCALL(glEnable, GL_DEPTH_TEST);
#ifdef PLATFORM_IOS
GLCALL(glGetIntegerv, GL_FRAMEBUFFER_BINDING, &g_default_fbo);
#endif
// Create a frame buffer object:
GLCALL(glGenFramebuffers, 1, &g_depth_fbo_id);
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, g_depth_fbo_id);
// Create a render buffer
GLCALL(glGenRenderbuffers, 1, &renderBuffer);
GLCALL(glBindRenderbuffer, GL_RENDERBUFFER, renderBuffer);
unsigned int depthMap_width, depthMap_height;
ENGINE->GetShadowMap()->GetDepthMapResolution(depthMap_width, depthMap_height);
// Create a depth texture:
GLCALL(glGenTextures, 1, &ENGINE->GetShadowMap()->depthTexture);
GLCALL(glActiveTexture, GL_TEXTURE2);
GLCALL(glBindTexture, GL_TEXTURE_2D, ENGINE->GetShadowMap()->depthTexture);
GLCALL(glTexImage2D, GL_TEXTURE_2D, 0, GL_RGBA, depthMap_width, depthMap_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
//
GLCALL(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
GLCALL(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLCALL(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
GLCALL(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GLCALL(glFramebufferTexture2D, GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ENGINE->GetShadowMap()->depthTexture, 0);
// Allocate 16-bit depth buffer
GLCALL(glRenderbufferStorage, GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, depthMap_width, depthMap_height);
// Attach the render buffer as depth buffer - will be ignored
GLCALL(glFramebufferRenderbuffer, GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderBuffer);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { // GLCALL
ASSERT(0, "Framebuffer OK");
}
#if MULTISAMPLING_ENABLED
//Generate our MSAA Frame and Render buffers
glGenFramebuffers(1, &msaaFramebuffer);
glGenRenderbuffers(1, &msaaRenderBuffer);
//Bind our MSAA buffers
glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer);
glBindRenderbuffer(GL_RENDERBUFFER, msaaRenderBuffer);
unsigned int numSamples = 4;
// Generate the msaaDepthBuffer.
// numSamples will be the number of pixels that the MSAA buffer will use in order to make one pixel on the render buffer.
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, numSamples, GL_RGB5_A1, FRAMEWORK->GetDeviceProperties()->GetWidthPixels(), FRAMEWORK->GetDeviceProperties()->GetHeightPixels());
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msaaRenderBuffer);
glGenRenderbuffers(1, &msaaDepthBuffer);
//Bind the msaa depth buffer.
glBindRenderbuffer(GL_RENDERBUFFER, msaaDepthBuffer);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, numSamples, GL_DEPTH_COMPONENT16, FRAMEWORK->GetDeviceProperties()->GetWidthPixels() , FRAMEWORK->GetDeviceProperties()->GetHeightPixels());
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, msaaDepthBuffer);
#endif
}
void RenderScene::CleanupStuff() {
// TODO [Implement] Call this from somewhere:
// Free up the frame buffer object:
GLCALL(glDeleteFramebuffers, 1, &g_depth_fbo_id);
}
void RenderScene::RenderScene(RenderLists* renderLists, Camera* camera) {
#ifdef PLATFORM_IOS
GLCALL(glGetIntegerv, GL_FRAMEBUFFER_BINDING, &g_default_fbo);
#endif
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, SCREEN_FRAME_BUFFER /* default window framebuffer */);
renderLists->Draw(camera, false, DISTANCE_FROM_CAMERA_COMPARE_TYPE_ortho_z);
}
void RenderScene::RenderScene(RenderLists* renderLists, Camera* camera,
DirectionalLight* directionalLight,
std::vector<DirectionalLight*> additionalLights) {
#ifdef PLATFORM_IOS
GLCALL(glGetIntegerv, GL_FRAMEBUFFER_BINDING, &g_default_fbo);
#endif
std::vector<DirectionalLight*> emptyVector;
{
// Switch off blend for depth pass:
GLCALL(glDisable, GL_BLEND);
Camera* depthCamera = ENGINE->GetShadowMap()->GetDepthCamera();
#if defined(DRAWING_DEPTH_BUFFER_CONTENTS)
GLCALL(glViewport, 0, 0, FRAMEWORK->GetDeviceProperties()->GetWidthPixels(), FRAMEWORK->GetDeviceProperties()->GetHeightPixels());
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, SCREEN_FRAME_BUFFER /* default window framebuffer */);
#else
/*
* Draw to the depth buffer:
*/
unsigned int depthMap_width, depthMap_height;
ENGINE->GetShadowMap()->GetDepthMapResolution(depthMap_width, depthMap_height);
//
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, g_depth_fbo_id);
GLCALL(glViewport, 0, 0, depthMap_width, depthMap_height);
GLCALL(glClear, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
#endif
// Depth pass draw:
ENGINE->GetSceneGraph3D()->SetMainCameraId(depthCamera->GetObject()->GetId());
renderLists->Draw(depthCamera, nullptr /* no lights in depth pass */, emptyVector /* no lights in depth pass */, true, DISTANCE_FROM_CAMERA_COMPARE_TYPE_perspective);
// Switch blend back on:
GLCALL(glEnable, GL_BLEND);
}
#if MULTISAMPLING_ENABLED
glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
#endif
{
#if !defined(DRAWING_DEPTH_BUFFER_CONTENTS)
/*
* Draw again, this time to the screen:
*/
ENGINE->GetSceneGraph3D()->SetMainCameraId(camera->GetObject()->GetId());
#if !MULTISAMPLING_ENABLED
GLCALL(glBindFramebuffer, GL_FRAMEBUFFER, SCREEN_FRAME_BUFFER /* default window framebuffer */);
#endif
GLCALL(glViewport, 0, 0, FRAMEWORK->GetDeviceProperties()->GetWidthPixels(), FRAMEWORK->GetDeviceProperties()->GetHeightPixels());
renderLists->Draw(camera, directionalLight, additionalLights, false, DISTANCE_FROM_CAMERA_COMPARE_TYPE_perspective);
#endif
}
#if MULTISAMPLING_ENABLED
// Apple (and the khronos group) encourages you to discard depth
// render buffer contents whenever is possible
const GLenum discard1[] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT};
glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, discard1);
const GLenum discard2[] = {GL_DEPTH_ATTACHMENT};
glDiscardFramebufferEXT(GL_DRAW_FRAMEBUFFER_APPLE, 1, discard2);
//Bind both MSAA and View FrameBuffers.
glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, msaaFramebuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, SCREEN_FRAME_BUFFER);
// Call a resolve to combine both buffers
glResolveMultisampleFramebufferAPPLE();
// Present final image to screen
glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
// [context presentRenderbuffer:GL_RENDERBUFFER];
#endif
}
<|endoftext|> |
<commit_before>#include <znc/main.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <znc/Nick.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/version.h>
#include <limits>
#include "twitchtmi.h"
#include "jload.h"
#if (VERSION_MAJOR < 1) || (VERSION_MAJOR == 1 && VERSION_MINOR < 7)
#error This module needs at least ZNC 1.7.0 or later.
#endif
TwitchTMI::~TwitchTMI()
{
}
bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage)
{
OnBoot();
if(GetNetwork())
{
for(CChan *ch: GetNetwork()->GetChans())
{
ch->SetTopic(CString());
CString chname = ch->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
}
}
if(GetArgs().Token(0) != "FrankerZ")
lastFrankerZ = std::numeric_limits<decltype(lastFrankerZ)>::max();
return true;
}
bool TwitchTMI::OnBoot()
{
initCurl();
timer = new TwitchTMIUpdateTimer(this);
AddTimer(timer);
return true;
}
CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine)
{
if(sLine.Left(5).Equals("WHO #"))
return CModule::HALT;
if(sLine.Left(5).Equals("AWAY "))
return CModule::HALT;
if(sLine.Left(12).Equals("TWITCHCLIENT"))
return CModule::HALT;
if(sLine.Left(9).Equals("JTVCLIENT"))
return CModule::HALT;
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnRawMessage(CMessage &msg)
{
if(msg.GetCommand().Equals("WHISPER"))
msg.SetCommand("PRIVMSG");
CString realNick = msg.GetTag("display-name").Trim_n();
if(realNick != "")
msg.GetNick().SetNick(realNick);
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey)
{
CString chname = sChannel.substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnPrivMessage(CTextMessage &Message)
{
if(Message.GetNick().GetNick().Equals("jtv"))
return CModule::HALT;
return CModule::CONTINUE;
}
void TwitchTMI::PutUserChanMessage(CChan *chan, const CString &from, const CString &msg)
{
std::stringstream ss;
ss << ":" << from << " PRIVMSG " << chan->GetName() << " :";
CString s = ss.str();
PutUser(s + msg);
if(!chan->AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || chan->IsDetached())
chan->AddBuffer(s + "{text}", msg);
}
CModule::EModRet TwitchTMI::OnChanMessage(CTextMessage &Message)
{
if(Message.GetNick().GetNick().Equals("jtv"))
return CModule::HALT;
if(Message.GetText() == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10)
{
std::stringstream ss;
CString mynick = GetNetwork()->GetIRCNick().GetNickMask();
CChan *chan = Message.GetChan();
ss << "PRIVMSG " << chan->GetName() << " :FrankerZ";
PutIRC(ss.str());
CThreadPool::Get().addJob(new GenericJob([]() {}, [this, chan, mynick]()
{
PutUserChanMessage(chan, mynick, "FrankerZ");
}));
lastFrankerZ = std::time(nullptr);
}
return CModule::CONTINUE;
}
bool TwitchTMI::OnServerCapAvailable(const CString &sCap)
{
if(sCap == "twitch.tv/membership")
return true;
else if(sCap == "twitch.tv/tags")
return true;
else if(sCap == "twitch.tv/commands")
return true;
return false;
}
CModule::EModRet TwitchTMI::OnUserTextMessage(CTextMessage &msg)
{
if(msg.GetTarget().Left(1).Equals("#"))
return CModule::CONTINUE;
msg.SetText(msg.GetText().insert(0, " ").insert(0, msg.GetTarget()).insert(0, "/w "));
msg.SetTarget("#jtv");
return CModule::HALT;
}
TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod)
:CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information")
,mod(tmod)
{
}
void TwitchTMIUpdateTimer::RunJob()
{
if(!mod->GetNetwork())
return;
for(CChan *chan: mod->GetNetwork()->GetChans())
{
CString chname = chan->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(mod, chname));
}
}
void TwitchTMIJob::runThread()
{
std::stringstream ss, ss2;
ss << "https://api.twitch.tv/kraken/channels/" << channel;
ss2 << "https://api.twitch.tv/kraken/streams/" << channel;
CString url = ss.str();
CString url2 = ss2.str();
Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json");
Json::Value root2 = getJsonFromUrl(url2.c_str(), "Accept: application/vnd.twitchtv.v3+json");
if(!root.isNull())
{
Json::Value &titleVal = root["status"];
title = CString();
if(!titleVal.isString())
titleVal = root["title"];
if(titleVal.isString())
{
title = titleVal.asString();
title.Trim();
}
}
live = false;
if(!root2.isNull())
{
Json::Value &streamVal = root2["stream"];
if(!streamVal.isNull())
live = true;
}
}
void TwitchTMIJob::runMain()
{
if(title.empty())
return;
CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel);
if(!chan)
return;
if(chan->GetTopic() != title)
{
chan->SetTopic(title);
chan->SetTopicOwner("jtv");
chan->SetTopicDate((unsigned long)time(nullptr));
std::stringstream ss;
ss << ":jtv TOPIC #" << channel << " :" << title;
mod->PutUser(ss.str());
}
auto it = mod->liveChannels.find(channel);
if(it != mod->liveChannels.end())
{
if(!live)
{
mod->liveChannels.erase(it);
mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went offline! <<<");
}
}
else
{
if(live)
{
mod->liveChannels.insert(channel);
mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went live! <<<");
}
}
}
template<> void TModInfo<TwitchTMI>(CModInfo &info)
{
info.SetWikiPage("Twitch");
info.SetHasArgs(true);
}
NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module")
<commit_msg>Fix suprious HALT<commit_after>#include <znc/main.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <znc/Nick.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/version.h>
#include <limits>
#include "twitchtmi.h"
#include "jload.h"
#if (VERSION_MAJOR < 1) || (VERSION_MAJOR == 1 && VERSION_MINOR < 7)
#error This module needs at least ZNC 1.7.0 or later.
#endif
TwitchTMI::~TwitchTMI()
{
}
bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage)
{
OnBoot();
if(GetNetwork())
{
for(CChan *ch: GetNetwork()->GetChans())
{
ch->SetTopic(CString());
CString chname = ch->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
}
}
if(GetArgs().Token(0) != "FrankerZ")
lastFrankerZ = std::numeric_limits<decltype(lastFrankerZ)>::max();
return true;
}
bool TwitchTMI::OnBoot()
{
initCurl();
timer = new TwitchTMIUpdateTimer(this);
AddTimer(timer);
return true;
}
CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine)
{
if(sLine.Left(5).Equals("WHO #"))
return CModule::HALT;
if(sLine.Left(5).Equals("AWAY "))
return CModule::HALT;
if(sLine.Left(12).Equals("TWITCHCLIENT"))
return CModule::HALT;
if(sLine.Left(9).Equals("JTVCLIENT"))
return CModule::HALT;
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnRawMessage(CMessage &msg)
{
if(msg.GetCommand().Equals("WHISPER"))
msg.SetCommand("PRIVMSG");
CString realNick = msg.GetTag("display-name").Trim_n();
if(realNick != "")
msg.GetNick().SetNick(realNick);
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey)
{
CString chname = sChannel.substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnPrivMessage(CTextMessage &Message)
{
if(Message.GetNick().GetNick().Equals("jtv"))
return CModule::HALT;
return CModule::CONTINUE;
}
void TwitchTMI::PutUserChanMessage(CChan *chan, const CString &from, const CString &msg)
{
std::stringstream ss;
ss << ":" << from << " PRIVMSG " << chan->GetName() << " :";
CString s = ss.str();
PutUser(s + msg);
if(!chan->AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || chan->IsDetached())
chan->AddBuffer(s + "{text}", msg);
}
CModule::EModRet TwitchTMI::OnChanMessage(CTextMessage &Message)
{
if(Message.GetNick().GetNick().Equals("jtv"))
return CModule::HALT;
if(Message.GetText() == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10)
{
std::stringstream ss;
CString mynick = GetNetwork()->GetIRCNick().GetNickMask();
CChan *chan = Message.GetChan();
ss << "PRIVMSG " << chan->GetName() << " :FrankerZ";
PutIRC(ss.str());
CThreadPool::Get().addJob(new GenericJob([]() {}, [this, chan, mynick]()
{
PutUserChanMessage(chan, mynick, "FrankerZ");
}));
lastFrankerZ = std::time(nullptr);
}
return CModule::CONTINUE;
}
bool TwitchTMI::OnServerCapAvailable(const CString &sCap)
{
if(sCap == "twitch.tv/membership")
return true;
else if(sCap == "twitch.tv/tags")
return true;
else if(sCap == "twitch.tv/commands")
return true;
return false;
}
CModule::EModRet TwitchTMI::OnUserTextMessage(CTextMessage &msg)
{
if(msg.GetTarget().Left(1).Equals("#"))
return CModule::CONTINUE;
msg.SetText(msg.GetText().insert(0, " ").insert(0, msg.GetTarget()).insert(0, "/w "));
msg.SetTarget("#jtv");
return CModule::CONTINUE;
}
TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod)
:CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information")
,mod(tmod)
{
}
void TwitchTMIUpdateTimer::RunJob()
{
if(!mod->GetNetwork())
return;
for(CChan *chan: mod->GetNetwork()->GetChans())
{
CString chname = chan->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(mod, chname));
}
}
void TwitchTMIJob::runThread()
{
std::stringstream ss, ss2;
ss << "https://api.twitch.tv/kraken/channels/" << channel;
ss2 << "https://api.twitch.tv/kraken/streams/" << channel;
CString url = ss.str();
CString url2 = ss2.str();
Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json");
Json::Value root2 = getJsonFromUrl(url2.c_str(), "Accept: application/vnd.twitchtv.v3+json");
if(!root.isNull())
{
Json::Value &titleVal = root["status"];
title = CString();
if(!titleVal.isString())
titleVal = root["title"];
if(titleVal.isString())
{
title = titleVal.asString();
title.Trim();
}
}
live = false;
if(!root2.isNull())
{
Json::Value &streamVal = root2["stream"];
if(!streamVal.isNull())
live = true;
}
}
void TwitchTMIJob::runMain()
{
if(title.empty())
return;
CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel);
if(!chan)
return;
if(chan->GetTopic() != title)
{
chan->SetTopic(title);
chan->SetTopicOwner("jtv");
chan->SetTopicDate((unsigned long)time(nullptr));
std::stringstream ss;
ss << ":jtv TOPIC #" << channel << " :" << title;
mod->PutUser(ss.str());
}
auto it = mod->liveChannels.find(channel);
if(it != mod->liveChannels.end())
{
if(!live)
{
mod->liveChannels.erase(it);
mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went offline! <<<");
}
}
else
{
if(live)
{
mod->liveChannels.insert(channel);
mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went live! <<<");
}
}
}
template<> void TModInfo<TwitchTMI>(CModInfo &info)
{
info.SetWikiPage("Twitch");
info.SetHasArgs(true);
}
NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module")
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/message_center/views/message_popup_collection.h"
#include <set>
#include "base/bind.h"
#include "base/timer.h"
#include "ui/gfx/screen.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/message_center_constants.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/notification_list.h"
#include "ui/message_center/views/message_view.h"
#include "ui/message_center/views/notification_view.h"
#include "ui/views/background.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace message_center {
class ToastContentsView : public views::WidgetDelegateView {
public:
ToastContentsView(const Notification* notification,
MessagePopupCollection* collection)
: collection_(collection) {
DCHECK(collection_);
set_notify_enter_exit_on_child(true);
SetLayoutManager(new views::FillLayout());
// Sets the transparent background. Then, when the message view is slid out,
// the whole toast seems to slide although the actual bound of the widget
// remains. This is hacky but easier to keep the consistency.
set_background(views::Background::CreateSolidBackground(0, 0, 0, 0));
int seconds = kAutocloseDefaultDelaySeconds;
if (notification->priority() > DEFAULT_PRIORITY)
seconds = kAutocloseHighPriorityDelaySeconds;
delay_ = base::TimeDelta::FromSeconds(seconds);
}
views::Widget* CreateWidget(gfx::NativeView context) {
views::Widget::InitParams params(
views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.keep_on_top = true;
params.context = context;
params.transparent = true;
// The origin of the initial bounds are set to (0, 0). It'll then moved by
// MessagePopupCollection.
params.bounds = gfx::Rect(
gfx::Size(kWebNotificationWidth, GetPreferredSize().height()));
params.delegate = this;
views::Widget* widget = new views::Widget();
widget->Init(params);
return widget;
}
void SetContents(MessageView* view) {
RemoveAllChildViews(true);
AddChildView(view);
Layout();
}
void SuspendTimer() {
timer_.Reset();
}
void RestartTimer() {
base::TimeDelta passed = base::Time::Now() - start_time_;
if (passed > delay_) {
GetWidget()->Close();
} else {
delay_ -= passed;
StartTimer();
}
}
void StartTimer() {
start_time_ = base::Time::Now();
timer_.Start(FROM_HERE,
delay_,
base::Bind(&views::Widget::Close,
base::Unretained(GetWidget())));
}
// Overridden from views::WidgetDelegate:
virtual views::View* GetContentsView() OVERRIDE {
return this;
}
virtual void WindowClosing() OVERRIDE {
if (timer_.IsRunning())
SuspendTimer();
}
virtual bool CanActivate() const OVERRIDE {
return false;
}
// Overridden from views::View:
virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE {
collection_->OnMouseEntered();
}
virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE {
collection_->OnMouseExited();
}
private:
base::TimeDelta delay_;
base::Time start_time_;
base::OneShotTimer<views::Widget> timer_;
MessagePopupCollection* collection_;
DISALLOW_COPY_AND_ASSIGN(ToastContentsView);
};
MessagePopupCollection::MessagePopupCollection(gfx::NativeView context,
MessageCenter* message_center)
: context_(context),
message_center_(message_center) {
DCHECK(message_center_);
}
MessagePopupCollection::~MessagePopupCollection() {
CloseAllWidgets();
}
void MessagePopupCollection::UpdatePopups() {
NotificationList::PopupNotifications popups =
message_center_->notification_list()->GetPopupNotifications();
if (popups.empty()) {
CloseAllWidgets();
return;
}
gfx::Screen* screen = gfx::Screen::GetScreenFor(context_);
gfx::Rect work_area = screen->GetDisplayNearestWindow(context_).work_area();
std::set<std::string> old_toast_ids;
for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end();
++iter) {
old_toast_ids.insert(iter->first);
}
int total_height = 0;
std::vector<views::Widget*> widgets;
for (NotificationList::PopupNotifications::const_iterator iter =
popups.begin(); iter != popups.end(); ++iter) {
ToastContainer::iterator toast_iter = toasts_.find((*iter)->id());
views::Widget* widget = NULL;
// NotificationViews are expanded by default here because
// MessagePopupCollection hasn't been tested yet with changing subview
// sizes, and such changes could come if those subviews were initially
// collapsed and allowed to be expanded by users. TODO(dharcourt): Fix.
MessageView* view = NotificationView::Create(*(*iter), message_center_,
true);
if (toast_iter != toasts_.end()) {
widget = toast_iter->second->GetWidget();
old_toast_ids.erase((*iter)->id());
// Need to replace the contents because |view| can be updated, like
// image loads.
toast_iter->second->SetContents(view);
} else {
ToastContentsView* toast = new ToastContentsView(*iter, this);
toast->SetContents(view);
widget = toast->CreateWidget(context_);
widget->AddObserver(this);
toast->StartTimer();
toasts_[(*iter)->id()] = toast;
}
if (widget) {
gfx::Rect bounds = widget->GetWindowBoundsInScreen();
int new_height = total_height + bounds.height() + kMarginBetweenItems;
if (new_height < work_area.height()) {
total_height = new_height;
widgets.push_back(widget);
} else {
if (toast_iter != toasts_.end())
toasts_.erase(toast_iter);
delete widget;
break;
}
}
}
for (std::set<std::string>::const_iterator iter = old_toast_ids.begin();
iter != old_toast_ids.end(); ++iter) {
ToastContainer::iterator toast_iter = toasts_.find(*iter);
DCHECK(toast_iter != toasts_.end());
views::Widget* widget = toast_iter->second->GetWidget();
widget->RemoveObserver(this);
widget->Close();
toasts_.erase(toast_iter);
}
// Place/move the toast widgets. Currently it stacks the widgets from the
// right-bottom of the work area.
// TODO(mukai): allow to specify the placement policy from outside of this
// class. The policy should be specified from preference on Windows, or
// the launcher alignment on ChromeOS.
int top = work_area.bottom() - total_height;
int left = work_area.right() - kWebNotificationWidth - kMarginBetweenItems;
for (size_t i = 0; i < widgets.size(); ++i) {
gfx::Rect widget_bounds = widgets[i]->GetWindowBoundsInScreen();
widgets[i]->SetBounds(gfx::Rect(
left, top, widget_bounds.width(), widget_bounds.height()));
if (!widgets[i]->IsVisible())
widgets[i]->Show();
top += widget_bounds.height() + kMarginBetweenItems;
}
}
void MessagePopupCollection::OnMouseEntered() {
for (ToastContainer::iterator iter = toasts_.begin();
iter != toasts_.end(); ++iter) {
iter->second->SuspendTimer();
}
}
void MessagePopupCollection::OnMouseExited() {
for (ToastContainer::iterator iter = toasts_.begin();
iter != toasts_.end(); ++iter) {
iter->second->RestartTimer();
}
}
void MessagePopupCollection::CloseAllWidgets() {
for (ToastContainer::iterator iter = toasts_.begin();
iter != toasts_.end(); ++iter) {
iter->second->SuspendTimer();
views::Widget* widget = iter->second->GetWidget();
widget->RemoveObserver(this);
widget->Close();
}
toasts_.clear();
}
void MessagePopupCollection::OnWidgetDestroying(views::Widget* widget) {
widget->RemoveObserver(this);
for (ToastContainer::iterator iter = toasts_.begin();
iter != toasts_.end(); ++iter) {
if (iter->second->GetWidget() == widget) {
message_center_->notification_list()->MarkSinglePopupAsShown(
iter->first, false);
toasts_.erase(iter);
break;
}
}
UpdatePopups();
}
} // namespace message_center
<commit_msg>Fixes message popup collection bugs.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/message_center/views/message_popup_collection.h"
#include <set>
#include "base/bind.h"
#include "base/timer.h"
#include "ui/gfx/screen.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/message_center_constants.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/notification_list.h"
#include "ui/message_center/views/message_view.h"
#include "ui/message_center/views/notification_view.h"
#include "ui/views/background.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace message_center {
class ToastContentsView : public views::WidgetDelegateView {
public:
ToastContentsView(const Notification* notification,
MessagePopupCollection* collection)
: collection_(collection) {
DCHECK(collection_);
set_notify_enter_exit_on_child(true);
SetLayoutManager(new views::FillLayout());
// Sets the transparent background. Then, when the message view is slid out,
// the whole toast seems to slide although the actual bound of the widget
// remains. This is hacky but easier to keep the consistency.
set_background(views::Background::CreateSolidBackground(0, 0, 0, 0));
int seconds = kAutocloseDefaultDelaySeconds;
if (notification->priority() > DEFAULT_PRIORITY)
seconds = kAutocloseHighPriorityDelaySeconds;
delay_ = base::TimeDelta::FromSeconds(seconds);
}
views::Widget* CreateWidget(gfx::NativeView context) {
views::Widget::InitParams params(
views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.keep_on_top = true;
params.context = context;
params.transparent = true;
// The origin of the initial bounds are set to (0, 0). It'll then moved by
// MessagePopupCollection.
params.bounds = gfx::Rect(
gfx::Size(kWebNotificationWidth,
GetHeightForWidth(kWebNotificationWidth)));
params.delegate = this;
views::Widget* widget = new views::Widget();
widget->Init(params);
return widget;
}
void SetContents(MessageView* view) {
RemoveAllChildViews(true);
AddChildView(view);
views::Widget* widget = GetWidget();
if (widget) {
gfx::Rect bounds = widget->GetWindowBoundsInScreen();
bounds.set_height(view->GetHeightForWidth(kWebNotificationWidth));
widget->SetBounds(bounds);
}
Layout();
}
void SuspendTimer() {
timer_.Reset();
}
void RestartTimer() {
base::TimeDelta passed = base::Time::Now() - start_time_;
if (passed > delay_) {
GetWidget()->Close();
} else {
delay_ -= passed;
StartTimer();
}
}
void StartTimer() {
start_time_ = base::Time::Now();
timer_.Start(FROM_HERE,
delay_,
base::Bind(&views::Widget::Close,
base::Unretained(GetWidget())));
}
// Overridden from views::WidgetDelegate:
virtual views::View* GetContentsView() OVERRIDE {
return this;
}
virtual void WindowClosing() OVERRIDE {
if (timer_.IsRunning())
SuspendTimer();
}
virtual bool CanActivate() const OVERRIDE {
return false;
}
// Overridden from views::View:
virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE {
collection_->OnMouseEntered();
}
virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE {
collection_->OnMouseExited();
}
private:
base::TimeDelta delay_;
base::Time start_time_;
base::OneShotTimer<views::Widget> timer_;
MessagePopupCollection* collection_;
DISALLOW_COPY_AND_ASSIGN(ToastContentsView);
};
MessagePopupCollection::MessagePopupCollection(gfx::NativeView context,
MessageCenter* message_center)
: context_(context),
message_center_(message_center) {
DCHECK(message_center_);
}
MessagePopupCollection::~MessagePopupCollection() {
CloseAllWidgets();
}
void MessagePopupCollection::UpdatePopups() {
NotificationList::PopupNotifications popups =
message_center_->notification_list()->GetPopupNotifications();
if (popups.empty()) {
CloseAllWidgets();
return;
}
gfx::Screen* screen = gfx::Screen::GetScreenFor(context_);
gfx::Rect work_area = screen->GetDisplayNearestWindow(context_).work_area();
std::set<std::string> old_toast_ids;
for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end();
++iter) {
old_toast_ids.insert(iter->first);
}
int bottom = work_area.bottom() - kMarginBetweenItems;
int left = work_area.right() - kWebNotificationWidth - kMarginBetweenItems;
// Iterate in the reverse order to keep the oldest toasts on screen. Newer
// items may be ignored if there are no room to place them.
for (NotificationList::PopupNotifications::const_reverse_iterator iter =
popups.rbegin(); iter != popups.rend(); ++iter) {
MessageView* view =
NotificationView::Create(*(*iter), message_center_, true);
int view_height = view->GetHeightForWidth(kWebNotificationWidth);
if (bottom - view_height - kMarginBetweenItems < 0) {
delete view;
break;
}
ToastContainer::iterator toast_iter = toasts_.find((*iter)->id());
views::Widget* widget = NULL;
if (toast_iter != toasts_.end()) {
widget = toast_iter->second->GetWidget();
old_toast_ids.erase((*iter)->id());
// Need to replace the contents because |view| can be updated, like
// image loads.
toast_iter->second->SetContents(view);
} else {
ToastContentsView* toast = new ToastContentsView(*iter, this);
toast->SetContents(view);
widget = toast->CreateWidget(context_);
widget->AddObserver(this);
toast->StartTimer();
toasts_[(*iter)->id()] = toast;
}
// Place/move the toast widgets. Currently it stacks the widgets from the
// right-bottom of the work area.
// TODO(mukai): allow to specify the placement policy from outside of this
// class. The policy should be specified from preference on Windows, or
// the launcher alignment on ChromeOS.
if (widget) {
gfx::Rect bounds(widget->GetWindowBoundsInScreen());
bounds.set_origin(gfx::Point(left, bottom - bounds.height()));
widget->SetBounds(bounds);
if (!widget->IsVisible())
widget->Show();
}
bottom -= view_height + kMarginBetweenItems;
}
for (std::set<std::string>::const_iterator iter = old_toast_ids.begin();
iter != old_toast_ids.end(); ++iter) {
ToastContainer::iterator toast_iter = toasts_.find(*iter);
DCHECK(toast_iter != toasts_.end());
views::Widget* widget = toast_iter->second->GetWidget();
widget->RemoveObserver(this);
widget->Close();
toasts_.erase(toast_iter);
}
}
void MessagePopupCollection::OnMouseEntered() {
for (ToastContainer::iterator iter = toasts_.begin();
iter != toasts_.end(); ++iter) {
iter->second->SuspendTimer();
}
}
void MessagePopupCollection::OnMouseExited() {
for (ToastContainer::iterator iter = toasts_.begin();
iter != toasts_.end(); ++iter) {
iter->second->RestartTimer();
}
}
void MessagePopupCollection::CloseAllWidgets() {
for (ToastContainer::iterator iter = toasts_.begin();
iter != toasts_.end(); ++iter) {
iter->second->SuspendTimer();
views::Widget* widget = iter->second->GetWidget();
widget->RemoveObserver(this);
widget->Close();
}
toasts_.clear();
}
void MessagePopupCollection::OnWidgetDestroying(views::Widget* widget) {
widget->RemoveObserver(this);
for (ToastContainer::iterator iter = toasts_.begin();
iter != toasts_.end(); ++iter) {
if (iter->second->GetWidget() == widget) {
message_center_->notification_list()->MarkSinglePopupAsShown(
iter->first, false);
toasts_.erase(iter);
break;
}
}
UpdatePopups();
}
} // namespace message_center
<|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <uv.h>
#include <string>
#include <sstream>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "../worker_platform.h"
#include "../worker_thread.h"
#include "../../message.h"
#include "../../log.h"
#include "../../lock.h"
using std::string;
using std::wstring;
using std::ostringstream;
using std::unique_ptr;
using std::shared_ptr;
using std::default_delete;
using std::map;
using std::pair;
using std::make_pair;
using std::vector;
using std::move;
using std::endl;
const DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;
const DWORD NETWORK_BUFFER_SIZE = 64 * 1024;
static void CALLBACK command_perform_helper(__in ULONG_PTR payload);
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);
static Result<string> to_utf8(const wstring &in);
template < class V = void* >
static Result<V> windows_error_result(const string &prefix);
template < class V = void* >
static Result<V> windows_error_result(const string &prefix, DWORD error_code);
class WindowsWorkerPlatform;
class Subscription {
public:
Subscription(ChannelID channel, HANDLE root, const string &path, WindowsWorkerPlatform *platform) :
channel{channel},
platform{platform},
path{path},
root{root},
buffer_size{DEFAULT_BUFFER_SIZE},
buffer{new BYTE[buffer_size]},
written{new BYTE[buffer_size]}
{
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
overlapped.hEvent = this;
}
~Subscription()
{
CloseHandle(root);
}
Result<> schedule()
{
int success = ReadDirectoryChangesW(
root, // root directory handle
buffer.get(), // result buffer
buffer_size, // result buffer size
TRUE, // recursive
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES
| FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS
| FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, // change flags
NULL, // bytes returned
&overlapped, // overlapped
&event_helper // completion routine
);
if (!success) {
return windows_error_result<>("Unable to subscribe to filesystem events");
}
return ok_result();
}
Result<> use_network_size()
{
if (buffer_size <= NETWORK_BUFFER_SIZE) {
ostringstream out("Buffer size of ");
out
<< buffer_size
<< " is already lower than the network buffer size "
<< NETWORK_BUFFER_SIZE;
return error_result(out.str());
}
buffer_size = NETWORK_BUFFER_SIZE;
buffer.reset(new BYTE[buffer_size]);
written.reset(new BYTE[buffer_size]);
return ok_result();
}
ChannelID get_channel() const {
return channel;
}
WindowsWorkerPlatform* get_platform() const {
return platform;
}
BYTE *get_written(DWORD written_size) {
memcpy(written.get(), buffer.get(), written_size);
return written.get();
}
string make_absolute(const string &sub_path)
{
ostringstream out;
out << path;
if (path.back() != '\\' && sub_path.front() != '\\') {
out << '\\';
}
out << sub_path;
return out.str();
}
private:
ChannelID channel;
WindowsWorkerPlatform *platform;
string path;
HANDLE root;
OVERLAPPED overlapped;
DWORD buffer_size;
unique_ptr<BYTE[]> buffer;
unique_ptr<BYTE[]> written;
};
class WindowsWorkerPlatform : public WorkerPlatform {
public:
WindowsWorkerPlatform(WorkerThread *thread) :
WorkerPlatform(thread),
thread_handle{0}
{
int err;
err = uv_mutex_init(&thread_handle_mutex);
if (err) {
report_uv_error(err);
}
};
~WindowsWorkerPlatform() override
{
uv_mutex_destroy(&thread_handle_mutex);
}
Result<> wake() override
{
Lock lock(thread_handle_mutex);
if (!thread_handle) {
return ok_result();
}
BOOL success = QueueUserAPC(
command_perform_helper,
thread_handle,
reinterpret_cast<ULONG_PTR>(this)
);
if (!success) {
return windows_error_result<>("Unable to queue APC");
}
return ok_result();
}
Result<> listen() override
{
{
Lock lock(thread_handle_mutex);
HANDLE pseudo_handle = GetCurrentThread();
BOOL success = DuplicateHandle(
GetCurrentProcess(), // Source process
pseudo_handle, // Source handle
GetCurrentProcess(), // Destination process
&thread_handle, // Destination handle
0, // Desired access
FALSE, // Inheritable by new processes
DUPLICATE_SAME_ACCESS // options
);
if (!success) {
Result<> r = windows_error_result<>("Unable to duplicate thread handle");
report_error("Unable to acquire thread handle");
return r;
}
}
while (true) {
SleepEx(INFINITE, true);
}
report_error("listen loop ended unexpectedly");
return health_err_result();
}
Result<> handle_add_command(const ChannelID channel, const string &root_path)
{
LOGGER << "Watching: " << root_path << endl;
// Convert the path to a wide-character array
size_t wlen = MultiByteToWideChar(
CP_UTF8, // code page
0, // flags
root_path.data(), // source string data
-1, // source string length (null-terminated)
0, // output buffer
0 // output buffer size
);
if (wlen == 0) {
return windows_error_result<>("Unable to measure UTF-16 buffer");
}
unique_ptr<WCHAR[]> root_path_w{new WCHAR[wlen]};
size_t conv_success = MultiByteToWideChar(
CP_UTF8, // code page
0, // flags,
root_path.data(), // source string data
-1, // source string length (null-terminated)
root_path_w.get(), // output buffer
wlen // output buffer size
);
if (!conv_success) {
return windows_error_result<>("Unable to convert root path to UTF-16");
}
// Open a directory handle
HANDLE root = CreateFileW(
root_path_w.get(), // file name
FILE_LIST_DIRECTORY, // desired access
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // share mode
NULL, // security attributes
OPEN_EXISTING, // creation disposition
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // flags and attributes
NULL // template file
);
if (root == INVALID_HANDLE_VALUE) {
return windows_error_result<>("Unable to open directory handle");
}
// Allocate and persist the subscription
Subscription *sub = new Subscription(channel, root, root_path, this);
auto insert_result = subscriptions.insert(make_pair(channel, sub));
if (!insert_result.second) {
delete sub;
ostringstream msg("Channel collision: ");
msg << channel;
return error_result(msg.str());
}
LOGGER << "Now watching directory " << root_path << "." << endl;
return sub->schedule();
}
Result<> handle_remove_command(const ChannelID channel)
{
return ok_result();
}
Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription* sub)
{
// Ensure that the subscription is valid.
ChannelID channel = sub->get_channel();
auto it = subscriptions.find(channel);
if (it == subscriptions.end() || it->second != sub) {
return ok_result();
}
// Handle errors.
if (error_code == ERROR_OPERATION_ABORTED) {
LOGGER << "Operation aborted." << endl;
subscriptions.erase(it);
delete sub;
return ok_result();
}
if (error_code == ERROR_INVALID_PARAMETER) {
Result<> resize = sub->use_network_size();
if (resize.is_error()) return resize;
return sub->schedule();
}
if (error_code == ERROR_NOTIFY_ENUM_DIR) {
LOGGER << "Change buffer overflow. Some events may have been lost." << endl;
return sub->schedule();
}
if (error_code != ERROR_SUCCESS) {
return windows_error_result<>("Completion callback error", error_code);
}
// Schedule the next completion callback.
BYTE *base = sub->get_written(num_bytes);
Result<> next = sub->schedule();
if (next.is_error()) {
report_error(string(next.get_error()));
}
// Process received events.
vector<Message> messages;
bool old_path_seen = false;
string old_path;
while (true) {
PFILE_NOTIFY_INFORMATION info = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(base);
wstring wpath{info->FileName, info->FileNameLength};
Result<string> u8r = to_utf8(wpath);
if (u8r.is_error()) {
LOGGER << "Skipping path: " << u8r << "." << endl;
} else {
string path = u8r.get_value();
switch (info->Action) {
case FILE_ACTION_ADDED:
{
FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_MODIFIED:
{
FileSystemPayload payload(channel, ACTION_MODIFIED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_REMOVED:
{
FileSystemPayload payload(channel, ACTION_DELETED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_RENAMED_OLD_NAME:
old_path_seen = true;
old_path = move(path);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
if (old_path_seen) {
// Old name received first
{
FileSystemPayload payload(channel, ACTION_RENAMED, KIND_UNKNOWN, move(old_path), move(path));
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
old_path_seen = false;
} else {
// No old name. Treat it as a creation
{
FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
}
break;
default:
LOGGER << "Skipping unexpected action " << info->Action << "." << endl;
break;
}
}
if (info->NextEntryOffset == 0) {
break;
}
base += info->NextEntryOffset;
}
if (!messages.empty()) {
Result<> er = emit_all(messages.begin(), messages.end());
if (er.is_error()) {
LOGGER << "Unable to emit messages: " << er << "." << endl;
}
}
return next;
}
private:
uv_mutex_t thread_handle_mutex;
HANDLE thread_handle;
map<ChannelID, Subscription*> subscriptions;
};
unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)
{
return unique_ptr<WorkerPlatform>(new WindowsWorkerPlatform(thread));
}
void CALLBACK command_perform_helper(__in ULONG_PTR payload)
{
WindowsWorkerPlatform *platform = reinterpret_cast<WindowsWorkerPlatform*>(payload);
platform->handle_commands();
}
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)
{
Subscription *sub = static_cast<Subscription*>(overlapped->hEvent);
Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);
if (r.is_error()) {
LOGGER << "Unable to handle filesystem events: " << r << "." << endl;
}
}
Result<string> to_utf8(const wstring &in)
{
size_t len = WideCharToMultiByte(
CP_UTF8, // code page
0, // flags
in.data(), // source string
in.size(), // source string length
nullptr, // destination string, null to measure
0, // destination string length
nullptr, // default char
nullptr // used default char
);
if (!len) {
return windows_error_result<string>("Unable to measure path as UTF-8");
}
char *out = new char[len];
size_t copied = WideCharToMultiByte(
CP_UTF8, // code page
0, // flags
in.data(), // source string
in.size(), // source string length
out, // destination string
len, // destination string length
nullptr, // default char
nullptr // used default char
);
if (!copied) {
delete [] out;
return windows_error_result<string>("Unable to convert path to UTF-8");
}
return ok_result(string{out, len});
}
template < class V >
Result<V> windows_error_result(const string &prefix)
{
return windows_error_result<V>(prefix, GetLastError());
}
template < class V >
Result<V> windows_error_result(const string &prefix, DWORD error_code)
{
LPVOID msg_buffer;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, // source
error_code, // message ID
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // language ID
(LPSTR) &msg_buffer, // output buffer
0, // size
NULL // arguments
);
ostringstream msg;
msg << prefix << "\n (" << error_code << ") " << (char*) msg_buffer;
LocalFree(msg_buffer);
return Result<V>::make_error(msg.str());
}
<commit_msg>Report absolute paths<commit_after>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <uv.h>
#include <string>
#include <sstream>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "../worker_platform.h"
#include "../worker_thread.h"
#include "../../message.h"
#include "../../log.h"
#include "../../lock.h"
using std::string;
using std::wstring;
using std::ostringstream;
using std::unique_ptr;
using std::shared_ptr;
using std::default_delete;
using std::map;
using std::pair;
using std::make_pair;
using std::vector;
using std::move;
using std::endl;
const DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;
const DWORD NETWORK_BUFFER_SIZE = 64 * 1024;
static void CALLBACK command_perform_helper(__in ULONG_PTR payload);
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);
static Result<string> to_utf8(const wstring &in);
template < class V = void* >
static Result<V> windows_error_result(const string &prefix);
template < class V = void* >
static Result<V> windows_error_result(const string &prefix, DWORD error_code);
class WindowsWorkerPlatform;
class Subscription {
public:
Subscription(ChannelID channel, HANDLE root, const string &path, WindowsWorkerPlatform *platform) :
channel{channel},
platform{platform},
path{path},
root{root},
buffer_size{DEFAULT_BUFFER_SIZE},
buffer{new BYTE[buffer_size]},
written{new BYTE[buffer_size]}
{
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
overlapped.hEvent = this;
}
~Subscription()
{
CloseHandle(root);
}
Result<> schedule()
{
int success = ReadDirectoryChangesW(
root, // root directory handle
buffer.get(), // result buffer
buffer_size, // result buffer size
TRUE, // recursive
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES
| FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS
| FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, // change flags
NULL, // bytes returned
&overlapped, // overlapped
&event_helper // completion routine
);
if (!success) {
return windows_error_result<>("Unable to subscribe to filesystem events");
}
return ok_result();
}
Result<> use_network_size()
{
if (buffer_size <= NETWORK_BUFFER_SIZE) {
ostringstream out("Buffer size of ");
out
<< buffer_size
<< " is already lower than the network buffer size "
<< NETWORK_BUFFER_SIZE;
return error_result(out.str());
}
buffer_size = NETWORK_BUFFER_SIZE;
buffer.reset(new BYTE[buffer_size]);
written.reset(new BYTE[buffer_size]);
return ok_result();
}
ChannelID get_channel() const {
return channel;
}
WindowsWorkerPlatform* get_platform() const {
return platform;
}
BYTE *get_written(DWORD written_size) {
memcpy(written.get(), buffer.get(), written_size);
return written.get();
}
string make_absolute(const string &sub_path)
{
ostringstream out;
out << path;
if (path.back() != '\\' && sub_path.front() != '\\') {
out << '\\';
}
out << sub_path;
return out.str();
}
private:
ChannelID channel;
WindowsWorkerPlatform *platform;
string path;
HANDLE root;
OVERLAPPED overlapped;
DWORD buffer_size;
unique_ptr<BYTE[]> buffer;
unique_ptr<BYTE[]> written;
};
class WindowsWorkerPlatform : public WorkerPlatform {
public:
WindowsWorkerPlatform(WorkerThread *thread) :
WorkerPlatform(thread),
thread_handle{0}
{
int err;
err = uv_mutex_init(&thread_handle_mutex);
if (err) {
report_uv_error(err);
}
};
~WindowsWorkerPlatform() override
{
uv_mutex_destroy(&thread_handle_mutex);
}
Result<> wake() override
{
Lock lock(thread_handle_mutex);
if (!thread_handle) {
return ok_result();
}
BOOL success = QueueUserAPC(
command_perform_helper,
thread_handle,
reinterpret_cast<ULONG_PTR>(this)
);
if (!success) {
return windows_error_result<>("Unable to queue APC");
}
return ok_result();
}
Result<> listen() override
{
{
Lock lock(thread_handle_mutex);
HANDLE pseudo_handle = GetCurrentThread();
BOOL success = DuplicateHandle(
GetCurrentProcess(), // Source process
pseudo_handle, // Source handle
GetCurrentProcess(), // Destination process
&thread_handle, // Destination handle
0, // Desired access
FALSE, // Inheritable by new processes
DUPLICATE_SAME_ACCESS // options
);
if (!success) {
Result<> r = windows_error_result<>("Unable to duplicate thread handle");
report_error("Unable to acquire thread handle");
return r;
}
}
while (true) {
SleepEx(INFINITE, true);
}
report_error("listen loop ended unexpectedly");
return health_err_result();
}
Result<> handle_add_command(const ChannelID channel, const string &root_path)
{
LOGGER << "Watching: " << root_path << endl;
// Convert the path to a wide-character array
size_t wlen = MultiByteToWideChar(
CP_UTF8, // code page
0, // flags
root_path.data(), // source string data
-1, // source string length (null-terminated)
0, // output buffer
0 // output buffer size
);
if (wlen == 0) {
return windows_error_result<>("Unable to measure UTF-16 buffer");
}
unique_ptr<WCHAR[]> root_path_w{new WCHAR[wlen]};
size_t conv_success = MultiByteToWideChar(
CP_UTF8, // code page
0, // flags,
root_path.data(), // source string data
-1, // source string length (null-terminated)
root_path_w.get(), // output buffer
wlen // output buffer size
);
if (!conv_success) {
return windows_error_result<>("Unable to convert root path to UTF-16");
}
// Open a directory handle
HANDLE root = CreateFileW(
root_path_w.get(), // file name
FILE_LIST_DIRECTORY, // desired access
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // share mode
NULL, // security attributes
OPEN_EXISTING, // creation disposition
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // flags and attributes
NULL // template file
);
if (root == INVALID_HANDLE_VALUE) {
return windows_error_result<>("Unable to open directory handle");
}
// Allocate and persist the subscription
Subscription *sub = new Subscription(channel, root, root_path, this);
auto insert_result = subscriptions.insert(make_pair(channel, sub));
if (!insert_result.second) {
delete sub;
ostringstream msg("Channel collision: ");
msg << channel;
return error_result(msg.str());
}
LOGGER << "Now watching directory " << root_path << "." << endl;
return sub->schedule();
}
Result<> handle_remove_command(const ChannelID channel)
{
return ok_result();
}
Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription* sub)
{
// Ensure that the subscription is valid.
ChannelID channel = sub->get_channel();
auto it = subscriptions.find(channel);
if (it == subscriptions.end() || it->second != sub) {
return ok_result();
}
// Handle errors.
if (error_code == ERROR_OPERATION_ABORTED) {
LOGGER << "Operation aborted." << endl;
subscriptions.erase(it);
delete sub;
return ok_result();
}
if (error_code == ERROR_INVALID_PARAMETER) {
Result<> resize = sub->use_network_size();
if (resize.is_error()) return resize;
return sub->schedule();
}
if (error_code == ERROR_NOTIFY_ENUM_DIR) {
LOGGER << "Change buffer overflow. Some events may have been lost." << endl;
return sub->schedule();
}
if (error_code != ERROR_SUCCESS) {
return windows_error_result<>("Completion callback error", error_code);
}
// Schedule the next completion callback.
BYTE *base = sub->get_written(num_bytes);
Result<> next = sub->schedule();
if (next.is_error()) {
report_error(string(next.get_error()));
}
// Process received events.
vector<Message> messages;
bool old_path_seen = false;
string old_path;
while (true) {
PFILE_NOTIFY_INFORMATION info = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(base);
wstring wpath{info->FileName, info->FileNameLength};
Result<string> u8r = to_utf8(wpath);
if (u8r.is_error()) {
LOGGER << "Skipping path: " << u8r << "." << endl;
} else {
string path = sub->make_absolute(u8r.get_value());
switch (info->Action) {
case FILE_ACTION_ADDED:
{
FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_MODIFIED:
{
FileSystemPayload payload(channel, ACTION_MODIFIED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_REMOVED:
{
FileSystemPayload payload(channel, ACTION_DELETED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_RENAMED_OLD_NAME:
old_path_seen = true;
old_path = move(path);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
if (old_path_seen) {
// Old name received first
{
FileSystemPayload payload(channel, ACTION_RENAMED, KIND_UNKNOWN, move(old_path), move(path));
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
old_path_seen = false;
} else {
// No old name. Treat it as a creation
{
FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
}
break;
default:
LOGGER << "Skipping unexpected action " << info->Action << "." << endl;
break;
}
}
if (info->NextEntryOffset == 0) {
break;
}
base += info->NextEntryOffset;
}
if (!messages.empty()) {
Result<> er = emit_all(messages.begin(), messages.end());
if (er.is_error()) {
LOGGER << "Unable to emit messages: " << er << "." << endl;
}
}
return next;
}
private:
uv_mutex_t thread_handle_mutex;
HANDLE thread_handle;
map<ChannelID, Subscription*> subscriptions;
};
unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)
{
return unique_ptr<WorkerPlatform>(new WindowsWorkerPlatform(thread));
}
void CALLBACK command_perform_helper(__in ULONG_PTR payload)
{
WindowsWorkerPlatform *platform = reinterpret_cast<WindowsWorkerPlatform*>(payload);
platform->handle_commands();
}
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)
{
Subscription *sub = static_cast<Subscription*>(overlapped->hEvent);
Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);
if (r.is_error()) {
LOGGER << "Unable to handle filesystem events: " << r << "." << endl;
}
}
Result<string> to_utf8(const wstring &in)
{
size_t len = WideCharToMultiByte(
CP_UTF8, // code page
0, // flags
in.data(), // source string
in.size(), // source string length
nullptr, // destination string, null to measure
0, // destination string length
nullptr, // default char
nullptr // used default char
);
if (!len) {
return windows_error_result<string>("Unable to measure path as UTF-8");
}
char *out = new char[len];
size_t copied = WideCharToMultiByte(
CP_UTF8, // code page
0, // flags
in.data(), // source string
in.size(), // source string length
out, // destination string
len, // destination string length
nullptr, // default char
nullptr // used default char
);
if (!copied) {
delete [] out;
return windows_error_result<string>("Unable to convert path to UTF-8");
}
return ok_result(string{out, len});
}
template < class V >
Result<V> windows_error_result(const string &prefix)
{
return windows_error_result<V>(prefix, GetLastError());
}
template < class V >
Result<V> windows_error_result(const string &prefix, DWORD error_code)
{
LPVOID msg_buffer;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, // source
error_code, // message ID
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // language ID
(LPSTR) &msg_buffer, // output buffer
0, // size
NULL // arguments
);
ostringstream msg;
msg << prefix << "\n (" << error_code << ") " << (char*) msg_buffer;
LocalFree(msg_buffer);
return Result<V>::make_error(msg.str());
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "INSMomentumLaplaceForm.h"
template<>
InputParameters validParams<INSMomentumLaplaceForm>()
{
InputParameters params = validParams<INSMomentumBase>();
return params;
}
INSMomentumLaplaceForm::INSMomentumLaplaceForm(const InputParameters & parameters) :
INSMomentumBase(parameters)
{
}
Real INSMomentumLaplaceForm::computeQpResidualViscousPart()
{
// Simplified version: mu * Laplacian(u_component)
return _mu * (_grad_u[_qp] * _grad_test[_i][_qp]);
}
Real INSMomentumLaplaceForm::computeQpJacobianViscousPart()
{
// Viscous part, Laplacian version
return _mu * (_grad_phi[_j][_qp] * _grad_test[_i][_qp]);
}
Real INSMomentumLaplaceForm::computeQpOffDiagJacobianViscousPart(unsigned jvar)
{
return 0.;
}
<commit_msg>Fix unused variable warning.<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "INSMomentumLaplaceForm.h"
template<>
InputParameters validParams<INSMomentumLaplaceForm>()
{
InputParameters params = validParams<INSMomentumBase>();
return params;
}
INSMomentumLaplaceForm::INSMomentumLaplaceForm(const InputParameters & parameters) :
INSMomentumBase(parameters)
{
}
Real INSMomentumLaplaceForm::computeQpResidualViscousPart()
{
// Simplified version: mu * Laplacian(u_component)
return _mu * (_grad_u[_qp] * _grad_test[_i][_qp]);
}
Real INSMomentumLaplaceForm::computeQpJacobianViscousPart()
{
// Viscous part, Laplacian version
return _mu * (_grad_phi[_j][_qp] * _grad_test[_i][_qp]);
}
Real INSMomentumLaplaceForm::computeQpOffDiagJacobianViscousPart(unsigned /*jvar*/)
{
return 0.;
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxextension utility methods
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/clipbrd.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
bool exClipboardAdd(const wxString& text)
{
wxClipboardLocker locker;
if (!locker) return false;
if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;
if (!wxTheClipboard->Flush()) return false; // take care that clipboard data remain after exiting
return true;
}
const wxString exClipboardGet()
{
wxBusyCursor wait;
wxClipboardLocker locker;
if (!locker)
{
wxLogError("Cannot open clipboard");
return wxEmptyString;
}
if (!wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxLogError("Clipboard format not supported");
return wxEmptyString;
}
wxTextDataObject data;
if (!wxTheClipboard->GetData(data))
{
wxLogError("Cannot get clipboard data");
return wxEmptyString;
}
return data.GetText();
}
#if wxUSE_GUI
void exComboBoxFromString(
wxComboBox* cb,
const wxString& text,
const wxChar field_separator)
{
wxStringTokenizer tkz(text, field_separator);
while (tkz.HasMoreTokens())
{
const wxString val = tkz.GetNextToken();
if (cb->FindString(val) == wxNOT_FOUND)
{
cb->Append(val);
}
}
if (cb->GetCount() > 0) cb->SetValue(cb->GetString(0));
}
bool exComboBoxToString(
const wxComboBox* cb,
wxString& text,
const wxChar field_separator,
size_t max_items)
{
if (cb == NULL)
{
return false;
}
text = cb->GetValue();
switch (cb->FindString(cb->GetValue()))
{
case wxNOT_FOUND:
{
// Add the string, as it is not in the combo box, to the text,
// simply by appending all combobox items.
for (size_t i = 0; i < max_items; i++)
if (i < max_items - 1 && i < cb->GetCount())
text += field_separator + cb->GetString(i);
}
break;
// No change necessary, the string is already present as the first one.
case 0: return false; break;
default:
{
// Reorder. The new first element already present, just add all others.
for (size_t i = 0; i < cb->GetCount(); i++)
{
const wxString cb_element = cb->GetString(i);
if (cb_element != cb->GetValue())
text += field_separator + cb_element;
}
}
}
return true;
}
#endif // wxUSE_GUI
long exColourToLong(const wxColour& c)
{
return c.Red() | (c.Green() << 8) | (c.Blue() << 16);
}
const wxString exEllipsed(const wxString& text, const wxString& control)
{
return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}
const wxString exGetEndOfWord(
const wxString& text,
size_t max_chars)
{
wxString text_out(text);
if (text_out.length() > max_chars)
{
text_out = "..." + text_out.substr(text_out.length() - max_chars);
}
return text_out;
}
int exGetNumberOfLines(const wxString& text)
{
if (text.empty())
{
return 0;
}
else if (text.Find(wxChar('\r')) != wxNOT_FOUND)
{
return text.Freq(wxChar('\r')) + 1;
}
else if (text.Find(wxChar('\n')) != wxNOT_FOUND)
{
return text.Freq(wxChar('\n')) + 1;
}
else
{
return 1;
}
}
int exGetLineNumberFromText(const wxString& text)
{
// Get text after :.
const size_t pos_char = text.rfind(":");
if (pos_char == wxString::npos)
{
return 0;
}
const wxString linenumber = text.substr(pos_char + 1);
long line;
if (linenumber.ToLong(&line))
{
return line;
}
else
{
return 0;
}
}
void exLog(const wxString& text, const exFileName& filename)
{
wxFile(
filename.GetFullPath(),
wxFile::write_append).Write(
wxDateTime::Now().Format() + " " + text + wxTextFile::GetEOL());
}
const exFileName exLogfileName()
{
if (wxTheApp == NULL)
{
return exFileName("app.log");
}
#ifdef EX_PORTABLE
return exFileName(
wxPathOnly(wxStandardPaths::Get().GetExecutablePath()) + wxFileName::GetPathSeparator() +
wxTheApp->GetAppName().Lower() + ".log");
#else
return exFileName(
wxStandardPaths::Get().GetUserDataDir() + wxFileName::GetPathSeparator() +
wxTheApp->GetAppName().Lower() + ".log");
#endif
}
bool exMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
if (pattern == "*") return true; // asterix matches always.
const wxString fullname_uppercase = filename.GetFullName().Upper();
wxStringTokenizer tokenizer(pattern.Upper(), ";");
while (tokenizer.HasMoreTokens())
{
if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
}
return false;
}
const wxString exSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
wxString output = text;
wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
return output;
}
const wxString exTranslate(const wxString& text, int pageNum, int numPages)
{
wxString translation = text;
wxString num;
num.Printf("%i", pageNum);
translation.Replace("@PAGENUM@", num);
num.Printf("%i", numPages);
translation.Replace("@PAGESCNT@", num);
return translation;
}
<commit_msg>fix for ubuntu<commit_after>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxextension utility methods
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/clipbrd.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
bool exClipboardAdd(const wxString& text)
{
wxClipboardLocker locker;
if (!locker) return false;
if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;
// Take care that clipboard data remain after exiting
// This is a boolean method as well, we don't check it, as
// clipboard data is copied.
// At least on Ubuntu 8.10 FLush returns false.
wxTheClipboard->Flush();
return true;
}
const wxString exClipboardGet()
{
wxBusyCursor wait;
wxClipboardLocker locker;
if (!locker)
{
wxLogError("Cannot open clipboard");
return wxEmptyString;
}
if (!wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxLogError("Clipboard format not supported");
return wxEmptyString;
}
wxTextDataObject data;
if (!wxTheClipboard->GetData(data))
{
wxLogError("Cannot get clipboard data");
return wxEmptyString;
}
return data.GetText();
}
#if wxUSE_GUI
void exComboBoxFromString(
wxComboBox* cb,
const wxString& text,
const wxChar field_separator)
{
wxStringTokenizer tkz(text, field_separator);
while (tkz.HasMoreTokens())
{
const wxString val = tkz.GetNextToken();
if (cb->FindString(val) == wxNOT_FOUND)
{
cb->Append(val);
}
}
if (cb->GetCount() > 0) cb->SetValue(cb->GetString(0));
}
bool exComboBoxToString(
const wxComboBox* cb,
wxString& text,
const wxChar field_separator,
size_t max_items)
{
if (cb == NULL)
{
return false;
}
text = cb->GetValue();
switch (cb->FindString(cb->GetValue()))
{
case wxNOT_FOUND:
{
// Add the string, as it is not in the combo box, to the text,
// simply by appending all combobox items.
for (size_t i = 0; i < max_items; i++)
if (i < max_items - 1 && i < cb->GetCount())
text += field_separator + cb->GetString(i);
}
break;
// No change necessary, the string is already present as the first one.
case 0: return false; break;
default:
{
// Reorder. The new first element already present, just add all others.
for (size_t i = 0; i < cb->GetCount(); i++)
{
const wxString cb_element = cb->GetString(i);
if (cb_element != cb->GetValue())
text += field_separator + cb_element;
}
}
}
return true;
}
#endif // wxUSE_GUI
long exColourToLong(const wxColour& c)
{
return c.Red() | (c.Green() << 8) | (c.Blue() << 16);
}
const wxString exEllipsed(const wxString& text, const wxString& control)
{
return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}
const wxString exGetEndOfWord(
const wxString& text,
size_t max_chars)
{
wxString text_out(text);
if (text_out.length() > max_chars)
{
text_out = "..." + text_out.substr(text_out.length() - max_chars);
}
return text_out;
}
int exGetNumberOfLines(const wxString& text)
{
if (text.empty())
{
return 0;
}
else if (text.Find(wxChar('\r')) != wxNOT_FOUND)
{
return text.Freq(wxChar('\r')) + 1;
}
else if (text.Find(wxChar('\n')) != wxNOT_FOUND)
{
return text.Freq(wxChar('\n')) + 1;
}
else
{
return 1;
}
}
int exGetLineNumberFromText(const wxString& text)
{
// Get text after :.
const size_t pos_char = text.rfind(":");
if (pos_char == wxString::npos)
{
return 0;
}
const wxString linenumber = text.substr(pos_char + 1);
long line;
if (linenumber.ToLong(&line))
{
return line;
}
else
{
return 0;
}
}
void exLog(const wxString& text, const exFileName& filename)
{
wxFile(
filename.GetFullPath(),
wxFile::write_append).Write(
wxDateTime::Now().Format() + " " + text + wxTextFile::GetEOL());
}
const exFileName exLogfileName()
{
if (wxTheApp == NULL)
{
return exFileName("app.log");
}
#ifdef EX_PORTABLE
return exFileName(
wxPathOnly(wxStandardPaths::Get().GetExecutablePath()) + wxFileName::GetPathSeparator() +
wxTheApp->GetAppName().Lower() + ".log");
#else
return exFileName(
wxStandardPaths::Get().GetUserDataDir() + wxFileName::GetPathSeparator() +
wxTheApp->GetAppName().Lower() + ".log");
#endif
}
bool exMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
if (pattern == "*") return true; // asterix matches always.
const wxString fullname_uppercase = filename.GetFullName().Upper();
wxStringTokenizer tokenizer(pattern.Upper(), ";");
while (tokenizer.HasMoreTokens())
{
if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
}
return false;
}
const wxString exSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
wxString output = text;
wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
return output;
}
const wxString exTranslate(const wxString& text, int pageNum, int numPages)
{
wxString translation = text;
wxString num;
num.Printf("%i", pageNum);
translation.Replace("@PAGENUM@", num);
num.Printf("%i", numPages);
translation.Replace("@PAGESCNT@", num);
return translation;
}
<|endoftext|> |
<commit_before>TEveWindowSlot *s = 0;
void test_windows()
{
TEveManager::Create();
TEveUtil::Macro("pointset_test.C");
TEveWindowSlot *slot = 0;
TEveWindowFrame *evef = 0;
TEveViewer *v = 0;
TGCompositeFrame *cf = 0;
// ----------------------------------------------------------------
slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight());
TEveWindowPack* pack1 = slot->MakePack();
slot = pack1->NewSlot();
// Embedded viewer.
v = new TEveViewer("BarViewer");
TGLEmbeddedViewer* xx = new TGLEmbeddedViewer(0, 0, 0);
v->SetGLViewer(xx);
evef = slot->MakeFrame(xx->GetFrame());
evef->SetElementName("Bar Embedded Viewer");
gEve->GetViewers()->AddElement(v);
v->AddScene(gEve->GetEventScene());
slot = pack1->NewSlot();
TEveWindowPack* pack2 = slot->MakePack();
pack2->FlipOrientation();
slot = pack2->NewSlot();
slot->StartEmbedding();
new TCanvas;
slot->StopEmbedding();
slot = pack2->NewSlot();
// SA viewer.
v = new TEveViewer("FooViewer");
slot->StartEmbedding();
v->SpawnGLViewer(gClient->GetRoot(), gEve->GetEditor());
slot->StopEmbedding("Foo StandAlone Viewer");
gEve->GetViewers()->AddElement(v);
v->AddScene(gEve->GetEventScene());
// ----------------------------------------------------------------
slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight());
TEveWindowTab* tab1 = slot->MakeTab();
tab1->NewSlot();
slot = tab1->NewSlot();
TEveWindowTab* tab2 = slot->MakeTab();
tab2->NewSlot();
tab2->NewSlot();
// ----------------------------------------------------------------
gEve->GetBrowser()->GetTabRight()->SetTab(1);
}
<commit_msg>From Bertrand: allow running via ACLiC.<commit_after>#include "TEveWindow.h"
#include "TEveViewer.h"
#include "TEveManager.h"
#include "TEveBrowser.h"
#include "TEveGedEditor.h"
#include "TGLEmbeddedViewer.h"
#include "TCanvas.h"
#include "TGTab.h"
void test_windows()
{
TEveManager::Create();
TEveUtil::Macro("pointset_test.C");
TEveWindowSlot *slot = 0;
TEveWindowFrame *evef = 0;
TEveViewer *v = 0;
// ----------------------------------------------------------------
slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight());
TEveWindowPack* pack1 = slot->MakePack();
slot = pack1->NewSlot();
// Embedded viewer.
v = new TEveViewer("BarViewer");
TGLEmbeddedViewer* xx = new TGLEmbeddedViewer(0, 0, 0);
v->SetGLViewer(xx);
evef = slot->MakeFrame(xx->GetFrame());
evef->SetElementName("Bar Embedded Viewer");
gEve->GetViewers()->AddElement(v);
v->AddScene(gEve->GetEventScene());
slot = pack1->NewSlot();
TEveWindowPack* pack2 = slot->MakePack();
pack2->FlipOrientation();
slot = pack2->NewSlot();
slot->StartEmbedding();
new TCanvas(); // Sometimes crashes on destroy - should use embedded canvas?
slot->StopEmbedding();
slot = pack2->NewSlot();
// SA viewer.
v = new TEveViewer("FooViewer");
slot->StartEmbedding();
v->SpawnGLViewer(gClient->GetRoot(), gEve->GetEditor());
slot->StopEmbedding("Foo StandAlone Viewer");
gEve->GetViewers()->AddElement(v);
v->AddScene(gEve->GetEventScene());
// ----------------------------------------------------------------
slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight());
TEveWindowTab* tab1 = slot->MakeTab();
tab1->NewSlot();
slot = tab1->NewSlot();
TEveWindowTab* tab2 = slot->MakeTab();
tab2->NewSlot();
tab2->NewSlot();
// ----------------------------------------------------------------
gEve->GetBrowser()->GetTabRight()->SetTab(1);
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_FUN_GRAD_REG_INC_GAMMA_HPP
#define STAN_MATH_PRIM_SCAL_FUN_GRAD_REG_INC_GAMMA_HPP
#include <stan/math/prim/scal/err/domain_error.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/fun/gamma_p.hpp>
#include <stan/math/prim/scal/fun/gamma_q.hpp>
#include <stan/math/prim/scal/fun/is_inf.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <cmath>
#include <limits>
namespace stan {
namespace math {
/**
* Gradient of the regularized incomplete gamma functions igamma(a, z)
*
* For small z, the gradient is computed via the series expansion;
* for large z, the series is numerically inaccurate due to cancellation
* and the asymptotic expansion is used.
*
* @param a shape parameter, a > 0
* @param z location z >= 0
* @param g boost::math::tgamma(a) (precomputed value)
* @param dig boost::math::digamma(a) (precomputed value)
* @param precision required precision; applies to series expansion only
* @param max_steps number of steps to take.
* @throw throws std::domain_error if not converged after max_steps
* or increment overflows to inf.
*
* For the asymptotic expansion, the gradient is given by:
\f[
\begin{array}{rcl}
\Gamma(a, z) & = & z^{a-1}e^{-z} \sum_{k=0}^N \frac{(a-1)_k}{z^k} \qquad , z \gg a\\
Q(a, z) & = & \frac{z^{a-1}e^{-z}}{\Gamma(a)} \sum_{k=0}^N \frac{(a-1)_k}{z^k}\\
(a)_k & = & (a)_{k-1}(a-k)\\
\frac{d}{da} (a)_k & = & (a)_{k-1} + (a-k)\frac{d}{da} (a)_{k-1}\\
\frac{d}{da}Q(a, z) & = & (log(z) - \psi(a)) Q(a, z)\\
&& + \frac{z^{a-1}e^{-z}}{\Gamma(a)} \sum_{k=0}^N \left(\frac{d}{da} (a-1)_k\right) \frac{1}{z^k}
\end{array}
\f]
*/
template<typename T>
T grad_reg_inc_gamma(T a, T z, T g, T dig, double precision = 1e-6,
int max_steps = 1e5) {
using std::domain_error;
using std::exp;
using std::fabs;
using std::log;
check_not_nan("grad_reg_inc_gamma", "a", a);
check_not_nan("grad_reg_inc_gamma", "z", z);
check_not_nan("grad_reg_inc_gamma", "g", g);
check_not_nan("grad_reg_inc_gamma", "dig", dig);
T l = log(z);
if (z >= a && z >= 8) {
// asymptotic expansion http://dlmf.nist.gov/8.11#E2
T S = 0;
T a_minus_one_minus_k = a - 1;
T fac = a_minus_one_minus_k; // falling_factorial(a-1, k)
T dfac = 1; // d/da[falling_factorial(a-1, k)]
T zpow = z; // z ** k
T delta = dfac / zpow;
for (int k = 1; k < 10; ++k) {
a_minus_one_minus_k -= 1;
S += delta;
zpow *= z;
dfac = a_minus_one_minus_k * dfac + fac;
fac *= a_minus_one_minus_k;
delta = dfac / zpow;
if (is_inf(delta))
stan::math::domain_error("grad_reg_inc_gamma",
"is not converging", "", "");
}
return gamma_q(a, z) * (l - dig) + exp(-z + (a - 1) * l) * S / g;
} else {
// gradient of series expansion http://dlmf.nist.gov/8.7#E3
T S = 0;
T log_s = 0.0;
double s_sign = 1.0;
T log_z = log(z);
T log_delta = log_s - 2 * log(a);
for (int k = 1; k <= max_steps; ++k) {
S += s_sign >= 0.0 ? exp(log_delta) : -exp(log_delta);
log_s += log_z - log(k);
s_sign = -s_sign;
log_delta = log_s - 2 * log(k + a);
if (is_inf(log_delta))
stan::math::domain_error("grad_reg_inc_gamma",
"is not converging", "", "");
if (log_delta <= log(precision))
return gamma_p(a, z) * ( dig - l ) + exp( a * l ) * S / g;
}
stan::math::domain_error("grad_reg_inc_gamma",
"k (internal counter)",
max_steps, "exceeded ",
" iterations, gamma function gradient did not converge.");
return std::numeric_limits<T>::infinity();
}
}
}
}
#endif
<commit_msg>tests expect grad_reg_inc_gamma to return NaN silently.<commit_after>#ifndef STAN_MATH_PRIM_SCAL_FUN_GRAD_REG_INC_GAMMA_HPP
#define STAN_MATH_PRIM_SCAL_FUN_GRAD_REG_INC_GAMMA_HPP
#include <stan/math/prim/scal/err/domain_error.hpp>
#include <stan/math/prim/scal/fun/gamma_p.hpp>
#include <stan/math/prim/scal/fun/gamma_q.hpp>
#include <stan/math/prim/scal/fun/is_inf.hpp>
#include <stan/math/prim/scal/fun/is_nan.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <cmath>
#include <limits>
namespace stan {
namespace math {
/**
* Gradient of the regularized incomplete gamma functions igamma(a, z)
*
* For small z, the gradient is computed via the series expansion;
* for large z, the series is numerically inaccurate due to cancellation
* and the asymptotic expansion is used.
*
* @param a shape parameter, a > 0
* @param z location z >= 0
* @param g boost::math::tgamma(a) (precomputed value)
* @param dig boost::math::digamma(a) (precomputed value)
* @param precision required precision; applies to series expansion only
* @param max_steps number of steps to take.
* @throw throws std::domain_error if not converged after max_steps
* or increment overflows to inf.
*
* For the asymptotic expansion, the gradient is given by:
\f[
\begin{array}{rcl}
\Gamma(a, z) & = & z^{a-1}e^{-z} \sum_{k=0}^N \frac{(a-1)_k}{z^k} \qquad , z \gg a\\
Q(a, z) & = & \frac{z^{a-1}e^{-z}}{\Gamma(a)} \sum_{k=0}^N \frac{(a-1)_k}{z^k}\\
(a)_k & = & (a)_{k-1}(a-k)\\
\frac{d}{da} (a)_k & = & (a)_{k-1} + (a-k)\frac{d}{da} (a)_{k-1}\\
\frac{d}{da}Q(a, z) & = & (log(z) - \psi(a)) Q(a, z)\\
&& + \frac{z^{a-1}e^{-z}}{\Gamma(a)} \sum_{k=0}^N \left(\frac{d}{da} (a-1)_k\right) \frac{1}{z^k}
\end{array}
\f]
*/
template<typename T>
T grad_reg_inc_gamma(T a, T z, T g, T dig, double precision = 1e-6,
int max_steps = 1e5) {
using std::domain_error;
using std::exp;
using std::fabs;
using std::log;
if (is_nan(a)) return std::numeric_limits<T>::quiet_NaN();
if (is_nan(z)) return std::numeric_limits<T>::quiet_NaN();
if (is_nan(g)) return std::numeric_limits<T>::quiet_NaN();
if (is_nan(dig)) return std::numeric_limits<T>::quiet_NaN();
T l = log(z);
if (z >= a && z >= 8) {
// asymptotic expansion http://dlmf.nist.gov/8.11#E2
T S = 0;
T a_minus_one_minus_k = a - 1;
T fac = a_minus_one_minus_k; // falling_factorial(a-1, k)
T dfac = 1; // d/da[falling_factorial(a-1, k)]
T zpow = z; // z ** k
T delta = dfac / zpow;
for (int k = 1; k < 10; ++k) {
a_minus_one_minus_k -= 1;
S += delta;
zpow *= z;
dfac = a_minus_one_minus_k * dfac + fac;
fac *= a_minus_one_minus_k;
delta = dfac / zpow;
if (is_inf(delta))
stan::math::domain_error("grad_reg_inc_gamma",
"is not converging", "", "");
}
return gamma_q(a, z) * (l - dig) + exp(-z + (a - 1) * l) * S / g;
} else {
// gradient of series expansion http://dlmf.nist.gov/8.7#E3
T S = 0;
T log_s = 0.0;
double s_sign = 1.0;
T log_z = log(z);
T log_delta = log_s - 2 * log(a);
for (int k = 1; k <= max_steps; ++k) {
S += s_sign >= 0.0 ? exp(log_delta) : -exp(log_delta);
log_s += log_z - log(k);
s_sign = -s_sign;
log_delta = log_s - 2 * log(k + a);
if (is_inf(log_delta))
stan::math::domain_error("grad_reg_inc_gamma",
"is not converging", "", "");
if (log_delta <= log(precision))
return gamma_p(a, z) * ( dig - l ) + exp( a * l ) * S / g;
}
stan::math::domain_error("grad_reg_inc_gamma",
"k (internal counter)",
max_steps, "exceeded ",
" iterations, gamma function gradient did not converge.");
return std::numeric_limits<T>::infinity();
}
}
}
}
#endif
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <ncurses.h>
#define N 0x10
struct TCoordenada{
double x;
double y;
};
struct TAnillo{
double x;
double y;
};
void rellena_con_mierda_la_piii_serpiente(struct TAnillo coordenada[N]){
for (int i=0; i<N; i++){
coordenada[i].x = 10 + i;
coordenada[i].y = 10;
}
}
void muestra(struct TAnillo coordenada[N]){
clear();
for (int i=0; i<N; i++)
mvprintw( coordenada[i].y, coordenada[i].x, "*");
refresh();
}
void mover(struct TCoordenada incremento, struct TAnillo coordenada[N]){
for (int i=N-1; i>0; i--){
coordenada[i].x = coordenada[i-1].x;
coordenada[i].y = coordenada[i-1].y;
}
coordenada[0].x += incremento.x;
coordenada[0].y += incremento.y;
}
int main(int argc, char *argv[]){
struct TAnillo serpiente[N];
struct TCoordenada movimiento = {0, -1};
int user_input;
rellena_con_mierda_la_piii_serpiente(serpiente);
initscr(); // Crea una matriz para pintar
halfdelay(3); // Hace que getch espere 3 decimas de segundo
keypad(stdscr, TRUE); // Vale para leer las flechas
noecho(); // Para que no se vea el caracter pulsado.
curs_set(0); // No se ve el cursor.
while(1){
user_input = getch();
switch(tolower(user_input)){
case 'q':
case KEY_UP:
movimiento.x = 0;
movimiento.y = -1;
break;
case 'a':
case KEY_DOWN:
movimiento.x = 0;
movimiento.y = 1;
break;
case 'o':
case KEY_LEFT:
movimiento.x = -1;
movimiento.y = 0;
break;
case 'p':
case KEY_RIGHT:
movimiento.x = 1;
movimiento.y = 0;
break;
}
mover( movimiento, serpiente);
muestra(serpiente);
}
getchar();
endwin(); // Libera la matriz.
return EXIT_SUCCESS;
}
<commit_msg>Delete snake.cpp<commit_after><|endoftext|> |
<commit_before>#include "encoder.hh"
#include "../format/format-stream.hh"
namespace mimosa
{
namespace json
{
Encoder::Encoder(stream::Stream::Ptr output)
: output_(output)
{
}
bool
Encoder::startObject()
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (output_->loopWrite("{", 1) != 1)
return false;
state_.push_back(kObjectKey);
return true;
}
bool
Encoder::endObject()
{
if (state_.empty() ||
(state_.back() != kObjectKey && state_.back() != kObjectNext))
throw SyntaxError();
if (output_->loopWrite("}", 1) != 1)
return false;
state_.pop_back();
nextState();
return true;
}
bool
Encoder::startArray()
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (output_->loopWrite("[", 1) != 1)
return false;
state_.push_back(kArray);
return true;
}
bool
Encoder::endArray()
{
if (state_.empty() || (state_.back() != kArray && state_.back() != kArrayNext))
throw SyntaxError();
if (output_->loopWrite("]", 1) != 1)
return false;
state_.pop_back();
nextState();
return true;
}
bool
Encoder::pushBoolean(bool value)
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if ((value && output_->loopWrite("true", 4) != 4) ||
(!value && output_->loopWrite("false", 5) != 5))
return false;
nextState();
return true;
}
bool
Encoder::pushNull()
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (output_->loopWrite("null", 4) != 4)
return false;
nextState();
return true;
}
bool
Encoder::pushString(const std::string & data)
{
if (!pushSeparator())
return false;
if (output_->loopWrite("\"", 1) != 1)
return false;
for (auto it = data.begin(); it != data.end(); ++it) {
if (*it == '\\' || *it == '"')
if (output_->loopWrite("\\", 1) != 1)
return false;
switch (*it) {
case '\r':
if (output_->loopWrite("\\r", 2) != 2)
return false;
break;
case '\n':
if (output_->loopWrite("\\n", 2) != 2)
return false;
break;
case '\t':
if (output_->loopWrite("\\t", 2) != 2)
return false;
break;
case '\v':
if (output_->loopWrite("\\v", 2) != 2)
return false;
break;
case '\b':
if (output_->loopWrite("\\b", 2) != 2)
return false;
break;
case '\\':
case '"':
if (output_->loopWrite("\\", 1) != 1)
return false;
/* fall through */
default:
if (output_->loopWrite(&*it, 1) != 1)
return false;
}
}
if (output_->loopWrite("\"", 1) != 1)
return false;
nextState();
return true;
}
bool
Encoder::pushNumber(int64_t value)
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (!format::format(*output_, "%d", value))
return false;
nextState();
return true;
}
bool
Encoder::pushFloat(double value)
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (!format::format(*output_, "%v", value))
return false;
nextState();
return true;
}
bool
Encoder::pushSeparator()
{
if (state_.empty())
return true;
switch (state_.back()) {
case kArray:
case kObjectKey:
return true;
case kArrayNext:
if (output_->loopWrite(",", 1) != 1)
return false;
state_.back() = kArray;
return true;
case kObjectNext:
if (output_->loopWrite(",", 1) != 1)
return false;
state_.back() = kObjectKey;
return true;
case kObjectValue:
return output_->loopWrite(":", 1) == 1;
default:
return true;
}
}
void
Encoder::nextState()
{
if (state_.empty())
return;
switch (state_.back()) {
case kArray:
state_.back() = kArrayNext;
break;
case kArrayNext:
break;
case kObjectKey:
state_.back() = kObjectValue;
break;
case kObjectValue:
state_.back() = kObjectNext;
break;
case kObjectNext:
state_.back() = kObjectKey;
break;
default:
break;
}
}
}
}
<commit_msg>Remove bug<commit_after>#include "encoder.hh"
#include "../format/format-stream.hh"
namespace mimosa
{
namespace json
{
Encoder::Encoder(stream::Stream::Ptr output)
: output_(output)
{
}
bool
Encoder::startObject()
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (output_->loopWrite("{", 1) != 1)
return false;
state_.push_back(kObjectKey);
return true;
}
bool
Encoder::endObject()
{
if (state_.empty() ||
(state_.back() != kObjectKey && state_.back() != kObjectNext))
throw SyntaxError();
if (output_->loopWrite("}", 1) != 1)
return false;
state_.pop_back();
nextState();
return true;
}
bool
Encoder::startArray()
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (output_->loopWrite("[", 1) != 1)
return false;
state_.push_back(kArray);
return true;
}
bool
Encoder::endArray()
{
if (state_.empty() || (state_.back() != kArray && state_.back() != kArrayNext))
throw SyntaxError();
if (output_->loopWrite("]", 1) != 1)
return false;
state_.pop_back();
nextState();
return true;
}
bool
Encoder::pushBoolean(bool value)
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if ((value && output_->loopWrite("true", 4) != 4) ||
(!value && output_->loopWrite("false", 5) != 5))
return false;
nextState();
return true;
}
bool
Encoder::pushNull()
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (output_->loopWrite("null", 4) != 4)
return false;
nextState();
return true;
}
bool
Encoder::pushString(const std::string & data)
{
if (!pushSeparator())
return false;
if (output_->loopWrite("\"", 1) != 1)
return false;
for (auto it = data.begin(); it != data.end(); ++it) {
if (*it == '\\' || *it == '"')
if (output_->loopWrite("\\", 1) != 1)
return false;
switch (*it) {
case '\r':
if (output_->loopWrite("\\r", 2) != 2)
return false;
break;
case '\n':
if (output_->loopWrite("\\n", 2) != 2)
return false;
break;
case '\t':
if (output_->loopWrite("\\t", 2) != 2)
return false;
break;
case '\v':
if (output_->loopWrite("\\v", 2) != 2)
return false;
break;
case '\b':
if (output_->loopWrite("\\b", 2) != 2)
return false;
break;
default:
if (output_->loopWrite(&*it, 1) != 1)
return false;
}
}
if (output_->loopWrite("\"", 1) != 1)
return false;
nextState();
return true;
}
bool
Encoder::pushNumber(int64_t value)
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (!format::format(*output_, "%d", value))
return false;
nextState();
return true;
}
bool
Encoder::pushFloat(double value)
{
if (!state_.empty() && state_.back() == kObjectKey)
throw SyntaxError();
if (!pushSeparator())
return false;
if (!format::format(*output_, "%v", value))
return false;
nextState();
return true;
}
bool
Encoder::pushSeparator()
{
if (state_.empty())
return true;
switch (state_.back()) {
case kArray:
case kObjectKey:
return true;
case kArrayNext:
if (output_->loopWrite(",", 1) != 1)
return false;
state_.back() = kArray;
return true;
case kObjectNext:
if (output_->loopWrite(",", 1) != 1)
return false;
state_.back() = kObjectKey;
return true;
case kObjectValue:
return output_->loopWrite(":", 1) == 1;
default:
return true;
}
}
void
Encoder::nextState()
{
if (state_.empty())
return;
switch (state_.back()) {
case kArray:
state_.back() = kArrayNext;
break;
case kArrayNext:
break;
case kObjectKey:
state_.back() = kObjectValue;
break;
case kObjectValue:
state_.back() = kObjectNext;
break;
case kObjectNext:
state_.back() = kObjectKey;
break;
default:
break;
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef BITS_HPP
#define BITS_HPP
#include <cstdint>
#ifdef _MSC_VER
# include <intrin.h>
#endif
#if defined(__GNUC__)
static int
popcnt(std::uint8_t n)
{
return __builtin_popcount(n);
}
static int
popcnt(std::uint16_t n)
{
return __builtin_popcount(n);
}
static int
popcnt(std::uint32_t n)
{
return __builtin_popcount(n);
}
static int
popcnt(std::uint64_t n)
{
return __builtin_popcountll(n);
}
#elif defined(_MSC_VER)
static int
popcnt(std::uint8_t n)
{
return __popcnt16(n);
}
static int
popcnt(std::uint16_t n)
{
return __popcnt16(n);
}
static int
popcnt(std::uint32_t n)
{
return __popcnt(n);
}
static int
popcnt(std::uint64_t n)
{
return __popcnt64(n);
}
#endif // __GNUC__
// 0x55555555 = 0b01010101010101010101010101010101
// 0x33333333 = 0b00110011001100110011001100110011
// 0x0f0f0f0f = 0b00001111000011110000111100001111
// 0x00ff00ff = 0b00000000111111110000000011111111
// 0x0000ffff = 0b00000000000000001111111111111111
static int
popcnt(std::uint8_t n)
{
n = (n & 0x55u) + (n >> 1 & 0x55u);
n = (n & 0x33u) + (n >> 2 & 0x33u);
return (n & 0x0fu) + (n >> 4 & 0x0fu);
}
static int
popcnt(std::uint16_t n)
{
n = (n & 0x5555u) + (n >> 1 & 0x5555u);
n = (n & 0x3333u) + (n >> 2 & 0x3333u);
n = (n & 0x0f0fu) + (n >> 4 & 0x0f0fu);
return (n & 0x00ffu) + (n >> 8 & 0x00ffu);
}
static int
popcnt(std::uint32_t n)
{
n = (n & 0x55555555u) + (n >> 1 & 0x55555555u);
n = (n & 0x33333333u) + (n >> 2 & 0x33333333u);
n = (n & 0x0f0f0f0fu) + (n >> 4 & 0x0f0f0f0fu);
n = (n & 0x00ff00ffu) + (n >> 8 & 0x00ff00ffu);
return (n & 0x0000ffffu) + (n >> 16 & 0x0000ffffu);
}
static int
popcnt(std::uint64_t n)
{
n = (n & 0x5555555555555555ull) + (n >> 1 & 0x5555555555555555ull);
n = (n & 0x3333333333333333ull) + (n >> 2 & 0x3333333333333333ull);
n = (n & 0x0f0f0f0f0f0f0f0full) + (n >> 4 & 0x0f0f0f0f0f0f0f0full);
n = (n & 0x00ff00ff00ff00ffull) + (n >> 8 & 0x00ff00ff00ff00ffull);
n = (n & 0x0000ffff0000ffffull) + (n >> 16 & 0x0000ffff0000ffffull);
return (n & 0x00000000ffffffffull) + (n >> 32 & 0x00000000ffffffffull);
}
static int
popcnt(std::int8_t n)
{
return popcnt(static_cast<std::uint8_t>(n));
}
static int
popcnt(std::int16_t n)
{
return popcnt(static_cast<std::uint16_t>(n));
}
static int
popcnt(std::int32_t n)
{
return popcnt(static_cast<std::uint32_t>(n));
}
static int
popcnt(std::int64_t n)
{
return popcnt(static_cast<std::uint64_t>(n));
}
#if defined(__GNUC__)
static int
bsf(std::uint8_t n)
{
return __builtin_ffs(n) - 1;
}
static int
bsf(std::uint16_t n)
{
return __builtin_ffs(n) - 1;
}
static int
bsf(std::uint32_t n)
{
return __builtin_ffs(n) - 1;
}
static int
bsf(std::uint64_t n)
{
return __builtin_ffsll(n) - 1;
}
#elif defined(_MSC_VER)
static int
bsf(std::uint8_t n)
{
int index;
unsigned char isNonZero = _BitScanForward(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static int
bsf(std::uint16_t n)
{
int index;
unsigned char isNonZero = _BitScanForward(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static int
bsf(std::uint32_t n)
{
int index;
unsigned char isNonZero = _BitScanForward(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static int
bsf(std::uint64_t n)
{
int index;
unsigned char isNonZero = _BitScanForward64(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
#endif // defined(__GNUC__)
static int
bsf(std::uint8_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
return popcnt(static_cast<std::uint8_t>(~n));
}
}
static int
bsf(std::uint16_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
return popcnt(static_cast<std::uint16_t>(~n));
}
}
static int
bsf(std::uint32_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
n |= (n << 16);
return popcnt(~n);
}
}
static int
bsf(std::uint64_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
n |= (n << 16);
n |= (n << 32);
return popcnt(~n);
}
}
static int
bsf(std::int8_t n)
{
return bsf(static_cast<std::uint8_t>(n));
}
static int
bsf(std::int16_t n)
{
return bsf(static_cast<std::uint16_t>(n));
}
static int
bsf(std::int32_t n)
{
return bsf(static_cast<std::uint32_t>(n));
}
static int
bsf(std::int64_t n)
{
return bsf(static_cast<std::uint64_t>(n));
}
#if defined(__GNUC__)
static int
bsr(std::uint8_t n)
{
return n == 0 ? -1 : (((__builtin_clz(n) & 0x07u) ^ 0x07u));
}
static int
bsr(std::uint16_t n)
{
return n == 0 ? -1 : (((__builtin_clz(n) & 0x0fu) ^ 0x0fu));
}
static int
bsr(std::uint32_t n)
{
return n == 0 ? -1 : (__builtin_clz(n) ^ 0x1fu);
}
static int
bsr(std::uint64_t n)
{
return n == 0 ? -1 : (__builtin_clzll(n) ^ 0x3fu);
}
#elif defined(_MSC_VER)
static int
bsr(std::uint8_t n)
{
int index;
unsigned char isNonZero = _BitScanReverse(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static int
bsr(std::uint16_t n)
{
int index;
unsigned char isNonZero = _BitScanReverse(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static int
bsr(std::uint32_t n)
{
int index;
unsigned char isNonZero = _BitScanReverse(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static int
bsr(std::uint64_t n)
{
int index;
unsigned char isNonZero = _BitScanReverse64(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
#endif // defined(__GNUC__)
static int
bsr(std::uint8_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
return popcnt(n) - 1;
}
}
static int
bsr(std::uint16_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
return popcnt(n) - 1;
}
}
static int
bsr(std::uint32_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return popcnt(n) - 1;
}
}
static int
bsr(std::uint64_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
n |= (n >> 32);
return popcnt(n) - 1;
}
}
static int
bsr(std::int8_t n)
{
return bsr(static_cast<std::uint8_t>(n));
}
static int
bsr(std::int16_t n)
{
return bsr(static_cast<std::uint16_t>(n));
}
static int
bsr(std::int32_t n)
{
return bsr(static_cast<std::uint32_t>(n));
}
static int
bsr(std::int64_t n)
{
return bsr(static_cast<std::uint64_t>(n));
}
#endif // BITS_HPP
<commit_msg>Use SFINAE and std::make_unsigned<commit_after>#ifndef BITS_HPP
#define BITS_HPP
#include <cstdint>
#include <type_traits>
#ifdef _MSC_VER
# include <intrin.h>
#endif
#if defined(__GNUC__)
static inline int
popcnt(std::uint8_t n)
{
return __builtin_popcount(n);
}
static inline int
popcnt(std::uint16_t n)
{
return __builtin_popcount(n);
}
static inline int
popcnt(std::uint32_t n)
{
return __builtin_popcount(n);
}
static inline int
popcnt(std::uint64_t n)
{
return __builtin_popcountll(n);
}
#elif defined(_MSC_VER)
static inline int
popcnt(std::uint8_t n)
{
return __popcnt16(n);
}
static inline int
popcnt(std::uint16_t n)
{
return __popcnt16(n);
}
static inline int
popcnt(std::uint32_t n)
{
return __popcnt(n);
}
static inline int
popcnt(std::uint64_t n)
{
return __popcnt64(n);
}
#else
// 0x55555555 = 0b01010101010101010101010101010101
// 0x33333333 = 0b00110011001100110011001100110011
// 0x0f0f0f0f = 0b00001111000011110000111100001111
// 0x00ff00ff = 0b00000000111111110000000011111111
// 0x0000ffff = 0b00000000000000001111111111111111
static inline int
popcnt(std::uint8_t n)
{
n = (n & 0x55u) + (n >> 1 & 0x55u);
n = (n & 0x33u) + (n >> 2 & 0x33u);
return (n & 0x0fu) + (n >> 4 & 0x0fu);
}
static inline int
popcnt(std::uint16_t n)
{
n = (n & 0x5555u) + (n >> 1 & 0x5555u);
n = (n & 0x3333u) + (n >> 2 & 0x3333u);
n = (n & 0x0f0fu) + (n >> 4 & 0x0f0fu);
return (n & 0x00ffu) + (n >> 8 & 0x00ffu);
}
static inline int
popcnt(std::uint32_t n)
{
n = (n & 0x55555555u) + (n >> 1 & 0x55555555u);
n = (n & 0x33333333u) + (n >> 2 & 0x33333333u);
n = (n & 0x0f0f0f0fu) + (n >> 4 & 0x0f0f0f0fu);
n = (n & 0x00ff00ffu) + (n >> 8 & 0x00ff00ffu);
return (n & 0x0000ffffu) + (n >> 16 & 0x0000ffffu);
}
static inline int
popcnt(std::uint64_t n)
{
n = (n & 0x5555555555555555ull) + (n >> 1 & 0x5555555555555555ull);
n = (n & 0x3333333333333333ull) + (n >> 2 & 0x3333333333333333ull);
n = (n & 0x0f0f0f0f0f0f0f0full) + (n >> 4 & 0x0f0f0f0f0f0f0f0full);
n = (n & 0x00ff00ff00ff00ffull) + (n >> 8 & 0x00ff00ff00ff00ffull);
n = (n & 0x0000ffff0000ffffull) + (n >> 16 & 0x0000ffff0000ffffull);
return (n & 0x00000000ffffffffull) + (n >> 32 & 0x00000000ffffffffull);
}
#endif // __GNUC__
template<typename T, typename std::enable_if<std::is_signed<T>::value, std::nullptr_t>::type = nullptr>
static inline int
popcnt(T n)
{
return popcnt(static_cast<typename std::make_unsigned<T>::type>(n));
}
#if defined(__GNUC__)
static inline int
bsf(std::uint8_t n)
{
return __builtin_ffs(n) - 1;
}
static inline int
bsf(std::uint16_t n)
{
return __builtin_ffs(n) - 1;
}
static inline int
bsf(std::uint32_t n)
{
return __builtin_ffs(n) - 1;
}
static inline int
bsf(std::uint64_t n)
{
return __builtin_ffsll(n) - 1;
}
#elif defined(_MSC_VER)
static inline int
bsf(std::uint8_t n)
{
int index;
unsigned char isNonZero = _BitScanForward(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static inline int
bsf(std::uint16_t n)
{
int index;
unsigned char isNonZero = _BitScanForward(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static inline int
bsf(std::uint32_t n)
{
int index;
unsigned char isNonZero = _BitScanForward(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static inline int
bsf(std::uint64_t n)
{
int index;
unsigned char isNonZero = _BitScanForward64(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
#else
static inline int
bsf(std::uint8_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
return popcnt(static_cast<std::uint8_t>(~n));
}
}
static inline int
bsf(std::uint16_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
return popcnt(static_cast<std::uint16_t>(~n));
}
}
static inline int
bsf(std::uint32_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
n |= (n << 16);
return popcnt(~n);
}
}
static inline int
bsf(std::uint64_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
n |= (n << 16);
n |= (n << 32);
return popcnt(~n);
}
}
#endif // defined(__GNUC__)
template<typename T, typename std::enable_if<std::is_signed<T>::value, std::nullptr_t>::type = nullptr>
static inline int
bfs(T n)
{
return bfs(static_cast<typename std::make_unsigned<T>::type>(n));
}
#if defined(__GNUC__)
static inline int
bsr(std::uint8_t n)
{
return n == 0 ? -1 : (((__builtin_clz(n) & 0x07u) ^ 0x07u));
}
static inline int
bsr(std::uint16_t n)
{
return n == 0 ? -1 : (((__builtin_clz(n) & 0x0fu) ^ 0x0fu));
}
static inline int
bsr(std::uint32_t n)
{
return n == 0 ? -1 : (__builtin_clz(n) ^ 0x1fu);
}
static inline int
bsr(std::uint64_t n)
{
return n == 0 ? -1 : (__builtin_clzll(n) ^ 0x3fu);
}
#elif defined(_MSC_VER)
static inline int
bsr(std::uint8_t n)
{
int index;
unsigned char isNonZero = _BitScanReverse(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static inline int
bsr(std::uint16_t n)
{
int index;
unsigned char isNonZero = _BitScanReverse(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static inline int
bsr(std::uint32_t n)
{
int index;
unsigned char isNonZero = _BitScanReverse(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
static inline int
bsr(std::uint64_t n)
{
int index;
unsigned char isNonZero = _BitScanReverse64(reinterpret_cast<unsigned long *>(&index), n);
return isNonZero ? index : -1;
}
#else
static inline int
bsr(std::uint8_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
return popcnt(n) - 1;
}
}
static inline int
bsr(std::uint16_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
return popcnt(n) - 1;
}
}
static inline int
bsr(std::uint32_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return popcnt(n) - 1;
}
}
static inline int
bsr(std::uint64_t n)
{
if (n == 0) {
return -1;
} else {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
n |= (n >> 32);
return popcnt(n) - 1;
}
}
#endif // defined(__GNUC__)
template<typename T, typename std::enable_if<std::is_signed<T>::value, std::nullptr_t>::type = nullptr>
static inline int
bsr(T n)
{
return bsr(static_cast<typename std::make_unsigned<T>::type>(n));
}
#endif // BITS_HPP
<|endoftext|> |
<commit_before>/*****************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2011 Laszlo Papp <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*****************************************************************************/
#include "gamewindowmanager.h"
#include "lib/models/gameviewitem.h"
#include "lib/models/gameitemsmodel.h"
#include "lib/models/commentitemsmodel.h"
#include "lib/authentication.h"
#include <input/inputmanager.h>
#include <engine/scene.h>
#include <graphics/renderwidget.h>
#include <QtDeclarative/QDeclarativeView>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative>
#include <QtGui/QGraphicsObject>
#include <QtGui/QApplication>
#include <QtGui/QStackedWidget>
#include <QtCore/QTimer>
#include <QtCore/QDebug>
using namespace GluonQMLPlayer;
class GameWindowManager::GameWindowManagerPrivate
{
public:
GameWindowManagerPrivate()
: stackedWidget( new QStackedWidget( 0 ) )
, gameItemsModel( new GluonPlayer::GameItemsModel() )
, commentItemsModel( 0 )
, auth( 0 )
, declarativeView( new QDeclarativeView(stackedWidget) )
, renderWidget( new GluonGraphics::RenderWidget(stackedWidget) )
, ctxt( 0 )
{
}
~GameWindowManagerPrivate()
{
delete stackedWidget;
delete gameItemsModel;
delete commentItemsModel;
}
QString title;
QString fileName;
int msecElapsed;
int frameCount;
QStackedWidget *stackedWidget;
GluonPlayer::GameItemsModel *gameItemsModel;
GluonPlayer::CommentItemsModel *commentItemsModel;
GluonPlayer::Authentication* auth;
QDeclarativeView *declarativeView;
GluonGraphics::RenderWidget* renderWidget;
QDeclarativeContext *ctxt;
QObject* rootObj;
QObject* login;
};
GameWindowManager::GameWindowManager( const QString& /* filename */ )
: QObject()
, d( new GameWindowManagerPrivate )
{
d->auth = GluonPlayer::Authentication::instance();
d->renderWidget->initializeGL();
d->ctxt = d->declarativeView->rootContext();
d->ctxt->setContextProperty( "authentication", d->auth );
d->ctxt->setContextProperty( "gameItemsModel", d->gameItemsModel );
d->ctxt->setContextProperty( "commentItemsModel", d->commentItemsModel );
d->ctxt->setContextProperty( "gameWindowManager", this );
// Note QML enum handling is more or less bonkers at the moment
// It should be removed after the QML enum support is not that flaky
qmlRegisterUncreatableType<GluonPlayer::GameViewItem>("GluonPlayerGameViewItem", 1, 0, "GameViewItem", QString("Support the Status enumeration"));
d->declarativeView->setSource( QUrl( "qrc:/main.qml" ) );
d->rootObj = d->declarativeView->rootObject();
d->login = d->rootObj->findChild<QObject*>( "login" );
QObject::connect( d->auth, SIGNAL( initialized() ), d->login, SLOT( providerSet() ) );
d->stackedWidget->addWidget(d->declarativeView);
d->stackedWidget->addWidget(d->renderWidget);
d->stackedWidget->setCurrentIndex(0);
connect(QApplication::instance(), SIGNAL(lastWindowClosed()), GluonEngine::Game::instance(), SLOT( stopGame()));
}
GameWindowManager::~GameWindowManager ( )
{
delete d;
}
bool GameWindowManager::isViewportGLWidget( )
{
return qobject_cast<QGLWidget*>(d->declarativeView);
}
void GameWindowManager::startGame( )
{
GluonCore::GluonObjectFactory::instance()->loadPlugins();
m_project = new GluonEngine::GameProject();
m_project->loadFromFile( m_gameFileName );
GluonEngine::Game::instance()->setGameProject( m_project );
GluonEngine::Game::instance()->setCurrentScene( m_project->entryPoint() );
d->stackedWidget->setCurrentIndex(1);
d->renderWidget->setFocus();
GluonEngine::Game::instance()->runGame();
}
void GameWindowManager::pauseGame()
{
GluonEngine::Game::instance()->setPause( true );
// stateChanged( "paused" );
}
void GameWindowManager::stopGame()
{
// d->stackedWidget->setCurrentIndex(0);
GluonEngine::Game::instance()->stopGame();
}
void GameWindowManager::setProject( int index )
{
m_gameFileName = d->gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString();
openProject();
}
int GameWindowManager::availableGamesCount( ) const
{
return d->gameItemsModel->rowCount();
}
void GameWindowManager::buildCommentsModel( int index )
{
QString gameID = d->gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::IDRole).toString();
if( gameID.isEmpty() )
{
return;
}
d->commentItemsModel = new GluonPlayer::CommentItemsModel( gameID );
}
void GameWindowManager::setProject( const QModelIndex& index )
{
m_gameFileName = index.data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString();
openProject();
}
void GameWindowManager::openProject()
{
if( m_gameFileName.isEmpty() )
{
return;
}
connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->renderWidget, SLOT( updateGL() ) );
connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );
connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );
GluonInput::InputManager::instance()->setFilteredObject(d->renderWidget);
QTimer::singleShot( 1000, this, SLOT( startGame() ) );
}
void GameWindowManager::activated( QModelIndex index )
{
if( index.isValid() )
{
}
}
void GameWindowManager::updateTitle( int msec )
{
d->msecElapsed += msec;
static int fps = 0;
if( d->msecElapsed > 1000 )
{
fps = d->frameCount;
d->frameCount = 0;
d->msecElapsed = 0;
}
}
void GameWindowManager::countFrames( int /* time */ )
{
d->frameCount++;
}
GluonPlayer::GameItemsModel* GameWindowManager::gameItemsModel() const
{
return d->gameItemsModel;
}
void GameWindowManager::setGameItemsModel(GluonPlayer::GameItemsModel* gameItemsModel)
{
d->gameItemsModel = gameItemsModel;
}
GluonPlayer::CommentItemsModel* GameWindowManager::commentItemsModel() const
{
return d->commentItemsModel;
}
void GameWindowManager::setCommentItemsModel(GluonPlayer::CommentItemsModel* commentItemsModel)
{
d->commentItemsModel = commentItemsModel;
}
void GameWindowManager::show()
{
d->stackedWidget->show();
}
#include "gamewindowmanager.moc"
<commit_msg>Use setCurrentWidget instead of setCurrentIndex to avoid numbers<commit_after>/*****************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2011 Laszlo Papp <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*****************************************************************************/
#include "gamewindowmanager.h"
#include "lib/models/gameviewitem.h"
#include "lib/models/gameitemsmodel.h"
#include "lib/models/commentitemsmodel.h"
#include "lib/authentication.h"
#include <input/inputmanager.h>
#include <engine/scene.h>
#include <graphics/renderwidget.h>
#include <QtDeclarative/QDeclarativeView>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative>
#include <QtGui/QGraphicsObject>
#include <QtGui/QApplication>
#include <QtGui/QStackedWidget>
#include <QtCore/QTimer>
#include <QtCore/QDebug>
using namespace GluonQMLPlayer;
class GameWindowManager::GameWindowManagerPrivate
{
public:
GameWindowManagerPrivate()
: stackedWidget( new QStackedWidget( 0 ) )
, gameItemsModel( new GluonPlayer::GameItemsModel() )
, commentItemsModel( 0 )
, auth( 0 )
, declarativeView( new QDeclarativeView(stackedWidget) )
, renderWidget( new GluonGraphics::RenderWidget(stackedWidget) )
, ctxt( 0 )
{
}
~GameWindowManagerPrivate()
{
delete stackedWidget;
delete gameItemsModel;
delete commentItemsModel;
}
QString title;
QString fileName;
int msecElapsed;
int frameCount;
QStackedWidget *stackedWidget;
GluonPlayer::GameItemsModel *gameItemsModel;
GluonPlayer::CommentItemsModel *commentItemsModel;
GluonPlayer::Authentication* auth;
QDeclarativeView *declarativeView;
GluonGraphics::RenderWidget* renderWidget;
QDeclarativeContext *ctxt;
QObject* rootObj;
QObject* login;
};
GameWindowManager::GameWindowManager( const QString& /* filename */ )
: QObject()
, d( new GameWindowManagerPrivate )
{
d->auth = GluonPlayer::Authentication::instance();
d->renderWidget->initializeGL();
d->ctxt = d->declarativeView->rootContext();
d->ctxt->setContextProperty( "authentication", d->auth );
d->ctxt->setContextProperty( "gameItemsModel", d->gameItemsModel );
d->ctxt->setContextProperty( "commentItemsModel", d->commentItemsModel );
d->ctxt->setContextProperty( "gameWindowManager", this );
// Note QML enum handling is more or less bonkers at the moment
// It should be removed after the QML enum support is not that flaky
qmlRegisterUncreatableType<GluonPlayer::GameViewItem>("GluonPlayerGameViewItem", 1, 0, "GameViewItem", QString("Support the Status enumeration"));
d->declarativeView->setSource( QUrl( "qrc:/main.qml" ) );
d->rootObj = d->declarativeView->rootObject();
d->login = d->rootObj->findChild<QObject*>( "login" );
QObject::connect( d->auth, SIGNAL( initialized() ), d->login, SLOT( providerSet() ) );
d->stackedWidget->addWidget(d->declarativeView);
d->stackedWidget->addWidget(d->renderWidget);
d->stackedWidget->setCurrentIndex(0);
connect(QApplication::instance(), SIGNAL(lastWindowClosed()), GluonEngine::Game::instance(), SLOT( stopGame()));
}
GameWindowManager::~GameWindowManager ( )
{
delete d;
}
bool GameWindowManager::isViewportGLWidget( )
{
return qobject_cast<QGLWidget*>(d->declarativeView);
}
void GameWindowManager::startGame( )
{
GluonCore::GluonObjectFactory::instance()->loadPlugins();
m_project = new GluonEngine::GameProject();
m_project->loadFromFile( m_gameFileName );
GluonEngine::Game::instance()->setGameProject( m_project );
GluonEngine::Game::instance()->setCurrentScene( m_project->entryPoint() );
d->stackedWidget->setCurrentWidget(d->renderWidget);
d->renderWidget->setFocus();
GluonEngine::Game::instance()->runGame();
}
void GameWindowManager::pauseGame()
{
GluonEngine::Game::instance()->setPause( true );
// stateChanged( "paused" );
}
void GameWindowManager::stopGame()
{
GluonEngine::Game::instance()->stopGame();
}
void GameWindowManager::setProject( int index )
{
m_gameFileName = d->gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString();
openProject();
}
int GameWindowManager::availableGamesCount( ) const
{
return d->gameItemsModel->rowCount();
}
void GameWindowManager::buildCommentsModel( int index )
{
QString gameID = d->gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::IDRole).toString();
if( gameID.isEmpty() )
{
return;
}
d->commentItemsModel = new GluonPlayer::CommentItemsModel( gameID );
}
void GameWindowManager::setProject( const QModelIndex& index )
{
m_gameFileName = index.data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString();
openProject();
}
void GameWindowManager::openProject()
{
if( m_gameFileName.isEmpty() )
{
return;
}
connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->renderWidget, SLOT( updateGL() ) );
connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );
connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );
GluonInput::InputManager::instance()->setFilteredObject(d->renderWidget);
QTimer::singleShot( 1000, this, SLOT( startGame() ) );
}
void GameWindowManager::activated( QModelIndex index )
{
if( index.isValid() )
{
}
}
void GameWindowManager::updateTitle( int msec )
{
d->msecElapsed += msec;
static int fps = 0;
if( d->msecElapsed > 1000 )
{
fps = d->frameCount;
d->frameCount = 0;
d->msecElapsed = 0;
}
}
void GameWindowManager::countFrames( int /* time */ )
{
d->frameCount++;
}
GluonPlayer::GameItemsModel* GameWindowManager::gameItemsModel() const
{
return d->gameItemsModel;
}
void GameWindowManager::setGameItemsModel(GluonPlayer::GameItemsModel* gameItemsModel)
{
d->gameItemsModel = gameItemsModel;
}
GluonPlayer::CommentItemsModel* GameWindowManager::commentItemsModel() const
{
return d->commentItemsModel;
}
void GameWindowManager::setCommentItemsModel(GluonPlayer::CommentItemsModel* commentItemsModel)
{
d->commentItemsModel = commentItemsModel;
}
void GameWindowManager::show()
{
d->stackedWidget->show();
}
#include "gamewindowmanager.moc"
<|endoftext|> |
<commit_before>#include "base/logging.h"
#include "input/input_state.h"
#include "ui/screen.h"
#include "ui/ui.h"
ScreenManager::ScreenManager() {
nextScreen_ = 0;
uiContext_ = 0;
dialogFinished_ = 0;
}
ScreenManager::~ScreenManager() {
shutdown();
}
void ScreenManager::switchScreen(Screen *screen) {
// Note that if a dialog is found, this will be a silent background switch that
// will only become apparent if the dialog is closed. The previous screen will stick around
// until that switch.
// TODO: is this still true?
if (nextScreen_ != 0) {
FLOG("WTF? Already had a nextScreen_");
}
if (screen == 0) {
WLOG("Swiching to a zero screen, this can't be good");
}
if (stack_.empty() || screen != stack_.back().screen) {
nextScreen_ = screen;
nextScreen_->setScreenManager(this);
}
}
void ScreenManager::update(InputState &input) {
if (nextScreen_) {
switchToNext();
}
if (stack_.size()) {
stack_.back().screen->update(input);
}
}
void ScreenManager::switchToNext() {
if (!nextScreen_) {
ELOG("switchToNext: No nextScreen_!");
}
Layer temp = {0, 0};
if (!stack_.empty()) {
temp = stack_.back();
stack_.pop_back();
}
Layer newLayer = {nextScreen_, 0};
stack_.push_back(newLayer);
if (temp.screen) {
delete temp.screen;
}
nextScreen_ = 0;
}
void ScreenManager::touch(const TouchInput &touch) {
if (!stack_.empty())
stack_.back().screen->touch(touch);
}
void ScreenManager::key(const KeyInput &key) {
if (!stack_.empty())
stack_.back().screen->key(key);
}
void ScreenManager::axis(const AxisInput &axis) {
if (!stack_.empty())
stack_.back().screen->axis(axis);
}
void ScreenManager::render() {
if (!stack_.empty()) {
switch (stack_.back().flags) {
case LAYER_SIDEMENU:
case LAYER_TRANSPARENT:
if (stack_.size() == 1) {
ELOG("Can't have sidemenu over nothing");
break;
} else {
auto iter = stack_.end();
iter--;
iter--;
Layer backback = *iter;
UIDisableBegin();
// Also shift to the right somehow...
backback.screen->render();
UIDisableEnd();
stack_.back().screen->render();
break;
}
default:
stack_.back().screen->render();
break;
}
} else {
ELOG("No current screen!");
}
processFinishDialog();
}
void ScreenManager::sendMessage(const char *msg, const char *value) {
if (!stack_.empty())
stack_.back().screen->sendMessage(msg, value);
}
void ScreenManager::deviceLost() {
for (size_t i = 0; i < stack_.size(); i++) {
stack_[i].screen->deviceLost();
}
// Dialogs too? Nah, they should only use the standard UI texture anyway.
// TODO: Change this when it becomes necessary.
}
Screen *ScreenManager::topScreen() const {
if (!stack_.empty())
return stack_.back().screen;
else
return 0;
}
void ScreenManager::shutdown() {
for (auto x = stack_.begin(); x != stack_.end(); x++)
delete x->screen;
stack_.clear();
delete nextScreen_;
nextScreen_ = 0;
}
void ScreenManager::push(Screen *screen, int layerFlags) {
if (nextScreen_ && stack_.empty()) {
// we're during init, this is OK
switchToNext();
}
screen->setScreenManager(this);
if (screen->isTransparent()) {
layerFlags |= LAYER_TRANSPARENT;
}
Layer layer = {screen, layerFlags};
stack_.push_back(layer);
}
void ScreenManager::pop() {
if (stack_.size()) {
delete stack_.back().screen;
stack_.pop_back();
} else {
ELOG("Can't pop when stack empty");
}
}
void ScreenManager::RecreateAllViews() {
for (auto it = stack_.begin(); it != stack_.end(); ++it) {
it->screen->RecreateViews();
}
}
void ScreenManager::finishDialog(const Screen *dialog, DialogResult result) {
if (dialog != stack_.back().screen) {
ELOG("Wrong dialog being finished!");
return;
}
if (!stack_.size()) {
ELOG("Must be in a dialog to finishDialog");
return;
}
dialogFinished_ = dialog;
dialogResult_ = result;
}
void ScreenManager::processFinishDialog() {
if (dialogFinished_) {
if (stack_.size()) {
stack_.pop_back();
}
Screen *caller = topScreen();
if (caller) {
caller->dialogFinished(dialogFinished_, dialogResult_);
} else {
ELOG("ERROR: no top screen when finishing dialog");
}
delete dialogFinished_;
dialogFinished_ = 0;
}
}
<commit_msg>Don't crash if another dialog is added while finishing.<commit_after>#include "base/logging.h"
#include "input/input_state.h"
#include "ui/screen.h"
#include "ui/ui.h"
ScreenManager::ScreenManager() {
nextScreen_ = 0;
uiContext_ = 0;
dialogFinished_ = 0;
}
ScreenManager::~ScreenManager() {
shutdown();
}
void ScreenManager::switchScreen(Screen *screen) {
// Note that if a dialog is found, this will be a silent background switch that
// will only become apparent if the dialog is closed. The previous screen will stick around
// until that switch.
// TODO: is this still true?
if (nextScreen_ != 0) {
FLOG("WTF? Already had a nextScreen_");
}
if (screen == 0) {
WLOG("Swiching to a zero screen, this can't be good");
}
if (stack_.empty() || screen != stack_.back().screen) {
nextScreen_ = screen;
nextScreen_->setScreenManager(this);
}
}
void ScreenManager::update(InputState &input) {
if (nextScreen_) {
switchToNext();
}
if (stack_.size()) {
stack_.back().screen->update(input);
}
}
void ScreenManager::switchToNext() {
if (!nextScreen_) {
ELOG("switchToNext: No nextScreen_!");
}
Layer temp = {0, 0};
if (!stack_.empty()) {
temp = stack_.back();
stack_.pop_back();
}
Layer newLayer = {nextScreen_, 0};
stack_.push_back(newLayer);
if (temp.screen) {
delete temp.screen;
}
nextScreen_ = 0;
}
void ScreenManager::touch(const TouchInput &touch) {
if (!stack_.empty())
stack_.back().screen->touch(touch);
}
void ScreenManager::key(const KeyInput &key) {
if (!stack_.empty())
stack_.back().screen->key(key);
}
void ScreenManager::axis(const AxisInput &axis) {
if (!stack_.empty())
stack_.back().screen->axis(axis);
}
void ScreenManager::render() {
if (!stack_.empty()) {
switch (stack_.back().flags) {
case LAYER_SIDEMENU:
case LAYER_TRANSPARENT:
if (stack_.size() == 1) {
ELOG("Can't have sidemenu over nothing");
break;
} else {
auto iter = stack_.end();
iter--;
iter--;
Layer backback = *iter;
UIDisableBegin();
// Also shift to the right somehow...
backback.screen->render();
UIDisableEnd();
stack_.back().screen->render();
break;
}
default:
stack_.back().screen->render();
break;
}
} else {
ELOG("No current screen!");
}
processFinishDialog();
}
void ScreenManager::sendMessage(const char *msg, const char *value) {
if (!stack_.empty())
stack_.back().screen->sendMessage(msg, value);
}
void ScreenManager::deviceLost() {
for (size_t i = 0; i < stack_.size(); i++) {
stack_[i].screen->deviceLost();
}
// Dialogs too? Nah, they should only use the standard UI texture anyway.
// TODO: Change this when it becomes necessary.
}
Screen *ScreenManager::topScreen() const {
if (!stack_.empty())
return stack_.back().screen;
else
return 0;
}
void ScreenManager::shutdown() {
for (auto x = stack_.begin(); x != stack_.end(); x++)
delete x->screen;
stack_.clear();
delete nextScreen_;
nextScreen_ = 0;
}
void ScreenManager::push(Screen *screen, int layerFlags) {
if (nextScreen_ && stack_.empty()) {
// we're during init, this is OK
switchToNext();
}
screen->setScreenManager(this);
if (screen->isTransparent()) {
layerFlags |= LAYER_TRANSPARENT;
}
Layer layer = {screen, layerFlags};
stack_.push_back(layer);
}
void ScreenManager::pop() {
if (stack_.size()) {
delete stack_.back().screen;
stack_.pop_back();
} else {
ELOG("Can't pop when stack empty");
}
}
void ScreenManager::RecreateAllViews() {
for (auto it = stack_.begin(); it != stack_.end(); ++it) {
it->screen->RecreateViews();
}
}
void ScreenManager::finishDialog(const Screen *dialog, DialogResult result) {
if (stack_.empty()) {
ELOG("Must be in a dialog to finishDialog");
return;
}
if (dialog != stack_.back().screen) {
ELOG("Wrong dialog being finished!");
return;
}
dialogFinished_ = dialog;
dialogResult_ = result;
}
void ScreenManager::processFinishDialog() {
if (dialogFinished_) {
// Another dialog may have been pushed before the render, so search for it.
Screen *caller = 0;
for (size_t i = 0; i < stack_.size(); ++i) {
if (stack_[i].screen != dialogFinished_) {
continue;
}
stack_.erase(stack_.begin() + i);
// The previous screen was the caller (not necessarily the topmost.)
if (i > 0) {
caller = stack_[i - 1].screen;
}
}
if (!caller) {
ELOG("ERROR: no top screen when finishing dialog");
} else if (caller != topScreen()) {
// The caller may get confused if we call dialogFinished() now.
WLOG("Skipping non-top dialog when finishing dialog.");
} else {
caller->dialogFinished(dialogFinished_, dialogResult_);
}
delete dialogFinished_;
dialogFinished_ = 0;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unopropertyarrayhelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 12:56:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#define _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#include <cppuhelper/propshlp.hxx>
#include <tools/table.hxx>
#include <list>
// ----------------------------------------------------
// class UnoPropertyArrayHelper
// ----------------------------------------------------
class UnoPropertyArrayHelper : public ::cppu::IPropertyArrayHelper
{
private:
Table maIDs;
protected:
sal_Bool ImplHasProperty( sal_uInt16 nPropId ) const;
public:
UnoPropertyArrayHelper( const ::com::sun::star::uno::Sequence<sal_Int32>& rIDs );
UnoPropertyArrayHelper( const std::list< sal_uInt16 > &rIDs );
// ::cppu::IPropertyArrayHelper
sal_Bool SAL_CALL fillPropertyMembersByHandle( ::rtl::OUString * pPropName, sal_Int16 * pAttributes, sal_Int32 nHandle );
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL getProperties();
::com::sun::star::beans::Property SAL_CALL getPropertyByName(const ::rtl::OUString& rPropertyName) throw (::com::sun::star::beans::UnknownPropertyException);
sal_Bool SAL_CALL hasPropertyByName(const ::rtl::OUString& rPropertyName);
sal_Int32 SAL_CALL getHandleByName( const ::rtl::OUString & rPropertyName );
sal_Int32 SAL_CALL fillHandles( sal_Int32* pHandles, const ::com::sun::star::uno::Sequence< ::rtl::OUString > & rPropNames );
};
#endif // _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.32); FILE MERGED 2008/03/28 15:40:10 rt 1.4.32.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: unopropertyarrayhelper.hxx,v $
* $Revision: 1.5 $
*
* 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 _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#define _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#include <cppuhelper/propshlp.hxx>
#include <tools/table.hxx>
#include <list>
// ----------------------------------------------------
// class UnoPropertyArrayHelper
// ----------------------------------------------------
class UnoPropertyArrayHelper : public ::cppu::IPropertyArrayHelper
{
private:
Table maIDs;
protected:
sal_Bool ImplHasProperty( sal_uInt16 nPropId ) const;
public:
UnoPropertyArrayHelper( const ::com::sun::star::uno::Sequence<sal_Int32>& rIDs );
UnoPropertyArrayHelper( const std::list< sal_uInt16 > &rIDs );
// ::cppu::IPropertyArrayHelper
sal_Bool SAL_CALL fillPropertyMembersByHandle( ::rtl::OUString * pPropName, sal_Int16 * pAttributes, sal_Int32 nHandle );
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL getProperties();
::com::sun::star::beans::Property SAL_CALL getPropertyByName(const ::rtl::OUString& rPropertyName) throw (::com::sun::star::beans::UnknownPropertyException);
sal_Bool SAL_CALL hasPropertyByName(const ::rtl::OUString& rPropertyName);
sal_Int32 SAL_CALL getHandleByName( const ::rtl::OUString & rPropertyName );
sal_Int32 SAL_CALL fillHandles( sal_Int32* pHandles, const ::com::sun::star::uno::Sequence< ::rtl::OUString > & rPropNames );
};
#endif // _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "SurgSim/Framework/Timer.h"
//#include "MockObjects.h" //NOLINT
using SurgSim::Framework::Timer;
TEST(TimerTest, Constructor)
{
EXPECT_NO_THROW({std::shared_ptr<Timer> timer(new Timer());});
}
TEST(TimerTest, Starting)
{
std::shared_ptr<Timer> timer(new Timer());
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 0);
EXPECT_EQ(timer->getNumberOfClockFails(), 0);
}
TEST(TimerTest, SettingFrames)
{
std::shared_ptr<Timer> timer(new Timer());
timer->endFrame();
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 1);
EXPECT_EQ(timer->getAverageFrameRate(), timer->getLastFrameRate());
EXPECT_EQ(timer->getAverageFramePeriod(), timer->getLastFramePeriod());
timer->start();
timer->setNumberOfFrames(3);
for (auto i = 0; i < 5; ++i)
{
timer->endFrame();
}
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 3);
}
TEST(TimerTest, Comparison)
{
std::shared_ptr<Timer> timer1(new Timer());
std::shared_ptr<Timer> timer2(new Timer());
for (auto i = 0; i < 100; ++i)
{
timer2->beginFrame();
timer2->endFrame();
timer1->endFrame();
}
EXPECT_TRUE(timer1->getAverageFramePeriod() >= timer2->getAverageFramePeriod());
}
<commit_msg>Remove commented-out #include line from TimerTest.cpp<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "SurgSim/Framework/Timer.h"
using SurgSim::Framework::Timer;
TEST(TimerTest, Constructor)
{
EXPECT_NO_THROW({std::shared_ptr<Timer> timer(new Timer());});
}
TEST(TimerTest, Starting)
{
std::shared_ptr<Timer> timer(new Timer());
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 0);
EXPECT_EQ(timer->getNumberOfClockFails(), 0);
}
TEST(TimerTest, SettingFrames)
{
std::shared_ptr<Timer> timer(new Timer());
timer->endFrame();
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 1);
EXPECT_EQ(timer->getAverageFrameRate(), timer->getLastFrameRate());
EXPECT_EQ(timer->getAverageFramePeriod(), timer->getLastFramePeriod());
timer->start();
timer->setNumberOfFrames(3);
for (auto i = 0; i < 5; ++i)
{
timer->endFrame();
}
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 3);
}
TEST(TimerTest, Comparison)
{
std::shared_ptr<Timer> timer1(new Timer());
std::shared_ptr<Timer> timer2(new Timer());
for (auto i = 0; i < 100; ++i)
{
timer2->beginFrame();
timer2->endFrame();
timer1->endFrame();
}
EXPECT_TRUE(timer1->getAverageFramePeriod() >= timer2->getAverageFramePeriod());
}
<|endoftext|> |
<commit_before>/*
* A simple pelvis motion control block for use with bipeds. Uses PD control to regulate the pelvis
* to a fixed height above the feet and drives the yaw to match the average foot yaw.
*
*/
#include "controlUtil.h"
struct PelvisMotionControlData {
RigidBodyManipulator* r;
double alpha;
double pelvis_height_previous;
double nominal_pelvis_height;
Vector6d Kp;
Vector6d Kd;
int pelvis_body_index;
int rfoot_body_index;
int lfoot_body_index;
};
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs<1) mexErrMsgTxt("usage: ptr = pelvisMotionControlmex(0,robot_obj,alpha,nominal_pelvis_height,Kp,Kd); y=pelvisMotionControlmex(ptr,x)");
if (nlhs<1) mexErrMsgTxt("take at least one output... please.");
struct PelvisMotionControlData* pdata;
if (mxGetScalar(prhs[0])==0) { // then construct the data object and return
pdata = new struct PelvisMotionControlData;
// get robot mex model ptr
if (!mxIsNumeric(prhs[1]) || mxGetNumberOfElements(prhs[1])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the second argument should be the robot mex ptr");
memcpy(&(pdata->r),mxGetData(prhs[1]),sizeof(pdata->r));
if (!mxIsNumeric(prhs[2]) || mxGetNumberOfElements(prhs[2])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the third argument should be alpha");
memcpy(&(pdata->alpha),mxGetPr(prhs[2]),sizeof(pdata->alpha));
if (!mxIsNumeric(prhs[3]) || mxGetNumberOfElements(prhs[3])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the fourth argument should be nominal_pelvis_height");
memcpy(&(pdata->nominal_pelvis_height),mxGetPr(prhs[3]),sizeof(pdata->nominal_pelvis_height));
if (!mxIsNumeric(prhs[4]) || mxGetM(prhs[4])!=6 || mxGetN(prhs[4])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the fifth argument should be Kp");
memcpy(&(pdata->Kp),mxGetPr(prhs[4]),sizeof(pdata->Kp));
if (!mxIsNumeric(prhs[5]) || mxGetM(prhs[5])!=6 || mxGetN(prhs[5])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the sixth argument should be Kd");
memcpy(&(pdata->Kd),mxGetPr(prhs[5]),sizeof(pdata->Kd));
mxClassID cid;
if (sizeof(pdata)==4) cid = mxUINT32_CLASS;
else if (sizeof(pdata)==8) cid = mxUINT64_CLASS;
else mexErrMsgIdAndTxt("Drake:pelvisMotionControlmex:PointerSize","Are you on a 32-bit machine or 64-bit machine??");
pdata->pelvis_height_previous = -1;
pdata->pelvis_body_index = pdata->r->findLinkInd("pelvis", 0);
pdata->rfoot_body_index = pdata->r->findLinkInd("r_foot", 0);
pdata->lfoot_body_index = pdata->r->findLinkInd("l_foot", 0);
plhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);
memcpy(mxGetData(plhs[0]),&pdata,sizeof(pdata));
return;
}
// first get the ptr back from matlab
if (!mxIsNumeric(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the first argument should be the ptr");
memcpy(&pdata,mxGetData(prhs[0]),sizeof(pdata));
int nq = pdata->r->num_dof;
double *q = mxGetPr(prhs[1]);
double *qd = &q[nq];
Map<VectorXd> qdvec(qd,nq);
pdata->r->doKinematics(q,false,qd);
// TODO: this must be updated to use quaternions/spatial velocity
Vector6d pelvis_pose,rfoot_pose,lfoot_pose;
MatrixXd Jpelvis = MatrixXd::Zero(6,pdata->r->num_dof);
Vector4d zero = Vector4d::Zero();
zero(3) = 1.0;
pdata->r->forwardKin(pdata->pelvis_body_index,zero,1,pelvis_pose);
pdata->r->forwardJac(pdata->pelvis_body_index,zero,1,Jpelvis);
pdata->r->forwardKin(pdata->rfoot_body_index,zero,1,rfoot_pose);
pdata->r->forwardKin(pdata->lfoot_body_index,zero,1,lfoot_pose);
if (pdata->pelvis_height_previous<0) {
pdata->pelvis_height_previous = pelvis_pose(2);
}
double min_foot_z = std::min(lfoot_pose(2),rfoot_pose(2));
double mean_foot_yaw = (lfoot_pose(5)+rfoot_pose(5))/2.0;
double pelvis_height_desired = pdata->alpha*pdata->pelvis_height_previous + (1.0-pdata->alpha)*(min_foot_z + pdata->nominal_pelvis_height);
pdata->pelvis_height_previous = pelvis_height_desired;
Vector6d body_des;
double nan = std::numeric_limits<double>::quiet_NaN();
body_des << nan,nan,pelvis_height_desired,0,0,mean_foot_yaw;
Vector6d error;
error.head<3>()= body_des.head<3>()-pelvis_pose.head<3>();
Vector3d error_rpy,pose_rpy,des_rpy;
pose_rpy = pelvis_pose.tail<3>();
des_rpy = body_des.tail<3>();
angleDiff(pose_rpy,des_rpy,error_rpy);
error.tail(3) = error_rpy;
Vector6d body_vdot = (pdata->Kp.array()*error.array()).matrix() - (pdata->Kd.array()*(Jpelvis*qdvec).array()).matrix();
plhs[0] = eigenToMatlab(body_vdot);
}<commit_msg>pelvis cpp controller uses angleAverage<commit_after>/*
* A simple pelvis motion control block for use with bipeds. Uses PD control to regulate the pelvis
* to a fixed height above the feet and drives the yaw to match the average foot yaw.
*
*/
#include "controlUtil.h"
struct PelvisMotionControlData {
RigidBodyManipulator* r;
double alpha;
double pelvis_height_previous;
double nominal_pelvis_height;
Vector6d Kp;
Vector6d Kd;
int pelvis_body_index;
int rfoot_body_index;
int lfoot_body_index;
};
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs<1) mexErrMsgTxt("usage: ptr = pelvisMotionControlmex(0,robot_obj,alpha,nominal_pelvis_height,Kp,Kd); y=pelvisMotionControlmex(ptr,x)");
if (nlhs<1) mexErrMsgTxt("take at least one output... please.");
struct PelvisMotionControlData* pdata;
if (mxGetScalar(prhs[0])==0) { // then construct the data object and return
pdata = new struct PelvisMotionControlData;
// get robot mex model ptr
if (!mxIsNumeric(prhs[1]) || mxGetNumberOfElements(prhs[1])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the second argument should be the robot mex ptr");
memcpy(&(pdata->r),mxGetData(prhs[1]),sizeof(pdata->r));
if (!mxIsNumeric(prhs[2]) || mxGetNumberOfElements(prhs[2])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the third argument should be alpha");
memcpy(&(pdata->alpha),mxGetPr(prhs[2]),sizeof(pdata->alpha));
if (!mxIsNumeric(prhs[3]) || mxGetNumberOfElements(prhs[3])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the fourth argument should be nominal_pelvis_height");
memcpy(&(pdata->nominal_pelvis_height),mxGetPr(prhs[3]),sizeof(pdata->nominal_pelvis_height));
if (!mxIsNumeric(prhs[4]) || mxGetM(prhs[4])!=6 || mxGetN(prhs[4])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the fifth argument should be Kp");
memcpy(&(pdata->Kp),mxGetPr(prhs[4]),sizeof(pdata->Kp));
if (!mxIsNumeric(prhs[5]) || mxGetM(prhs[5])!=6 || mxGetN(prhs[5])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the sixth argument should be Kd");
memcpy(&(pdata->Kd),mxGetPr(prhs[5]),sizeof(pdata->Kd));
mxClassID cid;
if (sizeof(pdata)==4) cid = mxUINT32_CLASS;
else if (sizeof(pdata)==8) cid = mxUINT64_CLASS;
else mexErrMsgIdAndTxt("Drake:pelvisMotionControlmex:PointerSize","Are you on a 32-bit machine or 64-bit machine??");
pdata->pelvis_height_previous = -1;
pdata->pelvis_body_index = pdata->r->findLinkInd("pelvis", 0);
pdata->rfoot_body_index = pdata->r->findLinkInd("r_foot", 0);
pdata->lfoot_body_index = pdata->r->findLinkInd("l_foot", 0);
plhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);
memcpy(mxGetData(plhs[0]),&pdata,sizeof(pdata));
return;
}
// first get the ptr back from matlab
if (!mxIsNumeric(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1)
mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the first argument should be the ptr");
memcpy(&pdata,mxGetData(prhs[0]),sizeof(pdata));
int nq = pdata->r->num_dof;
double *q = mxGetPr(prhs[1]);
double *qd = &q[nq];
Map<VectorXd> qdvec(qd,nq);
pdata->r->doKinematics(q,false,qd);
// TODO: this must be updated to use quaternions/spatial velocity
Vector6d pelvis_pose,rfoot_pose,lfoot_pose;
MatrixXd Jpelvis = MatrixXd::Zero(6,pdata->r->num_dof);
Vector4d zero = Vector4d::Zero();
zero(3) = 1.0;
pdata->r->forwardKin(pdata->pelvis_body_index,zero,1,pelvis_pose);
pdata->r->forwardJac(pdata->pelvis_body_index,zero,1,Jpelvis);
pdata->r->forwardKin(pdata->rfoot_body_index,zero,1,rfoot_pose);
pdata->r->forwardKin(pdata->lfoot_body_index,zero,1,lfoot_pose);
if (pdata->pelvis_height_previous<0) {
pdata->pelvis_height_previous = pelvis_pose(2);
}
double min_foot_z = std::min(lfoot_pose(2),rfoot_pose(2));
double mean_foot_yaw = angleAverage(lfoot_pose(5),rfoot_pose(5));
double pelvis_height_desired = pdata->alpha*pdata->pelvis_height_previous + (1.0-pdata->alpha)*(min_foot_z + pdata->nominal_pelvis_height);
pdata->pelvis_height_previous = pelvis_height_desired;
Vector6d body_des;
double nan = std::numeric_limits<double>::quiet_NaN();
body_des << nan,nan,pelvis_height_desired,0,0,mean_foot_yaw;
Vector6d error;
error.head<3>()= body_des.head<3>()-pelvis_pose.head<3>();
Vector3d error_rpy,pose_rpy,des_rpy;
pose_rpy = pelvis_pose.tail<3>();
des_rpy = body_des.tail<3>();
angleDiff(pose_rpy,des_rpy,error_rpy);
error.tail(3) = error_rpy;
Vector6d body_vdot = (pdata->Kp.array()*error.array()).matrix() - (pdata->Kd.array()*(Jpelvis*qdvec).array()).matrix();
plhs[0] = eigenToMatlab(body_vdot);
}<|endoftext|> |
<commit_before>#include <plugin.hpp>
#include <output.hpp>
#include <core.hpp>
#include <linux/input.h>
#include <linux/input-event-codes.h>
static bool begins_with(std::string word, std::string prefix)
{
if (word.length() < prefix.length())
return false;
return word.substr(0, prefix.length()) == prefix;
}
/* Initial repeat delay passed */
static int repeat_delay_timeout_handler(void *callback)
{
(*reinterpret_cast<std::function<void()>*> (callback)) ();
return 1; // disconnect
};
/* Between each repeat */
static int repeat_once_handler(void *callback)
{
(*reinterpret_cast<std::function<void()>*> (callback)) ();
return 1; // continue timer
}
/* Provides a way to bind specific commands to activator bindings.
*
* It supports 2 modes:
*
* 1. Regular bindings
* 2. Repeatable bindings - for example, if the user binds a keybinding, then
* after a specific delay the command begins to be executed repeatedly, until
* the user released the key. In the config file, repeatable bindings have the
* prefix repeatable_
* 3. Always bindings - bindings that can be executed even if a plugin is already
* active, or if the screen is locked. They have a prefix always_
* */
class wayfire_command : public wf::plugin_interface_t
{
std::vector<activator_callback> bindings;
struct
{
uint32_t pressed_button = 0;
uint32_t pressed_key = 0;
std::string repeat_command;
} repeat;
wl_event_source *repeat_source = NULL, *repeat_delay_source = NULL;
enum binding_mode {
BINDING_NORMAL,
BINDING_REPEAT,
BINDING_ALWAYS,
};
void on_binding(std::string command, binding_mode mode, wf_activator_source source,
uint32_t value)
{
/* We already have a repeatable command, do not accept further bindings */
if (repeat.pressed_key || repeat.pressed_button)
return;
if (!output->activate_plugin(grab_interface, mode == BINDING_ALWAYS))
return;
wf::get_core().run(command.c_str());
/* No repeat necessary in any of those cases */
if (mode != BINDING_REPEAT || source == ACTIVATOR_SOURCE_GESTURE ||
value == 0)
{
output->deactivate_plugin(grab_interface);
return;
}
/* Grab if grab wasn't active up to now */
if (!grab_interface->is_grabbed())
grab_interface->grab();
repeat.repeat_command = command;
if (source == ACTIVATOR_SOURCE_KEYBINDING) {
repeat.pressed_key = value;
} else {
repeat.pressed_button = value;
}
repeat_delay_source = wl_event_loop_add_timer(wf::get_core().ev_loop,
repeat_delay_timeout_handler, &on_repeat_delay_timeout);
wl_event_source_timer_update(repeat_delay_source,
wf::get_core().config->get_section("input")
->get_option("kb_repeat_delay", "400")->as_int());
}
std::function<void()> on_repeat_delay_timeout = [=] ()
{
repeat_delay_source = NULL;
repeat_source = wl_event_loop_add_timer(wf::get_core().ev_loop,
repeat_once_handler, &on_repeat_once);
on_repeat_once();
};
std::function<void()> on_repeat_once = [=] ()
{
uint32_t repeat_rate = wf::get_core().config->get_section("input")
->get_option("kb_repeat_rate", "40")->as_int();
if (repeat_rate <= 0 || repeat_rate > 1000)
return reset_repeat();
wl_event_source_timer_update(repeat_source, 1000 / repeat_rate);
wf::get_core().run(repeat.repeat_command.c_str());
};
void reset_repeat()
{
if (repeat_delay_source)
{
wl_event_source_remove(repeat_delay_source);
repeat_delay_source = NULL;
}
if (repeat_source)
{
wl_event_source_remove(repeat_source);
repeat_source = NULL;
}
repeat.pressed_key = repeat.pressed_button = 0;
grab_interface->ungrab();
output->deactivate_plugin(grab_interface);
}
std::function<void(uint32_t, uint32_t)> on_button =
[=] (uint32_t button, uint32_t state)
{
if (button == repeat.pressed_button && state == WLR_BUTTON_RELEASED)
reset_repeat();
};
std::function<void(uint32_t, uint32_t)> on_key =
[=] (uint32_t key, uint32_t state)
{
if (key == repeat.pressed_key && state == WLR_KEY_RELEASED)
reset_repeat();
};
public:
void setup_bindings_from_config(wayfire_config *config)
{
auto section = config->get_section("command");
std::vector<std::string> command_names;
const std::string exec_prefix = "command_";
for (auto command : section->options)
{
if (begins_with(command->name, exec_prefix))
{
command_names.push_back(
command->name.substr(exec_prefix.length()));
}
}
bindings.resize(command_names.size());
const std::string norepeat = "...norepeat...";
const std::string noalways = "...noalways...";
for (size_t i = 0; i < command_names.size(); i++)
{
auto command = exec_prefix + command_names[i];
auto regular_binding_name = "binding_" + command_names[i];
auto repeat_binding_name = "repeatable_binding_" + command_names[i];
auto always_binding_name = "always_binding_" + command_names[i];
auto executable = section->get_option(command, "")->as_string();
auto repeatable_opt = section->get_option(repeat_binding_name, norepeat);
auto regular_opt = section->get_option(regular_binding_name, "none");
auto always_opt = section->get_option(always_binding_name, noalways);
using namespace std::placeholders;
if (repeatable_opt->as_string() != norepeat)
{
bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding),
this, executable, BINDING_REPEAT, _1, _2);
output->add_activator(repeatable_opt, &bindings[i]);
}
else if (always_opt->as_string() != noalways)
{
bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding),
this, executable, BINDING_ALWAYS, _1, _2);
output->add_activator(always_opt, &bindings[i]);
}
else
{
bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding),
this, executable, BINDING_NORMAL, _1, _2);
output->add_activator(regular_opt, &bindings[i]);
}
}
}
void clear_bindings()
{
for (auto& binding : bindings)
output->rem_binding(&binding);
bindings.clear();
}
wf::signal_callback_t reload_config;
void init(wayfire_config *config)
{
grab_interface->name = "command";
grab_interface->capabilities = wf::CAPABILITY_GRAB_INPUT;
grab_interface->callbacks.pointer.button = on_button;
grab_interface->callbacks.keyboard.key = on_key;
grab_interface->callbacks.cancel = [=]() {reset_repeat();};
using namespace std::placeholders;
setup_bindings_from_config(config);
reload_config = [=] (wf::signal_data_t*)
{
clear_bindings();
setup_bindings_from_config(wf::get_core().config);
};
wf::get_core().connect_signal("reload-config", &reload_config);
}
void fini()
{
wf::get_core().disconnect_signal("reload-config", &reload_config);
clear_bindings();
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_command);
<commit_msg>command: use raw events instead of grabbing input<commit_after>#include <plugin.hpp>
#include <output.hpp>
#include <core.hpp>
#include <linux/input.h>
#include <linux/input-event-codes.h>
#include <signal-definitions.hpp>
static bool begins_with(std::string word, std::string prefix)
{
if (word.length() < prefix.length())
return false;
return word.substr(0, prefix.length()) == prefix;
}
/* Initial repeat delay passed */
static int repeat_delay_timeout_handler(void *callback)
{
(*reinterpret_cast<std::function<void()>*> (callback)) ();
return 1; // disconnect
};
/* Between each repeat */
static int repeat_once_handler(void *callback)
{
(*reinterpret_cast<std::function<void()>*> (callback)) ();
return 1; // continue timer
}
/* Provides a way to bind specific commands to activator bindings.
*
* It supports 2 modes:
*
* 1. Regular bindings
* 2. Repeatable bindings - for example, if the user binds a keybinding, then
* after a specific delay the command begins to be executed repeatedly, until
* the user released the key. In the config file, repeatable bindings have the
* prefix repeatable_
* 3. Always bindings - bindings that can be executed even if a plugin is already
* active, or if the screen is locked. They have a prefix always_
* */
class wayfire_command : public wf::plugin_interface_t
{
std::vector<activator_callback> bindings;
struct
{
uint32_t pressed_button = 0;
uint32_t pressed_key = 0;
std::string repeat_command;
} repeat;
wl_event_source *repeat_source = NULL, *repeat_delay_source = NULL;
enum binding_mode {
BINDING_NORMAL,
BINDING_REPEAT,
BINDING_ALWAYS,
};
void on_binding(std::string command, binding_mode mode, wf_activator_source source,
uint32_t value)
{
/* We already have a repeatable command, do not accept further bindings */
if (repeat.pressed_key || repeat.pressed_button)
return;
if (!output->activate_plugin(grab_interface, mode == BINDING_ALWAYS))
return;
wf::get_core().run(command.c_str());
/* No repeat necessary in any of those cases */
if (mode != BINDING_REPEAT || source == ACTIVATOR_SOURCE_GESTURE ||
value == 0)
{
output->deactivate_plugin(grab_interface);
return;
}
repeat.repeat_command = command;
if (source == ACTIVATOR_SOURCE_KEYBINDING) {
repeat.pressed_key = value;
} else {
repeat.pressed_button = value;
}
repeat_delay_source = wl_event_loop_add_timer(wf::get_core().ev_loop,
repeat_delay_timeout_handler, &on_repeat_delay_timeout);
wl_event_source_timer_update(repeat_delay_source,
wf::get_core().config->get_section("input")
->get_option("kb_repeat_delay", "400")->as_int());
wf::get_core().connect_signal("pointer_button", &on_button_event);
wf::get_core().connect_signal("keyboard_key", &on_key_event);
}
std::function<void()> on_repeat_delay_timeout = [=] ()
{
repeat_delay_source = NULL;
repeat_source = wl_event_loop_add_timer(wf::get_core().ev_loop,
repeat_once_handler, &on_repeat_once);
on_repeat_once();
};
std::function<void()> on_repeat_once = [=] ()
{
uint32_t repeat_rate = wf::get_core().config->get_section("input")
->get_option("kb_repeat_rate", "40")->as_int();
if (repeat_rate <= 0 || repeat_rate > 1000)
return reset_repeat();
wl_event_source_timer_update(repeat_source, 1000 / repeat_rate);
wf::get_core().run(repeat.repeat_command.c_str());
};
void reset_repeat()
{
if (repeat_delay_source)
{
wl_event_source_remove(repeat_delay_source);
repeat_delay_source = NULL;
}
if (repeat_source)
{
wl_event_source_remove(repeat_source);
repeat_source = NULL;
}
repeat.pressed_key = repeat.pressed_button = 0;
output->deactivate_plugin(grab_interface);
wf::get_core().disconnect_signal("pointer_button", &on_button_event);
wf::get_core().disconnect_signal("keyboard_key", &on_key_event);
}
wf::signal_callback_t on_button_event = [=] (wf::signal_data_t *data)
{
auto ev = static_cast<
wf::input_event_signal<wlr_event_pointer_button>*>(data);
if (ev->event->button == repeat.pressed_button &&
ev->event->state == WLR_BUTTON_RELEASED)
{
reset_repeat();
}
};
wf::signal_callback_t on_key_event = [=] (wf::signal_data_t *data)
{
auto ev = static_cast<
wf::input_event_signal<wlr_event_keyboard_key>*>(data);
if (ev->event->keycode == repeat.pressed_key &&
ev->event->state == WLR_KEY_RELEASED)
{
reset_repeat();
}
};
public:
void setup_bindings_from_config(wayfire_config *config)
{
auto section = config->get_section("command");
std::vector<std::string> command_names;
const std::string exec_prefix = "command_";
for (auto command : section->options)
{
if (begins_with(command->name, exec_prefix))
{
command_names.push_back(
command->name.substr(exec_prefix.length()));
}
}
bindings.resize(command_names.size());
const std::string norepeat = "...norepeat...";
const std::string noalways = "...noalways...";
for (size_t i = 0; i < command_names.size(); i++)
{
auto command = exec_prefix + command_names[i];
auto regular_binding_name = "binding_" + command_names[i];
auto repeat_binding_name = "repeatable_binding_" + command_names[i];
auto always_binding_name = "always_binding_" + command_names[i];
auto executable = section->get_option(command, "")->as_string();
auto repeatable_opt = section->get_option(repeat_binding_name, norepeat);
auto regular_opt = section->get_option(regular_binding_name, "none");
auto always_opt = section->get_option(always_binding_name, noalways);
using namespace std::placeholders;
if (repeatable_opt->as_string() != norepeat)
{
bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding),
this, executable, BINDING_REPEAT, _1, _2);
output->add_activator(repeatable_opt, &bindings[i]);
}
else if (always_opt->as_string() != noalways)
{
bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding),
this, executable, BINDING_ALWAYS, _1, _2);
output->add_activator(always_opt, &bindings[i]);
}
else
{
bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding),
this, executable, BINDING_NORMAL, _1, _2);
output->add_activator(regular_opt, &bindings[i]);
}
}
}
void clear_bindings()
{
for (auto& binding : bindings)
output->rem_binding(&binding);
bindings.clear();
}
wf::signal_callback_t reload_config;
void init(wayfire_config *config)
{
grab_interface->name = "command";
grab_interface->capabilities = wf::CAPABILITY_GRAB_INPUT;
using namespace std::placeholders;
setup_bindings_from_config(config);
reload_config = [=] (wf::signal_data_t*)
{
clear_bindings();
setup_bindings_from_config(wf::get_core().config);
};
wf::get_core().connect_signal("reload-config", &reload_config);
}
void fini()
{
wf::get_core().disconnect_signal("reload-config", &reload_config);
clear_bindings();
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_command);
<|endoftext|> |
<commit_before>#include <plugin.hpp>
#include <output.hpp>
#include <opengl.hpp>
#include <debug.hpp>
#include <animation.hpp>
#include <render-manager.hpp>
static const char* vertex_shader =
R"(
#version 100
attribute mediump vec2 position;
void main() {
gl_Position = vec4(position.xy, 0.0, 1.0);
}
)";
static const char* fragment_shader =
R"(
#version 100
precision mediump float;
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_radius;
uniform float u_zoom;
uniform sampler2D u_texture;
const float PI = 3.1415926535;
void main()
{
float radius = u_radius;
float zoom = u_zoom;
float pw = 1.0 / u_resolution.x;
float ph = 1.0 / u_resolution.y;
vec4 p0 = vec4(u_mouse.x, u_resolution.y - u_mouse.y, 1.0 / radius, 0.0);
vec4 p1 = vec4(pw, ph, PI / radius, (zoom - 1.0) * zoom);
vec4 p2 = vec4(0, 0, -PI / 2.0, 0.0);
vec4 t0, t1, t2, t3;
vec3 tc = vec3(1.0, 0.0, 0.0);
vec2 uv = vec2(gl_FragCoord.x, gl_FragCoord.y);
t1 = p0.xyww - vec4(uv, 0.0, 0.0);
t2.x = t2.y = t2.z = t2.w = 1.0 / sqrt(dot(t1.xyz, t1.xyz));
t0 = t2 - p0;
t3.x = t3.y = t3.z = t3.w = 1.0 / t2.x;
t3 = t3 * p1.z + p2.z;
t3.x = t3.y = t3.z = t3.w = cos(t3.x);
t3 = t3 * p1.w;
t1 = t2 * t1;
t1 = t1 * t3 + vec4(uv, 0.0, 0.0);
if (t0.z < 0.0) {
t1.x = uv.x;
t1.y = uv.y;
}
t1 = t1 * p1 + p2;
tc = texture2D(u_texture, t1.xy).rgb;
gl_FragColor = vec4(tc, 1.0);
}
)";
class wayfire_fisheye : public wayfire_plugin_t
{
post_hook_t hook;
key_callback toggle_cb;
wf_duration duration;
float target_zoom;
bool active, hook_set;
wf_option radius, zoom;
GLuint program, posID, mouseID, resID, radiusID, zoomID;
public:
void init(wayfire_config *config)
{
auto section = config->get_section("fisheye");
auto toggle_key = section->get_option("toggle", "<super> KEY_F");
radius = section->get_option("radius", "300");
zoom = section->get_option("zoom", "7");
if (!toggle_key->as_key().valid())
return;
target_zoom = zoom->as_double();
hook = [=] (uint32_t fb, uint32_t tex, uint32_t target)
{
render(fb, tex, target);
};
toggle_cb = [=] (uint32_t key)
{
if (active)
{
active = false;
duration.start(duration.progress(), 0);
} else
{
active = true;
duration.start(duration.progress(), target_zoom);
if (!hook_set)
{
hook_set = true;
output->render->add_post(&hook);
}
}
};
auto vs = OpenGL::compile_shader(vertex_shader, GL_VERTEX_SHADER);
auto fs = OpenGL::compile_shader(fragment_shader, GL_FRAGMENT_SHADER);
program = GL_CALL(glCreateProgram());
GL_CALL(glAttachShader(program, vs));
GL_CALL(glAttachShader(program, fs));
GL_CALL(glLinkProgram(program));
posID = GL_CALL(glGetAttribLocation(program, "position"));
mouseID = GL_CALL(glGetUniformLocation(program, "u_mouse"));
resID = GL_CALL(glGetUniformLocation(program, "u_resolution"));
radiusID = GL_CALL(glGetUniformLocation(program, "u_radius"));
zoomID = GL_CALL(glGetUniformLocation(program, "u_zoom"));
duration = wf_duration(new_static_option("700"));
duration.start(0, 0); // so that the first value we get is correct
output->add_key(toggle_key, &toggle_cb);
}
void render(uint32_t fb, uint32_t tex, uint32_t target)
{
GetTuple(x, y, output->get_cursor_position());
GL_CALL(glUseProgram(program));
GL_CALL(glBindTexture(GL_TEXTURE_2D, tex));
GL_CALL(glActiveTexture(GL_TEXTURE0));
static const float vertexData[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
auto current_zoom = duration.progress();
target_zoom = zoom->as_double();
glUniform2f(mouseID, x, y);
glUniform2f(resID, output->handle->width, output->handle->height);
glUniform1f(radiusID, radius->as_double());
glUniform1f(zoomID, current_zoom);
GL_CALL(glVertexAttribPointer(posID, 2, GL_FLOAT, GL_FALSE, 0, vertexData));
GL_CALL(glEnableVertexAttribArray(posID));
GL_CALL(glDisable(GL_BLEND));
GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target));
GL_CALL(glDrawArrays (GL_TRIANGLE_FAN, 0, 4));
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0));
GL_CALL(glDisableVertexAttribArray(posID));
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
if (active)
{
/* Reset animation in case target_zoom
* was changed via config */
duration.start(current_zoom, target_zoom);
} else if (!duration.running())
{
output->render->rem_post(&hook);
hook_set = false;
}
}
};
extern "C"
{
wayfire_plugin_t *newInstance()
{
return new wayfire_fisheye();
}
}
<commit_msg>fisheye: Add copyright header<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Scott Moreau
*
* 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 <plugin.hpp>
#include <output.hpp>
#include <opengl.hpp>
#include <debug.hpp>
#include <animation.hpp>
#include <render-manager.hpp>
static const char* vertex_shader =
R"(
#version 100
attribute mediump vec2 position;
void main() {
gl_Position = vec4(position.xy, 0.0, 1.0);
}
)";
static const char* fragment_shader =
R"(
#version 100
precision mediump float;
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_radius;
uniform float u_zoom;
uniform sampler2D u_texture;
const float PI = 3.1415926535;
void main()
{
float radius = u_radius;
float zoom = u_zoom;
float pw = 1.0 / u_resolution.x;
float ph = 1.0 / u_resolution.y;
vec4 p0 = vec4(u_mouse.x, u_resolution.y - u_mouse.y, 1.0 / radius, 0.0);
vec4 p1 = vec4(pw, ph, PI / radius, (zoom - 1.0) * zoom);
vec4 p2 = vec4(0, 0, -PI / 2.0, 0.0);
vec4 t0, t1, t2, t3;
vec3 tc = vec3(1.0, 0.0, 0.0);
vec2 uv = vec2(gl_FragCoord.x, gl_FragCoord.y);
t1 = p0.xyww - vec4(uv, 0.0, 0.0);
t2.x = t2.y = t2.z = t2.w = 1.0 / sqrt(dot(t1.xyz, t1.xyz));
t0 = t2 - p0;
t3.x = t3.y = t3.z = t3.w = 1.0 / t2.x;
t3 = t3 * p1.z + p2.z;
t3.x = t3.y = t3.z = t3.w = cos(t3.x);
t3 = t3 * p1.w;
t1 = t2 * t1;
t1 = t1 * t3 + vec4(uv, 0.0, 0.0);
if (t0.z < 0.0) {
t1.x = uv.x;
t1.y = uv.y;
}
t1 = t1 * p1 + p2;
tc = texture2D(u_texture, t1.xy).rgb;
gl_FragColor = vec4(tc, 1.0);
}
)";
class wayfire_fisheye : public wayfire_plugin_t
{
post_hook_t hook;
key_callback toggle_cb;
wf_duration duration;
float target_zoom;
bool active, hook_set;
wf_option radius, zoom;
GLuint program, posID, mouseID, resID, radiusID, zoomID;
public:
void init(wayfire_config *config)
{
auto section = config->get_section("fisheye");
auto toggle_key = section->get_option("toggle", "<super> KEY_F");
radius = section->get_option("radius", "300");
zoom = section->get_option("zoom", "7");
if (!toggle_key->as_key().valid())
return;
target_zoom = zoom->as_double();
hook = [=] (uint32_t fb, uint32_t tex, uint32_t target)
{
render(fb, tex, target);
};
toggle_cb = [=] (uint32_t key)
{
if (active)
{
active = false;
duration.start(duration.progress(), 0);
} else
{
active = true;
duration.start(duration.progress(), target_zoom);
if (!hook_set)
{
hook_set = true;
output->render->add_post(&hook);
}
}
};
auto vs = OpenGL::compile_shader(vertex_shader, GL_VERTEX_SHADER);
auto fs = OpenGL::compile_shader(fragment_shader, GL_FRAGMENT_SHADER);
program = GL_CALL(glCreateProgram());
GL_CALL(glAttachShader(program, vs));
GL_CALL(glAttachShader(program, fs));
GL_CALL(glLinkProgram(program));
posID = GL_CALL(glGetAttribLocation(program, "position"));
mouseID = GL_CALL(glGetUniformLocation(program, "u_mouse"));
resID = GL_CALL(glGetUniformLocation(program, "u_resolution"));
radiusID = GL_CALL(glGetUniformLocation(program, "u_radius"));
zoomID = GL_CALL(glGetUniformLocation(program, "u_zoom"));
duration = wf_duration(new_static_option("700"));
duration.start(0, 0); // so that the first value we get is correct
output->add_key(toggle_key, &toggle_cb);
}
void render(uint32_t fb, uint32_t tex, uint32_t target)
{
GetTuple(x, y, output->get_cursor_position());
GL_CALL(glUseProgram(program));
GL_CALL(glBindTexture(GL_TEXTURE_2D, tex));
GL_CALL(glActiveTexture(GL_TEXTURE0));
static const float vertexData[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
auto current_zoom = duration.progress();
target_zoom = zoom->as_double();
glUniform2f(mouseID, x, y);
glUniform2f(resID, output->handle->width, output->handle->height);
glUniform1f(radiusID, radius->as_double());
glUniform1f(zoomID, current_zoom);
GL_CALL(glVertexAttribPointer(posID, 2, GL_FLOAT, GL_FALSE, 0, vertexData));
GL_CALL(glEnableVertexAttribArray(posID));
GL_CALL(glDisable(GL_BLEND));
GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target));
GL_CALL(glDrawArrays (GL_TRIANGLE_FAN, 0, 4));
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0));
GL_CALL(glDisableVertexAttribArray(posID));
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
if (active)
{
/* Reset animation in case target_zoom
* was changed via config */
duration.start(current_zoom, target_zoom);
} else if (!duration.running())
{
output->render->rem_post(&hook);
hook_set = false;
}
}
};
extern "C"
{
wayfire_plugin_t *newInstance()
{
return new wayfire_fisheye();
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************/
/* Bela Csound Rendering functions */
/* */
/*******************************************************************************/
#include <Bela.h>
#include <Midi.h>
#include <csound/csound.hpp>
#include <vector>
#include <sstream>
#define ANCHNS 8
static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
int nbytes);
struct CsChan {
std::vector<MYFLT> data;
std::stringstream name;
};
struct CsData {
Csound *csound;
int blocksize;
int res;
int count;
CsChan channel[ANCHNS];
};
CsData gCsData;
bool setup(BelaContext *context, void *Data)
{
Csound *csound;
const char *csdfile = "my.csd"; /* CSD name */
const char *midiDev = "-Mhw:1,0,0"; /* MIDI device */
const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
"--realtime", "--daemon", midiDev };
int numArgs = (int) (sizeof(args)/sizeof(char *));
if(context->audioInChannels != context->audioOutChannels) {
printf("Number of audio inputs != number of audio outputs.\n");
return false;
}
/* setup Csound */
csound = new Csound();
csound->SetHostImplementedAudioIO(1,0);
csound->SetHostImplementedMIDIIO(1);
csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
csound->SetExternalMidiReadCallback(ReadMidiData);
csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
gCsData.csound = csound;
gCsData.res = csound->Compile(numArgs, args);
gCsData.blocksize = csound->GetKsmps()*csound->GetNchnls();
gCsData.count = 0;
/* set up the channels */
for(int i; i < ANCHNS; i++) {
gCsData.channel[i].data.resize(csound->GetKsmps());
gCsData.channel[i].name << "analogue" << i+1;
}
if(gCsData.res != 0) return false;
else return true;
}
void render(BelaContext *context, void *Data)
{
if(gCsData.res == 0) {
int n,i,k,count, frmcount,blocksize,res;
Csound *csound = gCsData.csound;
MYFLT scal = csound->Get0dBFS();
MYFLT* audioIn = csound->GetSpin();
MYFLT* audioOut = csound->GetSpout();
int nchnls = csound->GetNchnls();
int chns = nchnls < context->audioOutChannels ?
nchnls : context->audioOutChannels;
int an_chns = context->analogInChannels > ANCHNS ?
ANCHNS : context->analogInChannels;
CsChan *channel = &(gCsData.channel[0]);
float frm = 0, incr = ((float) context->analogFrames)/context->audioFrames;
int an_chans = context->analogInChannels;
count = gCsData.count;
blocksize = gCsData.blocksize;
/* this is called when Csound is not running */
if(count < 0) {
for(n = 0; n < context->audioFrames; n++){
for(i = 0; i < context->audioOutChannels; i++){
audioWrite(context,n,i,0);
}
}
return;
}
/* this is where Csound is called */
for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
if(count == blocksize) {
/* set the channels */
for(i = 0; i < an_chns; i++) {
csound->SetChannel(channel[i].name.str().c_str(),
&(channel[i].data[0]));
}
/* run csound */
if((res = csound->PerformKsmps()) == 0) count = 0;
else {
count = -1;
break;
}
}
/* read/write audio data */
for(i = 0; i < chns; i++){
audioIn[count+i] = audioRead(context,n,i);
audioWrite(context,n,i,audioOut[count+i]/scal);
}
/* read analogue data
analogue frame pos gets incremented according to the
ratio analogFrames/audioFrames.
*/
frmcount = count/nchnls;
for(i = 0; i < an_chns; i++) {
k = (int) frm;
channel[i].data[frmcount] = analogRead(context,k,i);
}
}
gCsData.res = res;
gCsData.count = count;
}
}
void cleanup(BelaContext *context, void *Data)
{
delete gCsData.csound;
}
/** MIDI Input functions
*/
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
Midi *midi = new Midi;
midi->readFrom(dev);
midi->enableParser(false);
*userData = (void *) midi;
}
int CloseMidiInDevice(CSOUND *csound, void *userData) {
delete (Midi *) userData;
}
int ReadMidiData(CSOUND *csound, void *userData,
unsigned char *mbuf, int nbytes) {
int n = 0;
Midi midi = (Midi *) userData;
while((byte = midi->getInput()) >= 0) {
*mbuf++ = (unsigned char) byte;
if(++n == nbytes) break;
}
return n;
}
<commit_msg>marking as static<commit_after>/*******************************************************************************/
/* Bela Csound Rendering functions */
/* */
/*******************************************************************************/
#include <Bela.h>
#include <Midi.h>
#include <csound/csound.hpp>
#include <vector>
#include <sstream>
#define ANCHNS 8
static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
int nbytes);
struct CsChan {
std::vector<MYFLT> data;
std::stringstream name;
};
struct CsData {
Csound *csound;
int blocksize;
int res;
int count;
CsChan channel[ANCHNS];
};
static CsData gCsData;
bool setup(BelaContext *context, void *Data)
{
Csound *csound;
const char *csdfile = "my.csd"; /* CSD name */
const char *midiDev = "-Mhw:1,0,0"; /* MIDI device */
const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
"--realtime", "--daemon", midiDev };
int numArgs = (int) (sizeof(args)/sizeof(char *));
if(context->audioInChannels != context->audioOutChannels) {
printf("Number of audio inputs != number of audio outputs.\n");
return false;
}
/* setup Csound */
csound = new Csound();
csound->SetHostImplementedAudioIO(1,0);
csound->SetHostImplementedMIDIIO(1);
csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
csound->SetExternalMidiReadCallback(ReadMidiData);
csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
gCsData.csound = csound;
gCsData.res = csound->Compile(numArgs, args);
gCsData.blocksize = csound->GetKsmps()*csound->GetNchnls();
gCsData.count = 0;
/* set up the channels */
for(int i; i < ANCHNS; i++) {
gCsData.channel[i].data.resize(csound->GetKsmps());
gCsData.channel[i].name << "analogue" << i+1;
}
if(gCsData.res != 0) return false;
else return true;
}
void render(BelaContext *context, void *Data)
{
if(gCsData.res == 0) {
int n,i,k,count, frmcount,blocksize,res;
Csound *csound = gCsData.csound;
MYFLT scal = csound->Get0dBFS();
MYFLT* audioIn = csound->GetSpin();
MYFLT* audioOut = csound->GetSpout();
int nchnls = csound->GetNchnls();
int chns = nchnls < context->audioOutChannels ?
nchnls : context->audioOutChannels;
int an_chns = context->analogInChannels > ANCHNS ?
ANCHNS : context->analogInChannels;
CsChan *channel = &(gCsData.channel[0]);
float frm = 0, incr = ((float) context->analogFrames)/context->audioFrames;
int an_chans = context->analogInChannels;
count = gCsData.count;
blocksize = gCsData.blocksize;
/* this is called when Csound is not running */
if(count < 0) {
for(n = 0; n < context->audioFrames; n++){
for(i = 0; i < context->audioOutChannels; i++){
audioWrite(context,n,i,0);
}
}
return;
}
/* this is where Csound is called */
for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
if(count == blocksize) {
/* set the channels */
for(i = 0; i < an_chns; i++) {
csound->SetChannel(channel[i].name.str().c_str(),
&(channel[i].data[0]));
}
/* run csound */
if((res = csound->PerformKsmps()) == 0) count = 0;
else {
count = -1;
break;
}
}
/* read/write audio data */
for(i = 0; i < chns; i++){
audioIn[count+i] = audioRead(context,n,i);
audioWrite(context,n,i,audioOut[count+i]/scal);
}
/* read analogue data
analogue frame pos gets incremented according to the
ratio analogFrames/audioFrames.
*/
frmcount = count/nchnls;
for(i = 0; i < an_chns; i++) {
k = (int) frm;
channel[i].data[frmcount] = analogRead(context,k,i);
}
}
gCsData.res = res;
gCsData.count = count;
}
}
void cleanup(BelaContext *context, void *Data)
{
delete gCsData.csound;
}
/** MIDI Input functions
*/
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
Midi *midi = new Midi;
midi->readFrom(dev);
midi->enableParser(false);
*userData = (void *) midi;
}
int CloseMidiInDevice(CSOUND *csound, void *userData) {
delete (Midi *) userData;
}
int ReadMidiData(CSOUND *csound, void *userData,
unsigned char *mbuf, int nbytes) {
int n = 0;
Midi midi = (Midi *) userData;
while((byte = midi->getInput()) >= 0) {
*mbuf++ = (unsigned char) byte;
if(++n == nbytes) break;
}
return n;
}
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/contrib/repeat/kernels/repeat_op.h"
namespace tensorflow{
typedef Eigen::ThreadPoolDevice CPUDevice;
#if GOOGLE_CUDA
typedef Eigen::GpuDevice GPUDevice;
#endif // GOOGLE_CUDA
template <typename Device, typename T>
class RepeatOp : public OpKernel {
public:
explicit RepeatOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("axis", &axis_));
}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
const Tensor& repeats = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsVector(repeats.shape()) ||
TensorShapeUtils::IsScalar(repeats.shape()),
errors::InvalidArgument("`repeats` expects a scalar or a 1-D vector."));
OP_REQUIRES(context, repeats.NumElements() == input.dim_size(axis_) ||
repeats.NumElements() == 1,
errors::InvalidArgument(
"Expected `repeats` argument to be a vector of length ",
input.dim_size(axis_), " or 1, but got length ",
repeats.NumElements()));
OP_REQUIRES(context, FastBoundsCheck(axis_, input.dims()),
errors::InvalidArgument("Expected 0 <= `axis` < ", input.dims()));
TensorShape output_shape = input.shape();
auto repeats_flat = repeats.flat<int32>();
const int old_dim = input.shape().dim_size(axis_);
int new_dim = 0;
if (repeats.NumElements() == 1) {
new_dim = repeats_flat(0) * old_dim;
} else {
const int N = repeats_flat.size();
for (int i = 0; i < N; ++i) {
new_dim += repeats_flat(i);
}
}
output_shape.set_dim(axis_, new_dim);
Tensor* output = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
#if GOOGLE_CUDA
if (std::is_same<Device, GPUDevice>::value) {
RepeatGPUImpl<T>(context->eigen_gpu_device(), input, repeats_flat, axis_, output);
return ;
}
#endif // GOOGLE_CUDA
RepeatCPUImplV2<T>(context->device(), input, repeats_flat,
axis_, 10000, output);
}
private:
int32 axis_;
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Repeat") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T"), \
RepeatOp<CPUDevice, type>)
TF_CALL_ALL_TYPES(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#if GOOGLE_CUDA
#define REGISTER_KERNEL_GPU(type) \
REGISTER_KERNEL_BUILDER( \
Name("Repeat") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.HostMemory("repeats"), \
RepeatOp<GPUDevice, type>)
TF_CALL_GPU_NUMBER_TYPES(REGISTER_KERNEL_GPU);
#undef REGISTER_KERNEL_GPU
#endif // GOOGLE_CUDA
} //end namespace tensorflow
<commit_msg>Add support for scalar input and negative axis<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/contrib/repeat/kernels/repeat_op.h"
namespace tensorflow{
typedef Eigen::ThreadPoolDevice CPUDevice;
#if GOOGLE_CUDA
typedef Eigen::GpuDevice GPUDevice;
#endif // GOOGLE_CUDA
template <typename Device, typename T>
class RepeatOp : public OpKernel {
public:
explicit RepeatOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("axis", &axis_));
}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
const Tensor& repeats = context->input(1);
const int input_rank = input.dims()==0 ? 1 : input.dims();
const int32 axis = axis_>=0 ? axis_ : axis_+input_rank;
OP_REQUIRES(context, TensorShapeUtils::IsVector(repeats.shape()) ||
TensorShapeUtils::IsScalar(repeats.shape()),
errors::InvalidArgument("`repeats` expects a scalar or a 1-D vector."));
OP_REQUIRES(context, FastBoundsCheck(axis, input_rank),
errors::InvalidArgument(
"Expected -", input_rank, " <= `axis` < ", input_rank));
OP_REQUIRES(context, repeats.NumElements() == input.dim_size(axis) ||
repeats.NumElements() == 1,
errors::InvalidArgument(
"Expected `repeats` argument to be a vector of length ",
input.dim_size(axis_), " or 1, but got length ",
repeats.NumElements()));
auto repeats_flat = repeats.flat<int32>();
TensorShape output_shape({1});
int old_dim;
if (input.dims() != 0) {
output_shape = input.shape();
old_dim = input.shape().dim_size(axis);
} else {
old_dim = 1;
}
int new_dim = 0;
if (repeats.NumElements() == 1) {
new_dim = repeats_flat(0) * old_dim;
} else {
const int N = repeats_flat.size();
for (int i = 0; i < N; ++i) {
new_dim += repeats_flat(i);
}
}
output_shape.set_dim(axis, new_dim);
Tensor* output = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
#if GOOGLE_CUDA
if (std::is_same<Device, GPUDevice>::value) {
RepeatGPUImpl<T>(context->eigen_gpu_device(), input, repeats_flat, axis, output);
return ;
}
#endif // GOOGLE_CUDA
RepeatCPUImplV2<T>(context->device(), input, repeats_flat,
axis, 10000, output);
}
private:
int32 axis_;
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Repeat") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T"), \
RepeatOp<CPUDevice, type>)
TF_CALL_ALL_TYPES(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#if GOOGLE_CUDA
#define REGISTER_KERNEL_GPU(type) \
REGISTER_KERNEL_BUILDER( \
Name("Repeat") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.HostMemory("repeats"), \
RepeatOp<GPUDevice, type>)
TF_CALL_GPU_NUMBER_TYPES(REGISTER_KERNEL_GPU);
#undef REGISTER_KERNEL_GPU
#endif // GOOGLE_CUDA
} //end namespace tensorflow
<|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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
//#define MAIN
#include "otbImage.h"
#include "itkVectorImage.h"
#include "itkExceptionObject.h"
#include <iostream>
#include "itkComplexToModulusImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiChannelExtractROI.h"
int otbImageFileReaderERS(int argc, char* argv[])
{
try
{
// Verify the number of parameters in the command line
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
typedef float InputPixelType;
typedef unsigned short OutputPixelType;
const unsigned int Dimension = 2;
typedef otb::VectorImage< InputPixelType, Dimension > InputImageType;
typedef otb::VectorImage< OutputPixelType, Dimension > OutputImageType;
typedef otb::ImageFileReader< InputImageType > ReaderType;
typedef otb::ImageFileWriter< OutputImageType > WriterType;
typedef itk::StreamingImageFilter< InputImageType, OutputImageType > StreamingType;
StreamingType::Pointer streaming = StreamingType::New();
ReaderType::Pointer complexReader = ReaderType::New();
complexReader->SetFileName( inputFilename );
streaming->SetNumberOfStreamDivisions(100);
streaming->SetInput(complexReader->GetOutput());
typedef otb::MultiChannelExtractROI< OutputPixelType,
OutputPixelType > ExtractROIFilterType;
ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
extractROIFilter->SetStartX( 10 );
extractROIFilter->SetStartY( 10 );
extractROIFilter->SetSizeX( 100 );
extractROIFilter->SetSizeY( 100 );
extractROIFilter->SetSizeY( 100 );
extractROIFilter->SetInput( streaming->GetOutput() );
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFilename );
writer->SetInput( extractROIFilter->GetOutput() );
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "Exception OTB attrappee dans exception ITK !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
catch( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cerr << "Exception OTB non attrappee !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>correction test.<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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
//#define MAIN
#include "otbImage.h"
#include "itkVectorImage.h"
#include "itkExceptionObject.h"
#include <iostream>
#include "itkComplexToModulusImageFilter.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiChannelExtractROI.h"
int otbImageFileReaderERS(int argc, char* argv[])
{
try
{
// Verify the number of parameters in the command line
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
typedef float InputPixelType;
typedef unsigned short OutputPixelType;
const unsigned int Dimension = 2;
typedef otb::VectorImage< InputPixelType, Dimension > InputImageType;
typedef otb::VectorImage< OutputPixelType, Dimension > OutputImageType;
typedef otb::ImageFileReader< InputImageType > ReaderType;
typedef otb::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer complexReader = ReaderType::New();
complexReader->SetFileName( inputFilename );
typedef otb::MultiChannelExtractROI< InputPixelType,
OutputPixelType > ExtractROIFilterType;
ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
extractROIFilter->SetStartX( 10 );
extractROIFilter->SetStartY( 10 );
extractROIFilter->SetSizeX( 100 );
extractROIFilter->SetSizeY( 100 );
extractROIFilter->SetSizeY( 100 );
extractROIFilter->SetInput( complexReader->GetOutput() );
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFilename );
writer->SetInput( extractROIFilter->GetOutput() );
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "Exception OTB attrappee dans exception ITK !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
catch( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cerr << "Exception OTB non attrappee !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#pragma once
#include "toast/environment.hpp"
#include "toast/filesystem.hpp"
#include <string>
// The Toast Shared Memory Internals
#define TOAST_PRIVATE_MEMPOOL_SIZE 256
// Private Memory Pool Init/Error Flags
#define PMP_VERIFY 0x7A
#define PMP_VALID 0x7B
#define PMP_LOAD_COMPLETE 0x7C
#define PMP_INVALID 0x80
#define PMP_LOAD_ERR 0x8A
#define PMP_INFO_ERR 0x8B
#define PMP_INIT_ERR 0x8C
#ifdef OS_WIN
#include <windows.h>
#include <conio.h>
#include <tchar.h>
#define SHM_HANDLE HANDLE
#else
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <fcntl.h>
#define SHM_HANDLE int
#endif
namespace Toast {
namespace Internal {
namespace SHM {
API SHM_HANDLE create_shm_file(std::string name, int size);
API SHM_HANDLE open_shm_file(std::string name);
API char *map_shm_file(SHM_HANDLE handle, int size);
API void unmap_shm_file(void *addr, int size);
API void close_shm_file(std::string name, SHM_HANDLE handle);
}
}
}<commit_msg>Make the private pool a little bit smaller<commit_after>#pragma once
#include "toast/environment.hpp"
#include "toast/filesystem.hpp"
#include <string>
// The Toast Shared Memory Internals
#define TOAST_PRIVATE_MEMPOOL_SIZE 128
// Private Memory Pool Init/Error Flags
#define PMP_VERIFY 0x7A
#define PMP_VALID 0x7B
#define PMP_LOAD_COMPLETE 0x7C
#define PMP_INVALID 0x80
#define PMP_LOAD_ERR 0x8A
#define PMP_INFO_ERR 0x8B
#define PMP_INIT_ERR 0x8C
#ifdef OS_WIN
#include <windows.h>
#include <conio.h>
#include <tchar.h>
#define SHM_HANDLE HANDLE
#else
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <fcntl.h>
#define SHM_HANDLE int
#endif
namespace Toast {
namespace Internal {
namespace SHM {
API SHM_HANDLE create_shm_file(std::string name, int size);
API SHM_HANDLE open_shm_file(std::string name);
API char *map_shm_file(SHM_HANDLE handle, int size);
API void unmap_shm_file(void *addr, int size);
API void close_shm_file(std::string name, SHM_HANDLE handle);
}
}
}<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file VoiceToolWidget.cpp
* @brief Widget for voice communication control
*
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "VoiceToolWidget.h"
#include "CommunicationsService.h"
#include "VoiceStateWidget.h"
#include "UiServiceInterface.h"
#include "Input.h"
#include "UiProxyWidget.h"
#include "VoiceControllerWidget.h"
#include "VoiceUsersInfoWidget.h"
#include "VoiceTransmissionModeWidget.h"
#include "VoiceController.h"
#include <QSettings>
#include <QComboBox>
#include "DebugOperatorNew.h"
namespace CommUI
{
VoiceToolWidget::VoiceToolWidget(Foundation::Framework* framework) :
framework_(framework),
voice_users_info_widget_(0),
in_world_voice_session_(0),
voice_state_widget_(0),
voice_controller_widget_(0),
voice_controller_proxy_widget_(0),
channel_selection_(0),
transmission_mode_widget_(0),
voice_controller_(0)
{
setupUi(this);
InitializeInWorldVoice();
}
VoiceToolWidget::~VoiceToolWidget()
{
UninitializeInWorldVoice();
}
void VoiceToolWidget::InitializeInWorldVoice()
{
if (framework_ && framework_->GetServiceManager())
{
Communications::ServiceInterface *communication_service = framework_->GetService<Communications::ServiceInterface>();
if (communication_service)
ConnectInWorldVoiceSession( communication_service->InWorldVoiceSession() );
}
}
void VoiceToolWidget::ConnectInWorldVoiceSession(Communications::InWorldVoice::SessionInterface* session)
{
in_world_voice_session_ = session;
if (!session)
return;
QObject::connect(in_world_voice_session_, SIGNAL(StartSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
QObject::connect(in_world_voice_session_, SIGNAL(StopSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
QObject::connect(in_world_voice_session_, SIGNAL(StateChanged(Communications::InWorldVoice::SessionInterface::State)), this, SLOT(UpdateInWorldVoiceIndicator()));
QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface*)) );
QObject::connect(in_world_voice_session_, SIGNAL(ParticipantLeft(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
QObject::connect(in_world_voice_session_, SIGNAL(destroyed()), this, SLOT(UninitializeInWorldVoice()));
QObject::connect(in_world_voice_session_, SIGNAL(SpeakerVoiceActivityChanged(double)), this, SLOT(UpdateInWorldVoiceIndicator()));
QObject::connect(in_world_voice_session_, SIGNAL(ActiceChannelChanged(QString)), this, SLOT(UpdateUI()));
QObject::connect(in_world_voice_session_, SIGNAL(ChannelListChanged(QStringList)), this, SLOT(UpdateUI()));
}
void VoiceToolWidget::Minimize()
{
}
void VoiceToolWidget::Maximize()
{
}
void VoiceToolWidget::UpdateInWorldVoiceIndicator()
{
if (!in_world_voice_session_)
return;
if (in_world_voice_session_->GetState() != Communications::InWorldVoice::SessionInterface::STATE_OPEN)
{
voice_users_info_widget_->hide();
voice_state_widget_->hide();
if (voice_controller_proxy_widget_)
voice_controller_proxy_widget_->hide();
return;
}
else
{
voice_users_info_widget_->show();
voice_state_widget_->show();
}
if (in_world_voice_session_->IsAudioSendingEnabled())
{
if (voice_state_widget_)
{
voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_ONLINE);
voice_state_widget_->SetVoiceActivity(in_world_voice_session_->SpeakerVoiceActivity());
}
}
else
{
if (voice_state_widget_)
voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_OFFLINE);
}
if (voice_users_info_widget_)
{
double channel_voice_activity = 0;
QList<Communications::InWorldVoice::ParticipantInterface*> list = in_world_voice_session_->Participants();
foreach(Communications::InWorldVoice::ParticipantInterface* p, list)
{
if (p->IsSpeaking())
{
channel_voice_activity = 1;
break;
}
}
voice_users_info_widget_->SetVoiceActivity(channel_voice_activity);
voice_users_info_widget_->SetUsersCount(in_world_voice_session_->Participants().count());
}
}
void VoiceToolWidget::ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface* p)
{
connect(p, SIGNAL(StartSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
connect(p, SIGNAL(StopSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
}
void VoiceToolWidget::UninitializeInWorldVoice()
{
if (voice_controller_proxy_widget_)
framework_->UiService()->RemoveWidgetFromScene(voice_controller_proxy_widget_);
if (voice_controller_widget_)
SAFE_DELETE(voice_controller_widget_);
if (voice_controller_)
SAFE_DELETE(voice_controller_);
in_world_voice_session_ = 0;
}
void VoiceToolWidget::ToggleVoiceControlWidget()
{
if (!in_world_voice_session_ || !voice_controller_proxy_widget_)
return;
if (voice_controller_proxy_widget_->isVisible())
voice_controller_proxy_widget_->AnimatedHide();
else
{
voice_controller_proxy_widget_->show();
/// @todo fixme HACK BEGIN
voice_controller_proxy_widget_->moveBy(1,1);
voice_controller_proxy_widget_->moveBy(-1,-1);
/// HACK END
}
}
void VoiceToolWidget::UpdateUI()
{
QString channel = in_world_voice_session_->GetActiveChannel();
if (!voice_controller_)
{
voice_controller_ = new VoiceController(in_world_voice_session_);
/// @todo Use Settings class from MumbeVoipModule
QSettings settings(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/MumbleVoip");
switch(settings.value("MumbleVoice/default_voice_mode").toInt())
{
case 0:
voice_controller_->SetTransmissionMode(VoiceController::Mute);
break;
case 1:
voice_controller_->SetTransmissionMode(VoiceController::ContinuousTransmission);
break;
case 2:
voice_controller_->SetTransmissionMode(VoiceController::PushToTalk);
break;
case 3:
voice_controller_->SetTransmissionMode(VoiceController::ToggleMode);
break;
}
}
if (!voice_state_widget_)
{
voice_state_widget_ = new VoiceStateWidget();
connect(voice_state_widget_, SIGNAL( clicked() ), SLOT(ToggleTransmissionModeWidget() ) );
this->layout()->addWidget(voice_state_widget_);
voice_state_widget_->show();
}
if (!voice_users_info_widget_)
{
voice_users_info_widget_ = new CommUI::VoiceUsersInfoWidget(0);
connect(voice_users_info_widget_, SIGNAL( clicked() ), SLOT(ToggleVoiceControlWidget() ) );
this->layout()->addWidget(voice_users_info_widget_);
}
voice_users_info_widget_->show();
voice_users_info_widget_->updateGeometry();
if (!channel_selection_)
{
channel_selection_ = new QComboBox();
this->layout()->addWidget(channel_selection_);
}
disconnect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
channel_selection_->clear();
channel_selection_->addItems(in_world_voice_session_->GetChannels());
channel_selection_->addItems( QStringList() << ""); // no active channel
channel_selection_->setCurrentIndex(channel_selection_->findText(in_world_voice_session_->GetActiveChannel()));
channel_selection_->updateGeometry();
connect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
this->update();
if (voice_controller_widget_)
{
SAFE_DELETE(voice_controller_widget_);
voice_controller_proxy_widget_ = 0; // automatically deleted by framework
}
if (in_world_voice_session_->GetState() == Communications::InWorldVoice::SessionInterface::STATE_OPEN)
{
voice_controller_widget_ = new VoiceControllerWidget(in_world_voice_session_);
voice_controller_proxy_widget_ = framework_->UiService()->AddWidgetToScene(voice_controller_widget_);
voice_controller_proxy_widget_->setWindowTitle("In-world voice");
voice_controller_proxy_widget_->hide();
/// @todo fixme HACK BEGIN
voice_controller_proxy_widget_->moveBy(1,1);
voice_controller_proxy_widget_->moveBy(-1,-1);
/// HACK END
/// @todo Make these configurable
input_context_ = framework_->GetInput()->RegisterInputContext("CommunicationWidget", 90);
connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_, SLOT(SetPushToTalkOn()));
connect(input_context_.get(), SIGNAL(MouseMiddleReleased(MouseEvent*)),voice_controller_, SLOT(SetPushToTalkOff()));
connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_, SLOT(Toggle()));
}
UpdateInWorldVoiceIndicator();
}
void VoiceToolWidget::ToggleTransmissionModeWidget()
{
if (!transmission_mode_widget_)
{
/// @todo Use Settings class from MumbeVoipModule
QSettings settings(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/MumbleVoip");
int default_voice_mode = settings.value("MumbleVoice/default_voice_mode").toInt();
transmission_mode_widget_ = new VoiceTransmissionModeWidget(default_voice_mode);
connect(transmission_mode_widget_, SIGNAL(TransmissionModeSelected(int)), this, SLOT(ChangeTransmissionMode(int)));
UiProxyWidget* proxy = framework_->UiService()->AddWidgetToScene(transmission_mode_widget_, Qt::Widget);
connect(proxy->scene(), SIGNAL(sceneRectChanged(const QRectF)), this, SLOT(UpdateTransmissionModeWidgetPosition()));
UpdateTransmissionModeWidgetPosition();
transmission_mode_widget_->show();
}
else
{
if (transmission_mode_widget_->isVisible())
transmission_mode_widget_->hide();
else
{
transmission_mode_widget_->show();
}
}
}
void VoiceToolWidget::UpdateTransmissionModeWidgetPosition()
{
QPoint absolute_pos;
QWidget* p = parentWidget();
while (p)
{
absolute_pos += p->pos();
p = p->parentWidget();
}
absolute_pos.setY(absolute_pos.y() - transmission_mode_widget_->height());
transmission_mode_widget_->move(absolute_pos);
}
void VoiceToolWidget::ChangeTransmissionMode(int mode)
{
voice_controller_->SetTransmissionMode(static_cast<VoiceController::TransmissionMode>(mode));
}
} // CommUI
<commit_msg>Trying to fix rest of the linux build problems.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file VoiceToolWidget.cpp
* @brief Widget for voice communication control
*
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "VoiceToolWidget.h"
#include "CommunicationsService.h"
#include "VoiceStateWidget.h"
#include "UiServiceInterface.h"
#include "Input.h"
#include "UiProxyWidget.h"
#include "VoiceControllerWidget.h"
#include "VoiceUsersInfoWidget.h"
#include "VoiceTransmissionModeWidget.h"
#include "VoiceController.h"
#include <QSettings>
#include <QComboBox>
#include <QGraphicsScene>
#include "DebugOperatorNew.h"
namespace CommUI
{
VoiceToolWidget::VoiceToolWidget(Foundation::Framework* framework) :
framework_(framework),
voice_users_info_widget_(0),
in_world_voice_session_(0),
voice_state_widget_(0),
voice_controller_widget_(0),
voice_controller_proxy_widget_(0),
channel_selection_(0),
transmission_mode_widget_(0),
voice_controller_(0)
{
setupUi(this);
InitializeInWorldVoice();
}
VoiceToolWidget::~VoiceToolWidget()
{
UninitializeInWorldVoice();
}
void VoiceToolWidget::InitializeInWorldVoice()
{
if (framework_ && framework_->GetServiceManager())
{
Communications::ServiceInterface *communication_service = framework_->GetService<Communications::ServiceInterface>();
if (communication_service)
ConnectInWorldVoiceSession( communication_service->InWorldVoiceSession() );
}
}
void VoiceToolWidget::ConnectInWorldVoiceSession(Communications::InWorldVoice::SessionInterface* session)
{
in_world_voice_session_ = session;
if (!session)
return;
QObject::connect(in_world_voice_session_, SIGNAL(StartSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
QObject::connect(in_world_voice_session_, SIGNAL(StopSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
QObject::connect(in_world_voice_session_, SIGNAL(StateChanged(Communications::InWorldVoice::SessionInterface::State)), this, SLOT(UpdateInWorldVoiceIndicator()));
QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface*)) );
QObject::connect(in_world_voice_session_, SIGNAL(ParticipantLeft(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
QObject::connect(in_world_voice_session_, SIGNAL(destroyed()), this, SLOT(UninitializeInWorldVoice()));
QObject::connect(in_world_voice_session_, SIGNAL(SpeakerVoiceActivityChanged(double)), this, SLOT(UpdateInWorldVoiceIndicator()));
QObject::connect(in_world_voice_session_, SIGNAL(ActiceChannelChanged(QString)), this, SLOT(UpdateUI()));
QObject::connect(in_world_voice_session_, SIGNAL(ChannelListChanged(QStringList)), this, SLOT(UpdateUI()));
}
void VoiceToolWidget::Minimize()
{
}
void VoiceToolWidget::Maximize()
{
}
void VoiceToolWidget::UpdateInWorldVoiceIndicator()
{
if (!in_world_voice_session_)
return;
if (in_world_voice_session_->GetState() != Communications::InWorldVoice::SessionInterface::STATE_OPEN)
{
voice_users_info_widget_->hide();
voice_state_widget_->hide();
if (voice_controller_proxy_widget_)
voice_controller_proxy_widget_->hide();
return;
}
else
{
voice_users_info_widget_->show();
voice_state_widget_->show();
}
if (in_world_voice_session_->IsAudioSendingEnabled())
{
if (voice_state_widget_)
{
voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_ONLINE);
voice_state_widget_->SetVoiceActivity(in_world_voice_session_->SpeakerVoiceActivity());
}
}
else
{
if (voice_state_widget_)
voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_OFFLINE);
}
if (voice_users_info_widget_)
{
double channel_voice_activity = 0;
QList<Communications::InWorldVoice::ParticipantInterface*> list = in_world_voice_session_->Participants();
foreach(Communications::InWorldVoice::ParticipantInterface* p, list)
{
if (p->IsSpeaking())
{
channel_voice_activity = 1;
break;
}
}
voice_users_info_widget_->SetVoiceActivity(channel_voice_activity);
voice_users_info_widget_->SetUsersCount(in_world_voice_session_->Participants().count());
}
}
void VoiceToolWidget::ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface* p)
{
connect(p, SIGNAL(StartSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
connect(p, SIGNAL(StopSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
}
void VoiceToolWidget::UninitializeInWorldVoice()
{
if (voice_controller_proxy_widget_)
framework_->UiService()->RemoveWidgetFromScene(voice_controller_proxy_widget_);
if (voice_controller_widget_)
SAFE_DELETE(voice_controller_widget_);
if (voice_controller_)
SAFE_DELETE(voice_controller_);
in_world_voice_session_ = 0;
}
void VoiceToolWidget::ToggleVoiceControlWidget()
{
if (!in_world_voice_session_ || !voice_controller_proxy_widget_)
return;
if (voice_controller_proxy_widget_->isVisible())
voice_controller_proxy_widget_->AnimatedHide();
else
{
voice_controller_proxy_widget_->show();
/// @todo fixme HACK BEGIN
voice_controller_proxy_widget_->moveBy(1,1);
voice_controller_proxy_widget_->moveBy(-1,-1);
/// HACK END
}
}
void VoiceToolWidget::UpdateUI()
{
QString channel = in_world_voice_session_->GetActiveChannel();
if (!voice_controller_)
{
voice_controller_ = new VoiceController(in_world_voice_session_);
/// @todo Use Settings class from MumbeVoipModule
QSettings settings(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/MumbleVoip");
switch(settings.value("MumbleVoice/default_voice_mode").toInt())
{
case 0:
voice_controller_->SetTransmissionMode(VoiceController::Mute);
break;
case 1:
voice_controller_->SetTransmissionMode(VoiceController::ContinuousTransmission);
break;
case 2:
voice_controller_->SetTransmissionMode(VoiceController::PushToTalk);
break;
case 3:
voice_controller_->SetTransmissionMode(VoiceController::ToggleMode);
break;
}
}
if (!voice_state_widget_)
{
voice_state_widget_ = new VoiceStateWidget();
connect(voice_state_widget_, SIGNAL( clicked() ), SLOT(ToggleTransmissionModeWidget() ) );
this->layout()->addWidget(voice_state_widget_);
voice_state_widget_->show();
}
if (!voice_users_info_widget_)
{
voice_users_info_widget_ = new CommUI::VoiceUsersInfoWidget(0);
connect(voice_users_info_widget_, SIGNAL( clicked() ), SLOT(ToggleVoiceControlWidget() ) );
this->layout()->addWidget(voice_users_info_widget_);
}
voice_users_info_widget_->show();
voice_users_info_widget_->updateGeometry();
if (!channel_selection_)
{
channel_selection_ = new QComboBox();
this->layout()->addWidget(channel_selection_);
}
disconnect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
channel_selection_->clear();
channel_selection_->addItems(in_world_voice_session_->GetChannels());
channel_selection_->addItems( QStringList() << ""); // no active channel
channel_selection_->setCurrentIndex(channel_selection_->findText(in_world_voice_session_->GetActiveChannel()));
channel_selection_->updateGeometry();
connect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
this->update();
if (voice_controller_widget_)
{
SAFE_DELETE(voice_controller_widget_);
voice_controller_proxy_widget_ = 0; // automatically deleted by framework
}
if (in_world_voice_session_->GetState() == Communications::InWorldVoice::SessionInterface::STATE_OPEN)
{
voice_controller_widget_ = new VoiceControllerWidget(in_world_voice_session_);
voice_controller_proxy_widget_ = framework_->UiService()->AddWidgetToScene(voice_controller_widget_);
voice_controller_proxy_widget_->setWindowTitle("In-world voice");
voice_controller_proxy_widget_->hide();
/// @todo fixme HACK BEGIN
voice_controller_proxy_widget_->moveBy(1,1);
voice_controller_proxy_widget_->moveBy(-1,-1);
/// HACK END
/// @todo Make these configurable
input_context_ = framework_->GetInput()->RegisterInputContext("CommunicationWidget", 90);
connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_, SLOT(SetPushToTalkOn()));
connect(input_context_.get(), SIGNAL(MouseMiddleReleased(MouseEvent*)),voice_controller_, SLOT(SetPushToTalkOff()));
connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_, SLOT(Toggle()));
}
UpdateInWorldVoiceIndicator();
}
void VoiceToolWidget::ToggleTransmissionModeWidget()
{
if (!transmission_mode_widget_)
{
/// @todo Use Settings class from MumbeVoipModule
QSettings settings(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/MumbleVoip");
int default_voice_mode = settings.value("MumbleVoice/default_voice_mode").toInt();
transmission_mode_widget_ = new VoiceTransmissionModeWidget(default_voice_mode);
connect(transmission_mode_widget_, SIGNAL(TransmissionModeSelected(int)), this, SLOT(ChangeTransmissionMode(int)));
UiProxyWidget* proxy = framework_->UiService()->AddWidgetToScene(transmission_mode_widget_, Qt::Widget);
QObject::connect(proxy->scene(), SIGNAL(sceneRectChanged(const QRectF)), this, SLOT(UpdateTransmissionModeWidgetPosition()));
UpdateTransmissionModeWidgetPosition();
transmission_mode_widget_->show();
}
else
{
if (transmission_mode_widget_->isVisible())
transmission_mode_widget_->hide();
else
{
transmission_mode_widget_->show();
}
}
}
void VoiceToolWidget::UpdateTransmissionModeWidgetPosition()
{
QPoint absolute_pos;
QWidget* p = parentWidget();
while (p)
{
absolute_pos += p->pos();
p = p->parentWidget();
}
absolute_pos.setY(absolute_pos.y() - transmission_mode_widget_->height());
transmission_mode_widget_->move(absolute_pos);
}
void VoiceToolWidget::ChangeTransmissionMode(int mode)
{
voice_controller_->SetTransmissionMode(static_cast<VoiceController::TransmissionMode>(mode));
}
} // CommUI
<|endoftext|> |
<commit_before>#include "Arduino.h"
#include <EBot.h>
#ifdef WOKE
IRrecv irrecv(receiverpin);
decode_results results;
#endif
EBot::EBot() {
}
EBot::~EBot() {
}
void EBot::begin() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(Echo, INPUT);
pinMode(Trig, OUTPUT);
servo.attach(ServoPin);
servo.write(90);
this->setDirection();
this->setSpeed();
#ifdef WOKE
irrecv.enableIRIn();
#endif
}
void EBot::setDirection(EBot::direction move) {
switch(move) {
case STOP:
this->stop();
break;
case FORWARD:
this->forward(this->speed);
break;
case BACKWARD:
this->backward(this->speed);
break;
case TURNLEFT:
this->turnLeft(this->speed);
break;
case TURNRIGHT:
this->turnRight(this->speed);
break;
case ROTATELEFT:
this->rotateLeft(this->speed);
break;
case ROTATERIGHT:
this->rotateRight(this->speed);
break;
case LEFTWHEELSTOP:
this->leftWheelStop();
break;
case RIGHTWHEELSTOP:
this->rightWheelStop();
break;
case LEFTWHEELFORWARD:
this->leftWheelForward(this->speed);
break;
case RIGHTWHEELFORWARD:
this->rightWheelForward(this->speed);
break;
case LEFTWHEELBACKWARD:
this->leftWheelBackward(this->speed);
break;
case RIGHTWHEELBACKWARD:
this->rightWheelBackward(this->speed);
break;
}
}
void EBot::setSpeed(int speed) {
this->speed = speed;
}
void EBot::stop() {
leftWheelStop();
rightWheelStop();
}
void EBot::forward(int speed) {
leftWheelForward(speed);
rightWheelForward(speed);
}
void EBot::backward(int speed) {
leftWheelBackward(speed);
rightWheelBackward(speed);
}
void EBot::turnLeft(int speed) {
leftWheelStop();
rightWheelForward(speed);
}
void EBot::turnRight(int speed) {
leftWheelForward(speed);
rightWheelStop();
}
void EBot::rotateLeft(int speed) {
leftWheelBackward(speed);
rightWheelForward(speed);
}
void EBot::rotateRight(int speed) {
leftWheelForward(speed);
rightWheelBackward(speed);
}
void EBot::leftWheelStop() {
digitalWrite(ENB, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}
void EBot::rightWheelStop() {
digitalWrite(ENA, LOW);
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
}
void EBot::leftWheelForward(int speed) {
speed = boundaries(speed, 0, 255);
analogWrite(ENB, speed);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
void EBot::rightWheelForward(int speed) {
speed = boundaries(speed, 0, 255);
analogWrite(ENA, speed);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
}
void EBot::leftWheelBackward(int speed) {
speed = boundaries(speed, 0, 255);
analogWrite(ENB, speed);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
}
void EBot::rightWheelBackward(int speed) {
speed = boundaries(speed, 0, 255);
analogWrite(ENA, speed);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
}
void EBot::setAngle(int angle) {
angle = boundaries(angle, 0, 179);
this->servo.write(angle);
}
unsigned long EBot::getDistance() {
unsigned long duration;
digitalWrite(Trig, LOW);
delayMicroseconds(2);
digitalWrite(Trig, HIGH);
delayMicroseconds(5);
digitalWrite(Trig, LOW);
duration = pulseIn(Echo, HIGH);
return duration / 29 / 2;
}
unsigned long EBot::getIR() {
unsigned long value = 0;
#ifdef WOKE
if (irrecv.decode(&results)) {
value = results.value;
irrecv.resume(); // Receive the next value
}
#endif
return value;
}
bool EBot::readLS1() {
return digitalRead(LS1);
}
bool EBot::readLS2() {
return digitalRead(LS2);
}
bool EBot::readLS3() {
return digitalRead(LS3);
}
int EBot::boundaries(int value, int min, int max) {
value = value < min ? min : value;
value = value > max ? max : value;
return value;
}
<commit_msg>replace variable<commit_after>#include "Arduino.h"
#include <EBot.h>
#ifdef IRREMOTE
IRrecv irrecv(receiverpin);
decode_results results;
#endif
EBot::EBot() {
}
EBot::~EBot() {
}
void EBot::begin() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(Echo, INPUT);
pinMode(Trig, OUTPUT);
servo.attach(ServoPin);
servo.write(90);
this->setDirection();
this->setSpeed();
#ifdef IRREMOTE
irrecv.enableIRIn();
#endif
}
void EBot::setDirection(EBot::direction move) {
switch(move) {
case STOP:
this->stop();
break;
case FORWARD:
this->forward(this->speed);
break;
case BACKWARD:
this->backward(this->speed);
break;
case TURNLEFT:
this->turnLeft(this->speed);
break;
case TURNRIGHT:
this->turnRight(this->speed);
break;
case ROTATELEFT:
this->rotateLeft(this->speed);
break;
case ROTATERIGHT:
this->rotateRight(this->speed);
break;
case LEFTWHEELSTOP:
this->leftWheelStop();
break;
case RIGHTWHEELSTOP:
this->rightWheelStop();
break;
case LEFTWHEELFORWARD:
this->leftWheelForward(this->speed);
break;
case RIGHTWHEELFORWARD:
this->rightWheelForward(this->speed);
break;
case LEFTWHEELBACKWARD:
this->leftWheelBackward(this->speed);
break;
case RIGHTWHEELBACKWARD:
this->rightWheelBackward(this->speed);
break;
}
}
void EBot::setSpeed(int speed) {
this->speed = speed;
}
void EBot::stop() {
leftWheelStop();
rightWheelStop();
}
void EBot::forward(int speed) {
leftWheelForward(speed);
rightWheelForward(speed);
}
void EBot::backward(int speed) {
leftWheelBackward(speed);
rightWheelBackward(speed);
}
void EBot::turnLeft(int speed) {
leftWheelStop();
rightWheelForward(speed);
}
void EBot::turnRight(int speed) {
leftWheelForward(speed);
rightWheelStop();
}
void EBot::rotateLeft(int speed) {
leftWheelBackward(speed);
rightWheelForward(speed);
}
void EBot::rotateRight(int speed) {
leftWheelForward(speed);
rightWheelBackward(speed);
}
void EBot::leftWheelStop() {
digitalWrite(ENB, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}
void EBot::rightWheelStop() {
digitalWrite(ENA, LOW);
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
}
void EBot::leftWheelForward(int speed) {
speed = boundaries(speed, 0, 255);
analogWrite(ENB, speed);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
void EBot::rightWheelForward(int speed) {
speed = boundaries(speed, 0, 255);
analogWrite(ENA, speed);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
}
void EBot::leftWheelBackward(int speed) {
speed = boundaries(speed, 0, 255);
analogWrite(ENB, speed);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
}
void EBot::rightWheelBackward(int speed) {
speed = boundaries(speed, 0, 255);
analogWrite(ENA, speed);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
}
void EBot::setAngle(int angle) {
angle = boundaries(angle, 0, 179);
this->servo.write(angle);
}
unsigned long EBot::getDistance() {
unsigned long duration;
digitalWrite(Trig, LOW);
delayMicroseconds(2);
digitalWrite(Trig, HIGH);
delayMicroseconds(5);
digitalWrite(Trig, LOW);
duration = pulseIn(Echo, HIGH);
return duration / 29 / 2;
}
unsigned long EBot::getIR() {
unsigned long value = 0;
#ifdef IRREMOTE
if (irrecv.decode(&results)) {
value = results.value;
irrecv.resume(); // Receive the next value
}
#endif
return value;
}
bool EBot::readLS1() {
return digitalRead(LS1);
}
bool EBot::readLS2() {
return digitalRead(LS2);
}
bool EBot::readLS3() {
return digitalRead(LS3);
}
int EBot::boundaries(int value, int min, int max) {
value = value < min ? min : value;
value = value > max ? max : value;
return value;
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/math/forward.h>
#include <visionaray/array.h>
#include <visionaray/material.h>
#include <visionaray/get_surface.h>
using namespace visionaray;
// Material type to check
template <typename T>
using mat_type = matte<T>;
#if defined WITHOUT_TEX_COLOR
template <typename N, typename M, int SIZE>
using param_type = array<surface<N, M>, SIZE>;
template <typename N, typename M>
using result_type = surface<N, M>;
#elif defined WITH_TEX_COLOR
template <typename N, typename M, int SIZE>
using param_type = array<surface<N, M, vec3f>, SIZE>;
template <typename N, typename M>
using result_type = surface<N, M, N>;
#endif
int main()
{
#if defined SURFACE_PACK_FLOAT4
param_type<vec3f, mat_type<float>, 4> surf_array;
result_type<vector<3, simd::float4>, mat_type<simd::float4>> surf = simd::pack(surf_array);
#elif defined SURFACE_PACK_FLOAT8
#if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX)
param_type<vec3f, mat_type<float>, 8> surf_array;
result_type<vector<3, simd::float8>, mat_type<simd::float8>> surf = simd::pack(surf_array);
#endif
#elif defined SURFACE_PACK_ILLEGAL_LENGTH_1
param_type<vec3f, mat_type<float>, 1> surf_array;
auto surf = simd::pack(surf_array);
#elif defined SURFACE_PACK_ILLEGAL_LENGTH_3
param_type<vec3f, mat_type<float>, 3> surf_array;
auto surf = simd::pack(surf_array);
#elif defined SURFACE_PACK_ILLEGAL_INTEGRAL_1
param_type<vec3f, mat_type<int>, 4> surf_array;
auto surf = simd::pack(surf_array);
#elif defined SURFACE_PACK_ILLEGAL_INTEGRAL_2
param_type<vec3i, mat_type<float>, 4> surf_array;
auto surf = simd::pack(surf_array);
#endif
return 0;
}
<commit_msg>Adapt to changed surface interface<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/math/forward.h>
#include <visionaray/array.h>
#include <visionaray/material.h>
#include <visionaray/get_surface.h>
using namespace visionaray;
// Material type to check
template <typename T>
using mat_type = matte<T>;
#if defined WITHOUT_TEX_COLOR
template <typename N, typename M, int SIZE>
using param_type = array<surface<N, M>, SIZE>;
template <typename N, typename M>
using result_type = surface<N, M>;
#elif defined WITH_TEX_COLOR
template <typename N, typename M, int SIZE>
using param_type = array<surface<N, vec3f, M>, SIZE>;
template <typename N, typename M>
using result_type = surface<N, N/*TODO: in general TexCol != N*/, M>;
#endif
int main()
{
#if defined SURFACE_PACK_FLOAT4
param_type<vec3f, mat_type<float>, 4> surf_array;
result_type<vector<3, simd::float4>, mat_type<simd::float4>> surf = simd::pack(surf_array);
#elif defined SURFACE_PACK_FLOAT8
#if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX)
param_type<vec3f, mat_type<float>, 8> surf_array;
result_type<vector<3, simd::float8>, mat_type<simd::float8>> surf = simd::pack(surf_array);
#endif
#elif defined SURFACE_PACK_ILLEGAL_LENGTH_1
param_type<vec3f, mat_type<float>, 1> surf_array;
auto surf = simd::pack(surf_array);
#elif defined SURFACE_PACK_ILLEGAL_LENGTH_3
param_type<vec3f, mat_type<float>, 3> surf_array;
auto surf = simd::pack(surf_array);
#elif defined SURFACE_PACK_ILLEGAL_INTEGRAL_1
param_type<vec3f, mat_type<int>, 4> surf_array;
auto surf = simd::pack(surf_array);
#elif defined SURFACE_PACK_ILLEGAL_INTEGRAL_2
param_type<vec3i, mat_type<float>, 4> surf_array;
auto surf = simd::pack(surf_array);
#endif
return 0;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
* $Id$
*/
#ifndef PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_
#define PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_
#include "pcl/keypoints/smoothed_surfaces_keypoint.h"
#include <pcl/kdtree/kdtree_flann.h>
//#include <pcl/io/pcd_io.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::addSmoothedPointCloud (const PointCloudTConstPtr &cloud,
const PointCloudNTConstPtr &normals,
KdTreePtr &kdtree,
float &scale)
{
clouds_.push_back (cloud);
cloud_normals_.push_back (normals);
cloud_trees_.push_back (kdtree);
scales_.push_back (std::pair<float, size_t> (scale, scales_.size ()));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::resetClouds ()
{
clouds_.clear ();
cloud_normals_.clear ();
scales_.clear ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::detectKeypoints (PointCloudT &output)
{
// Calculate differences for each cloud
std::vector<std::vector<float> > diffs (scales_.size ());
// The cloud with the smallest scale has no differences
std::vector<float> aux_diffs (input_->points.size (), 0.0f);
diffs[scales_[0].second] = aux_diffs;
cloud_trees_[scales_[0].second]->setInputCloud (clouds_[scales_[0].second]);
for (size_t scale_i = 1; scale_i < clouds_.size (); ++scale_i)
{
size_t cloud_i = scales_[scale_i].second,
cloud_i_minus_one = scales_[scale_i - 1].second;
diffs[cloud_i].resize (input_->points.size ());
PCL_INFO ("cloud_i %u cloud_i_minus_one %u\n", cloud_i, cloud_i_minus_one);
for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
diffs[cloud_i][point_i] = cloud_normals_[cloud_i]->points[point_i].getNormalVector3fMap ().dot (
clouds_[cloud_i]->points[point_i].getVector3fMap () - clouds_[cloud_i_minus_one]->points[point_i].getVector3fMap ());
// Setup kdtree for this cloud
cloud_trees_[cloud_i]->setInputCloud (clouds_[cloud_i]);
}
// Find minima and maxima in differences inside the input cloud
typename KdTree<PointT>::Ptr input_tree = cloud_trees_.back ();
for (int point_i = 0; point_i < (int)input_->points.size (); ++point_i)
{
std::vector<int> nn_indices;
std::vector<float> nn_distances;
input_tree->radiusSearch (point_i, input_scale_ * neighborhood_constant_, nn_indices, nn_distances);
bool is_min = true, is_max = true;
for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
if (*nn_it != point_i)
{
if (diffs[input_index_][point_i] < diffs[input_index_][*nn_it])
is_max = false;
else if (diffs[input_index_][point_i] > diffs[input_index_][*nn_it])
is_min = false;
}
// If the point is a local minimum/maximum, check if it is the same over all the scales
if (is_min || is_max)
{
bool passed_min = true, passed_max = true;
for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
{
size_t cloud_i = scales_[scale_i].second;
// skip input cloud
if (cloud_i == clouds_.size () - 1)
continue;
nn_indices.clear (); nn_distances.clear ();
cloud_trees_[cloud_i]->radiusSearch (point_i, scales_[scale_i].first * neighborhood_constant_, nn_indices, nn_distances);
bool is_min_other_scale = true, is_max_other_scale = true;
for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
if (*nn_it != point_i)
{
if (diffs[input_index_][point_i] < diffs[cloud_i][*nn_it])
is_max_other_scale = false;
else if (diffs[input_index_][point_i] > diffs[cloud_i][*nn_it])
is_min_other_scale = false;
}
if (is_min == true && is_min_other_scale == false)
passed_min = false;
if (is_max == true && is_max_other_scale == false)
passed_max = false;
if (!passed_min && !passed_max)
break;
}
// check if point was minimum/maximum over all the scales
if (passed_min || passed_max)
output.points.push_back (input_->points[point_i]);
}
}
output.header = input_->header;
output.width = output.points.size ();
output.height = 1;
// debug stuff
// for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
// {
// PointCloud<PointXYZI>::Ptr debug_cloud (new PointCloud<PointXYZI> ());
// debug_cloud->points.resize (input_->points.size ());
// debug_cloud->width = input_->width;
// debug_cloud->height = input_->height;
// for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
// {
// debug_cloud->points[point_i].intensity = diffs[scales_[scale_i].second][point_i];
// debug_cloud->points[point_i].x = input_->points[point_i].x;
// debug_cloud->points[point_i].y = input_->points[point_i].y;
// debug_cloud->points[point_i].z = input_->points[point_i].z;
// }
// char str[512]; sprintf (str, "diffs_%2d.pcd", scale_i);
// io::savePCDFile (str, *debug_cloud);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::initCompute ()
{
PCL_INFO ("SmoothedSurfacesKeypoint initCompute () called\n");
if ( !Keypoint<PointT, PointT>::initCompute ())
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Keypoint::initCompute failed\n");
return false;
}
if (!normals_)
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Input normals were not set\n");
return false;
}
if (clouds_.size () == 0)
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] No other clouds were set apart from the input\n");
return false;
}
if (input_->points.size () != normals_->points.size ())
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] The input cloud and the input normals differ in size\n");
return false;
}
for (size_t cloud_i = 0; cloud_i < clouds_.size (); ++cloud_i)
{
if (clouds_[cloud_i]->points.size () != input_->points.size ())
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Cloud %d does not have the same number of points as the input cloud\n", cloud_i);
return false;
}
if (cloud_normals_[cloud_i]->points.size () != input_->points.size ())
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Normals for cloud %d do not have the same number of points as the input cloud\n", cloud_i);
return false;
}
}
// Add the input cloud as the last index
scales_.push_back (std::pair<float, size_t> (input_scale_, scales_.size ()));
clouds_.push_back (input_);
cloud_normals_.push_back (normals_);
cloud_trees_.push_back (tree_);
// Sort the clouds by their scales
sort (scales_.begin (), scales_.end (), compareScalesFunction);
// Find the index of the input after sorting
for (size_t i = 0; i < scales_.size (); ++i)
if (scales_[i].second == scales_.size () - 1)
{
input_index_ = i;
break;
}
PCL_INFO ("Scales: ");
for (size_t i = 0; i < scales_.size (); ++i) PCL_INFO ("(%d %f), ", scales_[i].second, scales_[i].first);
PCL_INFO ("\n");
return true;
}
#define PCL_INSTANTIATE_SmoothedSurfacesKeypoint(T,NT) template class PCL_EXPORTS pcl::SmoothedSurfacesKeypoint<T,NT>;
#endif /* PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_ */
<commit_msg>just because I have to break the build once in a while :-), sorry folks<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
* $Id$
*/
#ifndef PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_
#define PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_
#include "pcl/keypoints/smoothed_surfaces_keypoint.h"
#include <pcl/kdtree/kdtree_flann.h>
//#include <pcl/io/pcd_io.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::addSmoothedPointCloud (const PointCloudTConstPtr &cloud,
const PointCloudNTConstPtr &normals,
KdTreePtr &kdtree,
float &scale)
{
clouds_.push_back (cloud);
cloud_normals_.push_back (normals);
cloud_trees_.push_back (kdtree);
scales_.push_back (std::pair<float, size_t> (scale, scales_.size ()));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::resetClouds ()
{
clouds_.clear ();
cloud_normals_.clear ();
scales_.clear ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::detectKeypoints (PointCloudT &output)
{
// Calculate differences for each cloud
std::vector<std::vector<float> > diffs (scales_.size ());
// The cloud with the smallest scale has no differences
std::vector<float> aux_diffs (input_->points.size (), 0.0f);
diffs[scales_[0].second] = aux_diffs;
cloud_trees_[scales_[0].second]->setInputCloud (clouds_[scales_[0].second]);
for (size_t scale_i = 1; scale_i < clouds_.size (); ++scale_i)
{
size_t cloud_i = scales_[scale_i].second,
cloud_i_minus_one = scales_[scale_i - 1].second;
diffs[cloud_i].resize (input_->points.size ());
PCL_INFO ("cloud_i %u cloud_i_minus_one %u\n", cloud_i, cloud_i_minus_one);
for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
diffs[cloud_i][point_i] = cloud_normals_[cloud_i]->points[point_i].getNormalVector3fMap ().dot (
clouds_[cloud_i]->points[point_i].getVector3fMap () - clouds_[cloud_i_minus_one]->points[point_i].getVector3fMap ());
// Setup kdtree for this cloud
cloud_trees_[cloud_i]->setInputCloud (clouds_[cloud_i]);
}
// Find minima and maxima in differences inside the input cloud
typename KdTree<PointT>::Ptr input_tree = cloud_trees_.back ();
for (int point_i = 0; point_i < (int)input_->points.size (); ++point_i)
{
std::vector<int> nn_indices;
std::vector<float> nn_distances;
input_tree->radiusSearch (point_i, input_scale_ * neighborhood_constant_, nn_indices, nn_distances);
bool is_min = true, is_max = true;
for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
if (*nn_it != point_i)
{
if (diffs[input_index_][point_i] < diffs[input_index_][*nn_it])
is_max = false;
else if (diffs[input_index_][point_i] > diffs[input_index_][*nn_it])
is_min = false;
}
// If the point is a local minimum/maximum, check if it is the same over all the scales
if (is_min || is_max)
{
bool passed_min = true, passed_max = true;
for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
{
size_t cloud_i = scales_[scale_i].second;
// skip input cloud
if (cloud_i == clouds_.size () - 1)
continue;
nn_indices.clear (); nn_distances.clear ();
cloud_trees_[cloud_i]->radiusSearch (point_i, scales_[scale_i].first * neighborhood_constant_, nn_indices, nn_distances);
bool is_min_other_scale = true, is_max_other_scale = true;
for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
if (*nn_it != point_i)
{
if (diffs[input_index_][point_i] < diffs[cloud_i][*nn_it])
is_max_other_scale = false;
else if (diffs[input_index_][point_i] > diffs[cloud_i][*nn_it])
is_min_other_scale = false;
}
if (is_min == true && is_min_other_scale == false)
passed_min = false;
if (is_max == true && is_max_other_scale == false)
passed_max = false;
if (!passed_min && !passed_max)
break;
}
// check if point was minimum/maximum over all the scales
if (passed_min || passed_max)
output.points.push_back (input_->points[point_i]);
}
}
output.header = input_->header;
output.width = output.points.size ();
output.height = 1;
// debug stuff
// for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
// {
// PointCloud<PointXYZI>::Ptr debug_cloud (new PointCloud<PointXYZI> ());
// debug_cloud->points.resize (input_->points.size ());
// debug_cloud->width = input_->width;
// debug_cloud->height = input_->height;
// for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
// {
// debug_cloud->points[point_i].intensity = diffs[scales_[scale_i].second][point_i];
// debug_cloud->points[point_i].x = input_->points[point_i].x;
// debug_cloud->points[point_i].y = input_->points[point_i].y;
// debug_cloud->points[point_i].z = input_->points[point_i].z;
// }
// char str[512]; sprintf (str, "diffs_%2d.pcd", scale_i);
// io::savePCDFile (str, *debug_cloud);
// }
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::initCompute ()
{
PCL_INFO ("SmoothedSurfacesKeypoint initCompute () called\n");
if ( !Keypoint<PointT, PointT>::initCompute ())
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Keypoint::initCompute failed\n");
return false;
}
if (!normals_)
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Input normals were not set\n");
return false;
}
if (clouds_.size () == 0)
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] No other clouds were set apart from the input\n");
return false;
}
if (input_->points.size () != normals_->points.size ())
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] The input cloud and the input normals differ in size\n");
return false;
}
for (size_t cloud_i = 0; cloud_i < clouds_.size (); ++cloud_i)
{
if (clouds_[cloud_i]->points.size () != input_->points.size ())
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Cloud %d does not have the same number of points as the input cloud\n", cloud_i);
return false;
}
if (cloud_normals_[cloud_i]->points.size () != input_->points.size ())
{
PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Normals for cloud %d do not have the same number of points as the input cloud\n", cloud_i);
return false;
}
}
// Add the input cloud as the last index
scales_.push_back (std::pair<float, size_t> (input_scale_, scales_.size ()));
clouds_.push_back (input_);
cloud_normals_.push_back (normals_);
cloud_trees_.push_back (tree_);
// Sort the clouds by their scales
sort (scales_.begin (), scales_.end (), compareScalesFunction);
// Find the index of the input after sorting
for (size_t i = 0; i < scales_.size (); ++i)
if (scales_[i].second == scales_.size () - 1)
{
input_index_ = i;
break;
}
PCL_INFO ("Scales: ");
for (size_t i = 0; i < scales_.size (); ++i) PCL_INFO ("(%d %f), ", scales_[i].second, scales_[i].first);
PCL_INFO ("\n");
return true;
}
#define PCL_INSTANTIATE_SmoothedSurfacesKeypoint(T,NT) template class PCL_EXPORTS pcl::SmoothedSurfacesKeypoint<T,NT>;
#endif /* PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_ */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Bastien Penavayre
* Filip Roséen <[email protected]>
* http://b.atch.se/posts/constexpr-meta-container
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include "uniq_value.hpp"
namespace unconstexpr
{
namespace detail
{
template <class Tag = void, class Type = int, Type Start = 0, Type Step = 1>
class meta_counter
{
template<Type N>
struct Flag
{
friend constexpr bool adl_flag (Flag<N>);
};
template<Type N>
struct Writer
{
friend constexpr bool adl_flag (Flag<N>) { return true; }
static constexpr Type value = N;
};
template<Type N, bool = adl_flag(Flag<N>{})>
static constexpr Type reader (int, Flag<N>, Type r = reader(0, Flag<N + Step>{}))
{
return r;
}
template <Type N>
static constexpr Type reader(float, Flag<N>)
{
return N - Step;
}
public:
template <Type = Writer<Start>::value>
static constexpr Type value(Type r = reader(0, Flag<Start>{}))
{
return r;
}
template <Type Value = value()>
static constexpr Type next(Type r = Writer<Value + Step>::value)
{
return r;
}
};
template <unsigned> struct unique_type {};
}
template <class Type = int, Type Start = 0, Type It = 1, unsigned I = uniq_value::value<> >
using meta_counter = detail::meta_counter<detail::unique_type<I>, Type, Start, It>;
}
<commit_msg>streamline meta_counter<commit_after>/*
* Copyright (C) 2017 Bastien Penavayre
* Filip Roséen <[email protected]>
* http://b.atch.se/posts/constexpr-meta-container
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include "uniq_value.hpp"
namespace unconstexpr
{
namespace detail
{
template <class Tag = void, class Type = int, Type Start = 0, Type Step = 1>
class meta_counter
{
template<Type N>
struct Flag
{
friend constexpr bool adl_flag (Flag<N>);
};
template<Type N>
struct Writer
{
friend constexpr bool adl_flag (Flag<N>) { return true; }
static constexpr Type value = N;
};
template<Type N, bool = adl_flag(Flag<N>{})>
static constexpr Type reader (int, Flag<N>, Type r = reader(0, Flag<N + Step>{}))
{
return r;
}
template <Type N>
static constexpr Type reader(float, Flag<N>)
{
return N;
}
public:
static constexpr Type value(Type r = reader(0, Flag<Start>{}))
{
return r;
}
template <Type Value = value()>
static constexpr Type next(Type r = Writer<Value>::value)
{
return r + Step;
}
};
template <unsigned> struct unique_type {};
}
template <class Type = int, Type Start = 0, Type It = 1, unsigned I = uniq_value::value<> >
using meta_counter = detail::meta_counter<detail::unique_type<I>, Type, Start, It>;
}
<|endoftext|> |
<commit_before>#ifndef PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_IS_NONE_HPP
#define PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_IS_NONE_HPP
#include "pythonic/include/utils/functor.hpp"
#include "pythonic/include/types/NoneType.hpp"
PYTHONIC_NS_BEGIN
namespace types
{
struct false_type;
struct true_type {
operator bool() const
{
return true;
}
false_type operator!() const;
true_type operator&(true_type) const;
false_type operator&(false_type) const;
true_type operator|(true_type) const;
true_type operator|(false_type) const;
true_type operator==(true_type) const;
false_type operator==(false_type) const;
};
struct false_type {
operator bool() const
{
return false;
}
true_type operator!() const
{
return {};
}
false_type operator&(true_type)
{
return {};
}
false_type operator&(false_type)
{
return {};
}
true_type operator|(true_type)
{
return {};
}
false_type operator|(false_type)
{
return {};
}
false_type operator==(true_type)
{
return {};
}
true_type operator==(false_type)
{
return {};
}
};
false_type true_type::operator!() const
{
return {};
}
true_type true_type::operator&(true_type) const
{
return {};
}
false_type true_type::operator&(false_type) const
{
return {};
}
true_type true_type::operator|(true_type) const
{
return {};
}
true_type true_type::operator|(false_type) const
{
return {};
}
true_type true_type::operator==(true_type) const
{
return {};
}
false_type true_type::operator==(false_type) const
{
return {};
}
}
namespace __builtin__
{
namespace pythran
{
template <class T>
types::false_type is_none(T const &)
{
return {};
};
template <class T>
bool is_none(types::none<T> const &n)
{
return n.is_none;
};
types::true_type is_none(types::none_type const &)
{
return {};
};
DEFINE_FUNCTOR(pythonic::__builtin__::pythran, is_none);
}
}
template <>
struct to_python<types::true_type> : to_python<bool> {
};
template <>
struct to_python<types::false_type> : to_python<bool> {
};
PYTHONIC_NS_END
#endif
<commit_msg>fix compile without ENABLE_PYTHON_MODULE<commit_after>#ifndef PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_IS_NONE_HPP
#define PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_IS_NONE_HPP
#include "pythonic/include/utils/functor.hpp"
#include "pythonic/include/types/NoneType.hpp"
PYTHONIC_NS_BEGIN
namespace types
{
struct false_type;
struct true_type {
operator bool() const
{
return true;
}
false_type operator!() const;
true_type operator&(true_type) const;
false_type operator&(false_type) const;
true_type operator|(true_type) const;
true_type operator|(false_type) const;
true_type operator==(true_type) const;
false_type operator==(false_type) const;
};
struct false_type {
operator bool() const
{
return false;
}
true_type operator!() const
{
return {};
}
false_type operator&(true_type)
{
return {};
}
false_type operator&(false_type)
{
return {};
}
true_type operator|(true_type)
{
return {};
}
false_type operator|(false_type)
{
return {};
}
false_type operator==(true_type)
{
return {};
}
true_type operator==(false_type)
{
return {};
}
};
false_type true_type::operator!() const
{
return {};
}
true_type true_type::operator&(true_type) const
{
return {};
}
false_type true_type::operator&(false_type) const
{
return {};
}
true_type true_type::operator|(true_type) const
{
return {};
}
true_type true_type::operator|(false_type) const
{
return {};
}
true_type true_type::operator==(true_type) const
{
return {};
}
false_type true_type::operator==(false_type) const
{
return {};
}
}
namespace __builtin__
{
namespace pythran
{
template <class T>
types::false_type is_none(T const &)
{
return {};
};
template <class T>
bool is_none(types::none<T> const &n)
{
return n.is_none;
};
types::true_type is_none(types::none_type const &)
{
return {};
};
DEFINE_FUNCTOR(pythonic::__builtin__::pythran, is_none);
}
}
#ifdef ENABLE_PYTHON_MODULE
template <>
struct to_python<types::true_type> : to_python<bool> {
};
template <>
struct to_python<types::false_type> : to_python<bool> {
};
#endif
PYTHONIC_NS_END
#endif
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <string>
#include <sstream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
#include "Config.h"
#include "Device.h"
#include "Game.h"
#include "Exceptions.h"
using namespace std;
Game::Game()
{
// may throw exceptions
this->initSDL_Video();
this->initSDL_ttf();
//this->initSDL_Mixer();
this->nbPlayers = 0;
this->pauseStr = "";
}
Game::~Game()
{
int i;
for (i=0; i<this->nbPlayers; i++)
{
delete this->players[i];
}
TTF_CloseFont(this->font);
TTF_Quit();
//Mix_HaltMusic();
//Mix_FreeMusic(this->sound);
SDL_DestroyTexture(this->tileset);
SDL_DestroyRenderer(this->renderer);
SDL_DestroyWindow(this->screen);
SDL_Quit();
}
void Game::initSDL_Video()
{
// Init SDL
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
this->screen = SDL_CreateWindow(WINDOW_TITLE,
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
2 * MATRIX_Y*TILE_S + MATRIX_SPACE*TILE_S,
MATRIX_X*TILE_S,
0);
this->renderer = SDL_CreateRenderer(this->screen, -1, 0);
this->loadTextures();
}
void Game::initSDL_ttf()
{
// Init SDL ttf
TTF_Init();
this->font = TTF_OpenFont(FONT_FILE, FONT_SIZE);
}
void Game::initSDL_Mixer()
{
// Init audio
if (Mix_OpenAudio(AUDIO_RATE, AUDIO_FORMAT, AUDIO_CHANNELS, AUDIO_BUFFERS))
{
Alert(NULL, Mix_GetError(), NULL, 0);
throw ERR_INIT_AUDIO;
}
this->sound = Mix_LoadMUS(AUDIO_FILE);
if(this->sound == NULL) {
Alert(NULL, Mix_GetError(), NULL, 0);
throw ERR_INIT_AUDIO_FILE;
}
// auto pause
//Mix_PlayMusic(this->sound, -1);
}
void Game::loadTextures()
{
int i;
SDL_Surface* img;
if (access(TILESET_FILE, F_OK) != 0)
{
Alert(NULL, "Could not open '" TILESET_FILE "'", NULL, 0);
throw ERR_INIT_TEXTURE_FILE;
}
img = SDL_LoadBMP(TILESET_FILE);
if (img == NULL)
{
Alert(NULL, "Could not load '" TILESET_FILE "'", NULL, 0);
throw ERR_INIT_TEXTURE;
}
this->tileset = SDL_CreateTextureFromSurface(this->renderer, img);
SDL_FreeSurface(img);
for(i=0; i<NB_PX; i++)
{
this->props[i].R.h = TILE_S;
this->props[i].R.w = TILE_S;
this->props[i].R.y = 0;
this->props[i].R.x = TILE_S * i;
this->props[i].type = i;
}
}
void Game::setPlayers(int n)
{
this->nbPlayers = n;
this->players[PLAYER_A] = new Player(this, PLAYER_A);
this->players[PLAYER_A]->setOpponent(NULL);
if (n == 2)
{
this->players[PLAYER_B] = new Player(this, PLAYER_B);
this->players[PLAYER_A]->setOpponent(this->players[PLAYER_B]);
this->players[PLAYER_B]->setOpponent(this->players[PLAYER_A]);
}
}
void Game::display()
{
int p, x, y;
SDL_Rect rect;
Position pos;
int px;
SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 255);
SDL_RenderClear(this->renderer);
rect.h = TILE_S;
rect.w = TILE_S;
for (p=0; p<this->nbPlayers; p++)
{
// display matrix
for(x=0; x<MATRIX_X; x++)
{
for(y=0; y<MATRIX_Y; y++)
{
rect.y = TILE_S * (x);
rect.x = TILE_S * (y + p * (MATRIX_Y + MATRIX_SPACE));
SDL_RenderCopy(this->renderer,
this->tileset,
&(this->props[this->players[p]->matrix[x][y]].R),
&rect);
}
}
// display current piece(s)
if (this->players[p]->getCurPiece() != NULL)
{
pos = this->players[p]->getCurPiece()->getCurPos();
for(x=0; x<LG_PIECE; x++)
{
for(y=0; y<LG_PIECE; y++)
{
px = Piece::tabPieces[this->players[p]->getCurPiece()->getCurType()][x][y];
if (px != PX_V)
{
rect.y = TILE_S * (pos.x + x);
rect.x = TILE_S * (pos.y + y + p * (MATRIX_Y + MATRIX_SPACE));
SDL_RenderCopy(this->renderer,
this->tileset,
&(this->props[px].R),
&rect);
}
}
}
}
// display new piece(s)
for(x=0; x<LG_PIECE; x++)
{
for(y=0; y<LG_PIECE; y++)
{
px = Piece::tabPieces[this->players[p]->getNewPiece()->getCurType()][x][y];
if (px != PX_V)
{
rect.y = (x + 1) * TILE_S;
rect.x = TILE_S * (y + 1 + MATRIX_SPACE + p * (LG_PIECE + 2));
SDL_RenderCopy(this->renderer,
this->tileset,
&(this->props[px].R),
&rect);
}
}
}
}
// display scores
this->displayScore();
SDL_RenderPresent(this->renderer);
}
void Game::displayScore()
{
SDL_Surface * surface;
SDL_Texture * texture;
SDL_Rect rect;
int p;
ostringstream text("");
text << "score : " << endl;
for (p=0; p<this->nbPlayers; p++)
text << this->players[p]->getScore() << " ";
text << endl;
text << "level : " << endl;
for (p=0; p<this->nbPlayers; p++)
text << this->players[p]->getLevel() << " ";
text << endl;
text << "lines : " << endl;
for (p=0; p<this->nbPlayers; p++)
text << this->players[p]->getLines() << " ";
text << endl;
text << "pieces : " << endl;
for (p=0; p<this->nbPlayers; p++)
text << this->players[p]->getPieces() << " ";
text << endl;
if (this->pauseStr.size() > 1)
{
text << endl;
text << endl;
text << this->pauseStr;
}
/* surface = TTF_RenderText_Solid(this->font, text.str().c_str(), FONT_COLOR); */
surface = TTF_RenderText_Blended_Wrapped(this->font, text.str().c_str(), FONT_COLOR, MATRIX_SPACE*TILE_S);
texture = SDL_CreateTextureFromSurface(this->renderer, surface);
// display texture
rect.h = surface->h;
rect.w = surface->w;
rect.y = SCORE_DISPLAY_X;
rect.x = SCORE_DISPLAY_Y;
SDL_RenderCopy(this->renderer, texture, NULL, &rect);
SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);
}
int Game::play()
{
int act[this->nbPlayers];
Action action;
int i = 0;
int p;
SDL_Event event;
// purge queue events
//while(SDL_PollEvent(&event));
fill_n(act, this->nbPlayers, ACTION_NONE);
// init pause
p = this->actionPause(string("Press Enter to begin"));
if (p == ACTION_QUIT) return ACTION_QUIT;
while (1)
{
// Get players' actions
action = this->getAction();
// Quit game
if (action.action == ACTION_QUIT) return ACTION_QUIT;
if (action.player >= 0)
{
act[action.player] = action.action;
}
i++;
// play
if (i > 10)
{
for (p=0; p<this->nbPlayers; p++)
{
if (this->players[p]->play(act[p]) == 1)
{
this->actionPause(string("Game over !"));
return ACTION_QUIT;
}
act[p] = ACTION_NONE;
}
this->display();
SDL_Delay(20);
i = 0;
}
}
}
Action Game::getAction()
{
Action action;
int ret = ACTION_NONE;
int player = -1;
SDL_Event event;
if (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_WINDOWEVENT:
// Set pause on focus lost
if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)
{
ret = this->actionPause(string("Pause..."));
}
break;
case SDL_QUIT:
ret = ACTION_QUIT;
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
ret = this->actionPause(string("Pause..."));
break;
case SDLK_m:
/* pause music */
if (this->pause == 1)
{
Mix_PlayMusic(this->sound, -1);
this->pause = 0;
}
/* resume music */
else
{
Mix_HaltMusic();
this->pause = 1;
}
ret = ACTION_NONE;
break;
case SDLK_p:
case SDLK_LALT:
ret = this->actionPause(string("Pause..."));
break;
case SDLK_UP:
ret = ACTION_ROTATE;
player = PLAYER_B;
break;
case SDLK_DOWN:
ret = ACTION_MOVE_DOWN;
player = PLAYER_B;
break;
case SDLK_RIGHT:
ret = ACTION_MOVE_RIGHT;
player = PLAYER_B;
break;
case SDLK_LEFT:
ret = ACTION_MOVE_LEFT;
player = PLAYER_B;
break;
case SDLK_RCTRL:
ret = ACTION_DROP;
player = PLAYER_B;
break;
case SDLK_z: // azerty
case SDLK_w: // qwerty
ret = ACTION_ROTATE;
player = PLAYER_A;
break;
case SDLK_s:
ret = ACTION_MOVE_DOWN;
player = PLAYER_A;
break;
case SDLK_d:
ret = ACTION_MOVE_RIGHT;
player = PLAYER_A;
break;
case SDLK_q: // azerty
case SDLK_a: // qwerty
ret = ACTION_MOVE_LEFT;
player = PLAYER_A;
break;
case SDLK_LCTRL:
ret = ACTION_DROP;
player = PLAYER_A;
break;
default:
ret = ACTION_NONE;
break;
}
break;
}
}
// purge events in queue
//while(SDL_PollEvent(&event));
action.action = ret;
action.player = player;
return action;
}
int Game::actionPause(string str)
{
int action = ACTION_NONE;
SDL_Event event;
this->pauseStr = str;
this->display();
// purge events in queue
while(SDL_PollEvent(&event));
// wait for end pause or quit
while(action == ACTION_NONE)
{
SDL_WaitEvent(&event);
switch(event.type)
{
case SDL_QUIT:
action = ACTION_QUIT;
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
action = ACTION_QUIT;
break;
case SDLK_p:
case SDLK_RETURN:
action = ACTION_PAUSE;
break;
case SDLK_m:
/* pause music */
if (this->pause == 1)
{
Mix_PlayMusic(this->sound, -1);
this->pause = 0;
}
/* resume music */
else
{
Mix_HaltMusic();
this->pause = 1;
}
action = ACTION_NONE;
break;
default:
action = ACTION_NONE;
break;
}
break;
}
this->display();
SDL_Delay(50);
}
this->pauseStr = "";
return action;
}
/********************************
accessors
********************************/
/********************************
end accessors
********************************/
<commit_msg>fix music bug<commit_after>#include <unistd.h>
#include <string>
#include <sstream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
#include "Config.h"
#include "Device.h"
#include "Game.h"
#include "Exceptions.h"
using namespace std;
Game::Game()
{
// may throw exceptions
this->initSDL_Video();
this->initSDL_ttf();
this->initSDL_Mixer();
this->nbPlayers = 0;
this->pauseStr = "";
}
Game::~Game()
{
int i;
for (i=0; i<this->nbPlayers; i++)
{
delete this->players[i];
}
TTF_CloseFont(this->font);
TTF_Quit();
Mix_HaltMusic();
Mix_FreeMusic(this->sound);
SDL_DestroyTexture(this->tileset);
SDL_DestroyRenderer(this->renderer);
SDL_DestroyWindow(this->screen);
SDL_Quit();
}
void Game::initSDL_Video()
{
// Init SDL
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
this->screen = SDL_CreateWindow(WINDOW_TITLE,
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
2 * MATRIX_Y*TILE_S + MATRIX_SPACE*TILE_S,
MATRIX_X*TILE_S,
0);
this->renderer = SDL_CreateRenderer(this->screen, -1, 0);
this->loadTextures();
}
void Game::initSDL_ttf()
{
// Init SDL ttf
TTF_Init();
this->font = TTF_OpenFont(FONT_FILE, FONT_SIZE);
}
void Game::initSDL_Mixer()
{
// Init audio
if (Mix_OpenAudio(AUDIO_RATE, AUDIO_FORMAT, AUDIO_CHANNELS, AUDIO_BUFFERS))
{
Alert(NULL, Mix_GetError(), NULL, 0);
throw ERR_INIT_AUDIO;
}
this->sound = Mix_LoadMUS(AUDIO_FILE);
if(this->sound == NULL) {
Alert(NULL, Mix_GetError(), NULL, 0);
throw ERR_INIT_AUDIO_FILE;
}
// auto pause
this->pause = 1;
//Mix_PlayMusic(this->sound, -1);
}
void Game::loadTextures()
{
int i;
SDL_Surface* img;
if (access(TILESET_FILE, F_OK) != 0)
{
Alert(NULL, "Could not open '" TILESET_FILE "'", NULL, 0);
throw ERR_INIT_TEXTURE_FILE;
}
img = SDL_LoadBMP(TILESET_FILE);
if (img == NULL)
{
Alert(NULL, "Could not load '" TILESET_FILE "'", NULL, 0);
throw ERR_INIT_TEXTURE;
}
this->tileset = SDL_CreateTextureFromSurface(this->renderer, img);
SDL_FreeSurface(img);
for(i=0; i<NB_PX; i++)
{
this->props[i].R.h = TILE_S;
this->props[i].R.w = TILE_S;
this->props[i].R.y = 0;
this->props[i].R.x = TILE_S * i;
this->props[i].type = i;
}
}
void Game::setPlayers(int n)
{
this->nbPlayers = n;
this->players[PLAYER_A] = new Player(this, PLAYER_A);
this->players[PLAYER_A]->setOpponent(NULL);
if (n == 2)
{
this->players[PLAYER_B] = new Player(this, PLAYER_B);
this->players[PLAYER_A]->setOpponent(this->players[PLAYER_B]);
this->players[PLAYER_B]->setOpponent(this->players[PLAYER_A]);
}
}
void Game::display()
{
int p, x, y;
SDL_Rect rect;
Position pos;
int px;
SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 255);
SDL_RenderClear(this->renderer);
rect.h = TILE_S;
rect.w = TILE_S;
for (p=0; p<this->nbPlayers; p++)
{
// display matrix
for(x=0; x<MATRIX_X; x++)
{
for(y=0; y<MATRIX_Y; y++)
{
rect.y = TILE_S * (x);
rect.x = TILE_S * (y + p * (MATRIX_Y + MATRIX_SPACE));
SDL_RenderCopy(this->renderer,
this->tileset,
&(this->props[this->players[p]->matrix[x][y]].R),
&rect);
}
}
// display current piece(s)
if (this->players[p]->getCurPiece() != NULL)
{
pos = this->players[p]->getCurPiece()->getCurPos();
for(x=0; x<LG_PIECE; x++)
{
for(y=0; y<LG_PIECE; y++)
{
px = Piece::tabPieces[this->players[p]->getCurPiece()->getCurType()][x][y];
if (px != PX_V)
{
rect.y = TILE_S * (pos.x + x);
rect.x = TILE_S * (pos.y + y + p * (MATRIX_Y + MATRIX_SPACE));
SDL_RenderCopy(this->renderer,
this->tileset,
&(this->props[px].R),
&rect);
}
}
}
}
// display new piece(s)
for(x=0; x<LG_PIECE; x++)
{
for(y=0; y<LG_PIECE; y++)
{
px = Piece::tabPieces[this->players[p]->getNewPiece()->getCurType()][x][y];
if (px != PX_V)
{
rect.y = (x + 1) * TILE_S;
rect.x = TILE_S * (y + 1 + MATRIX_SPACE + p * (LG_PIECE + 2));
SDL_RenderCopy(this->renderer,
this->tileset,
&(this->props[px].R),
&rect);
}
}
}
}
// display scores
this->displayScore();
SDL_RenderPresent(this->renderer);
}
void Game::displayScore()
{
SDL_Surface * surface;
SDL_Texture * texture;
SDL_Rect rect;
int p;
ostringstream text("");
text << "score : " << endl;
for (p=0; p<this->nbPlayers; p++)
text << this->players[p]->getScore() << " ";
text << endl;
text << "level : " << endl;
for (p=0; p<this->nbPlayers; p++)
text << this->players[p]->getLevel() << " ";
text << endl;
text << "lines : " << endl;
for (p=0; p<this->nbPlayers; p++)
text << this->players[p]->getLines() << " ";
text << endl;
text << "pieces : " << endl;
for (p=0; p<this->nbPlayers; p++)
text << this->players[p]->getPieces() << " ";
text << endl;
text << endl;
text << "Music : " << ((this->pause == 1) ? "Off" : "On") << endl;
if (this->pauseStr.size() > 1)
{
text << endl;
text << endl;
text << this->pauseStr;
}
//surface = TTF_RenderText_Solid(this->font, text.str().c_str(), FONT_COLOR);
surface = TTF_RenderText_Blended_Wrapped(this->font, text.str().c_str(), FONT_COLOR, MATRIX_SPACE*TILE_S);
texture = SDL_CreateTextureFromSurface(this->renderer, surface);
// display texture
rect.h = surface->h;
rect.w = surface->w;
rect.y = SCORE_DISPLAY_X;
rect.x = SCORE_DISPLAY_Y;
SDL_RenderCopy(this->renderer, texture, NULL, &rect);
SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);
}
int Game::play()
{
int act[this->nbPlayers];
Action action;
int i = 0;
int p;
SDL_Event event;
// purge queue events
//while(SDL_PollEvent(&event));
fill_n(act, this->nbPlayers, ACTION_NONE);
// init pause
p = this->actionPause(string("Press Enter to begin"));
if (p == ACTION_QUIT) return ACTION_QUIT;
while (1)
{
// Get players' actions
action = this->getAction();
// Quit game
if (action.action == ACTION_QUIT) return ACTION_QUIT;
if (action.player >= 0)
{
act[action.player] = action.action;
}
i++;
// play
if (i > 10)
{
for (p=0; p<this->nbPlayers; p++)
{
if (this->players[p]->play(act[p]) == 1)
{
this->actionPause(string("Game over !"));
return ACTION_QUIT;
}
act[p] = ACTION_NONE;
}
this->display();
SDL_Delay(20);
i = 0;
}
}
}
Action Game::getAction()
{
Action action;
int ret = ACTION_NONE;
int player = -1;
SDL_Event event;
if (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_WINDOWEVENT:
// Set pause on focus lost
if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)
{
ret = this->actionPause(string("Pause..."));
}
break;
case SDL_QUIT:
ret = ACTION_QUIT;
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
ret = this->actionPause(string("Pause..."));
break;
case SDLK_m:
/* pause music */
if (this->pause == 1)
{
Mix_PlayMusic(this->sound, -1);
this->pause = 0;
}
/* resume music */
else
{
Mix_HaltMusic();
this->pause = 1;
}
ret = ACTION_NONE;
break;
case SDLK_p:
case SDLK_LALT:
ret = this->actionPause(string("Pause..."));
break;
case SDLK_UP:
ret = ACTION_ROTATE;
player = PLAYER_B;
break;
case SDLK_DOWN:
ret = ACTION_MOVE_DOWN;
player = PLAYER_B;
break;
case SDLK_RIGHT:
ret = ACTION_MOVE_RIGHT;
player = PLAYER_B;
break;
case SDLK_LEFT:
ret = ACTION_MOVE_LEFT;
player = PLAYER_B;
break;
case SDLK_RCTRL:
ret = ACTION_DROP;
player = PLAYER_B;
break;
case SDLK_z: // azerty
case SDLK_w: // qwerty
ret = ACTION_ROTATE;
player = PLAYER_A;
break;
case SDLK_s:
ret = ACTION_MOVE_DOWN;
player = PLAYER_A;
break;
case SDLK_d:
ret = ACTION_MOVE_RIGHT;
player = PLAYER_A;
break;
case SDLK_q: // azerty
case SDLK_a: // qwerty
ret = ACTION_MOVE_LEFT;
player = PLAYER_A;
break;
case SDLK_LCTRL:
ret = ACTION_DROP;
player = PLAYER_A;
break;
default:
ret = ACTION_NONE;
break;
}
break;
}
}
// purge events in queue
//while(SDL_PollEvent(&event));
action.action = ret;
action.player = player;
return action;
}
int Game::actionPause(string str)
{
int action = ACTION_NONE;
SDL_Event event;
this->pauseStr = str;
this->display();
// purge events in queue
while(SDL_PollEvent(&event));
// wait for end pause or quit
while(action == ACTION_NONE)
{
SDL_WaitEvent(&event);
switch(event.type)
{
case SDL_QUIT:
action = ACTION_QUIT;
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
action = ACTION_QUIT;
break;
case SDLK_p:
case SDLK_RETURN:
action = ACTION_PAUSE;
break;
case SDLK_m:
/* pause music */
if (this->pause == 1)
{
Mix_PlayMusic(this->sound, -1);
this->pause = 0;
}
/* resume music */
else
{
Mix_HaltMusic();
this->pause = 1;
}
action = ACTION_NONE;
break;
default:
action = ACTION_NONE;
break;
}
break;
}
this->display();
SDL_Delay(50);
}
this->pauseStr = "";
return action;
}
/********************************
accessors
********************************/
/********************************
end accessors
********************************/
<|endoftext|> |
<commit_before>#include "extensions/common/wasm/wasm.h"
#include "common/common/thread.h"
#include "common/common/thread_synchronizer.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/thread_factory_for_test.h"
#include "test/test_common/utility.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/notification.h"
#include "benchmark/benchmark.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tools/cpp/runfiles/runfiles.h"
using bazel::tools::cpp::runfiles::Runfiles;
void bmWasmSpeedTest(benchmark::State& state) {
Envoy::Thread::MutexBasicLockable lock;
Envoy::Logger::Context logging_state(spdlog::level::warn,
Envoy::Logger::Logger::DEFAULT_LOG_FORMAT, lock, false);
Envoy::Logger::Registry::getLog(Envoy::Logger::Id::wasm).set_level(spdlog::level::off);
Envoy::Stats::IsolatedStoreImpl stats_store;
Envoy::Api::ApiPtr api = Envoy::Api::createApiForTest(stats_store);
Envoy::Upstream::MockClusterManager cluster_manager;
Envoy::Event::DispatcherPtr dispatcher(api->allocateDispatcher("wasm_test"));
auto scope = Envoy::Stats::ScopeSharedPtr(stats_store.createScope("wasm."));
auto wasm = std::make_unique<Envoy::Extensions::Common::Wasm::Wasm>(
"envoy.wasm.runtime.null", "", "", "", scope, cluster_manager, *dispatcher);
auto context = std::make_shared<Envoy::Extensions::Common::Wasm::Context>(wasm.get());
Envoy::Thread::ThreadFactory& thread_factory{Envoy::Thread::threadFactoryForTest()};
std::pair<std::string, uint32_t> data;
int n_threads = 10;
for (__attribute__((unused)) auto _ : state) {
auto thread_fn = [&]() {
for (int i = 0; i < 1000000; i++) {
context->getSharedData("foo", &data);
context->setSharedData("foo", "bar", 1);
}
return new uint32_t(42);
};
std::vector<Envoy::Thread::ThreadPtr> threads;
for (int i = 0; i < n_threads; ++i) {
std::string name = absl::StrCat("thread", i);
threads.emplace_back(thread_factory.createThread(thread_fn, Envoy::Thread::Options{name}));
}
for (auto& thread : threads) {
thread->join();
}
}
}
BENCHMARK(bmWasmSpeedTest);
int main(int argc, char** argv) {
::benchmark::Initialize(&argc, argv);
Envoy::TestEnvironment::initializeOptions(argc, argv);
// Create a Runfiles object for runfiles lookup.
// https://github.com/bazelbuild/bazel/blob/master/tools/cpp/runfiles/runfiles_src.h#L32
std::string error;
std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error));
RELEASE_ASSERT(Envoy::TestEnvironment::getOptionalEnvVar("NORUNFILES").has_value() ||
runfiles != nullptr,
error);
Envoy::TestEnvironment::setRunfiles(runfiles.get());
Envoy::TestEnvironment::setEnvVar("ENVOY_IP_TEST_VERSIONS", "all", 0);
Envoy::Event::Libevent::Global::initialize();
if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
return 1;
}
::benchmark::RunSpecifiedBenchmarks();
return 0;
}
<commit_msg>FIx formatting.<commit_after>#include "common/common/thread.h"
#include "common/common/thread_synchronizer.h"
#include "extensions/common/wasm/wasm.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/thread_factory_for_test.h"
#include "test/test_common/utility.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/notification.h"
#include "benchmark/benchmark.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tools/cpp/runfiles/runfiles.h"
using bazel::tools::cpp::runfiles::Runfiles;
namespace Envoy {
void bmWasmSpeedTest(benchmark::State& state) {
Envoy::Thread::MutexBasicLockable lock;
Envoy::Logger::Context logging_state(spdlog::level::warn,
Envoy::Logger::Logger::DEFAULT_LOG_FORMAT, lock, false);
Envoy::Logger::Registry::getLog(Envoy::Logger::Id::wasm).set_level(spdlog::level::off);
Envoy::Stats::IsolatedStoreImpl stats_store;
Envoy::Api::ApiPtr api = Envoy::Api::createApiForTest(stats_store);
Envoy::Upstream::MockClusterManager cluster_manager;
Envoy::Event::DispatcherPtr dispatcher(api->allocateDispatcher("wasm_test"));
auto scope = Envoy::Stats::ScopeSharedPtr(stats_store.createScope("wasm."));
auto wasm = std::make_unique<Envoy::Extensions::Common::Wasm::Wasm>(
"envoy.wasm.runtime.null", "", "", "", scope, cluster_manager, *dispatcher);
auto context = std::make_shared<Envoy::Extensions::Common::Wasm::Context>(wasm.get());
Envoy::Thread::ThreadFactory& thread_factory{Envoy::Thread::threadFactoryForTest()};
std::pair<std::string, uint32_t> data;
int n_threads = 10;
for (__attribute__((unused)) auto _ : state) {
auto thread_fn = [&]() {
for (int i = 0; i < 1000000; i++) {
context->getSharedData("foo", &data);
context->setSharedData("foo", "bar", 1);
}
return new uint32_t(42);
};
std::vector<Envoy::Thread::ThreadPtr> threads;
for (int i = 0; i < n_threads; ++i) {
std::string name = absl::StrCat("thread", i);
threads.emplace_back(thread_factory.createThread(thread_fn, Envoy::Thread::Options{name}));
}
for (auto& thread : threads) {
thread->join();
}
}
}
BENCHMARK(bmWasmSpeedTest);
} // namespace Envoy
int main(int argc, char** argv) {
::benchmark::Initialize(&argc, argv);
Envoy::TestEnvironment::initializeOptions(argc, argv);
// Create a Runfiles object for runfiles lookup.
// https://github.com/bazelbuild/bazel/blob/master/tools/cpp/runfiles/runfiles_src.h#L32
std::string error;
std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error));
RELEASE_ASSERT(Envoy::TestEnvironment::getOptionalEnvVar("NORUNFILES").has_value() ||
runfiles != nullptr,
error);
Envoy::TestEnvironment::setRunfiles(runfiles.get());
Envoy::TestEnvironment::setEnvVar("ENVOY_IP_TEST_VERSIONS", "all", 0);
Envoy::Event::Libevent::Global::initialize();
if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
return 1;
}
::benchmark::RunSpecifiedBenchmarks();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <fc/io/json.hpp>
#include <fc/io/stdio.hpp>
#include <fc/network/http/server.hpp>
#include <fc/network/http/websocket.hpp>
#include <fc/rpc/cli.hpp>
#include <fc/rpc/http_api.hpp>
#include <fc/rpc/websocket_api.hpp>
#include <fc/smart_ref_impl.hpp>
#include <graphene/app/api.hpp>
#include <graphene/chain/protocol/protocol.hpp>
#include <graphene/egenesis/egenesis.hpp>
#include <graphene/utilities/key_conversion.hpp>
#include <graphene/wallet/wallet.hpp>
#include <fc/interprocess/signals.hpp>
#include <boost/program_options.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#ifdef WIN32
# include <signal.h>
#else
# include <csignal>
#endif
using namespace graphene::app;
using namespace graphene::chain;
using namespace graphene::utilities;
using namespace graphene::wallet;
using namespace std;
namespace bpo = boost::program_options;
int main( int argc, char** argv )
{
try {
boost::program_options::options_description opts;
opts.add_options()
("help,h", "Print this help message and exit.")
("server-rpc-endpoint,s", bpo::value<string>()->implicit_value("ws://127.0.0.1:8090"), "Server websocket RPC endpoint")
("server-rpc-user,u", bpo::value<string>(), "Server Username")
("server-rpc-password,p", bpo::value<string>(), "Server Password")
("rpc-endpoint,r", bpo::value<string>()->implicit_value("127.0.0.1:8091"), "Endpoint for wallet websocket RPC to listen on")
("rpc-tls-endpoint,t", bpo::value<string>()->implicit_value("127.0.0.1:8092"), "Endpoint for wallet websocket TLS RPC to listen on")
("rpc-tls-certificate,c", bpo::value<string>()->implicit_value("server.pem"), "PEM certificate for wallet websocket TLS RPC")
("rpc-http-endpoint,H", bpo::value<string>()->implicit_value("127.0.0.1:8093"), "Endpoint for wallet HTTP RPC to listen on")
("daemon,d", "Run the wallet in daemon mode" )
("wallet-file,w", bpo::value<string>()->implicit_value("wallet.json"), "wallet to load")
("chain-id", bpo::value<string>(), "chain ID to connect to");
bpo::variables_map options;
bpo::store( bpo::parse_command_line(argc, argv, opts), options );
if( options.count("help") )
{
std::cout << opts << "\n";
return 0;
}
fc::path data_dir;
fc::logging_config cfg;
fc::path log_dir = data_dir / "logs";
fc::file_appender::config ac;
ac.filename = log_dir / "rpc" / "rpc.log";
ac.flush = true;
ac.rotate = true;
ac.rotation_interval = fc::hours( 1 );
ac.rotation_limit = fc::days( 1 );
std::cout << "Logging RPC to file: " << (data_dir / ac.filename).preferred_string() << "\n";
cfg.appenders.push_back(fc::appender_config( "default", "console", fc::variant(fc::console_appender::config())));
cfg.appenders.push_back(fc::appender_config( "rpc", "file", fc::variant(ac)));
cfg.loggers = { fc::logger_config("default"), fc::logger_config( "rpc") };
cfg.loggers.front().level = fc::log_level::info;
cfg.loggers.front().appenders = {"default"};
cfg.loggers.back().level = fc::log_level::debug;
cfg.loggers.back().appenders = {"rpc"};
//fc::configure_logging( cfg );
fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")));
idump( (key_to_wif( committee_private_key ) ) );
fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan")));
public_key_type nathan_pub_key = nathan_private_key.get_public_key();
idump( (nathan_pub_key) );
idump( (key_to_wif( nathan_private_key ) ) );
//
// TODO: We read wallet_data twice, once in main() to grab the
// socket info, again in wallet_api when we do
// load_wallet_file(). Seems like this could be better
// designed.
//
wallet_data wdata;
fc::path wallet_file( options.count("wallet-file") ? options.at("wallet-file").as<string>() : "wallet.json");
if( fc::exists( wallet_file ) )
{
wdata = fc::json::from_file( wallet_file ).as<wallet_data>();
if( options.count("chain-id") )
{
// the --chain-id on the CLI must match the chain ID embedded in the wallet file
if( chain_id_type(options.at("chain-id").as<std::string>()) != wdata.chain_id )
{
std::cout << "Chain ID in wallet file does not match specified chain ID\n";
return 1;
}
}
}
else
{
if( options.count("chain-id") )
{
wdata.chain_id = chain_id_type(options.at("chain-id").as<std::string>());
std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from CLI)\n";
}
else
{
wdata.chain_id = graphene::egenesis::get_egenesis_chain_id();
std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from egenesis)\n";
}
}
// but allow CLI to override
if( options.count("server-rpc-endpoint") )
wdata.ws_server = options.at("server-rpc-endpoint").as<std::string>();
if( options.count("server-rpc-user") )
wdata.ws_user = options.at("server-rpc-user").as<std::string>();
if( options.count("server-rpc-password") )
wdata.ws_password = options.at("server-rpc-password").as<std::string>();
fc::http::websocket_client client;
idump((wdata.ws_server));
auto con = client.connect( wdata.ws_server );
auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);
auto remote_api = apic->get_remote_api< login_api >(1);
edump((wdata.ws_user)(wdata.ws_password) );
// TODO: Error message here
FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );
auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api );
wapiptr->set_wallet_filename( wallet_file.generic_string() );
wapiptr->load_wallet_file();
fc::api<wallet_api> wapi(wapiptr);
auto wallet_cli = std::make_shared<fc::rpc::cli>();
for( auto& name_formatter : wapiptr->get_result_formatters() )
wallet_cli->format_result( name_formatter.first, name_formatter.second );
boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{
cerr << "Server has disconnected us.\n";
wallet_cli->stop();
}));
(void)(closed_connection);
if( wapiptr->is_new() )
{
std::cout << "Please use the set_password method to initialize a new wallet before continuing\n";
wallet_cli->set_prompt( "new >>> " );
} else
wallet_cli->set_prompt( "locked >>> " );
boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {
wallet_cli->set_prompt( locked ? "locked >>> " : "unlocked >>> " );
}));
auto _websocket_server = std::make_shared<fc::http::websocket_server>();
if( options.count("rpc-endpoint") )
{
_websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){
std::cout << "here... \n";
wlog("." );
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
wsc->register_api(wapi);
c->set_session_data( wsc );
});
ilog( "Listening for incoming RPC requests on ${p}", ("p", options.at("rpc-endpoint").as<string>() ));
_websocket_server->listen( fc::ip::endpoint::from_string(options.at("rpc-endpoint").as<string>()) );
_websocket_server->start_accept();
}
string cert_pem = "server.pem";
if( options.count( "rpc-tls-certificate" ) )
cert_pem = options.at("rpc-tls-certificate").as<string>();
auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem);
if( options.count("rpc-tls-endpoint") )
{
_websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
wsc->register_api(wapi);
c->set_session_data( wsc );
});
ilog( "Listening for incoming TLS RPC requests on ${p}", ("p", options.at("rpc-tls-endpoint").as<string>() ));
_websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at("rpc-tls-endpoint").as<string>()) );
_websocket_tls_server->start_accept();
}
auto _http_server = std::make_shared<fc::http::server>();
if( options.count("rpc-http-endpoint" ) )
{
ilog( "Listening for incoming HTTP RPC requests on ${p}", ("p", options.at("rpc-http-endpoint").as<string>() ) );
_http_server->listen( fc::ip::endpoint::from_string( options.at( "rpc-http-endpoint" ).as<string>() ) );
//
// due to implementation, on_request() must come AFTER listen()
//
_http_server->on_request(
[&]( const fc::http::request& req, const fc::http::server::response& resp )
{
std::shared_ptr< fc::rpc::http_api_connection > conn =
std::make_shared< fc::rpc::http_api_connection>();
conn->register_api( wapi );
conn->on_request( req, resp );
} );
}
if( !options.count( "daemon" ) )
{
wallet_cli->register_api( wapi );
wallet_cli->start();
wallet_cli->wait();
}
else
{
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
fc::set_signal_handler([&exit_promise](int signal) {
exit_promise->set_value(signal);
}, SIGINT);
ilog( "Entering Daemon Mode, ^C to exit" );
exit_promise->wait();
}
wapi->save_wallet_file(wallet_file.generic_string());
locked_connection.disconnect();
closed_connection.disconnect();
}
catch ( const fc::exception& e )
{
std::cout << e.to_detail_string() << "\n";
return -1;
}
return 0;
}
<commit_msg>change default cli_wallet rpc port to 9090<commit_after>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <fc/io/json.hpp>
#include <fc/io/stdio.hpp>
#include <fc/network/http/server.hpp>
#include <fc/network/http/websocket.hpp>
#include <fc/rpc/cli.hpp>
#include <fc/rpc/http_api.hpp>
#include <fc/rpc/websocket_api.hpp>
#include <fc/smart_ref_impl.hpp>
#include <graphene/app/api.hpp>
#include <graphene/chain/protocol/protocol.hpp>
#include <graphene/egenesis/egenesis.hpp>
#include <graphene/utilities/key_conversion.hpp>
#include <graphene/wallet/wallet.hpp>
#include <fc/interprocess/signals.hpp>
#include <boost/program_options.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#ifdef WIN32
# include <signal.h>
#else
# include <csignal>
#endif
using namespace graphene::app;
using namespace graphene::chain;
using namespace graphene::utilities;
using namespace graphene::wallet;
using namespace std;
namespace bpo = boost::program_options;
int main( int argc, char** argv )
{
try {
boost::program_options::options_description opts;
opts.add_options()
("help,h", "Print this help message and exit.")
("server-rpc-endpoint,s", bpo::value<string>()->implicit_value("ws://127.0.0.1:9090"), "Server websocket RPC endpoint")
("server-rpc-user,u", bpo::value<string>(), "Server Username")
("server-rpc-password,p", bpo::value<string>(), "Server Password")
("rpc-endpoint,r", bpo::value<string>()->implicit_value("127.0.0.1:8091"), "Endpoint for wallet websocket RPC to listen on")
("rpc-tls-endpoint,t", bpo::value<string>()->implicit_value("127.0.0.1:8092"), "Endpoint for wallet websocket TLS RPC to listen on")
("rpc-tls-certificate,c", bpo::value<string>()->implicit_value("server.pem"), "PEM certificate for wallet websocket TLS RPC")
("rpc-http-endpoint,H", bpo::value<string>()->implicit_value("127.0.0.1:8093"), "Endpoint for wallet HTTP RPC to listen on")
("daemon,d", "Run the wallet in daemon mode" )
("wallet-file,w", bpo::value<string>()->implicit_value("wallet.json"), "wallet to load")
("chain-id", bpo::value<string>(), "chain ID to connect to");
bpo::variables_map options;
bpo::store( bpo::parse_command_line(argc, argv, opts), options );
if( options.count("help") )
{
std::cout << opts << "\n";
return 0;
}
fc::path data_dir;
fc::logging_config cfg;
fc::path log_dir = data_dir / "logs";
fc::file_appender::config ac;
ac.filename = log_dir / "rpc" / "rpc.log";
ac.flush = true;
ac.rotate = true;
ac.rotation_interval = fc::hours( 1 );
ac.rotation_limit = fc::days( 1 );
std::cout << "Logging RPC to file: " << (data_dir / ac.filename).preferred_string() << "\n";
cfg.appenders.push_back(fc::appender_config( "default", "console", fc::variant(fc::console_appender::config())));
cfg.appenders.push_back(fc::appender_config( "rpc", "file", fc::variant(ac)));
cfg.loggers = { fc::logger_config("default"), fc::logger_config( "rpc") };
cfg.loggers.front().level = fc::log_level::info;
cfg.loggers.front().appenders = {"default"};
cfg.loggers.back().level = fc::log_level::debug;
cfg.loggers.back().appenders = {"rpc"};
//fc::configure_logging( cfg );
fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")));
idump( (key_to_wif( committee_private_key ) ) );
fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan")));
public_key_type nathan_pub_key = nathan_private_key.get_public_key();
idump( (nathan_pub_key) );
idump( (key_to_wif( nathan_private_key ) ) );
//
// TODO: We read wallet_data twice, once in main() to grab the
// socket info, again in wallet_api when we do
// load_wallet_file(). Seems like this could be better
// designed.
//
wallet_data wdata;
fc::path wallet_file( options.count("wallet-file") ? options.at("wallet-file").as<string>() : "wallet.json");
if( fc::exists( wallet_file ) )
{
wdata = fc::json::from_file( wallet_file ).as<wallet_data>();
if( options.count("chain-id") )
{
// the --chain-id on the CLI must match the chain ID embedded in the wallet file
if( chain_id_type(options.at("chain-id").as<std::string>()) != wdata.chain_id )
{
std::cout << "Chain ID in wallet file does not match specified chain ID\n";
return 1;
}
}
}
else
{
if( options.count("chain-id") )
{
wdata.chain_id = chain_id_type(options.at("chain-id").as<std::string>());
std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from CLI)\n";
}
else
{
wdata.chain_id = graphene::egenesis::get_egenesis_chain_id();
std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from egenesis)\n";
}
}
// but allow CLI to override
if( options.count("server-rpc-endpoint") )
wdata.ws_server = options.at("server-rpc-endpoint").as<std::string>();
if( options.count("server-rpc-user") )
wdata.ws_user = options.at("server-rpc-user").as<std::string>();
if( options.count("server-rpc-password") )
wdata.ws_password = options.at("server-rpc-password").as<std::string>();
fc::http::websocket_client client;
idump((wdata.ws_server));
auto con = client.connect( wdata.ws_server );
auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);
auto remote_api = apic->get_remote_api< login_api >(1);
edump((wdata.ws_user)(wdata.ws_password) );
// TODO: Error message here
FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );
auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api );
wapiptr->set_wallet_filename( wallet_file.generic_string() );
wapiptr->load_wallet_file();
fc::api<wallet_api> wapi(wapiptr);
auto wallet_cli = std::make_shared<fc::rpc::cli>();
for( auto& name_formatter : wapiptr->get_result_formatters() )
wallet_cli->format_result( name_formatter.first, name_formatter.second );
boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{
cerr << "Server has disconnected us.\n";
wallet_cli->stop();
}));
(void)(closed_connection);
if( wapiptr->is_new() )
{
std::cout << "Please use the set_password method to initialize a new wallet before continuing\n";
wallet_cli->set_prompt( "new >>> " );
} else
wallet_cli->set_prompt( "locked >>> " );
boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {
wallet_cli->set_prompt( locked ? "locked >>> " : "unlocked >>> " );
}));
auto _websocket_server = std::make_shared<fc::http::websocket_server>();
if( options.count("rpc-endpoint") )
{
_websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){
std::cout << "here... \n";
wlog("." );
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
wsc->register_api(wapi);
c->set_session_data( wsc );
});
ilog( "Listening for incoming RPC requests on ${p}", ("p", options.at("rpc-endpoint").as<string>() ));
_websocket_server->listen( fc::ip::endpoint::from_string(options.at("rpc-endpoint").as<string>()) );
_websocket_server->start_accept();
}
string cert_pem = "server.pem";
if( options.count( "rpc-tls-certificate" ) )
cert_pem = options.at("rpc-tls-certificate").as<string>();
auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem);
if( options.count("rpc-tls-endpoint") )
{
_websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
wsc->register_api(wapi);
c->set_session_data( wsc );
});
ilog( "Listening for incoming TLS RPC requests on ${p}", ("p", options.at("rpc-tls-endpoint").as<string>() ));
_websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at("rpc-tls-endpoint").as<string>()) );
_websocket_tls_server->start_accept();
}
auto _http_server = std::make_shared<fc::http::server>();
if( options.count("rpc-http-endpoint" ) )
{
ilog( "Listening for incoming HTTP RPC requests on ${p}", ("p", options.at("rpc-http-endpoint").as<string>() ) );
_http_server->listen( fc::ip::endpoint::from_string( options.at( "rpc-http-endpoint" ).as<string>() ) );
//
// due to implementation, on_request() must come AFTER listen()
//
_http_server->on_request(
[&]( const fc::http::request& req, const fc::http::server::response& resp )
{
std::shared_ptr< fc::rpc::http_api_connection > conn =
std::make_shared< fc::rpc::http_api_connection>();
conn->register_api( wapi );
conn->on_request( req, resp );
} );
}
if( !options.count( "daemon" ) )
{
wallet_cli->register_api( wapi );
wallet_cli->start();
wallet_cli->wait();
}
else
{
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
fc::set_signal_handler([&exit_promise](int signal) {
exit_promise->set_value(signal);
}, SIGINT);
ilog( "Entering Daemon Mode, ^C to exit" );
exit_promise->wait();
}
wapi->save_wallet_file(wallet_file.generic_string());
locked_connection.disconnect();
closed_connection.disconnect();
}
catch ( const fc::exception& e )
{
std::cout << e.to_detail_string() << "\n";
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <string>
#include <string.h>
#include <csignal>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <functional>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <sstream>
#if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49
#include <regex>
#endif
#include <cassert>
#include <vector>
#include <fstream>
#include <future>
#include <ctime>
#define BUF_SIZE 4096
#define MAX_LISTEN 128
namespace Cappuccino {
class Request;
class Response;
struct {
time_t time;
struct tm *t_st;
int port = 1204;
int sockfd = 0;
int sessionfd = 0;
fd_set mask1fds, mask2fds;
std::shared_ptr<std::string> view_root;
std::shared_ptr<std::string> static_root;
std::unordered_map<std::string,
std::function<Response(std::shared_ptr<Request>)>
> routes;
} context;
namespace Log{
std::string current(){
char timestr[256];
time(&context.time);
strftime(timestr, 255, "%Y-%m-%d %H:%M:%S %Z", localtime(&context.time));
return timestr;
}
static int LogLevel = 0;
static void debug(std::string msg){
if(LogLevel >= 1){
std::cout <<current()<<"[debug] "<< msg << std::endl;
}
}
static void info(std::string msg){
if(LogLevel >= 2){
std::cout <<current()<<"[info] "<< msg << std::endl;
}
}
};
namespace signal_utils{
void signal_handler(int signal){
close(context.sessionfd);
close(context.sockfd);
exit(0);
}
void signal_handler_child(int SignalName){
while(waitpid(-1,NULL,WNOHANG)>0){}
signal(SIGCHLD, signal_utils::signal_handler_child);
}
void init_signal(){
if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){
exit(1);
}
if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){
exit(1);
}
}
}
namespace utils{
std::vector<std::string> split(const std::string& str, std::string delim) noexcept{
std::vector<std::string> result;
std::string::size_type pos = 0;
while(pos != std::string::npos ){
std::string::size_type p = str.find(delim, pos);
if(p == std::string::npos){
result.push_back(str.substr(pos));
break;
}else{
result.push_back(str.substr(pos, p - pos));
}
pos = p + delim.size();
}
return result;
}
};
void init_socket(){
struct sockaddr_in server;
if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
exit(EXIT_FAILURE);
}
memset( &server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(context.port);
char opt = 1;
setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char));
int temp = 1;
if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR,
&temp, sizeof(int))){
}
if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) {
exit(EXIT_FAILURE);
}
if(listen(context.sockfd, MAX_LISTEN) < 0) {
exit(EXIT_FAILURE);
}
FD_ZERO(&context.mask1fds);
FD_SET(context.sockfd, &context.mask1fds);
}
using namespace std;
pair<string,string> openFile(string aFilename){
auto filename = aFilename;
std::ifstream ifs( filename, std::ios::in | std::ios::binary);
if(ifs.fail()){
throw std::runtime_error("No such file or directory \""+ filename +"\"\n");
}
ifs.seekg( 0, std::ios::end);
auto pos = ifs.tellg();
ifs.seekg( 0, std::ios::beg);
std::vector<char> buf(pos);
ifs.read(buf.data(), pos);
string response(buf.cbegin(), buf.cend());
if( response[0] == '\xFF' && response[1] == '\xD8'){
return make_pair(response, "image/jpg");
}else if( response[0] == '\x89' && response[1] == 'P' && response[2] == 'N' && response[3] == 'G'){
return make_pair(response, "image/png");
}else if( response[0] == 'G' && response[1] == 'I' && response[2] == 'F' && response[3] == '8' && (response[4] == '7' || response[4] == '9') && response[2] == 'a'){
return make_pair(response, "image/gif");
}else{
return make_pair(response, "text/html");
}
}
void option(int argc, char *argv[]) noexcept{
char result;
while((result = getopt(argc,argv,"dvp:")) != -1){
switch(result){
case 'd':
Log::LogLevel = 1;
break;
case 'p':
context.port = atoi(optarg);
break;
case 'v':
Log::info("version 0.0.3");
exit(0);
}
}
}
class Request{
unordered_map<string, string> headerset;
unordered_map<string, string> paramset;
public:
Request(string method, string url,string protocol):
method(move(method)),
url(move(url)),
protocol(move(protocol))
{}
const string method;
const string url;
const string protocol;
void addHeader(string key,string value){
headerset[key] = move(value);
}
void addParams(string key,string value){
paramset[key] = move(value);
}
string header(string key){
if(headerset.find(key) == headerset.end())
return "INVALID";
return headerset[key];
}
string params(string key){
if(paramset.find(key) == paramset.end())
return "INVALID";
return paramset[key];
}
};
class Response{
unordered_map<string, string> headerset;
int status_;
string message_;
string url_;
string body_;
string protocol_;
public:
Response(weak_ptr<Request> req){
auto r = req.lock();
if(r){
url_ = r->url;
protocol_ = r->protocol;
}else{
throw std::runtime_error("Request expired!\n");
}
}
Response(int st,string msg,string pro, string bod):
status_(st),
message_(msg),
body_(bod),
protocol_(pro)
{}
Response* message(string msg){
message_ = msg;
return this;
}
Response* status(int st){
status_ = st;
return this;
}
Response* headeer(string key,string val){
if(headerset.find(key)!= headerset.end())
Log::debug(key+" is already setted.");
headerset[key] = val;
return this;
}
Response* file(string filename){
auto file = openFile(*context.view_root + "/" + filename);
body_ = file.first;
headerset["Content-type"] = move(file.second);
return this;
}
operator string(){
return protocol_ + " " + to_string(status_) +" "+ message_ + "\n\n" + body_;
}
};
string createResponse(char* req) noexcept{
auto lines = utils::split(string(req), "\n");
if(lines.empty())
return Response(400, "Bad Request", "HTTP/1.1", "NN");
auto tops = utils::split(lines[0], " ");
if(tops.size() < 3)
return Response(401, "Bad Request", "HTTP/1.1", "NN");
Log::debug(tops[0] +" "+ tops[1] +" "+ tops[2]);
auto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2]));
if(context.routes.find(tops[1]) != context.routes.end()){
return context.routes[tops[1]](move(request));
}
return Response( 404,"Not found", tops[2], "AA");
}
string receiveProcess(int sessionfd){
char buf[BUF_SIZE] = {};
if (recv(sessionfd, buf, sizeof(buf), 0) < 0) {
exit(EXIT_FAILURE);
}
do{
if(strstr(buf, "\r\n")){
break;
}
if (strlen(buf) >= sizeof(buf)) {
memset(&buf, 0, sizeof(buf));
}
}while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0);
return createResponse(buf);
}
void load(string directory, string filename) noexcept{
if(filename == "." || filename == "..") return;
if(filename!="")
directory += "/" + move(filename);
DIR* dir = opendir(directory.c_str());
if(dir != NULL){
struct dirent* dent;
dent = readdir(dir);
while(dent!=NULL){
dent = readdir(dir);
if(dent!=NULL)
load(directory, string(dent->d_name));
}
if(dir!=NULL){
closedir(dir);
//delete dent;
//delete dir;
}
}else{
Log::debug("add "+directory);
context.routes.insert( make_pair(
"/" + directory,
[directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{
return Response(200,"OK","HTTP/1.1",openFile(directory).first);
}
));
}
}
void loadStaticFiles() noexcept{
load(*context.static_root,"");
}
void route(string url,std::function<Response(std::shared_ptr<Request>)> F){
context.routes.insert( make_pair( move(url), move(F) ));
}
void root(string r){
context.view_root = make_shared<string>(move(r));
}
void resource(string s){
context.static_root = make_shared<string>(move(s));
}
void run(){
init_socket();
signal_utils::init_signal();
loadStaticFiles();
int cd[FD_SETSIZE];
struct sockaddr_in client;
int fd;
struct timeval tv;
for(int i = 0;i < FD_SETSIZE; i++){
cd[i] = 0;
}
while(1) {
tv.tv_sec = 0;
tv.tv_usec = 0;
memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds));
int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv);
if(select_result < 1) {
for(fd = 0; fd < FD_SETSIZE; fd++) {
if(cd[fd] == 1) {
close(fd);
FD_CLR(fd, &context.mask1fds);
cd[fd] = 0;
}
}
continue;
}
for(fd = 0; fd < FD_SETSIZE; fd++){
if(FD_ISSET(fd,&context.mask2fds)) {
if(fd == context.sockfd) {
memset( &client, 0, sizeof(client));
int len = sizeof(client);
int clientfd = accept(context.sockfd,
(struct sockaddr *)&client,(socklen_t *) &len);
FD_SET(clientfd, &context.mask1fds);
}else {
if(cd[fd] == 1) {
close(fd);
FD_CLR(fd, &context.mask1fds);
cd[fd] = 0;
} else {
string response = receiveProcess(fd);
write(fd, response.c_str(), response.size());
cd[fd] = 1;
}
}
}
}
}
}
void Cappuccino(int argc, char *argv[]) {
option(argc, argv);
context.view_root = make_shared<string>("");
context.static_root = make_shared<string>("public");
}
};
namespace Cocoa{
using namespace Cappuccino;
using namespace std;
// Unit Test
void testOpenFile(){
auto res = openFile("html/index.html");
auto lines = utils::split(res.first, "\n");
assert(!lines.empty());
}
void testOpenInvalidFile(){
try{
auto res = openFile("html/index");
}catch(std::runtime_error e){
cout<< e.what() << endl;
}
}
};
<commit_msg>[Add] Validate HTTP Version<commit_after>#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <string>
#include <string.h>
#include <csignal>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <functional>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <sstream>
#if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49
#include <regex>
#endif
#include <cassert>
#include <vector>
#include <fstream>
#include <future>
#include <ctime>
#define BUF_SIZE 4096
#define MAX_LISTEN 128
namespace Cappuccino {
class Request;
class Response;
struct {
time_t time;
struct tm *t_st;
int port = 1204;
int sockfd = 0;
int sessionfd = 0;
fd_set mask1fds, mask2fds;
std::shared_ptr<std::string> view_root;
std::shared_ptr<std::string> static_root;
std::unordered_map<std::string,
std::function<Response(std::shared_ptr<Request>)>
> routes;
} context;
namespace Log{
std::string current(){
char timestr[256];
time(&context.time);
strftime(timestr, 255, "%Y-%m-%d %H:%M:%S %Z", localtime(&context.time));
return timestr;
}
static int LogLevel = 0;
static void debug(std::string msg){
if(LogLevel >= 1){
std::cout <<current()<<"[debug] "<< msg << std::endl;
}
}
static void info(std::string msg){
if(LogLevel >= 2){
std::cout <<current()<<"[info] "<< msg << std::endl;
}
}
};
namespace signal_utils{
void signal_handler(int signal){
close(context.sessionfd);
close(context.sockfd);
exit(0);
}
void signal_handler_child(int SignalName){
while(waitpid(-1,NULL,WNOHANG)>0){}
signal(SIGCHLD, signal_utils::signal_handler_child);
}
void init_signal(){
if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){
exit(1);
}
if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){
exit(1);
}
}
}
namespace utils{
std::vector<std::string> split(const std::string& str, std::string delim) noexcept{
std::vector<std::string> result;
std::string::size_type pos = 0;
while(pos != std::string::npos ){
std::string::size_type p = str.find(delim, pos);
if(p == std::string::npos){
result.push_back(str.substr(pos));
break;
}else{
result.push_back(str.substr(pos, p - pos));
}
pos = p + delim.size();
}
return result;
}
};
void init_socket(){
struct sockaddr_in server;
if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
exit(EXIT_FAILURE);
}
memset( &server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(context.port);
char opt = 1;
setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char));
int temp = 1;
if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR,
&temp, sizeof(int))){
}
if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) {
exit(EXIT_FAILURE);
}
if(listen(context.sockfd, MAX_LISTEN) < 0) {
exit(EXIT_FAILURE);
}
FD_ZERO(&context.mask1fds);
FD_SET(context.sockfd, &context.mask1fds);
}
using namespace std;
pair<string,string> openFile(string aFilename){
auto filename = aFilename;
std::ifstream ifs( filename, std::ios::in | std::ios::binary);
if(ifs.fail()){
throw std::runtime_error("No such file or directory \""+ filename +"\"\n");
}
ifs.seekg( 0, std::ios::end);
auto pos = ifs.tellg();
ifs.seekg( 0, std::ios::beg);
std::vector<char> buf(pos);
ifs.read(buf.data(), pos);
string response(buf.cbegin(), buf.cend());
if( response[0] == '\xFF' && response[1] == '\xD8'){
return make_pair(response, "image/jpg");
}else if( response[0] == '\x89' && response[1] == 'P' && response[2] == 'N' && response[3] == 'G'){
return make_pair(response, "image/png");
}else if( response[0] == 'G' && response[1] == 'I' && response[2] == 'F' && response[3] == '8' && (response[4] == '7' || response[4] == '9') && response[2] == 'a'){
return make_pair(response, "image/gif");
}else{
return make_pair(response, "text/html");
}
}
void option(int argc, char *argv[]) noexcept{
char result;
while((result = getopt(argc,argv,"dvp:")) != -1){
switch(result){
case 'd':
Log::LogLevel = 1;
break;
case 'p':
context.port = atoi(optarg);
break;
case 'v':
Log::info("version 0.0.3");
exit(0);
}
}
}
class Request{
map<string, string> headerset;
map<string, string> paramset;
bool correctRequest;
public:
Request(string method, string url,string protocol):
method(move(method)),
url(move(url)),
protocol(move(protocol))
{
correctRequest = validateHttpVersion(protocol);
}
const string method;
const string url;
const string protocol;
// HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
bool validateHttpVersion(string v){
if(v.size() < 5) return false;
if(v[0] != 'H' || v[1] != 'T' ||
v[2] != 'T' || v[3] != 'P') return false;
if(v[4] != '/') return false;
for(int i=5;i < v.size();i++){
if(!isdigit(v[i]) && v[i] != '.') return false;
}
return true;
}
void addHeader(string key,string value){
headerset[key] = move(value);
}
void addParams(string key,string value){
paramset[key] = move(value);
}
string header(string key){
if(headerset.find(key) == headerset.end())
return "INVALID";
return headerset[key];
}
string params(string key){
if(paramset.find(key) == paramset.end())
return "INVALID";
return paramset[key];
}
};
class Response{
unordered_map<string, string> headerset;
int status_;
string message_;
string url_;
string body_;
string protocol_;
public:
Response(weak_ptr<Request> req){
auto r = req.lock();
if(r){
url_ = r->url;
protocol_ = r->protocol;
}else{
throw std::runtime_error("Request expired!\n");
}
}
Response(int st,string msg,string pro, string bod):
status_(st),
message_(msg),
body(bod),
protocol(pro)
{}
Response* message(string msg){
message_ = msg;
return this;
}
Response* status(int st){
status_ = st;
return this;
}
Response* headeer(string key,string val){
if(headerset.find(key)!= headerset.end())
Log::debug(key+" is already setted.");
headerset[key] = val;
return this;
}
Response* file(string filename){
auto file = openFile(*context.view_root + "/" + filename);
body_ = file.first;
headerset["Content-type"] = move(file.second);
return this;
}
operator string(){
return protocol_ + " " + to_string(status_) +" "+ message_ + "\n\n" + body_;
}
};
string createResponse(char* req) noexcept{
auto lines = utils::split(string(req), "\n");
if(lines.empty())
return Response(400, "Bad Request", "HTTP/1.1", "NN");
auto tops = utils::split(lines[0], " ");
if(tops.size() < 3)
return Response(401, "Bad Request", "HTTP/1.1", "NN");
Log::debug(tops[0] +" "+ tops[1] +" "+ tops[2]);
auto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2]));
if(context.routes.find(tops[1]) != context.routes.end()){
return context.routes[tops[1]](move(request));
}
return Response( 404,"Not found", tops[2], "AA");
}
string receiveProcess(int sessionfd){
char buf[BUF_SIZE] = {};
if (recv(sessionfd, buf, sizeof(buf), 0) < 0) {
exit(EXIT_FAILURE);
}
do{
if(strstr(buf, "\r\n")){
break;
}
if (strlen(buf) >= sizeof(buf)) {
memset(&buf, 0, sizeof(buf));
}
}while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0);
return createResponse(buf);
}
void load(string directory, string filename) noexcept{
if(filename == "." || filename == "..") return;
if(filename!="")
directory += "/" + move(filename);
DIR* dir = opendir(directory.c_str());
if(dir != NULL){
struct dirent* dent;
dent = readdir(dir);
while(dent!=NULL){
dent = readdir(dir);
if(dent!=NULL)
load(directory, string(dent->d_name));
}
if(dir!=NULL){
closedir(dir);
//delete dent;
//delete dir;
}
}else{
Log::debug("add "+directory);
context.routes.insert( make_pair(
"/" + directory,
[directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{
return Response(200,"OK","HTTP/1.1",openFile(directory).first);
}
));
}
}
void loadStaticFiles() noexcept{
load(*context.static_root,"");
}
void route(string url,std::function<Response(std::shared_ptr<Request>)> F){
context.routes.insert( make_pair( move(url), move(F) ));
}
void root(string r){
context.view_root = make_shared<string>(move(r));
}
void resource(string s){
context.static_root = make_shared<string>(move(s));
}
void run(){
init_socket();
signal_utils::init_signal();
loadStaticFiles();
int cd[FD_SETSIZE];
struct sockaddr_in client;
int fd;
struct timeval tv;
for(int i = 0;i < FD_SETSIZE; i++){
cd[i] = 0;
}
while(1) {
tv.tv_sec = 0;
tv.tv_usec = 0;
memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds));
int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv);
if(select_result < 1) {
for(fd = 0; fd < FD_SETSIZE; fd++) {
if(cd[fd] == 1) {
close(fd);
FD_CLR(fd, &context.mask1fds);
cd[fd] = 0;
}
}
continue;
}
for(fd = 0; fd < FD_SETSIZE; fd++){
if(FD_ISSET(fd,&context.mask2fds)) {
if(fd == context.sockfd) {
memset( &client, 0, sizeof(client));
int len = sizeof(client);
int clientfd = accept(context.sockfd,
(struct sockaddr *)&client,(socklen_t *) &len);
FD_SET(clientfd, &context.mask1fds);
}else {
if(cd[fd] == 1) {
close(fd);
FD_CLR(fd, &context.mask1fds);
cd[fd] = 0;
} else {
string response = receiveProcess(fd);
write(fd, response.c_str(), response.size());
cd[fd] = 1;
}
}
}
}
}
}
void Cappuccino(int argc, char *argv[]) {
option(argc, argv);
context.view_root = make_shared<string>("");
context.static_root = make_shared<string>("public");
}
};
namespace Cocoa{
using namespace Cappuccino;
using namespace std;
// Unit Test
void testOpenFile(){
auto res = openFile("html/index.html");
auto lines = utils::split(res.first, "\n");
assert(!lines.empty());
}
void testOpenInvalidFile(){
try{
auto res = openFile("html/index");
}catch(std::runtime_error e){
cout<< e.what() << endl;
}
}
};
<|endoftext|> |
<commit_before>#pragma once
#include <iterator>
// ======================================================================
namespace acmacs
{
template <typename Parent, typename Reference> class iterator
{
public:
using reference = Reference;
using pointer = typename std::add_pointer<Reference>::type;
using value_type = typename std::remove_reference<Reference>::type;
using difference_type = ssize_t;
using iterator_category = std::random_access_iterator_tag;
constexpr iterator& operator++()
{
++mIndex;
return *this;
}
constexpr iterator& operator+=(difference_type n)
{
mIndex += n;
return *this;
}
constexpr iterator& operator-=(difference_type n)
{
mIndex -= n;
return *this;
}
constexpr iterator operator-(difference_type n)
{
iterator temp = *this;
return temp -= n;
}
constexpr difference_type operator-(const iterator& rhs) { return mIndex - rhs.mIndex; }
constexpr bool operator==(const iterator& other) const { return &mParent == &other.mParent && mIndex == other.mIndex; }
constexpr bool operator!=(const iterator& other) const { return &mParent != &other.mParent || mIndex != other.mIndex; }
constexpr reference operator*() { return mParent[mIndex]; }
constexpr size_t index() const { return mIndex; }
constexpr bool operator<(const iterator& rhs) const { return mIndex < rhs.mIndex; }
constexpr bool operator<=(const iterator& rhs) const { return mIndex <= rhs.mIndex; }
constexpr bool operator>(const iterator& rhs) const { return mIndex > rhs.mIndex; }
constexpr bool operator>=(const iterator& rhs) const { return mIndex >= rhs.mIndex; }
private:
iterator(const Parent& aParent, size_t aIndex) : mParent{aParent}, mIndex{aIndex} {}
const Parent& mParent;
size_t mIndex;
friend Parent;
};
} // namespace acmacs
// ======================================================================
// ----------------------------------------------------------------------
// polyfill for std::ostream_joiner of c++17
// #if __cplusplus <= 201500
// clang 8.1 on macOS 10.12
// namespace polyfill
// {
// template <typename Stream, typename _DelimT/* , typename _CharT = char, typename _Traits = char_traits<_CharT> */> class ostream_joiner
// {
// public:
// using char_type = typename Stream::char_type; // _CharT;
// using traits_type = typename Stream::traits_type; //_Traits;
// using iterator_category = std::output_iterator_tag;
// using value_type = void;
// using difference_type = void;
// using pointer = void;
// using reference = void;
// inline ostream_joiner(Stream& __os, const _DelimT& __delimiter)
// // noexcept(is_nothrow_copy_constructible_v<_DelimT>)
// : _M_out(std::addressof(__os)), _M_delim(__delimiter)
// { }
// inline ostream_joiner(Stream& __os, _DelimT&& __delimiter)
// // noexcept(is_nothrow_move_constructible_v<_DelimT>)
// : _M_out(std::addressof(__os)), _M_delim(std::move(__delimiter))
// { }
// template <typename _Tp> inline ostream_joiner& operator=(const _Tp& __value)
// {
// if (!_M_first)
// *_M_out << _M_delim;
// _M_first = false;
// *_M_out << __value;
// return *this;
// }
// ostream_joiner& operator*() noexcept { return *this; }
// ostream_joiner& operator++() noexcept { return *this; }
// ostream_joiner& operator++(int) noexcept { return *this; }
// private:
// Stream* _M_out;
// _DelimT _M_delim;
// bool _M_first = true;
// };
// template <typename Stream, typename _DelimT/* , typename _CharT = char, typename _Traits = char_traits<_CharT> */> inline ostream_joiner<Stream, std::decay_t<_DelimT>> make_ostream_joiner(Stream& __os, _DelimT&& __delimiter)
// {
// return { __os, std::forward<_DelimT>(__delimiter) };
// }
// } // namespace polyfill
// #else
// // gcc 6.2+
// #include <experimental/iterator>
// namespace std
// {
// template<typename _DelimT> using ostream_joiner = experimental::fundamentals_v2::ostream_joiner<_DelimT>;
// }
// #endif
// ======================================================================
// https://internalpointers.com/post/writing-custom-iterators-modern-cpp
// ======================================================================
//
// #include <iterator>
// #include <cstddef>
//
// class Integers
// {
// public:
// struct Iterator
// {
// using iterator_category = std::forward_iterator_tag;
// using difference_type = std::ptrdiff_t;
// using value_type = int;
// using pointer = int*;
// using reference = int&;
//
// Iterator(pointer ptr) : m_ptr(ptr) {}
//
// reference operator*() const { return *m_ptr; }
// pointer operator->() { return m_ptr; }
// Iterator& operator++() { m_ptr++; return *this; }
// Iterator operator++(int) { Iterator tmp = *this; ++(*this); return tmp; }
// friend bool operator== (const Iterator& a, const Iterator& b) { return a.m_ptr == b.m_ptr; };
// friend bool operator!= (const Iterator& a, const Iterator& b) { return a.m_ptr != b.m_ptr; };
//
// private:
// pointer m_ptr;
// };
//
// Iterator begin() { return Iterator(&m_data[0]); }
// Iterator end() { return Iterator(&m_data[200]); }
//
// private:
// int m_data[200];
// };
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>iterator improvement<commit_after>#pragma once
#include <iterator>
// ======================================================================
namespace acmacs
{
template <typename Parent, typename Reference, typename Index = size_t> class iterator
{
public:
using reference = Reference;
using pointer = typename std::add_pointer<Reference>::type;
using value_type = typename std::remove_reference<Reference>::type;
using difference_type = ssize_t;
using iterator_category = std::random_access_iterator_tag;
constexpr iterator& operator++()
{
++mIndex;
return *this;
}
constexpr iterator& operator+=(difference_type n)
{
mIndex += n;
return *this;
}
constexpr iterator& operator-=(difference_type n)
{
mIndex -= n;
return *this;
}
constexpr iterator operator-(difference_type n)
{
iterator temp = *this;
return temp -= n;
}
constexpr difference_type operator-(const iterator& rhs) { return mIndex - rhs.mIndex; }
constexpr bool operator==(const iterator& other) const { return &mParent == &other.mParent && mIndex == other.mIndex; }
constexpr bool operator!=(const iterator& other) const { return &mParent != &other.mParent || mIndex != other.mIndex; }
constexpr reference operator*() { return mParent[mIndex]; }
constexpr Index index() const { return mIndex; }
constexpr bool operator<(const iterator& rhs) const { return mIndex < rhs.mIndex; }
constexpr bool operator<=(const iterator& rhs) const { return mIndex <= rhs.mIndex; }
constexpr bool operator>(const iterator& rhs) const { return mIndex > rhs.mIndex; }
constexpr bool operator>=(const iterator& rhs) const { return mIndex >= rhs.mIndex; }
private:
iterator(const Parent& aParent, Index aIndex) : mParent{aParent}, mIndex{aIndex} {}
const Parent& mParent;
Index mIndex;
friend Parent;
};
} // namespace acmacs
// ======================================================================
// ----------------------------------------------------------------------
// polyfill for std::ostream_joiner of c++17
// #if __cplusplus <= 201500
// clang 8.1 on macOS 10.12
// namespace polyfill
// {
// template <typename Stream, typename _DelimT/* , typename _CharT = char, typename _Traits = char_traits<_CharT> */> class ostream_joiner
// {
// public:
// using char_type = typename Stream::char_type; // _CharT;
// using traits_type = typename Stream::traits_type; //_Traits;
// using iterator_category = std::output_iterator_tag;
// using value_type = void;
// using difference_type = void;
// using pointer = void;
// using reference = void;
// inline ostream_joiner(Stream& __os, const _DelimT& __delimiter)
// // noexcept(is_nothrow_copy_constructible_v<_DelimT>)
// : _M_out(std::addressof(__os)), _M_delim(__delimiter)
// { }
// inline ostream_joiner(Stream& __os, _DelimT&& __delimiter)
// // noexcept(is_nothrow_move_constructible_v<_DelimT>)
// : _M_out(std::addressof(__os)), _M_delim(std::move(__delimiter))
// { }
// template <typename _Tp> inline ostream_joiner& operator=(const _Tp& __value)
// {
// if (!_M_first)
// *_M_out << _M_delim;
// _M_first = false;
// *_M_out << __value;
// return *this;
// }
// ostream_joiner& operator*() noexcept { return *this; }
// ostream_joiner& operator++() noexcept { return *this; }
// ostream_joiner& operator++(int) noexcept { return *this; }
// private:
// Stream* _M_out;
// _DelimT _M_delim;
// bool _M_first = true;
// };
// template <typename Stream, typename _DelimT/* , typename _CharT = char, typename _Traits = char_traits<_CharT> */> inline ostream_joiner<Stream, std::decay_t<_DelimT>> make_ostream_joiner(Stream& __os, _DelimT&& __delimiter)
// {
// return { __os, std::forward<_DelimT>(__delimiter) };
// }
// } // namespace polyfill
// #else
// // gcc 6.2+
// #include <experimental/iterator>
// namespace std
// {
// template<typename _DelimT> using ostream_joiner = experimental::fundamentals_v2::ostream_joiner<_DelimT>;
// }
// #endif
// ======================================================================
// https://internalpointers.com/post/writing-custom-iterators-modern-cpp
// ======================================================================
//
// #include <iterator>
// #include <cstddef>
//
// class Integers
// {
// public:
// struct Iterator
// {
// using iterator_category = std::forward_iterator_tag;
// using difference_type = std::ptrdiff_t;
// using value_type = int;
// using pointer = int*;
// using reference = int&;
//
// Iterator(pointer ptr) : m_ptr(ptr) {}
//
// reference operator*() const { return *m_ptr; }
// pointer operator->() { return m_ptr; }
// Iterator& operator++() { m_ptr++; return *this; }
// Iterator operator++(int) { Iterator tmp = *this; ++(*this); return tmp; }
// friend bool operator== (const Iterator& a, const Iterator& b) { return a.m_ptr == b.m_ptr; };
// friend bool operator!= (const Iterator& a, const Iterator& b) { return a.m_ptr != b.m_ptr; };
//
// private:
// pointer m_ptr;
// };
//
// Iterator begin() { return Iterator(&m_data[0]); }
// Iterator end() { return Iterator(&m_data[200]); }
//
// private:
// int m_data[200];
// };
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "cinder/app/AppBasic.h"
#include "cinder/Rand.h"
#include "NVPTextBox.h"
#include "NVPFont.h"
#include "cinder/params/Params.h"
#include "cinder/Timeline.h"
#include "cinder/gl/TextureFont.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "cinder/Text.h"
using namespace ci;
using namespace ci::app;
class NVPBasicTextSampleApp : public AppBasic {
public:
void prepareSettings( Settings* settings );
void setup();
void draw();
void update();
std::vector<NVPTextBoxRef> mTexts;
NVPTextBoxRef mText2;
bool mSetup;
ci::params::InterfaceGl mParams;
Vec2f mPos;
float mScale;
float mKerning;
float mStrokeWidth;
bool mFill;
bool mUnderline;
bool mDebugFonts;
NVPFontRef mFont;
NVPFontRef mFont2;
std::vector<ci::gl::Texture> mTexs;
};
void NVPBasicTextSampleApp::prepareSettings( Settings* settings )
{
//settings->setFullScreen( true );
settings->setWindowPos(0,0);
settings->setBorderless(true);
settings->setWindowSize(1920,1080);
}
void NVPBasicTextSampleApp::setup()
{
mSetup = false;
mFill = true;
mStrokeWidth = .05f;
mUnderline = true;
mDebugFonts = true;
gl::enableAlphaBlending();
gl::enableDepthRead();
gl::enableDepthWrite();
//hack because nvidia path rendering won't work in setup with glew not initialized?
timeline().add( [this] {
mFont = NVPFont::create(std::string("Arial"));
for(int i=60; i>5; i-=10){
NVPTextBoxRef mText = NVPTextBox::create();
mText->setText("Hello Cinder!");
mText->setFont(mFont);
mText->setDebugDraw(false);
mText->setFontPt(float(i));
mTexts.push_back(mText);
}
mFont2 = NVPFont::create(std::string("Pacifico"));
mText2 = NVPTextBox::create();
mText2->setText("james Bass");
mText2->setFont(mFont2);
mText2->setDebugDraw(true);
mText2->setFontPt(200);
//display Cinder textbox
for(int i=60; i>5; i-=10){
gl::TextureFont::Format f;
ci::gl::TextureFontRef mFontRef = cinder::gl::TextureFont::create( Font( "Arial", float(i) ), f );
TextLayout layout;
layout.setFont(mFontRef->getFont() );
layout.setColor(Color::white() );
layout.addLine( "Hello Cinder!" );
mTexs.push_back(gl::Texture( layout.render(true,false) ));
}
mSetup = true;
},timeline().getCurrentTime()+.01f);
mPos = Vec2f(105.f,108.f);
mScale = 1.f;
mParams = ci::params::InterfaceGl( "Parameters", Vec2i( 250, 500 ) );
mKerning = 1.00f;
mParams.addParam( "posx", &mPos.x );
mParams.addParam( "posy", &mPos.y );
mParams.addParam( "kerning", &mKerning,"min=0.0000 max=2.000 step=.0001" );
mParams.addParam( "fill", &mFill);
mParams.addParam( "underline", &mUnderline);
mParams.addParam( "debug fonts", &mDebugFonts);
mParams.addParam( "stroke width", &mStrokeWidth,"min=0.0000 max=2.000 step=.001" );
}
void NVPBasicTextSampleApp::update()
{
if(mSetup){
mFont2->setStrokeWidth(mStrokeWidth);
mText2->setKerning(mKerning);
mText2->setUnderline(mUnderline);
mText2->setFilling(mFill);
mText2->setKerning(mKerning);
mText2->setDebugDraw(mDebugFonts);
}
}
void NVPBasicTextSampleApp::draw()
{
gl::clear( Color( 0, 0.1f, 0.2f ) );
if(mSetup){
gl::setViewport( getWindowBounds() );
gl::setMatricesWindow( getWindowWidth(), getWindowHeight() );
gl::pushMatrices();
float yOffset = 0;
gl::translate(mPos);
for(auto mText : mTexts){
mText->draw(Vec2f(300,yOffset));
yOffset+=60;
}
gl::popMatrices();
mText2->draw(Vec2f(200,700.f));
gl::color(Color::white());
gl::translate(100,0);
for(auto mTex : mTexs){
if(mTex)
gl::translate(0,60);
gl::draw(mTex);
}
mParams.draw();
}
}
CINDER_APP_BASIC( NVPBasicTextSampleApp, RendererGl(RendererGl::AA_MSAA_32 ))<commit_msg>initialize extension loading<commit_after>#include "cinder/app/AppBasic.h"
#include "cinder/Rand.h"
#include "NVPTextBox.h"
#include "NVPFont.h"
#include "cinder/params/Params.h"
#include "cinder/Timeline.h"
#include "cinder/gl/TextureFont.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "cinder/Text.h"
using namespace ci;
using namespace ci::app;
class NVPBasicTextSampleApp : public AppBasic {
public:
void prepareSettings( Settings* settings );
void setup();
void draw();
void update();
std::vector<NVPTextBoxRef> mTexts;
NVPTextBoxRef mText2;
bool mSetup;
ci::params::InterfaceGl mParams;
Vec2f mPos;
float mScale;
float mKerning;
float mStrokeWidth;
bool mFill;
bool mUnderline;
bool mDebugFonts;
NVPFontRef mFont;
NVPFontRef mFont2;
std::vector<ci::gl::Texture> mTexs;
};
void NVPBasicTextSampleApp::prepareSettings( Settings* settings )
{
//settings->setFullScreen( true );
settings->setWindowPos(0,0);
settings->setBorderless(true);
settings->setWindowSize(1920,1080);
}
void NVPBasicTextSampleApp::setup()
{
initializeNVPR("");
mSetup = false;
mFill = true;
mStrokeWidth = .05f;
mUnderline = true;
mDebugFonts = true;
gl::enableAlphaBlending();
gl::enableDepthRead();
gl::enableDepthWrite();
//hack because nvidia path rendering won't work in setup with glew not initialized?
timeline().add( [this] {
mFont = NVPFont::create(std::string("Arial"));
for(int i=60; i>5; i-=10){
NVPTextBoxRef mText = NVPTextBox::create();
mText->setText("Hello Cinder!");
mText->setFont(mFont);
mText->setDebugDraw(false);
mText->setFontPt(float(i));
mTexts.push_back(mText);
}
mFont2 = NVPFont::create(std::string("Pacifico"));
mText2 = NVPTextBox::create();
mText2->setText("james Bass");
mText2->setFont(mFont2);
mText2->setDebugDraw(true);
mText2->setFontPt(200);
//display Cinder textbox
for(int i=60; i>5; i-=10){
gl::TextureFont::Format f;
ci::gl::TextureFontRef mFontRef = cinder::gl::TextureFont::create( Font( "Arial", float(i) ), f );
TextLayout layout;
layout.setFont(mFontRef->getFont() );
layout.setColor(Color::white() );
layout.addLine( "Hello Cinder!" );
mTexs.push_back(gl::Texture( layout.render(true,false) ));
}
mSetup = true;
},timeline().getCurrentTime()+.01f);
mPos = Vec2f(105.f,108.f);
mScale = 1.f;
mParams = ci::params::InterfaceGl( "Parameters", Vec2i( 250, 500 ) );
mKerning = 1.00f;
mParams.addParam( "posx", &mPos.x );
mParams.addParam( "posy", &mPos.y );
mParams.addParam( "kerning", &mKerning,"min=0.0000 max=2.000 step=.0001" );
mParams.addParam( "fill", &mFill);
mParams.addParam( "underline", &mUnderline);
mParams.addParam( "debug fonts", &mDebugFonts);
mParams.addParam( "stroke width", &mStrokeWidth,"min=0.0000 max=2.000 step=.001" );
}
void NVPBasicTextSampleApp::update()
{
if(mSetup){
mFont2->setStrokeWidth(mStrokeWidth);
mText2->setKerning(mKerning);
mText2->setUnderline(mUnderline);
mText2->setFilling(mFill);
mText2->setKerning(mKerning);
mText2->setDebugDraw(mDebugFonts);
}
}
void NVPBasicTextSampleApp::draw()
{
gl::clear( Color( 0, 0.1f, 0.2f ) );
if(mSetup){
gl::setViewport( getWindowBounds() );
gl::setMatricesWindow( getWindowWidth(), getWindowHeight() );
gl::pushMatrices();
float yOffset = 0;
gl::translate(mPos);
for(auto mText : mTexts){
mText->draw(Vec2f(300,yOffset));
yOffset+=60;
}
gl::popMatrices();
mText2->draw(Vec2f(200,700.f));
gl::color(Color::white());
gl::translate(100,0);
for(auto mTex : mTexs){
if(mTex)
gl::translate(0,60);
gl::draw(mTex);
}
mParams.draw();
}
}
CINDER_APP_BASIC( NVPBasicTextSampleApp, RendererGl(RendererGl::AA_MSAA_32 ))<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsSlideFunction.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:07:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "controller/SlsSlideFunction.hxx"
#include "SlideSorterViewShell.hxx"
#include "controller/SlideSorterController.hxx"
#include "view/SlideSorterView.hxx"
#include "model/SlideSorterModel.hxx"
namespace sd { namespace slidesorter { namespace controller {
TYPEINIT1(SlideFunction, FuPoor);
SlideFunction::SlideFunction (
SlideSorterController& rController,
SfxRequest& rRequest)
: FuPoor (
&rController.GetViewShell(),
rController.GetView().GetWindow(),
& rController.GetView(),
rController.GetModel().GetDocument(),
rRequest)
{
}
FunctionReference SlideFunction::Create( SlideSorterController& rController, SfxRequest& rRequest )
{
FunctionReference xFunc( new SlideFunction( rController, rRequest ) );
return xFunc;
}
void SlideFunction::ScrollStart (void)
{
}
void SlideFunction::ScrollEnd (void)
{
}
BOOL SlideFunction::MouseMove(const MouseEvent& rMEvt)
{
return FALSE;
}
BOOL SlideFunction::MouseButtonUp(const MouseEvent& rMEvt)
{
return FALSE;
}
BOOL SlideFunction::MouseButtonDown(const MouseEvent& rMEvt)
{
return FALSE;
}
} } } // end of namespace ::sd::slidesorter::controller
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.38); FILE MERGED 2006/11/22 12:42:12 cl 1.5.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsSlideFunction.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2006-12-12 18:32:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "controller/SlsSlideFunction.hxx"
#include "SlideSorterViewShell.hxx"
#include "controller/SlideSorterController.hxx"
#include "view/SlideSorterView.hxx"
#include "model/SlideSorterModel.hxx"
namespace sd { namespace slidesorter { namespace controller {
TYPEINIT1(SlideFunction, FuPoor);
SlideFunction::SlideFunction (
SlideSorterController& rController,
SfxRequest& rRequest)
: FuPoor (
&rController.GetViewShell(),
rController.GetView().GetWindow(),
& rController.GetView(),
rController.GetModel().GetDocument(),
rRequest)
{
}
FunctionReference SlideFunction::Create( SlideSorterController& rController, SfxRequest& rRequest )
{
FunctionReference xFunc( new SlideFunction( rController, rRequest ) );
return xFunc;
}
void SlideFunction::ScrollStart (void)
{
}
void SlideFunction::ScrollEnd (void)
{
}
BOOL SlideFunction::MouseMove(const MouseEvent& )
{
return FALSE;
}
BOOL SlideFunction::MouseButtonUp(const MouseEvent& )
{
return FALSE;
}
BOOL SlideFunction::MouseButtonDown(const MouseEvent& )
{
return FALSE;
}
} } } // end of namespace ::sd::slidesorter::controller
<|endoftext|> |
<commit_before>#include "Version.h"
#include "SourceControl.h"
#include "System/Config.h"
#include "System/Events/EventLoop.h"
#include "System/IO/IOProcessor.h"
#include "System/Service.h"
#include "System/FileSystem.h"
#include "System/CrashReporter.h"
#include "Framework/Storage/BloomFilter.h"
#include "Application/Common/ContextTransport.h"
#include "Application/ConfigServer/ConfigServerApp.h"
#include "Application/ShardServer/ShardServerApp.h"
#define IDENT "ScalienDB"
const char PRODUCT_STRING[] = IDENT " v" VERSION_STRING " " PLATFORM_STRING;
const char BUILD_DATE[] = "Build date: " __DATE__ " " __TIME__;
static void InitLog();
static void ParseArgs(int argc, char** argv);
static void SetupServiceIdentity(ServiceIdentity& ident);
static void RunMain(int argc, char** argv);
static void RunApplication();
static void ConfigureSystemSettings();
static bool IsController();
static void InitContextTransport();
static void LogPrintVersion(bool isController);
static void CrashReporterCallback();
// the application object is global for debugging purposes
static Application* app;
static bool restoreMode = false;
static bool setNodeID = false;
static uint64_t nodeID = 0;
int main(int argc, char** argv)
{
SetMemoryLeakReports();
try
{
// crash reporter messes up the debugging on Windows
#ifndef DEBUG
CrashReporter::SetCallback(CFunc(CrashReporterCallback));
#endif
RunMain(argc, argv);
}
catch (std::bad_alloc& e)
{
UNUSED(e);
STOP_FAIL(1, "Out of memory error");
}
catch (std::exception& e)
{
STOP_FAIL(1, "Unexpected exception happened (%s)", e.what());
}
catch (...)
{
STOP_FAIL(1, "Unexpected exception happened");
}
ReportMemoryLeaks();
return 0;
}
static void RunMain(int argc, char** argv)
{
ServiceIdentity identity;
ParseArgs(argc, argv);
if (argc < 2)
STOP_FAIL(1, "Config file argument not given");
if (!configFile.Init(argv[1]))
STOP_FAIL(1, "Invalid config file (%s)", argv[1]);
InitLog();
// HACK: this is called twice, because command line arguments may override log settings
ParseArgs(argc, argv);
SetupServiceIdentity(identity);
Service::Main(argc, argv, RunApplication, identity);
}
static void RunApplication()
{
bool isController;
StartClock();
ConfigureSystemSettings();
IOProcessor::Init(configFile.GetIntValue("io.maxfd", 32768));
InitContextTransport();
BloomFilter::StaticInit();
isController = IsController();
LogPrintVersion(isController);
if (isController)
app = new ConfigServerApp(restoreMode);
else
app = new ShardServerApp(restoreMode, setNodeID, nodeID);
Service::SetStatus(SERVICE_STATUS_RUNNING);
app->Init();
IOProcessor::BlockSignals(IOPROCESSOR_BLOCK_ALL);
EventLoop::Init();
EventLoop::Run();
Service::SetStatus(SERVICE_STATUS_STOP_PENDING);
Log_Message("Shutting down...");
EventLoop::Shutdown();
app->Shutdown();
delete app;
IOProcessor::Shutdown();
StopClock();
configFile.Shutdown();
Registry::Shutdown();
// This is here and not the end of main(), because logging may be turned off by then
Log_Message(IDENT " exited normally");
Log_Shutdown();
}
static void SetupServiceIdentity(ServiceIdentity& identity)
{
// set up service identity based on role
if (IsController())
{
identity.name = "ScalienController";
identity.displayName = "Scalien Database Controller";
identity.description = "Provides and stores metadata for Scalien Database cluster";
}
else
{
identity.name = "ScalienShardServer";
identity.displayName = "Scalien Database Shard Server";
identity.description = "Provides reliable and replicated data storage for Scalien Database cluster";
}
}
static void InitLog()
{
int logTargets;
bool debug;
#ifdef DEBUG
debug = true;
#else
debug = false;
#endif
logTargets = 0;
if (configFile.GetListNum("log.targets") == 0)
logTargets = LOG_TARGET_STDOUT;
for (int i = 0; i < configFile.GetListNum("log.targets"); i++)
{
if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0)
{
logTargets |= LOG_TARGET_FILE;
Log_SetOutputFile(configFile.GetValue("log.file", NULL),
configFile.GetBoolValue("log.truncate", false));
}
if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0)
logTargets |= LOG_TARGET_STDOUT;
if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0)
logTargets |= LOG_TARGET_STDERR;
}
Log_SetTarget(logTargets);
Log_SetTrace(configFile.GetBoolValue("log.trace", false));
Log_SetDebug(configFile.GetBoolValue("log.debug", debug));
Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false));
Log_SetAutoFlush(configFile.GetBoolValue("log.autoFlush", true));
Log_SetMaxSize(configFile.GetIntValue("log.maxSize", 100*1000*1000) / (1000 * 1000));
Log_SetTraceBufferSize(configFile.GetIntValue("log.traceBufferSize", 0));
Log_SetFlushInterval(configFile.GetIntValue("log.flushInterval", 0) * 1000);
}
static void ParseDebugArgs(char* arg)
{
bool pause = false;
switch (arg[0])
{
case 'X':
// Do not exit on error or assert
SetExitOnError(false);
SetAssertCritical(false);
break;
case 'P':
// Pause execution while debugger is attaching
// Once the debugger is attached, change the value of pause to false
pause = true;
while (pause)
MSleep(1000); // <- Put debugger breakpoint this line
break;
}
}
static void ParseArgs(int argc, char** argv)
{
ReadBuffer arg;
for (int i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
switch (argv[i][1])
{
case 't':
Log_SetTrace(true);
break;
case 'D':
// Debugging options
ParseDebugArgs(&argv[i][2]);
break;
case 'v':
STOP("%s", PRODUCT_STRING);
break;
case 'r':
restoreMode = true;
break;
case 'n':
setNodeID = true;
i++;
arg.Wrap(argv[i]);
arg.Readf("%U", &nodeID);
break;
case 'h':
STOP("Usage:\n"
"\n"
" %s config-file [options] [service-options]\n"
"\n"
"Options:\n"
"\n"
" -v: print version number and exit\n"
" -r: start server in restore mode\n"
" -t: turn trace mode on\n"
" -h: print this help\n"
"\n"
"Service options (mutually exclusive):\n"
"\n"
" --install: install service\n"
" --reinstall: reinstall service\n"
" --uninstall: uninstall server\n"
, argv[0]);
break;
}
}
}
}
static void ConfigureSystemSettings()
{
int memLimitPerc;
uint64_t memLimit;
uint64_t maxFileCacheSize;
const char* dir;
// percentage of physical memory can be used by the program
memLimitPerc = configFile.GetIntValue("system.memoryLimitPercentage", 90);
if (memLimitPerc < 0)
memLimitPerc = 90;
// memoryLimit overrides memoryLimitPercentage
memLimit = configFile.GetInt64Value("system.memoryLimit", 0);
if (memLimit == 0)
memLimit = (uint64_t) (GetTotalPhysicalMemory() * memLimit / 100.0 + 0.5);
if (memLimit != 0)
SetMemoryLimit(memLimit);
// Set the maximum size of file system cache used by the OS.
// This is needed on Windows, because it has _really_ dumb cache allocation strategy,
// that totally kills IO intensive applications like databases.
// For more, see:
// http://blogs.msdn.com/b/ntdebugging/archive/2009/02/06/microsoft-windows-dynamic-cache-service.aspx
maxFileCacheSize = configFile.GetInt64Value("system.maxFileCacheSize", 0);
if (maxFileCacheSize != 0)
SetMaxFileCacheSize(maxFileCacheSize);
*(Registry::GetUintPtr("system.maxFileCacheSize")) = maxFileCacheSize;
// set the base directory
dir = configFile.GetValue("dir", NULL);
if (dir)
{
if (!FS_ChangeDir(dir))
STOP_FAIL(1, "Cannot change to dir: %s", dir);
// setting the base dir may affect the location of the log file
InitLog();
}
// set exit on error: this is how ASSERTs are handled in release build
SetExitOnError(true);
// this must be called here, because the first value it returns might be unreliable
GetTotalCpuUsage();
SeedRandom();
}
static bool IsController()
{
const char* role;
role = configFile.GetValue("role", "");
if (role == NULL)
STOP_FAIL(1, "Missing \"role\" in config file!");
if (strcmp(role, "controller") == 0)
return true;
else
return false;
}
static void InitContextTransport()
{
const char* str;
Endpoint endpoint;
// set my endpoint
str = configFile.GetValue("endpoint", "");
if (str == NULL)
STOP_FAIL(1, "Missing \"endpoint\" in config file!");
if (!endpoint.Set(str, true))
STOP_FAIL(1, "Bad endpoint format in config file!");
CONTEXT_TRANSPORT->Init(endpoint);
}
static void LogPrintVersion(bool isController)
{
Log_Message("%s started as %s", PRODUCT_STRING,
isController ? "CONTROLLER" : "SHARD SERVER");
Log_Message("Pid: %U", GetProcessID());
Log_Message("%s", BUILD_DATE);
Log_Message("Branch: %s", SOURCE_CONTROL_BRANCH);
Log_Message("Source control version: %s", SOURCE_CONTROL_VERSION);
Log_Message("================================================================");
}
static void CrashReporterCallback()
{
const char* msg;
// We need to be careful here, because by the time the control gets here the stack and the heap
// may already be corrupted. Therefore there must not be any heap allocations here, but unfortunately
// stack allocations cannot be avoided.
// When rotating the log there is heap allocation. To prevent it, we turn off log rotation ASAP.
Log_SetMaxSize(0);
CrashReporter::ReportSystemEvent(IDENT);
// Generate report and send it to log and standard error
msg = CrashReporter::GetReport();
Log_SetTarget(Log_GetTarget() | LOG_TARGET_STDERR | LOG_TARGET_FILE);
Log_Message("%s", msg);
IFDEBUG(ASSERT_FAIL());
_exit(1);
}
<commit_msg>Changed SetMemoryLeakReports location in Main.<commit_after>#include "Version.h"
#include "SourceControl.h"
#include "System/Config.h"
#include "System/Events/EventLoop.h"
#include "System/IO/IOProcessor.h"
#include "System/Service.h"
#include "System/FileSystem.h"
#include "System/CrashReporter.h"
#include "Framework/Storage/BloomFilter.h"
#include "Application/Common/ContextTransport.h"
#include "Application/ConfigServer/ConfigServerApp.h"
#include "Application/ShardServer/ShardServerApp.h"
#define IDENT "ScalienDB"
const char PRODUCT_STRING[] = IDENT " v" VERSION_STRING " " PLATFORM_STRING;
const char BUILD_DATE[] = "Build date: " __DATE__ " " __TIME__;
static void InitLog();
static void ParseArgs(int argc, char** argv);
static void SetupServiceIdentity(ServiceIdentity& ident);
static void RunMain(int argc, char** argv);
static void RunApplication();
static void ConfigureSystemSettings();
static bool IsController();
static void InitContextTransport();
static void LogPrintVersion(bool isController);
static void CrashReporterCallback();
// the application object is global for debugging purposes
static Application* app;
static bool restoreMode = false;
static bool setNodeID = false;
static uint64_t nodeID = 0;
int main(int argc, char** argv)
{
try
{
// crash reporter messes up the debugging on Windows
#ifndef DEBUG
CrashReporter::SetCallback(CFunc(CrashReporterCallback));
#endif
RunMain(argc, argv);
}
catch (std::bad_alloc& e)
{
UNUSED(e);
STOP_FAIL(1, "Out of memory error");
}
catch (std::exception& e)
{
STOP_FAIL(1, "Unexpected exception happened (%s)", e.what());
}
catch (...)
{
STOP_FAIL(1, "Unexpected exception happened");
}
ReportMemoryLeaks();
return 0;
}
static void RunMain(int argc, char** argv)
{
ServiceIdentity identity;
ParseArgs(argc, argv);
if (argc < 2)
STOP_FAIL(1, "Config file argument not given");
if (!configFile.Init(argv[1]))
STOP_FAIL(1, "Invalid config file (%s)", argv[1]);
InitLog();
// HACK: this is called twice, because command line arguments may override log settings
ParseArgs(argc, argv);
SetupServiceIdentity(identity);
Service::Main(argc, argv, RunApplication, identity);
}
static void RunApplication()
{
bool isController;
StartClock();
ConfigureSystemSettings();
IOProcessor::Init(configFile.GetIntValue("io.maxfd", 32768));
InitContextTransport();
BloomFilter::StaticInit();
isController = IsController();
LogPrintVersion(isController);
if (isController)
app = new ConfigServerApp(restoreMode);
else
app = new ShardServerApp(restoreMode, setNodeID, nodeID);
Service::SetStatus(SERVICE_STATUS_RUNNING);
app->Init();
IOProcessor::BlockSignals(IOPROCESSOR_BLOCK_ALL);
EventLoop::Init();
EventLoop::Run();
Service::SetStatus(SERVICE_STATUS_STOP_PENDING);
Log_Message("Shutting down...");
EventLoop::Shutdown();
app->Shutdown();
delete app;
IOProcessor::Shutdown();
StopClock();
configFile.Shutdown();
Registry::Shutdown();
// This is here and not the end of main(), because logging may be turned off by then
Log_Message(IDENT " exited normally");
Log_Shutdown();
}
static void SetupServiceIdentity(ServiceIdentity& identity)
{
// set up service identity based on role
if (IsController())
{
identity.name = "ScalienController";
identity.displayName = "Scalien Database Controller";
identity.description = "Provides and stores metadata for Scalien Database cluster";
}
else
{
identity.name = "ScalienShardServer";
identity.displayName = "Scalien Database Shard Server";
identity.description = "Provides reliable and replicated data storage for Scalien Database cluster";
}
}
static void InitLog()
{
int logTargets;
bool debug;
#ifdef DEBUG
debug = true;
#else
debug = false;
#endif
logTargets = 0;
if (configFile.GetListNum("log.targets") == 0)
logTargets = LOG_TARGET_STDOUT;
for (int i = 0; i < configFile.GetListNum("log.targets"); i++)
{
if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0)
{
logTargets |= LOG_TARGET_FILE;
Log_SetOutputFile(configFile.GetValue("log.file", NULL),
configFile.GetBoolValue("log.truncate", false));
}
if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0)
logTargets |= LOG_TARGET_STDOUT;
if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0)
logTargets |= LOG_TARGET_STDERR;
}
Log_SetTarget(logTargets);
Log_SetTrace(configFile.GetBoolValue("log.trace", false));
Log_SetDebug(configFile.GetBoolValue("log.debug", debug));
Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false));
Log_SetAutoFlush(configFile.GetBoolValue("log.autoFlush", true));
Log_SetMaxSize(configFile.GetIntValue("log.maxSize", 100*1000*1000) / (1000 * 1000));
Log_SetTraceBufferSize(configFile.GetIntValue("log.traceBufferSize", 0));
Log_SetFlushInterval(configFile.GetIntValue("log.flushInterval", 0) * 1000);
}
static void ParseDebugArgs(char* arg)
{
bool pause = false;
switch (arg[0])
{
case 'X':
// Do not exit on error or assert
SetExitOnError(false);
SetAssertCritical(false);
break;
case 'P':
// Pause execution while debugger is attaching
// Once the debugger is attached, change the value of pause to false
pause = true;
while (pause)
MSleep(1000); // <- Put debugger breakpoint this line
break;
}
}
static void ParseArgs(int argc, char** argv)
{
ReadBuffer arg;
for (int i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
switch (argv[i][1])
{
case 't':
Log_SetTrace(true);
break;
case 'D':
// Debugging options
ParseDebugArgs(&argv[i][2]);
break;
case 'v':
STOP("%s", PRODUCT_STRING);
break;
case 'r':
restoreMode = true;
break;
case 'n':
setNodeID = true;
i++;
arg.Wrap(argv[i]);
arg.Readf("%U", &nodeID);
break;
case 'h':
STOP("Usage:\n"
"\n"
" %s config-file [options] [service-options]\n"
"\n"
"Options:\n"
"\n"
" -v: print version number and exit\n"
" -r: start server in restore mode\n"
" -t: turn trace mode on\n"
" -h: print this help\n"
"\n"
"Service options (mutually exclusive):\n"
"\n"
" --install: install service\n"
" --reinstall: reinstall service\n"
" --uninstall: uninstall server\n"
, argv[0]);
break;
}
}
}
}
static void ConfigureSystemSettings()
{
int memLimitPerc;
uint64_t memLimit;
uint64_t maxFileCacheSize;
const char* dir;
// percentage of physical memory can be used by the program
memLimitPerc = configFile.GetIntValue("system.memoryLimitPercentage", 90);
if (memLimitPerc < 0)
memLimitPerc = 90;
// memoryLimit overrides memoryLimitPercentage
memLimit = configFile.GetInt64Value("system.memoryLimit", 0);
if (memLimit == 0)
memLimit = (uint64_t) (GetTotalPhysicalMemory() * memLimit / 100.0 + 0.5);
if (memLimit != 0)
SetMemoryLimit(memLimit);
// Set the maximum size of file system cache used by the OS.
// This is needed on Windows, because it has _really_ dumb cache allocation strategy,
// that totally kills IO intensive applications like databases.
// For more, see:
// http://blogs.msdn.com/b/ntdebugging/archive/2009/02/06/microsoft-windows-dynamic-cache-service.aspx
maxFileCacheSize = configFile.GetInt64Value("system.maxFileCacheSize", 0);
if (maxFileCacheSize != 0)
SetMaxFileCacheSize(maxFileCacheSize);
*(Registry::GetUintPtr("system.maxFileCacheSize")) = maxFileCacheSize;
// set the base directory
dir = configFile.GetValue("dir", NULL);
if (dir)
{
if (!FS_ChangeDir(dir))
STOP_FAIL(1, "Cannot change to dir: %s", dir);
// setting the base dir may affect the location of the log file
InitLog();
}
// set exit on error: this is how ASSERTs are handled in release build
SetExitOnError(true);
// this must be called here, because the first value it returns might be unreliable
GetTotalCpuUsage();
SeedRandom();
SetMemoryLeakReports();
}
static bool IsController()
{
const char* role;
role = configFile.GetValue("role", "");
if (role == NULL)
STOP_FAIL(1, "Missing \"role\" in config file!");
if (strcmp(role, "controller") == 0)
return true;
else
return false;
}
static void InitContextTransport()
{
const char* str;
Endpoint endpoint;
// set my endpoint
str = configFile.GetValue("endpoint", "");
if (str == NULL)
STOP_FAIL(1, "Missing \"endpoint\" in config file!");
if (!endpoint.Set(str, true))
STOP_FAIL(1, "Bad endpoint format in config file!");
CONTEXT_TRANSPORT->Init(endpoint);
}
static void LogPrintVersion(bool isController)
{
Log_Message("%s started as %s", PRODUCT_STRING,
isController ? "CONTROLLER" : "SHARD SERVER");
Log_Message("Pid: %U", GetProcessID());
Log_Message("%s", BUILD_DATE);
Log_Message("Branch: %s", SOURCE_CONTROL_BRANCH);
Log_Message("Source control version: %s", SOURCE_CONTROL_VERSION);
Log_Message("================================================================");
}
static void CrashReporterCallback()
{
const char* msg;
// We need to be careful here, because by the time the control gets here the stack and the heap
// may already be corrupted. Therefore there must not be any heap allocations here, but unfortunately
// stack allocations cannot be avoided.
// When rotating the log there is heap allocation. To prevent it, we turn off log rotation ASAP.
Log_SetMaxSize(0);
CrashReporter::ReportSystemEvent(IDENT);
// Generate report and send it to log and standard error
msg = CrashReporter::GetReport();
Log_SetTarget(Log_GetTarget() | LOG_TARGET_STDERR | LOG_TARGET_FILE);
Log_Message("%s", msg);
IFDEBUG(ASSERT_FAIL());
_exit(1);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <vector>
#include <boost/dynamic_bitset.hpp>
/**
* Lessons learned so far:
* - SIMD registers are used as soon as we compile with -03
* - If we want to get the real speed up (and use all SIMD registers by unfolding both loops,
* we have to know both, input-size and number of comparisons, at compile time.
* - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to
* code optimized with 02.
* - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd
* - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp
*/
typedef std::mt19937 Engine;
typedef std::uniform_int_distribution<unsigned> Intdistr;
template <typename T, typename U>
void smaller (const T *input, U outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; ++m) {
outputs[m*array_size+i] = input[i] < comparison_values[m];
}
}
}
//template <typename T>
//void pretty_print (T *arr, unsigned size, std::string s = "Pretty Print") {
// std::cout << s << ":" << std::endl;
// for (auto r = arr; r < arr+size; ++r ) {
// std::cout << *r << std::endl;
// }
//}
template <typename T>
void fill (T *arr, unsigned size) {
Engine engine (0);
Intdistr distr (0, 100000);
for (auto r = arr; r < arr+size; ++r ) {
*r = distr(engine);
}
}
int main (int argc, char *argv[]) {
typedef unsigned TestType;
static constexpr unsigned repetitions = 100;
constexpr unsigned input_size = 1000000;
constexpr unsigned comparisons = 3;
// if (argc != 3)
// {
// std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl;
// return -1;
// }
// unsigned long input_size = std::stoi(argv[1]);
// unsigned comparisons = std::stoi(argv[2]);
std::cout << "input size: " << input_size << std::endl;
std::cout << "comparisons :" << comparisons<< std::endl;
TestType test_input [input_size];
fill(test_input, input_size);
// pretty_print(test_input, input_size, "Input");
TestType comparison_values [comparisons];
for (unsigned c = 0; c < comparisons; ++c) {
comparison_values[c] = test_input[c];
}
// pretty_print(comparison_values, comparisons, "Comparison values");
bool results [comparisons * input_size];
// std::vector<bool> results (comparisons * input_size);
// boost::dynamic_bitset<> results(comparisons * input_size);
auto start = std::chrono::high_resolution_clock::now();
for (unsigned i = 0; i < repetitions; ++i)
smaller(test_input, results, comparison_values, input_size, comparisons);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Avg Time [microsecs]: "
<< (std::chrono::duration_cast<std::chrono::microseconds>(end-start).count())
/((double)repetitions)
<< std::endl;
// for (unsigned c = 0; c < comparisons; ++c) {
// pretty_print(&results[c*input_size], input_size, "Result");
// }
return 0;
}
<commit_msg>finished simd experiments for all-same-operator (smaller)<commit_after>#include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include <numeric>
/**
* Lessons learned so far:
* - SIMD registers are used as soon as we compile with -03
* - If we want to get the real speed up (and use all SIMD registers by unfolding both loops,
* we have to know both, input-size and number of comparisons, at compile time.
* - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to
* code optimized with 02.
* - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd
* - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp
*/
typedef std::mt19937 Engine;
typedef std::uniform_int_distribution<unsigned> Intdistr;
template <typename T, typename U>
void smaller (const T *input, U outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; ++m) {
outputs[m*array_size+i] = (float) (input[i] < comparison_values[m]);
}
}
}
template <typename T>
void pretty_print (T *arr, unsigned size, std::string s = "Pretty Print") {
std::cout << s << ":" << std::endl;
for (auto r = arr; r < arr+size; ++r ) {
std::cout << *r << std::endl;
}
}
template <typename T>
void compute_stats(const std::vector<T> stats, double &mean, double &stdev) {
double sum = std::accumulate(stats.begin(), stats.end(), 0.0);
mean = sum / stats.size();
std::vector<double> diff(stats.size());
std::transform(stats.begin(), stats.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
stdev = std::sqrt(sq_sum / stats.size());
}
template <typename T>
void fill (T *arr, unsigned size) {
Engine engine (0);
Intdistr distr (0, 100000);
for (auto r = arr; r < arr+size; ++r ) {
*r = distr(engine);
}
}
int main (int argc, char *argv[]) {
//**** PARAMS ****/
typedef unsigned TestType;
static constexpr unsigned repetitions = 10000;
// constexpr unsigned input_size = 500000;
constexpr unsigned comparisons = 1;
// if (argc != 3)
// {
// std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl;
// return -1;
// }
unsigned long input_size = std::stoi(argv[1]);
// unsigned comparisons = std::stoi(argv[2]);
std::cout << "input size: " << input_size << std::endl;
std::cout << "comparisons: " << comparisons<< std::endl;
//**** INPUT ****/
TestType test_input [input_size];
fill(test_input, input_size);
// pretty_print(test_input, input_size, "Input");
TestType comparison_values [comparisons];
for (unsigned c = 0; c < comparisons; ++c) {
comparison_values[c] = test_input[c];
}
// pretty_print(comparison_values, comparisons, "Comparison values");
//**** COMPUTE ****/
std::vector<unsigned long> stats (repetitions);
bool results [comparisons * input_size];
// std::vector<bool> results (comparisons * input_size);
// boost::dynamic_bitset<> results(comparisons * input_size);
for (unsigned i = 0; i < repetitions; ++i) {
auto start = std::chrono::high_resolution_clock::now();
smaller(test_input, results, comparison_values, input_size, comparisons);
auto end = std::chrono::high_resolution_clock::now();
stats [i] =
std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
}
//**** REPORT ****/
double mean, stdev;
compute_stats(stats, mean, stdev);
std::cout
// << "Avg Time [microsecs]: "
<< mean
<< "\t"
// << "(+/- "
<< stdev
// << ")"
<< std::endl;
// pretty_print(stats.data(), repetitions, "Stats");
// for (unsigned c = 0; c < comparisons; ++c) {
// pretty_print(&results[c*input_size], input_size, "Result");
// }
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 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 "modules/audio_processing/aec3/echo_path_delay_estimator.h"
#include <algorithm>
#include <string>
#include "api/audio/echo_canceller3_config.h"
#include "modules/audio_processing/aec3/aec3_common.h"
#include "modules/audio_processing/aec3/render_delay_buffer.h"
#include "modules/audio_processing/logging/apm_data_dumper.h"
#include "modules/audio_processing/test/echo_canceller_test_tools.h"
#include "rtc_base/random.h"
#include "rtc_base/strings/string_builder.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
std::string ProduceDebugText(size_t delay, size_t down_sampling_factor) {
rtc::StringBuilder ss;
ss << "Delay: " << delay;
ss << ", Down sampling factor: " << down_sampling_factor;
return ss.Release();
}
} // namespace
class EchoPathDelayEstimatorMultiChannel
: public ::testing::Test,
public ::testing::WithParamInterface<std::tuple<size_t, size_t>> {};
INSTANTIATE_TEST_SUITE_P(MultiChannel,
EchoPathDelayEstimatorMultiChannel,
::testing::Combine(::testing::Values(1, 2, 3, 6, 8),
::testing::Values(1, 2, 4)));
// Verifies that the basic API calls work.
TEST_P(EchoPathDelayEstimatorMultiChannel, BasicApiCalls) {
const size_t num_render_channels = std::get<0>(GetParam());
const size_t num_capture_channels = std::get<1>(GetParam());
constexpr int kSampleRateHz = 48000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
ApmDataDumper data_dumper(0);
EchoCanceller3Config config;
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, kSampleRateHz, num_render_channels));
EchoPathDelayEstimator estimator(&data_dumper, config, num_capture_channels);
std::vector<std::vector<std::vector<float>>> render(
kNumBands, std::vector<std::vector<float>>(
num_render_channels, std::vector<float>(kBlockSize)));
std::vector<std::vector<float>> capture(num_capture_channels,
std::vector<float>(kBlockSize));
for (size_t k = 0; k < 100; ++k) {
render_delay_buffer->Insert(render);
estimator.EstimateDelay(render_delay_buffer->GetDownsampledRenderBuffer(),
capture);
}
}
// Verifies that the delay estimator produces correct delay for artificially
// delayed signals.
TEST(EchoPathDelayEstimator, DelayEstimation) {
constexpr size_t kNumRenderChannels = 1;
constexpr size_t kNumCaptureChannels = 1;
constexpr int kSampleRateHz = 48000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
Random random_generator(42U);
std::vector<std::vector<std::vector<float>>> render(
kNumBands, std::vector<std::vector<float>>(
kNumRenderChannels, std::vector<float>(kBlockSize)));
std::vector<std::vector<float>> capture(kNumCaptureChannels,
std::vector<float>(kBlockSize));
ApmDataDumper data_dumper(0);
constexpr size_t kDownSamplingFactors[] = {2, 4, 8};
for (auto down_sampling_factor : kDownSamplingFactors) {
EchoCanceller3Config config;
config.delay.down_sampling_factor = down_sampling_factor;
config.delay.num_filters = 10;
for (size_t delay_samples : {30, 64, 150, 200, 800, 4000}) {
SCOPED_TRACE(ProduceDebugText(delay_samples, down_sampling_factor));
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, kSampleRateHz, kNumRenderChannels));
DelayBuffer<float> signal_delay_buffer(delay_samples);
EchoPathDelayEstimator estimator(&data_dumper, config,
kNumCaptureChannels);
absl::optional<DelayEstimate> estimated_delay_samples;
for (size_t k = 0; k < (500 + (delay_samples) / kBlockSize); ++k) {
RandomizeSampleVector(&random_generator, render[0][0]);
signal_delay_buffer.Delay(render[0][0], capture[0]);
render_delay_buffer->Insert(render);
if (k == 0) {
render_delay_buffer->Reset();
}
render_delay_buffer->PrepareCaptureProcessing();
auto estimate = estimator.EstimateDelay(
render_delay_buffer->GetDownsampledRenderBuffer(), capture);
if (estimate) {
estimated_delay_samples = estimate;
}
}
if (estimated_delay_samples) {
// Allow estimated delay to be off by one sample in the down-sampled
// domain.
size_t delay_ds = delay_samples / down_sampling_factor;
size_t estimated_delay_ds =
estimated_delay_samples->delay / down_sampling_factor;
EXPECT_NEAR(delay_ds, estimated_delay_ds, 1);
} else {
ADD_FAILURE();
}
}
}
}
// Verifies that the delay estimator does not produce delay estimates for render
// signals of low level.
TEST(EchoPathDelayEstimator, NoDelayEstimatesForLowLevelRenderSignals) {
constexpr size_t kNumRenderChannels = 1;
constexpr size_t kNumCaptureChannels = 1;
constexpr int kSampleRateHz = 48000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
Random random_generator(42U);
EchoCanceller3Config config;
std::vector<std::vector<std::vector<float>>> render(
kNumBands, std::vector<std::vector<float>>(
kNumRenderChannels, std::vector<float>(kBlockSize)));
std::vector<std::vector<float>> capture(kNumCaptureChannels,
std::vector<float>(kBlockSize));
ApmDataDumper data_dumper(0);
EchoPathDelayEstimator estimator(&data_dumper, config, kNumCaptureChannels);
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(EchoCanceller3Config(), kSampleRateHz,
kNumRenderChannels));
for (size_t k = 0; k < 100; ++k) {
RandomizeSampleVector(&random_generator, render[0][0]);
for (auto& render_k : render[0][0]) {
render_k *= 100.f / 32767.f;
}
std::copy(render[0][0].begin(), render[0][0].end(), capture[0].begin());
render_delay_buffer->Insert(render);
render_delay_buffer->PrepareCaptureProcessing();
EXPECT_FALSE(estimator.EstimateDelay(
render_delay_buffer->GetDownsampledRenderBuffer(), capture));
}
}
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
// Verifies the check for the render blocksize.
// TODO(peah): Re-enable the test once the issue with memory leaks during DEATH
// tests on test bots has been fixed.
TEST(EchoPathDelayEstimator, DISABLED_WrongRenderBlockSize) {
ApmDataDumper data_dumper(0);
EchoCanceller3Config config;
EchoPathDelayEstimator estimator(&data_dumper, config, 1);
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, 48000, 1));
std::vector<std::vector<float>> capture(1, std::vector<float>(kBlockSize));
EXPECT_DEATH(estimator.EstimateDelay(
render_delay_buffer->GetDownsampledRenderBuffer(), capture),
"");
}
// Verifies the check for the capture blocksize.
// TODO(peah): Re-enable the test once the issue with memory leaks during DEATH
// tests on test bots has been fixed.
TEST(EchoPathDelayEstimator, WrongCaptureBlockSize) {
ApmDataDumper data_dumper(0);
EchoCanceller3Config config;
EchoPathDelayEstimator estimator(&data_dumper, config, 1);
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, 48000, 1));
std::vector<std::vector<float>> capture(1,
std::vector<float>(kBlockSize - 1));
EXPECT_DEATH(estimator.EstimateDelay(
render_delay_buffer->GetDownsampledRenderBuffer(), capture),
"");
}
// Verifies the check for non-null data dumper.
TEST(EchoPathDelayEstimator, NullDataDumper) {
EXPECT_DEATH(EchoPathDelayEstimator(nullptr, EchoCanceller3Config(), 1), "");
}
#endif
} // namespace webrtc
<commit_msg>Rename EchoPathDelayEstimator to EchoPathDelayEstimatorDeathTest.<commit_after>/*
* Copyright (c) 2017 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 "modules/audio_processing/aec3/echo_path_delay_estimator.h"
#include <algorithm>
#include <string>
#include "api/audio/echo_canceller3_config.h"
#include "modules/audio_processing/aec3/aec3_common.h"
#include "modules/audio_processing/aec3/render_delay_buffer.h"
#include "modules/audio_processing/logging/apm_data_dumper.h"
#include "modules/audio_processing/test/echo_canceller_test_tools.h"
#include "rtc_base/random.h"
#include "rtc_base/strings/string_builder.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
std::string ProduceDebugText(size_t delay, size_t down_sampling_factor) {
rtc::StringBuilder ss;
ss << "Delay: " << delay;
ss << ", Down sampling factor: " << down_sampling_factor;
return ss.Release();
}
} // namespace
class EchoPathDelayEstimatorMultiChannel
: public ::testing::Test,
public ::testing::WithParamInterface<std::tuple<size_t, size_t>> {};
INSTANTIATE_TEST_SUITE_P(MultiChannel,
EchoPathDelayEstimatorMultiChannel,
::testing::Combine(::testing::Values(1, 2, 3, 6, 8),
::testing::Values(1, 2, 4)));
// Verifies that the basic API calls work.
TEST_P(EchoPathDelayEstimatorMultiChannel, BasicApiCalls) {
const size_t num_render_channels = std::get<0>(GetParam());
const size_t num_capture_channels = std::get<1>(GetParam());
constexpr int kSampleRateHz = 48000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
ApmDataDumper data_dumper(0);
EchoCanceller3Config config;
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, kSampleRateHz, num_render_channels));
EchoPathDelayEstimator estimator(&data_dumper, config, num_capture_channels);
std::vector<std::vector<std::vector<float>>> render(
kNumBands, std::vector<std::vector<float>>(
num_render_channels, std::vector<float>(kBlockSize)));
std::vector<std::vector<float>> capture(num_capture_channels,
std::vector<float>(kBlockSize));
for (size_t k = 0; k < 100; ++k) {
render_delay_buffer->Insert(render);
estimator.EstimateDelay(render_delay_buffer->GetDownsampledRenderBuffer(),
capture);
}
}
// Verifies that the delay estimator produces correct delay for artificially
// delayed signals.
TEST(EchoPathDelayEstimator, DelayEstimation) {
constexpr size_t kNumRenderChannels = 1;
constexpr size_t kNumCaptureChannels = 1;
constexpr int kSampleRateHz = 48000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
Random random_generator(42U);
std::vector<std::vector<std::vector<float>>> render(
kNumBands, std::vector<std::vector<float>>(
kNumRenderChannels, std::vector<float>(kBlockSize)));
std::vector<std::vector<float>> capture(kNumCaptureChannels,
std::vector<float>(kBlockSize));
ApmDataDumper data_dumper(0);
constexpr size_t kDownSamplingFactors[] = {2, 4, 8};
for (auto down_sampling_factor : kDownSamplingFactors) {
EchoCanceller3Config config;
config.delay.down_sampling_factor = down_sampling_factor;
config.delay.num_filters = 10;
for (size_t delay_samples : {30, 64, 150, 200, 800, 4000}) {
SCOPED_TRACE(ProduceDebugText(delay_samples, down_sampling_factor));
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, kSampleRateHz, kNumRenderChannels));
DelayBuffer<float> signal_delay_buffer(delay_samples);
EchoPathDelayEstimator estimator(&data_dumper, config,
kNumCaptureChannels);
absl::optional<DelayEstimate> estimated_delay_samples;
for (size_t k = 0; k < (500 + (delay_samples) / kBlockSize); ++k) {
RandomizeSampleVector(&random_generator, render[0][0]);
signal_delay_buffer.Delay(render[0][0], capture[0]);
render_delay_buffer->Insert(render);
if (k == 0) {
render_delay_buffer->Reset();
}
render_delay_buffer->PrepareCaptureProcessing();
auto estimate = estimator.EstimateDelay(
render_delay_buffer->GetDownsampledRenderBuffer(), capture);
if (estimate) {
estimated_delay_samples = estimate;
}
}
if (estimated_delay_samples) {
// Allow estimated delay to be off by one sample in the down-sampled
// domain.
size_t delay_ds = delay_samples / down_sampling_factor;
size_t estimated_delay_ds =
estimated_delay_samples->delay / down_sampling_factor;
EXPECT_NEAR(delay_ds, estimated_delay_ds, 1);
} else {
ADD_FAILURE();
}
}
}
}
// Verifies that the delay estimator does not produce delay estimates for render
// signals of low level.
TEST(EchoPathDelayEstimator, NoDelayEstimatesForLowLevelRenderSignals) {
constexpr size_t kNumRenderChannels = 1;
constexpr size_t kNumCaptureChannels = 1;
constexpr int kSampleRateHz = 48000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
Random random_generator(42U);
EchoCanceller3Config config;
std::vector<std::vector<std::vector<float>>> render(
kNumBands, std::vector<std::vector<float>>(
kNumRenderChannels, std::vector<float>(kBlockSize)));
std::vector<std::vector<float>> capture(kNumCaptureChannels,
std::vector<float>(kBlockSize));
ApmDataDumper data_dumper(0);
EchoPathDelayEstimator estimator(&data_dumper, config, kNumCaptureChannels);
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(EchoCanceller3Config(), kSampleRateHz,
kNumRenderChannels));
for (size_t k = 0; k < 100; ++k) {
RandomizeSampleVector(&random_generator, render[0][0]);
for (auto& render_k : render[0][0]) {
render_k *= 100.f / 32767.f;
}
std::copy(render[0][0].begin(), render[0][0].end(), capture[0].begin());
render_delay_buffer->Insert(render);
render_delay_buffer->PrepareCaptureProcessing();
EXPECT_FALSE(estimator.EstimateDelay(
render_delay_buffer->GetDownsampledRenderBuffer(), capture));
}
}
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
// Verifies the check for the render blocksize.
// TODO(peah): Re-enable the test once the issue with memory leaks during DEATH
// tests on test bots has been fixed.
TEST(EchoPathDelayEstimatorDeathTest, DISABLED_WrongRenderBlockSize) {
ApmDataDumper data_dumper(0);
EchoCanceller3Config config;
EchoPathDelayEstimator estimator(&data_dumper, config, 1);
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, 48000, 1));
std::vector<std::vector<float>> capture(1, std::vector<float>(kBlockSize));
EXPECT_DEATH(estimator.EstimateDelay(
render_delay_buffer->GetDownsampledRenderBuffer(), capture),
"");
}
// Verifies the check for the capture blocksize.
// TODO(peah): Re-enable the test once the issue with memory leaks during DEATH
// tests on test bots has been fixed.
TEST(EchoPathDelayEstimatorDeathTest, WrongCaptureBlockSize) {
ApmDataDumper data_dumper(0);
EchoCanceller3Config config;
EchoPathDelayEstimator estimator(&data_dumper, config, 1);
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, 48000, 1));
std::vector<std::vector<float>> capture(1,
std::vector<float>(kBlockSize - 1));
EXPECT_DEATH(estimator.EstimateDelay(
render_delay_buffer->GetDownsampledRenderBuffer(), capture),
"");
}
// Verifies the check for non-null data dumper.
TEST(EchoPathDelayEstimatorDeathTest, NullDataDumper) {
EXPECT_DEATH(EchoPathDelayEstimator(nullptr, EchoCanceller3Config(), 1), "");
}
#endif
} // namespace webrtc
<|endoftext|> |
<commit_before>#include <sys/time.h>
#include <ctime>
#include <cerrno>
#include "../utils/utils.hpp"
double walltime() {
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1)
fatalx(errno, "gettimeofday failed");
return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
}
double cputime() {
return clock() / CLOCKS_PER_SEC;
}
<commit_msg>utils: fix cputime computation.<commit_after>#include <sys/time.h>
#include <ctime>
#include <cerrno>
#include "../utils/utils.hpp"
double walltime() {
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1)
fatalx(errno, "gettimeofday failed");
return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
}
double cputime() {
return clock() / (double) CLOCKS_PER_SEC;
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "precompiled.h"
#include "core.h"
QString SystemCommandResult::stdoutOneLine() const {
Q_ASSERT(stdout_.size() == 1);
return stdout_.first();
}
SystemCommandResult::operator QString() const
{
Q_ASSERT(exitCode() == 0);
Q_ASSERT(stderr_.size() == 0);
return stdoutOneLine();
}
SystemCommandResult::operator QStringList() const
{
Q_ASSERT(exitCode() == 0);
Q_ASSERT(stderr_.size() == 0);
return stdout_;
}
SystemCommandResult runSystemCommand(const QString& program, const QStringList& arguments,
const QString& workingDirectory)
{
QProcess process;
process.setProgram(program);
if (!arguments.isEmpty()) process.setArguments(arguments);
if (!workingDirectory.isNull()) process.setWorkingDirectory(workingDirectory);
process.start();
process.waitForFinished();
SystemCommandResult result;
result.exitCode_ = process.exitCode();
auto EOLRegex = QRegularExpression("(\\r\\n|\\r|\\n)");
result.stdout_ = QString(process.readAllStandardOutput()).split(EOLRegex);
if (!result.stdout_.isEmpty() && result.stdout_.last().isEmpty()) result.stdout_.removeLast();
result.stderr_ = QString(process.readAllStandardError()).split(EOLRegex);
if (!result.stderr_.isEmpty() && result.stderr_.last().isEmpty()) result.stderr_.removeLast();
return result;
}
<commit_msg>remove unused include<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "precompiled.h"
QString SystemCommandResult::stdoutOneLine() const {
Q_ASSERT(stdout_.size() == 1);
return stdout_.first();
}
SystemCommandResult::operator QString() const
{
Q_ASSERT(exitCode() == 0);
Q_ASSERT(stderr_.size() == 0);
return stdoutOneLine();
}
SystemCommandResult::operator QStringList() const
{
Q_ASSERT(exitCode() == 0);
Q_ASSERT(stderr_.size() == 0);
return stdout_;
}
SystemCommandResult runSystemCommand(const QString& program, const QStringList& arguments,
const QString& workingDirectory)
{
QProcess process;
process.setProgram(program);
if (!arguments.isEmpty()) process.setArguments(arguments);
if (!workingDirectory.isNull()) process.setWorkingDirectory(workingDirectory);
process.start();
process.waitForFinished();
SystemCommandResult result;
result.exitCode_ = process.exitCode();
auto EOLRegex = QRegularExpression("(\\r\\n|\\r|\\n)");
result.stdout_ = QString(process.readAllStandardOutput()).split(EOLRegex);
if (!result.stdout_.isEmpty() && result.stdout_.last().isEmpty()) result.stdout_.removeLast();
result.stderr_ = QString(process.readAllStandardError()).split(EOLRegex);
if (!result.stderr_.isEmpty() && result.stderr_.last().isEmpty()) result.stderr_.removeLast();
return result;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 - Decho Corp.
#include "mordor/pch.h"
#include "broker.h"
#include "mordor/streams/pipe.h"
#include "mordor/streams/socket.h"
#include "mordor/streams/ssl.h"
#include "proxy.h"
namespace Mordor {
namespace HTTP {
RequestBroker::ptr defaultRequestBroker(IOManager *ioManager,
Scheduler *scheduler,
ConnectionBroker::ptr *connBroker)
{
StreamBroker::ptr socketBroker(new SocketStreamBroker(ioManager, scheduler));
StreamBrokerFilter::ptr sslBroker(new SSLStreamBroker(socketBroker));
ConnectionCache::ptr connectionBroker(new ConnectionCache(sslBroker));
if (connBroker != NULL)
*connBroker = connectionBroker;
RequestBroker::ptr requestBroker(new BaseRequestBroker(connectionBroker));
socketBroker.reset(new ProxyStreamBroker(socketBroker, requestBroker));
sslBroker->parent(StreamBroker::weak_ptr(socketBroker));
connectionBroker.reset(new ProxyConnectionBroker(connectionBroker));
requestBroker.reset(new BaseRequestBroker(connectionBroker));
return requestBroker;
}
StreamBroker::ptr
StreamBrokerFilter::parent()
{
if (m_parent)
return m_parent;
return StreamBroker::ptr(m_weakParent);
}
Stream::ptr
SocketStreamBroker::getStream(const URI &uri)
{
if (m_cancelled)
MORDOR_THROW_EXCEPTION(OperationAbortedException());
MORDOR_ASSERT(uri.authority.hostDefined());
MORDOR_ASSERT(uri.authority.portDefined() || uri.schemeDefined());
std::ostringstream os;
os << uri.authority.host();
if (uri.authority.portDefined())
os << ":" << uri.authority.port();
else if (uri.schemeDefined())
os << ":" << uri.scheme();
std::vector<Address::ptr> addresses;
{
SchedulerSwitcher switcher(m_scheduler);
addresses = Address::lookup(os.str(), AF_UNSPEC, SOCK_STREAM);
}
Socket::ptr socket;
for (std::vector<Address::ptr>::const_iterator it(addresses.begin());
it != addresses.end();
) {
if (m_ioManager)
socket = (*it)->createSocket(*m_ioManager);
else
socket = (*it)->createSocket();
std::list<Socket::ptr>::iterator it2;
{
boost::mutex::scoped_lock lock(m_mutex);
if (m_cancelled)
MORDOR_THROW_EXCEPTION(OperationAbortedException());
m_pending.push_back(socket);
it2 = m_pending.end();
--it2;
}
socket->sendTimeout(connectTimeout);
try {
socket->connect(*it);
socket->sendTimeout(sendTimeout);
socket->receiveTimeout(receiveTimeout);
boost::mutex::scoped_lock lock(m_mutex);
m_pending.erase(it2);
break;
} catch (...) {
boost::mutex::scoped_lock lock(m_mutex);
m_pending.erase(it2);
if (++it == addresses.end())
throw;
}
}
Stream::ptr stream(new SocketStream(socket));
return stream;
}
void
SocketStreamBroker::cancelPending()
{
boost::mutex::scoped_lock lock(m_mutex);
m_cancelled = true;
for (std::list<Socket::ptr>::iterator it(m_pending.begin());
it != m_pending.end();
++it) {
(*it)->cancelConnect();
(*it)->cancelSend();
(*it)->cancelReceive();
}
}
Stream::ptr
SSLStreamBroker::getStream(const URI &uri)
{
Stream::ptr result = parent()->getStream(uri);
if (uri.schemeDefined() && uri.scheme() == "https") {
SSLStream::ptr sslStream(new SSLStream(result, true, true, m_sslCtx));
result = sslStream;
sslStream->connect();
if (m_verifySslCert)
sslStream->verifyPeerCertificate();
if (m_verifySslCertHost)
sslStream->verifyPeerCertificate(uri.authority.host());
}
return result;
}
static bool least(const ClientConnection::ptr &lhs,
const ClientConnection::ptr &rhs)
{
if (lhs && rhs)
return lhs->outstandingRequests() <
rhs->outstandingRequests();
if (!lhs)
return false;
if (!rhs)
return true;
MORDOR_NOTREACHED();
}
std::pair<ClientConnection::ptr, bool>
ConnectionCache::getConnection(const URI &uri, bool forceNewConnection)
{
URI schemeAndAuthority;
std::map<URI, std::pair<ConnectionList,
boost::shared_ptr<FiberCondition> > >::iterator it, it3;
ConnectionList::iterator it2;
std::pair<ClientConnection::ptr, bool> result;
{
FiberMutex::ScopedLock lock(m_mutex);
// Clean out any dead conns
for (it = m_conns.begin(); it != m_conns.end();) {
for (it2 = it->second.first.begin();
it2 != it->second.first.end();) {
if (*it2 && !(*it2)->newRequestsAllowed()) {
it2 = it->second.first.erase(it2);
} else {
++it2;
}
}
if (it->second.first.empty()) {
it3 = it;
++it3;
m_conns.erase(it);
it = it3;
} else {
++it;
}
}
schemeAndAuthority = uri;
schemeAndAuthority.path = URI::Path();
schemeAndAuthority.queryDefined(false);
schemeAndAuthority.fragmentDefined(false);
if (!forceNewConnection) {
while (true) {
// Look for an existing connection
it = m_conns.find(schemeAndAuthority);
if (it != m_conns.end() &&
!it->second.first.empty() &&
it->second.first.size() >= m_connectionsPerHost) {
ConnectionList &connsForThisUri = it->second.first;
// Assign it2 to point to the connection with the
// least number of outstanding requests
it2 = std::min_element(connsForThisUri.begin(),
connsForThisUri.end(), &least);
// No connection has completed yet (but it's in progress)
if (!*it2) {
// Wait for somebody to let us try again
it->second.second->wait();
} else {
// Return the existing, completed connection
return std::make_pair(*it2, false);
}
} else {
// No existing connections
break;
}
}
}
// Create a new (blank) connection
m_conns[schemeAndAuthority].first.push_back(ClientConnection::ptr());
if (it == m_conns.end()) {
// This is the first connection for this schemeAndAuthority
it = m_conns.find(schemeAndAuthority);
// (double-check)
if (!it->second.second)
// Create the condition variable for it
it->second.second.reset(new FiberCondition(m_mutex));
}
}
// Establish a new connection
try {
Stream::ptr stream = m_streamBroker->getStream(schemeAndAuthority);
{
FiberMutex::ScopedLock lock(m_mutex);
result = std::make_pair(ClientConnection::ptr(
new ClientConnection(stream)), false);
// Assign this connection to the first blank connection for this
// schemeAndAuthority
// it should still be valid, even if the map changed
for (it2 = it->second.first.begin();
it2 != it->second.first.end();
++it2) {
if (!*it2) {
*it2 = result.first;
break;
}
}
// Unblock all waiters for them to choose an existing connection
it->second.second->broadcast();
}
} catch (...) {
FiberMutex::ScopedLock lock(m_mutex);
// This connection attempt failed; remove the first blank connection
// for this schemeAndAuthority to let someone else try to establish a
// connection
// it should still be valid, even if the map changed
for (it2 = it->second.first.begin();
it2 != it->second.first.end();
++it2) {
if (!*it2) {
it->second.first.erase(it2);
break;
}
}
it->second.second->broadcast();
if (it->second.first.empty())
m_conns.erase(it);
throw;
}
return result;
}
void
ConnectionCache::closeConnections()
{
m_streamBroker->cancelPending();
FiberMutex::ScopedLock lock(m_mutex);
std::map<URI, std::pair<ConnectionList,
boost::shared_ptr<FiberCondition> > >::iterator it;
for (it = m_conns.begin(); it != m_conns.end(); ++it) {
it->second.second->broadcast();
for (ConnectionList::iterator it2 = it->second.first.begin();
it2 != it->second.first.end();
++it2) {
if (*it2) {
Stream::ptr connStream = (*it2)->stream();
connStream->cancelRead();
connStream->cancelWrite();
}
}
}
m_conns.clear();
}
std::pair<ClientConnection::ptr, bool>
MockConnectionBroker::getConnection(const URI &uri, bool forceNewConnection)
{
ConnectionCache::iterator it = m_conns.find(uri);
if (it != m_conns.end() && !it->second.first->newRequestsAllowed()) {
m_conns.erase(it);
it = m_conns.end();
}
if (it == m_conns.end()) {
std::pair<Stream::ptr, Stream::ptr> pipes = pipeStream();
ClientConnection::ptr client(
new ClientConnection(pipes.first));
ServerConnection::ptr server(
new ServerConnection(pipes.second, boost::bind(m_dg,
uri, _1)));
Scheduler::getThis()->schedule(Fiber::ptr(new Fiber(boost::bind(
&ServerConnection::processRequests, server))));
m_conns[uri] = std::make_pair(client, server);
return std::make_pair(client, false);
}
return std::make_pair(it->second.first, false);
}
RequestBroker::ptr
RequestBrokerFilter::parent()
{
if (m_parent)
return m_parent;
return RequestBroker::ptr(m_weakParent);
}
ClientRequest::ptr
BaseRequestBroker::request(Request &requestHeaders, bool forceNewConnection,
boost::function<void (ClientRequest::ptr)> bodyDg)
{
URI ¤tUri = requestHeaders.requestLine.uri;
URI originalUri = currentUri;
bool connect = requestHeaders.requestLine.method == CONNECT;
MORDOR_ASSERT(connect || originalUri.authority.hostDefined());
MORDOR_ASSERT(!connect || !requestHeaders.request.host.empty());
if (!connect)
requestHeaders.request.host = originalUri.authority.host();
else
originalUri = "http://" + requestHeaders.request.host;
while (true) {
std::pair<ClientConnection::ptr, bool> conn =
m_connectionBroker->getConnection(
connect ? originalUri : currentUri, forceNewConnection);
try {
// Fix up our URI for use with/without proxies
if (!connect) {
if (conn.second && !currentUri.authority.hostDefined()) {
currentUri.authority = originalUri.authority;
if (originalUri.schemeDefined())
currentUri.scheme(originalUri.scheme());
} else if (!conn.second && currentUri.authority.hostDefined()) {
currentUri.schemeDefined(false);
currentUri.authority.hostDefined(false);
}
}
ClientRequest::ptr request = conn.first->request(requestHeaders);
if (bodyDg)
bodyDg(request);
if (!connect)
currentUri = originalUri;
// Force reading the response here to check for connectivity problems
request->response();
return request;
} catch (SocketException &) {
if (!m_retry) {
if (!connect)
currentUri = originalUri;
throw;
}
continue;
} catch (PriorRequestFailedException &) {
if (!m_retry) {
if (!connect)
currentUri = originalUri;
throw;
}
continue;
} catch (...) {
if (!connect)
currentUri = originalUri;
throw;
}
MORDOR_NOTREACHED();
}
}
ClientRequest::ptr
RedirectRequestBroker::request(Request &requestHeaders, bool forceNewConnection,
boost::function<void (ClientRequest::ptr)> bodyDg)
{
URI ¤tUri = requestHeaders.requestLine.uri;
URI originalUri = currentUri;
std::list<URI> uris;
uris.push_back(originalUri);
size_t redirects = 0;
while (true) {
try {
ClientRequest::ptr request = parent()->request(requestHeaders,
forceNewConnection, bodyDg);
bool handleRedirect = false;
switch (request->response().status.status)
{
case FOUND:
handleRedirect = m_handle302;
break;
case TEMPORARY_REDIRECT:
handleRedirect = m_handle307;
break;
case MOVED_PERMANENTLY:
handleRedirect = m_handle301;
break;
default:
currentUri = originalUri;
return request;
}
if (handleRedirect) {
if (++redirects == m_maxRedirects)
MORDOR_THROW_EXCEPTION(CircularRedirectException(originalUri));
currentUri = URI::transform(currentUri,
request->response().response.location);
if (std::find(uris.begin(), uris.end(), currentUri)
!= uris.end())
MORDOR_THROW_EXCEPTION(CircularRedirectException(originalUri));
uris.push_back(currentUri);
if (request->response().status.status == MOVED_PERMANENTLY)
originalUri = currentUri;
request->finish();
continue;
} else {
currentUri = originalUri;
return request;
}
} catch (...) {
currentUri = originalUri;
throw;
}
MORDOR_NOTREACHED();
}
}
ClientRequest::ptr
UserAgentRequestBroker::request(Request &requestHeaders, bool forceNewConnection,
boost::function<void (ClientRequest::ptr)> bodyDg)
{
requestHeaders.request.userAgent = m_userAgent;
return parent()->request(requestHeaders, forceNewConnection, bodyDg);
}
}}
<commit_msg>Reset the URI before retrying in BaseRequestBroker<commit_after>// Copyright (c) 2009 - Decho Corp.
#include "mordor/pch.h"
#include "broker.h"
#include "mordor/streams/pipe.h"
#include "mordor/streams/socket.h"
#include "mordor/streams/ssl.h"
#include "proxy.h"
namespace Mordor {
namespace HTTP {
RequestBroker::ptr defaultRequestBroker(IOManager *ioManager,
Scheduler *scheduler,
ConnectionBroker::ptr *connBroker)
{
StreamBroker::ptr socketBroker(new SocketStreamBroker(ioManager, scheduler));
StreamBrokerFilter::ptr sslBroker(new SSLStreamBroker(socketBroker));
ConnectionCache::ptr connectionBroker(new ConnectionCache(sslBroker));
if (connBroker != NULL)
*connBroker = connectionBroker;
RequestBroker::ptr requestBroker(new BaseRequestBroker(connectionBroker));
socketBroker.reset(new ProxyStreamBroker(socketBroker, requestBroker));
sslBroker->parent(StreamBroker::weak_ptr(socketBroker));
connectionBroker.reset(new ProxyConnectionBroker(connectionBroker));
requestBroker.reset(new BaseRequestBroker(connectionBroker));
return requestBroker;
}
StreamBroker::ptr
StreamBrokerFilter::parent()
{
if (m_parent)
return m_parent;
return StreamBroker::ptr(m_weakParent);
}
Stream::ptr
SocketStreamBroker::getStream(const URI &uri)
{
if (m_cancelled)
MORDOR_THROW_EXCEPTION(OperationAbortedException());
MORDOR_ASSERT(uri.authority.hostDefined());
MORDOR_ASSERT(uri.authority.portDefined() || uri.schemeDefined());
std::ostringstream os;
os << uri.authority.host();
if (uri.authority.portDefined())
os << ":" << uri.authority.port();
else if (uri.schemeDefined())
os << ":" << uri.scheme();
std::vector<Address::ptr> addresses;
{
SchedulerSwitcher switcher(m_scheduler);
addresses = Address::lookup(os.str(), AF_UNSPEC, SOCK_STREAM);
}
Socket::ptr socket;
for (std::vector<Address::ptr>::const_iterator it(addresses.begin());
it != addresses.end();
) {
if (m_ioManager)
socket = (*it)->createSocket(*m_ioManager);
else
socket = (*it)->createSocket();
std::list<Socket::ptr>::iterator it2;
{
boost::mutex::scoped_lock lock(m_mutex);
if (m_cancelled)
MORDOR_THROW_EXCEPTION(OperationAbortedException());
m_pending.push_back(socket);
it2 = m_pending.end();
--it2;
}
socket->sendTimeout(connectTimeout);
try {
socket->connect(*it);
socket->sendTimeout(sendTimeout);
socket->receiveTimeout(receiveTimeout);
boost::mutex::scoped_lock lock(m_mutex);
m_pending.erase(it2);
break;
} catch (...) {
boost::mutex::scoped_lock lock(m_mutex);
m_pending.erase(it2);
if (++it == addresses.end())
throw;
}
}
Stream::ptr stream(new SocketStream(socket));
return stream;
}
void
SocketStreamBroker::cancelPending()
{
boost::mutex::scoped_lock lock(m_mutex);
m_cancelled = true;
for (std::list<Socket::ptr>::iterator it(m_pending.begin());
it != m_pending.end();
++it) {
(*it)->cancelConnect();
(*it)->cancelSend();
(*it)->cancelReceive();
}
}
Stream::ptr
SSLStreamBroker::getStream(const URI &uri)
{
Stream::ptr result = parent()->getStream(uri);
if (uri.schemeDefined() && uri.scheme() == "https") {
SSLStream::ptr sslStream(new SSLStream(result, true, true, m_sslCtx));
result = sslStream;
sslStream->connect();
if (m_verifySslCert)
sslStream->verifyPeerCertificate();
if (m_verifySslCertHost)
sslStream->verifyPeerCertificate(uri.authority.host());
}
return result;
}
static bool least(const ClientConnection::ptr &lhs,
const ClientConnection::ptr &rhs)
{
if (lhs && rhs)
return lhs->outstandingRequests() <
rhs->outstandingRequests();
if (!lhs)
return false;
if (!rhs)
return true;
MORDOR_NOTREACHED();
}
std::pair<ClientConnection::ptr, bool>
ConnectionCache::getConnection(const URI &uri, bool forceNewConnection)
{
URI schemeAndAuthority;
std::map<URI, std::pair<ConnectionList,
boost::shared_ptr<FiberCondition> > >::iterator it, it3;
ConnectionList::iterator it2;
std::pair<ClientConnection::ptr, bool> result;
{
FiberMutex::ScopedLock lock(m_mutex);
// Clean out any dead conns
for (it = m_conns.begin(); it != m_conns.end();) {
for (it2 = it->second.first.begin();
it2 != it->second.first.end();) {
if (*it2 && !(*it2)->newRequestsAllowed()) {
it2 = it->second.first.erase(it2);
} else {
++it2;
}
}
if (it->second.first.empty()) {
it3 = it;
++it3;
m_conns.erase(it);
it = it3;
} else {
++it;
}
}
schemeAndAuthority = uri;
schemeAndAuthority.path = URI::Path();
schemeAndAuthority.queryDefined(false);
schemeAndAuthority.fragmentDefined(false);
if (!forceNewConnection) {
while (true) {
// Look for an existing connection
it = m_conns.find(schemeAndAuthority);
if (it != m_conns.end() &&
!it->second.first.empty() &&
it->second.first.size() >= m_connectionsPerHost) {
ConnectionList &connsForThisUri = it->second.first;
// Assign it2 to point to the connection with the
// least number of outstanding requests
it2 = std::min_element(connsForThisUri.begin(),
connsForThisUri.end(), &least);
// No connection has completed yet (but it's in progress)
if (!*it2) {
// Wait for somebody to let us try again
it->second.second->wait();
} else {
// Return the existing, completed connection
return std::make_pair(*it2, false);
}
} else {
// No existing connections
break;
}
}
}
// Create a new (blank) connection
m_conns[schemeAndAuthority].first.push_back(ClientConnection::ptr());
if (it == m_conns.end()) {
// This is the first connection for this schemeAndAuthority
it = m_conns.find(schemeAndAuthority);
// (double-check)
if (!it->second.second)
// Create the condition variable for it
it->second.second.reset(new FiberCondition(m_mutex));
}
}
// Establish a new connection
try {
Stream::ptr stream = m_streamBroker->getStream(schemeAndAuthority);
{
FiberMutex::ScopedLock lock(m_mutex);
result = std::make_pair(ClientConnection::ptr(
new ClientConnection(stream)), false);
// Assign this connection to the first blank connection for this
// schemeAndAuthority
// it should still be valid, even if the map changed
for (it2 = it->second.first.begin();
it2 != it->second.first.end();
++it2) {
if (!*it2) {
*it2 = result.first;
break;
}
}
// Unblock all waiters for them to choose an existing connection
it->second.second->broadcast();
}
} catch (...) {
FiberMutex::ScopedLock lock(m_mutex);
// This connection attempt failed; remove the first blank connection
// for this schemeAndAuthority to let someone else try to establish a
// connection
// it should still be valid, even if the map changed
for (it2 = it->second.first.begin();
it2 != it->second.first.end();
++it2) {
if (!*it2) {
it->second.first.erase(it2);
break;
}
}
it->second.second->broadcast();
if (it->second.first.empty())
m_conns.erase(it);
throw;
}
return result;
}
void
ConnectionCache::closeConnections()
{
m_streamBroker->cancelPending();
FiberMutex::ScopedLock lock(m_mutex);
std::map<URI, std::pair<ConnectionList,
boost::shared_ptr<FiberCondition> > >::iterator it;
for (it = m_conns.begin(); it != m_conns.end(); ++it) {
it->second.second->broadcast();
for (ConnectionList::iterator it2 = it->second.first.begin();
it2 != it->second.first.end();
++it2) {
if (*it2) {
Stream::ptr connStream = (*it2)->stream();
connStream->cancelRead();
connStream->cancelWrite();
}
}
}
m_conns.clear();
}
std::pair<ClientConnection::ptr, bool>
MockConnectionBroker::getConnection(const URI &uri, bool forceNewConnection)
{
ConnectionCache::iterator it = m_conns.find(uri);
if (it != m_conns.end() && !it->second.first->newRequestsAllowed()) {
m_conns.erase(it);
it = m_conns.end();
}
if (it == m_conns.end()) {
std::pair<Stream::ptr, Stream::ptr> pipes = pipeStream();
ClientConnection::ptr client(
new ClientConnection(pipes.first));
ServerConnection::ptr server(
new ServerConnection(pipes.second, boost::bind(m_dg,
uri, _1)));
Scheduler::getThis()->schedule(Fiber::ptr(new Fiber(boost::bind(
&ServerConnection::processRequests, server))));
m_conns[uri] = std::make_pair(client, server);
return std::make_pair(client, false);
}
return std::make_pair(it->second.first, false);
}
RequestBroker::ptr
RequestBrokerFilter::parent()
{
if (m_parent)
return m_parent;
return RequestBroker::ptr(m_weakParent);
}
ClientRequest::ptr
BaseRequestBroker::request(Request &requestHeaders, bool forceNewConnection,
boost::function<void (ClientRequest::ptr)> bodyDg)
{
URI ¤tUri = requestHeaders.requestLine.uri;
URI originalUri = currentUri;
bool connect = requestHeaders.requestLine.method == CONNECT;
MORDOR_ASSERT(connect || originalUri.authority.hostDefined());
MORDOR_ASSERT(!connect || !requestHeaders.request.host.empty());
if (!connect)
requestHeaders.request.host = originalUri.authority.host();
else
originalUri = "http://" + requestHeaders.request.host;
while (true) {
std::pair<ClientConnection::ptr, bool> conn =
m_connectionBroker->getConnection(
connect ? originalUri : currentUri, forceNewConnection);
try {
// Fix up our URI for use with/without proxies
if (!connect) {
if (conn.second && !currentUri.authority.hostDefined()) {
currentUri.authority = originalUri.authority;
if (originalUri.schemeDefined())
currentUri.scheme(originalUri.scheme());
} else if (!conn.second && currentUri.authority.hostDefined()) {
currentUri.schemeDefined(false);
currentUri.authority.hostDefined(false);
}
}
ClientRequest::ptr request = conn.first->request(requestHeaders);
if (bodyDg)
bodyDg(request);
if (!connect)
currentUri = originalUri;
// Force reading the response here to check for connectivity problems
request->response();
return request;
} catch (SocketException &) {
if (!connect)
currentUri = originalUri;
if (!m_retry)
throw;
continue;
} catch (PriorRequestFailedException &) {
if (!connect)
currentUri = originalUri;
if (!m_retry)
throw;
continue;
} catch (...) {
if (!connect)
currentUri = originalUri;
throw;
}
MORDOR_NOTREACHED();
}
}
ClientRequest::ptr
RedirectRequestBroker::request(Request &requestHeaders, bool forceNewConnection,
boost::function<void (ClientRequest::ptr)> bodyDg)
{
URI ¤tUri = requestHeaders.requestLine.uri;
URI originalUri = currentUri;
std::list<URI> uris;
uris.push_back(originalUri);
size_t redirects = 0;
while (true) {
try {
ClientRequest::ptr request = parent()->request(requestHeaders,
forceNewConnection, bodyDg);
bool handleRedirect = false;
switch (request->response().status.status)
{
case FOUND:
handleRedirect = m_handle302;
break;
case TEMPORARY_REDIRECT:
handleRedirect = m_handle307;
break;
case MOVED_PERMANENTLY:
handleRedirect = m_handle301;
break;
default:
currentUri = originalUri;
return request;
}
if (handleRedirect) {
if (++redirects == m_maxRedirects)
MORDOR_THROW_EXCEPTION(CircularRedirectException(originalUri));
currentUri = URI::transform(currentUri,
request->response().response.location);
if (std::find(uris.begin(), uris.end(), currentUri)
!= uris.end())
MORDOR_THROW_EXCEPTION(CircularRedirectException(originalUri));
uris.push_back(currentUri);
if (request->response().status.status == MOVED_PERMANENTLY)
originalUri = currentUri;
request->finish();
continue;
} else {
currentUri = originalUri;
return request;
}
} catch (...) {
currentUri = originalUri;
throw;
}
MORDOR_NOTREACHED();
}
}
ClientRequest::ptr
UserAgentRequestBroker::request(Request &requestHeaders, bool forceNewConnection,
boost::function<void (ClientRequest::ptr)> bodyDg)
{
requestHeaders.request.userAgent = m_userAgent;
return parent()->request(requestHeaders, forceNewConnection, bodyDg);
}
}}
<|endoftext|> |
<commit_before>// $Id$
#include "ConfusionNet.h"
#include <sstream>
#include "FactorCollection.h"
#include "Util.h"
#include "TranslationOptionCollectionConfusionNet.h"
#include "StaticData.h"
#include "Sentence.h"
#include "UserMessage.h"
#include "moses/FF/InputFeature.h"
#include "util/exception.hh"
namespace Moses
{
struct CNStats {
size_t created,destr,read,colls,words;
CNStats() : created(0),destr(0),read(0),colls(0),words(0) {}
~CNStats() {
print(std::cerr);
}
void createOne() {
++created;
}
void destroyOne() {
++destr;
}
void collect(const ConfusionNet& cn) {
++read;
colls+=cn.GetSize();
for(size_t i=0; i<cn.GetSize(); ++i)
words+=cn[i].size();
}
void print(std::ostream& out) const {
if(created>0) {
out<<"confusion net statistics:\n"
" created:\t"<<created<<"\n"
" destroyed:\t"<<destr<<"\n"
" succ. read:\t"<<read<<"\n"
" columns:\t"<<colls<<"\n"
" words:\t"<<words<<"\n"
" avg. word/column:\t"<<words/(1.0*colls)<<"\n"
" avg. cols/sent:\t"<<colls/(1.0*read)<<"\n"
"\n\n";
}
}
};
CNStats stats;
size_t
ConfusionNet::
GetColumnIncrement(size_t i, size_t j) const
{
(void) i;
(void) j;
return 1;
}
ConfusionNet::
ConfusionNet()
: InputType()
{
stats.createOne();
const StaticData& staticData = StaticData::Instance();
if (staticData.IsChart()) {
m_defaultLabelSet.insert(StaticData::Instance().GetInputDefaultNonTerminal());
}
UTIL_THROW_IF2(&InputFeature::Instance() == NULL, "Input feature must be specified");
}
ConfusionNet::
~ConfusionNet()
{
stats.destroyOne();
}
ConfusionNet::
ConfusionNet(Sentence const& s)
{
data.resize(s.GetSize());
for(size_t i=0; i<s.GetSize(); ++i) {
ScorePair scorePair;
std::pair<Word, ScorePair > temp = std::make_pair(s.GetWord(i), scorePair);
data[i].push_back(temp);
}
}
bool
ConfusionNet::
ReadF(std::istream& in, const std::vector<FactorType>& factorOrder, int format)
{
VERBOSE(2, "read confusion net with format "<<format<<"\n");
switch(format) {
case 0:
return ReadFormat0(in,factorOrder);
case 1:
return ReadFormat1(in,factorOrder);
default:
std::stringstream strme;
strme << "ERROR: unknown format '"<<format
<<"' in ConfusionNet::Read";
UserMessage::Add(strme.str());
}
return false;
}
int
ConfusionNet::
Read(std::istream& in,
const std::vector<FactorType>& factorOrder)
{
int rv=ReadF(in,factorOrder,0);
if(rv) stats.collect(*this);
return rv;
}
#if 0
// Deprecated due to code duplication;
// use Word::CreateFromString() instead
void
ConfusionNet::
String2Word(const std::string& s,Word& w,
const std::vector<FactorType>& factorOrder)
{
std::vector<std::string> factorStrVector = Tokenize(s, "|");
for(size_t i=0; i<factorOrder.size(); ++i)
w.SetFactor(factorOrder[i],
FactorCollection::Instance().AddFactor
(Input,factorOrder[i], factorStrVector[i]));
}
#endif
bool
ConfusionNet::
ReadFormat0(std::istream& in, const std::vector<FactorType>& factorOrder)
{
Clear();
const StaticData &staticData = StaticData::Instance();
const InputFeature &inputFeature = InputFeature::Instance();
size_t numInputScores = inputFeature.GetNumInputScores();
size_t numRealWordCount = inputFeature.GetNumRealWordsInInput();
size_t totalCount = numInputScores + numRealWordCount;
bool addRealWordCount = (numRealWordCount > 0);
std::string line;
while(getline(in,line)) {
std::istringstream is(line);
std::string word;
Column col;
while(is>>word) {
Word w;
// String2Word(word,w,factorOrder);
w.CreateFromString(Input,factorOrder,StringPiece(word),false,false);
std::vector<float> probs(totalCount, 0.0);
for(size_t i=0; i < numInputScores; i++) {
double prob;
if (!(is>>prob)) {
TRACE_ERR("ERROR: unable to parse CN input - bad link probability, or wrong number of scores\n");
return false;
}
if(prob<0.0) {
VERBOSE(1, "WARN: negative prob: "<<prob<<" ->set to 0.0\n");
prob=0.0;
} else if (prob>1.0) {
VERBOSE(1, "WARN: prob > 1.0 : "<<prob<<" -> set to 1.0\n");
prob=1.0;
}
probs[i] = (std::max(static_cast<float>(log(prob)),LOWEST_SCORE));
}
//store 'real' word count in last feature if we have one more weight than we do arc scores and not epsilon
if (addRealWordCount && word!=EPSILON && word!="")
probs.back() = -1.0;
ScorePair scorePair(probs);
col.push_back(std::make_pair(w,scorePair));
}
if(col.size()) {
data.push_back(col);
ShrinkToFit(data.back());
} else break;
}
return !data.empty();
}
bool
ConfusionNet::
ReadFormat1(std::istream& in, const std::vector<FactorType>& factorOrder)
{
Clear();
std::string line;
if(!getline(in,line)) return 0;
size_t s;
if(getline(in,line)) s=atoi(line.c_str());
else return 0;
data.resize(s);
for(size_t i=0; i<data.size(); ++i) {
if(!getline(in,line)) return 0;
std::istringstream is(line);
if(!(is>>s)) return 0;
std::string word;
double prob;
data[i].resize(s);
for(size_t j=0; j<s; ++j)
if(is>>word>>prob) {
//TODO: we are only reading one prob from this input format, should read many... but this function is unused anyway. -JS
data[i][j].second.denseScores = std::vector<float> (1);
data[i][j].second.denseScores.push_back((float) log(prob));
if(data[i][j].second.denseScores[0]<0) {
VERBOSE(1, "WARN: neg costs: "<<data[i][j].second.denseScores[0]<<" -> set to 0\n");
data[i][j].second.denseScores[0]=0.0;
}
// String2Word(word,data[i][j].first,factorOrder);
Word& w = data[i][j].first;
w.CreateFromString(Input,factorOrder,StringPiece(word),false,false);
} else return 0;
}
return !data.empty();
}
void ConfusionNet::Print(std::ostream& out) const
{
out<<"conf net: "<<data.size()<<"\n";
for(size_t i=0; i<data.size(); ++i) {
out<<i<<" -- ";
for(size_t j=0; j<data[i].size(); ++j) {
out<<"("<<data[i][j].first.ToString()<<", ";
// dense
std::vector<float>::const_iterator iterDense;
for(iterDense = data[i][j].second.denseScores.begin();
iterDense < data[i][j].second.denseScores.end();
++iterDense) {
out<<", "<<*iterDense;
}
// sparse
std::map<StringPiece, float>::const_iterator iterSparse;
for(iterSparse = data[i][j].second.sparseScores.begin();
iterSparse != data[i][j].second.sparseScores.end();
++iterSparse) {
out << ", " << iterSparse->first << "=" << iterSparse->second;
}
out<<") ";
}
out<<"\n";
}
out<<"\n\n";
}
#ifdef _WIN32
#pragma warning(disable:4716)
#endif
Phrase
ConfusionNet::
GetSubString(const WordsRange&) const
{
UTIL_THROW2("ERROR: call to ConfusionNet::GetSubString\n");
//return Phrase(Input);
}
std::string
ConfusionNet::
GetStringRep(const std::vector<FactorType> /* factorsToPrint */) const //not well defined yet
{
TRACE_ERR("ERROR: call to ConfusionNet::GeStringRep\n");
return "";
}
#ifdef _WIN32
#pragma warning(disable:4716)
#endif
const Word& ConfusionNet::GetWord(size_t) const
{
UTIL_THROW2("ERROR: call to ConfusionNet::GetFactorArray\n");
}
#ifdef _WIN32
#pragma warning(default:4716)
#endif
std::ostream& operator<<(std::ostream& out,const ConfusionNet& cn)
{
cn.Print(out);
return out;
}
TranslationOptionCollection*
ConfusionNet::
CreateTranslationOptionCollection() const
{
size_t maxNoTransOptPerCoverage
= StaticData::Instance().GetMaxNoTransOptPerCoverage();
float translationOptionThreshold
= StaticData::Instance().GetTranslationOptionThreshold();
TranslationOptionCollection *rv
= new TranslationOptionCollectionConfusionNet
(*this, maxNoTransOptPerCoverage, translationOptionThreshold);
assert(rv);
return rv;
}
}
<commit_msg>Commented out unused variable.<commit_after>// $Id$
#include "ConfusionNet.h"
#include <sstream>
#include "FactorCollection.h"
#include "Util.h"
#include "TranslationOptionCollectionConfusionNet.h"
#include "StaticData.h"
#include "Sentence.h"
#include "UserMessage.h"
#include "moses/FF/InputFeature.h"
#include "util/exception.hh"
namespace Moses
{
struct CNStats {
size_t created,destr,read,colls,words;
CNStats() : created(0),destr(0),read(0),colls(0),words(0) {}
~CNStats() {
print(std::cerr);
}
void createOne() {
++created;
}
void destroyOne() {
++destr;
}
void collect(const ConfusionNet& cn) {
++read;
colls+=cn.GetSize();
for(size_t i=0; i<cn.GetSize(); ++i)
words+=cn[i].size();
}
void print(std::ostream& out) const {
if(created>0) {
out<<"confusion net statistics:\n"
" created:\t"<<created<<"\n"
" destroyed:\t"<<destr<<"\n"
" succ. read:\t"<<read<<"\n"
" columns:\t"<<colls<<"\n"
" words:\t"<<words<<"\n"
" avg. word/column:\t"<<words/(1.0*colls)<<"\n"
" avg. cols/sent:\t"<<colls/(1.0*read)<<"\n"
"\n\n";
}
}
};
CNStats stats;
size_t
ConfusionNet::
GetColumnIncrement(size_t i, size_t j) const
{
(void) i;
(void) j;
return 1;
}
ConfusionNet::
ConfusionNet()
: InputType()
{
stats.createOne();
const StaticData& staticData = StaticData::Instance();
if (staticData.IsChart()) {
m_defaultLabelSet.insert(StaticData::Instance().GetInputDefaultNonTerminal());
}
UTIL_THROW_IF2(&InputFeature::Instance() == NULL, "Input feature must be specified");
}
ConfusionNet::
~ConfusionNet()
{
stats.destroyOne();
}
ConfusionNet::
ConfusionNet(Sentence const& s)
{
data.resize(s.GetSize());
for(size_t i=0; i<s.GetSize(); ++i) {
ScorePair scorePair;
std::pair<Word, ScorePair > temp = std::make_pair(s.GetWord(i), scorePair);
data[i].push_back(temp);
}
}
bool
ConfusionNet::
ReadF(std::istream& in, const std::vector<FactorType>& factorOrder, int format)
{
VERBOSE(2, "read confusion net with format "<<format<<"\n");
switch(format) {
case 0:
return ReadFormat0(in,factorOrder);
case 1:
return ReadFormat1(in,factorOrder);
default:
std::stringstream strme;
strme << "ERROR: unknown format '"<<format
<<"' in ConfusionNet::Read";
UserMessage::Add(strme.str());
}
return false;
}
int
ConfusionNet::
Read(std::istream& in,
const std::vector<FactorType>& factorOrder)
{
int rv=ReadF(in,factorOrder,0);
if(rv) stats.collect(*this);
return rv;
}
#if 0
// Deprecated due to code duplication;
// use Word::CreateFromString() instead
void
ConfusionNet::
String2Word(const std::string& s,Word& w,
const std::vector<FactorType>& factorOrder)
{
std::vector<std::string> factorStrVector = Tokenize(s, "|");
for(size_t i=0; i<factorOrder.size(); ++i)
w.SetFactor(factorOrder[i],
FactorCollection::Instance().AddFactor
(Input,factorOrder[i], factorStrVector[i]));
}
#endif
bool
ConfusionNet::
ReadFormat0(std::istream& in, const std::vector<FactorType>& factorOrder)
{
Clear();
// const StaticData &staticData = StaticData::Instance();
const InputFeature &inputFeature = InputFeature::Instance();
size_t numInputScores = inputFeature.GetNumInputScores();
size_t numRealWordCount = inputFeature.GetNumRealWordsInInput();
size_t totalCount = numInputScores + numRealWordCount;
bool addRealWordCount = (numRealWordCount > 0);
std::string line;
while(getline(in,line)) {
std::istringstream is(line);
std::string word;
Column col;
while(is>>word) {
Word w;
// String2Word(word,w,factorOrder);
w.CreateFromString(Input,factorOrder,StringPiece(word),false,false);
std::vector<float> probs(totalCount, 0.0);
for(size_t i=0; i < numInputScores; i++) {
double prob;
if (!(is>>prob)) {
TRACE_ERR("ERROR: unable to parse CN input - bad link probability, or wrong number of scores\n");
return false;
}
if(prob<0.0) {
VERBOSE(1, "WARN: negative prob: "<<prob<<" ->set to 0.0\n");
prob=0.0;
} else if (prob>1.0) {
VERBOSE(1, "WARN: prob > 1.0 : "<<prob<<" -> set to 1.0\n");
prob=1.0;
}
probs[i] = (std::max(static_cast<float>(log(prob)),LOWEST_SCORE));
}
//store 'real' word count in last feature if we have one more weight than we do arc scores and not epsilon
if (addRealWordCount && word!=EPSILON && word!="")
probs.back() = -1.0;
ScorePair scorePair(probs);
col.push_back(std::make_pair(w,scorePair));
}
if(col.size()) {
data.push_back(col);
ShrinkToFit(data.back());
} else break;
}
return !data.empty();
}
bool
ConfusionNet::
ReadFormat1(std::istream& in, const std::vector<FactorType>& factorOrder)
{
Clear();
std::string line;
if(!getline(in,line)) return 0;
size_t s;
if(getline(in,line)) s=atoi(line.c_str());
else return 0;
data.resize(s);
for(size_t i=0; i<data.size(); ++i) {
if(!getline(in,line)) return 0;
std::istringstream is(line);
if(!(is>>s)) return 0;
std::string word;
double prob;
data[i].resize(s);
for(size_t j=0; j<s; ++j)
if(is>>word>>prob) {
//TODO: we are only reading one prob from this input format, should read many... but this function is unused anyway. -JS
data[i][j].second.denseScores = std::vector<float> (1);
data[i][j].second.denseScores.push_back((float) log(prob));
if(data[i][j].second.denseScores[0]<0) {
VERBOSE(1, "WARN: neg costs: "<<data[i][j].second.denseScores[0]<<" -> set to 0\n");
data[i][j].second.denseScores[0]=0.0;
}
// String2Word(word,data[i][j].first,factorOrder);
Word& w = data[i][j].first;
w.CreateFromString(Input,factorOrder,StringPiece(word),false,false);
} else return 0;
}
return !data.empty();
}
void ConfusionNet::Print(std::ostream& out) const
{
out<<"conf net: "<<data.size()<<"\n";
for(size_t i=0; i<data.size(); ++i) {
out<<i<<" -- ";
for(size_t j=0; j<data[i].size(); ++j) {
out<<"("<<data[i][j].first.ToString()<<", ";
// dense
std::vector<float>::const_iterator iterDense;
for(iterDense = data[i][j].second.denseScores.begin();
iterDense < data[i][j].second.denseScores.end();
++iterDense) {
out<<", "<<*iterDense;
}
// sparse
std::map<StringPiece, float>::const_iterator iterSparse;
for(iterSparse = data[i][j].second.sparseScores.begin();
iterSparse != data[i][j].second.sparseScores.end();
++iterSparse) {
out << ", " << iterSparse->first << "=" << iterSparse->second;
}
out<<") ";
}
out<<"\n";
}
out<<"\n\n";
}
#ifdef _WIN32
#pragma warning(disable:4716)
#endif
Phrase
ConfusionNet::
GetSubString(const WordsRange&) const
{
UTIL_THROW2("ERROR: call to ConfusionNet::GetSubString\n");
//return Phrase(Input);
}
std::string
ConfusionNet::
GetStringRep(const std::vector<FactorType> /* factorsToPrint */) const //not well defined yet
{
TRACE_ERR("ERROR: call to ConfusionNet::GeStringRep\n");
return "";
}
#ifdef _WIN32
#pragma warning(disable:4716)
#endif
const Word& ConfusionNet::GetWord(size_t) const
{
UTIL_THROW2("ERROR: call to ConfusionNet::GetFactorArray\n");
}
#ifdef _WIN32
#pragma warning(default:4716)
#endif
std::ostream& operator<<(std::ostream& out,const ConfusionNet& cn)
{
cn.Print(out);
return out;
}
TranslationOptionCollection*
ConfusionNet::
CreateTranslationOptionCollection() const
{
size_t maxNoTransOptPerCoverage
= StaticData::Instance().GetMaxNoTransOptPerCoverage();
float translationOptionThreshold
= StaticData::Instance().GetTranslationOptionThreshold();
TranslationOptionCollection *rv
= new TranslationOptionCollectionConfusionNet
(*this, maxNoTransOptPerCoverage, translationOptionThreshold);
assert(rv);
return rv;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010 Timothy Lovorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __SCSS__BZONE_H
#define __SCSS__BZONE_H
#include <cmath>
#include <cfloat>
#include "BaseState.hh"
#include "ZeroTempState.hh"
class BZone {
public:
template <class SpecializedState>
static double average(const BaseState& stBase,
const SpecializedState& stSpec,
double (*innerFunc)(const SpecializedState&, double, double));
template <class SpecializedState>
static double minimum(const BaseState& stBase,
const SpecializedState& stSpec,
double (*innerFunc)(const SpecializedState&, double, double));
};
// Would be nice to have a single function handle transforming one BZone point
// into another instead of duplicating the traversal
// OR just specify accumulator function (val = accum(val, thisPointVal))
template <class SpecializedState>
double BZone::minimum(const BaseState& stBase,
const SpecializedState& stSpec,
double (*innerFunc)(const SpecializedState&, double, double)) {
double kx = -M_PI, ky = -M_PI, min = DBL_MAX, val;
int N = stBase.env.gridLen;
double step = 2 * M_PI / N;
while (ky < M_PI) {
while (kx < M_PI) {
val = innerFunc(stSpec, kx, ky);
if (val < min) {
min = val;
}
kx += step;
}
ky += step;
kx = -M_PI;
}
return min;
}
template <class SpecializedState>
double BZone::average(const BaseState& stBase,
const SpecializedState& stSpec,
double (*innerFunc)(const SpecializedState&, double, double)) {
double kx = -M_PI, ky = -M_PI, min = DBL_MAX, sum = 0.0;
int N = stBase.env.gridLen;
double step = 2 * M_PI / N;
while (ky < M_PI) {
while (kx < M_PI) {
sum += innerFunc(stSpec, kx, ky);
kx += step;
}
ky += step;
kx = -M_PI;
}
return sum / (N * N);
}
#endif
<commit_msg>starting on BZone vector average<commit_after>/*
Copyright (c) 2010 Timothy Lovorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __SCSS__BZONE_H
#define __SCSS__BZONE_H
#include <cmath>
#include <cfloat>
#include <vector>
#include "BaseState.hh"
#include "ZeroTempState.hh"
class BZone {
public:
template <class SpecializedState>
static double average(const BaseState& stBase,
const SpecializedState& stSpec,
double (*innerFunc)(const SpecializedState&, double, double));
template <class SpecializedState>
static double minimum(const BaseState& stBase,
const SpecializedState& stSpec,
double (*innerFunc)(const SpecializedState&, double, double));
template <class SpecializedState>
static std::vector average(const BaseState& stBase,
const SpecializedState& stSpec,
std::vector (*innerFunc)(const SpecializedState&, double, double));
};
// Would be nice to have a single function handle transforming one BZone point
// into another instead of duplicating the traversal
// OR just specify accumulator function (val = accum(val, thisPointVal))
template <class SpecializedState>
double BZone::minimum(const BaseState& stBase,
const SpecializedState& stSpec,
double (*innerFunc)(const SpecializedState&, double, double)) {
double kx = -M_PI, ky = -M_PI, min = DBL_MAX, val;
int N = stBase.env.gridLen;
double step = 2 * M_PI / N;
while (ky < M_PI) {
while (kx < M_PI) {
val = innerFunc(stSpec, kx, ky);
if (val < min) {
min = val;
}
kx += step;
}
ky += step;
kx = -M_PI;
}
return min;
}
template <class SpecializedState>
double BZone::average(const BaseState& stBase,
const SpecializedState& stSpec,
double (*innerFunc)(const SpecializedState&, double, double)) {
double kx = -M_PI, ky = -M_PI, min = DBL_MAX, sum = 0.0;
int N = stBase.env.gridLen;
double step = 2 * M_PI / N;
while (ky < M_PI) {
while (kx < M_PI) {
sum += innerFunc(stSpec, kx, ky);
kx += step;
}
ky += step;
kx = -M_PI;
}
return sum / (N * N);
}
template <class SpecializedState>
std::vector<double> BZone::vectorAverage(const BaseState& stBase,
const SpecializedState& stSpec,
std::vector<double> (*innerFunc)(const SpecializedState&,
double, double)) {
double kx = -M_PI, ky = -M_PI, min = DBL_MAX;
int N = stBase.env.gridLen;
double step = 2 * M_PI / N;
std::vector sums;
while (ky < M_PI) {
while (kx < M_PI) {
std::vector newTerms = innerFunc(stSpec, kx, ky);
for (it = newTerms.begin() ; it < newTerms.end(); it++ ) {
// expanded sums if needed; added newTerms
}
kx += step;
}
ky += step;
kx = -M_PI;
}
return sum / (N * N);
}
#endif
<|endoftext|> |
<commit_before>#include <bitbots_ros_control/wolfgang_hardware_interface.h>
namespace bitbots_ros_control {
/**
* This class provides a combination of multiple hardware interfaces to construct a complete Wolfgang robot.
* It is similar to a CombinedRobotHw class as specified in ros_control, but it is changed a bit to make sharing of
* a common bus driver over multiple hardware interfaces possible.
*/
WolfgangHardwareInterface::WolfgangHardwareInterface(ros::NodeHandle &nh) {
first_ping_error_ = true;
speak_pub_ = nh.advertise<humanoid_league_msgs::Audio>("/speak", 1);
// load parameters
ROS_INFO_STREAM("Loading parameters from namespace " << nh.getNamespace());
nh.param<bool>("only_imu", only_imu_, false);
if (only_imu_) ROS_WARN("Starting in only IMU mode");
nh.param<bool>("only_pressure", only_pressure_, false);
if (only_pressure_) ROS_WARN("starting in only pressure sensor mode");
if (only_pressure_ && only_imu_) {
ROS_ERROR("only_imu AND only_pressure was set to true");
exit(1);
}
// get list of all bus devices
XmlRpc::XmlRpcValue dxls_xml;
nh.getParam("device_info", dxls_xml);
ROS_ASSERT(dxls_xml.getType() == XmlRpc::XmlRpcValue::TypeStruct);
// Convert dxls to native type: a vector of tuples with name and id for sorting purposes
std::vector<std::pair<std::string, int>> dxl_devices;
for (XmlRpc::XmlRpcValue::ValueStruct::const_iterator it = dxls_xml.begin(); it != dxls_xml.end(); ++it) {
std::string name = it->first;
XmlRpc::XmlRpcValue data = it->second;
int id = data["id"];
dxl_devices.emplace_back(name, id);
}
// sort the devices by id. This way the devices will always be read and written in ID order later, making debug easier.
std::sort(dxl_devices.begin(), dxl_devices.end(),
[](std::pair<std::string, int> &a, std::pair<std::string, int> &b) { return a.second < b.second; });
// create overall servo interface since we need a single interface for the controllers
servo_interface_ = DynamixelServoHardwareInterface();
servo_interface_.setParent(this);
//todo check and remove if possible
/* duplicate?
// set the dynamic reconfigure and load standard params for servo interface
dynamic_reconfigure::Server<bitbots_ros_control::dynamixel_servo_hardware_interface_paramsConfig> server;
dynamic_reconfigure::Server<bitbots_ros_control::dynamixel_servo_hardware_interface_paramsConfig>::CallbackType
f;
f = boost::bind(&bitbots_ros_control::DynamixelServoHardwareInterface::reconfCallback, servo_interface_, _1, _2);
server.setCallback(f);*/
// try to ping all devices on the list, add them to the driver and create corresponding hardware interfaces
// try until interruption to enable the user to turn on the power
while (ros::ok()) {
if (create_interfaces(nh, dxl_devices)) {
break;
}
//sleep(3);
}
}
//todo this could be done parallel with threads for speed up
bool WolfgangHardwareInterface::create_interfaces(ros::NodeHandle &nh,
std::vector<std::pair<std::string, int>> dxl_devices) {
interfaces_ = std::vector<std::vector<hardware_interface::RobotHW *>>();
// init bus drivers
std::vector<std::string> pinged;
XmlRpc::XmlRpcValue port_xml;
nh.getParam("port_info", port_xml);
for (XmlRpc::XmlRpcValue::ValueStruct::const_iterator it = port_xml.begin(); it != port_xml.end(); ++it) {
// read bus driver specifications from config
XmlRpc::XmlRpcValue port_data = it->second;
std::string device_file = port_data["device_file"];
int baudrate = port_data["baudrate"];
int protocol_version = port_data["protocol_version"];
auto driver = std::make_shared<DynamixelDriver>();
if (!driver->init(device_file.c_str(), uint32_t(baudrate))) {
ROS_ERROR("Error opening serial port %s", device_file.c_str());
speakError(speak_pub_, "Error opening serial port");
sleep(1);
exit(1);
}
// some interface seem to produce some gitter directly after connecting. wait or it will interfere with pings
// sleep(1);
driver->setPacketHandler(protocol_version);
std::vector<hardware_interface::RobotHW *> interfaces_on_port;
// iterate over all devices and ping them to see what is connected to this bus
std::vector<std::tuple<int, std::string, float, float>> servos_on_port;
for (std::pair<std::string, int> &device : dxl_devices) {
std::string name = device.first;
int id = device.second;
if (std::find(pinged.begin(), pinged.end(), device.first) != pinged.end()) {
// we already found this and dont have to search again
} else {
ros::NodeHandle dxl_nh(nh, "device_info/" + name);
int model_number_specified;
dxl_nh.getParam("model_number", model_number_specified);
// some devices provide more than one type of interface, e.g. the IMU provides additionally buttons and LEDs
std::string interface_type;
dxl_nh.param<std::string>("interface_type", interface_type, "");
uint16_t model_number_specified_16 = uint16_t(model_number_specified);
uint16_t *model_number_returned_16 = new uint16_t;
if (driver->ping(uint8_t(id), model_number_returned_16)) {
// check if the specified model number matches the actual model number of the device
if (model_number_specified_16 != *model_number_returned_16) {
ROS_WARN("Model number of id %d does not match", id);
}
// ping was successful, add device correspondingly
// only add them if the mode is set correspondingly
// TODO maybe move more of the parameter stuff in the init of the modules instead of doing everything here
if (model_number_specified == 0xABBA && interface_type == "CORE") {
// CORE
int read_rate;
dxl_nh.param<int>("read_rate", read_rate, 1);
driver->setTools(model_number_specified_16, id);
CoreHardwareInterface *interface = new CoreHardwareInterface(driver, id, read_rate);
// turn on power, just to be sure
interface->write(ros::Time::now(), ros::Duration(0));
interfaces_on_port.push_back(interface);
} else if (model_number_specified == 0 && !only_imu_) {//model number is currently 0 on foot sensors
// bitfoot
std::string topic;
if (!dxl_nh.getParam("topic", topic)) {
ROS_WARN("Bitfoot topic not specified");
}
BitFootHardwareInterface *interface = new BitFootHardwareInterface(driver, id, topic, name);
interfaces_on_port.push_back(interface);
} else if (model_number_specified == 0xBAFF && interface_type == "IMU" && !only_pressure_) {
//IMU
std::string topic;
if (!dxl_nh.getParam("topic", topic)) {
ROS_WARN("IMU topic not specified");
}
std::string frame;
if (!dxl_nh.getParam("frame", frame)) {
ROS_WARN("IMU frame not specified");
}
driver->setTools(model_number_specified_16, id);
ImuHardwareInterface *interface = new ImuHardwareInterface(driver, id, topic, frame, name);
/* Hardware interfaces must be registered at the main RobotHW class.
* Therefore, a pointer to this class is passed down to the RobotHW classes
* registering further interfaces */
interface->setParent(this);
interfaces_on_port.push_back(interface);
} else if (model_number_specified == 0xBAFF && interface_type == "Button" && !only_pressure_) {
// Buttons
std::string topic;
if (!dxl_nh.getParam("topic", topic)) {
ROS_WARN("Button topic not specified");
}
int read_rate;
dxl_nh.param<int>("read_rate", read_rate, 50);
interfaces_on_port.push_back(new ButtonHardwareInterface(driver, id, topic, read_rate));
} else if ((model_number_specified == 0xBAFF || model_number_specified == 0xABBA) && interface_type == "LED" && !only_pressure_) {
// LEDs
int number_of_LEDs, start_number;
dxl_nh.param<int>("number_of_LEDs", number_of_LEDs, 3);
dxl_nh.param<int>("start_number", start_number, 0);
interfaces_on_port.push_back(new LedsHardwareInterface(driver, id, number_of_LEDs, start_number));
} else if ((model_number_specified == 311 || model_number_specified == 321 || model_number_specified == 1100)
&& !only_pressure_
&& !only_imu_) {
// Servos
// We need to add the tool to the driver for later reading and writing
driver->setTools(model_number_specified_16, id);
float mounting_offset;
dxl_nh.param<float>("mounting_offset", mounting_offset, 0.0);
float joint_offset;
dxl_nh.param<float>("joint_offset", joint_offset, 0.0);
servos_on_port.push_back(std::make_tuple(id, name, mounting_offset, joint_offset));
} else {
if (!only_pressure_ && !only_imu_) {
ROS_WARN("Could not identify device for ID %d", id);
}
}
pinged.push_back(name);
}
}
}
// create a servo bus interface if there were servos found on this bus
if (servos_on_port.size() > 0) {
ServoBusInterface *interface = new ServoBusInterface(driver, servos_on_port);
interfaces_on_port.push_back(interface);
servo_interface_.addBusInterface(interface);
}
// add vector of interfaces on this port to overall collection of interfaces
interfaces_.push_back(interfaces_on_port);
}
if (pinged.size() != dxl_devices.size()) {
// when we only have 1 or two devices its only the core
if (pinged.empty() || pinged.size() == 1 || pinged.size() == 2) {
ROS_ERROR("Could not start ros control. Power is off!");
speakError(speak_pub_, "Could not start ros control. Power is off!");
} else {
if (first_ping_error_) {
first_ping_error_ = false;
} else {
ROS_ERROR("Could not ping all devices!");
speakError(speak_pub_, "error starting ros control");
// check which devices were not pinged successful
for (std::pair<std::string, int> &device : dxl_devices) {
if (std::find(pinged.begin(), pinged.end(), device.first) != pinged.end()) {
} else {
ROS_ERROR("%s with id %d missing", device.first.c_str(), device.second);
}
}
}
}
return false;
} else {
speakError(speak_pub_, "ross control startup successful");
return true;
}
}
void threaded_init(std::vector<hardware_interface::RobotHW *> &port_interfaces,
ros::NodeHandle &root_nh,
int &success) {
success = true;
for (hardware_interface::RobotHW *interface : port_interfaces) {
// giving 2 times same node handle to keep interface of base class, dirty
success &= interface->init(root_nh, root_nh);
}
}
bool WolfgangHardwareInterface::init(ros::NodeHandle &root_nh) {
// iterate through all ports
std::vector<std::thread> threads;
std::vector<int *> successes;
int i = 0;
for (std::vector<hardware_interface::RobotHW *> &port_interfaces : interfaces_) {
// iterate through all interfaces on this port
int suc = 0;
successes.push_back(&suc);
threads.push_back(std::thread(threaded_init, std::ref(port_interfaces), std::ref(root_nh), std::ref(suc)));
i++;
}
// wait for all reads to finish
for (std::thread &thread : threads) {
thread.join();
}
// see if all inits were successfull
bool success = true;
for (bool s : successes) {
success &= s;
}
// init servo interface last after all servo busses are there
success &= servo_interface_.init(root_nh, root_nh);
return success;
}
void threaded_read(std::vector<hardware_interface::RobotHW *> &port_interfaces,
const ros::Time &t,
const ros::Duration &dt) {
for (hardware_interface::RobotHW *interface : port_interfaces) {
// giving 2 times same node handle to keep interface of base class, dirty
interface->read(t, dt);
}
}
void WolfgangHardwareInterface::read(const ros::Time &t, const ros::Duration &dt) {
std::vector<std::thread> threads;
// start all reads
for (std::vector<hardware_interface::RobotHW *> &port_interfaces : interfaces_) {
threads.push_back(std::thread(threaded_read, std::ref(port_interfaces), std::ref(t), std::ref(dt)));
}
// wait for all reads to finish
for (std::thread &thread : threads) {
thread.join();
}
// aggrigate all servo values for controller
servo_interface_.read(t, dt);
}
void threaded_write(std::vector<hardware_interface::RobotHW *> &port_interfaces,
const ros::Time &t,
const ros::Duration &dt) {
for (hardware_interface::RobotHW *interface : port_interfaces) {
// giving 2 times same node handle to keep interface of base class, dirty
interface->write(t, dt);
}
}
void WolfgangHardwareInterface::write(const ros::Time &t, const ros::Duration &dt) {
// write all controller values to interfaces
servo_interface_.write(t, dt);
std::vector<std::thread> threads;
// start all reads
for (std::vector<hardware_interface::RobotHW *> &port_interfaces : interfaces_) {
threads.push_back(std::thread(threaded_write, std::ref(port_interfaces), std::ref(t), std::ref(dt)));
}
// wait for all reads to finish
for (std::thread &thread : threads) {
thread.join();
}
}
}
<commit_msg>Update bitbots_ros_control/src/wolfgang_hardware_interface.cpp<commit_after>#include <bitbots_ros_control/wolfgang_hardware_interface.h>
namespace bitbots_ros_control {
/**
* This class provides a combination of multiple hardware interfaces to construct a complete Wolfgang robot.
* It is similar to a CombinedRobotHw class as specified in ros_control, but it is changed a bit to make sharing of
* a common bus driver over multiple hardware interfaces possible.
*/
WolfgangHardwareInterface::WolfgangHardwareInterface(ros::NodeHandle &nh) {
first_ping_error_ = true;
speak_pub_ = nh.advertise<humanoid_league_msgs::Audio>("/speak", 1);
// load parameters
ROS_INFO_STREAM("Loading parameters from namespace " << nh.getNamespace());
nh.param<bool>("only_imu", only_imu_, false);
if (only_imu_) ROS_WARN("Starting in only IMU mode");
nh.param<bool>("only_pressure", only_pressure_, false);
if (only_pressure_) ROS_WARN("starting in only pressure sensor mode");
if (only_pressure_ && only_imu_) {
ROS_ERROR("only_imu AND only_pressure was set to true");
exit(1);
}
// get list of all bus devices
XmlRpc::XmlRpcValue dxls_xml;
nh.getParam("device_info", dxls_xml);
ROS_ASSERT(dxls_xml.getType() == XmlRpc::XmlRpcValue::TypeStruct);
// Convert dxls to native type: a vector of tuples with name and id for sorting purposes
std::vector<std::pair<std::string, int>> dxl_devices;
for (XmlRpc::XmlRpcValue::ValueStruct::const_iterator it = dxls_xml.begin(); it != dxls_xml.end(); ++it) {
std::string name = it->first;
XmlRpc::XmlRpcValue data = it->second;
int id = data["id"];
dxl_devices.emplace_back(name, id);
}
// sort the devices by id. This way the devices will always be read and written in ID order later, making debug easier.
std::sort(dxl_devices.begin(), dxl_devices.end(),
[](std::pair<std::string, int> &a, std::pair<std::string, int> &b) { return a.second < b.second; });
// create overall servo interface since we need a single interface for the controllers
servo_interface_ = DynamixelServoHardwareInterface();
servo_interface_.setParent(this);
//todo check and remove if possible
/* duplicate?
// set the dynamic reconfigure and load standard params for servo interface
dynamic_reconfigure::Server<bitbots_ros_control::dynamixel_servo_hardware_interface_paramsConfig> server;
dynamic_reconfigure::Server<bitbots_ros_control::dynamixel_servo_hardware_interface_paramsConfig>::CallbackType
f;
f = boost::bind(&bitbots_ros_control::DynamixelServoHardwareInterface::reconfCallback, servo_interface_, _1, _2);
server.setCallback(f);*/
// try to ping all devices on the list, add them to the driver and create corresponding hardware interfaces
// try until interruption to enable the user to turn on the power
while (ros::ok()) {
if (create_interfaces(nh, dxl_devices)) {
break;
}
//sleep(3);
}
}
//todo this could be done parallel with threads for speed up
bool WolfgangHardwareInterface::create_interfaces(ros::NodeHandle &nh,
std::vector<std::pair<std::string, int>> dxl_devices) {
interfaces_ = std::vector<std::vector<hardware_interface::RobotHW *>>();
// init bus drivers
std::vector<std::string> pinged;
XmlRpc::XmlRpcValue port_xml;
nh.getParam("port_info", port_xml);
for (XmlRpc::XmlRpcValue::ValueStruct::const_iterator it = port_xml.begin(); it != port_xml.end(); ++it) {
// read bus driver specifications from config
XmlRpc::XmlRpcValue port_data = it->second;
std::string device_file = port_data["device_file"];
int baudrate = port_data["baudrate"];
int protocol_version = port_data["protocol_version"];
auto driver = std::make_shared<DynamixelDriver>();
if (!driver->init(device_file.c_str(), uint32_t(baudrate))) {
ROS_ERROR("Error opening serial port %s", device_file.c_str());
speakError(speak_pub_, "Error opening serial port");
sleep(1);
exit(1);
}
// some interface seem to produce some gitter directly after connecting. wait or it will interfere with pings
// sleep(1);
driver->setPacketHandler(protocol_version);
std::vector<hardware_interface::RobotHW *> interfaces_on_port;
// iterate over all devices and ping them to see what is connected to this bus
std::vector<std::tuple<int, std::string, float, float>> servos_on_port;
for (std::pair<std::string, int> &device : dxl_devices) {
std::string name = device.first;
int id = device.second;
if (std::find(pinged.begin(), pinged.end(), device.first) != pinged.end()) {
// we already found this and dont have to search again
} else {
ros::NodeHandle dxl_nh(nh, "device_info/" + name);
int model_number_specified;
dxl_nh.getParam("model_number", model_number_specified);
// some devices provide more than one type of interface, e.g. the IMU provides additionally buttons and LEDs
std::string interface_type;
dxl_nh.param<std::string>("interface_type", interface_type, "");
uint16_t model_number_specified_16 = uint16_t(model_number_specified);
uint16_t *model_number_returned_16 = new uint16_t;
if (driver->ping(uint8_t(id), model_number_returned_16)) {
// check if the specified model number matches the actual model number of the device
if (model_number_specified_16 != *model_number_returned_16) {
ROS_WARN("Model number of id %d does not match", id);
}
// ping was successful, add device correspondingly
// only add them if the mode is set correspondingly
// TODO maybe move more of the parameter stuff in the init of the modules instead of doing everything here
if (model_number_specified == 0xABBA && interface_type == "CORE") {
// CORE
int read_rate;
dxl_nh.param<int>("read_rate", read_rate, 1);
driver->setTools(model_number_specified_16, id);
CoreHardwareInterface *interface = new CoreHardwareInterface(driver, id, read_rate);
// turn on power, just to be sure
interface->write(ros::Time::now(), ros::Duration(0));
interfaces_on_port.push_back(interface);
} else if (model_number_specified == 0 && !only_imu_) {//model number is currently 0 on foot sensors
// bitfoot
std::string topic;
if (!dxl_nh.getParam("topic", topic)) {
ROS_WARN("Bitfoot topic not specified");
}
BitFootHardwareInterface *interface = new BitFootHardwareInterface(driver, id, topic, name);
interfaces_on_port.push_back(interface);
} else if (model_number_specified == 0xBAFF && interface_type == "IMU" && !only_pressure_) {
//IMU
std::string topic;
if (!dxl_nh.getParam("topic", topic)) {
ROS_WARN("IMU topic not specified");
}
std::string frame;
if (!dxl_nh.getParam("frame", frame)) {
ROS_WARN("IMU frame not specified");
}
driver->setTools(model_number_specified_16, id);
ImuHardwareInterface *interface = new ImuHardwareInterface(driver, id, topic, frame, name);
/* Hardware interfaces must be registered at the main RobotHW class.
* Therefore, a pointer to this class is passed down to the RobotHW classes
* registering further interfaces */
interface->setParent(this);
interfaces_on_port.push_back(interface);
} else if (model_number_specified == 0xBAFF && interface_type == "Button" && !only_pressure_) {
// Buttons
std::string topic;
if (!dxl_nh.getParam("topic", topic)) {
ROS_WARN("Button topic not specified");
}
int read_rate;
dxl_nh.param<int>("read_rate", read_rate, 50);
interfaces_on_port.push_back(new ButtonHardwareInterface(driver, id, topic, read_rate));
} else if ((model_number_specified == 0xBAFF || model_number_specified == 0xABBA) && interface_type == "LED" && !only_pressure_) {
// LEDs
int number_of_LEDs, start_number;
dxl_nh.param<int>("number_of_LEDs", number_of_LEDs, 3);
dxl_nh.param<int>("start_number", start_number, 0);
interfaces_on_port.push_back(new LedsHardwareInterface(driver, id, number_of_LEDs, start_number));
} else if ((model_number_specified == 311 || model_number_specified == 321 || model_number_specified == 1100)
&& !only_pressure_
&& !only_imu_) {
// Servos
// We need to add the tool to the driver for later reading and writing
driver->setTools(model_number_specified_16, id);
float mounting_offset;
dxl_nh.param<float>("mounting_offset", mounting_offset, 0.0);
float joint_offset;
dxl_nh.param<float>("joint_offset", joint_offset, 0.0);
servos_on_port.push_back(std::make_tuple(id, name, mounting_offset, joint_offset));
} else {
if (!only_pressure_ && !only_imu_) {
ROS_WARN("Could not identify device for ID %d", id);
}
}
pinged.push_back(name);
}
}
}
// create a servo bus interface if there were servos found on this bus
if (servos_on_port.size() > 0) {
ServoBusInterface *interface = new ServoBusInterface(driver, servos_on_port);
interfaces_on_port.push_back(interface);
servo_interface_.addBusInterface(interface);
}
// add vector of interfaces on this port to overall collection of interfaces
interfaces_.push_back(interfaces_on_port);
}
if (pinged.size() != dxl_devices.size()) {
// when we only have 1 or two devices its only the core
if (pinged.empty() || pinged.size() == 1 || pinged.size() == 2) {
ROS_ERROR("Could not start ros control. Power is off!");
speakError(speak_pub_, "Could not start ros control. Power is off!");
} else {
if (first_ping_error_) {
first_ping_error_ = false;
} else {
ROS_ERROR("Could not ping all devices!");
speakError(speak_pub_, "error starting ros control");
// check which devices were not pinged successful
for (std::pair<std::string, int> &device : dxl_devices) {
if (std::find(pinged.begin(), pinged.end(), device.first) != pinged.end()) {
} else {
ROS_ERROR("%s with id %d missing", device.first.c_str(), device.second);
}
}
}
}
return false;
} else {
speakError(speak_pub_, "ross control startup successful");
return true;
}
}
void threaded_init(std::vector<hardware_interface::RobotHW *> &port_interfaces,
ros::NodeHandle &root_nh,
int &success) {
success = true;
for (hardware_interface::RobotHW *interface : port_interfaces) {
// giving 2 times same node handle to keep interface of base class, dirty
success &= interface->init(root_nh, root_nh);
}
}
bool WolfgangHardwareInterface::init(ros::NodeHandle &root_nh) {
// iterate through all ports
std::vector<std::thread> threads;
std::vector<int *> successes;
int i = 0;
for (std::vector<hardware_interface::RobotHW *> &port_interfaces : interfaces_) {
// iterate through all interfaces on this port
int suc = 0;
successes.push_back(&suc);
threads.push_back(std::thread(threaded_init, std::ref(port_interfaces), std::ref(root_nh), std::ref(suc)));
i++;
}
// wait for all inits to finish
for (std::thread &thread : threads) {
thread.join();
}
// see if all inits were successfull
bool success = true;
for (bool s : successes) {
success &= s;
}
// init servo interface last after all servo busses are there
success &= servo_interface_.init(root_nh, root_nh);
return success;
}
void threaded_read(std::vector<hardware_interface::RobotHW *> &port_interfaces,
const ros::Time &t,
const ros::Duration &dt) {
for (hardware_interface::RobotHW *interface : port_interfaces) {
// giving 2 times same node handle to keep interface of base class, dirty
interface->read(t, dt);
}
}
void WolfgangHardwareInterface::read(const ros::Time &t, const ros::Duration &dt) {
std::vector<std::thread> threads;
// start all reads
for (std::vector<hardware_interface::RobotHW *> &port_interfaces : interfaces_) {
threads.push_back(std::thread(threaded_read, std::ref(port_interfaces), std::ref(t), std::ref(dt)));
}
// wait for all reads to finish
for (std::thread &thread : threads) {
thread.join();
}
// aggrigate all servo values for controller
servo_interface_.read(t, dt);
}
void threaded_write(std::vector<hardware_interface::RobotHW *> &port_interfaces,
const ros::Time &t,
const ros::Duration &dt) {
for (hardware_interface::RobotHW *interface : port_interfaces) {
// giving 2 times same node handle to keep interface of base class, dirty
interface->write(t, dt);
}
}
void WolfgangHardwareInterface::write(const ros::Time &t, const ros::Duration &dt) {
// write all controller values to interfaces
servo_interface_.write(t, dt);
std::vector<std::thread> threads;
// start all reads
for (std::vector<hardware_interface::RobotHW *> &port_interfaces : interfaces_) {
threads.push_back(std::thread(threaded_write, std::ref(port_interfaces), std::ref(t), std::ref(dt)));
}
// wait for all reads to finish
for (std::thread &thread : threads) {
thread.join();
}
}
}
<|endoftext|> |
<commit_before>#include <dirent.h>
#include "../InternalTypes.h"
void DirectoryType::__constructor__() {
auto file_path = Program::argument<TextInstance>();
auto self = Program::create<DirectoryInstance>();
self->file_path = file_path->text();
Program::push(self);
}
void DirectoryType::contents() {
auto self = Program::argument<DirectoryInstance>();
auto contents = Program::create<ListInstance>();
auto directory = opendir(self->file_path.c_str());
if (directory == nullptr) {
throw ExceptionInstance(Program::create<TextInstance>("Cannot read directory contents"));
}
while(auto entry = readdir(directory)) {
contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type)));
}
Program::push(contents);
}
std::string DirectoryInstance::text() {
return "Directory(" + this->file_path + ")";
}
bool DirectoryInstance::boolean() {
return true;
}
<commit_msg>Explictly intern ExceptionInstance thrown by Directory.contents()<commit_after>#include <dirent.h>
#include "../InternalTypes.h"
void DirectoryType::__constructor__() {
auto file_path = Program::argument<TextInstance>();
auto self = Program::create<DirectoryInstance>();
self->file_path = file_path->text();
Program::push(self);
}
void DirectoryType::contents() {
auto self = Program::argument<DirectoryInstance>();
auto contents = Program::create<ListInstance>();
auto directory = opendir(self->file_path.c_str());
if (directory == nullptr) {
throw Program::create<ExceptionInstance>(Program::create<TextInstance>("Cannot read directory contents"));
}
while(auto entry = readdir(directory)) {
contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type)));
}
Program::push(contents);
}
std::string DirectoryInstance::text() {
return "Directory(" + this->file_path + ")";
}
bool DirectoryInstance::boolean() {
return true;
}
<|endoftext|> |
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "PoiRingController.h"
#include "InteriorsFloorModel.h"
#include "InteriorsModel.h"
#include "InteriorId.h"
#include "TtyHandler.h"
#include "CameraHelpers.h"
#include "RenderCamera.h"
#include "IRayPicker.h"
#include "PoiRingView.h"
#include "RenderContext.h"
#include "MathFunc.h"
#include "MathsHelpers.h"
#include "IMyPinCreationInitiationViewModel.h"
#include "IMyPinCreationModel.h"
#include "EarthConstants.h"
#include "TerrainHeightProvider.h"
#include "TransformHelpers.h"
#include "VectorMath.h"
#include "InteriorController.h"
#include "InteriorHeightHelpers.h"
#include "ScreenProperties.h"
namespace ExampleApp
{
namespace MyPinCreation
{
namespace PoiRing
{
namespace SdkModel
{
namespace
{
float CalculateAltitudeBasedSphereOuterScale(float altitude)
{
const float minAltitude = 10.f;
const float maxAltitude = 1500.f;
const float lowAltitudeScale = 0.05f;
const float highAltitudeScale = 1.0f;
float t = Eegeo::Math::Clamp01((altitude - minAltitude)/(maxAltitude-minAltitude));
return Eegeo::Math::Lerp(lowAltitudeScale, highAltitudeScale, t);
}
float CalculateAltitudeBasedSphereScale(float altitude, float outerRingRadiusInMeters)
{
const float minAltitude = 10.f;
const float maxAltitude = 18000.f;
const float lowAltitudeSphereScale = outerRingRadiusInMeters - 0.5f;
const float highAltitudeSphereScale = outerRingRadiusInMeters - 100.f;
return lowAltitudeSphereScale + (((altitude - minAltitude)/maxAltitude) * (highAltitudeSphereScale - lowAltitudeSphereScale));
}
bool RingIsOnScreen(const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& position, float radius)
{
const Eegeo::Geometry::Frustum& frustum = renderCamera.GetFrustum();
const Eegeo::dv3 cameraRelativePosition = position - renderCamera.GetEcefLocation();
for (int i = 0; i < Eegeo::Geometry::Frustum::PLANES_COUNT; ++i)
{
const Eegeo::Geometry::Plane& p = frustum.planes[i];
double signedDist = p.a * cameraRelativePosition.GetX() + p.b * cameraRelativePosition.GetY() + p.c * cameraRelativePosition.GetZ() + p.d;
if (signedDist < -radius)
{
return false;
}
}
return true;
}
}
PoiRingController::PoiRingController(MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel,
PoiRingView& poiRingView,
Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService,
Eegeo::Resources::Terrain::Heights::TerrainHeightProvider& terrainHeightProvider,
Eegeo::Resources::Interiors::InteriorController& interiorController,
Eegeo::Rendering::ScreenProperties& screenProperties)
: m_myPinCreationModel(myPinCreationModel)
, m_poiRingView(poiRingView)
, m_scaleInterpolationParam(0.f)
, m_easeDurationInSeconds(1.2f)
, m_environmentFlatteningService(environmentFlatteningService)
, m_terrainHeightProvider(terrainHeightProvider)
, m_iconPosition(Eegeo::dv3::Zero())
, m_iconSize(0.0f)
, m_ringRadius(0.0f)
, m_interiorController(interiorController)
, m_screenProperties(screenProperties)
{
}
void PoiRingController::Update(float dt, const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& cameraEcefInterestPoint)
{
const bool showingInterior = m_interiorController.InteriorIsVisible();
float interiorDownScale = showingInterior ? 0.5f : 1.0f;
const float altitude = (float)(renderCamera.GetAltitude() - (m_myPinCreationModel.GetPosition().Length() - Eegeo::Space::EarthConstants::Radius));
const float outerRingRadiusInMeters = 120.f * interiorDownScale;
const float altitudeScale = CalculateAltitudeBasedSphereOuterScale(altitude);
const float transitionScale = CalculateTransitionScale(dt);
m_ringRadius = outerRingRadiusInMeters * altitudeScale * transitionScale;
const bool ringIsOnScreen = RingIsOnScreen(renderCamera, m_myPinCreationModel.GetPosition(), m_ringRadius);
m_poiRingView.SetShouldRenderRing(m_scaleInterpolationParam > 0.f && ringIsOnScreen);
if (m_myPinCreationModel.GetCreationStage() == Inactive && !ringIsOnScreen)
{
m_scaleInterpolationParam = 0.f;
}
if (m_scaleInterpolationParam < 0.01f && m_myPinCreationModel.GetCreationStage() != Details)
{
m_myPinCreationModel.SetPosition(cameraEcefInterestPoint);
}
if(m_myPinCreationModel.NeedsTerrainHeight())
{
float terrainHeight;
if(m_terrainHeightProvider.TryGetHeight(m_myPinCreationModel.GetPosition(), 11, terrainHeight))
{
m_myPinCreationModel.SetTerrainHeight(terrainHeight);
}
}
if(m_myPinCreationModel.GetCreationStage() == Ring)
{
m_myPinCreationModel.SetInterior(showingInterior);
if(showingInterior)
{
const Eegeo::Resources::Interiors::InteriorsModel *pModel = NULL;
bool success = m_interiorController.TryGetCurrentModel(pModel);
if(success)
{
const Eegeo::Resources::Interiors::InteriorId& buildingId = pModel->GetId();
m_myPinCreationModel.SetBuildingId(buildingId);
}
m_myPinCreationModel.SetFloor(m_interiorController.GetCurrentFloorIndex());
float floorHeightAboveSeaLevel = Helpers::InteriorHeightHelpers::GetFloorHeightAboveSeaLevel(*pModel, m_interiorController.GetCurrentFloorIndex());
const float floorHeightAboveTerrain = floorHeightAboveSeaLevel - m_myPinCreationModel.GetTerrainHeight();
m_myPinCreationModel.SetHeightAboveTerrain(floorHeightAboveTerrain);
}
}
Eegeo::m44 sphereTransformMatrix;
sphereTransformMatrix.Scale(m_ringRadius);
Eegeo::dv3 scaledPoint = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(m_myPinCreationModel.GetPosition(), m_environmentFlatteningService.GetCurrentScale());
Eegeo::dv3 cameraRelativePosition = scaledPoint - renderCamera.GetEcefLocation();
sphereTransformMatrix.SetRow(3, Eegeo::v4(cameraRelativePosition.ToSingle(), 1.f));
m_poiRingView.SetRingTransforms(sphereTransformMatrix);
float altitudeBasedScale = CalculateAltitudeBasedSphereScale(altitude, m_ringRadius);
m_poiRingView.SetInnerSphereScale(altitudeBasedScale);
Eegeo::dv3 unflattenedIconPosition = m_myPinCreationModel.GetPosition();
Eegeo::dv3 iconPosition = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(
unflattenedIconPosition,
m_environmentFlatteningService.GetCurrentScale());
const float assetSize = 75.f;
const float iconScale = Eegeo::Helpers::TransformHelpers::ComputeModelScaleForConstantScreenSizeWithVerticalFoV(renderCamera, iconPosition) / (m_screenProperties.GetScreenHeight()* 0.5f)*m_screenProperties.GetPixelScale() * assetSize;
m_iconSize = Eegeo::Max(iconScale * transitionScale, 0.0f);
m_poiRingView.AddIconSprite(renderCamera, iconPosition, m_iconSize);
m_iconPosition = iconPosition + (Eegeo::dv3)renderCamera.GetModelMatrix().GetRow(1) * m_iconSize * 0.5f;
}
float PoiRingController::CalculateTransitionScale(float dt)
{
float delta = m_myPinCreationModel.GetCreationStage() == Ring ? dt : -dt;
delta /= m_easeDurationInSeconds;
m_scaleInterpolationParam = Eegeo::Clamp(m_scaleInterpolationParam + delta, 0.f, 1.f);
return Eegeo::Helpers::MathsHelpers::PennerElasticEaseInOut(0.f, 1.f, m_scaleInterpolationParam);
}
void PoiRingController::GetIconPositionAndSize(Eegeo::dv3& out_positionEcef, float& out_sizeMeters) const
{
out_positionEcef = m_iconPosition;
out_sizeMeters = m_iconSize;
}
void PoiRingController::GetSpherePositionAndRadius(Eegeo::dv3& out_sphereCenterEcef, float& out_sphereRadius) const
{
out_sphereCenterEcef = m_myPinCreationModel.GetPosition();
out_sphereRadius = m_ringRadius;
}
}
}
}
}
<commit_msg>Fix for MPLY-6048. Pin creation should no longer associated pins being in the last interior entered while in exterior mode. Buddy: Ian H<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "PoiRingController.h"
#include "InteriorsFloorModel.h"
#include "InteriorsModel.h"
#include "InteriorId.h"
#include "TtyHandler.h"
#include "CameraHelpers.h"
#include "RenderCamera.h"
#include "IRayPicker.h"
#include "PoiRingView.h"
#include "RenderContext.h"
#include "MathFunc.h"
#include "MathsHelpers.h"
#include "IMyPinCreationInitiationViewModel.h"
#include "IMyPinCreationModel.h"
#include "EarthConstants.h"
#include "TerrainHeightProvider.h"
#include "TransformHelpers.h"
#include "VectorMath.h"
#include "InteriorController.h"
#include "InteriorHeightHelpers.h"
#include "ScreenProperties.h"
namespace ExampleApp
{
namespace MyPinCreation
{
namespace PoiRing
{
namespace SdkModel
{
namespace
{
float CalculateAltitudeBasedSphereOuterScale(float altitude)
{
const float minAltitude = 10.f;
const float maxAltitude = 1500.f;
const float lowAltitudeScale = 0.05f;
const float highAltitudeScale = 1.0f;
float t = Eegeo::Math::Clamp01((altitude - minAltitude)/(maxAltitude-minAltitude));
return Eegeo::Math::Lerp(lowAltitudeScale, highAltitudeScale, t);
}
float CalculateAltitudeBasedSphereScale(float altitude, float outerRingRadiusInMeters)
{
const float minAltitude = 10.f;
const float maxAltitude = 18000.f;
const float lowAltitudeSphereScale = outerRingRadiusInMeters - 0.5f;
const float highAltitudeSphereScale = outerRingRadiusInMeters - 100.f;
return lowAltitudeSphereScale + (((altitude - minAltitude)/maxAltitude) * (highAltitudeSphereScale - lowAltitudeSphereScale));
}
bool RingIsOnScreen(const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& position, float radius)
{
const Eegeo::Geometry::Frustum& frustum = renderCamera.GetFrustum();
const Eegeo::dv3 cameraRelativePosition = position - renderCamera.GetEcefLocation();
for (int i = 0; i < Eegeo::Geometry::Frustum::PLANES_COUNT; ++i)
{
const Eegeo::Geometry::Plane& p = frustum.planes[i];
double signedDist = p.a * cameraRelativePosition.GetX() + p.b * cameraRelativePosition.GetY() + p.c * cameraRelativePosition.GetZ() + p.d;
if (signedDist < -radius)
{
return false;
}
}
return true;
}
}
PoiRingController::PoiRingController(MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel,
PoiRingView& poiRingView,
Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService,
Eegeo::Resources::Terrain::Heights::TerrainHeightProvider& terrainHeightProvider,
Eegeo::Resources::Interiors::InteriorController& interiorController,
Eegeo::Rendering::ScreenProperties& screenProperties)
: m_myPinCreationModel(myPinCreationModel)
, m_poiRingView(poiRingView)
, m_scaleInterpolationParam(0.f)
, m_easeDurationInSeconds(1.2f)
, m_environmentFlatteningService(environmentFlatteningService)
, m_terrainHeightProvider(terrainHeightProvider)
, m_iconPosition(Eegeo::dv3::Zero())
, m_iconSize(0.0f)
, m_ringRadius(0.0f)
, m_interiorController(interiorController)
, m_screenProperties(screenProperties)
{
}
void PoiRingController::Update(float dt, const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& cameraEcefInterestPoint)
{
const bool showingInterior = m_interiorController.InteriorIsVisible();
float interiorDownScale = showingInterior ? 0.5f : 1.0f;
const float altitude = (float)(renderCamera.GetAltitude() - (m_myPinCreationModel.GetPosition().Length() - Eegeo::Space::EarthConstants::Radius));
const float outerRingRadiusInMeters = 120.f * interiorDownScale;
const float altitudeScale = CalculateAltitudeBasedSphereOuterScale(altitude);
const float transitionScale = CalculateTransitionScale(dt);
m_ringRadius = outerRingRadiusInMeters * altitudeScale * transitionScale;
const bool ringIsOnScreen = RingIsOnScreen(renderCamera, m_myPinCreationModel.GetPosition(), m_ringRadius);
m_poiRingView.SetShouldRenderRing(m_scaleInterpolationParam > 0.f && ringIsOnScreen);
if (m_myPinCreationModel.GetCreationStage() == Inactive && !ringIsOnScreen)
{
m_scaleInterpolationParam = 0.f;
}
if (m_scaleInterpolationParam < 0.01f && m_myPinCreationModel.GetCreationStage() != Details)
{
m_myPinCreationModel.SetPosition(cameraEcefInterestPoint);
}
if(m_myPinCreationModel.NeedsTerrainHeight())
{
float terrainHeight;
if(m_terrainHeightProvider.TryGetHeight(m_myPinCreationModel.GetPosition(), 11, terrainHeight))
{
m_myPinCreationModel.SetTerrainHeight(terrainHeight);
}
}
if(m_myPinCreationModel.GetCreationStage() == Ring)
{
m_myPinCreationModel.SetInterior(showingInterior);
if(showingInterior)
{
const Eegeo::Resources::Interiors::InteriorsModel *pModel = NULL;
bool success = m_interiorController.TryGetCurrentModel(pModel);
if(success)
{
const Eegeo::Resources::Interiors::InteriorId& buildingId = pModel->GetId();
m_myPinCreationModel.SetBuildingId(buildingId);
}
m_myPinCreationModel.SetFloor(m_interiorController.GetCurrentFloorIndex());
float floorHeightAboveSeaLevel = Helpers::InteriorHeightHelpers::GetFloorHeightAboveSeaLevel(*pModel, m_interiorController.GetCurrentFloorIndex());
const float floorHeightAboveTerrain = floorHeightAboveSeaLevel - m_myPinCreationModel.GetTerrainHeight();
m_myPinCreationModel.SetHeightAboveTerrain(floorHeightAboveTerrain);
}
else
{
m_myPinCreationModel.SetBuildingId(Eegeo::Resources::Interiors::InteriorId::NullId());
m_myPinCreationModel.SetFloor(0);
}
}
Eegeo::m44 sphereTransformMatrix;
sphereTransformMatrix.Scale(m_ringRadius);
Eegeo::dv3 scaledPoint = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(m_myPinCreationModel.GetPosition(), m_environmentFlatteningService.GetCurrentScale());
Eegeo::dv3 cameraRelativePosition = scaledPoint - renderCamera.GetEcefLocation();
sphereTransformMatrix.SetRow(3, Eegeo::v4(cameraRelativePosition.ToSingle(), 1.f));
m_poiRingView.SetRingTransforms(sphereTransformMatrix);
float altitudeBasedScale = CalculateAltitudeBasedSphereScale(altitude, m_ringRadius);
m_poiRingView.SetInnerSphereScale(altitudeBasedScale);
Eegeo::dv3 unflattenedIconPosition = m_myPinCreationModel.GetPosition();
Eegeo::dv3 iconPosition = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(
unflattenedIconPosition,
m_environmentFlatteningService.GetCurrentScale());
const float assetSize = 75.f;
const float iconScale = Eegeo::Helpers::TransformHelpers::ComputeModelScaleForConstantScreenSizeWithVerticalFoV(renderCamera, iconPosition) / (m_screenProperties.GetScreenHeight()* 0.5f)*m_screenProperties.GetPixelScale() * assetSize;
m_iconSize = Eegeo::Max(iconScale * transitionScale, 0.0f);
m_poiRingView.AddIconSprite(renderCamera, iconPosition, m_iconSize);
m_iconPosition = iconPosition + (Eegeo::dv3)renderCamera.GetModelMatrix().GetRow(1) * m_iconSize * 0.5f;
}
float PoiRingController::CalculateTransitionScale(float dt)
{
float delta = m_myPinCreationModel.GetCreationStage() == Ring ? dt : -dt;
delta /= m_easeDurationInSeconds;
m_scaleInterpolationParam = Eegeo::Clamp(m_scaleInterpolationParam + delta, 0.f, 1.f);
return Eegeo::Helpers::MathsHelpers::PennerElasticEaseInOut(0.f, 1.f, m_scaleInterpolationParam);
}
void PoiRingController::GetIconPositionAndSize(Eegeo::dv3& out_positionEcef, float& out_sizeMeters) const
{
out_positionEcef = m_iconPosition;
out_sizeMeters = m_iconSize;
}
void PoiRingController::GetSpherePositionAndRadius(Eegeo::dv3& out_sphereCenterEcef, float& out_sphereRadius) const
{
out_sphereCenterEcef = m_myPinCreationModel.GetPosition();
out_sphereRadius = m_ringRadius;
}
}
}
}
}
<|endoftext|> |
<commit_before>#include "Pipe.h"
const int Pipe::pipe_size_middle = (PIPE_SIZE / 2);
const int Pipe::pipe_size_middle_start = Pipe::pipe_size_middle - 1;
Pipe::Pipe(SDL_Surface *sprite_param, SDL_Surface *alt_sprite_param, bool top_param, bool right_param, bool down_param, bool left_param)
{
init(sprite_param, alt_sprite_param, top_param, right_param, down_param, left_param);
}
Pipe::Pipe(SDL_Surface *sprite_param, SDL_Surface *alt_sprite_param)
{
bool t = rand() & 0x1;
bool r = rand() & 0x1;
bool d = rand() & 0x1;
bool l = rand() & 0x1;
init(sprite_param, alt_sprite_param, t, r, d, l);
}
void Pipe::init(SDL_Surface *sprite_param, SDL_Surface *alt_sprite_param, bool top_param, bool right_param, bool down_param, bool left_param)
{
sprite = sprite_param;
alt_sprite = alt_sprite_param;
top = top_param;
right = right_param;
down = down_param;
left = left_param;
sprite_position.w = sprite_position.h = PIPE_SIZE;
flow = false;
flowed_pixels = time = 0;
// Sets up the sprites position based on the pipe openings
if(top == true && right == true && down == true && left == true) {
sprite_position.x = 0;
sprite_position.y = 0;
} else if(top == true && right == true && down == true) {
sprite_position.x = PIPE_SIZE * 4;
sprite_position.y = 0;
} else if(top == true && right == true && left == true) {
sprite_position.x = PIPE_SIZE * 3;
sprite_position.y = 0;
} else if(top == true && down == true && left == true) {
sprite_position.x = PIPE_SIZE * 2;
sprite_position.y = 0;
} else if(right == true && down == true && left == true) {
sprite_position.x = PIPE_SIZE;
sprite_position.y = 0;
} else if(top == true && right == true) {
sprite_position.x = PIPE_SIZE;
sprite_position.y = PIPE_SIZE;
} else if(top == true && down == true) {
sprite_position.x = PIPE_SIZE * 3;
sprite_position.y = PIPE_SIZE;
} else if(top == true && left == true) {
sprite_position.x = PIPE_SIZE * 2;
sprite_position.y = PIPE_SIZE;
} else if(right == true && down == true) {
sprite_position.x = PIPE_SIZE * 5;
sprite_position.y = 0;
} else if(right == true && left == true) {
sprite_position.x = PIPE_SIZE * 4;
sprite_position.y = PIPE_SIZE;
} else if(down == true && left == true) {
sprite_position.x = 0;
sprite_position.y = PIPE_SIZE;
} else if(top == true) {
sprite_position.x = PIPE_SIZE * 2;
sprite_position.y = PIPE_SIZE * 2;
} else if(right == true) {
sprite_position.x = PIPE_SIZE * 5;
sprite_position.y = PIPE_SIZE;
} else if(down == true) {
sprite_position.x = PIPE_SIZE;
sprite_position.y = PIPE_SIZE * 2;
} else if(left == true) {
sprite_position.x = 0;
sprite_position.y = PIPE_SIZE * 2;
} else {
sprite_position.x = PIPE_SIZE * 5;
sprite_position.y = PIPE_SIZE * 2;
}
}
void Pipe::Draw(SDL_Surface* surface, SDL_Rect* position) {
// draws the pipe
SDL_BlitSurface(alt_sprite, &sprite_position, surface, position);
unsigned int rgb = SDL_MapRGB(surface->format, 255, 0, 0);
// first half flow
SDL_Rect rect = FirstFlowRect(position, flow_start_position);
SDL_FillRect(surface, &rect, rgb);
// second half flow
if(flowed_pixels >= PIPE_SIZE / 2) {
rect = LastFlowRect(position, flow_turn_position);
SDL_FillRect(surface, &rect, rgb);
}
}
void Pipe::Update() {
if(flowed_pixels < PIPE_SIZE && flow == true) {
int current_time = SDL_GetTicks();
if(current_time > time + FLOW_SPEED) {
flowed_pixels += 2;
time = current_time;
}
}
}
bool Pipe::isBlocked (void)
{
// if it has flow then its blocked
return flow;
}
bool Pipe::hasFlowEntry(int entry) {
return (entry == FLOW_TOP && top) ||
(entry == FLOW_RIGHT && right) ||
(entry == FLOW_DOWN && down) ||
(entry == FLOW_LEFT && left);
}
void Pipe::StartFlow(int start_position) {
if(flow == false) {
flow = true;
flow_start_position = start_position;
flow_turn_position = 0;
time = SDL_GetTicks();
}
}
SDL_Rect Pipe::FirstFlowRect(SDL_Rect* position, unsigned int flow_start) {
SDL_Rect rect;
// makes it go only halfway
int max_flowed_pixels = flowed_pixels <= Pipe::pipe_size_middle ? flowed_pixels : Pipe::pipe_size_middle;
if(flow_start == FLOW_TOP) {
rect.x = position->x + Pipe::pipe_size_middle_start;
rect.y = position->y;
rect.w = FLOW_LENGTH;
rect.h = max_flowed_pixels;
} else if(flow_start == FLOW_RIGHT) {
rect.x = (position->x + PIPE_SIZE) - max_flowed_pixels;
rect.y = position->y + Pipe::pipe_size_middle_start;
rect.w = PIPE_SIZE - (PIPE_SIZE - max_flowed_pixels);
rect.h = FLOW_LENGTH;
} else if(flow_start == FLOW_DOWN) {
rect.x = position->x + Pipe::pipe_size_middle_start;
rect.y = (position->y + PIPE_SIZE) - max_flowed_pixels;
rect.w = FLOW_LENGTH;
rect.h = PIPE_SIZE - (PIPE_SIZE - max_flowed_pixels);
} else if(flow_start == FLOW_LEFT) {
rect.x = position->x;
rect.y = position->y + Pipe::pipe_size_middle_start;
rect.w = max_flowed_pixels;
rect.h = FLOW_LENGTH;
}
return rect;
}
SDL_Rect Pipe::LastFlowRect(SDL_Rect* position, unsigned int flow_end) {
SDL_Rect rect;
// makes it go only halfway
int max_flowed_pixels = flowed_pixels - Pipe::pipe_size_middle;
if(flow_end == FLOW_TOP) {
rect.x = position->x + Pipe::pipe_size_middle_start;
rect.y = (position->y + pipe_size_middle) - max_flowed_pixels;
rect.w = FLOW_LENGTH;
rect.h = PIPE_SIZE - (PIPE_SIZE - max_flowed_pixels);
} else if(flow_end == FLOW_RIGHT) {
rect.x = position->x + Pipe::pipe_size_middle;
rect.y = position->y + Pipe::pipe_size_middle_start;
rect.w = max_flowed_pixels;
rect.h = FLOW_LENGTH;
} else if(flow_end == FLOW_DOWN) {
rect.x = position->x + Pipe::pipe_size_middle_start;
rect.y = position->y + pipe_size_middle;
rect.w = FLOW_LENGTH;
rect.h = max_flowed_pixels;
} else if(flow_end == FLOW_LEFT) {
rect.x = (position->x + pipe_size_middle) - max_flowed_pixels;
rect.y = position->y + Pipe::pipe_size_middle_start;
rect.w = pipe_size_middle - (pipe_size_middle - max_flowed_pixels);
rect.h = FLOW_LENGTH;
}
return rect;
}
bool Pipe::isFlowFinished() {
return flowed_pixels == PIPE_SIZE;
}
int Pipe::getFlowStartPosition() {
return flow_start_position;
}
int Pipe::getFlowTurnPosition() {
return flow_turn_position;
}
void Pipe::setFlowTurnPosition(int direction) {
flow_turn_position = direction;
}
<commit_msg>Debug flow path algorithm only allowing the creation of pipes with 2 connections (1 in 1 out).<commit_after>#include "Pipe.h"
const int Pipe::pipe_size_middle = (PIPE_SIZE / 2);
const int Pipe::pipe_size_middle_start = Pipe::pipe_size_middle - 1;
Pipe::Pipe(SDL_Surface *sprite_param, SDL_Surface *alt_sprite_param, bool top_param, bool right_param, bool down_param, bool left_param)
{
init(sprite_param, alt_sprite_param, top_param, right_param, down_param, left_param);
}
Pipe::Pipe(SDL_Surface *sprite_param, SDL_Surface *alt_sprite_param)
{
int sum;
bool t = rand() & 0x1;
bool r = rand() & 0x1;
bool d = rand() & 0x1;
bool l = rand() & 0x1;
do {
t = rand() & 0x1;
r = rand() & 0x1;
d = rand() & 0x1;
l = rand() & 0x1;
sum = t + r + d + l;
} while (sum != 2);
init(sprite_param, alt_sprite_param, t, r, d, l);
}
void Pipe::init(SDL_Surface *sprite_param, SDL_Surface *alt_sprite_param, bool top_param, bool right_param, bool down_param, bool left_param)
{
sprite = sprite_param;
alt_sprite = alt_sprite_param;
top = top_param;
right = right_param;
down = down_param;
left = left_param;
sprite_position.w = sprite_position.h = PIPE_SIZE;
flow = false;
flowed_pixels = time = 0;
// Sets up the sprites position based on the pipe openings
if(top == true && right == true && down == true && left == true) {
sprite_position.x = 0;
sprite_position.y = 0;
} else if(top == true && right == true && down == true) {
sprite_position.x = PIPE_SIZE * 4;
sprite_position.y = 0;
} else if(top == true && right == true && left == true) {
sprite_position.x = PIPE_SIZE * 3;
sprite_position.y = 0;
} else if(top == true && down == true && left == true) {
sprite_position.x = PIPE_SIZE * 2;
sprite_position.y = 0;
} else if(right == true && down == true && left == true) {
sprite_position.x = PIPE_SIZE;
sprite_position.y = 0;
} else if(top == true && right == true) {
sprite_position.x = PIPE_SIZE;
sprite_position.y = PIPE_SIZE;
} else if(top == true && down == true) {
sprite_position.x = PIPE_SIZE * 3;
sprite_position.y = PIPE_SIZE;
} else if(top == true && left == true) {
sprite_position.x = PIPE_SIZE * 2;
sprite_position.y = PIPE_SIZE;
} else if(right == true && down == true) {
sprite_position.x = PIPE_SIZE * 5;
sprite_position.y = 0;
} else if(right == true && left == true) {
sprite_position.x = PIPE_SIZE * 4;
sprite_position.y = PIPE_SIZE;
} else if(down == true && left == true) {
sprite_position.x = 0;
sprite_position.y = PIPE_SIZE;
} else if(top == true) {
sprite_position.x = PIPE_SIZE * 2;
sprite_position.y = PIPE_SIZE * 2;
} else if(right == true) {
sprite_position.x = PIPE_SIZE * 5;
sprite_position.y = PIPE_SIZE;
} else if(down == true) {
sprite_position.x = PIPE_SIZE;
sprite_position.y = PIPE_SIZE * 2;
} else if(left == true) {
sprite_position.x = 0;
sprite_position.y = PIPE_SIZE * 2;
} else {
sprite_position.x = PIPE_SIZE * 5;
sprite_position.y = PIPE_SIZE * 2;
}
}
void Pipe::Draw(SDL_Surface* surface, SDL_Rect* position) {
// draws the pipe
SDL_BlitSurface(alt_sprite, &sprite_position, surface, position);
unsigned int rgb = SDL_MapRGB(surface->format, 255, 0, 0);
// first half flow
SDL_Rect rect = FirstFlowRect(position, flow_start_position);
SDL_FillRect(surface, &rect, rgb);
// second half flow
if(flowed_pixels >= PIPE_SIZE / 2) {
rect = LastFlowRect(position, flow_turn_position);
SDL_FillRect(surface, &rect, rgb);
}
}
void Pipe::Update() {
if(flowed_pixels < PIPE_SIZE && flow == true) {
int current_time = SDL_GetTicks();
if(current_time > time + FLOW_SPEED) {
flowed_pixels += 2;
time = current_time;
}
}
}
bool Pipe::isBlocked (void)
{
// if it has flow then its blocked
return flow;
}
bool Pipe::hasFlowEntry(int entry) {
return (entry == FLOW_TOP && top) ||
(entry == FLOW_RIGHT && right) ||
(entry == FLOW_DOWN && down) ||
(entry == FLOW_LEFT && left);
}
void Pipe::StartFlow(int start_position) {
if(flow == false) {
flow = true;
flow_start_position = start_position;
flow_turn_position = 0;
time = SDL_GetTicks();
}
}
SDL_Rect Pipe::FirstFlowRect(SDL_Rect* position, unsigned int flow_start) {
SDL_Rect rect;
// makes it go only halfway
int max_flowed_pixels = flowed_pixels <= Pipe::pipe_size_middle ? flowed_pixels : Pipe::pipe_size_middle;
if(flow_start == FLOW_TOP) {
rect.x = position->x + Pipe::pipe_size_middle_start;
rect.y = position->y;
rect.w = FLOW_LENGTH;
rect.h = max_flowed_pixels;
} else if(flow_start == FLOW_RIGHT) {
rect.x = (position->x + PIPE_SIZE) - max_flowed_pixels;
rect.y = position->y + Pipe::pipe_size_middle_start;
rect.w = PIPE_SIZE - (PIPE_SIZE - max_flowed_pixels);
rect.h = FLOW_LENGTH;
} else if(flow_start == FLOW_DOWN) {
rect.x = position->x + Pipe::pipe_size_middle_start;
rect.y = (position->y + PIPE_SIZE) - max_flowed_pixels;
rect.w = FLOW_LENGTH;
rect.h = PIPE_SIZE - (PIPE_SIZE - max_flowed_pixels);
} else if(flow_start == FLOW_LEFT) {
rect.x = position->x;
rect.y = position->y + Pipe::pipe_size_middle_start;
rect.w = max_flowed_pixels;
rect.h = FLOW_LENGTH;
}
return rect;
}
SDL_Rect Pipe::LastFlowRect(SDL_Rect* position, unsigned int flow_end) {
SDL_Rect rect;
// makes it go only halfway
int max_flowed_pixels = flowed_pixels - Pipe::pipe_size_middle;
if(flow_end == FLOW_TOP) {
rect.x = position->x + Pipe::pipe_size_middle_start;
rect.y = (position->y + pipe_size_middle) - max_flowed_pixels;
rect.w = FLOW_LENGTH;
rect.h = PIPE_SIZE - (PIPE_SIZE - max_flowed_pixels);
} else if(flow_end == FLOW_RIGHT) {
rect.x = position->x + Pipe::pipe_size_middle;
rect.y = position->y + Pipe::pipe_size_middle_start;
rect.w = max_flowed_pixels;
rect.h = FLOW_LENGTH;
} else if(flow_end == FLOW_DOWN) {
rect.x = position->x + Pipe::pipe_size_middle_start;
rect.y = position->y + pipe_size_middle;
rect.w = FLOW_LENGTH;
rect.h = max_flowed_pixels;
} else if(flow_end == FLOW_LEFT) {
rect.x = (position->x + pipe_size_middle) - max_flowed_pixels;
rect.y = position->y + Pipe::pipe_size_middle_start;
rect.w = pipe_size_middle - (pipe_size_middle - max_flowed_pixels);
rect.h = FLOW_LENGTH;
}
return rect;
}
bool Pipe::isFlowFinished() {
return flowed_pixels == PIPE_SIZE;
}
int Pipe::getFlowStartPosition() {
return flow_start_position;
}
int Pipe::getFlowTurnPosition() {
return flow_turn_position;
}
void Pipe::setFlowTurnPosition(int direction) {
flow_turn_position = direction;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Plane.cc
Language: C++
Date: $Date$
Version: $Revision$
Description:
---------------------------------------------------------------------------
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Plane.hh"
#include "vlMath.hh"
vlPlane::vlPlane()
{
this->Normal[0] = 0.0;
this->Normal[1] = 0.0;
this->Normal[2] = 1.0;
this->Origin[0] = 0.0;
this->Origin[1] = 0.0;
this->Origin[2] = 0.0;
}
void vlPlane::ProjectPoint(float x[3], float origin[3], float normal[3], float xproj[3])
{
int i;
vlMath math;
float t, xo[3];
for (i=0; i<3; i++) xo[i] = x[i] - origin[i];
t = math.Dot(normal,xo);
for (i=0; i<3; i++) xproj[i] = x[i] - t * normal[i];
}
float vlPlane::Evaluate(float x, float y, float z)
{
return ( this->Normal[0]*(x-this->Origin[0]) +
this->Normal[1]*(y-this->Origin[1]) +
this->Normal[2]*(z-this->Origin[2]) );
}
<commit_msg>*** empty log message ***<commit_after>/*=========================================================================
Program: Visualization Library
Module: Plane.cc
Language: C++
Date: $Date$
Version: $Revision$
Description:
---------------------------------------------------------------------------
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Plane.hh"
#include "vlMath.hh"
vlPlane::vlPlane()
{
this->Normal[0] = 0.0;
this->Normal[1] = 0.0;
this->Normal[2] = 1.0;
this->Origin[0] = 0.0;
this->Origin[1] = 0.0;
this->Origin[2] = 0.0;
}
// NOTE : normal assumed to have magnitude 1
void vlPlane::ProjectPoint(float x[3], float origin[3], float normal[3], float xproj[3])
{
int i;
vlMath math;
float t, xo[3];
for (i=0; i<3; i++) xo[i] = x[i] - origin[i];
t = math.Dot(normal,xo);
for (i=0; i<3; i++) xproj[i] = x[i] - t * normal[i];
}
float vlPlane::Evaluate(float x, float y, float z)
{
return ( this->Normal[0]*(x-this->Origin[0]) +
this->Normal[1]*(y-this->Origin[1]) +
this->Normal[2]*(z-this->Origin[2]) );
}
<|endoftext|> |
<commit_before>#include "RDom.h"
#include "Util.h"
#include "IROperator.h"
#include "IRPrinter.h"
namespace Halide {
using namespace Internal;
using std::string;
using std::vector;
RVar::operator Expr() const {
if (!min().defined() || !extent().defined()) {
user_error << "Use of undefined RDom dimension: " <<
(name().empty() ? "<unknown>" : name()) << "\n";
}
return Variable::make(Int(32), name(), domain());
}
Expr RVar::min() const {
if (_domain.defined()) {
return _var().min;
} else {
return Expr();
}
}
Expr RVar::extent() const {
if (_domain.defined()) {
return _var().extent;
} else {
return Expr();
}
}
const std::string &RVar::name() const {
if (_domain.defined()) {
return _var().var;
} else {
return _name;
}
}
template <int N>
ReductionDomain build_domain(ReductionVariable (&vars)[N]) {
vector<ReductionVariable> d(&vars[0], &vars[N]);
ReductionDomain dom(d);
return dom;
}
// This just initializes the predefined x, y, z, w members of RDom.
void RDom::init_vars(string name) {
static string var_names[] = { "x", "y", "z", "w" };
const std::vector<ReductionVariable> &dom_vars = dom.domain();
RVar *vars[] = { &x, &y, &z, &w };
for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) {
if (i < dom_vars.size()) {
*(vars[i]) = RVar(dom, i);
} else {
*(vars[i]) = RVar(name + "." + var_names[i]);
}
}
}
RDom::RDom(ReductionDomain d) : dom(d) {
if (d.defined()) {
init_vars("");
}
}
void RDom::initialize_from_ranges(const std::vector<std::pair<Expr, Expr>> &ranges, string name) {
if (name.empty()) {
name = make_entity_name(this, "Halide::RDom", 'r');
}
std::vector<ReductionVariable> vars;
for (size_t i = 0; i < ranges.size(); i++) {
std::string rvar_uniquifier;
switch (i) {
case 0: rvar_uniquifier = "x"; break;
case 1: rvar_uniquifier = "y"; break;
case 2: rvar_uniquifier = "z"; break;
case 3: rvar_uniquifier = "w"; break;
default: rvar_uniquifier = std::to_string(i); break;
}
ReductionVariable rv;
rv.var = name + "." + rvar_uniquifier + "$r";
rv.min = cast<int32_t>(ranges[i].first);
rv.extent = cast<int32_t>(ranges[i].second);
vars.push_back(rv);
}
dom = ReductionDomain(vars);
init_vars(name);
}
RDom::RDom(Buffer b) {
static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
std::vector<ReductionVariable> vars;
for (int i = 0; i < b.dimensions(); i++) {
ReductionVariable var = {
b.name() + "." + var_names[i],
b.min(i),
b.extent(i)
};
vars.push_back(var);
}
dom = ReductionDomain(vars);
init_vars(b.name());
}
RDom::RDom(ImageParam p) {
static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
std::vector<ReductionVariable> vars;
for (int i = 0; i < p.dimensions(); i++) {
ReductionVariable var = {
p.name() + "." + var_names[i],
p.min(i),
p.extent(i)
};
vars.push_back(var);
}
dom = ReductionDomain(vars);
init_vars(p.name());
}
int RDom::dimensions() const {
return (int)dom.domain().size();
}
RVar RDom::operator[](int i) const {
if (i == 0) return x;
if (i == 1) return y;
if (i == 2) return z;
if (i == 3) return w;
if (i < dimensions()) {
return RVar(dom, i);
}
user_error << "Reduction domain index out of bounds: " << i << "\n";
return x; // Keep the compiler happy
}
RDom::operator Expr() const {
if (dimensions() != 1) {
user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n"
<< (*this) << "\n"
<< "Only single-dimensional RDoms can be cast to Expr.\n";
}
return Expr(x);
}
RDom::operator RVar() const {
if (dimensions() != 1) {
user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n"
<< (*this) << "\n"
<< "Only single-dimensional RDoms can be cast to RVar.\n";
}
return x;
}
/** Emit an RVar in a human-readable form */
std::ostream &operator<<(std::ostream &stream, RVar v) {
stream << v.name() << "(" << v.min() << ", " << v.extent() << ")";
return stream;
}
/** Emit an RDom in a human-readable form. */
std::ostream &operator<<(std::ostream &stream, RDom dom) {
stream << "RDom(\n";
for (int i = 0; i < dom.dimensions(); i++) {
stream << " " << dom[i] << "\n";
}
stream << ")\n";
return stream;
}
}
<commit_msg>Better error messages when RDoms depend on Funcs or Vars<commit_after>#include "RDom.h"
#include "Util.h"
#include "IROperator.h"
#include "IRPrinter.h"
namespace Halide {
using namespace Internal;
using std::string;
using std::vector;
RVar::operator Expr() const {
if (!min().defined() || !extent().defined()) {
user_error << "Use of undefined RDom dimension: " <<
(name().empty() ? "<unknown>" : name()) << "\n";
}
return Variable::make(Int(32), name(), domain());
}
Expr RVar::min() const {
if (_domain.defined()) {
return _var().min;
} else {
return Expr();
}
}
Expr RVar::extent() const {
if (_domain.defined()) {
return _var().extent;
} else {
return Expr();
}
}
const std::string &RVar::name() const {
if (_domain.defined()) {
return _var().var;
} else {
return _name;
}
}
template <int N>
ReductionDomain build_domain(ReductionVariable (&vars)[N]) {
vector<ReductionVariable> d(&vars[0], &vars[N]);
ReductionDomain dom(d);
return dom;
}
// This just initializes the predefined x, y, z, w members of RDom.
void RDom::init_vars(string name) {
static string var_names[] = { "x", "y", "z", "w" };
const std::vector<ReductionVariable> &dom_vars = dom.domain();
RVar *vars[] = { &x, &y, &z, &w };
for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) {
if (i < dom_vars.size()) {
*(vars[i]) = RVar(dom, i);
} else {
*(vars[i]) = RVar(name + "." + var_names[i]);
}
}
}
RDom::RDom(ReductionDomain d) : dom(d) {
if (d.defined()) {
init_vars("");
}
}
namespace {
class CheckRDomBounds : public IRGraphVisitor {
using IRGraphVisitor::visit;
void visit(const Call *op) {
IRGraphVisitor::visit(op);
if (op->call_type == Call::Halide) {
offending_func = op->name;
}
}
void visit(const Variable *op) {
if (!op->param.defined() && !op->image.defined()) {
offending_free_var = op->name;
}
}
public:
string offending_func;
string offending_free_var;
};
}
void RDom::initialize_from_ranges(const std::vector<std::pair<Expr, Expr>> &ranges, string name) {
if (name.empty()) {
name = make_entity_name(this, "Halide::RDom", 'r');
}
std::vector<ReductionVariable> vars;
for (size_t i = 0; i < ranges.size(); i++) {
CheckRDomBounds checker;
ranges[i].first.accept(&checker);
ranges[i].second.accept(&checker);
user_assert(checker.offending_func.empty())
<< "The bounds of the RDom " << name
<< " in dimension " << i
<< " are:\n"
<< " " << ranges[i].first << " ... " << ranges[i].second << "\n"
<< "These depend on a call to the Func " << checker.offending_func << ".\n"
<< "The bounds of an RDom may not depend on a call to a Func.\n";
user_assert(checker.offending_free_var.empty())
<< "The bounds of the RDom " << name
<< " in dimension " << i
<< " are:\n"
<< " " << ranges[i].first << " ... " << ranges[i].second << "\n"
<< "These depend on the variable " << checker.offending_free_var << ".\n"
<< "The bounds of an RDom may not depend on a free variable.\n";
std::string rvar_uniquifier;
switch (i) {
case 0: rvar_uniquifier = "x"; break;
case 1: rvar_uniquifier = "y"; break;
case 2: rvar_uniquifier = "z"; break;
case 3: rvar_uniquifier = "w"; break;
default: rvar_uniquifier = std::to_string(i); break;
}
ReductionVariable rv;
rv.var = name + "." + rvar_uniquifier + "$r";
rv.min = cast<int32_t>(ranges[i].first);
rv.extent = cast<int32_t>(ranges[i].second);
vars.push_back(rv);
}
dom = ReductionDomain(vars);
init_vars(name);
}
RDom::RDom(Buffer b) {
static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
std::vector<ReductionVariable> vars;
for (int i = 0; i < b.dimensions(); i++) {
ReductionVariable var = {
b.name() + "." + var_names[i],
b.min(i),
b.extent(i)
};
vars.push_back(var);
}
dom = ReductionDomain(vars);
init_vars(b.name());
}
RDom::RDom(ImageParam p) {
static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
std::vector<ReductionVariable> vars;
for (int i = 0; i < p.dimensions(); i++) {
ReductionVariable var = {
p.name() + "." + var_names[i],
p.min(i),
p.extent(i)
};
vars.push_back(var);
}
dom = ReductionDomain(vars);
init_vars(p.name());
}
int RDom::dimensions() const {
return (int)dom.domain().size();
}
RVar RDom::operator[](int i) const {
if (i == 0) return x;
if (i == 1) return y;
if (i == 2) return z;
if (i == 3) return w;
if (i < dimensions()) {
return RVar(dom, i);
}
user_error << "Reduction domain index out of bounds: " << i << "\n";
return x; // Keep the compiler happy
}
RDom::operator Expr() const {
if (dimensions() != 1) {
user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n"
<< (*this) << "\n"
<< "Only single-dimensional RDoms can be cast to Expr.\n";
}
return Expr(x);
}
RDom::operator RVar() const {
if (dimensions() != 1) {
user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n"
<< (*this) << "\n"
<< "Only single-dimensional RDoms can be cast to RVar.\n";
}
return x;
}
/** Emit an RVar in a human-readable form */
std::ostream &operator<<(std::ostream &stream, RVar v) {
stream << v.name() << "(" << v.min() << ", " << v.extent() << ")";
return stream;
}
/** Emit an RDom in a human-readable form. */
std::ostream &operator<<(std::ostream &stream, RDom dom) {
stream << "RDom(\n";
for (int i = 0; i < dom.dimensions(); i++) {
stream << " " << dom[i] << "\n";
}
stream << ")\n";
return stream;
}
}
<|endoftext|> |
<commit_before>/*
Copyright 2014-2015 Adam Grandquist
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 Adam Grandquist
* @copyright Apache
*/
#ifndef REQL_HPP_
#define REQL_HPP_
#include "./cpp/connection.hpp"
#include "./cpp/cursor.hpp"
#include "./cpp/error.hpp"
#include "./cpp/query.hpp"
#endif // REQL_H_
<commit_msg>Fix bad end comment.<commit_after>/*
Copyright 2014-2015 Adam Grandquist
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 Adam Grandquist
* @copyright Apache
*/
#ifndef REQL_HPP_
#define REQL_HPP_
#include "./cpp/connection.hpp"
#include "./cpp/cursor.hpp"
#include "./cpp/error.hpp"
#include "./cpp/query.hpp"
#endif // REQL_HPP_
<|endoftext|> |
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005, 2006, 2007 Roman Schindlauer
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner
* Copyright (C) 2009, 2010 Peter Schüller
* Copyright (C) 2011, 2012, 2013 Christoph Redl
*
* This file is part of dlvhex.
*
* dlvhex is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* dlvhex is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file Term.cpp
* @author Christoph Redl
*
* @brief Implementation of Term.h
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include "dlvhex2/Term.h"
#include "dlvhex2/Logger.h"
#include "dlvhex2/Printhelpers.h"
#include "dlvhex2/Interpretation.h"
#include "dlvhex2/Registry.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/PluginInterface.h"
#include "dlvhex2/OrdinaryAtomTable.h"
#include <boost/foreach.hpp>
#include <map>
DLVHEX_NAMESPACE_BEGIN
Term::Term(IDKind kind, const std::vector<ID>& arguments, RegistryPtr reg): kind(kind), arguments(arguments) {
assert(ID(kind,0).isTerm());
assert(arguments.size() > 0);
updateSymbolOfNestedTerm(reg.get());
}
void Term::updateSymbolOfNestedTerm(Registry* reg){
std::stringstream ss;
ss << reg->terms.getByID(arguments[0]).symbol;
if (arguments.size() > 1){
ss << "(";
for (uint32_t i = 1; i < arguments.size(); ++i){
ss << (i > 1 ? "," : "");
if (arguments[i].isIntegerTerm()){
ss << arguments[i].address;
}else{
ss << reg->terms.getByID(arguments[i]).symbol;
}
}
ss << ")";
}
symbol = ss.str();
}
// restores the hierarchical structure of a term from a string representation
void Term::analyzeTerm(RegistryPtr reg){
// get token: function name and arguments
bool quoted = false;
bool primitive = true;
int nestedcount = 0;
int start = 0;
int end = symbol.length();
std::vector<std::string> tuple;
//DBGLOG(DBG,"Analyzing Term '" << symbol << "'");
for (int pos = 0; pos < end; ++pos){
if (symbol[pos] == '\"' &&
(pos == 0 || symbol[pos-1] != '\\')) quoted = !quoted;
if (symbol[pos] == '(' && !quoted ) {
if (nestedcount == 0) {
primitive = false;
tuple.push_back(symbol.substr(start, pos - start));
start = pos + 1;
// eliminate closing bracket
assert(symbol[end-1] == ')');
end--;
}
nestedcount++;
}
if (symbol[pos] == ')' && !quoted){
nestedcount--;
}
if (symbol[pos] == ',' && !quoted && nestedcount == 1){
tuple.push_back(symbol.substr(start, pos - start));
start = pos + 1;
}
if (pos == end - 1){
tuple.push_back(symbol.substr(start, pos - start + 1));
}
}
// we did not find a ( -> it is primitive, or
// we came into (, increased by one, and eliminated the closing )
// therefore if it is not primitive we must leave the loop at 1
assert(primitive || nestedcount == 1);
#ifndef NDEBUG
{
std::stringstream ss;
ss << "Term tuple: ";
bool first = true;
BOOST_FOREACH (std::string str, tuple){
if (!first) ss << ", ";
first = false;
ss << str;
}
DBGLOG(DBG, ss.str());
}
#endif
// convert tuple of strings to terms
arguments.clear();
if (primitive){
arguments.push_back(ID_FAIL);
if (islower(symbol[0]) || symbol[0] == '\"') kind |= ID::SUBKIND_TERM_CONSTANT;
if (isupper(symbol[0])) kind |= ID::SUBKIND_TERM_VARIABLE;
}else{
BOOST_FOREACH (std::string str, tuple){
Term t(ID::MAINKIND_TERM, str);
t.analyzeTerm(reg);
if (t.arguments[0] == ID_FAIL){
if (islower(t.symbol[0]) || t.symbol[0] == '\"') t.kind |= ID::SUBKIND_TERM_CONSTANT;
if (isupper(t.symbol[0])) t.kind |= ID::SUBKIND_TERM_VARIABLE;
}else{
t.kind |= ID::SUBKIND_TERM_NESTED;
}
ID tid = reg->storeTerm(t);
arguments.push_back(tid);
}
kind |= ID::SUBKIND_TERM_NESTED;
}
}
DLVHEX_NAMESPACE_END
<commit_msg>not putting "dummy ID" for non-nested terms<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005, 2006, 2007 Roman Schindlauer
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner
* Copyright (C) 2009, 2010 Peter Schüller
* Copyright (C) 2011, 2012, 2013 Christoph Redl
*
* This file is part of dlvhex.
*
* dlvhex is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* dlvhex is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file Term.cpp
* @author Christoph Redl
*
* @brief Implementation of Term.h
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include "dlvhex2/Term.h"
#include "dlvhex2/Logger.h"
#include "dlvhex2/Printhelpers.h"
#include "dlvhex2/Interpretation.h"
#include "dlvhex2/Registry.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/PluginInterface.h"
#include "dlvhex2/OrdinaryAtomTable.h"
#include <boost/foreach.hpp>
#include <map>
DLVHEX_NAMESPACE_BEGIN
Term::Term(IDKind kind, const std::vector<ID>& arguments, RegistryPtr reg): kind(kind), arguments(arguments) {
assert(ID(kind,0).isTerm());
assert(arguments.size() > 0);
updateSymbolOfNestedTerm(reg.get());
}
void Term::updateSymbolOfNestedTerm(Registry* reg){
std::stringstream ss;
ss << reg->terms.getByID(arguments[0]).symbol;
if (arguments.size() > 1){
ss << "(";
for (uint32_t i = 1; i < arguments.size(); ++i){
ss << (i > 1 ? "," : "");
if (arguments[i].isIntegerTerm()){
ss << arguments[i].address;
}else{
ss << reg->terms.getByID(arguments[i]).symbol;
}
}
ss << ")";
}
symbol = ss.str();
}
// restores the hierarchical structure of a term from a string representation
void Term::analyzeTerm(RegistryPtr reg){
// get token: function name and arguments
bool quoted = false;
bool primitive = true;
int nestedcount = 0;
int start = 0;
int end = symbol.length();
std::vector<std::string> tuple;
//DBGLOG(DBG,"Analyzing Term '" << symbol << "'");
for (int pos = 0; pos < end; ++pos){
if (symbol[pos] == '\"' &&
(pos == 0 || symbol[pos-1] != '\\')) quoted = !quoted;
if (symbol[pos] == '(' && !quoted ) {
if (nestedcount == 0) {
primitive = false;
tuple.push_back(symbol.substr(start, pos - start));
start = pos + 1;
// eliminate closing bracket
assert(symbol[end-1] == ')');
end--;
}
nestedcount++;
}
if (symbol[pos] == ')' && !quoted){
nestedcount--;
}
if (symbol[pos] == ',' && !quoted && nestedcount == 1){
tuple.push_back(symbol.substr(start, pos - start));
start = pos + 1;
}
if (pos == end - 1){
tuple.push_back(symbol.substr(start, pos - start + 1));
}
}
// we did not find a ( -> it is primitive, or
// we came into (, increased by one, and eliminated the closing )
// therefore if it is not primitive we must leave the loop at 1
assert(primitive || nestedcount == 1);
#ifndef NDEBUG
{
std::stringstream ss;
ss << "Term tuple: ";
bool first = true;
BOOST_FOREACH (std::string str, tuple){
if (!first) ss << ", ";
first = false;
ss << str;
}
DBGLOG(DBG, ss.str());
}
#endif
// convert tuple of strings to terms
arguments.clear();
if (primitive){
// no arguments
if (islower(symbol[0]) || symbol[0] == '\"') kind |= ID::SUBKIND_TERM_CONSTANT;
if (isupper(symbol[0])) kind |= ID::SUBKIND_TERM_VARIABLE;
}else{
BOOST_FOREACH (std::string str, tuple){
Term t(ID::MAINKIND_TERM, str);
t.analyzeTerm(reg);
if (t.arguments[0] == ID_FAIL){
if (islower(t.symbol[0]) || t.symbol[0] == '\"') t.kind |= ID::SUBKIND_TERM_CONSTANT;
if (isupper(t.symbol[0])) t.kind |= ID::SUBKIND_TERM_VARIABLE;
}else{
t.kind |= ID::SUBKIND_TERM_NESTED;
}
ID tid = reg->storeTerm(t);
arguments.push_back(tid);
}
kind |= ID::SUBKIND_TERM_NESTED;
}
}
DLVHEX_NAMESPACE_END
<|endoftext|> |
<commit_before>//2014.04.01 - 2014.04.02 - 2014.04.03 Gustaf - CTG.
/* OBJECTIVE :
=== PLAN ===
- Function to identify the start and end positions of the target inside the source string.
ok- Convert to a function and Test functionality.
- Return a list with the positions.
For each target string, just the initial position is needed.
The final can be calculated easily with the length of the target string.
*/
#include <iostream>
using namespace std;
typedef char *arrayString;
typedef int *arrayInt;
struct posIniNode
{
int posInitial;
posIniNode *next; // Pointer to the same struct.
};
typedef posIniNode *posList; // type reserved for the head pointer.
int lengthFunction(arrayString s)
{
// Determine the length of a string array.
int count = 0;
while (s[count] != 0) // not includes the "null terminator".
{
count++;
}
return count;
}
// void identifyLimits (arrayString sourceStr, arrayString targetStr, arrayInt &arrayLimitsResult)
void identifyLimits (arrayString sourceStr, arrayString targetStr, posList &positionsResult)
{
int posIni = -1, posFinal = -1;
/*
const int RESULT_SIZE = 2;
arrayInt newArrayLimits = new int[RESULT_SIZE]; // At the end it is going to point to: arrayLimitsResult.
*/
int SOURCE_SIZE = lengthFunction(sourceStr);
int TARGET_SIZE = lengthFunction(targetStr);
// --- Linked list
// Head pointer
posList newPositionsResult;
// Nodes
posIniNode *node1 = new posIniNode;
node1 -> posInitial = -1;
//Linking the list, just one node.
newPositionsResult = node1;
node1 -> next = NULL;
// Cleaning things up to avoid cross-linking.
node1 = NULL;
// ---
// -----------------------------------
// -----------------------------------
posIni = -1, posFinal = -1;
for (int i = 0; i < SOURCE_SIZE; ++i)
{
// Find first character.
if ( (posIni == -1) && (posFinal == -1) && (sourceStr[i] == targetStr[0]) )
{
posIni = i;
newPositionsResult -> posInitial = posIni; //New node????
// Handles special case of one character.
if (TARGET_SIZE == 1)
{
cout << "Target initial/final - index: " << targetStr[0] << " - " << posIni << endl;
cout << endl;
posIni = -1, posFinal = -1; // Reset.
}
// Handles cases from two characters until ...
for (int j = 1; j < TARGET_SIZE; ++j)
{
// Check second adjacent character.
if ( (posFinal == -1) && ( (i + j) == (posIni + j)) )
{
if (sourceStr[i + j] == targetStr[j])
{
posFinal = i + j;
}
if (sourceStr[i + j] != targetStr[j])
{
posIni = -1, posFinal = -1; // Reset.
}
}
// Check next adjacent character. BUT not the last.
if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j <= (TARGET_SIZE - 2)) )
{
if (sourceStr[i + j] == targetStr[j])
{
posFinal = i + j;
}
if (sourceStr[i + j] != targetStr[j])
{
posIni = -1, posFinal = -1; // Reset.
}
}
// Check last adjacent character.
if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j == (TARGET_SIZE - 1)) )
{
if (sourceStr[i + j] == targetStr[j])
{
posFinal = i + j;
cout << "Target initial - index: " << targetStr[0] << " - " << posIni << endl;
cout << "Target final - index: " << targetStr[j] << " - " << posFinal << endl;
cout << endl;
}
posIni = -1, posFinal = -1; // Reset.
}
} // internal for
} // if that check the first character.
} // external for
// -----------------------------------
// -----------------------------------
// -- To avoid a memory leak.
/*
delete[] arrayLimitsResult;
arrayLimitsResult = newArrayLimits;
*/
delete[] positionsResult;
positionsResult = newPositionsResult;
}
void identifyLimitsTester ()
{
const int ARRAY_SIZE = 9;
arrayString a = new char[ARRAY_SIZE];
a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd';
a[4] = 'a'; a[5] = 'b'; a[6] = 'c'; a[7] = 'e'; a[8] = 0;
// -- Different tests for the TARGET STRING
// const int TARGET_SIZE = 9;
// arrayString t = new char[TARGET_SIZE];
// t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 'd';
// t[4] = 'a'; t[5] = 'b'; t[6] = 'c'; t[7] = 'e'; t[8] = 'f'; t[9] = 0;
// const int TARGET_SIZE = 8;
// arrayString t = new char[TARGET_SIZE];
// t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 'd';
// t[4] = 'a'; t[5] = 'b'; t[6] = 'c'; t[7] = 'e'; t[8] = 0;
// const int TARGET_SIZE = 4;
// arrayString t = new char[TARGET_SIZE];
// t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 0;
// const int TARGET_SIZE = 3;
// arrayString t = new char[TARGET_SIZE];
// t[0] = 'a'; t[1] = 'b'; t[2] = 0;
const int TARGET_SIZE = 2; arrayString t = new char[TARGET_SIZE];
t[0] = 'a'; t[1] = 0;
/// ---
//--------------------------
// const int RESULT_SIZE = 1;
// arrayInt resultLimits = new int[RESULT_SIZE];
/*=================
struct posIniNode
{
int posInitial;
posIniNode *next; // Pointer to the same struct.
};
typedef posIniNode *posList;
==========================
*/
// -- Linked list
// Head pointer
posList resultLimits;
// Nodes
posIniNode *node1 = new posIniNode;
node1 -> posInitial = -1;
//Linking the list, just one node.
resultLimits = node1;
node1 -> next = NULL;
// Cleaning things up to avoid cross-linking.
node1 = NULL;
//-------------------------------------------------
cout << "Initial string : " << a << endl;
cout << "Target string : " << t << endl;
cout << endl;
identifyLimits(a, t, resultLimits);
cout << "Positions: " << resultLimits -> posInitial << endl;
cout << endl;
// Free dynamic memory.
delete[] a;
delete[] t;
delete[] resultLimits;
}
int main()
{
cout << "Variable-Length String Manipulation. Function to identify limits." << endl;
identifyLimitsTester();
cout << endl;
return 0;
}
<commit_msg>Chapter 04 exercice 4-3 partial progress. Now return a linked list of initial positions. Work in progress.<commit_after>//2014.04.01 - 2014.04.02 - 2014.04.03 - 2014.04.05 Gustaf - CTG.
/* OBJECTIVE :
=== PLAN ===
- Function to identify the start and end positions of the target inside the source string.
ok- Convert to a function and Test functionality.
- Return a list with the positions.
For each target string, just the initial position is needed.
The final can be calculated easily with the length of the target string.
*/
#include <iostream>
using namespace std;
typedef char *arrayString;
typedef int *arrayInt;
struct posIniNode
{
int posInitial;
posIniNode *next; // Pointer to the same struct.
};
typedef posIniNode *posList; // type reserved for the head pointer.
void addPosition(posList &posResult, int posIni)
{
// After the new node is created, it is linked into the list at the beginning.
// New node
posIniNode *newNode = new posIniNode;
newNode -> posInitial = posIni;
newNode -> next = posResult; // linked at the beginning of the list.
posResult = newNode; // new head pointer.
}
int lengthFunction(arrayString s)
{
// Determine the length of a string array.
int count = 0;
while (s[count] != 0) // not includes the "null terminator".
{
count++;
}
return count;
}
// void identifyLimits (arrayString sourceStr, arrayString targetStr, arrayInt &arrayLimitsResult)
void identifyLimits (arrayString sourceStr, arrayString targetStr, posList &positionsResult)
{
int posIni = -1, posFinal = -1;
/*
const int RESULT_SIZE = 2;
arrayInt newArrayLimits = new int[RESULT_SIZE]; // At the end it is going to point to: arrayLimitsResult.
*/
int SOURCE_SIZE = lengthFunction(sourceStr);
int TARGET_SIZE = lengthFunction(targetStr);
// --- Linked list
// Head pointer
posList newPositionsResult;
/* // Nodes
posIniNode *node1 = new posIniNode;
node1 -> posInitial = -1;
//Linking the list, just one node.
newPositionsResult = node1;
node1 -> next = NULL;
// Cleaning things up to avoid cross-linking.
node1 = NULL;
*/
// ---
// -----------------------------------
// -----------------------------------
posIni = -1, posFinal = -1;
for (int i = 0; i < SOURCE_SIZE; ++i)
{
// Find first character.
if ( (posIni == -1) && (posFinal == -1) && (sourceStr[i] == targetStr[0]) )
{
posIni = i;
// Handles special case of one character.
if (TARGET_SIZE == 1)
{
addPosition(newPositionsResult, posIni); // A new node for every new initial position.
cout << "Target initial/final - index: " << targetStr[0] << " - " << posIni << endl;
cout << endl;
posIni = -1, posFinal = -1; // Reset.
}
// Handles cases from two characters until ...
for (int j = 1; j < TARGET_SIZE; ++j)
{
// Check second adjacent character.
if ( (posFinal == -1) && ( (i + j) == (posIni + j)) )
{
if (sourceStr[i + j] == targetStr[j])
{
posFinal = i + j;
}
if (sourceStr[i + j] != targetStr[j])
{
posIni = -1, posFinal = -1; // Reset.
}
}
// Check next adjacent character. BUT not the last.
if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j <= (TARGET_SIZE - 2)) )
{
if (sourceStr[i + j] == targetStr[j])
{
posFinal = i + j;
}
if (sourceStr[i + j] != targetStr[j])
{
posIni = -1, posFinal = -1; // Reset.
}
}
// Check last adjacent character.
if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j == (TARGET_SIZE - 1)) )
{
if (sourceStr[i + j] == targetStr[j])
{
posFinal = i + j;
addPosition(newPositionsResult, posIni); // A new node for every new initial position.
cout << "Target initial - index: " << targetStr[0] << " - " << posIni << endl;
cout << "Target final - index: " << targetStr[j] << " - " << posFinal << endl;
cout << endl;
}
posIni = -1, posFinal = -1; // Reset.
}
} // for - inner
} // if - check the first character.
} // for - outer
// -----------------------------------
// -----------------------------------
// -- To avoid a memory leak.
/*
delete[] arrayLimitsResult;
arrayLimitsResult = newArrayLimits;
*/
delete[] positionsResult;
positionsResult = newPositionsResult;
}
void identifyLimitsTester ()
{
const int ARRAY_SIZE = 9;
arrayString a = new char[ARRAY_SIZE];
a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd';
a[4] = 'a'; a[5] = 'b'; a[6] = 'c'; a[7] = 'e'; a[8] = 0;
// -- Different tests for the TARGET STRING
// const int TARGET_SIZE = 9;
// arrayString t = new char[TARGET_SIZE];
// t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 'd';
// t[4] = 'a'; t[5] = 'b'; t[6] = 'c'; t[7] = 'e'; t[8] = 'f'; t[9] = 0;
// const int TARGET_SIZE = 8;
// arrayString t = new char[TARGET_SIZE];
// t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 'd';
// t[4] = 'a'; t[5] = 'b'; t[6] = 'c'; t[7] = 'e'; t[8] = 0;
const int TARGET_SIZE = 4;
arrayString t = new char[TARGET_SIZE];
t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 0;
// const int TARGET_SIZE = 3;
// arrayString t = new char[TARGET_SIZE];
// t[0] = 'b'; t[1] = 'c'; t[2] = 0;
// const int TARGET_SIZE = 2; arrayString t = new char[TARGET_SIZE];
// t[0] = 'a'; t[1] = 0;
/// ---
//--------------------------
// const int RESULT_SIZE = 1;
// arrayInt resultLimits = new int[RESULT_SIZE];
// -- Linked list
// Head pointer
posList resultLimits;
/*
// Nodes
posIniNode *node1 = new posIniNode;
node1 -> posInitial = 99;
//Linking the list, just one node.
resultLimits = node1;
node1 -> next = NULL;
// Cleaning things up to avoid cross-linking.
node1 = NULL;
*/
//-------------------------------------------------
/*
=================
struct posIniNode
{
int posInitial;
posIniNode *next; // Pointer to the same struct.
};
typedef posIniNode *posList;
==========================
*/
cout << "Initial string : " << a << endl;
cout << "Target string : " << t << endl;
cout << endl;
identifyLimits(a, t, resultLimits);
cout << "Initial Positions (reverse order): ";
posIniNode *loopPtr = resultLimits;
while (loopPtr != NULL)
{
cout << loopPtr->posInitial << " - ";
loopPtr = loopPtr->next;
}
cout << endl;
// Free dynamic memory.
delete[] a;
delete[] t;
delete[] resultLimits;
}
int main()
{
cout << "Variable-Length String Manipulation. Function to identify limits." << endl;
identifyLimitsTester();
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "meegosensorbase.h"
SensorManagerInterface* meegosensorbase::m_remoteSensorManager = 0;
const float meegosensorbase::GRAVITY_EARTH = 9.80665;
const float meegosensorbase::GRAVITY_EARTH_THOUSANDTH = 0.00980665;
const int meegosensorbase::KErrNotFound=-1;
const int meegosensorbase::KErrInUse=-14;
const char* const meegosensorbase::ALWAYS_ON = "alwaysOn";
const char* const meegosensorbase::BUFFER_SIZE = "bufferSize";
const char* const meegosensorbase::MAX_BUFFER_SIZE = "maxBufferSize";
const char* const meegosensorbase::EFFICIENT_BUFFER_SIZE = "efficientBufferSize";
meegosensorbase::meegosensorbase(QSensor *sensor)
: QSensorBackend(sensor), m_sensorInterface(0), m_bufferSize(-1), m_prevOutputRange(0), m_efficientBufferSize(1), m_maxBufferSize(1)
{
if (!m_remoteSensorManager)
m_remoteSensorManager = &SensorManagerInterface::instance();
}
meegosensorbase::~meegosensorbase()
{
if (m_sensorInterface) {
stop();
QObject::disconnect(m_sensorInterface);
delete m_sensorInterface, m_sensorInterface = 0;
}
}
void meegosensorbase::start()
{
if (m_sensorInterface) {
// dataRate
QString type = sensor()->type();
if (type!="QTapSensor" && type!="QProximitySensor"){
int dataRate = sensor()->dataRate();
int interval = dataRate>0 ? 1000 / dataRate : 0;
// for testing maximum speed
//interval = 1;
//dataRate = 1000;
qDebug() << "Setting data rate" << dataRate << "Hz (interval" << interval << "ms) for" << sensor()->identifier();
m_sensorInterface->setInterval(interval);
}
// outputRange
int currentRange = sensor()->outputRange();
int l = sensor()->outputRanges().size();
if (l>1){
if (currentRange != m_prevOutputRange){
#ifdef Q_WS_MAEMO6
bool isOk = m_sensorInterface->setDataRangeIndex(currentRange); //NOTE THAT THE CHANGE MIGHT NOT SUCCEED, FIRST COME FIRST SERVED
if (!isOk) sensorError(KErrInUse);
else m_prevOutputRange = currentRange;
#else
// TODO: remove when sensord integrated, in MeeGo env there is a delay
qoutputrange range = sensor()->outputRanges().at(currentRange);
qreal correction = 1/correctionFactor();
DataRange range1(range.minimum*correction, range.maximum*correction, range.accuracy*correction);
m_sensorInterface->requestDataRange(range1);
m_prevOutputRange = currentRange;
#endif
}
}
// always on
QVariant alwaysOn = sensor()->property(ALWAYS_ON);
alwaysOn.isValid()?
m_sensorInterface->setStandbyOverride(alwaysOn.toBool()):
m_sensorInterface->setStandbyOverride(false);
// connects after buffering checks
doConnectAfterCheck();
int returnCode = m_sensorInterface->start().error().type();
if (returnCode==0) return;
qWarning()<<"m_sensorInterface did not start, error code:"<<returnCode;
}
sensorStopped();
}
void meegosensorbase::stop()
{
if (m_sensorInterface) m_sensorInterface->stop();
}
void meegosensorbase::setRanges(qreal correctionFactor){
if (!m_sensorInterface) return;
QList<DataRange> ranges = m_sensorInterface->getAvailableDataRanges();
for (int i=0, l=ranges.size(); i<l; i++){
DataRange range = ranges.at(i);
qreal rangeMin = range.min * correctionFactor;
qreal rangeMax = range.max * correctionFactor;
qreal resolution = range.resolution * correctionFactor;
addOutputRange(rangeMin, rangeMax, resolution);
}
}
bool meegosensorbase::doConnectAfterCheck(){
if (!m_sensorInterface) return false;
// buffer size
int size = bufferSize();
if (size == m_bufferSize) return true;
m_sensorInterface->setBufferSize(size);
// if multiple->single or single->multiple or if uninitialized
if ((m_bufferSize>1 && size==1) || (m_bufferSize==1 && size>1) || m_bufferSize==-1){
m_bufferSize = size;
disconnect(this);
if (!doConnect()){
qWarning() << "Unable to connect "<< sensorName();
return false;
}
return true;
}
m_bufferSize = size;
return true;
}
const int meegosensorbase::bufferSize(){
QVariant bufferVariant = sensor()->property(BUFFER_SIZE);
int bufferSize = bufferVariant.isValid()?bufferVariant.toInt():1;
if (bufferSize==1) return 1;
// otherwise check validity
if (bufferSize<1){
qWarning()<<"bufferSize cannot be "<<bufferSize<<", must be a positive number";
return m_bufferSize>0?m_bufferSize:1;
}
if (bufferSize>m_maxBufferSize){
qWarning()<<"bufferSize cannot be "<<bufferSize<<", MAX value is "<<m_maxBufferSize;
return m_bufferSize>0?m_bufferSize:1;
}
return bufferSize;
}
const qreal meegosensorbase::correctionFactor(){return 1;}
<commit_msg>polishing<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "meegosensorbase.h"
SensorManagerInterface* meegosensorbase::m_remoteSensorManager = 0;
//According to wikipedia link http://en.wikipedia.org/wiki/Standard_gravity
//const float meegosensorbase::GRAVITY_EARTH = 9.812865328;
const float meegosensorbase::GRAVITY_EARTH_THOUSANDTH = 0.009812865328;
const int meegosensorbase::KErrNotFound=-1;
const int meegosensorbase::KErrInUse=-14;
const char* const meegosensorbase::ALWAYS_ON = "alwaysOn";
const char* const meegosensorbase::BUFFER_SIZE = "bufferSize";
const char* const meegosensorbase::MAX_BUFFER_SIZE = "maxBufferSize";
const char* const meegosensorbase::EFFICIENT_BUFFER_SIZE = "efficientBufferSize";
meegosensorbase::meegosensorbase(QSensor *sensor)
: QSensorBackend(sensor), m_sensorInterface(0), m_bufferSize(-1), m_prevOutputRange(0), m_efficientBufferSize(1), m_maxBufferSize(1)
{
if (!m_remoteSensorManager)
m_remoteSensorManager = &SensorManagerInterface::instance();
}
meegosensorbase::~meegosensorbase()
{
if (m_sensorInterface) {
stop();
QObject::disconnect(m_sensorInterface);
delete m_sensorInterface, m_sensorInterface = 0;
}
}
void meegosensorbase::start()
{
if (m_sensorInterface) {
// dataRate
QString type = sensor()->type();
if (type!="QTapSensor" && type!="QProximitySensor"){
int dataRate = sensor()->dataRate();
int interval = dataRate>0 ? 1000 / dataRate : 0;
// for testing maximum speed
//interval = 1;
//dataRate = 1000;
qDebug() << "Setting data rate" << dataRate << "Hz (interval" << interval << "ms) for" << sensor()->identifier();
m_sensorInterface->setInterval(interval);
}
// outputRange
int currentRange = sensor()->outputRange();
int l = sensor()->outputRanges().size();
if (l>1){
if (currentRange != m_prevOutputRange){
#ifdef Q_WS_MAEMO6
bool isOk = m_sensorInterface->setDataRangeIndex(currentRange); //NOTE THAT THE CHANGE MIGHT NOT SUCCEED, FIRST COME FIRST SERVED
if (!isOk) sensorError(KErrInUse);
else m_prevOutputRange = currentRange;
#else
// TODO: remove when sensord integrated, in MeeGo env there is a delay
qoutputrange range = sensor()->outputRanges().at(currentRange);
qreal correction = 1/correctionFactor();
DataRange range1(range.minimum*correction, range.maximum*correction, range.accuracy*correction);
m_sensorInterface->requestDataRange(range1);
m_prevOutputRange = currentRange;
#endif
}
}
// always on
QVariant alwaysOn = sensor()->property(ALWAYS_ON);
alwaysOn.isValid()?
m_sensorInterface->setStandbyOverride(alwaysOn.toBool()):
m_sensorInterface->setStandbyOverride(false);
// connects after buffering checks
doConnectAfterCheck();
int returnCode = m_sensorInterface->start().error().type();
if (returnCode==0) return;
qWarning()<<"m_sensorInterface did not start, error code:"<<returnCode;
}
sensorStopped();
}
void meegosensorbase::stop()
{
if (m_sensorInterface) m_sensorInterface->stop();
}
void meegosensorbase::setRanges(qreal correctionFactor){
if (!m_sensorInterface) return;
QList<DataRange> ranges = m_sensorInterface->getAvailableDataRanges();
for (int i=0, l=ranges.size(); i<l; i++){
DataRange range = ranges.at(i);
qreal rangeMin = range.min * correctionFactor;
qreal rangeMax = range.max * correctionFactor;
qreal resolution = range.resolution * correctionFactor;
addOutputRange(rangeMin, rangeMax, resolution);
}
}
bool meegosensorbase::doConnectAfterCheck(){
if (!m_sensorInterface) return false;
// buffer size
int size = bufferSize();
if (size == m_bufferSize) return true;
m_sensorInterface->setBufferSize(size);
// if multiple->single or single->multiple or if uninitialized
if ((m_bufferSize>1 && size==1) || (m_bufferSize==1 && size>1) || m_bufferSize==-1){
m_bufferSize = size;
disconnect(this);
if (!doConnect()){
qWarning() << "Unable to connect "<< sensorName();
return false;
}
return true;
}
m_bufferSize = size;
return true;
}
const int meegosensorbase::bufferSize(){
QVariant bufferVariant = sensor()->property(BUFFER_SIZE);
int bufferSize = bufferVariant.isValid()?bufferVariant.toInt():1;
if (bufferSize==1) return 1;
// otherwise check validity
if (bufferSize<1){
qWarning()<<"bufferSize cannot be "<<bufferSize<<", must be a positive number";
return m_bufferSize>0?m_bufferSize:1;
}
if (bufferSize>m_maxBufferSize){
qWarning()<<"bufferSize cannot be "<<bufferSize<<", MAX value is "<<m_maxBufferSize;
return m_bufferSize>0?m_bufferSize:1;
}
return bufferSize;
}
const qreal meegosensorbase::correctionFactor(){return 1;}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/dp16.H $ */
/* */
/* 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 dp16.H
/// @brief Subroutines to control the DP16 logic blocks
///
// *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
#ifndef _MSS_DP16_H_
#define _MSS_DP16_H_
#include <vector>
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
namespace mss
{
///
/// @brief Given a mt/s, create a PHY 'standard' bit field for that freq.
/// @param[in] i_freq the value from mss::freq for your target
/// @return uint64_t a right-aligned bitfield which can be inserted in to a buffer
///
inline uint64_t freq_bitfield_helper( const uint64_t i_freq )
{
fapi2::buffer<uint64_t> l_data(0b1000);
FAPI_DBG("freq_bitfield_helper seeing MT/s: %d", i_freq);
// Shift l_data over based on freq.
switch(i_freq)
{
// We don't support 1866 on Nimbus.
case fapi2::ENUM_ATTR_MSS_FREQ_MT1866:
l_data >>= 3;
break;
case fapi2::ENUM_ATTR_MSS_FREQ_MT2133:
l_data >>= 2;
break;
case fapi2::ENUM_ATTR_MSS_FREQ_MT2400:
l_data >>= 1;
break;
case fapi2::ENUM_ATTR_MSS_FREQ_MT2666:
l_data >>= 0;
break;
default:
FAPI_ERR("Unkown MT/s: %d", i_freq);
fapi2::Assert(false);
break;
};
return l_data;
}
// I have a dream that the PHY code can be shared among controllers. So, I drive the
// engine from a set of traits. This might be folly. Allow me to dream. BRS
///
/// @class dp16Traits
/// @brief a collection of traits associated with the PHY DP16 block
/// @tparam T fapi2::TargetType representing the PHY
///
template< fapi2::TargetType T >
class dp16Traits;
///
/// @class dp16Traits
/// @brief a collection of traits associated with the Centaur PHY
///
template<>
class dp16Traits<fapi2::TARGET_TYPE_MBA>
{
};
///
/// @class dp16Traits
/// @brief a collection of traits associated with the Nimbus PHY DP16 block
///
template<>
class dp16Traits<fapi2::TARGET_TYPE_MCA>
{
};
namespace dp16
{
///
/// @brief Configure the DP16 sysclk
/// @tparam T the fapi2 target type
/// @tparam TT the target traits
/// @param[in] i_target a target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_sysclk( const fapi2::Target<T>& i_target );
///
/// @brief Reset the training delay configureation
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target the port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_delay_values( const fapi2::Target<T>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the read clock enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_read_clock_enable( const fapi2::Target<T>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Resets the write clock enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_write_clock_enable( const fapi2::Target<T>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the data bit enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_data_bit_enable( const fapi2::Target<T>& i_target );
///
/// @brief Reset the bad-bits masks for a port
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target the target (MCA or MBA?)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
inline fapi2::ReturnCode reset_bad_bits(const fapi2::Target<T>& i_target);
///
/// @brief Configure the DP16 io_tx config0 registers
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target a fapi2 target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_io_tx_config0( const fapi2::Target<T>& i_target );
///
/// @brief Configure ADR DLL/VREG Config 1
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target a fapi2 target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_dll_vreg_config1( const fapi2::Target<T>& i_target );
///
/// Specializations
///
///
/// @brief Configure the DP16 sysclk
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_sysclk( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
///
/// @brief Reset the training delay configureation
/// @param[in] i_target the port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_delay_values( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the read clock enable registers
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_read_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the write clock enable registers
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_write_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the data bit enable registers
/// @param[in] i_target a port target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_data_bit_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target );
///
/// @brief Reset the bad-bits masks for a port
/// @tparam T the fapi2::TargetType
/// @param[in] i_target the target (MCA or MBA?)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
inline fapi2::ReturnCode reset_bad_bits( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target)
{
// Note: We need to do this ... BRS
return fapi2::FAPI2_RC_SUCCESS;
}
///
/// @brief Configure the DP16 io_tx config0 registers
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_io_tx_config0( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
///
/// @brief Configure ADR DLL/VREG Config 1
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_dll_vreg_config1( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
} // close namespace dp16
} // close namespace mss
#endif
<commit_msg>Add DLL Calibration<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/dp16.H $ */
/* */
/* 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 dp16.H
/// @brief Subroutines to control the DP16 logic blocks
///
// *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
#ifndef _MSS_DP16_H_
#define _MSS_DP16_H_
#include <vector>
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/utils/scom.H>
namespace mss
{
///
/// @brief Given a mt/s, create a PHY 'standard' bit field for that freq.
/// @param[in] i_freq the value from mss::freq for your target
/// @return uint64_t a right-aligned bitfield which can be inserted in to a buffer
///
inline uint64_t freq_bitfield_helper( const uint64_t i_freq )
{
fapi2::buffer<uint64_t> l_data(0b1000);
FAPI_DBG("freq_bitfield_helper seeing MT/s: %d", i_freq);
// Shift l_data over based on freq.
switch(i_freq)
{
// We don't support 1866 on Nimbus.
case fapi2::ENUM_ATTR_MSS_FREQ_MT1866:
l_data >>= 3;
break;
case fapi2::ENUM_ATTR_MSS_FREQ_MT2133:
l_data >>= 2;
break;
case fapi2::ENUM_ATTR_MSS_FREQ_MT2400:
l_data >>= 1;
break;
case fapi2::ENUM_ATTR_MSS_FREQ_MT2666:
l_data >>= 0;
break;
default:
FAPI_ERR("Unkown MT/s: %d", i_freq);
fapi2::Assert(false);
break;
};
return l_data;
}
// I have a dream that the PHY code can be shared among controllers. So, I drive the
// engine from a set of traits. This might be folly. Allow me to dream. BRS
///
/// @class dp16Traits
/// @brief a collection of traits associated with the PHY DP16 block
/// @tparam T fapi2::TargetType representing the PHY
///
template< fapi2::TargetType T >
class dp16Traits;
///
/// @class dp16Traits
/// @brief a collection of traits associated with the Centaur PHY
///
template<>
class dp16Traits<fapi2::TARGET_TYPE_MBA>
{
};
///
/// @class dp16Traits
/// @brief a collection of traits associated with the Nimbus PHY DP16 block
///
template<>
class dp16Traits<fapi2::TARGET_TYPE_MCA>
{
public:
// Number of DP instances
static constexpr uint64_t DP_COUNT = 5;
// Number of instances of the DLL per DP16. Used for checking parameters, the rest of the
// code assumes 2 DLL per DP16. There are no DLL in Centaur so we don't need to worry about
// any of this for some time.
static constexpr uint64_t DLL_PER_DP16 = 2;
// Vector of the DLL configuration registers. The pair represents the two DLL in per DP16
static const std::vector< std::pair<uint64_t, uint64_t> > DLL_CNFG_REG;
enum
{
DLL_CNTL_INIT_RXDLL_CAL_RESET = MCA_DDRPHY_DP16_DLL_CNTL0_P0_0_01_INIT_RXDLL_CAL_RESET,
};
};
namespace dp16
{
///
/// @brief Read DLL_CNTL
/// @tparam I DP16 instance
/// @tparam D DLL instance in the specified DP16
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to dp16Traits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, uint64_t D, fapi2::TargetType T, typename TT = dp16Traits<T> >
inline fapi2::ReturnCode read_dll_cntl( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
static_assert( I < TT::DP_COUNT, "dp16 instance out of range");
static_assert( D < TT::DLL_PER_DP16, "dll instance out of range");
// The pair represents the upper and lower bytes of the DP16 - each has its own DLL regiters
const uint64_t& l_addr = (D == 0) ? TT::DLL_CNFG_REG[I].first : TT::DLL_CNFG_REG[I].second;
FAPI_TRY( mss::getScom(i_target, l_addr, o_data) );
FAPI_INF("dll_cntl dp16<%d, %d>: 0x%016lx", I, D, o_data);
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Write DLL_CNTL
/// @tparam I DP16 instance
/// @tparam D DLL instance in the specified DP16
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to dp16Traits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, uint64_t D, fapi2::TargetType T, typename TT = dp16Traits<T> >
inline fapi2::ReturnCode write_dll_cntl( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
static_assert( I < TT::DP_COUNT, "dp16 instance out of range");
static_assert( D < TT::DLL_PER_DP16, "dll instance out of range");
// The pair represents the upper and lower bytes of the DP16 - each has its own DLL regiters
const uint64_t& l_addr = (D == 0) ? TT::DLL_CNFG_REG[I].first : TT::DLL_CNFG_REG[I].second;
FAPI_INF("dll_cntl dp16<%d,%d>: 0x%016lx", I, D, i_data);
FAPI_TRY( mss::putScom(i_target, l_addr, i_data) );
fapi_try_exit:
return fapi2::current_err;
}
//
// Reseting the DLL registers TODO RTC:156518
//
///
/// @brief Set the DLL cal reset (begins DLL cal operations)
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to dp16Traits<T>
/// @param[in] o_data the value of the register
/// @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit
/// @note Default state is 'low' as writing a 0 forces the cal to begin.
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = dp16Traits<T> >
inline void set_dll_cal_reset( fapi2::buffer<uint64_t>& o_data, const states i_state = mss::LOW )
{
FAPI_INF("set_dll_cal_reset %s", (i_state == mss::LOW ? "low" : "high"));
o_data.writeBit<TT::DLL_CNTL_INIT_RXDLL_CAL_RESET>(i_state);
}
///
/// @brief Configure the DP16 sysclk
/// @tparam T the fapi2 target type
/// @tparam TT the target traits
/// @param[in] i_target a target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_sysclk( const fapi2::Target<T>& i_target );
///
/// @brief Reset the training delay configureation
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target the port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_delay_values( const fapi2::Target<T>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the read clock enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_read_clock_enable( const fapi2::Target<T>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Resets the write clock enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_write_clock_enable( const fapi2::Target<T>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the data bit enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_data_bit_enable( const fapi2::Target<T>& i_target );
///
/// @brief Reset the bad-bits masks for a port
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target the target (MCA or MBA?)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
inline fapi2::ReturnCode reset_bad_bits(const fapi2::Target<T>& i_target);
///
/// @brief Configure the DP16 io_tx config0 registers
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target a fapi2 target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_io_tx_config0( const fapi2::Target<T>& i_target );
///
/// @brief Configure ADR DLL/VREG Config 1
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target a fapi2 target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_dll_vreg_config1( const fapi2::Target<T>& i_target );
///
/// Specializations
///
///
/// @brief Configure the DP16 sysclk
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_sysclk( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
///
/// @brief Reset the training delay configureation
/// @param[in] i_target the port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_delay_values( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the read clock enable registers
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_read_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the write clock enable registers
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_write_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const std::vector< uint64_t >& l_rank_pairs );
///
/// @brief Reset the data bit enable registers
/// @param[in] i_target a port target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_data_bit_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target );
///
/// @brief Reset the bad-bits masks for a port
/// @tparam T the fapi2::TargetType
/// @param[in] i_target the target (MCA or MBA?)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
inline fapi2::ReturnCode reset_bad_bits( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target)
{
// Note: We need to do this ... BRS
return fapi2::FAPI2_RC_SUCCESS;
}
///
/// @brief Configure the DP16 io_tx config0 registers
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_io_tx_config0( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
///
/// @brief Configure ADR DLL/VREG Config 1
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_dll_vreg_config1( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
} // close namespace dp16
} // close namespace mss
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StockChartTypeTemplate.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:25:05 $
*
* 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 CHART_STOCKCHARTTYPETEMPLATE_HXX
#define CHART_STOCKCHARTTYPETEMPLATE_HXX
#include "ChartTypeTemplate.hxx"
#include "OPropertySet.hxx"
#include "MutexContainer.hxx"
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
namespace chart
{
class StockChartTypeTemplate :
public helper::MutexContainer,
public ChartTypeTemplate,
public ::property::OPropertySet
{
public:
enum StockVariant
{
LOW_HI_CLOSE,
OPEN_LOW_HI_CLOSE,
VOL_LOW_HI_CLOSE,
VOL_OPEN_LOW_HI_CLOSE
};
explicit StockChartTypeTemplate(
::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > const & xContext,
const ::rtl::OUString & rServiceName,
StockVariant eVariant );
virtual ~StockChartTypeTemplate();
/// XServiceInfo declarations
APPHELPER_XSERVICEINFO_DECL()
/// merge XInterface implementations
DECLARE_XINTERFACE()
/// merge XTypeProvider implementations
DECLARE_XTYPEPROVIDER()
protected:
// ____ OPropertySet ____
virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
throw(::com::sun::star::beans::UnknownPropertyException);
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
// ____ XPropertySet ____
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
getPropertySetInfo()
throw (::com::sun::star::uno::RuntimeException);
// ____ XChartTypeTemplate ____
virtual sal_Bool SAL_CALL matchesTemplate(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram >& xDiagram )
throw (::com::sun::star::uno::RuntimeException);
// ____ ChartTypeTemplate ____
virtual ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartType > getDefaultChartType()
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeriesTreeParent > createDataSeriesTree(
const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > >& aSeriesSeq,
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XBoundedCoordinateSystem > & rCoordSys
);
private:
};
} // namespace chart
// CHART_STOCKCHARTTYPETEMPLATE_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2007/03/26 14:21:59 iha 1.2.4.23: #i75590# copy some aspects from old charttype during creation of new 2007/03/01 13:54:31 iha 1.2.4.22: #i71167 & i74564# keep charttype properties if possible when switching charttypes 2006/08/10 17:10:42 bm 1.2.4.21: second axis for stock charts fixed 2006/04/10 12:25:14 iha 1.2.4.20: api restructure axis, grids, scales and increments 2005/11/28 18:01:02 iha 1.2.4.19: set series to correct axis for stockcharts 2005/10/24 11:06:53 iha 1.2.4.18: coordinate system restructure 2005/10/13 17:39:06 iha 1.2.4.17: renamed BoundedCoordinateSystem to CoordinateSystem 2005/10/07 12:06:29 bm 1.2.4.16: RESYNC: (1.2-1.3); FILE MERGED 2005/08/04 11:53:43 bm 1.2.4.15: set stack mode at new series. Percent stacking is now set in adaptScales 2005/07/15 16:07:22 bm 1.2.4.14: keep more old objects on chart type changes 2005/05/09 09:51:28 bm 1.2.4.13: moved parts of API to data namespace 2004/09/15 17:32:08 bm 1.2.4.12: API simplification 2004/06/29 12:26:36 bm 1.2.4.11: XChartTypeTemplate changes 2004/05/27 17:27:14 bm 1.2.4.10: +getChartTypeForNewSeries at XChartTypeTemplate 2004/04/01 10:53:12 bm 1.2.4.9: XChartType: may return a coordinate system now 2004/03/24 19:05:26 bm 1.2.4.8: XChartTypeTemplate changed: matchesTemplate may modify the template s properties if bAdaptProperties is true 2004/03/22 15:28:21 iha 1.2.4.7: added parameter SwapXAndYAxis for horizontal bar chart to method createCoordinateSystems 2004/03/19 14:32:59 bm 1.2.4.6: XDataSource now contains XLabeledDataSources 2004/03/12 15:39:42 iha 1.2.4.5: create a secondary y axis for stock charts 2004/03/03 14:14:41 bm 1.2.4.4: create 2 coordinate-systems if there is volume 2004/03/02 16:40:45 bm 1.2.4.3: allow creating more than one coordinate system 2004/02/20 17:43:58 iha 1.2.4.2: integrate categories at ScaleData 2004/02/13 16:51:45 bm 1.2.4.1: join from changes on branch bm_post_chart01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StockChartTypeTemplate.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:52:40 $
*
* 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 CHART_STOCKCHARTTYPETEMPLATE_HXX
#define CHART_STOCKCHARTTYPETEMPLATE_HXX
#include "ChartTypeTemplate.hxx"
#include "OPropertySet.hxx"
#include "MutexContainer.hxx"
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
namespace chart
{
class StockChartTypeTemplate :
public MutexContainer,
public ChartTypeTemplate,
public ::property::OPropertySet
{
public:
enum StockVariant
{
LOW_HI_CLOSE,
OPEN_LOW_HI_CLOSE,
VOL_LOW_HI_CLOSE,
VOL_OPEN_LOW_HI_CLOSE
};
/** CTOR
@param bJapaneseStyle
If true, the candlesticks are drawn as solid white or black boxes
depending on rising or falling stock-values. Otherwise the
open-value will be drawn as a small line at the left side of a
straight vertical line, and the close-value on the right hand side.
*/
explicit StockChartTypeTemplate(
::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > const & xContext,
const ::rtl::OUString & rServiceName,
StockVariant eVariant,
bool bJapaneseStyle );
virtual ~StockChartTypeTemplate();
/// XServiceInfo declarations
APPHELPER_XSERVICEINFO_DECL()
/// merge XInterface implementations
DECLARE_XINTERFACE()
/// merge XTypeProvider implementations
DECLARE_XTYPEPROVIDER()
protected:
// ____ OPropertySet ____
virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
throw(::com::sun::star::beans::UnknownPropertyException);
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
// ____ XPropertySet ____
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
getPropertySetInfo()
throw (::com::sun::star::uno::RuntimeException);
// ____ XChartTypeTemplate ____
virtual sal_Bool SAL_CALL matchesTemplate(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram >& xDiagram,
sal_Bool bAdaptProperties )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > SAL_CALL
getChartTypeForNewSeries( const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartType > >& aFormerlyUsedChartTypes )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataInterpreter > SAL_CALL getDataInterpreter()
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL applyStyle(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries,
::sal_Int32 nChartTypeIndex,
::sal_Int32 nSeriesIndex,
::sal_Int32 nSeriesCount )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL resetStyles(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram )
throw (::com::sun::star::uno::RuntimeException);
// ChartTypeTemplate
virtual sal_Int32 getAxisCountByDimension( sal_Int32 nDimension );
// ____ ChartTypeTemplate ____
virtual void createChartTypes(
const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > > >& aSeriesSeq,
const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XCoordinateSystem > > & rCoordSys,
const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartType > > & aOldChartTypesSeq
);
private:
// todo: deprecate this variable
StockVariant m_eStockVariant;
};
} // namespace chart
// CHART_STOCKCHARTTYPETEMPLATE_HXX
#endif
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/signin/signin_manager_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/browsing_data_helper.h"
#include "chrome/browser/browsing_data/browsing_data_remover.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/android_profile_oauth2_token_service.h"
#include "chrome/browser/signin/google_auto_login_helper.h"
#include "chrome/browser/signin/profile_oauth2_token_service.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/profile_management_switches.h"
#include "jni/SigninManager_jni.h"
#if defined(ENABLE_CONFIGURATION_POLICY)
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h"
#include "components/policy/core/common/cloud/cloud_policy_core.h"
#include "components/policy/core/common/cloud/cloud_policy_store.h"
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#include "google_apis/gaia/gaia_auth_util.h"
#endif
namespace {
// A BrowsingDataRemover::Observer that clears all Profile data and then
// invokes a callback and deletes itself.
class ProfileDataRemover : public BrowsingDataRemover::Observer {
public:
ProfileDataRemover(Profile* profile, const base::Closure& callback)
: callback_(callback),
origin_loop_(base::MessageLoopProxy::current()),
remover_(BrowsingDataRemover::CreateForUnboundedRange(profile)) {
remover_->AddObserver(this);
remover_->Remove(BrowsingDataRemover::REMOVE_ALL, BrowsingDataHelper::ALL);
}
virtual ~ProfileDataRemover() {}
virtual void OnBrowsingDataRemoverDone() OVERRIDE {
remover_->RemoveObserver(this);
origin_loop_->PostTask(FROM_HERE, callback_);
origin_loop_->DeleteSoon(FROM_HERE, this);
}
private:
base::Closure callback_;
scoped_refptr<base::MessageLoopProxy> origin_loop_;
BrowsingDataRemover* remover_;
DISALLOW_COPY_AND_ASSIGN(ProfileDataRemover);
};
} // namespace
SigninManagerAndroid::SigninManagerAndroid(JNIEnv* env, jobject obj)
: profile_(NULL),
weak_factory_(this) {
java_signin_manager_.Reset(env, obj);
DCHECK(g_browser_process);
DCHECK(g_browser_process->profile_manager());
profile_ = g_browser_process->profile_manager()->GetDefaultProfile();
DCHECK(profile_);
}
SigninManagerAndroid::~SigninManagerAndroid() {}
void SigninManagerAndroid::CheckPolicyBeforeSignIn(JNIEnv* env,
jobject obj,
jstring username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
username_ = base::android::ConvertJavaStringToUTF8(env, username);
policy::UserPolicySigninService* service =
policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
service->RegisterForPolicy(
base::android::ConvertJavaStringToUTF8(env, username),
base::Bind(&SigninManagerAndroid::OnPolicyRegisterDone,
weak_factory_.GetWeakPtr()));
#else
// This shouldn't be called when ShouldLoadPolicyForUser() is false.
NOTREACHED();
base::android::ScopedJavaLocalRef<jstring> domain;
Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
java_signin_manager_.obj(),
domain.obj());
#endif
}
void SigninManagerAndroid::FetchPolicyBeforeSignIn(JNIEnv* env, jobject obj) {
#if defined(ENABLE_CONFIGURATION_POLICY)
if (!dm_token_.empty()) {
policy::UserPolicySigninService* service =
policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
service->FetchPolicyForSignedInUser(
username_,
dm_token_,
client_id_,
base::Bind(&SigninManagerAndroid::OnPolicyFetchDone,
weak_factory_.GetWeakPtr()));
dm_token_.clear();
client_id_.clear();
return;
}
#endif
// This shouldn't be called when ShouldLoadPolicyForUser() is false, or when
// CheckPolicyBeforeSignIn() failed.
NOTREACHED();
Java_SigninManager_onPolicyFetchedBeforeSignIn(env,
java_signin_manager_.obj());
}
void SigninManagerAndroid::OnSignInCompleted(JNIEnv* env,
jobject obj,
jstring username) {
SigninManagerFactory::GetForProfile(profile_)->OnExternalSigninCompleted(
base::android::ConvertJavaStringToUTF8(env, username));
}
void SigninManagerAndroid::SignOut(JNIEnv* env, jobject obj) {
SigninManagerFactory::GetForProfile(profile_)->SignOut();
}
base::android::ScopedJavaLocalRef<jstring>
SigninManagerAndroid::GetManagementDomain(JNIEnv* env, jobject obj) {
base::android::ScopedJavaLocalRef<jstring> domain;
#if defined(ENABLE_CONFIGURATION_POLICY)
policy::UserCloudPolicyManager* manager =
policy::UserCloudPolicyManagerFactory::GetForBrowserContext(profile_);
policy::CloudPolicyStore* store = manager->core()->store();
if (store && store->is_managed() && store->policy()->has_username()) {
domain.Reset(
base::android::ConvertUTF8ToJavaString(
env, gaia::ExtractDomainName(store->policy()->username())));
}
#endif
return domain;
}
void SigninManagerAndroid::WipeProfileData(JNIEnv* env, jobject obj) {
// The ProfileDataRemover deletes itself once done.
new ProfileDataRemover(
profile_,
base::Bind(&SigninManagerAndroid::OnBrowsingDataRemoverDone,
weak_factory_.GetWeakPtr()));
}
#if defined(ENABLE_CONFIGURATION_POLICY)
void SigninManagerAndroid::OnPolicyRegisterDone(
const std::string& dm_token,
const std::string& client_id) {
dm_token_ = dm_token;
client_id_ = client_id_;
JNIEnv* env = base::android::AttachCurrentThread();
base::android::ScopedJavaLocalRef<jstring> domain;
if (!dm_token_.empty()) {
DCHECK(!username_.empty());
domain.Reset(
base::android::ConvertUTF8ToJavaString(
env, gaia::ExtractDomainName(username_)));
} else {
username_.clear();
}
Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
java_signin_manager_.obj(),
domain.obj());
}
void SigninManagerAndroid::OnPolicyFetchDone(bool success) {
Java_SigninManager_onPolicyFetchedBeforeSignIn(
base::android::AttachCurrentThread(),
java_signin_manager_.obj());
}
#endif
void SigninManagerAndroid::OnBrowsingDataRemoverDone() {
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
model->RemoveAll();
// All the Profile data has been wiped. Clear the last signed in username as
// well, so that the next signin doesn't trigger the acount change dialog.
profile_->GetPrefs()->ClearPref(prefs::kGoogleServicesLastUsername);
Java_SigninManager_onProfileDataWiped(base::android::AttachCurrentThread(),
java_signin_manager_.obj());
}
void SigninManagerAndroid::LogInSignedInUser(JNIEnv* env, jobject obj) {
if (switches::IsNewProfileManagement()) {
// New Mirror code path that just fires the events and let the
// Account Reconcilor handles everything.
AndroidProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetPlatformSpecificForProfile(
profile_);
const std::string& primary_acct = token_service->GetPrimaryAccountId();
const std::vector<std::string>& ids = token_service->GetAccounts();
token_service->ValidateAccounts(primary_acct, ids);
} else {
DVLOG(1) << "SigninManagerAndroid::LogInSignedInUser "
" Manually calling GoogleAutoLoginHelper";
// Old code path that doesn't depend on the new Account Reconcilor.
// We manually login.
// AutoLogin deletes itself.
GoogleAutoLoginHelper* autoLogin = new GoogleAutoLoginHelper(profile_);
autoLogin->LogIn();
}
}
static jlong Init(JNIEnv* env, jobject obj) {
SigninManagerAndroid* signin_manager_android =
new SigninManagerAndroid(env, obj);
return reinterpret_cast<intptr_t>(signin_manager_android);
}
static jboolean ShouldLoadPolicyForUser(JNIEnv* env,
jobject obj,
jstring j_username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
std::string username =
base::android::ConvertJavaStringToUTF8(env, j_username);
return !policy::BrowserPolicyConnector::IsNonEnterpriseUser(username);
#else
return false;
#endif
}
// static
bool SigninManagerAndroid::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
<commit_msg>Fix typo in SigninManagerAndroid that left client_id unset<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/signin/signin_manager_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/browsing_data_helper.h"
#include "chrome/browser/browsing_data/browsing_data_remover.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/android_profile_oauth2_token_service.h"
#include "chrome/browser/signin/google_auto_login_helper.h"
#include "chrome/browser/signin/profile_oauth2_token_service.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/profile_management_switches.h"
#include "jni/SigninManager_jni.h"
#if defined(ENABLE_CONFIGURATION_POLICY)
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h"
#include "components/policy/core/common/cloud/cloud_policy_core.h"
#include "components/policy/core/common/cloud/cloud_policy_store.h"
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#include "google_apis/gaia/gaia_auth_util.h"
#endif
namespace {
// A BrowsingDataRemover::Observer that clears all Profile data and then
// invokes a callback and deletes itself.
class ProfileDataRemover : public BrowsingDataRemover::Observer {
public:
ProfileDataRemover(Profile* profile, const base::Closure& callback)
: callback_(callback),
origin_loop_(base::MessageLoopProxy::current()),
remover_(BrowsingDataRemover::CreateForUnboundedRange(profile)) {
remover_->AddObserver(this);
remover_->Remove(BrowsingDataRemover::REMOVE_ALL, BrowsingDataHelper::ALL);
}
virtual ~ProfileDataRemover() {}
virtual void OnBrowsingDataRemoverDone() OVERRIDE {
remover_->RemoveObserver(this);
origin_loop_->PostTask(FROM_HERE, callback_);
origin_loop_->DeleteSoon(FROM_HERE, this);
}
private:
base::Closure callback_;
scoped_refptr<base::MessageLoopProxy> origin_loop_;
BrowsingDataRemover* remover_;
DISALLOW_COPY_AND_ASSIGN(ProfileDataRemover);
};
} // namespace
SigninManagerAndroid::SigninManagerAndroid(JNIEnv* env, jobject obj)
: profile_(NULL),
weak_factory_(this) {
java_signin_manager_.Reset(env, obj);
DCHECK(g_browser_process);
DCHECK(g_browser_process->profile_manager());
profile_ = g_browser_process->profile_manager()->GetDefaultProfile();
DCHECK(profile_);
}
SigninManagerAndroid::~SigninManagerAndroid() {}
void SigninManagerAndroid::CheckPolicyBeforeSignIn(JNIEnv* env,
jobject obj,
jstring username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
username_ = base::android::ConvertJavaStringToUTF8(env, username);
policy::UserPolicySigninService* service =
policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
service->RegisterForPolicy(
base::android::ConvertJavaStringToUTF8(env, username),
base::Bind(&SigninManagerAndroid::OnPolicyRegisterDone,
weak_factory_.GetWeakPtr()));
#else
// This shouldn't be called when ShouldLoadPolicyForUser() is false.
NOTREACHED();
base::android::ScopedJavaLocalRef<jstring> domain;
Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
java_signin_manager_.obj(),
domain.obj());
#endif
}
void SigninManagerAndroid::FetchPolicyBeforeSignIn(JNIEnv* env, jobject obj) {
#if defined(ENABLE_CONFIGURATION_POLICY)
if (!dm_token_.empty()) {
policy::UserPolicySigninService* service =
policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
service->FetchPolicyForSignedInUser(
username_,
dm_token_,
client_id_,
base::Bind(&SigninManagerAndroid::OnPolicyFetchDone,
weak_factory_.GetWeakPtr()));
dm_token_.clear();
client_id_.clear();
return;
}
#endif
// This shouldn't be called when ShouldLoadPolicyForUser() is false, or when
// CheckPolicyBeforeSignIn() failed.
NOTREACHED();
Java_SigninManager_onPolicyFetchedBeforeSignIn(env,
java_signin_manager_.obj());
}
void SigninManagerAndroid::OnSignInCompleted(JNIEnv* env,
jobject obj,
jstring username) {
SigninManagerFactory::GetForProfile(profile_)->OnExternalSigninCompleted(
base::android::ConvertJavaStringToUTF8(env, username));
}
void SigninManagerAndroid::SignOut(JNIEnv* env, jobject obj) {
SigninManagerFactory::GetForProfile(profile_)->SignOut();
}
base::android::ScopedJavaLocalRef<jstring>
SigninManagerAndroid::GetManagementDomain(JNIEnv* env, jobject obj) {
base::android::ScopedJavaLocalRef<jstring> domain;
#if defined(ENABLE_CONFIGURATION_POLICY)
policy::UserCloudPolicyManager* manager =
policy::UserCloudPolicyManagerFactory::GetForBrowserContext(profile_);
policy::CloudPolicyStore* store = manager->core()->store();
if (store && store->is_managed() && store->policy()->has_username()) {
domain.Reset(
base::android::ConvertUTF8ToJavaString(
env, gaia::ExtractDomainName(store->policy()->username())));
}
#endif
return domain;
}
void SigninManagerAndroid::WipeProfileData(JNIEnv* env, jobject obj) {
// The ProfileDataRemover deletes itself once done.
new ProfileDataRemover(
profile_,
base::Bind(&SigninManagerAndroid::OnBrowsingDataRemoverDone,
weak_factory_.GetWeakPtr()));
}
#if defined(ENABLE_CONFIGURATION_POLICY)
void SigninManagerAndroid::OnPolicyRegisterDone(
const std::string& dm_token,
const std::string& client_id) {
dm_token_ = dm_token;
client_id_ = client_id;
JNIEnv* env = base::android::AttachCurrentThread();
base::android::ScopedJavaLocalRef<jstring> domain;
if (!dm_token_.empty()) {
DCHECK(!username_.empty());
domain.Reset(
base::android::ConvertUTF8ToJavaString(
env, gaia::ExtractDomainName(username_)));
} else {
username_.clear();
}
Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
java_signin_manager_.obj(),
domain.obj());
}
void SigninManagerAndroid::OnPolicyFetchDone(bool success) {
Java_SigninManager_onPolicyFetchedBeforeSignIn(
base::android::AttachCurrentThread(),
java_signin_manager_.obj());
}
#endif
void SigninManagerAndroid::OnBrowsingDataRemoverDone() {
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
model->RemoveAll();
// All the Profile data has been wiped. Clear the last signed in username as
// well, so that the next signin doesn't trigger the acount change dialog.
profile_->GetPrefs()->ClearPref(prefs::kGoogleServicesLastUsername);
Java_SigninManager_onProfileDataWiped(base::android::AttachCurrentThread(),
java_signin_manager_.obj());
}
void SigninManagerAndroid::LogInSignedInUser(JNIEnv* env, jobject obj) {
if (switches::IsNewProfileManagement()) {
// New Mirror code path that just fires the events and let the
// Account Reconcilor handles everything.
AndroidProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetPlatformSpecificForProfile(
profile_);
const std::string& primary_acct = token_service->GetPrimaryAccountId();
const std::vector<std::string>& ids = token_service->GetAccounts();
token_service->ValidateAccounts(primary_acct, ids);
} else {
DVLOG(1) << "SigninManagerAndroid::LogInSignedInUser "
" Manually calling GoogleAutoLoginHelper";
// Old code path that doesn't depend on the new Account Reconcilor.
// We manually login.
// AutoLogin deletes itself.
GoogleAutoLoginHelper* autoLogin = new GoogleAutoLoginHelper(profile_);
autoLogin->LogIn();
}
}
static jlong Init(JNIEnv* env, jobject obj) {
SigninManagerAndroid* signin_manager_android =
new SigninManagerAndroid(env, obj);
return reinterpret_cast<intptr_t>(signin_manager_android);
}
static jboolean ShouldLoadPolicyForUser(JNIEnv* env,
jobject obj,
jstring j_username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
std::string username =
base::android::ConvertJavaStringToUTF8(env, j_username);
return !policy::BrowserPolicyConnector::IsNonEnterpriseUser(username);
#else
return false;
#endif
}
// static
bool SigninManagerAndroid::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.