text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/options/import_data_handler.h"
#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/scoped_ptr.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "chrome/browser/importer/importer_data_types.h"
ImportDataHandler::ImportDataHandler() : importer_host_(NULL) {
}
ImportDataHandler::~ImportDataHandler() {
if (importer_host_)
importer_host_->SetObserver(NULL);
}
void ImportDataHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
localized_strings->SetString("import_data_title",
l10n_util::GetStringUTF16(IDS_IMPORT_SETTINGS_TITLE));
localized_strings->SetString("import_from_label",
l10n_util::GetStringUTF16(IDS_IMPORT_FROM_LABEL));
localized_strings->SetString("import_commit",
l10n_util::GetStringUTF16(IDS_IMPORT_COMMIT));
localized_strings->SetString("import_description",
l10n_util::GetStringUTF16(IDS_IMPORT_ITEMS_LABEL));
localized_strings->SetString("import_favorites",
l10n_util::GetStringUTF16(IDS_IMPORT_FAVORITES_CHKBOX));
localized_strings->SetString("import_search",
l10n_util::GetStringUTF16(IDS_IMPORT_SEARCH_ENGINES_CHKBOX));
localized_strings->SetString("import_passwords",
l10n_util::GetStringUTF16(IDS_IMPORT_PASSWORDS_CHKBOX));
localized_strings->SetString("import_history",
l10n_util::GetStringUTF16(IDS_IMPORT_HISTORY_CHKBOX));
localized_strings->SetString("no_profile_found",
l10n_util::GetStringUTF16(IDS_IMPORT_NO_PROFILE_FOUND));
}
void ImportDataHandler::Initialize() {
importer_list_.reset(new ImporterList);
// We should not be loading profiles from the UI thread!
// Temporarily allow this until we fix
// http://code.google.com/p/chromium/issues/detail?id=60825
base::ThreadRestrictions::ScopedAllowIO allow_io;
importer_list_->DetectSourceProfiles();
int profiles_count = importer_list_->GetAvailableProfileCount();
ListValue browser_profiles;
if (profiles_count > 0) {
for (int i = 0; i < profiles_count; i++) {
const importer::ProfileInfo& source_profile =
importer_list_->GetSourceProfileInfoAt(i);
string16 browser_name = WideToUTF16Hack(source_profile.description);
uint16 browser_services = source_profile.services_supported;
DictionaryValue* browser_profile = new DictionaryValue();
browser_profile->SetString("name", browser_name);
browser_profile->SetInteger("index", i);
browser_profile->SetBoolean("history",
(browser_services & importer::HISTORY) != 0);
browser_profile->SetBoolean("favorites",
(browser_services & importer::FAVORITES) != 0);
browser_profile->SetBoolean("passwords",
(browser_services & importer::PASSWORDS) != 0);
browser_profile->SetBoolean("search",
(browser_services & importer::SEARCH_ENGINES) != 0);
browser_profiles.Append(browser_profile);
}
}
dom_ui_->CallJavascriptFunction(
L"options.ImportDataOverlay.updateSupportedBrowsers",
browser_profiles);
}
void ImportDataHandler::RegisterMessages() {
dom_ui_->RegisterMessageCallback(
"importData", NewCallback(this, &ImportDataHandler::ImportData));
}
void ImportDataHandler::ImportData(const ListValue* args) {
std::string string_value;
int browser_index;
if (!args->GetString(0, &string_value) ||
!base::StringToInt(string_value, &browser_index)) {
NOTREACHED();
return;
}
uint16 selected_items = importer::NONE;
if (args->GetString(1, &string_value) && string_value == "true") {
selected_items |= importer::HISTORY;
}
if (args->GetString(2, &string_value) && string_value == "true") {
selected_items |= importer::FAVORITES;
}
if (args->GetString(3, &string_value) && string_value == "true") {
selected_items |= importer::PASSWORDS;
}
if (args->GetString(4, &string_value) && string_value == "true") {
selected_items |= importer::SEARCH_ENGINES;
}
const ProfileInfo& source_profile =
importer_list_->GetSourceProfileInfoAt(browser_index);
uint16 supported_items = source_profile.services_supported;
uint16 import_services = (selected_items & supported_items);
if (import_services) {
FundamentalValue state(true);
dom_ui_->CallJavascriptFunction(
L"ImportDataOverlay.setImportingState", state);
// TODO(csilv): Out-of-process import has only been qualified on MacOS X,
// so we will only use it on that platform since it is required. Remove this
// conditional logic once oop import is qualified for Linux/Windows.
// http://crbug.com/22142
#if defined(OS_MACOSX)
importer_host_ = new ExternalProcessImporterHost;
#else
importer_host_ = new ImporterHost;
#endif
importer_host_->SetObserver(this);
Profile* profile = dom_ui_->GetProfile();
importer_host_->StartImportSettings(source_profile, profile,
import_services,
new ProfileWriter(profile), false);
} else {
LOG(WARNING) << "There were no settings to import from '"
<< source_profile.description << "'.";
}
}
void ImportDataHandler::ImportStarted() {
}
void ImportDataHandler::ImportItemStarted(importer::ImportItem item) {
// TODO(csilv): show progress detail in the web view.
}
void ImportDataHandler::ImportItemEnded(importer::ImportItem item) {
// TODO(csilv): show progress detail in the web view.
}
void ImportDataHandler::ImportEnded() {
importer_host_->SetObserver(NULL);
importer_host_ = NULL;
dom_ui_->CallJavascriptFunction(L"ImportDataOverlay.dismiss");
}
<commit_msg>Add supression for a DCHECK that occurs when the ImporterHost object is created.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/options/import_data_handler.h"
#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/scoped_ptr.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "chrome/browser/importer/importer_data_types.h"
ImportDataHandler::ImportDataHandler() : importer_host_(NULL) {
}
ImportDataHandler::~ImportDataHandler() {
if (importer_host_)
importer_host_->SetObserver(NULL);
}
void ImportDataHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
localized_strings->SetString("import_data_title",
l10n_util::GetStringUTF16(IDS_IMPORT_SETTINGS_TITLE));
localized_strings->SetString("import_from_label",
l10n_util::GetStringUTF16(IDS_IMPORT_FROM_LABEL));
localized_strings->SetString("import_commit",
l10n_util::GetStringUTF16(IDS_IMPORT_COMMIT));
localized_strings->SetString("import_description",
l10n_util::GetStringUTF16(IDS_IMPORT_ITEMS_LABEL));
localized_strings->SetString("import_favorites",
l10n_util::GetStringUTF16(IDS_IMPORT_FAVORITES_CHKBOX));
localized_strings->SetString("import_search",
l10n_util::GetStringUTF16(IDS_IMPORT_SEARCH_ENGINES_CHKBOX));
localized_strings->SetString("import_passwords",
l10n_util::GetStringUTF16(IDS_IMPORT_PASSWORDS_CHKBOX));
localized_strings->SetString("import_history",
l10n_util::GetStringUTF16(IDS_IMPORT_HISTORY_CHKBOX));
localized_strings->SetString("no_profile_found",
l10n_util::GetStringUTF16(IDS_IMPORT_NO_PROFILE_FOUND));
}
void ImportDataHandler::Initialize() {
importer_list_.reset(new ImporterList);
// The ImporterHost object creates an ImporterList, which calls PathExists
// one or more times. Because we are currently in the UI thread, this will
// trigger a DCHECK due to IO being done on the UI thread. For now we will
// supress the DCHECK. See the following bug for more detail:
// http://crbug.com/60825
base::ThreadRestrictions::ScopedAllowIO allow_io;
importer_list_->DetectSourceProfiles();
int profiles_count = importer_list_->GetAvailableProfileCount();
ListValue browser_profiles;
if (profiles_count > 0) {
for (int i = 0; i < profiles_count; i++) {
const importer::ProfileInfo& source_profile =
importer_list_->GetSourceProfileInfoAt(i);
string16 browser_name = WideToUTF16Hack(source_profile.description);
uint16 browser_services = source_profile.services_supported;
DictionaryValue* browser_profile = new DictionaryValue();
browser_profile->SetString("name", browser_name);
browser_profile->SetInteger("index", i);
browser_profile->SetBoolean("history",
(browser_services & importer::HISTORY) != 0);
browser_profile->SetBoolean("favorites",
(browser_services & importer::FAVORITES) != 0);
browser_profile->SetBoolean("passwords",
(browser_services & importer::PASSWORDS) != 0);
browser_profile->SetBoolean("search",
(browser_services & importer::SEARCH_ENGINES) != 0);
browser_profiles.Append(browser_profile);
}
}
dom_ui_->CallJavascriptFunction(
L"options.ImportDataOverlay.updateSupportedBrowsers",
browser_profiles);
}
void ImportDataHandler::RegisterMessages() {
dom_ui_->RegisterMessageCallback(
"importData", NewCallback(this, &ImportDataHandler::ImportData));
}
void ImportDataHandler::ImportData(const ListValue* args) {
std::string string_value;
int browser_index;
if (!args->GetString(0, &string_value) ||
!base::StringToInt(string_value, &browser_index)) {
NOTREACHED();
return;
}
uint16 selected_items = importer::NONE;
if (args->GetString(1, &string_value) && string_value == "true") {
selected_items |= importer::HISTORY;
}
if (args->GetString(2, &string_value) && string_value == "true") {
selected_items |= importer::FAVORITES;
}
if (args->GetString(3, &string_value) && string_value == "true") {
selected_items |= importer::PASSWORDS;
}
if (args->GetString(4, &string_value) && string_value == "true") {
selected_items |= importer::SEARCH_ENGINES;
}
const ProfileInfo& source_profile =
importer_list_->GetSourceProfileInfoAt(browser_index);
uint16 supported_items = source_profile.services_supported;
uint16 import_services = (selected_items & supported_items);
if (import_services) {
FundamentalValue state(true);
dom_ui_->CallJavascriptFunction(
L"ImportDataOverlay.setImportingState", state);
// The ImporterHost object creates an ImporterList, which calls PathExists
// one or more times. Because we are currently in the UI thread, this will
// trigger a DCHECK due to IO being done on the UI thread. For now we will
// supress the DCHECK. See the following bug for more detail:
// http://crbug.com/60825
base::ThreadRestrictions::ScopedAllowIO allow_io;
// TODO(csilv): Out-of-process import has only been qualified on MacOS X,
// so we will only use it on that platform since it is required. Remove this
// conditional logic once oop import is qualified for Linux/Windows.
// http://crbug.com/22142
#if defined(OS_MACOSX)
importer_host_ = new ExternalProcessImporterHost;
#else
importer_host_ = new ImporterHost;
#endif
importer_host_->SetObserver(this);
Profile* profile = dom_ui_->GetProfile();
importer_host_->StartImportSettings(source_profile, profile,
import_services,
new ProfileWriter(profile), false);
} else {
LOG(WARNING) << "There were no settings to import from '"
<< source_profile.description << "'.";
}
}
void ImportDataHandler::ImportStarted() {
}
void ImportDataHandler::ImportItemStarted(importer::ImportItem item) {
// TODO(csilv): show progress detail in the web view.
}
void ImportDataHandler::ImportItemEnded(importer::ImportItem item) {
// TODO(csilv): show progress detail in the web view.
}
void ImportDataHandler::ImportEnded() {
importer_host_->SetObserver(NULL);
importer_host_ = NULL;
dom_ui_->CallJavascriptFunction(L"ImportDataOverlay.dismiss");
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/webkit_test_platform_support.h"
namespace content {
bool WebKitTestPlatformInitialize() {
return true;
}
} // namespace
<commit_msg>[content shell] configure AHEM font for windows and check correct system setup<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/webkit_test_platform_support.h"
#include <iostream>
#include <list>
#include <string>
#include <windows.h>
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#define SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(struct_name, member) \
offsetof(struct_name, member) + \
(sizeof static_cast<struct_name*>(0)->member)
#define NONCLIENTMETRICS_SIZE_PRE_VISTA \
SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(NONCLIENTMETRICS, lfMessageFont)
namespace content {
namespace {
bool SetupFonts() {
// Load Ahem font.
// AHEM____.TTF is copied to the directory of DumpRenderTree.exe by
// WebKit.gyp.
base::FilePath base_path;
PathService::Get(base::DIR_MODULE, &base_path);
base::FilePath font_path =
base_path.Append(FILE_PATH_LITERAL("/AHEM____.TTF"));
std::string font_buffer;
if (!file_util::ReadFileToString(font_path, &font_buffer)) {
std::cerr << "Failed to load font " << WideToUTF8(font_path.value())
<< "\n";
return false;
}
DWORD num_fonts = 1;
HANDLE font_handle =
::AddFontMemResourceEx(const_cast<char*>(font_buffer.c_str()),
font_buffer.length(),
0,
&num_fonts);
if (!font_handle) {
std::cerr << "Failed to register Ahem font\n";
return false;
}
return true;
}
bool CheckLayoutTestSystemDependencies() {
std::list<std::string> errors;
// This metric will be 17 when font size is "Normal".
// The size of drop-down menus depends on it.
if (::GetSystemMetrics(SM_CXVSCROLL) != 17)
errors.push_back("Must use normal size fonts (96 dpi).");
// ClearType must be disabled, because the rendering is unpredictable.
BOOL font_smoothing_enabled;
::SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &font_smoothing_enabled, 0);
int font_smoothing_type;
::SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &font_smoothing_type, 0);
if (font_smoothing_enabled &&
(font_smoothing_type == FE_FONTSMOOTHINGCLEARTYPE))
errors.push_back("ClearType must be disabled.");
// Check that we're using the default system fonts.
OSVERSIONINFO version_info = {0};
version_info.dwOSVersionInfoSize = sizeof(version_info);
::GetVersionEx(&version_info);
bool is_vista_or_later = (version_info.dwMajorVersion >= 6);
NONCLIENTMETRICS metrics = {0};
metrics.cbSize = is_vista_or_later ? (sizeof NONCLIENTMETRICS)
: NONCLIENTMETRICS_SIZE_PRE_VISTA;
bool success = !!::SystemParametersInfo(
SPI_GETNONCLIENTMETRICS, metrics.cbSize, &metrics, 0);
CHECK(success);
LOGFONTW* system_fonts[] =
{&metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont};
const wchar_t* required_font = is_vista_or_later ? L"Segoe UI" : L"Tahoma";
int required_font_size = is_vista_or_later ? -12 : -11;
for (size_t i = 0; i < arraysize(system_fonts); ++i) {
if (system_fonts[i]->lfHeight != required_font_size ||
wcscmp(required_font, system_fonts[i]->lfFaceName)) {
errors.push_back(is_vista_or_later
? "Must use either the Aero or Basic theme."
: "Must use the default XP theme (Luna).");
break;
}
}
for (std::list<std::string>::iterator it = errors.begin(); it != errors.end();
++it) {
std::cerr << *it << "\n";
}
return errors.empty();
}
} // namespace
bool WebKitTestPlatformInitialize() {
return CheckLayoutTestSystemDependencies() && SetupFonts();
}
} // namespace content
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/keyboard_codes.h"
#include "chrome/browser/wrench_menu_model.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)
namespace {
class KeyboardAccessTest : public UITest {
public:
KeyboardAccessTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
// Use the keyboard to select "New Tab" from the app menu.
// This test depends on the fact that there are two menus and that
// New Tab is the first item in the app menu. If the menus change,
// this test will need to be changed to reflect that.
//
// If alternate_key_sequence is true, use "Alt" instead of "F10" to
// open the menu bar, and "Down" instead of "Enter" to open a menu.
void TestMenuKeyboardAccess(bool alternate_key_sequence);
DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};
void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence) {
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
// Navigate to a page in the first tab, which makes sure that focus is
// set to the browser window.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(GURL("about:")));
// The initial tab index should be 0.
int tab_index = -1;
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(0, tab_index);
// Get the focused view ID, then press a key to activate the
// page menu, then wait until the focused view changes.
int original_view_id = -1;
ASSERT_TRUE(window->GetFocusedViewID(&original_view_id));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_MENU, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_F10, 0));
int new_view_id = -1;
ASSERT_TRUE(window->WaitForFocusedViewIDToChange(
original_view_id, &new_view_id));
ASSERT_TRUE(browser->StartTrackingPopupMenus());
if (!WrenchMenuModel::IsEnabled()) {
// Press RIGHT to focus the app menu, then RETURN or DOWN to open it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RIGHT, 0));
}
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait until the popup menu actually opens.
ASSERT_TRUE(browser->WaitForPopupMenuToOpen());
// Press DOWN to select the first item, then RETURN to select it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait for the new tab to appear.
ASSERT_TRUE(browser->WaitForTabCountToBecome(2, action_timeout_ms()));
// Make sure that the new tab index is 1.
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(1, tab_index);
}
TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
TestMenuKeyboardAccess(false);
}
TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true);
}
} // namespace
#endif // defined(TOOLKIT_VIEWS)
<commit_msg>chromeos: Fix keyboard_access_uitest.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/keyboard_codes.h"
#include "chrome/browser/wrench_menu_model.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)
namespace {
class KeyboardAccessTest : public UITest {
public:
KeyboardAccessTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
// Use the keyboard to select "New Tab" from the app menu.
// This test depends on the fact that there are two menus and that
// New Tab is the first item in the app menu. If the menus change,
// this test will need to be changed to reflect that.
//
// If alternate_key_sequence is true, use "Alt" instead of "F10" to
// open the menu bar, and "Down" instead of "Enter" to open a menu.
void TestMenuKeyboardAccess(bool alternate_key_sequence);
DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};
void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence) {
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
// Navigate to a page in the first tab, which makes sure that focus is
// set to the browser window.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(GURL("about:")));
// The initial tab index should be 0.
int tab_index = -1;
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(0, tab_index);
// Get the focused view ID, then press a key to activate the
// page menu, then wait until the focused view changes.
int original_view_id = -1;
ASSERT_TRUE(window->GetFocusedViewID(&original_view_id));
base::KeyboardCode menu_key =
alternate_key_sequence ? base::VKEY_MENU : base::VKEY_F10;
#if defined(OS_CHROMEOS)
// Chrome OS has different function key accelerators, so we always use the
// menu key there.
menu_key = base::VKEY_MENU;
#endif
ASSERT_TRUE(window->SimulateOSKeyPress(menu_key, 0));
int new_view_id = -1;
ASSERT_TRUE(window->WaitForFocusedViewIDToChange(
original_view_id, &new_view_id));
ASSERT_TRUE(browser->StartTrackingPopupMenus());
if (!WrenchMenuModel::IsEnabled()) {
// Press RIGHT to focus the app menu, then RETURN or DOWN to open it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RIGHT, 0));
}
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait until the popup menu actually opens.
ASSERT_TRUE(browser->WaitForPopupMenuToOpen());
// Press DOWN to select the first item, then RETURN to select it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait for the new tab to appear.
ASSERT_TRUE(browser->WaitForTabCountToBecome(2, action_timeout_ms()));
// Make sure that the new tab index is 1.
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(1, tab_index);
}
TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
TestMenuKeyboardAccess(false);
}
TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true);
}
} // namespace
#endif // defined(TOOLKIT_VIEWS)
<|endoftext|> |
<commit_before>// Copyright 2008, Google 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 Google 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.
//
// NPAPI interactive UI tests.
//
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("npapi");
// Tests if a plugin executing a self deleting script in the context of
// a synchronous mousemove works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousMouseMove) {
if (!UITest::in_process_renderer()) {
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
HWND tab_window = NULL;
tab_proxy->GetHWND(&tab_window);
EXPECT_TRUE(IsWindow(tab_window));
show_window_ = true;
const FilePath kTestDir(FILE_PATH_LITERAL("npapi"));
const FilePath test_case(
FILE_PATH_LITERAL("execute_script_delete_in_mouse_move.html"));
GURL url = ui_test_utils::GetTestUrl(kTestDir, test_case);
NavigateToURL(url);
POINT cursor_position = {130, 130};
ClientToScreen(tab_window, &cursor_position);
double screen_width = ::GetSystemMetrics(SM_CXSCREEN) - 1;
double screen_height = ::GetSystemMetrics(SM_CYSCREEN) - 1;
double location_x = cursor_position.x * (65535.0f / screen_width);
double location_y = cursor_position.y * (65535.0f / screen_height);
INPUT input_info = {0};
input_info.type = INPUT_MOUSE;
input_info.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
input_info.mi.dx = static_cast<long>(location_x);
input_info.mi.dy = static_cast<long>(location_y);
::SendInput(1, &input_info, sizeof(INPUT));
WaitForFinish("execute_script_delete_in_mouse_move", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
}
TEST_F(NPAPIVisiblePluginTester, GetURLRequest404Response) {
if (UITest::in_process_renderer())
return;
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL(
"npapi/plugin_url_request_404.html"))));
NavigateToURL(url);
// Wait for the alert dialog and then close it.
automation()->WaitForAppModalDialog();
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_ESCAPE, 0));
WaitForFinish("geturl_404_response", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, action_max_timeout_ms());
}
// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeAlert) {
const FilePath test_case(
FILE_PATH_LITERAL("self_delete_plugin_invoke_alert.html"));
GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
// Wait for the alert dialog and then close it.
ASSERT_TRUE(automation()->WaitForAppModalDialog());
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_ESCAPE, 0));
WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
<commit_msg>[GTTF] Disable NPAPIVisiblePluginTester.SelfDeletePluginInvokeAlert which flakily exceeds test timeout.<commit_after>// Copyright 2008, Google 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 Google 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.
//
// NPAPI interactive UI tests.
//
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("npapi");
// Tests if a plugin executing a self deleting script in the context of
// a synchronous mousemove works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousMouseMove) {
if (!UITest::in_process_renderer()) {
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
HWND tab_window = NULL;
tab_proxy->GetHWND(&tab_window);
EXPECT_TRUE(IsWindow(tab_window));
show_window_ = true;
const FilePath kTestDir(FILE_PATH_LITERAL("npapi"));
const FilePath test_case(
FILE_PATH_LITERAL("execute_script_delete_in_mouse_move.html"));
GURL url = ui_test_utils::GetTestUrl(kTestDir, test_case);
NavigateToURL(url);
POINT cursor_position = {130, 130};
ClientToScreen(tab_window, &cursor_position);
double screen_width = ::GetSystemMetrics(SM_CXSCREEN) - 1;
double screen_height = ::GetSystemMetrics(SM_CYSCREEN) - 1;
double location_x = cursor_position.x * (65535.0f / screen_width);
double location_y = cursor_position.y * (65535.0f / screen_height);
INPUT input_info = {0};
input_info.type = INPUT_MOUSE;
input_info.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
input_info.mi.dx = static_cast<long>(location_x);
input_info.mi.dy = static_cast<long>(location_y);
::SendInput(1, &input_info, sizeof(INPUT));
WaitForFinish("execute_script_delete_in_mouse_move", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
}
TEST_F(NPAPIVisiblePluginTester, GetURLRequest404Response) {
if (UITest::in_process_renderer())
return;
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL(
"npapi/plugin_url_request_404.html"))));
NavigateToURL(url);
// Wait for the alert dialog and then close it.
automation()->WaitForAppModalDialog();
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_ESCAPE, 0));
WaitForFinish("geturl_404_response", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, action_max_timeout_ms());
}
// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
// Disabled, flakily exceeds timeout, http://crbug.com/46257.
TEST_F(NPAPIVisiblePluginTester, DISABLED_SelfDeletePluginInvokeAlert) {
const FilePath test_case(
FILE_PATH_LITERAL("self_delete_plugin_invoke_alert.html"));
GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
// Wait for the alert dialog and then close it.
ASSERT_TRUE(automation()->WaitForAppModalDialog());
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_ESCAPE, 0));
WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
<|endoftext|> |
<commit_before>//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Sema routines for C++ exception specification testing.
//
//===----------------------------------------------------------------------===//
#include "Sema.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "llvm/ADT/SmallPtrSet.h"
namespace clang {
static const FunctionProtoType *GetUnderlyingFunction(QualType T)
{
if (const PointerType *PtrTy = T->getAs<PointerType>())
T = PtrTy->getPointeeType();
else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
T = RefTy->getPointeeType();
else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
T = MPTy->getPointeeType();
return T->getAs<FunctionProtoType>();
}
/// CheckSpecifiedExceptionType - Check if the given type is valid in an
/// exception specification. Incomplete types, or pointers to incomplete types
/// other than void are not allowed.
bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
// FIXME: This may not correctly work with the fix for core issue 437,
// where a class's own type is considered complete within its body. But
// perhaps RequireCompleteType itself should contain this logic?
// C++ 15.4p2: A type denoted in an exception-specification shall not denote
// an incomplete type.
if (RequireCompleteType(Range.getBegin(), T,
PDiag(diag::err_incomplete_in_exception_spec) << /*direct*/0 << Range))
return true;
// C++ 15.4p2: A type denoted in an exception-specification shall not denote
// an incomplete type a pointer or reference to an incomplete type, other
// than (cv) void*.
int kind;
if (const PointerType* IT = T->getAs<PointerType>()) {
T = IT->getPointeeType();
kind = 1;
} else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
T = IT->getPointeeType();
kind = 2;
} else
return false;
if (!T->isVoidType() && RequireCompleteType(Range.getBegin(), T,
PDiag(diag::err_incomplete_in_exception_spec) << /*direct*/kind << Range))
return true;
return false;
}
/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
/// to member to a function with an exception specification. This means that
/// it is invalid to add another level of indirection.
bool Sema::CheckDistantExceptionSpec(QualType T) {
if (const PointerType *PT = T->getAs<PointerType>())
T = PT->getPointeeType();
else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
T = PT->getPointeeType();
else
return false;
const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
if (!FnT)
return false;
return FnT->hasExceptionSpec();
}
/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
/// exception specifications. Exception specifications are equivalent if
/// they allow exactly the same set of exception types. It does not matter how
/// that is achieved. See C++ [except.spec]p2.
bool Sema::CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc) {
return CheckEquivalentExceptionSpec(diag::err_mismatched_exception_spec,
diag::note_previous_declaration,
Old, OldLoc, New, NewLoc);
}
/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
/// exception specifications. Exception specifications are equivalent if
/// they allow exactly the same set of exception types. It does not matter how
/// that is achieved. See C++ [except.spec]p2.
bool Sema::CheckEquivalentExceptionSpec(
unsigned DiagID, unsigned NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc) {
bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec();
bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec();
if (OldAny && NewAny)
return false;
if (OldAny || NewAny) {
Diag(NewLoc, DiagID);
if (NoteID != 0)
Diag(OldLoc, NoteID);
return true;
}
bool Success = true;
// Both have a definite exception spec. Collect the first set, then compare
// to the second.
llvm::SmallPtrSet<const Type*, 8> OldTypes, NewTypes;
for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
E = Old->exception_end(); I != E; ++I)
OldTypes.insert(Context.getCanonicalType(*I).getTypePtr());
for (FunctionProtoType::exception_iterator I = New->exception_begin(),
E = New->exception_end(); I != E && Success; ++I) {
const Type *TypePtr = Context.getCanonicalType(*I).getTypePtr();
if(OldTypes.count(TypePtr))
NewTypes.insert(TypePtr);
else
Success = false;
}
Success = Success && OldTypes.size() == NewTypes.size();
if (Success) {
return false;
}
Diag(NewLoc, DiagID);
if (NoteID != 0)
Diag(OldLoc, NoteID);
return true;
}
/// CheckExceptionSpecSubset - Check whether the second function type's
/// exception specification is a subset (or equivalent) of the first function
/// type. This is used by override and pointer assignment checks.
bool Sema::CheckExceptionSpecSubset(unsigned DiagID, unsigned NoteID,
const FunctionProtoType *Superset, SourceLocation SuperLoc,
const FunctionProtoType *Subset, SourceLocation SubLoc) {
// FIXME: As usual, we could be more specific in our error messages, but
// that better waits until we've got types with source locations.
if (!SubLoc.isValid())
SubLoc = SuperLoc;
// If superset contains everything, we're done.
if (!Superset->hasExceptionSpec() || Superset->hasAnyExceptionSpec())
return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
// It does not. If the subset contains everything, we've failed.
if (!Subset->hasExceptionSpec() || Subset->hasAnyExceptionSpec()) {
Diag(SubLoc, DiagID);
if (NoteID != 0)
Diag(SuperLoc, NoteID);
return true;
}
// Neither contains everything. Do a proper comparison.
for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
// Take one type from the subset.
QualType CanonicalSubT = Context.getCanonicalType(*SubI);
// Unwrap pointers and references so that we can do checks within a class
// hierarchy. Don't unwrap member pointers; they don't have hierarchy
// conversions on the pointee.
bool SubIsPointer = false;
if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
CanonicalSubT = RefTy->getPointeeType();
if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
CanonicalSubT = PtrTy->getPointeeType();
SubIsPointer = true;
}
bool SubIsClass = CanonicalSubT->isRecordType();
CanonicalSubT = CanonicalSubT.getUnqualifiedType();
CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
/*DetectVirtual=*/false);
bool Contained = false;
// Make sure it's in the superset.
for (FunctionProtoType::exception_iterator SuperI =
Superset->exception_begin(), SuperE = Superset->exception_end();
SuperI != SuperE; ++SuperI) {
QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
// SubT must be SuperT or derived from it, or pointer or reference to
// such types.
if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
CanonicalSuperT = RefTy->getPointeeType();
if (SubIsPointer) {
if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
CanonicalSuperT = PtrTy->getPointeeType();
else {
continue;
}
}
CanonicalSuperT = CanonicalSuperT.getUnqualifiedType();
// If the types are the same, move on to the next type in the subset.
if (CanonicalSubT == CanonicalSuperT) {
Contained = true;
break;
}
// Otherwise we need to check the inheritance.
if (!SubIsClass || !CanonicalSuperT->isRecordType())
continue;
Paths.clear();
if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
continue;
if (Paths.isAmbiguous(CanonicalSuperT))
continue;
if (FindInaccessibleBase(CanonicalSubT, CanonicalSuperT, Paths, true))
continue;
Contained = true;
break;
}
if (!Contained) {
Diag(SubLoc, DiagID);
if (NoteID != 0)
Diag(SuperLoc, NoteID);
return true;
}
}
// We've run half the gauntlet.
return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
}
static bool CheckSpecForTypesEquivalent(Sema &S,
unsigned DiagID, unsigned NoteID,
QualType Target, SourceLocation TargetLoc,
QualType Source, SourceLocation SourceLoc)
{
const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
if (!TFunc)
return false;
const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
if (!SFunc)
return false;
return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
SFunc, SourceLoc);
}
/// CheckParamExceptionSpec - Check if the parameter and return types of the
/// two functions have equivalent exception specs. This is part of the
/// assignment and override compatibility check. We do not check the parameters
/// of parameter function pointers recursively, as no sane programmer would
/// even be able to write such a function type.
bool Sema::CheckParamExceptionSpec(unsigned NoteID,
const FunctionProtoType *Target, SourceLocation TargetLoc,
const FunctionProtoType *Source, SourceLocation SourceLoc)
{
if (CheckSpecForTypesEquivalent(*this, diag::err_return_type_specs_differ, 0,
Target->getResultType(), TargetLoc,
Source->getResultType(), SourceLoc))
return true;
// We shouldn't even testing this unless the arguments are otherwise
// compatible.
assert(Target->getNumArgs() == Source->getNumArgs() &&
"Functions have different argument counts.");
for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
if (CheckSpecForTypesEquivalent(*this, diag::err_arg_type_specs_differ, 0,
Target->getArgType(i), TargetLoc,
Source->getArgType(i), SourceLoc))
return true;
}
return false;
}
bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
{
// First we check for applicability.
// Target type must be a function, function pointer or function reference.
const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
if (!ToFunc)
return false;
// SourceType must be a function or function pointer.
const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
if (!FromFunc)
return false;
// Now we've got the correct types on both sides, check their compatibility.
// This means that the source of the conversion can only throw a subset of
// the exceptions of the target, and any exception specs on arguments or
// return types must be equivalent.
return CheckExceptionSpecSubset(diag::err_incompatible_exception_specs,
0, ToFunc, From->getSourceRange().getBegin(),
FromFunc, SourceLocation());
}
bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old) {
return CheckExceptionSpecSubset(diag::err_override_exception_spec,
diag::note_overridden_virtual_function,
Old->getType()->getAs<FunctionProtoType>(),
Old->getLocation(),
New->getType()->getAs<FunctionProtoType>(),
New->getLocation());
}
} // end namespace clang
<commit_msg>Use CanQualType in the exception specification verification type sets.<commit_after>//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Sema routines for C++ exception specification testing.
//
//===----------------------------------------------------------------------===//
#include "Sema.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "llvm/ADT/SmallPtrSet.h"
namespace clang {
static const FunctionProtoType *GetUnderlyingFunction(QualType T)
{
if (const PointerType *PtrTy = T->getAs<PointerType>())
T = PtrTy->getPointeeType();
else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
T = RefTy->getPointeeType();
else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
T = MPTy->getPointeeType();
return T->getAs<FunctionProtoType>();
}
/// CheckSpecifiedExceptionType - Check if the given type is valid in an
/// exception specification. Incomplete types, or pointers to incomplete types
/// other than void are not allowed.
bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
// FIXME: This may not correctly work with the fix for core issue 437,
// where a class's own type is considered complete within its body. But
// perhaps RequireCompleteType itself should contain this logic?
// C++ 15.4p2: A type denoted in an exception-specification shall not denote
// an incomplete type.
if (RequireCompleteType(Range.getBegin(), T,
PDiag(diag::err_incomplete_in_exception_spec) << /*direct*/0 << Range))
return true;
// C++ 15.4p2: A type denoted in an exception-specification shall not denote
// an incomplete type a pointer or reference to an incomplete type, other
// than (cv) void*.
int kind;
if (const PointerType* IT = T->getAs<PointerType>()) {
T = IT->getPointeeType();
kind = 1;
} else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
T = IT->getPointeeType();
kind = 2;
} else
return false;
if (!T->isVoidType() && RequireCompleteType(Range.getBegin(), T,
PDiag(diag::err_incomplete_in_exception_spec) << /*direct*/kind << Range))
return true;
return false;
}
/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
/// to member to a function with an exception specification. This means that
/// it is invalid to add another level of indirection.
bool Sema::CheckDistantExceptionSpec(QualType T) {
if (const PointerType *PT = T->getAs<PointerType>())
T = PT->getPointeeType();
else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
T = PT->getPointeeType();
else
return false;
const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
if (!FnT)
return false;
return FnT->hasExceptionSpec();
}
/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
/// exception specifications. Exception specifications are equivalent if
/// they allow exactly the same set of exception types. It does not matter how
/// that is achieved. See C++ [except.spec]p2.
bool Sema::CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc) {
return CheckEquivalentExceptionSpec(diag::err_mismatched_exception_spec,
diag::note_previous_declaration,
Old, OldLoc, New, NewLoc);
}
/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
/// exception specifications. Exception specifications are equivalent if
/// they allow exactly the same set of exception types. It does not matter how
/// that is achieved. See C++ [except.spec]p2.
bool Sema::CheckEquivalentExceptionSpec(
unsigned DiagID, unsigned NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc) {
bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec();
bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec();
if (OldAny && NewAny)
return false;
if (OldAny || NewAny) {
Diag(NewLoc, DiagID);
if (NoteID != 0)
Diag(OldLoc, NoteID);
return true;
}
bool Success = true;
// Both have a definite exception spec. Collect the first set, then compare
// to the second.
llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
E = Old->exception_end(); I != E; ++I)
OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
for (FunctionProtoType::exception_iterator I = New->exception_begin(),
E = New->exception_end(); I != E && Success; ++I) {
CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
if(OldTypes.count(TypePtr))
NewTypes.insert(TypePtr);
else
Success = false;
}
Success = Success && OldTypes.size() == NewTypes.size();
if (Success) {
return false;
}
Diag(NewLoc, DiagID);
if (NoteID != 0)
Diag(OldLoc, NoteID);
return true;
}
/// CheckExceptionSpecSubset - Check whether the second function type's
/// exception specification is a subset (or equivalent) of the first function
/// type. This is used by override and pointer assignment checks.
bool Sema::CheckExceptionSpecSubset(unsigned DiagID, unsigned NoteID,
const FunctionProtoType *Superset, SourceLocation SuperLoc,
const FunctionProtoType *Subset, SourceLocation SubLoc) {
// FIXME: As usual, we could be more specific in our error messages, but
// that better waits until we've got types with source locations.
if (!SubLoc.isValid())
SubLoc = SuperLoc;
// If superset contains everything, we're done.
if (!Superset->hasExceptionSpec() || Superset->hasAnyExceptionSpec())
return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
// It does not. If the subset contains everything, we've failed.
if (!Subset->hasExceptionSpec() || Subset->hasAnyExceptionSpec()) {
Diag(SubLoc, DiagID);
if (NoteID != 0)
Diag(SuperLoc, NoteID);
return true;
}
// Neither contains everything. Do a proper comparison.
for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
// Take one type from the subset.
QualType CanonicalSubT = Context.getCanonicalType(*SubI);
// Unwrap pointers and references so that we can do checks within a class
// hierarchy. Don't unwrap member pointers; they don't have hierarchy
// conversions on the pointee.
bool SubIsPointer = false;
if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
CanonicalSubT = RefTy->getPointeeType();
if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
CanonicalSubT = PtrTy->getPointeeType();
SubIsPointer = true;
}
bool SubIsClass = CanonicalSubT->isRecordType();
CanonicalSubT = CanonicalSubT.getUnqualifiedType();
CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
/*DetectVirtual=*/false);
bool Contained = false;
// Make sure it's in the superset.
for (FunctionProtoType::exception_iterator SuperI =
Superset->exception_begin(), SuperE = Superset->exception_end();
SuperI != SuperE; ++SuperI) {
QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
// SubT must be SuperT or derived from it, or pointer or reference to
// such types.
if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
CanonicalSuperT = RefTy->getPointeeType();
if (SubIsPointer) {
if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
CanonicalSuperT = PtrTy->getPointeeType();
else {
continue;
}
}
CanonicalSuperT = CanonicalSuperT.getUnqualifiedType();
// If the types are the same, move on to the next type in the subset.
if (CanonicalSubT == CanonicalSuperT) {
Contained = true;
break;
}
// Otherwise we need to check the inheritance.
if (!SubIsClass || !CanonicalSuperT->isRecordType())
continue;
Paths.clear();
if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
continue;
if (Paths.isAmbiguous(CanonicalSuperT))
continue;
if (FindInaccessibleBase(CanonicalSubT, CanonicalSuperT, Paths, true))
continue;
Contained = true;
break;
}
if (!Contained) {
Diag(SubLoc, DiagID);
if (NoteID != 0)
Diag(SuperLoc, NoteID);
return true;
}
}
// We've run half the gauntlet.
return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
}
static bool CheckSpecForTypesEquivalent(Sema &S,
unsigned DiagID, unsigned NoteID,
QualType Target, SourceLocation TargetLoc,
QualType Source, SourceLocation SourceLoc)
{
const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
if (!TFunc)
return false;
const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
if (!SFunc)
return false;
return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
SFunc, SourceLoc);
}
/// CheckParamExceptionSpec - Check if the parameter and return types of the
/// two functions have equivalent exception specs. This is part of the
/// assignment and override compatibility check. We do not check the parameters
/// of parameter function pointers recursively, as no sane programmer would
/// even be able to write such a function type.
bool Sema::CheckParamExceptionSpec(unsigned NoteID,
const FunctionProtoType *Target, SourceLocation TargetLoc,
const FunctionProtoType *Source, SourceLocation SourceLoc)
{
if (CheckSpecForTypesEquivalent(*this, diag::err_return_type_specs_differ, 0,
Target->getResultType(), TargetLoc,
Source->getResultType(), SourceLoc))
return true;
// We shouldn't even testing this unless the arguments are otherwise
// compatible.
assert(Target->getNumArgs() == Source->getNumArgs() &&
"Functions have different argument counts.");
for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
if (CheckSpecForTypesEquivalent(*this, diag::err_arg_type_specs_differ, 0,
Target->getArgType(i), TargetLoc,
Source->getArgType(i), SourceLoc))
return true;
}
return false;
}
bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
{
// First we check for applicability.
// Target type must be a function, function pointer or function reference.
const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
if (!ToFunc)
return false;
// SourceType must be a function or function pointer.
const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
if (!FromFunc)
return false;
// Now we've got the correct types on both sides, check their compatibility.
// This means that the source of the conversion can only throw a subset of
// the exceptions of the target, and any exception specs on arguments or
// return types must be equivalent.
return CheckExceptionSpecSubset(diag::err_incompatible_exception_specs,
0, ToFunc, From->getSourceRange().getBegin(),
FromFunc, SourceLocation());
}
bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old) {
return CheckExceptionSpecSubset(diag::err_override_exception_spec,
diag::note_overridden_virtual_function,
Old->getType()->getAs<FunctionProtoType>(),
Old->getLocation(),
New->getType()->getAs<FunctionProtoType>(),
New->getLocation());
}
} // end namespace clang
<|endoftext|> |
<commit_before>//===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Constant.h"
#include "llvm/DerivedTypes.h"
namespace llvm {
// External object describing the machine instructions
// Initialized only when the TargetMachine class is created
// and reset when that class is destroyed.
//
const TargetInstrDescriptor* TargetInstrDescriptors = 0;
TargetInstrInfo::TargetInstrInfo(const TargetInstrDescriptor* Desc,
unsigned DescSize,
unsigned NumRealOpCodes)
: desc(Desc), descSize(DescSize), numRealOpCodes(NumRealOpCodes) {
// FIXME: TargetInstrDescriptors should not be global
assert(TargetInstrDescriptors == NULL && desc != NULL);
TargetInstrDescriptors = desc; // initialize global variable
}
TargetInstrInfo::~TargetInstrInfo() {
TargetInstrDescriptors = NULL; // reset global variable
}
bool TargetInstrInfo::constantFitsInImmedField(MachineOpCode opCode,
int64_t intValue) const {
// First, check if opCode has an immed field.
bool isSignExtended;
uint64_t maxImmedValue = maxImmedConstant(opCode, isSignExtended);
if (maxImmedValue != 0)
{
// NEED TO HANDLE UNSIGNED VALUES SINCE THEY MAY BECOME MUCH
// SMALLER AFTER CASTING TO SIGN-EXTENDED int, short, or char.
// See CreateUIntSetInstruction in SparcInstrInfo.cpp.
// Now check if the constant fits
if (intValue <= (int64_t) maxImmedValue &&
intValue >= -((int64_t) maxImmedValue+1))
return true;
}
return false;
}
bool TargetInstrInfo::ConstantTypeMustBeLoaded(const Constant* CV) const {
assert(CV->getType()->isPrimitiveType() || isa<PointerType>(CV->getType()));
return !(CV->getType()->isIntegral() || isa<PointerType>(CV->getType()));
}
} // End llvm namespace
<commit_msg>Make this assertion more self-explanatory.<commit_after>//===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Constant.h"
#include "llvm/DerivedTypes.h"
namespace llvm {
// External object describing the machine instructions
// Initialized only when the TargetMachine class is created
// and reset when that class is destroyed.
//
const TargetInstrDescriptor* TargetInstrDescriptors = 0;
TargetInstrInfo::TargetInstrInfo(const TargetInstrDescriptor* Desc,
unsigned DescSize,
unsigned NumRealOpCodes)
: desc(Desc), descSize(DescSize), numRealOpCodes(NumRealOpCodes) {
// FIXME: TargetInstrDescriptors should not be global
assert(TargetInstrDescriptors == NULL && desc != NULL
&& "TargetMachine data structure corrupt; maybe you tried to create another TargetMachine? (only one may exist in a program)");
TargetInstrDescriptors = desc; // initialize global variable
}
TargetInstrInfo::~TargetInstrInfo() {
TargetInstrDescriptors = NULL; // reset global variable
}
bool TargetInstrInfo::constantFitsInImmedField(MachineOpCode opCode,
int64_t intValue) const {
// First, check if opCode has an immed field.
bool isSignExtended;
uint64_t maxImmedValue = maxImmedConstant(opCode, isSignExtended);
if (maxImmedValue != 0)
{
// NEED TO HANDLE UNSIGNED VALUES SINCE THEY MAY BECOME MUCH
// SMALLER AFTER CASTING TO SIGN-EXTENDED int, short, or char.
// See CreateUIntSetInstruction in SparcInstrInfo.cpp.
// Now check if the constant fits
if (intValue <= (int64_t) maxImmedValue &&
intValue >= -((int64_t) maxImmedValue+1))
return true;
}
return false;
}
bool TargetInstrInfo::ConstantTypeMustBeLoaded(const Constant* CV) const {
assert(CV->getType()->isPrimitiveType() || isa<PointerType>(CV->getType()));
return !(CV->getType()->isIntegral() || isa<PointerType>(CV->getType()));
}
} // End llvm namespace
<|endoftext|> |
<commit_before>//===-- SchedInfo.cpp - Generic code to support target schedulers ----------==//
//
// This file implements the generic part of a Scheduler description for a
// target. This functionality is defined in the llvm/Target/SchedInfo.h file.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetSchedInfo.h"
#include "llvm/Target/TargetMachine.h"
resourceId_t MachineResource::nextId = 0;
// Check if fromRVec and toRVec have *any* common entries.
// Assume the vectors are sorted in increasing order.
// Algorithm copied from function set_intersection() for sorted ranges
// (stl_algo.h).
//
inline static bool
RUConflict(const std::vector<resourceId_t>& fromRVec,
const std::vector<resourceId_t>& toRVec)
{
unsigned fN = fromRVec.size(), tN = toRVec.size();
unsigned fi = 0, ti = 0;
while (fi < fN && ti < tN)
{
if (fromRVec[fi] < toRVec[ti])
++fi;
else if (toRVec[ti] < fromRVec[fi])
++ti;
else
return true;
}
return false;
}
static cycles_t
ComputeMinGap(const InstrRUsage &fromRU,
const InstrRUsage &toRU)
{
cycles_t minGap = 0;
if (fromRU.numBubbles > 0)
minGap = fromRU.numBubbles;
if (minGap < fromRU.numCycles)
{
// only need to check from cycle `minGap' onwards
for (cycles_t gap=minGap; gap <= fromRU.numCycles-1; gap++)
{
// check if instr. #2 can start executing `gap' cycles after #1
// by checking for resource conflicts in each overlapping cycle
cycles_t numOverlap =std::min(fromRU.numCycles - gap, toRU.numCycles);
for (cycles_t c = 0; c <= numOverlap-1; c++)
if (RUConflict(fromRU.resourcesByCycle[gap + c],
toRU.resourcesByCycle[c]))
{
// conflict found so minGap must be more than `gap'
minGap = gap+1;
break;
}
}
}
return minGap;
}
//---------------------------------------------------------------------------
// class TargetSchedInfo
// Interface to machine description for instruction scheduling
//---------------------------------------------------------------------------
TargetSchedInfo::TargetSchedInfo(const TargetMachine& tgt,
int NumSchedClasses,
const InstrClassRUsage* ClassRUsages,
const InstrRUsageDelta* UsageDeltas,
const InstrIssueDelta* IssueDeltas,
unsigned NumUsageDeltas,
unsigned NumIssueDeltas)
: target(tgt),
numSchedClasses(NumSchedClasses), mii(& tgt.getInstrInfo()),
classRUsages(ClassRUsages), usageDeltas(UsageDeltas),
issueDeltas(IssueDeltas), numUsageDeltas(NumUsageDeltas),
numIssueDeltas(NumIssueDeltas)
{}
void
TargetSchedInfo::initializeResources()
{
assert(MAX_NUM_SLOTS >= (int)getMaxNumIssueTotal()
&& "Insufficient slots for static data! Increase MAX_NUM_SLOTS");
// First, compute common resource usage info for each class because
// most instructions will probably behave the same as their class.
// Cannot allocate a vector of InstrRUsage so new each one.
//
std::vector<InstrRUsage> instrRUForClasses;
instrRUForClasses.resize(numSchedClasses);
for (InstrSchedClass sc = 0; sc < numSchedClasses; sc++) {
// instrRUForClasses.push_back(new InstrRUsage);
instrRUForClasses[sc].setMaxSlots(getMaxNumIssueTotal());
instrRUForClasses[sc].setTo(classRUsages[sc]);
}
computeInstrResources(instrRUForClasses);
computeIssueGaps(instrRUForClasses);
}
void
TargetSchedInfo::computeInstrResources(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumRealOpCodes();
instrRUsages.resize(numOpCodes);
// First get the resource usage information from the class resource usages.
for (MachineOpCode op = 0; op < numOpCodes; ++op) {
InstrSchedClass sc = getSchedClass(op);
assert(sc < numSchedClasses);
instrRUsages[op] = instrRUForClasses[sc];
}
// Now, modify the resource usages as specified in the deltas.
for (unsigned i = 0; i < numUsageDeltas; ++i) {
MachineOpCode op = usageDeltas[i].opCode;
assert(op < numOpCodes);
instrRUsages[op].addUsageDelta(usageDeltas[i]);
}
// Then modify the issue restrictions as specified in the deltas.
for (unsigned i = 0; i < numIssueDeltas; ++i) {
MachineOpCode op = issueDeltas[i].opCode;
assert(op < numOpCodes);
instrRUsages[issueDeltas[i].opCode].addIssueDelta(issueDeltas[i]);
}
}
void
TargetSchedInfo::computeIssueGaps(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumRealOpCodes();
issueGaps.resize(numOpCodes);
conflictLists.resize(numOpCodes);
assert(numOpCodes < (1 << MAX_OPCODE_SIZE) - 1
&& "numOpCodes invalid for implementation of class OpCodePair!");
// First, compute issue gaps between pairs of classes based on common
// resources usages for each class, because most instruction pairs will
// usually behave the same as their class.
//
int classPairGaps[numSchedClasses][numSchedClasses];
for (InstrSchedClass fromSC=0; fromSC < numSchedClasses; fromSC++)
for (InstrSchedClass toSC=0; toSC < numSchedClasses; toSC++)
{
int classPairGap = ComputeMinGap(instrRUForClasses[fromSC],
instrRUForClasses[toSC]);
classPairGaps[fromSC][toSC] = classPairGap;
}
// Now, for each pair of instructions, use the class pair gap if both
// instructions have identical resource usage as their respective classes.
// If not, recompute the gap for the pair from scratch.
longestIssueConflict = 0;
for (MachineOpCode fromOp=0; fromOp < numOpCodes; fromOp++)
for (MachineOpCode toOp=0; toOp < numOpCodes; toOp++)
{
int instrPairGap =
(instrRUsages[fromOp].sameAsClass && instrRUsages[toOp].sameAsClass)
? classPairGaps[getSchedClass(fromOp)][getSchedClass(toOp)]
: ComputeMinGap(instrRUsages[fromOp], instrRUsages[toOp]);
if (instrPairGap > 0)
{
this->setGap(instrPairGap, fromOp, toOp);
conflictLists[fromOp].push_back(toOp);
longestIssueConflict=std::max(longestIssueConflict, instrPairGap);
}
}
}
void InstrRUsage::setTo(const InstrClassRUsage& classRU) {
sameAsClass = true;
isSingleIssue = classRU.isSingleIssue;
breaksGroup = classRU.breaksGroup;
numBubbles = classRU.numBubbles;
for (unsigned i=0; i < classRU.numSlots; i++)
{
unsigned slot = classRU.feasibleSlots[i];
assert(slot < feasibleSlots.size() && "Invalid slot specified!");
this->feasibleSlots[slot] = true;
}
numCycles = classRU.totCycles;
resourcesByCycle.resize(this->numCycles);
for (unsigned i=0; i < classRU.numRUEntries; i++)
for (unsigned c=classRU.V[i].startCycle, NC = c + classRU.V[i].numCycles;
c < NC; c++)
this->resourcesByCycle[c].push_back(classRU.V[i].resourceId);
// Sort each resource usage vector by resourceId_t to speed up conflict checking
for (unsigned i=0; i < this->resourcesByCycle.size(); i++)
sort(resourcesByCycle[i].begin(), resourcesByCycle[i].end());
}
// Add the extra resource usage requirements specified in the delta.
// Note that a negative value of `numCycles' means one entry for that
// resource should be deleted for each cycle.
//
void InstrRUsage::addUsageDelta(const InstrRUsageDelta &delta) {
int NC = delta.numCycles;
sameAsClass = false;
// resize the resources vector if more cycles are specified
unsigned maxCycles = this->numCycles;
maxCycles = std::max(maxCycles, delta.startCycle + abs(NC) - 1);
if (maxCycles > this->numCycles)
{
this->resourcesByCycle.resize(maxCycles);
this->numCycles = maxCycles;
}
if (NC >= 0)
for (unsigned c=delta.startCycle, last=c+NC-1; c <= last; c++)
this->resourcesByCycle[c].push_back(delta.resourceId);
else
// Remove the resource from all NC cycles.
for (unsigned c=delta.startCycle, last=(c-NC)-1; c <= last; c++)
{
// Look for the resource backwards so we remove the last entry
// for that resource in each cycle.
std::vector<resourceId_t>& rvec = this->resourcesByCycle[c];
int r;
for (r = rvec.size() - 1; r >= 0; r--)
if (rvec[r] == delta.resourceId)
{// found last entry for the resource
rvec.erase(rvec.begin() + r);
break;
}
assert(r >= 0 && "Resource to remove was unused in cycle c!");
}
}
<commit_msg>Reformatted code to match the prevalent LLVM style; fit code into 80 columns.<commit_after>//===-- SchedInfo.cpp - Generic code to support target schedulers ----------==//
//
// This file implements the generic part of a Scheduler description for a
// target. This functionality is defined in the llvm/Target/SchedInfo.h file.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetSchedInfo.h"
#include "llvm/Target/TargetMachine.h"
resourceId_t MachineResource::nextId = 0;
// Check if fromRVec and toRVec have *any* common entries.
// Assume the vectors are sorted in increasing order.
// Algorithm copied from function set_intersection() for sorted ranges
// (stl_algo.h).
//
inline static bool
RUConflict(const std::vector<resourceId_t>& fromRVec,
const std::vector<resourceId_t>& toRVec)
{
unsigned fN = fromRVec.size(), tN = toRVec.size();
unsigned fi = 0, ti = 0;
while (fi < fN && ti < tN) {
if (fromRVec[fi] < toRVec[ti])
++fi;
else if (toRVec[ti] < fromRVec[fi])
++ti;
else
return true;
}
return false;
}
static cycles_t
ComputeMinGap(const InstrRUsage &fromRU,
const InstrRUsage &toRU)
{
cycles_t minGap = 0;
if (fromRU.numBubbles > 0)
minGap = fromRU.numBubbles;
if (minGap < fromRU.numCycles) {
// only need to check from cycle `minGap' onwards
for (cycles_t gap=minGap; gap <= fromRU.numCycles-1; gap++) {
// check if instr. #2 can start executing `gap' cycles after #1
// by checking for resource conflicts in each overlapping cycle
cycles_t numOverlap =std::min(fromRU.numCycles - gap, toRU.numCycles);
for (cycles_t c = 0; c <= numOverlap-1; c++)
if (RUConflict(fromRU.resourcesByCycle[gap + c],
toRU.resourcesByCycle[c])) {
// conflict found so minGap must be more than `gap'
minGap = gap+1;
break;
}
}
}
return minGap;
}
//---------------------------------------------------------------------------
// class TargetSchedInfo
// Interface to machine description for instruction scheduling
//---------------------------------------------------------------------------
TargetSchedInfo::TargetSchedInfo(const TargetMachine& tgt,
int NumSchedClasses,
const InstrClassRUsage* ClassRUsages,
const InstrRUsageDelta* UsageDeltas,
const InstrIssueDelta* IssueDeltas,
unsigned NumUsageDeltas,
unsigned NumIssueDeltas)
: target(tgt),
numSchedClasses(NumSchedClasses), mii(& tgt.getInstrInfo()),
classRUsages(ClassRUsages), usageDeltas(UsageDeltas),
issueDeltas(IssueDeltas), numUsageDeltas(NumUsageDeltas),
numIssueDeltas(NumIssueDeltas)
{}
void
TargetSchedInfo::initializeResources()
{
assert(MAX_NUM_SLOTS >= (int)getMaxNumIssueTotal()
&& "Insufficient slots for static data! Increase MAX_NUM_SLOTS");
// First, compute common resource usage info for each class because
// most instructions will probably behave the same as their class.
// Cannot allocate a vector of InstrRUsage so new each one.
//
std::vector<InstrRUsage> instrRUForClasses;
instrRUForClasses.resize(numSchedClasses);
for (InstrSchedClass sc = 0; sc < numSchedClasses; sc++) {
// instrRUForClasses.push_back(new InstrRUsage);
instrRUForClasses[sc].setMaxSlots(getMaxNumIssueTotal());
instrRUForClasses[sc].setTo(classRUsages[sc]);
}
computeInstrResources(instrRUForClasses);
computeIssueGaps(instrRUForClasses);
}
void
TargetSchedInfo::computeInstrResources(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumRealOpCodes();
instrRUsages.resize(numOpCodes);
// First get the resource usage information from the class resource usages.
for (MachineOpCode op = 0; op < numOpCodes; ++op) {
InstrSchedClass sc = getSchedClass(op);
assert(sc < numSchedClasses);
instrRUsages[op] = instrRUForClasses[sc];
}
// Now, modify the resource usages as specified in the deltas.
for (unsigned i = 0; i < numUsageDeltas; ++i) {
MachineOpCode op = usageDeltas[i].opCode;
assert(op < numOpCodes);
instrRUsages[op].addUsageDelta(usageDeltas[i]);
}
// Then modify the issue restrictions as specified in the deltas.
for (unsigned i = 0; i < numIssueDeltas; ++i) {
MachineOpCode op = issueDeltas[i].opCode;
assert(op < numOpCodes);
instrRUsages[issueDeltas[i].opCode].addIssueDelta(issueDeltas[i]);
}
}
void
TargetSchedInfo::computeIssueGaps(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumRealOpCodes();
issueGaps.resize(numOpCodes);
conflictLists.resize(numOpCodes);
assert(numOpCodes < (1 << MAX_OPCODE_SIZE) - 1
&& "numOpCodes invalid for implementation of class OpCodePair!");
// First, compute issue gaps between pairs of classes based on common
// resources usages for each class, because most instruction pairs will
// usually behave the same as their class.
//
int classPairGaps[numSchedClasses][numSchedClasses];
for (InstrSchedClass fromSC=0; fromSC < numSchedClasses; fromSC++)
for (InstrSchedClass toSC=0; toSC < numSchedClasses; toSC++) {
int classPairGap = ComputeMinGap(instrRUForClasses[fromSC],
instrRUForClasses[toSC]);
classPairGaps[fromSC][toSC] = classPairGap;
}
// Now, for each pair of instructions, use the class pair gap if both
// instructions have identical resource usage as their respective classes.
// If not, recompute the gap for the pair from scratch.
longestIssueConflict = 0;
for (MachineOpCode fromOp=0; fromOp < numOpCodes; fromOp++)
for (MachineOpCode toOp=0; toOp < numOpCodes; toOp++) {
int instrPairGap =
(instrRUsages[fromOp].sameAsClass && instrRUsages[toOp].sameAsClass)
? classPairGaps[getSchedClass(fromOp)][getSchedClass(toOp)]
: ComputeMinGap(instrRUsages[fromOp], instrRUsages[toOp]);
if (instrPairGap > 0) {
this->setGap(instrPairGap, fromOp, toOp);
conflictLists[fromOp].push_back(toOp);
longestIssueConflict=std::max(longestIssueConflict, instrPairGap);
}
}
}
void InstrRUsage::setTo(const InstrClassRUsage& classRU) {
sameAsClass = true;
isSingleIssue = classRU.isSingleIssue;
breaksGroup = classRU.breaksGroup;
numBubbles = classRU.numBubbles;
for (unsigned i=0; i < classRU.numSlots; i++) {
unsigned slot = classRU.feasibleSlots[i];
assert(slot < feasibleSlots.size() && "Invalid slot specified!");
this->feasibleSlots[slot] = true;
}
numCycles = classRU.totCycles;
resourcesByCycle.resize(this->numCycles);
for (unsigned i=0; i < classRU.numRUEntries; i++)
for (unsigned c=classRU.V[i].startCycle, NC = c + classRU.V[i].numCycles;
c < NC; c++)
this->resourcesByCycle[c].push_back(classRU.V[i].resourceId);
// Sort each resource usage vector by resourceId_t to speed up conflict
// checking
for (unsigned i=0; i < this->resourcesByCycle.size(); i++)
sort(resourcesByCycle[i].begin(), resourcesByCycle[i].end());
}
// Add the extra resource usage requirements specified in the delta.
// Note that a negative value of `numCycles' means one entry for that
// resource should be deleted for each cycle.
//
void InstrRUsage::addUsageDelta(const InstrRUsageDelta &delta) {
int NC = delta.numCycles;
sameAsClass = false;
// resize the resources vector if more cycles are specified
unsigned maxCycles = this->numCycles;
maxCycles = std::max(maxCycles, delta.startCycle + abs(NC) - 1);
if (maxCycles > this->numCycles) {
this->resourcesByCycle.resize(maxCycles);
this->numCycles = maxCycles;
}
if (NC >= 0)
for (unsigned c=delta.startCycle, last=c+NC-1; c <= last; c++)
this->resourcesByCycle[c].push_back(delta.resourceId);
else
// Remove the resource from all NC cycles.
for (unsigned c=delta.startCycle, last=(c-NC)-1; c <= last; c++) {
// Look for the resource backwards so we remove the last entry
// for that resource in each cycle.
std::vector<resourceId_t>& rvec = this->resourcesByCycle[c];
int r;
for (r = rvec.size() - 1; r >= 0; r--)
if (rvec[r] == delta.resourceId) {
// found last entry for the resource
rvec.erase(rvec.begin() + r);
break;
}
assert(r >= 0 && "Resource to remove was unused in cycle c!");
}
}
<|endoftext|> |
<commit_before>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#define tkDialog 3300
#define tkDialogTitle 3301
#define tkDialogText 3302
#define tkDialogForgive 3303
#define tkDialogAnnounce 3304
#define tkDialogPunish 3305
class TeamkillDialog {
idd = tkDialog;
movingEnable = true;
enableSimulation = true;
onLoad = "";
class controlsBackground {
class MainBG:w_RscPicture {
idc = -1;
moving = true;
x = 0.25;
y = 0.1;
w = 0.70;
h = 0.5 * (SafeZoneW / SafeZoneH);
};
class MainTitle:w_RscText {
idc = tkDialogTitle;
style = ST_CENTER;
text = "You have been team killed.";
sizeEx = 0.04;
shadow = 2;
x = 0.35;
y = 0.125;
w = 0.46;
h = 0.03;
};
class TeamkillText:w_RscText {
idc = tkDialogText;
type = CT_STRUCTURED_TEXT+ST_LEFT;
size = 0.04;
x = 0.26;
y = 0.19;
w = 0.65;
h = 0.358;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "";
class Attributes {
font = "TahomaB";
align = "center";
valign = "middle";
shadow = 2;
};
};
};
class controls {
class ForgiveButton:w_RscButton {
idc = tkDialogForgive;
text = "Forgive";
onButtonClick = "false call teamkillAction";
size = 0.031;
color[] = {0.10, 0.95, 0.10, 1};
x = 0.30; y = 0.585;
w = 0.16; h = 0.065;
};
// class AnnounceButton:w_RscButton {
// idc = tkDialogAnnounce;
// text = "Announce";
// // onButtonClick = "false call teamkillAction";
//
// size = 0.031;
// color[] = {0.95, 0.95, 0.10, 1};
//
// x = 0.505; y = 0.585;
// w = 0.16; h = 0.065;
// };
class PunishButton:w_RscButton {
idc = tkDialogPunish;
text = "Punish";
onButtonClick = "true call teamkillAction";
size = 0.031;
color[] = {0.95, 0.10, 0.10, 1};
x = 0.71; y = 0.585;
w = 0.16; h = 0.065;
};
};
};
<commit_msg>Update teamkill_dialog.hpp<commit_after>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#define tkDialog 3300
#define tkDialogTitle 3301
#define tkDialogText 3302
#define tkDialogForgive 3303
#define tkDialogAnnounce 3304
#define tkDialogPunish 3305
class TeamkillDialog {
idd = tkDialog;
movingEnable = true;
enableSimulation = true;
onLoad = "";
class controlsBackground {
class MainBG:w_RscPicture {
idc = -1;
moving = true;
x = 0.25;
y = 0.1;
w = 0.70;
h = 0.5 * (SafeZoneW / SafeZoneH);
};
class MainTitle:w_RscText {
idc = tkDialogTitle;
style = ST_CENTER;
text = "Te ha matado un compañero de equipo.";
sizeEx = 0.04;
shadow = 2;
x = 0.35;
y = 0.125;
w = 0.46;
h = 0.03;
};
class TeamkillText:w_RscText {
idc = tkDialogText;
type = CT_STRUCTURED_TEXT+ST_LEFT;
size = 0.04;
x = 0.26;
y = 0.19;
w = 0.65;
h = 0.358;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "";
class Attributes {
font = "TahomaB";
align = "center";
valign = "middle";
shadow = 2;
};
};
};
class controls {
class ForgiveButton:w_RscButton {
idc = tkDialogForgive;
text = "Perdonar";
onButtonClick = "false call teamkillAction";
size = 0.031;
color[] = {0.10, 0.95, 0.10, 1};
x = 0.30; y = 0.585;
w = 0.16; h = 0.065;
};
// class AnnounceButton:w_RscButton {
// idc = tkDialogAnnounce;
// text = "Announce";
// // onButtonClick = "false call teamkillAction";
//
// size = 0.031;
// color[] = {0.95, 0.95, 0.10, 1};
//
// x = 0.505; y = 0.585;
// w = 0.16; h = 0.065;
// };
class PunishButton:w_RscButton {
idc = tkDialogPunish;
text = "Castigar";
onButtonClick = "true call teamkillAction";
size = 0.031;
color[] = {0.95, 0.10, 0.10, 1};
x = 0.71; y = 0.585;
w = 0.16; h = 0.065;
};
};
};
<|endoftext|> |
<commit_before>// Best-first Utility-Guided Search Yes! From:
// "Best-first Utility-Guided Search," Wheeler Ruml and Minh B. Do,
// Proceedings of the Twentieth International Joint Conference on
// Artificial Intelligence (IJCAI-07), 2007
#include "../search/search.hpp"
#include "../structs/binheap.hpp"
#include "../utils/pool.hpp"
template <class D> struct Bugsy : public SearchAlgorithm<D> {
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
struct Node : SearchNode<D> {
typename D::Cost f, h, d;
double u, t;
// The expansion count when this node was
// generated.
unsigned long expct;
static bool pred(Node *a, Node *b) {
if (a->u != b->u)
return a->u > b->u;
if (a->t != b->t)
return a->t < b->t;
if (a->f != b->f)
return a->f < b->f;
return a->g > b->g;
}
};
Bugsy(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv), usehhat(false),
usedhat(false), navg(0), herror(0), derror(0),
useexpdelay(false), avgdelay(0), timeper(0.0), nresort(0),
batchsize(20), nexp(0), state(WaitTick), closed(30000001) {
wf = wt = -1;
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-wf") == 0)
wf = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0)
wt = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-expdelay") == 0)
useexpdelay = true;
else if (i < argc - 1 && strcmp(argv[i], "-hhat") == 0)
usehhat = true;
else if (i < argc - 1 && strcmp(argv[i], "-dhat") == 0)
usedhat = true;
}
if (wf < 0)
fatal("Must specify non-negative f-weight using -wf");
if (wt < 0)
fatal("Must specify non-negative t-weight using -wt");
nodes = new Pool<Node>();
}
~Bugsy() {
delete nodes;
}
enum { WaitTick, ExpandSome, WaitExpand };
void search(D &d, typename D::State &s0) {
this->start();
closed.init(d);
Node *n0 = init(d, s0);
closed.add(n0);
open.push(n0);
lasttick = walltime();
while (!open.empty() && !SearchAlgorithm<D>::limit()) {
updatetime();
Node* n = *open.pop();
State buf, &state = d.unpack(buf, n->packed);
if (d.isgoal(state)) {
SearchAlgorithm<D>::res.goal(d, n);
break;
}
expand(d, n, state);
}
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
open.clear();
closed.clear();
delete nodes;
timeper = 0.0;
state = WaitTick;
batchsize = 20;
nexp = 0;
nresort = 0;
navg = 0;
herror = derror = 0;
nodes = new Pool<Node>();
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
closed.prstats(stdout, "closed ");
dfpair(stdout, "open list type", "%s", "binary heap");
dfpair(stdout, "node size", "%u", sizeof(Node));
dfpair(stdout, "cost weight", "%g", wf);
dfpair(stdout, "time weight", "%g", wt);
dfpair(stdout, "final time per expand", "%g", timeper);
dfpair(stdout, "number of resorts", "%lu", nresort);
if (usehhat)
dfpair(stdout, "mean single-step h error", "%g", herror);
if (usedhat)
dfpair(stdout, "mean single-step d error", "%g", derror);
if (useexpdelay)
dfpair(stdout, "mean expansion delay", "%g", avgdelay);
}
private:
// Kidinfo holds information about a node used for
// correcting the heuristic estimates.
struct Kidinfo {
Kidinfo() : f(-1), h(-1), d(-1) { }
Kidinfo(Cost gval, Cost hval, Cost dval) : f(gval + hval), h(hval), d(dval) { }
Cost f, h, d;
};
// expand expands the node, adding its children to the
// open and closed lists as appropriate.
void expand(D &d, Node *n, State &state) {
this->res.expd++;
if (useexpdelay) {
unsigned long delay = this->res.expd - n->expct;
avgdelay = avgdelay + (delay - avgdelay)/this->res.expd;
}
Kidinfo bestinfo;
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
if (ops[i] == n->pop)
continue;
this->res.gend++;
Kidinfo kinfo = considerkid(d, n, state, ops[i]);
if (bestinfo.f < Cost(0) || kinfo.f < bestinfo.f)
bestinfo = kinfo;
}
if (bestinfo.f < Cost(0))
return;
navg++;
if (usehhat) {
double herr = bestinfo.f - n->f;
assert (herr >= 0);
herror = herror + (herr - herror)/navg;
}
if (usedhat) {
double derr = bestinfo.d + 1 - n->d;
assert (derr >= 0);
derror = derror + (derr - derror)/navg;
}
}
// considers adding the child to the open and closed lists.
Kidinfo considerkid(D &d, Node *parent, State &state, Oper op) {
Node *kid = nodes->construct();
typename D::Edge e(d, state, op);
kid->g = parent->g + e.cost;
// single step path-max on d
kid->d = d.d(e.state);
if (kid->d < parent->d - Cost(1))
kid->d = parent->d - Cost(1);
// single step path-max on h
kid->h = d.h(e.state);
if (kid->h < parent->h - e.cost)
kid->h = parent->h - e.cost;
kid->f = kid->g + kid->h;
if (useexpdelay)
kid->expct = this->res.expd;
Kidinfo kinfo(kid->g, kid->h, kid->d);
d.pack(kid->packed, e.state);
unsigned long hash = d.hash(kid->packed);
Node *dup = static_cast<Node*>(closed.find(kid->packed, hash));
if (dup) {
this->res.dups++;
if (kid->g < dup->g) {
this->res.reopnd++;
dup->f = dup->f - dup->g + kid->g;
dup->update(kid->g, parent, op, e.revop);
computeutil(dup);
open.pushupdate(dup, dup->ind);
}
nodes->destruct(kid);
} else {
kid->update(kid->g, parent, op, e.revop);
computeutil(kid);
closed.add(kid, hash);
open.push(kid);
}
return kinfo;
}
Node *init(D &d, State &s0) {
Node *n0 = nodes->construct();
d.pack(n0->packed, s0);
n0->g = Cost(0);
n0->h = n0->f = d.h(s0);
n0->d = d.d(s0);
computeutil(n0);
n0->op = n0->pop = D::Nop;
n0->parent = NULL;
n0->expct = 0;
return n0;
}
// compututil computes the utility value of the given node
// using corrected estimates of d and h.
void computeutil(Node *n) {
double d = n->d;
if (usedhat)
d /= (1 - derror);
double h = n->h;
if (usehhat)
h += d * herror;
if (useexpdelay && avgdelay > 0)
d *= avgdelay;
double f = h + n->g;
n->t = timeper * d;
n->u = -(wf * f + wt * n->t);
}
// updatetime runs a simple state machine (from Wheeler's BUGSY
// implementation) that estimates the node expansion rate.
void updatetime() {
double now;
switch (state) {
case WaitTick: // wait until the clock ticks
now = walltime();
if (now <= lasttick)
break;
starttime = now;
state = ExpandSome;
break;
case ExpandSome: // expand a batch of nodes
nexp++;
if (nexp < batchsize)
break;
lasttick = walltime();
state = WaitExpand;
break;
case WaitExpand: // estimate the exps for the next tick and reset
nexp++;
now = walltime();
if (now <= lasttick) // clock hasn't ticked yet
break;
updateopen();
timeper = (now - starttime) / nexp;
// Re-check the time after 1.8*nexp expansions.
// 1.8 is from Wheeler's bugsy_old.ml code. This
// should be geometrically increasing in nexp to
// ensure that we only sort the open list a logarithmic
// number of times.
batchsize = nexp * 9 / 5;
nexp = 0;
starttime = now;
state = ExpandSome;
break;
default:
fatal("Unknown update time state: %d\n", state);
}
}
void updateopen() {
nresort++;
for (int i = 0; i < open.size(); i++)
computeutil(open.at(i));
open.reinit();
}
double wf, wt;
// heuristic correction
bool usehhat, usedhat;
unsigned long navg;
double herror, derror;
// expansion delay
bool useexpdelay; // is it enabled?
double avgdelay;
// for nodes-per-second estimation
double timeper;
unsigned long nresort, batchsize, nexp;
double starttime, lasttick;
int state;
BinHeap<Node, Node*> open;
ClosedList<SearchNode<D>, SearchNode<D>, D> closed;
Pool<Node> *nodes;
};
<commit_msg>bugsy: simplify nodes-per-second computation.<commit_after>// Best-first Utility-Guided Search Yes! From:
// "Best-first Utility-Guided Search," Wheeler Ruml and Minh B. Do,
// Proceedings of the Twentieth International Joint Conference on
// Artificial Intelligence (IJCAI-07), 2007
#include "../search/search.hpp"
#include "../structs/binheap.hpp"
#include "../utils/pool.hpp"
template <class D> struct Bugsy : public SearchAlgorithm<D> {
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
struct Node : SearchNode<D> {
typename D::Cost f, h, d;
double u, t;
// The expansion count when this node was
// generated.
unsigned long expct;
static bool pred(Node *a, Node *b) {
if (a->u != b->u)
return a->u > b->u;
if (a->t != b->t)
return a->t < b->t;
if (a->f != b->f)
return a->f < b->f;
return a->g > b->g;
}
};
enum {
// Resort1 is the number of expansions to perform
// before the 1st open list resort.
Resort1 = 128,
};
Bugsy(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv), usehhat(false),
usedhat(false), navg(0), herror(0), derror(0),
useexpdelay(false), avgdelay(0), timeper(0.0),
nextresort(Resort1), nresort(0), closed(30000001) {
wf = wt = -1;
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-wf") == 0)
wf = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0)
wt = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-expdelay") == 0)
useexpdelay = true;
else if (i < argc - 1 && strcmp(argv[i], "-hhat") == 0)
usehhat = true;
else if (i < argc - 1 && strcmp(argv[i], "-dhat") == 0)
usedhat = true;
}
if (wf < 0)
fatal("Must specify non-negative f-weight using -wf");
if (wt < 0)
fatal("Must specify non-negative t-weight using -wt");
nodes = new Pool<Node>();
}
~Bugsy() {
delete nodes;
}
void search(D &d, typename D::State &s0) {
this->start();
last = walltime();
closed.init(d);
Node *n0 = init(d, s0);
closed.add(n0);
open.push(n0);
while (!open.empty() && !SearchAlgorithm<D>::limit()) {
Node* n = *open.pop();
State buf, &state = d.unpack(buf, n->packed);
if (d.isgoal(state)) {
SearchAlgorithm<D>::res.goal(d, n);
break;
}
expand(d, n, state);
updatetime();
updateopen();
}
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
open.clear();
closed.clear();
delete nodes;
timeper = 0.0;
nresort = 0;
nextresort = Resort1;
navg = 0;
herror = derror = 0;
nodes = new Pool<Node>();
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
closed.prstats(stdout, "closed ");
dfpair(stdout, "open list type", "%s", "binary heap");
dfpair(stdout, "node size", "%u", sizeof(Node));
dfpair(stdout, "cost weight", "%g", wf);
dfpair(stdout, "time weight", "%g", wt);
dfpair(stdout, "final time per expand", "%g", timeper);
dfpair(stdout, "number of resorts", "%lu", nresort);
if (usehhat)
dfpair(stdout, "mean single-step h error", "%g", herror);
if (usedhat)
dfpair(stdout, "mean single-step d error", "%g", derror);
if (useexpdelay)
dfpair(stdout, "mean expansion delay", "%g", avgdelay);
}
private:
// Kidinfo holds information about a node used for
// correcting the heuristic estimates.
struct Kidinfo {
Kidinfo() : f(-1), h(-1), d(-1) { }
Kidinfo(Cost gval, Cost hval, Cost dval) : f(gval + hval), h(hval), d(dval) { }
Cost f, h, d;
};
// expand expands the node, adding its children to the
// open and closed lists as appropriate.
void expand(D &d, Node *n, State &state) {
this->res.expd++;
if (useexpdelay) {
unsigned long delay = this->res.expd - n->expct;
avgdelay = avgdelay + (delay - avgdelay)/this->res.expd;
}
Kidinfo bestinfo;
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
if (ops[i] == n->pop)
continue;
this->res.gend++;
Kidinfo kinfo = considerkid(d, n, state, ops[i]);
if (bestinfo.f < Cost(0) || kinfo.f < bestinfo.f)
bestinfo = kinfo;
}
if (bestinfo.f < Cost(0))
return;
navg++;
if (usehhat) {
double herr = bestinfo.f - n->f;
assert (herr >= 0);
herror = herror + (herr - herror)/navg;
}
if (usedhat) {
double derr = bestinfo.d + 1 - n->d;
assert (derr >= 0);
derror = derror + (derr - derror)/navg;
}
}
// considers adding the child to the open and closed lists.
Kidinfo considerkid(D &d, Node *parent, State &state, Oper op) {
Node *kid = nodes->construct();
typename D::Edge e(d, state, op);
kid->g = parent->g + e.cost;
// single step path-max on d
kid->d = d.d(e.state);
if (kid->d < parent->d - Cost(1))
kid->d = parent->d - Cost(1);
// single step path-max on h
kid->h = d.h(e.state);
if (kid->h < parent->h - e.cost)
kid->h = parent->h - e.cost;
kid->f = kid->g + kid->h;
if (useexpdelay)
kid->expct = this->res.expd;
Kidinfo kinfo(kid->g, kid->h, kid->d);
d.pack(kid->packed, e.state);
unsigned long hash = d.hash(kid->packed);
Node *dup = static_cast<Node*>(closed.find(kid->packed, hash));
if (dup) {
this->res.dups++;
if (kid->g < dup->g) {
this->res.reopnd++;
dup->f = dup->f - dup->g + kid->g;
dup->update(kid->g, parent, op, e.revop);
computeutil(dup);
open.pushupdate(dup, dup->ind);
}
nodes->destruct(kid);
} else {
kid->update(kid->g, parent, op, e.revop);
computeutil(kid);
closed.add(kid, hash);
open.push(kid);
}
return kinfo;
}
Node *init(D &d, State &s0) {
Node *n0 = nodes->construct();
d.pack(n0->packed, s0);
n0->g = Cost(0);
n0->h = n0->f = d.h(s0);
n0->d = d.d(s0);
computeutil(n0);
n0->op = n0->pop = D::Nop;
n0->parent = NULL;
n0->expct = 0;
return n0;
}
// compututil computes the utility value of the given node
// using corrected estimates of d and h.
void computeutil(Node *n) {
double d = n->d;
if (usedhat)
d /= (1 - derror);
double h = n->h;
if (usehhat)
h += d * herror;
if (useexpdelay && avgdelay > 0)
d *= avgdelay;
double f = h + n->g;
n->t = timeper * d;
n->u = -(wf * f + wt * n->t);
}
// updatetime runs a simple state machine (from Wheeler's BUGSY
// implementation) that estimates the node expansion rate.
void updatetime() {
double t = walltime() - last;
timeper = timeper + (t - timeper)/this->res.expd;
last = walltime();
}
// updateopen updates the utilities of all nodes on open and
// reinitializes the heap every 2^i expansions.
void updateopen() {
if (this->res.expd < nextresort)
return;
nextresort *= 2;
nresort++;
for (int i = 0; i < open.size(); i++)
computeutil(open.at(i));
open.reinit();
}
double wf, wt;
// heuristic correction
bool usehhat, usedhat;
unsigned long navg;
double herror, derror;
// expansion delay
bool useexpdelay;
double avgdelay;
// for nodes-per-second estimation
double timeper, last;
// for resorting the open list
unsigned long nextresort;
unsigned int nresort;
BinHeap<Node, Node*> open;
ClosedList<SearchNode<D>, SearchNode<D>, D> closed;
Pool<Node> *nodes;
};
<|endoftext|> |
<commit_before>//===-- Value.cpp - Implement the Value class -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Value and User classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/Constant.h"
#include "llvm/DerivedTypes.h"
#include "llvm/InstrTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/ValueSymbolTable.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/LeakDetector.h"
#include <algorithm>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Value Class
//===----------------------------------------------------------------------===//
static inline const Type *checkType(const Type *Ty) {
assert(Ty && "Value defined with a null type: Error!");
return Ty;
}
Value::Value(const Type *ty, unsigned scid)
: SubclassID(scid), SubclassData(0), Ty(checkType(ty)),
UseList(0), Name(0) {
if (isa<CallInst>(this) || isa<InvokeInst>(this))
assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
isa<OpaqueType>(ty) || Ty->getTypeID() == Type::StructTyID) &&
"invalid CallInst type!");
else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
isa<OpaqueType>(ty)) &&
"Cannot create non-first-class values except for constants!");
}
Value::~Value() {
#ifndef NDEBUG // Only in -g mode...
// Check to make sure that there are no uses of this value that are still
// around when the value is destroyed. If there are, then we have a dangling
// reference and something is wrong. This code is here to print out what is
// still being referenced. The value in question should be printed as
// a <badref>
//
if (!use_empty()) {
DOUT << "While deleting: " << *Ty << " %" << Name << "\n";
for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
DOUT << "Use still stuck around after Def is destroyed:"
<< **I << "\n";
}
#endif
assert(use_empty() && "Uses remain when a value is destroyed!");
// If this value is named, destroy the name. This should not be in a symtab
// at this point.
if (Name)
Name->Destroy();
// There should be no uses of this object anymore, remove it.
LeakDetector::removeGarbageObject(this);
}
/// hasNUses - Return true if this Value has exactly N users.
///
bool Value::hasNUses(unsigned N) const {
use_const_iterator UI = use_begin(), E = use_end();
for (; N; --N, ++UI)
if (UI == E) return false; // Too few.
return UI == E;
}
/// hasNUsesOrMore - Return true if this value has N users or more. This is
/// logically equivalent to getNumUses() >= N.
///
bool Value::hasNUsesOrMore(unsigned N) const {
use_const_iterator UI = use_begin(), E = use_end();
for (; N; --N, ++UI)
if (UI == E) return false; // Too few.
return true;
}
/// getNumUses - This method computes the number of uses of this Value. This
/// is a linear time operation. Use hasOneUse or hasNUses to check for specific
/// values.
unsigned Value::getNumUses() const {
return (unsigned)std::distance(use_begin(), use_end());
}
static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
ST = 0;
if (Instruction *I = dyn_cast<Instruction>(V)) {
if (BasicBlock *P = I->getParent())
if (Function *PP = P->getParent())
ST = &PP->getValueSymbolTable();
} else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
if (Function *P = BB->getParent())
ST = &P->getValueSymbolTable();
} else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
if (Module *P = GV->getParent())
ST = &P->getValueSymbolTable();
} else if (Argument *A = dyn_cast<Argument>(V)) {
if (Function *P = A->getParent())
ST = &P->getValueSymbolTable();
} else {
assert(isa<Constant>(V) && "Unknown value type!");
return true; // no name is setable for this.
}
return false;
}
/// getNameStart - Return a pointer to a null terminated string for this name.
/// Note that names can have null characters within the string as well as at
/// their end. This always returns a non-null pointer.
const char *Value::getNameStart() const {
if (Name == 0) return "";
return Name->getKeyData();
}
/// getNameLen - Return the length of the string, correctly handling nul
/// characters embedded into them.
unsigned Value::getNameLen() const {
return Name ? Name->getKeyLength() : 0;
}
std::string Value::getNameStr() const {
if (Name == 0) return "";
return std::string(Name->getKeyData(),
Name->getKeyData()+Name->getKeyLength());
}
void Value::setName(const std::string &name) {
setName(&name[0], name.size());
}
void Value::setName(const char *Name) {
setName(Name, Name ? strlen(Name) : 0);
}
void Value::setName(const char *NameStr, unsigned NameLen) {
if (NameLen == 0 && !hasName()) return;
assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
// Get the symbol table to update for this object.
ValueSymbolTable *ST;
if (getSymTab(this, ST))
return; // Cannot set a name on this value (e.g. constant).
if (!ST) { // No symbol table to update? Just do the change.
if (NameLen == 0) {
// Free the name for this value.
Name->Destroy();
Name = 0;
return;
}
if (Name) {
// Name isn't changing?
if (NameLen == Name->getKeyLength() &&
!memcmp(Name->getKeyData(), NameStr, NameLen))
return;
Name->Destroy();
}
// NOTE: Could optimize for the case the name is shrinking to not deallocate
// then reallocated.
// Create the new name.
Name = ValueName::Create(NameStr, NameStr+NameLen);
Name->setValue(this);
return;
}
// NOTE: Could optimize for the case the name is shrinking to not deallocate
// then reallocated.
if (hasName()) {
// Name isn't changing?
if (NameLen == Name->getKeyLength() &&
!memcmp(Name->getKeyData(), NameStr, NameLen))
return;
// Remove old name.
ST->removeValueName(Name);
Name->Destroy();
Name = 0;
if (NameLen == 0)
return;
}
// Name is changing to something new.
Name = ST->createValueName(NameStr, NameLen, this);
}
/// takeName - transfer the name from V to this value, setting V's name to
/// empty. It is an error to call V->takeName(V).
void Value::takeName(Value *V) {
ValueSymbolTable *ST = 0;
// If this value has a name, drop it.
if (hasName()) {
// Get the symtab this is in.
if (getSymTab(this, ST)) {
// We can't set a name on this value, but we need to clear V's name if
// it has one.
if (V->hasName()) V->setName(0, 0);
return; // Cannot set a name on this value (e.g. constant).
}
// Remove old name.
if (ST)
ST->removeValueName(Name);
Name->Destroy();
Name = 0;
}
// Now we know that this has no name.
// If V has no name either, we're done.
if (!V->hasName()) return;
// Get this's symtab if we didn't before.
if (!ST) {
if (getSymTab(this, ST)) {
// Clear V's name.
V->setName(0, 0);
return; // Cannot set a name on this value (e.g. constant).
}
}
// Get V's ST, this should always succed, because V has a name.
ValueSymbolTable *VST;
bool Failure = getSymTab(V, VST);
assert(!Failure && "V has a name, so it should have a ST!");
// If these values are both in the same symtab, we can do this very fast.
// This works even if both values have no symtab yet.
if (ST == VST) {
// Take the name!
Name = V->Name;
V->Name = 0;
Name->setValue(this);
return;
}
// Otherwise, things are slightly more complex. Remove V's name from VST and
// then reinsert it into ST.
if (VST)
VST->removeValueName(V->Name);
Name = V->Name;
V->Name = 0;
Name->setValue(this);
if (ST)
ST->reinsertValue(this);
}
// uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
// except that it doesn't have all of the asserts. The asserts fail because we
// are half-way done resolving types, which causes some types to exist as two
// different Type*'s at the same time. This is a sledgehammer to work around
// this problem.
//
void Value::uncheckedReplaceAllUsesWith(Value *New) {
while (!use_empty()) {
Use &U = *UseList;
// Must handle Constants specially, we cannot call replaceUsesOfWith on a
// constant because they are uniqued.
if (Constant *C = dyn_cast<Constant>(U.getUser())) {
if (!isa<GlobalValue>(C)) {
C->replaceUsesOfWithOnConstant(this, New, &U);
continue;
}
}
U.set(New);
}
}
void Value::replaceAllUsesWith(Value *New) {
assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
assert(New->getType() == getType() &&
"replaceAllUses of value with new value of different type!");
uncheckedReplaceAllUsesWith(New);
}
//===----------------------------------------------------------------------===//
// User Class
//===----------------------------------------------------------------------===//
// replaceUsesOfWith - Replaces all references to the "From" definition with
// references to the "To" definition.
//
void User::replaceUsesOfWith(Value *From, Value *To) {
if (From == To) return; // Duh what?
assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
"Cannot call User::replaceUsesofWith on a constant!");
for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
if (getOperand(i) == From) { // Is This operand is pointing to oldval?
// The side effects of this setOperand call include linking to
// "To", adding "this" to the uses list of To, and
// most importantly, removing "this" from the use list of "From".
setOperand(i, To); // Fix it now...
}
}
<commit_msg>Print the name, not a pointer.<commit_after>//===-- Value.cpp - Implement the Value class -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Value and User classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/Constant.h"
#include "llvm/DerivedTypes.h"
#include "llvm/InstrTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/ValueSymbolTable.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/LeakDetector.h"
#include <algorithm>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Value Class
//===----------------------------------------------------------------------===//
static inline const Type *checkType(const Type *Ty) {
assert(Ty && "Value defined with a null type: Error!");
return Ty;
}
Value::Value(const Type *ty, unsigned scid)
: SubclassID(scid), SubclassData(0), Ty(checkType(ty)),
UseList(0), Name(0) {
if (isa<CallInst>(this) || isa<InvokeInst>(this))
assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
isa<OpaqueType>(ty) || Ty->getTypeID() == Type::StructTyID) &&
"invalid CallInst type!");
else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
isa<OpaqueType>(ty)) &&
"Cannot create non-first-class values except for constants!");
}
Value::~Value() {
#ifndef NDEBUG // Only in -g mode...
// Check to make sure that there are no uses of this value that are still
// around when the value is destroyed. If there are, then we have a dangling
// reference and something is wrong. This code is here to print out what is
// still being referenced. The value in question should be printed as
// a <badref>
//
if (!use_empty()) {
DOUT << "While deleting: " << *Ty << " %" << getNameStr() << "\n";
for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
DOUT << "Use still stuck around after Def is destroyed:"
<< **I << "\n";
}
#endif
assert(use_empty() && "Uses remain when a value is destroyed!");
// If this value is named, destroy the name. This should not be in a symtab
// at this point.
if (Name)
Name->Destroy();
// There should be no uses of this object anymore, remove it.
LeakDetector::removeGarbageObject(this);
}
/// hasNUses - Return true if this Value has exactly N users.
///
bool Value::hasNUses(unsigned N) const {
use_const_iterator UI = use_begin(), E = use_end();
for (; N; --N, ++UI)
if (UI == E) return false; // Too few.
return UI == E;
}
/// hasNUsesOrMore - Return true if this value has N users or more. This is
/// logically equivalent to getNumUses() >= N.
///
bool Value::hasNUsesOrMore(unsigned N) const {
use_const_iterator UI = use_begin(), E = use_end();
for (; N; --N, ++UI)
if (UI == E) return false; // Too few.
return true;
}
/// getNumUses - This method computes the number of uses of this Value. This
/// is a linear time operation. Use hasOneUse or hasNUses to check for specific
/// values.
unsigned Value::getNumUses() const {
return (unsigned)std::distance(use_begin(), use_end());
}
static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
ST = 0;
if (Instruction *I = dyn_cast<Instruction>(V)) {
if (BasicBlock *P = I->getParent())
if (Function *PP = P->getParent())
ST = &PP->getValueSymbolTable();
} else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
if (Function *P = BB->getParent())
ST = &P->getValueSymbolTable();
} else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
if (Module *P = GV->getParent())
ST = &P->getValueSymbolTable();
} else if (Argument *A = dyn_cast<Argument>(V)) {
if (Function *P = A->getParent())
ST = &P->getValueSymbolTable();
} else {
assert(isa<Constant>(V) && "Unknown value type!");
return true; // no name is setable for this.
}
return false;
}
/// getNameStart - Return a pointer to a null terminated string for this name.
/// Note that names can have null characters within the string as well as at
/// their end. This always returns a non-null pointer.
const char *Value::getNameStart() const {
if (Name == 0) return "";
return Name->getKeyData();
}
/// getNameLen - Return the length of the string, correctly handling nul
/// characters embedded into them.
unsigned Value::getNameLen() const {
return Name ? Name->getKeyLength() : 0;
}
std::string Value::getNameStr() const {
if (Name == 0) return "";
return std::string(Name->getKeyData(),
Name->getKeyData()+Name->getKeyLength());
}
void Value::setName(const std::string &name) {
setName(&name[0], name.size());
}
void Value::setName(const char *Name) {
setName(Name, Name ? strlen(Name) : 0);
}
void Value::setName(const char *NameStr, unsigned NameLen) {
if (NameLen == 0 && !hasName()) return;
assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
// Get the symbol table to update for this object.
ValueSymbolTable *ST;
if (getSymTab(this, ST))
return; // Cannot set a name on this value (e.g. constant).
if (!ST) { // No symbol table to update? Just do the change.
if (NameLen == 0) {
// Free the name for this value.
Name->Destroy();
Name = 0;
return;
}
if (Name) {
// Name isn't changing?
if (NameLen == Name->getKeyLength() &&
!memcmp(Name->getKeyData(), NameStr, NameLen))
return;
Name->Destroy();
}
// NOTE: Could optimize for the case the name is shrinking to not deallocate
// then reallocated.
// Create the new name.
Name = ValueName::Create(NameStr, NameStr+NameLen);
Name->setValue(this);
return;
}
// NOTE: Could optimize for the case the name is shrinking to not deallocate
// then reallocated.
if (hasName()) {
// Name isn't changing?
if (NameLen == Name->getKeyLength() &&
!memcmp(Name->getKeyData(), NameStr, NameLen))
return;
// Remove old name.
ST->removeValueName(Name);
Name->Destroy();
Name = 0;
if (NameLen == 0)
return;
}
// Name is changing to something new.
Name = ST->createValueName(NameStr, NameLen, this);
}
/// takeName - transfer the name from V to this value, setting V's name to
/// empty. It is an error to call V->takeName(V).
void Value::takeName(Value *V) {
ValueSymbolTable *ST = 0;
// If this value has a name, drop it.
if (hasName()) {
// Get the symtab this is in.
if (getSymTab(this, ST)) {
// We can't set a name on this value, but we need to clear V's name if
// it has one.
if (V->hasName()) V->setName(0, 0);
return; // Cannot set a name on this value (e.g. constant).
}
// Remove old name.
if (ST)
ST->removeValueName(Name);
Name->Destroy();
Name = 0;
}
// Now we know that this has no name.
// If V has no name either, we're done.
if (!V->hasName()) return;
// Get this's symtab if we didn't before.
if (!ST) {
if (getSymTab(this, ST)) {
// Clear V's name.
V->setName(0, 0);
return; // Cannot set a name on this value (e.g. constant).
}
}
// Get V's ST, this should always succed, because V has a name.
ValueSymbolTable *VST;
bool Failure = getSymTab(V, VST);
assert(!Failure && "V has a name, so it should have a ST!");
// If these values are both in the same symtab, we can do this very fast.
// This works even if both values have no symtab yet.
if (ST == VST) {
// Take the name!
Name = V->Name;
V->Name = 0;
Name->setValue(this);
return;
}
// Otherwise, things are slightly more complex. Remove V's name from VST and
// then reinsert it into ST.
if (VST)
VST->removeValueName(V->Name);
Name = V->Name;
V->Name = 0;
Name->setValue(this);
if (ST)
ST->reinsertValue(this);
}
// uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
// except that it doesn't have all of the asserts. The asserts fail because we
// are half-way done resolving types, which causes some types to exist as two
// different Type*'s at the same time. This is a sledgehammer to work around
// this problem.
//
void Value::uncheckedReplaceAllUsesWith(Value *New) {
while (!use_empty()) {
Use &U = *UseList;
// Must handle Constants specially, we cannot call replaceUsesOfWith on a
// constant because they are uniqued.
if (Constant *C = dyn_cast<Constant>(U.getUser())) {
if (!isa<GlobalValue>(C)) {
C->replaceUsesOfWithOnConstant(this, New, &U);
continue;
}
}
U.set(New);
}
}
void Value::replaceAllUsesWith(Value *New) {
assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
assert(New->getType() == getType() &&
"replaceAllUses of value with new value of different type!");
uncheckedReplaceAllUsesWith(New);
}
//===----------------------------------------------------------------------===//
// User Class
//===----------------------------------------------------------------------===//
// replaceUsesOfWith - Replaces all references to the "From" definition with
// references to the "To" definition.
//
void User::replaceUsesOfWith(Value *From, Value *To) {
if (From == To) return; // Duh what?
assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
"Cannot call User::replaceUsesofWith on a constant!");
for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
if (getOperand(i) == From) { // Is This operand is pointing to oldval?
// The side effects of this setOperand call include linking to
// "To", adding "this" to the uses list of To, and
// most importantly, removing "this" from the use list of "From".
setOperand(i, To); // Fix it now...
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xeescher.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-11-09 15:07:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XEESCHER_HXX
#define SC_XEESCHER_HXX
#ifndef SC_XLESCHER_HXX
#include "xlescher.hxx"
#endif
#include "xcl97rec.hxx"
// ============================================================================
class XclExpTokenArray;
/** Helper to manage controls linked to the sheet. */
class XclExpCtrlLinkHelper : protected XclExpRoot
{
public:
explicit XclExpCtrlLinkHelper( const XclExpRoot& rRoot );
virtual ~XclExpCtrlLinkHelper();
/** Sets the address of the control's linked cell. */
void SetCellLink( const ScAddress& rCellLink );
/** Sets the address of the control's linked source cell range. */
void SetSourceRange( const ScRange& rSrcRange );
protected:
/** Returns the Excel token array of the cell link, or 0, if no link present. */
inline const XclExpTokenArray* GetCellLinkTokArr() const { return mxCellLink.get(); }
/** Returns the Excel token array of the source range, or 0, if no link present. */
inline const XclExpTokenArray* GetSourceRangeTokArr() const { return mxSrcRange.get(); }
/** Returns the number of entries in the source range, or 0, if no source set. */
inline sal_uInt16 GetSourceEntryCount() const { return mnEntryCount; }
/** Writes a sheet link formula with special style only valid in OBJ records. */
void WriteFormula( XclExpStream& rStrm, const XclExpTokenArray& rTokArr ) const;
private:
XclExpTokenArrayRef mxCellLink; /// Formula for linked cell.
XclExpTokenArrayRef mxSrcRange; /// Formula for source data range.
sal_uInt16 mnEntryCount; /// Number of entries in source range.
};
// ----------------------------------------------------------------------------
#if EXC_EXP_OCX_CTRL
/** Represents an OBJ record for an OCX form control. */
class XclExpObjOcxCtrl : public XclObj, public XclExpCtrlLinkHelper
{
public:
explicit XclExpObjOcxCtrl(
const XclExpRoot& rRoot,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::awt::XControlModel >& rxCtrlModel,
const String& rClassName,
sal_uInt32 nStrmStart, sal_uInt32 nStrmSize );
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
private:
String maClassName; /// Class name of the control.
sal_uInt32 mnStrmStart; /// Start position in 'Ctls' stream.
sal_uInt32 mnStrmSize; /// Size in 'Ctls' stream.
};
#else
/** Represents an OBJ record for an TBX form control. */
class XclExpObjTbxCtrl : public XclObj, public XclExpCtrlLinkHelper
{
public:
explicit XclExpObjTbxCtrl(
const XclExpRoot& rRoot,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::awt::XControlModel >& rxCtrlModel );
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
/** Writes a sub structure containing a cell link, or nothing, if no link present. */
void WriteCellLinkFmla( XclExpStream& rStrm, sal_uInt16 nSubRecId );
/** Writes the ftSbs sub structure containing scrollbar data. */
void WriteSbs( XclExpStream& rStrm );
private:
ScfInt16Vec maMultiSel; /// Indexes of all selected entries in a multi selection.
sal_Int32 mnHeight; /// Height of the control.
sal_uInt16 mnState; /// Checked/unchecked state.
sal_Int16 mnLineCount; /// Combobox dropdown line count.
sal_Int16 mnSelEntry; /// Selected entry in combobox (1-based).
sal_Int16 mnScrollValue; /// Scrollbar: Current value.
sal_Int16 mnScrollMin; /// Scrollbar: Minimum value.
sal_Int16 mnScrollMax; /// Scrollbar: Maximum value.
sal_Int16 mnScrollStep; /// Scrollbar: Single step.
sal_Int16 mnScrollPage; /// Scrollbar: Page step.
bool mbFlatButton; /// False = 3D button style; True = Flat button style.
bool mbFlatBorder; /// False = 3D border style; True = Flat border style.
bool mbMultiSel; /// true = Multi selection in listbox.
bool mbScrollHor; /// Scrollbar: true = horizontal.
};
#endif
// ============================================================================
/** Represents a NOTE record containing the relevant data of a cell note.
NOTE records differ significantly in various BIFF versions. This class
encapsulates all needed actions for each supported BIFF version.
BIFF5/BIFF7: Stores the note text and generates a single or multiple NOTE
records on saving.
BIFF8: Creates the Escher object containing the drawing information and the
note text.
*/
class XclExpNote : public XclExpRecord
{
public:
/** Constructs a NOTE record from the passed note object and/or the text.
@descr The additional text will be separated from the note text with
an empty line.
@param rScPos The Calc cell address of the note.
@param pScNote The Calc note object. May be 0 to create a note from rAddText only.
@param rAddText Additional text appended to the note text. */
explicit XclExpNote(
const XclExpRoot& rRoot,
const ScAddress& rScPos,
const ScPostIt* pScNote,
const String& rAddText );
/** Writes the NOTE record, if the respective Escher object is present. */
virtual void Save( XclExpStream& rStrm );
private:
/** Writes the body of the NOTE record. */
virtual void WriteBody( XclExpStream& rStrm );
private:
XclExpString maAuthor; /// Name of the author.
ByteString maNoteText; /// Main text of the note (<=BIFF7).
ScAddress maScPos; /// Calc cell address of the note.
sal_uInt16 mnObjId; /// Escher object ID (BIFF8).
bool mbVisible; /// true = permanently visible.
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS dr31 (1.4.32); FILE MERGED 2004/12/09 09:04:37 dr 1.4.32.1: #i37965# import/export of control<->macro links, code cleanup<commit_after>/*************************************************************************
*
* $RCSfile: xeescher.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2005-01-14 12:09:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XEESCHER_HXX
#define SC_XEESCHER_HXX
#ifndef SC_XLESCHER_HXX
#include "xlescher.hxx"
#endif
#include "xcl97rec.hxx"
namespace com { namespace sun { namespace star {
namespace script { struct ScriptEventDescriptor; }
} } }
// ============================================================================
class XclExpTokenArray;
/** Helper to manage controls linked to the sheet. */
class XclExpCtrlLinkHelper : protected XclExpRoot
{
public:
explicit XclExpCtrlLinkHelper( const XclExpRoot& rRoot );
virtual ~XclExpCtrlLinkHelper();
/** Sets the address of the control's linked cell. */
void SetCellLink( const ScAddress& rCellLink );
/** Sets the address of the control's linked source cell range. */
void SetSourceRange( const ScRange& rSrcRange );
protected:
/** Returns the Excel token array of the cell link, or 0, if no link present. */
inline const XclExpTokenArray* GetCellLinkTokArr() const { return mxCellLink.get(); }
/** Returns the Excel token array of the source range, or 0, if no link present. */
inline const XclExpTokenArray* GetSourceRangeTokArr() const { return mxSrcRange.get(); }
/** Returns the number of entries in the source range, or 0, if no source set. */
inline sal_uInt16 GetSourceEntryCount() const { return mnEntryCount; }
/** Writes a formula with special style only valid in OBJ records. */
void WriteFormula( XclExpStream& rStrm, const XclExpTokenArray& rTokArr ) const;
/** Writes a formula subrecord with special style only valid in OBJ records. */
void WriteFormulaSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId, const XclExpTokenArray& rTokArr ) const;
private:
XclExpTokenArrayRef mxCellLink; /// Formula for linked cell.
XclExpTokenArrayRef mxSrcRange; /// Formula for source data range.
sal_uInt16 mnEntryCount; /// Number of entries in source range.
};
// ----------------------------------------------------------------------------
#if EXC_EXP_OCX_CTRL
/** Represents an OBJ record for an OCX form control. */
class XclExpObjOcxCtrl : public XclObj, public XclExpCtrlLinkHelper
{
public:
explicit XclExpObjOcxCtrl(
const XclExpRoot& rRoot,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::awt::XControlModel >& rxCtrlModel,
const String& rClassName,
sal_uInt32 nStrmStart, sal_uInt32 nStrmSize );
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
private:
String maClassName; /// Class name of the control.
sal_uInt32 mnStrmStart; /// Start position in 'Ctls' stream.
sal_uInt32 mnStrmSize; /// Size in 'Ctls' stream.
};
#else
/** Represents an OBJ record for an TBX form control. */
class XclExpObjTbxCtrl : public XclObj, public XclExpCtrlLinkHelper
{
public:
explicit XclExpObjTbxCtrl(
const XclExpRoot& rRoot,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::awt::XControlModel >& rxCtrlModel );
/** Sets the name of a macro attached to this control.
@return true = The passed event descriptor was valid, macro name has been found. */
bool SetMacroLink( const ::com::sun::star::script::ScriptEventDescriptor& rEvent );
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
/** Writes an ftMacro subrecord containing a macro link, or nothing, if no macro present. */
void WriteMacroSubRec( XclExpStream& rStrm );
/** Writes a subrecord containing a cell link, or nothing, if no link present. */
void WriteCellLinkSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId );
/** Writes the ftSbs sub structure containing scrollbar data. */
void WriteSbs( XclExpStream& rStrm );
private:
ScfInt16Vec maMultiSel; /// Indexes of all selected entries in a multi selection.
XclExpTokenArrayRef mxMacroLink; /// Token array containing a link to an attached macro.
sal_Int32 mnHeight; /// Height of the control.
sal_uInt16 mnState; /// Checked/unchecked state.
sal_Int16 mnLineCount; /// Combobox dropdown line count.
sal_Int16 mnSelEntry; /// Selected entry in combobox (1-based).
sal_Int16 mnScrollValue; /// Scrollbar: Current value.
sal_Int16 mnScrollMin; /// Scrollbar: Minimum value.
sal_Int16 mnScrollMax; /// Scrollbar: Maximum value.
sal_Int16 mnScrollStep; /// Scrollbar: Single step.
sal_Int16 mnScrollPage; /// Scrollbar: Page step.
bool mbFlatButton; /// False = 3D button style; True = Flat button style.
bool mbFlatBorder; /// False = 3D border style; True = Flat border style.
bool mbMultiSel; /// true = Multi selection in listbox.
bool mbScrollHor; /// Scrollbar: true = horizontal.
};
#endif
// ============================================================================
/** Represents a NOTE record containing the relevant data of a cell note.
NOTE records differ significantly in various BIFF versions. This class
encapsulates all needed actions for each supported BIFF version.
BIFF5/BIFF7: Stores the note text and generates a single or multiple NOTE
records on saving.
BIFF8: Creates the Escher object containing the drawing information and the
note text.
*/
class XclExpNote : public XclExpRecord
{
public:
/** Constructs a NOTE record from the passed note object and/or the text.
@descr The additional text will be separated from the note text with
an empty line.
@param rScPos The Calc cell address of the note.
@param pScNote The Calc note object. May be 0 to create a note from rAddText only.
@param rAddText Additional text appended to the note text. */
explicit XclExpNote(
const XclExpRoot& rRoot,
const ScAddress& rScPos,
const ScPostIt* pScNote,
const String& rAddText );
/** Writes the NOTE record, if the respective Escher object is present. */
virtual void Save( XclExpStream& rStrm );
private:
/** Writes the body of the NOTE record. */
virtual void WriteBody( XclExpStream& rStrm );
private:
XclExpString maAuthor; /// Name of the author.
ByteString maNoteText; /// Main text of the note (<=BIFF7).
ScAddress maScPos; /// Calc cell address of the note.
sal_uInt16 mnObjId; /// Escher object ID (BIFF8).
bool mbVisible; /// true = permanently visible.
};
// ============================================================================
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlexprt.hxx,v $
*
* $Revision: 1.82 $
*
* last change: $Author: kz $ $Date: 2006-01-31 18:37:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_XMLEXPRT_HXX
#define SC_XMLEXPRT_HXX
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEET_HPP_
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HDL_
#include <com/sun/star/drawing/XShapes.hdl>
#endif
#ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_
#include <com/sun/star/table/XCellRange.hpp>
#endif
class ScOutlineArray;
class SvXMLExportPropertyMapper;
class ScMyShapesContainer;
class ScMyMergedRangesContainer;
class ScMyValidationsContainer;
class ScMyNotEmptyCellsIterator;
class ScChangeTrackingExportHelper;
class ScColumnStyles;
class ScRowStyles;
class ScFormatRangeStyles;
class ScRowFormatRanges;
class ScMyOpenCloseColumnRowGroup;
class ScMyAreaLinksContainer;
class ScMyDetectiveOpContainer;
struct ScMyCell;
class ScDocument;
class ScMySharedData;
class ScMyDefaultStyles;
class XMLNumberFormatAttributesExportHelper;
class ScChartListener;
class SfxItemPool;
class ScAddress;
typedef std::vector< com::sun::star::uno::Reference < com::sun::star::drawing::XShapes > > ScMyXShapesVec;
class ScXMLExport : public SvXMLExport
{
ScDocument* pDoc;
com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet> xCurrentTable;
com::sun::star::uno::Reference <com::sun::star::table::XCellRange> xCurrentTableCellRange;
UniReference < XMLPropertyHandlerFactory > xScPropHdlFactory;
UniReference < XMLPropertySetMapper > xCellStylesPropertySetMapper;
UniReference < XMLPropertySetMapper > xColumnStylesPropertySetMapper;
UniReference < XMLPropertySetMapper > xRowStylesPropertySetMapper;
UniReference < XMLPropertySetMapper > xTableStylesPropertySetMapper;
UniReference < SvXMLExportPropertyMapper > xCellStylesExportPropertySetMapper;
UniReference < SvXMLExportPropertyMapper > xColumnStylesExportPropertySetMapper;
UniReference < SvXMLExportPropertyMapper > xRowStylesExportPropertySetMapper;
UniReference < SvXMLExportPropertyMapper > xTableStylesExportPropertySetMapper;
XMLNumberFormatAttributesExportHelper* pNumberFormatAttributesExportHelper;
ScMySharedData* pSharedData;
ScColumnStyles* pColumnStyles;
ScRowStyles* pRowStyles;
ScFormatRangeStyles* pCellStyles;
ScRowFormatRanges* pRowFormatRanges;
std::vector<rtl::OUString> aTableStyles;
com::sun::star::table::CellRangeAddress aRowHeaderRange;
ScMyOpenCloseColumnRowGroup* pGroupColumns;
ScMyOpenCloseColumnRowGroup* pGroupRows;
ScMyDefaultStyles* pDefaults;
ScChartListener* pChartListener;
const ScMyCell* pCurrentCell;
ScMyMergedRangesContainer* pMergedRangesContainer;
ScMyValidationsContainer* pValidationsContainer;
ScMyNotEmptyCellsIterator* pCellsItr;
ScChangeTrackingExportHelper* pChangeTrackingExportHelper;
const rtl::OUString sLayerID;
const rtl::OUString sCaptionShape;
rtl::OUString sAttrName;
rtl::OUString sAttrStyleName;
rtl::OUString sAttrColumnsRepeated;
rtl::OUString sAttrFormula;
rtl::OUString sAttrValueType;
rtl::OUString sAttrStringValue;
rtl::OUString sElemCell;
rtl::OUString sElemCoveredCell;
rtl::OUString sElemCol;
rtl::OUString sElemRow;
rtl::OUString sElemTab;
rtl::OUString sElemP;
sal_Int32 nOpenRow;
sal_Int32 nProgressCount;
sal_uInt16 nCurrentTable;
sal_Bool bHasRowHeader;
sal_Bool bRowHeaderOpen;
sal_Bool mbShowProgress;
sal_Bool HasDrawPages(com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheetDocument>& xDoc);
void CollectSharedData(sal_Int32& nTableCount, sal_Int32& nShapesCount, const sal_Int32 nCellCount);
void CollectShapesAutoStyles(const sal_Int32 nTableCount);
void WriteTablesView(const com::sun::star::uno::Any& aTableView);
void WriteView(const com::sun::star::uno::Any& aView);
virtual void _ExportFontDecls();
virtual void _ExportStyles( sal_Bool bUsed );
virtual void _ExportAutoStyles();
virtual void _ExportMasterStyles();
virtual void SetBodyAttributes();
virtual void _ExportContent();
virtual void _ExportMeta();
void CollectInternalShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape );
com::sun::star::table::CellRangeAddress GetEndAddress(com::sun::star::uno::Reference<com::sun::star::sheet::XSpreadsheet>& xTable,
const sal_Int32 nTable);
// ScMyEmptyDatabaseRangesContainer GetEmptyDatabaseRanges();
void GetAreaLinks( com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc, ScMyAreaLinksContainer& rAreaLinks );
void GetDetectiveOpList( ScMyDetectiveOpContainer& rDetOp );
void WriteSingleColumn(const sal_Int32 nRepeatColumns, const sal_Int32 nStyleIndex,
const sal_Int32 nIndex, const sal_Bool bIsAutoStyle, const sal_Bool bIsVisible);
void WriteColumn(const sal_Int32 nColumn, const sal_Int32 nRepeatColumns,
const sal_Int32 nStyleIndex, const sal_Bool bIsVisible);
void OpenHeaderColumn();
void CloseHeaderColumn();
void ExportColumns(const sal_Int32 nTable, const com::sun::star::table::CellRangeAddress& aColumnHeaderRange, const sal_Bool bHasColumnHeader);
void ExportFormatRanges(const sal_Int32 nStartCol, const sal_Int32 nStartRow,
const sal_Int32 nEndCol, const sal_Int32 nEndRow, const sal_Int32 nSheet);
void WriteRowContent();
void WriteRowStartTag(sal_Int32 nRow, const sal_Int32 nIndex, const sal_Int8 nFlag, const sal_Int32 nEmptyRows);
void OpenHeaderRows();
void CloseHeaderRows();
void OpenNewRow(const sal_Int32 nIndex, const sal_Int8 nFlag, const sal_Int32 nStartRow, const sal_Int32 nEmptyRows);
void OpenAndCloseRow(const sal_Int32 nIndex, const sal_Int8 nFlag,
const sal_Int32 nStartRow, const sal_Int32 nEmptyRows);
void OpenRow(const sal_Int32 nTable, const sal_Int32 nStartRow, const sal_Int32 nRepeatRow);
void CloseRow(const sal_Int32 nRow);
void GetColumnRowHeader(sal_Bool& bHasColumnHeader, com::sun::star::table::CellRangeAddress& aColumnHeaderRange,
sal_Bool& bHasRowHeader, com::sun::star::table::CellRangeAddress& aRowHeaderRange,
rtl::OUString& rPrintRanges) const;
void FillFieldGroup(ScOutlineArray* pFields, ScMyOpenCloseColumnRowGroup* pGroups);
void FillColumnRowGroups();
sal_Bool GetMerge (const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet>& xTable,
sal_Int32 nCol, sal_Int32 nRow,
com::sun::star::table::CellRangeAddress& aCellAddress);
sal_Bool GetMerged (const com::sun::star::table::CellRangeAddress* pCellRange,
const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet>& xTable);
sal_Bool GetCellText (ScMyCell& rMyCell, const ScAddress& aPos) const;
void WriteCell (ScMyCell& aCell);
void WriteAreaLink(const ScMyCell& rMyCell);
void WriteAnnotation(ScMyCell& rMyCell);
void RemoveTempAnnotaionShape(const sal_Int32 nTable);
void WriteDetective(const ScMyCell& rMyCell);
void ExportShape(const com::sun::star::uno::Reference < com::sun::star::drawing::XShape >& xShape, com::sun::star::awt::Point* pPoint);
void WriteShapes(const ScMyCell& rMyCell);
void WriteTableShapes();
void SetRepeatAttribute (const sal_Int32 nEqualCellCount);
sal_Bool IsCellTypeEqual (const ScMyCell& aCell1, const ScMyCell& aCell2) const;
sal_Bool IsEditCell(const com::sun::star::table::CellAddress& aAddress) const;
sal_Bool IsEditCell(const com::sun::star::uno::Reference <com::sun::star::table::XCell>& xCell) const;
sal_Bool IsEditCell(ScMyCell& rCell) const;
sal_Bool IsAnnotationEqual(const com::sun::star::uno::Reference<com::sun::star::table::XCell>& xCell1,
const com::sun::star::uno::Reference<com::sun::star::table::XCell>& xCell2);
sal_Bool IsCellEqual (ScMyCell& aCell1, ScMyCell& aCell2);
void WriteCalculationSettings(const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc);
void WriteTableSource();
void WriteScenario(); // core implementation
void WriteTheLabelRanges(const com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc);
void WriteLabelRanges( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& xRangesIAccess, sal_Bool bColumn );
void WriteNamedExpressions(const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc);
void WriteConsolidation(); // core implementation
void CollectUserDefinedNamespaces(const SfxItemPool* pPool, sal_uInt16 nAttrib);
void IncrementProgressBar(sal_Bool bEditCell, sal_Int32 nInc = 1);
protected:
virtual SvXMLAutoStylePoolP* CreateAutoStylePool();
virtual XMLPageExport* CreatePageExport();
virtual XMLShapeExport* CreateShapeExport();
virtual XMLFontAutoStylePool* CreateFontAutoStylePool();
public:
// #110680#
ScXMLExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const sal_uInt16 nExportFlag);
virtual ~ScXMLExport();
static sal_Int16 GetFieldUnit();
inline ScDocument* GetDocument() { return pDoc; }
inline const ScDocument* GetDocument() const { return pDoc; }
sal_Bool IsMatrix (const com::sun::star::uno::Reference <com::sun::star::table::XCellRange>& xCellRange,
const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet>& xTable,
const sal_Int32 nCol, const sal_Int32 nRow,
com::sun::star::table::CellRangeAddress& aCellAddress, sal_Bool& bIsFirst) const;
sal_Bool IsMatrix (const ScAddress& aCell,
com::sun::star::table::CellRangeAddress& aCellAddress, sal_Bool& bIsFirst) const;
UniReference < XMLPropertySetMapper > GetCellStylesPropertySetMapper() { return xCellStylesPropertySetMapper; }
UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() { return xTableStylesPropertySetMapper; }
void GetChangeTrackViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps);
virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps);
virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps);
virtual void exportAnnotationMeta( const com::sun::star::uno::Reference < com::sun::star::drawing::XShape >& xShape);
void CreateSharedData(const sal_Int32 nTableCount);
void SetSharedData(ScMySharedData* pTemp) { pSharedData = pTemp; }
ScMySharedData* GetSharedData() { return pSharedData; }
XMLNumberFormatAttributesExportHelper* GetNumberFormatAttributesExportHelper();
// Export the document.
virtual sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass = ::xmloff::token::XML_TOKEN_INVALID );
// XExporter
virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
// XFilter
virtual sal_Bool SAL_CALL filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL cancel() throw(::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);
// XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
virtual void DisposingModel();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.82.622); FILE MERGED 2008/04/01 15:30:31 thb 1.82.622.3: #i85898# Stripping all external header guards 2008/04/01 12:36:34 thb 1.82.622.2: #i85898# Stripping all external header guards 2008/03/31 17:14:58 rt 1.82.622.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: xmlexprt.hxx,v $
* $Revision: 1.83 $
*
* 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 SC_XMLEXPRT_HXX
#define SC_XMLEXPRT_HXX
#include <xmloff/xmlexp.hxx>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/table/CellRangeAddress.hpp>
#include <com/sun/star/table/CellAddress.hpp>
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HDL_
#include <com/sun/star/drawing/XShapes.hdl>
#endif
#include <com/sun/star/table/XCellRange.hpp>
class ScOutlineArray;
class SvXMLExportPropertyMapper;
class ScMyShapesContainer;
class ScMyMergedRangesContainer;
class ScMyValidationsContainer;
class ScMyNotEmptyCellsIterator;
class ScChangeTrackingExportHelper;
class ScColumnStyles;
class ScRowStyles;
class ScFormatRangeStyles;
class ScRowFormatRanges;
class ScMyOpenCloseColumnRowGroup;
class ScMyAreaLinksContainer;
class ScMyDetectiveOpContainer;
struct ScMyCell;
class ScDocument;
class ScMySharedData;
class ScMyDefaultStyles;
class XMLNumberFormatAttributesExportHelper;
class ScChartListener;
class SfxItemPool;
class ScAddress;
typedef std::vector< com::sun::star::uno::Reference < com::sun::star::drawing::XShapes > > ScMyXShapesVec;
class ScXMLExport : public SvXMLExport
{
ScDocument* pDoc;
com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet> xCurrentTable;
com::sun::star::uno::Reference <com::sun::star::table::XCellRange> xCurrentTableCellRange;
UniReference < XMLPropertyHandlerFactory > xScPropHdlFactory;
UniReference < XMLPropertySetMapper > xCellStylesPropertySetMapper;
UniReference < XMLPropertySetMapper > xColumnStylesPropertySetMapper;
UniReference < XMLPropertySetMapper > xRowStylesPropertySetMapper;
UniReference < XMLPropertySetMapper > xTableStylesPropertySetMapper;
UniReference < SvXMLExportPropertyMapper > xCellStylesExportPropertySetMapper;
UniReference < SvXMLExportPropertyMapper > xColumnStylesExportPropertySetMapper;
UniReference < SvXMLExportPropertyMapper > xRowStylesExportPropertySetMapper;
UniReference < SvXMLExportPropertyMapper > xTableStylesExportPropertySetMapper;
XMLNumberFormatAttributesExportHelper* pNumberFormatAttributesExportHelper;
ScMySharedData* pSharedData;
ScColumnStyles* pColumnStyles;
ScRowStyles* pRowStyles;
ScFormatRangeStyles* pCellStyles;
ScRowFormatRanges* pRowFormatRanges;
std::vector<rtl::OUString> aTableStyles;
com::sun::star::table::CellRangeAddress aRowHeaderRange;
ScMyOpenCloseColumnRowGroup* pGroupColumns;
ScMyOpenCloseColumnRowGroup* pGroupRows;
ScMyDefaultStyles* pDefaults;
ScChartListener* pChartListener;
const ScMyCell* pCurrentCell;
ScMyMergedRangesContainer* pMergedRangesContainer;
ScMyValidationsContainer* pValidationsContainer;
ScMyNotEmptyCellsIterator* pCellsItr;
ScChangeTrackingExportHelper* pChangeTrackingExportHelper;
const rtl::OUString sLayerID;
const rtl::OUString sCaptionShape;
rtl::OUString sAttrName;
rtl::OUString sAttrStyleName;
rtl::OUString sAttrColumnsRepeated;
rtl::OUString sAttrFormula;
rtl::OUString sAttrValueType;
rtl::OUString sAttrStringValue;
rtl::OUString sElemCell;
rtl::OUString sElemCoveredCell;
rtl::OUString sElemCol;
rtl::OUString sElemRow;
rtl::OUString sElemTab;
rtl::OUString sElemP;
sal_Int32 nOpenRow;
sal_Int32 nProgressCount;
sal_uInt16 nCurrentTable;
sal_Bool bHasRowHeader;
sal_Bool bRowHeaderOpen;
sal_Bool mbShowProgress;
sal_Bool HasDrawPages(com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheetDocument>& xDoc);
void CollectSharedData(sal_Int32& nTableCount, sal_Int32& nShapesCount, const sal_Int32 nCellCount);
void CollectShapesAutoStyles(const sal_Int32 nTableCount);
void WriteTablesView(const com::sun::star::uno::Any& aTableView);
void WriteView(const com::sun::star::uno::Any& aView);
virtual void _ExportFontDecls();
virtual void _ExportStyles( sal_Bool bUsed );
virtual void _ExportAutoStyles();
virtual void _ExportMasterStyles();
virtual void SetBodyAttributes();
virtual void _ExportContent();
virtual void _ExportMeta();
void CollectInternalShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape );
com::sun::star::table::CellRangeAddress GetEndAddress(com::sun::star::uno::Reference<com::sun::star::sheet::XSpreadsheet>& xTable,
const sal_Int32 nTable);
// ScMyEmptyDatabaseRangesContainer GetEmptyDatabaseRanges();
void GetAreaLinks( com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc, ScMyAreaLinksContainer& rAreaLinks );
void GetDetectiveOpList( ScMyDetectiveOpContainer& rDetOp );
void WriteSingleColumn(const sal_Int32 nRepeatColumns, const sal_Int32 nStyleIndex,
const sal_Int32 nIndex, const sal_Bool bIsAutoStyle, const sal_Bool bIsVisible);
void WriteColumn(const sal_Int32 nColumn, const sal_Int32 nRepeatColumns,
const sal_Int32 nStyleIndex, const sal_Bool bIsVisible);
void OpenHeaderColumn();
void CloseHeaderColumn();
void ExportColumns(const sal_Int32 nTable, const com::sun::star::table::CellRangeAddress& aColumnHeaderRange, const sal_Bool bHasColumnHeader);
void ExportFormatRanges(const sal_Int32 nStartCol, const sal_Int32 nStartRow,
const sal_Int32 nEndCol, const sal_Int32 nEndRow, const sal_Int32 nSheet);
void WriteRowContent();
void WriteRowStartTag(sal_Int32 nRow, const sal_Int32 nIndex, const sal_Int8 nFlag, const sal_Int32 nEmptyRows);
void OpenHeaderRows();
void CloseHeaderRows();
void OpenNewRow(const sal_Int32 nIndex, const sal_Int8 nFlag, const sal_Int32 nStartRow, const sal_Int32 nEmptyRows);
void OpenAndCloseRow(const sal_Int32 nIndex, const sal_Int8 nFlag,
const sal_Int32 nStartRow, const sal_Int32 nEmptyRows);
void OpenRow(const sal_Int32 nTable, const sal_Int32 nStartRow, const sal_Int32 nRepeatRow);
void CloseRow(const sal_Int32 nRow);
void GetColumnRowHeader(sal_Bool& bHasColumnHeader, com::sun::star::table::CellRangeAddress& aColumnHeaderRange,
sal_Bool& bHasRowHeader, com::sun::star::table::CellRangeAddress& aRowHeaderRange,
rtl::OUString& rPrintRanges) const;
void FillFieldGroup(ScOutlineArray* pFields, ScMyOpenCloseColumnRowGroup* pGroups);
void FillColumnRowGroups();
sal_Bool GetMerge (const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet>& xTable,
sal_Int32 nCol, sal_Int32 nRow,
com::sun::star::table::CellRangeAddress& aCellAddress);
sal_Bool GetMerged (const com::sun::star::table::CellRangeAddress* pCellRange,
const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet>& xTable);
sal_Bool GetCellText (ScMyCell& rMyCell, const ScAddress& aPos) const;
void WriteCell (ScMyCell& aCell);
void WriteAreaLink(const ScMyCell& rMyCell);
void WriteAnnotation(ScMyCell& rMyCell);
void RemoveTempAnnotaionShape(const sal_Int32 nTable);
void WriteDetective(const ScMyCell& rMyCell);
void ExportShape(const com::sun::star::uno::Reference < com::sun::star::drawing::XShape >& xShape, com::sun::star::awt::Point* pPoint);
void WriteShapes(const ScMyCell& rMyCell);
void WriteTableShapes();
void SetRepeatAttribute (const sal_Int32 nEqualCellCount);
sal_Bool IsCellTypeEqual (const ScMyCell& aCell1, const ScMyCell& aCell2) const;
sal_Bool IsEditCell(const com::sun::star::table::CellAddress& aAddress) const;
sal_Bool IsEditCell(const com::sun::star::uno::Reference <com::sun::star::table::XCell>& xCell) const;
sal_Bool IsEditCell(ScMyCell& rCell) const;
sal_Bool IsAnnotationEqual(const com::sun::star::uno::Reference<com::sun::star::table::XCell>& xCell1,
const com::sun::star::uno::Reference<com::sun::star::table::XCell>& xCell2);
sal_Bool IsCellEqual (ScMyCell& aCell1, ScMyCell& aCell2);
void WriteCalculationSettings(const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc);
void WriteTableSource();
void WriteScenario(); // core implementation
void WriteTheLabelRanges(const com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc);
void WriteLabelRanges( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& xRangesIAccess, sal_Bool bColumn );
void WriteNamedExpressions(const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc);
void WriteConsolidation(); // core implementation
void CollectUserDefinedNamespaces(const SfxItemPool* pPool, sal_uInt16 nAttrib);
void IncrementProgressBar(sal_Bool bEditCell, sal_Int32 nInc = 1);
protected:
virtual SvXMLAutoStylePoolP* CreateAutoStylePool();
virtual XMLPageExport* CreatePageExport();
virtual XMLShapeExport* CreateShapeExport();
virtual XMLFontAutoStylePool* CreateFontAutoStylePool();
public:
// #110680#
ScXMLExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const sal_uInt16 nExportFlag);
virtual ~ScXMLExport();
static sal_Int16 GetFieldUnit();
inline ScDocument* GetDocument() { return pDoc; }
inline const ScDocument* GetDocument() const { return pDoc; }
sal_Bool IsMatrix (const com::sun::star::uno::Reference <com::sun::star::table::XCellRange>& xCellRange,
const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet>& xTable,
const sal_Int32 nCol, const sal_Int32 nRow,
com::sun::star::table::CellRangeAddress& aCellAddress, sal_Bool& bIsFirst) const;
sal_Bool IsMatrix (const ScAddress& aCell,
com::sun::star::table::CellRangeAddress& aCellAddress, sal_Bool& bIsFirst) const;
UniReference < XMLPropertySetMapper > GetCellStylesPropertySetMapper() { return xCellStylesPropertySetMapper; }
UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() { return xTableStylesPropertySetMapper; }
void GetChangeTrackViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps);
virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps);
virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps);
virtual void exportAnnotationMeta( const com::sun::star::uno::Reference < com::sun::star::drawing::XShape >& xShape);
void CreateSharedData(const sal_Int32 nTableCount);
void SetSharedData(ScMySharedData* pTemp) { pSharedData = pTemp; }
ScMySharedData* GetSharedData() { return pSharedData; }
XMLNumberFormatAttributesExportHelper* GetNumberFormatAttributesExportHelper();
// Export the document.
virtual sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass = ::xmloff::token::XML_TOKEN_INVALID );
// XExporter
virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
// XFilter
virtual sal_Bool SAL_CALL filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL cancel() throw(::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);
// XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
virtual void DisposingModel();
};
#endif
<|endoftext|> |
<commit_before>#pragma ident "$Id$"
/*
Think, navdmp for mdp, with bonus output that you get data from all code/carrier
combos.
*/
#include "Geodetic.hpp"
#include "NavProc.hpp"
#include "RinexConverters.hpp"
using namespace std;
using namespace gpstk;
using namespace gpstk::StringUtils;
//-----------------------------------------------------------------------------
MDPNavProcessor::MDPNavProcessor(MDPStream& in, std::ofstream& out)
: MDPProcessor(in, out),
firstNav(true), almOut(false), ephOut(false), minimalAlm(false),
badNavSubframeCount(0), navSubframeCount(0)
{
timeFormat = "%4Y/%03j/%02H:%02M:%02S";
binByElevation = true;
if (binByElevation)
{
double binSize=5;
for (double x=0; x<90; x+=binSize)
bins.push_back(Histogram::BinRange(x, x+binSize));
}
else
{
bins.push_back(Histogram::BinRange(0, 30));
double binSize=3;
for (double x=30; x<60; x+=binSize)
bins.push_back(Histogram::BinRange(x, x+binSize));
bins.push_back(Histogram::BinRange(60, 99));
}
}
//-----------------------------------------------------------------------------
MDPNavProcessor::~MDPNavProcessor()
{
using gpstk::RangeCode;
using gpstk::CarrierCode;
using gpstk::StringUtils::asString;
out << "Done processing data." << endl << endl;
if (firstNav)
{
out << " No Navigation Subframe messages processed." << endl;
return;
}
out << endl
<< "Navigation Subframe message summary:" << endl
<< " navSubframeCount: " << navSubframeCount << endl
<< " badNavSubframeCount: " << badNavSubframeCount << endl
<< " percent bad: " << setprecision(3)
<< 100.0 * badNavSubframeCount/navSubframeCount << " %" << endl;
out << "Parity Errors" << endl;
out << "# elev";
std::map<RangeCarrierPair, Histogram>::const_iterator peh_itr;
for (peh_itr = peHist.begin(); peh_itr != peHist.end(); peh_itr++)
{
const RangeCarrierPair& rcp=peh_itr->first;
out << " " << asString(rcp.second)
<< "-" << leftJustify(asString(rcp.first), 2);
}
out << endl;
Histogram::BinRangeList::const_iterator brl_itr;
for (brl_itr = bins.begin(); brl_itr != bins.end(); brl_itr++)
{
const Histogram::BinRange& br = *brl_itr ;
out << setprecision(0)
<< right << setw(2) << br.first << "-"
<< left << setw(2) << br.second << ":";
for (peh_itr = peHist.begin(); peh_itr != peHist.end(); peh_itr++)
{
const RangeCarrierPair& rcp=peh_itr->first;
Histogram h=peh_itr->second;
out << right << setw(9) << h.bins[br];
}
out << endl;
}
// Whoever would write a reference like this should be shot...
out << right << setw(2) << peHist.begin()->second.bins.begin()->first.first
<< "-" << left << setw(2) << peHist.begin()->second.bins.rbegin()->first.second
<< ":";
for (peh_itr = peHist.begin(); peh_itr != peHist.end(); peh_itr++)
out << right << setw(9) << peh_itr->second.total;
out << endl;
}
//-----------------------------------------------------------------------------
void MDPNavProcessor::process(const MDPNavSubframe& msg)
{
if (firstNav)
{
firstNav = false;
if (verboseLevel)
out << msg.time.printf(timeFormat)
<< " Received first Navigation Subframe message"
<< endl;
}
navSubframeCount++;
RangeCarrierPair rcp(msg.range, msg.carrier);
NavIndex ni(rcp, msg.prn);
MDPNavSubframe umsg = msg;
ostringstream oss;
oss << umsg.time.printf(timeFormat)
<< " PRN:" << setw(2) << umsg.prn
<< " " << asString(umsg.carrier)
<< ":" << setw(2) << left << asString(umsg.range)
<< " ";
string msgPrefix = oss.str();
umsg.cookSubframe();
if (verboseLevel>3 && umsg.neededCooking)
out << msgPrefix << "Subframe required cooking" << endl;
if (!umsg.parityGood)
{
badNavSubframeCount++;
if (verboseLevel)
out << msgPrefix << "Parity error"
<< " SNR:" << fixed << setprecision(1) << snr[ni]
<< " EL:" << el[ni]
<< endl;
if (peHist.find(rcp) == peHist.end())
peHist[rcp].resetBins(bins);
if (binByElevation)
peHist[rcp].addValue(el[ni]);
else
peHist[rcp].addValue(snr[ni]);
return;
}
short sfid = umsg.getSFID();
short svid = umsg.getSVID();
bool isAlm = sfid > 3;
long sow = umsg.getHOWTime();
short page = ((sow-6) / 30) % 25 + 1;
if (((isAlm && almOut) || (!isAlm && ephOut))
&& verboseLevel>2)
{
out << msgPrefix
<< "SOW:" << setw(6) << sow
<< " NC:" << static_cast<int>(umsg.nav)
<< " I:" << umsg.inverted
<< " SFID:" << sfid;
if (isAlm)
out << " SVID:" << svid
<< " Page:" << page;
out << endl;
}
// Sanity check on the header time versus the HOW time
short week = umsg.time.GPSfullweek();
if (sow <0 || sow>=604800)
{
badNavSubframeCount++;
if (verboseLevel>1)
out << msgPrefix << " Bad SOW: " << sow << endl;
return;
}
DayTime howTime(week, umsg.getHOWTime());
if (howTime == umsg.time)
{
if (verboseLevel && ! (bugMask & 0x4))
out << msgPrefix << " Header time==HOW time" << endl;
}
else if (howTime != umsg.time+6)
{
badNavSubframeCount++;
if (verboseLevel>1)
out << msgPrefix << " HOW time != hdr time+6, HOW:"
<< howTime.printf(timeFormat)
<< endl;
if (verboseLevel>3)
umsg.dump(out);
return;
}
prev[ni] = curr[ni];
curr[ni] = umsg;
if (prev[ni].parityGood &&
prev[ni].inverted != curr[ni].inverted &&
curr[ni].time - prev[ni].time <= 12)
{
if (verboseLevel)
out << msgPrefix << "Polarity inversion"
<< " SNR:" << fixed << setprecision(1) << snr[ni]
<< " EL:" << el[ni]
<< endl;
}
if (isAlm && almOut)
{
AlmanacPages& almPages = almPageStore[ni];
EngAlmanac& engAlm = almStore[ni];
SubframePage sp(sfid, page);
almPages[sp] = umsg;
almPages.insert(make_pair(sp, umsg));
if (makeEngAlmanac(engAlm, almPages, !minimalAlm))
{
out << msgPrefix << "Built complete almanac" << endl;
if (verboseLevel>2)
dump(out, almPages);
if (verboseLevel>1)
engAlm.dump(out);
almPages.clear();
engAlm = EngAlmanac();
}
}
if (!isAlm && ephOut)
{
EphemerisPages& ephPages = ephPageStore[ni];
ephPages[sfid] = umsg;
EngEphemeris engEph;
try
{
if (makeEngEphemeris(engEph, ephPages))
{
out << msgPrefix << "Built complete ephemeris, iocd:0x"
<< hex << setw(3) << engEph.getIODC() << dec
<< endl;
if (verboseLevel>2)
dump(out, ephPages);
if (verboseLevel>1)
out << engEph;
ephStore[ni] = engEph;
}
}
catch (Exception& e)
{
out << e << endl;
}
}
} // end of process()
void MDPNavProcessor::process(const MDPObsEpoch& msg)
{
if (!msg)
return;
for (MDPObsEpoch::ObsMap::const_iterator i = msg.obs.begin();
i != msg.obs.end(); i++)
{
const MDPObsEpoch::Observation& obs=i->second;
NavIndex ni(RangeCarrierPair(obs.range, obs.carrier), msg.prn);
snr[ni] = obs.snr;
el[ni] = msg.elevation;
}
}
<commit_msg>Fixed a bug where nav style of mdptool would cause a segfalut when there were n parity errors<commit_after>#pragma ident "$Id$"
/*
Think, navdmp for mdp, with bonus output that you get data from all code/carrier
combos.
*/
#include "Geodetic.hpp"
#include "NavProc.hpp"
#include "RinexConverters.hpp"
using namespace std;
using namespace gpstk;
using namespace gpstk::StringUtils;
//-----------------------------------------------------------------------------
MDPNavProcessor::MDPNavProcessor(MDPStream& in, std::ofstream& out)
: MDPProcessor(in, out),
firstNav(true), almOut(false), ephOut(false), minimalAlm(false),
badNavSubframeCount(0), navSubframeCount(0)
{
timeFormat = "%4Y/%03j/%02H:%02M:%02S";
binByElevation = true;
if (binByElevation)
{
double binSize=5;
for (double x=0; x<90; x+=binSize)
bins.push_back(Histogram::BinRange(x, x+binSize));
}
else
{
bins.push_back(Histogram::BinRange(0, 30));
double binSize=3;
for (double x=30; x<60; x+=binSize)
bins.push_back(Histogram::BinRange(x, x+binSize));
bins.push_back(Histogram::BinRange(60, 99));
}
}
//-----------------------------------------------------------------------------
MDPNavProcessor::~MDPNavProcessor()
{
using gpstk::RangeCode;
using gpstk::CarrierCode;
using gpstk::StringUtils::asString;
out << "Done processing data." << endl << endl;
if (firstNav)
{
out << " No Navigation Subframe messages processed." << endl;
return;
}
out << endl
<< "Navigation Subframe message summary:" << endl
<< " navSubframeCount: " << navSubframeCount << endl
<< " badNavSubframeCount: " << badNavSubframeCount << endl
<< " percent bad: " << setprecision(3)
<< 100.0 * badNavSubframeCount/navSubframeCount << " %" << endl;
if (badNavSubframeCount==0)
return;
out << "Parity Errors" << endl;
out << "# elev";
std::map<RangeCarrierPair, Histogram>::const_iterator peh_itr;
for (peh_itr = peHist.begin(); peh_itr != peHist.end(); peh_itr++)
{
const RangeCarrierPair& rcp=peh_itr->first;
out << " " << asString(rcp.second)
<< "-" << leftJustify(asString(rcp.first), 2);
}
out << endl;
Histogram::BinRangeList::const_iterator brl_itr;
for (brl_itr = bins.begin(); brl_itr != bins.end(); brl_itr++)
{
const Histogram::BinRange& br = *brl_itr ;
out << setprecision(0)
<< right << setw(2) << br.first << "-"
<< left << setw(2) << br.second << ":";
for (peh_itr = peHist.begin(); peh_itr != peHist.end(); peh_itr++)
{
const RangeCarrierPair& rcp=peh_itr->first;
Histogram h=peh_itr->second;
out << right << setw(9) << h.bins[br];
}
out << endl;
}
// Whoever would write a reference like this should be shot...
out << right << setw(2) << peHist.begin()->second.bins.begin()->first.first
<< "-" << left << setw(2) << peHist.begin()->second.bins.rbegin()->first.second
<< ":";
for (peh_itr = peHist.begin(); peh_itr != peHist.end(); peh_itr++)
out << right << setw(9) << peh_itr->second.total;
out << endl;
}
//-----------------------------------------------------------------------------
void MDPNavProcessor::process(const MDPNavSubframe& msg)
{
if (firstNav)
{
firstNav = false;
if (verboseLevel)
out << msg.time.printf(timeFormat)
<< " Received first Navigation Subframe message"
<< endl;
}
navSubframeCount++;
RangeCarrierPair rcp(msg.range, msg.carrier);
NavIndex ni(rcp, msg.prn);
MDPNavSubframe umsg = msg;
ostringstream oss;
oss << umsg.time.printf(timeFormat)
<< " PRN:" << setw(2) << umsg.prn
<< " " << asString(umsg.carrier)
<< ":" << setw(2) << left << asString(umsg.range)
<< " ";
string msgPrefix = oss.str();
umsg.cookSubframe();
if (verboseLevel>3 && umsg.neededCooking)
out << msgPrefix << "Subframe required cooking" << endl;
if (!umsg.parityGood)
{
badNavSubframeCount++;
if (verboseLevel)
out << msgPrefix << "Parity error"
<< " SNR:" << fixed << setprecision(1) << snr[ni]
<< " EL:" << el[ni]
<< endl;
if (peHist.find(rcp) == peHist.end())
peHist[rcp].resetBins(bins);
if (binByElevation)
peHist[rcp].addValue(el[ni]);
else
peHist[rcp].addValue(snr[ni]);
return;
}
short sfid = umsg.getSFID();
short svid = umsg.getSVID();
bool isAlm = sfid > 3;
long sow = umsg.getHOWTime();
short page = ((sow-6) / 30) % 25 + 1;
if (((isAlm && almOut) || (!isAlm && ephOut))
&& verboseLevel>2)
{
out << msgPrefix
<< "SOW:" << setw(6) << sow
<< " NC:" << static_cast<int>(umsg.nav)
<< " I:" << umsg.inverted
<< " SFID:" << sfid;
if (isAlm)
out << " SVID:" << svid
<< " Page:" << page;
out << endl;
}
// Sanity check on the header time versus the HOW time
short week = umsg.time.GPSfullweek();
if (sow <0 || sow>=604800)
{
badNavSubframeCount++;
if (verboseLevel>1)
out << msgPrefix << " Bad SOW: " << sow << endl;
return;
}
DayTime howTime(week, umsg.getHOWTime());
if (howTime == umsg.time)
{
if (verboseLevel && ! (bugMask & 0x4))
out << msgPrefix << " Header time==HOW time" << endl;
}
else if (howTime != umsg.time+6)
{
badNavSubframeCount++;
if (verboseLevel>1)
out << msgPrefix << " HOW time != hdr time+6, HOW:"
<< howTime.printf(timeFormat)
<< endl;
if (verboseLevel>3)
umsg.dump(out);
return;
}
prev[ni] = curr[ni];
curr[ni] = umsg;
if (prev[ni].parityGood &&
prev[ni].inverted != curr[ni].inverted &&
curr[ni].time - prev[ni].time <= 12)
{
if (verboseLevel)
out << msgPrefix << "Polarity inversion"
<< " SNR:" << fixed << setprecision(1) << snr[ni]
<< " EL:" << el[ni]
<< endl;
}
if (isAlm && almOut)
{
AlmanacPages& almPages = almPageStore[ni];
EngAlmanac& engAlm = almStore[ni];
SubframePage sp(sfid, page);
almPages[sp] = umsg;
almPages.insert(make_pair(sp, umsg));
if (makeEngAlmanac(engAlm, almPages, !minimalAlm))
{
out << msgPrefix << "Built complete almanac" << endl;
if (verboseLevel>2)
dump(out, almPages);
if (verboseLevel>1)
engAlm.dump(out);
almPages.clear();
engAlm = EngAlmanac();
}
}
if (!isAlm && ephOut)
{
EphemerisPages& ephPages = ephPageStore[ni];
ephPages[sfid] = umsg;
EngEphemeris engEph;
try
{
if (makeEngEphemeris(engEph, ephPages))
{
out << msgPrefix << "Built complete ephemeris, iocd:0x"
<< hex << setw(3) << engEph.getIODC() << dec
<< endl;
if (verboseLevel>2)
dump(out, ephPages);
if (verboseLevel>1)
out << engEph;
ephStore[ni] = engEph;
}
}
catch (Exception& e)
{
out << e << endl;
}
}
} // end of process()
void MDPNavProcessor::process(const MDPObsEpoch& msg)
{
if (!msg)
return;
for (MDPObsEpoch::ObsMap::const_iterator i = msg.obs.begin();
i != msg.obs.end(); i++)
{
const MDPObsEpoch::Observation& obs=i->second;
NavIndex ni(RangeCarrierPair(obs.range, obs.carrier), msg.prn);
snr[ni] = obs.snr;
el[ni] = msg.elevation;
}
}
<|endoftext|> |
<commit_before>// **********************************************************************************
// Programmateur Fil Pilote et Suivi Conso
// **********************************************************************************
// Copyright (C) 2014 Thibault Ducret
// Licence MIT
//
// History : 15/01/2015 Charles-Henri Hallard (http://hallard.me)
// Intégration de version 1.2 de la carte electronique
//
// **********************************************************************************
#include "pilotes.h"
int SortiesFP[NB_FILS_PILOTES*2] = { FP1,FP2,FP3,FP4,FP5,FP6,FP7 };
char etatFP[20] = "";
// Instanciation de l'I/O expander
Adafruit_MCP23017 mcp;
/* ======================================================================
Function: setFP
Purpose : selectionne le mode d'un des fils pilotes
Input : commande numéro du fil pilote (1 à NB_FILS_PILOTE) + commande
C=Confort, A=Arrêt, E=Eco, H=Hors gel, 1=Eco-1, 2=Eco-2
ex: 1A => FP1 Arrêt
41 => FP4 eco -1 (To DO)
6C => FP6 confort
72 => FP7 eco -2 (To DO)
Output : 0 si ok -1 sinon
Comments: exposée par l'API spark donc attaquable par requête HTTP(S)
====================================================================== */
int setFP(String command)
{
command.trim();
command.toUpperCase();
// Vérifier que l'on a la commande d'un seul fil pilote (2 caractères)
if (command.length() != 2)
{
return (-1);
}
else
{
// numéro du fil pilote concerné, avec conversion ASCII > entier
// la commande est vérifiée dans fpC, pas besoin de traiter ici
uint8_t fp = command[0]-'0';
char cOrdre= command[1];
// Vérifier que le numéro du fil pilote ne dépasse le MAX et
// que la commande est correcte
// Pour le moment les ordres Eco-1 et Eco-2 ne sont pas traités
if ( (fp < 1 || fp > NB_FILS_PILOTES) ||
(cOrdre!='C' && cOrdre!='E' && cOrdre!='H' && cOrdre!='A') )
{
// erreur
return (-1);
}
// Ok ici tout est correct
else
{
// Commande à passer
uint8_t fpcmd1, fpcmd2;
// tableau d'index de 0 à 6 pas de 1 à 7
// on en profite pour Sauver l'état
etatFP[--fp]=cOrdre;
switch (cOrdre)
{
// Confort => Commande 0/0
case 'C': fpcmd1=LOW; fpcmd2=LOW; break;
// Eco => Commande 1/1
case 'E': fpcmd1=HIGH; fpcmd2=HIGH; break;
// Hors gel => Commande 1/0
case 'H': fpcmd1=HIGH; fpcmd2=LOW; break;
// Arrêt => Commande 0/1
case 'A': fpcmd1=LOW; fpcmd2=HIGH; break;
// Eco - 1
case '1': { /* to DO */ } ; break;
// Eco - 2
case '2': { /* to DO */ }; break;
}
// On positionne les sorties physiquement
_digitalWrite(SortiesFP[2*fp+0], fpcmd1);
_digitalWrite(SortiesFP[2*fp+1], fpcmd2);
return (0);
}
}
}
/* ======================================================================
Function: delestage
Purpose : met tous les fils pilotes en mode hors-gel
Input : -
Output : -
Comments: -
====================================================================== */
void delestage(void)
{
// buffer contenant la commande à passer à setFP
char cmd[] = "xH" ;
// On positionne tous les FP en Hors-Gel
for (uint8_t i=1; i<=NB_FILS_PILOTES; i+=1)
{
cmd[0]='0' + i;
setFP(cmd);
}
}
/* ======================================================================
Function: fpControl
Purpose : selectionne le mode d'un ou plusieurs les fils pilotes d'un coup
Input : liste des commandes
-=rien, C=Confort, A=Arrêt, E=Eco, H=Hors gel, 1=Eco-1, 2=Eco-2,
ex: 1A => FP1 Arrêt
CCCCCCC => Commande tous les fils pilote en mode confort (ON)
AAAAAAA => Commande tous les fils pilote en mode arrêt
EEEEEEE => Commande tous les fils pilote en mode éco
CAAAAAA => Tous OFF sauf le fil pilote 1 en confort
A-AAAAA => Tous OFF sauf le fil pilote 2 inchangé
E-CHA12 => FP2 Eco , FP2 inchangé, FP3 confort, FP4 hors gel
FP5 arrêt, FP6 Eco-1 , FP7 Eco-2
Output : 0 si ok -1 sinon
Comments: exposée par l'API spark donc attaquable par requête HTTP(S)
====================================================================== */
int fpControl(String command)
{
command.trim();
command.toUpperCase();
// Vérifier que l'on a la commande de tous les fils pilotes
if (command.length() != NB_FILS_PILOTES)
{
return(-1) ;
}
else
{
int8_t returnValue = 0; // Init à 0 => OK
char cmd[] = "xx" ; // buffer contenant la commande à passer à setFP
// envoyer les commandes pour tous les fils pilotes
for (uint8_t i=1; i<=NB_FILS_PILOTES; i++)
{
cmd[0] = i ;
cmd[1] = command[i-1]; // l'index de la chaine commence à 0 donc i-1
// Si on ne doit pas laisser le fil pilote inchangé
if (cmd[1] != '-' )
{
// ok ici au cas ou la commande setFP n'est pas bonne
// on positionne le code de retour à -1 mais on
// continue le traitement, les suivantes sont
// peut-être correctes
if (setFP(cmd) == -1)
returnValue = -1;
}
}
return returnValue;
}
}
/* ======================================================================
Function: relais
Purpose : selectionne l'état du relais
Input : état du relais (0 ouvert, 1 fermé)
Output : etat du relais (0 ou 1)
Comments: exposée par l'API spark donc attaquable par requête HTTP(S)
====================================================================== */
int relais(String command)
{
command.trim();
uint8_t cmd = command[0];
// Vérifier que l'on a la commande d'un seul caractère
if (command.length()!=1 || (cmd!='1' && cmd!='0'))
return (-1);
// Conversion en 0,1 numerique
etatrelais= cmd - '0';
// Allumer/Etteindre le relais et la LED
#ifdef RELAIS_PIN
_digitalWrite(RELAIS_PIN, etatrelais);
#endif
#ifdef LED_PIN
_digitalWrite(LED_PIN, etatrelais);
#endif
return (etatrelais);
}
/* ======================================================================
Function: pilotes_Setup
Purpose : prepare and init stuff, configuration, ..
Input : -
Output : true if MCP23017 module found, false otherwise
Comments: -
====================================================================== */
bool pilotes_setup(void)
{
// Cartes Version 1.0 et 1.1 pilotage part port I/O du spark
#if defined (REMORA_BOARD_V10) || defined (REMORA_BOARD_V11)
// 2*nbFilPilotes car 2 pins pour commander 1 fil pilote
for (uint8_t i=0; i < (NB_FILS_PILOTES*2); i++)
_pinMode(SortiesFP[i], OUTPUT); // Chaque commande de fil pilote est une sortie
// Cartes Version 1.2+ pilotage part I/O Expander
#else
Serial.print("Initializing MCP23017...");
// Détection du MCP23017
if (!i2c_detect(MCP23017_ADDRESS))
{
Serial.println("Not found!");
return (false);
}
else
{
Serial.println("OK!");
// et l'initialiser
mcp.begin();
// Mettre les 16 I/O PIN en sortie
mcp.writeRegister(MCP23017_IODIRA,0x00);
mcp.writeRegister(MCP23017_IODIRB,0x00);
}
#endif
// ou l'a trouvé
return (true);
}
<commit_msg>Correction bug commande dans fpcontrol<commit_after>// **********************************************************************************
// Programmateur Fil Pilote et Suivi Conso
// **********************************************************************************
// Copyright (C) 2014 Thibault Ducret
// Licence MIT
//
// History : 15/01/2015 Charles-Henri Hallard (http://hallard.me)
// Intégration de version 1.2 de la carte electronique
//
// **********************************************************************************
#include "pilotes.h"
int SortiesFP[NB_FILS_PILOTES*2] = { FP1,FP2,FP3,FP4,FP5,FP6,FP7 };
char etatFP[20] = "";
// Instanciation de l'I/O expander
Adafruit_MCP23017 mcp;
/* ======================================================================
Function: setFP
Purpose : selectionne le mode d'un des fils pilotes
Input : commande numéro du fil pilote (1 à NB_FILS_PILOTE) + commande
C=Confort, A=Arrêt, E=Eco, H=Hors gel, 1=Eco-1, 2=Eco-2
ex: 1A => FP1 Arrêt
41 => FP4 eco -1 (To DO)
6C => FP6 confort
72 => FP7 eco -2 (To DO)
Output : 0 si ok -1 sinon
Comments: exposée par l'API spark donc attaquable par requête HTTP(S)
====================================================================== */
int setFP(String command)
{
command.trim();
command.toUpperCase();
Serial.print("setFP=");
Serial.println(command);
// Vérifier que l'on a la commande d'un seul fil pilote (2 caractères)
if (command.length() != 2)
{
return (-1);
}
else
{
// numéro du fil pilote concerné, avec conversion ASCII > entier
// la commande est vérifiée dans fpC, pas besoin de traiter ici
uint8_t fp = command[0]-'0';
char cOrdre= command[1];
// Vérifier que le numéro du fil pilote ne dépasse le MAX et
// que la commande est correcte
// Pour le moment les ordres Eco-1 et Eco-2 ne sont pas traités
if ( (fp < 1 || fp > NB_FILS_PILOTES) ||
(cOrdre!='C' && cOrdre!='E' && cOrdre!='H' && cOrdre!='A') )
{
// erreur
return (-1);
}
// Ok ici tout est correct
else
{
// Commande à passer
uint8_t fpcmd1, fpcmd2;
// tableau d'index de 0 à 6 pas de 1 à 7
// on en profite pour Sauver l'état
etatFP[--fp]=cOrdre;
switch (cOrdre)
{
// Confort => Commande 0/0
case 'C': fpcmd1=LOW; fpcmd2=LOW; break;
// Eco => Commande 1/1
case 'E': fpcmd1=HIGH; fpcmd2=HIGH; break;
// Hors gel => Commande 1/0
case 'H': fpcmd1=HIGH; fpcmd2=LOW; break;
// Arrêt => Commande 0/1
case 'A': fpcmd1=LOW; fpcmd2=HIGH; break;
// Eco - 1
case '1': { /* to DO */ } ; break;
// Eco - 2
case '2': { /* to DO */ }; break;
}
// On positionne les sorties physiquement
_digitalWrite(SortiesFP[2*fp+0], fpcmd1);
_digitalWrite(SortiesFP[2*fp+1], fpcmd2);
return (0);
}
}
}
/* ======================================================================
Function: delestage
Purpose : met tous les fils pilotes en mode hors-gel
Input : -
Output : -
Comments: -
====================================================================== */
void delestage(void)
{
// buffer contenant la commande à passer à setFP
char cmd[] = "xH" ;
// On positionne tous les FP en Hors-Gel
for (uint8_t i=1; i<=NB_FILS_PILOTES; i+=1)
{
cmd[0]='0' + i;
setFP(cmd);
}
}
/* ======================================================================
Function: fpControl
Purpose : selectionne le mode d'un ou plusieurs les fils pilotes d'un coup
Input : liste des commandes
-=rien, C=Confort, A=Arrêt, E=Eco, H=Hors gel, 1=Eco-1, 2=Eco-2,
ex: 1A => FP1 Arrêt
CCCCCCC => Commande tous les fils pilote en mode confort (ON)
AAAAAAA => Commande tous les fils pilote en mode arrêt
EEEEEEE => Commande tous les fils pilote en mode éco
CAAAAAA => Tous OFF sauf le fil pilote 1 en confort
A-AAAAA => Tous OFF sauf le fil pilote 2 inchangé
E-CHA12 => FP2 Eco , FP2 inchangé, FP3 confort, FP4 hors gel
FP5 arrêt, FP6 Eco-1 , FP7 Eco-2
Output : 0 si ok -1 sinon
Comments: exposée par l'API spark donc attaquable par requête HTTP(S)
====================================================================== */
int fpControl(String command)
{
command.trim();
command.toUpperCase();
Serial.print("fpControl=");
Serial.println(command);
// Vérifier que l'on a la commande de tous les fils pilotes
if (command.length() != NB_FILS_PILOTES)
{
return(-1) ;
}
else
{
int8_t returnValue = 0; // Init à 0 => OK
char cmd[] = "xx" ; // buffer contenant la commande à passer à setFP
// envoyer les commandes pour tous les fils pilotes
for (uint8_t i=1; i<=NB_FILS_PILOTES; i++)
{
cmd[0] = '0' + i ;
cmd[1] = command[i-1]; // l'index de la chaine commence à 0 donc i-1
// Si on ne doit pas laisser le fil pilote inchangé
if (cmd[1] != '-' )
{
// ok ici au cas ou la commande setFP n'est pas bonne
// on positionne le code de retour à -1 mais on
// continue le traitement, les suivantes sont
// peut-être correctes
if (setFP(cmd) == -1)
returnValue = -1;
}
}
return returnValue;
}
}
/* ======================================================================
Function: relais
Purpose : selectionne l'état du relais
Input : état du relais (0 ouvert, 1 fermé)
Output : etat du relais (0 ou 1)
Comments: exposée par l'API spark donc attaquable par requête HTTP(S)
====================================================================== */
int relais(String command)
{
command.trim();
uint8_t cmd = command[0];
// Vérifier que l'on a la commande d'un seul caractère
if (command.length()!=1 || (cmd!='1' && cmd!='0'))
return (-1);
// Conversion en 0,1 numerique
etatrelais= cmd - '0';
// Allumer/Etteindre le relais et la LED
#ifdef RELAIS_PIN
_digitalWrite(RELAIS_PIN, etatrelais);
#endif
#ifdef LED_PIN
_digitalWrite(LED_PIN, etatrelais);
#endif
return (etatrelais);
}
/* ======================================================================
Function: pilotes_Setup
Purpose : prepare and init stuff, configuration, ..
Input : -
Output : true if MCP23017 module found, false otherwise
Comments: -
====================================================================== */
bool pilotes_setup(void)
{
// Cartes Version 1.0 et 1.1 pilotage part port I/O du spark
#if defined (REMORA_BOARD_V10) || defined (REMORA_BOARD_V11)
// 2*nbFilPilotes car 2 pins pour commander 1 fil pilote
for (uint8_t i=0; i < (NB_FILS_PILOTES*2); i++)
_pinMode(SortiesFP[i], OUTPUT); // Chaque commande de fil pilote est une sortie
// Cartes Version 1.2+ pilotage part I/O Expander
#else
Serial.print("Initializing MCP23017...");
// Détection du MCP23017
if (!i2c_detect(MCP23017_ADDRESS))
{
Serial.println("Not found!");
return (false);
}
else
{
Serial.println("OK!");
// et l'initialiser
mcp.begin();
// Mettre les 16 I/O PIN en sortie
mcp.writeRegister(MCP23017_IODIRA,0x00);
mcp.writeRegister(MCP23017_IODIRB,0x00);
}
#endif
// ou l'a trouvé
return (true);
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/RenderKit/RenderManager.h>
#include <osvr/RenderKit/RenderManagerImpl.h>
#include <osvr/RenderKit/RenderKitGraphicsTransforms.h>
// We pull these in so we know the right types to delete for the
// RenderBuffers
#ifdef _WIN32
#include <d3d11.h>
#include <osvr/RenderKit/GraphicsLibraryD3D11.h>
#endif
#include <osvr/RenderKit/GraphicsLibraryOpenGL.h>
// Library/third-party includes
/* none */
// Standard includes
#include <iostream>
#include <vector>
OSVR_ReturnCode osvrDestroyRenderManager(OSVR_RenderManager renderManager) {
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
delete rm;
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode
osvrRenderManagerGetNumRenderInfo(OSVR_RenderManager renderManager,
OSVR_RenderParams renderParams,
OSVR_RenderInfoCount* numRenderInfoOut) {
osvr::renderkit::RenderManager::RenderParams _renderParams;
ConvertRenderParams(renderParams, _renderParams);
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
auto ri = rm->GetRenderInfo(_renderParams);
*numRenderInfoOut = ri.size();
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode
osvrRenderManagerGetDoingOkay(OSVR_RenderManager renderManager) {
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
return rm->doingOkay() ? OSVR_RETURN_SUCCESS : OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode
osvrRenderManagerGetDefaultRenderParams(OSVR_RenderParams* renderParamsOut) {
auto& _renderParamsOut = *renderParamsOut;
_renderParamsOut.nearClipDistanceMeters = 0.1;
_renderParamsOut.farClipDistanceMeters = 100.0f;
_renderParamsOut.IPDMeters = rp.IPDMeters;
_renderParamsOut.worldFromRoomAppend = nullptr;
_renderParamsOut.roomFromHeadReplace = nullptr;
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrRenderManagerStartPresentRenderBuffers(
OSVR_RenderManagerPresentState* presentStateOut) {
RenderManagerPresentState* presentState = new RenderManagerPresentState();
(*presentStateOut) =
reinterpret_cast<OSVR_RenderManagerPresentState*>(presentState);
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrRenderManagerFinishPresentRenderBuffers(
OSVR_RenderManager renderManager,
OSVR_RenderManagerPresentState presentState, OSVR_RenderParams renderParams,
OSVR_CBool shouldFlipY) {
auto state = reinterpret_cast<RenderManagerPresentState*>(presentState);
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
osvr::renderkit::RenderManager::RenderParams _renderParams;
ConvertRenderParams(renderParams, _renderParams);
if (!rm->PresentRenderBuffers(state->renderBuffers, state->renderInfoUsed,
_renderParams, state->normalizedCroppingViewports,
shouldFlipY == OSVR_TRUE)) {
return OSVR_RETURN_FAILURE;
}
// Delete any space allocated for the buffers in the ConvertRenderBuffers
// routines. They must have put nullptr in the fields they did not
// allocate to avoid a crash here.
for (size_t i = 0; i < state->renderBuffers.size(); i++) {
#ifdef _WIN32
delete state->renderBuffers[i].D3D11;
#endif
delete state->renderBuffers[i].OpenGL;
}
delete state;
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrRenderManagerStartRegisterRenderBuffers(
OSVR_RenderManagerRegisterBufferState* registerBufferStateOut) {
RenderManagerRegisterBufferState* ret =
new RenderManagerRegisterBufferState();
*registerBufferStateOut =
reinterpret_cast<OSVR_RenderManagerRegisterBufferState>(ret);
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrRenderManagerFinishRegisterRenderBuffers(
OSVR_RenderManager renderManager,
OSVR_RenderManagerRegisterBufferState registerBufferState,
OSVR_CBool appWillNotOverwriteBeforeNewPresent) {
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
auto state = reinterpret_cast<RenderManagerRegisterBufferState*>(
registerBufferState);
bool success = rm->RegisterRenderBuffers(
state->renderBuffers, appWillNotOverwriteBeforeNewPresent == OSVR_TRUE);
delete state;
return success ? OSVR_RETURN_SUCCESS : OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode osvrRenderManagerPresentSolidColorf(
OSVR_RenderManager renderManager,
OSVR_RGB_FLOAT rgb) {
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
osvr::renderkit::RGBColorf color;
color.r = rgb.r;
color.g = rgb.g;
color.b = rgb.b;
bool success = rm->PresentSolidColor(color);
return success ? OSVR_RETURN_SUCCESS : OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode osvrRenderManagerGetRenderInfoCollection(
OSVR_RenderManager renderManager,
OSVR_RenderParams renderParams,
OSVR_RenderInfoCollection* renderInfoCollectionOut) {
if (renderManager && renderInfoCollectionOut) {
osvr::renderkit::RenderManager::RenderParams _renderParams;
ConvertRenderParams(renderParams, _renderParams);
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
RenderManagerRenderInfoCollection* ret = new RenderManagerRenderInfoCollection();
ret->renderInfo = rm->GetRenderInfo(_renderParams);
(*renderInfoCollectionOut) =
reinterpret_cast<OSVR_RenderInfoCollection*>(ret);
return OSVR_RETURN_SUCCESS;
}
return OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode osvrRenderManagerReleaseRenderInfoCollection(
OSVR_RenderInfoCollection renderInfoCollection) {
if (renderInfoCollection) {
auto ri = reinterpret_cast<RenderManagerRenderInfoCollection*>(renderInfoCollection);
delete ri;
return OSVR_RETURN_SUCCESS;
}
return OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode osvrRenderManagerGetNumRenderInfoInCollection(
OSVR_RenderInfoCollection renderInfoCollection,
OSVR_RenderInfoCount* countOut) {
if (renderInfoCollection && countOut) {
auto ri = reinterpret_cast<RenderManagerRenderInfoCollection*>(renderInfoCollection);
(*countOut) = ri->renderInfo.size();
return OSVR_RETURN_SUCCESS;
}
return OSVR_RETURN_FAILURE;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_PoseState_to_OpenGL(
double* OpenGL_out, OSVR_PoseState state_in)
{
if (!osvr::renderkit::OSVR_PoseState_to_OpenGL(
OpenGL_out, state_in)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_PoseState_to_D3D(
float D3D_out[16], OSVR_PoseState state_in)
{
if (!osvr::renderkit::OSVR_PoseState_to_D3D(
D3D_out, state_in)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_PoseState_to_Unity(
OSVR_PoseState* state_out, OSVR_PoseState state_in)
{
if (!state_out) { return OSVR_RETURN_FAILURE; }
if (!osvr::renderkit::OSVR_PoseState_to_Unity(
*state_out, state_in)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_Projection_to_OpenGL(
double* OpenGL_out, OSVR_ProjectionMatrix projection_in)
{
osvr::renderkit::OSVR_ProjectionMatrix proj;
ConvertProjection(projection_in, proj);
if (!osvr::renderkit::OSVR_Projection_to_OpenGL(
OpenGL_out, proj)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_Projection_to_D3D(
float D3D_out[16], OSVR_ProjectionMatrix projection_in)
{
osvr::renderkit::OSVR_ProjectionMatrix proj;
ConvertProjection(projection_in, proj);
if (!osvr::renderkit::OSVR_Projection_to_D3D(
D3D_out, proj)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_Projection_to_Unreal(
float Unreal_out[16], OSVR_ProjectionMatrix projection_in)
{
osvr::renderkit::OSVR_ProjectionMatrix proj;
ConvertProjection(projection_in, proj);
if (!osvr::renderkit::OSVR_Projection_to_Unreal(
Unreal_out, proj)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
<commit_msg>Copying fields from default-constructed struct.<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/RenderKit/RenderManager.h>
#include <osvr/RenderKit/RenderManagerImpl.h>
#include <osvr/RenderKit/RenderKitGraphicsTransforms.h>
// We pull these in so we know the right types to delete for the
// RenderBuffers
#ifdef _WIN32
#include <d3d11.h>
#include <osvr/RenderKit/GraphicsLibraryD3D11.h>
#endif
#include <osvr/RenderKit/GraphicsLibraryOpenGL.h>
// Library/third-party includes
/* none */
// Standard includes
#include <iostream>
#include <vector>
OSVR_ReturnCode osvrDestroyRenderManager(OSVR_RenderManager renderManager) {
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
delete rm;
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode
osvrRenderManagerGetNumRenderInfo(OSVR_RenderManager renderManager,
OSVR_RenderParams renderParams,
OSVR_RenderInfoCount* numRenderInfoOut) {
osvr::renderkit::RenderManager::RenderParams _renderParams;
ConvertRenderParams(renderParams, _renderParams);
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
auto ri = rm->GetRenderInfo(_renderParams);
*numRenderInfoOut = ri.size();
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode
osvrRenderManagerGetDoingOkay(OSVR_RenderManager renderManager) {
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
return rm->doingOkay() ? OSVR_RETURN_SUCCESS : OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode
osvrRenderManagerGetDefaultRenderParams(OSVR_RenderParams* renderParamsOut) {
auto& _renderParamsOut = *renderParamsOut;
osvr::renderkit::RenderManager::RenderParams rp;
_renderParamsOut.nearClipDistanceMeters = rp.nearClipDistanceMeters;
_renderParamsOut.farClipDistanceMeters = rp.farClipDistanceMeters;
_renderParamsOut.IPDMeters = rp.IPDMeters;
_renderParamsOut.worldFromRoomAppend = nullptr;
_renderParamsOut.roomFromHeadReplace = nullptr;
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrRenderManagerStartPresentRenderBuffers(
OSVR_RenderManagerPresentState* presentStateOut) {
RenderManagerPresentState* presentState = new RenderManagerPresentState();
(*presentStateOut) =
reinterpret_cast<OSVR_RenderManagerPresentState*>(presentState);
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrRenderManagerFinishPresentRenderBuffers(
OSVR_RenderManager renderManager,
OSVR_RenderManagerPresentState presentState, OSVR_RenderParams renderParams,
OSVR_CBool shouldFlipY) {
auto state = reinterpret_cast<RenderManagerPresentState*>(presentState);
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
osvr::renderkit::RenderManager::RenderParams _renderParams;
ConvertRenderParams(renderParams, _renderParams);
if (!rm->PresentRenderBuffers(state->renderBuffers, state->renderInfoUsed,
_renderParams, state->normalizedCroppingViewports,
shouldFlipY == OSVR_TRUE)) {
return OSVR_RETURN_FAILURE;
}
// Delete any space allocated for the buffers in the ConvertRenderBuffers
// routines. They must have put nullptr in the fields they did not
// allocate to avoid a crash here.
for (size_t i = 0; i < state->renderBuffers.size(); i++) {
#ifdef _WIN32
delete state->renderBuffers[i].D3D11;
#endif
delete state->renderBuffers[i].OpenGL;
}
delete state;
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrRenderManagerStartRegisterRenderBuffers(
OSVR_RenderManagerRegisterBufferState* registerBufferStateOut) {
RenderManagerRegisterBufferState* ret =
new RenderManagerRegisterBufferState();
*registerBufferStateOut =
reinterpret_cast<OSVR_RenderManagerRegisterBufferState>(ret);
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrRenderManagerFinishRegisterRenderBuffers(
OSVR_RenderManager renderManager,
OSVR_RenderManagerRegisterBufferState registerBufferState,
OSVR_CBool appWillNotOverwriteBeforeNewPresent) {
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
auto state = reinterpret_cast<RenderManagerRegisterBufferState*>(
registerBufferState);
bool success = rm->RegisterRenderBuffers(
state->renderBuffers, appWillNotOverwriteBeforeNewPresent == OSVR_TRUE);
delete state;
return success ? OSVR_RETURN_SUCCESS : OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode osvrRenderManagerPresentSolidColorf(
OSVR_RenderManager renderManager,
OSVR_RGB_FLOAT rgb) {
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
osvr::renderkit::RGBColorf color;
color.r = rgb.r;
color.g = rgb.g;
color.b = rgb.b;
bool success = rm->PresentSolidColor(color);
return success ? OSVR_RETURN_SUCCESS : OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode osvrRenderManagerGetRenderInfoCollection(
OSVR_RenderManager renderManager,
OSVR_RenderParams renderParams,
OSVR_RenderInfoCollection* renderInfoCollectionOut) {
if (renderManager && renderInfoCollectionOut) {
osvr::renderkit::RenderManager::RenderParams _renderParams;
ConvertRenderParams(renderParams, _renderParams);
auto rm = reinterpret_cast<osvr::renderkit::RenderManager*>(renderManager);
RenderManagerRenderInfoCollection* ret = new RenderManagerRenderInfoCollection();
ret->renderInfo = rm->GetRenderInfo(_renderParams);
(*renderInfoCollectionOut) =
reinterpret_cast<OSVR_RenderInfoCollection*>(ret);
return OSVR_RETURN_SUCCESS;
}
return OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode osvrRenderManagerReleaseRenderInfoCollection(
OSVR_RenderInfoCollection renderInfoCollection) {
if (renderInfoCollection) {
auto ri = reinterpret_cast<RenderManagerRenderInfoCollection*>(renderInfoCollection);
delete ri;
return OSVR_RETURN_SUCCESS;
}
return OSVR_RETURN_FAILURE;
}
OSVR_ReturnCode osvrRenderManagerGetNumRenderInfoInCollection(
OSVR_RenderInfoCollection renderInfoCollection,
OSVR_RenderInfoCount* countOut) {
if (renderInfoCollection && countOut) {
auto ri = reinterpret_cast<RenderManagerRenderInfoCollection*>(renderInfoCollection);
(*countOut) = ri->renderInfo.size();
return OSVR_RETURN_SUCCESS;
}
return OSVR_RETURN_FAILURE;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_PoseState_to_OpenGL(
double* OpenGL_out, OSVR_PoseState state_in)
{
if (!osvr::renderkit::OSVR_PoseState_to_OpenGL(
OpenGL_out, state_in)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_PoseState_to_D3D(
float D3D_out[16], OSVR_PoseState state_in)
{
if (!osvr::renderkit::OSVR_PoseState_to_D3D(
D3D_out, state_in)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_PoseState_to_Unity(
OSVR_PoseState* state_out, OSVR_PoseState state_in)
{
if (!state_out) { return OSVR_RETURN_FAILURE; }
if (!osvr::renderkit::OSVR_PoseState_to_Unity(
*state_out, state_in)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_Projection_to_OpenGL(
double* OpenGL_out, OSVR_ProjectionMatrix projection_in)
{
osvr::renderkit::OSVR_ProjectionMatrix proj;
ConvertProjection(projection_in, proj);
if (!osvr::renderkit::OSVR_Projection_to_OpenGL(
OpenGL_out, proj)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_Projection_to_D3D(
float D3D_out[16], OSVR_ProjectionMatrix projection_in)
{
osvr::renderkit::OSVR_ProjectionMatrix proj;
ConvertProjection(projection_in, proj);
if (!osvr::renderkit::OSVR_Projection_to_D3D(
D3D_out, proj)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
OSVR_RENDERMANAGER_EXPORT OSVR_ReturnCode OSVR_Projection_to_Unreal(
float Unreal_out[16], OSVR_ProjectionMatrix projection_in)
{
osvr::renderkit::OSVR_ProjectionMatrix proj;
ConvertProjection(projection_in, proj);
if (!osvr::renderkit::OSVR_Projection_to_Unreal(
Unreal_out, proj)) {
return OSVR_RETURN_FAILURE;
}
return OSVR_RETURN_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2018, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the copyright holders nor the names of their 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 "sdl_rpc_plugin/sdl_rpc_plugin.h"
#include "application_manager/message_helper.h"
#include "application_manager/plugin_manager/plugin_keys.h"
#include "sdl_rpc_plugin/extensions/system_capability_app_extension.h"
#include "sdl_rpc_plugin/sdl_command_factory.h"
#include "sdl_rpc_plugin/waypoints_app_extension.h"
#include "sdl_rpc_plugin/waypoints_pending_resumption_handler.h"
namespace sdl_rpc_plugin {
namespace app_mngr = application_manager;
namespace plugins = application_manager::plugin_manager;
SDL_CREATE_LOG_VARIABLE("SdlRPCPlugin")
SDLRPCPlugin::SDLRPCPlugin()
: application_manager_(nullptr), pending_resumption_handler_(nullptr) {}
bool SDLRPCPlugin::Init(app_mngr::ApplicationManager& app_manager,
app_mngr::rpc_service::RPCService& rpc_service,
app_mngr::HMICapabilities& hmi_capabilities,
policy::PolicyHandlerInterface& policy_handler,
resumption::LastStateWrapperPtr last_state) {
UNUSED(last_state);
application_manager_ = &app_manager;
pending_resumption_handler_ =
std::make_shared<WayPointsPendingResumptionHandler>(app_manager);
command_factory_.reset(new sdl_rpc_plugin::SDLCommandFactory(
app_manager, rpc_service, hmi_capabilities, policy_handler));
return true;
}
bool SDLRPCPlugin::Init(
application_manager::ApplicationManager& app_manager,
application_manager::rpc_service::RPCService& rpc_service,
application_manager::HMICapabilities& hmi_capabilities,
policy::PolicyHandlerInterface& policy_handler,
resumption::LastState& last_state) {
UNUSED(last_state);
command_factory_.reset(new sdl_rpc_plugin::SDLCommandFactory(
app_manager, rpc_service, hmi_capabilities, policy_handler));
return true;
}
bool SDLRPCPlugin::IsAbleToProcess(
const int32_t function_id,
const app_mngr::commands::Command::CommandSource message_source) {
return command_factory_->IsAbleToProcess(function_id, message_source);
}
std::string SDLRPCPlugin::PluginName() {
return plugins::plugin_names::sdl_rpc_plugin;
}
app_mngr::CommandFactory& SDLRPCPlugin::GetCommandFactory() {
return *command_factory_;
}
void SDLRPCPlugin::OnPolicyEvent(plugins::PolicyEvent event) {}
void SDLRPCPlugin::OnApplicationEvent(
plugins::ApplicationEvent event,
app_mngr::ApplicationSharedPtr application) {
SDL_LOG_AUTO_TRACE();
if (plugins::ApplicationEvent::kApplicationRegistered == event) {
application->AddExtension(
std::make_shared<WayPointsAppExtension>(*this, *application));
auto sys_cap_ext_ptr =
std::make_shared<SystemCapabilityAppExtension>(*this, *application);
application->AddExtension(sys_cap_ext_ptr);
// Processing automatic subscription to SystemCapabilities for DISPLAY type
const auto capability_type =
mobile_apis::SystemCapabilityType::eType::DISPLAYS;
SDL_LOG_DEBUG("Subscription to DISPLAYS capability is enabled");
sys_cap_ext_ptr->SubscribeTo(capability_type);
} else if (plugins::ApplicationEvent::kDeleteApplicationData == event) {
ClearSubscriptions(application);
}
}
void SDLRPCPlugin::ProcessResumptionSubscription(
application_manager::Application& app, WayPointsAppExtension& ext) {
SDL_LOG_AUTO_TRACE();
pending_resumption_handler_->HandleResumptionSubscriptionRequest(ext, app);
}
void SDLRPCPlugin::SaveResumptionData(
application_manager::Application& app,
smart_objects::SmartObject& resumption_data) {
resumption_data[application_manager::strings::subscribed_for_way_points] =
application_manager_->IsAppSubscribedForWayPoints(app);
}
void SDLRPCPlugin::RevertResumption(application_manager::Application& app) {
SDL_LOG_AUTO_TRACE();
pending_resumption_handler_->OnResumptionRevert();
if (application_manager_->IsAppSubscribedForWayPoints(app)) {
application_manager_->UnsubscribeAppFromWayPoints(app.app_id());
if (!application_manager_->IsAnyAppSubscribedForWayPoints()) {
SDL_LOG_DEBUG("Send UnsubscribeWayPoints");
auto request =
application_manager::MessageHelper::CreateUnsubscribeWayPointsRequest(
application_manager_->GetNextHMICorrelationID());
application_manager_->GetRPCService().ManageHMICommand(request);
}
}
}
void SDLRPCPlugin::ClearSubscriptions(app_mngr::ApplicationSharedPtr app) {
auto& ext = SystemCapabilityAppExtension::ExtractExtension(*app);
ext.UnsubscribeFromAll();
}
} // namespace sdl_rpc_plugin
extern "C" __attribute__((visibility("default")))
application_manager::plugin_manager::RPCPlugin*
Create(logger::Logger* logger_instance) {
logger::Logger::instance(logger_instance);
return new sdl_rpc_plugin::SDLRPCPlugin();
}
extern "C" __attribute__((visibility("default"))) void Delete(
application_manager::plugin_manager::RPCPlugin* data) {
delete data;
}
<commit_msg>Check waypoint subscription size in resumption (#3684)<commit_after>/*
Copyright (c) 2018, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the copyright holders nor the names of their 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 "sdl_rpc_plugin/sdl_rpc_plugin.h"
#include "application_manager/message_helper.h"
#include "application_manager/plugin_manager/plugin_keys.h"
#include "sdl_rpc_plugin/extensions/system_capability_app_extension.h"
#include "sdl_rpc_plugin/sdl_command_factory.h"
#include "sdl_rpc_plugin/waypoints_app_extension.h"
#include "sdl_rpc_plugin/waypoints_pending_resumption_handler.h"
namespace sdl_rpc_plugin {
namespace app_mngr = application_manager;
namespace plugins = application_manager::plugin_manager;
SDL_CREATE_LOG_VARIABLE("SdlRPCPlugin")
SDLRPCPlugin::SDLRPCPlugin()
: application_manager_(nullptr), pending_resumption_handler_(nullptr) {}
bool SDLRPCPlugin::Init(app_mngr::ApplicationManager& app_manager,
app_mngr::rpc_service::RPCService& rpc_service,
app_mngr::HMICapabilities& hmi_capabilities,
policy::PolicyHandlerInterface& policy_handler,
resumption::LastStateWrapperPtr last_state) {
UNUSED(last_state);
application_manager_ = &app_manager;
pending_resumption_handler_ =
std::make_shared<WayPointsPendingResumptionHandler>(app_manager);
command_factory_.reset(new sdl_rpc_plugin::SDLCommandFactory(
app_manager, rpc_service, hmi_capabilities, policy_handler));
return true;
}
bool SDLRPCPlugin::Init(
application_manager::ApplicationManager& app_manager,
application_manager::rpc_service::RPCService& rpc_service,
application_manager::HMICapabilities& hmi_capabilities,
policy::PolicyHandlerInterface& policy_handler,
resumption::LastState& last_state) {
UNUSED(last_state);
command_factory_.reset(new sdl_rpc_plugin::SDLCommandFactory(
app_manager, rpc_service, hmi_capabilities, policy_handler));
return true;
}
bool SDLRPCPlugin::IsAbleToProcess(
const int32_t function_id,
const app_mngr::commands::Command::CommandSource message_source) {
return command_factory_->IsAbleToProcess(function_id, message_source);
}
std::string SDLRPCPlugin::PluginName() {
return plugins::plugin_names::sdl_rpc_plugin;
}
app_mngr::CommandFactory& SDLRPCPlugin::GetCommandFactory() {
return *command_factory_;
}
void SDLRPCPlugin::OnPolicyEvent(plugins::PolicyEvent event) {}
void SDLRPCPlugin::OnApplicationEvent(
plugins::ApplicationEvent event,
app_mngr::ApplicationSharedPtr application) {
SDL_LOG_AUTO_TRACE();
if (plugins::ApplicationEvent::kApplicationRegistered == event) {
application->AddExtension(
std::make_shared<WayPointsAppExtension>(*this, *application));
auto sys_cap_ext_ptr =
std::make_shared<SystemCapabilityAppExtension>(*this, *application);
application->AddExtension(sys_cap_ext_ptr);
// Processing automatic subscription to SystemCapabilities for DISPLAY type
const auto capability_type =
mobile_apis::SystemCapabilityType::eType::DISPLAYS;
SDL_LOG_DEBUG("Subscription to DISPLAYS capability is enabled");
sys_cap_ext_ptr->SubscribeTo(capability_type);
} else if (plugins::ApplicationEvent::kDeleteApplicationData == event) {
ClearSubscriptions(application);
}
}
void SDLRPCPlugin::ProcessResumptionSubscription(
application_manager::Application& app, WayPointsAppExtension& ext) {
SDL_LOG_AUTO_TRACE();
pending_resumption_handler_->HandleResumptionSubscriptionRequest(ext, app);
}
void SDLRPCPlugin::SaveResumptionData(
application_manager::Application& app,
smart_objects::SmartObject& resumption_data) {
resumption_data[application_manager::strings::subscribed_for_way_points] =
application_manager_->IsAppSubscribedForWayPoints(app);
}
void SDLRPCPlugin::RevertResumption(application_manager::Application& app) {
SDL_LOG_AUTO_TRACE();
pending_resumption_handler_->OnResumptionRevert();
if (application_manager_->IsAppSubscribedForWayPoints(app)) {
const auto subscribed_apps =
application_manager_->GetAppsSubscribedForWayPoints();
const bool send_unsubscribe =
subscribed_apps.size() <= 1 &&
application_manager_->IsSubscribedToHMIWayPoints();
if (send_unsubscribe) {
SDL_LOG_DEBUG("Send UnsubscribeWayPoints");
auto request =
application_manager::MessageHelper::CreateUnsubscribeWayPointsRequest(
application_manager_->GetNextHMICorrelationID());
application_manager_->GetRPCService().ManageHMICommand(request);
}
application_manager_->UnsubscribeAppFromWayPoints(app.app_id(),
send_unsubscribe);
}
}
void SDLRPCPlugin::ClearSubscriptions(app_mngr::ApplicationSharedPtr app) {
auto& ext = SystemCapabilityAppExtension::ExtractExtension(*app);
ext.UnsubscribeFromAll();
}
} // namespace sdl_rpc_plugin
extern "C" __attribute__((visibility("default")))
application_manager::plugin_manager::RPCPlugin*
Create(logger::Logger* logger_instance) {
logger::Logger::instance(logger_instance);
return new sdl_rpc_plugin::SDLRPCPlugin();
}
extern "C" __attribute__((visibility("default"))) void Delete(
application_manager::plugin_manager::RPCPlugin* data) {
delete data;
}
<|endoftext|> |
<commit_before>
// Projectname: amos-ss16-proj5
//
// Created on 03.06.2016.
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// 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 <math.h>
#include "scenario.h"
float Scenario::Distance(Element first, Element second){
//compute distance with pythagorean theorem
std::vector<int> first_position = first.GetPosition();
std::vector<int> second_position = second.GetPosition();
float first_sum = pow( (static_cast<float>(second_position.at(0)) - static_cast<float>(first_position.at(0))), 2.0);
float second_sum = pow( (static_cast<float>(second_position.at(1)) - static_cast<float>(first_position.at(1))), 2.0);
float distance = sqrt(first_sum + second_sum);
return distance;
}
bool Scenario::Overlap(Element first, Element second){
//determine whether the bounding box of the first element overlaps with the second one
int first_min_x = first.GetPosition().at(0);
int first_min_y = first.GetPosition().at(1);
int first_max_x = first_min_x + first.GetBoxSize().at(0);
int first_max_y = first_min_y + first.GetBoxSize().at(1);
// TODO
}
<commit_msg>Finished the overlap function<commit_after>
// Projectname: amos-ss16-proj5
//
// Created on 03.06.2016.
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// 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 <math.h>
#include "scenario.h"
float Scenario::Distance(Element first, Element second){
//compute distance with pythagorean theorem
std::vector<int> first_position = first.GetPosition();
std::vector<int> second_position = second.GetPosition();
float first_sum = pow( (static_cast<float>(second_position.at(0)) - static_cast<float>(first_position.at(0))), 2.0);
float second_sum = pow( (static_cast<float>(second_position.at(1)) - static_cast<float>(first_position.at(1))), 2.0);
float distance = sqrt(first_sum + second_sum);
return distance;
}
bool Scenario::Overlap(Element first, Element second){
//determine whether the bounding box of the first element overlaps with the second one
int first_min_x = first.GetPosition().at(0);
int first_min_y = first.GetPosition().at(1);
int first_max_x = first_min_x + first.GetBoxSize().at(0);
int first_max_y = first_min_y + first.GetBoxSize().at(1);
int second_min_x = second.GetPosition().at(0);
int second_min_y = second.GetPosition().at(1);
int second_max_x = second_min_x + second.GetBoxSize().at(0);
int second_max_y = second_min_y + second.GetBoxSize().at(1);
if( (first_min_x <= second_min_x) || (first_max_x >= second_max_x) ){
if( ( (second_min_y >= first_min_y) && (second_min_y <= first_max_y) )
|| ( (second_max_y <= first_max_y) && (second_max_y >= first_min_y) ) ){
return true;
}
return false;
}
return false;
}
<|endoftext|> |
<commit_before>#include "aerial_autonomy/controller_hardware_connectors/rpyt_relative_pose_visual_servoing_connector.h"
#include "aerial_autonomy/log/log.h"
bool RPYTRelativePoseVisualServoingConnector::extractSensorData(
std::tuple<tf::Transform, tf::Transform, VelocityYawRate> &sensor_data) {
parsernode::common::quaddata quad_data;
drone_hardware_.getquaddata(quad_data);
tf::Transform tracking_pose;
if (!getTrackingTransformRotationCompensatedQuadFrame(tracking_pose)) {
VLOG(1) << "Invalid tracking vector";
return false;
}
// Estimator
tracking_vector_estimator_.estimate(
tracking_pose.getOrigin(),
tf::Vector3(quad_data.linvel.x, quad_data.linvel.y, quad_data.linvel.z));
///\todo Check estimator health
tf::Vector3 estimated_marker_direction =
tracking_vector_estimator_.getMarkerDirection();
tf::Vector3 estimated_velocity = tracking_vector_estimator_.getVelocity();
VelocityYawRate estimated_velocity_yawrate(
estimated_velocity.x(), estimated_velocity.y(), estimated_velocity.z(),
quad_data.omega.z);
auto tracking_origin = tracking_pose.getOrigin();
double tracking_r, tracking_p, tracking_y;
tracking_pose.getBasis().getRPY(tracking_r, tracking_p, tracking_y);
DATA_LOG("rpyt_relative_pose_visual_servoing_connector")
<< quad_data.linvel.x << quad_data.linvel.y << quad_data.linvel.z
<< quad_data.rpydata.x << quad_data.rpydata.y << quad_data.rpydata.z
<< quad_data.omega.x << quad_data.omega.y << quad_data.omega.z
<< tracking_origin.x() << tracking_origin.y() << tracking_origin.z()
<< tracking_r << tracking_p << tracking_y << DataStream::endl;
// Update tracking pose to use estimated marker direction instead
// of measured direction
tf::Transform estimated_pose(tracking_pose.getRotation(),
estimated_marker_direction);
// giving transform in rotation-compensated quad frame
sensor_data = std::make_tuple(getBodyFrameRotation(), estimated_pose,
estimated_velocity_yawrate);
thrust_gain_estimator_.addSensorData(quad_data.rpydata.x, quad_data.rpydata.y,
quad_data.linacc.z);
auto rpyt_controller_config = private_reference_controller_.getRPYTConfig();
rpyt_controller_config.set_kt(thrust_gain_estimator_.getThrustGain());
private_reference_controller_.updateRPYTConfig(rpyt_controller_config);
return true;
}
void RPYTRelativePoseVisualServoingConnector::sendHardwareCommands(
RollPitchYawRateThrust controls) {
geometry_msgs::Quaternion rpyt_msg;
rpyt_msg.x = controls.r;
rpyt_msg.y = controls.p;
rpyt_msg.z = controls.y;
rpyt_msg.w = controls.t;
thrust_gain_estimator_.addThrustCommand(controls.t);
drone_hardware_.cmdrpyawratethrust(rpyt_msg);
}
void RPYTRelativePoseVisualServoingConnector::setGoal(PositionYaw goal) {
BaseClass::setGoal(goal);
VLOG(1) << "Clearing thrust estimator buffer";
thrust_gain_estimator_.clearBuffer();
VLOG(1) << "Clearing initial state from kalman filter";
tracking_vector_estimator_.resetState();
}
<commit_msg>Add todo for when tracker produces repeated messages<commit_after>#include "aerial_autonomy/controller_hardware_connectors/rpyt_relative_pose_visual_servoing_connector.h"
#include "aerial_autonomy/log/log.h"
bool RPYTRelativePoseVisualServoingConnector::extractSensorData(
std::tuple<tf::Transform, tf::Transform, VelocityYawRate> &sensor_data) {
parsernode::common::quaddata quad_data;
drone_hardware_.getquaddata(quad_data);
tf::Transform tracking_pose;
///\todo Figure out what to do when the tracking pose is repeated
if (!getTrackingTransformRotationCompensatedQuadFrame(tracking_pose)) {
VLOG(1) << "Invalid tracking vector";
return false;
}
// Estimator
tracking_vector_estimator_.estimate(
tracking_pose.getOrigin(),
tf::Vector3(quad_data.linvel.x, quad_data.linvel.y, quad_data.linvel.z));
///\todo Check estimator health
tf::Vector3 estimated_marker_direction =
tracking_vector_estimator_.getMarkerDirection();
tf::Vector3 estimated_velocity = tracking_vector_estimator_.getVelocity();
VelocityYawRate estimated_velocity_yawrate(
estimated_velocity.x(), estimated_velocity.y(), estimated_velocity.z(),
quad_data.omega.z);
auto tracking_origin = tracking_pose.getOrigin();
double tracking_r, tracking_p, tracking_y;
tracking_pose.getBasis().getRPY(tracking_r, tracking_p, tracking_y);
DATA_LOG("rpyt_relative_pose_visual_servoing_connector")
<< quad_data.linvel.x << quad_data.linvel.y << quad_data.linvel.z
<< quad_data.rpydata.x << quad_data.rpydata.y << quad_data.rpydata.z
<< quad_data.omega.x << quad_data.omega.y << quad_data.omega.z
<< tracking_origin.x() << tracking_origin.y() << tracking_origin.z()
<< tracking_r << tracking_p << tracking_y << DataStream::endl;
// Update tracking pose to use estimated marker direction instead
// of measured direction
tf::Transform estimated_pose(tracking_pose.getRotation(),
estimated_marker_direction);
// giving transform in rotation-compensated quad frame
sensor_data = std::make_tuple(getBodyFrameRotation(), estimated_pose,
estimated_velocity_yawrate);
thrust_gain_estimator_.addSensorData(quad_data.rpydata.x, quad_data.rpydata.y,
quad_data.linacc.z);
auto rpyt_controller_config = private_reference_controller_.getRPYTConfig();
rpyt_controller_config.set_kt(thrust_gain_estimator_.getThrustGain());
private_reference_controller_.updateRPYTConfig(rpyt_controller_config);
return true;
}
void RPYTRelativePoseVisualServoingConnector::sendHardwareCommands(
RollPitchYawRateThrust controls) {
geometry_msgs::Quaternion rpyt_msg;
rpyt_msg.x = controls.r;
rpyt_msg.y = controls.p;
rpyt_msg.z = controls.y;
rpyt_msg.w = controls.t;
thrust_gain_estimator_.addThrustCommand(controls.t);
drone_hardware_.cmdrpyawratethrust(rpyt_msg);
}
void RPYTRelativePoseVisualServoingConnector::setGoal(PositionYaw goal) {
BaseClass::setGoal(goal);
VLOG(1) << "Clearing thrust estimator buffer";
thrust_gain_estimator_.clearBuffer();
VLOG(1) << "Clearing initial state from kalman filter";
tracking_vector_estimator_.resetState();
}
<|endoftext|> |
<commit_before>/*
* alarmcalendar.cpp - KAlarm calendar file access
* Program: kalarm
* (C) 2001, 2002 by David Jarvie software@astrojar.org.uk
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "kalarm.h"
#include <unistd.h>
#include <time.h>
#include <qfile.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kconfig.h>
#include <kaboutdata.h>
#include <kio/netaccess.h>
#include <kfileitem.h>
#include <ktempfile.h>
#include <dcopclient.h>
#include <kdebug.h>
extern "C" {
#include <ical.h>
}
#include <libkcal/vcaldrag.h>
#include <libkcal/vcalformat.h>
#include <libkcal/icalformat.h>
#include "kalarmapp.h"
#include "alarmcalendar.h"
const QString DEFAULT_CALENDAR_FILE(QString::fromLatin1("calendar.ics"));
/******************************************************************************
* Read the calendar file URL from the config file (or use the default).
* If there is an error, the program exits.
*/
void AlarmCalendar::getURL() const
{
if (!mUrl.isValid())
{
KConfig* config = kapp->config();
config->setGroup(QString::fromLatin1("General"));
*const_cast<KURL*>(&mUrl) = config->readEntry(QString::fromLatin1("Calendar"),
locateLocal("appdata", DEFAULT_CALENDAR_FILE));
if (!mUrl.isValid())
{
kdDebug(5950) << "AlarmCalendar::getURL(): invalid name: " << mUrl.prettyURL() << endl;
KMessageBox::error(0L, i18n("Invalid calendar file name: %1").arg(mUrl.prettyURL()),
kapp->aboutData()->programName());
kapp->exit(1);
}
}
}
/******************************************************************************
* Open the calendar file and load it into memory.
*/
bool AlarmCalendar::open()
{
getURL();
mCalendar = new CalendarLocal();
mCalendar->setLocalTime(); // write out using local time (i.e. no time zone)
// Find out whether the calendar is ICal or VCal format
QString ext = mUrl.filename().right(4);
mVCal = (ext == QString::fromLatin1(".vcs"));
if (!KIO::NetAccess::exists(mUrl))
{
if (!create()) // create the calendar file
return false;
}
// Load the calendar file
switch (load())
{
case 1:
break;
case 0:
if (!create() || load() <= 0)
return false;
case -1:
/* if (!KIO::NetAccess::exists(mUrl))
{
if (!create() || load() <= 0)
return false;
}*/
return false;
}
return true;
}
/******************************************************************************
* Create a new calendar file.
*/
bool AlarmCalendar::create()
{
// Create the calendar file
KTempFile* tmpFile = 0L;
QString filename;
if (mUrl.isLocalFile())
filename = mUrl.path();
else
{
tmpFile = new KTempFile;
filename = tmpFile->name();
}
if (!save(filename))
{
delete tmpFile;
return false;
}
delete tmpFile;
return true;
}
/******************************************************************************
* Load the calendar file into memory.
* Reply = 1 if success, -2 if failure, 0 if zero-length file exists.
*/
int AlarmCalendar::load()
{
getURL();
kdDebug(5950) << "AlarmCalendar::load(): " << mUrl.prettyURL() << endl;
QString tmpFile;
if (!KIO::NetAccess::download(mUrl, tmpFile))
{
kdError(5950) << "AlarmCalendar::load(): Load failure" << endl;
KMessageBox::error(0L, i18n("Cannot open calendar:\n%1").arg(mUrl.prettyURL()), kapp->aboutData()->programName());
return -1;
}
kdDebug(5950) << "AlarmCalendar::load(): --- Downloaded to " << tmpFile << endl;
mKAlarmVersion = -1;
mKAlarmVersion057_UTC = false;
mCalendar->setTimeZoneId(QString::null); // default to the local time zone for reading
bool loaded = mCalendar->load(tmpFile);
mCalendar->setLocalTime(); // write using local time (i.e. no time zone)
if (!loaded)
{
// Check if the file is zero length
KIO::NetAccess::removeTempFile(tmpFile);
KIO::UDSEntry uds;
KIO::NetAccess::stat(mUrl, uds);
KFileItem fi(uds, mUrl);
if (!fi.size())
return 0; // file is zero length
kdDebug(5950) << "AlarmCalendar::load(): Error loading calendar file '" << tmpFile << "'" << endl;
KMessageBox::error(0L, i18n("Error loading calendar:\n%1\n\nPlease fix or delete the file.").arg(mUrl.prettyURL()),
kapp->aboutData()->programName());
return -1;
}
if (!mLocalFile.isEmpty())
KIO::NetAccess::removeTempFile(mLocalFile);
mLocalFile = tmpFile;
// Find the version of KAlarm which wrote the calendar file, and do
// any necessary conversions to the current format
getKAlarmVersion();
if (mKAlarmVersion == KAlarmVersion(0,5,7))
{
// KAlarm version 0.5.7 - check whether times are stored in UTC, in which
// case it is the KDE 3.0.0 version which needs adjustment of summer times.
mKAlarmVersion057_UTC = isUTC();
kdDebug(5950) << "AlarmCalendar::load(): version 0.5.7 (" << (mKAlarmVersion057_UTC ? "" : "non-") << "UTC)\n";
}
else
kdDebug(5950) << "AlarmCalendar::load(): version " << mKAlarmVersion << endl;
KAlarmEvent::convertKCalEvents(); // convert events to current KAlarm format for when calendar is saved
return 1;
}
/******************************************************************************
* Reload the calendar file into memory.
* Reply = 1 if success, -2 if failure, 0 if zero-length file exists.
*/
int AlarmCalendar::reload()
{
if (!mCalendar)
return -2;
kdDebug(5950) << "AlarmCalendar::reload(): " << mUrl.prettyURL() << endl;
close();
return load();
}
/******************************************************************************
* Save the calendar from memory to file.
*/
bool AlarmCalendar::save(const QString& filename)
{
kdDebug(5950) << "AlarmCalendar::save(): " << filename << endl;
CalFormat* format;
if(mVCal)
format = new VCalFormat;
else
format = new ICalFormat;
bool success = mCalendar->save(filename, format);
if (!success)
{
kdDebug(5950) << "AlarmCalendar::save(): calendar save failed." << endl;
return false;
}
getURL();
if (!mUrl.isLocalFile())
{
if (!KIO::NetAccess::upload(filename, mUrl))
{
KMessageBox::error(0L, i18n("Cannot upload calendar to\n'%1'").arg(mUrl.prettyURL()), kapp->aboutData()->programName());
return false;
}
}
// Tell the alarm daemon to reload the calendar
QByteArray data;
QDataStream arg(data, IO_WriteOnly);
arg << QCString(kapp->aboutData()->appName()) << mUrl.url();
if (!kapp->dcopClient()->send(DAEMON_APP_NAME, DAEMON_DCOP_OBJECT, "reloadMsgCal(QCString,QString)", data))
kdDebug(5950) << "AlarmCalendar::save(): addCal dcop send failed" << endl;
return true;
}
/******************************************************************************
* Delete any temporary file at program exit.
*/
void AlarmCalendar::close()
{
if (!mLocalFile.isEmpty())
KIO::NetAccess::removeTempFile(mLocalFile);
if (mCalendar)
mCalendar->close();
}
/******************************************************************************
* Add the specified event to the calendar.
*/
void AlarmCalendar::addEvent(const KAlarmEvent& event)
{
Event* kcalEvent = new Event;
event.updateEvent(*kcalEvent);
mCalendar->addEvent(kcalEvent);
const_cast<KAlarmEvent&>(event).setEventID(kcalEvent->uid());
}
/******************************************************************************
* Update the specified event in the calendar with its new contents.
* The event retains the same ID.
*/
void AlarmCalendar::updateEvent(const KAlarmEvent& evnt)
{
Event* kcalEvent = event(evnt.id());
if (kcalEvent)
evnt.updateEvent(*kcalEvent);
}
/******************************************************************************
* Delete the specified event from the calendar.
*/
void AlarmCalendar::deleteEvent(const QString& eventID)
{
Event* kcalEvent = event(eventID);
if (kcalEvent)
mCalendar->deleteEvent(kcalEvent);
}
/******************************************************************************
* Return the KAlarm version which wrote the calendar which has been loaded.
* The format is, for example, 000507 for 0.5.7, or 0 if unknown.
*/
void AlarmCalendar::getKAlarmVersion() const
{
// N.B. Remember to change KAlarmVersion(int major, int minor, int rev)
// if the representation returned by this method changes.
mKAlarmVersion = 0; // set default to KAlarm pre-0.3.5, or another program
if (mCalendar)
{
const QString& prodid = mCalendar->loadedProductId();
int i = prodid.find(theApp()->aboutData()->programName(), 0, false);
if (i >= 0)
{
QString ver = prodid.mid(i + theApp()->aboutData()->programName().length()).stripWhiteSpace();
i = ver.find('/');
int j = ver.find(' ');
if (j >= 0 && j < i)
i = j;
if (i > 0)
{
ver = ver.left(i);
// ver now contains the KAlarm version string
if ((i = ver.find('.')) > 0)
{
bool ok;
int version = ver.left(i).toInt(&ok) * 10000; // major version
if (ok)
{
ver = ver.mid(i + 1);
if ((i = ver.find('.')) > 0)
{
int v = ver.left(i).toInt(&ok); // minor version
if (ok)
{
version += (v < 9 ? v : 9) * 100;
ver = ver.mid(i + 1);
if (ver.at(0).isDigit())
{
// Allow other characters to follow last digit
v = ver.toInt(); // issue number
mKAlarmVersion = version + (v < 9 ? v : 9);
}
}
}
else
{
// There is no issue number
if (ver.at(0).isDigit())
{
// Allow other characters to follow last digit
int v = ver.toInt(); // minor number
mKAlarmVersion = version + (v < 9 ? v : 9) * 100;
}
}
}
}
}
}
}
}
/******************************************************************************
* Check whether the calendar file has its times stored as UTC times,
* indicating that it was written by the KDE 3.0.0 version of KAlarm 0.5.7.
* Reply = true if times are stored in UTC
* = false if the calendar is a vCalendar, times are not UTC, or any error occurred.
*/
bool AlarmCalendar::isUTC() const
{
// Read the calendar file into a QString
QFile file(mLocalFile);
if (!file.open(IO_ReadOnly))
return false;
QTextStream ts(&file);
ts.setEncoding(QTextStream::UnicodeUTF8);
QString text = ts.read();
file.close();
// Extract the CREATED property for the first VEVENT from the calendar
bool result = false;
icalcomponent* calendar = icalcomponent_new_from_string(text.local8Bit().data());
if (calendar)
{
if (icalcomponent_isa(calendar) == ICAL_VCALENDAR_COMPONENT)
{
icalcomponent* c = icalcomponent_get_first_component(calendar, ICAL_VEVENT_COMPONENT);
if (c)
{
icalproperty* p = icalcomponent_get_first_property(c, ICAL_CREATED_PROPERTY);
if (p)
{
struct icaltimetype datetime = icalproperty_get_created(p);
if (datetime.is_utc)
result = true;
}
}
}
icalcomponent_free(calendar);
}
return result;
}
<commit_msg>Identify KAlarm calendar with more certainty<commit_after>/*
* alarmcalendar.cpp - KAlarm calendar file access
* Program: kalarm
* (C) 2001, 2002 by David Jarvie software@astrojar.org.uk
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "kalarm.h"
#include <unistd.h>
#include <time.h>
#include <qfile.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kconfig.h>
#include <kaboutdata.h>
#include <kio/netaccess.h>
#include <kfileitem.h>
#include <ktempfile.h>
#include <dcopclient.h>
#include <kdebug.h>
extern "C" {
#include <ical.h>
}
#include <libkcal/vcaldrag.h>
#include <libkcal/vcalformat.h>
#include <libkcal/icalformat.h>
#include "kalarmapp.h"
#include "alarmcalendar.h"
const QString DEFAULT_CALENDAR_FILE(QString::fromLatin1("calendar.ics"));
/******************************************************************************
* Read the calendar file URL from the config file (or use the default).
* If there is an error, the program exits.
*/
void AlarmCalendar::getURL() const
{
if (!mUrl.isValid())
{
KConfig* config = kapp->config();
config->setGroup(QString::fromLatin1("General"));
*const_cast<KURL*>(&mUrl) = config->readEntry(QString::fromLatin1("Calendar"),
locateLocal("appdata", DEFAULT_CALENDAR_FILE));
if (!mUrl.isValid())
{
kdDebug(5950) << "AlarmCalendar::getURL(): invalid name: " << mUrl.prettyURL() << endl;
KMessageBox::error(0L, i18n("Invalid calendar file name: %1").arg(mUrl.prettyURL()),
kapp->aboutData()->programName());
kapp->exit(1);
}
}
}
/******************************************************************************
* Open the calendar file and load it into memory.
*/
bool AlarmCalendar::open()
{
getURL();
mCalendar = new CalendarLocal();
mCalendar->setLocalTime(); // write out using local time (i.e. no time zone)
// Find out whether the calendar is ICal or VCal format
QString ext = mUrl.filename().right(4);
mVCal = (ext == QString::fromLatin1(".vcs"));
if (!KIO::NetAccess::exists(mUrl))
{
if (!create()) // create the calendar file
return false;
}
// Load the calendar file
switch (load())
{
case 1:
break;
case 0:
if (!create() || load() <= 0)
return false;
case -1:
/* if (!KIO::NetAccess::exists(mUrl))
{
if (!create() || load() <= 0)
return false;
}*/
return false;
}
return true;
}
/******************************************************************************
* Create a new calendar file.
*/
bool AlarmCalendar::create()
{
// Create the calendar file
KTempFile* tmpFile = 0L;
QString filename;
if (mUrl.isLocalFile())
filename = mUrl.path();
else
{
tmpFile = new KTempFile;
filename = tmpFile->name();
}
if (!save(filename))
{
delete tmpFile;
return false;
}
delete tmpFile;
return true;
}
/******************************************************************************
* Load the calendar file into memory.
* Reply = 1 if success, -2 if failure, 0 if zero-length file exists.
*/
int AlarmCalendar::load()
{
getURL();
kdDebug(5950) << "AlarmCalendar::load(): " << mUrl.prettyURL() << endl;
QString tmpFile;
if (!KIO::NetAccess::download(mUrl, tmpFile))
{
kdError(5950) << "AlarmCalendar::load(): Load failure" << endl;
KMessageBox::error(0L, i18n("Cannot open calendar:\n%1").arg(mUrl.prettyURL()), kapp->aboutData()->programName());
return -1;
}
kdDebug(5950) << "AlarmCalendar::load(): --- Downloaded to " << tmpFile << endl;
mKAlarmVersion = -1;
mKAlarmVersion057_UTC = false;
mCalendar->setTimeZoneId(QString::null); // default to the local time zone for reading
bool loaded = mCalendar->load(tmpFile);
mCalendar->setLocalTime(); // write using local time (i.e. no time zone)
if (!loaded)
{
// Check if the file is zero length
KIO::NetAccess::removeTempFile(tmpFile);
KIO::UDSEntry uds;
KIO::NetAccess::stat(mUrl, uds);
KFileItem fi(uds, mUrl);
if (!fi.size())
return 0; // file is zero length
kdDebug(5950) << "AlarmCalendar::load(): Error loading calendar file '" << tmpFile << "'" << endl;
KMessageBox::error(0L, i18n("Error loading calendar:\n%1\n\nPlease fix or delete the file.").arg(mUrl.prettyURL()),
kapp->aboutData()->programName());
return -1;
}
if (!mLocalFile.isEmpty())
KIO::NetAccess::removeTempFile(mLocalFile);
mLocalFile = tmpFile;
// Find the version of KAlarm which wrote the calendar file, and do
// any necessary conversions to the current format
getKAlarmVersion();
if (mKAlarmVersion == KAlarmVersion(0,5,7))
{
// KAlarm version 0.5.7 - check whether times are stored in UTC, in which
// case it is the KDE 3.0.0 version which needs adjustment of summer times.
mKAlarmVersion057_UTC = isUTC();
kdDebug(5950) << "AlarmCalendar::load(): KAlarm version 0.5.7 (" << (mKAlarmVersion057_UTC ? "" : "non-") << "UTC)\n";
}
else
kdDebug(5950) << "AlarmCalendar::load(): KAlarm version " << mKAlarmVersion << endl;
KAlarmEvent::convertKCalEvents(); // convert events to current KAlarm format for when calendar is saved
return 1;
}
/******************************************************************************
* Reload the calendar file into memory.
* Reply = 1 if success, -2 if failure, 0 if zero-length file exists.
*/
int AlarmCalendar::reload()
{
if (!mCalendar)
return -2;
kdDebug(5950) << "AlarmCalendar::reload(): " << mUrl.prettyURL() << endl;
close();
return load();
}
/******************************************************************************
* Save the calendar from memory to file.
*/
bool AlarmCalendar::save(const QString& filename)
{
kdDebug(5950) << "AlarmCalendar::save(): " << filename << endl;
CalFormat* format;
if(mVCal)
format = new VCalFormat;
else
format = new ICalFormat;
bool success = mCalendar->save(filename, format);
if (!success)
{
kdDebug(5950) << "AlarmCalendar::save(): calendar save failed." << endl;
return false;
}
getURL();
if (!mUrl.isLocalFile())
{
if (!KIO::NetAccess::upload(filename, mUrl))
{
KMessageBox::error(0L, i18n("Cannot upload calendar to\n'%1'").arg(mUrl.prettyURL()), kapp->aboutData()->programName());
return false;
}
}
// Tell the alarm daemon to reload the calendar
QByteArray data;
QDataStream arg(data, IO_WriteOnly);
arg << QCString(kapp->aboutData()->appName()) << mUrl.url();
if (!kapp->dcopClient()->send(DAEMON_APP_NAME, DAEMON_DCOP_OBJECT, "reloadMsgCal(QCString,QString)", data))
kdDebug(5950) << "AlarmCalendar::save(): addCal dcop send failed" << endl;
return true;
}
/******************************************************************************
* Delete any temporary file at program exit.
*/
void AlarmCalendar::close()
{
if (!mLocalFile.isEmpty())
KIO::NetAccess::removeTempFile(mLocalFile);
if (mCalendar)
mCalendar->close();
}
/******************************************************************************
* Add the specified event to the calendar.
*/
void AlarmCalendar::addEvent(const KAlarmEvent& event)
{
Event* kcalEvent = new Event;
event.updateEvent(*kcalEvent);
mCalendar->addEvent(kcalEvent);
const_cast<KAlarmEvent&>(event).setEventID(kcalEvent->uid());
}
/******************************************************************************
* Update the specified event in the calendar with its new contents.
* The event retains the same ID.
*/
void AlarmCalendar::updateEvent(const KAlarmEvent& evnt)
{
Event* kcalEvent = event(evnt.id());
if (kcalEvent)
evnt.updateEvent(*kcalEvent);
}
/******************************************************************************
* Delete the specified event from the calendar.
*/
void AlarmCalendar::deleteEvent(const QString& eventID)
{
Event* kcalEvent = event(eventID);
if (kcalEvent)
mCalendar->deleteEvent(kcalEvent);
}
/******************************************************************************
* Return the KAlarm version which wrote the calendar which has been loaded.
* The format is, for example, 000507 for 0.5.7, or 0 if unknown.
*/
void AlarmCalendar::getKAlarmVersion() const
{
// N.B. Remember to change KAlarmVersion(int major, int minor, int rev)
// if the representation returned by this method changes.
mKAlarmVersion = 0; // set default to KAlarm pre-0.3.5, or another program
if (mCalendar)
{
const QString& prodid = mCalendar->loadedProductId();
QString progname = QString(" ") + theApp()->aboutData()->programName() + " ";
int i = prodid.find(progname, 0, false);
if (i >= 0)
{
QString ver = prodid.mid(i + progname.length()).stripWhiteSpace();
i = ver.find('/');
int j = ver.find(' ');
if (j >= 0 && j < i)
i = j;
if (i > 0)
{
ver = ver.left(i);
// ver now contains the KAlarm version string
if ((i = ver.find('.')) > 0)
{
bool ok;
int version = ver.left(i).toInt(&ok) * 10000; // major version
if (ok)
{
ver = ver.mid(i + 1);
if ((i = ver.find('.')) > 0)
{
int v = ver.left(i).toInt(&ok); // minor version
if (ok)
{
version += (v < 9 ? v : 9) * 100;
ver = ver.mid(i + 1);
if (ver.at(0).isDigit())
{
// Allow other characters to follow last digit
v = ver.toInt(); // issue number
mKAlarmVersion = version + (v < 9 ? v : 9);
}
}
}
else
{
// There is no issue number
if (ver.at(0).isDigit())
{
// Allow other characters to follow last digit
int v = ver.toInt(); // minor number
mKAlarmVersion = version + (v < 9 ? v : 9) * 100;
}
}
}
}
}
}
}
}
/******************************************************************************
* Check whether the calendar file has its times stored as UTC times,
* indicating that it was written by the KDE 3.0.0 version of KAlarm 0.5.7.
* Reply = true if times are stored in UTC
* = false if the calendar is a vCalendar, times are not UTC, or any error occurred.
*/
bool AlarmCalendar::isUTC() const
{
// Read the calendar file into a QString
QFile file(mLocalFile);
if (!file.open(IO_ReadOnly))
return false;
QTextStream ts(&file);
ts.setEncoding(QTextStream::UnicodeUTF8);
QString text = ts.read();
file.close();
// Extract the CREATED property for the first VEVENT from the calendar
bool result = false;
icalcomponent* calendar = icalcomponent_new_from_string(text.local8Bit().data());
if (calendar)
{
if (icalcomponent_isa(calendar) == ICAL_VCALENDAR_COMPONENT)
{
icalcomponent* c = icalcomponent_get_first_component(calendar, ICAL_VEVENT_COMPONENT);
if (c)
{
icalproperty* p = icalcomponent_get_first_property(c, ICAL_CREATED_PROPERTY);
if (p)
{
struct icaltimetype datetime = icalproperty_get_created(p);
if (datetime.is_utc)
result = true;
}
}
}
icalcomponent_free(calendar);
}
return result;
}
<|endoftext|> |
<commit_before>#include <phypp.hpp>
void print_help();
int phypp_main(int argc, char* argv[]) {
if (argc < 2) {
print_help();
return 0;
}
uint_t continuum_width = 350; // in spectral element
read_args(argc-1, argv+1, arg_list(continuum_width));
// Copy and open cube
std::string infile = argv[1];
std::string outfile = file::remove_extension(file::get_basename(infile))+"_contsub.fits";
file::copy(infile, outfile);
vec3d cflx, cerr;
fits::image fimg(outfile);
fimg.reach_hdu(1);
fimg.read(cflx);
fimg.reach_hdu(1);
fimg.read(cerr);
// Estimate and subtract the continuum emission
for (uint_t y : range(cflx.dims[1]))
for (uint_t x : range(cflx.dims[2])) {
vec1d tflx = cflx(_,y,x);
// vec1d twei = 1.0/cerr(_,y,x);
vec1d twei = 0.0*cerr(_,y,x) + 1.0;
for (uint_t l : range(cflx.dims[0])) {
uint_t l0 = max(0, int_t(l)-int_t(continuum_width/2));
uint_t l1 = min(cflx.dims[0]-1, int_t(l)+int_t(continuum_width/2));
cflx(l,y,x) -= weighted_median(tflx[l0-_-l1], twei[l0-_-l1]);
}
}
fimg.reach_hdu(1);
fimg.update(cflx);
return 0;
}
void print_help() {
using namespace format;
print("contsub v1.0");
print("usage: contsub <kmos_cube.fits> continuum_width=...");
print("");
print("Main parameter:");
paragraph("'kmos_cube.fits' should be a cube created by the KMOS pipeline, with 3 "
"extensions: the first is empty (KMOS convention), the second contains the flux "
"and the third contains the uncertainty. This program will then compute the "
"weighted median flux of each pixel along a wide wavelength range to estimate "
"the flux of the continuum, and subtract it from the cube.");
print("Available option:");
bullet("continuum_width=...", "Must be an integer. It defines the width of the "
"wavelength range within which the continuum level is estimated, for each pixel "
"and each wavelength element. It must be given in number of wavelength elements. "
"Default is 350. Be cautious not to pick too small a value, else you may start to "
"subtract part of the flux of your emission lines. You will, however, obtain a "
"higher resolution spectrum of the continuum.");
}
<commit_msg>Fixed harmless warning for sign comparison<commit_after>#include <phypp.hpp>
void print_help();
int phypp_main(int argc, char* argv[]) {
if (argc < 2) {
print_help();
return 0;
}
uint_t continuum_width = 350; // in spectral element
read_args(argc-1, argv+1, arg_list(continuum_width));
// Copy and open cube
std::string infile = argv[1];
std::string outfile = file::remove_extension(file::get_basename(infile))+"_contsub.fits";
file::copy(infile, outfile);
vec3d cflx, cerr;
fits::image fimg(outfile);
fimg.reach_hdu(1);
fimg.read(cflx);
fimg.reach_hdu(1);
fimg.read(cerr);
// Estimate and subtract the continuum emission
for (uint_t y : range(cflx.dims[1]))
for (uint_t x : range(cflx.dims[2])) {
vec1d tflx = cflx.safe(_,y,x);
// vec1d twei = 1.0/cerr(_,y,x);
vec1d twei = 0.0*cerr.safe(_,y,x) + 1.0;
for (uint_t l : range(cflx.dims[0])) {
uint_t l0 = max(0, int_t(l)-int_t(continuum_width/2));
uint_t l1 = min(cflx.dims[0]-1, l+continuum_width/2);
cflx.safe(l,y,x) -= weighted_median(tflx.safe[l0-_-l1], twei.safe[l0-_-l1]);
}
}
fimg.reach_hdu(1);
fimg.update(cflx);
return 0;
}
void print_help() {
using namespace format;
print("contsub v1.0");
print("usage: contsub <kmos_cube.fits> continuum_width=...");
print("");
print("Main parameter:");
paragraph("'kmos_cube.fits' should be a cube created by the KMOS pipeline, with 3 "
"extensions: the first is empty (KMOS convention), the second contains the flux "
"and the third contains the uncertainty. This program will then compute the "
"weighted median flux of each pixel along a wide wavelength range to estimate "
"the flux of the continuum, and subtract it from the cube.");
print("Available option:");
bullet("continuum_width=...", "Must be an integer. It defines the width of the "
"wavelength range within which the continuum level is estimated, for each pixel "
"and each wavelength element. It must be given in number of wavelength elements. "
"Default is 350. Be cautious not to pick too small a value, else you may start to "
"subtract part of the flux of your emission lines. You will, however, obtain a "
"higher resolution spectrum of the continuum.");
}
<|endoftext|> |
<commit_before><commit_msg>[Gui]Fix Py SyntaxError on " in PropertyStringList<commit_after><|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "RocksDBPathBasedIndex.h"
#include "Aql/AstNode.h"
#include "Basics/FixedSizeAllocator.h"
#include "Basics/StaticStrings.h"
#include "Basics/VelocyPackHelper.h"
#include "Logger/Logger.h"
#include "RocksDBEngine/RocksDBKey.h"
#include "RocksDBEngine/RocksDBValue.h"
#include "Transaction/Helpers.h"
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
/// @brief the _key attribute, which, when used in an index, will implictly make
/// it unique
static std::vector<arangodb::basics::AttributeName> const KeyAttribute{
arangodb::basics::AttributeName("_key", false)};
/// @brief create the index
RocksDBPathBasedIndex::RocksDBPathBasedIndex(
TRI_idx_iid_t iid, arangodb::LogicalCollection* collection,
VPackSlice const& info, size_t baseSize, bool allowPartialIndex)
: RocksDBIndex(iid, collection, info),
_useExpansion(false),
_allowPartialIndex(allowPartialIndex) {
TRI_ASSERT(!_fields.empty());
TRI_ASSERT(iid != 0);
fillPaths(_paths, _expanding);
for (auto const& it : _fields) {
if (TRI_AttributeNamesHaveExpansion(it)) {
_useExpansion = true;
break;
}
}
//_allocator.reset(new FixedSizeAllocator(baseSize +
//sizeof(MMFilesIndexElementValue) * numPaths()));
}
/// @brief destroy the index
RocksDBPathBasedIndex::~RocksDBPathBasedIndex() {
//_allocator->deallocateAll();
}
/// @brief whether or not the index is implicitly unique
/// this can be the case if the index is not declared as unique, but contains a
/// unique attribute such as _key
bool RocksDBPathBasedIndex::implicitlyUnique() const {
if (_unique) {
// a unique index is always unique
return true;
}
if (_useExpansion) {
// when an expansion such as a[*] is used, the index may not be unique, even
// if it contains attributes that are guaranteed to be unique
return false;
}
for (auto const& it : _fields) {
// if _key is contained in the index fields definition, then the index is
// implicitly unique
if (it == KeyAttribute) {
return true;
}
}
// _key not contained
return false;
}
/// @brief helper function to insert a document into any index type
/// Should result in a
int RocksDBPathBasedIndex::fillElement(
transaction::Methods* trx, TRI_voc_rid_t revisionId, VPackSlice const& doc,
std::vector<std::pair<RocksDBKey, RocksDBValue>>& elements) {
if (doc.isNone()) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "encountered invalid marker with slice of type None";
return TRI_ERROR_INTERNAL;
}
TRI_IF_FAILURE("FillElementIllegalSlice") { return TRI_ERROR_INTERNAL; }
if (!_useExpansion) {
// fast path for inserts... no array elements used
transaction::BuilderLeaser indexVals(trx);
indexVals->openArray();
size_t const n = _paths.size();
for (size_t i = 0; i < n; ++i) {
TRI_ASSERT(!_paths[i].empty());
VPackSlice slice = doc.get(_paths[i]);
if (slice.isNone() || slice.isNull()) {
// attribute not found
if (_sparse) {
// if sparse we do not have to index, this is indicated by result
// being shorter than n
return TRI_ERROR_NO_ERROR;
}
// null, note that this will be copied later!
indexVals->add(VPackSlice::nullSlice());
} else {
indexVals->add(slice);
}
}
indexVals->close();
StringRef key(doc.get(StaticStrings::KeyString));
if (_unique) {
// Unique VPack index values are stored as follows:
// - Key: 7 + 8-byte object ID of index + VPack array with index value(s)
// - Value: primary key
elements.emplace_back(
RocksDBKey::UniqueIndexValue(_objectId, indexVals->slice()),
RocksDBValue::UniqueIndexValue(key));
} else {
// Non-unique VPack index values are stored as follows:
// - Key: 6 + 8-byte object ID of index + VPack array with index value(s)
// + primary key
// - Value: empty
elements.emplace_back(
RocksDBKey::IndexValue(_objectId, key, indexVals->slice()),
RocksDBValue::IndexValue());
}
} else {
// other path for handling array elements, too
std::vector<VPackSlice> sliceStack;
transaction::BuilderLeaser indexVals(trx);
buildIndexValues(doc, 0, elements, sliceStack);
}
return TRI_ERROR_NO_ERROR;
}
void RocksDBPathBasedIndex::addIndexValue(
VPackSlice const& document,
std::vector<std::pair<RocksDBKey, RocksDBValue>>& elements,
std::vector<VPackSlice>& sliceStack) {
// TODO maybe use leaded Builder from transaction.
VPackBuilder b;
b.openArray();
for (VPackSlice const& s : sliceStack) {
b.add(s);
}
b.close();
StringRef key (document.get(StaticStrings::KeyString));
if (_unique) {
// Unique VPack index values are stored as follows:
// - Key: 7 + 8-byte object ID of index + VPack array with index value(s)
// - Value: primary key
elements.emplace_back(RocksDBKey::UniqueIndexValue(_objectId, b.slice()),
RocksDBValue::UniqueIndexValue(key));
} else {
// Non-unique VPack index values are stored as follows:
// - Key: 6 + 8-byte object ID of index + VPack array with index value(s)
// + primary key
// - Value: empty
elements.emplace_back(
RocksDBKey::IndexValue(_objectId, StringRef(key), b.slice()),
RocksDBValue::IndexValue());
}
}
/// @brief helper function to create a set of index combinations to insert
void RocksDBPathBasedIndex::buildIndexValues(
VPackSlice const document, size_t level,
std::vector<std::pair<RocksDBKey, RocksDBValue>>& elements,
std::vector<VPackSlice>& sliceStack) {
// Invariant: level == sliceStack.size()
// Stop the recursion:
if (level == _paths.size()) {
addIndexValue(document, elements, sliceStack);
return;
}
if (_expanding[level] == -1) { // the trivial, non-expanding case
VPackSlice slice = document.get(_paths[level]);
if (slice.isNone() || slice.isNull()) {
if (_sparse) {
return;
}
sliceStack.emplace_back(arangodb::basics::VelocyPackHelper::NullValue());
} else {
sliceStack.emplace_back(slice);
}
buildIndexValues(document, level + 1, elements, sliceStack);
sliceStack.pop_back();
return;
}
// Finally, the complex case, where we have to expand one entry.
// Note again that at most one step in the attribute path can be
// an array step. Furthermore, if _allowPartialIndex is true and
// anything goes wrong with this attribute path, we have to bottom out
// with None values to be able to use the index for a prefix match.
// Trivial case to bottom out with Illegal types.
VPackSlice illegalSlice = arangodb::basics::VelocyPackHelper::IllegalValue();
auto finishWithNones = [&]() -> void {
if (!_allowPartialIndex || level == 0) {
return;
}
for (size_t i = level; i < _paths.size(); i++) {
sliceStack.emplace_back(illegalSlice);
}
addIndexValue(document.get(StaticStrings::KeyString), elements, sliceStack);
for (size_t i = level; i < _paths.size(); i++) {
sliceStack.pop_back();
}
};
size_t const n = _paths[level].size();
// We have 0 <= _expanding[level] < n.
VPackSlice current(document);
for (size_t i = 0; i <= static_cast<size_t>(_expanding[level]); i++) {
if (!current.isObject()) {
finishWithNones();
return;
}
current = current.get(_paths[level][i]);
if (current.isNone()) {
finishWithNones();
return;
}
}
// Now the expansion:
if (!current.isArray() || current.length() == 0) {
finishWithNones();
return;
}
std::unordered_set<VPackSlice, arangodb::basics::VelocyPackHelper::VPackHash,
arangodb::basics::VelocyPackHelper::VPackEqual>
seen(2, arangodb::basics::VelocyPackHelper::VPackHash(),
arangodb::basics::VelocyPackHelper::VPackEqual());
auto moveOn = [&](VPackSlice something) -> void {
auto it = seen.find(something);
if (it == seen.end()) {
seen.insert(something);
sliceStack.emplace_back(something);
buildIndexValues(document, level + 1, elements, sliceStack);
sliceStack.pop_back();
}
};
for (auto const& member : VPackArrayIterator(current)) {
VPackSlice current2(member);
bool doneNull = false;
for (size_t i = _expanding[level] + 1; i < n; i++) {
if (!current2.isObject()) {
if (!_sparse) {
moveOn(arangodb::basics::VelocyPackHelper::NullValue());
}
doneNull = true;
break;
}
current2 = current2.get(_paths[level][i]);
if (current2.isNone()) {
if (!_sparse) {
moveOn(arangodb::basics::VelocyPackHelper::NullValue());
}
doneNull = true;
break;
}
}
if (!doneNull) {
moveOn(current2);
}
// Finally, if, because of sparsity, we have not inserted anything by now,
// we need to play the above trick with None because of the above mentioned
// reasons:
if (seen.empty()) {
finishWithNones();
}
}
}
/// @brief helper function to transform AttributeNames into strings.
void RocksDBPathBasedIndex::fillPaths(
std::vector<std::vector<std::string>>& paths, std::vector<int>& expanding) {
paths.clear();
expanding.clear();
for (std::vector<arangodb::basics::AttributeName> const& list : _fields) {
paths.emplace_back();
std::vector<std::string>& interior(paths.back());
int expands = -1;
int count = 0;
for (auto const& att : list) {
interior.emplace_back(att.name);
if (att.shouldExpand) {
expands = count;
}
++count;
}
expanding.emplace_back(expands);
}
}
<commit_msg>Added some documentation<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "RocksDBPathBasedIndex.h"
#include "Aql/AstNode.h"
#include "Basics/FixedSizeAllocator.h"
#include "Basics/StaticStrings.h"
#include "Basics/VelocyPackHelper.h"
#include "Logger/Logger.h"
#include "RocksDBEngine/RocksDBKey.h"
#include "RocksDBEngine/RocksDBValue.h"
#include "Transaction/Helpers.h"
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
/// @brief the _key attribute, which, when used in an index, will implictly make
/// it unique
static std::vector<arangodb::basics::AttributeName> const KeyAttribute{
arangodb::basics::AttributeName("_key", false)};
/// @brief create the index
RocksDBPathBasedIndex::RocksDBPathBasedIndex(
TRI_idx_iid_t iid, arangodb::LogicalCollection* collection,
VPackSlice const& info, size_t baseSize, bool allowPartialIndex)
: RocksDBIndex(iid, collection, info),
_useExpansion(false),
_allowPartialIndex(allowPartialIndex) {
TRI_ASSERT(!_fields.empty());
TRI_ASSERT(iid != 0);
fillPaths(_paths, _expanding);
for (auto const& it : _fields) {
if (TRI_AttributeNamesHaveExpansion(it)) {
_useExpansion = true;
break;
}
}
//_allocator.reset(new FixedSizeAllocator(baseSize +
//sizeof(MMFilesIndexElementValue) * numPaths()));
}
/// @brief destroy the index
RocksDBPathBasedIndex::~RocksDBPathBasedIndex() {
//_allocator->deallocateAll();
}
/// @brief whether or not the index is implicitly unique
/// this can be the case if the index is not declared as unique, but contains a
/// unique attribute such as _key
bool RocksDBPathBasedIndex::implicitlyUnique() const {
if (_unique) {
// a unique index is always unique
return true;
}
if (_useExpansion) {
// when an expansion such as a[*] is used, the index may not be unique, even
// if it contains attributes that are guaranteed to be unique
return false;
}
for (auto const& it : _fields) {
// if _key is contained in the index fields definition, then the index is
// implicitly unique
if (it == KeyAttribute) {
return true;
}
}
// _key not contained
return false;
}
/// @brief helper function to insert a document into any index type
/// Should result in an elements vector filled with the new index entries
/// uses the _unique field to determine the kind of key structure
int RocksDBPathBasedIndex::fillElement(
transaction::Methods* trx, TRI_voc_rid_t revisionId, VPackSlice const& doc,
std::vector<std::pair<RocksDBKey, RocksDBValue>>& elements) {
if (doc.isNone()) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "encountered invalid marker with slice of type None";
return TRI_ERROR_INTERNAL;
}
TRI_IF_FAILURE("FillElementIllegalSlice") { return TRI_ERROR_INTERNAL; }
if (!_useExpansion) {
// fast path for inserts... no array elements used
transaction::BuilderLeaser indexVals(trx);
indexVals->openArray();
size_t const n = _paths.size();
for (size_t i = 0; i < n; ++i) {
TRI_ASSERT(!_paths[i].empty());
VPackSlice slice = doc.get(_paths[i]);
if (slice.isNone() || slice.isNull()) {
// attribute not found
if (_sparse) {
// if sparse we do not have to index, this is indicated by result
// being shorter than n
return TRI_ERROR_NO_ERROR;
}
// null, note that this will be copied later!
indexVals->add(VPackSlice::nullSlice());
} else {
indexVals->add(slice);
}
}
indexVals->close();
StringRef key(doc.get(StaticStrings::KeyString));
if (_unique) {
// Unique VPack index values are stored as follows:
// - Key: 7 + 8-byte object ID of index + VPack array with index value(s)
// - Value: primary key
elements.emplace_back(
RocksDBKey::UniqueIndexValue(_objectId, indexVals->slice()),
RocksDBValue::UniqueIndexValue(key));
} else {
// Non-unique VPack index values are stored as follows:
// - Key: 6 + 8-byte object ID of index + VPack array with index value(s)
// + primary key
// - Value: empty
elements.emplace_back(
RocksDBKey::IndexValue(_objectId, key, indexVals->slice()),
RocksDBValue::IndexValue());
}
} else {
// other path for handling array elements, too
std::vector<VPackSlice> sliceStack;
transaction::BuilderLeaser indexVals(trx);
buildIndexValues(doc, 0, elements, sliceStack);
}
return TRI_ERROR_NO_ERROR;
}
void RocksDBPathBasedIndex::addIndexValue(
VPackSlice const& document,
std::vector<std::pair<RocksDBKey, RocksDBValue>>& elements,
std::vector<VPackSlice>& sliceStack) {
// TODO maybe use leaded Builder from transaction.
VPackBuilder b;
b.openArray();
for (VPackSlice const& s : sliceStack) {
b.add(s);
}
b.close();
StringRef key (document.get(StaticStrings::KeyString));
if (_unique) {
// Unique VPack index values are stored as follows:
// - Key: 7 + 8-byte object ID of index + VPack array with index value(s)
// - Value: primary key
elements.emplace_back(RocksDBKey::UniqueIndexValue(_objectId, b.slice()),
RocksDBValue::UniqueIndexValue(key));
} else {
// Non-unique VPack index values are stored as follows:
// - Key: 6 + 8-byte object ID of index + VPack array with index value(s)
// + primary key
// - Value: empty
elements.emplace_back(
RocksDBKey::IndexValue(_objectId, StringRef(key), b.slice()),
RocksDBValue::IndexValue());
}
}
/// @brief helper function to create a set of index combinations to insert
void RocksDBPathBasedIndex::buildIndexValues(
VPackSlice const document, size_t level,
std::vector<std::pair<RocksDBKey, RocksDBValue>>& elements,
std::vector<VPackSlice>& sliceStack) {
// Invariant: level == sliceStack.size()
// Stop the recursion:
if (level == _paths.size()) {
addIndexValue(document, elements, sliceStack);
return;
}
if (_expanding[level] == -1) { // the trivial, non-expanding case
VPackSlice slice = document.get(_paths[level]);
if (slice.isNone() || slice.isNull()) {
if (_sparse) {
return;
}
sliceStack.emplace_back(arangodb::basics::VelocyPackHelper::NullValue());
} else {
sliceStack.emplace_back(slice);
}
buildIndexValues(document, level + 1, elements, sliceStack);
sliceStack.pop_back();
return;
}
// Finally, the complex case, where we have to expand one entry.
// Note again that at most one step in the attribute path can be
// an array step. Furthermore, if _allowPartialIndex is true and
// anything goes wrong with this attribute path, we have to bottom out
// with None values to be able to use the index for a prefix match.
// Trivial case to bottom out with Illegal types.
VPackSlice illegalSlice = arangodb::basics::VelocyPackHelper::IllegalValue();
auto finishWithNones = [&]() -> void {
if (!_allowPartialIndex || level == 0) {
return;
}
for (size_t i = level; i < _paths.size(); i++) {
sliceStack.emplace_back(illegalSlice);
}
addIndexValue(document.get(StaticStrings::KeyString), elements, sliceStack);
for (size_t i = level; i < _paths.size(); i++) {
sliceStack.pop_back();
}
};
size_t const n = _paths[level].size();
// We have 0 <= _expanding[level] < n.
VPackSlice current(document);
for (size_t i = 0; i <= static_cast<size_t>(_expanding[level]); i++) {
if (!current.isObject()) {
finishWithNones();
return;
}
current = current.get(_paths[level][i]);
if (current.isNone()) {
finishWithNones();
return;
}
}
// Now the expansion:
if (!current.isArray() || current.length() == 0) {
finishWithNones();
return;
}
std::unordered_set<VPackSlice, arangodb::basics::VelocyPackHelper::VPackHash,
arangodb::basics::VelocyPackHelper::VPackEqual>
seen(2, arangodb::basics::VelocyPackHelper::VPackHash(),
arangodb::basics::VelocyPackHelper::VPackEqual());
auto moveOn = [&](VPackSlice something) -> void {
auto it = seen.find(something);
if (it == seen.end()) {
seen.insert(something);
sliceStack.emplace_back(something);
buildIndexValues(document, level + 1, elements, sliceStack);
sliceStack.pop_back();
}
};
for (auto const& member : VPackArrayIterator(current)) {
VPackSlice current2(member);
bool doneNull = false;
for (size_t i = _expanding[level] + 1; i < n; i++) {
if (!current2.isObject()) {
if (!_sparse) {
moveOn(arangodb::basics::VelocyPackHelper::NullValue());
}
doneNull = true;
break;
}
current2 = current2.get(_paths[level][i]);
if (current2.isNone()) {
if (!_sparse) {
moveOn(arangodb::basics::VelocyPackHelper::NullValue());
}
doneNull = true;
break;
}
}
if (!doneNull) {
moveOn(current2);
}
// Finally, if, because of sparsity, we have not inserted anything by now,
// we need to play the above trick with None because of the above mentioned
// reasons:
if (seen.empty()) {
finishWithNones();
}
}
}
/// @brief helper function to transform AttributeNames into strings.
void RocksDBPathBasedIndex::fillPaths(
std::vector<std::vector<std::string>>& paths, std::vector<int>& expanding) {
paths.clear();
expanding.clear();
for (std::vector<arangodb::basics::AttributeName> const& list : _fields) {
paths.emplace_back();
std::vector<std::string>& interior(paths.back());
int expands = -1;
int count = 0;
for (auto const& att : list) {
interior.emplace_back(att.name);
if (att.shouldExpand) {
expands = count;
}
++count;
}
expanding.emplace_back(expands);
}
}
<|endoftext|> |
<commit_before>#include "CPUStatsPrinter.h"
#include "CPUSnapshot.h"
#include <iostream>
const int CPUStatsPrinter::CPU_LABEL_W = 3;
const int CPUStatsPrinter::STATE_PERC_BASE_W = 4;
const char * CPUStatsPrinter::STR_STATES[CPUData::NUM_CPU_STATES] = { "usr",
"sys",
"nic",
"idl",
"iow",
"hir",
"sir",
"ste",
"gue",
"gun" };
// == PUBLIC FUNCTIONS ==
CPUStatsPrinter::CPUStatsPrinter(const CPUSnapshot& s1, const CPUSnapshot& s2)
: mS1(s1)
, mS2(s2)
, mPrecision(2)
, mVerbose(false)
{
}
void CPUStatsPrinter::PrintActivePercentageTotal()
{
if(mVerbose)
std::cout << mS1.GetLabelTotal() << "] ";
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(mPrecision);
std::cout << GetPercActiveTotal();
if(mVerbose)
std::cout << "%";
std::cout << std::endl;
}
void CPUStatsPrinter::PrintActivePercentageCPU(unsigned int cpu)
{
if(cpu >= mS1.GetNumEntries())
{
std::cout << "ERROR - CPU " << cpu << " not available." << std::endl;
return ;
}
if(mVerbose)
{
std::cout.width(CPU_LABEL_W);
std::cout << mS1.GetLabel(cpu) << "] ";
}
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(mPrecision);
std::cout << GetPercActive(cpu);
if(mVerbose)
std::cout << "%";
std::cout << std::endl;
}
void CPUStatsPrinter::PrintActivePercentageAll()
{
// PRINT TOTAL
PrintActivePercentageTotal();
// PRINT ALL CPUS
const unsigned int NUM_ENTRIES = mS1.GetNumEntries();
for(unsigned int i = 0; i < NUM_ENTRIES; ++i)
PrintActivePercentageCPU(i);
}
void CPUStatsPrinter::PrintStatePercentageTotal(unsigned int state)
{
if(mVerbose)
std::cout << mS1.GetLabelTotal() << "] ";
PrintStatePercentageNoLabelTotal(state);
std::cout << std::endl;
}
void CPUStatsPrinter::PrintStatePercentageCPU(unsigned int state, unsigned int cpu)
{
if(cpu >= mS1.GetNumEntries())
{
std::cout << "ERROR - CPU " << cpu << " not available." << std::endl;
return ;
}
if(mVerbose)
{
std::cout.width(CPU_LABEL_W);
std::cout << mS1.GetLabel(cpu) << "] ";
}
PrintStatePercentageNoLabelCPU(state, cpu);
std::cout << std::endl;
}
void CPUStatsPrinter::PrintStatePercentageAll(unsigned int state)
{
// PRINT TOTAL
PrintStatePercentageTotal(state);
// PRINT ALL CPUS
const unsigned int NUM_ENTRIES = mS1.GetNumEntries();
for(unsigned int i = 0; i < NUM_ENTRIES; ++i)
PrintStatePercentageCPU(state, i);
}
void CPUStatsPrinter::PrintFullStatePercentageTotal()
{
if(mVerbose)
std::cout << mS1.GetLabelTotal() << "] ";
for(int s = 0; s < CPUData::NUM_CPU_STATES; ++s)
{
PrintStatePercentageNoLabelTotal(s);
std::cout << " | ";
}
std::cout << std::endl;
}
void CPUStatsPrinter::PrintFullStatePercentageCPU(unsigned int cpu)
{
if(mVerbose)
{
std::cout.width(CPU_LABEL_W);
std::cout << mS1.GetLabel(cpu) << "] ";
}
for(int s = 0; s < CPUData::NUM_CPU_STATES; ++s)
{
PrintStatePercentageNoLabelCPU(s, cpu);
std::cout << " | ";
}
std::cout << std::endl;
}
void CPUStatsPrinter::PrintFullStatePercentageAll()
{
// PRINT TOTAL
PrintFullStatePercentageTotal();
// PRINT ALL CPUS
const unsigned int NUM_ENTRIES = mS1.GetNumEntries();
for(unsigned int i = 0; i < NUM_ENTRIES; ++i)
PrintFullStatePercentageCPU(i);
}
// == PRIVATE FUNCTIONS ==
float CPUStatsPrinter::GetPercActiveTotal()
{
const float ACTIVE_TIME = mS2.GetActiveTimeTotal() - mS1.GetActiveTimeTotal();
const float IDLE_TIME = mS2.GetIdleTimeTotal() - mS1.GetIdleTimeTotal();
const float TOTAL_TIME = ACTIVE_TIME + IDLE_TIME;
return 100.f * ACTIVE_TIME / TOTAL_TIME;
}
float CPUStatsPrinter::GetPercActive(unsigned int cpu)
{
const float ACTIVE_TIME = mS2.GetActiveTime(cpu) - mS1.GetActiveTime(cpu);
const float IDLE_TIME = mS2.GetIdleTime(cpu) - mS1.GetIdleTime(cpu);
const float TOTAL_TIME = ACTIVE_TIME + IDLE_TIME;
return 100.f * ACTIVE_TIME / TOTAL_TIME;
}
float CPUStatsPrinter::GetPercStateTotal(unsigned int state)
{
const float STATE_TIME = mS2.GetStateTimeTotal(state) - mS1.GetStateTimeTotal(state);
const float TOTAL_TIME = mS2.GetTotalTimeTotal() - mS1.GetTotalTimeTotal();
return 100.f * STATE_TIME / TOTAL_TIME;
}
float CPUStatsPrinter::GetPercState(unsigned int state, unsigned int cpu)
{
const float STATE_TIME = mS2.GetStateTime(state, cpu) - mS1.GetStateTime(state, cpu);
const float TOTAL_TIME = mS2.GetTotalTime(cpu) - mS1.GetTotalTime(cpu);
return 100.f * STATE_TIME / TOTAL_TIME;
}
void CPUStatsPrinter::PrintStatePercentageNoLabelTotal(unsigned int state)
{
if(mVerbose)
std:: cout << STR_STATES[state] << ": ";
std::cout.width(STATE_PERC_BASE_W + mPrecision);
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(mPrecision);
std::cout << GetPercStateTotal(state);
if(mVerbose)
std::cout << "%";
}
void CPUStatsPrinter::PrintStatePercentageNoLabelCPU(unsigned int state, unsigned int cpu)
{
if(mVerbose)
std::cout << STR_STATES[state] << ": ";
std::cout.width(STATE_PERC_BASE_W + mPrecision);
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(mPrecision);
std::cout << GetPercState(state, cpu);
if(mVerbose)
std::cout << "%";
}
<commit_msg>Removed fixed output width when printing state percentage.<commit_after>#include "CPUStatsPrinter.h"
#include "CPUSnapshot.h"
#include <iostream>
const int CPUStatsPrinter::CPU_LABEL_W = 3;
const int CPUStatsPrinter::STATE_PERC_BASE_W = 4;
const char * CPUStatsPrinter::STR_STATES[CPUData::NUM_CPU_STATES] = { "usr",
"sys",
"nic",
"idl",
"iow",
"hir",
"sir",
"ste",
"gue",
"gun" };
// == PUBLIC FUNCTIONS ==
CPUStatsPrinter::CPUStatsPrinter(const CPUSnapshot& s1, const CPUSnapshot& s2)
: mS1(s1)
, mS2(s2)
, mPrecision(2)
, mVerbose(false)
{
}
void CPUStatsPrinter::PrintActivePercentageTotal()
{
if(mVerbose)
std::cout << mS1.GetLabelTotal() << "] ";
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(mPrecision);
std::cout << GetPercActiveTotal();
if(mVerbose)
std::cout << "%";
std::cout << std::endl;
}
void CPUStatsPrinter::PrintActivePercentageCPU(unsigned int cpu)
{
if(cpu >= mS1.GetNumEntries())
{
std::cout << "ERROR - CPU " << cpu << " not available." << std::endl;
return ;
}
if(mVerbose)
{
std::cout.width(CPU_LABEL_W);
std::cout << mS1.GetLabel(cpu) << "] ";
}
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(mPrecision);
std::cout << GetPercActive(cpu);
if(mVerbose)
std::cout << "%";
std::cout << std::endl;
}
void CPUStatsPrinter::PrintActivePercentageAll()
{
// PRINT TOTAL
PrintActivePercentageTotal();
// PRINT ALL CPUS
const unsigned int NUM_ENTRIES = mS1.GetNumEntries();
for(unsigned int i = 0; i < NUM_ENTRIES; ++i)
PrintActivePercentageCPU(i);
}
void CPUStatsPrinter::PrintStatePercentageTotal(unsigned int state)
{
if(mVerbose)
std::cout << mS1.GetLabelTotal() << "] ";
PrintStatePercentageNoLabelTotal(state);
std::cout << std::endl;
}
void CPUStatsPrinter::PrintStatePercentageCPU(unsigned int state, unsigned int cpu)
{
if(cpu >= mS1.GetNumEntries())
{
std::cout << "ERROR - CPU " << cpu << " not available." << std::endl;
return ;
}
if(mVerbose)
{
std::cout.width(CPU_LABEL_W);
std::cout << mS1.GetLabel(cpu) << "] ";
}
PrintStatePercentageNoLabelCPU(state, cpu);
std::cout << std::endl;
}
void CPUStatsPrinter::PrintStatePercentageAll(unsigned int state)
{
// PRINT TOTAL
PrintStatePercentageTotal(state);
// PRINT ALL CPUS
const unsigned int NUM_ENTRIES = mS1.GetNumEntries();
for(unsigned int i = 0; i < NUM_ENTRIES; ++i)
PrintStatePercentageCPU(state, i);
}
void CPUStatsPrinter::PrintFullStatePercentageTotal()
{
if(mVerbose)
std::cout << mS1.GetLabelTotal() << "] ";
for(int s = 0; s < CPUData::NUM_CPU_STATES; ++s)
{
PrintStatePercentageNoLabelTotal(s);
std::cout << " | ";
}
std::cout << std::endl;
}
void CPUStatsPrinter::PrintFullStatePercentageCPU(unsigned int cpu)
{
if(mVerbose)
{
std::cout.width(CPU_LABEL_W);
std::cout << mS1.GetLabel(cpu) << "] ";
}
for(int s = 0; s < CPUData::NUM_CPU_STATES; ++s)
{
PrintStatePercentageNoLabelCPU(s, cpu);
std::cout << " | ";
}
std::cout << std::endl;
}
void CPUStatsPrinter::PrintFullStatePercentageAll()
{
// PRINT TOTAL
PrintFullStatePercentageTotal();
// PRINT ALL CPUS
const unsigned int NUM_ENTRIES = mS1.GetNumEntries();
for(unsigned int i = 0; i < NUM_ENTRIES; ++i)
PrintFullStatePercentageCPU(i);
}
// == PRIVATE FUNCTIONS ==
float CPUStatsPrinter::GetPercActiveTotal()
{
const float ACTIVE_TIME = mS2.GetActiveTimeTotal() - mS1.GetActiveTimeTotal();
const float IDLE_TIME = mS2.GetIdleTimeTotal() - mS1.GetIdleTimeTotal();
const float TOTAL_TIME = ACTIVE_TIME + IDLE_TIME;
return 100.f * ACTIVE_TIME / TOTAL_TIME;
}
float CPUStatsPrinter::GetPercActive(unsigned int cpu)
{
const float ACTIVE_TIME = mS2.GetActiveTime(cpu) - mS1.GetActiveTime(cpu);
const float IDLE_TIME = mS2.GetIdleTime(cpu) - mS1.GetIdleTime(cpu);
const float TOTAL_TIME = ACTIVE_TIME + IDLE_TIME;
return 100.f * ACTIVE_TIME / TOTAL_TIME;
}
float CPUStatsPrinter::GetPercStateTotal(unsigned int state)
{
const float STATE_TIME = mS2.GetStateTimeTotal(state) - mS1.GetStateTimeTotal(state);
const float TOTAL_TIME = mS2.GetTotalTimeTotal() - mS1.GetTotalTimeTotal();
return 100.f * STATE_TIME / TOTAL_TIME;
}
float CPUStatsPrinter::GetPercState(unsigned int state, unsigned int cpu)
{
const float STATE_TIME = mS2.GetStateTime(state, cpu) - mS1.GetStateTime(state, cpu);
const float TOTAL_TIME = mS2.GetTotalTime(cpu) - mS1.GetTotalTime(cpu);
return 100.f * STATE_TIME / TOTAL_TIME;
}
void CPUStatsPrinter::PrintStatePercentageNoLabelTotal(unsigned int state)
{
if(mVerbose)
{
std:: cout << STR_STATES[state] << ": ";
std::cout.width(STATE_PERC_BASE_W + mPrecision);
}
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(mPrecision);
std::cout << GetPercStateTotal(state);
if(mVerbose)
std::cout << "%";
}
void CPUStatsPrinter::PrintStatePercentageNoLabelCPU(unsigned int state, unsigned int cpu)
{
if(mVerbose)
{
std::cout << STR_STATES[state] << ": ";
std::cout.width(STATE_PERC_BASE_W + mPrecision);
}
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(mPrecision);
std::cout << GetPercState(state, cpu);
if(mVerbose)
std::cout << "%";
}
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <bh.h>
#include <vector>
#include <map>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include "bh_ir.h"
#include "bh_dag.h"
using namespace std;
namespace io = boost::iostreams;
/* Creates a Bohrium Internal Representation (BhIR) from a instruction list.
*
* @ninstr Number of instructions
* @instr_list The instruction list
*/
bh_ir::bh_ir(bh_intp ninstr, const bh_instruction instr_list[])
{
bh_ir::instr_list = vector<bh_instruction>(instr_list, &instr_list[ninstr]);
}
/* Creates a BhIR from a serialized BhIR.
*
* @bhir The BhIr serialized as a char array or vector
*/
bh_ir::bh_ir(const char bhir[], bh_intp size)
{
io::basic_array_source<char> source(bhir,size);
io::stream<io::basic_array_source <char> > input_stream(source);
boost::archive::binary_iarchive ia(input_stream);
ia >> *this;
}
/* Serialize the BhIR object into a char buffer
* (use the bh_ir constructor for deserialization)
*
* @buffer The char vector to serialize into
*/
void bh_ir::serialize(vector<char> &buffer) const
{
io::stream<io::back_insert_device<vector<char> > > output_stream(buffer);
boost::archive::binary_oarchive oa(output_stream);
oa << *this;
output_stream.flush();
}
/* Returns the cost of the BhIR */
uint64_t bh_ir::cost() const
{
uint64_t cost = 0;
BOOST_FOREACH(const bh_ir_kernel &k, kernel_list)
{
BOOST_FOREACH(const bh_view &v, k.input_list())
{
cost += bh_nelements_nbcast(&v) * bh_type_size(v.base->type);
}
BOOST_FOREACH(const bh_view &v, k.output_list())
{
cost += bh_nelements_nbcast(&v) * bh_type_size(v.base->type);
}
}
return cost;
}
/* Pretty print the kernel list */
void bh_ir::pprint_kernel_list() const
{
char msg[100]; int i=0;
BOOST_FOREACH(const bh_ir_kernel &k, kernel_list)
{
snprintf(msg, 100, "kernel-%d", i++);
bh_pprint_instr_list(&k.instr_list()[0], k.instr_list().size(), msg);
}
}
/* Pretty write the kernel DAG as a DOT file
*
* @filename Name of the DOT file
*/
void bh_ir::pprint_kernel_dag(const char filename[]) const
{
using namespace boost;
typedef adjacency_list<setS, vecS, bidirectionalS, const bh_ir_kernel> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
Graph dag;
BOOST_FOREACH(const bh_ir_kernel &kernel, kernel_list)
{
Vertex new_v = add_vertex(kernel, dag);
//Add dependencies
BOOST_FOREACH(Vertex v, vertices(dag))
{
if(new_v != v)//We do not depend on ourself
{
if(kernel.dependency(dag[v]))
add_edge(v, new_v, dag);
}
}
}
stringstream header;
header << "labelloc=\"t\";" << endl;
header << "label=\"DAG with a total cost of " << (cost()/1024) << " kbytes\";" << endl;
bh_dag_pprint(dag, filename, header.str().c_str());
}
/* Determines whether there are cyclic dependencies between the kernels in the BhIR
*
* @index_map A map from an instruction in the kernel_list (a pair of a kernel and
* an instruction index) to an index into the original instruction list
* @return True when no cycles was found
*/
bool bh_ir::check_kernel_cycles(const map<pair<int,int>,int> index_map) const
{
//Create a DAG of the kernels and check for cycles
using namespace boost;
typedef adjacency_list<setS, vecS, bidirectionalS, bh_ir_kernel> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
Graph dag(kernel_list.size());
//First we build a map from an index in the original instruction list
//to a vertex in the 'dag'
map<int,Vertex> instr2vertex;
unsigned int k=0;
BOOST_FOREACH(Vertex v, vertices(dag))
{
const vector<bh_instruction> &kernel = kernel_list[k].instr_list();
dag[v] = kernel_list[k];
for(unsigned int i=0; i<kernel.size(); ++i)
{
int instr_index = index_map.at(make_pair(k,i));
instr2vertex.insert(pair<int,Vertex>(instr_index,v));
}
++k;
}
//Then we add edges to the 'dag' for each dependency in the original
//instruction list
for(unsigned int i=0; i<instr_list.size(); ++i)
{
Vertex v = instr2vertex[i];
for(unsigned int j=0; j<i; ++j)//We may depend on any previous instruction
{
if(bh_instr_dependency(&instr_list[i], &instr_list[j]))
{
if(instr2vertex[j] != v)
add_edge(instr2vertex[j], v, dag);
}
}
}
//Finally we check for cycles between the kernel dependencies
vector<Vertex> topological_order;
try
{
//TODO: topological sort is an efficient method for finding cycles,
//but we should avoid allocating a vector
topological_sort(dag, back_inserter(topological_order));
return true;
}
catch (const not_a_dag &e)
{
cout << "Writing the failed kernel list: check_kernel_cycles-fail.dot" << endl;
bh_dag_pprint(dag, "check_kernel_cycles-fail.dot");
return false;
}
}
/* Add an instruction to the kernel
*
* @instr The instruction to add
* @return The boolean answer
*/
void bh_ir_kernel::add_instr(const bh_instruction &instr)
{
if(instr.opcode == BH_DISCARD)
{
const bh_base *base = instr.operand[0].base;
for(vector<bh_view>::iterator it=outputs.begin(); it != outputs.end(); ++it)
{
if(base == it->base)
{
temps.push_back(base);
outputs.erase(it);
break;
}
}
}
else if(instr.opcode != BH_FREE)
{
{
bool duplicates = false;
const bh_view &v = instr.operand[0];
BOOST_FOREACH(const bh_view &i, outputs)
{
if(bh_view_identical(&v, &i))
{
duplicates = true;
break;
}
}
if(!duplicates)
outputs.push_back(v);
}
const int nop = bh_operands(instr.opcode);
for(int i=1; i<nop; ++i)
{
const bh_view &v = instr.operand[i];
if(bh_is_constant(&v))
continue;
bool duplicates = false;
BOOST_FOREACH(const bh_view &i, inputs)
{
if(bh_view_identical(&v, &i))
{
duplicates = true;
break;
}
}
if(duplicates)
continue;
bool local_source = false;
BOOST_FOREACH(const bh_instruction &i, instrs)
{
if(bh_view_identical(&v, &i.operand[0]))
{
local_source = true;
break;
}
}
if(!local_source)
inputs.push_back(v);
}
}
instrs.push_back(instr);
};
/* Determines whether this kernel depends on 'other',
* which is true when:
* 'other' writes to an array that 'this' access
* or
* 'this' writes to an array that 'other' access
*
* @other The other kernel
* @return The boolean answer
*/
bool bh_ir_kernel::dependency(const bh_ir_kernel &other) const
{
BOOST_FOREACH(const bh_instruction &i, instr_list())
{
BOOST_FOREACH(const bh_instruction &o, other.instr_list())
{
if(bh_instr_dependency(&i, &o))
return true;
}
}
return false;
}
/* Determines whether it is legal to fuse with the kernel
*
* @other The other kernel
* @return The boolean answer
*/
bool bh_ir_kernel::fusible(const bh_ir_kernel &other) const
{
BOOST_FOREACH(const bh_instruction &a, instr_list())
{
BOOST_FOREACH(const bh_instruction &b, other.instr_list())
{
if(not bh_instr_fusible(&a, &b))
return false;
}
}
return true;
}
/* Determines whether it is legal to fuse with the instruction
*
* @instr The instruction
* @return The boolean answer
*/
bool bh_ir_kernel::fusible(const bh_instruction &instr) const
{
BOOST_FOREACH(const bh_instruction &i, instr_list())
{
if(not bh_instr_fusible(&i, &instr))
return false;
}
return true;
}
/* Determines whether it is legal to fuse with the instruction
* without changing this kernel's dependencies.
*
* @instr The instruction
* @return The boolean answer
*/
bool bh_ir_kernel::fusible_gently(const bh_instruction &instr) const
{
if(bh_opcode_is_system(instr.opcode))
return true;
//Check that 'instr' is fusible with least one existing instruction
BOOST_FOREACH(const bh_instruction &i, instr_list())
{
if(bh_opcode_is_system(i.opcode))
continue;
if(bh_instr_fusible_gently(&instr, &i))
return true;
}
return false;
}
/* Determines whether it is legal to fuse with the kernel without
* changing this kernel's dependencies.
*
* @other The other kernel
* @return The boolean answer
*/
bool bh_ir_kernel::fusible_gently(const bh_ir_kernel &other) const
{
BOOST_FOREACH(const bh_instruction &i, other.instr_list())
{
if(not fusible_gently(i))
return false;
}
return true;
}
<commit_msg>bhir: now bh_ir_kernel::add_instr() uses bh_view_aligned() instead of bh_view_identical()<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <bh.h>
#include <vector>
#include <map>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include "bh_ir.h"
#include "bh_dag.h"
using namespace std;
namespace io = boost::iostreams;
/* Creates a Bohrium Internal Representation (BhIR) from a instruction list.
*
* @ninstr Number of instructions
* @instr_list The instruction list
*/
bh_ir::bh_ir(bh_intp ninstr, const bh_instruction instr_list[])
{
bh_ir::instr_list = vector<bh_instruction>(instr_list, &instr_list[ninstr]);
}
/* Creates a BhIR from a serialized BhIR.
*
* @bhir The BhIr serialized as a char array or vector
*/
bh_ir::bh_ir(const char bhir[], bh_intp size)
{
io::basic_array_source<char> source(bhir,size);
io::stream<io::basic_array_source <char> > input_stream(source);
boost::archive::binary_iarchive ia(input_stream);
ia >> *this;
}
/* Serialize the BhIR object into a char buffer
* (use the bh_ir constructor for deserialization)
*
* @buffer The char vector to serialize into
*/
void bh_ir::serialize(vector<char> &buffer) const
{
io::stream<io::back_insert_device<vector<char> > > output_stream(buffer);
boost::archive::binary_oarchive oa(output_stream);
oa << *this;
output_stream.flush();
}
/* Returns the cost of the BhIR */
uint64_t bh_ir::cost() const
{
uint64_t cost = 0;
BOOST_FOREACH(const bh_ir_kernel &k, kernel_list)
{
BOOST_FOREACH(const bh_view &v, k.input_list())
{
cost += bh_nelements_nbcast(&v) * bh_type_size(v.base->type);
}
BOOST_FOREACH(const bh_view &v, k.output_list())
{
cost += bh_nelements_nbcast(&v) * bh_type_size(v.base->type);
}
}
return cost;
}
/* Pretty print the kernel list */
void bh_ir::pprint_kernel_list() const
{
char msg[100]; int i=0;
BOOST_FOREACH(const bh_ir_kernel &k, kernel_list)
{
snprintf(msg, 100, "kernel-%d", i++);
bh_pprint_instr_list(&k.instr_list()[0], k.instr_list().size(), msg);
}
}
/* Pretty write the kernel DAG as a DOT file
*
* @filename Name of the DOT file
*/
void bh_ir::pprint_kernel_dag(const char filename[]) const
{
using namespace boost;
typedef adjacency_list<setS, vecS, bidirectionalS, const bh_ir_kernel> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
Graph dag;
BOOST_FOREACH(const bh_ir_kernel &kernel, kernel_list)
{
Vertex new_v = add_vertex(kernel, dag);
//Add dependencies
BOOST_FOREACH(Vertex v, vertices(dag))
{
if(new_v != v)//We do not depend on ourself
{
if(kernel.dependency(dag[v]))
add_edge(v, new_v, dag);
}
}
}
stringstream header;
header << "labelloc=\"t\";" << endl;
header << "label=\"DAG with a total cost of " << (cost()/1024) << " kbytes\";" << endl;
bh_dag_pprint(dag, filename, header.str().c_str());
}
/* Determines whether there are cyclic dependencies between the kernels in the BhIR
*
* @index_map A map from an instruction in the kernel_list (a pair of a kernel and
* an instruction index) to an index into the original instruction list
* @return True when no cycles was found
*/
bool bh_ir::check_kernel_cycles(const map<pair<int,int>,int> index_map) const
{
//Create a DAG of the kernels and check for cycles
using namespace boost;
typedef adjacency_list<setS, vecS, bidirectionalS, bh_ir_kernel> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
Graph dag(kernel_list.size());
//First we build a map from an index in the original instruction list
//to a vertex in the 'dag'
map<int,Vertex> instr2vertex;
unsigned int k=0;
BOOST_FOREACH(Vertex v, vertices(dag))
{
const vector<bh_instruction> &kernel = kernel_list[k].instr_list();
dag[v] = kernel_list[k];
for(unsigned int i=0; i<kernel.size(); ++i)
{
int instr_index = index_map.at(make_pair(k,i));
instr2vertex.insert(pair<int,Vertex>(instr_index,v));
}
++k;
}
//Then we add edges to the 'dag' for each dependency in the original
//instruction list
for(unsigned int i=0; i<instr_list.size(); ++i)
{
Vertex v = instr2vertex[i];
for(unsigned int j=0; j<i; ++j)//We may depend on any previous instruction
{
if(bh_instr_dependency(&instr_list[i], &instr_list[j]))
{
if(instr2vertex[j] != v)
add_edge(instr2vertex[j], v, dag);
}
}
}
//Finally we check for cycles between the kernel dependencies
vector<Vertex> topological_order;
try
{
//TODO: topological sort is an efficient method for finding cycles,
//but we should avoid allocating a vector
topological_sort(dag, back_inserter(topological_order));
return true;
}
catch (const not_a_dag &e)
{
cout << "Writing the failed kernel list: check_kernel_cycles-fail.dot" << endl;
bh_dag_pprint(dag, "check_kernel_cycles-fail.dot");
return false;
}
}
/* Add an instruction to the kernel
*
* @instr The instruction to add
* @return The boolean answer
*/
void bh_ir_kernel::add_instr(const bh_instruction &instr)
{
if(instr.opcode == BH_DISCARD)
{
const bh_base *base = instr.operand[0].base;
for(vector<bh_view>::iterator it=outputs.begin(); it != outputs.end(); ++it)
{
if(base == it->base)
{
temps.push_back(base);
outputs.erase(it);
break;
}
}
}
else if(instr.opcode != BH_FREE)
{
{
bool duplicates = false;
const bh_view &v = instr.operand[0];
BOOST_FOREACH(const bh_view &i, outputs)
{
if(bh_view_aligned(&v, &i))
{
duplicates = true;
break;
}
}
if(!duplicates)
outputs.push_back(v);
}
const int nop = bh_operands(instr.opcode);
for(int i=1; i<nop; ++i)
{
const bh_view &v = instr.operand[i];
if(bh_is_constant(&v))
continue;
bool duplicates = false;
BOOST_FOREACH(const bh_view &i, inputs)
{
if(bh_view_aligned(&v, &i))
{
duplicates = true;
break;
}
}
if(duplicates)
continue;
bool local_source = false;
BOOST_FOREACH(const bh_instruction &i, instrs)
{
if(bh_view_aligned(&v, &i.operand[0]))
{
local_source = true;
break;
}
}
if(!local_source)
inputs.push_back(v);
}
}
instrs.push_back(instr);
};
/* Determines whether this kernel depends on 'other',
* which is true when:
* 'other' writes to an array that 'this' access
* or
* 'this' writes to an array that 'other' access
*
* @other The other kernel
* @return The boolean answer
*/
bool bh_ir_kernel::dependency(const bh_ir_kernel &other) const
{
BOOST_FOREACH(const bh_instruction &i, instr_list())
{
BOOST_FOREACH(const bh_instruction &o, other.instr_list())
{
if(bh_instr_dependency(&i, &o))
return true;
}
}
return false;
}
/* Determines whether it is legal to fuse with the kernel
*
* @other The other kernel
* @return The boolean answer
*/
bool bh_ir_kernel::fusible(const bh_ir_kernel &other) const
{
BOOST_FOREACH(const bh_instruction &a, instr_list())
{
BOOST_FOREACH(const bh_instruction &b, other.instr_list())
{
if(not bh_instr_fusible(&a, &b))
return false;
}
}
return true;
}
/* Determines whether it is legal to fuse with the instruction
*
* @instr The instruction
* @return The boolean answer
*/
bool bh_ir_kernel::fusible(const bh_instruction &instr) const
{
BOOST_FOREACH(const bh_instruction &i, instr_list())
{
if(not bh_instr_fusible(&i, &instr))
return false;
}
return true;
}
/* Determines whether it is legal to fuse with the instruction
* without changing this kernel's dependencies.
*
* @instr The instruction
* @return The boolean answer
*/
bool bh_ir_kernel::fusible_gently(const bh_instruction &instr) const
{
if(bh_opcode_is_system(instr.opcode))
return true;
//Check that 'instr' is fusible with least one existing instruction
BOOST_FOREACH(const bh_instruction &i, instr_list())
{
if(bh_opcode_is_system(i.opcode))
continue;
if(bh_instr_fusible_gently(&instr, &i))
return true;
}
return false;
}
/* Determines whether it is legal to fuse with the kernel without
* changing this kernel's dependencies.
*
* @other The other kernel
* @return The boolean answer
*/
bool bh_ir_kernel::fusible_gently(const bh_ir_kernel &other) const
{
BOOST_FOREACH(const bh_instruction &i, other.instr_list())
{
if(not fusible_gently(i))
return false;
}
return true;
}
<|endoftext|> |
<commit_before>#include "CodeGen_PTX_Dev.h"
#include "IROperator.h"
#include <iostream>
#include "buffer_t.h"
#include "IRPrinter.h"
#include "IRMatch.h"
#include "Debug.h"
#include "Util.h"
#include "Var.h"
#include "Param.h"
#include "Target.h"
#include "integer_division_table.h"
#include "LLVM_Headers.h"
// This is declared in NVPTX.h, which is not exported. Ugly, but seems better than
// hardcoding a path to the .h file.
#if WITH_PTX
namespace llvm { ModulePass *createNVVMReflectPass(const StringMap<int>& Mapping); }
#endif
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using namespace llvm;
CodeGen_PTX_Dev::CodeGen_PTX_Dev() : CodeGen() {
#if !(WITH_PTX)
assert(false && "ptx not enabled for this build of Halide.");
#endif
assert(llvm_NVPTX_enabled && "llvm build not configured with nvptx target enabled.");
}
void CodeGen_PTX_Dev::compile(Stmt stmt, std::string name, const std::vector<Argument> &args) {
debug(2) << "In CodeGen_PTX_Dev::compile\n";
// Now deduce the types of the arguments to our function
vector<llvm::Type *> arg_types(args.size());
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer) {
arg_types[i] = llvm_type_of(UInt(8))->getPointerTo();
} else {
arg_types[i] = llvm_type_of(args[i].type);
}
}
// Make our function
function_name = name;
FunctionType *func_t = FunctionType::get(void_t, arg_types, false);
function = llvm::Function::Create(func_t, llvm::Function::ExternalLinkage, name, module);
// Mark the buffer args as no alias
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer) {
function->setDoesNotAlias(i+1);
}
}
// Make the initial basic block
entry_block = BasicBlock::Create(*context, "entry", function);
builder->SetInsertPoint(entry_block);
// Put the arguments in the symbol table
vector<string> arg_sym_names;
{
size_t i = 0;
for (llvm::Function::arg_iterator iter = function->arg_begin();
iter != function->arg_end();
iter++) {
string arg_sym_name = args[i].name;
if (args[i].is_buffer) {
// HACK: codegen expects a load from foo to use base
// address 'foo.host', so we store the device pointer
// as foo.host in this scope.
arg_sym_name += ".host";
}
sym_push(arg_sym_name, iter);
iter->setName(arg_sym_name);
arg_sym_names.push_back(arg_sym_name);
i++;
}
}
// We won't end the entry block yet, because we'll want to add
// some allocas to it later if there are local allocations. Start
// a new block to put all the code.
BasicBlock *body_block = BasicBlock::Create(*context, "body", function);
builder->SetInsertPoint(body_block);
debug(1) << "Generating llvm bitcode for kernel...\n";
// Ok, we have a module, function, context, and a builder
// pointing at a brand new basic block. We're good to go.
stmt.accept(this);
// Now we need to end the function
builder->CreateRetVoid();
// Make the entry block point to the body block
builder->SetInsertPoint(entry_block);
builder->CreateBr(body_block);
// Add the nvvm annotation that it is a kernel function.
MDNode *mdNode = MDNode::get(*context, vec<Value *>(function,
MDString::get(*context, "kernel"),
ConstantInt::get(i32, 1)));
module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(mdNode);
// Now verify the function is ok
verifyFunction(*function);
// Finally, verify the module is ok
verifyModule(*module);
debug(2) << "Done generating llvm bitcode for PTX\n";
// Clear the symbol table
for (size_t i = 0; i < arg_sym_names.size(); i++) {
sym_pop(arg_sym_names[i]);
}
}
void CodeGen_PTX_Dev::init_module() {
CodeGen::init_module();
#if WITH_PTX
module = get_initial_module_for_ptx_device(context);
#endif
owns_module = true;
}
string CodeGen_PTX_Dev::simt_intrinsic(const string &name) {
if (ends_with(name, ".threadidx")) {
return "llvm.nvvm.read.ptx.sreg.tid.x";
} else if (ends_with(name, ".threadidy")) {
return "llvm.nvvm.read.ptx.sreg.tid.y";
} else if (ends_with(name, ".threadidz")) {
return "llvm.nvvm.read.ptx.sreg.tid.z";
} else if (ends_with(name, ".threadidw")) {
return "llvm.nvvm.read.ptx.sreg.tid.w";
} else if (ends_with(name, ".blockidx")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.x";
} else if (ends_with(name, ".blockidy")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.y";
} else if (ends_with(name, ".blockidz")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.z";
} else if (ends_with(name, ".blockidw")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.w";
}
assert(false && "simt_intrinsic called on bad variable name");
return "";
}
void CodeGen_PTX_Dev::visit(const For *loop) {
if (is_gpu_var(loop->name)) {
debug(2) << "Dropping loop " << loop->name << " (" << loop->min << ", " << loop->extent << ")\n";
assert(loop->for_type == For::Parallel && "kernel loop must be parallel");
Expr simt_idx = Call::make(Int(32), simt_intrinsic(loop->name), std::vector<Expr>(), Call::Extern);
Expr loop_var = loop->min + simt_idx;
Expr cond = simt_idx < loop->extent;
debug(3) << "for -> if (" << cond << ")\n";
BasicBlock *loop_bb = BasicBlock::Create(*context, loop->name + "_loop", function);
BasicBlock *after_bb = BasicBlock::Create(*context, loop->name + "_after_loop", function);
builder->CreateCondBr(codegen(cond), loop_bb, after_bb);
builder->SetInsertPoint(loop_bb);
sym_push(loop->name, codegen(loop_var));
codegen(loop->body);
sym_pop(loop->name);
builder->CreateBr(after_bb);
builder->SetInsertPoint(after_bb);
} else {
CodeGen::visit(loop);
}
}
void CodeGen_PTX_Dev::visit(const Pipeline *n) {
n->produce.accept(this);
// Grab the syncthreads intrinsic, or declare it if it doesn't exist yet
llvm::Function *syncthreads = module->getFunction("llvm.nvvm.barrier0");
if (!syncthreads) {
FunctionType *func_t = FunctionType::get(llvm::Type::getVoidTy(*context), vector<llvm::Type *>(), false);
syncthreads = llvm::Function::Create(func_t, llvm::Function::ExternalLinkage, "llvm.nvvm.barrier0", module);
syncthreads->setCallingConv(CallingConv::C);
debug(2) << "Declaring syncthreads intrinsic\n";
}
if (n->update.defined()) {
// If we're producing into shared or global memory we need a
// syncthreads before continuing.
builder->CreateCall(syncthreads, std::vector<Value *>());
n->update.accept(this);
}
builder->CreateCall(syncthreads, std::vector<Value *>());
n->consume.accept(this);
}
void CodeGen_PTX_Dev::visit(const Allocate *alloc) {
debug(1) << "Allocate " << alloc->name << " on device\n";
llvm::Type *llvm_type = llvm_type_of(alloc->type);
string allocation_name = alloc->name + ".host";
debug(3) << "Pushing allocation called " << allocation_name << " onto the symbol table\n";
// If this is a shared allocation, there should already be a
// pointer into shared memory in the symbol table.
Value *ptr;
Value *offset = sym_get(alloc->name + ".shared_mem", false);
if (offset) {
// Bit-cast it to a shared memory pointer (address-space 3 is shared memory)
ptr = builder->CreateIntToPtr(offset, PointerType::get(llvm_type, 3));
} else {
// Otherwise jump back to the entry and generate an
// alloca. Note that by jumping back we're rendering any
// expression we carry back meaningless, so we had better only
// be dealing with constants here.
const IntImm *size = alloc->size.as<IntImm>();
assert(size && "Only fixed-size allocations are supported on the gpu. Try storing into shared memory instead.");
BasicBlock *here = builder->GetInsertBlock();
builder->SetInsertPoint(entry_block);
ptr = builder->CreateAlloca(llvm_type_of(alloc->type), ConstantInt::get(i32, size->value));
builder->SetInsertPoint(here);
}
sym_push(allocation_name, ptr);
codegen(alloc->body);
}
void CodeGen_PTX_Dev::visit(const Free *f) {
sym_pop(f->name + ".host");
}
string CodeGen_PTX_Dev::march() const {
return "nvptx64";
}
string CodeGen_PTX_Dev::mcpu() const {
return "sm_20";
}
string CodeGen_PTX_Dev::mattrs() const {
return "";
}
bool CodeGen_PTX_Dev::use_soft_float_abi() const {
return false;
}
vector<char> CodeGen_PTX_Dev::compile_to_src() {
#if WITH_PTX
debug(2) << "In CodeGen_PTX_Dev::compile_to_src";
optimize_module();
// DISABLED - hooked in here to force PrintBeforeAll option - seems to be the only way?
/*char* argv[] = { "llc", "-print-before-all" };*/
/*int argc = sizeof(argv)/sizeof(char*);*/
/*cl::ParseCommandLineOptions(argc, argv, "Halide PTX internal compiler\n");*/
// Set up TargetTriple
module->setTargetTriple(Triple::normalize(march()+"--"));
Triple TheTriple(module->getTargetTriple());
// Allocate target machine
const std::string MArch = march();
const std::string MCPU = mcpu();
const llvm::Target* TheTarget = 0;
std::string errStr;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), errStr);
assert(TheTarget);
TargetOptions Options;
Options.LessPreciseFPMADOption = true;
Options.PrintMachineCode = false;
Options.NoFramePointerElim = false;
//Options.NoExcessFPPrecision = false;
Options.AllowFPOpFusion = FPOpFusion::Fast;
Options.UnsafeFPMath = true;
Options.NoInfsFPMath = false;
Options.NoNaNsFPMath = false;
Options.HonorSignDependentRoundingFPMathOption = false;
Options.UseSoftFloat = false;
/* if (FloatABIForCalls != FloatABI::Default) */
/* Options.FloatABIType = FloatABIForCalls; */
Options.NoZerosInBSS = false;
#if defined(LLVM_VERSION_MINOR) && LLVM_VERSION_MINOR < 3
Options.JITExceptionHandling = false;
#endif
Options.JITEmitDebugInfo = false;
Options.JITEmitDebugInfoToDisk = false;
Options.GuaranteedTailCallOpt = false;
Options.StackAlignmentOverride = 0;
// Options.DisableJumpTables = false;
Options.TrapFuncName = "";
Options.EnableSegmentedStacks = false;
CodeGenOpt::Level OLvl = CodeGenOpt::Aggressive;
const std::string FeaturesStr = "";
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
MCPU, FeaturesStr, Options,
llvm::Reloc::Default,
llvm::CodeModel::Default,
OLvl));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Set up passes
PassManager PM;
TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
PM.add(TLI);
if (target.get()) {
#if defined(LLVM_VERSION_MINOR) && LLVM_VERSION_MINOR < 3
PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
target->getVectorTargetTransformInfo()));
#else
target->addAnalysisPasses(PM);
#endif
}
// Add the target data from the target machine, if it exists, or the module.
if (const DataLayout *TD = Target.getDataLayout())
PM.add(new DataLayout(*TD));
else
PM.add(new DataLayout(module));
// NVidia's libdevice library uses a __nvvm_reflect to choose
// how to handle denormalized numbers. (The pass replaces calls
// to __nvvm_reflect with a constant via a map lookup. The inliner
// pass then resolves these situations to fast code, often a single
// instruction per decision point.)
//
// The default is (more) IEEE like handling. FTZ mode flushes them
// to zero. (This may only apply to single-precision.)
//
// The libdevice documentation covers other options for math accuracy
// such as replacing division with multiply by the reciprocal and
// use of fused-multiply-add, but they do not seem to be controlled
// by this __nvvvm_reflect mechanism and may be flags to earlier compiler
// passes.
#define kDefaultDenorms 0
#define kFTZDenorms 1
StringMap<int> reflect_mapping;
reflect_mapping[StringRef("__CUDA_FTZ")] = kFTZDenorms;
PM.add(createNVVMReflectPass(reflect_mapping));
// Inlining functions is essential to PTX
PM.add(createAlwaysInlinerPass());
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
// Output string stream
std::string outstr;
raw_string_ostream outs(outstr);
formatted_raw_ostream ostream(outs);
// Ask the target to add backend passes as necessary.
bool fail = Target.addPassesToEmitFile(PM, ostream,
TargetMachine::CGFT_AssemblyFile,
true);
if (fail) {
debug(0) << "Failed to set up passes to emit PTX source\n";
assert(false);
}
PM.run(*module);
ostream.flush();
if (debug::debug_level >= 2) {
module->dump();
}
debug(2) << "Done with CodeGen_PTX_Dev::compile_to_src";
string str = outs.str();
vector<char> buffer(str.begin(), str.end());
buffer.push_back(0);
return buffer;
#else // WITH_PTX
vector<char> empty();
return empty();
#endif
}
string CodeGen_PTX_Dev::get_current_kernel_name() {
return function->getName();
}
void CodeGen_PTX_Dev::dump() {
module->dump();
}
}}
<commit_msg>Fixed linker errors regarding empty() 'function'<commit_after>#include "CodeGen_PTX_Dev.h"
#include "IROperator.h"
#include <iostream>
#include "buffer_t.h"
#include "IRPrinter.h"
#include "IRMatch.h"
#include "Debug.h"
#include "Util.h"
#include "Var.h"
#include "Param.h"
#include "Target.h"
#include "integer_division_table.h"
#include "LLVM_Headers.h"
// This is declared in NVPTX.h, which is not exported. Ugly, but seems better than
// hardcoding a path to the .h file.
#if WITH_PTX
namespace llvm { ModulePass *createNVVMReflectPass(const StringMap<int>& Mapping); }
#endif
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using namespace llvm;
CodeGen_PTX_Dev::CodeGen_PTX_Dev() : CodeGen() {
#if !(WITH_PTX)
assert(false && "ptx not enabled for this build of Halide.");
#endif
assert(llvm_NVPTX_enabled && "llvm build not configured with nvptx target enabled.");
}
void CodeGen_PTX_Dev::compile(Stmt stmt, std::string name, const std::vector<Argument> &args) {
debug(2) << "In CodeGen_PTX_Dev::compile\n";
// Now deduce the types of the arguments to our function
vector<llvm::Type *> arg_types(args.size());
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer) {
arg_types[i] = llvm_type_of(UInt(8))->getPointerTo();
} else {
arg_types[i] = llvm_type_of(args[i].type);
}
}
// Make our function
function_name = name;
FunctionType *func_t = FunctionType::get(void_t, arg_types, false);
function = llvm::Function::Create(func_t, llvm::Function::ExternalLinkage, name, module);
// Mark the buffer args as no alias
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer) {
function->setDoesNotAlias(i+1);
}
}
// Make the initial basic block
entry_block = BasicBlock::Create(*context, "entry", function);
builder->SetInsertPoint(entry_block);
// Put the arguments in the symbol table
vector<string> arg_sym_names;
{
size_t i = 0;
for (llvm::Function::arg_iterator iter = function->arg_begin();
iter != function->arg_end();
iter++) {
string arg_sym_name = args[i].name;
if (args[i].is_buffer) {
// HACK: codegen expects a load from foo to use base
// address 'foo.host', so we store the device pointer
// as foo.host in this scope.
arg_sym_name += ".host";
}
sym_push(arg_sym_name, iter);
iter->setName(arg_sym_name);
arg_sym_names.push_back(arg_sym_name);
i++;
}
}
// We won't end the entry block yet, because we'll want to add
// some allocas to it later if there are local allocations. Start
// a new block to put all the code.
BasicBlock *body_block = BasicBlock::Create(*context, "body", function);
builder->SetInsertPoint(body_block);
debug(1) << "Generating llvm bitcode for kernel...\n";
// Ok, we have a module, function, context, and a builder
// pointing at a brand new basic block. We're good to go.
stmt.accept(this);
// Now we need to end the function
builder->CreateRetVoid();
// Make the entry block point to the body block
builder->SetInsertPoint(entry_block);
builder->CreateBr(body_block);
// Add the nvvm annotation that it is a kernel function.
MDNode *mdNode = MDNode::get(*context, vec<Value *>(function,
MDString::get(*context, "kernel"),
ConstantInt::get(i32, 1)));
module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(mdNode);
// Now verify the function is ok
verifyFunction(*function);
// Finally, verify the module is ok
verifyModule(*module);
debug(2) << "Done generating llvm bitcode for PTX\n";
// Clear the symbol table
for (size_t i = 0; i < arg_sym_names.size(); i++) {
sym_pop(arg_sym_names[i]);
}
}
void CodeGen_PTX_Dev::init_module() {
CodeGen::init_module();
#if WITH_PTX
module = get_initial_module_for_ptx_device(context);
#endif
owns_module = true;
}
string CodeGen_PTX_Dev::simt_intrinsic(const string &name) {
if (ends_with(name, ".threadidx")) {
return "llvm.nvvm.read.ptx.sreg.tid.x";
} else if (ends_with(name, ".threadidy")) {
return "llvm.nvvm.read.ptx.sreg.tid.y";
} else if (ends_with(name, ".threadidz")) {
return "llvm.nvvm.read.ptx.sreg.tid.z";
} else if (ends_with(name, ".threadidw")) {
return "llvm.nvvm.read.ptx.sreg.tid.w";
} else if (ends_with(name, ".blockidx")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.x";
} else if (ends_with(name, ".blockidy")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.y";
} else if (ends_with(name, ".blockidz")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.z";
} else if (ends_with(name, ".blockidw")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.w";
}
assert(false && "simt_intrinsic called on bad variable name");
return "";
}
void CodeGen_PTX_Dev::visit(const For *loop) {
if (is_gpu_var(loop->name)) {
debug(2) << "Dropping loop " << loop->name << " (" << loop->min << ", " << loop->extent << ")\n";
assert(loop->for_type == For::Parallel && "kernel loop must be parallel");
Expr simt_idx = Call::make(Int(32), simt_intrinsic(loop->name), std::vector<Expr>(), Call::Extern);
Expr loop_var = loop->min + simt_idx;
Expr cond = simt_idx < loop->extent;
debug(3) << "for -> if (" << cond << ")\n";
BasicBlock *loop_bb = BasicBlock::Create(*context, loop->name + "_loop", function);
BasicBlock *after_bb = BasicBlock::Create(*context, loop->name + "_after_loop", function);
builder->CreateCondBr(codegen(cond), loop_bb, after_bb);
builder->SetInsertPoint(loop_bb);
sym_push(loop->name, codegen(loop_var));
codegen(loop->body);
sym_pop(loop->name);
builder->CreateBr(after_bb);
builder->SetInsertPoint(after_bb);
} else {
CodeGen::visit(loop);
}
}
void CodeGen_PTX_Dev::visit(const Pipeline *n) {
n->produce.accept(this);
// Grab the syncthreads intrinsic, or declare it if it doesn't exist yet
llvm::Function *syncthreads = module->getFunction("llvm.nvvm.barrier0");
if (!syncthreads) {
FunctionType *func_t = FunctionType::get(llvm::Type::getVoidTy(*context), vector<llvm::Type *>(), false);
syncthreads = llvm::Function::Create(func_t, llvm::Function::ExternalLinkage, "llvm.nvvm.barrier0", module);
syncthreads->setCallingConv(CallingConv::C);
debug(2) << "Declaring syncthreads intrinsic\n";
}
if (n->update.defined()) {
// If we're producing into shared or global memory we need a
// syncthreads before continuing.
builder->CreateCall(syncthreads, std::vector<Value *>());
n->update.accept(this);
}
builder->CreateCall(syncthreads, std::vector<Value *>());
n->consume.accept(this);
}
void CodeGen_PTX_Dev::visit(const Allocate *alloc) {
debug(1) << "Allocate " << alloc->name << " on device\n";
llvm::Type *llvm_type = llvm_type_of(alloc->type);
string allocation_name = alloc->name + ".host";
debug(3) << "Pushing allocation called " << allocation_name << " onto the symbol table\n";
// If this is a shared allocation, there should already be a
// pointer into shared memory in the symbol table.
Value *ptr;
Value *offset = sym_get(alloc->name + ".shared_mem", false);
if (offset) {
// Bit-cast it to a shared memory pointer (address-space 3 is shared memory)
ptr = builder->CreateIntToPtr(offset, PointerType::get(llvm_type, 3));
} else {
// Otherwise jump back to the entry and generate an
// alloca. Note that by jumping back we're rendering any
// expression we carry back meaningless, so we had better only
// be dealing with constants here.
const IntImm *size = alloc->size.as<IntImm>();
assert(size && "Only fixed-size allocations are supported on the gpu. Try storing into shared memory instead.");
BasicBlock *here = builder->GetInsertBlock();
builder->SetInsertPoint(entry_block);
ptr = builder->CreateAlloca(llvm_type_of(alloc->type), ConstantInt::get(i32, size->value));
builder->SetInsertPoint(here);
}
sym_push(allocation_name, ptr);
codegen(alloc->body);
}
void CodeGen_PTX_Dev::visit(const Free *f) {
sym_pop(f->name + ".host");
}
string CodeGen_PTX_Dev::march() const {
return "nvptx64";
}
string CodeGen_PTX_Dev::mcpu() const {
return "sm_20";
}
string CodeGen_PTX_Dev::mattrs() const {
return "";
}
bool CodeGen_PTX_Dev::use_soft_float_abi() const {
return false;
}
vector<char> CodeGen_PTX_Dev::compile_to_src() {
#if WITH_PTX
debug(2) << "In CodeGen_PTX_Dev::compile_to_src";
optimize_module();
// DISABLED - hooked in here to force PrintBeforeAll option - seems to be the only way?
/*char* argv[] = { "llc", "-print-before-all" };*/
/*int argc = sizeof(argv)/sizeof(char*);*/
/*cl::ParseCommandLineOptions(argc, argv, "Halide PTX internal compiler\n");*/
// Set up TargetTriple
module->setTargetTriple(Triple::normalize(march()+"--"));
Triple TheTriple(module->getTargetTriple());
// Allocate target machine
const std::string MArch = march();
const std::string MCPU = mcpu();
const llvm::Target* TheTarget = 0;
std::string errStr;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), errStr);
assert(TheTarget);
TargetOptions Options;
Options.LessPreciseFPMADOption = true;
Options.PrintMachineCode = false;
Options.NoFramePointerElim = false;
//Options.NoExcessFPPrecision = false;
Options.AllowFPOpFusion = FPOpFusion::Fast;
Options.UnsafeFPMath = true;
Options.NoInfsFPMath = false;
Options.NoNaNsFPMath = false;
Options.HonorSignDependentRoundingFPMathOption = false;
Options.UseSoftFloat = false;
/* if (FloatABIForCalls != FloatABI::Default) */
/* Options.FloatABIType = FloatABIForCalls; */
Options.NoZerosInBSS = false;
#if defined(LLVM_VERSION_MINOR) && LLVM_VERSION_MINOR < 3
Options.JITExceptionHandling = false;
#endif
Options.JITEmitDebugInfo = false;
Options.JITEmitDebugInfoToDisk = false;
Options.GuaranteedTailCallOpt = false;
Options.StackAlignmentOverride = 0;
// Options.DisableJumpTables = false;
Options.TrapFuncName = "";
Options.EnableSegmentedStacks = false;
CodeGenOpt::Level OLvl = CodeGenOpt::Aggressive;
const std::string FeaturesStr = "";
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
MCPU, FeaturesStr, Options,
llvm::Reloc::Default,
llvm::CodeModel::Default,
OLvl));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Set up passes
PassManager PM;
TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
PM.add(TLI);
if (target.get()) {
#if defined(LLVM_VERSION_MINOR) && LLVM_VERSION_MINOR < 3
PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
target->getVectorTargetTransformInfo()));
#else
target->addAnalysisPasses(PM);
#endif
}
// Add the target data from the target machine, if it exists, or the module.
if (const DataLayout *TD = Target.getDataLayout())
PM.add(new DataLayout(*TD));
else
PM.add(new DataLayout(module));
// NVidia's libdevice library uses a __nvvm_reflect to choose
// how to handle denormalized numbers. (The pass replaces calls
// to __nvvm_reflect with a constant via a map lookup. The inliner
// pass then resolves these situations to fast code, often a single
// instruction per decision point.)
//
// The default is (more) IEEE like handling. FTZ mode flushes them
// to zero. (This may only apply to single-precision.)
//
// The libdevice documentation covers other options for math accuracy
// such as replacing division with multiply by the reciprocal and
// use of fused-multiply-add, but they do not seem to be controlled
// by this __nvvvm_reflect mechanism and may be flags to earlier compiler
// passes.
#define kDefaultDenorms 0
#define kFTZDenorms 1
StringMap<int> reflect_mapping;
reflect_mapping[StringRef("__CUDA_FTZ")] = kFTZDenorms;
PM.add(createNVVMReflectPass(reflect_mapping));
// Inlining functions is essential to PTX
PM.add(createAlwaysInlinerPass());
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
// Output string stream
std::string outstr;
raw_string_ostream outs(outstr);
formatted_raw_ostream ostream(outs);
// Ask the target to add backend passes as necessary.
bool fail = Target.addPassesToEmitFile(PM, ostream,
TargetMachine::CGFT_AssemblyFile,
true);
if (fail) {
debug(0) << "Failed to set up passes to emit PTX source\n";
assert(false);
}
PM.run(*module);
ostream.flush();
if (debug::debug_level >= 2) {
module->dump();
}
debug(2) << "Done with CodeGen_PTX_Dev::compile_to_src";
string str = outs.str();
vector<char> buffer(str.begin(), str.end());
#else // WITH_PTX
vector<char> buffer;
#endif
buffer.push_back(0);
return buffer;
}
string CodeGen_PTX_Dev::get_current_kernel_name() {
return function->getName();
}
void CodeGen_PTX_Dev::dump() {
module->dump();
}
}}
<|endoftext|> |
<commit_before>#include <iostream>
#include <typeinfo>
#include <vector>
#include <tuple>
template<typename T, typename... Ts>
struct MultiVectorBase
{
using Data = decltype(
std::tuple_cat(
std::tuple<std::vector<T>>(),
std::declval<typename MultiVectorBase<Ts...>::Data>()
)
);
};
template<typename T>
struct MultiVectorBase<T>
{
using Data = std::tuple<std::vector<T>>;
};
template<size_t N, size_t Max>
struct Pack
{
template<typename... Ts, typename... Vs>
static void DoPack(std::tuple<Ts...>& tpl, const std::tuple<Vs...>& vals)
{
std::get<N>(tpl).push_back(std::get<N>(vals));
Pack<N+1, Max>::DoPack(tpl, vals);
}
};
template<size_t Max>
struct Pack<Max, Max>
{
template<typename... Ts, typename... Vs>
static void DoPack(std::tuple<Ts...>& tpl, const std::tuple<Vs...>& vals)
{
}
};
template<typename... Ts>
struct MultiVector
{
typename MultiVectorBase<Ts...>::Data data_;
template<typename... Vs>
void push_back(const Vs&... vs)
{
static_assert(sizeof...(Ts)==sizeof...(Vs), "Argument count mismatch");
Pack<0,sizeof...(Ts)>::DoPack(data_, std::make_tuple(vs...));
}
};
template<size_t N, typename... Ts>
const auto& get(MultiVector<Ts...>& mv)
{
return std::get<N>(mv.data_);
}
int main(int argc, char* argv[])
{
MultiVector<int,double,char> mv;
mv.push_back(1,2.718281,'e');
mv.push_back(2,3.14159,'p');
mv.push_back(3,2.718281,'e');
mv.push_back(4,3.14159,'p');
const std::vector<int>& ints = get<0>(mv);
const std::vector<double>& dbls = get<1>(mv);
const std::vector<char>& chars = get<2>(mv);
std::copy(ints.begin(),ints.end(),std::ostream_iterator<int>(std::cout," "));
std::cout << '\n';
std::copy(dbls.begin(),dbls.end(),std::ostream_iterator<double>(std::cout," "));
std::cout << '\n';
std::copy(chars.begin(),chars.end(),std::ostream_iterator<char>(std::cout," "));
std::cout << '\n';
}
<commit_msg>Added accessor and const vector accessor<commit_after>#include <iostream>
#include <typeinfo>
#include <vector>
#include <tuple>
template<typename T, typename... Ts>
struct MultiVectorBase
{
using Data = decltype(
std::tuple_cat(
std::tuple<std::vector<T>>(),
std::declval<typename MultiVectorBase<Ts...>::Data>()
)
);
};
template<typename T>
struct MultiVectorBase<T>
{
using Data = std::tuple<std::vector<T>>;
};
template<size_t N, size_t Max>
struct PushBack
{
template<typename... Ts, typename... Vs>
static void DoPushBack(std::tuple<Ts...>& tpl, const std::tuple<Vs...>& vals)
{
std::get<N>(tpl).push_back(std::get<N>(vals));
PushBack<N+1, Max>::DoPushBack(tpl, vals);
}
};
template<size_t Max>
struct PushBack<Max, Max>
{
template<typename... Ts, typename... Vs>
static void DoPushBack(std::tuple<Ts...>& tpl, const std::tuple<Vs...>& vals)
{
}
};
template<size_t N, size_t Max>
struct BuildReferenceTuple
{
template<typename... Ts>
static auto DoBuildReferenceTuple(std::tuple<Ts...>& tpl, size_t i)
{
return std::tuple_cat(std::forward_as_tuple(std::get<N>(tpl)[i]),
BuildReferenceTuple<N+1,Max>::DoBuildReferenceTuple(tpl,i));
}
};
template<size_t Max>
struct BuildReferenceTuple<Max, Max>
{
template<typename... Ts>
static auto DoBuildReferenceTuple(std::tuple<Ts...>& tpl, size_t i)
{
return std::make_tuple();
}
};
template<size_t N, size_t Max>
struct BuildConstReferenceTuple
{
template<typename... Ts>
static auto DoBuildConstReferenceTuple(const std::tuple<Ts...>& tpl, size_t i)
{
return std::tuple_cat(std::forward_as_tuple(std::get<N>(tpl)[i]),
BuildConstReferenceTuple<N+1,Max>::DoBuildReferenceTuple(tpl,i));
}
};
template<size_t Max>
struct BuildConstReferenceTuple<Max, Max>
{
template<typename... Ts>
static auto DoBuildConstReferenceTuple(const std::tuple<Ts...>& tpl, size_t i)
{
return std::make_tuple();
}
};
template<typename... Ts>
struct MultiVector
{
typename MultiVectorBase<Ts...>::Data data_;
template<typename... Vs>
void push_back(const Vs&... vs)
{
static_assert(sizeof...(Ts)==sizeof...(Vs), "Argument count mismatch");
PushBack<0,sizeof...(Ts)>::DoPushBack(data_, std::make_tuple(vs...));
}
std::tuple<Ts&...> operator[](size_t i)
{
return BuildReferenceTuple<0,sizeof...(Ts)>::DoBuildReferenceTuple(data_, i);
}
std::tuple<const Ts&...> operator[](size_t i) const
{
return BuildConstReferenceTuple<0,sizeof...(Ts)>::DoBuildConstReferenceTuple(data_, i);
}
size_t size() const { return data_.size(); }
};
template<size_t N, typename... Ts>
auto& get(MultiVector<Ts...>& mv)
{
return std::get<N>(mv.data_);
}
template<size_t N, typename... Ts>
const auto& get(const MultiVector<Ts...>& mv)
{
return std::get<N>(mv.data_);
}
int main(int argc, char* argv[])
{
MultiVector<int,double,char> mv;
mv.push_back(1,2.718281,'e');
mv.push_back(2,3.14159,'p');
mv.push_back(3,4,'x');
mv.push_back(4,5,'y');
const std::vector<int>& ints = get<0>(mv);
const std::vector<double>& dbls = get<1>(mv);
const std::vector<char>& chars = get<2>(mv);
std::copy(ints.begin(),ints.end(),std::ostream_iterator<int>(std::cout," "));
std::cout << '\n';
std::copy(dbls.begin(),dbls.end(),std::ostream_iterator<double>(std::cout," "));
std::cout << '\n';
std::copy(chars.begin(),chars.end(),std::ostream_iterator<char>(std::cout," "));
std::cout << '\n';
auto x = mv[0];
std::get<0>(x)=99;
std::copy(ints.begin(),ints.end(),std::ostream_iterator<int>(std::cout," "));
std::cout << '\n';
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2011 Juergen Riegel <FreeCAD@juergen-riegel.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMessageBox>
# include <QApplication>
#include <Inventor/nodes/SoSwitch.h>
#endif
#include <Gui/Command.h>
#include <Gui/MDIView.h>
#include <Gui/Control.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Base/Exception.h>
#include <Mod/PartDesign/App/Body.h>
#include <Mod/PartDesign/App/Feature.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include "TaskFeatureParameters.h"
#include "ViewProvider.h"
#include "ViewProviderPy.h"
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProvider, PartGui::ViewProviderPart)
ViewProvider::ViewProvider()
:oldWb(""), oldTip(NULL), isSetTipIcon(false)
{
}
ViewProvider::~ViewProvider()
{
}
bool ViewProvider::doubleClicked(void)
{
PartDesign::Body* body = PartDesign::Body::findBodyOf(getObject());
// TODO May be move to setEdit()? (2015-07-26, Fat-Zer)
if (body != NULL) {
// Drop into insert mode so that the user doesn't see all the geometry that comes later in the tree
// Also, this way the user won't be tempted to use future geometry as external references for the sketch
oldTip = body->Tip.getValue();
if (oldTip != this->pcObject)
Gui::Command::doCommand(Gui::Command::Gui,"FreeCADGui.runCommand('PartDesign_MoveTip')");
else
oldTip = NULL;
} else {
oldTip = NULL;
}
try {
std::string Msg("Edit ");
Msg += this->pcObject->Label.getValue();
Gui::Command::openCommand(Msg.c_str());
Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().setEdit('%s',0)",
this->pcObject->getNameInDocument());
}
catch (const Base::Exception&) {
Gui::Command::abortCommand();
}
return true;
}
bool ViewProvider::setEdit(int ModNum)
{
if (ModNum == ViewProvider::Default ) {
// When double-clicking on the item for this feature the
// object unsets and sets its edit mode without closing
// the task panel
Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog();
TaskDlgFeatureParameters *featureDlg = qobject_cast<TaskDlgFeatureParameters *>(dlg);
// NOTE: if the dialog is not partDesigan dialog the featureDlg will be NULL
if (featureDlg && featureDlg->viewProvider() != this) {
featureDlg = 0; // another feature left open its task panel
}
if (dlg && !featureDlg) {
QMessageBox msgBox;
msgBox.setText(QObject::tr("A dialog is already open in the task panel"));
msgBox.setInformativeText(QObject::tr("Do you want to close this dialog?"));
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
int ret = msgBox.exec();
if (ret == QMessageBox::Yes) {
Gui::Control().reject();
} else {
return false;
}
}
// clear the selection (convenience)
Gui::Selection().clearSelection();
// always change to PartDesign WB, remember where we come from
oldWb = Gui::Command::assureWorkbench("PartDesignWorkbench");
// start the edit dialog if
if (!featureDlg) {
featureDlg = this->getEditDialog();
if (!featureDlg) { // Shouldn't generally happen
throw Base::Exception ("Failed to create new edit dialog.");
}
}
Gui::Control().showDialog(featureDlg);
return true;
} else {
return PartGui::ViewProviderPart::setEdit(ModNum);
}
}
TaskDlgFeatureParameters *ViewProvider::getEditDialog() {
throw Base::Exception("getEditDialog() not implemented");
}
void ViewProvider::unsetEdit(int ModNum)
{
// return to the WB we were in before editing the PartDesign feature
if (!oldWb.empty())
Gui::Command::assureWorkbench(oldWb.c_str());
if (ModNum == ViewProvider::Default) {
// when pressing ESC make sure to close the dialog
PartDesign::Body* activeBody = Gui::Application::Instance->activeView()->getActiveObject<PartDesign::Body*>(PDBODYKEY);
Gui::Control().closeDialog();
if ((activeBody != NULL) && (oldTip != NULL)) {
Gui::Selection().clearSelection();
Gui::Selection().addSelection(oldTip->getDocument()->getName(), oldTip->getNameInDocument());
Gui::Command::doCommand(Gui::Command::Gui,"FreeCADGui.runCommand('PartDesign_MoveTip')");
}
oldTip = NULL;
}
else {
PartGui::ViewProviderPart::unsetEdit(ModNum);
oldTip = NULL;
}
}
void ViewProvider::updateData(const App::Property* prop)
{
// TODO What's that? (2015-07-24, Fat-Zer)
if (prop->getTypeId() == Part::PropertyPartShape::getClassTypeId() &&
strcmp(prop->getName(),"AddSubShape") == 0) {
return;
}
inherited::updateData(prop);
}
void ViewProvider::onChanged(const App::Property* prop) {
//if the object is inside of a body we make sure it is the only visible one on activation
if(prop == &Visibility && Visibility.getValue()) {
Part::BodyBase* body = Part::BodyBase::findBodyOf(getObject());
if(body) {
//hide all features in the body other than this object
for(App::DocumentObject* obj : body->Group.getValues()) {
if(obj->isDerivedFrom(PartDesign::Feature::getClassTypeId()) && obj != getObject()) {
Gui::ViewProvider* vp = Gui::Application::Instance->activeDocument()->getViewProvider(obj);
if(!vp)
return;
Gui::ViewProviderDocumentObject* vpd = static_cast<ViewProviderDocumentObject*>(vp);
if(vpd && vpd->Visibility.getValue())
vpd->Visibility.setValue(false);
}
}
}
}
PartGui::ViewProviderPartExt::onChanged(prop);
}
void ViewProvider::setTipIcon(bool onoff) {
isSetTipIcon = onoff;
signalChangeIcon();
}
QIcon ViewProvider::getIcon(void) const
{
return mergeTip(Gui::BitmapFactory().pixmap(sPixmap));
}
QIcon ViewProvider::mergeTip(QIcon orig) const
{
if(isSetTipIcon) {
QPixmap px;
static const char * const feature_error_xpm[]={
"9 9 3 1",
". c None",
"# c #00ff00",
"a c #ffffff",
"...###...",
".##aaa##.",
".##aaa##.",
"###aaa###",
"##aaaaa##",
"##aaaaa##",
".##aaa##.",
".##aaa##.",
"...###..."};
px = QPixmap(feature_error_xpm);
QIcon icon_mod;
int w = QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize);
icon_mod.addPixmap(Gui::BitmapFactory().merge(orig.pixmap(w, w, QIcon::Normal, QIcon::Off),
px,Gui::BitmapFactoryInst::BottomRight), QIcon::Normal, QIcon::Off);
icon_mod.addPixmap(Gui::BitmapFactory().merge(orig.pixmap(w, w, QIcon::Normal, QIcon::On ),
px,Gui::BitmapFactoryInst::BottomRight), QIcon::Normal, QIcon::Off);
return icon_mod;
}
else
return orig;
}
bool ViewProvider::onDelete(const std::vector<std::string> &)
{
PartDesign::Feature* feature = static_cast<PartDesign::Feature*>(getObject());
App::DocumentObject* previousfeat = feature->BaseFeature.getValue();
// Visibility - we want:
// 1. If the visible object is not the one being deleted, we leave that one visible.
// 2. If the visible object is the one being deleted, we make the previous object visible.
if (isShow() && previousfeat && Gui::Application::Instance->getViewProvider(previousfeat)) {
Gui::Application::Instance->getViewProvider(previousfeat)->show();
}
// find surrounding features in the tree
Part::BodyBase* body = PartDesign::Body::findBodyOf(getObject());
if (body != NULL) {
// Deletion from the tree of a feature is handled by Document.removeObject, which has no clue
// about what a body is. Therefore, Bodies, although an "activable" container, know nothing
// about what happens at Document level with the features they contain.
//
// The Deletion command StdCmdDelete::activated, however does notify the viewprovider corresponding
// to the feature (not body) of the imminent deletion (before actually doing it).
//
// Consequently, the only way of notifying a body of the imminent deletion of one of its features
// so as to do the clean up required (moving basefeature references, tip management) is from the
// viewprovider, so we call it here.
//
// fixes (#3084)
Gui::Command::doCommand ( Gui::Command::Doc,"App.activeDocument().%s.removeObject(App.activeDocument().%s)",
body->getNameInDocument(), feature->getNameInDocument() );
}
return true;
}
void ViewProvider::setBodyMode(bool bodymode) {
std::vector<App::Property*> props;
getPropertyList(props);
auto vp = getBodyViewProvider();
if(!vp)
return;
for(App::Property* prop : props) {
//we keep visibility and selectibility per object
if(prop == &Visibility ||
prop == &Selectable)
continue;
//we hide only properties which are available in the body, not special ones
if(!vp->getPropertyByName(prop->getName()))
continue;
prop->setStatus(App::Property::Hidden, bodymode);
}
}
void ViewProvider::makeTemporaryVisible(bool onoff)
{
//make sure to not use the overridden versions, as they change properties
if (onoff) {
if (VisualTouched) {
updateVisual(static_cast<Part::Feature*>(getObject())->Shape.getValue());
}
Gui::ViewProvider::show();
}
else
Gui::ViewProvider::hide();
}
PyObject* ViewProvider::getPyObject()
{
if (!pyViewObject)
pyViewObject = new ViewProviderPy(this);
pyViewObject->IncRef();
return pyViewObject;
}
ViewProviderBody* ViewProvider::getBodyViewProvider() {
auto body = PartDesign::Body::findBodyOf(getObject());
auto doc = getDocument();
if(body && doc) {
auto vp = doc->getViewProvider(body);
if(vp && vp->isDerivedFrom(ViewProviderBody::getClassTypeId()))
return static_cast<ViewProviderBody*>(vp);
}
return nullptr;
}
namespace Gui {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(PartDesignGui::ViewProviderPython, PartDesignGui::ViewProvider);
/// @endcond
// explicit template instantiation
template class PartDesignGuiExport ViewProviderPythonFeatureT<PartDesignGui::ViewProvider>;
}
<commit_msg>make green for tip a bit darker<commit_after>/***************************************************************************
* Copyright (c) 2011 Juergen Riegel <FreeCAD@juergen-riegel.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMessageBox>
# include <QApplication>
#include <Inventor/nodes/SoSwitch.h>
#endif
#include <Gui/Command.h>
#include <Gui/MDIView.h>
#include <Gui/Control.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Base/Exception.h>
#include <Mod/PartDesign/App/Body.h>
#include <Mod/PartDesign/App/Feature.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include "TaskFeatureParameters.h"
#include "ViewProvider.h"
#include "ViewProviderPy.h"
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProvider, PartGui::ViewProviderPart)
ViewProvider::ViewProvider()
:oldWb(""), oldTip(NULL), isSetTipIcon(false)
{
}
ViewProvider::~ViewProvider()
{
}
bool ViewProvider::doubleClicked(void)
{
PartDesign::Body* body = PartDesign::Body::findBodyOf(getObject());
// TODO May be move to setEdit()? (2015-07-26, Fat-Zer)
if (body != NULL) {
// Drop into insert mode so that the user doesn't see all the geometry that comes later in the tree
// Also, this way the user won't be tempted to use future geometry as external references for the sketch
oldTip = body->Tip.getValue();
if (oldTip != this->pcObject)
Gui::Command::doCommand(Gui::Command::Gui,"FreeCADGui.runCommand('PartDesign_MoveTip')");
else
oldTip = NULL;
} else {
oldTip = NULL;
}
try {
std::string Msg("Edit ");
Msg += this->pcObject->Label.getValue();
Gui::Command::openCommand(Msg.c_str());
Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().setEdit('%s',0)",
this->pcObject->getNameInDocument());
}
catch (const Base::Exception&) {
Gui::Command::abortCommand();
}
return true;
}
bool ViewProvider::setEdit(int ModNum)
{
if (ModNum == ViewProvider::Default ) {
// When double-clicking on the item for this feature the
// object unsets and sets its edit mode without closing
// the task panel
Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog();
TaskDlgFeatureParameters *featureDlg = qobject_cast<TaskDlgFeatureParameters *>(dlg);
// NOTE: if the dialog is not partDesigan dialog the featureDlg will be NULL
if (featureDlg && featureDlg->viewProvider() != this) {
featureDlg = 0; // another feature left open its task panel
}
if (dlg && !featureDlg) {
QMessageBox msgBox;
msgBox.setText(QObject::tr("A dialog is already open in the task panel"));
msgBox.setInformativeText(QObject::tr("Do you want to close this dialog?"));
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
int ret = msgBox.exec();
if (ret == QMessageBox::Yes) {
Gui::Control().reject();
} else {
return false;
}
}
// clear the selection (convenience)
Gui::Selection().clearSelection();
// always change to PartDesign WB, remember where we come from
oldWb = Gui::Command::assureWorkbench("PartDesignWorkbench");
// start the edit dialog if
if (!featureDlg) {
featureDlg = this->getEditDialog();
if (!featureDlg) { // Shouldn't generally happen
throw Base::Exception ("Failed to create new edit dialog.");
}
}
Gui::Control().showDialog(featureDlg);
return true;
} else {
return PartGui::ViewProviderPart::setEdit(ModNum);
}
}
TaskDlgFeatureParameters *ViewProvider::getEditDialog() {
throw Base::Exception("getEditDialog() not implemented");
}
void ViewProvider::unsetEdit(int ModNum)
{
// return to the WB we were in before editing the PartDesign feature
if (!oldWb.empty())
Gui::Command::assureWorkbench(oldWb.c_str());
if (ModNum == ViewProvider::Default) {
// when pressing ESC make sure to close the dialog
PartDesign::Body* activeBody = Gui::Application::Instance->activeView()->getActiveObject<PartDesign::Body*>(PDBODYKEY);
Gui::Control().closeDialog();
if ((activeBody != NULL) && (oldTip != NULL)) {
Gui::Selection().clearSelection();
Gui::Selection().addSelection(oldTip->getDocument()->getName(), oldTip->getNameInDocument());
Gui::Command::doCommand(Gui::Command::Gui,"FreeCADGui.runCommand('PartDesign_MoveTip')");
}
oldTip = NULL;
}
else {
PartGui::ViewProviderPart::unsetEdit(ModNum);
oldTip = NULL;
}
}
void ViewProvider::updateData(const App::Property* prop)
{
// TODO What's that? (2015-07-24, Fat-Zer)
if (prop->getTypeId() == Part::PropertyPartShape::getClassTypeId() &&
strcmp(prop->getName(),"AddSubShape") == 0) {
return;
}
inherited::updateData(prop);
}
void ViewProvider::onChanged(const App::Property* prop) {
//if the object is inside of a body we make sure it is the only visible one on activation
if(prop == &Visibility && Visibility.getValue()) {
Part::BodyBase* body = Part::BodyBase::findBodyOf(getObject());
if(body) {
//hide all features in the body other than this object
for(App::DocumentObject* obj : body->Group.getValues()) {
if(obj->isDerivedFrom(PartDesign::Feature::getClassTypeId()) && obj != getObject()) {
Gui::ViewProvider* vp = Gui::Application::Instance->activeDocument()->getViewProvider(obj);
if(!vp)
return;
Gui::ViewProviderDocumentObject* vpd = static_cast<ViewProviderDocumentObject*>(vp);
if(vpd && vpd->Visibility.getValue())
vpd->Visibility.setValue(false);
}
}
}
}
PartGui::ViewProviderPartExt::onChanged(prop);
}
void ViewProvider::setTipIcon(bool onoff) {
isSetTipIcon = onoff;
signalChangeIcon();
}
QIcon ViewProvider::getIcon(void) const
{
return mergeTip(Gui::BitmapFactory().pixmap(sPixmap));
}
QIcon ViewProvider::mergeTip(QIcon orig) const
{
if(isSetTipIcon) {
QPixmap px;
static const char * const feature_tip_xpm[]={
"9 9 3 1",
". c None",
"# c #00cc00",
"a c #ffffff",
"...###...",
".##aaa##.",
".##aaa##.",
"###aaa###",
"##aaaaa##",
"##aaaaa##",
".##aaa##.",
".##aaa##.",
"...###..."};
px = QPixmap(feature_tip_xpm);
QIcon icon_mod;
int w = QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize);
icon_mod.addPixmap(Gui::BitmapFactory().merge(orig.pixmap(w, w, QIcon::Normal, QIcon::Off),
px,Gui::BitmapFactoryInst::BottomRight), QIcon::Normal, QIcon::Off);
icon_mod.addPixmap(Gui::BitmapFactory().merge(orig.pixmap(w, w, QIcon::Normal, QIcon::On ),
px,Gui::BitmapFactoryInst::BottomRight), QIcon::Normal, QIcon::Off);
return icon_mod;
}
else
return orig;
}
bool ViewProvider::onDelete(const std::vector<std::string> &)
{
PartDesign::Feature* feature = static_cast<PartDesign::Feature*>(getObject());
App::DocumentObject* previousfeat = feature->BaseFeature.getValue();
// Visibility - we want:
// 1. If the visible object is not the one being deleted, we leave that one visible.
// 2. If the visible object is the one being deleted, we make the previous object visible.
if (isShow() && previousfeat && Gui::Application::Instance->getViewProvider(previousfeat)) {
Gui::Application::Instance->getViewProvider(previousfeat)->show();
}
// find surrounding features in the tree
Part::BodyBase* body = PartDesign::Body::findBodyOf(getObject());
if (body != NULL) {
// Deletion from the tree of a feature is handled by Document.removeObject, which has no clue
// about what a body is. Therefore, Bodies, although an "activable" container, know nothing
// about what happens at Document level with the features they contain.
//
// The Deletion command StdCmdDelete::activated, however does notify the viewprovider corresponding
// to the feature (not body) of the imminent deletion (before actually doing it).
//
// Consequently, the only way of notifying a body of the imminent deletion of one of its features
// so as to do the clean up required (moving basefeature references, tip management) is from the
// viewprovider, so we call it here.
//
// fixes (#3084)
Gui::Command::doCommand ( Gui::Command::Doc,"App.activeDocument().%s.removeObject(App.activeDocument().%s)",
body->getNameInDocument(), feature->getNameInDocument() );
}
return true;
}
void ViewProvider::setBodyMode(bool bodymode) {
std::vector<App::Property*> props;
getPropertyList(props);
auto vp = getBodyViewProvider();
if(!vp)
return;
for(App::Property* prop : props) {
//we keep visibility and selectibility per object
if(prop == &Visibility ||
prop == &Selectable)
continue;
//we hide only properties which are available in the body, not special ones
if(!vp->getPropertyByName(prop->getName()))
continue;
prop->setStatus(App::Property::Hidden, bodymode);
}
}
void ViewProvider::makeTemporaryVisible(bool onoff)
{
//make sure to not use the overridden versions, as they change properties
if (onoff) {
if (VisualTouched) {
updateVisual(static_cast<Part::Feature*>(getObject())->Shape.getValue());
}
Gui::ViewProvider::show();
}
else
Gui::ViewProvider::hide();
}
PyObject* ViewProvider::getPyObject()
{
if (!pyViewObject)
pyViewObject = new ViewProviderPy(this);
pyViewObject->IncRef();
return pyViewObject;
}
ViewProviderBody* ViewProvider::getBodyViewProvider() {
auto body = PartDesign::Body::findBodyOf(getObject());
auto doc = getDocument();
if(body && doc) {
auto vp = doc->getViewProvider(body);
if(vp && vp->isDerivedFrom(ViewProviderBody::getClassTypeId()))
return static_cast<ViewProviderBody*>(vp);
}
return nullptr;
}
namespace Gui {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(PartDesignGui::ViewProviderPython, PartDesignGui::ViewProvider);
/// @endcond
// explicit template instantiation
template class PartDesignGuiExport ViewProviderPythonFeatureT<PartDesignGui::ViewProvider>;
}
<|endoftext|> |
<commit_before>#include <QtGui>
#include <QtOpenGL>
#include <cmath>
#include "DiamondGLWidget.h"
typedef QList<QVector3D>::const_iterator PointIter;
const float TAIL_Z = 75;
const float INNER_CIRCLE_Z = -20;
const float INNER_CIRCLE_SIZE = 35;
const float OUTER_CIRCLE_Z = 0;
const float OUTER_CIRCLE_SIZE = 50;
static const QList<QVector3D> buildCircle(const float size, const float z, const bool twisted = false)
{
QList<QVector3D> points;
static const float PI = 3.14159;
float offset = 0;
if (twisted) {
offset = PI / 16.0f;
}
for (int i = 0; i <= 16; i++) {
float angle = offset + (i * (float) PI / 8.0f);
float x = size * (float) sin(angle);
float y = size * (float) cos(angle);
points << QVector3D(x, y, z);
}
return points;
}
DiamondGLWidget::DiamondGLWidget(QWidget* const parent) :
GLWidget(parent),
useDepthTesting(true),
backFaceCulling(true),
drawBacksAsWireframe(true),
correctWindingOrder(true)
{
outerCircle.append(buildCircle(OUTER_CIRCLE_SIZE, OUTER_CIRCLE_Z));
innerCircle.append(buildCircle(INNER_CIRCLE_SIZE, INNER_CIRCLE_Z, true));
}
void DiamondGLWidget::initializeGL()
{
glShadeModel(GL_FLAT);
}
void DiamondGLWidget::render()
{
const static QColor lightColor(135, 206, 250);
const static QColor darkColor(0, 191, 255);
glClear(GL_DEPTH_BUFFER_BIT);
glFrontFace(GL_CCW);
if (usingDepthTesting()) {
glEnable(GL_DEPTH_TEST);
} else {
glDisable(GL_DEPTH_TEST);
}
if (usingBackFaceCulling()) {
glEnable(GL_CULL_FACE);
} else {
glDisable(GL_CULL_FACE);
if (drawingBacksAsWireframes()) {
glPolygonMode(GL_BACK, GL_LINE);
} else {
glPolygonMode(GL_BACK, GL_FILL);
}
}
int evenOrOdd = 0;
glBegin(GL_TRIANGLE_FAN);
glVertex3f(0, 0, TAIL_Z);
for (PointIter iter = outerCircle.begin(); iter != outerCircle.end(); ++iter) {
const QColor* color = &lightColor;
if (evenOrOdd++ % 2 == 0) {
color = &darkColor;
}
glColor3f(color->redF(), color->greenF(), color->blueF());
const QVector3D point = *iter;
glVertex3d(point.x(), point.y(), point.z());
}
glEnd();
{
glBegin(GL_TRIANGLE_STRIP);
PointIter innerIter = innerCircle.begin();
PointIter outerIter = outerCircle.begin();
while(innerIter != innerCircle.end() && outerIter != outerCircle.end()) {
QVector3D point = *outerIter++;
glColor3f(darkColor.redF(), darkColor.greenF(), darkColor.blueF());
glVertex3d(point.x(), point.y(), point.z());
point = *innerIter++;
glColor3f(lightColor.redF(), lightColor.greenF(), lightColor.blueF());
glVertex3d(point.x(), point.y(), point.z());
}
glEnd();
}
if (correctingWindingOrder()) {
glFrontFace(GL_CW);
}
glBegin(GL_TRIANGLE_FAN);
glVertex3f(0, 0, INNER_CIRCLE_Z);
for (PointIter iter = innerCircle.begin(); iter != innerCircle.end(); ++iter) {
const QColor* color = &lightColor;
if (evenOrOdd++ % 2 == 0) {
color = &darkColor;
}
glColor3f(color->redF(), color->greenF(), color->blueF());
const QVector3D point = *iter;
glVertex3d(point.x(), point.y(), point.z());
}
glEnd();
}
<commit_msg>Rotated the diamond for better initial look<commit_after>#include <QtGui>
#include <QtOpenGL>
#include <cmath>
#include "DiamondGLWidget.h"
typedef QList<QVector3D>::const_iterator PointIter;
const float TAIL_Z = 75;
const float INNER_CIRCLE_Z = -20;
const float INNER_CIRCLE_SIZE = 35;
const float OUTER_CIRCLE_Z = 0;
const float OUTER_CIRCLE_SIZE = 50;
static const QList<QVector3D> buildCircle(const float size, const float z, const bool twisted = false)
{
QList<QVector3D> points;
static const float PI = 3.14159;
float offset = 0;
if (twisted) {
offset = PI / 16.0f;
}
for (int i = 0; i <= 16; i++) {
float angle = offset + (i * (float) PI / 8.0f);
float x = size * (float) sin(angle);
float y = size * (float) cos(angle);
points << QVector3D(x, y, z);
}
return points;
}
DiamondGLWidget::DiamondGLWidget(QWidget* const parent) :
GLWidget(parent),
useDepthTesting(true),
backFaceCulling(true),
drawBacksAsWireframe(true),
correctWindingOrder(true)
{
outerCircle.append(buildCircle(OUTER_CIRCLE_SIZE, OUTER_CIRCLE_Z));
innerCircle.append(buildCircle(INNER_CIRCLE_SIZE, INNER_CIRCLE_Z, true));
}
void DiamondGLWidget::initializeGL()
{
glShadeModel(GL_FLAT);
setXRotation(50);
setYRotation(-15);
setZRotation(0);
}
void DiamondGLWidget::render()
{
const static QColor lightColor(135, 206, 250);
const static QColor darkColor(0, 191, 255);
glClear(GL_DEPTH_BUFFER_BIT);
glFrontFace(GL_CCW);
if (usingDepthTesting()) {
glEnable(GL_DEPTH_TEST);
} else {
glDisable(GL_DEPTH_TEST);
}
if (usingBackFaceCulling()) {
glEnable(GL_CULL_FACE);
} else {
glDisable(GL_CULL_FACE);
if (drawingBacksAsWireframes()) {
glPolygonMode(GL_BACK, GL_LINE);
} else {
glPolygonMode(GL_BACK, GL_FILL);
}
}
int evenOrOdd = 0;
glBegin(GL_TRIANGLE_FAN);
glVertex3f(0, 0, TAIL_Z);
for (PointIter iter = outerCircle.begin(); iter != outerCircle.end(); ++iter) {
const QColor* color = &lightColor;
if (evenOrOdd++ % 2 == 0) {
color = &darkColor;
}
glColor3f(color->redF(), color->greenF(), color->blueF());
const QVector3D point = *iter;
glVertex3d(point.x(), point.y(), point.z());
}
glEnd();
{
glBegin(GL_TRIANGLE_STRIP);
PointIter innerIter = innerCircle.begin();
PointIter outerIter = outerCircle.begin();
while(innerIter != innerCircle.end() && outerIter != outerCircle.end()) {
QVector3D point = *outerIter++;
glColor3f(darkColor.redF(), darkColor.greenF(), darkColor.blueF());
glVertex3d(point.x(), point.y(), point.z());
point = *innerIter++;
glColor3f(lightColor.redF(), lightColor.greenF(), lightColor.blueF());
glVertex3d(point.x(), point.y(), point.z());
}
glEnd();
}
if (correctingWindingOrder()) {
glFrontFace(GL_CW);
}
glBegin(GL_TRIANGLE_FAN);
glVertex3f(0, 0, INNER_CIRCLE_Z);
for (PointIter iter = innerCircle.begin(); iter != innerCircle.end(); ++iter) {
const QColor* color = &lightColor;
if (evenOrOdd++ % 2 == 0) {
color = &darkColor;
}
glColor3f(color->redF(), color->greenF(), color->blueF());
const QVector3D point = *iter;
glVertex3d(point.x(), point.y(), point.z());
}
glEnd();
}
<|endoftext|> |
<commit_before>/*
Kopete , The KDE Instant Messenger
Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Viva Chile Mierda!
Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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. *
* *
*************************************************************************
*/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopete.h"
#include <dcopclient.h>
#include "kopeteiface.h"
#define KOPETE_VERSION "0.7.0"
static const char description[] =
I18N_NOOP("Kopete, the KDE Instant Messenger");
static KCmdLineOptions options[] =
{
{ "noplugins", I18N_NOOP("Do not load plugins"), 0 },
{ "noconnect" , I18N_NOOP("Disable auto-connection") , 0 },
// { "connect <account>" , I18N_NOOP("auto-connect specified account") , 0 }, //TODO
{ "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 },
{ "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 },
KCmdLineLastOption
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
KOPETE_VERSION, description, KAboutData::License_GPL,
I18N_NOOP("(c) 2001,2003, Duncan Mac-Vicar Prett\n(c) 2002,2003, The Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");
aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org");
aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" );
aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net");
aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer, MSN Plugin"), "ogoffart@tiscalinet.be");
aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "metz@gehn.net", "http://metz.gehn.net" );
aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" );
aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Gadu plugin developer"), "gj@pointblue.com.pl" );
aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" );
aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net");
aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Core developer"), "jason@keirstead.org", "http://www.keirstead.org");
aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@pandora.be" );
aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, Icons, Plugins"), "lists@stevello.free-online.co.uk" );
aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Yahoo Plugin Maintainer"), "mattrogers@sbcglobal.net" );
aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") );
aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") );
aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") );
aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
//aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") );
aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") );
aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/");
aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" );
aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former Developer"), "remenic@linuxfromscratch.org");
aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former Developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former Developer"), "dae@chez.com" );
aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "pfeiffer@kde.org" );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
Kopete kopete;
kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec
kopete.exec();
}
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>cvs version in HEAD<commit_after>/*
Kopete , The KDE Instant Messenger
Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Viva Chile Mierda!
Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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. *
* *
*************************************************************************
*/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopete.h"
#include <dcopclient.h>
#include "kopeteiface.h"
#define KOPETE_VERSION "0.7.90cvs >= 20030803"
static const char description[] =
I18N_NOOP("Kopete, the KDE Instant Messenger");
static KCmdLineOptions options[] =
{
{ "noplugins", I18N_NOOP("Do not load plugins"), 0 },
{ "noconnect" , I18N_NOOP("Disable auto-connection") , 0 },
// { "connect <account>" , I18N_NOOP("auto-connect specified account") , 0 }, //TODO
{ "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 },
{ "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 },
KCmdLineLastOption
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
KOPETE_VERSION, description, KAboutData::License_GPL,
I18N_NOOP("(c) 2001,2003, Duncan Mac-Vicar Prett\n(c) 2002,2003, The Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");
aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org");
aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" );
aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net");
aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer, MSN Plugin"), "ogoffart@tiscalinet.be");
aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "metz@gehn.net", "http://metz.gehn.net" );
aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" );
aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Gadu plugin developer"), "gj@pointblue.com.pl" );
aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" );
aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net");
aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Core developer"), "jason@keirstead.org", "http://www.keirstead.org");
aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@pandora.be" );
aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, Icons, Plugins"), "lists@stevello.free-online.co.uk" );
aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Yahoo Plugin Maintainer"), "mattrogers@sbcglobal.net" );
aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") );
aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") );
aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") );
aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
//aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") );
aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") );
aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/");
aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" );
aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former Developer"), "remenic@linuxfromscratch.org");
aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former Developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former Developer"), "dae@chez.com" );
aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "pfeiffer@kde.org" );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
Kopete kopete;
kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec
kopete.exec();
}
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/***************************************************************************
main.cpp - description
-------------------
begin : Wed Dec 26 03:12:10 CLST 2001
copyright : (C) 2001 by Duncan Mac-Vicar Prett
email : duncan@puc.cl
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include "kopete.h"
static const char *description =
I18N_NOOP("Kopete, the KDE Messenger");
// INSERT A DESCRIPTION FOR YOUR APPLICATION HERE
static const char *version="0.2";
static KCmdLineOptions options[] =
{
{ 0, 0, 0 }
// INSERT YOUR COMMANDLINE OPTIONS HERE
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
version, description, KAboutData::License_GPL,
"(c) 2002, Duncan Mac-Vicar Prett", 0, 0, "duncan@puc.cl");
aboutData.addAuthor("Duncan Mac-Vicar Prett","Author, core developer", "duncan@puc.cl","http://www.mac-vicar.com");
aboutData.addAuthor ("Nick Betcher", "core developer, faster plugin developer in the earth.","nbetcher@usinternet.com", "http://www.kdedevelopers.net" );
aboutData.addCredit("Herwin Jan Steehouwer", I18N_NOOP("KxEngine ICQ code"));
aboutData.addCredit("Olaf Lueg", I18N_NOOP("Kmerlin MSN Code"));
aboutData.addCredit("Neil Stevens", I18N_NOOP("TAim engine AIM Code"));
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
Kopete kopete;
//kopete->show();
kopete.exec();
}
<commit_msg><commit_after>/***************************************************************************
main.cpp - description
-------------------
begin : Wed Dec 26 03:12:10 CLST 2001
copyright : (C) 2001 by Duncan Mac-Vicar Prett
email : duncan@puc.cl
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include "kopete.h"
static const char *description =
I18N_NOOP("Kopete, the KDE Messenger");
// INSERT A DESCRIPTION FOR YOUR APPLICATION HERE
static const char *version="0.23";
static KCmdLineOptions options[] =
{
{ 0, 0, 0 }
// INSERT YOUR COMMANDLINE OPTIONS HERE
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
version, description, KAboutData::License_GPL,
"(c) 2002, Duncan Mac-Vicar Prett", 0, 0, "duncan@kde.org");
aboutData.addAuthor("Duncan Mac-Vicar Prett","Author, core developer", "duncan@kde.org","http://www.mac-vicar.com");
aboutData.addAuthor ("Nick Betcher", "core developer, faster plugin developer in the earth.","nbetcher@usinternet.com", "http://www.kdedevelopers.net" );
aboutData.addCredit("Herwin Jan Steehouwer", I18N_NOOP("KxEngine ICQ code"));
aboutData.addCredit("Olaf Lueg", I18N_NOOP("Kmerlin MSN Code"));
aboutData.addCredit("Neil Stevens", I18N_NOOP("TAim engine AIM Code"));
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
Kopete kopete;
//kopete->show();
kopete.exec();
}
<|endoftext|> |
<commit_before>#include "xchainer/memory.h"
#include <cassert>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/error.h"
namespace xchainer {
bool IsPointerCudaMemory(const void* ptr) {
#ifdef XCHAINER_ENABLE_CUDA
cudaPointerAttributes attr = {};
cudaError_t status = cudaPointerGetAttributes(&attr, ptr);
switch (status) {
case cudaSuccess:
return true;
case cudaErrorInvalidValue:
return false;
default:
cuda::CheckError(status);
break;
}
assert(false); // should never be reached
#else
return false;
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> Allocate(const Device& device, size_t bytesize) {
if (device == MakeDevice("cpu")) {
return std::make_unique<uint8_t[]>(bytesize);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
void* raw_ptr = nullptr;
cuda::CheckError(cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal));
return std::shared_ptr<void>{raw_ptr, cudaFree};
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);
bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);
if (is_dst_cuda_memory) {
if (is_src_cuda_memory) {
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));
} else {
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));
}
} else {
if (is_src_cuda_memory) {
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));
} else {
std::memcpy(dst_ptr, src_ptr, bytesize);
}
}
#else
std::memcpy(dst_ptr, src_ptr, bytesize);
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> MemoryFromBuffer(const Device& device, const std::shared_ptr<void>& src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
if (device == MakeDevice("cpu")) {
if (IsPointerCudaMemory(src_ptr.get())) {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));
return dst_ptr;
} else {
return src_ptr;
}
} else if (device == MakeDevice("cuda")) {
if (IsPointerCudaMemory(src_ptr.get())) {
return src_ptr;
} else {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));
return dst_ptr;
}
} else {
throw DeviceError("invalid device");
}
#else
return src_ptr;
#endif // XCHAINER_ENABLE_CUDA
}
} // namespace
<commit_msg>add comments<commit_after>#include "xchainer/memory.h"
#include <cassert>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/error.h"
namespace xchainer {
bool IsPointerCudaMemory(const void* ptr) {
#ifdef XCHAINER_ENABLE_CUDA
cudaPointerAttributes attr = {};
cudaError_t status = cudaPointerGetAttributes(&attr, ptr);
switch (status) {
case cudaSuccess:
return true;
case cudaErrorInvalidValue:
return false;
default:
cuda::CheckError(status);
break;
}
assert(false); // should never be reached
#else
return false;
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> Allocate(const Device& device, size_t bytesize) {
if (device == MakeDevice("cpu")) {
return std::make_unique<uint8_t[]>(bytesize);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
void* raw_ptr = nullptr;
cuda::CheckError(cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal));
return std::shared_ptr<void>{raw_ptr, cudaFree};
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);
bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);
if (is_dst_cuda_memory) {
if (is_src_cuda_memory) {
// Copy from device to device is faster even in unified memory
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));
} else {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));
}
} else {
if (is_src_cuda_memory) {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));
} else {
std::memcpy(dst_ptr, src_ptr, bytesize);
}
}
#else
std::memcpy(dst_ptr, src_ptr, bytesize);
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> MemoryFromBuffer(const Device& device, const std::shared_ptr<void>& src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
if (device == MakeDevice("cpu")) {
if (IsPointerCudaMemory(src_ptr.get())) {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));
return dst_ptr;
} else {
return src_ptr;
}
} else if (device == MakeDevice("cuda")) {
if (IsPointerCudaMemory(src_ptr.get())) {
return src_ptr;
} else {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));
return dst_ptr;
}
} else {
throw DeviceError("invalid device");
}
#else
return src_ptr;
#endif // XCHAINER_ENABLE_CUDA
}
} // namespace
<|endoftext|> |
<commit_before>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include <iostream>
#include "LoopedFramework.hpp"
#include "CommandOptionWithTimeArg.hpp"
#include "EphReader.hpp"
#include "MSCData.hpp"
#include "MSCStream.hpp"
#include "FFIdentifier.hpp"
using namespace std;
using namespace gpstk;
class SVVis : public BasicFramework
{
public:
SVVis(const string& applName) throw()
: BasicFramework(
applName,
"Compute when satellites are visible at a given point on the earth")
{};
bool initialize(int argc, char *argv[]) throw();
protected:
virtual void spinUp() {};
virtual void process();
virtual void shutDown() {};
private:
EphReader ephReader;
double minElev;
DayTime startTime, stopTime;
Triple rxPos;
double timeStep;
bool printElev;
};
bool SVVis::initialize(int argc, char *argv[]) throw()
{
CommandOptionWithAnyArg
minElevOpt(
'\0', "min-elev",
"Give an integer for the elevation (degrees) above which you want "
"to find more than 12 SVs at a given time."),
rxPosOpt(
'p', "position",
"Receiver antenna position in ECEF (x,y,z) coordinates. Format as "
"a string: \"X Y Z\"."),
ephFileOpt(
'e', "eph",
"Where to get the ephemeris data. Can be "
+ EphReader::formatsUnderstood() + ".", true),
mscFileOpt(
'c', "msc",
"Station coordinate file."),
msidOpt(
'm', "msid",
"Station number to use from the msc file."),
timeSpanOpt(
'l', "time-span",
"How much data to process, in seconds");
CommandOptionWithTimeArg
startTimeOpt(
'\0', "start-time", "%4Y/%03j/%02H:%02M:%05.2f",
"Ignore data before this time. (%4Y/%03j/%02H:%02M:%05.2f)"),
stopTimeOpt(
'\0', "stop-time", "%4Y/%03j/%02H:%02M:%05.2f",
"Ignore any data after this time");
CommandOptionNoArg
printElevOpt('\0', "print-elev",
"Print the elevation of the sv at each change in tracking. "
"The defaut is to just to output the PRN of the sv.");
if (!BasicFramework::initialize(argc,argv)) return false;
// get the minimum elevation
if (minElevOpt.getCount())
minElev = StringUtils::asDouble((minElevOpt.getValue())[0]);
else
minElev = 0;
// get the ephemeris source(s)
ephReader.verboseLevel = verboseLevel;
FFIdentifier::debugLevel = debugLevel;
for (int i=0; i<ephFileOpt.getCount(); i++)
ephReader.read(ephFileOpt.getValue()[i]);
if (ephReader.eph == NULL)
{
cout << "Didn't get any ephemeris data from the eph files. "
<< "Exiting." << endl;
exit(-1);
}
if (debugLevel)
ephReader.eph->dump(cout, debugLevel-1);
// get the antenna position
bool haveRxPos = false;
if (rxPosOpt.getCount())
{
double x,y,z;
sscanf(rxPosOpt.getValue().front().c_str(),"%lf %lf %lf", &x, &y, &z);
rxPos[0] = x;
rxPos[1] = y;
rxPos[2] = z;
haveRxPos = true;
}
else if (msidOpt.getCount() && mscFileOpt.getCount())
{
long msid = StringUtils::asUnsigned(msidOpt.getValue()[0]);
string fn = mscFileOpt.getValue()[0];
MSCStream mscs(fn.c_str(), ios::in);
MSCData mscd;
while (mscs >> mscd)
{
if (mscd.station == msid)
{
rxPos = mscd.coordinates;
haveRxPos=true;
break;
}
}
if (!haveRxPos)
cout << "Did not find station " << msid << " in " << fn << "." << endl;
}
if (!haveRxPos)
return false;
timeStep=900;
if (startTimeOpt.getCount())
startTime = startTimeOpt.getTime()[0];
else
{
startTime = ephReader.eph->getInitialTime();
long sow = static_cast<long>(startTime.GPSsow());
sow -= sow % static_cast<long>(timeStep);
startTime.setGPS(startTime.GPSfullweek(), static_cast<double>(sow));
startTime += timeStep;
}
if (stopTimeOpt.getCount())
stopTime = stopTimeOpt.getTime()[0];
else
stopTime = ephReader.eph->getFinalTime();
if (timeSpanOpt.getCount())
{
double dt = StringUtils::asDouble(timeSpanOpt.getValue()[0]);
stopTime = startTime + dt;
}
printElev = printElevOpt.getCount() > 0;
if (verboseLevel)
cout << "debugLevel: " << debugLevel << endl
<< "verboseLevel: " << verboseLevel << endl
<< "rxPos: " << rxPos << endl
<< "minElev: " << minElev << endl
<< "startTime: " << startTime << endl
<< "stopTime: " << stopTime << endl;
return true;
}
void SVVis::process()
{
gpstk::XvtStore<SatID>& ephStore = *ephReader.eph;
DayTime t = startTime;
Xvt rxXvt;
rxXvt.x = rxPos;
cout << "# date time #: ";
for (int prn=1; prn <= MAX_PRN; prn++)
cout << left << setw(3) << prn;
cout << endl;
string up, prev_up, el;
int n_up;
for (DayTime t=startTime; t < stopTime; t+=1)
{
up = "";
el = "";
n_up = 0;
for (int prn=1; prn <= MAX_PRN; prn++)
{
try
{
using namespace StringUtils;
Xvt svXvt = ephStore.getXvt(SatID(prn, SatID::systemGPS),t);
double elev = rxXvt.x.elvAngle(svXvt.x);
if (elev>=minElev)
{
up += leftJustify(asString(prn), 3);
el += leftJustify(asString(elev,0), 3);
n_up++;
}
else
{
up += " ";
el += " ";
}
}
catch(gpstk::Exception& e)
{
up += " ? ";
if (debugLevel)
cout << e << endl;
}
}
if (up != prev_up)
{
cout << t << " " << setw(2) << n_up << ": ";
if (printElev)
cout << el;
else
cout << up;
cout << endl;
}
prev_up = up;
}
}
int main(int argc, char *argv[])
{
try
{
SVVis crap(argv[0]);
if (!crap.initialize(argc, argv))
exit(0);
crap.run();
}
catch (gpstk::Exception &exc)
{ cout << exc << endl; }
catch (std::exception &exc)
{ cout << "Caught std::exception " << exc.what() << endl; }
catch (...)
{ cout << "Caught unknown exception" << endl; }
}
<commit_msg>Fixed a colum allignment error when printing elevations<commit_after>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include <iostream>
#include "LoopedFramework.hpp"
#include "CommandOptionWithTimeArg.hpp"
#include "EphReader.hpp"
#include "MSCData.hpp"
#include "MSCStream.hpp"
#include "FFIdentifier.hpp"
using namespace std;
using namespace gpstk;
class SVVis : public BasicFramework
{
public:
SVVis(const string& applName) throw()
: BasicFramework(
applName,
"Compute when satellites are visible at a given point on the earth")
{};
bool initialize(int argc, char *argv[]) throw();
protected:
virtual void spinUp() {};
virtual void process();
virtual void shutDown() {};
private:
EphReader ephReader;
double minElev;
DayTime startTime, stopTime;
Triple rxPos;
double timeStep;
bool printElev;
int graphElev;
};
bool SVVis::initialize(int argc, char *argv[]) throw()
{
CommandOptionWithAnyArg
minElevOpt(
'\0', "elevation-mask",
"The elevation above which an SV is visible. The default is 0 degrees."),
rxPosOpt(
'p', "position",
"Receiver antenna position in ECEF (x,y,z) coordinates. Format as "
"a string: \"X Y Z\"."),
ephFileOpt(
'e', "eph",
"Where to get the ephemeris data. Can be "
+ EphReader::formatsUnderstood() + ".", true),
mscFileOpt(
'c', "msc",
"Station coordinate file."),
msidOpt(
'm', "msid",
"Station number to use from the msc file."),
graphElevOpt(
'\0', "graph-elev",
"Output data at the specified interval. Interval is in seconds."),
timeSpanOpt(
'l', "time-span",
"How much data to process, in seconds. Default is 86400.");
CommandOptionWithTimeArg
startTimeOpt(
'\0', "start-time", "%4Y/%03j/%02H:%02M:%05.2f",
"When to start computing positions. The default is the start of the "
"ephemers data. (%4Y/%03j/%02H:%02M:%05.2f)"),
stopTimeOpt(
'\0', "stop-time", "%4Y/%03j/%02H:%02M:%05.2f",
"When to stop computing positions. The default is one day after "
"the start time");
CommandOptionNoArg
printElevOpt(
'\0', "print-elev",
"Print the elevation of the sv at each change in tracking. "
"The defaut is to just to output the PRN of the sv.");
if (!BasicFramework::initialize(argc,argv)) return false;
// get the minimum elevation
if (minElevOpt.getCount())
minElev = StringUtils::asDouble((minElevOpt.getValue())[0]);
else
minElev = 0;
// get the ephemeris source(s)
ephReader.verboseLevel = verboseLevel;
FFIdentifier::debugLevel = debugLevel;
for (int i=0; i<ephFileOpt.getCount(); i++)
ephReader.read(ephFileOpt.getValue()[i]);
if (ephReader.eph == NULL)
{
cout << "Didn't get any ephemeris data from the eph files. "
<< "Exiting." << endl;
exit(-1);
}
if (debugLevel)
ephReader.eph->dump(cout, debugLevel-1);
// get the antenna position
bool haveRxPos = false;
if (rxPosOpt.getCount())
{
double x,y,z;
sscanf(rxPosOpt.getValue().front().c_str(),"%lf %lf %lf", &x, &y, &z);
rxPos[0] = x;
rxPos[1] = y;
rxPos[2] = z;
haveRxPos = true;
}
else if (msidOpt.getCount() && mscFileOpt.getCount())
{
long msid = StringUtils::asUnsigned(msidOpt.getValue()[0]);
string fn = mscFileOpt.getValue()[0];
MSCStream mscs(fn.c_str(), ios::in);
MSCData mscd;
while (mscs >> mscd)
{
if (mscd.station == msid)
{
rxPos = mscd.coordinates;
haveRxPos=true;
break;
}
}
if (!haveRxPos)
cout << "Did not find station " << msid << " in " << fn << "." << endl;
}
if (!haveRxPos)
return false;
timeStep=900;
if (startTimeOpt.getCount())
startTime = startTimeOpt.getTime()[0];
else
{
startTime = ephReader.eph->getInitialTime();
long sow = static_cast<long>(startTime.GPSsow());
sow -= sow % static_cast<long>(timeStep);
startTime.setGPS(startTime.GPSfullweek(), static_cast<double>(sow));
startTime += timeStep;
}
if (stopTimeOpt.getCount())
stopTime = stopTimeOpt.getTime()[0];
else
stopTime = ephReader.eph->getFinalTime();
if (timeSpanOpt.getCount())
{
double dt = StringUtils::asDouble(timeSpanOpt.getValue()[0]);
stopTime = startTime + dt;
}
if (graphElevOpt.getCount())
graphElev = StringUtils::asInt(graphElevOpt.getValue()[0]);
else
graphElev = 0;
printElev = printElevOpt.getCount() > 0;
if (debugLevel)
cout << "debugLevel: " << debugLevel << endl
<< "verboseLevel: " << verboseLevel << endl
<< "rxPos: " << rxPos << endl
<< "minElev: " << minElev << endl
<< "graphElev: " << graphElev << endl
<< "startTime: " << startTime << endl
<< "stopTime: " << stopTime << endl;
return true;
}
void SVVis::process()
{
gpstk::XvtStore<SatID>& ephStore = *ephReader.eph;
DayTime t = startTime;
Xvt rxXvt;
rxXvt.x = rxPos;
cout << "# date time #: ";
for (int prn=1; prn <= MAX_PRN; prn++)
cout << left << setw(3) << prn;
cout << endl;
string up, prev_up, el;
int n_up;
for (DayTime t=startTime; t < stopTime; t+=1)
{
up = "";
el = "";
n_up = 0;
for (int prn=1; prn <= MAX_PRN; prn++)
{
try
{
using namespace StringUtils;
Xvt svXvt = ephStore.getXvt(SatID(prn, SatID::systemGPS),t);
double elev = rxXvt.x.elvAngle(svXvt.x);
if (elev>=minElev)
{
up += leftJustify(asString(prn), 3);
el += leftJustify(asString(elev,0), 3);
n_up++;
}
else
{
up += " ";
el += " ";
}
}
catch(gpstk::Exception& e)
{
up += " ? ";
el += " ? ";
if (debugLevel)
cout << e << endl;
}
}
long sod=static_cast<long>(t.DOYsecond());
if (up != prev_up || (graphElev && (sod % graphElev==0)) )
{
cout << t << " " << setw(2) << n_up << ": ";
if (printElev)
cout << el;
else
cout << up;
cout << endl;
}
prev_up = up;
}
}
int main(int argc, char *argv[])
{
SVVis crap(argv[0]);
if (!crap.initialize(argc, argv))
exit(0);
crap.run();
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2013, John Haddon. All rights reserved.
// Copyright (c) 2013, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software 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 "boost/bind.hpp"
#include "IECore/Camera.h"
#include "IECore/Transform.h"
#include "IECore/AngleConversion.h"
#include "IECore/MatrixTransform.h"
#include "IECoreGL/Primitive.h"
#include "Gaffer/CompoundPlug.h"
#include "Gaffer/NumericPlug.h"
#include "Gaffer/TypedPlug.h"
#include "GafferUI/View3D.h"
using namespace Imath;
using namespace IECoreGL;
using namespace Gaffer;
using namespace GafferUI;
IE_CORE_DEFINERUNTIMETYPED( View3D );
View3D::View3D( const std::string &name, Gaffer::PlugPtr inPlug )
: View( name, inPlug ), m_baseState( new IECoreGL::State( true ) )
{
// base state setup
m_baseState->add( new WireframeColorStateComponent( Color4f( 0.2f, 0.2f, 0.2f, 1.0f ) ) );
m_baseState->add( new PointColorStateComponent( Color4f( 0.9f, 0.9f, 0.9f, 1.0f ) ) );
m_baseState->add( new IECoreGL::Primitive::PointWidth( 2.0f ) );
// plugs
CompoundPlugPtr baseState = new CompoundPlug( "baseState" );
addChild( baseState );
CompoundPlugPtr solid = new CompoundPlug( "solid" );
baseState->addChild( solid );
solid->addChild( new BoolPlug( "enabled", Plug::In, true ) );
solid->addChild( new BoolPlug( "override" ) );
CompoundPlugPtr wireframe = new CompoundPlug( "wireframe" );
baseState->addChild( wireframe );
wireframe->addChild( new BoolPlug( "enabled" ) );
wireframe->addChild( new BoolPlug( "override" ) );
CompoundPlugPtr points = new CompoundPlug( "points" );
baseState->addChild( points );
points->addChild( new BoolPlug( "enabled" ) );
points->addChild( new BoolPlug( "override" ) );
CompoundPlugPtr bound = new CompoundPlug( "bound" );
baseState->addChild( bound );
bound->addChild( new BoolPlug( "enabled" ) );
bound->addChild( new BoolPlug( "override" ) );
plugSetSignal().connect( boost::bind( &View3D::plugSet, this, ::_1 ) );
// camera
// weird two stage assignment is to work around bogus
// uninitialised variable warnings in debug builds with
// gcc 4.1.2.
IECore::CameraPtr camera; camera = new IECore::Camera();
camera->parameters()["projection"] = new IECore::StringData( "perspective" );
camera->parameters()["projection:fov"] = new IECore::FloatData( 54.43 ); // 35 mm focal length
M44f matrix;
matrix.translate( V3f( 0, 0, 1 ) );
matrix.rotate( IECore::degreesToRadians( V3f( -25, 45, 0 ) ) );
camera->setTransform( new IECore::MatrixTransform( matrix ) );
viewportGadget()->setCamera( camera.get() );
}
View3D::~View3D()
{
}
const IECoreGL::State *View3D::baseState() const
{
return m_baseState.get();
}
View3D::BaseStateChangedSignal &View3D::baseStateChangedSignal()
{
return m_baseStateChangedSignal;
}
void View3D::plugSet( const Gaffer::Plug *plug )
{
if( plug == getChild<Plug>( "baseState" ) )
{
updateBaseState();
}
}
void View3D::updateBaseState()
{
const CompoundPlug *baseState = getChild<CompoundPlug>( "baseState" );
const CompoundPlug *solid = baseState->getChild<CompoundPlug>( "solid" );
m_baseState->add(
new Primitive::DrawSolid( solid->getChild<BoolPlug>( "enabled" )->getValue() ),
solid->getChild<BoolPlug>( "override" )->getValue()
);
const CompoundPlug *wireframe = baseState->getChild<CompoundPlug>( "wireframe" );
m_baseState->add(
new Primitive::DrawWireframe( wireframe->getChild<BoolPlug>( "enabled" )->getValue() ),
wireframe->getChild<BoolPlug>( "override" )->getValue()
);
const CompoundPlug *points = baseState->getChild<CompoundPlug>( "points" );
m_baseState->add(
new Primitive::DrawPoints( points->getChild<BoolPlug>( "enabled" )->getValue() ),
points->getChild<BoolPlug>( "override" )->getValue()
);
const CompoundPlug *bound = baseState->getChild<CompoundPlug>( "bound" );
m_baseState->add(
new Primitive::DrawBound( bound->getChild<BoolPlug>( "enabled" )->getValue() ),
bound->getChild<BoolPlug>( "override" )->getValue()
);
baseStateChangedSignal()( this );
}
<commit_msg>View3D : Removed use of CompoundPlug.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2013, John Haddon. All rights reserved.
// Copyright (c) 2013, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software 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 "boost/bind.hpp"
#include "IECore/Camera.h"
#include "IECore/Transform.h"
#include "IECore/AngleConversion.h"
#include "IECore/MatrixTransform.h"
#include "IECoreGL/Primitive.h"
#include "Gaffer/NumericPlug.h"
#include "Gaffer/TypedPlug.h"
#include "GafferUI/View3D.h"
using namespace Imath;
using namespace IECoreGL;
using namespace Gaffer;
using namespace GafferUI;
IE_CORE_DEFINERUNTIMETYPED( View3D );
View3D::View3D( const std::string &name, Gaffer::PlugPtr inPlug )
: View( name, inPlug ), m_baseState( new IECoreGL::State( true ) )
{
// base state setup
m_baseState->add( new WireframeColorStateComponent( Color4f( 0.2f, 0.2f, 0.2f, 1.0f ) ) );
m_baseState->add( new PointColorStateComponent( Color4f( 0.9f, 0.9f, 0.9f, 1.0f ) ) );
m_baseState->add( new IECoreGL::Primitive::PointWidth( 2.0f ) );
// plugs
ValuePlugPtr baseState = new ValuePlug( "baseState" );
addChild( baseState );
ValuePlugPtr solid = new ValuePlug( "solid" );
baseState->addChild( solid );
solid->addChild( new BoolPlug( "enabled", Plug::In, true ) );
solid->addChild( new BoolPlug( "override" ) );
ValuePlugPtr wireframe = new ValuePlug( "wireframe" );
baseState->addChild( wireframe );
wireframe->addChild( new BoolPlug( "enabled" ) );
wireframe->addChild( new BoolPlug( "override" ) );
ValuePlugPtr points = new ValuePlug( "points" );
baseState->addChild( points );
points->addChild( new BoolPlug( "enabled" ) );
points->addChild( new BoolPlug( "override" ) );
ValuePlugPtr bound = new ValuePlug( "bound" );
baseState->addChild( bound );
bound->addChild( new BoolPlug( "enabled" ) );
bound->addChild( new BoolPlug( "override" ) );
plugSetSignal().connect( boost::bind( &View3D::plugSet, this, ::_1 ) );
// camera
// weird two stage assignment is to work around bogus
// uninitialised variable warnings in debug builds with
// gcc 4.1.2.
IECore::CameraPtr camera; camera = new IECore::Camera();
camera->parameters()["projection"] = new IECore::StringData( "perspective" );
camera->parameters()["projection:fov"] = new IECore::FloatData( 54.43 ); // 35 mm focal length
M44f matrix;
matrix.translate( V3f( 0, 0, 1 ) );
matrix.rotate( IECore::degreesToRadians( V3f( -25, 45, 0 ) ) );
camera->setTransform( new IECore::MatrixTransform( matrix ) );
viewportGadget()->setCamera( camera.get() );
}
View3D::~View3D()
{
}
const IECoreGL::State *View3D::baseState() const
{
return m_baseState.get();
}
View3D::BaseStateChangedSignal &View3D::baseStateChangedSignal()
{
return m_baseStateChangedSignal;
}
void View3D::plugSet( const Gaffer::Plug *plug )
{
if( plug == getChild<Plug>( "baseState" ) )
{
updateBaseState();
}
}
void View3D::updateBaseState()
{
const ValuePlug *baseState = getChild<ValuePlug>( "baseState" );
const ValuePlug *solid = baseState->getChild<ValuePlug>( "solid" );
m_baseState->add(
new Primitive::DrawSolid( solid->getChild<BoolPlug>( "enabled" )->getValue() ),
solid->getChild<BoolPlug>( "override" )->getValue()
);
const ValuePlug *wireframe = baseState->getChild<ValuePlug>( "wireframe" );
m_baseState->add(
new Primitive::DrawWireframe( wireframe->getChild<BoolPlug>( "enabled" )->getValue() ),
wireframe->getChild<BoolPlug>( "override" )->getValue()
);
const ValuePlug *points = baseState->getChild<ValuePlug>( "points" );
m_baseState->add(
new Primitive::DrawPoints( points->getChild<BoolPlug>( "enabled" )->getValue() ),
points->getChild<BoolPlug>( "override" )->getValue()
);
const ValuePlug *bound = baseState->getChild<ValuePlug>( "bound" );
m_baseState->add(
new Primitive::DrawBound( bound->getChild<BoolPlug>( "enabled" )->getValue() ),
bound->getChild<BoolPlug>( "override" )->getValue()
);
baseStateChangedSignal()( this );
}
<|endoftext|> |
<commit_before>
//@HEADER
// ************************************************************************
//
// HPCG: Simple Conjugate Gradient Benchmark Code
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
/*!
@file GenerateProblem.cpp
HPCG routine
*/
#if defined(HPCG_DEBUG) || defined(HPCG_DETAILED_DEBUG)
#include <fstream>
using std::endl;
#include "hpcg.hpp"
#endif
#include <cassert>
#include "GenerateProblem.hpp"
#ifndef HPCG_NOMPI
#include <mpi.h>
#endif
#ifndef HPCG_NOOPENMP
#include <omp.h>
#endif
/*!
Routine to read a sparse matrix, right hand side, initial guess, and exact
solution (as computed by a direct solver).
@param[in] geom data structure that stores the parallel run parameters and the factoring of total number of processes into three dimensional grid
@param[in] A The known system matrix
@param[out] b The newly allocated and generated right hand side vector
@param[out] x The newly allocated solution vector with entries set to 0.0
@param[out] xexact The newly allocated solution vector with entries set to the exact solution
@see GenerateGeometry
*/
void GenerateProblem(const Geometry & geom, SparseMatrix & A, double ** b, double ** x, double ** xexact) {
int nx = geom.nx;
int ny = geom.ny;
int nz = geom.nz;
int npx = geom.npx;
int npy = geom.npy;
int npz = geom.npz;
int ipx = geom.ipx;
int ipy = geom.ipy;
int ipz = geom.ipz;
int gnx = nx*npx;
int gny = ny*npy;
int gnz = nz*npz;
local_int_t localNumberOfRows = nx*ny*nz; // This is the size of our subblock
// If this assert fails, it most likely means that the local_int_t is set to int and should be set to long long
assert(localNumberOfRows>0); // Throw an exception of the number of rows is less than zero (can happen if int overflow)
int numberOfNonzerosPerRow = 27; // We are approximating a 27-point finite element/volume/difference 3D stencil
global_int_t totalNumberOfRows = localNumberOfRows*geom.size; // Total number of grid points in mesh
// If this assert fails, it most likely means that the global_int_t is set to int and should be set to long long
assert(totalNumberOfRows>0); // Throw an exception of the number of rows is less than zero (can happen if int overflow)
// Allocate arrays that are of length localNumberOfRows
char * nonzerosInRow = new char[localNumberOfRows];
global_int_t ** mtxIndG = new global_int_t*[localNumberOfRows];
local_int_t ** mtxIndL = new local_int_t*[localNumberOfRows];
double ** matrixValues = new double*[localNumberOfRows];
double ** matrixDiagonal = new double*[localNumberOfRows];
*x = new double[localNumberOfRows];
*b = new double[localNumberOfRows];
*xexact = new double[localNumberOfRows];
A.localToGlobalMap.resize(localNumberOfRows);
// Use a parallel loop to do initial assignment:
// distributes the physical placement of arrays of pointers across the memory system
#ifndef HPCG_NOOPENMP
#pragma omp parallel for
#endif
for (local_int_t i=0; i< localNumberOfRows; ++i) {
matrixValues[i] = 0;
matrixDiagonal[i] = 0;
mtxIndG[i] = 0;
mtxIndL[i] = 0;
}
// Now allocate the arrays pointed to
for (local_int_t i=0; i< localNumberOfRows; ++i) {
mtxIndL[i] = new local_int_t[numberOfNonzerosPerRow];
matrixValues[i] = new double[numberOfNonzerosPerRow];
mtxIndG[i] = new global_int_t[numberOfNonzerosPerRow];
}
local_int_t localNumberOfNonzeros = 0;
// TODO: This triply nested loop could be flattened or use nested parallelism
#ifndef HPCG_NOOPENMP
#pragma omp parallel for
#endif
for (local_int_t iz=0; iz<nz; iz++) {
global_int_t giz = ipz*nz+iz;
for (local_int_t iy=0; iy<ny; iy++) {
global_int_t giy = ipy*ny+iy;
for (local_int_t ix=0; ix<nx; ix++) {
global_int_t gix = ipx*nx+ix;
local_int_t currentLocalRow = iz*nx*ny+iy*nx+ix;
global_int_t currentGlobalRow = giz*gnx*gny+giy*gnx+gix;
#ifndef HPCG_NOOPENMP
// C++ std::map is not threadsafe for writing
#pragma omp critical
#endif
A.globalToLocalMap[currentGlobalRow] = currentLocalRow;
A.localToGlobalMap[currentLocalRow] = currentGlobalRow;
#ifdef HPCG_DETAILED_DEBUG
HPCG_fout << " rank, globalRow, localRow = " << geom.rank << " " << currentGlobalRow << " " << A.globalToLocalMap[currentGlobalRow] << endl;
#endif
char numberOfNonzerosInRow = 0;
double * currentValuePointer = matrixValues[currentLocalRow]; // Pointer to current value in current row
global_int_t * currentIndexPointerG = mtxIndG[currentLocalRow]; // Pointer to current index in current row
for (int sz=-1; sz<=1; sz++) {
if (giz+sz>-1 && giz+sz<gnz) {
for (int sy=-1; sy<=1; sy++) {
if (giy+sy>-1 && giy+sy<gny) {
for (int sx=-1; sx<=1; sx++) {
if (gix+sx>-1 && gix+sx<gnx) {
global_int_t curcol = currentGlobalRow+sz*gnx*gny+sy*gnx+sx;
if (curcol==currentGlobalRow) {
matrixDiagonal[currentLocalRow] = currentValuePointer;
*currentValuePointer++ = 27.0;
} else {
*currentValuePointer++ = -1.0;
}
*currentIndexPointerG++ = curcol;
numberOfNonzerosInRow++;
} // end x bounds test
} // end sx loop
} // end y bounds test
} // end sy loop
} // end z bounds test
} // end sz loop
nonzerosInRow[currentLocalRow] = numberOfNonzerosInRow;
#ifndef HPCG_NOOPENMP
#pragma omp critical
#endif
localNumberOfNonzeros += numberOfNonzerosInRow; // Protect this with an atomic
(*x)[currentLocalRow] = 0.0;
(*b)[currentLocalRow] = 27.0 - ((double) (numberOfNonzerosInRow-1));
(*xexact)[currentLocalRow] = 1.0;
} // end ix loop
} // end iy loop
} // end iz loop
#ifdef HPCG_DETAILED_DEBUG
HPCG_fout << "Process " << geom.rank << " of " << geom.size <<" has " << localNumberOfRows << " rows." << endl
<< "Process " << geom.rank << " of " << geom.size <<" has " << localNumberOfNonzeros<< " nonzeros." <<endl;
#endif
global_int_t totalNumberOfNonzeros = 0;
#ifndef HPCG_NOMPI
// Use MPI's reduce function to sum all nonzeros
#ifdef HPCG_NO_LONG_LONG
MPI_Allreduce(&localNumberOfNonzeros, &totalNumberOfNonzeros, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
#else
long long lnnz = localNumberOfNonzeros, gnnz = 0; // convert to 64 bit for MPI call
MPI_Allreduce(&lnnz, &gnnz, 1, MPI_LONG_LONG_INT, MPI_SUM, MPI_COMM_WORLD);
totalNumberOfNonzeros = gnnz; // Copy back
#endif
#else
totalNumberOfNonzeros = localNumberOfNonzeros;
#endif
// If this assert fails, it most likely means that the global_int_t is set to int and should be set to long long
// This assert is usually the first to fail as problem size increases beyond the 32-bit integer range.
assert(totalNumberOfNonzeros>0); // Throw an exception of the number of nonzeros is less than zero (can happen if int overflow)
A.title = 0;
A.totalNumberOfRows = totalNumberOfRows;
A.totalNumberOfNonzeros = totalNumberOfNonzeros;
A.localNumberOfRows = localNumberOfRows;
A.localNumberOfColumns = localNumberOfRows;
A.localNumberOfNonzeros = localNumberOfNonzeros;
A.nonzerosInRow = nonzerosInRow;
A.mtxIndG = mtxIndG;
A.mtxIndL = mtxIndL;
A.matrixValues = matrixValues;
A.matrixDiagonal = matrixDiagonal;
return;
}
<commit_msg>I have modified GenerateProblem so that all local variables, except the sx, sy, sz loop counters are of type global_int_t. This change should address the problem with overflow when the RHS variables are all 32-bit but the result requires 64-bit storage.<commit_after>
//@HEADER
// ************************************************************************
//
// HPCG: Simple Conjugate Gradient Benchmark Code
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
/*!
@file GenerateProblem.cpp
HPCG routine
*/
#if defined(HPCG_DEBUG) || defined(HPCG_DETAILED_DEBUG)
#include <fstream>
using std::endl;
#include "hpcg.hpp"
#endif
#include <cassert>
#include "GenerateProblem.hpp"
#ifndef HPCG_NOMPI
#include <mpi.h>
#endif
#ifndef HPCG_NOOPENMP
#include <omp.h>
#endif
/*!
Routine to read a sparse matrix, right hand side, initial guess, and exact
solution (as computed by a direct solver).
@param[in] geom data structure that stores the parallel run parameters and the factoring of total number of processes into three dimensional grid
@param[in] A The known system matrix
@param[out] b The newly allocated and generated right hand side vector
@param[out] x The newly allocated solution vector with entries set to 0.0
@param[out] xexact The newly allocated solution vector with entries set to the exact solution
@see GenerateGeometry
*/
void GenerateProblem(const Geometry & geom, SparseMatrix & A, double ** b, double ** x, double ** xexact) {
// Make local copies of geometry information. Use global_int_t since the RHS products in the calculations
// below may result in global range values.
global_int_t nx = geom.nx;
global_int_t ny = geom.ny;
global_int_t nz = geom.nz;
global_int_t npx = geom.npx;
global_int_t npy = geom.npy;
global_int_t npz = geom.npz;
global_int_t ipx = geom.ipx;
global_int_t ipy = geom.ipy;
global_int_t ipz = geom.ipz;
global_int_t size = geom.size;
global_int_t gnx = nx*npx;
global_int_t gny = ny*npy;
global_int_t gnz = nz*npz;
global_int_t localNumberOfRows = nx*ny*nz; // This is the size of our subblock
// If this assert fails, it most likely means that the local_int_t is set to int and should be set to long long
assert(localNumberOfRows>0); // Throw an exception of the number of rows is less than zero (can happen if int overflow)
global_int_t numberOfNonzerosPerRow = 27; // We are approximating a 27-point finite element/volume/difference 3D stencil
global_int_t totalNumberOfRows = localNumberOfRows*geom.size; // Total number of grid points in mesh
// If this assert fails, it most likely means that the global_int_t is set to int and should be set to long long
assert(totalNumberOfRows>0); // Throw an exception of the number of rows is less than zero (can happen if int overflow)
// Allocate arrays that are of length localNumberOfRows
char * nonzerosInRow = new char[localNumberOfRows];
global_int_t ** mtxIndG = new global_int_t*[localNumberOfRows];
local_int_t ** mtxIndL = new local_int_t*[localNumberOfRows];
double ** matrixValues = new double*[localNumberOfRows];
double ** matrixDiagonal = new double*[localNumberOfRows];
*x = new double[localNumberOfRows];
*b = new double[localNumberOfRows];
*xexact = new double[localNumberOfRows];
A.localToGlobalMap.resize(localNumberOfRows);
// Use a parallel loop to do initial assignment:
// distributes the physical placement of arrays of pointers across the memory system
#ifndef HPCG_NOOPENMP
#pragma omp parallel for
#endif
for (local_int_t i=0; i< localNumberOfRows; ++i) {
matrixValues[i] = 0;
matrixDiagonal[i] = 0;
mtxIndG[i] = 0;
mtxIndL[i] = 0;
}
// Now allocate the arrays pointed to
for (local_int_t i=0; i< localNumberOfRows; ++i) {
mtxIndL[i] = new local_int_t[numberOfNonzerosPerRow];
matrixValues[i] = new double[numberOfNonzerosPerRow];
mtxIndG[i] = new global_int_t[numberOfNonzerosPerRow];
}
local_int_t localNumberOfNonzeros = 0;
// TODO: This triply nested loop could be flattened or use nested parallelism
#ifndef HPCG_NOOPENMP
#pragma omp parallel for
#endif
for (local_int_t iz=0; iz<nz; iz++) {
global_int_t giz = ipz*nz+iz;
for (local_int_t iy=0; iy<ny; iy++) {
global_int_t giy = ipy*ny+iy;
for (local_int_t ix=0; ix<nx; ix++) {
global_int_t gix = ipx*nx+ix;
local_int_t currentLocalRow = iz*nx*ny+iy*nx+ix;
global_int_t currentGlobalRow = giz*gnx*gny+giy*gnx+gix;
#ifndef HPCG_NOOPENMP
// C++ std::map is not threadsafe for writing
#pragma omp critical
#endif
A.globalToLocalMap[currentGlobalRow] = currentLocalRow;
A.localToGlobalMap[currentLocalRow] = currentGlobalRow;
#ifdef HPCG_DETAILED_DEBUG
HPCG_fout << " rank, globalRow, localRow = " << geom.rank << " " << currentGlobalRow << " " << A.globalToLocalMap[currentGlobalRow] << endl;
#endif
char numberOfNonzerosInRow = 0;
double * currentValuePointer = matrixValues[currentLocalRow]; // Pointer to current value in current row
global_int_t * currentIndexPointerG = mtxIndG[currentLocalRow]; // Pointer to current index in current row
for (int sz=-1; sz<=1; sz++) {
if (giz+sz>-1 && giz+sz<gnz) {
for (int sy=-1; sy<=1; sy++) {
if (giy+sy>-1 && giy+sy<gny) {
for (int sx=-1; sx<=1; sx++) {
if (gix+sx>-1 && gix+sx<gnx) {
global_int_t curcol = currentGlobalRow+sz*gnx*gny+sy*gnx+sx;
if (curcol==currentGlobalRow) {
matrixDiagonal[currentLocalRow] = currentValuePointer;
*currentValuePointer++ = 27.0;
} else {
*currentValuePointer++ = -1.0;
}
*currentIndexPointerG++ = curcol;
numberOfNonzerosInRow++;
} // end x bounds test
} // end sx loop
} // end y bounds test
} // end sy loop
} // end z bounds test
} // end sz loop
nonzerosInRow[currentLocalRow] = numberOfNonzerosInRow;
#ifndef HPCG_NOOPENMP
#pragma omp critical
#endif
localNumberOfNonzeros += numberOfNonzerosInRow; // Protect this with an atomic
(*x)[currentLocalRow] = 0.0;
(*b)[currentLocalRow] = 27.0 - ((double) (numberOfNonzerosInRow-1));
(*xexact)[currentLocalRow] = 1.0;
} // end ix loop
} // end iy loop
} // end iz loop
#ifdef HPCG_DETAILED_DEBUG
HPCG_fout << "Process " << geom.rank << " of " << geom.size <<" has " << localNumberOfRows << " rows." << endl
<< "Process " << geom.rank << " of " << geom.size <<" has " << localNumberOfNonzeros<< " nonzeros." <<endl;
#endif
global_int_t totalNumberOfNonzeros = 0;
#ifndef HPCG_NOMPI
// Use MPI's reduce function to sum all nonzeros
#ifdef HPCG_NO_LONG_LONG
MPI_Allreduce(&localNumberOfNonzeros, &totalNumberOfNonzeros, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
#else
long long lnnz = localNumberOfNonzeros, gnnz = 0; // convert to 64 bit for MPI call
MPI_Allreduce(&lnnz, &gnnz, 1, MPI_LONG_LONG_INT, MPI_SUM, MPI_COMM_WORLD);
totalNumberOfNonzeros = gnnz; // Copy back
#endif
#else
totalNumberOfNonzeros = localNumberOfNonzeros;
#endif
// If this assert fails, it most likely means that the global_int_t is set to int and should be set to long long
// This assert is usually the first to fail as problem size increases beyond the 32-bit integer range.
assert(totalNumberOfNonzeros>0); // Throw an exception of the number of nonzeros is less than zero (can happen if int overflow)
A.title = 0;
A.totalNumberOfRows = totalNumberOfRows;
A.totalNumberOfNonzeros = totalNumberOfNonzeros;
A.localNumberOfRows = localNumberOfRows;
A.localNumberOfColumns = localNumberOfRows;
A.localNumberOfNonzeros = localNumberOfNonzeros;
A.nonzerosInRow = nonzerosInRow;
A.mtxIndG = mtxIndG;
A.mtxIndL = mtxIndL;
A.matrixValues = matrixValues;
A.matrixDiagonal = matrixDiagonal;
return;
}
<|endoftext|> |
<commit_before>#include <cv.h>
#include <highgui.h>
#include <iostream>
using namespace cv;
using namespace std;
void help(){
cout << "This is Crative Commons work, do what you like... " << endl;
cout << "Usage: ./binary <image_name> " << endl;
cout << "Hot keys: \n"
"\tr/R toggle croping \n"
"\tc/C toggle camera \n"
"\ts/S toggle taking screenshoot\n"
"\th/H toggle Hough Transform on screenshot\n"
"\te/E toggle edge detetction \n"
"\tt/T toggle template matching\n";
}
void canny_edge();
void cannyTreshold( int, void* );
void cannyTreshold2( int, void* );
void init_camera();
void onMouse( int event, int x, int y, int flags, void* param );
void draw_box( Mat& img, Rect rect );
void crop_image( Mat& img, Rect rect );
void match_template_on_crop( int match_method, Mat& templ );
void getPoints( int event, int x, int y, int flags, void* param );
void savePoint( int x, int y );
void callHoughTransform( );
void cannyForHT( Mat& img, Rect rect );
Mat temp, mat_image, gray_image, frame, ss;
Mat templ, result, imgRoi, imgRoi2;
Mat dst, detected_edges;
Point pt1, pt2, pt3, pt4;
vector<Point2f> imagePoints(4);
int n;
Rect box, box2;
bool drawing_box = false;
char ** global_argv;
int match_method = 0;
int lowThreshold;
int ratio = 3;
int const max_lowThreshold = 100;
int main(int argc, char** argv) {
help();
global_argv = argv;
if (argc < 2) {
cout << " Usage: "<< argv[0] <<" <image> " << endl;
return -1;
}
char* imageName = argv[1];
mat_image = imread( imageName, CV_LOAD_IMAGE_COLOR);
if( !mat_image.data ) {
cout << " Could not open or find the image" << endl;
return -1;
}
while ( 1 ){
namedWindow( imageName, CV_WINDOW_AUTOSIZE );
imshow( imageName, mat_image );
char c = waitKey(10);
switch( c )
{
case 27:
cout << "Exiting ... \n ";
return 0;
case 'e':
canny_edge();
break;
case 'E':
destroyWindow("canny edge");
break;
case 'r':
cout << "Setting callback, calling crop_image ...\n";
setMouseCallback( imageName, onMouse, (void*)&mat_image );
break;
case 'R':
destroyWindow( "ImgROI" );
break;
case 'c':
init_camera();
break;
case 't':
match_template_on_crop( 2, imgRoi );
break;
case 'T':
destroyWindow( "source" );
destroyWindow( "result" );
break;
case 'S':
destroyWindow( "snapshot" );
break;
case 'h':
cannyForHT( ss, box2 );
//callHoughTransform( ss, box2 );
break;
case 'H':
callHoughTransform( );
break;
}
}
return 0;
}
void onMouse( int event, int x, int y, int flags, void* param ) {
Mat& image = *(Mat*) param;
switch( event )
{
case CV_EVENT_LBUTTONDOWN:
drawing_box = true;
box = Rect(x, y, 0, 0);
break;
case CV_EVENT_MOUSEMOVE:
if( drawing_box ) {
box.width = x-box.x;
box.height = y-box.y;
}
break;
case CV_EVENT_LBUTTONUP:
drawing_box = false;
if( box.width<0 ) {
box.x+=box.width;
box.width *= -1;
}
if( box.height<0 ) {
box.y+=box.height;
box.height*=-1;
}
cout << "box coordinates \n"
<< "x\t y\t height\t width\n"
<< box.x << "\t" << box.y << "\t"
<< box.height << "\t" << box.width << "\n";
crop_image( image, box);
draw_box( image, box );
break;
}
}
void draw_box( Mat& img, Rect rect ){
rectangle( img, rect.tl(), rect.br(), Scalar(0,0,255));
}
void crop_image( Mat& img, Rect rect ){
imgRoi = img( rect );
namedWindow( "ImgROI", CV_WINDOW_AUTOSIZE );
imshow( "ImgROI", imgRoi );
/* gornji kod kopira samo header u imgRoi
* ako treba kopirat i sliku moze se ovako:
imgRoi.copyTo(temp);
namedWindow( "temp", CV_WINDOW_AUTOSIZE );
imshow( "temp", temp );
*/
}
void canny_edge(){
cout << "calling canny... \n";
cvtColor( mat_image, gray_image, CV_RGB2GRAY);
namedWindow( "canny edge", CV_WINDOW_AUTOSIZE);
createTrackbar( "Min Treshold: ", "canny edge", &lowThreshold, max_lowThreshold, cannyTreshold );
}
void cannyTreshold( int, void* ){
Canny( gray_image, detected_edges, lowThreshold, lowThreshold*ratio, 3 );
dst = Scalar::all(0);
gray_image.copyTo( dst, detected_edges);
imshow( "canny edge", dst);
}
void init_camera(){
cout << "Starting camera mode... \n";
VideoCapture cap(0);
if( !cap.isOpened() ){
cerr << "fail preko default camere \n";
cout << "isprobavam argv2 "
<< global_argv[2] << endl;
cap.open( global_argv[2] );
if( !cap.isOpened() ){
cerr << "fail i preko argv[2] \n";
}
}
while( 1 ){
cap >> frame;
if(!frame.data) break;
namedWindow( "camera", CV_WINDOW_AUTOSIZE );
imshow( "camera", frame );
char c = waitKey(10);
if( c == 'C' ){
destroyWindow("camera");
break;
}
switch ( c ) {
case 's':
frame.copyTo( ss );
namedWindow( "snapshot", CV_WINDOW_AUTOSIZE );
imshow( "snapshot", ss );
cout << " Setting MouseCallback getPoints " << endl;
setMouseCallback( "snapshot", getPoints, 0 );
break;
}
}
}
void match_template_on_crop( int match_method, Mat& templ ){
/// Source image to display
Mat img_display;
mat_image.copyTo( img_display );
/// Create the result matrix
int result_cols = mat_image.cols - templ.cols + 1;
int result_rows = mat_image.rows - templ.rows + 1;
result.create( result_cols, result_rows, CV_32FC1 );
/// Do the Matching and Normalize
matchTemplate( mat_image, templ, result, match_method );
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
/// Localizing the best match with minMaxLoc
double minVal; double maxVal; Point minLoc; Point maxLoc;
Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
{ matchLoc = minLoc; }
else
{ matchLoc = maxLoc; }
/// Show me what you got
rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
namedWindow( "source", CV_WINDOW_AUTOSIZE );
namedWindow( "result", CV_WINDOW_AUTOSIZE );
imshow( "source", img_display );
imshow( "result", result );
}
void savePoint( int x, int y ){
n++;
if ( n == 1 ){
pt1.x = x;
pt1.y = y;
imagePoints[0] = Point2f( x, y );
cout << pt1.x << " " << pt1.y << endl;
}
if ( n == 2 ){
pt2.x = x;
pt2.y = y;
imagePoints[1] = Point2f( x, y );
cout << pt2.x << " " << pt2.y << endl;
}
if ( n == 3 ){
pt3.x = x;
pt3.y = y;
imagePoints[2] = Point2f( x, y );
cout << pt3.x << " " << pt3.y << endl;
}
if ( n == 4 ){
pt4.x = x;
pt4.y = y;
imagePoints[3] = Point2f( x, y );
box2.x = pt1.x;
box2.y = pt1.y;
box2.width = pt4.x - box2.x;
box2.height = pt4.y - box2.y;
cout << pt4.x << " " << pt4.y << endl;
cout << box2.width << " " << box2.height << endl;
}
}
void getPoints( int event, int x, int y, int flags, void* param ) {
switch( event ) {
case CV_EVENT_LBUTTONDOWN:
break;
case CV_EVENT_LBUTTONUP:
savePoint( x, y );
break;
}
}
void cannyTreshold2( int, void* ){
Canny( temp, detected_edges, lowThreshold, lowThreshold*ratio, 3 );
dst = Scalar::all(0);
temp.copyTo( dst, detected_edges);
imshow( "imageRoi2", dst);
}
void cannyForHT( Mat& img, Rect rect ){
imgRoi2 = img( rect );
cvtColor( imgRoi2, temp, CV_RGB2GRAY);
namedWindow( "imageRoi2", CV_WINDOW_AUTOSIZE);
createTrackbar( "Min Treshold: ", "imageRoi2", &lowThreshold, max_lowThreshold, cannyTreshold2 );
}
void callHoughTransform( ){
vector<Vec2f> lines;
HoughLines( temp, lines, 1, CV_PI/180, 100, 0, 0 );
// temp nije output edge detectora, treba izmjeniti
/*
temp: Output of the edge detector.
lines: A vector that will store the parameters (r,\theta) of the detected lines
*/
// izvuci prvu linija, koja bi trebala vektor od dva elementa
// ro'' i theta
// prebacit ro u k.s. slike a ne ROI ro=ro'' +pt1.x*cos theta +
// +pt1.y*sin theta
// findExtrinsci, predat xml, vraca R koji treba konvertirit u 3*3 pogledi rodrigez,
// pomonzit R i P(iz xml, camera matrix) jedanko A
// pomnozit t i P dobijemo B
// dobijemo lamde
//
float rho, rho_roi, theta;
rho_roi= lines[0][0];
theta = lines[0][1];
// prebacivanje u k.s. slike
rho = rho_roi + pt1.x * cos( theta ) + pt1.y * sin( theta );
// ucitavanje
FileStorage fs("calib/cam.xml", FileStorage::READ);
cout << "procitao " << rho << " " << theta << endl;
Mat intrinsics, distortion;
fs["camera_matrix"] >> intrinsics; //3*3
fs["distortion_coefficients"] >> distortion; //4*1, kod mene 5*1
cout << "intrinsics = " << intrinsics << endl;
cout << "distortion = " << distortion << endl;
vector<Point3f> objectPoints(4);
objectPoints[0] = Point3f( 0, 0, 0 );
objectPoints[1] = Point3f( 0, 0, 0 );
objectPoints[2] = Point3f( 0, 0, 0 );
objectPoints[3] = Point3f( 0, 0, 0 );
cout << "A vector of 3D Object Points = " << objectPoints << endl << endl;
cout << "A vector of 2D Image Points = " << imagePoints << endl << endl;
Mat rvec( 1, 3, CV_32FC1 );
Mat tvec( 1, 3, CV_32FC1 );
Mat R( 3, 3, CV_32FC1 );
Mat A( 3, 3, CV_32FC1 );
Mat B( 3, 1, CV_32FC1 );
//cvFindExtrinsicCameraParams2() je zamjenjen s solvePnP()
solvePnP( Mat(objectPoints), Mat(imagePoints), intrinsics, distortion, rvec, tvec, false );
cout << "rvec = " << rvec << endl;
cout << "tvec = " << tvec << endl;
Rodrigues( rvec, R );
transpose( tvec, B );
cout << "R = " << R << endl;
cout << "B = " << B << endl;
}
<commit_msg>mnozenje<commit_after>#include <cv.h>
#include <highgui.h>
#include <iostream>
using namespace cv;
using namespace std;
void help(){
cout << "This is Crative Commons work, do what you like... " << endl;
cout << "Usage: ./binary <image_name> " << endl;
cout << "Hot keys: \n"
"\tr/R toggle croping \n"
"\tc/C toggle camera \n"
"\ts/S toggle taking screenshoot\n"
"\th/H toggle Hough Transform on screenshot\n"
"\te/E toggle edge detetction \n"
"\tt/T toggle template matching\n";
}
void canny_edge();
void cannyTreshold( int, void* );
void cannyTreshold2( int, void* );
void init_camera();
void onMouse( int event, int x, int y, int flags, void* param );
void draw_box( Mat& img, Rect rect );
void crop_image( Mat& img, Rect rect );
void match_template_on_crop( int match_method, Mat& templ );
void getPoints( int event, int x, int y, int flags, void* param );
void savePoint( int x, int y );
void callHoughTransform( );
void cannyForHT( Mat& img, Rect rect );
Mat temp, mat_image, gray_image, frame, ss;
Mat templ, result, imgRoi, imgRoi2;
Mat dst, detected_edges;
Point pt1, pt2, pt3, pt4;
vector<Point2f> imagePoints(4);
int n;
Rect box, box2;
bool drawing_box = false;
char ** global_argv;
int match_method = 0;
int lowThreshold;
int ratio = 3;
int const max_lowThreshold = 100;
int main(int argc, char** argv) {
help();
global_argv = argv;
if (argc < 2) {
cout << " Usage: "<< argv[0] <<" <image> " << endl;
return -1;
}
char* imageName = argv[1];
mat_image = imread( imageName, CV_LOAD_IMAGE_COLOR);
if( !mat_image.data ) {
cout << " Could not open or find the image" << endl;
return -1;
}
while ( 1 ){
namedWindow( imageName, CV_WINDOW_AUTOSIZE );
imshow( imageName, mat_image );
char c = waitKey(10);
switch( c )
{
case 27:
cout << "Exiting ... \n ";
return 0;
case 'e':
canny_edge();
break;
case 'E':
destroyWindow("canny edge");
break;
case 'r':
cout << "Setting callback, calling crop_image ...\n";
setMouseCallback( imageName, onMouse, (void*)&mat_image );
break;
case 'R':
destroyWindow( "ImgROI" );
break;
case 'c':
init_camera();
break;
case 't':
match_template_on_crop( 2, imgRoi );
break;
case 'T':
destroyWindow( "source" );
destroyWindow( "result" );
break;
case 'S':
destroyWindow( "snapshot" );
break;
case 'h':
cannyForHT( ss, box2 );
//callHoughTransform( ss, box2 );
break;
case 'H':
callHoughTransform( );
break;
}
}
return 0;
}
void onMouse( int event, int x, int y, int flags, void* param ) {
Mat& image = *(Mat*) param;
switch( event )
{
case CV_EVENT_LBUTTONDOWN:
drawing_box = true;
box = Rect(x, y, 0, 0);
break;
case CV_EVENT_MOUSEMOVE:
if( drawing_box ) {
box.width = x-box.x;
box.height = y-box.y;
}
break;
case CV_EVENT_LBUTTONUP:
drawing_box = false;
if( box.width<0 ) {
box.x+=box.width;
box.width *= -1;
}
if( box.height<0 ) {
box.y+=box.height;
box.height*=-1;
}
cout << "box coordinates \n"
<< "x\t y\t height\t width\n"
<< box.x << "\t" << box.y << "\t"
<< box.height << "\t" << box.width << "\n";
crop_image( image, box);
draw_box( image, box );
break;
}
}
void draw_box( Mat& img, Rect rect ){
rectangle( img, rect.tl(), rect.br(), Scalar(0,0,255));
}
void crop_image( Mat& img, Rect rect ){
imgRoi = img( rect );
namedWindow( "ImgROI", CV_WINDOW_AUTOSIZE );
imshow( "ImgROI", imgRoi );
/* gornji kod kopira samo header u imgRoi
* ako treba kopirat i sliku moze se ovako:
imgRoi.copyTo(temp);
namedWindow( "temp", CV_WINDOW_AUTOSIZE );
imshow( "temp", temp );
*/
}
void canny_edge(){
cout << "calling canny... \n";
cvtColor( mat_image, gray_image, CV_RGB2GRAY);
namedWindow( "canny edge", CV_WINDOW_AUTOSIZE);
createTrackbar( "Min Treshold: ", "canny edge", &lowThreshold, max_lowThreshold, cannyTreshold );
}
void cannyTreshold( int, void* ){
Canny( gray_image, detected_edges, lowThreshold, lowThreshold*ratio, 3 );
dst = Scalar::all(0);
gray_image.copyTo( dst, detected_edges);
imshow( "canny edge", dst);
}
void init_camera(){
cout << "Starting camera mode... \n";
VideoCapture cap(0);
if( !cap.isOpened() ){
cerr << "fail preko default camere \n";
cout << "isprobavam argv2 "
<< global_argv[2] << endl;
cap.open( global_argv[2] );
if( !cap.isOpened() ){
cerr << "fail i preko argv[2] \n";
}
}
while( 1 ){
cap >> frame;
if(!frame.data) break;
namedWindow( "camera", CV_WINDOW_AUTOSIZE );
imshow( "camera", frame );
char c = waitKey(10);
if( c == 'C' ){
destroyWindow("camera");
break;
}
switch ( c ) {
case 's':
frame.copyTo( ss );
namedWindow( "snapshot", CV_WINDOW_AUTOSIZE );
imshow( "snapshot", ss );
cout << " Setting MouseCallback getPoints " << endl;
setMouseCallback( "snapshot", getPoints, 0 );
break;
}
}
}
void match_template_on_crop( int match_method, Mat& templ ){
/// Source image to display
Mat img_display;
mat_image.copyTo( img_display );
/// Create the result matrix
int result_cols = mat_image.cols - templ.cols + 1;
int result_rows = mat_image.rows - templ.rows + 1;
result.create( result_cols, result_rows, CV_32FC1 );
/// Do the Matching and Normalize
matchTemplate( mat_image, templ, result, match_method );
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
/// Localizing the best match with minMaxLoc
double minVal; double maxVal; Point minLoc; Point maxLoc;
Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
{ matchLoc = minLoc; }
else
{ matchLoc = maxLoc; }
/// Show me what you got
rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
namedWindow( "source", CV_WINDOW_AUTOSIZE );
namedWindow( "result", CV_WINDOW_AUTOSIZE );
imshow( "source", img_display );
imshow( "result", result );
}
void savePoint( int x, int y ){
n++;
if ( n == 1 ){
pt1.x = x;
pt1.y = y;
imagePoints[0] = Point2f( x, y );
cout << pt1.x << " " << pt1.y << endl;
}
if ( n == 2 ){
pt2.x = x;
pt2.y = y;
imagePoints[1] = Point2f( x, y );
cout << pt2.x << " " << pt2.y << endl;
}
if ( n == 3 ){
pt3.x = x;
pt3.y = y;
imagePoints[2] = Point2f( x, y );
cout << pt3.x << " " << pt3.y << endl;
}
if ( n == 4 ){
pt4.x = x;
pt4.y = y;
imagePoints[3] = Point2f( x, y );
box2.x = pt1.x;
box2.y = pt1.y;
box2.width = pt4.x - box2.x;
box2.height = pt4.y - box2.y;
cout << pt4.x << " " << pt4.y << endl;
cout << box2.width << " " << box2.height << endl;
}
}
void getPoints( int event, int x, int y, int flags, void* param ) {
switch( event ) {
case CV_EVENT_LBUTTONDOWN:
break;
case CV_EVENT_LBUTTONUP:
savePoint( x, y );
break;
}
}
void cannyTreshold2( int, void* ){
Canny( temp, detected_edges, lowThreshold, lowThreshold*ratio, 3 );
dst = Scalar::all(0);
temp.copyTo( dst, detected_edges);
imshow( "imageRoi2", dst);
}
void cannyForHT( Mat& img, Rect rect ){
imgRoi2 = img( rect );
cvtColor( imgRoi2, temp, CV_RGB2GRAY);
namedWindow( "imageRoi2", CV_WINDOW_AUTOSIZE);
createTrackbar( "Min Treshold: ", "imageRoi2", &lowThreshold, max_lowThreshold, cannyTreshold2 );
}
void callHoughTransform( ){
vector<Vec2f> lines;
HoughLines( temp, lines, 1, CV_PI/180, 100, 0, 0 );
// temp nije output edge detectora, treba izmjeniti
/*
temp: Output of the edge detector.
lines: A vector that will store the parameters (r,\theta) of the detected lines
*/
// izvuci prvu linija, koja bi trebala vektor od dva elementa
// ro'' i theta
// prebacit ro u k.s. slike a ne ROI ro=ro'' +pt1.x*cos theta +
// +pt1.y*sin theta
// findExtrinsci, predat xml, vraca R koji treba konvertirit u 3*3 pogledi rodrigez,
// pomonzit R i P(iz xml, camera matrix) jedanko A
// pomnozit t i P dobijemo B
// dobijemo lamde
//
float rho, rho_roi, theta;
rho_roi= lines[0][0];
theta = lines[0][1];
// prebacivanje u k.s. slike
rho = rho_roi + pt1.x * cos( theta ) + pt1.y * sin( theta );
// ucitavanje
FileStorage fs("calib/cam.xml", FileStorage::READ);
cout << "procitao " << rho << " " << theta << endl;
Mat intrinsics, distortion;
fs["camera_matrix"] >> intrinsics; //3*3
fs["distortion_coefficients"] >> distortion; //4*1, kod mene 5*1
cout << "intrinsics = " << intrinsics << endl;
cout << "distortion = " << distortion << endl;
vector<Point3f> objectPoints(4);
objectPoints[0] = Point3f( 0, 0, 0 );
objectPoints[1] = Point3f( 0, 0, 0 );
objectPoints[2] = Point3f( 0, 0, 0 );
objectPoints[3] = Point3f( 0, 0, 0 );
cout << "A vector of 3D Object Points = " << objectPoints << endl << endl;
cout << "A vector of 2D Image Points = " << imagePoints << endl << endl;
Mat rvec( 1, 3, CV_32FC1 );
Mat tvec( 1, 3, CV_32FC1 );
Mat R( 3, 3, CV_32FC1 );
Mat A( 3, 3, CV_32FC1 );
Mat B( 3, 1, CV_32FC1 );
//cvFindExtrinsicCameraParams2() je zamjenjen s solvePnP()
solvePnP( Mat(objectPoints), Mat(imagePoints), intrinsics, distortion, rvec, tvec, false );
cout << "rvec = " << rvec << endl;
cout << "tvec = " << tvec << endl;
Rodrigues( rvec, R );
transpose( tvec, B );
cout << "R = " << R << endl;
cout << "B = " << B << endl;
A = intrinsics * R;
cout << "A = " << A << endl;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#ifndef MFEM_NONLININTEG
#define MFEM_NONLININTEG
#include "../config/config.hpp"
#include "fe.hpp"
#include "coefficient.hpp"
namespace mfem
{
/** The abstract base class NonlinearFormIntegrator is used to express the
local action of a general nonlinear finite element operator. In addition
it may provide the capability to assemble the local gradient operator
and to compute the local energy. */
class NonlinearFormIntegrator
{
protected:
const IntegrationRule *IntRule;
NonlinearFormIntegrator(const IntegrationRule *ir = NULL)
: IntRule(NULL) { }
public:
/** @brief Prescribe a fixed IntegrationRule to use (when @a ir != NULL) or
let the integrator choose (when @a ir == NULL). */
void SetIntRule(const IntegrationRule *ir) { IntRule = ir; }
/// Prescribe a fixed IntegrationRule to use.
void SetIntegrationRule(const IntegrationRule &irule) { IntRule = &irule; }
/// Perform the local action of the NonlinearFormIntegrator
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &Tr,
const Vector &elfun, Vector &elvect);
/// @brief Perform the local action of the NonlinearFormIntegrator resulting
/// from a face integral term.
virtual void AssembleFaceVector(const FiniteElement &el1,
const FiniteElement &el2,
FaceElementTransformations &Tr,
const Vector &elfun, Vector &elvect);
/// Assemble the local gradient matrix
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &Tr,
const Vector &elfun, DenseMatrix &elmat);
/// @brief Assemble the local action of the gradient of the
/// NonlinearFormIntegrator resulting from a face integral term.
virtual void AssembleFaceGrad(const FiniteElement &el1,
const FiniteElement &el2,
FaceElementTransformations &Tr,
const Vector &elfun, DenseMatrix &elmat);
/// Compute the local energy
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &Tr,
const Vector &elfun);
virtual ~NonlinearFormIntegrator() { }
};
/** The abstract base class BlockNonlinearFormIntegrator is
a generalization of the NonlinearFormIntegrator class suitable
for block state vectors. */
class BlockNonlinearFormIntegrator
{
public:
/// Compute the local energy
virtual double GetElementEnergy(const Array<const FiniteElement *>&el,
ElementTransformation &Tr,
const Array<const Vector *>&elfun);
/// Perform the local action of the BlockNonlinearFormIntegrator
virtual void AssembleElementVector(const Array<const FiniteElement *> &el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun,
const Array<Vector *> &elvec);
virtual void AssembleFaceVector(const Array<const FiniteElement *> &el1,
const Array<const FiniteElement *> &el2,
FaceElementTransformations &Tr,
const Array<const Vector *> &elfun,
const Array<Vector *> &elvect);
/// Assemble the local gradient matrix
virtual void AssembleElementGrad(const Array<const FiniteElement*> &el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun,
const Array2D<DenseMatrix *> &elmats);
virtual void AssembleFaceGrad(const Array<const FiniteElement *>&el1,
const Array<const FiniteElement *>&el2,
FaceElementTransformations &Tr,
const Array<const Vector *> &elfun,
const Array2D<DenseMatrix *> &elmats);
virtual ~BlockNonlinearFormIntegrator() { }
};
/// Abstract class for hyperelastic models
class HyperelasticModel
{
protected:
ElementTransformation *Ttr; /**< Reference-element to target-element
transformation. */
public:
HyperelasticModel() : Ttr(NULL) { }
virtual ~HyperelasticModel() { }
/// A reference-element to target-element transformation that can be used to
/// evaluate Coefficient%s.
/** @note It is assumed that _Ttr.SetIntPoint() is already called for the
point of interest. */
void SetTransformation(ElementTransformation &_Ttr) { Ttr = &_Ttr; }
/** @brief Evaluate the strain energy density function, W = W(Jpt).
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix. */
virtual double EvalW(const DenseMatrix &Jpt) const = 0;
/** @brief Evaluate the 1st Piola-Kirchhoff stress tensor, P = P(Jpt).
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix.
@param[out] P The evaluated 1st Piola-Kirchhoff stress tensor. */
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const = 0;
/** @brief Evaluate the derivative of the 1st Piola-Kirchhoff stress tensor
and assemble its contribution to the local gradient matrix 'A'.
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix.
@param[in] DS Gradient of the basis matrix (dof x dim).
@param[in] weight Quadrature weight coefficient for the point.
@param[in,out] A Local gradient matrix where the contribution from this
point will be added.
Computes weight * d(dW_dxi)_d(xj) at the current point, for all i and j,
where x1 ... xn are the FE dofs. This function is usually defined using
the matrix invariants and their derivatives.
*/
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const = 0;
};
/** Inverse-harmonic hyperelastic model with a strain energy density function
given by the formula: W(J) = (1/2) det(J) Tr((J J^t)^{-1}) where J is the
deformation gradient. */
class InverseHarmonicModel : public HyperelasticModel
{
protected:
mutable DenseMatrix Z, S; // dim x dim
mutable DenseMatrix G, C; // dof x dim
public:
virtual double EvalW(const DenseMatrix &J) const;
virtual void EvalP(const DenseMatrix &J, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &J, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/** Neo-Hookean hyperelastic model with a strain energy density function given
by the formula: \f$(\mu/2)(\bar{I}_1 - dim) + (K/2)(det(J)/g - 1)^2\f$ where
J is the deformation gradient and \f$\bar{I}_1 = (det(J))^{-2/dim} Tr(J
J^t)\f$. The parameters \f$\mu\f$ and K are the shear and bulk moduli,
respectively, and g is a reference volumetric scaling. */
class NeoHookeanModel : public HyperelasticModel
{
protected:
mutable double mu, K, g;
Coefficient *c_mu, *c_K, *c_g;
bool have_coeffs;
mutable DenseMatrix Z; // dim x dim
mutable DenseMatrix G, C; // dof x dim
inline void EvalCoeffs() const;
public:
NeoHookeanModel(double _mu, double _K, double _g = 1.0)
: mu(_mu), K(_K), g(_g), have_coeffs(false) { c_mu = c_K = c_g = NULL; }
NeoHookeanModel(Coefficient &_mu, Coefficient &_K, Coefficient *_g = NULL)
: mu(0.0), K(0.0), g(1.0), c_mu(&_mu), c_K(&_K), c_g(_g),
have_coeffs(true) { }
virtual double EvalW(const DenseMatrix &J) const;
virtual void EvalP(const DenseMatrix &J, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &J, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/** Hyperelastic integrator for any given HyperelasticModel.
Represents @f$ \int W(Jpt) dx @f$ over a target zone, where W is the
@a model's strain energy density function, and Jpt is the Jacobian of the
target->physical coordinates transformation. The target configuration is
given by the current mesh at the time of the evaluation of the integrator.
*/
class HyperelasticNLFIntegrator : public NonlinearFormIntegrator
{
private:
HyperelasticModel *model;
// Jrt: the Jacobian of the target-to-reference-element transformation.
// Jpr: the Jacobian of the reference-to-physical-element transformation.
// Jpt: the Jacobian of the target-to-physical-element transformation.
// P: represents dW_d(Jtp) (dim x dim).
// DSh: gradients of reference shape functions (dof x dim).
// DS: gradients of the shape functions in the target (stress-free)
// configuration (dof x dim).
// PMatI: coordinates of the deformed configuration (dof x dim).
// PMatO: reshaped view into the local element contribution to the operator
// output - the result of AssembleElementVector() (dof x dim).
DenseMatrix DSh, DS, Jrt, Jpr, Jpt, P, PMatI, PMatO;
public:
/** @param[in] m HyperelasticModel that will be integrated. */
HyperelasticNLFIntegrator(HyperelasticModel *m) : model(m) { }
/** @brief Computes the integral of W(Jacobian(Trt)) over a target zone
@param[in] el Type of FiniteElement.
@param[in] Ttr Represents ref->target coordinates transformation.
@param[in] elfun Physical coordinates of the zone. */
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &Ttr,
const Vector &elfun);
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &Ttr,
const Vector &elfun, Vector &elvect);
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &Ttr,
const Vector &elfun, DenseMatrix &elmat);
};
/** Hyperelastic incompressible Neo-Hookean integrator with the PK1 stress
\f$P = \mu F - p F^{-T}\f$ where \f$\mu\f$ is the shear modulus,
\f$p\f$ is the pressure, and \f$F\f$ is the deformation gradient */
class IncompressibleNeoHookeanIntegrator : public BlockNonlinearFormIntegrator
{
private:
Coefficient *c_mu;
DenseMatrix DSh_u, DS_u, J0i, J, J1, Finv, P, F, FinvT;
DenseMatrix PMatI_u, PMatO_u, PMatI_p, PMatO_p, Z, G, C;
Vector Sh_p;
public:
IncompressibleNeoHookeanIntegrator(Coefficient &_mu) : c_mu(&_mu) { }
virtual double GetElementEnergy(const Array<const FiniteElement *>&el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun);
/// Perform the local action of the NonlinearFormIntegrator
virtual void AssembleElementVector(const Array<const FiniteElement *> &el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun,
const Array<Vector *> &elvec);
/// Assemble the local gradient matrix
virtual void AssembleElementGrad(const Array<const FiniteElement*> &el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun,
const Array2D<DenseMatrix *> &elmats);
};
}
#endif
<commit_msg>Fixed assignment of an IntegrationRule in the constructor of NonlinearFormIntegrator.<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#ifndef MFEM_NONLININTEG
#define MFEM_NONLININTEG
#include "../config/config.hpp"
#include "fe.hpp"
#include "coefficient.hpp"
namespace mfem
{
/** The abstract base class NonlinearFormIntegrator is used to express the
local action of a general nonlinear finite element operator. In addition
it may provide the capability to assemble the local gradient operator
and to compute the local energy. */
class NonlinearFormIntegrator
{
protected:
const IntegrationRule *IntRule;
NonlinearFormIntegrator(const IntegrationRule *ir = NULL)
: IntRule(ir) { }
public:
/** @brief Prescribe a fixed IntegrationRule to use (when @a ir != NULL) or
let the integrator choose (when @a ir == NULL). */
void SetIntRule(const IntegrationRule *ir) { IntRule = ir; }
/// Prescribe a fixed IntegrationRule to use.
void SetIntegrationRule(const IntegrationRule &irule) { IntRule = &irule; }
/// Perform the local action of the NonlinearFormIntegrator
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &Tr,
const Vector &elfun, Vector &elvect);
/// @brief Perform the local action of the NonlinearFormIntegrator resulting
/// from a face integral term.
virtual void AssembleFaceVector(const FiniteElement &el1,
const FiniteElement &el2,
FaceElementTransformations &Tr,
const Vector &elfun, Vector &elvect);
/// Assemble the local gradient matrix
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &Tr,
const Vector &elfun, DenseMatrix &elmat);
/// @brief Assemble the local action of the gradient of the
/// NonlinearFormIntegrator resulting from a face integral term.
virtual void AssembleFaceGrad(const FiniteElement &el1,
const FiniteElement &el2,
FaceElementTransformations &Tr,
const Vector &elfun, DenseMatrix &elmat);
/// Compute the local energy
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &Tr,
const Vector &elfun);
virtual ~NonlinearFormIntegrator() { }
};
/** The abstract base class BlockNonlinearFormIntegrator is
a generalization of the NonlinearFormIntegrator class suitable
for block state vectors. */
class BlockNonlinearFormIntegrator
{
public:
/// Compute the local energy
virtual double GetElementEnergy(const Array<const FiniteElement *>&el,
ElementTransformation &Tr,
const Array<const Vector *>&elfun);
/// Perform the local action of the BlockNonlinearFormIntegrator
virtual void AssembleElementVector(const Array<const FiniteElement *> &el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun,
const Array<Vector *> &elvec);
virtual void AssembleFaceVector(const Array<const FiniteElement *> &el1,
const Array<const FiniteElement *> &el2,
FaceElementTransformations &Tr,
const Array<const Vector *> &elfun,
const Array<Vector *> &elvect);
/// Assemble the local gradient matrix
virtual void AssembleElementGrad(const Array<const FiniteElement*> &el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun,
const Array2D<DenseMatrix *> &elmats);
virtual void AssembleFaceGrad(const Array<const FiniteElement *>&el1,
const Array<const FiniteElement *>&el2,
FaceElementTransformations &Tr,
const Array<const Vector *> &elfun,
const Array2D<DenseMatrix *> &elmats);
virtual ~BlockNonlinearFormIntegrator() { }
};
/// Abstract class for hyperelastic models
class HyperelasticModel
{
protected:
ElementTransformation *Ttr; /**< Reference-element to target-element
transformation. */
public:
HyperelasticModel() : Ttr(NULL) { }
virtual ~HyperelasticModel() { }
/// A reference-element to target-element transformation that can be used to
/// evaluate Coefficient%s.
/** @note It is assumed that _Ttr.SetIntPoint() is already called for the
point of interest. */
void SetTransformation(ElementTransformation &_Ttr) { Ttr = &_Ttr; }
/** @brief Evaluate the strain energy density function, W = W(Jpt).
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix. */
virtual double EvalW(const DenseMatrix &Jpt) const = 0;
/** @brief Evaluate the 1st Piola-Kirchhoff stress tensor, P = P(Jpt).
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix.
@param[out] P The evaluated 1st Piola-Kirchhoff stress tensor. */
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const = 0;
/** @brief Evaluate the derivative of the 1st Piola-Kirchhoff stress tensor
and assemble its contribution to the local gradient matrix 'A'.
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix.
@param[in] DS Gradient of the basis matrix (dof x dim).
@param[in] weight Quadrature weight coefficient for the point.
@param[in,out] A Local gradient matrix where the contribution from this
point will be added.
Computes weight * d(dW_dxi)_d(xj) at the current point, for all i and j,
where x1 ... xn are the FE dofs. This function is usually defined using
the matrix invariants and their derivatives.
*/
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const = 0;
};
/** Inverse-harmonic hyperelastic model with a strain energy density function
given by the formula: W(J) = (1/2) det(J) Tr((J J^t)^{-1}) where J is the
deformation gradient. */
class InverseHarmonicModel : public HyperelasticModel
{
protected:
mutable DenseMatrix Z, S; // dim x dim
mutable DenseMatrix G, C; // dof x dim
public:
virtual double EvalW(const DenseMatrix &J) const;
virtual void EvalP(const DenseMatrix &J, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &J, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/** Neo-Hookean hyperelastic model with a strain energy density function given
by the formula: \f$(\mu/2)(\bar{I}_1 - dim) + (K/2)(det(J)/g - 1)^2\f$ where
J is the deformation gradient and \f$\bar{I}_1 = (det(J))^{-2/dim} Tr(J
J^t)\f$. The parameters \f$\mu\f$ and K are the shear and bulk moduli,
respectively, and g is a reference volumetric scaling. */
class NeoHookeanModel : public HyperelasticModel
{
protected:
mutable double mu, K, g;
Coefficient *c_mu, *c_K, *c_g;
bool have_coeffs;
mutable DenseMatrix Z; // dim x dim
mutable DenseMatrix G, C; // dof x dim
inline void EvalCoeffs() const;
public:
NeoHookeanModel(double _mu, double _K, double _g = 1.0)
: mu(_mu), K(_K), g(_g), have_coeffs(false) { c_mu = c_K = c_g = NULL; }
NeoHookeanModel(Coefficient &_mu, Coefficient &_K, Coefficient *_g = NULL)
: mu(0.0), K(0.0), g(1.0), c_mu(&_mu), c_K(&_K), c_g(_g),
have_coeffs(true) { }
virtual double EvalW(const DenseMatrix &J) const;
virtual void EvalP(const DenseMatrix &J, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &J, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/** Hyperelastic integrator for any given HyperelasticModel.
Represents @f$ \int W(Jpt) dx @f$ over a target zone, where W is the
@a model's strain energy density function, and Jpt is the Jacobian of the
target->physical coordinates transformation. The target configuration is
given by the current mesh at the time of the evaluation of the integrator.
*/
class HyperelasticNLFIntegrator : public NonlinearFormIntegrator
{
private:
HyperelasticModel *model;
// Jrt: the Jacobian of the target-to-reference-element transformation.
// Jpr: the Jacobian of the reference-to-physical-element transformation.
// Jpt: the Jacobian of the target-to-physical-element transformation.
// P: represents dW_d(Jtp) (dim x dim).
// DSh: gradients of reference shape functions (dof x dim).
// DS: gradients of the shape functions in the target (stress-free)
// configuration (dof x dim).
// PMatI: coordinates of the deformed configuration (dof x dim).
// PMatO: reshaped view into the local element contribution to the operator
// output - the result of AssembleElementVector() (dof x dim).
DenseMatrix DSh, DS, Jrt, Jpr, Jpt, P, PMatI, PMatO;
public:
/** @param[in] m HyperelasticModel that will be integrated. */
HyperelasticNLFIntegrator(HyperelasticModel *m) : model(m) { }
/** @brief Computes the integral of W(Jacobian(Trt)) over a target zone
@param[in] el Type of FiniteElement.
@param[in] Ttr Represents ref->target coordinates transformation.
@param[in] elfun Physical coordinates of the zone. */
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &Ttr,
const Vector &elfun);
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &Ttr,
const Vector &elfun, Vector &elvect);
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &Ttr,
const Vector &elfun, DenseMatrix &elmat);
};
/** Hyperelastic incompressible Neo-Hookean integrator with the PK1 stress
\f$P = \mu F - p F^{-T}\f$ where \f$\mu\f$ is the shear modulus,
\f$p\f$ is the pressure, and \f$F\f$ is the deformation gradient */
class IncompressibleNeoHookeanIntegrator : public BlockNonlinearFormIntegrator
{
private:
Coefficient *c_mu;
DenseMatrix DSh_u, DS_u, J0i, J, J1, Finv, P, F, FinvT;
DenseMatrix PMatI_u, PMatO_u, PMatI_p, PMatO_p, Z, G, C;
Vector Sh_p;
public:
IncompressibleNeoHookeanIntegrator(Coefficient &_mu) : c_mu(&_mu) { }
virtual double GetElementEnergy(const Array<const FiniteElement *>&el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun);
/// Perform the local action of the NonlinearFormIntegrator
virtual void AssembleElementVector(const Array<const FiniteElement *> &el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun,
const Array<Vector *> &elvec);
/// Assemble the local gradient matrix
virtual void AssembleElementGrad(const Array<const FiniteElement*> &el,
ElementTransformation &Tr,
const Array<const Vector *> &elfun,
const Array2D<DenseMatrix *> &elmats);
};
}
#endif
<|endoftext|> |
<commit_before>//
// This file is a part of pomerol - a scientific ED code for obtaining
// properties of a Hubbard model on a finite-size lattice
//
// Copyright (C) 2010-2012 Andrey Antipov <antipov@ct-qmc.org>
// Copyright (C) 2010-2012 Igor Krivenko <igor@shg.ru>
//
// pomerol is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// pomerol 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 pomerol. If not, see <http://www.gnu.org/licenses/>.
#include"HamiltonianPart.h"
#include"StatesClassification.h"
#include<sstream>
#include<Eigen/Eigenvalues>
// class HamiltonianPart
namespace Pomerol{
HamiltonianPart::HamiltonianPart(const IndexClassification& IndexInfo, const IndexHamiltonian &F, const StatesClassification &S, const BlockNumber& Block):
ComputableObject(Constructed),IndexInfo(IndexInfo), F(F), S(S), Block(Block), QN(S.getQuantumNumbers(Block))
{
}
void HamiltonianPart::prepare()
{
size_t BlockSize = S.getBlockSize(Block);
H.resize(BlockSize,BlockSize);
H.setZero();
std::map<FockState,MelemType>::const_iterator melem_it;
for(InnerQuantumState right_st=0; right_st<BlockSize; right_st++)
{
FockState ket = S.getFockState(Block,right_st);
std::map<FockState,MelemType> mapStates = F.actRight(ket);
for (melem_it=mapStates.begin(); melem_it!=mapStates.end(); melem_it++) {
FockState bra = melem_it -> first;
MelemType melem = melem_it -> second;
InnerQuantumState left_st = S.getInnerState(bra);
// if (left_st > right_st) { ERROR("!"); exit(1); };
H(left_st,right_st) = melem;
}
}
// H.triangularView<Eigen::Lower>() = H.triangularView<Eigen::Upper>().transpose();
assert(MatrixType(H.triangularView<Eigen::Lower>()) == MatrixType(H.triangularView<Eigen::Upper>().transpose()));
Status = Prepared;
}
void HamiltonianPart::diagonalize() //method of diagonalization classificated part of Hamiltonian
{
if (Status >= Diagonalized) return;
if (H.rows() == 1) {
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
assert (std::abs(H(0,0) - std::real(H(0,0))) < std::numeric_limits<RealType>::epsilon());
#endif
Eigenvalues.resize(1);
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
Eigenvalues << std::real(H(0,0));
#else
Eigenvalues << H(0,0);
#endif
H(0,0) = 1;
}
else {
Eigen::SelfAdjointEigenSolver<MatrixType> Solver(H,Eigen::ComputeEigenvectors);
H = Solver.eigenvectors();
Eigenvalues = Solver.eigenvalues(); // eigenvectors are ready
}
Status = Diagonalized;
}
MelemType HamiltonianPart::getMatrixElement(InnerQuantumState m, InnerQuantumState n) const //return H(m,n)
{
return H(m,n);
}
RealType HamiltonianPart::getEigenValue(InnerQuantumState state) const // return Eigenvalues(state)
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
return Eigenvalues(state);
}
const RealVectorType& HamiltonianPart::getEigenValues() const
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
return Eigenvalues;
}
InnerQuantumState HamiltonianPart::getSize(void) const
{
return H.rows();
}
BlockNumber HamiltonianPart::getBlockNumber(void) const
{
return S.getBlockNumber(QN);
}
void HamiltonianPart::print_to_screen() const
{
INFO(H << std::endl);
}
const MatrixType& HamiltonianPart::getMatrix() const
{
return H;
}
VectorType HamiltonianPart::getEigenState(InnerQuantumState state) const
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
return H.col(state);
}
RealType HamiltonianPart::getMinimumEigenvalue() const
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
return Eigenvalues.minCoeff();
}
bool HamiltonianPart::reduce(RealType ActualCutoff)
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
InnerQuantumState counter=0;
for (counter=0; (counter< (unsigned int)Eigenvalues.size() && Eigenvalues[counter]<=ActualCutoff); ++counter){};
std::cout << "Left " << counter << " eigenvalues : " << std::endl;
if (counter)
{std::cout << Eigenvalues.head(counter) << std::endl << "_________" << std::endl;
Eigenvalues = Eigenvalues.head(counter);
H = H.topLeftCorner(counter,counter);
return true;
}
else return false;
}
void HamiltonianPart::save(H5::CommonFG* RootGroup) const
{
HDF5Storage::saveInt(RootGroup,"Block",Block);
HDF5Storage::saveRealVector(RootGroup,"V",Eigenvalues);
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
HDF5Storage::saveMatrix(RootGroup,"H",H);
#else
HDF5Storage::saveRealMatrix(RootGroup,"H",H);
#endif
}
void HamiltonianPart::load(const H5::CommonFG* RootGroup)
{
int Block_temp = HDF5Storage::loadInt(RootGroup,"Block");
if(! (Block_temp == (int) Block))
throw(H5::DataSetIException("HamiltonianPart::load()",
"Data in the storage is for another set of quantum numbers."));
HDF5Storage::loadRealVector(RootGroup,"V",Eigenvalues);
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
HDF5Storage::loadMatrix(RootGroup,"H",H);
#else
HDF5Storage::loadRealMatrix(RootGroup,"H",H);
#endif
Status = Diagonalized;
}
#ifdef POMEROL_USE_PLAIN_SAVE
bool HamiltonianPart::savetxt(const boost::filesystem::path &path)
{
return true;
}
#endif
} // end of namespace Pomerol
<commit_msg>Changed adjoint Hamiltonian assertion<commit_after>//
// This file is a part of pomerol - a scientific ED code for obtaining
// properties of a Hubbard model on a finite-size lattice
//
// Copyright (C) 2010-2012 Andrey Antipov <antipov@ct-qmc.org>
// Copyright (C) 2010-2012 Igor Krivenko <igor@shg.ru>
//
// pomerol is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// pomerol 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 pomerol. If not, see <http://www.gnu.org/licenses/>.
#include"HamiltonianPart.h"
#include"StatesClassification.h"
#include<sstream>
#include<Eigen/Eigenvalues>
// class HamiltonianPart
namespace Pomerol{
HamiltonianPart::HamiltonianPart(const IndexClassification& IndexInfo, const IndexHamiltonian &F, const StatesClassification &S, const BlockNumber& Block):
ComputableObject(Constructed),IndexInfo(IndexInfo), F(F), S(S), Block(Block), QN(S.getQuantumNumbers(Block))
{
}
void HamiltonianPart::prepare()
{
size_t BlockSize = S.getBlockSize(Block);
H.resize(BlockSize,BlockSize);
H.setZero();
std::map<FockState,MelemType>::const_iterator melem_it;
for(InnerQuantumState right_st=0; right_st<BlockSize; right_st++)
{
FockState ket = S.getFockState(Block,right_st);
std::map<FockState,MelemType> mapStates = F.actRight(ket);
for (melem_it=mapStates.begin(); melem_it!=mapStates.end(); melem_it++) {
FockState bra = melem_it -> first;
MelemType melem = melem_it -> second;
InnerQuantumState left_st = S.getInnerState(bra);
// if (left_st > right_st) { ERROR("!"); exit(1); };
H(left_st,right_st) = melem;
}
}
// H.triangularView<Eigen::Lower>() = H.triangularView<Eigen::Upper>().transpose();
// assert(MatrixType(H.triangularView<Eigen::Lower>()) == MatrixType(H.triangularView<Eigen::Upper>().transpose()));
assert(H.adjoint() == H);
Status = Prepared;
}
void HamiltonianPart::diagonalize() //method of diagonalization classificated part of Hamiltonian
{
if (Status >= Diagonalized) return;
if (H.rows() == 1) {
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
assert (std::abs(H(0,0) - std::real(H(0,0))) < std::numeric_limits<RealType>::epsilon());
#endif
Eigenvalues.resize(1);
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
Eigenvalues << std::real(H(0,0));
#else
Eigenvalues << H(0,0);
#endif
H(0,0) = 1;
}
else {
Eigen::SelfAdjointEigenSolver<MatrixType> Solver(H,Eigen::ComputeEigenvectors);
H = Solver.eigenvectors();
Eigenvalues = Solver.eigenvalues(); // eigenvectors are ready
}
Status = Diagonalized;
}
MelemType HamiltonianPart::getMatrixElement(InnerQuantumState m, InnerQuantumState n) const //return H(m,n)
{
return H(m,n);
}
RealType HamiltonianPart::getEigenValue(InnerQuantumState state) const // return Eigenvalues(state)
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
return Eigenvalues(state);
}
const RealVectorType& HamiltonianPart::getEigenValues() const
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
return Eigenvalues;
}
InnerQuantumState HamiltonianPart::getSize(void) const
{
return H.rows();
}
BlockNumber HamiltonianPart::getBlockNumber(void) const
{
return S.getBlockNumber(QN);
}
void HamiltonianPart::print_to_screen() const
{
INFO(H << std::endl);
}
const MatrixType& HamiltonianPart::getMatrix() const
{
return H;
}
VectorType HamiltonianPart::getEigenState(InnerQuantumState state) const
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
return H.col(state);
}
RealType HamiltonianPart::getMinimumEigenvalue() const
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
return Eigenvalues.minCoeff();
}
bool HamiltonianPart::reduce(RealType ActualCutoff)
{
if ( Status < Diagonalized ) throw (exStatusMismatch());
InnerQuantumState counter=0;
for (counter=0; (counter< (unsigned int)Eigenvalues.size() && Eigenvalues[counter]<=ActualCutoff); ++counter){};
std::cout << "Left " << counter << " eigenvalues : " << std::endl;
if (counter)
{std::cout << Eigenvalues.head(counter) << std::endl << "_________" << std::endl;
Eigenvalues = Eigenvalues.head(counter);
H = H.topLeftCorner(counter,counter);
return true;
}
else return false;
}
void HamiltonianPart::save(H5::CommonFG* RootGroup) const
{
HDF5Storage::saveInt(RootGroup,"Block",Block);
HDF5Storage::saveRealVector(RootGroup,"V",Eigenvalues);
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
HDF5Storage::saveMatrix(RootGroup,"H",H);
#else
HDF5Storage::saveRealMatrix(RootGroup,"H",H);
#endif
}
void HamiltonianPart::load(const H5::CommonFG* RootGroup)
{
int Block_temp = HDF5Storage::loadInt(RootGroup,"Block");
if(! (Block_temp == (int) Block))
throw(H5::DataSetIException("HamiltonianPart::load()",
"Data in the storage is for another set of quantum numbers."));
HDF5Storage::loadRealVector(RootGroup,"V",Eigenvalues);
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
HDF5Storage::loadMatrix(RootGroup,"H",H);
#else
HDF5Storage::loadRealMatrix(RootGroup,"H",H);
#endif
Status = Diagonalized;
}
#ifdef POMEROL_USE_PLAIN_SAVE
bool HamiltonianPart::savetxt(const boost::filesystem::path &path)
{
return true;
}
#endif
} // end of namespace Pomerol
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-sstable/binaryformat.h>
#include <fnord-sstable/fileheaderreader.h>
#include <fnord-base/exception.h>
#include <fnord-base/fnv.h>
namespace fnord {
namespace sstable {
FileHeaderReader::FileHeaderReader(
void* buf,
size_t buf_size) :
fnord::util::BinaryMessageReader(buf, buf_size) {
auto magic_bytes = *readUInt32();
if (magic_bytes != BinaryFormat::kMagicBytes) {
RAISE(kIllegalStateError, "not a valid sstable");
}
auto version = *readUInt16();
if (version != BinaryFormat::kVersion) {
RAISE(kIllegalStateError, "unsupported sstable version");
}
body_size_ = *readUInt64();
userdata_checksum_ = *readUInt32();
userdata_size_ = *readUInt32();
userdata_offset_ = pos_;
}
bool FileHeaderReader::verify() {
if (userdata_offset_ + userdata_size_ > size_) {
return false;
}
const void* userdata;
size_t userdata_size;
readUserdata(&userdata, &userdata_size);
hash::FNV<uint32_t> fnv;
uint32_t userdata_checksum = fnv.hash(userdata, userdata_size);
return userdata_checksum == userdata_checksum_;
}
size_t FileHeaderReader::headerSize() const {
return userdata_offset_ + userdata_size_;
}
size_t FileHeaderReader::bodySize() const {
return body_size_;
}
size_t FileHeaderReader::userdataSize() const {
return userdata_size_;
}
void FileHeaderReader::readUserdata(
const void** userdata,
size_t* userdata_size) {
seekTo(userdata_offset_);
*userdata = read(userdata_size_);
*userdata_size = userdata_size_;
}
}
}
<commit_msg>fix sstable::FileHeaderReader::verify for empty userdata<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-sstable/binaryformat.h>
#include <fnord-sstable/fileheaderreader.h>
#include <fnord-base/exception.h>
#include <fnord-base/fnv.h>
namespace fnord {
namespace sstable {
FileHeaderReader::FileHeaderReader(
void* buf,
size_t buf_size) :
fnord::util::BinaryMessageReader(buf, buf_size) {
auto magic_bytes = *readUInt32();
if (magic_bytes != BinaryFormat::kMagicBytes) {
RAISE(kIllegalStateError, "not a valid sstable");
}
auto version = *readUInt16();
if (version != BinaryFormat::kVersion) {
RAISE(kIllegalStateError, "unsupported sstable version");
}
body_size_ = *readUInt64();
userdata_checksum_ = *readUInt32();
userdata_size_ = *readUInt32();
userdata_offset_ = pos_;
}
bool FileHeaderReader::verify() {
if (userdata_offset_ + userdata_size_ > size_) {
return false;
}
if (userdata_size_ == 0) {
return true;
}
const void* userdata;
size_t userdata_size;
readUserdata(&userdata, &userdata_size);
hash::FNV<uint32_t> fnv;
uint32_t userdata_checksum = fnv.hash(userdata, userdata_size);
return userdata_checksum == userdata_checksum_;
}
size_t FileHeaderReader::headerSize() const {
return userdata_offset_ + userdata_size_;
}
size_t FileHeaderReader::bodySize() const {
return body_size_;
}
size_t FileHeaderReader::userdataSize() const {
return userdata_size_;
}
void FileHeaderReader::readUserdata(
const void** userdata,
size_t* userdata_size) {
seekTo(userdata_offset_);
*userdata = read(userdata_size_);
*userdata_size = userdata_size_;
}
}
}
<|endoftext|> |
<commit_before>#include "SettingsMenu.hpp"
#include "../../ResourceManager/AssetManager.hpp"
/* GUI headers */
#include "../../GUI/Containers/Column.hpp"
#include "../../GUI/Containers/Row.hpp"
#include "../../GUI/Widgets/Label.hpp"
#include "../../GUI/Widgets/Button.hpp"
#include "../../GUI/Widgets/Spacer.hpp"
#include "../../GUI/Widgets/Slider.hpp"
#include "../../GUI/Widgets/Toggle.hpp"
#include "../../GUI/Widgets/TextBox.hpp"
namespace swift
{
SettingsMenu::SettingsMenu(sf::RenderWindow& win, AssetManager& am, Settings& s)
: State(win, am),
settings(s)
{
returnType = State::Type::SettingsMenu;
}
SettingsMenu::~SettingsMenu()
{
}
void SettingsMenu::setup()
{
window.setKeyRepeatEnabled(true);
Script* setup = &assets.getScript("./data/scripts/settingsMenu.lua");
setup->setGUI(gui);
setup->setStateReturn(returnType);
setup->start();
cstr::Column& settingsColumn = gui.addContainer(new cstr::Column({50, 50, 700, 500}, false));
cstr::Column& titleCol = settingsColumn.addWidget(new cstr::Column({200, 50}, false));
titleCol.addWidget(new cstr::Label("Settings", assets.getFont("./data/fonts/segoeuisl.ttf")));
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for fullscreen label and toggle
cstr::Row& fullscreenRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& fullscreenLabelCol = fullscreenRow.addWidget(new cstr::Column({200, 50}, false));
fullscreenLabelCol.addWidget(new cstr::Label("Fullscreen:", assets.getFont("./data/fonts/segoeuisl.ttf")));
fullscreenRow.addWidget(new cstr::Spacer({450, 50}));
cstr::Column& fullscreenToggleCol = fullscreenRow.addWidget(new cstr::Column({50, 50}, false));
bool fullscreenState = false;
settings.get("fullscreen", fullscreenState);
fullscreenToggleCol.addWidget(new cstr::Toggle({50, 50}, assets.getTexture("./data/textures/toggleOn.png"), assets.getTexture("./data/textures/toggleOff.png"), fullscreenState,
[&](bool s)
{
settings.set("fullscreen", s);
if(s)
{
unsigned resx = 0;
unsigned resy = 0;
settings.get("res.x", resx);
settings.get("res.y", resy);
window.create({resx, resy, 32}, "Swift2", sf::Style::Fullscreen);
}
else
{
unsigned resx = 800;
unsigned resy = 600;
settings.get("res.x", resx);
settings.get("res.y", resy);
window.create({resx, resy, 32}, "Swift2", sf::Style::Titlebar | sf::Style::Close);
}
}));
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for vsync label and toggle
cstr::Row& vsyncRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& vsyncLabelCol = vsyncRow.addWidget(new cstr::Column({200, 50}, false));
vsyncLabelCol.addWidget(new cstr::Label("V-Sync:", assets.getFont("./data/fonts/segoeuisl.ttf")));
vsyncRow.addWidget(new cstr::Spacer({450, 50}));
cstr::Column& vsyncToggleCol = vsyncRow.addWidget(new cstr::Column({50, 50}, false));
bool vsyncState = false;
settings.get("vsync", vsyncState);
vsyncToggleCol.addWidget(new cstr::Toggle({50, 50}, assets.getTexture("./data/textures/toggleOn.png"), assets.getTexture("./data/textures/toggleOff.png"), vsyncState,
[&](bool s)
{
settings.set("vsync", s);
window.setVerticalSyncEnabled(s);
}));
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for graphics label and button
cstr::Row& graphicsRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& graphicsRowLabelCol = graphicsRow.addWidget(new cstr::Column({200, 50}, false));
graphicsRowLabelCol.addWidget(new cstr::Label("Graphics:", assets.getFont("./data/fonts/segoeuisl.ttf")));
graphicsRow.addWidget(new cstr::Spacer({400, 50}));
cstr::Column& graphicsRowButtonCol = graphicsRow.addWidget(new cstr::Column({100, 50}, false));
graphicsButton = &graphicsRowButtonCol.addWidget(new cstr::Button({100, 50}, assets.getTexture("./data/textures/button.png"), [&]()
{
unsigned graphicsLevel = 0;
settings.get("graphics", graphicsLevel);
graphicsLevel++;
switch(graphicsLevel)
{
case 0:
graphicsButton->setString("Low", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
case 1:
graphicsButton->setString("Medium", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
case 2:
graphicsButton->setString("High", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
default:
graphicsLevel = 0;
graphicsButton->setString("Low", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
}
settings.set("graphics", graphicsLevel);
}));
// set button to the correct text
unsigned graphicsLevel = 0;
settings.get("graphics", graphicsLevel);
switch(graphicsLevel)
{
case 0:
graphicsButton->setString("Low", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
case 1:
graphicsButton->setString("Medium", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
case 2:
graphicsButton->setString("High", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
default:
graphicsLevel = 0;
graphicsButton->setString("Low", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
}
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for text entering
cstr::Row& textEnterRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& textEnterLabelCol = textEnterRow.addWidget(new cstr::Column({200, 50}, false));
textEnterLabelCol.addWidget(new cstr::Label("Name:", assets.getFont("./data/fonts/segoeuisl.ttf")));
textEnterRow.addWidget(new cstr::Spacer({100, 50}));
cstr::Column& textEnterCol = textEnterRow.addWidget(new cstr::Column({400, 50}, false));
textEnterCol.addWidget(new cstr::TextBox({400, 50}, assets.getFont("./data/fonts/segoeuisl.ttf"), "name"));
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
cstr::Row& volumeRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& volumeCol = volumeRow.addWidget(new cstr::Column({200, 50}, false));
volumeCol.addWidget(new cstr::Label("Volume:", assets.getFont("./data/fonts/segoeuisl.ttf")));
volumeRow.addWidget(new cstr::Spacer({100, 50}));
volumeSlider = &volumeRow.addWidget(new cstr::Slider({400, 50}));
int sound = 75;
settings.get("sound", sound);
volumeSlider->setValue(sound / 100.f);
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for main menu return
cstr::Row& mainMenuReturnRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
mainMenuReturnRow.addWidget(new cstr::Spacer({600, 50}));
cstr::Column& mainMenuReturnCol = mainMenuReturnRow.addWidget(new cstr::Column({100, 50}, false));
mainMenuReturnCol.addWidget(new cstr::Button({100, 50}, assets.getTexture("./data/textures/button.png"), [&]()
{
returnType = State::Type::MainMenu;
})).setString("Main Menu", assets.getFont("./data/fonts/segoeuisl.ttf"));
}
void SettingsMenu::handleEvent(sf::Event &event)
{
gui.update(event);
keyboard(event);
mouse(event);
}
void SettingsMenu::update(sf::Time /*dt*/)
{
Script* setup = &assets.getScript("./data/scripts/settingsMenu.lua");
setup->run();
int sound = volumeSlider->getValue() * 100;
settings.set("sound", sound);
}
void SettingsMenu::draw(float /*e*/)
{
window.draw(gui);
}
bool SettingsMenu::switchFrom()
{
return returnType != State::Type::SettingsMenu;
}
State::Type SettingsMenu::finish()
{
return returnType;
}
}
<commit_msg>Added test for Slider.<commit_after>#include "SettingsMenu.hpp"
#include "../../ResourceManager/AssetManager.hpp"
/* GUI headers */
#include "../../GUI/Containers/Column.hpp"
#include "../../GUI/Containers/Row.hpp"
#include "../../GUI/Widgets/Label.hpp"
#include "../../GUI/Widgets/Button.hpp"
#include "../../GUI/Widgets/Spacer.hpp"
#include "../../GUI/Widgets/Slider.hpp"
#include "../../GUI/Widgets/Toggle.hpp"
#include "../../GUI/Widgets/TextBox.hpp"
namespace swift
{
SettingsMenu::SettingsMenu(sf::RenderWindow& win, AssetManager& am, Settings& s)
: State(win, am),
settings(s)
{
returnType = State::Type::SettingsMenu;
}
SettingsMenu::~SettingsMenu()
{
}
void SettingsMenu::setup()
{
window.setKeyRepeatEnabled(true);
Script* setup = &assets.getScript("./data/scripts/settingsMenu.lua");
setup->setGUI(gui);
setup->setStateReturn(returnType);
setup->start();
cstr::Column& settingsColumn = gui.addContainer(new cstr::Column({50, 50, 700, 500}, false));
cstr::Column& titleCol = settingsColumn.addWidget(new cstr::Column({200, 50}, false));
titleCol.addWidget(new cstr::Label("Settings", assets.getFont("./data/fonts/segoeuisl.ttf")));
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for fullscreen label and toggle
cstr::Row& fullscreenRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& fullscreenLabelCol = fullscreenRow.addWidget(new cstr::Column({200, 50}, false));
fullscreenLabelCol.addWidget(new cstr::Label("Fullscreen:", assets.getFont("./data/fonts/segoeuisl.ttf")));
fullscreenRow.addWidget(new cstr::Spacer({450, 50}));
cstr::Column& fullscreenToggleCol = fullscreenRow.addWidget(new cstr::Column({50, 50}, false));
bool fullscreenState = false;
settings.get("fullscreen", fullscreenState);
fullscreenToggleCol.addWidget(new cstr::Toggle({50, 50}, assets.getTexture("./data/textures/toggleOn.png"), assets.getTexture("./data/textures/toggleOff.png"), fullscreenState,
[&](bool s)
{
settings.set("fullscreen", s);
if(s)
{
unsigned resx = 0;
unsigned resy = 0;
settings.get("res.x", resx);
settings.get("res.y", resy);
window.create({resx, resy, 32}, "Swift2", sf::Style::Fullscreen);
}
else
{
unsigned resx = 800;
unsigned resy = 600;
settings.get("res.x", resx);
settings.get("res.y", resy);
window.create({resx, resy, 32}, "Swift2", sf::Style::Titlebar | sf::Style::Close);
}
}));
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for vsync label and toggle
cstr::Row& vsyncRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& vsyncLabelCol = vsyncRow.addWidget(new cstr::Column({200, 50}, false));
vsyncLabelCol.addWidget(new cstr::Label("V-Sync:", assets.getFont("./data/fonts/segoeuisl.ttf")));
vsyncRow.addWidget(new cstr::Spacer({450, 50}));
cstr::Column& vsyncToggleCol = vsyncRow.addWidget(new cstr::Column({50, 50}, false));
bool vsyncState = false;
settings.get("vsync", vsyncState);
vsyncToggleCol.addWidget(new cstr::Toggle({50, 50}, assets.getTexture("./data/textures/toggleOn.png"), assets.getTexture("./data/textures/toggleOff.png"), vsyncState,
[&](bool s)
{
settings.set("vsync", s);
window.setVerticalSyncEnabled(s);
}));
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for graphics label and button
cstr::Row& graphicsRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& graphicsRowLabelCol = graphicsRow.addWidget(new cstr::Column({200, 50}, false));
graphicsRowLabelCol.addWidget(new cstr::Label("Graphics:", assets.getFont("./data/fonts/segoeuisl.ttf")));
graphicsRow.addWidget(new cstr::Spacer({400, 50}));
cstr::Column& graphicsRowButtonCol = graphicsRow.addWidget(new cstr::Column({100, 50}, false));
graphicsButton = &graphicsRowButtonCol.addWidget(new cstr::Button({100, 50}, assets.getTexture("./data/textures/button.png"), [&]()
{
unsigned graphicsLevel = 0;
settings.get("graphics", graphicsLevel);
graphicsLevel++;
switch(graphicsLevel)
{
case 0:
graphicsButton->setString("Low", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
case 1:
graphicsButton->setString("Medium", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
case 2:
graphicsButton->setString("High", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
default:
graphicsLevel = 0;
graphicsButton->setString("Low", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
}
settings.set("graphics", graphicsLevel);
}));
// set button to the correct text
unsigned graphicsLevel = 0;
settings.get("graphics", graphicsLevel);
switch(graphicsLevel)
{
case 0:
graphicsButton->setString("Low", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
case 1:
graphicsButton->setString("Medium", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
case 2:
graphicsButton->setString("High", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
default:
graphicsLevel = 0;
graphicsButton->setString("Low", assets.getFont("./data/fonts/segoeuisl.ttf"));
break;
}
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for text entering
cstr::Row& textEnterRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& textEnterLabelCol = textEnterRow.addWidget(new cstr::Column({200, 50}, false));
textEnterLabelCol.addWidget(new cstr::Label("Name:", assets.getFont("./data/fonts/segoeuisl.ttf")));
textEnterRow.addWidget(new cstr::Spacer({100, 50}));
cstr::Column& textEnterCol = textEnterRow.addWidget(new cstr::Column({400, 50}, false));
textEnterCol.addWidget(new cstr::TextBox({400, 50}, assets.getFont("./data/fonts/segoeuisl.ttf"), "name"));
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for volume slider
cstr::Row& volumeRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
cstr::Column& volumeCol = volumeRow.addWidget(new cstr::Column({200, 50}, false));
volumeCol.addWidget(new cstr::Label("Volume:", assets.getFont("./data/fonts/segoeuisl.ttf")));
volumeRow.addWidget(new cstr::Spacer({100, 50}));
volumeSlider = &volumeRow.addWidget(new cstr::Slider({400, 50}));
int sound = 75;
settings.get("sound", sound);
volumeSlider->setValue(sound / 100.f);
settingsColumn.addWidget(new cstr::Spacer({700, 25}));
// row for main menu return
cstr::Row& mainMenuReturnRow = settingsColumn.addWidget(new cstr::Row({700, 50}, false));
mainMenuReturnRow.addWidget(new cstr::Spacer({600, 50}));
cstr::Column& mainMenuReturnCol = mainMenuReturnRow.addWidget(new cstr::Column({100, 50}, false));
mainMenuReturnCol.addWidget(new cstr::Button({100, 50}, assets.getTexture("./data/textures/button.png"), [&]()
{
returnType = State::Type::MainMenu;
})).setString("Main Menu", assets.getFont("./data/fonts/segoeuisl.ttf"));
}
void SettingsMenu::handleEvent(sf::Event &event)
{
gui.update(event);
keyboard(event);
mouse(event);
}
void SettingsMenu::update(sf::Time /*dt*/)
{
Script* setup = &assets.getScript("./data/scripts/settingsMenu.lua");
setup->run();
int sound = volumeSlider->getValue() * 100;
settings.set("sound", sound);
}
void SettingsMenu::draw(float /*e*/)
{
window.draw(gui);
}
bool SettingsMenu::switchFrom()
{
return returnType != State::Type::SettingsMenu;
}
State::Type SettingsMenu::finish()
{
return returnType;
}
}
<|endoftext|> |
<commit_before>#include "motor_api.h"
/************************
* Non public functions *
************************/
int32_t base_motor_get_degrees(Base_Motor* motor)
{
int32_t res;
// Mark reading as true, so no race conditions occur
motor->reading = true;
res = motor->degrees;
// Just to make sure motor->degrees never changes when reading = true
ASSERT(res == motor->degrees);
motor->reading = false;
return res * motor->degree_ratio;
}
/********************
* Public functions *
********************/
void motor_init(Motor* motor, float degree_ratio, uint8_t pin,
uint8_t interrupt_pin, void (*interrupt_handler)(void))
{
motor->pin = pin;
motor->base.degree_ratio = degree_ratio;
motor->base.buffer = 0;
motor->base.degrees = 0;
motor->base.reading = false;
pinMode(interrupt_pin, INPUT_PULLUP);
pinMode(pin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(interrupt_pin), interrupt_handler,
CHANGE);
}
void advanced_motor_init(Advanced_Motor* motor, float degree_ratio,
uint8_t pin1, uint8_t pin2, uint8_t interrupt_pin1,
uint8_t interrupt_pin2,
void (*interrupt_handler1)(void))
{
motor->pin1 = pin1;
motor->pin2 = pin2;
motor->interrupt_pin1 = interrupt_pin1;
motor->interrupt_pin2 = interrupt_pin2;
motor->base.degree_ratio = degree_ratio;
motor->base.buffer = 0;
motor->base.degrees = 0;
motor->base.reading = false;
pinMode(interrupt_pin1, INPUT_PULLUP);
pinMode(interrupt_pin2, INPUT_PULLUP);
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
attachInterrupt(digitalPinToInterrupt(interrupt_pin1), interrupt_handler1,
CHANGE);
}
void advanced_motor_turn_to_degree(Advanced_Motor* motor, uint16_t degree)
{
// Turn to degree should only accept a degree value between
// 0 and 359 inclusive
ASSERT(degree < 360);
int32_t current_pos = advanced_motor_get_degrees(motor);
// We need to floor, because default casting rounds towards 0, and
// we always wants it to round down for these calculations to work.
int32_t turns = floor(current_pos / 360.0);
// We need to choose two goal, one above and one below our current_pos.
// These goal needs to be the full number representaion of the degree number
// that has to be reached.
int32_t goal2, goal1 = 360 * turns + degree;
int32_t distance_forward, distance_backward;
if (goal1 > current_pos)
{
goal2 = 360 * (turns - 1) + degree;
distance_forward = current_pos - goal2;
distance_backward = goal1 - current_pos;
/*
DEBUG_PRINTLN_VAR(goal1 > current_pos);
DEBUG_PRINTLN_VAR(current_pos);
DEBUG_PRINTLN_VAR(degree);
DEBUG_PRINTLN_VAR(goal1);
DEBUG_PRINTLN_VAR(goal2);
DEBUG_PRINTLN_VAR(distance_forward);
DEBUG_PRINTLN_VAR(distance_backward);
/*
*/
}
else if (goal1 < current_pos)
{
goal2 = 360 * (turns + 1) + degree;
distance_forward = current_pos - goal1;
distance_backward = goal2 - current_pos;
/*
DEBUG_PRINTLN_VAR(goal1 < current_pos);
DEBUG_PRINTLN_VAR(current_pos);
DEBUG_PRINTLN_VAR(degree);
DEBUG_PRINTLN_VAR(goal1);
DEBUG_PRINTLN_VAR(goal2);
DEBUG_PRINTLN_VAR(distance_forward);
DEBUG_PRINTLN_VAR(distance_backward);
/*
*/
}
// If goal and current_pos are equal, the motor doesn't need to turn, so
// we just return
else
{
return;
}
ASSERT(distance_forward >= 0);
ASSERT(distance_backward >= 0);
// Choose which direction to turn based on which distance is shortest
if (distance_forward < distance_backward)
advanced_motor_turn_degrees(motor, distance_forward, FORWARD);
else
advanced_motor_turn_degrees(motor, distance_backward, BACKWARD);
}
void motor_turn_to_degree(Motor* motor, uint16_t degree)
{
// Turn to degree should only accept a degree value between
// 0 and 359 inclusive
ASSERT(degree < 360);
int32_t current_pos = motor_get_degrees(motor);
int32_t turns = (current_pos / 360);
int32_t goal = 360 * turns + degree;
// If goal is lower than current_pos, then we need to choose a new goal,
// 360 degrees bigger
if (goal < current_pos)
goal = 360 * (turns + 1) + degree;
// Turn motor by the distance to the goal
motor_turn_degrees(motor, goal - current_pos);
}
void advanced_motor_turn_degrees(Advanced_Motor* motor, uint16_t degrees,
int8_t direction)
{
// Calculate the goal that the motor should reach
int32_t read_degrees = advanced_motor_get_degrees(motor);
int32_t goal = read_degrees + ((int32_t)degrees * direction);
advanced_motor_turn(motor, direction);
bool running = true;
// Wait for the motor to reach the goal
switch (direction)
{
case FORWARD:
while (goal < advanced_motor_get_degrees(motor))
;
break;
case BACKWARD:
while (goal > advanced_motor_get_degrees(motor))
;
break;
default:
ASSERT(false);
break;
}
advanced_motor_stop(motor);
}
void motor_turn_degrees(Motor* motor, uint16_t degrees)
{
// Calculate the goal that the motor should reach
int32_t goal = motor_get_degrees(motor) + degrees;
motor_turn(motor);
// Wait for the motor to reach the goal
while (goal > motor_get_degrees(motor))
;
motor_stop(motor);
}
void advanced_motor_stop(Advanced_Motor* motor)
{
// HACK: To break, we turn the motor in the other direction for a
// fix amount of time.
// It is not perfect, but it does reduce the coasting by a lot
if (motor->direction == FORWARD)
advanced_motor_turn(motor, BACKWARD);
else
advanced_motor_turn(motor, FORWARD);
delay(50); // 50ms seems like a good delay
digitalWrite(motor->pin1, LOW);
digitalWrite(motor->pin2, LOW);
delay(100); // give the motor time to stop coasting
}
void motor_stop(Motor* motor)
{
digitalWrite(motor->pin, LOW);
}
void advanced_motor_turn(Advanced_Motor* motor, int8_t direction)
{
switch (direction)
{
case FORWARD:
digitalWrite(motor->pin1, HIGH);
digitalWrite(motor->pin2, LOW);
break;
case BACKWARD:
digitalWrite(motor->pin1, LOW);
digitalWrite(motor->pin2, HIGH);
break;
default:
ASSERT(false);
break;
}
}
void motor_turn(Motor* motor)
{
digitalWrite(motor->pin, HIGH);
}
int32_t motor_get_degrees(Motor* motor)
{
return base_motor_get_degrees(&motor->base);
}
int32_t advanced_motor_get_degrees(Advanced_Motor* motor)
{
return base_motor_get_degrees(&motor->base);
}
void motor_update_degrees(Motor* motor)
{
// If degrees are being read, update a buffer instead to avoid race condtions
if (motor->base.reading)
{
motor->base.buffer++;
}
else
{
// We need to add and reset the buffer when we are allowed to
// write to the degrees
motor->base.degrees += 1 + motor->base.buffer;
motor->base.buffer = 0;
}
}
void advanced_motor_update_degrees(Advanced_Motor* motor)
{
byte pattern = digitalRead(motor->interrupt_pin1);
pattern |= (digitalRead(motor->interrupt_pin2) << 1);
// We determin the direction by a pattern formed by the values
// read from pin1 and pin2
// LOW = 0, HIGH = 1
switch (pattern)
{
case 0b11:
case 0b00:
motor->direction = FORWARD;
break;
case 0b10:
case 0b01:
motor->direction = BACKWARD;
break;
default:
ASSERT(false);
break;
}
// If degrees are being read, update a buffer instead to avoid race condtions
if (motor->base.reading)
{
motor->base.buffer += motor->direction;
}
else
{
// We need to add and reset the buffer when we are allowed to
// write to the degrees
motor->base.degrees += motor->direction + motor->base.buffer;
motor->base.buffer = 0;
}
}
<commit_msg>Implemented the detection for motors not moving<commit_after>#include "motor_api.h"
/************************
* Non public functions *
************************/
int32_t base_motor_get_degrees(Base_Motor* motor)
{
int32_t res;
// Mark reading as true, so no race conditions occur
motor->reading = true;
res = motor->degrees;
// Just to make sure motor->degrees never changes when reading = true
ASSERT(res == motor->degrees);
motor->reading = false;
return res * motor->degree_ratio;
}
/********************
* Public functions *
********************/
void motor_init(Motor* motor, float degree_ratio, uint8_t pin,
uint8_t interrupt_pin, void (*interrupt_handler)(void))
{
motor->pin = pin;
motor->base.degree_ratio = degree_ratio;
motor->base.buffer = 0;
motor->base.degrees = 0;
motor->base.reading = false;
pinMode(interrupt_pin, INPUT_PULLUP);
pinMode(pin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(interrupt_pin), interrupt_handler,
CHANGE);
}
void advanced_motor_init(Advanced_Motor* motor, float degree_ratio,
uint8_t pin1, uint8_t pin2, uint8_t interrupt_pin1,
uint8_t interrupt_pin2,
void (*interrupt_handler1)(void))
{
motor->pin1 = pin1;
motor->pin2 = pin2;
motor->interrupt_pin1 = interrupt_pin1;
motor->interrupt_pin2 = interrupt_pin2;
motor->base.degree_ratio = degree_ratio;
motor->base.buffer = 0;
motor->base.degrees = 0;
motor->base.reading = false;
pinMode(interrupt_pin1, INPUT_PULLUP);
pinMode(interrupt_pin2, INPUT_PULLUP);
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
attachInterrupt(digitalPinToInterrupt(interrupt_pin1), interrupt_handler1,
CHANGE);
}
void advanced_motor_turn_to_degree(Advanced_Motor* motor, uint16_t degree)
{
// Turn to degree should only accept a degree value between
// 0 and 359 inclusive
ASSERT(degree < 360);
int32_t current_pos = advanced_motor_get_degrees(motor);
// We need to floor, because default casting rounds towards 0, and
// we always wants it to round down for these calculations to work.
int32_t turns = floor(current_pos / 360.0);
// We need to choose two goal, one above and one below our current_pos.
// These goal needs to be the full number representaion of the degree number
// that has to be reached.
int32_t goal2, goal1 = 360 * turns + degree;
int32_t distance_forward, distance_backward;
if (goal1 > current_pos)
{
goal2 = 360 * (turns - 1) + degree;
distance_forward = current_pos - goal2;
distance_backward = goal1 - current_pos;
/*
DEBUG_PRINTLN_VAR(goal1 > current_pos);
DEBUG_PRINTLN_VAR(current_pos);
DEBUG_PRINTLN_VAR(degree);
DEBUG_PRINTLN_VAR(goal1);
DEBUG_PRINTLN_VAR(goal2);
DEBUG_PRINTLN_VAR(distance_forward);
DEBUG_PRINTLN_VAR(distance_backward);
/*
*/
}
else if (goal1 < current_pos)
{
goal2 = 360 * (turns + 1) + degree;
distance_forward = current_pos - goal1;
distance_backward = goal2 - current_pos;
/*
DEBUG_PRINTLN_VAR(goal1 < current_pos);
DEBUG_PRINTLN_VAR(current_pos);
DEBUG_PRINTLN_VAR(degree);
DEBUG_PRINTLN_VAR(goal1);
DEBUG_PRINTLN_VAR(goal2);
DEBUG_PRINTLN_VAR(distance_forward);
DEBUG_PRINTLN_VAR(distance_backward);
/*
*/
}
// If goal and current_pos are equal, the motor doesn't need to turn, so
// we just return
else
{
return;
}
ASSERT(distance_forward >= 0);
ASSERT(distance_backward >= 0);
// Choose which direction to turn based on which distance is shortest
if (distance_forward < distance_backward)
advanced_motor_turn_degrees(motor, distance_forward, FORWARD);
else
advanced_motor_turn_degrees(motor, distance_backward, BACKWARD);
}
void motor_turn_to_degree(Motor* motor, uint16_t degree)
{
// Turn to degree should only accept a degree value between
// 0 and 359 inclusive
ASSERT(degree < 360);
int32_t current_pos = motor_get_degrees(motor);
int32_t turns = (current_pos / 360);
int32_t goal = 360 * turns + degree;
// If goal is lower than current_pos, then we need to choose a new goal,
// 360 degrees bigger
if (goal < current_pos)
goal = 360 * (turns + 1) + degree;
// Turn motor by the distance to the goal
motor_turn_degrees(motor, goal - current_pos);
}
bool lesser_than(int32_t value1, int32_t value2)
{
return value1 < value2;
}
bool greater_than(int32_t value1, int32_t value2)
{
return value1 > value2;
}
void advanced_motor_turn_degrees(Advanced_Motor* motor, uint16_t degrees,
int8_t direction)
{
// Calculate the goal that the motor should reach
int32_t read_degrees = advanced_motor_get_degrees(motor);
int32_t goal = read_degrees + ((int32_t)degrees * direction);
bool (*compare_to)(int32_t, int32_t);
advanced_motor_turn(motor, direction);
// Wait for the motor to reach the goal
switch (direction)
{
case FORWARD:
compare_to = lesser_than;
break;
case BACKWARD:
compare_to = greater_than;
break;
default:
ASSERT(false);
break;
}
int32_t previouse_read_degrees;
uint32_t error_timeout = millis() + 500;
do {
previouse_read_degrees = read_degrees;
read_degrees = advanced_motor_get_degrees(motor);
if (previouse_read_degrees != read_degrees)
error_timeout = millis() + 500;
else if (error_timeout < millis())
ASSERT(false);
} while (compare_to(goal, read_degrees));
advanced_motor_stop(motor);
}
void motor_turn_degrees(Motor* motor, uint16_t degrees)
{
// Calculate the goal that the motor should reach
int32_t read_degrees = motor_get_degrees(motor);
int32_t goal = read_degrees + degrees;
int32_t previouse_read_degrees;
uint32_t error_timeout = millis() + 500;
motor_turn(motor);
do {
previouse_read_degrees = read_degrees;
read_degrees = motor_get_degrees(motor);
if (previouse_read_degrees != read_degrees)
error_timeout = millis() + 500;
else if (error_timeout < millis())
ASSERT(false);
} while (goal > read_degrees);
// Wait for the motor to reach the goal
motor_stop(motor);
}
void advanced_motor_stop(Advanced_Motor* motor)
{
// HACK: To break, we turn the motor in the other direction for a
// fix amount of time.
// It is not perfect, but it does reduce the coasting by a lot
if (motor->direction == FORWARD)
advanced_motor_turn(motor, BACKWARD);
else
advanced_motor_turn(motor, FORWARD);
delay(50); // 50ms seems like a good delay
digitalWrite(motor->pin1, LOW);
digitalWrite(motor->pin2, LOW);
delay(100); // give the motor time to stop coasting
}
void motor_stop(Motor* motor)
{
digitalWrite(motor->pin, LOW);
}
void advanced_motor_turn(Advanced_Motor* motor, int8_t direction)
{
switch (direction)
{
case FORWARD:
digitalWrite(motor->pin1, HIGH);
digitalWrite(motor->pin2, LOW);
break;
case BACKWARD:
digitalWrite(motor->pin1, LOW);
digitalWrite(motor->pin2, HIGH);
break;
default:
ASSERT(false);
break;
}
}
void motor_turn(Motor* motor)
{
digitalWrite(motor->pin, HIGH);
}
int32_t motor_get_degrees(Motor* motor)
{
return base_motor_get_degrees(&motor->base);
}
int32_t advanced_motor_get_degrees(Advanced_Motor* motor)
{
return base_motor_get_degrees(&motor->base);
}
void motor_update_degrees(Motor* motor)
{
// If degrees are being read, update a buffer instead to avoid race condtions
if (motor->base.reading)
{
motor->base.buffer++;
}
else
{
// We need to add and reset the buffer when we are allowed to
// write to the degrees
motor->base.degrees += 1 + motor->base.buffer;
motor->base.buffer = 0;
}
}
void advanced_motor_update_degrees(Advanced_Motor* motor)
{
byte pattern = digitalRead(motor->interrupt_pin1);
pattern |= (digitalRead(motor->interrupt_pin2) << 1);
// We determin the direction by a pattern formed by the values
// read from pin1 and pin2
// LOW = 0, HIGH = 1
switch (pattern)
{
case 0b11:
case 0b00:
motor->direction = FORWARD;
break;
case 0b10:
case 0b01:
motor->direction = BACKWARD;
break;
default:
ASSERT(false);
break;
}
// If degrees are being read, update a buffer instead to avoid race condtions
if (motor->base.reading)
{
motor->base.buffer += motor->direction;
}
else
{
// We need to add and reset the buffer when we are allowed to
// write to the degrees
motor->base.degrees += motor->direction + motor->base.buffer;
motor->base.buffer = 0;
}
}
<|endoftext|> |
<commit_before>//===--- Rewriter.cpp - Code rewriting interface --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Rewriter class, which is used for code
// transformations.
//
//===----------------------------------------------------------------------===//
#include "clang/Rewrite/Rewriter.h"
#include "clang/AST/Stmt.h"
#include "clang/Lex/Lexer.h"
#include "clang/Basic/SourceManager.h"
#include <sstream>
using namespace clang;
void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size) {
// Nothing to remove, exit early.
if (Size == 0) return;
unsigned RealOffset = getMappedOffset(OrigOffset, true);
assert(RealOffset+Size < Buffer.size() && "Invalid location");
// Remove the dead characters.
Buffer.erase(RealOffset, Size);
// Add a delta so that future changes are offset correctly.
AddDelta(OrigOffset, -Size);
}
void RewriteBuffer::InsertText(unsigned OrigOffset,
const char *StrData, unsigned StrLen,
bool InsertAfter) {
// Nothing to insert, exit early.
if (StrLen == 0) return;
unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter);
Buffer.insert(RealOffset, StrData, StrData+StrLen);
// Add a delta so that future changes are offset correctly.
AddDelta(OrigOffset, StrLen);
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove+insert"
/// operation.
void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
const char *NewStr, unsigned NewLength) {
unsigned RealOffset = getMappedOffset(OrigOffset, false);
Buffer.erase(RealOffset, OrigLength);
Buffer.insert(RealOffset, NewStr, NewStr+NewLength);
if (OrigLength != NewLength)
AddDelta(OrigOffset, NewLength-OrigLength);
}
//===----------------------------------------------------------------------===//
// Rewriter class
//===----------------------------------------------------------------------===//
/// getRangeSize - Return the size in bytes of the specified range if they
/// are in the same file. If not, this returns -1.
int Rewriter::getRangeSize(SourceRange Range) const {
if (!isRewritable(Range.getBegin()) ||
!isRewritable(Range.getEnd())) return -1;
unsigned StartOff, StartFileID;
unsigned EndOff , EndFileID;
StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
if (StartFileID != EndFileID)
return -1;
// If edits have been made to this buffer, the delta between the range may
// have changed.
std::map<unsigned, RewriteBuffer>::const_iterator I =
RewriteBuffers.find(StartFileID);
if (I != RewriteBuffers.end()) {
const RewriteBuffer &RB = I->second;
EndOff = RB.getMappedOffset(EndOff, true);
StartOff = RB.getMappedOffset(StartOff);
}
// Adjust the end offset to the end of the last token, instead of being the
// start of the last token.
EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr);
return EndOff-StartOff;
}
unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
unsigned &FileID) const {
std::pair<unsigned,unsigned> V = SourceMgr->getDecomposedFileLoc(Loc);
FileID = V.first;
return V.second;
}
/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
///
RewriteBuffer &Rewriter::getEditBuffer(unsigned FileID) {
std::map<unsigned, RewriteBuffer>::iterator I =
RewriteBuffers.lower_bound(FileID);
if (I != RewriteBuffers.end() && I->first == FileID)
return I->second;
I = RewriteBuffers.insert(I, std::make_pair(FileID, RewriteBuffer()));
std::pair<const char*, const char*> MB = SourceMgr->getBufferData(FileID);
I->second.Initialize(MB.first, MB.second);
return I->second;
}
/// InsertText - Insert the specified string at the specified location in the
/// original buffer.
bool Rewriter::InsertText(SourceLocation Loc, const char *StrData,
unsigned StrLen, bool InsertAfter) {
if (!isRewritable(Loc)) return true;
unsigned FileID;
unsigned StartOffs = getLocationOffsetAndFileID(Loc, FileID);
getEditBuffer(FileID).InsertText(StartOffs, StrData, StrLen, InsertAfter);
return false;
}
/// RemoveText - Remove the specified text region.
bool Rewriter::RemoveText(SourceLocation Start, unsigned Length) {
if (!isRewritable(Start)) return true;
unsigned FileID;
unsigned StartOffs = getLocationOffsetAndFileID(Start, FileID);
getEditBuffer(FileID).RemoveText(StartOffs, Length);
return false;
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove/insert"
/// operation.
bool Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
const char *NewStr, unsigned NewLength) {
if (!isRewritable(Start)) return true;
unsigned StartFileID;
unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength,
NewStr, NewLength);
return false;
}
/// ReplaceStmt - This replaces a Stmt/Expr with another, using the pretty
/// printer to generate the replacement code. This returns true if the input
/// could not be rewritten, or false if successful.
bool Rewriter::ReplaceStmt(Stmt *From, Stmt *To) {
// Measaure the old text.
int Size = getRangeSize(From->getSourceRange());
if (Size == -1)
return true;
// Get the new text.
std::ostringstream S;
To->printPretty(S);
const std::string &Str = S.str();
ReplaceText(From->getLocStart(), Size, &Str[0], Str.size());
return false;
}
<commit_msg>add an assertion<commit_after>//===--- Rewriter.cpp - Code rewriting interface --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Rewriter class, which is used for code
// transformations.
//
//===----------------------------------------------------------------------===//
#include "clang/Rewrite/Rewriter.h"
#include "clang/AST/Stmt.h"
#include "clang/Lex/Lexer.h"
#include "clang/Basic/SourceManager.h"
#include <sstream>
using namespace clang;
void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size) {
// Nothing to remove, exit early.
if (Size == 0) return;
unsigned RealOffset = getMappedOffset(OrigOffset, true);
assert(RealOffset+Size < Buffer.size() && "Invalid location");
// Remove the dead characters.
Buffer.erase(RealOffset, Size);
// Add a delta so that future changes are offset correctly.
AddDelta(OrigOffset, -Size);
}
void RewriteBuffer::InsertText(unsigned OrigOffset,
const char *StrData, unsigned StrLen,
bool InsertAfter) {
// Nothing to insert, exit early.
if (StrLen == 0) return;
unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter);
Buffer.insert(RealOffset, StrData, StrData+StrLen);
// Add a delta so that future changes are offset correctly.
AddDelta(OrigOffset, StrLen);
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove+insert"
/// operation.
void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
const char *NewStr, unsigned NewLength) {
unsigned RealOffset = getMappedOffset(OrigOffset, false);
Buffer.erase(RealOffset, OrigLength);
Buffer.insert(RealOffset, NewStr, NewStr+NewLength);
if (OrigLength != NewLength)
AddDelta(OrigOffset, NewLength-OrigLength);
}
//===----------------------------------------------------------------------===//
// Rewriter class
//===----------------------------------------------------------------------===//
/// getRangeSize - Return the size in bytes of the specified range if they
/// are in the same file. If not, this returns -1.
int Rewriter::getRangeSize(SourceRange Range) const {
if (!isRewritable(Range.getBegin()) ||
!isRewritable(Range.getEnd())) return -1;
unsigned StartOff, StartFileID;
unsigned EndOff , EndFileID;
StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
if (StartFileID != EndFileID)
return -1;
// If edits have been made to this buffer, the delta between the range may
// have changed.
std::map<unsigned, RewriteBuffer>::const_iterator I =
RewriteBuffers.find(StartFileID);
if (I != RewriteBuffers.end()) {
const RewriteBuffer &RB = I->second;
EndOff = RB.getMappedOffset(EndOff, true);
StartOff = RB.getMappedOffset(StartOff);
}
// Adjust the end offset to the end of the last token, instead of being the
// start of the last token.
EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr);
return EndOff-StartOff;
}
unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
unsigned &FileID) const {
assert(Loc.isValid() && "Invalid location");
std::pair<unsigned,unsigned> V = SourceMgr->getDecomposedFileLoc(Loc);
FileID = V.first;
return V.second;
}
/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
///
RewriteBuffer &Rewriter::getEditBuffer(unsigned FileID) {
std::map<unsigned, RewriteBuffer>::iterator I =
RewriteBuffers.lower_bound(FileID);
if (I != RewriteBuffers.end() && I->first == FileID)
return I->second;
I = RewriteBuffers.insert(I, std::make_pair(FileID, RewriteBuffer()));
std::pair<const char*, const char*> MB = SourceMgr->getBufferData(FileID);
I->second.Initialize(MB.first, MB.second);
return I->second;
}
/// InsertText - Insert the specified string at the specified location in the
/// original buffer.
bool Rewriter::InsertText(SourceLocation Loc, const char *StrData,
unsigned StrLen, bool InsertAfter) {
if (!isRewritable(Loc)) return true;
unsigned FileID;
unsigned StartOffs = getLocationOffsetAndFileID(Loc, FileID);
getEditBuffer(FileID).InsertText(StartOffs, StrData, StrLen, InsertAfter);
return false;
}
/// RemoveText - Remove the specified text region.
bool Rewriter::RemoveText(SourceLocation Start, unsigned Length) {
if (!isRewritable(Start)) return true;
unsigned FileID;
unsigned StartOffs = getLocationOffsetAndFileID(Start, FileID);
getEditBuffer(FileID).RemoveText(StartOffs, Length);
return false;
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove/insert"
/// operation.
bool Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
const char *NewStr, unsigned NewLength) {
if (!isRewritable(Start)) return true;
unsigned StartFileID;
unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength,
NewStr, NewLength);
return false;
}
/// ReplaceStmt - This replaces a Stmt/Expr with another, using the pretty
/// printer to generate the replacement code. This returns true if the input
/// could not be rewritten, or false if successful.
bool Rewriter::ReplaceStmt(Stmt *From, Stmt *To) {
// Measaure the old text.
int Size = getRangeSize(From->getSourceRange());
if (Size == -1)
return true;
// Get the new text.
std::ostringstream S;
To->printPretty(S);
const std::string &Str = S.str();
ReplaceText(From->getLocStart(), Size, &Str[0], Str.size());
return false;
}
<|endoftext|> |
<commit_before>#include "mainboard.h"
#include "ui_mainboard.h"
#include <QLabel>
MainBoard::MainBoard(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainBoard)
{
ui->setupUi(this);
this->setFixedSize(1920, 1080);
this->setStyleSheet("background-color: lightgray;");
/*************Sqare A***************/
//label 1
QLabel *sqare_1 = new QLabel(this);
sqare_1->setText("1");
sqare_1->setGeometry(465,785, 12, 20);
//label A
QLabel *sqare_A = new QLabel(this);
sqare_A->setText("A");
sqare_A->setGeometry(525, 850, 12, 20);
sqare_A->setVisible(true);
// A1
QLabel *sqare_A1 = new QLabel(this);
sqare_A1->setStyleSheet("background-color: black;");
sqare_A1->setGeometry(480, 750, 100, 100);
sqare_A1->setVisible(true);
// A2
QLabel *sqare_A2 = new QLabel(this);
sqare_A2->setStyleSheet("background-color: white;");
sqare_A2->setGeometry(480, 650, 100, 100);
sqare_A2->setVisible(true);
// A3
QLabel *sqare_A3 = new QLabel(this);
sqare_A3->setStyleSheet("background-color: black;");
sqare_A3->setGeometry(480, 550, 100, 100);
sqare_A3->setVisible(true);
// A4
QLabel *sqare_A4 = new QLabel(this);
sqare_A4->setStyleSheet("background-color: white;");
sqare_A4->setGeometry(480, 450, 100, 100);
sqare_A4->setVisible(true);
// A5
QLabel *sqare_A5 = new QLabel(this);
sqare_A5->setStyleSheet("background-color: black;");
sqare_A5->setGeometry(480, 350, 100, 100);
sqare_A5->setVisible(true);
// A6
QLabel *sqare_A6 = new QLabel(this);
sqare_A6->setStyleSheet("background-color: white;");
sqare_A6->setGeometry(480, 250, 100, 100);
sqare_A6->setVisible(true);
// A7
QLabel *sqare_A7 = new QLabel(this);
sqare_A7->setStyleSheet("background-color: black;");
sqare_A7->setGeometry(480, 150, 100, 100);
sqare_A7->setVisible(true);
// A8
QLabel *sqare_A8 = new QLabel(this);
sqare_A8->setStyleSheet("background-color: white;");
sqare_A8->setGeometry(480, 50, 100, 100);
sqare_A8->setVisible(true);
/*************Sqare B***************/
//label 2
QLabel *sqare_2 = new QLabel(this);
sqare_2->setText("2");
sqare_2->setGeometry(465,685, 12, 20);
//label B
QLabel *sqare_B = new QLabel(this);
sqare_B->setText("B");
sqare_B->setGeometry(625, 850, 12, 20);
sqare_B->setVisible(true);
// B1
QLabel *sqare_B1 = new QLabel(this);
sqare_B1->setStyleSheet("background-color: white;");
sqare_B1->setGeometry(580, 750, 100, 100);
sqare_B1->setVisible(true);
// B2
QLabel *sqare_B2 = new QLabel(this);
sqare_B2->setStyleSheet("background-color: black;");
sqare_B2->setGeometry(580, 650, 100, 100);
sqare_B2->setVisible(true);
// B3
QLabel *sqare_B3 = new QLabel(this);
sqare_B3->setStyleSheet("background-color: white;");
sqare_B3->setGeometry(580, 550, 100, 100);
sqare_B3->setVisible(true);
// B4
QLabel *sqare_B4 = new QLabel(this);
sqare_B4->setStyleSheet("background-color: black;");
sqare_B4->setGeometry(580, 450, 100, 100);
sqare_B4->setVisible(true);
// B5
QLabel *sqare_B5 = new QLabel(this);
sqare_B5->setStyleSheet("background-color: white;");
sqare_B5->setGeometry(580, 350, 100, 100);
sqare_B5->setVisible(true);
// B6
QLabel *sqare_B6 = new QLabel(this);
sqare_B6->setStyleSheet("background-color: black;");
sqare_B6->setGeometry(580, 250, 100, 100);
sqare_B6->setVisible(true);
// B7
QLabel *sqare_B7 = new QLabel(this);
sqare_B7->setStyleSheet("background-color: white;");
sqare_B7->setGeometry(580, 150, 100, 100);
sqare_B7->setVisible(true);
// B8
QLabel *sqare_B8 = new QLabel(this);
sqare_B8->setStyleSheet("background-color: black;");
sqare_B8->setGeometry(580, 50, 100, 100);
sqare_B8->setVisible(true);
/*************Sqare C***************/
//label 1
QLabel *sqare_3 = new QLabel(this);
sqare_3->setText("3");
sqare_3->setGeometry(465,585, 12, 20);
//label C
QLabel *sqare_C = new QLabel(this);
sqare_C->setText("C");
sqare_C->setGeometry(725, 850, 12, 20);
sqare_C->setVisible(true);
// C1
QLabel *sqare_C1 = new QLabel(this);
sqare_C1->setStyleSheet("background-color: black;");
sqare_C1->setGeometry(680, 750, 100, 100);
sqare_C1->setVisible(true);
// C2
QLabel *sqare_C2 = new QLabel(this);
sqare_C2->setStyleSheet("background-color: white;");
sqare_C2->setGeometry(680, 650, 100, 100);
sqare_C2->setVisible(true);
// C3
QLabel *sqare_C3 = new QLabel(this);
sqare_C3->setStyleSheet("background-color: black;");
sqare_C3->setGeometry(680, 550, 100, 100);
sqare_C3->setVisible(true);
// C4
QLabel *sqare_C4 = new QLabel(this);
sqare_C4->setStyleSheet("background-color: white;");
sqare_C4->setGeometry(680, 450, 100, 100);
sqare_C4->setVisible(true);
// C5
QLabel *sqare_C5 = new QLabel(this);
sqare_C5->setStyleSheet("background-color: black;");
sqare_C5->setGeometry(680, 350, 100, 100);
sqare_C5->setVisible(true);
// C6
QLabel *sqare_C6 = new QLabel(this);
sqare_C6->setStyleSheet("background-color: white;");
sqare_C6->setGeometry(680, 250, 100, 100);
sqare_C6->setVisible(true);
// C7
QLabel *sqare_C7 = new QLabel(this);
sqare_C7->setStyleSheet("background-color: black;");
sqare_C7->setGeometry(680, 150, 100, 100);
sqare_C7->setVisible(true);
// C8
QLabel *sqare_C8 = new QLabel(this);
sqare_C8->setStyleSheet("background-color: white;");
sqare_C8->setGeometry(680, 50, 100, 100);
sqare_C8->setVisible(true);
/*************Sqare D***************/
//label 4
QLabel *sqare_4 = new QLabel(this);
sqare_4->setText("4");
sqare_4->setGeometry(465,485, 12, 20);
//label D
QLabel *sqare_D = new QLabel(this);
sqare_D->setText("D");
sqare_D->setGeometry(825, 850, 12, 20);
sqare_D->setVisible(true);
// D1
QLabel *sqare_D1 = new QLabel(this);
sqare_D1->setStyleSheet("background-color: white;");
sqare_D1->setGeometry(780, 750, 100, 100);
sqare_D1->setVisible(true);
// D2
QLabel *sqare_D2 = new QLabel(this);
sqare_D2->setStyleSheet("background-color: black;");
sqare_D2->setGeometry(780, 650, 100, 100);
sqare_D2->setVisible(true);
// D3
QLabel *sqare_D3 = new QLabel(this);
sqare_D3->setStyleSheet("background-color: white;");
sqare_D3->setGeometry(780, 550, 100, 100);
sqare_D3->setVisible(true);
// D4
QLabel *sqare_D4 = new QLabel(this);
sqare_D4->setStyleSheet("background-color: black;");
sqare_D4->setGeometry(780, 450, 100, 100);
sqare_D4->setVisible(true);
// D5
QLabel *sqare_D5 = new QLabel(this);
sqare_D5->setStyleSheet("background-color: white;");
sqare_D5->setGeometry(780, 350, 100, 100);
sqare_D5->setVisible(true);
// D6
QLabel *sqare_D6 = new QLabel(this);
sqare_D6->setStyleSheet("background-color: black;");
sqare_D6->setGeometry(780, 250, 100, 100);
sqare_D6->setVisible(true);
// D7
QLabel *sqare_D7 = new QLabel(this);
sqare_D7->setStyleSheet("background-color: white;");
sqare_D7->setGeometry(780, 150, 100, 100);
sqare_D7->setVisible(true);
// D8
QLabel *sqare_D8 = new QLabel(this);
sqare_D8->setStyleSheet("background-color: black;");
sqare_D8->setGeometry(780, 50, 100, 100);
sqare_D8->setVisible(true);
/*************Sqare E***************/
//label 5
QLabel *sqare_5 = new QLabel(this);
sqare_5->setText("5");
sqare_5->setGeometry(465,385, 12, 20);
//label E
QLabel *sqare_E = new QLabel(this);
sqare_E->setText("E");
sqare_E->setGeometry(925, 850, 12, 20);
sqare_E->setVisible(true);
// E1
QLabel *sqare_E1 = new QLabel(this);
sqare_E1->setStyleSheet("background-color: black;");
sqare_E1->setGeometry(880, 750, 100, 100);
sqare_E1->setVisible(true);
// E2
QLabel *sqare_E2 = new QLabel(this);
sqare_E2->setStyleSheet("background-color: white;");
sqare_E2->setGeometry(880, 650, 100, 100);
sqare_E2->setVisible(true);
// E3
QLabel *sqare_E3 = new QLabel(this);
sqare_E3->setStyleSheet("background-color: black;");
sqare_E3->setGeometry(880, 550, 100, 100);
sqare_E3->setVisible(true);
// E4
QLabel *sqare_E4 = new QLabel(this);
sqare_E4->setStyleSheet("background-color: white;");
sqare_E4->setGeometry(880, 450, 100, 100);
sqare_E4->setVisible(true);
// E5
QLabel *sqare_E5 = new QLabel(this);
sqare_E5->setStyleSheet("background-color: black;");
sqare_E5->setGeometry(880, 350, 100, 100);
sqare_E5->setVisible(true);
// E6
QLabel *sqare_E6 = new QLabel(this);
sqare_E6->setStyleSheet("background-color: white;");
sqare_E6->setGeometry(880, 250, 100, 100);
sqare_E6->setVisible(true);
// E7
QLabel *sqare_E7 = new QLabel(this);
sqare_E7->setStyleSheet("background-color: black;");
sqare_E7->setGeometry(880, 150, 100, 100);
sqare_E7->setVisible(true);
// E8
QLabel *sqare_E8 = new QLabel(this);
sqare_E8->setStyleSheet("background-color: white;");
sqare_E8->setGeometry(880, 50, 100, 100);
sqare_E8->setVisible(true);
/*************Sqare F***************/
//label 6
QLabel *sqare_6 = new QLabel(this);
sqare_6->setText("6");
sqare_6->setGeometry(465,285, 12, 20);
//label F
QLabel *sqare_F = new QLabel(this);
sqare_F->setText("F");
sqare_F->setGeometry(1025, 850, 12, 20);
sqare_F->setVisible(true);
// F1
QLabel *sqare_F1 = new QLabel(this);
sqare_F1->setStyleSheet("background-color: white;");
sqare_F1->setGeometry(980, 750, 100, 100);
sqare_F1->setVisible(true);
// F2
QLabel *sqare_F2 = new QLabel(this);
sqare_F2->setStyleSheet("background-color: black;");
sqare_F2->setGeometry(980, 650, 100, 100);
sqare_F2->setVisible(true);
// F3
QLabel *sqare_F3 = new QLabel(this);
sqare_F3->setStyleSheet("background-color: white;");
sqare_F3->setGeometry(980, 550, 100, 100);
sqare_F3->setVisible(true);
// F4
QLabel *sqare_F4 = new QLabel(this);
sqare_F4->setStyleSheet("background-color: black;");
sqare_F4->setGeometry(980, 450, 100, 100);
sqare_F4->setVisible(true);
// F5
QLabel *sqare_F5 = new QLabel(this);
sqare_F5->setStyleSheet("background-color: white;");
sqare_F5->setGeometry(980, 350, 100, 100);
sqare_F5->setVisible(true);
// F6
QLabel *sqare_F6 = new QLabel(this);
sqare_F6->setStyleSheet("background-color: black;");
sqare_F6->setGeometry(980, 250, 100, 100);
sqare_F6->setVisible(true);
// F7
QLabel *sqare_F7 = new QLabel(this);
sqare_F7->setStyleSheet("background-color: white;");
sqare_F7->setGeometry(980, 150, 100, 100);
sqare_F7->setVisible(true);
// F8
QLabel *sqare_F8 = new QLabel(this);
sqare_F8->setStyleSheet("background-color: black;");
sqare_F8->setGeometry(980, 50, 100, 100);
sqare_F8->setVisible(true);
/*************Sqare G***************/
//label 7
QLabel *sqare_7 = new QLabel(this);
sqare_7->setText("7");
sqare_7->setGeometry(465,185, 12, 20);
//label G
QLabel *sqare_G = new QLabel(this);
sqare_G->setText("G");
sqare_G->setGeometry(1125, 850, 12, 20);
sqare_G->setVisible(true);
// G1
QLabel *sqare_G1 = new QLabel(this);
sqare_G1->setStyleSheet("background-color: black;");
sqare_G1->setGeometry(1080, 750, 100, 100);
sqare_G1->setVisible(true);
// G2
QLabel *sqare_G2 = new QLabel(this);
sqare_G2->setStyleSheet("background-color: white;");
sqare_G2->setGeometry(1080, 650, 100, 100);
sqare_G2->setVisible(true);
// G3
QLabel *sqare_G3 = new QLabel(this);
sqare_G3->setStyleSheet("background-color: black;");
sqare_G3->setGeometry(1080, 550, 100, 100);
sqare_G3->setVisible(true);
// G4
QLabel *sqare_G4 = new QLabel(this);
sqare_G4->setStyleSheet("background-color: white;");
sqare_G4->setGeometry(1080, 450, 100, 100);
sqare_G4->setVisible(true);
// G5
QLabel *sqare_G5 = new QLabel(this);
sqare_G5->setStyleSheet("background-color: black;");
sqare_G5->setGeometry(1080, 350, 100, 100);
sqare_G5->setVisible(true);
// G6
QLabel *sqare_G6 = new QLabel(this);
sqare_G6->setStyleSheet("background-color: white;");
sqare_G6->setGeometry(1080, 250, 100, 100);
sqare_G6->setVisible(true);
// G7
QLabel *sqare_G7 = new QLabel(this);
sqare_G7->setStyleSheet("background-color: black;");
sqare_G7->setGeometry(1080, 150, 100, 100);
sqare_G7->setVisible(true);
// G8
QLabel *sqare_G8 = new QLabel(this);
sqare_G8->setStyleSheet("background-color: white;");
sqare_G8->setGeometry(1080, 50, 100, 100);
sqare_G8->setVisible(true);
/*************Sqare H***************/
//label 8
QLabel *sqare_8 = new QLabel(this);
sqare_8->setText("8");
sqare_8->setGeometry(465,85, 12, 20);
//label H
QLabel *sqare_H = new QLabel(this);
sqare_H->setText("H");
sqare_H->setGeometry(1225, 850, 12, 20);
sqare_H->setVisible(true);
// H1
QLabel *sqare_H1 = new QLabel(this);
sqare_H1->setStyleSheet("background-color: white;");
sqare_H1->setGeometry(1180, 750, 100, 100);
sqare_H1->setVisible(true);
// H2
QLabel *sqare_H2 = new QLabel(this);
sqare_H2->setStyleSheet("background-color: black;");
sqare_H2->setGeometry(1180, 650, 100, 100);
sqare_H2->setVisible(true);
// H3
QLabel *sqare_H3 = new QLabel(this);
sqare_H3->setStyleSheet("background-color: white;");
sqare_H3->setGeometry(1180, 550, 100, 100);
sqare_H3->setVisible(true);
// H4
QLabel *sqare_H4 = new QLabel(this);
sqare_H4->setStyleSheet("background-color: black;");
sqare_H4->setGeometry(1180, 450, 100, 100);
sqare_H4->setVisible(true);
// H5
QLabel *sqare_H5 = new QLabel(this);
sqare_H5->setStyleSheet("background-color: white;");
sqare_H5->setGeometry(1180, 350, 100, 100);
sqare_H5->setVisible(true);
// H6
QLabel *sqare_H6 = new QLabel(this);
sqare_H6->setStyleSheet("background-color: black;");
sqare_H6->setGeometry(1180, 250, 100, 100);
sqare_H6->setVisible(true);
// H7
QLabel *sqare_H7 = new QLabel(this);
sqare_H7->setStyleSheet("background-color: white;");
sqare_H7->setGeometry(1180, 150, 100, 100);
sqare_H7->setVisible(true);
// H8
QLabel *sqare_H8 = new QLabel(this);
sqare_H8->setStyleSheet("background-color: black;");
sqare_H8->setGeometry(1180, 50, 100, 100);
sqare_H8->setVisible(true);
}
MainBoard::~MainBoard()
{
delete ui;
}
<commit_msg>Optimization<commit_after>#include "mainboard.h"
#include "ui_mainboard.h"
#include <QTextStream>
#include <QLabel>
#include <QString>
MainBoard::MainBoard(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainBoard)
{
ui->setupUi(this);
this->setFixedSize(1920, 1080);
this->setStyleSheet("background-color: lightgray;");
const int BOARD_ROWS = 8;
const int BOARD_COLS = 8;
const int squares_size = 100;
const int squares_label_width = 12;
const int squares_label_height = 20;
const int x_axis[8] = {480, 580, 680, 780, 880, 980, 1080, 1180}; //pushing columns from left to right, starting at 480 pixels
const int y_axis[8] = {50, 150, 250, 350, 450, 550, 650, 750}; //pushing rows from top to bottom, starting at 50 pixels
const QString numb_label[8] ={"8", "7", "6", "5", "4", "3", "2", "1"};
const QString letter_label[8] = {"A", "B", "C", "D", "E", "F", "G", "H"};
QLabel* Sqares[BOARD_COLS][BOARD_ROWS];
QLabel* square_numb_label[8];
QLabel* square_letter_label[8];
//initializing each QLabel
for(int i = 0; i < 8; i++)
{
square_letter_label[i] = new QLabel(this);
square_numb_label[i] = new QLabel(this);
for(int j = 0; j < 8; j++)
{
Sqares[i][j] = new QLabel(this);
}
}
//chess board
for(int i = 0; i < 8; i++)
{
square_letter_label[i]->setText(letter_label[i]);
square_letter_label[i]->setGeometry(x_axis[i] + 45, y_axis[7] + 100, squares_label_width, squares_label_height);
square_numb_label[i]->setText(numb_label[i]);
square_numb_label[i]->setGeometry(x_axis[0] - 25,y_axis[i] + 35, squares_label_width, squares_label_height);
for(int j = 0; j < 8; j++)
{
Sqares[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
if((i%2) == 0)
{
if((j % 2) == 0)
{
Sqares[i][j]->setStyleSheet("background-color: white;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: black;");
}
}
else
{
if((j % 2) != 0)
{
Sqares[i][j]->setStyleSheet("background-color: white ;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: black;");
}
}
}
}
/* tester to see position of QLabel
Sqares[1][1]->setStyleSheet("background-color: red");
*/
}
MainBoard::~MainBoard()
{
delete ui;
}
<|endoftext|> |
<commit_before>#define GLEW_STATIC
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <iostream>
void key_callback(GLFWwindow * window, int key, int scancode, int action, int mode);
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow *window = glfwCreateWindow(800, 600, "OpenGLApp", nullptr, nullptr);
glfwMakeContextCurrent(window);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glViewport(0, 0, 800, 600);
glfwSetKeyCallback(window, key_callback);
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
//render command
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
return 0;
}
void key_callback(GLFWwindow * window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}<commit_msg>add vertex draw<commit_after>#define GLEW_STATIC
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <iostream>
void key_callback(GLFWwindow * window, int key, int scancode, int action, int mode);
const GLchar * vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\0";
const GLchar *fragmentShaderSource = "#version 330 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
"color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow *window = glfwCreateWindow(800, 600, "OpenGLApp", nullptr, nullptr);
glfwMakeContextCurrent(window);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glViewport(0, 0, 800, 600);
glfwSetKeyCallback(window, key_callback);
//vertex shader
GLuint vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
GLint success;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
//fragment shader
GLuint fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
//shader program
GLuint shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::PROGRAM\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
//vertex buffer
GLfloat vertices[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid *)0);
glEnableVertexAttribArray(0);
glUseProgram(shaderProgram);
//VAO
GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
//render command
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
return 0;
}
void key_callback(GLFWwindow * window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}<|endoftext|> |
<commit_before>
// Copyright (c) 2012 Nokia, Inc.
// Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <string.h>
#include <poll.h>
#include <errno.h>
#include <pthread.h>
#include "portal.h"
#include "sock_utils.h"
#ifdef ZYNQ
#include <android/log.h>
#define ALOGD(fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, "PORTAL", fmt, __VA_ARGS__)
#define ALOGE(fmt, ...) __android_log_print(ANDROID_LOG_ERROR, "PORTAL", fmt, __VA_ARGS__)
#else
#define ALOGD(fmt, ...) fprintf(stderr, "PORTAL: " fmt, __VA_ARGS__)
#define ALOGE(fmt, ...) fprintf(stderr, "PORTAL: " fmt, __VA_ARGS__)
#endif
#ifndef NO_CPP_PORTAL_CODE
PortalPoller *defaultPoller = new PortalPoller();
uint64_t poll_enter_time, poll_return_time; // for performance measurement
PortalPoller::PortalPoller()
: portal_wrappers(0), portal_fds(0), numFds(0), numWrappers(0), stopping(0)
{
sem_init(&sem_startup, 0, 0);
}
int PortalPoller::unregisterInstance(Portal *portal)
{
int i = 0;
while(i < numWrappers){
if(portal_wrappers[i]->pint.fpga_number == portal->pint.fpga_number) {
fprintf(stderr, "PortalPoller::unregisterInstance %d %d\n", i, portal->pint.fpga_number);
break;
}
i++;
}
while(i < numWrappers-1){
portal_wrappers[i] = portal_wrappers[i+1];
i++;
}
numWrappers--;
i = 0;
while(i < numFds){
if(portal_fds[i].fd == portal->pint.fpga_fd)
break;
i++;
}
while(i < numFds-1){
portal_fds[i] = portal_fds[i+1];
i++;
}
numFds--;
return 0;
}
int PortalPoller::registerInstance(Portal *portal)
{
numWrappers++;
fprintf(stderr, "Portal::registerInstance fpga%d fd %d\n", portal->pint.fpga_number, portal->pint.fpga_fd);
portal_wrappers = (Portal **)realloc(portal_wrappers, numWrappers*sizeof(Portal *));
portal_wrappers[numWrappers-1] = portal;
if (portal->pint.fpga_fd != -1) {
numFds++;
portal_fds = (struct pollfd *)realloc(portal_fds, numFds*sizeof(struct pollfd));
struct pollfd *pollfd = &portal_fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = portal->pint.fpga_fd;
pollfd->events = POLLIN;
}
return 0;
}
void* PortalPoller::portalExec_init(void)
{
portalExec_timeout = -1; // no interrupt timeout
#ifdef BSIM
if (global_sockfd != -1) {
portalExec_timeout = 100;
numFds++;
portal_fds = (struct pollfd *)realloc(portal_fds, numFds*sizeof(struct pollfd));
struct pollfd *pollfd = &portal_fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = global_sockfd;
pollfd->events = POLLIN;
}
#endif
if (!numFds) {
ALOGE("portalExec No fds open numFds=%d\n", numFds);
return (void*)-ENODEV;
}
for (int i = 0; i < numWrappers; i++) {
Portal *instance = portal_wrappers[i];
//fprintf(stderr, "portalExec::enabling interrupts portal %d fpga%d\n", i, instance->pint.fpga_number);
portalEnableInterrupts(&instance->pint, 1);
}
fprintf(stderr, "portalExec::about to enter loop, numFds=%d\n", numFds);
return NULL;
}
void PortalPoller::portalExec_stop(void)
{
stopping = 1;
}
void PortalPoller::portalExec_end(void)
{
stopping = 1;
for (int i = 0; i < numWrappers; i++) {
Portal *instance = portal_wrappers[i];
fprintf(stderr, "portalExec::disabling interrupts portal %d fpga%d\n", i, instance->pint.fpga_number);
portalEnableInterrupts(&instance->pint, 0);
}
}
void* PortalPoller::portalExec_poll(int timeout)
{
long rc = 0;
// LCS bypass the call to poll if the timeout is 0
if (timeout != 0) {
//poll_enter_time = portalCycleCount();
rc = poll(portal_fds, numFds, timeout);
//poll_return_time = portalCycleCount();
}
if(rc < 0) {
// return only in error case
fprintf(stderr, "poll returned rc=%ld errno=%d:%s\n", rc, errno, strerror(errno));
}
return (void*)rc;
}
void* PortalPoller::portalExec_event(void)
{
int mcnt = 0;
for (int i = 0; i < numWrappers; i++) {
if (!portal_wrappers) {
fprintf(stderr, "No portal_instances revents=%d\n", portal_fds[i].revents);
}
Portal *instance = portal_wrappers[i];
if (instance->pint.reqsize) {
/* sw portal */
if (instance->pint.accept_finished) { /* connection established */
int len = portalRecv(instance->pint.fpga_fd, (void *)instance->pint.map_base, sizeof(uint32_t));
if (len == 0 || (len == -1 && errno == EAGAIN))
continue;
if (len <= 0) {
fprintf(stderr, "%s[%d]: read error %d\n",__FUNCTION__, instance->pint.fpga_fd, errno);
exit(1);
}
instance->pint.handler(&instance->pint, *instance->pint.map_base >> 16);
}
else { /* have not received connection yet */
int sockfd = accept_socket(instance->pint.fpga_fd);
if (sockfd != -1) {
for (int j = 0; j < numFds; j++)
if (portal_fds[j].fd == instance->pint.fpga_fd) {
portal_fds[j].fd = sockfd;
break;
}
instance->pint.accept_finished = 1;
instance->pint.fpga_fd = sockfd;
}
}
continue;
}
volatile unsigned int *map_base = instance->pint.map_base;
// sanity check, to see the status of interrupt source and enable
unsigned int queue_status;
// handle all messasges from this portal instance
#ifdef BSIM
if (instance->pint.fpga_fd == -1 && !bsim_poll_interrupt())
continue;
#endif
volatile unsigned int *statp = &map_base[PORTAL_CTRL_REG_IND_QUEUE_STATUS];
volatile unsigned int *srcp = &map_base[PORTAL_CTRL_REG_INTERRUPT_STATUS];
volatile unsigned int *enp = &map_base[PORTAL_CTRL_REG_INTERRUPT_ENABLE];
while ((queue_status= READL(&instance->pint, &statp))) {
if(0) {
unsigned int int_src = READL(&instance->pint, &srcp);
unsigned int int_en = READL(&instance->pint, &enp);
fprintf(stderr, "(%d:fpga%d) about to receive messages int=%08x en=%08x qs=%08x\n", i, instance->pint.fpga_number, int_src, int_en, queue_status);
}
if (!instance->pint.handler) {
printf("[%s:%d] missing handler!!!!\n", __FUNCTION__, __LINE__);
exit(1);
}
instance->pint.handler(&instance->pint, queue_status-1);
mcnt++;
}
// re-enable interrupt which was disabled by portal_isr
portalEnableInterrupts(&instance->pint, 1);
}
return NULL;
}
void* PortalPoller::portalExec(void* __x)
{
void *rc = portalExec_init();
sem_post(&sem_startup);
while (!rc && !stopping) {
rc = portalExec_poll(portalExec_timeout);
if ((long) rc >= 0)
rc = portalExec_event();
}
portalExec_end();
printf("[%s] thread ending\n", __FUNCTION__);
return rc;
}
void* portalExec(void* __x)
{
return defaultPoller->portalExec(__x);
}
void* portalExec_init(void)
{
return defaultPoller->portalExec_init();
}
void* portalExec_poll(int timeout)
{
return defaultPoller->portalExec_poll(timeout);
}
void* portalExec_event(void)
{
return defaultPoller->portalExec_event();
}
void portalExec_end(void)
{
defaultPoller->portalExec_end();
}
static void *pthread_worker(void *__x)
{
((PortalPoller *)__x)->portalExec(__x);
return 0;
}
void PortalPoller::portalExec_start()
{
pthread_t threaddata;
pthread_create(&threaddata, NULL, &pthread_worker, (void *)this);
sem_wait(&sem_startup);
}
void portalExec_start()
{
defaultPoller->portalExec_start();
}
void portalExec_stop()
{
defaultPoller->portalExec_stop();
}
#endif // NO_CPP_PORTAL_CODE
<commit_msg>when stopping a poller, don't automatically disable interrupts for all registered portals.<commit_after>
// Copyright (c) 2012 Nokia, Inc.
// Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <string.h>
#include <poll.h>
#include <errno.h>
#include <pthread.h>
#include "portal.h"
#include "sock_utils.h"
#ifdef ZYNQ
#include <android/log.h>
#define ALOGD(fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, "PORTAL", fmt, __VA_ARGS__)
#define ALOGE(fmt, ...) __android_log_print(ANDROID_LOG_ERROR, "PORTAL", fmt, __VA_ARGS__)
#else
#define ALOGD(fmt, ...) fprintf(stderr, "PORTAL: " fmt, __VA_ARGS__)
#define ALOGE(fmt, ...) fprintf(stderr, "PORTAL: " fmt, __VA_ARGS__)
#endif
#ifndef NO_CPP_PORTAL_CODE
PortalPoller *defaultPoller = new PortalPoller();
uint64_t poll_enter_time, poll_return_time; // for performance measurement
PortalPoller::PortalPoller()
: portal_wrappers(0), portal_fds(0), numFds(0), numWrappers(0), stopping(0)
{
sem_init(&sem_startup, 0, 0);
}
int PortalPoller::unregisterInstance(Portal *portal)
{
int i = 0;
while(i < numWrappers){
if(portal_wrappers[i]->pint.fpga_number == portal->pint.fpga_number) {
fprintf(stderr, "PortalPoller::unregisterInstance %d %d\n", i, portal->pint.fpga_number);
break;
}
i++;
}
while(i < numWrappers-1){
portal_wrappers[i] = portal_wrappers[i+1];
i++;
}
numWrappers--;
i = 0;
while(i < numFds){
if(portal_fds[i].fd == portal->pint.fpga_fd)
break;
i++;
}
while(i < numFds-1){
portal_fds[i] = portal_fds[i+1];
i++;
}
numFds--;
return 0;
}
int PortalPoller::registerInstance(Portal *portal)
{
numWrappers++;
fprintf(stderr, "Portal::registerInstance fpga%d fd %d\n", portal->pint.fpga_number, portal->pint.fpga_fd);
portal_wrappers = (Portal **)realloc(portal_wrappers, numWrappers*sizeof(Portal *));
portal_wrappers[numWrappers-1] = portal;
if (portal->pint.fpga_fd != -1) {
numFds++;
portal_fds = (struct pollfd *)realloc(portal_fds, numFds*sizeof(struct pollfd));
struct pollfd *pollfd = &portal_fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = portal->pint.fpga_fd;
pollfd->events = POLLIN;
}
return 0;
}
void* PortalPoller::portalExec_init(void)
{
portalExec_timeout = -1; // no interrupt timeout
#ifdef BSIM
if (global_sockfd != -1) {
portalExec_timeout = 100;
numFds++;
portal_fds = (struct pollfd *)realloc(portal_fds, numFds*sizeof(struct pollfd));
struct pollfd *pollfd = &portal_fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = global_sockfd;
pollfd->events = POLLIN;
}
#endif
if (!numFds) {
ALOGE("portalExec No fds open numFds=%d\n", numFds);
return (void*)-ENODEV;
}
for (int i = 0; i < numWrappers; i++) {
Portal *instance = portal_wrappers[i];
//fprintf(stderr, "portalExec::enabling interrupts portal %d fpga%d\n", i, instance->pint.fpga_number);
portalEnableInterrupts(&instance->pint, 1);
}
fprintf(stderr, "portalExec::about to enter loop, numFds=%d\n", numFds);
return NULL;
}
void PortalPoller::portalExec_stop(void)
{
stopping = 1;
}
void PortalPoller::portalExec_end(void)
{
stopping = 1;
printf("%s: don't disable interrupts when stopping\n", __FUNCTION__);
return;
for (int i = 0; i < numWrappers; i++) {
Portal *instance = portal_wrappers[i];
fprintf(stderr, "portalExec::disabling interrupts portal %d fpga%d\n", i, instance->pint.fpga_number);
portalEnableInterrupts(&instance->pint, 0);
}
}
void* PortalPoller::portalExec_poll(int timeout)
{
long rc = 0;
// LCS bypass the call to poll if the timeout is 0
if (timeout != 0) {
//poll_enter_time = portalCycleCount();
rc = poll(portal_fds, numFds, timeout);
//poll_return_time = portalCycleCount();
}
if(rc < 0) {
// return only in error case
fprintf(stderr, "poll returned rc=%ld errno=%d:%s\n", rc, errno, strerror(errno));
}
return (void*)rc;
}
void* PortalPoller::portalExec_event(void)
{
int mcnt = 0;
for (int i = 0; i < numWrappers; i++) {
if (!portal_wrappers) {
fprintf(stderr, "No portal_instances revents=%d\n", portal_fds[i].revents);
}
Portal *instance = portal_wrappers[i];
if (instance->pint.reqsize) {
/* sw portal */
if (instance->pint.accept_finished) { /* connection established */
int len = portalRecv(instance->pint.fpga_fd, (void *)instance->pint.map_base, sizeof(uint32_t));
if (len == 0 || (len == -1 && errno == EAGAIN))
continue;
if (len <= 0) {
fprintf(stderr, "%s[%d]: read error %d\n",__FUNCTION__, instance->pint.fpga_fd, errno);
exit(1);
}
instance->pint.handler(&instance->pint, *instance->pint.map_base >> 16);
}
else { /* have not received connection yet */
int sockfd = accept_socket(instance->pint.fpga_fd);
if (sockfd != -1) {
for (int j = 0; j < numFds; j++)
if (portal_fds[j].fd == instance->pint.fpga_fd) {
portal_fds[j].fd = sockfd;
break;
}
instance->pint.accept_finished = 1;
instance->pint.fpga_fd = sockfd;
}
}
continue;
}
volatile unsigned int *map_base = instance->pint.map_base;
// sanity check, to see the status of interrupt source and enable
unsigned int queue_status;
// handle all messasges from this portal instance
#ifdef BSIM
if (instance->pint.fpga_fd == -1 && !bsim_poll_interrupt())
continue;
#endif
volatile unsigned int *statp = &map_base[PORTAL_CTRL_REG_IND_QUEUE_STATUS];
volatile unsigned int *srcp = &map_base[PORTAL_CTRL_REG_INTERRUPT_STATUS];
volatile unsigned int *enp = &map_base[PORTAL_CTRL_REG_INTERRUPT_ENABLE];
while ((queue_status= READL(&instance->pint, &statp))) {
if(0) {
unsigned int int_src = READL(&instance->pint, &srcp);
unsigned int int_en = READL(&instance->pint, &enp);
fprintf(stderr, "(%d:fpga%d) about to receive messages int=%08x en=%08x qs=%08x\n", i, instance->pint.fpga_number, int_src, int_en, queue_status);
}
if (!instance->pint.handler) {
printf("[%s:%d] missing handler!!!!\n", __FUNCTION__, __LINE__);
exit(1);
}
instance->pint.handler(&instance->pint, queue_status-1);
mcnt++;
}
// re-enable interrupt which was disabled by portal_isr
portalEnableInterrupts(&instance->pint, 1);
}
return NULL;
}
void* PortalPoller::portalExec(void* __x)
{
void *rc = portalExec_init();
sem_post(&sem_startup);
while (!rc && !stopping) {
rc = portalExec_poll(portalExec_timeout);
if ((long) rc >= 0)
rc = portalExec_event();
}
portalExec_end();
printf("[%s] thread ending\n", __FUNCTION__);
return rc;
}
void* portalExec(void* __x)
{
return defaultPoller->portalExec(__x);
}
void* portalExec_init(void)
{
return defaultPoller->portalExec_init();
}
void* portalExec_poll(int timeout)
{
return defaultPoller->portalExec_poll(timeout);
}
void* portalExec_event(void)
{
return defaultPoller->portalExec_event();
}
void portalExec_end(void)
{
defaultPoller->portalExec_end();
}
static void *pthread_worker(void *__x)
{
((PortalPoller *)__x)->portalExec(__x);
return 0;
}
void PortalPoller::portalExec_start()
{
pthread_t threaddata;
pthread_create(&threaddata, NULL, &pthread_worker, (void *)this);
sem_wait(&sem_startup);
}
void portalExec_start()
{
defaultPoller->portalExec_start();
}
void portalExec_stop()
{
defaultPoller->portalExec_stop();
}
#endif // NO_CPP_PORTAL_CODE
<|endoftext|> |
<commit_before>// Copyright (c) 2012 Nokia, Inc.
// Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "portal.h"
#include "sock_utils.h"
#include <string.h>
#include <poll.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h>
static int trace_poller;//=1;
#ifndef NO_CPP_PORTAL_CODE
PortalPoller *defaultPoller = new PortalPoller();
uint64_t poll_enter_time, poll_return_time; // for performance measurement
PortalPoller::PortalPoller(int autostart)
: startThread(autostart), numWrappers(0), numFds(0), inPoll(0), stopping(0)
{
memset(portal_fds, 0, sizeof(portal_fds));
memset(portal_wrappers, 0, sizeof(portal_wrappers));
int rc = pipe(pipefd);
if (rc != 0)
fprintf(stderr, "[%s:%d] pipe error %d:%s\n", __FUNCTION__, __LINE__, errno, strerror(errno));
sem_init(&sem_startup, 0, 0);
pthread_mutex_init(&mutex, NULL);
fcntl(pipefd[0], F_SETFL, O_NONBLOCK);
addFd(pipefd[0]);
timeout = -1;
#if defined(SIMULATION)
timeout = 100;
#endif
#if defined(BOARD_nfsume)
timeout = 100;
#endif
}
int PortalPoller::unregisterInstance(Portal *portal)
{
int i = 0;
pthread_mutex_lock(&mutex);
while(i < numWrappers){
if(portal_wrappers[i]->pint.fpga_number == portal->pint.fpga_number) {
//fprintf(stderr, "PortalPoller::unregisterInstance %d %d\n", i, portal->pint.fpga_number);
break;
}
i++;
}
while(i < numWrappers-1){
portal_wrappers[i] = portal_wrappers[i+1];
i++;
}
numWrappers--;
i = 0;
while(i < numFds){
if(portal_fds[i].fd == portal->pint.fpga_fd)
break;
i++;
}
while(i < numFds-1){
portal_fds[i] = portal_fds[i+1];
i++;
}
numFds--;
pthread_mutex_unlock(&mutex);
return 0;
}
void PortalPoller::addFd(int fd)
{
/* this internal function assumes mutex locked by caller.
* since it can be called from addFdToPoller(), which was called under mutex lock
* event().
*/
numFds++;
struct pollfd *pollfd = &portal_fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = fd;
pollfd->events = POLLIN;
}
int PortalPoller::registerInstance(Portal *portal)
{
uint8_t ch = 0;
pthread_mutex_lock(&mutex);
int rc = write(pipefd[1], &ch, 1); // get poll to return, so that it will try again with the new file descriptor
if (rc < 0)
fprintf(stderr, "[%s:%d] write error %d\n", __FUNCTION__, __LINE__, errno);
numWrappers++;
if (trace_poller)
fprintf(stderr, "Poller: registerInstance fpga%d fd %d clients %d\n", portal->pint.fpga_number, portal->pint.fpga_fd, portal->pint.client_fd_number);
while(inPoll)
usleep(1000);
portal_wrappers[numWrappers-1] = portal;
if (portal->pint.fpga_fd != -1)
addFd(portal->pint.fpga_fd);
for (int i = 0; i < portal->pint.client_fd_number; i++)
addFd(portal->pint.client_fd[i]);
portal->pint.transport->enableint(&portal->pint, 1);
pthread_mutex_unlock(&mutex);
start();
return 0;
}
void* PortalPoller::init(void)
{
#ifdef SIMULATION
if (global_sockfd != -1) {
pthread_mutex_lock(&mutex);
addFd(global_sockfd);
pthread_mutex_unlock(&mutex);
}
#endif
//fprintf(stderr, "Poller: about to enter loop, numFds=%d\n", numFds);
return NULL;
}
void PortalPoller::stop(void)
{
uint8_t ch = 0;
int rc;
stopping = 1;
startThread = 0;
rc = write(pipefd[1], &ch, 1);
if (rc < 0)
fprintf(stderr, "[%s:%d] write error %d\n", __FUNCTION__, __LINE__, errno);
}
void PortalPoller::end(void)
{
stopping = 1;
fprintf(stderr, "%s: don't disable interrupts when stopping\n", __FUNCTION__);
return;
pthread_mutex_lock(&mutex);
for (int i = 0; i < numWrappers; i++) {
Portal *instance = portal_wrappers[i];
fprintf(stderr, "Poller::disabling interrupts portal %d fpga%d\n", i, instance->pint.fpga_number);
instance->pint.transport->enableint(&instance->pint, 0);
}
pthread_mutex_unlock(&mutex);
}
void* PortalPoller::pollFn(int timeout)
{
long rc = 0;
//printf("[%s:%d] before poll %d numFds %d\n", __FUNCTION__, __LINE__, timeout, numFds);
//for (int i = 0; i < numFds; i++)
//printf("%s: fd %d events %x\n", __FUNCTION__, portal_fds[i].fd, portal_fds[i].events);
inPoll = 1;
if (timeout != 0)
rc = poll(portal_fds, numFds, timeout);
inPoll = 0;
if(rc < 0) {
// return only in error case
fprintf(stderr, "Poller: poll returned rc=%ld errno=%d:%s\n", rc, errno, strerror(errno));
}
return (void*)rc;
}
void* PortalPoller::event(void)
{
uint8_t ch;
pthread_mutex_lock(&mutex);
size_t rc = read(pipefd[0], &ch, 1);
if (rc < 0)
fprintf(stderr, "[%s:%d] read error %d\n", __FUNCTION__, __LINE__, errno);
for (int i = 0; i < numWrappers; i++) {
if (!portal_wrappers)
fprintf(stderr, "Poller: No portal_instances revents=%d\n", portal_fds[i].revents);
Portal *instance = portal_wrappers[i];
if (trace_poller)
fprintf(stderr, "Poller: event tile %d fpga%d fd %d handler %p parent %p\n",
instance->pint.fpga_tile, instance->pint.fpga_number, instance->pint.fpga_fd, instance->pint.handler, instance->pint.parent);
instance->pint.transport->event(&instance->pint);
if (instance->pint.handler) {
// re-enable interrupt which was disabled by portal_isr
instance->pint.transport->enableint(&instance->pint, 1);
}
}
pthread_mutex_unlock(&mutex);
return NULL;
}
extern "C" void addFdToPoller(struct PortalPoller *poller, int fd)
{
poller->addFd(fd);
}
void* PortalPoller::threadFn(void* __x)
{
void *rc = init();
sem_post(&sem_startup);
while (!rc && !stopping) {
rc = pollFn(timeout);
if ((long) rc >= 0)
rc = event();
}
end();
fprintf(stderr, "[%s] thread ending\n", __FUNCTION__);
return rc;
}
static void *pthread_worker(void *__x)
{
((PortalPoller *)__x)->threadFn(__x);
return 0;
}
void PortalPoller::start()
{
pthread_t threaddata;
pthread_mutex_lock(&mutex);
if (!startThread) {
pthread_mutex_unlock(&mutex);
return;
}
startThread = 0;
pthread_mutex_unlock(&mutex);
pthread_create(&threaddata, NULL, &pthread_worker, (void *)this);
sem_wait(&sem_startup);
}
#endif // NO_CPP_PORTAL_CODE
<commit_msg>use a timeout of 100 for PCIE gen3 until I fix the interrupt problem<commit_after>// Copyright (c) 2012 Nokia, Inc.
// Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "portal.h"
#include "sock_utils.h"
#include <string.h>
#include <poll.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h>
static int trace_poller;//=1;
#ifndef NO_CPP_PORTAL_CODE
PortalPoller *defaultPoller = new PortalPoller();
uint64_t poll_enter_time, poll_return_time; // for performance measurement
PortalPoller::PortalPoller(int autostart)
: startThread(autostart), numWrappers(0), numFds(0), inPoll(0), stopping(0)
{
memset(portal_fds, 0, sizeof(portal_fds));
memset(portal_wrappers, 0, sizeof(portal_wrappers));
int rc = pipe(pipefd);
if (rc != 0)
fprintf(stderr, "[%s:%d] pipe error %d:%s\n", __FUNCTION__, __LINE__, errno, strerror(errno));
sem_init(&sem_startup, 0, 0);
pthread_mutex_init(&mutex, NULL);
fcntl(pipefd[0], F_SETFL, O_NONBLOCK);
addFd(pipefd[0]);
timeout = -1;
#if defined(SIMULATION)
timeout = 100;
#endif
#if defined(PCIE3)
timeout = 100;
#endif
}
int PortalPoller::unregisterInstance(Portal *portal)
{
int i = 0;
pthread_mutex_lock(&mutex);
while(i < numWrappers){
if(portal_wrappers[i]->pint.fpga_number == portal->pint.fpga_number) {
//fprintf(stderr, "PortalPoller::unregisterInstance %d %d\n", i, portal->pint.fpga_number);
break;
}
i++;
}
while(i < numWrappers-1){
portal_wrappers[i] = portal_wrappers[i+1];
i++;
}
numWrappers--;
i = 0;
while(i < numFds){
if(portal_fds[i].fd == portal->pint.fpga_fd)
break;
i++;
}
while(i < numFds-1){
portal_fds[i] = portal_fds[i+1];
i++;
}
numFds--;
pthread_mutex_unlock(&mutex);
return 0;
}
void PortalPoller::addFd(int fd)
{
/* this internal function assumes mutex locked by caller.
* since it can be called from addFdToPoller(), which was called under mutex lock
* event().
*/
numFds++;
struct pollfd *pollfd = &portal_fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = fd;
pollfd->events = POLLIN;
}
int PortalPoller::registerInstance(Portal *portal)
{
uint8_t ch = 0;
pthread_mutex_lock(&mutex);
int rc = write(pipefd[1], &ch, 1); // get poll to return, so that it will try again with the new file descriptor
if (rc < 0)
fprintf(stderr, "[%s:%d] write error %d\n", __FUNCTION__, __LINE__, errno);
numWrappers++;
if (trace_poller)
fprintf(stderr, "Poller: registerInstance fpga%d fd %d clients %d\n", portal->pint.fpga_number, portal->pint.fpga_fd, portal->pint.client_fd_number);
while(inPoll)
usleep(1000);
portal_wrappers[numWrappers-1] = portal;
if (portal->pint.fpga_fd != -1)
addFd(portal->pint.fpga_fd);
for (int i = 0; i < portal->pint.client_fd_number; i++)
addFd(portal->pint.client_fd[i]);
portal->pint.transport->enableint(&portal->pint, 1);
pthread_mutex_unlock(&mutex);
start();
return 0;
}
void* PortalPoller::init(void)
{
#ifdef SIMULATION
if (global_sockfd != -1) {
pthread_mutex_lock(&mutex);
addFd(global_sockfd);
pthread_mutex_unlock(&mutex);
}
#endif
//fprintf(stderr, "Poller: about to enter loop, numFds=%d\n", numFds);
return NULL;
}
void PortalPoller::stop(void)
{
uint8_t ch = 0;
int rc;
stopping = 1;
startThread = 0;
rc = write(pipefd[1], &ch, 1);
if (rc < 0)
fprintf(stderr, "[%s:%d] write error %d\n", __FUNCTION__, __LINE__, errno);
}
void PortalPoller::end(void)
{
stopping = 1;
fprintf(stderr, "%s: don't disable interrupts when stopping\n", __FUNCTION__);
return;
pthread_mutex_lock(&mutex);
for (int i = 0; i < numWrappers; i++) {
Portal *instance = portal_wrappers[i];
fprintf(stderr, "Poller::disabling interrupts portal %d fpga%d\n", i, instance->pint.fpga_number);
instance->pint.transport->enableint(&instance->pint, 0);
}
pthread_mutex_unlock(&mutex);
}
void* PortalPoller::pollFn(int timeout)
{
long rc = 0;
//printf("[%s:%d] before poll %d numFds %d\n", __FUNCTION__, __LINE__, timeout, numFds);
//for (int i = 0; i < numFds; i++)
//printf("%s: fd %d events %x\n", __FUNCTION__, portal_fds[i].fd, portal_fds[i].events);
inPoll = 1;
if (timeout != 0)
rc = poll(portal_fds, numFds, timeout);
inPoll = 0;
if(rc < 0) {
// return only in error case
fprintf(stderr, "Poller: poll returned rc=%ld errno=%d:%s\n", rc, errno, strerror(errno));
}
return (void*)rc;
}
void* PortalPoller::event(void)
{
uint8_t ch;
pthread_mutex_lock(&mutex);
size_t rc = read(pipefd[0], &ch, 1);
if (rc < 0)
fprintf(stderr, "[%s:%d] read error %d\n", __FUNCTION__, __LINE__, errno);
for (int i = 0; i < numWrappers; i++) {
if (!portal_wrappers)
fprintf(stderr, "Poller: No portal_instances revents=%d\n", portal_fds[i].revents);
Portal *instance = portal_wrappers[i];
if (trace_poller)
fprintf(stderr, "Poller: event tile %d fpga%d fd %d handler %p parent %p\n",
instance->pint.fpga_tile, instance->pint.fpga_number, instance->pint.fpga_fd, instance->pint.handler, instance->pint.parent);
instance->pint.transport->event(&instance->pint);
if (instance->pint.handler) {
// re-enable interrupt which was disabled by portal_isr
instance->pint.transport->enableint(&instance->pint, 1);
}
}
pthread_mutex_unlock(&mutex);
return NULL;
}
extern "C" void addFdToPoller(struct PortalPoller *poller, int fd)
{
poller->addFd(fd);
}
void* PortalPoller::threadFn(void* __x)
{
void *rc = init();
sem_post(&sem_startup);
while (!rc && !stopping) {
rc = pollFn(timeout);
if ((long) rc >= 0)
rc = event();
}
end();
fprintf(stderr, "[%s] thread ending\n", __FUNCTION__);
return rc;
}
static void *pthread_worker(void *__x)
{
((PortalPoller *)__x)->threadFn(__x);
return 0;
}
void PortalPoller::start()
{
pthread_t threaddata;
pthread_mutex_lock(&mutex);
if (!startThread) {
pthread_mutex_unlock(&mutex);
return;
}
startThread = 0;
pthread_mutex_unlock(&mutex);
pthread_create(&threaddata, NULL, &pthread_worker, (void *)this);
sem_wait(&sem_startup);
}
#endif // NO_CPP_PORTAL_CODE
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* Mapnik 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 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.
*/
// qt
#include <QApplication>
#include <QStringList>
#include <QSettings>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include "mainwindow.hpp"
int main( int argc, char **argv )
{
using mapnik::datasource_cache;
using mapnik::freetype_engine;
try
{
QCoreApplication::setOrganizationName("Mapnik");
QCoreApplication::setOrganizationDomain("mapnik.org");
QCoreApplication::setApplicationName("Viewer");
QSettings settings("viewer.ini",QSettings::IniFormat);
// register input plug-ins
QString plugins_dir = settings.value("mapnik/plugins_dir",
QVariant("/usr/local/lib/mapnik/input/")).toString();
datasource_cache::instance().register_datasources(plugins_dir.toStdString());
// register fonts
int count = settings.beginReadArray("mapnik/fonts");
for (int index=0; index < count; ++index)
{
settings.setArrayIndex(index);
QString font_dir = settings.value("dir").toString();
freetype_engine::register_fonts(font_dir.toStdString());
}
settings.endArray();
QApplication app( argc, argv );
MainWindow window;
window.show();
if (argc > 1) window.open(argv[1]);
if (argc >= 3)
{
QStringList list = QString(argv[2]).split(",");
if (list.size()==4)
{
bool ok;
double x0 = list[0].toDouble(&ok);
double y0 = list[1].toDouble(&ok);
double x1 = list[2].toDouble(&ok);
double y1 = list[3].toDouble(&ok);
if (ok) window.set_default_extent(x0,y0,x1,y1);
}
}
else
{
std::shared_ptr<mapnik::Map> map = window.get_map();
if (map) map->zoom_all();
}
if (argc == 4)
{
bool ok;
double scaling_factor = QString(argv[3]).toDouble(&ok);
if (ok) window.set_scaling_factor(scaling_factor);
}
return app.exec();
}
catch (std::exception const& ex)
{
std::cerr << "Could not start viewer: '" << ex.what() << "'\n";
return 1;
}
}
<commit_msg>use sigleton interface when calling freetype_engine methods.<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* Mapnik 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 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.
*/
// qt
#include <QApplication>
#include <QStringList>
#include <QSettings>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include "mainwindow.hpp"
int main( int argc, char **argv )
{
using mapnik::datasource_cache;
using mapnik::freetype_engine;
try
{
QCoreApplication::setOrganizationName("Mapnik");
QCoreApplication::setOrganizationDomain("mapnik.org");
QCoreApplication::setApplicationName("Viewer");
QSettings settings("viewer.ini",QSettings::IniFormat);
// register input plug-ins
QString plugins_dir = settings.value("mapnik/plugins_dir",
QVariant("/usr/local/lib/mapnik/input/")).toString();
datasource_cache::instance().register_datasources(plugins_dir.toStdString());
// register fonts
int count = settings.beginReadArray("mapnik/fonts");
for (int index=0; index < count; ++index)
{
settings.setArrayIndex(index);
QString font_dir = settings.value("dir").toString();
freetype_engine::instance().register_fonts(font_dir.toStdString());
}
settings.endArray();
QApplication app( argc, argv );
MainWindow window;
window.show();
if (argc > 1) window.open(argv[1]);
if (argc >= 3)
{
QStringList list = QString(argv[2]).split(",");
if (list.size()==4)
{
bool ok;
double x0 = list[0].toDouble(&ok);
double y0 = list[1].toDouble(&ok);
double x1 = list[2].toDouble(&ok);
double y1 = list[3].toDouble(&ok);
if (ok) window.set_default_extent(x0,y0,x1,y1);
}
}
else
{
std::shared_ptr<mapnik::Map> map = window.get_map();
if (map) map->zoom_all();
}
if (argc == 4)
{
bool ok;
double scaling_factor = QString(argv[3]).toDouble(&ok);
if (ok) window.set_scaling_factor(scaling_factor);
}
return app.exec();
}
catch (std::exception const& ex)
{
std::cerr << "Could not start viewer: '" << ex.what() << "'\n";
return 1;
}
}
<|endoftext|> |
<commit_before>// File: linux_kvm_guest_tao_service.cc
// Author: Tom Roeder <tmroeder@google.com>
//
// Description: The Tao for Linux in a KVM guest.
//
// Copyright (c) 2013, Google Inc. 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 <fstream>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include <keyczar/base/base64w.h>
#include <keyczar/keyczar.h>
#include <openssl/ssl.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include "tao/linux_tao.h"
#include "tao/kvm_unix_tao_child_channel.h"
#include "tao/pipe_tao_channel.h"
#include "tao/process_factory.h"
#include "tao/tao_child_channel.h"
#include "tao/tao_child_channel_registry.h"
#include "tao/util.h"
#include "tao/whitelist_auth.h"
using std::ifstream;
using std::shared_ptr;
using std::string;
using std::stringstream;
using std::vector;
using keyczar::base::Base64WDecode;
using tao::LinuxTao;
using tao::KvmUnixTaoChildChannel;
using tao::PipeTaoChannel;
using tao::ProcessFactory;
using tao::TaoChildChannel;
using tao::TaoChildChannelRegistry;
using tao::WhitelistAuth;
DEFINE_string(secret_path, "linux_tao_service_secret",
"The path to the TPM-sealed key for this binary");
DEFINE_string(key_path, "linux_tao_service_files/key",
"An encrypted keyczar directory for an encryption key");
DEFINE_string(pk_key_path, "linux_tao_service_files/public_key",
"An encrypted keyczar directory for a signing key");
DEFINE_string(whitelist, "signed_whitelist", "A signed whitelist file");
DEFINE_string(policy_pk_path, "./policy_public_key",
"The path to the public policy key");
DEFINE_string(program_socket, "/tmp/.linux_tao_socket",
"The name of a file to use as the socket for incoming program "
"creation requests");
DEFINE_string(ca_host, "", "The hostname of the TCCA server, if any");
DEFINE_string(ca_port, "", "The port for the TCCA server, if any");
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
google::InstallFailureSignalHandler();
FLAGS_alsologtostderr = true;
google::InitGoogleLogging(argv[0]);
tao::InitializeOpenSSL();
// In the guest, the params are the last element in /proc/cmdline, as
// delimited by space.
ifstream proc_cmd("/proc/cmdline");
if (!proc_cmd) {
LOG(ERROR) << "Could not open /proc/cmdline to get the command line";
return 1;
}
stringstream proc_stream;
proc_stream << proc_cmd.rdbuf();
// Split on space and take the last element.
string cmdline(proc_stream.str());
size_t space_index = cmdline.find_last_of(' ');
if (space_index == string::npos) {
LOG(ERROR) << "Could not find any characters in the kernel boot params";
return 1;
}
string encoded_params(cmdline.substr(space_index + 1));
string params;
if (!Base64WDecode(encoded_params, ¶ms)) {
LOG(ERROR) << "Could not decode the encoded params " << encoded_params;
return 1;
}
TaoChildChannelRegistry registry;
tao::RegisterKnownChannels(®istry);
scoped_ptr<TaoChildChannel> child_channel(registry.Create(params));
CHECK(child_channel->Init()) << "Could not initialize the child channel";
scoped_ptr<WhitelistAuth> whitelist_auth(
new WhitelistAuth(FLAGS_whitelist, FLAGS_policy_pk_path));
CHECK(whitelist_auth->Init())
<< "Could not initialize the authorization manager";
// The Channels to use for hosted programs and the way to create hosted
// programs.
scoped_ptr<PipeTaoChannel> pipe_channel(
new PipeTaoChannel(FLAGS_program_socket));
scoped_ptr<ProcessFactory> process_factory(new ProcessFactory());
CHECK(process_factory->Init()) << "Could not initialize the process factory";
scoped_ptr<LinuxTao> tao(
new LinuxTao(FLAGS_secret_path, FLAGS_key_path, FLAGS_pk_key_path,
FLAGS_policy_pk_path, child_channel.release(),
pipe_channel.release(), process_factory.release(),
whitelist_auth.release(), FLAGS_ca_host, FLAGS_ca_port));
CHECK(tao->Init()) << "Could not initialize the LinuxTao";
LOG(INFO) << "Linux Tao Service started and waiting for requests";
// Listen for program creation requests and for messages from hosted programs
// that have been created.
CHECK(tao->Listen());
return 0;
}
<commit_msg>Changes to get the KVM Guest Tao to work<commit_after>// File: linux_kvm_guest_tao_service.cc
// Author: Tom Roeder <tmroeder@google.com>
//
// Description: The Tao for Linux in a KVM guest.
//
// Copyright (c) 2013, Google Inc. 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 <fstream>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include <keyczar/base/base64w.h>
#include <keyczar/keyczar.h>
#include <openssl/ssl.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include "tao/linux_tao.h"
#include "tao/kvm_unix_tao_child_channel.h"
#include "tao/pipe_tao_channel.h"
#include "tao/process_factory.h"
#include "tao/tao_child_channel.h"
#include "tao/tao_child_channel_registry.h"
#include "tao/util.h"
#include "tao/whitelist_auth.h"
using std::ifstream;
using std::shared_ptr;
using std::string;
using std::stringstream;
using std::vector;
using keyczar::base::Base64WDecode;
using tao::LinuxTao;
using tao::KvmUnixTaoChildChannel;
using tao::PipeTaoChannel;
using tao::ProcessFactory;
using tao::TaoChildChannel;
using tao::TaoChildChannelRegistry;
using tao::WhitelistAuth;
DEFINE_string(secret_path, "linux_tao_service_secret",
"The path to the TPM-sealed key for this binary");
DEFINE_string(key_path, "linux_tao_service_files/key",
"An encrypted keyczar directory for an encryption key");
DEFINE_string(pk_key_path, "linux_tao_service_files/public_key",
"An encrypted keyczar directory for a signing key");
DEFINE_string(whitelist, "signed_whitelist", "A signed whitelist file");
DEFINE_string(policy_pk_path, "./policy_public_key",
"The path to the public policy key");
DEFINE_string(program_socket, "/tmp/.linux_tao_socket",
"The name of a file to use as the socket for incoming program "
"creation requests");
DEFINE_string(ca_host, "", "The hostname of the TCCA server, if any");
DEFINE_string(ca_port, "", "The port for the TCCA server, if any");
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
google::InstallFailureSignalHandler();
FLAGS_alsologtostderr = true;
google::InitGoogleLogging(argv[0]);
tao::InitializeOpenSSL();
// In the guest, the params are the last element in /proc/cmdline, as
// delimited by space.
ifstream proc_cmd("/proc/cmdline");
if (!proc_cmd) {
LOG(ERROR) << "Could not open /proc/cmdline to get the command line";
return 1;
}
stringstream proc_stream;
proc_stream << proc_cmd.rdbuf();
// Split on space and take the last element.
string cmdline(proc_stream.str());
size_t space_index = cmdline.find_last_of(' ');
if (space_index == string::npos) {
LOG(ERROR) << "Could not find any characters in the kernel boot params";
return 1;
}
// The last character is a newline, so stop before it.
LOG(INFO) << "cmdline.size() == " << (int)cmdline.size();
LOG(INFO) << "space_index == " << (int)space_index;
string encoded_params(cmdline.substr(space_index + 1,
cmdline.size() - (space_index + 1) - 1));
LOG(INFO) << "The length of the encoded string is " << encoded_params.size();
string params;
if (!Base64WDecode(encoded_params, ¶ms)) {
LOG(ERROR) << "Could not decode the encoded params " << encoded_params;
return 1;
}
TaoChildChannelRegistry registry;
tao::RegisterKnownChannels(®istry);
scoped_ptr<TaoChildChannel> child_channel(registry.Create(params));
CHECK(child_channel->Init()) << "Could not initialize the child channel";
scoped_ptr<WhitelistAuth> whitelist_auth(
new WhitelistAuth(FLAGS_whitelist, FLAGS_policy_pk_path));
CHECK(whitelist_auth->Init())
<< "Could not initialize the authorization manager";
// The Channels to use for hosted programs and the way to create hosted
// programs.
scoped_ptr<PipeTaoChannel> pipe_channel(
new PipeTaoChannel(FLAGS_program_socket));
scoped_ptr<ProcessFactory> process_factory(new ProcessFactory());
CHECK(process_factory->Init()) << "Could not initialize the process factory";
scoped_ptr<LinuxTao> tao(
new LinuxTao(FLAGS_secret_path, FLAGS_key_path, FLAGS_pk_key_path,
FLAGS_policy_pk_path, child_channel.release(),
pipe_channel.release(), process_factory.release(),
whitelist_auth.release(), FLAGS_ca_host, FLAGS_ca_port));
CHECK(tao->Init()) << "Could not initialize the LinuxTao";
LOG(INFO) << "Linux Tao Service started and waiting for requests";
// Listen for program creation requests and for messages from hosted programs
// that have been created.
CHECK(tao->Listen());
return 0;
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// frontend_logger.cpp
//
// Identification: src/backend/logging/frontend_logger.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <thread>
#include "backend/common/logger.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/frontend_logger.h"
#include "backend/logging/checkpoint.h"
#include "backend/logging/checkpoint_factory.h"
#include "backend/logging/loggers/wal_frontend_logger.h"
#include "backend/logging/loggers/wbl_frontend_logger.h"
// configuration for testing
extern int64_t peloton_wait_timeout;
namespace peloton {
namespace logging {
FrontendLogger::FrontendLogger()
: checkpoint(CheckpointFactory::GetInstance()) {
logger_type = LOGGER_TYPE_FRONTEND;
// Set wait timeout
wait_timeout = peloton_wait_timeout;
}
FrontendLogger::~FrontendLogger() {
for (auto backend_logger : backend_loggers) {
delete backend_logger;
}
}
/** * @brief Return the frontend logger based on logging type
* @param logging type can be write ahead logging or write behind logging
*/
FrontendLogger *FrontendLogger::GetFrontendLogger(LoggingType logging_type) {
FrontendLogger *frontend_logger = nullptr;
if (IsBasedOnWriteAheadLogging(logging_type) == true) {
frontend_logger = new WriteAheadFrontendLogger();
} else if (IsBasedOnWriteBehindLogging(logging_type) == true) {
frontend_logger = new WriteBehindFrontendLogger();
} else {
LOG_ERROR("Unsupported logging type");
}
return frontend_logger;
}
/**
* @brief MainLoop
*/
void FrontendLogger::MainLoop(void) {
auto &log_manager = LogManager::GetInstance();
/////////////////////////////////////////////////////////////////////
// STANDBY MODE
/////////////////////////////////////////////////////////////////////
LOG_TRACE("FrontendLogger Standby Mode");
// Standby before we need to do RECOVERY
log_manager.WaitForModeTransition(LOGGING_STATUS_TYPE_STANDBY, false);
// Do recovery if we can, otherwise terminate
switch (log_manager.GetLoggingStatus()) {
case LOGGING_STATUS_TYPE_RECOVERY: {
LOG_TRACE("Frontendlogger] Recovery Mode");
/////////////////////////////////////////////////////////////////////
// RECOVERY MODE
/////////////////////////////////////////////////////////////////////
// First, do recovery if needed
LOG_INFO("Log manager: Invoking DoRecovery");
DoRecovery();
LOG_INFO("Log manager: DoRecovery done");
// Now, enter LOGGING mode
log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_LOGGING);
break;
}
case LOGGING_STATUS_TYPE_LOGGING: {
LOG_TRACE("Frontendlogger] Logging Mode");
} break;
default:
break;
}
/////////////////////////////////////////////////////////////////////
// LOGGING MODE
/////////////////////////////////////////////////////////////////////
// Periodically, wake up and do logging
while (log_manager.GetLoggingStatus() == LOGGING_STATUS_TYPE_LOGGING) {
// Collect LogRecords from all backend loggers
// LOG_INFO("Log manager: Invoking CollectLogRecordsFromBackendLoggers");
CollectLogRecordsFromBackendLoggers();
// Flush the data to the file
// LOG_INFO("Log manager: Invoking FlushLogRecords");
FlushLogRecords();
}
/////////////////////////////////////////////////////////////////////
// TERMINATE MODE
/////////////////////////////////////////////////////////////////////
// flush any remaining log records
CollectLogRecordsFromBackendLoggers();
FlushLogRecords();
/////////////////////////////////////////////////////////////////////
// SLEEP MODE
/////////////////////////////////////////////////////////////////////
LOG_TRACE("Frontendlogger Sleep Mode");
// Setting frontend logger status to sleep
log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_SLEEP);
}
/**
* @brief Collect the log records from BackendLoggers
*/
void FrontendLogger::CollectLogRecordsFromBackendLoggers() {
auto sleep_period = std::chrono::microseconds(wait_timeout);
std::this_thread::sleep_for(sleep_period);
{
cid_t max_possible_commit_id = MAX_CID;
// Look at the local queues of the backend loggers
for (auto backend_logger : backend_loggers) {
{
std::lock_guard<std::mutex> lock(backend_logger->local_queue_mutex);
auto local_queue_size = backend_logger->local_queue.size();
// Skip current backend_logger, nothing to do
if (local_queue_size == 0) continue;
// Move the log record from backend_logger to here
for (oid_t log_record_itr = 0; log_record_itr < local_queue_size;
log_record_itr++) {
LOG_INFO("Found a log record to push in global queue");
global_queue.push_back(
std::move(backend_logger->local_queue[log_record_itr]));
}
max_possible_commit_id = std::min(
backend_logger->GetHighestLoggedCommitId(), max_possible_commit_id);
// cleanup the local queue
backend_logger->local_queue.clear();
}
}
if (max_possible_commit_id != MAX_CID) {
assert(max_possible_commit_id >= max_collected_commit_id);
max_collected_commit_id = max_possible_commit_id;
}
}
}
/**
* @brief Store backend logger
* @param backend logger
*/
void FrontendLogger::AddBackendLogger(BackendLogger *backend_logger) {
// Add backend logger to the list of backend loggers
backend_loggers.push_back(backend_logger);
}
} // namespace logging
}
<commit_msg>test branch commit<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// frontend_logger.cpp
//
// Identification: src/backend/logging/frontend_logger.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <thread>
#include "backend/common/logger.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/frontend_logger.h"
#include "backend/logging/checkpoint.h"
#include "backend/logging/checkpoint_factory.h"
#include "backend/logging/loggers/wal_frontend_logger.h"
#include "backend/logging/loggers/wbl_frontend_logger.h"
// configuration for testing
extern int64_t peloton_wait_timeout;
namespace peloton {
namespace logging {
FrontendLogger::FrontendLogger()
: checkpoint(CheckpointFactory::GetInstance()) {
logger_type = LOGGER_TYPE_FRONTEND;
// Set wait timeout
wait_timeout = peloton_wait_timeout;
}
FrontendLogger::~FrontendLogger() {
for (auto backend_logger : backend_loggers) {
delete backend_logger;
}
}
/** * @brief Return the frontend logger based on logging type
* @param logging type can be write ahead logging or write behind logging
*/
FrontendLogger *FrontendLogger::GetFrontendLogger(LoggingType logging_type) {
FrontendLogger *frontend_logger = nullptr;
if (IsBasedOnWriteAheadLogging(logging_type) == true) {
frontend_logger = new WriteAheadFrontendLogger();
} else if (IsBasedOnWriteBehindLogging(logging_type) == true) {
frontend_logger = new WriteBehindFrontendLogger();
} else {
LOG_ERROR("Unsupported logging type");
}
return frontend_logger;
}
/**
* @brief MainLoop
*/
void FrontendLogger::MainLoop(void) {
auto &log_manager = LogManager::GetInstance();
/////////////////////////////////////////////////////////////////////
// STANDBY MODE
/////////////////////////////////////////////////////////////////////
LOG_TRACE("FrontendLogger Standby Mode");
// Standby before we need to do RECOVERY
log_manager.WaitForModeTransition(LOGGING_STATUS_TYPE_STANDBY, false);
// Do recovery if we can, otherwise terminate
switch (log_manager.GetLoggingStatus()) {
case LOGGING_STATUS_TYPE_RECOVERY: {
LOG_TRACE("Frontendlogger] Recovery Mode");
/////////////////////////////////////////////////////////////////////
// RECOVERY MODE
/////////////////////////////////////////////////////////////////////
// First, do recovery if needed
LOG_INFO("Log manager: Invoking DoRecovery");
DoRecovery();
LOG_INFO("Log manager: DoRecovery done");
// Now, enter LOGGING mode
log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_LOGGING);
break;
}
case LOGGING_STATUS_TYPE_LOGGING: {
LOG_TRACE("Frontendlogger] Logging Mode");
} break;
default:
break;
}
/////////////////////////////////////////////////////////////////////
// LOGGING MODE
/////////////////////////////////////////////////////////////////////
// Periodically, wake up and do logging
while (log_manager.GetLoggingStatus() == LOGGING_STATUS_TYPE_LOGGING) {
// Collect LogRecords from all backend loggers
// LOG_INFO("Log manager: Invoking CollectLogRecordsFromBackendLoggers");
CollectLogRecordsFromBackendLoggers();
// Flush the data to the file
// LOG_INFO("Log manager: Invoking FlushLogRecords");
FlushLogRecords();
}
/////////////////////////////////////////////////////////////////////
// TERMINATE MODE
/////////////////////////////////////////////////////////////////////
// flush any remaining log records
CollectLogRecordsFromBackendLoggers();
FlushLogRecords();
/////////////////////////////////////////////////////////////////////
// SLEEP MODE
/////////////////////////////////////////////////////////////////////
LOG_TRACE("Frontendlogger Sleep Mode");
// Setting frontend logger status to sleep
log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_SLEEP);
}
/**
* @brief Collect the log records from BackendLoggers
*/
void FrontendLogger::CollectLogRecordsFromBackendLoggers() {
auto sleep_period = std::chrono::microseconds(wait_timeout);
std::this_thread::sleep_for(sleep_period);
{
cid_t max_possible_commit_id = MAX_CID;
// Look at the local queues of the backend loggers
for (auto backend_logger : backend_loggers) {
{
std::lock_guard<std::mutex> lock(backend_logger->local_queue_mutex);
auto local_queue_size = backend_logger->local_queue.size();
// Skip current backend_logger, nothing to do
if (local_queue_size == 0) continue;
// Move the log record from backend_logger to here
for (oid_t log_record_itr = 0; log_record_itr < local_queue_size;
log_record_itr++) {
LOG_INFO("Found a log record to push in global queue");
global_queue.push_back(
std::move(backend_logger->local_queue[log_record_itr]));
}
max_possible_commit_id = std::min(
backend_logger->GetHighestLoggedCommitId(), max_possible_commit_id);
// cleanup the local queue
backend_logger->local_queue.clear();
}
}
if (max_possible_commit_id != MAX_CID) {
assert(max_possible_commit_id >= max_collected_commit_id);
max_collected_commit_id = max_possible_commit_id;
}
}
}
/**
* @brief Store backend logger
* @param backend logger
*/
void FrontendLogger::AddBackendLogger(BackendLogger *backend_logger) {
// Add backend logger to the list of backend loggers
backend_loggers.push_back(backend_logger);
}
} // namespace logging
}
<|endoftext|> |
<commit_before>#pragma once
#include <kernel_headers/transpose.hpp>
#define __CL_ENABLE_EXCEPTIONS
#include <cl.hpp>
#include <platform.hpp>
#include <traits.hpp>
#include <sstream>
#include <string>
#include <dispatch.hpp>
using cl::Buffer;
using cl::Program;
using cl::make_kernel;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;
namespace opencl
{
namespace kernel
{
static const dim_type TILE_DIM = 32;
static const dim_type THREADS_X = TILE_DIM;
static const dim_type THREADS_Y = TILE_DIM/4;
template<typename T>
void transpose( Buffer &out, const Buffer &in, const dim_type ndims, const dim_type * const dims,
const dim_type * const strides, const dim_type offset)
{
Program::Sources setSrc;
setSrc.emplace_back(transpose_cl, transpose_cl_len);
Program prog(getContext(), setSrc);
std::ostringstream options;
options << " -D T=" << dtype_traits<T>::getName()
<< " -D dim_type=" << dtype_traits<dim_type>::getName()
<< " -D TILE_DIM=" << TILE_DIM;
prog.build(options.str().c_str());
auto transposeOp = make_kernel< Buffer, Buffer,
dim_type, dim_type,
dim_type, dim_type,
dim_type, dim_type > (prog, "transpose");
NDRange local(THREADS_X,THREADS_Y);
dim_type blk_x = divup(dims[0],TILE_DIM);
dim_type blk_y = divup(dims[1],TILE_DIM);
// launch batch * blk_x blocks along x dimension
NDRange global( blk_x*TILE_DIM*dims[2],
blk_y*TILE_DIM);
transposeOp(EnqueueArgs(getQueue(), global, local),
out, in, dims[0], dims[1],
strides[1], strides[2], offset, blk_x);
}
}
}
<commit_msg>added opencl kernel caching for transpose<commit_after>#pragma once
#include <kernel_headers/transpose.hpp>
#define __CL_ENABLE_EXCEPTIONS
#include <cl.hpp>
#include <platform.hpp>
#include <traits.hpp>
#include <sstream>
#include <string>
#include <mutex>
#include <dispatch.hpp>
using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::make_kernel;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;
namespace opencl
{
namespace kernel
{
static const dim_type TILE_DIM = 32;
static const dim_type THREADS_X = TILE_DIM;
static const dim_type THREADS_Y = TILE_DIM/4;
template<typename T>
void transpose( Buffer &out, const Buffer &in, const dim_type ndims, const dim_type * const dims,
const dim_type * const strides, const dim_type offset)
{
static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
static Program trsProgs[DeviceManager::MAX_DEVICES];
static Kernel trsKernels[DeviceManager::MAX_DEVICES];
int device = getActiveDeviceId();
std::call_once( compileFlags[device], [device] () {
Program::Sources setSrc;
setSrc.emplace_back(transpose_cl, transpose_cl_len);
trsProgs[device] = Program(getContext(), setSrc);
std::ostringstream options;
options << " -D T=" << dtype_traits<T>::getName()
<< " -D dim_type=" << dtype_traits<dim_type>::getName()
<< " -D TILE_DIM=" << TILE_DIM;
trsProgs[device].build(options.str().c_str());
trsKernels[device] = Kernel(trsProgs[device], "transpose");
});
auto transposeOp = make_kernel< Buffer, Buffer,
dim_type, dim_type,
dim_type, dim_type,
dim_type, dim_type > (trsKernels[device]);
NDRange local(THREADS_X,THREADS_Y);
dim_type blk_x = divup(dims[0],TILE_DIM);
dim_type blk_y = divup(dims[1],TILE_DIM);
// launch batch * blk_x blocks along x dimension
NDRange global( blk_x*TILE_DIM*dims[2],
blk_y*TILE_DIM);
transposeOp(EnqueueArgs(getQueue(), global, local),
out, in, dims[0], dims[1],
strides[1], strides[2], offset, blk_x);
}
}
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <chartsql/runtime/ValueExpression.h>
#include <stx/inspect.h>
using namespace stx;
namespace csql {
ValueExpression::ValueExpression(
Instruction* entry,
ScratchMemory&& static_storage,
size_t dynamic_storage_size) :
entry_(entry),
static_storage_(std::move(static_storage)),
dynamic_storage_size_(dynamic_storage_size),
has_aggregate_(false) {
initProgram(entry_);
}
ValueExpression::~ValueExpression() {
freeProgram(entry_);
}
ValueExpression::Instance ValueExpression::allocInstance(
ScratchMemory* scratch) const {
Instance that;
if (has_aggregate_) {
that.scratch = scratch->alloc(dynamic_storage_size_);
initInstance(entry_, &that);
} else {
that.scratch = scratch->construct<SValue>();
}
return that;
}
void ValueExpression::freeInstance(Instance* instance) const {
if (has_aggregate_) {
freeInstance(entry_, instance);
} else {
((SValue*) instance->scratch)->~SValue();
}
}
void ValueExpression::reset(Instance* instance) const {
if (has_aggregate_) {
resetInstance(entry_, instance);
} else {
*((SValue*) instance->scratch) = SValue();
}
}
void ValueExpression::result(
Instance* instance,
SValue* out) const {
if (has_aggregate_) {
return evaluate(instance, entry_, 0, nullptr, out);
} else {
*out = *((SValue*) instance->scratch);
}
}
void ValueExpression::accumulate(
Instance* instance,
int argc,
const SValue* argv) const {
if (has_aggregate_) {
return accumulate(instance, entry_, argc, argv);
} else {
return evaluate(nullptr, entry_, argc, argv, (SValue*) instance->scratch);
}
}
void ValueExpression::evaluate(
int argc,
const SValue* argv,
SValue* out) const {
return evaluate(nullptr, entry_, argc, argv, out);
}
void ValueExpression::initInstance(Instruction* e, Instance* instance) const {
switch (e->type) {
case X_CALL_AGGREGATE:
if (e->vtable.t_aggregate.init) {
e->vtable.t_aggregate.init(
(char *) instance->scratch + (size_t) e->arg0);
}
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
initInstance(cur, instance);
}
}
void ValueExpression::freeInstance(Instruction* e, Instance* instance) const {
switch (e->type) {
case X_CALL_AGGREGATE:
if (e->vtable.t_aggregate.free) {
e->vtable.t_aggregate.free(
(char *) instance->scratch + (size_t) e->arg0);
}
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
freeInstance(cur, instance);
}
}
void ValueExpression::resetInstance(Instruction* e, Instance* instance) const {
switch (e->type) {
case X_CALL_AGGREGATE:
e->vtable.t_aggregate.reset(
(char *) instance->scratch + (size_t) e->arg0);
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
resetInstance(cur, instance);
}
}
void ValueExpression::initProgram(Instruction* e) {
switch (e->type) {
case X_CALL_AGGREGATE:
has_aggregate_ = true;
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
initProgram(cur);
}
}
void ValueExpression::freeProgram(Instruction* e) const {
switch (e->type) {
case X_LITERAL:
((SValue*) e->arg0)->~SValue();
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
freeProgram(cur);
}
}
void ValueExpression::evaluate(
Instance* instance,
Instruction* expr,
int argc,
const SValue* argv,
SValue* out) const {
/* execute expression */
switch (expr->type) {
case X_IF: {
SValue cond;
auto cond_expr = expr->child;
evaluate(instance, cond_expr, argc, argv, &cond);
auto branch = cond_expr->next;
if (!cond.getBoolWithConversion()) {
branch = branch->next;
}
evaluate(instance, branch, argc, argv, out);
return;
}
case X_CALL_PURE: {
SValue* stackv = nullptr;
auto stackn = expr->argn;
if (stackn > 0) {
// FIXPAUL free...
stackv = reinterpret_cast<SValue*>(alloca(sizeof(SValue) * expr->argn));
for (int i = 0; i < stackn; ++i) {
new (stackv + i) SValue();
}
auto stackp = stackv;
for (auto cur = expr->child; cur != nullptr; cur = cur->next) {
evaluate(instance, cur, argc, argv, stackp++);
}
}
expr->vtable.t_pure.call(stackn, stackv, out);
return;
}
case X_CALL_AGGREGATE: {
if (!instance) {
RAISE(
kIllegalArgumentError,
"non-static expression called without instance pointer");
}
auto scratch = (char *) instance->scratch + (size_t) expr->arg0;
expr->vtable.t_aggregate.get(scratch, out);
return;
}
case X_LITERAL: {
*out = *static_cast<SValue*>(expr->arg0);
return;
}
case X_INPUT: {
auto index = reinterpret_cast<uint64_t>(expr->arg0);
if (index >= argc) {
RAISE(kRuntimeError, "invalid row index %i", index);
}
*out = argv[index];
return;
}
}
}
void ValueExpression::accumulate(
Instance* instance,
Instruction* expr,
int argc,
const SValue* argv) const {
switch (expr->type) {
case X_CALL_AGGREGATE: {
SValue* stackv = nullptr;
auto stackn = expr->argn;
if (stackn > 0) {
stackv = reinterpret_cast<SValue*>(
alloca(sizeof(SValue) * expr->argn));
for (int i = 0; i < stackn; ++i) {
new (stackv + i) SValue();
}
auto stackp = stackv;
for (auto cur = expr->child; cur != nullptr; cur = cur->next) {
evaluate(
instance,
cur,
argc,
argv,
stackp++);
}
}
auto scratch = (char *) instance->scratch + (size_t) expr->arg0;
expr->vtable.t_aggregate.accumulate(scratch, stackn, stackv);
return;
}
default: {
for (auto cur = expr->child; cur != nullptr; cur = cur->next) {
accumulate(instance, cur, argc, argv);
}
return;
}
}
}
}
<commit_msg>free stack svalues in X_CALL_PURE<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <chartsql/runtime/ValueExpression.h>
#include <stx/inspect.h>
using namespace stx;
namespace csql {
ValueExpression::ValueExpression(
Instruction* entry,
ScratchMemory&& static_storage,
size_t dynamic_storage_size) :
entry_(entry),
static_storage_(std::move(static_storage)),
dynamic_storage_size_(dynamic_storage_size),
has_aggregate_(false) {
initProgram(entry_);
}
ValueExpression::~ValueExpression() {
freeProgram(entry_);
}
ValueExpression::Instance ValueExpression::allocInstance(
ScratchMemory* scratch) const {
Instance that;
if (has_aggregate_) {
that.scratch = scratch->alloc(dynamic_storage_size_);
initInstance(entry_, &that);
} else {
that.scratch = scratch->construct<SValue>();
}
return that;
}
void ValueExpression::freeInstance(Instance* instance) const {
if (has_aggregate_) {
freeInstance(entry_, instance);
} else {
((SValue*) instance->scratch)->~SValue();
}
}
void ValueExpression::reset(Instance* instance) const {
if (has_aggregate_) {
resetInstance(entry_, instance);
} else {
*((SValue*) instance->scratch) = SValue();
}
}
void ValueExpression::result(
Instance* instance,
SValue* out) const {
if (has_aggregate_) {
return evaluate(instance, entry_, 0, nullptr, out);
} else {
*out = *((SValue*) instance->scratch);
}
}
void ValueExpression::accumulate(
Instance* instance,
int argc,
const SValue* argv) const {
if (has_aggregate_) {
return accumulate(instance, entry_, argc, argv);
} else {
return evaluate(nullptr, entry_, argc, argv, (SValue*) instance->scratch);
}
}
void ValueExpression::evaluate(
int argc,
const SValue* argv,
SValue* out) const {
return evaluate(nullptr, entry_, argc, argv, out);
}
void ValueExpression::initInstance(Instruction* e, Instance* instance) const {
switch (e->type) {
case X_CALL_AGGREGATE:
if (e->vtable.t_aggregate.init) {
e->vtable.t_aggregate.init(
(char *) instance->scratch + (size_t) e->arg0);
}
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
initInstance(cur, instance);
}
}
void ValueExpression::freeInstance(Instruction* e, Instance* instance) const {
switch (e->type) {
case X_CALL_AGGREGATE:
if (e->vtable.t_aggregate.free) {
e->vtable.t_aggregate.free(
(char *) instance->scratch + (size_t) e->arg0);
}
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
freeInstance(cur, instance);
}
}
void ValueExpression::resetInstance(Instruction* e, Instance* instance) const {
switch (e->type) {
case X_CALL_AGGREGATE:
e->vtable.t_aggregate.reset(
(char *) instance->scratch + (size_t) e->arg0);
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
resetInstance(cur, instance);
}
}
void ValueExpression::initProgram(Instruction* e) {
switch (e->type) {
case X_CALL_AGGREGATE:
has_aggregate_ = true;
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
initProgram(cur);
}
}
void ValueExpression::freeProgram(Instruction* e) const {
switch (e->type) {
case X_LITERAL:
((SValue*) e->arg0)->~SValue();
break;
default:
break;
}
for (auto cur = e->child; cur != nullptr; cur = cur->next) {
freeProgram(cur);
}
}
void ValueExpression::evaluate(
Instance* instance,
Instruction* expr,
int argc,
const SValue* argv,
SValue* out) const {
/* execute expression */
switch (expr->type) {
case X_IF: {
SValue cond;
auto cond_expr = expr->child;
evaluate(instance, cond_expr, argc, argv, &cond);
auto branch = cond_expr->next;
if (!cond.getBoolWithConversion()) {
branch = branch->next;
}
evaluate(instance, branch, argc, argv, out);
return;
}
case X_CALL_PURE: {
SValue* stackv = nullptr;
auto stackn = expr->argn;
if (stackn > 0) {
stackv = reinterpret_cast<SValue*>(alloca(sizeof(SValue) * expr->argn));
for (int i = 0; i < stackn; ++i) {
new (stackv + i) SValue();
}
try {
auto stackp = stackv;
for (auto cur = expr->child; cur != nullptr; cur = cur->next) {
evaluate(instance, cur, argc, argv, stackp++);
}
} catch (...) {
for (int i = 0; i < stackn; ++i) {
(stackv + i)->~SValue();
}
throw;
};
for (int i = 0; i < stackn; ++i) {
(stackv + i)->~SValue();
}
}
expr->vtable.t_pure.call(stackn, stackv, out);
return;
}
case X_CALL_AGGREGATE: {
if (!instance) {
RAISE(
kIllegalArgumentError,
"non-static expression called without instance pointer");
}
auto scratch = (char *) instance->scratch + (size_t) expr->arg0;
expr->vtable.t_aggregate.get(scratch, out);
return;
}
case X_LITERAL: {
*out = *static_cast<SValue*>(expr->arg0);
return;
}
case X_INPUT: {
auto index = reinterpret_cast<uint64_t>(expr->arg0);
if (index >= argc) {
RAISE(kRuntimeError, "invalid row index %i", index);
}
*out = argv[index];
return;
}
}
}
void ValueExpression::accumulate(
Instance* instance,
Instruction* expr,
int argc,
const SValue* argv) const {
switch (expr->type) {
case X_CALL_AGGREGATE: {
SValue* stackv = nullptr;
auto stackn = expr->argn;
if (stackn > 0) {
stackv = reinterpret_cast<SValue*>(
alloca(sizeof(SValue) * expr->argn));
for (int i = 0; i < stackn; ++i) {
new (stackv + i) SValue();
}
auto stackp = stackv;
for (auto cur = expr->child; cur != nullptr; cur = cur->next) {
evaluate(
instance,
cur,
argc,
argv,
stackp++);
}
}
auto scratch = (char *) instance->scratch + (size_t) expr->arg0;
expr->vtable.t_aggregate.accumulate(scratch, stackn, stackv);
return;
}
default: {
for (auto cur = expr->child; cur != nullptr; cur = cur->next) {
accumulate(instance, cur, argc, argv);
}
return;
}
}
}
}
<|endoftext|> |
<commit_before>#include <cthun-client/connector/connector.hpp>
#include <cthun-client/connector/uuid.hpp>
#include <cthun-client/protocol/message.hpp>
#include <cthun-client/protocol/schemas.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE CTHUN_CLIENT_LOGGING_PREFIX".connector"
#include <leatherman/logging/logging.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cstdio>
#include <chrono>
namespace CthunClient {
//
// Constants
//
static const uint CONNECTION_CHECK_S { 15 }; // [s]
static const int DEFAULT_MSG_TIMEOUT { 10 }; // [s]
static const std::string MY_SERVER_URI { "cth:///server" };
//
// Utility functions
//
// TODO(ale): move this to leatherman
std::string getISO8601Time(unsigned int modifier_in_seconds) {
boost::posix_time::ptime t = boost::posix_time::microsec_clock::universal_time()
+ boost::posix_time::seconds(modifier_in_seconds);
return boost::posix_time::to_iso_extended_string(t) + "Z";
}
// TODO(ale): move plural from the common StringUtils in leatherman
template<typename T>
std::string plural(std::vector<T> things);
std::string plural(int num_of_things) {
return num_of_things > 1 ? "s" : "";
}
//
// Public api
//
Connector::Connector(const std::string& server_url,
const std::string& client_type,
const std::string& ca_crt_path,
const std::string& client_crt_path,
const std::string& client_key_path)
: server_url_ { server_url },
client_metadata_ { client_type,
ca_crt_path,
client_crt_path,
client_key_path },
connection_ptr_ { nullptr },
validator_ {},
schema_callback_pairs_ {},
mutex_ {},
cond_var_ {},
is_destructing_ { false },
is_monitoring_ { false } {
addSchemasToValidator();
}
Connector::~Connector() {
if (connection_ptr_ != nullptr) {
// reset callbacks to avoid breaking the Connection instance
// due to callbacks having an invalid reference context
LOG_INFO("Resetting the WebSocket event callbacks");
connection_ptr_->resetCallbacks();
}
{
std::lock_guard<std::mutex> the_lock { mutex_ };
is_destructing_ = true;
cond_var_.notify_one();
}
}
// Register schemas and onMessage callbacks
void Connector::registerMessageCallback(const Schema schema,
MessageCallback callback) {
validator_.registerSchema(schema);
auto p = std::pair<std::string, MessageCallback>(schema.getName(), callback);
schema_callback_pairs_.insert(p);
}
// Manage the connection state
void Connector::connect(int max_connect_attempts) {
if (connection_ptr_ == nullptr) {
// Initialize the WebSocket connection
connection_ptr_.reset(new Connection(server_url_, client_metadata_));
connection_ptr_->setOnMessageCallback(
[this](std::string message) {
processMessage(message);
});
connection_ptr_->setOnOpenCallback(
[this]() {
associateSession();
});
}
try {
// Open the WebSocket connection
connection_ptr_->connect(max_connect_attempts);
} catch (connection_processing_error& e) {
// NB: connection_fatal_errors are propagated whereas
// connection_processing_errors are converted to
// connection_config_errors (they can be thrown after
// websocketpp::Endpoint::connect() or ::send() failures)
LOG_ERROR("Failed to connect: %1%", e.what());
throw connection_config_error { e.what() };
}
}
bool Connector::isConnected() const {
// TODO(ale): make this consistent with the associate transaction
// as in the protocol specs (perhaps with an associated flag)
return connection_ptr_ != nullptr
&& connection_ptr_->getConnectionState() == ConnectionStateValues::open;
}
void Connector::monitorConnection(int max_connect_attempts) {
checkConnectionInitialization();
if (!is_monitoring_) {
is_monitoring_ = true;
startMonitorTask(max_connect_attempts);
} else {
LOG_WARNING("The monitorConnection has already been called");
}
}
// Send messages
void Connector::send(const Message& msg) {
checkConnectionInitialization();
auto serialized_msg = msg.getSerialized();
LOG_DEBUG("Sending message of %1% bytes:\n%2%",
serialized_msg.size(), msg.toString());
connection_ptr_->send(&serialized_msg[0], serialized_msg.size());
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
const DataContainer& data_json,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
false,
data_json.toString(),
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
const std::string& data_binary,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
false,
data_binary,
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const DataContainer& data_json,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
destination_report,
data_json.toString(),
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const std::string& data_binary,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
destination_report,
data_binary,
debug);
}
//
// Private interface
//
// Utility functions
void Connector::checkConnectionInitialization() {
if (connection_ptr_ == nullptr) {
throw connection_not_init_error { "connection not initialized" };
}
}
void Connector::addSchemasToValidator() {
validator_.registerSchema(Protocol::EnvelopeSchema());
validator_.registerSchema(Protocol::DebugSchema());
}
MessageChunk Connector::createEnvelope(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report) {
auto msg_id = UUID::getUUID();
auto expires = getISO8601Time(timeout);
LOG_INFO("Creating message with id %1% for %2% receiver%3%",
msg_id, targets.size(), plural(targets.size()));
DataContainer envelope_content {};
envelope_content.set<std::string>("id", msg_id);
envelope_content.set<std::string>("message_type", message_type);
envelope_content.set<std::vector<std::string>>("targets", targets);
envelope_content.set<std::string>("expires", expires);
envelope_content.set<std::string>("sender", client_metadata_.uri);
if (destination_report) {
envelope_content.set<bool>("destination_report", true);
}
return MessageChunk { ChunkDescriptor::ENVELOPE, envelope_content.toString() };
}
void Connector::sendMessage(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const std::string& data_txt,
const std::vector<DataContainer>& debug) {
auto envelope_chunk = createEnvelope(targets, message_type, timeout, destination_report);
MessageChunk data_chunk { ChunkDescriptor::DATA, data_txt };
Message msg { envelope_chunk, data_chunk };
for (auto debug_content : debug) {
MessageChunk d_c { ChunkDescriptor::DEBUG, debug_content.toString() };
msg.addDebugChunk(d_c);
}
send(msg);
}
// Login
void Connector::associateSession() {
// Envelope
auto envelope = createEnvelope(std::vector<std::string> { MY_SERVER_URI },
Protocol::ASSOCIATE_REQ_TYPE,
DEFAULT_MSG_TIMEOUT,
false);
// Create and send message
Message msg { envelope };
LOG_INFO("Sending Associate Session request");
send(msg);
}
// WebSocket onMessage callback
void Connector::processMessage(const std::string& msg_txt) {
LOG_DEBUG("Received message of %1% bytes:\n%2%", msg_txt.size(), msg_txt);
// Deserialize the incoming message
std::unique_ptr<Message> msg_ptr;
try {
msg_ptr.reset(new Message(msg_txt));
} catch (message_error& e) {
LOG_ERROR("Failed to deserialize message: %1%", e.what());
return;
}
// Parse message chunks
ParsedChunks parsed_chunks;
try {
parsed_chunks = msg_ptr->getParsedChunks(validator_);
} catch (validation_error& e) {
LOG_ERROR("Invalid message - bad content: %1%", e.what());
return;
} catch (data_parse_error& e) {
LOG_ERROR("Invalid message - invalid JSON content: %1%", e.what());
return;
} catch (schema_not_found_error& e) {
LOG_ERROR("Invalid message - unknown schema: %1%", e.what());
return;
}
// Execute the callback associated with the data schema
auto schema_name = parsed_chunks.envelope.get<std::string>("message_type");
if (schema_callback_pairs_.find(schema_name) != schema_callback_pairs_.end()) {
auto c_b = schema_callback_pairs_.at(schema_name);
LOG_TRACE("Executing callback for a message with '%1%' schema",
schema_name);
c_b(parsed_chunks);
} else {
LOG_WARNING("No message callback has be registered for '%1%' schema",
schema_name);
}
}
// Monitor task
void Connector::startMonitorTask(int max_connect_attempts) {
assert(connection_ptr_ != nullptr);
while (true) {
std::unique_lock<std::mutex> the_lock { mutex_ };
auto now = std::chrono::system_clock::now();
cond_var_.wait_until(the_lock,
now + std::chrono::seconds(CONNECTION_CHECK_S));
if (is_destructing_) {
// The dtor has been invoked
LOG_INFO("Stopping the monitor task");
is_monitoring_ = false;
the_lock.unlock();
return;
}
try {
if (!isConnected()) {
LOG_WARNING("Connection to Cthun server lost; retrying");
connection_ptr_->connect(max_connect_attempts);
} else {
LOG_DEBUG("Sending heartbeat ping");
connection_ptr_->ping();
}
} catch (connection_processing_error& e) {
// Connection::connect() or ping() failure - keep trying
LOG_ERROR("Connection monitor failure: %1%", e.what());
} catch (connection_fatal_error& e) {
// Failed to reconnect after max_connect_attempts - stop
LOG_ERROR("The connection monitor task will stop - failure: %1%",
e.what());
is_monitoring_ = false;
the_lock.unlock();
throw;
}
the_lock.unlock();
}
}
} // namespace CthunClient
<commit_msg>(maint) Trivial style change<commit_after>#include <cthun-client/connector/connector.hpp>
#include <cthun-client/connector/uuid.hpp>
#include <cthun-client/protocol/message.hpp>
#include <cthun-client/protocol/schemas.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE CTHUN_CLIENT_LOGGING_PREFIX".connector"
#include <leatherman/logging/logging.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cstdio>
#include <chrono>
namespace CthunClient {
//
// Constants
//
static const uint CONNECTION_CHECK_S { 15 }; // [s]
static const int DEFAULT_MSG_TIMEOUT { 10 }; // [s]
static const std::string MY_SERVER_URI { "cth:///server" };
//
// Utility functions
//
// TODO(ale): move this to leatherman
std::string getISO8601Time(unsigned int modifier_in_seconds) {
boost::posix_time::ptime t = boost::posix_time::microsec_clock::universal_time()
+ boost::posix_time::seconds(modifier_in_seconds);
return boost::posix_time::to_iso_extended_string(t) + "Z";
}
// TODO(ale): move plural from the common StringUtils in leatherman
template<typename T>
std::string plural(std::vector<T> things);
std::string plural(int num_of_things) {
return num_of_things > 1 ? "s" : "";
}
//
// Public api
//
Connector::Connector(const std::string& server_url,
const std::string& client_type,
const std::string& ca_crt_path,
const std::string& client_crt_path,
const std::string& client_key_path)
: server_url_ { server_url },
client_metadata_ { client_type,
ca_crt_path,
client_crt_path,
client_key_path },
connection_ptr_ { nullptr },
validator_ {},
schema_callback_pairs_ {},
mutex_ {},
cond_var_ {},
is_destructing_ { false },
is_monitoring_ { false } {
addSchemasToValidator();
}
Connector::~Connector() {
if (connection_ptr_ != nullptr) {
// reset callbacks to avoid breaking the Connection instance
// due to callbacks having an invalid reference context
LOG_INFO("Resetting the WebSocket event callbacks");
connection_ptr_->resetCallbacks();
}
{
std::lock_guard<std::mutex> the_lock { mutex_ };
is_destructing_ = true;
cond_var_.notify_one();
}
}
// Register schemas and onMessage callbacks
void Connector::registerMessageCallback(const Schema schema,
MessageCallback callback) {
validator_.registerSchema(schema);
auto p = std::pair<std::string, MessageCallback>(schema.getName(), callback);
schema_callback_pairs_.insert(p);
}
// Manage the connection state
void Connector::connect(int max_connect_attempts) {
if (connection_ptr_ == nullptr) {
// Initialize the WebSocket connection
connection_ptr_.reset(new Connection(server_url_, client_metadata_));
connection_ptr_->setOnMessageCallback(
[this](std::string message) {
processMessage(message);
});
connection_ptr_->setOnOpenCallback(
[this]() {
associateSession();
});
}
try {
// Open the WebSocket connection
connection_ptr_->connect(max_connect_attempts);
} catch (connection_processing_error& e) {
// NB: connection_fatal_errors are propagated whereas
// connection_processing_errors are converted to
// connection_config_errors (they can be thrown after
// websocketpp::Endpoint::connect() or ::send() failures)
LOG_ERROR("Failed to connect: %1%", e.what());
throw connection_config_error { e.what() };
}
}
bool Connector::isConnected() const {
// TODO(ale): make this consistent with the associate transaction
// as in the protocol specs (perhaps with an associated flag)
return connection_ptr_ != nullptr
&& connection_ptr_->getConnectionState() == ConnectionStateValues::open;
}
void Connector::monitorConnection(int max_connect_attempts) {
checkConnectionInitialization();
if (!is_monitoring_) {
is_monitoring_ = true;
startMonitorTask(max_connect_attempts);
} else {
LOG_WARNING("The monitorConnection has already been called");
}
}
// Send messages
void Connector::send(const Message& msg) {
checkConnectionInitialization();
auto serialized_msg = msg.getSerialized();
LOG_DEBUG("Sending message of %1% bytes:\n%2%",
serialized_msg.size(), msg.toString());
connection_ptr_->send(&serialized_msg[0], serialized_msg.size());
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
const DataContainer& data_json,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
false,
data_json.toString(),
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
const std::string& data_binary,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
false,
data_binary,
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const DataContainer& data_json,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
destination_report,
data_json.toString(),
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const std::string& data_binary,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
destination_report,
data_binary,
debug);
}
//
// Private interface
//
// Utility functions
void Connector::checkConnectionInitialization() {
if (connection_ptr_ == nullptr) {
throw connection_not_init_error { "connection not initialized" };
}
}
void Connector::addSchemasToValidator() {
validator_.registerSchema(Protocol::EnvelopeSchema());
validator_.registerSchema(Protocol::DebugSchema());
}
MessageChunk Connector::createEnvelope(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report) {
auto msg_id = UUID::getUUID();
auto expires = getISO8601Time(timeout);
LOG_INFO("Creating message with id %1% for %2% receiver%3%",
msg_id, targets.size(), plural(targets.size()));
DataContainer envelope_content {};
envelope_content.set<std::string>("id", msg_id);
envelope_content.set<std::string>("message_type", message_type);
envelope_content.set<std::vector<std::string>>("targets", targets);
envelope_content.set<std::string>("expires", expires);
envelope_content.set<std::string>("sender", client_metadata_.uri);
if (destination_report) {
envelope_content.set<bool>("destination_report", true);
}
return MessageChunk { ChunkDescriptor::ENVELOPE, envelope_content.toString() };
}
void Connector::sendMessage(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const std::string& data_txt,
const std::vector<DataContainer>& debug) {
auto envelope_chunk = createEnvelope(targets, message_type, timeout,
destination_report);
MessageChunk data_chunk { ChunkDescriptor::DATA, data_txt };
Message msg { envelope_chunk, data_chunk };
for (auto debug_content : debug) {
MessageChunk d_c { ChunkDescriptor::DEBUG, debug_content.toString() };
msg.addDebugChunk(d_c);
}
send(msg);
}
// Login
void Connector::associateSession() {
// Envelope
auto envelope = createEnvelope(std::vector<std::string> { MY_SERVER_URI },
Protocol::ASSOCIATE_REQ_TYPE,
DEFAULT_MSG_TIMEOUT,
false);
// Create and send message
Message msg { envelope };
LOG_INFO("Sending Associate Session request");
send(msg);
}
// WebSocket onMessage callback
void Connector::processMessage(const std::string& msg_txt) {
LOG_DEBUG("Received message of %1% bytes:\n%2%", msg_txt.size(), msg_txt);
// Deserialize the incoming message
std::unique_ptr<Message> msg_ptr;
try {
msg_ptr.reset(new Message(msg_txt));
} catch (message_error& e) {
LOG_ERROR("Failed to deserialize message: %1%", e.what());
return;
}
// Parse message chunks
ParsedChunks parsed_chunks;
try {
parsed_chunks = msg_ptr->getParsedChunks(validator_);
} catch (validation_error& e) {
LOG_ERROR("Invalid message - bad content: %1%", e.what());
return;
} catch (data_parse_error& e) {
LOG_ERROR("Invalid message - invalid JSON content: %1%", e.what());
return;
} catch (schema_not_found_error& e) {
LOG_ERROR("Invalid message - unknown schema: %1%", e.what());
return;
}
// Execute the callback associated with the data schema
auto schema_name = parsed_chunks.envelope.get<std::string>("message_type");
if (schema_callback_pairs_.find(schema_name) != schema_callback_pairs_.end()) {
auto c_b = schema_callback_pairs_.at(schema_name);
LOG_TRACE("Executing callback for a message with '%1%' schema",
schema_name);
c_b(parsed_chunks);
} else {
LOG_WARNING("No message callback has be registered for '%1%' schema",
schema_name);
}
}
// Monitor task
void Connector::startMonitorTask(int max_connect_attempts) {
assert(connection_ptr_ != nullptr);
while (true) {
std::unique_lock<std::mutex> the_lock { mutex_ };
auto now = std::chrono::system_clock::now();
cond_var_.wait_until(the_lock,
now + std::chrono::seconds(CONNECTION_CHECK_S));
if (is_destructing_) {
// The dtor has been invoked
LOG_INFO("Stopping the monitor task");
is_monitoring_ = false;
the_lock.unlock();
return;
}
try {
if (!isConnected()) {
LOG_WARNING("Connection to Cthun server lost; retrying");
connection_ptr_->connect(max_connect_attempts);
} else {
LOG_DEBUG("Sending heartbeat ping");
connection_ptr_->ping();
}
} catch (connection_processing_error& e) {
// Connection::connect() or ping() failure - keep trying
LOG_ERROR("Connection monitor failure: %1%", e.what());
} catch (connection_fatal_error& e) {
// Failed to reconnect after max_connect_attempts - stop
LOG_ERROR("The connection monitor task will stop - failure: %1%",
e.what());
is_monitoring_ = false;
the_lock.unlock();
throw;
}
the_lock.unlock();
}
}
} // namespace CthunClient
<|endoftext|> |
<commit_before>#include <x0/flow2/ASTPrinter.h>
#include <x0/flow2/AST.h>
namespace x0 {
inline std::string escape(char value) // {{{
{
switch (value) {
case '\t': return "<TAB>";
case '\r': return "<CR>";
case '\n': return "<LF>";
case ' ': return "<SPACE>";
default: break;
}
if (std::isprint(value)) {
std::string s;
s += value;
return s;
} else {
char buf[16];
snprintf(buf, sizeof(buf), "0x%02X", value);
return buf;
}
} // }}}
inline std::string escape(const std::string& value) // {{{
{
std::string result;
for (const char ch: value)
result += escape(ch);
return result;
} // }}}
void ASTPrinter::print(ASTNode* node)
{
ASTPrinter printer;
node->accept(printer);
}
ASTPrinter::ASTPrinter() :
depth_(0)
{
}
void ASTPrinter::prefix()
{
for (int i = 0; i < depth_; ++i)
std::printf(" ");
}
void ASTPrinter::print(const char* title, ASTNode* node)
{
enter();
printf("%s\n", title);
enter();
node->accept(*this);
leave();
leave();
}
void ASTPrinter::visit(Variable& variable)
{
printf("Variable: '%s'\n", variable.name().c_str());
print("initializer", variable.initializer());
}
void ASTPrinter::visit(Handler& handler)
{
printf("Handler: %s\n", handler.name().c_str());
enter();
printf("scope:\n");
enter();
for (Symbol* symbol: *handler.scope())
symbol->accept(*this);
leave();
printf("body:\n");
enter();
handler.body()->accept(*this);
leave();
leave();
}
void ASTPrinter::visit(BuiltinFunction& symbol)
{
printf("BuiltinFunction TODO\n");
}
void ASTPrinter::visit(BuiltinHandler& symbol)
{
printf("BuiltinHandler TODO\n");
}
void ASTPrinter::visit(Unit& unit)
{
printf("Unit: %s\n", unit.name().c_str());
enter();
for (Symbol* symbol: *unit.scope())
symbol->accept(*this);
leave();
}
void ASTPrinter::visit(UnaryExpr& expr)
{
printf("UnaryExpr TODO\n");
}
void ASTPrinter::visit(BinaryExpr& expr)
{
printf("BinaryExpr: %s\n", expr.op().c_str());
enter();
printf("lhs:\n");
enter();
expr.leftExpr()->accept(*this);
leave();
leave();
enter();
printf("rhs:\n");
enter();
expr.rightExpr()->accept(*this);
leave();
leave();
}
void ASTPrinter::visit(FunctionCallExpr& expr)
{
printf("FunctionCallExpr TODO\n");
}
void ASTPrinter::visit(VariableExpr& expr)
{
printf("VariableExpr: %s\n", expr.variable()->name().c_str());
}
void ASTPrinter::visit(HandlerRefExpr& handlerRef)
{
printf("HandlerRefExpr TODO\n");
}
void ASTPrinter::visit(ListExpr& list)
{
printf("ListExpr (%zu elements)\n", list.size());
size_t i = 0;
for (const auto& expr: list) {
char buf[16];
snprintf(buf, sizeof(buf), "[%zu]", i++);
print(buf, expr.get());
}
}
void ASTPrinter::visit(StringExpr& string)
{
printf("StringExpr: \"%s\"", escape(string.value()).c_str());
}
void ASTPrinter::visit(NumberExpr& number)
{
printf("NumberExpr: %lli\n", number.value());
}
void ASTPrinter::visit(BoolExpr& boolean)
{
printf("BoolExpr: %s\n", boolean.value() ? "true" : "false");
}
void ASTPrinter::visit(RegExpExpr& regexp)
{
printf("RegExpExpr: /%s/\n", regexp.value().c_str());
}
void ASTPrinter::visit(IPAddressExpr& ipaddr)
{
printf("IPAddressExpr: %s\n", ipaddr.value().str().c_str());
}
void ASTPrinter::visit(CidrExpr& cidr)
{
printf("CidrExpr: %s\n", cidr.value().str().c_str());
}
void ASTPrinter::visit(ExprStmt& stmt)
{
printf("ExprStmt\n");
}
void ASTPrinter::visit(CompoundStmt& compoundStmt)
{
printf("CompoundStmt (%d statements)\n", compoundStmt.count());
enter();
for (auto& stmt: compoundStmt) {
stmt->accept(*this);
}
leave();
}
void ASTPrinter::visit(CondStmt& cond)
{
printf("CondStmt\n");
print("condition", cond.condition());
print("thenStmt", cond.thenStmt());
print("elseStmt", cond.elseStmt());
}
void ASTPrinter::visit(AssignStmt& assign)
{
printf("AssignStmt\n");
enter();
printf("lhs(var): %s\n", assign.variable()->name().c_str());
leave();
print("rhs", assign.expression());
}
void ASTPrinter::visit(HandlerCallStmt& handlerCall)
{
printf("HandlerCallStmt: %s\n", handlerCall.handler()->name().c_str());
}
void ASTPrinter::visit(BuiltinHandlerCallStmt& handlerCall)
{
printf("BuiltinHandlerCallStmt: %s\n", handlerCall.handler()->name().c_str());
}
} // namespace x0
<commit_msg>flow: ASTPrinter may print NULL'd leaf-nodes<commit_after>#include <x0/flow2/ASTPrinter.h>
#include <x0/flow2/AST.h>
namespace x0 {
inline std::string escape(char value) // {{{
{
switch (value) {
case '\t': return "<TAB>";
case '\r': return "<CR>";
case '\n': return "<LF>";
case ' ': return "<SPACE>";
default: break;
}
if (std::isprint(value)) {
std::string s;
s += value;
return s;
} else {
char buf[16];
snprintf(buf, sizeof(buf), "0x%02X", value);
return buf;
}
} // }}}
inline std::string escape(const std::string& value) // {{{
{
std::string result;
for (const char ch: value)
result += escape(ch);
return result;
} // }}}
void ASTPrinter::print(ASTNode* node)
{
ASTPrinter printer;
node->accept(printer);
}
ASTPrinter::ASTPrinter() :
depth_(0)
{
}
void ASTPrinter::prefix()
{
for (int i = 0; i < depth_; ++i)
std::printf(" ");
}
void ASTPrinter::print(const char* title, ASTNode* node)
{
enter();
if (node) {
printf("%s\n", title);
enter();
node->accept(*this);
leave();
} else {
printf("%s (nil)\n", title);
}
leave();
}
void ASTPrinter::visit(Variable& variable)
{
printf("Variable: '%s'\n", variable.name().c_str());
print("initializer", variable.initializer());
}
void ASTPrinter::visit(Handler& handler)
{
printf("Handler: %s\n", handler.name().c_str());
enter();
printf("scope:\n");
enter();
for (Symbol* symbol: *handler.scope())
symbol->accept(*this);
leave();
printf("body:\n");
enter();
handler.body()->accept(*this);
leave();
leave();
}
void ASTPrinter::visit(BuiltinFunction& symbol)
{
printf("BuiltinFunction TODO\n");
}
void ASTPrinter::visit(BuiltinHandler& symbol)
{
printf("BuiltinHandler TODO\n");
}
void ASTPrinter::visit(Unit& unit)
{
printf("Unit: %s\n", unit.name().c_str());
enter();
for (Symbol* symbol: *unit.scope())
symbol->accept(*this);
leave();
}
void ASTPrinter::visit(UnaryExpr& expr)
{
printf("UnaryExpr TODO\n");
}
void ASTPrinter::visit(BinaryExpr& expr)
{
printf("BinaryExpr: %s\n", expr.op().c_str());
enter();
printf("lhs:\n");
enter();
expr.leftExpr()->accept(*this);
leave();
leave();
enter();
printf("rhs:\n");
enter();
expr.rightExpr()->accept(*this);
leave();
leave();
}
void ASTPrinter::visit(FunctionCallExpr& expr)
{
printf("FunctionCallExpr TODO\n");
}
void ASTPrinter::visit(VariableExpr& expr)
{
printf("VariableExpr: %s\n", expr.variable()->name().c_str());
}
void ASTPrinter::visit(HandlerRefExpr& handlerRef)
{
printf("HandlerRefExpr TODO\n");
}
void ASTPrinter::visit(ListExpr& list)
{
printf("ListExpr (%zu elements)\n", list.size());
size_t i = 0;
for (const auto& expr: list) {
char buf[16];
snprintf(buf, sizeof(buf), "[%zu]", i++);
print(buf, expr.get());
}
}
void ASTPrinter::visit(StringExpr& string)
{
printf("StringExpr: \"%s\"", escape(string.value()).c_str());
}
void ASTPrinter::visit(NumberExpr& number)
{
printf("NumberExpr: %lli\n", number.value());
}
void ASTPrinter::visit(BoolExpr& boolean)
{
printf("BoolExpr: %s\n", boolean.value() ? "true" : "false");
}
void ASTPrinter::visit(RegExpExpr& regexp)
{
printf("RegExpExpr: /%s/\n", regexp.value().c_str());
}
void ASTPrinter::visit(IPAddressExpr& ipaddr)
{
printf("IPAddressExpr: %s\n", ipaddr.value().str().c_str());
}
void ASTPrinter::visit(CidrExpr& cidr)
{
printf("CidrExpr: %s\n", cidr.value().str().c_str());
}
void ASTPrinter::visit(ExprStmt& stmt)
{
printf("ExprStmt\n");
}
void ASTPrinter::visit(CompoundStmt& compoundStmt)
{
printf("CompoundStmt (%d statements)\n", compoundStmt.count());
enter();
for (auto& stmt: compoundStmt) {
stmt->accept(*this);
}
leave();
}
void ASTPrinter::visit(CondStmt& cond)
{
printf("CondStmt\n");
print("condition", cond.condition());
print("thenStmt", cond.thenStmt());
print("elseStmt", cond.elseStmt());
}
void ASTPrinter::visit(AssignStmt& assign)
{
printf("AssignStmt\n");
enter();
printf("lhs(var): %s\n", assign.variable()->name().c_str());
leave();
print("rhs", assign.expression());
}
void ASTPrinter::visit(HandlerCallStmt& handlerCall)
{
printf("HandlerCallStmt: %s\n", handlerCall.handler()->name().c_str());
}
void ASTPrinter::visit(BuiltinHandlerCallStmt& handlerCall)
{
printf("BuiltinHandlerCallStmt: %s\n", handlerCall.handler()->name().c_str());
}
} // namespace x0
<|endoftext|> |
<commit_before>#include <Robot.hpp>
#include <gameplay/planning/bezier.hpp>
#include <framework/Dynamics.hpp>
#include <Utils.hpp>
#include <LogUtils.hpp>
#include <protobuf/LogFrame.pb.h>
#include <stdio.h>
#include <execinfo.h>
#include <stdexcept>
#include <boost/foreach.hpp>
using namespace std;
using namespace Geometry2d;
/** Constant for timestamp to seconds */
const float intTimeStampToFloat = 1000000.0f;
Robot::Robot(unsigned int shell, bool self)
{
_shell = shell;
_self = self;
angle = 0;
angleVel = 0;
}
OurRobot::OurRobot(int shell, SystemState *state):
Robot(shell, true),
_state(state)
{
willKick = false;
avoidBall = false;
exclude = false;
hasBall = false;
cmd_w = 0;
_lastChargedTime = 0;
_dynamics = new Planning::Dynamics(this);
_planner = new Planning::RRT::Planner();
for (size_t i = 0; i < Num_Shells; ++i)
{
approachOpponent[i] = false;
}
_planner->setDynamics(_dynamics);
_planner->maxIterations(250);
radioTx.set_board_id(shell);
for (int m = 0; m < 4; ++m)
{
radioTx.add_motors(0);
}
}
void OurRobot::addText(const QString& text, const QColor& qc)
{
Packet::DebugText *dbg = new Packet::DebugText;
// dbg->set_layer(_state->findDebugLayer(layer));
dbg->set_text(text.toStdString());
dbg->set_color(color(qc));
robotText.push_back(dbg);
}
void OurRobot::setCommandTrace()
{
void *trace[9];
int n = backtrace(trace, sizeof(trace) / sizeof(trace[0]));
// Skip the call into this function
_commandTrace.resize(n - 1);
for (int i = 0; i < n - 1; ++i)
{
_commandTrace[i] = trace[i + 1];
}
}
void OurRobot::resetMotionCommand()
{
robotText.clear();
willKick = false;
avoidBall = false;
radioTx.set_roller(0);
radioTx.set_kick(0);
radioTx.set_use_chipper(false);
for (int i = 0; i < 4; ++i)
{
radioTx.set_motors(i, 0);
}
cmd = MotionCmd();
// Stay in place if possible.
stop();
}
void OurRobot::stop()
{
move(pos);
}
void OurRobot::move(Geometry2d::Point pt, bool stopAtEnd)
{
if (!visible)
{
return;
}
// _state->drawLine(pos, pt);
// create a new path
Planning::Path newPath;
// determine the obstacles
ObstacleGroup& og = obstacles;
// run the RRT planner to generate a new plan
_planner->run(pos, angle, vel, pt, &og, newPath);
_path = newPath;
Geometry2d::Point last = pos;
BOOST_FOREACH(Geometry2d::Point pt, _path.points)
{
_state->drawLine(last, pt);
last = pt;
}
// call the path move command
executeMove(stopAtEnd);
// cmd.goalPosition = pt;
//
// // handle stop at end commands
// if (stopAtEnd)
// cmd.pathEnd = MotionCmd::StopAtEnd;
// else
// cmd.pathEnd = MotionCmd::FastAtEnd;
//
// // enable the RRT-based planner
// cmd.planner = MotionCmd::RRT;
}
void OurRobot::move(const vector<Geometry2d::Point>& path, bool stopAtEnd)
{
_state->drawLine(path.back(), pos);
// copy path from input
_path.clear();
_path.points = path;
// execute
executeMove(stopAtEnd);
}
void OurRobot::bezierMove(const vector<Geometry2d::Point>& controls,
MotionCmd::OrientationType facing,
MotionCmd::PathEndType endpoint) {
// calculate path using simple interpolation
// _path = Planning::createBezierPath(controls);
// execute path
//executeMove(endpoint); // FIXME: handles curves poorly
size_t degree = controls.size();
// generate coefficients
vector<float> coeffs;
for (size_t i=0; i<degree; ++i) {
coeffs.push_back(Planning::binomialCoefficient(degree-1, i));
}
// calculate length to allow for determination of time
double pathLength = Planning::bezierLength(controls, coeffs);
// calculate numerical derivative by stepping ahead a fixed constant
float lookAheadDist = 0.15; // in meters along path
float dt = lookAheadDist/pathLength;
float velGain = 3.0; // FIXME: should be dependent on the length of the curve
// calculate a target velocity for translation
Point targetVel = Planning::evaluateBezierVelocity(dt, controls, coeffs);
// apply gain
targetVel *= velGain;
// create a dummy goal position
cmd.goalPosition = pos + targetVel;
cmd.pathLength = pathLength;
cmd.planner = MotionCmd::Point;
}
void OurRobot::executeMove(bool stopAtEnd)
{
setCommandTrace();
// given a path, determine what the best point to use as a
// target point is, and assign to packet
if (_path.empty()) {
// THIS IS VERY BAD AND SHOULD NOT OCCUR
throw runtime_error("In OurRobot::executeMove: empty path!");
}
//dynamics path
float length = _path.length();
// handle direct point commands where the length may be very small
if (fabs(length) < 1e-5) {
length = pos.distTo(_path.points[0]);
}
//target point is the last point on the closest segment
Geometry2d::Point targetPos = _path.points[0]; // first point
size_t path_start = 0;
if (_path.points.size() > 1)
{
targetPos = _path.points[1];
}
//ideally we want to travel towards 2 points ahead...due to delays
if (_path.points.size() > 2)
{
targetPos = _path.points[2];
path_start = 1;
}
cmd.goalPosition = targetPos;
cmd.pathLength = _path.length(path_start);
cmd.planner = MotionCmd::Point;
}
void OurRobot::directVelocityCommands(const Geometry2d::Point& trans, double ang)
{
cmd.planner = MotionCmd::DirectVelocity;
cmd.direct_ang_vel = ang;
cmd.direct_trans_vel = trans;
}
void OurRobot::directMotorCommands(const vector<int8_t>& speeds) {
cmd.planner = MotionCmd::DirectMotor;
cmd.direct_motor_cmds = speeds;
}
Geometry2d::Point OurRobot::pointInRobotSpace(const Geometry2d::Point& pt) const {
Point p = pt;
p.rotate(pos, -angle);
return p;
}
const Geometry2d::Segment OurRobot::kickerBar() const {
TransformMatrix pose(pos, angle);
const float mouthHalf = Robot_MouthWidth/2.0f;
float x = sin(acos(mouthHalf/Robot_Radius))*Robot_Radius;
Point L(x, Robot_MouthWidth/2.0f);
Point R(x, -Robot_MouthWidth/2.0f);
return Segment(pose*L, pose*R);
}
bool OurRobot::behindBall(const Geometry2d::Point& ballPos) const {
Point ballTransformed = pointInRobotSpace(ballPos);
return ballTransformed.x < -Robot_Radius;
}
void OurRobot::setVScale(float scale) {
cmd.vScale = scale;
}
void OurRobot::setWScale(float scale) {
cmd.wScale = scale;
}
float OurRobot::kickTimer() const {
return (charged()) ? 0.0 : intTimeStampToFloat * (float) (Utils::timestamp() - _lastChargedTime);
}
void OurRobot::update() {
if (charged())
{
_lastChargedTime = Utils::timestamp();
}
}
void OurRobot::spin(MotionCmd::SpinType dir)
{
cmd.spin = dir;
}
bool OurRobot::hasChipper() const
{
return false;
}
void OurRobot::dribble(int8_t speed)
{
radioTx.set_roller(speed);
}
void OurRobot::pivot(Geometry2d::Point ctr, MotionCmd::PivotType dir)
{
cmd.pivotPoint = ctr;
cmd.pivot = dir;
}
void OurRobot::face(Geometry2d::Point pt, bool continuous)
{
cmd.goalOrientation = pt;
cmd.face = continuous ? MotionCmd::Endpoint : MotionCmd::Continuous;
}
void OurRobot::faceNone()
{
cmd.face = MotionCmd::None;
}
void OurRobot::kick(uint8_t strength)
{
willKick = true;
radioTx.set_kick(strength);
radioTx.set_use_chipper(false);
}
void OurRobot::chip(uint8_t strength)
{
willKick = true;
radioTx.set_kick(strength);
radioTx.set_use_chipper(true);
}
void OurRobot::pivot(Geometry2d::Point center, bool cw)
{
cmd.pivotPoint = center;
cmd.pivot = cw ? MotionCmd::CW : MotionCmd::CCW;
}
bool OurRobot::charged() const
{
return radioRx.charged();
}
void OurRobot::approachOpp(Robot * opp, bool value) {
approachOpponent[opp->shell()] = value;
}
<commit_msg>partially fixed problem with robots cutting corners<commit_after>#include <Robot.hpp>
#include <gameplay/planning/bezier.hpp>
#include <framework/Dynamics.hpp>
#include <Utils.hpp>
#include <LogUtils.hpp>
#include <protobuf/LogFrame.pb.h>
#include <stdio.h>
#include <execinfo.h>
#include <stdexcept>
#include <boost/foreach.hpp>
using namespace std;
using namespace Geometry2d;
/** Constant for timestamp to seconds */
const float intTimeStampToFloat = 1000000.0f;
Robot::Robot(unsigned int shell, bool self)
{
_shell = shell;
_self = self;
angle = 0;
angleVel = 0;
}
OurRobot::OurRobot(int shell, SystemState *state):
Robot(shell, true),
_state(state)
{
willKick = false;
avoidBall = false;
exclude = false;
hasBall = false;
cmd_w = 0;
_lastChargedTime = 0;
_dynamics = new Planning::Dynamics(this);
_planner = new Planning::RRT::Planner();
for (size_t i = 0; i < Num_Shells; ++i)
{
approachOpponent[i] = false;
}
_planner->setDynamics(_dynamics);
_planner->maxIterations(250);
radioTx.set_board_id(shell);
for (int m = 0; m < 4; ++m)
{
radioTx.add_motors(0);
}
}
void OurRobot::addText(const QString& text, const QColor& qc)
{
Packet::DebugText *dbg = new Packet::DebugText;
// dbg->set_layer(_state->findDebugLayer(layer));
dbg->set_text(text.toStdString());
dbg->set_color(color(qc));
robotText.push_back(dbg);
}
void OurRobot::setCommandTrace()
{
void *trace[9];
int n = backtrace(trace, sizeof(trace) / sizeof(trace[0]));
// Skip the call into this function
_commandTrace.resize(n - 1);
for (int i = 0; i < n - 1; ++i)
{
_commandTrace[i] = trace[i + 1];
}
}
void OurRobot::resetMotionCommand()
{
robotText.clear();
willKick = false;
avoidBall = false;
radioTx.set_roller(0);
radioTx.set_kick(0);
radioTx.set_use_chipper(false);
for (int i = 0; i < 4; ++i)
{
radioTx.set_motors(i, 0);
}
cmd = MotionCmd();
// Stay in place if possible.
stop();
}
void OurRobot::stop()
{
move(pos);
}
void OurRobot::move(Geometry2d::Point pt, bool stopAtEnd)
{
if (!visible)
{
return;
}
// _state->drawLine(pos, pt);
// create a new path
Planning::Path newPath;
// determine the obstacles
ObstacleGroup& og = obstacles;
// run the RRT planner to generate a new plan
_planner->run(pos, angle, vel, pt, &og, newPath);
_path = newPath;
Geometry2d::Point last = pos;
BOOST_FOREACH(Geometry2d::Point pt, _path.points)
{
_state->drawLine(last, pt);
last = pt;
}
// call the path move command
executeMove(stopAtEnd);
}
void OurRobot::move(const vector<Geometry2d::Point>& path, bool stopAtEnd)
{
_state->drawLine(path.back(), pos);
// copy path from input
_path.clear();
_path.points = path;
// execute
executeMove(stopAtEnd);
}
void OurRobot::bezierMove(const vector<Geometry2d::Point>& controls,
MotionCmd::OrientationType facing,
MotionCmd::PathEndType endpoint) {
// calculate path using simple interpolation
// _path = Planning::createBezierPath(controls);
// execute path
//executeMove(endpoint); // FIXME: handles curves poorly
size_t degree = controls.size();
// generate coefficients
vector<float> coeffs;
for (size_t i=0; i<degree; ++i) {
coeffs.push_back(Planning::binomialCoefficient(degree-1, i));
}
// calculate length to allow for determination of time
double pathLength = Planning::bezierLength(controls, coeffs);
// calculate numerical derivative by stepping ahead a fixed constant
float lookAheadDist = 0.15; // in meters along path
float dt = lookAheadDist/pathLength;
float velGain = 3.0; // FIXME: should be dependent on the length of the curve
// calculate a target velocity for translation
Point targetVel = Planning::evaluateBezierVelocity(dt, controls, coeffs);
// apply gain
targetVel *= velGain;
// create a dummy goal position
cmd.goalPosition = pos + targetVel;
cmd.pathLength = pathLength;
cmd.planner = MotionCmd::Point;
}
void OurRobot::executeMove(bool stopAtEnd)
{
setCommandTrace();
// given a path, determine what the best point to use as a
// target point is, and assign to packet
if (_path.empty()) {
// to avoid crashing if the path is empty, just stop the robot
stop();
return;
}
//dynamics path
float length = _path.length();
// handle direct point commands where the length may be very small
if (fabs(length) < 1e-5) {
length = pos.distTo(_path.points[0]);
}
//target point is the last point on the closest segment
if (_path.points.size() == 1) {
cmd.goalPosition = _path.points[0]; // first point
cmd.pathLength = pos.distTo(cmd.goalPosition);
cmd.planner = MotionCmd::Point;
return;
}
// simple case: one segment, go to end of segment
else if (_path.points.size() == 2)
{
cmd.goalPosition = _path.points[1];
cmd.pathLength = _path.length(0);
cmd.planner = MotionCmd::Point;
return;
}
// pull out relevant points
Point p0 = pos, p1 = _path.points[1], p2 = _path.points[2];
float dist1 = p1.distTo(p1), dist2 = p1.distTo(p2);
// mix the next point between the first and second point
float scale = 1-Utils::clamp(dist1/dist2, 1.0, 0.0);
Geometry2d::Point targetPos = p1 + (p2-p1)*scale;
cmd.goalPosition = targetPos;
cmd.pathLength = pos.distTo(targetPos) + targetPos.distTo(p2) + _path.length(2);
cmd.planner = MotionCmd::Point;
}
void OurRobot::directVelocityCommands(const Geometry2d::Point& trans, double ang)
{
cmd.planner = MotionCmd::DirectVelocity;
cmd.direct_ang_vel = ang;
cmd.direct_trans_vel = trans;
}
void OurRobot::directMotorCommands(const vector<int8_t>& speeds) {
cmd.planner = MotionCmd::DirectMotor;
cmd.direct_motor_cmds = speeds;
}
Geometry2d::Point OurRobot::pointInRobotSpace(const Geometry2d::Point& pt) const {
Point p = pt;
p.rotate(pos, -angle);
return p;
}
const Geometry2d::Segment OurRobot::kickerBar() const {
TransformMatrix pose(pos, angle);
const float mouthHalf = Robot_MouthWidth/2.0f;
float x = sin(acos(mouthHalf/Robot_Radius))*Robot_Radius;
Point L(x, Robot_MouthWidth/2.0f);
Point R(x, -Robot_MouthWidth/2.0f);
return Segment(pose*L, pose*R);
}
bool OurRobot::behindBall(const Geometry2d::Point& ballPos) const {
Point ballTransformed = pointInRobotSpace(ballPos);
return ballTransformed.x < -Robot_Radius;
}
void OurRobot::setVScale(float scale) {
cmd.vScale = scale;
}
void OurRobot::setWScale(float scale) {
cmd.wScale = scale;
}
float OurRobot::kickTimer() const {
return (charged()) ? 0.0 : intTimeStampToFloat * (float) (Utils::timestamp() - _lastChargedTime);
}
void OurRobot::update() {
if (charged())
{
_lastChargedTime = Utils::timestamp();
}
}
void OurRobot::spin(MotionCmd::SpinType dir)
{
cmd.spin = dir;
}
bool OurRobot::hasChipper() const
{
return false;
}
void OurRobot::dribble(int8_t speed)
{
radioTx.set_roller(speed);
}
void OurRobot::pivot(Geometry2d::Point ctr, MotionCmd::PivotType dir)
{
cmd.pivotPoint = ctr;
cmd.pivot = dir;
}
void OurRobot::face(Geometry2d::Point pt, bool continuous)
{
cmd.goalOrientation = pt;
cmd.face = continuous ? MotionCmd::Endpoint : MotionCmd::Continuous;
}
void OurRobot::faceNone()
{
cmd.face = MotionCmd::None;
}
void OurRobot::kick(uint8_t strength)
{
willKick = true;
radioTx.set_kick(strength);
radioTx.set_use_chipper(false);
}
void OurRobot::chip(uint8_t strength)
{
willKick = true;
radioTx.set_kick(strength);
radioTx.set_use_chipper(true);
}
void OurRobot::pivot(Geometry2d::Point center, bool cw)
{
cmd.pivotPoint = center;
cmd.pivot = cw ? MotionCmd::CW : MotionCmd::CCW;
}
bool OurRobot::charged() const
{
return radioRx.charged();
}
void OurRobot::approachOpp(Robot * opp, bool value) {
approachOpponent[opp->shell()] = value;
}
<|endoftext|> |
<commit_before>#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
#include <sstream>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "base64.h"
using namespace std;
using namespace rapidjson;
#define MACHINE_IP inet_addr("127.0.0.1")
vector<string> split(string str, char delimiter) {
vector<string> internal;
stringstream ss(str);
string tok;
while(getline(ss, tok, delimiter)) {
internal.push_back(tok);
}
return internal;
}
int sign(Document* d)
{
const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401";
const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1";
ECDSA_SIG *sig;
char sig_str[B64SIZE];
BN_CTX *ctx;
BIGNUM *a;
EVP_MD_CTX* mdctx;
const EVP_MD* md;
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
EC_KEY* auth_key;
Value si;
auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);
if (auth_key == NULL) {
printf("failed to initialize curve\n");
return 1;
}
ctx = BN_CTX_new();
if(!ctx) {
printf("failed to create bn ctx\n");
return 1;
}
EC_KEY_set_public_key(auth_key,
EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx));
a = BN_new();
BN_hex2bn(&a, private_key);
EC_KEY_set_private_key(auth_key, a);
BN_CTX_free(ctx);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d->Accept(writer);
printf("sig is signing: %s\n", buffer.GetString());
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha256");
if(md == 0) {
printf("Unknown message digest\n");
return 1;
}
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize());
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
printf("digest: ");
dump_mem(md_value, md_len);
sig = ECDSA_do_sign(md_value, md_len, auth_key);
if (sig == NULL) {
printf("Signing failed\n");
return 1;
}
base64encode(sig_str, sig->r, sig->s);
si.SetString(sig_str, B64SIZE, d->GetAllocator());
d->AddMember("si", si, d->GetAllocator());
printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s));
return 0;
}
int get_request(int fd, int choice, const char* port_mode1, const char* port_mode2) {
char* message;
size_t size = TOKENSIZE;
unsigned int offset;
// step 1: read request from client, common for both mode1 and mode2
message = (char*) realloc(NULL, sizeof(char)*size);
if(!message) {
printf("get_request: Failure to realloc\n");
exit(1);
}
offset = 0;
do {
if (offset == size) {
message = (char*) realloc(message, sizeof(char)*(size += 16));
if(!message) {
printf("get_request: Failure to realloc\n");
exit(1);
}
}
if(read(fd, message+offset, 1) <= 0) {
printf("get_request: EOF encountered\n");
char c = message[offset];
message[offset] = '\0';
printf("story so far (%d): %s%c\n", offset, message, c);
exit(1);
}
offset++;
} while (message[offset-1] != '\0');
printf("DEBUG: get_request: message at %p: %s\n", message, message);
// step 2: create token 'd', common for both mode1 and mode2
vector<string> sep = split(message, '\n');
const char * pub_key = sep[0].c_str();
const char * res_add = sep[1].c_str();
cout << "public key (b64): " << pub_key << "\n";
cout << "resource address: " << res_add << "\n";
Document d;
Value ii, nb, na, suv, dev;
unsigned int now;
d.Parse("{}");
now = time(NULL);
ii.SetInt(now);
nb.SetInt(now);
na.SetInt(1600000000);
suv.SetString(pub_key, strlen(pub_key), d.GetAllocator());
dev.SetString(res_add, strlen(res_add), d.GetAllocator());
d.AddMember("id", "fake identifier", d.GetAllocator());
d.AddMember("ii", ii, d.GetAllocator());
d.AddMember("is", "fake issuer", d.GetAllocator());
d.AddMember("su", suv, d.GetAllocator());
d.AddMember("de", dev, d.GetAllocator());
d.AddMember("ar", "fake access rights", d.GetAllocator());
d.AddMember("nb", nb, d.GetAllocator());
d.AddMember("na", na, d.GetAllocator());
sign(&d);
// Step 3: Mode choice dependent
// (Mode 1, return token to client)
if (choice == 1) {
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
cout << "buffer data : " << buffer.GetString();
cout << "\n buffer len:" << buffer.GetSize();
if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {
printf("Failed to write to socket\n");
}
return 1;
}
// (Mode 2, return token to resource, token ID to client)
else if(choice == 2 ){
cout << "Mode 2\n";
int soc2;
uint16_t port = strtol(port_mode2, NULL, 10);
char null_string[17];
soc2 = socket(AF_INET, SOCK_STREAM, 0);
if(soc2 < 0) {
printf("failed to create socket: %s\n", strerror(errno));
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
printf("send token to resource: failed to connect to resource: %s\n", strerror(errno));
}
// insert code for null string here
int i;
// add 17 NULLS before sending the json to resource -- one socket
for (i = 0; i <=17; i++){
null_string[i] = (char) 0;
}
if(write(soc2, null_string, 17) < 0) {
printf("Failed to write null string to resource socket\n");
}
//send token to resource here
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
cout << "buffer data : "<< buffer.GetString() ;
cout << "\n buffer len:" << buffer.GetSize() << "\n";
if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {
printf("Failed to write to token to resource socket\n");
}
//send token ID to client
int tokenID = d["ii"].GetInt();
std::string s_ID = std::to_string(tokenID);
char const *tokenID_str = s_ID.c_str();
cout << "string token ID: " << tokenID_str << "\n";
if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {
printf("Failed to write to socket\n");
}
return 1;
}// end of mode 2
}
int bootstrap_network(const char* port_sub){
int soc;
uint16_t port = strtol(port_sub, NULL, 10); // from arguments
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc == -1) {
printf("Failed to open socket\n");
return 1;
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) {
printf("bootstrap: Failed to bind\n");
exit(1);
}
if(listen(soc, 5) == -1) {
printf( "bootstrap: Failed to listen\n");
exit(1);
}
return soc;
}
int listen_block(int soc){
int fd;
socklen_t peer_addr_size = sizeof(struct sockaddr_in);
struct sockaddr_in retAddress;
printf("DEBUG: entering network loop\n");
while(true) {
printf("DEBUG: network loop: accepting connection...\n");
fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);
if( fd == -1) {
printf("listen: Failed to accept: %s\n", strerror(errno));
exit(1);
}
printf( "DEBUG: network loop: connection accepted, getting request from subject...\n");
return fd;
}
}
int main(int argc, char *argv[]){
if(argc <= 3){
printf("insufficient arguments\n");
printf("sample argument: ./auth <mode> <port_client> <port_resource>\n");
return 1;
}
int fd1, soc1;
soc1 = bootstrap_network(argv[2]);
fd1 = listen_block(soc1);
const char* port_client = argv[2];
const char* port_resource = argv[3];
if(!strcmp(argv[1], "1"))
get_request(fd1,1,port_client,port_resource);
else if(!strcmp(argv[1], "2")){
get_request(fd1,2,port_client,port_resource);
}
else{
printf("Invalid mode: %s", argv[1]);
exit(1);
}
return 1;
}
<commit_msg>updated auth.cpp for multiple connections, testing it now<commit_after>#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
#include <sstream>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "base64.h"
using namespace std;
using namespace rapidjson;
#define MACHINE_IP inet_addr("127.0.0.1")
vector<string> split(string str, char delimiter) {
vector<string> internal;
stringstream ss(str);
string tok;
while(getline(ss, tok, delimiter)) {
internal.push_back(tok);
}
return internal;
}
int sign(Document* d)
{
const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401";
const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1";
ECDSA_SIG *sig;
char sig_str[B64SIZE];
BN_CTX *ctx;
BIGNUM *a;
EVP_MD_CTX* mdctx;
const EVP_MD* md;
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
EC_KEY* auth_key;
Value si;
auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);
if (auth_key == NULL) {
printf("failed to initialize curve\n");
return 1;
}
ctx = BN_CTX_new();
if(!ctx) {
printf("failed to create bn ctx\n");
return 1;
}
EC_KEY_set_public_key(auth_key,
EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx));
a = BN_new();
BN_hex2bn(&a, private_key);
EC_KEY_set_private_key(auth_key, a);
BN_CTX_free(ctx);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d->Accept(writer);
printf("sig is signing: %s\n", buffer.GetString());
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha256");
if(md == 0) {
printf("Unknown message digest\n");
return 1;
}
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize());
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
printf("digest: ");
dump_mem(md_value, md_len);
sig = ECDSA_do_sign(md_value, md_len, auth_key);
if (sig == NULL) {
printf("Signing failed\n");
return 1;
}
base64encode(sig_str, sig->r, sig->s);
si.SetString(sig_str, B64SIZE, d->GetAllocator());
d->AddMember("si", si, d->GetAllocator());
printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s));
return 0;
}
int get_request(int fd, int choice, const char* port_mode1, const char* port_mode2) {
char* message;
size_t size = TOKENSIZE;
unsigned int offset;
// step 1: read request from client, common for both mode1 and mode2
message = (char*) realloc(NULL, sizeof(char)*size);
if(!message) {
printf("get_request: Failure to realloc\n");
exit(1);
}
offset = 0;
do {
if (offset == size) {
message = (char*) realloc(message, sizeof(char)*(size += 16));
if(!message) {
printf("get_request: Failure to realloc\n");
exit(1);
}
}
if(read(fd, message+offset, 1) <= 0) {
printf("get_request: EOF encountered\n");
char c = message[offset];
message[offset] = '\0';
printf("story so far (%d): %s%c\n", offset, message, c);
exit(1);
}
offset++;
} while (message[offset-1] != '\0');
printf("DEBUG: get_request: message at %p: %s\n", message, message);
// step 2: create token 'd', common for both mode1 and mode2
vector<string> sep = split(message, '\n');
const char * pub_key = sep[0].c_str();
const char * res_add = sep[1].c_str();
cout << "public key (b64): " << pub_key << "\n";
cout << "resource address: " << res_add << "\n";
Document d;
Value ii, nb, na, suv, dev;
unsigned int now;
d.Parse("{}");
now = time(NULL);
ii.SetInt(now);
nb.SetInt(now);
na.SetInt(1600000000);
suv.SetString(pub_key, strlen(pub_key), d.GetAllocator());
dev.SetString(res_add, strlen(res_add), d.GetAllocator());
d.AddMember("id", "fake identifier", d.GetAllocator());
d.AddMember("ii", ii, d.GetAllocator());
d.AddMember("is", "fake issuer", d.GetAllocator());
d.AddMember("su", suv, d.GetAllocator());
d.AddMember("de", dev, d.GetAllocator());
d.AddMember("ar", "fake access rights", d.GetAllocator());
d.AddMember("nb", nb, d.GetAllocator());
d.AddMember("na", na, d.GetAllocator());
sign(&d);
// Step 3: Mode choice dependent
// (Mode 1, return token to client)
if (choice == 1) {
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
cout << "buffer data : " << buffer.GetString();
cout << "\n buffer len:" << buffer.GetSize();
if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {
printf("Failed to write to socket\n");
}
// return 1;
}
// (Mode 2, return token to resource, token ID to client)
else if(choice == 2 ){
cout << "Mode 2\n";
int soc2;
uint16_t port = strtol(port_mode2, NULL, 10);
char null_string[17];
soc2 = socket(AF_INET, SOCK_STREAM, 0);
if(soc2 < 0) {
printf("failed to create socket: %s\n", strerror(errno));
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
printf("send token to resource: failed to connect to resource: %s\n", strerror(errno));
}
// insert code for null string here
int i;
// add 17 NULLS before sending the json to resource -- one socket
for (i = 0; i <=17; i++){
null_string[i] = (char) 0;
}
if(write(soc2, null_string, 17) < 0) {
printf("Failed to write null string to resource socket\n");
}
//send token to resource here
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
cout << "buffer data : "<< buffer.GetString() ;
cout << "\n buffer len:" << buffer.GetSize() << "\n";
if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {
printf("Failed to write to token to resource socket\n");
}
//send token ID to client
int tokenID = d["ii"].GetInt();
std::string s_ID = std::to_string(tokenID);
char const *tokenID_str = s_ID.c_str();
cout << "string token ID: " << tokenID_str << "\n";
if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {
printf("Failed to write to socket\n");
}
// return 1;
}// end of mode 2
}
int bootstrap_network(const char* port_sub){
int soc;
uint16_t port = strtol(port_sub, NULL, 10); // from arguments
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc == -1) {
printf("Failed to open socket\n");
return 1;
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) {
printf("bootstrap: Failed to bind\n");
exit(1);
}
if(listen(soc, 5) == -1) {
printf( "bootstrap: Failed to listen\n");
exit(1);
}
return soc;
}
int listen_block(int soc){
int fd;
socklen_t peer_addr_size = sizeof(struct sockaddr_in);
struct sockaddr_in retAddress;
printf("DEBUG: entering network loop\n");
while(true) {
printf("DEBUG: network loop: accepting connection...\n");
fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);
if( fd == -1) {
printf("listen: Failed to accept: %s\n", strerror(errno));
exit(1);
}
printf( "DEBUG: network loop: connection accepted, getting request from subject...\n");
return fd;
}
}
int main(int argc, char *argv[]){
if(argc <= 3){
printf("insufficient arguments\n");
printf("sample argument: ./auth <mode> <port_client> <port_resource>\n");
return 1;
}
int fd1, soc1;
soc1 = bootstrap_network(argv[2]);
fd1 = listen_block(soc1);
const char* port_client = argv[2];
const char* port_resource = argv[3];
if(!strcmp(argv[1], "1"))
get_request(fd1,1,port_client,port_resource);
else if(!strcmp(argv[1], "2")){
get_request(fd1,2,port_client,port_resource);
}
else{
printf("Invalid mode: %s", argv[1]);
exit(1);
}
return 1;
}
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_io.h"
#include "qmgr.h"
#include "condor_qmgr.h"
#include "condor_debug.h"
#include "condor_attributes.h"
#include "condor_classad.h"
#include "my_hostname.h"
#include "my_username.h"
#include "get_daemon_addr.h"
int open_url(char *, int, int);
extern "C" char* get_schedd_addr(const char*, const char*);
extern "C" int strcmp_until(const char *, const char *, const char);
ReliSock *qmgmt_sock = NULL;
static Qmgr_connection connection;
Qmgr_connection *
ConnectQ(char *qmgr_location, int timeout, bool read_only )
{
int rval, fd, cmd, ok, is_local = FALSE;
char tmp_file[255];
#if !defined(WIN32)
struct passwd *pwd;
#endif
char* scheddAddr = get_schedd_addr(0);
char* localScheddAddr = NULL;
if( scheddAddr ) {
localScheddAddr = strdup( scheddAddr );
scheddAddr = NULL;
}
// get the address of the schedd to which we want a connection
if( !qmgr_location || !*qmgr_location ) {
/* No schedd identified --- use local schedd */
scheddAddr = localScheddAddr;
is_local = TRUE;
} else if(qmgr_location[0] != '<') {
/* Get schedd's IP address from collector */
scheddAddr = get_schedd_addr(qmgr_location);
} else {
/* We were passed the sinful string already */
scheddAddr = qmgr_location;
}
// do we already have a connection active?
if( qmgmt_sock ) {
// yes; reject new connection (we can only handle one at a time)
if( localScheddAddr ) free( localScheddAddr );
return( NULL );
}
// no connection active as of now; create a new one
if(scheddAddr) {
qmgmt_sock = new ReliSock();
if ( timeout > 0 && qmgmt_sock ) {
qmgmt_sock->timeout(timeout);
}
ok = qmgmt_sock && qmgmt_sock->connect(scheddAddr, QMGR_PORT);
if( !ok ) {
dprintf(D_ALWAYS, "Can't connect to queue manager\n");
}
} else {
ok = FALSE;
if( qmgr_location ) {
dprintf( D_ALWAYS, "Can't find address of queue manager %s\n",
qmgr_location );
} else {
dprintf( D_ALWAYS, "Can't find address of local queue manager\n" );
}
}
if( !ok ) {
if ( localScheddAddr ) free(localScheddAddr);
if( qmgmt_sock ) delete qmgmt_sock;
qmgmt_sock = NULL;
return 0;
}
/* Figure out if we're trying to connect to a remote queue, in
which case we'll set our username to "nobody" */
if( localScheddAddr ) {
//mju replaced strcmp with new method that strcmp until char (:)
//so that we don't worry about the port number
if( ! is_local && ! strcmp_until(localScheddAddr, scheddAddr, ':' ) ) {
is_local = TRUE;
}
else {
dprintf(D_FULLDEBUG,"ConnectQ failed on check for localScheddAddr\n" );
}
free(localScheddAddr);
}
char *username = my_username();
if ( !username ) {
dprintf(D_FULLDEBUG,"Failure getting my_username()\n", username );
delete qmgmt_sock;
qmgmt_sock = NULL;
return( 0 );
}
dprintf(D_FULLDEBUG,"Connecting to queue as user \"%s\"\n", username );
/* Get the schedd to handle Q ops. */
qmgmt_sock->encode();
cmd = QMGMT_CMD;
qmgmt_sock->code(cmd);
if ( read_only ) {
rval = InitializeReadOnlyConnection( username );
} else {
rval = InitializeConnection( username );
}
free( username );
if (rval < 0) {
delete qmgmt_sock;
qmgmt_sock = NULL;
return 0;
}
if ( !read_only ) {
qmgmt_sock->authenticate();
}
return &connection;
}
bool
DisconnectQ(Qmgr_connection *conn)
{
int rval;
if (conn == 0) {
conn = &connection;
}
rval = CloseConnection();
delete qmgmt_sock;
qmgmt_sock = NULL;
return( rval >= 0 );
}
void
FreeJobAd(ClassAd *&ad)
{
delete ad;
ad = NULL;
}
int
SendSpoolFileBytes(char *filename)
{
qmgmt_sock->encode();
if (qmgmt_sock->put_file(filename) < 0) {
return -1;
}
return 0;
}
void
WalkJobQueue(scan_func func)
{
ClassAd *ad;
int rval = 0;
ad = GetNextJob(1);
while (ad != NULL && rval >= 0) {
rval = func(ad);
if (rval >= 0) {
FreeJobAd(ad);
ad = GetNextJob(0);
}
}
if (ad != NULL)
FreeJobAd(ad);
}
int
rusage_to_float(struct rusage ru, float *utime, float *stime )
{
float rval;
if ( utime )
*utime = (float) ru.ru_utime.tv_sec;
if ( stime )
*stime = (float) ru.ru_stime.tv_sec;
return 0;
}
int
float_to_rusage(float utime, float stime, struct rusage *ru)
{
ru->ru_utime.tv_sec = (time_t)utime;
ru->ru_stime.tv_sec = (time_t)stime;
ru->ru_utime.tv_usec = 0;
ru->ru_stime.tv_usec = 0;
return 0;
}
#if !defined(WIN32)
int
GetProc(int cl, int pr, PROC *p)
{
int disconn_when_done = 0;
char buf[ATTRLIST_MAX_EXPRESSION];
float utime,stime;
char *s;
if (!qmgmt_sock) {
disconn_when_done = 1;
if( !ConnectQ(0) ) {
return -1;
}
}
p->version_num = 3;
p->id.cluster = cl;
p->id.proc = pr;
GetAttributeInt(cl, pr, ATTR_JOB_UNIVERSE, &(p->universe));
GetAttributeInt(cl, pr, ATTR_WANT_CHECKPOINT, &(p->checkpoint));
GetAttributeInt(cl, pr, ATTR_WANT_REMOTE_SYSCALLS, &(p->remote_syscalls));
GetAttributeString(cl, pr, ATTR_OWNER, buf);
p->owner = strdup(buf);
GetAttributeInt(cl, pr, ATTR_Q_DATE, &(p->q_date));
GetAttributeInt(cl, pr, ATTR_COMPLETION_DATE, &(p->completion_date));
GetAttributeInt(cl, pr, ATTR_JOB_STATUS, &(p->status));
GetAttributeInt(cl, pr, ATTR_JOB_PRIO, &(p->prio));
GetAttributeInt(cl, pr, ATTR_JOB_NOTIFICATION, &(p->notification));
GetAttributeInt(cl, pr, ATTR_IMAGE_SIZE, &(p->image_size));
GetAttributeString(cl, pr, ATTR_JOB_ENVIRONMENT, buf);
p->env = strdup(buf);
p->n_cmds = 1;
p->cmd = (char **) malloc(p->n_cmds * sizeof(char *));
p->args = (char **) malloc(p->n_cmds * sizeof(char *));
p->in = (char **) malloc(p->n_cmds * sizeof(char *));
p->out = (char **) malloc(p->n_cmds * sizeof(char *));
p->err = (char **) malloc(p->n_cmds * sizeof(char *));
p->exit_status = (int *) malloc(p->n_cmds * sizeof(int));
GetAttributeString(cl, pr, ATTR_JOB_CMD, buf);
p->cmd[0] = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_ARGUMENTS, buf);
p->args[0] = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_INPUT, buf);
p->in[0] = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_OUTPUT, buf);
p->out[0] = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_ERROR, buf);
p->err[0] = strdup(buf);
GetAttributeInt(cl, pr, ATTR_JOB_EXIT_STATUS, &(p->exit_status[0]));
GetAttributeInt(cl, pr, ATTR_MIN_HOSTS, &(p->min_needed));
GetAttributeInt(cl, pr, ATTR_MAX_HOSTS, &(p->max_needed));
GetAttributeString(cl, pr, ATTR_JOB_ROOT_DIR, buf);
p->rootdir = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_IWD, buf);
p->iwd = strdup(buf);
GetAttributeExpr(cl, pr, ATTR_REQUIREMENTS, buf);
s = strchr(buf, '=');
if (s) {
s++;
p->requirements = strdup(s);
}
else {
p->requirements = strdup(buf);
}
GetAttributeExpr(cl, pr, ATTR_PREFERENCES, buf);
s = strchr(buf, '=');
if (s) {
s++;
p->preferences = strdup(s);
}
else {
p->preferences = strdup(buf);
}
GetAttributeFloat(cl, pr, ATTR_JOB_LOCAL_USER_CPU, &utime);
GetAttributeFloat(cl, pr, ATTR_JOB_LOCAL_SYS_CPU, &stime);
float_to_rusage(utime, stime, &(p->local_usage));
p->remote_usage = (struct rusage *) malloc(p->n_cmds *
sizeof(struct rusage));
memset(p->remote_usage, 0, sizeof( struct rusage ));
GetAttributeFloat(cl, pr, ATTR_JOB_REMOTE_USER_CPU, &utime);
GetAttributeFloat(cl, pr, ATTR_JOB_REMOTE_SYS_CPU, &stime);
float_to_rusage(utime, stime, &(p->remote_usage[0]));
if (disconn_when_done) {
DisconnectQ(&connection);
}
return 0;
}
#endif
<commit_msg>Recognize if the socket to the schedd has already been blown away when doing a DisconnectQ(). If so, don't do a CloseConnection(). (Otherwise, this will cause a segfault.)<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_io.h"
#include "qmgr.h"
#include "condor_qmgr.h"
#include "condor_debug.h"
#include "condor_attributes.h"
#include "condor_classad.h"
#include "my_hostname.h"
#include "my_username.h"
#include "get_daemon_addr.h"
int open_url(char *, int, int);
extern "C" char* get_schedd_addr(const char*, const char*);
extern "C" int strcmp_until(const char *, const char *, const char);
ReliSock *qmgmt_sock = NULL;
static Qmgr_connection connection;
Qmgr_connection *
ConnectQ(char *qmgr_location, int timeout, bool read_only )
{
int rval, fd, cmd, ok, is_local = FALSE;
char tmp_file[255];
#if !defined(WIN32)
struct passwd *pwd;
#endif
char* scheddAddr = get_schedd_addr(0);
char* localScheddAddr = NULL;
if( scheddAddr ) {
localScheddAddr = strdup( scheddAddr );
scheddAddr = NULL;
}
// get the address of the schedd to which we want a connection
if( !qmgr_location || !*qmgr_location ) {
/* No schedd identified --- use local schedd */
scheddAddr = localScheddAddr;
is_local = TRUE;
} else if(qmgr_location[0] != '<') {
/* Get schedd's IP address from collector */
scheddAddr = get_schedd_addr(qmgr_location);
} else {
/* We were passed the sinful string already */
scheddAddr = qmgr_location;
}
// do we already have a connection active?
if( qmgmt_sock ) {
// yes; reject new connection (we can only handle one at a time)
if( localScheddAddr ) free( localScheddAddr );
return( NULL );
}
// no connection active as of now; create a new one
if(scheddAddr) {
qmgmt_sock = new ReliSock();
if ( timeout > 0 && qmgmt_sock ) {
qmgmt_sock->timeout(timeout);
}
ok = qmgmt_sock && qmgmt_sock->connect(scheddAddr, QMGR_PORT);
if( !ok ) {
dprintf(D_ALWAYS, "Can't connect to queue manager\n");
}
} else {
ok = FALSE;
if( qmgr_location ) {
dprintf( D_ALWAYS, "Can't find address of queue manager %s\n",
qmgr_location );
} else {
dprintf( D_ALWAYS, "Can't find address of local queue manager\n" );
}
}
if( !ok ) {
if ( localScheddAddr ) free(localScheddAddr);
if( qmgmt_sock ) delete qmgmt_sock;
qmgmt_sock = NULL;
return 0;
}
/* Figure out if we're trying to connect to a remote queue, in
which case we'll set our username to "nobody" */
if( localScheddAddr ) {
//mju replaced strcmp with new method that strcmp until char (:)
//so that we don't worry about the port number
if( ! is_local && ! strcmp_until(localScheddAddr, scheddAddr, ':' ) ) {
is_local = TRUE;
}
else {
dprintf(D_FULLDEBUG,"ConnectQ failed on check for localScheddAddr\n" );
}
free(localScheddAddr);
}
char *username = my_username();
if ( !username ) {
dprintf(D_FULLDEBUG,"Failure getting my_username()\n", username );
delete qmgmt_sock;
qmgmt_sock = NULL;
return( 0 );
}
dprintf(D_FULLDEBUG,"Connecting to queue as user \"%s\"\n", username );
/* Get the schedd to handle Q ops. */
qmgmt_sock->encode();
cmd = QMGMT_CMD;
qmgmt_sock->code(cmd);
if ( read_only ) {
rval = InitializeReadOnlyConnection( username );
} else {
rval = InitializeConnection( username );
}
free( username );
if (rval < 0) {
delete qmgmt_sock;
qmgmt_sock = NULL;
return 0;
}
if ( !read_only ) {
qmgmt_sock->authenticate();
}
return &connection;
}
// we can ignore the parameter because there is only one connection
bool
DisconnectQ(Qmgr_connection *)
{
int rval;
if( !qmgmt_sock ) return( false );
rval = CloseConnection();
delete qmgmt_sock;
qmgmt_sock = NULL;
return( rval >= 0 );
}
void
FreeJobAd(ClassAd *&ad)
{
delete ad;
ad = NULL;
}
int
SendSpoolFileBytes(char *filename)
{
qmgmt_sock->encode();
if (qmgmt_sock->put_file(filename) < 0) {
return -1;
}
return 0;
}
void
WalkJobQueue(scan_func func)
{
ClassAd *ad;
int rval = 0;
ad = GetNextJob(1);
while (ad != NULL && rval >= 0) {
rval = func(ad);
if (rval >= 0) {
FreeJobAd(ad);
ad = GetNextJob(0);
}
}
if (ad != NULL)
FreeJobAd(ad);
}
int
rusage_to_float(struct rusage ru, float *utime, float *stime )
{
float rval;
if ( utime )
*utime = (float) ru.ru_utime.tv_sec;
if ( stime )
*stime = (float) ru.ru_stime.tv_sec;
return 0;
}
int
float_to_rusage(float utime, float stime, struct rusage *ru)
{
ru->ru_utime.tv_sec = (time_t)utime;
ru->ru_stime.tv_sec = (time_t)stime;
ru->ru_utime.tv_usec = 0;
ru->ru_stime.tv_usec = 0;
return 0;
}
#if !defined(WIN32)
int
GetProc(int cl, int pr, PROC *p)
{
int disconn_when_done = 0;
char buf[ATTRLIST_MAX_EXPRESSION];
float utime,stime;
char *s;
if (!qmgmt_sock) {
disconn_when_done = 1;
if( !ConnectQ(0) ) {
return -1;
}
}
p->version_num = 3;
p->id.cluster = cl;
p->id.proc = pr;
GetAttributeInt(cl, pr, ATTR_JOB_UNIVERSE, &(p->universe));
GetAttributeInt(cl, pr, ATTR_WANT_CHECKPOINT, &(p->checkpoint));
GetAttributeInt(cl, pr, ATTR_WANT_REMOTE_SYSCALLS, &(p->remote_syscalls));
GetAttributeString(cl, pr, ATTR_OWNER, buf);
p->owner = strdup(buf);
GetAttributeInt(cl, pr, ATTR_Q_DATE, &(p->q_date));
GetAttributeInt(cl, pr, ATTR_COMPLETION_DATE, &(p->completion_date));
GetAttributeInt(cl, pr, ATTR_JOB_STATUS, &(p->status));
GetAttributeInt(cl, pr, ATTR_JOB_PRIO, &(p->prio));
GetAttributeInt(cl, pr, ATTR_JOB_NOTIFICATION, &(p->notification));
GetAttributeInt(cl, pr, ATTR_IMAGE_SIZE, &(p->image_size));
GetAttributeString(cl, pr, ATTR_JOB_ENVIRONMENT, buf);
p->env = strdup(buf);
p->n_cmds = 1;
p->cmd = (char **) malloc(p->n_cmds * sizeof(char *));
p->args = (char **) malloc(p->n_cmds * sizeof(char *));
p->in = (char **) malloc(p->n_cmds * sizeof(char *));
p->out = (char **) malloc(p->n_cmds * sizeof(char *));
p->err = (char **) malloc(p->n_cmds * sizeof(char *));
p->exit_status = (int *) malloc(p->n_cmds * sizeof(int));
GetAttributeString(cl, pr, ATTR_JOB_CMD, buf);
p->cmd[0] = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_ARGUMENTS, buf);
p->args[0] = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_INPUT, buf);
p->in[0] = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_OUTPUT, buf);
p->out[0] = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_ERROR, buf);
p->err[0] = strdup(buf);
GetAttributeInt(cl, pr, ATTR_JOB_EXIT_STATUS, &(p->exit_status[0]));
GetAttributeInt(cl, pr, ATTR_MIN_HOSTS, &(p->min_needed));
GetAttributeInt(cl, pr, ATTR_MAX_HOSTS, &(p->max_needed));
GetAttributeString(cl, pr, ATTR_JOB_ROOT_DIR, buf);
p->rootdir = strdup(buf);
GetAttributeString(cl, pr, ATTR_JOB_IWD, buf);
p->iwd = strdup(buf);
GetAttributeExpr(cl, pr, ATTR_REQUIREMENTS, buf);
s = strchr(buf, '=');
if (s) {
s++;
p->requirements = strdup(s);
}
else {
p->requirements = strdup(buf);
}
GetAttributeExpr(cl, pr, ATTR_PREFERENCES, buf);
s = strchr(buf, '=');
if (s) {
s++;
p->preferences = strdup(s);
}
else {
p->preferences = strdup(buf);
}
GetAttributeFloat(cl, pr, ATTR_JOB_LOCAL_USER_CPU, &utime);
GetAttributeFloat(cl, pr, ATTR_JOB_LOCAL_SYS_CPU, &stime);
float_to_rusage(utime, stime, &(p->local_usage));
p->remote_usage = (struct rusage *) malloc(p->n_cmds *
sizeof(struct rusage));
memset(p->remote_usage, 0, sizeof( struct rusage ));
GetAttributeFloat(cl, pr, ATTR_JOB_REMOTE_USER_CPU, &utime);
GetAttributeFloat(cl, pr, ATTR_JOB_REMOTE_SYS_CPU, &stime);
float_to_rusage(utime, stime, &(p->remote_usage[0]));
if (disconn_when_done) {
DisconnectQ(&connection);
}
return 0;
}
#endif
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_classad.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "user_proc.h"
#include "script_proc.h"
#include "starter.h"
#include "condor_daemon_core.h"
#include "condor_attributes.h"
#include "exit.h"
#include "condor_uid.h"
extern CStarter *Starter;
/* ScriptProc class implementation */
ScriptProc::ScriptProc( ClassAd* ad, const char* proc_name )
{
dprintf ( D_FULLDEBUG, "In ScriptProc::ScriptProc()\n" );
if( proc_name ) {
name = strdup( proc_name );
} else {
EXCEPT( "Can't instantiate a ScriptProc without a name!" );
}
JobAd = ad;
is_suspended = false;
UserProc::initialize();
}
ScriptProc::~ScriptProc()
{
// Nothing special yet...
}
int
ScriptProc::StartJob()
{
dprintf(D_FULLDEBUG,"in ScriptProc::StartJob()\n");
if ( !JobAd ) {
dprintf ( D_ALWAYS, "No JobAd in ScriptProc::StartJob()!\n" );
return 0;
}
MyString attr;
attr = name;
attr += ATTR_JOB_CMD;
char* tmp = NULL;
if( ! JobAd->LookupString( attr.Value(), &tmp ) ) {
dprintf( D_ALWAYS, "%s not found in JobAd. Aborting StartJob.\n",
attr.Value() );
return 0;
}
// // // // // //
// executable
// // // // // //
// TODO: make it smart in cases we're not the gridshell and/or
// didn't transfer files so that we don't prepend the wrong
// path to the binary, and don't try to chmod it.
MyString exe_path = Starter->GetWorkingDir();
exe_path += DIR_DELIM_CHAR;
exe_path += tmp;
free( tmp );
tmp = NULL;
if( Starter->isGridshell() ) {
// if we're a gridshell, chmod() the binary, since globus
// probably transfered it for us and left it with bad
// permissions...
priv_state old_priv = set_user_priv();
int retval = chmod( exe_path.Value(), 0755 );
set_priv( old_priv );
if( retval < 0 ) {
dprintf( D_ALWAYS, "Failed to chmod %s: %s (errno %d)\n",
exe_path.Value(), strerror(errno), errno );
return 0;
}
}
// // // // // //
// Args
// // // // // //
char *args1 = NULL;
char *args2 = NULL;
MyString args1_attr;
MyString args2_attr;
args1_attr = name;
args1_attr += ATTR_JOB_ARGUMENTS1;
args2_attr = name;
args2_attr += ATTR_JOB_ARGUMENTS2;
JobAd->LookupString(args1_attr.Value(), &args1);
JobAd->LookupString(args2_attr.Value(), &args2);
ArgList args;
// Since we are adding to the argument list, we may need to deal
// with platform-specific arg syntax in the user's args in order
// to successfully merge them with the additional args.
args.SetArgV1SyntaxToCurrentPlatform();
// First, put "condor_<name>script" at the front of Args,
// since that will become argv[0] of what we exec(), either
// the wrapper or the actual job.
MyString arg0;
arg0 = "condor_";
arg0 += name;
arg0 += "script";
args.AppendArg(arg0.Value());
MyString args_error;
if(args2 && *args2) {
args.AppendArgsV2Raw(args2,&args_error);
}
else if(args1 && *args1) {
args.AppendArgsV1Raw(args1,&args_error);
}
else {
dprintf( D_FULLDEBUG, "neither %s nor %s could be found in JobAd\n",
args1_attr.Value(), args2_attr.Value());
}
free( args1 );
free( args2 );
// // // // // //
// Environment
// // // // // //
char *env1 = NULL;
char *env2 = NULL;
MyString env1_attr;
MyString env2_attr;
env1_attr = name;
env1_attr += ATTR_JOB_ENVIRONMENT1;
env2_attr = name;
env2_attr += ATTR_JOB_ENVIRONMENT2;
JobAd->LookupString( env1_attr.Value(), &env1 );
JobAd->LookupString( env2_attr.Value(), &env2 );
// TODO do we want to use the regular ATTR_JOB_ENVIRONMENT
// if there's nothing specific for this script?
// Now, instantiate an Env object so we can manipulate the
// environment as needed.
Env job_env;
MyString env_errors;
if( env2 && *env2 ) {
if( ! job_env.MergeFromV2Raw(env2,&env_errors) ) {
dprintf( D_ALWAYS, "Invalid %s found in JobAd (%s). "
"Aborting ScriptProc::StartJob.\n",
env2_attr.Value(),env_errors.Value() );
free( env1 );
free( env2 );
return 0;
}
}
else if( env1 && *env1 ) {
if( ! job_env.MergeFromV1Raw(env1,&env_errors) ) {
dprintf( D_ALWAYS, "Invalid %s found in JobAd (%s). "
"Aborting ScriptProc::StartJob.\n",
env1_attr.Value(),env_errors.Value() );
free( env1 );
free( env2 );
return 0;
}
}
free(env1);
free(env2);
// Now, let the starter publish any env vars it wants to add
Starter->PublishToEnv( &job_env );
// TODO: Deal with port regulation stuff?
// Grab the full environment back out of the Env object
if(IsFulldebug(D_FULLDEBUG)) {
MyString env_str;
job_env.getDelimitedStringForDisplay(&env_str);
dprintf(D_FULLDEBUG, "%sEnv = %s\n", name, env_str.Value() );
}
// // // // // //
// Standard Files
// // // // // //
// TODO???
// // // // // //
// Misc + Exec
// // // // // //
// TODO?
// Starter->jic->notifyJobPreSpawn( name );
// compute job's renice value by evaluating the machine's
// JOB_RENICE_INCREMENT in the context of the job ad...
// TODO?
int nice_inc = 10;
// in the below dprintfs, we want to skip past argv[0], which
// is sometimes condor_exec, in the Args string.
MyString args_string;
args.GetArgsStringForDisplay(&args_string,1);
dprintf( D_ALWAYS, "About to exec %s script: %s %s\n",
name, exe_path.Value(),
args_string.Value() );
// If there is a requested coresize for this job, enforce it.
// It is truncated because you can't put an unsigned integer
// into a classad. I could rewrite condor's use of ATTR_CORE_SIZE to
// be a float, but then when that attribute is read/written to the
// job queue log by/or shared between versions of Condor which view the
// type of that attribute differently, calamity would arise.
int core_size_truncated;
size_t core_size;
size_t *core_size_ptr = NULL;
if ( JobAd->LookupInteger(ATTR_CORE_SIZE, core_size_truncated) ) {
core_size = (size_t)core_size_truncated;
core_size_ptr = &core_size;
}
JobPid = daemonCore->Create_Process(exe_path.Value(),
args,
PRIV_USER_FINAL,
1,
FALSE,
FALSE,
&job_env,
Starter->jic->jobIWD(),
NULL,
NULL,
NULL,
NULL,
nice_inc,
NULL,
DCJOBOPT_NO_ENV_INHERIT,
core_size_ptr );
//NOTE: Create_Process() saves the errno for us if it is an
//"interesting" error.
char const *create_process_error = NULL;
int create_process_errno = errno;
if( JobPid == FALSE && errno ) {
create_process_error = strerror( errno );
}
if( JobPid == FALSE ) {
JobPid = -1;
if( create_process_error ) {
MyString err_msg = "Failed to execute '";
err_msg += exe_path.Value();
err_msg += "'";
if(!args_string.IsEmpty()) {
err_msg += " with arguments ";
err_msg += args_string.Value();
}
err_msg += ": ";
err_msg += create_process_error;
Starter->jic->notifyStarterError( err_msg.Value(), true, CONDOR_HOLD_CODE_FailedToCreateProcess, create_process_errno );
}
EXCEPT( "Create_Process(%s,%s, ...) failed",
exe_path.Value(), args_string.Value() );
return 0;
}
dprintf( D_ALWAYS, "Create_Process succeeded, pid=%d\n", JobPid );
condor_gettimestamp( job_start_time );
return 1;
}
bool
ScriptProc::JobExit( void )
{
dprintf( D_FULLDEBUG, "Inside ScriptProc::JobExit()\n" );
return true;
}
bool
ScriptProc::PublishUpdateAd( ClassAd* ad )
{
dprintf( D_FULLDEBUG, "Inside ScriptProc::PublishUpdateAd()\n" );
// TODO: anything interesting or specific in here?
return UserProc::PublishUpdateAd( ad );
}
void
ScriptProc::Suspend()
{
daemonCore->Send_Signal(JobPid, SIGSTOP);
is_suspended = true;
}
void
ScriptProc::Continue()
{
daemonCore->Send_Signal(JobPid, SIGCONT);
is_suspended = false;
}
bool
ScriptProc::ShutdownGraceful()
{
if ( is_suspended ) {
Continue();
}
requested_exit = true;
daemonCore->Send_Signal(JobPid, soft_kill_sig);
return false; // return false says shutdown is pending
}
bool
ScriptProc::ShutdownFast()
{
// We purposely do not do a SIGCONT here, since there is no sense
// in potentially swapping the job back into memory if our next
// step is to hard kill it.
requested_exit = true;
daemonCore->Send_Signal(JobPid, SIGKILL);
return false; // return false says shutdown is pending
}
bool
ScriptProc::Remove()
{
if ( is_suspended ) {
Continue();
}
requested_exit = true;
daemonCore->Send_Signal(JobPid, rm_kill_sig);
return false; // return false says shutdown is pending
}
bool
ScriptProc::Hold()
{
if ( is_suspended ) {
Continue();
}
requested_exit = true;
daemonCore->Send_Signal(JobPid, hold_kill_sig);
return false; // return false says shutdown is pending
}
<commit_msg>PreCmd and PostCmd now check + work correctly with absolute paths (#7770)<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_classad.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "user_proc.h"
#include "script_proc.h"
#include "starter.h"
#include "condor_daemon_core.h"
#include "condor_attributes.h"
#include "exit.h"
#include "condor_uid.h"
extern CStarter *Starter;
/* ScriptProc class implementation */
ScriptProc::ScriptProc( ClassAd* ad, const char* proc_name )
{
dprintf ( D_FULLDEBUG, "In ScriptProc::ScriptProc()\n" );
if( proc_name ) {
name = strdup( proc_name );
} else {
EXCEPT( "Can't instantiate a ScriptProc without a name!" );
}
JobAd = ad;
is_suspended = false;
UserProc::initialize();
}
ScriptProc::~ScriptProc()
{
// Nothing special yet...
}
int
ScriptProc::StartJob()
{
dprintf(D_FULLDEBUG,"in ScriptProc::StartJob()\n");
if ( !JobAd ) {
dprintf ( D_ALWAYS, "No JobAd in ScriptProc::StartJob()!\n" );
return 0;
}
MyString attr;
attr = name;
attr += ATTR_JOB_CMD;
char* tmp = NULL;
if( ! JobAd->LookupString( attr.Value(), &tmp ) ) {
dprintf( D_ALWAYS, "%s not found in JobAd. Aborting StartJob.\n",
attr.Value() );
return 0;
}
// // // // // //
// executable
// // // // // //
// TODO: make it smart in cases we're not the gridshell and/or
// didn't transfer files so that we don't prepend the wrong
// path to the binary, and don't try to chmod it.
MyString exe_path = "";
if( tmp != NULL && tmp[0] != DIR_DELIM_CHAR ) {
exe_path += Starter->GetWorkingDir();
exe_path += DIR_DELIM_CHAR;
}
exe_path += tmp;
free( tmp );
tmp = NULL;
if( Starter->isGridshell() ) {
// if we're a gridshell, chmod() the binary, since globus
// probably transfered it for us and left it with bad
// permissions...
priv_state old_priv = set_user_priv();
int retval = chmod( exe_path.Value(), 0755 );
set_priv( old_priv );
if( retval < 0 ) {
dprintf( D_ALWAYS, "Failed to chmod %s: %s (errno %d)\n",
exe_path.Value(), strerror(errno), errno );
return 0;
}
}
// // // // // //
// Args
// // // // // //
char *args1 = NULL;
char *args2 = NULL;
MyString args1_attr;
MyString args2_attr;
args1_attr = name;
args1_attr += ATTR_JOB_ARGUMENTS1;
args2_attr = name;
args2_attr += ATTR_JOB_ARGUMENTS2;
JobAd->LookupString(args1_attr.Value(), &args1);
JobAd->LookupString(args2_attr.Value(), &args2);
ArgList args;
// Since we are adding to the argument list, we may need to deal
// with platform-specific arg syntax in the user's args in order
// to successfully merge them with the additional args.
args.SetArgV1SyntaxToCurrentPlatform();
// First, put "condor_<name>script" at the front of Args,
// since that will become argv[0] of what we exec(), either
// the wrapper or the actual job.
MyString arg0;
arg0 = "condor_";
arg0 += name;
arg0 += "script";
args.AppendArg(arg0.Value());
MyString args_error;
if(args2 && *args2) {
args.AppendArgsV2Raw(args2,&args_error);
}
else if(args1 && *args1) {
args.AppendArgsV1Raw(args1,&args_error);
}
else {
dprintf( D_FULLDEBUG, "neither %s nor %s could be found in JobAd\n",
args1_attr.Value(), args2_attr.Value());
}
free( args1 );
free( args2 );
// // // // // //
// Environment
// // // // // //
char *env1 = NULL;
char *env2 = NULL;
MyString env1_attr;
MyString env2_attr;
env1_attr = name;
env1_attr += ATTR_JOB_ENVIRONMENT1;
env2_attr = name;
env2_attr += ATTR_JOB_ENVIRONMENT2;
JobAd->LookupString( env1_attr.Value(), &env1 );
JobAd->LookupString( env2_attr.Value(), &env2 );
// TODO do we want to use the regular ATTR_JOB_ENVIRONMENT
// if there's nothing specific for this script?
// Now, instantiate an Env object so we can manipulate the
// environment as needed.
Env job_env;
MyString env_errors;
if( env2 && *env2 ) {
if( ! job_env.MergeFromV2Raw(env2,&env_errors) ) {
dprintf( D_ALWAYS, "Invalid %s found in JobAd (%s). "
"Aborting ScriptProc::StartJob.\n",
env2_attr.Value(),env_errors.Value() );
free( env1 );
free( env2 );
return 0;
}
}
else if( env1 && *env1 ) {
if( ! job_env.MergeFromV1Raw(env1,&env_errors) ) {
dprintf( D_ALWAYS, "Invalid %s found in JobAd (%s). "
"Aborting ScriptProc::StartJob.\n",
env1_attr.Value(),env_errors.Value() );
free( env1 );
free( env2 );
return 0;
}
}
free(env1);
free(env2);
// Now, let the starter publish any env vars it wants to add
Starter->PublishToEnv( &job_env );
// TODO: Deal with port regulation stuff?
// Grab the full environment back out of the Env object
if(IsFulldebug(D_FULLDEBUG)) {
MyString env_str;
job_env.getDelimitedStringForDisplay(&env_str);
dprintf(D_FULLDEBUG, "%sEnv = %s\n", name, env_str.Value() );
}
// // // // // //
// Standard Files
// // // // // //
// TODO???
// // // // // //
// Misc + Exec
// // // // // //
// TODO?
// Starter->jic->notifyJobPreSpawn( name );
// compute job's renice value by evaluating the machine's
// JOB_RENICE_INCREMENT in the context of the job ad...
// TODO?
int nice_inc = 10;
// in the below dprintfs, we want to skip past argv[0], which
// is sometimes condor_exec, in the Args string.
MyString args_string;
args.GetArgsStringForDisplay(&args_string,1);
dprintf( D_ALWAYS, "About to exec %s script: %s %s\n",
name, exe_path.Value(),
args_string.Value() );
// If there is a requested coresize for this job, enforce it.
// It is truncated because you can't put an unsigned integer
// into a classad. I could rewrite condor's use of ATTR_CORE_SIZE to
// be a float, but then when that attribute is read/written to the
// job queue log by/or shared between versions of Condor which view the
// type of that attribute differently, calamity would arise.
int core_size_truncated;
size_t core_size;
size_t *core_size_ptr = NULL;
if ( JobAd->LookupInteger(ATTR_CORE_SIZE, core_size_truncated) ) {
core_size = (size_t)core_size_truncated;
core_size_ptr = &core_size;
}
JobPid = daemonCore->Create_Process(exe_path.Value(),
args,
PRIV_USER_FINAL,
1,
FALSE,
FALSE,
&job_env,
Starter->jic->jobIWD(),
NULL,
NULL,
NULL,
NULL,
nice_inc,
NULL,
DCJOBOPT_NO_ENV_INHERIT,
core_size_ptr );
//NOTE: Create_Process() saves the errno for us if it is an
//"interesting" error.
char const *create_process_error = NULL;
int create_process_errno = errno;
if( JobPid == FALSE && errno ) {
create_process_error = strerror( errno );
}
if( JobPid == FALSE ) {
JobPid = -1;
if( create_process_error ) {
MyString err_msg = "Failed to execute '";
err_msg += exe_path.Value();
err_msg += "'";
if(!args_string.IsEmpty()) {
err_msg += " with arguments ";
err_msg += args_string.Value();
}
err_msg += ": ";
err_msg += create_process_error;
Starter->jic->notifyStarterError( err_msg.Value(), true, CONDOR_HOLD_CODE_FailedToCreateProcess, create_process_errno );
}
EXCEPT( "Create_Process(%s,%s, ...) failed",
exe_path.Value(), args_string.Value() );
return 0;
}
dprintf( D_ALWAYS, "Create_Process succeeded, pid=%d\n", JobPid );
condor_gettimestamp( job_start_time );
return 1;
}
bool
ScriptProc::JobExit( void )
{
dprintf( D_FULLDEBUG, "Inside ScriptProc::JobExit()\n" );
return true;
}
bool
ScriptProc::PublishUpdateAd( ClassAd* ad )
{
dprintf( D_FULLDEBUG, "Inside ScriptProc::PublishUpdateAd()\n" );
// TODO: anything interesting or specific in here?
return UserProc::PublishUpdateAd( ad );
}
void
ScriptProc::Suspend()
{
daemonCore->Send_Signal(JobPid, SIGSTOP);
is_suspended = true;
}
void
ScriptProc::Continue()
{
daemonCore->Send_Signal(JobPid, SIGCONT);
is_suspended = false;
}
bool
ScriptProc::ShutdownGraceful()
{
if ( is_suspended ) {
Continue();
}
requested_exit = true;
daemonCore->Send_Signal(JobPid, soft_kill_sig);
return false; // return false says shutdown is pending
}
bool
ScriptProc::ShutdownFast()
{
// We purposely do not do a SIGCONT here, since there is no sense
// in potentially swapping the job back into memory if our next
// step is to hard kill it.
requested_exit = true;
daemonCore->Send_Signal(JobPid, SIGKILL);
return false; // return false says shutdown is pending
}
bool
ScriptProc::Remove()
{
if ( is_suspended ) {
Continue();
}
requested_exit = true;
daemonCore->Send_Signal(JobPid, rm_kill_sig);
return false; // return false says shutdown is pending
}
bool
ScriptProc::Hold()
{
if ( is_suspended ) {
Continue();
}
requested_exit = true;
daemonCore->Send_Signal(JobPid, hold_kill_sig);
return false; // return false says shutdown is pending
}
<|endoftext|> |
<commit_before>#pragma once
// https://infektor.net/posts/2017-03-31-range-based-enumerate.html
#include <iterator>
#include <utility>
// ----------------------------------------------------------------------
namespace acmacs
{
namespace _enumerate_internal
{
template <typename Iterator, typename index_type> struct enumerate_iterator
{
using iterator = Iterator;
//using index_type = typename std::iterator_traits<iterator>::difference_type;
using reference = typename std::iterator_traits<iterator>::reference;
enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
enumerate_iterator& operator++() { ++index; ++iter; return *this; }
bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
std::pair<index_type, reference> operator*() { return {index, *iter}; }
private:
index_type index;
iterator iter;
};
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> struct enumerate_range
{
// using index_type = typename std::iterator_traits<Iterator>::difference_type;
using iterator = enumerate_iterator<Iterator, index_type>;
enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
iterator begin() const { return iterator(initial, first); }
iterator end() const { return iterator(0, last); }
private:
Iterator first;
Iterator last;
index_type initial;
};
} // namespace _enumerate_internal
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)
{
return _enumerate_internal::enumerate_range<Iterator, index_type>(first, last, initial);
}
template <typename Container, typename index_type = size_t> inline auto enumerate(Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, index_type>(std::begin(content), std::end(content), initial);
}
template <typename Container, typename index_type = size_t> inline auto enumerate(const Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, index_type>(std::begin(content), std::end(content), initial);
}
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>bug fix in acmacs::enumerate<commit_after>#pragma once
// https://infektor.net/posts/2017-03-31-range-based-enumerate.html
#include <iterator>
#include <utility>
// ----------------------------------------------------------------------
namespace acmacs
{
namespace _enumerate_internal
{
template <typename Iterator, typename index_type> struct enumerate_iterator
{
using iterator = Iterator;
//using index_type = typename std::iterator_traits<iterator>::difference_type;
using reference = typename std::iterator_traits<iterator>::reference;
enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
enumerate_iterator& operator++() { ++index; ++iter; return *this; }
bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
std::pair<index_type, reference> operator*() { return {index, *iter}; }
private:
index_type index;
iterator iter;
};
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> struct enumerate_range
{
// using index_type = typename std::iterator_traits<Iterator>::difference_type;
using iterator = enumerate_iterator<Iterator, index_type>;
enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
iterator begin() const { return iterator(initial, first); }
iterator end() const { return iterator(0, last); }
private:
Iterator first;
Iterator last;
index_type initial;
};
} // namespace _enumerate_internal
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)
{
return _enumerate_internal::enumerate_range<Iterator, index_type>(first, last, initial);
}
template <typename Container, typename index_type = size_t> inline auto enumerate(Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, index_type>(std::begin(content), std::end(content), initial);
}
template <typename Container, typename index_type = size_t> inline auto enumerate(const Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, index_type>(std::begin(content), std::end(content), initial);
}
template <typename Container, typename index_type = size_t> inline auto enumerate(Container&&, size_t = 0)
{
static_assert(std::is_same_v<int, Container>, "acmacs::enumerate cannot use temp (&&) values as a container (g++9 will destroy container before starting enumeration");
}
template <typename Container, typename Func, typename Index = size_t> inline void enumerate(Container&& content, Func callback, Index index = 0)
{
for (auto& element : content) {
callback(index, element);
++index;
}
}
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro (ugarro@users.sourceforge.net) *
* *
* 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. *
***************************************************************************/
#include "ingredientmatcherdialog.h"
#include "datablocks/recipelist.h"
#include "elementlist.h"
#include "DBBackend/recipedb.h"
#include "widgets/krelistview.h"
#include <qpainter.h>
#include <qstringlist.h>
#include <kiconloader.h>
#include <klocale.h>
#include <iostream>
IngredientMatcherDialog::IngredientMatcherDialog(QWidget *parent,RecipeDB *db):QVBox(parent)
{
// Initialize internal variables
database=db;
//Design the dialog
setSpacing(10);
// Ingredient list
ingredientListView=new KreListView(this,i18n("Ingredients"),true,1);
ingredientListView->listView()->setAllColumnsShowFocus(true);
ingredientListView->listView()->addColumn("*");
ingredientListView->listView()->addColumn(i18n("Ingredient"));
// Box to select allowed number of missing ingredients
missingBox=new QHBox(this);
missingNumberLabel=new QLabel(missingBox);
missingNumberLabel->setText(i18n("Missing ingredients allowed:"));
missingNumberCombo=new KComboBox(missingBox);
QStringList optionsList;
optionsList.append(i18n("None"));
optionsList+="1";
optionsList+="2";
optionsList+="3";
optionsList+=i18n("any");
missingNumberCombo->insertStringList(optionsList);
// Found recipe list
recipeListView=new KreListView(this,i18n("Matching Recipes"),false,1,missingBox);
recipeListView->listView()->setAllColumnsShowFocus(true);
recipeListView->listView()->addColumn(i18n("Title"));
recipeListView->listView()->addColumn(i18n("Missing Ingredients"));
recipeListView->listView()->setSorting(-1);
KIconLoader il;
QHBox *buttonBox=new QHBox(this);
okButton=new QPushButton(buttonBox);
okButton->setIconSet(il.loadIconSet("button_ok", KIcon::Small));
okButton->setText(i18n("Find matching recipes"));
clearButton=new QPushButton(buttonBox);
clearButton->setIconSet(il.loadIconSet("editclear", KIcon::Small));
clearButton->setText(i18n("Clear recipe list"));
// Load the data
reloadIngredients();
// Connect signals & slots
connect (okButton,SIGNAL(clicked()), this,SLOT(findRecipes()));
connect (clearButton,SIGNAL(clicked()),recipeListView->listView(),SLOT(clear()));
}
IngredientMatcherDialog::~IngredientMatcherDialog()
{
}
void IngredientMatcherDialog::findRecipes(void)
{
RecipeList rlist;
IngredientList ilist;
database->loadRecipeDetails(&rlist,true,false);
QListViewItem *qlv_it;
// First make a list of the ingredients that we have
for (qlv_it=ingredientListView->listView()->firstChild();qlv_it;qlv_it=qlv_it->nextSibling())
{
IngredientListItem *il_it=(IngredientListItem*) qlv_it;
if (il_it->isOn())
{
Ingredient ing; ing.name=il_it->name(); ing.ingredientID=il_it->id();
ilist.append(ing);
}
}
// Clear the list
recipeListView->listView()->clear();
// Add the section header
new SectionItem(recipeListView->listView(),i18n("Possible recipes with the specified ingredients"));
// Now show the recipes with ingredients that are contained in the previous set
// of ingredients
RecipeList incompleteRecipes;
QValueList <int> missingNumbers;
RecipeList::Iterator it;
for (it=rlist.begin();it!=rlist.end();++it)
{
IngredientList il=(*it).ingList;
IngredientList missing;
if (ilist.containsSubSet(il,missing))
{
new RecipeListItem(recipeListView->listView(),*it);
}
else
{
incompleteRecipes.append(*it);
missingNumbers.append(missing.count());
}
}
//Check if the user wants to show missing ingredients
if (this->missingNumberCombo->currentItem()==0) return; //"None"
// Classify recipes with missing ingredients in different lists by ammount
QValueList<int>::Iterator nit;
int missingNoAllowed;
if (missingNumberCombo->currentItem()!=4) missingNoAllowed=missingNumberCombo->currentText().toInt(); //"1..3"
else missingNoAllowed=-1; // "Any"
std::cerr<<"missingNoAllowed: "<<missingNoAllowed<<"\n";
for (int missingNo=1; missingNo<=missingNoAllowed; missingNo++)
{
std::cerr<<"missingNo: "<<missingNo<<"\n";
nit=missingNumbers.begin();
bool titleShownYet=false;
for (it=incompleteRecipes.begin();it!=incompleteRecipes.end();++it,++nit)
{
std::cerr<<"*nit: "<<*nit<<"missingNo:"<<missingNo<<"\n";
if ((*nit)==missingNo)
{
if (!titleShownYet)
{
new SectionItem(recipeListView->listView(),i18n("You are missing %1 ingredients for:").arg(missingNo));
titleShownYet=true;
}
new RecipeListItem(recipeListView->listView(),*it);
}
}
}
}
void IngredientMatcherDialog::reloadIngredients(void)
{
ingredientListView->listView()->clear();
ElementList ingredientList;
database->loadIngredients(&ingredientList);
ElementList::Iterator it;
for (it=ingredientList.begin();it!=ingredientList.end();++it)
{
Element ingredient=*it;
new IngredientListItem(ingredientListView->listView(),ingredient);
}
}
void SectionItem::paintCell ( QPainter * p, const QColorGroup & cg, int column, int width, int align )
{
int totalWidth=listView()->columnWidth(0)+listView()->columnWidth(1);
QPixmap sectionPm(totalWidth,height()); QPainter painter(§ionPm);
// Draw the section's deco
painter.setPen(KGlobalSettings::activeTitleColor());
painter.setBrush(KGlobalSettings::activeTitleColor());
painter.drawRect(0,0,totalWidth,height());
// Draw the section's text
QFont titleFont=KGlobalSettings::windowTitleFont ();
painter.setFont(titleFont);
painter.setPen(KGlobalSettings::activeTextColor());
painter.drawText(0,0,totalWidth,height(),Qt::AlignHCenter|Qt::AlignVCenter,mText);
// Paint only this cell (causes trouble while resizing)
/*if (column==0) bitBlt(p->device(), 0, 0, &textPm,0,0,width,height());
else if (column==1) bitBlt(p->device(),listView()->columnWidth(0),0,&textPm,listView()->columnWidth(0),0,width,height());*/
// Paint full row
bitBlt(p->device(), 0, itemPos(), §ionPm,0,0,totalWidth,height());
}<commit_msg>Make "Any" option work again<commit_after>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro (ugarro@users.sourceforge.net) *
* *
* 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. *
***************************************************************************/
#include "ingredientmatcherdialog.h"
#include "datablocks/recipelist.h"
#include "elementlist.h"
#include "DBBackend/recipedb.h"
#include "widgets/krelistview.h"
#include <qpainter.h>
#include <qstringlist.h>
#include <kiconloader.h>
#include <klocale.h>
IngredientMatcherDialog::IngredientMatcherDialog(QWidget *parent,RecipeDB *db):QVBox(parent)
{
// Initialize internal variables
database=db;
//Design the dialog
setSpacing(10);
// Ingredient list
ingredientListView=new KreListView(this,i18n("Ingredients"),true,1);
ingredientListView->listView()->setAllColumnsShowFocus(true);
ingredientListView->listView()->addColumn("*");
ingredientListView->listView()->addColumn(i18n("Ingredient"));
// Box to select allowed number of missing ingredients
missingBox=new QHBox(this);
missingNumberLabel=new QLabel(missingBox);
missingNumberLabel->setText(i18n("Missing ingredients allowed:"));
missingNumberCombo=new KComboBox(missingBox);
QStringList optionsList;
optionsList.append(i18n("None"));
optionsList+="1";
optionsList+="2";
optionsList+="3";
optionsList+=i18n("any");
missingNumberCombo->insertStringList(optionsList);
// Found recipe list
recipeListView=new KreListView(this,i18n("Matching Recipes"),false,1,missingBox);
recipeListView->listView()->setAllColumnsShowFocus(true);
recipeListView->listView()->addColumn(i18n("Title"));
recipeListView->listView()->addColumn(i18n("Missing Ingredients"));
recipeListView->listView()->setSorting(-1);
KIconLoader il;
QHBox *buttonBox=new QHBox(this);
okButton=new QPushButton(buttonBox);
okButton->setIconSet(il.loadIconSet("button_ok", KIcon::Small));
okButton->setText(i18n("Find matching recipes"));
clearButton=new QPushButton(buttonBox);
clearButton->setIconSet(il.loadIconSet("editclear", KIcon::Small));
clearButton->setText(i18n("Clear recipe list"));
// Load the data
reloadIngredients();
// Connect signals & slots
connect (okButton,SIGNAL(clicked()), this,SLOT(findRecipes()));
connect (clearButton,SIGNAL(clicked()),recipeListView->listView(),SLOT(clear()));
}
IngredientMatcherDialog::~IngredientMatcherDialog()
{
}
void IngredientMatcherDialog::findRecipes(void)
{
RecipeList rlist;
IngredientList ilist;
database->loadRecipeDetails(&rlist,true,false);
QListViewItem *qlv_it;
// First make a list of the ingredients that we have
for (qlv_it=ingredientListView->listView()->firstChild();qlv_it;qlv_it=qlv_it->nextSibling())
{
IngredientListItem *il_it=(IngredientListItem*) qlv_it;
if (il_it->isOn())
{
Ingredient ing; ing.name=il_it->name(); ing.ingredientID=il_it->id();
ilist.append(ing);
}
}
// Clear the list
recipeListView->listView()->clear();
// Add the section header
new SectionItem(recipeListView->listView(),i18n("Possible recipes with the specified ingredients"));
// Now show the recipes with ingredients that are contained in the previous set
// of ingredients
RecipeList incompleteRecipes;
QValueList <int> missingNumbers;
RecipeList::Iterator it;
for (it=rlist.begin();it!=rlist.end();++it)
{
IngredientList il=(*it).ingList;
IngredientList missing;
if (ilist.containsSubSet(il,missing))
{
new RecipeListItem(recipeListView->listView(),*it);
}
else
{
incompleteRecipes.append(*it);
missingNumbers.append(missing.count());
}
}
//Check if the user wants to show missing ingredients
if (this->missingNumberCombo->currentItem()==0) return; //"None"
// Classify recipes with missing ingredients in different lists by ammount
QValueList<int>::Iterator nit;
int missingNoAllowed;
if (missingNumberCombo->currentItem()!=4) missingNoAllowed=missingNumberCombo->currentText().toInt(); //"1..3"
else // "Any"
{
missingNoAllowed=0;
for (nit=missingNumbers.begin();nit!=missingNumbers.end();++nit) if ((*nit)>missingNoAllowed) missingNoAllowed=(*nit);
}
for (int missingNo=1; missingNo<=missingNoAllowed; missingNo++)
{
nit=missingNumbers.begin();
bool titleShownYet=false;
for (it=incompleteRecipes.begin();it!=incompleteRecipes.end();++it,++nit)
{
if ((*nit)==missingNo)
{
if (!titleShownYet)
{
new SectionItem(recipeListView->listView(),i18n("You are missing %1 ingredients for:").arg(missingNo));
titleShownYet=true;
}
new RecipeListItem(recipeListView->listView(),*it);
}
}
}
}
void IngredientMatcherDialog::reloadIngredients(void)
{
ingredientListView->listView()->clear();
ElementList ingredientList;
database->loadIngredients(&ingredientList);
ElementList::Iterator it;
for (it=ingredientList.begin();it!=ingredientList.end();++it)
{
Element ingredient=*it;
new IngredientListItem(ingredientListView->listView(),ingredient);
}
}
void SectionItem::paintCell ( QPainter * p, const QColorGroup & cg, int column, int width, int align )
{
int totalWidth=listView()->columnWidth(0)+listView()->columnWidth(1);
QPixmap sectionPm(totalWidth,height()); QPainter painter(§ionPm);
// Draw the section's deco
painter.setPen(KGlobalSettings::activeTitleColor());
painter.setBrush(KGlobalSettings::activeTitleColor());
painter.drawRect(0,0,totalWidth,height());
// Draw the section's text
QFont titleFont=KGlobalSettings::windowTitleFont ();
painter.setFont(titleFont);
painter.setPen(KGlobalSettings::activeTextColor());
painter.drawText(0,0,totalWidth,height(),Qt::AlignHCenter|Qt::AlignVCenter,mText);
// Paint only this cell (causes trouble while resizing)
/*if (column==0) bitBlt(p->device(), 0, 0, &textPm,0,0,width,height());
else if (column==1) bitBlt(p->device(),listView()->columnWidth(0),0,&textPm,listView()->columnWidth(0),0,width,height());*/
// Paint full row
bitBlt(p->device(), 0, itemPos(), §ionPm,0,0,totalWidth,height());
}<|endoftext|> |
<commit_before>#include "domain/mesh_cartesian.h"
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <numeric>
#include <functional>
#include <vector>
#include <deal.II/base/point.h>
#include <deal.II/grid/tria.h>
#include "test_helpers/test_helper_functions.h"
#include "test_helpers/gmock_wrapper.h"
namespace {
using namespace bart;
template <typename DimensionWrapper>
class DomainMeshCartesianTest : public ::testing::Test {
protected:
static constexpr int dim = DimensionWrapper::value;
};
TYPED_TEST_CASE(DomainMeshCartesianTest, bart::testing::AllDimensions);
TYPED_TEST(DomainMeshCartesianTest, FillTriangulationTest) {
constexpr int dim = this->dim;
std::vector<double> spatial_max{btest::RandomVector(dim, 0, 100)};
std::vector<double> n_cells_double{btest::RandomVector(dim, 1, 20)};
std::vector<int> n_cells{n_cells_double.begin(), n_cells_double.end()};
int n_total_cells = std::accumulate(n_cells.begin(), n_cells.end(), 1,
std::multiplies<int>());
domain::MeshCartesian<dim> test_mesh(spatial_max, n_cells);
dealii::Triangulation<dim> test_triangulation;
test_mesh.FillTriangulation(test_triangulation);
EXPECT_EQ(test_triangulation.n_cells(), n_total_cells);
EXPECT_FALSE(test_mesh.has_material_mapping());
for (auto const &cell : test_triangulation.active_cell_iterators()) {
for (int i = 0; i < dim; ++i) {
EXPECT_THAT(cell->extent_in_direction(i),
::testing::DoubleNear(spatial_max[i]/n_cells[i], 1e-10));
}
}
}
TYPED_TEST(DomainMeshCartesianTest, BadSpatialSize) {
constexpr int dim = this->dim;
std::vector<std::vector<double>> spatial_maxes{
{},
btest::RandomVector(1, 0, 100),
btest::RandomVector(2, 0, 100),
btest::RandomVector(3, 0, 100),
btest::RandomVector(4, 0, 100)};
std::vector<std::vector<int>> n_cells{{}, {10}, {10, 20}, {10, 20, 30},
{10, 20, 30, 40}};
std::array<int, 2> i_values{-1, 1};
for (const auto& i : i_values) {
EXPECT_ANY_THROW({
domain::MeshCartesian<dim> test_mesh(spatial_maxes.at(dim + i),
n_cells.at(dim + i));
});
}
}
TYPED_TEST(DomainMeshCartesianTest, SingleMaterialMapping) {
constexpr int dim = this->dim;
std::vector<double> spatial_max{btest::RandomVector(dim, 5, 20)};
std::vector<double> n_cells_double{btest::RandomVector(dim, 5, 20)};
std::vector<int> n_cells{n_cells_double.cbegin(),
n_cells_double.cend()};
domain::MeshCartesian<dim> test_mesh(spatial_max, n_cells);
std::string material_mapping{'1'};
test_mesh.ParseMaterialMap(material_mapping);
EXPECT_TRUE(test_mesh.has_material_mapping());
// Random inner locations
std::array<std::array<double, dim>, 10> test_locations;
for (auto& location : test_locations) {
for (int i = 0; i < dim; ++i) {
location.at(i) = btest::RandomDouble(0, spatial_max.at(i));
}
EXPECT_EQ(test_mesh.GetMaterialID(location), 1);
}
// Edges and corners
std::array<double, dim> test_location;
std::array<double, 3> x_locations{0, spatial_max.at(0)/2, spatial_max.at(0)};
std::vector<double> y_locations{};
std::vector<double> z_locations{};
if (dim > 1) {
y_locations = {0, spatial_max.at(1)/2, spatial_max.at(1)};
if (dim > 2) {
z_locations = {0, spatial_max.at(2)/2, spatial_max.at(2)};
}
}
for (const int x : x_locations) {
test_location.at(0) = x;
for (const int y : y_locations) {
test_location.at(1) = y;
for (const int z : z_locations) {
test_location.at(2) = z;
}
}
EXPECT_EQ(test_mesh.GetMaterialID(test_location), 1);
}
}
class DomainMeshCartesianMappingTest : public ::testing::Test {};
TEST_F(DomainMeshCartesianMappingTest, MultipleMaterialMapping1D) {
std::vector<double> spatial_max{btest::RandomVector(1, 5, 20)};
std::vector<double> n_cells_double{btest::RandomVector(1, 5, 20)};
std::vector<int> n_cells{n_cells_double.cbegin(), n_cells_double.cend()};
domain::MeshCartesian<1> test_mesh(spatial_max, n_cells);
std::string material_mapping{"1 2"};
test_mesh.ParseMaterialMap(material_mapping);
EXPECT_TRUE(test_mesh.has_material_mapping());
std::array<std::array<double, 1>, 5> test_locations;
for (auto& location : test_locations) {
location.at(0) = btest::RandomDouble(0, spatial_max.at(0)/2);
EXPECT_EQ(test_mesh.GetMaterialID(location), 1);
location.at(0) = btest::RandomDouble(spatial_max.at(0)/2, spatial_max.at(0));
EXPECT_EQ(test_mesh.GetMaterialID(location), 2);
}
// Edge cases
std::array<double, 1> origin{0};
std::array<double, 1> midpoint{spatial_max.at(0)/2};
std::array<double, 1> endpoint{spatial_max.at(0)};
EXPECT_EQ(test_mesh.GetMaterialID(origin), 1);
EXPECT_EQ(test_mesh.GetMaterialID(midpoint), 1);
EXPECT_EQ(test_mesh.GetMaterialID(endpoint), 2);
}
TEST_F(DomainMeshCartesianMappingTest, MultipleMaterialMapping2D) {
std::vector<double> spatial_max{btest::RandomVector(2, 5, 20)};
std::vector<double> n_cells_double{btest::RandomVector(2, 5, 20)};
std::vector<int> n_cells{n_cells_double.cbegin(), n_cells_double.cend()};
domain::MeshCartesian<2> test_mesh(spatial_max, n_cells);
std::string material_mapping{"1 2\n3 4"};
test_mesh.ParseMaterialMap(material_mapping);
double x_max = spatial_max.at(0), x_mid = spatial_max.at(0)/2;
double y_max = spatial_max.at(1), y_mid = spatial_max.at(1)/2;
EXPECT_TRUE(test_mesh.has_material_mapping());
// Inner locations
std::array<std::array<double, 2>, 5> test_locations;
for (auto& location : test_locations) {
location.at(0) = btest::RandomDouble(0, x_mid);
location.at(1) = btest::RandomDouble(0, y_mid);
EXPECT_EQ(test_mesh.GetMaterialID(location), 3);
location.at(0) = btest::RandomDouble(x_mid, x_max);
location.at(1) = btest::RandomDouble(0, y_mid);
EXPECT_EQ(test_mesh.GetMaterialID(location), 4);
location.at(0) = btest::RandomDouble(0, x_mid);
location.at(1) = btest::RandomDouble(y_mid, y_max);
EXPECT_EQ(test_mesh.GetMaterialID(location), 1);
location.at(0) = btest::RandomDouble(x_mid, x_max);
location.at(1) = btest::RandomDouble(y_mid, y_max);
EXPECT_EQ(test_mesh.GetMaterialID(location), 2);
}
// Edges and corners
std::map<std::array<double, 2>, int> locations_and_material_ids{
{{0,0}, 3}, {{x_mid, 0}, 3}, {{x_max, 0}, 4},
{{0, y_mid}, 3}, {{x_mid, y_mid}, 3}, {{x_max, y_mid}, 4},
{{0, y_max}, 1}, {{x_mid, y_max}, 1}, {{x_max, y_max}, 2}
};
for (auto& location_and_material_id : locations_and_material_ids) {
auto& [location, id] = location_and_material_id;
EXPECT_EQ(test_mesh.GetMaterialID(location), id);
}
}
/*
TEST_F(Dom, MultipleMaterialMapping) {
constexpr int dim = this->dim;
std::vector<double> spatial_max{btest::RandomVector(dim, 5, 20)};
std::vector<double> n_cells_double{btest::RandomVector(dim, 5, 20)};
std::vector<int> n_cells{n_cells_double.cbegin(),
n_cells_double.cend()};
domain::MeshCartesian<dim> test_mesh(spatial_max, n_cells);
std::ostringstream material_mapping_stream;
material_mapping_stream << "1 2";
if (dim > 1)
material_mapping_stream << "\n3 4";
if (dim == 3)
material_mapping_stream << "\n\n5 6\n7 8";
std::string material_mapping = material_mapping_stream.str();
test_mesh.ParseMaterialMap(material_mapping);
EXPECT_TRUE(test_mesh.has_material_mapping());
std::array<double, 3> x_locations{0, spatial_max.at(0)/2, spatial_max.at(0)};
std::array<double, 3> y_locations;
std::array<double, 3> z_locations;
switch (dim) {
case 3: {
z_locations = {0, spatial_max.at(2)/2, spatial_max.at(2)};
[[fallthrough]];
}
case 2: {
y_locations = {0, spatial_max.at(1)/2, spatial_max.at(1)};
}
}
if (dim == 1) {
}
}
*/
} // namespace
<commit_msg>added testing for 3D material mapping check<commit_after>#include "domain/mesh_cartesian.h"
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <numeric>
#include <functional>
#include <vector>
#include <deal.II/base/point.h>
#include <deal.II/grid/tria.h>
#include "test_helpers/test_helper_functions.h"
#include "test_helpers/gmock_wrapper.h"
namespace {
using namespace bart;
template <typename DimensionWrapper>
class DomainMeshCartesianTest : public ::testing::Test {
protected:
static constexpr int dim = DimensionWrapper::value;
};
TYPED_TEST_CASE(DomainMeshCartesianTest, bart::testing::AllDimensions);
TYPED_TEST(DomainMeshCartesianTest, FillTriangulationTest) {
constexpr int dim = this->dim;
std::vector<double> spatial_max{btest::RandomVector(dim, 0, 100)};
std::vector<double> n_cells_double{btest::RandomVector(dim, 1, 20)};
std::vector<int> n_cells{n_cells_double.begin(), n_cells_double.end()};
int n_total_cells = std::accumulate(n_cells.begin(), n_cells.end(), 1,
std::multiplies<int>());
domain::MeshCartesian<dim> test_mesh(spatial_max, n_cells);
dealii::Triangulation<dim> test_triangulation;
test_mesh.FillTriangulation(test_triangulation);
EXPECT_EQ(test_triangulation.n_cells(), n_total_cells);
EXPECT_FALSE(test_mesh.has_material_mapping());
for (auto const &cell : test_triangulation.active_cell_iterators()) {
for (int i = 0; i < dim; ++i) {
EXPECT_THAT(cell->extent_in_direction(i),
::testing::DoubleNear(spatial_max[i]/n_cells[i], 1e-10));
}
}
}
TYPED_TEST(DomainMeshCartesianTest, BadSpatialSize) {
constexpr int dim = this->dim;
std::vector<std::vector<double>> spatial_maxes{
{},
btest::RandomVector(1, 0, 100),
btest::RandomVector(2, 0, 100),
btest::RandomVector(3, 0, 100),
btest::RandomVector(4, 0, 100)};
std::vector<std::vector<int>> n_cells{{}, {10}, {10, 20}, {10, 20, 30},
{10, 20, 30, 40}};
std::array<int, 2> i_values{-1, 1};
for (const auto& i : i_values) {
EXPECT_ANY_THROW({
domain::MeshCartesian<dim> test_mesh(spatial_maxes.at(dim + i),
n_cells.at(dim + i));
});
}
}
TYPED_TEST(DomainMeshCartesianTest, SingleMaterialMapping) {
constexpr int dim = this->dim;
std::vector<double> spatial_max{btest::RandomVector(dim, 5, 20)};
std::vector<double> n_cells_double{btest::RandomVector(dim, 5, 20)};
std::vector<int> n_cells{n_cells_double.cbegin(),
n_cells_double.cend()};
std::string material_mapping{'1'};
domain::MeshCartesian<dim> test_mesh(spatial_max, n_cells, material_mapping);
EXPECT_TRUE(test_mesh.has_material_mapping());
// Random inner locations
std::array<std::array<double, dim>, 10> test_locations;
for (auto& location : test_locations) {
for (int i = 0; i < dim; ++i) {
location.at(i) = btest::RandomDouble(0, spatial_max.at(i));
}
EXPECT_EQ(test_mesh.GetMaterialID(location), 1);
}
// Edges and corners
std::array<double, dim> test_location;
std::array<double, 3> x_locations{0, spatial_max.at(0)/2, spatial_max.at(0)};
std::vector<double> y_locations{};
std::vector<double> z_locations{};
if (dim > 1) {
y_locations = {0, spatial_max.at(1)/2, spatial_max.at(1)};
if (dim > 2) {
z_locations = {0, spatial_max.at(2)/2, spatial_max.at(2)};
}
}
for (const int x : x_locations) {
test_location.at(0) = x;
for (const int y : y_locations) {
test_location.at(1) = y;
for (const int z : z_locations) {
test_location.at(2) = z;
}
}
EXPECT_EQ(test_mesh.GetMaterialID(test_location), 1);
}
}
class DomainMeshCartesianMappingTest : public ::testing::Test {};
TEST_F(DomainMeshCartesianMappingTest, MultipleMaterialMapping1D) {
std::vector<double> spatial_max{btest::RandomVector(1, 5, 20)};
std::vector<double> n_cells_double{btest::RandomVector(1, 5, 20)};
std::vector<int> n_cells{n_cells_double.cbegin(), n_cells_double.cend()};
domain::MeshCartesian<1> test_mesh(spatial_max, n_cells);
std::string material_mapping{"1 2"};
test_mesh.ParseMaterialMap(material_mapping);
EXPECT_TRUE(test_mesh.has_material_mapping());
std::array<std::array<double, 1>, 5> test_locations;
for (auto& location : test_locations) {
location.at(0) = btest::RandomDouble(0, spatial_max.at(0)/2);
EXPECT_EQ(test_mesh.GetMaterialID(location), 1);
location.at(0) = btest::RandomDouble(spatial_max.at(0)/2, spatial_max.at(0));
EXPECT_EQ(test_mesh.GetMaterialID(location), 2);
}
// Edge cases
std::array<double, 1> origin{0};
std::array<double, 1> midpoint{spatial_max.at(0)/2};
std::array<double, 1> endpoint{spatial_max.at(0)};
EXPECT_EQ(test_mesh.GetMaterialID(origin), 1);
EXPECT_EQ(test_mesh.GetMaterialID(midpoint), 1);
EXPECT_EQ(test_mesh.GetMaterialID(endpoint), 2);
}
TEST_F(DomainMeshCartesianMappingTest, MultipleMaterialMapping2D) {
std::vector<double> spatial_max{btest::RandomVector(2, 5, 20)};
std::vector<double> n_cells_double{btest::RandomVector(2, 5, 20)};
std::vector<int> n_cells{n_cells_double.cbegin(), n_cells_double.cend()};
domain::MeshCartesian<2> test_mesh(spatial_max, n_cells);
std::string material_mapping{"1 2\n3 4"};
test_mesh.ParseMaterialMap(material_mapping);
double x_max = spatial_max.at(0), x_mid = spatial_max.at(0)/2;
double y_max = spatial_max.at(1), y_mid = spatial_max.at(1)/2;
EXPECT_TRUE(test_mesh.has_material_mapping());
// Inner locations
std::array<std::array<double, 2>, 5> test_locations;
for (auto& location : test_locations) {
location.at(0) = btest::RandomDouble(0, x_mid);
location.at(1) = btest::RandomDouble(0, y_mid);
EXPECT_EQ(test_mesh.GetMaterialID(location), 3);
location.at(0) = btest::RandomDouble(x_mid, x_max);
location.at(1) = btest::RandomDouble(0, y_mid);
EXPECT_EQ(test_mesh.GetMaterialID(location), 4);
location.at(0) = btest::RandomDouble(0, x_mid);
location.at(1) = btest::RandomDouble(y_mid, y_max);
EXPECT_EQ(test_mesh.GetMaterialID(location), 1);
location.at(0) = btest::RandomDouble(x_mid, x_max);
location.at(1) = btest::RandomDouble(y_mid, y_max);
EXPECT_EQ(test_mesh.GetMaterialID(location), 2);
}
// Edges and corners
std::map<std::array<double, 2>, int> locations_and_material_ids{
{{0,0}, 3}, {{x_mid, 0}, 3}, {{x_max, 0}, 4},
{{0, y_mid}, 3}, {{x_mid, y_mid}, 3}, {{x_max, y_mid}, 4},
{{0, y_max}, 1}, {{x_mid, y_max}, 1}, {{x_max, y_max}, 2}
};
for (auto& location_and_material_id : locations_and_material_ids) {
auto& [location, id] = location_and_material_id;
EXPECT_EQ(test_mesh.GetMaterialID(location), id);
}
}
TEST_F(DomainMeshCartesianMappingTest, MultipleMaterialMapping3D) {
std::vector<double> spatial_max{btest::RandomVector(3, 5, 20)};
std::vector<double> n_cells_double{btest::RandomVector(3, 5, 20)};
std::vector<int> n_cells{n_cells_double.cbegin(), n_cells_double.cend()};
domain::MeshCartesian<3> test_mesh(spatial_max, n_cells);
std::string material_mapping{"1 2\n3 4\n\n5 6\n7 8"};
test_mesh.ParseMaterialMap(material_mapping);
double x_max = spatial_max.at(0), x_mid = spatial_max.at(0)/2;
double y_max = spatial_max.at(1), y_mid = spatial_max.at(1)/2;
double z_max = spatial_max.at(2), z_mid = spatial_max.at(2)/2;
EXPECT_TRUE(test_mesh.has_material_mapping());
// Inner locations
std::array<std::array<double, 3>, 5> test_locations;
for (auto& location : test_locations) {
location.at(0) = btest::RandomDouble(0, x_mid);
location.at(1) = btest::RandomDouble(0, y_mid);
location.at(2) = btest::RandomDouble(0, z_mid);
EXPECT_EQ(test_mesh.GetMaterialID(location), 7);
location.at(0) = btest::RandomDouble(x_mid, x_max);
location.at(1) = btest::RandomDouble(0, y_mid);
location.at(2) = btest::RandomDouble(0, z_mid);
EXPECT_EQ(test_mesh.GetMaterialID(location), 8);
location.at(0) = btest::RandomDouble(0, x_mid);
location.at(1) = btest::RandomDouble(y_mid, y_max);
location.at(2) = btest::RandomDouble(0, z_mid);
EXPECT_EQ(test_mesh.GetMaterialID(location), 5);
location.at(0) = btest::RandomDouble(0, x_mid);
location.at(1) = btest::RandomDouble(0, y_mid);
location.at(2) = btest::RandomDouble(z_mid, z_max);
EXPECT_EQ(test_mesh.GetMaterialID(location), 3);
location.at(0) = btest::RandomDouble(x_mid, x_max);
location.at(1) = btest::RandomDouble(y_mid, y_max);
location.at(2) = btest::RandomDouble(0, z_mid);
EXPECT_EQ(test_mesh.GetMaterialID(location), 6);
location.at(0) = btest::RandomDouble(x_mid, x_max);
location.at(1) = btest::RandomDouble(y_mid, y_max);
location.at(2) = btest::RandomDouble(z_mid, z_max);
EXPECT_EQ(test_mesh.GetMaterialID(location), 2);
location.at(0) = btest::RandomDouble(x_mid, x_max);
location.at(1) = btest::RandomDouble(0, y_mid);
location.at(2) = btest::RandomDouble(z_mid, z_max);
EXPECT_EQ(test_mesh.GetMaterialID(location), 4);
location.at(0) = btest::RandomDouble(0, x_mid);
location.at(1) = btest::RandomDouble(y_mid, y_max);
location.at(2) = btest::RandomDouble(z_mid, z_max);
EXPECT_EQ(test_mesh.GetMaterialID(location), 1);
}
}
} // namespace
<|endoftext|> |
<commit_before>/* dtkComposerNodeFile.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Thu Jul 8 13:28:18 2010 (+0200)
* Version: $Id$
* Last-Updated: Fri Apr 8 16:26:53 2011 (+0200)
* By: Thibaud Kloczko
* Update #: 78
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNodeFile.h"
#include "dtkComposerNodeProperty.h"
#include <dtkCore/dtkGlobal.h>
#include <dtkCore/dtkLog.h>
#include <dtkGui/dtkTextEditor.h>
#include <QtGui/QFileDialog>
class dtkComposerNodeFilePrivate
{
public:
dtkComposerNodeProperty *property_output_file_name;
dtkComposerNodeProperty *property_output_file_text;
public:
QString file;
};
dtkComposerNodeFile::dtkComposerNodeFile(dtkComposerNode *parent) : dtkComposerNode(parent), d(new dtkComposerNodeFilePrivate)
{
d->property_output_file_name = new dtkComposerNodeProperty("name", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);
d->property_output_file_text = new dtkComposerNodeProperty("text", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);
this->setTitle("File");
this->setKind(dtkComposerNode::Atomic);
this->setType("dtkComposerFile");
this->addOutputProperty(d->property_output_file_name);
this->addOutputProperty(d->property_output_file_text);
this->addAction("Choose file", this, SLOT(getFileName()));
this->addAction("Edit file", this, SLOT(editFile()));
d->file = QString();
}
dtkComposerNodeFile::~dtkComposerNodeFile(void)
{
delete d;
d = NULL;
}
QVariant dtkComposerNodeFile::value(dtkComposerNodeProperty *property)
{
if(property == d->property_output_file_name) {
emit elapsed("00:00::000.001");
emit progressed(QString("File name: %1").arg(d->file));
emit progressed(100);
return QVariant(d->file);
}
return QVariant();
}
void dtkComposerNodeFile::editFile(void)
{
dtkTextEditor *editor = new dtkTextEditor;
editor->open(d->file);
editor->show();
connect(editor, SIGNAL(closed()), editor, SLOT(deleteLater()));
}
void dtkComposerNodeFile::getFileName(void)
{
d->file = QFileDialog::getOpenFileName(0, "File node");
}
void dtkComposerNodeFile::setFileName(const QString& file)
{
d->file = file;
}
void dtkComposerNodeFile::pull(dtkComposerEdge *edge, dtkComposerNodeProperty *property)
{
Q_UNUSED(edge);
Q_UNUSED(property);
DTK_DEFAULT_IMPLEMENTATION;
}
void dtkComposerNodeFile::run(void)
{
if (d->file.isEmpty())
dtkDebug() << "File has not been initialized.";
return;
}
void dtkComposerNodeFile::push(dtkComposerEdge *edge, dtkComposerNodeProperty *property)
{
Q_UNUSED(edge);
Q_UNUSED(property);
DTK_DEFAULT_IMPLEMENTATION;
}
<commit_msg>Remove dtk default inplementation messages from node file.<commit_after>/* dtkComposerNodeFile.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Thu Jul 8 13:28:18 2010 (+0200)
* Version: $Id$
* Last-Updated: Tue Aug 30 10:10:17 2011 (+0200)
* By: Thibaud Kloczko
* Update #: 80
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNodeFile.h"
#include "dtkComposerNodeProperty.h"
#include <dtkCore/dtkGlobal.h>
#include <dtkCore/dtkLog.h>
#include <dtkGui/dtkTextEditor.h>
#include <QtGui/QFileDialog>
class dtkComposerNodeFilePrivate
{
public:
dtkComposerNodeProperty *property_output_file_name;
dtkComposerNodeProperty *property_output_file_text;
public:
QString file;
};
dtkComposerNodeFile::dtkComposerNodeFile(dtkComposerNode *parent) : dtkComposerNode(parent), d(new dtkComposerNodeFilePrivate)
{
d->property_output_file_name = new dtkComposerNodeProperty("name", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);
d->property_output_file_text = new dtkComposerNodeProperty("text", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);
this->setTitle("File");
this->setKind(dtkComposerNode::Atomic);
this->setType("dtkComposerFile");
this->addOutputProperty(d->property_output_file_name);
this->addOutputProperty(d->property_output_file_text);
this->addAction("Choose file", this, SLOT(getFileName()));
this->addAction("Edit file", this, SLOT(editFile()));
d->file = QString();
}
dtkComposerNodeFile::~dtkComposerNodeFile(void)
{
delete d;
d = NULL;
}
QVariant dtkComposerNodeFile::value(dtkComposerNodeProperty *property)
{
if(property == d->property_output_file_name) {
emit elapsed("00:00::000.001");
emit progressed(QString("File name: %1").arg(d->file));
emit progressed(100);
return QVariant(d->file);
}
return QVariant();
}
void dtkComposerNodeFile::editFile(void)
{
dtkTextEditor *editor = new dtkTextEditor;
editor->open(d->file);
editor->show();
connect(editor, SIGNAL(closed()), editor, SLOT(deleteLater()));
}
void dtkComposerNodeFile::getFileName(void)
{
d->file = QFileDialog::getOpenFileName(0, "File node");
}
void dtkComposerNodeFile::setFileName(const QString& file)
{
d->file = file;
}
void dtkComposerNodeFile::pull(dtkComposerEdge *edge, dtkComposerNodeProperty *property)
{
Q_UNUSED(edge);
Q_UNUSED(property);
}
void dtkComposerNodeFile::run(void)
{
if (d->file.isEmpty())
dtkDebug() << "File has not been initialized.";
return;
}
void dtkComposerNodeFile::push(dtkComposerEdge *edge, dtkComposerNodeProperty *property)
{
Q_UNUSED(edge);
Q_UNUSED(property);
}
<|endoftext|> |
<commit_before>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include "AshtechMBEN.hpp"
#include "AshtechStream.hpp"
#include "icd_200_constants.hpp"
using namespace std;
namespace gpstk
{
const char* AshtechMBEN::mpcId = "MPC";
const char* AshtechMBEN::mcaId = "MCA";
//---------------------------------------------------------------------------
void AshtechMBEN::reallyGetRecord(FFStream& ffs)
throw(std::exception, FFStreamError, EndOfFile)
{
AshtechStream& stream=dynamic_cast<AshtechStream&>(ffs);
// make sure the object is reset before starting the search
clear(fmtbit | lenbit | crcbit);
string& rawData = stream.rawData;
// If this object doesn't have an id set yet, assume that the streams
// most recent read id is what we need to be
if (id == "" && rawData.size()>=11 &&
rawData.substr(0,7) == preamble &&
rawData[10]==',')
id = rawData.substr(7,3);
// If that didn't work, or this is object is not of the right type,
// then give up.
if (id == "" || !checkId(id))
return;
readBody(stream);
}
//---------------------------------------------------------------------------
void AshtechMBEN::decode(const std::string& data)
throw(std::exception, FFStreamError)
{
using gpstk::BinUtils::decodeVar;
string str(data);
if (debugLevel>2)
cout << "MBEN " << str.length() << " " << endl;
if (str.length() == 108 || str.length()==52)
{
ascii=false;
header = str.substr(0,11); str.erase(0,11);
seq = decodeVar<uint16_t>(str);
left = decodeVar<uint8_t>(str);
svprn = decodeVar<uint8_t>(str);
el = decodeVar<uint8_t>(str);
az = decodeVar<uint8_t>(str);
chid = decodeVar<uint8_t>(str);
ca.decodeBIN(str);
if (id == mpcId)
{
p1.decodeBIN(str);
p2.decodeBIN(str);
}
clear();
}
else
{
ascii=true;
header = str.substr(0,11); str.erase(0,11);
stringstream iss(str);
char c;
iss >> seq >> c
>> left >> c
>> svprn >> c
>> el >> c
>> az >> c
>> chid >> c;
ca.decodeASCII(iss);
if (id == mpcId)
{
p1.decodeASCII(iss);
p2.decodeASCII(iss);
}
clear();
}
if (seq>36000)
setstate(fmtbit);
}
//---------------------------------------------------------------------------
void AshtechMBEN::code_block::decodeASCII(stringstream& str)
throw(std::exception, FFStreamError)
{
char c;
str >> warning >> c
>> goodbad >> c
>> polarity_known>> c
>> ireg >> c
>> qa_phase >> c
>> full_phase >> c
>> raw_range >> c
>> doppler >> c
>> smoothing >> c
>> smooth_cnt >> c;
// The ashtech docs say this field should be in 1e-4 Hz
// The data sure doesn't look like it, however
//doppler *= 1e-4;
raw_range *= 1e-3; //convert ms to sec
}
//---------------------------------------------------------------------------
void AshtechMBEN::code_block::decodeBIN(string& str)
throw(std::exception, FFStreamError)
{
using gpstk::BinUtils::decodeVar;
uint32_t smo;
warning = decodeVar<uint8_t>(str);
goodbad = decodeVar<uint8_t>(str);
polarity_known = decodeVar<uint8_t>(str);
ireg = decodeVar<uint8_t>(str);
qa_phase = decodeVar<uint8_t>(str);
full_phase = decodeVar<double>(str);
raw_range = decodeVar<double>(str);
doppler = decodeVar<int32_t>(str);
smo = decodeVar<uint32_t>(str);
doppler *= 1e-4;
smoothing = (smo & 0x800000 ? -1e-3 : 1e-3) * (smo & 0x7fffff);
smooth_cnt = (smo >> 24) & 0xff;
}
//---------------------------------------------------------------------------
void AshtechMBEN::code_block::dump(ostream& out) const
{
using gpstk::StringUtils::asString;
out << hex
<< "warn:" << (int)warning
<< " gb:" << (int)goodbad
<< " pol:" << (int)polarity_known
<< dec
<< " phase:" << asString(full_phase, 1)
<< " range:" << asString(raw_range*1e3, 3)
<< " doppler:" << doppler
<< " smo:" << smoothing;
}
//---------------------------------------------------------------------------
float AshtechMBEN::code_block::snr(float chipRate) const throw()
{
const int n = 20000; // number of samples in 1 ms
const float m = 4.14; // magnitude of the carrier estimate;
float bw = 0.9 * chipRate; // equivalent noise bandwidth (Hz)
const float d = PI/(n*n*m*m*4.0);
float snr=0;
if (ireg)
{
snr = exp(((float)ireg)/25.0);
snr = snr*snr*bw*d;
snr = 10 * log10(snr);
}
return snr;
}
//---------------------------------------------------------------------------
void AshtechMBEN::dump(ostream& out) const throw()
{
ostringstream oss;
using gpstk::StringUtils::asString;
AshtechData::dump(oss);
oss << getName() << "1:"
<< " seq:" << 0.05 * seq
<< " left:" << (int)left
<< " prn:" << (int)svprn
<< " el:" << (int)el
<< " az:" << (int)az
<< " chid:" << (int)chid
<< " " << (ascii?"ascii":"bin")
<< endl;
oss << getName() << "2: ca";
ca.dump(oss);
oss << endl;
if (id == mpcId)
{
oss << getName() << "3: p1";
p1.dump(oss);
oss << endl;
oss << getName() << "4: p2";
p2.dump(oss);
oss << endl;
}
out << oss.str() << flush;
}
} // namespace gpstk
<commit_msg>Added output of the qa_phase value in the dump<commit_after>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include "AshtechMBEN.hpp"
#include "AshtechStream.hpp"
#include "icd_200_constants.hpp"
using namespace std;
namespace gpstk
{
const char* AshtechMBEN::mpcId = "MPC";
const char* AshtechMBEN::mcaId = "MCA";
//---------------------------------------------------------------------------
void AshtechMBEN::reallyGetRecord(FFStream& ffs)
throw(std::exception, FFStreamError, EndOfFile)
{
AshtechStream& stream=dynamic_cast<AshtechStream&>(ffs);
// make sure the object is reset before starting the search
clear(fmtbit | lenbit | crcbit);
string& rawData = stream.rawData;
// If this object doesn't have an id set yet, assume that the streams
// most recent read id is what we need to be
if (id == "" && rawData.size()>=11 &&
rawData.substr(0,7) == preamble &&
rawData[10]==',')
id = rawData.substr(7,3);
// If that didn't work, or this is object is not of the right type,
// then give up.
if (id == "" || !checkId(id))
return;
readBody(stream);
}
//---------------------------------------------------------------------------
void AshtechMBEN::decode(const std::string& data)
throw(std::exception, FFStreamError)
{
using gpstk::BinUtils::decodeVar;
string str(data);
if (debugLevel>2)
cout << "MBEN " << str.length() << " " << endl;
if (str.length() == 108 || str.length()==52)
{
ascii=false;
header = str.substr(0,11); str.erase(0,11);
seq = decodeVar<uint16_t>(str);
left = decodeVar<uint8_t>(str);
svprn = decodeVar<uint8_t>(str);
el = decodeVar<uint8_t>(str);
az = decodeVar<uint8_t>(str);
chid = decodeVar<uint8_t>(str);
ca.decodeBIN(str);
if (id == mpcId)
{
p1.decodeBIN(str);
p2.decodeBIN(str);
}
clear();
}
else
{
ascii=true;
header = str.substr(0,11); str.erase(0,11);
stringstream iss(str);
char c;
iss >> seq >> c
>> left >> c
>> svprn >> c
>> el >> c
>> az >> c
>> chid >> c;
ca.decodeASCII(iss);
if (id == mpcId)
{
p1.decodeASCII(iss);
p2.decodeASCII(iss);
}
clear();
}
if (seq>36000)
setstate(fmtbit);
}
//---------------------------------------------------------------------------
void AshtechMBEN::code_block::decodeASCII(stringstream& str)
throw(std::exception, FFStreamError)
{
char c;
str >> warning >> c
>> goodbad >> c
>> polarity_known>> c
>> ireg >> c
>> qa_phase >> c
>> full_phase >> c
>> raw_range >> c
>> doppler >> c
>> smoothing >> c
>> smooth_cnt >> c;
// The ashtech docs say this field should be in 1e-4 Hz
// The data sure doesn't look like it, however
//doppler *= 1e-4;
raw_range *= 1e-3; //convert ms to sec
}
//---------------------------------------------------------------------------
void AshtechMBEN::code_block::decodeBIN(string& str)
throw(std::exception, FFStreamError)
{
using gpstk::BinUtils::decodeVar;
uint32_t smo;
warning = decodeVar<uint8_t>(str);
goodbad = decodeVar<uint8_t>(str);
polarity_known = decodeVar<uint8_t>(str);
ireg = decodeVar<uint8_t>(str);
qa_phase = decodeVar<uint8_t>(str);
full_phase = decodeVar<double>(str);
raw_range = decodeVar<double>(str);
doppler = decodeVar<int32_t>(str);
smo = decodeVar<uint32_t>(str);
doppler *= 1e-4;
smoothing = (smo & 0x800000 ? -1e-3 : 1e-3) * (smo & 0x7fffff);
smooth_cnt = (smo >> 24) & 0xff;
}
//---------------------------------------------------------------------------
void AshtechMBEN::code_block::dump(ostream& out) const
{
using gpstk::StringUtils::asString;
out << hex
<< "warn:" << (int)warning
<< " gb:" << (int)goodbad
<< " pol:" << (int)polarity_known
<< " qa:" << (int)qa_phase
<< dec
<< " phase:" << asString(full_phase, 1)
<< " range:" << asString(raw_range*1e3, 3)
<< " doppler:" << doppler
<< " smo:" << smoothing;
}
//---------------------------------------------------------------------------
float AshtechMBEN::code_block::snr(float chipRate) const throw()
{
const int n = 20000; // number of samples in 1 ms
const float m = 4.14; // magnitude of the carrier estimate;
float bw = 0.9 * chipRate; // equivalent noise bandwidth (Hz)
const float d = PI/(n*n*m*m*4.0);
float snr=0;
if (ireg)
{
snr = exp(((float)ireg)/25.0);
snr = snr*snr*bw*d;
snr = 10 * log10(snr);
}
return snr;
}
//---------------------------------------------------------------------------
void AshtechMBEN::dump(ostream& out) const throw()
{
ostringstream oss;
using gpstk::StringUtils::asString;
AshtechData::dump(oss);
oss << getName() << "1:"
<< " seq:" << 0.05 * seq
<< " left:" << (int)left
<< " prn:" << (int)svprn
<< " el:" << (int)el
<< " az:" << (int)az
<< " chid:" << (int)chid
<< " " << (ascii?"ascii":"bin")
<< endl;
oss << getName() << "2: ca";
ca.dump(oss);
oss << endl;
if (id == mpcId)
{
oss << getName() << "3: p1";
p1.dump(oss);
oss << endl;
oss << getName() << "4: p2";
p2.dump(oss);
oss << endl;
}
out << oss.str() << flush;
}
} // namespace gpstk
<|endoftext|> |
<commit_before>/*
This file is part of libkcal.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <typeinfo>
#include <stdlib.h>
#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>
#include <klocale.h>
#include <kdebug.h>
#include <kurl.h>
#include <kio/job.h>
#include <kstandarddirs.h>
#include <kabc/stdaddressbook.h>
#include "vcaldrag.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "exceptions.h"
#include "incidence.h"
#include "event.h"
#include "todo.h"
#include "journal.h"
#include "filestorage.h"
#include "libkcal/alarm.h"
#include <kresources/resourceconfigwidget.h>
#include "resourcekabcconfig.h"
#include "resourcekabc.h"
using namespace KCal;
extern "C"
{
KRES::ResourceConfigWidget *config_widget( QWidget *parent ) {
return new ResourceKABCConfig( parent, "Configure addressbook birthdays" );
}
KRES::Resource *resource( const KConfig *config ) {
return new ResourceKABC( config );
}
}
ResourceKABC::ResourceKABC( const KConfig* config )
: ResourceCalendar( config )
{
if ( config ) {
readConfig( config );
}
init();
}
ResourceKABC::ResourceKABC( )
: ResourceCalendar( 0 )
{
mAlarmDays = 1;
mAlarm = false;
init();
}
ResourceKABC::~ResourceKABC()
{
}
void ResourceKABC::init()
{
setType( "birthdays" );
mOpen = false;
setReadOnly( true );
mAddressbook = KABC::StdAddressBook::self();
connect( mAddressbook, SIGNAL(addressBookChanged(AddressBook*)), SLOT( reload() ) );
}
void ResourceKABC::readConfig( const KConfig *config )
{
mAlarmDays = config->readNumEntry( "AlarmDays", 1 );
mAlarm = config->readBoolEntry( "Alarm", false );
}
void ResourceKABC::writeConfig( KConfig *config )
{
ResourceCalendar::writeConfig( config );
config->writeEntry( "AlarmDays", mAlarmDays );
config->writeEntry( "Alarm", mAlarm );
}
bool ResourceKABC::doOpen()
{
kdDebug(5800) << "ResourceKABC::doOpen()" << endl;
mOpen = true;
return true;
}
bool ResourceKABC::load()
{
kdDebug() << "ResourceKABC::load()" << endl;
if ( !mOpen ) return true;
mCalendar.close();
// import from kabc
QDateTime birthdate;
QString summary;
KABC::AddressBook::Iterator it;
for ( it = mAddressbook->begin(); it != mAddressbook->end(); ++it ) {
if ( (*it).birthday().date().isValid() ) {
kdDebug() << "found a birthday " << (*it).birthday().toString() << endl;
QString name = (*it).nickName();
if (name.isEmpty()) name = (*it).realName();
summary = i18n("%1's birthday").arg( name );
birthdate = (*it).birthday();
Event *ev = new Event();
ev->setDtStart(birthdate);
ev->setDtEnd(birthdate);
ev->setHasEndDate(true);
ev->setFloats(true);
ev->setSummary(summary);
// Set the recurrence
Recurrence *vRecurrence = ev->recurrence();
vRecurrence->setRecurStart(birthdate);
vRecurrence->setYearly(Recurrence::rYearlyMonth,1,-1);
vRecurrence->addYearlyNum(birthdate.date().month());
ev->clearAlarms();
if ( mAlarm ) {
// Set the alarm
Alarm* vAlarm = ev->newAlarm();
vAlarm->setText(summary);
vAlarm->setTime(birthdate);
// 24 hours before
vAlarm->setStartOffset( -1440 * mAlarmDays );
vAlarm->setEnabled(true);
}
// insert category
ev->setCategories(i18n("Birthday"));
mCalendar.addEvent(ev);
kdDebug() << "imported " << birthdate.toString() << endl;
}
}
emit resourceChanged( this );
return true;
}
void ResourceKABC::setAlarm( bool a )
{
mAlarm = a;
}
bool ResourceKABC::alarm()
{
return mAlarm;
}
void ResourceKABC::setAlarmDays( int ad )
{
mAlarmDays = ad;
}
int ResourceKABC::alarmDays()
{
return mAlarmDays;
}
bool ResourceKABC::save()
{
// is always read only!
return true;
}
bool ResourceKABC::isSaving()
{
return false;
}
void ResourceKABC::doClose()
{
if ( !mOpen ) return;
mCalendar.close();
mOpen = false;
}
bool ResourceKABC::addEvent(Event *event)
{
// read only!
return false;
//mCalendar.addEvent( event );
}
void ResourceKABC::deleteEvent(Event *event)
{
// read only!
//kdDebug(5800) << "ResourceKABC::deleteEvent" << endl;
//mCalendar.deleteEvent( event );
}
Event *ResourceKABC::event( const QString &uid )
{
return mCalendar.event( uid );
}
QPtrList<Event> ResourceKABC::rawEventsForDate(const QDate &qd, bool sorted)
{
return mCalendar.rawEventsForDate( qd, sorted );
}
QPtrList<Event> ResourceKABC::rawEvents( const QDate &start, const QDate &end,
bool inclusive )
{
return mCalendar.rawEvents( start, end, inclusive );
}
QPtrList<Event> ResourceKABC::rawEventsForDate(const QDateTime &qdt)
{
return mCalendar.rawEventsForDate( qdt.date() );
}
QPtrList<Event> ResourceKABC::rawEvents()
{
return mCalendar.rawEvents();
}
bool ResourceKABC::addTodo(Todo *todo)
{
//read only!
return false;
//mCalendar.addTodo( todo );
}
void ResourceKABC::deleteTodo(Todo *todo)
{
// read only!
//mCalendar.deleteTodo( todo );
}
QPtrList<Todo> ResourceKABC::rawTodos()
{
return mCalendar.rawTodos();
}
Todo *ResourceKABC::todo( const QString &uid )
{
return mCalendar.todo( uid );
}
QPtrList<Todo> ResourceKABC::todos( const QDate &date )
{
return mCalendar.todos( date );
}
bool ResourceKABC::addJournal(Journal *journal)
{
// read only!
//kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;
//return mCalendar.addJournal( journal );
return false;
}
Journal *ResourceKABC::journal(const QDate &date)
{
// kdDebug(5800) << "ResourceKABC::journal() " << date.toString() << endl;
return mCalendar.journal( date );
}
Journal *ResourceKABC::journal(const QString &uid)
{
return mCalendar.journal( uid );
}
QPtrList<Journal> ResourceKABC::journals()
{
return mCalendar.journals();
}
Alarm::List ResourceKABC::alarmsTo( const QDateTime &to )
{
return mCalendar.alarmsTo( to );
}
Alarm::List ResourceKABC::alarms( const QDateTime &from, const QDateTime &to )
{
// kdDebug(5800) << "ResourceKABC::alarms(" << from.toString() << " - " << to.toString() << ")\n";
return mCalendar.alarms( from, to );
}
void ResourceKABC::update(IncidenceBase *)
{
}
void ResourceKABC::dump() const
{
ResourceCalendar::dump();
}
void ResourceKABC::reload()
{
load();
}
#include "resourcekabc.moc"
<commit_msg>reload with new settings, after new configuration<commit_after>/*
This file is part of libkcal.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <typeinfo>
#include <stdlib.h>
#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>
#include <klocale.h>
#include <kdebug.h>
#include <kurl.h>
#include <kio/job.h>
#include <kstandarddirs.h>
#include <kabc/stdaddressbook.h>
#include "vcaldrag.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "exceptions.h"
#include "incidence.h"
#include "event.h"
#include "todo.h"
#include "journal.h"
#include "filestorage.h"
#include "libkcal/alarm.h"
#include <kresources/resourceconfigwidget.h>
#include "resourcekabcconfig.h"
#include "resourcekabc.h"
using namespace KCal;
extern "C"
{
KRES::ResourceConfigWidget *config_widget( QWidget *parent ) {
return new ResourceKABCConfig( parent, "Configure addressbook birthdays" );
}
KRES::Resource *resource( const KConfig *config ) {
return new ResourceKABC( config );
}
}
ResourceKABC::ResourceKABC( const KConfig* config )
: ResourceCalendar( config )
{
if ( config ) {
readConfig( config );
}
init();
}
ResourceKABC::ResourceKABC( )
: ResourceCalendar( 0 )
{
mAlarmDays = 1;
mAlarm = false;
init();
}
ResourceKABC::~ResourceKABC()
{
}
void ResourceKABC::init()
{
setType( "birthdays" );
mOpen = false;
setReadOnly( true );
mAddressbook = KABC::StdAddressBook::self();
connect( mAddressbook, SIGNAL(addressBookChanged(AddressBook*)), SLOT( reload() ) );
}
void ResourceKABC::readConfig( const KConfig *config )
{
mAlarmDays = config->readNumEntry( "AlarmDays", 1 );
mAlarm = config->readBoolEntry( "Alarm", false );
}
void ResourceKABC::writeConfig( KConfig *config )
{
ResourceCalendar::writeConfig( config );
config->writeEntry( "AlarmDays", mAlarmDays );
config->writeEntry( "Alarm", mAlarm );
load();
}
bool ResourceKABC::doOpen()
{
kdDebug(5800) << "ResourceKABC::doOpen()" << endl;
mOpen = true;
return true;
}
bool ResourceKABC::load()
{
kdDebug() << "ResourceKABC::load()" << endl;
if ( !mOpen ) return true;
mCalendar.close();
// import from kabc
QDateTime birthdate;
QString summary;
KABC::AddressBook::Iterator it;
for ( it = mAddressbook->begin(); it != mAddressbook->end(); ++it ) {
if ( (*it).birthday().date().isValid() ) {
kdDebug() << "found a birthday " << (*it).birthday().toString() << endl;
QString name = (*it).nickName();
if (name.isEmpty()) name = (*it).realName();
summary = i18n("%1's birthday").arg( name );
birthdate = (*it).birthday();
Event *ev = new Event();
ev->setDtStart(birthdate);
ev->setDtEnd(birthdate);
ev->setHasEndDate(true);
ev->setFloats(true);
ev->setSummary(summary);
// Set the recurrence
Recurrence *vRecurrence = ev->recurrence();
vRecurrence->setRecurStart(birthdate);
vRecurrence->setYearly(Recurrence::rYearlyMonth,1,-1);
vRecurrence->addYearlyNum(birthdate.date().month());
ev->clearAlarms();
if ( mAlarm ) {
// Set the alarm
Alarm* vAlarm = ev->newAlarm();
vAlarm->setText(summary);
vAlarm->setTime(birthdate);
// 24 hours before
vAlarm->setStartOffset( -1440 * mAlarmDays );
vAlarm->setEnabled(true);
}
// insert category
ev->setCategories(i18n("Birthday"));
mCalendar.addEvent(ev);
kdDebug() << "imported " << birthdate.toString() << endl;
}
}
emit resourceChanged( this );
return true;
}
void ResourceKABC::setAlarm( bool a )
{
mAlarm = a;
}
bool ResourceKABC::alarm()
{
return mAlarm;
}
void ResourceKABC::setAlarmDays( int ad )
{
mAlarmDays = ad;
}
int ResourceKABC::alarmDays()
{
return mAlarmDays;
}
bool ResourceKABC::save()
{
// is always read only!
return true;
}
bool ResourceKABC::isSaving()
{
return false;
}
void ResourceKABC::doClose()
{
if ( !mOpen ) return;
mCalendar.close();
mOpen = false;
}
bool ResourceKABC::addEvent(Event *event)
{
// read only!
return false;
//mCalendar.addEvent( event );
}
void ResourceKABC::deleteEvent(Event *event)
{
// read only!
//kdDebug(5800) << "ResourceKABC::deleteEvent" << endl;
//mCalendar.deleteEvent( event );
}
Event *ResourceKABC::event( const QString &uid )
{
return mCalendar.event( uid );
}
QPtrList<Event> ResourceKABC::rawEventsForDate(const QDate &qd, bool sorted)
{
return mCalendar.rawEventsForDate( qd, sorted );
}
QPtrList<Event> ResourceKABC::rawEvents( const QDate &start, const QDate &end,
bool inclusive )
{
return mCalendar.rawEvents( start, end, inclusive );
}
QPtrList<Event> ResourceKABC::rawEventsForDate(const QDateTime &qdt)
{
return mCalendar.rawEventsForDate( qdt.date() );
}
QPtrList<Event> ResourceKABC::rawEvents()
{
return mCalendar.rawEvents();
}
bool ResourceKABC::addTodo(Todo *todo)
{
//read only!
return false;
//mCalendar.addTodo( todo );
}
void ResourceKABC::deleteTodo(Todo *todo)
{
// read only!
//mCalendar.deleteTodo( todo );
}
QPtrList<Todo> ResourceKABC::rawTodos()
{
return mCalendar.rawTodos();
}
Todo *ResourceKABC::todo( const QString &uid )
{
return mCalendar.todo( uid );
}
QPtrList<Todo> ResourceKABC::todos( const QDate &date )
{
return mCalendar.todos( date );
}
bool ResourceKABC::addJournal(Journal *journal)
{
// read only!
//kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;
//return mCalendar.addJournal( journal );
return false;
}
Journal *ResourceKABC::journal(const QDate &date)
{
// kdDebug(5800) << "ResourceKABC::journal() " << date.toString() << endl;
return mCalendar.journal( date );
}
Journal *ResourceKABC::journal(const QString &uid)
{
return mCalendar.journal( uid );
}
QPtrList<Journal> ResourceKABC::journals()
{
return mCalendar.journals();
}
Alarm::List ResourceKABC::alarmsTo( const QDateTime &to )
{
return mCalendar.alarmsTo( to );
}
Alarm::List ResourceKABC::alarms( const QDateTime &from, const QDateTime &to )
{
// kdDebug(5800) << "ResourceKABC::alarms(" << from.toString() << " - " << to.toString() << ")\n";
return mCalendar.alarms( from, to );
}
void ResourceKABC::update(IncidenceBase *)
{
}
void ResourceKABC::dump() const
{
ResourceCalendar::dump();
}
void ResourceKABC::reload()
{
load();
}
#include "resourcekabc.moc"
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrConvolutionEffect.h"
#include "gl/GrGLProgramStage.h"
#include "gl/GrGLSL.h"
#include "gl/GrGLTexture.h"
#include "GrProgramStageFactory.h"
class GrGLConvolutionEffect : public GrGLProgramStage {
public:
GrGLConvolutionEffect(const GrProgramStageFactory& factory,
const GrCustomStage& stage);
virtual void setupVariables(GrGLShaderBuilder* state,
int stage) SK_OVERRIDE;
virtual void emitVS(GrGLShaderBuilder* state,
const char* vertexCoords) SK_OVERRIDE;
virtual void emitFS(GrGLShaderBuilder* state,
const char* outputColor,
const char* inputColor,
const char* samplerName) SK_OVERRIDE;
virtual void initUniforms(const GrGLInterface*, int programID) SK_OVERRIDE;
virtual void setData(const GrGLInterface*,
const GrGLTexture&,
const GrCustomStage&,
int stageNum) SK_OVERRIDE;
static inline StageKey GenKey(const GrCustomStage&);
private:
int width() const { return Gr1DKernelEffect::WidthFromRadius(fRadius); }
int fRadius;
const GrGLShaderVar* fKernelVar;
GrGLint fKernelLocation;
const GrGLShaderVar* fImageIncrementVar;
GrGLint fImageIncrementLocation;
typedef GrGLProgramStage INHERITED;
};
GrGLConvolutionEffect::GrGLConvolutionEffect(const GrProgramStageFactory& factory,
const GrCustomStage& stage)
: GrGLProgramStage(factory)
, fKernelVar(NULL)
, fKernelLocation(0)
, fImageIncrementVar(NULL)
, fImageIncrementLocation(0) {
const GrConvolutionEffect& c =
static_cast<const GrConvolutionEffect&>(stage);
fRadius = c.radius();
}
void GrGLConvolutionEffect::setupVariables(GrGLShaderBuilder* state,
int stage) {
fImageIncrementVar = &state->addUniform(
GrGLShaderBuilder::kBoth_VariableLifetime,
kVec2f_GrSLType, "uImageIncrement", stage);
fKernelVar = &state->addUniform(
GrGLShaderBuilder::kFragment_VariableLifetime,
kFloat_GrSLType, "uKernel", stage, this->width());
fImageIncrementLocation = kUseUniform;
fKernelLocation = kUseUniform;
}
void GrGLConvolutionEffect::emitVS(GrGLShaderBuilder* state,
const char* vertexCoords) {
GrStringBuilder* code = &state->fVSCode;
code->appendf("\t\t%s -= vec2(%d, %d) * %s;\n",
vertexCoords, fRadius, fRadius,
fImageIncrementVar->getName().c_str());
}
void GrGLConvolutionEffect::emitFS(GrGLShaderBuilder* state,
const char* outputColor,
const char* inputColor,
const char* samplerName) {
GrStringBuilder* code = &state->fFSCode;
code->appendf("\t\tvec4 sum = vec4(0, 0, 0, 0);\n");
code->appendf("\t\tvec2 coord = %s;\n", state->fSampleCoords.c_str());
// Manually unroll loop because some drivers don't; yields 20-30% speedup.
for (int i = 0; i < this->width(); i++) {
GrStringBuilder index;
GrStringBuilder kernelIndex;
index.appendS32(i);
fKernelVar->appendArrayAccess(index.c_str(), &kernelIndex);
code->appendf("\t\tsum += ");
state->emitTextureLookup(samplerName, "coord");
code->appendf(" * %s;\n", kernelIndex.c_str());
code->appendf("\t\tcoord += %s;\n",
fImageIncrementVar->getName().c_str());
}
code->appendf("\t\t%s = sum%s;\n", outputColor, state->fModulate.c_str());
}
void GrGLConvolutionEffect::initUniforms(const GrGLInterface* gl,
int programID) {
GR_GL_CALL_RET(gl, fImageIncrementLocation,
GetUniformLocation(programID,
fImageIncrementVar->getName().c_str()));
GR_GL_CALL_RET(gl, fKernelLocation,
GetUniformLocation(programID, fKernelVar->getName().c_str()));
}
void GrGLConvolutionEffect::setData(const GrGLInterface* gl,
const GrGLTexture& texture,
const GrCustomStage& data,
int stageNum) {
const GrConvolutionEffect& conv =
static_cast<const GrConvolutionEffect&>(data);
// the code we generated was for a specific kernel radius
GrAssert(conv.radius() == fRadius);
float imageIncrement[2] = { 0 };
switch (conv.direction()) {
case Gr1DKernelEffect::kX_Direction:
imageIncrement[0] = 1.0f / texture.width();
break;
case Gr1DKernelEffect::kY_Direction:
imageIncrement[1] = 1.0f / texture.height();
break;
default:
GrCrash("Unknown filter direction.");
}
GR_GL_CALL(gl, Uniform2fv(fImageIncrementLocation, 1, imageIncrement));
GR_GL_CALL(gl, Uniform1fv(fKernelLocation, this->width(), conv.kernel()));
}
GrGLProgramStage::StageKey GrGLConvolutionEffect::GenKey(
const GrCustomStage& s) {
return static_cast<const GrConvolutionEffect&>(s).radius();
}
///////////////////////////////////////////////////////////////////////////////
GrConvolutionEffect::GrConvolutionEffect(Direction direction,
int radius,
const float* kernel)
: Gr1DKernelEffect(direction, radius) {
GrAssert(radius <= kMaxKernelRadius);
int width = this->width();
if (NULL != kernel) {
for (int i = 0; i < width; i++) {
fKernel[i] = kernel[i];
}
}
}
GrConvolutionEffect::~GrConvolutionEffect() {
}
const GrProgramStageFactory& GrConvolutionEffect::getFactory() const {
return GrTProgramStageFactory<GrConvolutionEffect>::getInstance();
}
bool GrConvolutionEffect::isEqual(const GrCustomStage& sBase) const {
const GrConvolutionEffect& s =
static_cast<const GrConvolutionEffect&>(sBase);
return (this->radius() == s.radius() &&
this->direction() == s.direction() &&
0 == memcmp(fKernel, s.fKernel, this->width() * sizeof(float)));
}
void GrConvolutionEffect::setGaussianKernel(float sigma) {
int width = this->width();
float sum = 0.0f;
float denom = 1.0f / (2.0f * sigma * sigma);
for (int i = 0; i < width; ++i) {
float x = static_cast<float>(i - this->radius());
// Note that the constant term (1/(sqrt(2*pi*sigma^2)) of the Gaussian
// is dropped here, since we renormalize the kernel below.
fKernel[i] = sk_float_exp(- x * x * denom);
sum += fKernel[i];
}
// Normalize the kernel
float scale = 1.0f / sum;
for (int i = 0; i < width; ++i) {
fKernel[i] *= scale;
}
}
<commit_msg>Remove local variable from GrConvolutionEffect GLSL code; reported to give marginal speedup on some Intel architectures. Original patch from kondapallykalyan@.<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrConvolutionEffect.h"
#include "gl/GrGLProgramStage.h"
#include "gl/GrGLSL.h"
#include "gl/GrGLTexture.h"
#include "GrProgramStageFactory.h"
class GrGLConvolutionEffect : public GrGLProgramStage {
public:
GrGLConvolutionEffect(const GrProgramStageFactory& factory,
const GrCustomStage& stage);
virtual void setupVariables(GrGLShaderBuilder* state,
int stage) SK_OVERRIDE;
virtual void emitVS(GrGLShaderBuilder* state,
const char* vertexCoords) SK_OVERRIDE;
virtual void emitFS(GrGLShaderBuilder* state,
const char* outputColor,
const char* inputColor,
const char* samplerName) SK_OVERRIDE;
virtual void initUniforms(const GrGLInterface*, int programID) SK_OVERRIDE;
virtual void setData(const GrGLInterface*,
const GrGLTexture&,
const GrCustomStage&,
int stageNum) SK_OVERRIDE;
static inline StageKey GenKey(const GrCustomStage&);
private:
int width() const { return Gr1DKernelEffect::WidthFromRadius(fRadius); }
int fRadius;
const GrGLShaderVar* fKernelVar;
GrGLint fKernelLocation;
const GrGLShaderVar* fImageIncrementVar;
GrGLint fImageIncrementLocation;
typedef GrGLProgramStage INHERITED;
};
GrGLConvolutionEffect::GrGLConvolutionEffect(const GrProgramStageFactory& factory,
const GrCustomStage& stage)
: GrGLProgramStage(factory)
, fKernelVar(NULL)
, fKernelLocation(0)
, fImageIncrementVar(NULL)
, fImageIncrementLocation(0) {
const GrConvolutionEffect& c =
static_cast<const GrConvolutionEffect&>(stage);
fRadius = c.radius();
}
void GrGLConvolutionEffect::setupVariables(GrGLShaderBuilder* state,
int stage) {
fImageIncrementVar = &state->addUniform(
GrGLShaderBuilder::kBoth_VariableLifetime,
kVec2f_GrSLType, "uImageIncrement", stage);
fKernelVar = &state->addUniform(
GrGLShaderBuilder::kFragment_VariableLifetime,
kFloat_GrSLType, "uKernel", stage, this->width());
fImageIncrementLocation = kUseUniform;
fKernelLocation = kUseUniform;
}
void GrGLConvolutionEffect::emitVS(GrGLShaderBuilder* state,
const char* vertexCoords) {
GrStringBuilder* code = &state->fVSCode;
code->appendf("\t\t%s -= vec2(%d, %d) * %s;\n",
vertexCoords, fRadius, fRadius,
fImageIncrementVar->getName().c_str());
}
void GrGLConvolutionEffect::emitFS(GrGLShaderBuilder* state,
const char* outputColor,
const char* inputColor,
const char* samplerName) {
GrStringBuilder* code = &state->fFSCode;
code->appendf("\t\t%s = vec4(0, 0, 0, 0);\n", outputColor);
code->appendf("\t\tvec2 coord = %s;\n", state->fSampleCoords.c_str());
// Manually unroll loop because some drivers don't; yields 20-30% speedup.
for (int i = 0; i < this->width(); i++) {
GrStringBuilder index;
GrStringBuilder kernelIndex;
index.appendS32(i);
fKernelVar->appendArrayAccess(index.c_str(), &kernelIndex);
code->appendf("\t\t%s += ", outputColor);
state->emitTextureLookup(samplerName, "coord");
code->appendf(" * %s;\n", kernelIndex.c_str());
code->appendf("\t\tcoord += %s;\n",
fImageIncrementVar->getName().c_str());
}
if (state->fModulate.size()) {
code->appendf("\t\t%s = %s%s;\n", outputColor, outputColor,
state->fModulate.c_str());
}
}
void GrGLConvolutionEffect::initUniforms(const GrGLInterface* gl,
int programID) {
GR_GL_CALL_RET(gl, fImageIncrementLocation,
GetUniformLocation(programID,
fImageIncrementVar->getName().c_str()));
GR_GL_CALL_RET(gl, fKernelLocation,
GetUniformLocation(programID, fKernelVar->getName().c_str()));
}
void GrGLConvolutionEffect::setData(const GrGLInterface* gl,
const GrGLTexture& texture,
const GrCustomStage& data,
int stageNum) {
const GrConvolutionEffect& conv =
static_cast<const GrConvolutionEffect&>(data);
// the code we generated was for a specific kernel radius
GrAssert(conv.radius() == fRadius);
float imageIncrement[2] = { 0 };
switch (conv.direction()) {
case Gr1DKernelEffect::kX_Direction:
imageIncrement[0] = 1.0f / texture.width();
break;
case Gr1DKernelEffect::kY_Direction:
imageIncrement[1] = 1.0f / texture.height();
break;
default:
GrCrash("Unknown filter direction.");
}
GR_GL_CALL(gl, Uniform2fv(fImageIncrementLocation, 1, imageIncrement));
GR_GL_CALL(gl, Uniform1fv(fKernelLocation, this->width(), conv.kernel()));
}
GrGLProgramStage::StageKey GrGLConvolutionEffect::GenKey(
const GrCustomStage& s) {
return static_cast<const GrConvolutionEffect&>(s).radius();
}
///////////////////////////////////////////////////////////////////////////////
GrConvolutionEffect::GrConvolutionEffect(Direction direction,
int radius,
const float* kernel)
: Gr1DKernelEffect(direction, radius) {
GrAssert(radius <= kMaxKernelRadius);
int width = this->width();
if (NULL != kernel) {
for (int i = 0; i < width; i++) {
fKernel[i] = kernel[i];
}
}
}
GrConvolutionEffect::~GrConvolutionEffect() {
}
const GrProgramStageFactory& GrConvolutionEffect::getFactory() const {
return GrTProgramStageFactory<GrConvolutionEffect>::getInstance();
}
bool GrConvolutionEffect::isEqual(const GrCustomStage& sBase) const {
const GrConvolutionEffect& s =
static_cast<const GrConvolutionEffect&>(sBase);
return (this->radius() == s.radius() &&
this->direction() == s.direction() &&
0 == memcmp(fKernel, s.fKernel, this->width() * sizeof(float)));
}
void GrConvolutionEffect::setGaussianKernel(float sigma) {
int width = this->width();
float sum = 0.0f;
float denom = 1.0f / (2.0f * sigma * sigma);
for (int i = 0; i < width; ++i) {
float x = static_cast<float>(i - this->radius());
// Note that the constant term (1/(sqrt(2*pi*sigma^2)) of the Gaussian
// is dropped here, since we renormalize the kernel below.
fKernel[i] = sk_float_exp(- x * x * denom);
sum += fKernel[i];
}
// Normalize the kernel
float scale = 1.0f / sum;
for (int i = 0; i < width; ++i) {
fKernel[i] *= scale;
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "LeapSerialBench.h"
#include "Encryption.h"
#include <iostream>
#include <memory>
struct BenchmarkEntry {
BenchmarkEntry(const char* name, IBenchmark* benchmark) :
name(name),
benchmark(benchmark)
{}
const char* name;
std::unique_ptr<IBenchmark> benchmark;
};
static BenchmarkEntry benchmarks[] = {
{ "encryption", new Encryption }
};
static void PrintUsage(void) {
std::cout << "Available benchmarks:" << std::endl;
for (const auto& benchmark : benchmarks)
std::cout << ' ' << benchmark.name << std::endl;
}
int main(int argc, const char* argv[]) {
if (argc != 2)
return PrintUsage(), -1;
for(auto& cur : benchmarks)
if (!strcmp(argv[1], cur.name))
return cur.benchmark->Benchmark(std::cout);
return -1;
}
<commit_msg>Oh my god why are there so many missing includes<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "LeapSerialBench.h"
#include "Encryption.h"
#include <iostream>
#include <memory>
#include <string.h>
struct BenchmarkEntry {
BenchmarkEntry(const char* name, IBenchmark* benchmark) :
name(name),
benchmark(benchmark)
{}
const char* name;
std::unique_ptr<IBenchmark> benchmark;
};
static BenchmarkEntry benchmarks[] = {
{ "encryption", new Encryption }
};
static void PrintUsage(void) {
std::cout << "Available benchmarks:" << std::endl;
for (const auto& benchmark : benchmarks)
std::cout << ' ' << benchmark.name << std::endl;
}
int main(int argc, const char* argv[]) {
if (argc != 2)
return PrintUsage(), -1;
for(auto& cur : benchmarks)
if (!strcmp(argv[1], cur.name))
return cur.benchmark->Benchmark(std::cout);
return -1;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2008 Torsten Rahn <rahn@kde.org>
This file is part of the KDE project
This library is free software you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "GeoSceneLayer.h"
#include <limits>
#include "GeoSceneFilter.h"
#include "GeoSceneTypes.h"
namespace Marble
{
// FIXME: Filters are a Dataset.
GeoSceneAbstractDataset::GeoSceneAbstractDataset( const QString& name )
: m_name( name ),
m_fileFormat(),
m_expire( std::numeric_limits<int>::max() )
{
}
QString GeoSceneAbstractDataset::name() const
{
return m_name;
}
QString GeoSceneAbstractDataset::fileFormat() const
{
return m_fileFormat;
}
void GeoSceneAbstractDataset::setFileFormat( const QString& fileFormat )
{
m_fileFormat = fileFormat;
}
int GeoSceneAbstractDataset::expire() const
{
return m_expire;
}
void GeoSceneAbstractDataset::setExpire( int expire )
{
m_expire = expire;
}
class GeoSceneLayerPrivate
{
public:
GeoSceneLayerPrivate(){}
~GeoSceneLayerPrivate(){}
const char* nodeType() const
{
return GeoSceneTypes::GeoSceneLayerType;
}
};
GeoSceneLayer::GeoSceneLayer( const QString& name )
: m_filter( 0 ),
m_name( name ),
m_backend(),
m_role(),
m_tiled( true ),
d( new GeoSceneLayerPrivate )
{
}
GeoSceneLayer::~GeoSceneLayer()
{
qDeleteAll( m_datasets );
}
const char* GeoSceneLayer::nodeType() const
{
return d->nodeType();
}
void GeoSceneLayer::addDataset( GeoSceneAbstractDataset* dataset )
{
// Remove any dataset that has the same name
QVector<GeoSceneAbstractDataset *>::iterator it = m_datasets.begin();
while (it != m_datasets.end()) {
GeoSceneAbstractDataset * currentAbstractDataset = *it;
if ( currentAbstractDataset->name() == dataset->name() ) {
delete currentAbstractDataset;
it = m_datasets.erase(it);
break;
}
else {
++it;
}
}
if ( dataset ) {
m_datasets.append( dataset );
}
}
const GeoSceneAbstractDataset* GeoSceneLayer::dataset( const QString& name ) const
{
GeoSceneAbstractDataset* dataset = 0;
QVector<GeoSceneAbstractDataset*>::const_iterator it = m_datasets.constBegin();
QVector<GeoSceneAbstractDataset*>::const_iterator end = m_datasets.constEnd();
for (; it != end; ++it) {
if ( (*it)->name() == name ) {
dataset = *it;
break;
}
}
return dataset;
}
// implement non-const method by means of const method,
// for details, see "Effective C++" (third edition)
GeoSceneAbstractDataset* GeoSceneLayer::dataset( const QString& name )
{
return const_cast<GeoSceneAbstractDataset*>
( static_cast<GeoSceneLayer const *>( this )->dataset( name ));
}
const GeoSceneAbstractDataset * GeoSceneLayer::groundDataset() const
{
if ( m_datasets.isEmpty() )
return 0;
return m_datasets.first();
}
// implement non-const method by means of const method,
// for details, see "Effective C++" (third edition)
GeoSceneAbstractDataset * GeoSceneLayer::groundDataset()
{
return const_cast<GeoSceneAbstractDataset*>
( static_cast<GeoSceneLayer const *>( this )->groundDataset() );
}
QVector<GeoSceneAbstractDataset *> GeoSceneLayer::datasets() const
{
return m_datasets;
}
QString GeoSceneLayer::name() const
{
return m_name;
}
QString GeoSceneLayer::backend() const
{
return m_backend;
}
void GeoSceneLayer::setBackend( const QString& backend )
{
m_backend = backend;
}
bool GeoSceneLayer::isTiled() const
{
return m_tiled;
}
void GeoSceneLayer::setTiled( bool tiled )
{
m_tiled = tiled;
}
QString GeoSceneLayer::role() const
{
return m_role;
}
void GeoSceneLayer::setRole( const QString& role )
{
m_role = role;
}
const GeoSceneFilter* GeoSceneLayer::filter() const
{
return m_filter;
}
GeoSceneFilter* GeoSceneLayer::filter()
{
return m_filter;
}
void GeoSceneLayer::addFilter( GeoSceneFilter * filter )
{
m_filter = filter;
}
void GeoSceneLayer::removeFilter( GeoSceneFilter * filter )
{
if ( filter == m_filter ) {
m_filter = 0;
}
}
}
<commit_msg>Fix mem leak<commit_after>/*
Copyright (C) 2008 Torsten Rahn <rahn@kde.org>
This file is part of the KDE project
This library is free software you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "GeoSceneLayer.h"
#include <limits>
#include "GeoSceneFilter.h"
#include "GeoSceneTypes.h"
namespace Marble
{
// FIXME: Filters are a Dataset.
GeoSceneAbstractDataset::GeoSceneAbstractDataset( const QString& name )
: m_name( name ),
m_fileFormat(),
m_expire( std::numeric_limits<int>::max() )
{
}
QString GeoSceneAbstractDataset::name() const
{
return m_name;
}
QString GeoSceneAbstractDataset::fileFormat() const
{
return m_fileFormat;
}
void GeoSceneAbstractDataset::setFileFormat( const QString& fileFormat )
{
m_fileFormat = fileFormat;
}
int GeoSceneAbstractDataset::expire() const
{
return m_expire;
}
void GeoSceneAbstractDataset::setExpire( int expire )
{
m_expire = expire;
}
class GeoSceneLayerPrivate
{
public:
GeoSceneLayerPrivate(){}
~GeoSceneLayerPrivate(){}
const char* nodeType() const
{
return GeoSceneTypes::GeoSceneLayerType;
}
};
GeoSceneLayer::GeoSceneLayer( const QString& name )
: m_filter( 0 ),
m_name( name ),
m_backend(),
m_role(),
m_tiled( true ),
d( new GeoSceneLayerPrivate )
{
}
GeoSceneLayer::~GeoSceneLayer()
{
qDeleteAll( m_datasets );
delete d;
}
const char* GeoSceneLayer::nodeType() const
{
return d->nodeType();
}
void GeoSceneLayer::addDataset( GeoSceneAbstractDataset* dataset )
{
// Remove any dataset that has the same name
QVector<GeoSceneAbstractDataset *>::iterator it = m_datasets.begin();
while (it != m_datasets.end()) {
GeoSceneAbstractDataset * currentAbstractDataset = *it;
if ( currentAbstractDataset->name() == dataset->name() ) {
delete currentAbstractDataset;
it = m_datasets.erase(it);
break;
}
else {
++it;
}
}
if ( dataset ) {
m_datasets.append( dataset );
}
}
const GeoSceneAbstractDataset* GeoSceneLayer::dataset( const QString& name ) const
{
GeoSceneAbstractDataset* dataset = 0;
QVector<GeoSceneAbstractDataset*>::const_iterator it = m_datasets.constBegin();
QVector<GeoSceneAbstractDataset*>::const_iterator end = m_datasets.constEnd();
for (; it != end; ++it) {
if ( (*it)->name() == name ) {
dataset = *it;
break;
}
}
return dataset;
}
// implement non-const method by means of const method,
// for details, see "Effective C++" (third edition)
GeoSceneAbstractDataset* GeoSceneLayer::dataset( const QString& name )
{
return const_cast<GeoSceneAbstractDataset*>
( static_cast<GeoSceneLayer const *>( this )->dataset( name ));
}
const GeoSceneAbstractDataset * GeoSceneLayer::groundDataset() const
{
if ( m_datasets.isEmpty() )
return 0;
return m_datasets.first();
}
// implement non-const method by means of const method,
// for details, see "Effective C++" (third edition)
GeoSceneAbstractDataset * GeoSceneLayer::groundDataset()
{
return const_cast<GeoSceneAbstractDataset*>
( static_cast<GeoSceneLayer const *>( this )->groundDataset() );
}
QVector<GeoSceneAbstractDataset *> GeoSceneLayer::datasets() const
{
return m_datasets;
}
QString GeoSceneLayer::name() const
{
return m_name;
}
QString GeoSceneLayer::backend() const
{
return m_backend;
}
void GeoSceneLayer::setBackend( const QString& backend )
{
m_backend = backend;
}
bool GeoSceneLayer::isTiled() const
{
return m_tiled;
}
void GeoSceneLayer::setTiled( bool tiled )
{
m_tiled = tiled;
}
QString GeoSceneLayer::role() const
{
return m_role;
}
void GeoSceneLayer::setRole( const QString& role )
{
m_role = role;
}
const GeoSceneFilter* GeoSceneLayer::filter() const
{
return m_filter;
}
GeoSceneFilter* GeoSceneLayer::filter()
{
return m_filter;
}
void GeoSceneLayer::addFilter( GeoSceneFilter * filter )
{
m_filter = filter;
}
void GeoSceneLayer::removeFilter( GeoSceneFilter * filter )
{
if ( filter == m_filter ) {
m_filter = 0;
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2008 Torsten Rahn <rahn@kde.org>
This file is part of the KDE project
This library is free software you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "GeoSceneLayer.h"
#include <limits>
namespace Marble
{
// FIXME: Filters are a Dataset.
GeoSceneAbstractDataset::GeoSceneAbstractDataset( const QString& name )
: m_name( name ),
m_fileFormat( "" ),
m_expire( std::numeric_limits<int>::max() )
{
}
QString GeoSceneAbstractDataset::name() const
{
return m_name;
}
QString GeoSceneAbstractDataset::fileFormat() const
{
return m_fileFormat;
}
void GeoSceneAbstractDataset::setFileFormat( const QString& fileFormat )
{
m_fileFormat = fileFormat;
}
int GeoSceneAbstractDataset::expire() const
{
return m_expire;
}
void GeoSceneAbstractDataset::setExpire( int expire )
{
m_expire = expire;
}
GeoSceneLayer::GeoSceneLayer( const QString& name )
: m_filter( 0 ),
m_name( name ),
m_backend( "" ),
m_role( "" ),
m_tiled( true )
{
/* NOOP */
}
GeoSceneLayer::~GeoSceneLayer()
{
qDeleteAll( m_datasets );
}
void GeoSceneLayer::addDataset( GeoSceneAbstractDataset* dataset )
{
// Remove any dataset that has the same name
QVector<GeoSceneAbstractDataset *>::iterator it = m_datasets.begin();
while (it != m_datasets.end()) {
GeoSceneAbstractDataset * currentAbstractDataset = *it;
if ( currentAbstractDataset->name() == dataset->name() ) {
delete currentAbstractDataset;
it = m_datasets.erase(it);
}
else {
++it;
}
}
if ( dataset ) {
m_datasets.append( dataset );
}
}
GeoSceneAbstractDataset* GeoSceneLayer::dataset( const QString& name )
{
GeoSceneAbstractDataset* dataset = 0;
QVector<GeoSceneAbstractDataset*>::const_iterator it = m_datasets.constBegin();
for (; it != m_datasets.constEnd(); ++it) {
if ( (*it)->name() == name )
dataset = *it;
}
if ( dataset ) {
Q_ASSERT(dataset->name() == name);
return dataset;
}
// dataset = new GeoSceneAbstractDataset( name );
// addDataset( dataset );
return dataset;
}
GeoSceneAbstractDataset * GeoSceneLayer::groundDataset() const
{
if ( m_datasets.isEmpty() )
return 0;
return m_datasets.first();
}
QVector<GeoSceneAbstractDataset *> GeoSceneLayer::datasets() const
{
return m_datasets;
}
QString GeoSceneLayer::name() const
{
return m_name;
}
QString GeoSceneLayer::backend() const
{
return m_backend;
}
void GeoSceneLayer::setBackend( const QString& backend )
{
m_backend = backend;
}
bool GeoSceneLayer::isTiled() const
{
return m_tiled;
}
void GeoSceneLayer::setTiled( bool tiled )
{
m_tiled = tiled;
}
QString GeoSceneLayer::role() const
{
return m_role;
}
void GeoSceneLayer::setRole( const QString& role )
{
m_role = role;
}
GeoSceneFilter* GeoSceneLayer::filter()
{
return m_filter;
}
void GeoSceneLayer::addFilter( GeoSceneFilter * filter )
{
m_filter = filter;
}
void GeoSceneLayer::removeFilter( GeoSceneFilter * filter )
{
if( filter == m_filter ) { m_filter = 0; }
}
}
<commit_msg>Just use QString default ctor.<commit_after>/*
Copyright (C) 2008 Torsten Rahn <rahn@kde.org>
This file is part of the KDE project
This library is free software you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "GeoSceneLayer.h"
#include <limits>
namespace Marble
{
// FIXME: Filters are a Dataset.
GeoSceneAbstractDataset::GeoSceneAbstractDataset( const QString& name )
: m_name( name ),
m_fileFormat(),
m_expire( std::numeric_limits<int>::max() )
{
}
QString GeoSceneAbstractDataset::name() const
{
return m_name;
}
QString GeoSceneAbstractDataset::fileFormat() const
{
return m_fileFormat;
}
void GeoSceneAbstractDataset::setFileFormat( const QString& fileFormat )
{
m_fileFormat = fileFormat;
}
int GeoSceneAbstractDataset::expire() const
{
return m_expire;
}
void GeoSceneAbstractDataset::setExpire( int expire )
{
m_expire = expire;
}
GeoSceneLayer::GeoSceneLayer( const QString& name )
: m_filter( 0 ),
m_name( name ),
m_backend(),
m_role(),
m_tiled( true )
{
}
GeoSceneLayer::~GeoSceneLayer()
{
qDeleteAll( m_datasets );
}
void GeoSceneLayer::addDataset( GeoSceneAbstractDataset* dataset )
{
// Remove any dataset that has the same name
QVector<GeoSceneAbstractDataset *>::iterator it = m_datasets.begin();
while (it != m_datasets.end()) {
GeoSceneAbstractDataset * currentAbstractDataset = *it;
if ( currentAbstractDataset->name() == dataset->name() ) {
delete currentAbstractDataset;
it = m_datasets.erase(it);
}
else {
++it;
}
}
if ( dataset ) {
m_datasets.append( dataset );
}
}
GeoSceneAbstractDataset* GeoSceneLayer::dataset( const QString& name )
{
GeoSceneAbstractDataset* dataset = 0;
QVector<GeoSceneAbstractDataset*>::const_iterator it = m_datasets.constBegin();
for (; it != m_datasets.constEnd(); ++it) {
if ( (*it)->name() == name )
dataset = *it;
}
if ( dataset ) {
Q_ASSERT(dataset->name() == name);
return dataset;
}
// dataset = new GeoSceneAbstractDataset( name );
// addDataset( dataset );
return dataset;
}
GeoSceneAbstractDataset * GeoSceneLayer::groundDataset() const
{
if ( m_datasets.isEmpty() )
return 0;
return m_datasets.first();
}
QVector<GeoSceneAbstractDataset *> GeoSceneLayer::datasets() const
{
return m_datasets;
}
QString GeoSceneLayer::name() const
{
return m_name;
}
QString GeoSceneLayer::backend() const
{
return m_backend;
}
void GeoSceneLayer::setBackend( const QString& backend )
{
m_backend = backend;
}
bool GeoSceneLayer::isTiled() const
{
return m_tiled;
}
void GeoSceneLayer::setTiled( bool tiled )
{
m_tiled = tiled;
}
QString GeoSceneLayer::role() const
{
return m_role;
}
void GeoSceneLayer::setRole( const QString& role )
{
m_role = role;
}
GeoSceneFilter* GeoSceneLayer::filter()
{
return m_filter;
}
void GeoSceneLayer::addFilter( GeoSceneFilter * filter )
{
m_filter = filter;
}
void GeoSceneLayer::removeFilter( GeoSceneFilter * filter )
{
if( filter == m_filter ) { m_filter = 0; }
}
}
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decoders/RafDecoder.h"
#include "common/Common.h" // for uint32, ushort16
#include "common/Point.h" // for iPoint2D, iRecta...
#include "decoders/RawDecoderException.h" // for RawDecoderExcept...
#include "decompressors/UncompressedDecompressor.h" // for UncompressedDeco...
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for getHostEndianness
#include "metadata/BlackArea.h" // for BlackArea
#include "metadata/Camera.h" // for Camera, Hints
#include "metadata/CameraMetaData.h" // for CameraMetaData
#include "metadata/CameraSensorInfo.h" // for CameraSensorInfo
#include "metadata/ColorFilterArray.h" // for ColorFilterArray
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffIFD.h" // for TiffRootIFD, Tif...
#include "tiff/TiffTag.h" // for TiffTag::FUJIOLDWB
#include <cstdio> // for size_t
#include <cstring> // for memcmp
#include <memory> // for unique_ptr, allo...
#include <string> // for string
#include <vector> // for vector
using namespace std;
namespace RawSpeed {
bool RafDecoder::isRAF(Buffer* input) {
static const char magic[] = "FUJIFILMCCD-RAW ";
static const size_t magic_size = sizeof(magic) - 1; // excluding \0
const unsigned char* data = input->getData(0, magic_size);
return 0 == memcmp(&data[0], magic, magic_size);
}
RawImage RafDecoder::decodeRawInternal() {
auto raw = mRootIFD->getIFDWithTag(FUJI_STRIPOFFSETS);
uint32 height = 0;
uint32 width = 0;
if (raw->hasEntry(FUJI_RAWIMAGEFULLHEIGHT)) {
height = raw->getEntry(FUJI_RAWIMAGEFULLHEIGHT)->getU32();
width = raw->getEntry(FUJI_RAWIMAGEFULLWIDTH)->getU32();
} else if (raw->hasEntry(IMAGEWIDTH)) {
TiffEntry *e = raw->getEntry(IMAGEWIDTH);
height = e->getU16(0);
width = e->getU16(1);
} else
ThrowRDE("Unable to locate image size");
if (raw->hasEntry(FUJI_LAYOUT)) {
TiffEntry *e = raw->getEntry(FUJI_LAYOUT);
alt_layout = !(e->getByte(0) >> 7);
}
TiffEntry *offsets = raw->getEntry(FUJI_STRIPOFFSETS);
TiffEntry *counts = raw->getEntry(FUJI_STRIPBYTECOUNTS);
if (offsets->count != 1 || counts->count != 1)
ThrowRDE("Multiple Strips found: %u %u", offsets->count, counts->count);
int bps = 16;
if (raw->hasEntry(FUJI_BITSPERSAMPLE))
bps = raw->getEntry(FUJI_BITSPERSAMPLE)->getU32();
// x-trans sensors report 14bpp, but data isn't packed so read as 16bpp
if (bps == 14) bps = 16;
// Some fuji SuperCCD cameras include a second raw image next to the first one
// that is identical but darker to the first. The two combined can produce
// a higher dynamic range image. Right now we're ignoring it.
bool double_width = hints.has("double_width_unpacked");
mRaw->dim = iPoint2D(width*(double_width ? 2 : 1), height);
mRaw->createData();
ByteStream input = offsets->getRootIfdData();
input.setPosition(offsets->getU32());
UncompressedDecompressor u(input, mRaw, uncorrectedRawValues);
iPoint2D pos(0, 0);
if (counts->getU32()*8/(width*height) < 10) {
ThrowRDE("Don't know how to decode compressed images");
} else if (double_width) {
u.decode16BitRawUnpacked(width * 2, height);
} else if (input.isInNativeByteOrder() == (getHostEndianness() == big)) {
u.decode16BitRawBEunpacked(width, height);
} else {
if (hints.has("jpeg32_bitorder")) {
u.readUncompressedRaw(mRaw->dim, pos, width * bps / 8, bps,
BitOrder_Jpeg32);
} else {
u.readUncompressedRaw(mRaw->dim, pos, width * bps / 8, bps,
BitOrder_Plain);
}
}
return mRaw;
}
void RafDecoder::checkSupportInternal(const CameraMetaData* meta) {
if (!this->checkCameraSupported(meta, mRootIFD->getID(), ""))
ThrowRDE("Unknown camera. Will not guess.");
}
void RafDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {
int iso = 0;
if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS))
iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getU32();
mRaw->metadata.isoSpeed = iso;
// This is where we'd normally call setMetaData but since we may still need
// to rotate the image for SuperCCD cameras we do everything ourselves
auto id = mRootIFD->getID();
const Camera* cam = meta->getCamera(id.make, id.model, "");
if (!cam)
ThrowRDE("Couldn't find camera");
iPoint2D new_size(mRaw->dim);
iPoint2D crop_offset = iPoint2D(0,0);
if (applyCrop) {
new_size = cam->cropSize;
crop_offset = cam->cropPos;
bool double_width = hints.has("double_width_unpacked");
// If crop size is negative, use relative cropping
if (new_size.x <= 0)
new_size.x = mRaw->dim.x / (double_width ? 2 : 1) - cam->cropPos.x + new_size.x;
else
new_size.x /= (double_width ? 2 : 1);
if (new_size.y <= 0)
new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y;
}
bool rotate = hints.has("fuji_rotate");
rotate = rotate & fujiRotate;
// Rotate 45 degrees - could be multithreaded.
if (rotate && !this->uncorrectedRawValues) {
// Calculate the 45 degree rotated size;
uint32 rotatedsize;
uint32 rotationPos;
if (alt_layout) {
rotatedsize = new_size.y+new_size.x/2;
rotationPos = new_size.x/2 - 1;
}
else {
rotatedsize = new_size.x+new_size.y/2;
rotationPos = new_size.x - 1;
}
iPoint2D final_size(rotatedsize, rotatedsize-1);
RawImage rotated = RawImage::create(final_size, TYPE_USHORT16, 1);
rotated->clearArea(iRectangle2D(iPoint2D(0,0), rotated->dim));
rotated->metadata = mRaw->metadata;
rotated->metadata.fujiRotationPos = rotationPos;
int dest_pitch = (int)rotated->pitch / 2;
auto *dst = (ushort16 *)rotated->getData(0, 0);
for (int y = 0; y < new_size.y; y++) {
auto *src = (ushort16 *)mRaw->getData(crop_offset.x, crop_offset.y + y);
for (int x = 0; x < new_size.x; x++) {
int h, w;
if (alt_layout) { // Swapped x and y
h = rotatedsize - (new_size.y + 1 - y + (x >> 1));
w = ((x+1) >> 1) + y;
} else {
h = new_size.x - 1 - x + (y >> 1);
w = ((y+1) >> 1) + x;
}
if (h < rotated->dim.y && w < rotated->dim.x)
dst[w + h * dest_pitch] = src[x];
else
ThrowRDE("Trying to write out of bounds");
}
}
mRaw = rotated;
} else if (applyCrop) {
mRaw->subFrame(iRectangle2D(crop_offset, new_size));
}
const CameraSensorInfo *sensor = cam->getSensorInfo(iso);
mRaw->blackLevel = sensor->mBlackLevel;
// at least the (bayer sensor) X100 comes with a tag like this:
if (mRootIFD->hasEntryRecursive(FUJI_BLACKLEVEL)) {
TiffEntry* sep_black = mRootIFD->getEntryRecursive(FUJI_BLACKLEVEL);
if (sep_black->count == 4)
{
for(int k=0;k<4;k++)
mRaw->blackLevelSeparate[k] = sep_black->getU32(k);
} else if (sep_black->count == 36) {
for (int k = 0; k < 4; k++)
mRaw->blackLevelSeparate[k] = 0;
for (int y = 0; y < 6; y++)
for (int x = 0; x < 6; x++)
mRaw->blackLevelSeparate[2 * (y % 2) + (x % 2)] +=
sep_black->getU32(6 * y + x);
for (int k = 0; k < 4; k++)
mRaw->blackLevelSeparate[k] /= 9;
}
}
mRaw->whitePoint = sensor->mWhiteLevel;
mRaw->blackAreas = cam->blackAreas;
mRaw->cfa = cam->cfa;
mRaw->metadata.canonical_make = cam->canonical_make;
mRaw->metadata.canonical_model = cam->canonical_model;
mRaw->metadata.canonical_alias = cam->canonical_alias;
mRaw->metadata.canonical_id = cam->canonical_id;
mRaw->metadata.make = id.make;
mRaw->metadata.model = id.model;
if (mRootIFD->hasEntryRecursive(FUJI_WB_GRBLEVELS)) {
TiffEntry *wb = mRootIFD->getEntryRecursive(FUJI_WB_GRBLEVELS);
if (wb->count == 3) {
mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);
mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);
mRaw->metadata.wbCoeffs[2] = wb->getFloat(2);
}
} else if (mRootIFD->hasEntryRecursive(FUJIOLDWB)) {
TiffEntry *wb = mRootIFD->getEntryRecursive(FUJIOLDWB);
if (wb->count == 8) {
mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);
mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);
mRaw->metadata.wbCoeffs[2] = wb->getFloat(3);
}
}
}
} // namespace RawSpeed
<commit_msg>RafDecoder: sepblack: slight tidying<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decoders/RafDecoder.h"
#include "common/Common.h" // for uint32, ushort16
#include "common/Point.h" // for iPoint2D, iRecta...
#include "decoders/RawDecoderException.h" // for RawDecoderExcept...
#include "decompressors/UncompressedDecompressor.h" // for UncompressedDeco...
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for getHostEndianness
#include "metadata/BlackArea.h" // for BlackArea
#include "metadata/Camera.h" // for Camera, Hints
#include "metadata/CameraMetaData.h" // for CameraMetaData
#include "metadata/CameraSensorInfo.h" // for CameraSensorInfo
#include "metadata/ColorFilterArray.h" // for ColorFilterArray
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffIFD.h" // for TiffRootIFD, Tif...
#include "tiff/TiffTag.h" // for TiffTag::FUJIOLDWB
#include <cstdio> // for size_t
#include <cstring> // for memcmp
#include <memory> // for unique_ptr, allo...
#include <string> // for string
#include <vector> // for vector
using namespace std;
namespace RawSpeed {
bool RafDecoder::isRAF(Buffer* input) {
static const char magic[] = "FUJIFILMCCD-RAW ";
static const size_t magic_size = sizeof(magic) - 1; // excluding \0
const unsigned char* data = input->getData(0, magic_size);
return 0 == memcmp(&data[0], magic, magic_size);
}
RawImage RafDecoder::decodeRawInternal() {
auto raw = mRootIFD->getIFDWithTag(FUJI_STRIPOFFSETS);
uint32 height = 0;
uint32 width = 0;
if (raw->hasEntry(FUJI_RAWIMAGEFULLHEIGHT)) {
height = raw->getEntry(FUJI_RAWIMAGEFULLHEIGHT)->getU32();
width = raw->getEntry(FUJI_RAWIMAGEFULLWIDTH)->getU32();
} else if (raw->hasEntry(IMAGEWIDTH)) {
TiffEntry *e = raw->getEntry(IMAGEWIDTH);
height = e->getU16(0);
width = e->getU16(1);
} else
ThrowRDE("Unable to locate image size");
if (raw->hasEntry(FUJI_LAYOUT)) {
TiffEntry *e = raw->getEntry(FUJI_LAYOUT);
alt_layout = !(e->getByte(0) >> 7);
}
TiffEntry *offsets = raw->getEntry(FUJI_STRIPOFFSETS);
TiffEntry *counts = raw->getEntry(FUJI_STRIPBYTECOUNTS);
if (offsets->count != 1 || counts->count != 1)
ThrowRDE("Multiple Strips found: %u %u", offsets->count, counts->count);
int bps = 16;
if (raw->hasEntry(FUJI_BITSPERSAMPLE))
bps = raw->getEntry(FUJI_BITSPERSAMPLE)->getU32();
// x-trans sensors report 14bpp, but data isn't packed so read as 16bpp
if (bps == 14) bps = 16;
// Some fuji SuperCCD cameras include a second raw image next to the first one
// that is identical but darker to the first. The two combined can produce
// a higher dynamic range image. Right now we're ignoring it.
bool double_width = hints.has("double_width_unpacked");
mRaw->dim = iPoint2D(width*(double_width ? 2 : 1), height);
mRaw->createData();
ByteStream input = offsets->getRootIfdData();
input.setPosition(offsets->getU32());
UncompressedDecompressor u(input, mRaw, uncorrectedRawValues);
iPoint2D pos(0, 0);
if (counts->getU32()*8/(width*height) < 10) {
ThrowRDE("Don't know how to decode compressed images");
} else if (double_width) {
u.decode16BitRawUnpacked(width * 2, height);
} else if (input.isInNativeByteOrder() == (getHostEndianness() == big)) {
u.decode16BitRawBEunpacked(width, height);
} else {
if (hints.has("jpeg32_bitorder")) {
u.readUncompressedRaw(mRaw->dim, pos, width * bps / 8, bps,
BitOrder_Jpeg32);
} else {
u.readUncompressedRaw(mRaw->dim, pos, width * bps / 8, bps,
BitOrder_Plain);
}
}
return mRaw;
}
void RafDecoder::checkSupportInternal(const CameraMetaData* meta) {
if (!this->checkCameraSupported(meta, mRootIFD->getID(), ""))
ThrowRDE("Unknown camera. Will not guess.");
}
void RafDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {
int iso = 0;
if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS))
iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getU32();
mRaw->metadata.isoSpeed = iso;
// This is where we'd normally call setMetaData but since we may still need
// to rotate the image for SuperCCD cameras we do everything ourselves
auto id = mRootIFD->getID();
const Camera* cam = meta->getCamera(id.make, id.model, "");
if (!cam)
ThrowRDE("Couldn't find camera");
iPoint2D new_size(mRaw->dim);
iPoint2D crop_offset = iPoint2D(0,0);
if (applyCrop) {
new_size = cam->cropSize;
crop_offset = cam->cropPos;
bool double_width = hints.has("double_width_unpacked");
// If crop size is negative, use relative cropping
if (new_size.x <= 0)
new_size.x = mRaw->dim.x / (double_width ? 2 : 1) - cam->cropPos.x + new_size.x;
else
new_size.x /= (double_width ? 2 : 1);
if (new_size.y <= 0)
new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y;
}
bool rotate = hints.has("fuji_rotate");
rotate = rotate & fujiRotate;
// Rotate 45 degrees - could be multithreaded.
if (rotate && !this->uncorrectedRawValues) {
// Calculate the 45 degree rotated size;
uint32 rotatedsize;
uint32 rotationPos;
if (alt_layout) {
rotatedsize = new_size.y+new_size.x/2;
rotationPos = new_size.x/2 - 1;
}
else {
rotatedsize = new_size.x+new_size.y/2;
rotationPos = new_size.x - 1;
}
iPoint2D final_size(rotatedsize, rotatedsize-1);
RawImage rotated = RawImage::create(final_size, TYPE_USHORT16, 1);
rotated->clearArea(iRectangle2D(iPoint2D(0,0), rotated->dim));
rotated->metadata = mRaw->metadata;
rotated->metadata.fujiRotationPos = rotationPos;
int dest_pitch = (int)rotated->pitch / 2;
auto *dst = (ushort16 *)rotated->getData(0, 0);
for (int y = 0; y < new_size.y; y++) {
auto *src = (ushort16 *)mRaw->getData(crop_offset.x, crop_offset.y + y);
for (int x = 0; x < new_size.x; x++) {
int h, w;
if (alt_layout) { // Swapped x and y
h = rotatedsize - (new_size.y + 1 - y + (x >> 1));
w = ((x+1) >> 1) + y;
} else {
h = new_size.x - 1 - x + (y >> 1);
w = ((y+1) >> 1) + x;
}
if (h < rotated->dim.y && w < rotated->dim.x)
dst[w + h * dest_pitch] = src[x];
else
ThrowRDE("Trying to write out of bounds");
}
}
mRaw = rotated;
} else if (applyCrop) {
mRaw->subFrame(iRectangle2D(crop_offset, new_size));
}
const CameraSensorInfo *sensor = cam->getSensorInfo(iso);
mRaw->blackLevel = sensor->mBlackLevel;
// at least the (bayer sensor) X100 comes with a tag like this:
if (mRootIFD->hasEntryRecursive(FUJI_BLACKLEVEL)) {
TiffEntry* sep_black = mRootIFD->getEntryRecursive(FUJI_BLACKLEVEL);
if (sep_black->count == 4)
{
for(int k=0;k<4;k++)
mRaw->blackLevelSeparate[k] = sep_black->getU32(k);
} else if (sep_black->count == 36) {
for (int& k : mRaw->blackLevelSeparate)
k = 0;
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 6; x++)
mRaw->blackLevelSeparate[2 * (y % 2) + (x % 2)] +=
sep_black->getU32(6 * y + x);
}
for (int& k : mRaw->blackLevelSeparate)
k /= 9;
}
}
mRaw->whitePoint = sensor->mWhiteLevel;
mRaw->blackAreas = cam->blackAreas;
mRaw->cfa = cam->cfa;
mRaw->metadata.canonical_make = cam->canonical_make;
mRaw->metadata.canonical_model = cam->canonical_model;
mRaw->metadata.canonical_alias = cam->canonical_alias;
mRaw->metadata.canonical_id = cam->canonical_id;
mRaw->metadata.make = id.make;
mRaw->metadata.model = id.model;
if (mRootIFD->hasEntryRecursive(FUJI_WB_GRBLEVELS)) {
TiffEntry *wb = mRootIFD->getEntryRecursive(FUJI_WB_GRBLEVELS);
if (wb->count == 3) {
mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);
mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);
mRaw->metadata.wbCoeffs[2] = wb->getFloat(2);
}
} else if (mRootIFD->hasEntryRecursive(FUJIOLDWB)) {
TiffEntry *wb = mRootIFD->getEntryRecursive(FUJIOLDWB);
if (wb->count == 8) {
mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);
mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);
mRaw->metadata.wbCoeffs[2] = wb->getFloat(3);
}
}
}
} // namespace RawSpeed
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "ProguardMap.h"
#include <algorithm>
#include <cstring>
#include "Debug.h"
namespace {
constexpr size_t kBufSize = 4096;
std::string convert_scalar_type(const char* type) {
static const std::map<std::string, std::string> prim_map =
{{"void", "V"},
{"boolean", "Z"},
{"byte", "B"},
{"short", "S"},
{"char", "C"},
{"int", "I"},
{"long", "J"},
{"float", "F"},
{"double", "D"}};
auto it = prim_map.find(type);
if (it != prim_map.end()) {
return it->second;
}
std::string ret(type);
std::replace(ret.begin(), ret.end(), '.', '/');
return std::string("L") + ret + ";";
}
std::string convert_type(const char* type) {
if (type[strlen(type) - 1] == ']') {
std::string elem_type(type, strrchr(type, '[') - type);
return std::string("[") + convert_type(elem_type.c_str());
}
return convert_scalar_type(type);
}
std::string convert_args(const char* args) {
const char* p = args;
std::string ret;
while (*p != '\0') {
const char* n = strchr(p, ',');
if (n) {
std::string arg(p, n - p);
ret += convert_type(arg.c_str());
p = n + 1;
} else {
ret += convert_type(p);
break;
}
}
return ret;
}
std::string convert_proguard_field(
const std::string& cls,
const char* type,
const char* name) {
return cls + "." + name + ":" + convert_type(type);
}
std::string convert_proguard_method(
const std::string& cls,
const char* rtype,
const char* methodname,
const char* args) {
return cls + "." +
std::string(methodname) +
"(" + convert_args(args) + ")" +
convert_type(rtype);
}
}
ProguardMap::ProguardMap(const std::string& filename) {
if (!filename.empty()) {
std::ifstream fp(filename);
always_assert_log(fp, "Can't open proguard map: %s\n", filename.c_str());
parse_proguard_map(fp);
}
}
const std::string& ProguardMap::translate_class(const std::string& cls) {
auto it = m_classMap.find(cls);
if (it == m_classMap.end()) return cls;
return it->second;
}
const std::string& ProguardMap::translate_field(const std::string& field) {
return m_fieldMap[field];
}
const std::string& ProguardMap::translate_method(const std::string& method) {
return m_methodMap[method];
}
void ProguardMap::parse_line(const std::string& line) {
if (parse_class(line)) {
return;
}
if (parse_field(line)) {
return;
}
if (parse_method(line)) {
return;
}
always_assert_log(false,
"Bogus line encountered in proguard map: %s\n",
line.c_str());
}
bool ProguardMap::parse_class(const std::string& line) {
char classname[kBufSize];
char newname[kBufSize];
int n;
n = sscanf(line.c_str(), "%s -> %[^:]:", classname, newname);
if (n != 2) {
return false;
}
m_currClass = convert_type(classname);
m_currNewClass = convert_type(newname);
m_classMap[m_currClass] = m_currNewClass;
return true;
}
bool ProguardMap::parse_field(const std::string& line) {
char type[kBufSize];
char fieldname[kBufSize];
char newname[kBufSize];
int n = sscanf(line.c_str(), " %s %[a-zA-Z0-9$_] -> %s",
type, fieldname, newname);
if (n != 3) {
return false;
}
auto pgnew = convert_proguard_field(m_currNewClass, type, newname);
auto pgold = convert_proguard_field(m_currClass, type, fieldname);
m_fieldMap[pgold] = pgnew;
return true;
}
bool ProguardMap::parse_method(const std::string& line) {
int line1;
int line2;
char type[kBufSize];
char methodname[kBufSize];
char args[kBufSize];
char newname[kBufSize];
int n;
n = sscanf(line.c_str(), " %d:%d:%s %[^(]() -> %s",
&line1, &line2, type, methodname, newname);
if (n == 5) {
add_method_mapping(type, methodname, newname, "");
return true;
}
n = sscanf(line.c_str(), " %d:%d:%s %[^(](%[^)]) -> %s",
&line1, &line2, type, methodname, args, newname);
if (n == 6) {
add_method_mapping(type, methodname, newname, args);
return true;
}
n = sscanf(line.c_str(), " %s %[^(]() -> %s", type, methodname, newname);
if (n == 3) {
add_method_mapping(type, methodname, newname, "");
return true;
}
n = sscanf(line.c_str(), " %s %[^(](%[^)]) -> %s",
type, methodname, args, newname);
if (n == 4) {
add_method_mapping(type, methodname, newname, args);
return true;
}
return false;
}
void ProguardMap::add_method_mapping(
const char* type,
const char* methodname,
const char* newname,
const char* args) {
auto pgold = convert_proguard_method(m_currClass, type, methodname, args);
auto pgnew = convert_proguard_method(m_currNewClass, type, newname, args);
m_methodMap[pgold] = pgnew;
}
<commit_msg>Fix buffer overrun in proguard map parsing<commit_after>/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "ProguardMap.h"
#include <algorithm>
#include <cstring>
#include "Debug.h"
namespace {
constexpr size_t kBufSize = 4096;
std::string convert_scalar_type(const char* type) {
static const std::map<std::string, std::string> prim_map =
{{"void", "V"},
{"boolean", "Z"},
{"byte", "B"},
{"short", "S"},
{"char", "C"},
{"int", "I"},
{"long", "J"},
{"float", "F"},
{"double", "D"}};
auto it = prim_map.find(type);
if (it != prim_map.end()) {
return it->second;
}
std::string ret(type);
std::replace(ret.begin(), ret.end(), '.', '/');
return std::string("L") + ret + ";";
}
std::string convert_type(const char* type) {
if (type[strlen(type) - 1] == ']') {
std::string elem_type(type, strrchr(type, '[') - type);
return std::string("[") + convert_type(elem_type.c_str());
}
return convert_scalar_type(type);
}
std::string convert_args(const char* args) {
const char* p = args;
std::string ret;
while (*p != '\0') {
const char* n = strchr(p, ',');
if (n) {
std::string arg(p, n - p);
ret += convert_type(arg.c_str());
p = n + 1;
} else {
ret += convert_type(p);
break;
}
}
return ret;
}
std::string convert_proguard_field(
const std::string& cls,
const char* type,
const char* name) {
return cls + "." + name + ":" + convert_type(type);
}
std::string convert_proguard_method(
const std::string& cls,
const char* rtype,
const char* methodname,
const char* args) {
return cls + "." +
std::string(methodname) +
"(" + convert_args(args) + ")" +
convert_type(rtype);
}
}
ProguardMap::ProguardMap(const std::string& filename) {
if (!filename.empty()) {
std::ifstream fp(filename);
always_assert_log(fp, "Can't open proguard map: %s\n", filename.c_str());
parse_proguard_map(fp);
}
}
const std::string& ProguardMap::translate_class(const std::string& cls) {
auto it = m_classMap.find(cls);
if (it == m_classMap.end()) return cls;
return it->second;
}
const std::string& ProguardMap::translate_field(const std::string& field) {
return m_fieldMap[field];
}
const std::string& ProguardMap::translate_method(const std::string& method) {
return m_methodMap[method];
}
void ProguardMap::parse_line(const std::string& line) {
if (parse_class(line)) {
return;
}
if (parse_field(line)) {
return;
}
if (parse_method(line)) {
return;
}
always_assert_log(false,
"Bogus line encountered in proguard map: %s\n",
line.c_str());
}
bool ProguardMap::parse_class(const std::string& line) {
char classname[kBufSize];
char newname[kBufSize];
int n;
n = sscanf(line.c_str(), "%s -> %[^:]:", classname, newname);
if (n != 2) {
return false;
}
m_currClass = convert_type(classname);
m_currNewClass = convert_type(newname);
m_classMap[m_currClass] = m_currNewClass;
return true;
}
bool ProguardMap::parse_field(const std::string& line) {
char type[kBufSize];
char fieldname[kBufSize];
char newname[kBufSize];
int n = sscanf(line.c_str(), " %s %[a-zA-Z0-9$_] -> %s",
type, fieldname, newname);
if (n != 3) {
return false;
}
auto pgnew = convert_proguard_field(m_currNewClass, type, newname);
auto pgold = convert_proguard_field(m_currClass, type, fieldname);
m_fieldMap[pgold] = pgnew;
return true;
}
bool ProguardMap::parse_method(const std::string& line) {
const char* type;
const char* methodname;
const char* args;
const char* newname;
char* linecopy = strdup(line.c_str());
char* p = linecopy;
while (!isalpha(*p)) {
if (!*p) goto no_match;
p++;
}
type = p;
while (!isspace(*p)) {
if (!*p) goto no_match;
p++;
}
*p++ = '\0';
methodname = p;
while (*p != '(') {
if (!*p) goto no_match;
p++;
}
*p++ = '\0';
args = p;
while (*p != ')') {
if (!*p) goto no_match;
p++;
}
*p++ = '\0';
if (strncmp(p, " -> ", 4)) {
goto no_match;
}
p += 4;
newname = p;
add_method_mapping(type, methodname, newname, args);
free(linecopy);
return true;
no_match:
free(linecopy);
return false;
}
void ProguardMap::add_method_mapping(
const char* type,
const char* methodname,
const char* newname,
const char* args) {
auto pgold = convert_proguard_method(m_currClass, type, methodname, args);
auto pgnew = convert_proguard_method(m_currNewClass, type, newname, args);
m_methodMap[pgold] = pgnew;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2001 by Christopher Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgeom/csrectrg.h"
csRectRegion::csRectRegion() : region(0), region_count(0), region_max(0) {}
csRectRegion::~csRectRegion()
{
if (region != 0)
free(region);
}
void csRectRegion::pushRect(csRect const& r)
{
if (region_count >= region_max)
{
region_max += 64;
int const nbytes = region_max * sizeof(region[0]);
if (region == 0)
region = (csRect*)malloc(nbytes);
else
region = (csRect*)realloc(region, nbytes);
}
region[region_count++] = r;
}
void csRectRegion::deleteRect(int i)
{
if (region_count > 0 && i >= 0 && i < --region_count)
memmove(region + i, region + i + 1, region_count - i);
}
// This operation takes a rect r1 which completely contains rect r2
// and turns it into as many rects as it takes to exclude r2 from the
// area controlled by r1.
void
csRectRegion::fragmentContainedRect(csRect &r1, csRect &r2)
{
// Edge flags
const unsigned int LX=1, TY=2, RX=4, BY=8;
unsigned int edges=0;
// First check for edging.
edges |= (r1.xmin == r2.xmin ? LX : 0);
edges |= (r1.ymin == r2.ymin ? TY : 0);
edges |= (r1.xmax == r2.xmax ? RX : 0);
edges |= (r1.ymax == r2.ymax ? BY : 0);
switch(edges)
{
case 0:
// This is the easy case. Split the r1 into four pieces that exclude r2.
// The include function pre-checks for this case and exits, so it is
// properly handled.
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r2.xmin, r1.ymin, r2.xmax, r1.ymin-1)); //top
pushRect(csRect(r2.xmin, r2.ymax+1, r2.xmax, r1.ymax)); //bottom
return;
case 1:
// Three rects (top, right, bottom) [rect on left side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r2.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 2:
// Three rects (bot, left, right) [rect on top side, middle]
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r2.ymax)); //left
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r2.ymax)); //right
return;
case 3:
// Two rects (right, bottom) [rect on top left corner]
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r2.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 4:
// Three rects (top, left, bottom) [rect on right side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymin, r2.xmax-1, r2.ymax)); //left
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 5:
// Two rects (top, bottom) [rect in middle, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 6:
// Two rects (left, bottom) [rect on top, right corner]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 7:
// One rect (bottom) [rect covers entire top]
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 8:
// Three rects (top, left, right) [rect on bottom side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r2.ymax)); //right
return;
case 9:
// Two rects (right, top) [rect on bottom, left corner]
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
return;
case 10:
// Two rects (left, right) [rect in middle, vertically touches top and bottom sides]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r1.ymax)); //right
return;
case 11:
// One rect (right) [rect on left, vertically touches top and bottom sides]
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
return;
case 12:
// Two rects (left, top) [rect on bottom, right corner]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
return;
case 13:
// One rect (top) [rect on bottom, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmax, r2.ymin-1)); //top
return;
case 14:
// One rect (bot) [rect on top, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bottom
return;
case 15:
// No rects
// In this case, the rects cancel themselves out.
return;
}
}
// The purpose of this function is to take r1 and fragment it around r2,
// removing the area that overlaps. This function can be used by either
// Include() or Exclude(), since it simply fragments r1.
void csRectRegion::fragmentRect(
csRect &r1, csRect &r2, bool testedContains, bool testedEdge)
{
// We may have to fragment r1 into four pieces if r2 is totally inside r1
if (!testedContains)
{
csRect tr1(r1), tr2(r2);
tr2.Exclude(tr1);
if (tr2.IsEmpty())
{
// It now becomes irritating. Not only do we have to possibly split it into two
// rectangles, we may have to split it into as few as one. Call a separate
// function to handle this business.
fragmentContainedRect(r1, r2);
}
}
// We may have to fragment r1 into three pieces if an entire edge of r2 is
// inside r1.
if (!testedEdge)
{
//Fix me: this code needs to be written!!
}
// If we've gotten here then we should only have to break the rect into 2
// pieces.
if (r1.Contains(r2.xmin, r2.ymin))
{
// Break r1 into left, top since top left corner of r2 is inside.
pushRect(csRect(r1.xmin, r2.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
}
else if (r1.Contains(r2.xmin, r2.ymax))
{
// Break r1 into left, bot since bot left corner of r2 is inside.
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r2.ymax)); //left
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
}
else if (r1.Contains(r2.xmax, r2.ymin))
{
// Break r1 into right, top since top right corner of r2 is inside.
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r1.xmin, r1.ymin, r2.xmax, r2.ymin-1)); //top
}
else
{
// Break r1 into right, bot since bot right corner of r2 is inside.
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax+1, r2.xmax, r1.ymax)); //bot
}
}
// Chop the intersection of rect1 and rect2 off of rect1 (the smaller rect)
// Tests to make sure the intersection happens on an edge and not a corner.
// Returns false if it is unable to process the chop because of bad
// intersections
bool csRectRegion::chopEdgeIntersection(csRect &rect1, csRect &rect2)
{
if ((rect1.xmax <= rect2.xmax && rect1.xmin >= rect2.xmin) ||
(rect1.ymax <= rect2.ymax && rect1.ymin >= rect2.ymin))
{
csRect i(rect1);
i.Intersect(rect2);
rect1.Subtract(i);
return true;
}
return false;
}
void csRectRegion::Include(csRect &rect)
{
// If there are no rects in the region, add this and leave.
if (region_count == 0)
{
pushRect(rect);
return;
}
// Otherwise, we have to see if this rect creates a union with any other
// rectangles.
int i;
for(i = 0; i < region_count; i++)
{
csRect &r1 = region[i];
csRect r2(rect);
// Check to see if these even touch
if (r2.Intersects(r1)==false)
continue;
// If r1 totally contains rect, then we leave.
r2.Exclude(r1);
if (r2.IsEmpty())
return;
// If rect totally contains r1, then we kill r1 from the list.
r2.Set(r1);
r2.Exclude(rect);
if (r2.IsEmpty())
{
// Kill from list
deleteRect(i);
// Iterate
continue;
}
// We know that the two rects intersect, but neither of them completely
// contains each other. Therefore, we must now see what to chop off of
// what. It may be more efficient to chop part off of one or the other.
// Usually, it's easier to chop up the smaller one.
bool edgeChopWorked;
if (!(edgeChopWorked = chopEdgeIntersection(r1, r2)))
edgeChopWorked = chopEdgeIntersection(r2, r1);
// If we were able to chop the edge off of one of them, cool.
if (edgeChopWorked)
continue;
// Otherwise we have to do the most irritating part: A full split operation
// that may create other rects that need to be tested against the database
// recursively. For this algorithm, we fragment the one that is already in
// the database, that way we don't cause more tests: we already know that
// that rect is good.
r2.Set(rect);
// Kill rect from list
deleteRect(i);
// Fragment it
fragmentRect(r1, r2, true, true);
} // end for
}
void
csRectRegion::Exclude(csRect &rect)
{
// If there are no rects in the region, just leave.
if (region_count == 0)
return;
// Otherwise, we have to see if this rect overlaps or touches any other.
int i;
for(i = 0; i < region_count; i++)
{
csRect &r1 = region[i];
csRect r2(rect);
// Check to see if these even touch
if (r2.Intersects(r1)==false)
continue;
// If r1 totally contains rect, then we call the fragment contained rect function.
r2.Exclude(r1);
if (r2.IsEmpty())
{
csRect rc1(region[i]);
deleteRect(i);
fragmentContainedRect(rc1, rect);
continue;
}
// If rect totally contains r1, then we kill r1 from the list.
r2.Set(r1);
r2.Exclude(rect);
if (r2.IsEmpty())
{
// Kill from list
deleteRect(i);
// Iterate
continue;
}
// This part is similiar to Include, except that we are trying to remove a portion. Instead
// of calling chopEdgeIntersection, we actually have to fragment rect1 and chop off an edge
// of the excluding rect. This code should be handled inside fragment rect.
r2.Set(rect);
// Kill rect from list
deleteRect(i);
// Fragment it
fragmentRect(r1, r2, true, false);
} // end for
}
<commit_msg>Realized that code for proper fragmentation of edge cases in exclude already exists, i simply have to call it for an intersection rather than a whole. Changed code to perform this function. Regions should now be correct and optimal. Note that the code is still untested.<commit_after>/*
Copyright (C) 2001 by Christopher Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgeom/csrectrg.h"
csRectRegion::csRectRegion() : region(0), region_count(0), region_max(0) {}
csRectRegion::~csRectRegion()
{
if (region != 0)
free(region);
}
void csRectRegion::pushRect(csRect const& r)
{
if (region_count >= region_max)
{
region_max += 64;
int const nbytes = region_max * sizeof(region[0]);
if (region == 0)
region = (csRect*)malloc(nbytes);
else
region = (csRect*)realloc(region, nbytes);
}
region[region_count++] = r;
}
void csRectRegion::deleteRect(int i)
{
if (region_count > 0 && i >= 0 && i < --region_count)
memmove(region + i, region + i + 1, region_count - i);
}
// This operation takes a rect r1 which completely contains rect r2
// and turns it into as many rects as it takes to exclude r2 from the
// area controlled by r1.
void
csRectRegion::fragmentContainedRect(csRect &r1, csRect &r2)
{
// Edge flags
const unsigned int LX=1, TY=2, RX=4, BY=8;
unsigned int edges=0;
// First check for edging.
edges |= (r1.xmin == r2.xmin ? LX : 0);
edges |= (r1.ymin == r2.ymin ? TY : 0);
edges |= (r1.xmax == r2.xmax ? RX : 0);
edges |= (r1.ymax == r2.ymax ? BY : 0);
switch(edges)
{
case 0:
// This is the easy case. Split the r1 into four pieces that exclude r2.
// The include function pre-checks for this case and exits, so it is
// properly handled.
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r2.xmin, r1.ymin, r2.xmax, r1.ymin-1)); //top
pushRect(csRect(r2.xmin, r2.ymax+1, r2.xmax, r1.ymax)); //bottom
return;
case 1:
// Three rects (top, right, bottom) [rect on left side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r2.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 2:
// Three rects (bot, left, right) [rect on top side, middle]
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r2.ymax)); //left
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r2.ymax)); //right
return;
case 3:
// Two rects (right, bottom) [rect on top left corner]
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r2.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 4:
// Three rects (top, left, bottom) [rect on right side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymin, r2.xmax-1, r2.ymax)); //left
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 5:
// Two rects (top, bottom) [rect in middle, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 6:
// Two rects (left, bottom) [rect on top, right corner]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 7:
// One rect (bottom) [rect covers entire top]
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 8:
// Three rects (top, left, right) [rect on bottom side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r2.ymax)); //right
return;
case 9:
// Two rects (right, top) [rect on bottom, left corner]
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
return;
case 10:
// Two rects (left, right) [rect in middle, vertically touches top and bottom sides]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r1.ymax)); //right
return;
case 11:
// One rect (right) [rect on left, vertically touches top and bottom sides]
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
return;
case 12:
// Two rects (left, top) [rect on bottom, right corner]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
return;
case 13:
// One rect (top) [rect on bottom, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmax, r2.ymin-1)); //top
return;
case 14:
// One rect (bot) [rect on top, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bottom
return;
case 15:
// No rects
// In this case, the rects cancel themselves out.
return;
}
}
// The purpose of this function is to take r1 and fragment it around r2,
// removing the area that overlaps. This function can be used by either
// Include() or Exclude(), since it simply fragments r1.
void csRectRegion::fragmentRect(
csRect &r1, csRect &r2, bool testedContains, bool testedEdge)
{
// We may have to fragment r1 into four pieces if r2 is totally inside r1
if (!testedContains)
{
csRect tr1(r1), tr2(r2);
tr2.Exclude(tr1);
if (tr2.IsEmpty())
{
// It now becomes irritating. Not only do we have to possibly split it into two
// rectangles, we may have to split it into as few as one. Call a separate
// function to handle this business.
fragmentContainedRect(r1, r2);
return;
}
}
// We may have to fragment r1 into three pieces if an entire edge of r2 is
// inside r1.
if (!testedEdge)
{
if (r1.Intersects(r2))
{
// Since fragment rect already test for all cases, the ideal method here is to call
// fragment rect on the intersection of r1 and r2 with r1 as the fragmentee. This
// creates a properly fragmented system.
csRect ri(r1);
ri.Intersect(r2);
fragmentContainedRect(r1, ri);
return;
}
}
// If we've gotten here then we should only have to break the rect into 2
// pieces.
if (r1.Contains(r2.xmin, r2.ymin))
{
// Break r1 into left, top since top left corner of r2 is inside.
pushRect(csRect(r1.xmin, r2.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
}
else if (r1.Contains(r2.xmin, r2.ymax))
{
// Break r1 into left, bot since bot left corner of r2 is inside.
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r2.ymax)); //left
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
}
else if (r1.Contains(r2.xmax, r2.ymin))
{
// Break r1 into right, top since top right corner of r2 is inside.
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r1.xmin, r1.ymin, r2.xmax, r2.ymin-1)); //top
}
else
{
// Break r1 into right, bot since bot right corner of r2 is inside.
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax+1, r2.xmax, r1.ymax)); //bot
}
}
// Chop the intersection of rect1 and rect2 off of rect1 (the smaller rect)
// Tests to make sure the intersection happens on an edge and not a corner.
// Returns false if it is unable to process the chop because of bad
// intersections
bool csRectRegion::chopEdgeIntersection(csRect &rect1, csRect &rect2)
{
if ((rect1.xmax <= rect2.xmax && rect1.xmin >= rect2.xmin) ||
(rect1.ymax <= rect2.ymax && rect1.ymin >= rect2.ymin))
{
csRect i(rect1);
i.Intersect(rect2);
rect1.Subtract(i);
return true;
}
return false;
}
void csRectRegion::Include(csRect &rect)
{
// If there are no rects in the region, add this and leave.
if (region_count == 0)
{
pushRect(rect);
return;
}
// Otherwise, we have to see if this rect creates a union with any other
// rectangles.
int i;
for(i = 0; i < region_count; i++)
{
csRect &r1 = region[i];
csRect r2(rect);
// Check to see if these even touch
if (r2.Intersects(r1)==false)
continue;
// If r1 totally contains rect, then we leave.
r2.Exclude(r1);
if (r2.IsEmpty())
return;
// If rect totally contains r1, then we kill r1 from the list.
r2.Set(r1);
r2.Exclude(rect);
if (r2.IsEmpty())
{
// Kill from list
deleteRect(i);
// Iterate
continue;
}
// We know that the two rects intersect, but neither of them completely
// contains each other. Therefore, we must now see what to chop off of
// what. It may be more efficient to chop part off of one or the other.
// Usually, it's easier to chop up the smaller one.
bool edgeChopWorked;
if (!(edgeChopWorked = chopEdgeIntersection(r1, r2)))
edgeChopWorked = chopEdgeIntersection(r2, r1);
// If we were able to chop the edge off of one of them, cool.
if (edgeChopWorked)
continue;
// Otherwise we have to do the most irritating part: A full split operation
// that may create other rects that need to be tested against the database
// recursively. For this algorithm, we fragment the one that is already in
// the database, that way we don't cause more tests: we already know that
// that rect is good.
r2.Set(rect);
// Kill rect from list
deleteRect(i);
// Fragment it
fragmentRect(r1, r2, true, true);
} // end for
}
void
csRectRegion::Exclude(csRect &rect)
{
// If there are no rects in the region, just leave.
if (region_count == 0)
return;
// Otherwise, we have to see if this rect overlaps or touches any other.
int i;
for(i = 0; i < region_count; i++)
{
csRect &r1 = region[i];
csRect r2(rect);
// Check to see if these even touch
if (r2.Intersects(r1)==false)
continue;
// If r1 totally contains rect, then we call the fragment contained rect function.
r2.Exclude(r1);
if (r2.IsEmpty())
{
csRect rc1(region[i]);
deleteRect(i);
fragmentContainedRect(rc1, rect);
continue;
}
// If rect totally contains r1, then we kill r1 from the list.
r2.Set(r1);
r2.Exclude(rect);
if (r2.IsEmpty())
{
// Kill from list
deleteRect(i);
// Iterate
continue;
}
// This part is similiar to Include, except that we are trying to remove a portion. Instead
// of calling chopEdgeIntersection, we actually have to fragment rect1 and chop off an edge
// of the excluding rect. This code should be handled inside fragment rect.
r2.Set(rect);
// Kill rect from list
deleteRect(i);
// Fragment it
fragmentRect(r1, r2, true, false);
} // end for
}
<|endoftext|> |
<commit_before>/*
Crystal Space Vector class
Copyright (C) 1998,1999 by Andrew Zabolotny <bit@eltech.ru>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdlib.h>
#include <string.h>
#include "sysdef.h"
#include "csutil/csvector.h"
csVector::csVector (int ilimit, int ithreshold)
{
root = (csSome *)malloc ((limit = ilimit) * sizeof (csSome));
count = 0; threshold = ithreshold;
}
csVector::~csVector ()
{
//not much sense to call DeleteAll () since even for inherited classes
//anyway will be called csVector::FreeItem which is empty.
//DeleteAll ();
if (root) free (root);
}
void csVector::DeleteAll ()
{
int idx;
for (idx = count - 1; idx >= 0; idx--)
if (!FreeItem (root [idx]))
break;
SetLength (idx + 1);
while (idx >= 0)
Delete (idx--);
}
void csVector::SetLength (int n)
{
count = n;
if ((n > limit) || ((limit > threshold) && (n < limit - threshold)))
{
n = ((n + threshold - 1) / threshold) * threshold;
root = n ? (csSome *)realloc (root, n * sizeof (csSome)) : NULL;
limit = n;
}
}
bool csVector::FreeItem (csSome Item)
{
(void)Item;
return true;
}
bool csVector::Delete (int n)
{
if (n < count)
{
if (!FreeItem (root [n]))
return false;
int ncount = count - 1;
memmove (&root [n], &root [n + 1], (ncount - n) * sizeof (csSome));
SetLength (ncount);
return true;
}
else
return false;
}
bool csVector::Replace (int n, csSome what)
{
if (n < count)
{
if (!FreeItem (root [n]))
return false;
root [n] = what;
return true;
}
else
return false;
}
bool csVector::Insert (int n, csSome Item)
{
if (n <= count)
{
SetLength (count + 1); // Increments 'count' as a side-effect.
memmove (&root [n + 1], &root [n], (count - n - 1) * sizeof (csSome));
root [n] = Item;
return true;
}
else
return false;
}
int csVector::Find (csSome which) const
{
for (int i = 0; i < Length (); i++)
if (root [i] == which)
return i;
return -1;
}
int csVector::FindKey (csConstSome Key, int Mode) const
{
for (int i = 0; i < Length (); i++)
if (CompareKey (root [i], Key, Mode) == 0)
return i;
return -1;
}
int csVector::FindSortedKey (csConstSome Key, int Mode) const
{
int l = 0, r = Length () - 1;
while (l <= r)
{
int m = (l + r) / 2;
int cmp = CompareKey (root [m], Key, Mode);
if (cmp == 0)
return m;
else if (cmp < 0)
l = m + 1;
else
r = m - 1;
}
return -1;
}
int csVector::InsertSorted (csSome Item, int *oEqual, int Mode)
{
int m = 0, l = 0, r = Length () - 1;
while (l <= r)
{
m = (l + r) / 2;
int cmp = Compare (root [m], Item, Mode);
if (cmp == 0)
{
if (oEqual)
*oEqual = m;
Insert (++m, Item);
return m;
}
else if (cmp < 0)
l = m + 1;
else
r = m - 1;
}
if (r == m)
m++;
Insert (m, Item);
if (oEqual)
*oEqual = -1;
return m;
}
void csVector::QuickSort (int Left, int Right, int Mode)
{
recurse:
int i = Left, j = Right;
int x = (Left + Right) / 2;
do
{
while ((i != x) && (Compare (Get (i), Get (x), Mode) < 0))
i++;
while ((j != x) && (Compare (Get (j), Get (x), Mode) > 0))
j--;
if (i < j)
{
Exchange (i, j);
if (x == i)
x = j;
else if (x == j)
x = i;
}
if (i <= j)
{
i++;
if (j > Left)
j--;
}
} while (i <= j);
if (j - Left < Right - i)
{
if (Left < j)
QuickSort (Left, j, Mode);
if (i < Right)
{
Left = i;
goto recurse;
}
}
else
{
if (i < Right)
QuickSort (i, Right, Mode);
if (Left < j)
{
Right = j;
goto recurse;
}
}
}
int csVector::Compare (csSome Item1, csSome Item2, int Mode) const
{
(void)Mode;
return ((int)Item1 > (int)Item2) ? +1 : ((int)Item1 == (int)Item2) ? 0 : -1;
}
int csVector::CompareKey (csSome Item, csConstSome Key, int Mode) const
{
(void)Mode;
return (Item > Key) ? +1 : (Item == Key) ? 0 : -1;
}
<commit_msg>Fixed a memory leak in csVector::SetLength(). Thanks to Denis Dmitriev for mentioning this.<commit_after>/*
Crystal Space Vector class
Copyright (C) 1998,1999 by Andrew Zabolotny <bit@eltech.ru>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdlib.h>
#include <string.h>
#include "sysdef.h"
#include "csutil/csvector.h"
csVector::csVector (int ilimit, int ithreshold)
{
root = (csSome *)malloc ((limit = ilimit) * sizeof (csSome));
count = 0; threshold = ithreshold;
}
csVector::~csVector ()
{
//not much sense to call DeleteAll () since even for inherited classes
//anyway will be called csVector::FreeItem which is empty.
//DeleteAll ();
if (root) free (root);
}
void csVector::DeleteAll ()
{
int idx;
for (idx = count - 1; idx >= 0; idx--)
if (!FreeItem (root [idx]))
break;
SetLength (idx + 1);
while (idx >= 0)
Delete (idx--);
}
void csVector::SetLength (int n)
{
count = n;
if ((n > limit) || ((limit > threshold) && (n < limit - threshold)))
{
n = ((n + threshold - 1) / threshold) * threshold;
if (!n)
{
free (root);
root = NULL;
}
else
root = (csSome *)realloc (root, n * sizeof (csSome));
limit = n;
}
}
bool csVector::FreeItem (csSome Item)
{
(void)Item;
return true;
}
bool csVector::Delete (int n)
{
if (n < count)
{
if (!FreeItem (root [n]))
return false;
int ncount = count - 1;
memmove (&root [n], &root [n + 1], (ncount - n) * sizeof (csSome));
SetLength (ncount);
return true;
}
else
return false;
}
bool csVector::Replace (int n, csSome what)
{
if (n < count)
{
if (!FreeItem (root [n]))
return false;
root [n] = what;
return true;
}
else
return false;
}
bool csVector::Insert (int n, csSome Item)
{
if (n <= count)
{
SetLength (count + 1); // Increments 'count' as a side-effect.
memmove (&root [n + 1], &root [n], (count - n - 1) * sizeof (csSome));
root [n] = Item;
return true;
}
else
return false;
}
int csVector::Find (csSome which) const
{
for (int i = 0; i < Length (); i++)
if (root [i] == which)
return i;
return -1;
}
int csVector::FindKey (csConstSome Key, int Mode) const
{
for (int i = 0; i < Length (); i++)
if (CompareKey (root [i], Key, Mode) == 0)
return i;
return -1;
}
int csVector::FindSortedKey (csConstSome Key, int Mode) const
{
int l = 0, r = Length () - 1;
while (l <= r)
{
int m = (l + r) / 2;
int cmp = CompareKey (root [m], Key, Mode);
if (cmp == 0)
return m;
else if (cmp < 0)
l = m + 1;
else
r = m - 1;
}
return -1;
}
int csVector::InsertSorted (csSome Item, int *oEqual, int Mode)
{
int m = 0, l = 0, r = Length () - 1;
while (l <= r)
{
m = (l + r) / 2;
int cmp = Compare (root [m], Item, Mode);
if (cmp == 0)
{
if (oEqual)
*oEqual = m;
Insert (++m, Item);
return m;
}
else if (cmp < 0)
l = m + 1;
else
r = m - 1;
}
if (r == m)
m++;
Insert (m, Item);
if (oEqual)
*oEqual = -1;
return m;
}
void csVector::QuickSort (int Left, int Right, int Mode)
{
recurse:
int i = Left, j = Right;
int x = (Left + Right) / 2;
do
{
while ((i != x) && (Compare (Get (i), Get (x), Mode) < 0))
i++;
while ((j != x) && (Compare (Get (j), Get (x), Mode) > 0))
j--;
if (i < j)
{
Exchange (i, j);
if (x == i)
x = j;
else if (x == j)
x = i;
}
if (i <= j)
{
i++;
if (j > Left)
j--;
}
} while (i <= j);
if (j - Left < Right - i)
{
if (Left < j)
QuickSort (Left, j, Mode);
if (i < Right)
{
Left = i;
goto recurse;
}
}
else
{
if (i < Right)
QuickSort (i, Right, Mode);
if (Left < j)
{
Right = j;
goto recurse;
}
}
}
int csVector::Compare (csSome Item1, csSome Item2, int Mode) const
{
(void)Mode;
return ((int)Item1 > (int)Item2) ? +1 : ((int)Item1 == (int)Item2) ? 0 : -1;
}
int csVector::CompareKey (csSome Item, csConstSome Key, int Mode) const
{
(void)Mode;
return (Item > Key) ? +1 : (Item == Key) ? 0 : -1;
}
<|endoftext|> |
<commit_before>#include "winpch.h"
#include "winhttp.h"
#include "..\exceptions\fileExceptions.h"
#include "..\text\textParser.tcc"
#include "..\text\textFormat.tcc"
#include "../containers/autoArray.tcc"
#include "../interface.tcc"
#include "../exceptions/httpStatusException.h"
namespace LightSpeed {
template IHTTPStream &IInterface::getIfc<IHTTPStream>(void);
template const IHTTPStream &IInterface::getIfc<IHTTPStream>(void) const;
template Pointer<IHTTPStream>IInterface::getIfcPtr<IHTTPStream>(void);
template Pointer<const IHTTPStream>IInterface::getIfcPtr<IHTTPStream>(void) const;
#pragma comment (lib, "Wininet.lib")
WinHttpStream::WinHttpStream( String url, const HTTPSettings &settings )
:WinHTTPSettings(this->settings),hInternet(0),hConnect(0),hHTTPConn(0),exceptionDisabled(false),redirDisabled(false)
,url(url),settings(settings),method("GET")
,curState(stIdle),tmaction(0)
{
}
WinHttpStream::~WinHttpStream()
{
if (!postBuffer.empty() && !std::uncaught_exception()) setState(stReadResponse);
timeoutThr.stop();
if (hHTTPConn) InternetCloseHandle(hHTTPConn);
if (hConnect) InternetCloseHandle(hConnect);
if (hInternet) InternetCloseHandle(hInternet);
}
IHTTPStream & WinHttpStream::setMethod( ConstStrA method )
{
this->method = method;
return *this;
}
IHTTPStream & WinHttpStream::setHeader( ConstStrA headerName, ConstStrA headerValue )
{
hdrmap.replace(headerName,headerValue);
return *this;
}
IHTTPStream & WinHttpStream::cancel()
{
if (hHTTPConn) {
InternetCloseHandle(hHTTPConn);
hHTTPConn = 0;
}
return *this;
}
StringA WinHttpStream::getReplyHeaders()
{
setState(stReadResponse);
AutoArray<char> buffer;
buffer.resize(1000);
DWORD size = (DWORD)buffer.length();
while (!HttpQueryInfoA(hHTTPConn,HTTP_QUERY_RAW_HEADERS_CRLF,
buffer.data(),&size,0)) {
DWORD res = GetLastError();
if (res == ERROR_INSUFFICIENT_BUFFER) {
buffer.resize(size);
} else {
throw ErrNoWithDescException(THISLOCATION,GetLastError(),
"Cannot retrieve headers from the request");
}
}
buffer.resize(size);
return buffer;
}
IHTTPStream & WinHttpStream::disableRedirect()
{
redirDisabled = true;
return *this;
}
IHTTPStream & WinHttpStream::disableException()
{
exceptionDisabled= true;
return *this;
}
IHTTPStream & WinHttpStream::connect()
{
if (method == ConstStrA("GET") || method == ConstStrA("HEAD"))
setState(stReadResponse);
else
setState(stWriteRequest);
return *this;
}
LightSpeed::natural WinHttpStream::getStatusCode()
{
setState(stReadResponse);
DWORD statusCode = 0;
DWORD buffSz = sizeof(statusCode);
DWORD index = 0;
if (HttpQueryInfo(hHTTPConn,HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,
&statusCode,&buffSz,&index) == FALSE)
throw FileMsgException(THISLOCATION,GetLastError(),
url,
"Unable to retrieve status code. HttpQueryInfo has failed");
else
return statusCode;
}
void WinHttpStream::setState( State newState )
{
while (newState > curState) {
if (curState == stIdle) {
initRequest();
curState = stWriteRequest;
} else if (curState == stWriteRequest) {
sendRequest();
curState = stReadResponse;
} else {
break;
}
}
}
natural WinHttpStream::read( void *buffer, natural size )
{
setState(stReadResponse);
if (!peekBuffer.empty()) {
natural r = peekBuffer.length();
if (r <= size) {
memcpy(buffer,peekBuffer.data(),r);
peekBuffer.clear();
return r;
} else {
memcpy(buffer,peekBuffer.data(),size);
peekBuffer.erase(0,size);
return size;
}
} else {
return readInternal(buffer, size);
}
}
LightSpeed::natural WinHttpStream::peek( void *buffer, natural size ) const
{
const_cast<WinHttpStream *>(this)->setState(stReadResponse);
if (size <= peekBuffer.length()) {
memcpy(buffer,peekBuffer.data(),size);
return size;
}
natural rm = size - peekBuffer.length();
AutoArray<byte, StaticAlloc<256> > peekBuffer2;
peekBuffer2.resize(rm);
natural r = const_cast<WinHttpStream *>(this)->readInternal(peekBuffer2.data(),peekBuffer2.length());
peekBuffer2.resize(r);
peekBuffer.append(peekBuffer2);
return peek(buffer,r);
}
LightSpeed::natural WinHttpStream::readInternal( void * buffer, natural size )
{
DWORD rd;
BOOL res = InternetReadFile(hHTTPConn,buffer,(DWORD)size,&rd);
DWORD err = GetLastError();
if (res == FALSE) {
throw FileMsgException(THISLOCATION,err,url,"Read failed");
}
return rd;
}
LightSpeed::natural WinHttpStream::write( const void *buffer, natural size )
{
postBuffer.append(ArrayRef<const byte>(reinterpret_cast<const byte *>(buffer),size));
if (method == ConstStrA("GET")) method == ConstStrA("POST");
/*
if (curState == stIdle) {
setState(stWriteRequest);
}
TMWatch _w(*this);
DWORD rd;
BOOL res = InternetWriteFile(hHTTPConn,buffer,size,&rd);
DWORD err = GetLastError();
if (res == FALSE) {
throw FileMsgException(THISLOCATION,err,url,"Write failed");
}*/
return size;
}
bool WinHttpStream::canRead() const
{
byte b;
return peek(&b,1) != 0;
}
bool WinHttpStream::canWrite() const
{
return (method != ConstStrA("GET") && method != ConstStrA("HEAD")) || hHTTPConn == 0;
}
void WinHttpStream::flush()
{
}
natural WinHttpStream::dataReady() const
{
return 0;
}
void WinHttpStream::initRequest()
{
TextParser<wchar_t> parser;
if (!parser(L"%1://%[*-_.a-zA-Z0-9:@]2%%[/](*)*3",url))
throw FileOpenError(THISLOCATION,ERROR_FILE_NOT_FOUND,url);
String protocol = parser[1].str();
String hostident = parser[2].str();
String::SplitIterator hostidentsplit = hostident.split('@');
String ident;
String domain;
domain = hostidentsplit.getNext();
while (hostidentsplit.hasItems()) {
ident = ident + domain + ConstStrW('@');
domain = hostidentsplit.getNext();
}
String path = parser[3].str();
natural port;
String username;
String password;
bool secure;
if (parser( L"%1:%u2",domain)) {
domain = parser[1].str();
port = parser[2];
} else if (protocol == ConstStrW(L"http")) {
port = INTERNET_DEFAULT_HTTP_PORT;
secure = false;
} else if (protocol == ConstStrW(L"https")) {
port = INTERNET_DEFAULT_HTTPS_PORT;
secure = true;
} else
throw FileOpenError(THISLOCATION,ERROR_NOT_FOUND,url);
if (!ident.empty()) {
if (parser(L"%1:%2@",ident)) {
username = parser[1].str();
password = parser[2].str();
} else {
throw FileMsgException(THISLOCATION,0,url,"Invalid identification field in the url");
}
}
DWORD accessType;
switch (settings.proxyMode) {
case pmManual: accessType = INTERNET_OPEN_TYPE_PROXY;
case pmDirect: accessType = INTERNET_OPEN_TYPE_DIRECT;
case pmAuto: accessType = INTERNET_OPEN_TYPE_PRECONFIG;
}
TextFormatBuff<wchar_t> fmt;
String proxyName;
if (accessType == INTERNET_OPEN_TYPE_PROXY) {
fmt(L"%1:%2") << settings.proxyAddr << settings.proxyPort;
proxyName = fmt.write();
}
if (hInternet) InternetCloseHandle(hInternet);
hInternet = InternetOpenW(settings.userAgent.cStr(),accessType,proxyName.cStr(),0,0);
if (hInternet == 0)
throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot initialize WinInet");
if (hConnect) InternetCloseHandle(hConnect);
hConnect = InternetConnectW(hInternet,domain.cStr(),(INTERNET_PORT)port,
username.empty()?0:username.cStr(),
password.empty()?0:password.cStr(),
INTERNET_SERVICE_HTTP ,0,0);
if (hConnect == 0)
throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot connect remote site");
DWORD reqFlags = INTERNET_FLAG_NO_UI |INTERNET_FLAG_HYPERLINK ;
if (redirDisabled) reqFlags|=INTERNET_FLAG_NO_AUTO_REDIRECT ;
if (!settings.cookiesEnabled) reqFlags|=INTERNET_FLAG_NO_COOKIES;
if (secure) reqFlags|=INTERNET_FLAG_SECURE;
hHTTPConn = HttpOpenRequestW(hConnect,String(method).cStr(),path.cStr(),
0,0,0,reqFlags,0);
if (hHTTPConn == 0)
throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot connect remote site");
AutoArray<wchar_t> hdrall;
for (HeaderMap::Iterator iter = hdrmap.getFwIter(); iter.hasItems();) {
const HeaderMap::Entity &e = iter.getNext();
fmt(L"%1: %2\n") << e.key << e.value;
hdrall.append(fmt.write());
}
if (!hdrall.empty() &&
!HttpAddRequestHeadersW(hHTTPConn,hdrall.data(),(DWORD)hdrall.length(),HTTP_ADDREQ_FLAG_REPLACE|HTTP_ADDREQ_FLAG_ADD))
throw FileMsgException(THISLOCATION,GetLastError(),url,"AddRequest failed");
if (!HttpSendRequestW(hHTTPConn,0,0,postBuffer.data(),(DWORD)postBuffer.length())) {
bool stillError = true;
DWORD dwError = GetLastError();
if (dwError == ERROR_INTERNET_INVALID_CA && settings.allowUntrustedCert) {
DWORD dwFlags;
DWORD dwBuffLen = sizeof(dwFlags);
InternetQueryOption (hHTTPConn, INTERNET_OPTION_SECURITY_FLAGS,
(LPVOID)&dwFlags, &dwBuffLen);
dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
InternetSetOption (hHTTPConn, INTERNET_OPTION_SECURITY_FLAGS,
&dwFlags, sizeof (dwFlags) );
if (HttpSendRequestW(hHTTPConn,0,0,postBuffer.data(),(DWORD)postBuffer.length()))
stillError = false;
}
if (stillError)
throw FileMsgException(THISLOCATION,GetLastError(),url,"Failed to SendRequest");
}
postBuffer.clear();
}
void WinHttpStream::sendRequest()
{
if (!exceptionDisabled) {
curState = stReadResponse;
natural status = getStatusCode();
if (status >= 300)
throw HttpStatusException(THISLOCATION,url,status,String());
}
}
bool WinHttpStream::inConnected() const
{
return curState != stIdle;
}
LightSpeed::ConstStrA WinHttpStream::getHeader( ConstStrA field )
{
class FillHdrMap: public IEnumHeaders {
public:
HeaderMap &hdrmap;
FillHdrMap(HeaderMap &hdrmap):hdrmap(hdrmap) {}
virtual bool operator()(ConstStrA field, ConstStrA value) {
hdrmap.insert(field, value);
return false;
}
};
if (curState != stReadResponse) {
setState(stReadResponse);
hdrmap.clear();
FillHdrMap x(hdrmap);
enumHeaders(x);
}
StringA *k = hdrmap.find(StringAI(field));
if (k == 0) return ConstStrA();
else return *k;
}
bool WinHttpStream::enumHeaders( IEnumHeaders &enumHdr )
{
setState(stReadResponse);
AutoArray<char> buffer;
buffer.resize(1000);
DWORD size = (DWORD)buffer.length();
while (!HttpQueryInfoA(hHTTPConn,HTTP_QUERY_RAW_HEADERS,
buffer.data(),&size,0)) {
DWORD res = GetLastError();
if (res == ERROR_INSUFFICIENT_BUFFER) {
buffer.resize(size);
} else {
throw ErrNoWithDescException(THISLOCATION,GetLastError(),
"Cannot retrieve headers from the request");
}
}
buffer.resize(size);
AutoArray<char>::SplitIterator iter=buffer.split((char)0);
TextParser<char> parser;
while (iter.hasItems()) {
ConstStrA line = iter.getNext();
if (parser("%1 : %2",line)) {
ConstStrA field = parser[1].str();
ConstStrA value = parser[2].str();
if(enumHdr(field, value)) return true;
}
}
return false;
}
void WinHttpStream::closeOutput()
{
setState(stReadResponse);
}
}
<commit_msg>POST method was not properly set<commit_after>#include "winpch.h"
#include "winhttp.h"
#include "..\exceptions\fileExceptions.h"
#include "..\text\textParser.tcc"
#include "..\text\textFormat.tcc"
#include "../containers/autoArray.tcc"
#include "../interface.tcc"
#include "../exceptions/httpStatusException.h"
namespace LightSpeed {
template IHTTPStream &IInterface::getIfc<IHTTPStream>(void);
template const IHTTPStream &IInterface::getIfc<IHTTPStream>(void) const;
template Pointer<IHTTPStream>IInterface::getIfcPtr<IHTTPStream>(void);
template Pointer<const IHTTPStream>IInterface::getIfcPtr<IHTTPStream>(void) const;
#pragma comment (lib, "Wininet.lib")
WinHttpStream::WinHttpStream( String url, const HTTPSettings &settings )
:WinHTTPSettings(this->settings),hInternet(0),hConnect(0),hHTTPConn(0),exceptionDisabled(false),redirDisabled(false)
,url(url),settings(settings),method("GET")
,curState(stIdle),tmaction(0)
{
}
WinHttpStream::~WinHttpStream()
{
if (!postBuffer.empty() && !std::uncaught_exception()) setState(stReadResponse);
timeoutThr.stop();
if (hHTTPConn) InternetCloseHandle(hHTTPConn);
if (hConnect) InternetCloseHandle(hConnect);
if (hInternet) InternetCloseHandle(hInternet);
}
IHTTPStream & WinHttpStream::setMethod( ConstStrA method )
{
this->method = method;
return *this;
}
IHTTPStream & WinHttpStream::setHeader( ConstStrA headerName, ConstStrA headerValue )
{
hdrmap.replace(headerName,headerValue);
return *this;
}
IHTTPStream & WinHttpStream::cancel()
{
if (hHTTPConn) {
InternetCloseHandle(hHTTPConn);
hHTTPConn = 0;
}
return *this;
}
StringA WinHttpStream::getReplyHeaders()
{
setState(stReadResponse);
AutoArray<char> buffer;
buffer.resize(1000);
DWORD size = (DWORD)buffer.length();
while (!HttpQueryInfoA(hHTTPConn,HTTP_QUERY_RAW_HEADERS_CRLF,
buffer.data(),&size,0)) {
DWORD res = GetLastError();
if (res == ERROR_INSUFFICIENT_BUFFER) {
buffer.resize(size);
} else {
throw ErrNoWithDescException(THISLOCATION,GetLastError(),
"Cannot retrieve headers from the request");
}
}
buffer.resize(size);
return buffer;
}
IHTTPStream & WinHttpStream::disableRedirect()
{
redirDisabled = true;
return *this;
}
IHTTPStream & WinHttpStream::disableException()
{
exceptionDisabled= true;
return *this;
}
IHTTPStream & WinHttpStream::connect()
{
if (method == ConstStrA("GET") || method == ConstStrA("HEAD"))
setState(stReadResponse);
else
setState(stWriteRequest);
return *this;
}
LightSpeed::natural WinHttpStream::getStatusCode()
{
setState(stReadResponse);
DWORD statusCode = 0;
DWORD buffSz = sizeof(statusCode);
DWORD index = 0;
if (HttpQueryInfo(hHTTPConn,HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,
&statusCode,&buffSz,&index) == FALSE)
throw FileMsgException(THISLOCATION,GetLastError(),
url,
"Unable to retrieve status code. HttpQueryInfo has failed");
else
return statusCode;
}
void WinHttpStream::setState( State newState )
{
while (newState > curState) {
if (curState == stIdle) {
initRequest();
curState = stWriteRequest;
} else if (curState == stWriteRequest) {
sendRequest();
curState = stReadResponse;
} else {
break;
}
}
}
natural WinHttpStream::read( void *buffer, natural size )
{
setState(stReadResponse);
if (!peekBuffer.empty()) {
natural r = peekBuffer.length();
if (r <= size) {
memcpy(buffer,peekBuffer.data(),r);
peekBuffer.clear();
return r;
} else {
memcpy(buffer,peekBuffer.data(),size);
peekBuffer.erase(0,size);
return size;
}
} else {
return readInternal(buffer, size);
}
}
LightSpeed::natural WinHttpStream::peek( void *buffer, natural size ) const
{
const_cast<WinHttpStream *>(this)->setState(stReadResponse);
if (size <= peekBuffer.length()) {
memcpy(buffer,peekBuffer.data(),size);
return size;
}
natural rm = size - peekBuffer.length();
AutoArray<byte, StaticAlloc<256> > peekBuffer2;
peekBuffer2.resize(rm);
natural r = const_cast<WinHttpStream *>(this)->readInternal(peekBuffer2.data(),peekBuffer2.length());
peekBuffer2.resize(r);
peekBuffer.append(peekBuffer2);
return peek(buffer,r);
}
LightSpeed::natural WinHttpStream::readInternal( void * buffer, natural size )
{
DWORD rd;
BOOL res = InternetReadFile(hHTTPConn,buffer,(DWORD)size,&rd);
DWORD err = GetLastError();
if (res == FALSE) {
throw FileMsgException(THISLOCATION,err,url,"Read failed");
}
return rd;
}
LightSpeed::natural WinHttpStream::write( const void *buffer, natural size )
{
postBuffer.append(ArrayRef<const byte>(reinterpret_cast<const byte *>(buffer),size));
if (method == ConstStrA("GET")) method = ConstStrA("POST");
/*
if (curState == stIdle) {
setState(stWriteRequest);
}
TMWatch _w(*this);
DWORD rd;
BOOL res = InternetWriteFile(hHTTPConn,buffer,size,&rd);
DWORD err = GetLastError();
if (res == FALSE) {
throw FileMsgException(THISLOCATION,err,url,"Write failed");
}*/
return size;
}
bool WinHttpStream::canRead() const
{
byte b;
return peek(&b,1) != 0;
}
bool WinHttpStream::canWrite() const
{
return (method != ConstStrA("GET") && method != ConstStrA("HEAD")) || hHTTPConn == 0;
}
void WinHttpStream::flush()
{
}
natural WinHttpStream::dataReady() const
{
return 0;
}
void WinHttpStream::initRequest()
{
TextParser<wchar_t> parser;
if (!parser(L"%1://%[*-_.a-zA-Z0-9:@]2%%[/](*)*3",url))
throw FileOpenError(THISLOCATION,ERROR_FILE_NOT_FOUND,url);
String protocol = parser[1].str();
String hostident = parser[2].str();
String::SplitIterator hostidentsplit = hostident.split('@');
String ident;
String domain;
domain = hostidentsplit.getNext();
while (hostidentsplit.hasItems()) {
ident = ident + domain + ConstStrW('@');
domain = hostidentsplit.getNext();
}
String path = parser[3].str();
natural port;
String username;
String password;
bool secure;
if (parser( L"%1:%u2",domain)) {
domain = parser[1].str();
port = parser[2];
} else if (protocol == ConstStrW(L"http")) {
port = INTERNET_DEFAULT_HTTP_PORT;
secure = false;
} else if (protocol == ConstStrW(L"https")) {
port = INTERNET_DEFAULT_HTTPS_PORT;
secure = true;
} else
throw FileOpenError(THISLOCATION,ERROR_NOT_FOUND,url);
if (!ident.empty()) {
if (parser(L"%1:%2@",ident)) {
username = parser[1].str();
password = parser[2].str();
} else {
throw FileMsgException(THISLOCATION,0,url,"Invalid identification field in the url");
}
}
DWORD accessType;
switch (settings.proxyMode) {
case pmManual: accessType = INTERNET_OPEN_TYPE_PROXY;
case pmDirect: accessType = INTERNET_OPEN_TYPE_DIRECT;
case pmAuto: accessType = INTERNET_OPEN_TYPE_PRECONFIG;
}
TextFormatBuff<wchar_t> fmt;
String proxyName;
if (accessType == INTERNET_OPEN_TYPE_PROXY) {
fmt(L"%1:%2") << settings.proxyAddr << settings.proxyPort;
proxyName = fmt.write();
}
if (hInternet) InternetCloseHandle(hInternet);
hInternet = InternetOpenW(settings.userAgent.cStr(),accessType,proxyName.cStr(),0,0);
if (hInternet == 0)
throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot initialize WinInet");
if (hConnect) InternetCloseHandle(hConnect);
hConnect = InternetConnectW(hInternet,domain.cStr(),(INTERNET_PORT)port,
username.empty()?0:username.cStr(),
password.empty()?0:password.cStr(),
INTERNET_SERVICE_HTTP ,0,0);
if (hConnect == 0)
throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot connect remote site");
DWORD reqFlags = INTERNET_FLAG_NO_UI |INTERNET_FLAG_HYPERLINK ;
if (redirDisabled) reqFlags|=INTERNET_FLAG_NO_AUTO_REDIRECT ;
if (!settings.cookiesEnabled) reqFlags|=INTERNET_FLAG_NO_COOKIES;
if (secure) reqFlags|=INTERNET_FLAG_SECURE;
hHTTPConn = HttpOpenRequestW(hConnect,String(method).cStr(),path.cStr(),
0,0,0,reqFlags,0);
if (hHTTPConn == 0)
throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot connect remote site");
AutoArray<wchar_t> hdrall;
for (HeaderMap::Iterator iter = hdrmap.getFwIter(); iter.hasItems();) {
const HeaderMap::Entity &e = iter.getNext();
fmt(L"%1: %2\n") << e.key << e.value;
hdrall.append(fmt.write());
}
if (!hdrall.empty() &&
!HttpAddRequestHeadersW(hHTTPConn,hdrall.data(),(DWORD)hdrall.length(),HTTP_ADDREQ_FLAG_REPLACE|HTTP_ADDREQ_FLAG_ADD))
throw FileMsgException(THISLOCATION,GetLastError(),url,"AddRequest failed");
if (!HttpSendRequestW(hHTTPConn,0,0,postBuffer.data(),(DWORD)postBuffer.length())) {
bool stillError = true;
DWORD dwError = GetLastError();
if (dwError == ERROR_INTERNET_INVALID_CA && settings.allowUntrustedCert) {
DWORD dwFlags;
DWORD dwBuffLen = sizeof(dwFlags);
InternetQueryOption (hHTTPConn, INTERNET_OPTION_SECURITY_FLAGS,
(LPVOID)&dwFlags, &dwBuffLen);
dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
InternetSetOption (hHTTPConn, INTERNET_OPTION_SECURITY_FLAGS,
&dwFlags, sizeof (dwFlags) );
if (HttpSendRequestW(hHTTPConn,0,0,postBuffer.data(),(DWORD)postBuffer.length()))
stillError = false;
}
if (stillError)
throw FileMsgException(THISLOCATION,GetLastError(),url,"Failed to SendRequest");
}
postBuffer.clear();
}
void WinHttpStream::sendRequest()
{
if (!exceptionDisabled) {
curState = stReadResponse;
natural status = getStatusCode();
if (status >= 300)
throw HttpStatusException(THISLOCATION,url,status,String());
}
}
bool WinHttpStream::inConnected() const
{
return curState != stIdle;
}
LightSpeed::ConstStrA WinHttpStream::getHeader( ConstStrA field )
{
class FillHdrMap: public IEnumHeaders {
public:
HeaderMap &hdrmap;
FillHdrMap(HeaderMap &hdrmap):hdrmap(hdrmap) {}
virtual bool operator()(ConstStrA field, ConstStrA value) {
hdrmap.insert(field, value);
return false;
}
};
if (curState != stReadResponse) {
setState(stReadResponse);
hdrmap.clear();
FillHdrMap x(hdrmap);
enumHeaders(x);
}
StringA *k = hdrmap.find(StringAI(field));
if (k == 0) return ConstStrA();
else return *k;
}
bool WinHttpStream::enumHeaders( IEnumHeaders &enumHdr )
{
setState(stReadResponse);
AutoArray<char> buffer;
buffer.resize(1000);
DWORD size = (DWORD)buffer.length();
while (!HttpQueryInfoA(hHTTPConn,HTTP_QUERY_RAW_HEADERS,
buffer.data(),&size,0)) {
DWORD res = GetLastError();
if (res == ERROR_INSUFFICIENT_BUFFER) {
buffer.resize(size);
} else {
throw ErrNoWithDescException(THISLOCATION,GetLastError(),
"Cannot retrieve headers from the request");
}
}
buffer.resize(size);
AutoArray<char>::SplitIterator iter=buffer.split((char)0);
TextParser<char> parser;
while (iter.hasItems()) {
ConstStrA line = iter.getNext();
if (parser("%1 : %2",line)) {
ConstStrA field = parser[1].str();
ConstStrA value = parser[2].str();
if(enumHdr(field, value)) return true;
}
}
return false;
}
void WinHttpStream::closeOutput()
{
setState(stReadResponse);
}
}
<|endoftext|> |
<commit_before>/**
* @file Version.hpp
* @brief Version class prototype.
* @author zer0
* @date 2017-05-25
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_UTIL_VERSION_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_UTIL_VERSION_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Err.hpp>
#include <cstdint>
#include <string>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace util {
/**
* Version class prototype.
*
* @author zer0
* @date 2017-05-25
*/
class TBAG_API Version
{
public:
TBAG_CONSTEXPR static char const * const POINT_STR = ".";
private:
uint32_t _major;
uint32_t _minor;
uint32_t _patch;
public:
Version() TBAG_NOEXCEPT;
Version(uint32_t major, uint32_t minor = 0, uint32_t patch = 0) TBAG_NOEXCEPT;
Version(Version const & obj) TBAG_NOEXCEPT;
Version(Version && obj) TBAG_NOEXCEPT;
~Version();
public:
Version & operator =(Version const & obj) TBAG_NOEXCEPT;
Version & operator =(Version && obj) TBAG_NOEXCEPT;
public:
inline uint32_t getMajor() const TBAG_NOEXCEPT { return _major; }
inline uint32_t getMinor() const TBAG_NOEXCEPT { return _minor; }
inline uint32_t getPatch() const TBAG_NOEXCEPT { return _patch; }
inline void setMajor(uint32_t val) TBAG_NOEXCEPT { _major = val; }
inline void setMinor(uint32_t val) TBAG_NOEXCEPT { _minor = val; }
inline void setPatch(uint32_t val) TBAG_NOEXCEPT { _patch = val; }
inline void set(uint32_t major = 0, uint32_t minor = 0, uint32_t patch = 0) TBAG_NOEXCEPT
{ _major = major; _minor = minor; _patch = patch; }
public:
void clear() TBAG_NOEXCEPT;
void swap(Version & obj) TBAG_NOEXCEPT;
public:
inline friend bool operator ==(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{ return lh._major == rh._major && lh._minor == rh._minor && lh._patch == rh._patch; }
inline friend bool operator !=(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{ return !(lh == rh); }
inline friend bool operator <(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{
#ifndef _TBAG_VERSION_LT_SINGLE
#define _TBAG_VERSION_LT_SINGLE(lh, rh) \
if (lh < rh) { return true; } else if (lh > rh) { return false; }
#endif
_TBAG_VERSION_LT_SINGLE(lh._major, rh._major);
_TBAG_VERSION_LT_SINGLE(lh._minor, rh._minor);
_TBAG_VERSION_LT_SINGLE(lh._patch, rh._patch);
#undef _TBAG_VERSION_LT_SINGLE
return false;
}
inline friend bool operator >(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{
#ifndef _TBAG_VERSION_GT_SINGLE
#define _TBAG_VERSION_GT_SINGLE(lh, rh) \
if (lh > rh) { return true; } else if (lh < rh) { return false; }
#endif
_TBAG_VERSION_GT_SINGLE(lh._major, rh._major);
_TBAG_VERSION_GT_SINGLE(lh._minor, rh._minor);
_TBAG_VERSION_GT_SINGLE(lh._patch, rh._patch);
#undef _TBAG_VERSION_GT_SINGLE
return false;
}
inline friend bool operator <=(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{ return lh == rh || lh < rh; }
inline friend bool operator >=(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{ return lh == rh || lh > rh; }
public:
Err fromString(std::string const & version);
std::string toString();
public:
static Err fromString(std::string const & version, Version & result);
static std::string toString(Version const & version);
};
// --------------------
// Utilities functions.
// --------------------
TBAG_API Version getTbagVersion() TBAG_NOEXCEPT;
} // namespace util
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_UTIL_VERSION_HPP__
<commit_msg>Trivial commit.<commit_after>/**
* @file Version.hpp
* @brief Version class prototype.
* @author zer0
* @date 2017-05-25
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_UTIL_VERSION_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_UTIL_VERSION_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Err.hpp>
#include <cstdint>
#include <string>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace util {
/**
* Version class prototype.
*
* @author zer0
* @date 2017-05-25
*/
class TBAG_API Version
{
public:
TBAG_CONSTEXPR static char const * const POINT_STR = ".";
private:
uint32_t _major;
uint32_t _minor;
uint32_t _patch;
public:
Version() TBAG_NOEXCEPT;
Version(uint32_t major, uint32_t minor = 0, uint32_t patch = 0) TBAG_NOEXCEPT;
Version(Version const & obj) TBAG_NOEXCEPT;
Version(Version && obj) TBAG_NOEXCEPT;
~Version();
public:
Version & operator =(Version const & obj) TBAG_NOEXCEPT;
Version & operator =(Version && obj) TBAG_NOEXCEPT;
public:
inline uint32_t getMajor() const TBAG_NOEXCEPT { return _major; }
inline uint32_t getMinor() const TBAG_NOEXCEPT { return _minor; }
inline uint32_t getPatch() const TBAG_NOEXCEPT { return _patch; }
inline void setMajor(uint32_t val) TBAG_NOEXCEPT { _major = val; }
inline void setMinor(uint32_t val) TBAG_NOEXCEPT { _minor = val; }
inline void setPatch(uint32_t val) TBAG_NOEXCEPT { _patch = val; }
inline void set(uint32_t major = 0, uint32_t minor = 0, uint32_t patch = 0) TBAG_NOEXCEPT
{ _major = major; _minor = minor; _patch = patch; }
public:
void clear() TBAG_NOEXCEPT;
void swap(Version & obj) TBAG_NOEXCEPT;
public:
inline friend bool operator ==(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{ return lh._major == rh._major && lh._minor == rh._minor && lh._patch == rh._patch; }
inline friend bool operator !=(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{ return !(lh == rh); }
inline friend bool operator <(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{
#ifndef _TBAG_VERSION_LT_SINGLE
#define _TBAG_VERSION_LT_SINGLE(lh, rh) \
if (lh < rh) { return true; } else if (lh > rh) { return false; }
#endif
_TBAG_VERSION_LT_SINGLE(lh._major, rh._major);
_TBAG_VERSION_LT_SINGLE(lh._minor, rh._minor);
_TBAG_VERSION_LT_SINGLE(lh._patch, rh._patch);
#undef _TBAG_VERSION_LT_SINGLE
return false;
}
inline friend bool operator >(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{
#ifndef _TBAG_VERSION_GT_SINGLE
#define _TBAG_VERSION_GT_SINGLE(lh, rh) \
if (lh > rh) { return true; } else if (lh < rh) { return false; }
#endif
_TBAG_VERSION_GT_SINGLE(lh._major, rh._major);
_TBAG_VERSION_GT_SINGLE(lh._minor, rh._minor);
_TBAG_VERSION_GT_SINGLE(lh._patch, rh._patch);
#undef _TBAG_VERSION_GT_SINGLE
return false;
}
inline friend bool operator <=(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{ return !(lh > rh); }
inline friend bool operator >=(Version const & lh, Version const & rh) TBAG_NOEXCEPT
{ return !(lh < rh); }
public:
Err fromString(std::string const & version);
std::string toString();
public:
static Err fromString(std::string const & version, Version & result);
static std::string toString(Version const & version);
};
// --------------------
// Utilities functions.
// --------------------
TBAG_API Version getTbagVersion() TBAG_NOEXCEPT;
} // namespace util
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_UTIL_VERSION_HPP__
<|endoftext|> |
<commit_before>/**
* @file Process.cpp
* @brief Process class implementation.
* @author zer0
* @date 2017-02-03
*/
#include <libtbag/uvpp/Process.hpp>
#include <libtbag/log/Log.hpp>
#include <libtbag/uvpp/Loop.hpp>
#include <libtbag/uvpp/Stream.hpp>
#include <uv.h>
#include <sstream>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace uvpp {
using CharPtrs = std::vector<char*>;
using Stdios = std::vector<uv_stdio_container_t>;
// --------------------
// Global libuv events.
// --------------------
static void __global_uv_exit_cb__(uv_process_t * handle, int64_t exit_status, int term_signal)
{
// Type definition for callback passed in uv_process_options_t
// which will indicate the exit status and the signal that caused the process to terminate, if any.
Process * p = static_cast<Process*>(handle->data);
if (p == nullptr) {
tDLogE("__global_uv_exit_cb__() handle.data is nullptr.");
} else if (isDeletedAddress(p)) {
tDLogE("__global_uv_exit_cb__() handle.data is deleted.");
} else {
p->onExit(exit_status, term_signal);
}
}
/* inline */ namespace impl {
static bool updateOptions(Process::Options & options,
CharPtrs & args,
CharPtrs & envs,
Stdios & stdios,
uv_process_options_t & native)
{
std::size_t const ARGS_SIZE = options.args.size();
std::size_t const ENVS_SIZE = options.envs.size();
args.clear();
envs.clear();
args.resize(ARGS_SIZE + 2); // [EXE_PATH], [...], [NULL]
envs.resize(ENVS_SIZE + 1); // [...], [NULL]
// First: exe file path.
args[0] = &options.file[0];
// Argument pointers.
for (std::size_t index = 0; index < ARGS_SIZE; ++index) {
args[index + 1] = &options.args[index][0];
}
// Environment pointers.
for (std::size_t index = 0; index < ENVS_SIZE; ++index) {
envs[index] = &options.envs[index][0];
}
// Last: NULL pointer.
args[ARGS_SIZE + 1] = nullptr;
envs[ENVS_SIZE + 0] = nullptr;
native.exit_cb = __global_uv_exit_cb__;
// Path pointing to the program to be executed.
native.file = options.file.c_str();
// If non-null this represents a directory the subprocess should execute
// in. Stands for current working directory.
native.cwd = options.cwd.c_str();
// Command line arguments. args[0] should be the path to the program. On
// Windows this uses CreateProcess which concatenates the arguments into a
// string this can cause some strange errors. See the
// UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS flag on uv_process_flags.
native.args = &args[0];
// This will be set as the environ variable in the subprocess. If this is
// NULL then the parents environ will be used.
native.env = &envs[0];
static_assert(sizeof(native.uid) == sizeof(options.uid), "Not equal uid size type.");
static_assert(sizeof(native.gid) == sizeof(options.gid), "Not equal gid size type.");
// Libuv can change the child process user/group id. This happens only when
// the appropriate bits are set in the flags fields.
// Note: This is not supported on Windows, uv_spawn() will fail and set the error to UV_ENOTSUP.
native.uid = options.uid;
native.gid = options.gid;
// Various flags that control how uv_spawn() behaves. See the definition of
// 'enum uv_process_flags' below.
native.flags = 0;
native.flags |= (options.setuid ? UV_PROCESS_SETUID : 0);
native.flags |= (options.setgid ? UV_PROCESS_SETGID : 0);
// Do not wrap any arguments in quotes, or perform any other escaping, when
// converting the argument list into a command line string. This option is
// only meaningful on Windows systems. On Unix it is silently ignored.
native.flags |= (options.verbatim_args ? UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS : 0);
// Spawn the child process in a detached state - this will make it a process
// group leader, and will effectively enable the child to keep running after
// the parent exits. Note that the child process will still keep the
// parent's event loop alive unless the parent process calls uv_unref() on
// the child's process handle.
native.flags |= (options.detached ? UV_PROCESS_DETACHED : 0);
// Hide the subprocess console window that would normally be created. This
// option is only meaningful on Windows systems. On Unix it is silently
// ignored.
native.flags |= (options.hide ? UV_PROCESS_WINDOWS_HIDE : 0);
std::size_t const STDIOS_SIZE = options.stdios.size();
native.stdio_count = static_cast<int>(options.stdios.size());
stdios.clear();
stdios.resize(STDIOS_SIZE);
native.stdio = &stdios[0];
// The 'stdio' field points to an array of uv_stdio_container_t structs that
// describe the file descriptors that will be made available to the child
// process. The convention is that stdio[0] points to stdin, fd 1 is used for
// stdout, and fd 2 is stderr.
//
// Note: that on windows file descriptors greater than 2 are available to the
// child process only if the child processes uses the MSVCRT runtime.
for (std::size_t index = 0; index < STDIOS_SIZE; ++index) {
Process::StdioContainer & stdio = options.stdios[index];
if (stdio.ignore) {
stdios[index].flags = static_cast<uv_stdio_flags>(UV_IGNORE);
} else {
stdios[index].flags = static_cast<uv_stdio_flags>(0);
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.create_pipe ? UV_CREATE_PIPE : 0));
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.inherit_fd ? UV_INHERIT_FD : 0));
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.inherit_stream ? UV_INHERIT_STREAM : 0));
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.readable_pipe ? UV_READABLE_PIPE : 0));
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.writable_pipe ? UV_WRITABLE_PIPE : 0));
if (stdio.type == Process::StdioContainer::Type::STDIO_CONTAINER_STREAM && stdio.stream != nullptr) {
stdios[index].data.stream = stdio.stream->cast<uv_stream_t>();
} else /*if (stdio.type == Process::StdioContainer::Type::STDIO_CONTAINER_FD)*/ {
stdios[index].data.fd = stdio.fd;
}
}
}
return true;
}
} // namespace impl
// ---------------------------------------
// Process::StdioContainer implementation.
// ---------------------------------------
Process::StdioContainer::StdioContainer() : type(Type::STDIO_CONTAINER_FD), stream(nullptr), fd(0),
ignore(false), create_pipe(false), inherit_fd(false), inherit_stream(false),
readable_pipe(false), writable_pipe(false)
{
// EMPTY.
}
Process::StdioContainer::StdioContainer(Stream * s, bool inherit) : StdioContainer()
{
type = Type::STDIO_CONTAINER_STREAM;
stream = s;
inherit_stream = inherit;
}
Process::StdioContainer::StdioContainer(int f, bool inherit) : StdioContainer()
{
type = Type::STDIO_CONTAINER_FD;
fd = f;
inherit_fd = inherit;
}
Process::StdioContainer::~StdioContainer()
{
// EMPTY.
}
Process::StdioContainer & Process::StdioContainer::clear()
{
type = Type::STDIO_CONTAINER_FD;
stream = nullptr;
fd = 0;
ignore = false;
create_pipe = false;
inherit_fd = false;
inherit_stream = false;
readable_pipe = false;
writable_pipe = false;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setStream(Stream * s)
{
type = Type::STDIO_CONTAINER_STREAM;
stream = s;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setFd(int f)
{
type = Type::STDIO_CONTAINER_FD;
fd = f;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setIgnore()
{
ignore = true;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setCreatePipe(bool flag)
{
create_pipe = flag;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setInheritFd(bool flag)
{
inherit_fd = flag;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setInheritStream(bool flag)
{
inherit_stream = flag;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setReadablePipe(bool flag)
{
readable_pipe = flag;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setWritablePipe(bool flag)
{
writable_pipe = flag;
return *this;
}
// --------------------------------
// Process::Options implementation.
// --------------------------------
Process::Options::Options() : file(), cwd(), args(), envs(), stdios(),
uid(0), gid(0), setuid(false), setgid(false),
detached(false), verbatim_args(false), hide(false)
{
// EMPTY.
}
Process::Options::~Options()
{
// EMPTY.
}
Process::Options & Process::Options::clear()
{
file.clear();
cwd.clear();
args.clear();
envs.clear();
stdios.clear();
uid = 0;
gid = 0;
setuid = false;
setgid = false;
detached = false;
verbatim_args = false;
hide = false;
return *this;
}
Process::Options & Process::Options::setFile(std::string const & path)
{
file = path;
return *this;
}
Process::Options & Process::Options::setWorking(std::string const & dir)
{
cwd = dir;
return *this;
}
Process::Options & Process::Options::setCurrentWorking()
{
cwd = filesystem::Path::getWorkDir().getString();
return *this;
}
Process::Options & Process::Options::appendArgument(std::string const & arg)
{
args.push_back(arg);
return *this;
}
Process::Options & Process::Options::appendEnvironment(std::string const & env)
{
envs.push_back(env);
return *this;
}
Process::Options & Process::Options::appendStdio(StdioContainer const & io)
{
stdios.push_back(io);
return *this;
}
Process::Options & Process::Options::setUserId(uuser id, bool enable)
{
uid = id;
setuid = enable;
return *this;
}
Process::Options & Process::Options::setGroupId(ugroup id, bool enable)
{
gid = id;
setgid = enable;
return *this;
}
Process::Options & Process::Options::setDetached(bool flag)
{
detached = flag;
return *this;
}
Process::Options & Process::Options::setVerbatimArguments(bool flag)
{
verbatim_args = flag;
return *this;
}
Process::Options & Process::Options::setHide(bool flag)
{
hide = flag;
return *this;
}
std::string Process::Options::getAllArguments() const
{
std::stringstream ss;
std::size_t const SIZE = args.size();
for (std::size_t i = 0; i < SIZE; ++i) {
ss << args[i];
if (i + 1 < SIZE) {
ss << ' ';
}
}
return ss.str();
}
// -----------------------
// Process implementation.
// -----------------------
Process::Process(Loop & loop, Options const & options) : Handle(uhandle::PROCESS)
{
if (spawn(loop, options) != Err::E_SUCCESS) {
throw std::bad_alloc();
}
}
Process::~Process()
{
// EMPTY.
}
int Process::getPid() const
{
return Parent::cast<uv_process_t>()->pid;
}
Err Process::spawn(Loop & loop, Options const & options)
{
_options = options; // IMPORTANT!!
uv_process_options_t uv_options = {0,};
CharPtrs args;
CharPtrs envs;
Stdios stdios;
if (impl::updateOptions(_options, args, envs, stdios, uv_options) == false) {
tDLogE("Process::spawn() options error.");
return Err::E_ILLARGS;
}
// If the process is successfully spawned, this function will return 0.
// Otherwise, the negative error code corresponding to the reason it couldn’t spawn is returned.
//
// Possible reasons for failing to spawn would include
// (but not be limited to) the file to execute not existing,
// not having permissions to use the setuid or setgid specified,
// or not having enough memory to allocate for the new process.
tDLogD("Process::spawn() {} {}", _options.file, _options.getAllArguments());
int const CODE = ::uv_spawn(loop.cast<uv_loop_t>(), Parent::cast<uv_process_t>(), &uv_options);
return convertUvErrorToErrWithLogging("Process::spawn()", CODE);
}
Err Process::processKill(int signum)
{
// uv_signal_t - Signal handle for signal support, specially on Windows.
int const CODE = ::uv_process_kill(Parent::cast<uv_process_t>(), signum);
return convertUvErrorToErrWithLogging("Process::processKill()", CODE);
}
// --------------
// Event methods.
// --------------
void Process::onExit(int64_t exit_status, int term_signal)
{
tDLogD("Process::onExit({}, {}) called.", exit_status, term_signal);
}
// ---------------
// Static methods.
// ---------------
void Process::disableStdioInheritance()
{
// The effect is that child processes spawned by this process don’t accidentally inherit these handles.
//
// It is recommended to call this function as early in your program as possible,
// before the inherited file descriptors can be closed or duplicated.
//
// Note:
// This function works on a best-effort basis:
// there is no guarantee that libuv can discover all file descriptors that were inherited.
// In general it does a better job on Windows than it does on Unix.
::uv_disable_stdio_inheritance();
}
Err Process::kill(int pid, int signum)
{
// uv_signal_t - Signal handle for signal support, specially on Windows.
int const CODE = ::uv_kill(pid, signum);
return convertUvErrorToErrWithLogging("Process::kill()", CODE);
}
} // namespace uvpp
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
<commit_msg>Fixed SIGABRT of Process class compiled in MSVC.<commit_after>/**
* @file Process.cpp
* @brief Process class implementation.
* @author zer0
* @date 2017-02-03
*/
#include <libtbag/uvpp/Process.hpp>
#include <libtbag/log/Log.hpp>
#include <libtbag/uvpp/Loop.hpp>
#include <libtbag/uvpp/Stream.hpp>
#include <uv.h>
#include <sstream>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace uvpp {
using CharPtrs = std::vector<char*>;
using Stdios = std::vector<uv_stdio_container_t>;
// --------------------
// Global libuv events.
// --------------------
static void __global_uv_exit_cb__(uv_process_t * handle, int64_t exit_status, int term_signal)
{
// Type definition for callback passed in uv_process_options_t
// which will indicate the exit status and the signal that caused the process to terminate, if any.
Process * p = static_cast<Process*>(handle->data);
if (p == nullptr) {
tDLogE("__global_uv_exit_cb__() handle.data is nullptr.");
} else if (isDeletedAddress(p)) {
tDLogE("__global_uv_exit_cb__() handle.data is deleted.");
} else {
p->onExit(exit_status, term_signal);
}
}
/* inline */ namespace impl {
static bool updateOptions(Process::Options & options,
CharPtrs & args,
CharPtrs & envs,
Stdios & stdios,
uv_process_options_t & native)
{
std::size_t const ARGS_SIZE = options.args.size();
std::size_t const ENVS_SIZE = options.envs.size();
args.clear();
envs.clear();
args.resize(ARGS_SIZE + 2); // [EXE_PATH], [...], [NULL]
envs.resize(ENVS_SIZE + 1); // [...], [NULL]
// First: exe file path.
args[0] = &options.file[0];
// Argument pointers.
for (std::size_t index = 0; index < ARGS_SIZE; ++index) {
args[index + 1] = &options.args[index][0];
}
// Environment pointers.
for (std::size_t index = 0; index < ENVS_SIZE; ++index) {
envs[index] = &options.envs[index][0];
}
// Last: NULL pointer.
args[ARGS_SIZE + 1] = nullptr;
envs[ENVS_SIZE + 0] = nullptr;
native.exit_cb = __global_uv_exit_cb__;
// Path pointing to the program to be executed.
native.file = options.file.c_str();
// If non-null this represents a directory the subprocess should execute
// in. Stands for current working directory.
native.cwd = options.cwd.c_str();
// Command line arguments. args[0] should be the path to the program. On
// Windows this uses CreateProcess which concatenates the arguments into a
// string this can cause some strange errors. See the
// UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS flag on uv_process_flags.
native.args = &args[0];
// This will be set as the environ variable in the subprocess. If this is
// NULL then the parents environ will be used.
native.env = &envs[0];
static_assert(sizeof(native.uid) == sizeof(options.uid), "Not equal uid size type.");
static_assert(sizeof(native.gid) == sizeof(options.gid), "Not equal gid size type.");
// Libuv can change the child process user/group id. This happens only when
// the appropriate bits are set in the flags fields.
// Note: This is not supported on Windows, uv_spawn() will fail and set the error to UV_ENOTSUP.
native.uid = options.uid;
native.gid = options.gid;
// Various flags that control how uv_spawn() behaves. See the definition of
// 'enum uv_process_flags' below.
native.flags = 0;
native.flags |= (options.setuid ? UV_PROCESS_SETUID : 0);
native.flags |= (options.setgid ? UV_PROCESS_SETGID : 0);
// Do not wrap any arguments in quotes, or perform any other escaping, when
// converting the argument list into a command line string. This option is
// only meaningful on Windows systems. On Unix it is silently ignored.
native.flags |= (options.verbatim_args ? UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS : 0);
// Spawn the child process in a detached state - this will make it a process
// group leader, and will effectively enable the child to keep running after
// the parent exits. Note that the child process will still keep the
// parent's event loop alive unless the parent process calls uv_unref() on
// the child's process handle.
native.flags |= (options.detached ? UV_PROCESS_DETACHED : 0);
// Hide the subprocess console window that would normally be created. This
// option is only meaningful on Windows systems. On Unix it is silently
// ignored.
native.flags |= (options.hide ? UV_PROCESS_WINDOWS_HIDE : 0);
std::size_t const STDIOS_SIZE = options.stdios.size();
native.stdio_count = static_cast<int>(options.stdios.size());
stdios.clear();
stdios.resize(STDIOS_SIZE);
if (stdios.empty()) {
native.stdio = nullptr;
} else {
native.stdio = &stdios[0];
}
// The 'stdio' field points to an array of uv_stdio_container_t structs that
// describe the file descriptors that will be made available to the child
// process. The convention is that stdio[0] points to stdin, fd 1 is used for
// stdout, and fd 2 is stderr.
//
// Note: that on windows file descriptors greater than 2 are available to the
// child process only if the child processes uses the MSVCRT runtime.
for (std::size_t index = 0; index < STDIOS_SIZE; ++index) {
Process::StdioContainer & stdio = options.stdios[index];
if (stdio.ignore) {
stdios[index].flags = static_cast<uv_stdio_flags>(UV_IGNORE);
} else {
stdios[index].flags = static_cast<uv_stdio_flags>(0);
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.create_pipe ? UV_CREATE_PIPE : 0));
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.inherit_fd ? UV_INHERIT_FD : 0));
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.inherit_stream ? UV_INHERIT_STREAM : 0));
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.readable_pipe ? UV_READABLE_PIPE : 0));
stdios[index].flags = static_cast<uv_stdio_flags>(stdios[index].flags | (stdio.writable_pipe ? UV_WRITABLE_PIPE : 0));
if (stdio.type == Process::StdioContainer::Type::STDIO_CONTAINER_STREAM && stdio.stream != nullptr) {
stdios[index].data.stream = stdio.stream->cast<uv_stream_t>();
} else /*if (stdio.type == Process::StdioContainer::Type::STDIO_CONTAINER_FD)*/ {
stdios[index].data.fd = stdio.fd;
}
}
}
return true;
}
} // namespace impl
// ---------------------------------------
// Process::StdioContainer implementation.
// ---------------------------------------
Process::StdioContainer::StdioContainer() : type(Type::STDIO_CONTAINER_FD), stream(nullptr), fd(0),
ignore(false), create_pipe(false), inherit_fd(false), inherit_stream(false),
readable_pipe(false), writable_pipe(false)
{
// EMPTY.
}
Process::StdioContainer::StdioContainer(Stream * s, bool inherit) : StdioContainer()
{
type = Type::STDIO_CONTAINER_STREAM;
stream = s;
inherit_stream = inherit;
}
Process::StdioContainer::StdioContainer(int f, bool inherit) : StdioContainer()
{
type = Type::STDIO_CONTAINER_FD;
fd = f;
inherit_fd = inherit;
}
Process::StdioContainer::~StdioContainer()
{
// EMPTY.
}
Process::StdioContainer & Process::StdioContainer::clear()
{
type = Type::STDIO_CONTAINER_FD;
stream = nullptr;
fd = 0;
ignore = false;
create_pipe = false;
inherit_fd = false;
inherit_stream = false;
readable_pipe = false;
writable_pipe = false;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setStream(Stream * s)
{
type = Type::STDIO_CONTAINER_STREAM;
stream = s;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setFd(int f)
{
type = Type::STDIO_CONTAINER_FD;
fd = f;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setIgnore()
{
ignore = true;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setCreatePipe(bool flag)
{
create_pipe = flag;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setInheritFd(bool flag)
{
inherit_fd = flag;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setInheritStream(bool flag)
{
inherit_stream = flag;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setReadablePipe(bool flag)
{
readable_pipe = flag;
return *this;
}
Process::StdioContainer & Process::StdioContainer::setWritablePipe(bool flag)
{
writable_pipe = flag;
return *this;
}
// --------------------------------
// Process::Options implementation.
// --------------------------------
Process::Options::Options() : file(), cwd(), args(), envs(), stdios(),
uid(0), gid(0), setuid(false), setgid(false),
detached(false), verbatim_args(false), hide(false)
{
// EMPTY.
}
Process::Options::~Options()
{
// EMPTY.
}
Process::Options & Process::Options::clear()
{
file.clear();
cwd.clear();
args.clear();
envs.clear();
stdios.clear();
uid = 0;
gid = 0;
setuid = false;
setgid = false;
detached = false;
verbatim_args = false;
hide = false;
return *this;
}
Process::Options & Process::Options::setFile(std::string const & path)
{
file = path;
return *this;
}
Process::Options & Process::Options::setWorking(std::string const & dir)
{
cwd = dir;
return *this;
}
Process::Options & Process::Options::setCurrentWorking()
{
cwd = filesystem::Path::getWorkDir().getString();
return *this;
}
Process::Options & Process::Options::appendArgument(std::string const & arg)
{
args.push_back(arg);
return *this;
}
Process::Options & Process::Options::appendEnvironment(std::string const & env)
{
envs.push_back(env);
return *this;
}
Process::Options & Process::Options::appendStdio(StdioContainer const & io)
{
stdios.push_back(io);
return *this;
}
Process::Options & Process::Options::setUserId(uuser id, bool enable)
{
uid = id;
setuid = enable;
return *this;
}
Process::Options & Process::Options::setGroupId(ugroup id, bool enable)
{
gid = id;
setgid = enable;
return *this;
}
Process::Options & Process::Options::setDetached(bool flag)
{
detached = flag;
return *this;
}
Process::Options & Process::Options::setVerbatimArguments(bool flag)
{
verbatim_args = flag;
return *this;
}
Process::Options & Process::Options::setHide(bool flag)
{
hide = flag;
return *this;
}
std::string Process::Options::getAllArguments() const
{
std::stringstream ss;
std::size_t const SIZE = args.size();
for (std::size_t i = 0; i < SIZE; ++i) {
ss << args[i];
if (i + 1 < SIZE) {
ss << ' ';
}
}
return ss.str();
}
// -----------------------
// Process implementation.
// -----------------------
Process::Process(Loop & loop, Options const & options) : Handle(uhandle::PROCESS)
{
if (spawn(loop, options) != Err::E_SUCCESS) {
throw std::bad_alloc();
}
}
Process::~Process()
{
// EMPTY.
}
int Process::getPid() const
{
return Parent::cast<uv_process_t>()->pid;
}
Err Process::spawn(Loop & loop, Options const & options)
{
_options = options; // IMPORTANT!!
uv_process_options_t uv_options = {0,};
CharPtrs args;
CharPtrs envs;
Stdios stdios;
if (impl::updateOptions(_options, args, envs, stdios, uv_options) == false) {
tDLogE("Process::spawn() options error.");
return Err::E_ILLARGS;
}
// If the process is successfully spawned, this function will return 0.
// Otherwise, the negative error code corresponding to the reason it couldn’t spawn is returned.
//
// Possible reasons for failing to spawn would include
// (but not be limited to) the file to execute not existing,
// not having permissions to use the setuid or setgid specified,
// or not having enough memory to allocate for the new process.
tDLogD("Process::spawn() {} {}", _options.file, _options.getAllArguments());
int const CODE = ::uv_spawn(loop.cast<uv_loop_t>(), Parent::cast<uv_process_t>(), &uv_options);
return convertUvErrorToErrWithLogging("Process::spawn()", CODE);
}
Err Process::processKill(int signum)
{
// uv_signal_t - Signal handle for signal support, specially on Windows.
int const CODE = ::uv_process_kill(Parent::cast<uv_process_t>(), signum);
return convertUvErrorToErrWithLogging("Process::processKill()", CODE);
}
// --------------
// Event methods.
// --------------
void Process::onExit(int64_t exit_status, int term_signal)
{
tDLogD("Process::onExit({}, {}) called.", exit_status, term_signal);
}
// ---------------
// Static methods.
// ---------------
void Process::disableStdioInheritance()
{
// The effect is that child processes spawned by this process don’t accidentally inherit these handles.
//
// It is recommended to call this function as early in your program as possible,
// before the inherited file descriptors can be closed or duplicated.
//
// Note:
// This function works on a best-effort basis:
// there is no guarantee that libuv can discover all file descriptors that were inherited.
// In general it does a better job on Windows than it does on Unix.
::uv_disable_stdio_inheritance();
}
Err Process::kill(int pid, int signum)
{
// uv_signal_t - Signal handle for signal support, specially on Windows.
int const CODE = ::uv_kill(pid, signum);
return convertUvErrorToErrWithLogging("Process::kill()", CODE);
}
} // namespace uvpp
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef TWSM_SERVER_BROWSER
#define TWSM_SERVER_BROWSER
#include "popup_manager.hpp"
#include "ui_main_window.h"
#include <mlk/log/log.h>
#include <mlk/time/simple_timer.h>
#include <twl/network/network.hpp>
#include <QObject>
#include <QTableWidgetItem>
namespace Ui
{class main_window;}
namespace twsm
{
class server_browser : public QObject
{
Q_OBJECT
Ui::main_window& m_ui;
popup_manager& m_popupmgr;
twl::master_server m_masters;
twl::game_server m_servers;
mlk::tm::simple_timer m_stopwatch{0};
bool m_refreshing_masters{false}, m_refreshing{false};
public:
server_browser(Ui::main_window& ui, popup_manager& pm) :
m_ui(ui),
m_popupmgr(pm)
{ }
void update()
{
m_masters.update();
m_servers.update();
}
void init()
{
mlk::lout("server_browser", true) << "init. setting default masters. setting up events.";
// setup default masters
m_masters.add_master({"master1.teeworlds.com:8300"});
m_masters.add_master({"master2.teeworlds.com:8300"});
m_masters.add_master({"master3.teeworlds.com:8300"});
m_masters.add_master({"master4.teeworlds.com:8300"});
// setup events
m_masters.on_finish = [this]{this->masters_finished();};
m_servers.on_finish = [this]{this->servers_finished();};
// ui events
QObject::connect(m_ui.m_pb_srvb_refresh, SIGNAL(clicked()), this, SLOT(refresh()));
}
public slots:
void refresh()
{
// reset ui
m_ui.m_tw_srvb_list->clearContents();
m_ui.m_tw_srvb_list->setRowCount(0);
m_ui.m_lb_srvb_status->setText("Refreshing masters...");
// request masterlist
m_refreshing_masters = true;
m_masters.request_list();
}
private:
void masters_finished()
{
// master refresh finished
m_refreshing_masters = false;
m_refreshing = true;
auto ips(m_masters.get_list());
mlk::lout("server_browser") << "refreshed masters. got " << ips.size() << " ips.";
if(ips.empty())
{
m_ui.m_lb_srvb_status->setText("Got no servers from masters. Stopping refreshing.");
return;
}
m_ui.m_lb_srvb_status->setText(QString{"Refreshed masters, processing %1 servers..."}.arg(ips.size()));
// make ready for server refreshing
m_servers.reset();
m_servers.add_masterlist(ips);
m_servers.request_info();
m_stopwatch.restart();
}
void servers_finished()
{
// server refresh finished
m_refreshing = false;
auto tm(m_stopwatch.elapsed_time());
mlk::lout("server_browser") << "refreshed servers. (twl) processed " << m_servers.get_infos().size() << " servers in " << tm << "ms.";
m_ui.m_tw_srvb_list->setSortingEnabled(false);
for(auto& a : m_servers.get_infos())
{
m_ui.m_tw_srvb_list->insertRow(m_ui.m_tw_srvb_list->rowCount());
auto* name(new QTableWidgetItem{a.name().c_str()});
auto* type(new QTableWidgetItem{a.gametype().c_str()});
auto* map(new QTableWidgetItem{a.mapname().c_str()});
auto* players(new QTableWidgetItem{QString{"%1/%2"}.arg(a.numclients()).arg(a.maxclients())});
auto* ping(new QTableWidgetItem{QString{"%1"}.arg(a.ping())});
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 0, name);
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 1, type);
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 2, map);
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 3, players);
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 4, ping);
}
m_ui.m_tw_srvb_list->setSortingEnabled(true);
m_ui.m_lb_srvb_status->setText("Servers refreshed.");
m_popupmgr.create_popup<popup_type::info>("Serverlist refreshed");
mlk::lout("server_browser") << "ui took " << m_stopwatch.elapsed_time() - tm << " ms.";
}
};
}
#endif // TWSM_SERVER_BROWSER
<commit_msg>serverbrowser: fixed defines<commit_after>//
// Copyright (c) 2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef TWSM_SERVER_BROWSER_HPP
#define TWSM_SERVER_BROWSER_HPP
#include "popup_manager.hpp"
#include "ui_main_window.h"
#include <mlk/log/log.h>
#include <mlk/time/simple_timer.h>
#include <twl/network/network.hpp>
#include <QObject>
#include <QTableWidgetItem>
namespace Ui
{class main_window;}
namespace twsm
{
class server_browser : public QObject
{
Q_OBJECT
Ui::main_window& m_ui;
popup_manager& m_popupmgr;
twl::master_server m_masters;
twl::game_server m_servers;
mlk::tm::simple_timer m_stopwatch{0};
bool m_refreshing_masters{false}, m_refreshing{false};
public:
server_browser(Ui::main_window& ui, popup_manager& pm) :
m_ui(ui),
m_popupmgr(pm)
{ }
void update()
{
m_masters.update();
m_servers.update();
}
void init()
{
mlk::lout("server_browser", true) << "init. setting default masters. setting up events.";
// setup default masters
m_masters.add_master({"master1.teeworlds.com:8300"});
m_masters.add_master({"master2.teeworlds.com:8300"});
m_masters.add_master({"master3.teeworlds.com:8300"});
m_masters.add_master({"master4.teeworlds.com:8300"});
// setup events
m_masters.on_finish = [this]{this->masters_finished();};
m_servers.on_finish = [this]{this->servers_finished();};
// ui events
QObject::connect(m_ui.m_pb_srvb_refresh, SIGNAL(clicked()), this, SLOT(refresh()));
}
public slots:
void refresh()
{
// reset ui
m_ui.m_tw_srvb_list->clearContents();
m_ui.m_tw_srvb_list->setRowCount(0);
m_ui.m_lb_srvb_status->setText("Refreshing masters...");
// request masterlist
m_refreshing_masters = true;
m_masters.request_list();
}
private:
void masters_finished()
{
// master refresh finished
m_refreshing_masters = false;
m_refreshing = true;
auto ips(m_masters.get_list());
mlk::lout("server_browser") << "refreshed masters. got " << ips.size() << " ips.";
if(ips.empty())
{
m_ui.m_lb_srvb_status->setText("Got no servers from masters. Stopping refreshing.");
return;
}
m_ui.m_lb_srvb_status->setText(QString{"Refreshed masters, processing %1 servers..."}.arg(ips.size()));
// make ready for server refreshing
m_servers.reset();
m_servers.add_masterlist(ips);
m_servers.request_info();
m_stopwatch.restart();
}
void servers_finished()
{
// server refresh finished
m_refreshing = false;
auto tm(m_stopwatch.elapsed_time());
mlk::lout("server_browser") << "refreshed servers. (twl) processed " << m_servers.get_infos().size() << " servers in " << tm << "ms.";
m_ui.m_tw_srvb_list->setSortingEnabled(false);
for(auto& a : m_servers.get_infos())
{
m_ui.m_tw_srvb_list->insertRow(m_ui.m_tw_srvb_list->rowCount());
auto* name(new QTableWidgetItem{a.name().c_str()});
auto* type(new QTableWidgetItem{a.gametype().c_str()});
auto* map(new QTableWidgetItem{a.mapname().c_str()});
auto* players(new QTableWidgetItem{QString{"%1/%2"}.arg(a.numclients()).arg(a.maxclients())});
auto* ping(new QTableWidgetItem{QString{"%1"}.arg(a.ping())});
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 0, name);
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 1, type);
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 2, map);
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 3, players);
m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 4, ping);
}
m_ui.m_tw_srvb_list->setSortingEnabled(true);
m_ui.m_lb_srvb_status->setText("Servers refreshed.");
m_popupmgr.create_popup<popup_type::info>("Serverlist refreshed");
mlk::lout("server_browser") << "ui took " << m_stopwatch.elapsed_time() - tm << " ms.";
}
};
}
#endif // TWSM_SERVER_BROWSER_HPP
<|endoftext|> |
<commit_before>/*
Copyright (C) 2002 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csqint.h"
#include "csqsqrt.h"
#include "csgeom/box.h"
#include "csgeom/math3d.h"
#include "csgeom/poly2d.h"
#include "csgeom/poly3d.h"
#include "csgeom/polyclip.h"
#include "csgeom/transfrm.h"
#include "csgeom/tri.h"
#include "csutil/scfstr.h"
#include "csutil/sysfunc.h"
#include "iengine/camera.h"
#include "iengine/movable.h"
#include "iutil/string.h"
#include "exvis.h"
//---------------------------------------------------------------------------
csExactCuller::csExactCuller (int w, int h)
{
width = w;
height = h;
scr_buffer = new uint32[w*h];
z_buffer = new float[w*h];
for (int i = 0 ; i < w*h ; i++)
{
scr_buffer[i] = (uint32)~0;
z_buffer[i] = 1000000000000.0f;
}
num_objects = 0;
max_objects = 100;
objects = new csExVisObj [max_objects];
boxclip = new csBoxClipper (0, 0, float (w), float (h));
}
csExactCuller::~csExactCuller ()
{
delete boxclip;
delete[] scr_buffer;
delete[] z_buffer;
delete[] objects;
}
void csExactCuller::InsertPolygon (csVector2* tr_verts, size_t num_verts,
float M, float N, float O, uint32 obj_number, int& totpix)
{
totpix = 0;
size_t i;
size_t min_i, max_i;
min_i = max_i = 0;
float min_y, max_y;
min_y = max_y = tr_verts[0].y;
// count 'real' number of vertices
int real_num_verts = 1;
for (i = 1 ; i < num_verts ; i++)
{
if (tr_verts[i].y > max_y)
{
max_y = tr_verts[i].y;
max_i = i;
}
else if (tr_verts[i].y < min_y)
{
min_y = tr_verts[i].y;
min_i = i;
}
if ((ABS (tr_verts [i].x - tr_verts [i - 1].x)
+ ABS (tr_verts [i].y - tr_verts [i - 1].y))
> 0.001)
real_num_verts++;
}
// If this is a 'degenerate' polygon, skip it.
if (real_num_verts < 3)
return;
size_t scanL1, scanL2, scanR1, scanR2; // scan vertex left/right start/final
float sxL, sxR, dxL, dxR; // scanline X left/right and deltas
int sy, fyL, fyR; // scanline Y, final Y l, final Y r
int xL, xR;
int screenY;
sxL = sxR = dxL = dxR = 0; // Avoid warnings about "uninit vars"
scanL2 = scanR2 = max_i;
sy = fyL = fyR = csQround (tr_verts [scanL2].y);
for ( ; ; )
{
//-----
// We have reached the next segment. Recalculate the slopes.
//-----
bool leave;
do
{
leave = true;
if (sy <= fyR)
{
// Check first if polygon has been finished
if (scanR2 == min_i)
return;
scanR1 = scanR2;
if (++scanR2 >= num_verts)
scanR2 = 0;
leave = false;
fyR = csQround (tr_verts [scanR2].y);
if (sy <= fyR)
continue;
float dyR = (tr_verts [scanR1].y - tr_verts [scanR2].y);
if (dyR)
{
sxR = tr_verts [scanR1].x;
dxR = (tr_verts [scanR2].x - sxR) / dyR;
// horizontal pixel correction
sxR += dxR * (tr_verts [scanR1].y - (float (sy) - 0.5));
}
}
if (sy <= fyL)
{
scanL1 = scanL2;
if (scanL2 == 0)
scanL2 = num_verts - 1;
else
scanL2 = scanL2 - 1;
leave = false;
fyL = csQround (tr_verts [scanL2].y);
if (sy <= fyL)
continue;
float dyL = (tr_verts [scanL1].y - tr_verts [scanL2].y);
if (dyL)
{
sxL = tr_verts [scanL1].x;
dxL = (tr_verts [scanL2].x - sxL) / dyL;
// horizontal pixel correction
sxL += dxL * (tr_verts [scanL1].y - (float (sy) - 0.5));
}
}
} while (!leave);
// Find the trapezoid top (or bottom in inverted Y coordinates)
int fin_y;
if (fyL > fyR)
fin_y = fyL;
else
fin_y = fyR;
screenY = height - sy;
while (sy > fin_y)
{
if (screenY >= 0 && screenY < height)
{
// Compute the rounded screen coordinates of horizontal strip
xL = csQround (sxL);
xR = csQround (sxR);
if (xR >= 0 && xL < width && xR != xL)
{
if (xL < 0) xL = 0;
if (xR >= width) xR = width-1;
uint32* scr_buf = scr_buffer + width * screenY + xL;
float* z_buf = z_buffer + width * screenY + xL;
float invz = M * (xL-width/2) + N * (sy-height/2) + O;
int xx = xR - xL;
if (xx > 0)
{
do
{
if (*scr_buf != obj_number) totpix++;
float z;
if (ABS (invz) > 0.001)
z = 1.0 / invz;
else
z = 9999999999999.0f;
if (z < *z_buf)
{
*scr_buf = obj_number;
*z_buf = z;
}
z_buf++;
scr_buf++;
invz += M;
xx--;
}
while (xx);
}
}
}
sxL += dxL;
sxR += dxR;
sy--;
screenY++;
}
}
}
static void Perspective (const csVector3& v, csVector2& p, float fov,
float sx, float sy)
{
float iz = fov / v.z;
p.x = v.x * iz + sx;
p.y = v.y * iz + sy;
}
void csExactCuller::AddObject (void* obj,
iTriangleMesh* trimesh, iMovable* movable, iCamera* camera,
const csPlane3* planes)
{
if (num_objects >= max_objects)
{
if (max_objects < 10000)
max_objects += max_objects+1;
else
max_objects += 2000;
csExVisObj* new_objects = new csExVisObj [max_objects];
memcpy (new_objects, objects, sizeof (csExVisObj)*num_objects);
delete[] objects;
objects = new_objects;
}
objects[num_objects].obj = obj;
objects[num_objects].totpix = 0;
objects[num_objects].vispix = 0;
num_objects++;
const csVector3* verts = trimesh->GetVertices ();
size_t vertex_count = trimesh->GetVertexCount ();
size_t tri_count = trimesh->GetTriangleCount ();
csReversibleTransform movtrans = movable->GetFullTransform ();
const csReversibleTransform& camtrans = camera->GetTransform ();
csReversibleTransform trans = camtrans / movtrans;
float fov = camera->GetFOV ();
float sx = camera->GetShiftX ();
float sy = camera->GetShiftY ();
// Calculate camera position in object space.
csVector3 campos_object = movtrans.Other2This (camtrans.GetOrigin ());
size_t i;
// First check visibility of all vertices.
bool* vis = new bool[vertex_count];
for (i = 0 ; i < vertex_count ; i++)
{
csVector3 camv = trans.Other2This (verts[i]);
vis[i] = (camv.z > 0.1);
}
// Then insert all polygons.
csTriangle* tri = trimesh->GetTriangles ();
for (i = 0 ; i < tri_count ; i++, tri++)
{
if (planes[i].Classify (campos_object) >= 0.0)
continue;
if (vis[tri->a] || vis[tri->b] || vis[tri->c])
{
// Here we need to clip the polygon.
csPoly3D clippoly;
clippoly.AddVertex (trans.Other2This (verts[tri->a]));
clippoly.AddVertex (trans.Other2This (verts[tri->b]));
clippoly.AddVertex (trans.Other2This (verts[tri->c]));
csPoly3D front, back;
csPoly3D* spoly;
if (!(vis[tri->a] && vis[tri->b] && vis[tri->c]))
{
clippoly.SplitWithPlaneZ (front, back, 0.1f);
spoly = &back;
}
else
{
spoly = &clippoly;
}
csVector2 clipped[100];
size_t num_clipped = spoly->GetVertexCount ();
csBox2 out_box;
out_box.StartBoundingBox ();
for (size_t k = 0 ; k < spoly->GetVertexCount () ; k++)
{
Perspective ((*spoly)[k], clipped[k], fov, sx, sy);
out_box.AddBoundingVertex (clipped[k]);
}
if (boxclip->ClipInPlace (clipped, num_clipped, out_box)
!= CS_CLIP_OUTSIDE)
{
//csPlane3 camplane = trans.Other2This (planes[i]);
csPlane3 camplane;
trans.Other2This (planes[i], (*spoly)[0], camplane);
//csPrintf (" %g,%g,%g\n", (*spoly)[0].x, (*spoly)[0].y, (*spoly)[0].z);
//csPrintf (" planes[i] %g,%g,%g,%g\n",
//planes[i].A (), planes[i].B (), planes[i].C (), planes[i].D ());
//csPrintf (" camplane %g,%g,%g,%g\n",
//camplane.A (), camplane.B (), camplane.C (), camplane.D ());
if (ABS (camplane.D ()) < 0.001)
continue;
float M, N, O;
float inv_D = 1.0 / camplane.D ();
M = -camplane.A () * inv_D / fov;
N = -camplane.B () * inv_D / fov;
O = -camplane.C () * inv_D;
//csPrintf (" MNO %g,%g,%g\n", M, N, O);
//fflush (stdout);
int totpix;
InsertPolygon (clipped, num_clipped, M, N, O,
num_objects-1, totpix);
objects[num_objects-1].totpix += totpix;
}
}
}
delete[] vis;
}
void csExactCuller::VisTest ()
{
int i;
for (i = 0 ; i < num_objects ; i++)
objects[i].vispix = 0;
for (i = 0 ; i < width * height ; i++)
{
uint32 obj_num = scr_buffer[i];
if (obj_num < (uint32)num_objects)
{
objects[obj_num].vispix++;
}
}
}
void csExactCuller::GetObjectStatus (void* obj, int& vispix, int& totpix)
{
int i;
for (i = 0 ; i < num_objects ; i++)
if (objects[i].obj == obj)
{
vispix = objects[i].vispix;
totpix = objects[i].totpix;
return;
}
CS_ASSERT (false);
}
<commit_msg>- Fixed deprecation warnings wrt. iPerspectiveCamera.<commit_after>/*
Copyright (C) 2002 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csqint.h"
#include "csqsqrt.h"
#include "csgeom/box.h"
#include "csgeom/math3d.h"
#include "csgeom/poly2d.h"
#include "csgeom/poly3d.h"
#include "csgeom/polyclip.h"
#include "csgeom/transfrm.h"
#include "csgeom/tri.h"
#include "csutil/scfstr.h"
#include "csutil/sysfunc.h"
#include "iengine/camera.h"
#include "iengine/movable.h"
#include "iutil/string.h"
#include "exvis.h"
//---------------------------------------------------------------------------
csExactCuller::csExactCuller (int w, int h)
{
width = w;
height = h;
scr_buffer = new uint32[w*h];
z_buffer = new float[w*h];
for (int i = 0 ; i < w*h ; i++)
{
scr_buffer[i] = (uint32)~0;
z_buffer[i] = 1000000000000.0f;
}
num_objects = 0;
max_objects = 100;
objects = new csExVisObj [max_objects];
boxclip = new csBoxClipper (0, 0, float (w), float (h));
}
csExactCuller::~csExactCuller ()
{
delete boxclip;
delete[] scr_buffer;
delete[] z_buffer;
delete[] objects;
}
void csExactCuller::InsertPolygon (csVector2* tr_verts, size_t num_verts,
float M, float N, float O, uint32 obj_number, int& totpix)
{
totpix = 0;
size_t i;
size_t min_i, max_i;
min_i = max_i = 0;
float min_y, max_y;
min_y = max_y = tr_verts[0].y;
// count 'real' number of vertices
int real_num_verts = 1;
for (i = 1 ; i < num_verts ; i++)
{
if (tr_verts[i].y > max_y)
{
max_y = tr_verts[i].y;
max_i = i;
}
else if (tr_verts[i].y < min_y)
{
min_y = tr_verts[i].y;
min_i = i;
}
if ((ABS (tr_verts [i].x - tr_verts [i - 1].x)
+ ABS (tr_verts [i].y - tr_verts [i - 1].y))
> 0.001)
real_num_verts++;
}
// If this is a 'degenerate' polygon, skip it.
if (real_num_verts < 3)
return;
size_t scanL1, scanL2, scanR1, scanR2; // scan vertex left/right start/final
float sxL, sxR, dxL, dxR; // scanline X left/right and deltas
int sy, fyL, fyR; // scanline Y, final Y l, final Y r
int xL, xR;
int screenY;
sxL = sxR = dxL = dxR = 0; // Avoid warnings about "uninit vars"
scanL2 = scanR2 = max_i;
sy = fyL = fyR = csQround (tr_verts [scanL2].y);
for ( ; ; )
{
//-----
// We have reached the next segment. Recalculate the slopes.
//-----
bool leave;
do
{
leave = true;
if (sy <= fyR)
{
// Check first if polygon has been finished
if (scanR2 == min_i)
return;
scanR1 = scanR2;
if (++scanR2 >= num_verts)
scanR2 = 0;
leave = false;
fyR = csQround (tr_verts [scanR2].y);
if (sy <= fyR)
continue;
float dyR = (tr_verts [scanR1].y - tr_verts [scanR2].y);
if (dyR)
{
sxR = tr_verts [scanR1].x;
dxR = (tr_verts [scanR2].x - sxR) / dyR;
// horizontal pixel correction
sxR += dxR * (tr_verts [scanR1].y - (float (sy) - 0.5));
}
}
if (sy <= fyL)
{
scanL1 = scanL2;
if (scanL2 == 0)
scanL2 = num_verts - 1;
else
scanL2 = scanL2 - 1;
leave = false;
fyL = csQround (tr_verts [scanL2].y);
if (sy <= fyL)
continue;
float dyL = (tr_verts [scanL1].y - tr_verts [scanL2].y);
if (dyL)
{
sxL = tr_verts [scanL1].x;
dxL = (tr_verts [scanL2].x - sxL) / dyL;
// horizontal pixel correction
sxL += dxL * (tr_verts [scanL1].y - (float (sy) - 0.5));
}
}
} while (!leave);
// Find the trapezoid top (or bottom in inverted Y coordinates)
int fin_y;
if (fyL > fyR)
fin_y = fyL;
else
fin_y = fyR;
screenY = height - sy;
while (sy > fin_y)
{
if (screenY >= 0 && screenY < height)
{
// Compute the rounded screen coordinates of horizontal strip
xL = csQround (sxL);
xR = csQround (sxR);
if (xR >= 0 && xL < width && xR != xL)
{
if (xL < 0) xL = 0;
if (xR >= width) xR = width-1;
uint32* scr_buf = scr_buffer + width * screenY + xL;
float* z_buf = z_buffer + width * screenY + xL;
float invz = M * (xL-width/2) + N * (sy-height/2) + O;
int xx = xR - xL;
if (xx > 0)
{
do
{
if (*scr_buf != obj_number) totpix++;
float z;
if (ABS (invz) > 0.001)
z = 1.0 / invz;
else
z = 9999999999999.0f;
if (z < *z_buf)
{
*scr_buf = obj_number;
*z_buf = z;
}
z_buf++;
scr_buf++;
invz += M;
xx--;
}
while (xx);
}
}
}
sxL += dxL;
sxR += dxR;
sy--;
screenY++;
}
}
}
static void Perspective (const csVector3& v, csVector2& p, float fov,
float sx, float sy)
{
float iz = fov / v.z;
p.x = v.x * iz + sx;
p.y = v.y * iz + sy;
}
void csExactCuller::AddObject (void* obj,
iTriangleMesh* trimesh, iMovable* movable, iCamera* camera,
const csPlane3* planes)
{
if (num_objects >= max_objects)
{
if (max_objects < 10000)
max_objects += max_objects+1;
else
max_objects += 2000;
csExVisObj* new_objects = new csExVisObj [max_objects];
memcpy (new_objects, objects, sizeof (csExVisObj)*num_objects);
delete[] objects;
objects = new_objects;
}
objects[num_objects].obj = obj;
objects[num_objects].totpix = 0;
objects[num_objects].vispix = 0;
num_objects++;
const csVector3* verts = trimesh->GetVertices ();
size_t vertex_count = trimesh->GetVertexCount ();
size_t tri_count = trimesh->GetTriangleCount ();
csReversibleTransform movtrans = movable->GetFullTransform ();
const csReversibleTransform& camtrans = camera->GetTransform ();
csReversibleTransform trans = camtrans / movtrans;
float fov, sx, sy;
csRef<iPerspectiveCamera> pcam =
scfQueryInterface<iPerspectiveCamera> (camera);
if (pcam)
{
fov = pcam->GetFOV ();
sx = pcam->GetShiftX ();
sy = pcam->GetShiftY ();
}
else
{
fov = 1.0f;
sx = 0.0f;
sy = 0.0f;
}
// Calculate camera position in object space.
csVector3 campos_object = movtrans.Other2This (camtrans.GetOrigin ());
size_t i;
// First check visibility of all vertices.
bool* vis = new bool[vertex_count];
for (i = 0 ; i < vertex_count ; i++)
{
csVector3 camv = trans.Other2This (verts[i]);
vis[i] = (camv.z > 0.1);
}
// Then insert all polygons.
csTriangle* tri = trimesh->GetTriangles ();
for (i = 0 ; i < tri_count ; i++, tri++)
{
if (planes[i].Classify (campos_object) >= 0.0)
continue;
if (vis[tri->a] || vis[tri->b] || vis[tri->c])
{
// Here we need to clip the polygon.
csPoly3D clippoly;
clippoly.AddVertex (trans.Other2This (verts[tri->a]));
clippoly.AddVertex (trans.Other2This (verts[tri->b]));
clippoly.AddVertex (trans.Other2This (verts[tri->c]));
csPoly3D front, back;
csPoly3D* spoly;
if (!(vis[tri->a] && vis[tri->b] && vis[tri->c]))
{
clippoly.SplitWithPlaneZ (front, back, 0.1f);
spoly = &back;
}
else
{
spoly = &clippoly;
}
csVector2 clipped[100];
size_t num_clipped = spoly->GetVertexCount ();
csBox2 out_box;
out_box.StartBoundingBox ();
for (size_t k = 0 ; k < spoly->GetVertexCount () ; k++)
{
Perspective ((*spoly)[k], clipped[k], fov, sx, sy);
out_box.AddBoundingVertex (clipped[k]);
}
if (boxclip->ClipInPlace (clipped, num_clipped, out_box)
!= CS_CLIP_OUTSIDE)
{
//csPlane3 camplane = trans.Other2This (planes[i]);
csPlane3 camplane;
trans.Other2This (planes[i], (*spoly)[0], camplane);
//csPrintf (" %g,%g,%g\n", (*spoly)[0].x, (*spoly)[0].y, (*spoly)[0].z);
//csPrintf (" planes[i] %g,%g,%g,%g\n",
//planes[i].A (), planes[i].B (), planes[i].C (), planes[i].D ());
//csPrintf (" camplane %g,%g,%g,%g\n",
//camplane.A (), camplane.B (), camplane.C (), camplane.D ());
if (ABS (camplane.D ()) < 0.001)
continue;
float M, N, O;
float inv_D = 1.0 / camplane.D ();
M = -camplane.A () * inv_D / fov;
N = -camplane.B () * inv_D / fov;
O = -camplane.C () * inv_D;
//csPrintf (" MNO %g,%g,%g\n", M, N, O);
//fflush (stdout);
int totpix;
InsertPolygon (clipped, num_clipped, M, N, O,
num_objects-1, totpix);
objects[num_objects-1].totpix += totpix;
}
}
}
delete[] vis;
}
void csExactCuller::VisTest ()
{
int i;
for (i = 0 ; i < num_objects ; i++)
objects[i].vispix = 0;
for (i = 0 ; i < width * height ; i++)
{
uint32 obj_num = scr_buffer[i];
if (obj_num < (uint32)num_objects)
{
objects[obj_num].vispix++;
}
}
}
void csExactCuller::GetObjectStatus (void* obj, int& vispix, int& totpix)
{
int i;
for (i = 0 ; i < num_objects ; i++)
if (objects[i].obj == obj)
{
vispix = objects[i].vispix;
totpix = objects[i].totpix;
return;
}
CS_ASSERT (false);
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef ResultContainer_h__
#define ResultContainer_h__
#include <array>
namespace bpp
{
class ResultContainer
{
public:
ResultContainer(BenchmarkarbleItem* item, BenchmarkScope* scope, int reserveSize);
~ResultContainer();
int Count( void ) const;
void AddResult( const Result& result );
const std::vector<Result>& Results( void ) const;
BenchmarkScope* Scope() const;
BenchmarkarbleItem* Item() const;
Result AverageResult( void ) const;
Result ShortestResult( void ) const;
Result LongestResult( void ) const;
private:
BenchmarkarbleItem* m_Item;
BenchmarkScope* m_Scope;
std::vector<Result> m_Results;
};
}
#include "ResultContainer.inl"
#endif // ResultContainer_h__
<commit_msg>Removed obsolete array include<commit_after>#pragma once
#ifndef ResultContainer_h__
#define ResultContainer_h__
namespace bpp
{
class ResultContainer
{
public:
ResultContainer(BenchmarkarbleItem* item, BenchmarkScope* scope, int reserveSize);
~ResultContainer();
int Count( void ) const;
void AddResult( const Result& result );
const std::vector<Result>& Results( void ) const;
BenchmarkScope* Scope() const;
BenchmarkarbleItem* Item() const;
Result AverageResult( void ) const;
Result ShortestResult( void ) const;
Result LongestResult( void ) const;
private:
BenchmarkarbleItem* m_Item;
BenchmarkScope* m_Scope;
std::vector<Result> m_Results;
};
}
#include "ResultContainer.inl"
#endif // ResultContainer_h__
<|endoftext|> |
<commit_before>//
// Created by arssivka on 11/27/15.
//
#include <rd/remote/hardware/RemoteJoints.h>
#include <xmlrpc-c/girerr.hpp>
using namespace xmlrpc_c;
using namespace boost;
using namespace std;
using namespace rd;
RemoteJoints::RemoteJoints(shared_ptr<Joints> joints)
: RemoteModule("joints") {
this->addMethod(shared_ptr<RemoteMethod>(new KeysMethod(joints)));
this->addMethod(shared_ptr<RemoteMethod>(new HardnessMethod(joints)));
this->addMethod(shared_ptr<RemoteMethod>(new PositionMethod(joints)));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RemoteJoints::KeysMethod::KeysMethod(shared_ptr<Joints> joints)
: RemoteMethod("keys", "A:", "Return array of joint names") {
const vector<string> &keys = joints->getKeys();
vector<value> values;
for (vector<string>::const_iterator it = keys.begin();
it != keys.end(); ++it) {
values.push_back(value_string(*it));
}
this->keys = value_array(values);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RemoteJoints::KeysMethod::execute(paramList const ¶mList, value *const resultP) {
*resultP = this->keys;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RemoteJoints::HardnessMethod::HardnessMethod(shared_ptr<Joints> joints)
: RemoteMethod("hardness", "S:,S:A,n:AA,n:d", "Stifness control method"), joints(joints) { }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RemoteJoints::HardnessMethod::execute(paramList const ¶mList, value *const resultP) {
// n:d
if (paramList.size() == 1) {
try {
double value = paramList.getDouble(0);
this->joints->setHardness(value);
*resultP = value_nil();
return;
} catch (girerr::error &e) { }
}
// n:AA
if (paramList.size() == 2) {
vector<value> keys = paramList.getArray(0);
vector<value> values = paramList.getArray(1);
// Size check
if (keys.size() != values.size()) throw girerr::error("Keys vector and values vector doesn't have same size");
// Empty check
if (keys.empty()) return;
bool integer_keys = keys[0].type() == xmlrpc_c::value::TYPE_INT;
vector<double> data;
for (int i = 0; i < values.size(); ++i) data.push_back((double) value_double(values[i]));
if (integer_keys) {
vector<string> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((string) value_string(keys[i]));
this->joints->setHardness(joint_names, data);
} else {
vector<int> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((int) value_int(keys[i]));
this->joints->setHardness(joint_names, data);
}
*resultP = value_nil();
return;
}
// S:
SensorData<double> data;
if (paramList.size() == 0) {
data = this->joints->getHardness();
} else if (paramList.size() == 1) {
// Empty check
vector<value> keys = paramList.getArray(0);
if (keys.empty()) return;
bool integer_keys = keys[0].type() == xmlrpc_c::value::TYPE_INT;
if (integer_keys) {
vector<string> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((string) value_string(keys[i]));
data = this->joints->getHardness(joint_names);
} else {
vector<int> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((int) value_int(keys[i]));
data = this->joints->getHardness(joint_names);
}
} else throw girerr::error("Unknown signature for hardness function");
vector<value> values;
map<string, value> result;
for (int i = 0; i < data.data->size(); ++i) values.push_back(value_double(data.data->at(i)));
result.insert(make_pair<string, value>("data", value_array(values)));
result.insert(make_pair<string, value>("timestamp", value_int(data.timestamp)));
*resultP = value_struct(result);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RemoteJoints::PositionMethod::PositionMethod(shared_ptr<Joints> joints)
: RemoteMethod("position", "A:,S:A,n:AA", "Position control method"), joints(joints) { }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RemoteJoints::PositionMethod::execute(paramList const ¶mList, value *const resultP) {
// n:AA
if (paramList.size() == 2) {
vector<value> keys = paramList.getArray(0);
vector<value> values = paramList.getArray(1);
// Size check
if (keys.size() != values.size()) throw girerr::error("Keys vector and values vector doesn't have same size");
// Empty check
if (keys.empty()) return;
bool integer_keys = keys[0].type() == xmlrpc_c::value::TYPE_INT;
vector<double> data;
for (int i = 0; i < values.size(); ++i) data.push_back((double) value_double(values[i]));
if (integer_keys) {
vector<int> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((int) value_int(keys[i]));
this->joints->setPosition(joint_names, data);
} else {
vector<string> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((string) value_string(keys[i]));
this->joints->setPosition(joint_names, data);
}
*resultP = value_nil();
return;
}
// S:
SensorData<double> data;
if (paramList.size() == 0) {
data = this->joints->getPosition();
} else if (paramList.size() == 1) {
// Empty check
vector<value> keys = paramList.getArray(0);
if (keys.empty()) return;
bool integer_keys = keys[0].type() == xmlrpc_c::value::TYPE_INT;
if (integer_keys) {
vector<string> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((string) value_string(keys[i]));
data = this->joints->getPosition(joint_names);
} else {
vector<int> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((int) value_int(keys[i]));
data = this->joints->getPosition(joint_names);
}
} else throw girerr::error("Unknown signature for hardness function");
vector<value> values;
map<string, value> result;
for (int i = 0; i < data.data->size(); ++i) values.push_back(value_double(data.data->at(i)));
result.insert(make_pair<string, value>("data", value_array(values)));
result.insert(make_pair<string, value>("timestamp", value_int(data.timestamp)));
*resultP = value_struct(result);
}
<commit_msg>SensorData refactoring and some xmlrpc-c optimisations<commit_after>//
// Created by arssivka on 11/27/15.
//
#include <rd/remote/hardware/RemoteJoints.h>
#include <xmlrpc-c/girerr.hpp>
using namespace xmlrpc_c;
using namespace boost;
using namespace std;
using namespace rd;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RemoteJoints::RemoteJoints(shared_ptr<Joints> joints)
: RemoteModule("joints") {
this->addMethod(shared_ptr<RemoteMethod>(new KeysMethod(joints)));
this->addMethod(shared_ptr<RemoteMethod>(new HardnessMethod(joints)));
this->addMethod(shared_ptr<RemoteMethod>(new PositionMethod(joints)));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RemoteJoints::KeysMethod::KeysMethod(shared_ptr<Joints> joints)
: RemoteMethod("keys", "A:", "Return array of joint names") {
const vector<string> &keys = joints->getKeys();
vector<value> values;
for (vector<string>::const_iterator it = keys.begin();
it != keys.end(); ++it) {
values.push_back(value_string(*it));
}
this->keys = value_array(values);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RemoteJoints::KeysMethod::execute(paramList const ¶mList, value *const resultP) {
*resultP = this->keys;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RemoteJoints::HardnessMethod::HardnessMethod(shared_ptr<Joints> joints)
: RemoteMethod("hardness", "S:,S:A,n:AA,n:d", "Stifness control method"), joints(joints) { }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RemoteJoints::HardnessMethod::execute(paramList const ¶mList, value *const resultP) {
// n:d
if (paramList.size() == 1) {
try {
double value = paramList.getDouble(0);
this->joints->setHardness(value);
*resultP = value_nil();
return;
} catch (girerr::error &e) { }
}
// n:AA
if (paramList.size() == 2) {
vector<value> keys = paramList.getArray(0);
vector<value> values = paramList.getArray(1);
// Size check
if (keys.size() != values.size()) throw girerr::error("Keys vector and values vector doesn't have same size");
// Empty check
if (keys.empty()) return;
bool integer_keys = keys[0].type() == xmlrpc_c::value::TYPE_INT;
vector<double> data;
for (int i = 0; i < values.size(); ++i) data.push_back((double) value_double(values[i]));
if (integer_keys) {
vector<string> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((string) value_string(keys[i]));
this->joints->setHardness(joint_names, data);
} else {
vector<int> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((int) value_int(keys[i]));
this->joints->setHardness(joint_names, data);
}
*resultP = value_nil();
return;
}
// S:
shared_ptr<SensorData<double> > data;
if (paramList.size() == 0) {
data = this->joints->getHardness();
} else if (paramList.size() == 1) {
// Empty check
vector<value> keys = paramList.getArray(0);
if (keys.empty()) return;
bool integer_keys = keys[0].type() == xmlrpc_c::value::TYPE_INT;
if (integer_keys) {
vector<string> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((string) value_string(keys[i]));
data = this->joints->getHardness(joint_names);
} else {
vector<int> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((int) value_int(keys[i]));
data = this->joints->getHardness(joint_names);
}
} else throw girerr::error("Unknown signature for hardness function");
vector<value> values;
map<string, value> result;
for (int i = 0; i < data->data.size(); ++i) values.push_back(value_double(data->data[i]));
result.insert(make_pair<string, value>("data", value_array(values)));
result.insert(make_pair<string, value>("timestamp", value_int(data->timestamp)));
*resultP = value_struct(result);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RemoteJoints::PositionMethod::PositionMethod(shared_ptr<Joints> joints)
: RemoteMethod("position", "A:,S:A,n:AA", "Position control method"), joints(joints) { }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RemoteJoints::PositionMethod::execute(paramList const ¶mList, value *const resultP) {
// n:AA
if (paramList.size() == 2) {
vector<value> keys = paramList.getArray(0);
vector<value> values = paramList.getArray(1);
// Size check
if (keys.size() != values.size()) throw girerr::error("Keys vector and values vector doesn't have same size");
// Empty check
if (keys.empty()) return;
bool integer_keys = keys[0].type() == xmlrpc_c::value::TYPE_INT;
vector<double> data;
for (int i = 0; i < values.size(); ++i) data.push_back((double) value_double(values[i]));
if (integer_keys) {
vector<int> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((int) value_int(keys[i]));
this->joints->setPosition(joint_names, data);
} else {
vector<string> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((string) value_string(keys[i]));
this->joints->setPosition(joint_names, data);
}
*resultP = value_nil();
return;
}
// S:
shared_ptr<SensorData<double> > data;
if (paramList.size() == 0) {
data = this->joints->getPosition();
} else if (paramList.size() == 1) {
// Empty check
vector<value> keys = paramList.getArray(0);
if (keys.empty()) return;
bool integer_keys = keys[0].type() == xmlrpc_c::value::TYPE_INT;
if (integer_keys) {
vector<string> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((string) value_string(keys[i]));
data = this->joints->getPosition(joint_names);
} else {
vector<int> joint_names;
for (int i = 0; i < keys.size(); ++i) joint_names.push_back((int) value_int(keys[i]));
data = this->joints->getPosition(joint_names);
}
} else throw girerr::error("Unknown signature for hardness function");
// TODO Check for memory leaks
// Some optimisation by using C library of xmlrpc-c
xmlrpc_env env;
xmlrpc_env_init(&env);
xmlrpc_value *elem;
xmlrpc_value *values;
xmlrpc_value *result;
// Init result array
for (int i = 0; i < data->data.size(); ++i) {
elem = xmlrpc_double_new(&env, data->data[i]);
xmlrpc_array_append_item(&env, values, elem);
xmlrpc_DECREF(elem);
}
// XMLRPC-C timestamp
elem = xmlrpc_double_new(&env, data->timestamp);
// Create result struct
result = xmlrpc_struct_new(&env);
xmlrpc_struct_set_value(&env, result, "data", values);
xmlrpc_struct_set_value(&env, result, "timestamp", elem);
// Apply result
resultP->instantiate(result);
// Clean this shit!
xmlrpc_DECREF(elem);
xmlrpc_DECREF(values);
xmlrpc_DECREF(result);
xmlrpc_env_clean(&env);
}
<|endoftext|> |
<commit_before>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mappackets.h"
#include "srv_changemapreply.h"
#include "srv_serverdata.h"
namespace RoseCommon {
//---------------------------------------------
RoseCommon::SrvChangeMapReply::SrvChangeMapReply(
uint16_t object_index, uint16_t current_hp, uint16_t current_mp,
uint16_t current_exp, uint16_t penalize_exp, uint16_t world_time,
uint16_t team_number)
: CRosePacket(ePacketType::PAKWC_CHANGE_MAP_REPLY),
object_index_(object_index),
current_hp_(current_hp),
current_mp_(current_mp),
current_exp_(current_exp),
penalize_exp_(penalize_exp),
world_time_(world_time),
team_number_(team_number) {
for (int idx = 0; idx < MAX_SELL_TYPE; ++idx) {
zone_vars_.item_rate_[idx] = 0;
}
}
RoseCommon::SrvChangeMapReply::~SrvChangeMapReply() {}
uint16_t RoseCommon::SrvChangeMapReply::object_index() const {
return object_index_;
}
uint16_t RoseCommon::SrvChangeMapReply::current_hp() const {
return current_hp_;
}
uint16_t RoseCommon::SrvChangeMapReply::current_mp() const {
return current_mp_;
}
void RoseCommon::SrvChangeMapReply::setItemRate(uint8_t type, uint8_t rate) {
zone_vars_.item_rate_[type] = rate;
}
void RoseCommon::SrvChangeMapReply::pack() {
*this << object_index_ << current_hp_ << current_mp_ << current_exp_
<< penalize_exp_;
{ // global_var
*this << zone_vars_.craft_rate_ << zone_vars_.update_time_
<< zone_vars_.world_rate_ << zone_vars_.town_rate_;
for (int idx = 0; idx < MAX_SELL_TYPE; ++idx) {
*this << zone_vars_.item_rate_[idx];
}
*this << zone_vars_.flags_;
} // global_var
*this << world_time_ << team_number_;
}
//---------------------------------------------
//---------------------------------------------
RoseCommon::SrvServerData::SrvServerData(uint8_t type)
: CRosePacket(ePacketType::PAKWC_GLOBAL_VARS), type_(type) {}
RoseCommon::SrvServerData::~SrvServerData() {}
uint8_t RoseCommon::SrvServerData::type() const { return type_; }
void RoseCommon::SrvServerData::pack() {
*this << type_;
switch (type_) {
case data_type::ECONOMY: {
*this << enconmy_data_.counter_ << enconmy_data_.pop_base_
<< enconmy_data_.dev_base_;
for (int idx = MIN_SELL_TYPE; idx < MAX_SELL_TYPE; ++idx) {
*this << enconmy_data_.consume_[idx];
}
*this << enconmy_data_.dev_ << enconmy_data_.pop_;
for (int idx = MIN_SELL_TYPE; idx < MAX_SELL_TYPE; ++idx) {
*this << enconmy_data_.item_[idx];
}
break;
}
case data_type::NPC:
default:
break;
}
}
}
<commit_msg>Delete mappackets.cpp<commit_after><|endoftext|> |
<commit_before>#include "MapData.h"
using namespace std;
MapData::MapData()
{
display_global_offset = false;
}
void MapData::addToGPSRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_gps_seen_x[rover]) max_gps_seen_x[rover] = x;
if (y > max_gps_seen_y[rover]) max_gps_seen_y[rover] = y;
if (x < min_gps_seen_x[rover]) min_gps_seen_x[rover] = x;
if (y < min_gps_seen_y[rover]) min_gps_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_gps_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
gps_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::addToEncoderRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_encoder_seen_x[rover]) max_encoder_seen_x[rover] = x;
if (y > max_encoder_seen_y[rover]) max_encoder_seen_y[rover] = y;
if (x < min_encoder_seen_x[rover]) min_encoder_seen_x[rover] = x;
if (y < min_encoder_seen_y[rover]) min_encoder_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_encoder_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
encoder_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
// Expects the input y to be flipped with respect to y the map coordinate system
void MapData::addToEKFRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_ekf_seen_x[rover]) max_ekf_seen_x[rover] = x;
if (y > max_ekf_seen_y[rover]) max_ekf_seen_y[rover] = y;
if (x < min_ekf_seen_x[rover]) min_ekf_seen_x[rover] = x;
if (y < min_ekf_seen_y[rover]) min_ekf_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_ekf_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
ekf_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
// Expects the input y to be consistent with the map coordinate system
int MapData::addToWaypointPath(string rover, float x, float y)
{
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
int this_id = waypoint_id_counter++; // Get the next waypoint id.
global_offset_waypoint_path[rover][this_id]=make_tuple(x+offset_x,y-offset_y,false);
waypoint_path[rover][this_id]=make_tuple(x,y,false);
update_mutex.unlock();
return this_id;
}
void MapData::removeFromWaypointPath(std::string rover, int id)
{
update_mutex.lock();
global_offset_waypoint_path[rover].erase(id);
waypoint_path[rover].erase(id);
update_mutex.unlock();
}
void MapData::reachedWaypoint(int waypoint_id)
{
update_mutex.lock();
// Update the reached waypoint in both the normal waypoint path AND the global
// waypoint path. We must update both to prevent incorrect color display for
// reached waypoints when switching back and forth between the global frame.
for (auto &rover : global_offset_waypoint_path)
{
map<int, std::tuple<float,float,bool>>::iterator found;
if ((found = rover.second.find(waypoint_id)) != rover.second.end())
{
get<2>(found->second) = true;
}
}
for (auto &rover : waypoint_path)
{
map<int, std::tuple<float,float,bool>>::iterator found;
if ((found = rover.second.find(waypoint_id)) != rover.second.end())
{
get<2>(found->second) = true;
}
}
update_mutex.unlock();
}
void MapData::addTargetLocation(string rover, float x, float y)
{
//The QT drawing coordinate system is reversed from the robot coordinate system in the y direction
y = -y;
update_mutex.lock();
target_locations[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::addCollectionPoint(string rover, float x, float y)
{
// The QT drawing coordinate system is reversed from the robot coordinate system in the y direction
y = -y;
update_mutex.lock();
collection_points[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::setGlobalOffset(bool display)
{
display_global_offset = display;
}
void MapData::setGlobalOffsetForRover(string rover, float x, float y)
{
rover_global_offsets[rover] = pair<float,float>(x,y);
}
std::pair<float,float> MapData::getGlobalOffsetForRover(string rover)
{
return rover_global_offsets[rover];
}
bool MapData::isDisplayingGlobalOffset()
{
return display_global_offset;
}
void MapData::clear()
{
update_mutex.lock();
ekf_rover_path.clear();
encoder_rover_path.clear();
gps_rover_path.clear();
waypoint_path.clear();
global_offset_ekf_rover_path.clear();
global_offset_encoder_rover_path.clear();
global_offset_gps_rover_path.clear();
global_offset_waypoint_path.clear();
target_locations.clear();
collection_points.clear();
waypoint_path.clear();
rover_mode.clear();
update_mutex.unlock();
}
void MapData::clear(string rover)
{
update_mutex.lock();
ekf_rover_path[rover].clear();
global_offset_ekf_rover_path[rover].clear();
ekf_rover_path.erase(rover);
global_offset_ekf_rover_path.erase(rover);
encoder_rover_path[rover].clear();
global_offset_encoder_rover_path[rover].clear();
encoder_rover_path.erase(rover);
global_offset_encoder_rover_path.erase(rover);
gps_rover_path[rover].clear();
global_offset_gps_rover_path[rover].clear();
gps_rover_path.erase(rover);
global_offset_gps_rover_path.erase(rover);
waypoint_path[rover].clear();
global_offset_waypoint_path[rover].clear();
waypoint_path.erase(rover);
global_offset_waypoint_path.erase(rover);
target_locations[rover].clear();
collection_points[rover].clear();
target_locations.erase(rover);
collection_points.erase(rover);
rover_mode.erase(rover);
update_mutex.unlock();
}
std::vector< std::pair<float,float> >* MapData::getEKFPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_ekf_rover_path[rover_name];
}
return &ekf_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getGPSPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_gps_rover_path[rover_name];
}
return &gps_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getEncoderPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_encoder_rover_path[rover_name];
}
return &encoder_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getTargetLocations(std::string rover_name)
{
return &target_locations[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getCollectionPoints(std::string rover_name)
{
return &collection_points[rover_name];
}
std::map<int, std::tuple<float,float,bool> >* MapData::getWaypointPath(std::string rover_name) {
if(display_global_offset)
{
return &global_offset_waypoint_path[rover_name];
}
return &waypoint_path[rover_name];
}
void MapData::resetAllWaypointPaths()
{
waypoint_path.clear();
global_offset_waypoint_path.clear();
waypoint_id_counter = 0;
}
void MapData::resetWaypointPathForSelectedRover(std::string rover)
{
waypoint_path[rover].clear();
global_offset_waypoint_path[rover].clear();
}
// These functions report the maximum and minimum map values seen. This is useful for the GUI when it is calculating the map coordinate system.
float MapData::getMaxGPSX(string rover_name)
{
if(display_global_offset)
{
return max_gps_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_gps_seen_x[rover_name];
}
float MapData::getMaxGPSY(string rover_name)
{
if(display_global_offset)
{
return max_gps_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_gps_seen_y[rover_name];
}
float MapData::getMinGPSX(string rover_name)
{
if(display_global_offset)
{
return min_gps_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_gps_seen_x[rover_name];
}
float MapData::getMinGPSY(string rover_name)
{
if(display_global_offset)
{
return min_gps_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_gps_seen_y[rover_name];
}
float MapData::getMaxEKFX(string rover_name)
{
if(display_global_offset)
{
return max_ekf_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_ekf_seen_x[rover_name];
}
float MapData::getMaxEKFY(string rover_name)
{
if(display_global_offset)
{
return max_ekf_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_ekf_seen_y[rover_name];
}
float MapData::getMinEKFX(string rover_name)
{
if(display_global_offset)
{
return min_ekf_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_ekf_seen_x[rover_name];
}
float MapData::getMinEKFY(string rover_name)
{
if(display_global_offset)
{
return min_ekf_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_ekf_seen_y[rover_name];
}
float MapData::getMaxEncoderX(string rover_name)
{
if(display_global_offset)
{
return max_encoder_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_encoder_seen_x[rover_name];
}
float MapData::getMaxEncoderY(string rover_name)
{
if(display_global_offset)
{
return max_encoder_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_encoder_seen_y[rover_name];
}
float MapData::getMinEncoderX(string rover_name)
{
if(display_global_offset)
{
return min_encoder_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_encoder_seen_x[rover_name];
}
float MapData::getMinEncoderY(string rover_name)
{
if(display_global_offset)
{
return min_encoder_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_encoder_seen_y[rover_name];
}
bool MapData::inManualMode(string rover_name)
{
return rover_mode[rover_name] == 0;
}
void MapData::setAutonomousMode(string rover_name)
{
update_mutex.lock();
rover_mode[rover_name] = 1;
update_mutex.unlock();
}
void MapData::setManualMode(string rover_name)
{
update_mutex.lock();
rover_mode[rover_name] = 0;
update_mutex.unlock();
}
void MapData::lock()
{
update_mutex.lock();
}
void MapData::unlock()
{
update_mutex.unlock();
}
MapData::~MapData()
{
clear();
}
<commit_msg>Remove waypoint path from map when entering autonomous mode<commit_after>#include "MapData.h"
using namespace std;
MapData::MapData()
{
display_global_offset = false;
}
void MapData::addToGPSRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_gps_seen_x[rover]) max_gps_seen_x[rover] = x;
if (y > max_gps_seen_y[rover]) max_gps_seen_y[rover] = y;
if (x < min_gps_seen_x[rover]) min_gps_seen_x[rover] = x;
if (y < min_gps_seen_y[rover]) min_gps_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_gps_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
gps_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::addToEncoderRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_encoder_seen_x[rover]) max_encoder_seen_x[rover] = x;
if (y > max_encoder_seen_y[rover]) max_encoder_seen_y[rover] = y;
if (x < min_encoder_seen_x[rover]) min_encoder_seen_x[rover] = x;
if (y < min_encoder_seen_y[rover]) min_encoder_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_encoder_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
encoder_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
// Expects the input y to be flipped with respect to y the map coordinate system
void MapData::addToEKFRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_ekf_seen_x[rover]) max_ekf_seen_x[rover] = x;
if (y > max_ekf_seen_y[rover]) max_ekf_seen_y[rover] = y;
if (x < min_ekf_seen_x[rover]) min_ekf_seen_x[rover] = x;
if (y < min_ekf_seen_y[rover]) min_ekf_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_ekf_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
ekf_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
// Expects the input y to be consistent with the map coordinate system
int MapData::addToWaypointPath(string rover, float x, float y)
{
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
int this_id = waypoint_id_counter++; // Get the next waypoint id.
global_offset_waypoint_path[rover][this_id]=make_tuple(x+offset_x,y-offset_y,false);
waypoint_path[rover][this_id]=make_tuple(x,y,false);
update_mutex.unlock();
return this_id;
}
void MapData::removeFromWaypointPath(std::string rover, int id)
{
update_mutex.lock();
global_offset_waypoint_path[rover].erase(id);
waypoint_path[rover].erase(id);
update_mutex.unlock();
}
void MapData::reachedWaypoint(int waypoint_id)
{
update_mutex.lock();
// Update the reached waypoint in both the normal waypoint path AND the global
// waypoint path. We must update both to prevent incorrect color display for
// reached waypoints when switching back and forth between the global frame.
for (auto &rover : global_offset_waypoint_path)
{
map<int, std::tuple<float,float,bool>>::iterator found;
if ((found = rover.second.find(waypoint_id)) != rover.second.end())
{
get<2>(found->second) = true;
}
}
for (auto &rover : waypoint_path)
{
map<int, std::tuple<float,float,bool>>::iterator found;
if ((found = rover.second.find(waypoint_id)) != rover.second.end())
{
get<2>(found->second) = true;
}
}
update_mutex.unlock();
}
void MapData::addTargetLocation(string rover, float x, float y)
{
//The QT drawing coordinate system is reversed from the robot coordinate system in the y direction
y = -y;
update_mutex.lock();
target_locations[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::addCollectionPoint(string rover, float x, float y)
{
// The QT drawing coordinate system is reversed from the robot coordinate system in the y direction
y = -y;
update_mutex.lock();
collection_points[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::setGlobalOffset(bool display)
{
display_global_offset = display;
}
void MapData::setGlobalOffsetForRover(string rover, float x, float y)
{
rover_global_offsets[rover] = pair<float,float>(x,y);
}
std::pair<float,float> MapData::getGlobalOffsetForRover(string rover)
{
return rover_global_offsets[rover];
}
bool MapData::isDisplayingGlobalOffset()
{
return display_global_offset;
}
void MapData::clear()
{
update_mutex.lock();
ekf_rover_path.clear();
encoder_rover_path.clear();
gps_rover_path.clear();
waypoint_path.clear();
global_offset_ekf_rover_path.clear();
global_offset_encoder_rover_path.clear();
global_offset_gps_rover_path.clear();
global_offset_waypoint_path.clear();
target_locations.clear();
collection_points.clear();
waypoint_path.clear();
rover_mode.clear();
update_mutex.unlock();
}
void MapData::clear(string rover)
{
update_mutex.lock();
ekf_rover_path[rover].clear();
global_offset_ekf_rover_path[rover].clear();
ekf_rover_path.erase(rover);
global_offset_ekf_rover_path.erase(rover);
encoder_rover_path[rover].clear();
global_offset_encoder_rover_path[rover].clear();
encoder_rover_path.erase(rover);
global_offset_encoder_rover_path.erase(rover);
gps_rover_path[rover].clear();
global_offset_gps_rover_path[rover].clear();
gps_rover_path.erase(rover);
global_offset_gps_rover_path.erase(rover);
waypoint_path[rover].clear();
global_offset_waypoint_path[rover].clear();
waypoint_path.erase(rover);
global_offset_waypoint_path.erase(rover);
target_locations[rover].clear();
collection_points[rover].clear();
target_locations.erase(rover);
collection_points.erase(rover);
rover_mode.erase(rover);
update_mutex.unlock();
}
std::vector< std::pair<float,float> >* MapData::getEKFPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_ekf_rover_path[rover_name];
}
return &ekf_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getGPSPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_gps_rover_path[rover_name];
}
return &gps_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getEncoderPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_encoder_rover_path[rover_name];
}
return &encoder_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getTargetLocations(std::string rover_name)
{
return &target_locations[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getCollectionPoints(std::string rover_name)
{
return &collection_points[rover_name];
}
std::map<int, std::tuple<float,float,bool> >* MapData::getWaypointPath(std::string rover_name) {
if(display_global_offset)
{
return &global_offset_waypoint_path[rover_name];
}
return &waypoint_path[rover_name];
}
void MapData::resetAllWaypointPaths()
{
waypoint_path.clear();
global_offset_waypoint_path.clear();
waypoint_id_counter = 0;
}
void MapData::resetWaypointPathForSelectedRover(std::string rover)
{
waypoint_path[rover].clear();
global_offset_waypoint_path[rover].clear();
}
// These functions report the maximum and minimum map values seen. This is useful for the GUI when it is calculating the map coordinate system.
float MapData::getMaxGPSX(string rover_name)
{
if(display_global_offset)
{
return max_gps_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_gps_seen_x[rover_name];
}
float MapData::getMaxGPSY(string rover_name)
{
if(display_global_offset)
{
return max_gps_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_gps_seen_y[rover_name];
}
float MapData::getMinGPSX(string rover_name)
{
if(display_global_offset)
{
return min_gps_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_gps_seen_x[rover_name];
}
float MapData::getMinGPSY(string rover_name)
{
if(display_global_offset)
{
return min_gps_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_gps_seen_y[rover_name];
}
float MapData::getMaxEKFX(string rover_name)
{
if(display_global_offset)
{
return max_ekf_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_ekf_seen_x[rover_name];
}
float MapData::getMaxEKFY(string rover_name)
{
if(display_global_offset)
{
return max_ekf_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_ekf_seen_y[rover_name];
}
float MapData::getMinEKFX(string rover_name)
{
if(display_global_offset)
{
return min_ekf_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_ekf_seen_x[rover_name];
}
float MapData::getMinEKFY(string rover_name)
{
if(display_global_offset)
{
return min_ekf_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_ekf_seen_y[rover_name];
}
float MapData::getMaxEncoderX(string rover_name)
{
if(display_global_offset)
{
return max_encoder_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_encoder_seen_x[rover_name];
}
float MapData::getMaxEncoderY(string rover_name)
{
if(display_global_offset)
{
return max_encoder_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_encoder_seen_y[rover_name];
}
float MapData::getMinEncoderX(string rover_name)
{
if(display_global_offset)
{
return min_encoder_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_encoder_seen_x[rover_name];
}
float MapData::getMinEncoderY(string rover_name)
{
if(display_global_offset)
{
return min_encoder_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_encoder_seen_y[rover_name];
}
bool MapData::inManualMode(string rover_name)
{
return rover_mode[rover_name] == 0;
}
void MapData::setAutonomousMode(string rover_name)
{
update_mutex.lock();
rover_mode[rover_name] = 1;
resetWaypointPathForSelectedRover(rover_name);
update_mutex.unlock();
}
void MapData::setManualMode(string rover_name)
{
update_mutex.lock();
rover_mode[rover_name] = 0;
update_mutex.unlock();
}
void MapData::lock()
{
update_mutex.lock();
}
void MapData::unlock()
{
update_mutex.unlock();
}
MapData::~MapData()
{
clear();
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/file_manager/file_manager_jstest_base.h"
class GalleryJsTest : public FileManagerJsTestBase {
protected:
GalleryJsTest() : FileManagerJsTestBase(
base::FilePath(FILE_PATH_LITERAL("ui/file_manager/gallery/js"))) {}
};
IN_PROC_BROWSER_TEST_F(GalleryJsTest, ImageEncoderTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("image_editor/image_encoder_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, ExifEncoderTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("image_editor/exif_encoder_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, ImageViewTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("image_editor/image_view_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, EntryListWatcherTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("entry_list_watcher_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, GalleryUtilTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("gallery_util_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, GalleryItemTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("gallery_item_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, GalleryDataModelTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("gallery_data_model_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, RibbonTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("ribbon_unittest.html")));
}
<commit_msg>Gallery: disable GalleryJsText.ExifEncoderTest on Debug build.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/file_manager/file_manager_jstest_base.h"
class GalleryJsTest : public FileManagerJsTestBase {
protected:
GalleryJsTest() : FileManagerJsTestBase(
base::FilePath(FILE_PATH_LITERAL("ui/file_manager/gallery/js"))) {}
};
IN_PROC_BROWSER_TEST_F(GalleryJsTest, ImageEncoderTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("image_editor/image_encoder_unittest.html")));
}
// TODO(yawano): This test fails on Debug build and this is a temporary fix.
#if defined(NDEBUG)
#define MAYBE_ExifEncoderTest ExifEncoderTest
#else
#define MAYBE_ExifEncoderTest DISABLED_ExifEncoderTest
#endif
IN_PROC_BROWSER_TEST_F(GalleryJsTest, MAYBE_ExifEncoderTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("image_editor/exif_encoder_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, ImageViewTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("image_editor/image_view_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, EntryListWatcherTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("entry_list_watcher_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, GalleryUtilTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("gallery_util_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, GalleryItemTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("gallery_item_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, GalleryDataModelTest) {
RunTest(base::FilePath(
FILE_PATH_LITERAL("gallery_data_model_unittest.html")));
}
IN_PROC_BROWSER_TEST_F(GalleryJsTest, RibbonTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("ribbon_unittest.html")));
}
<|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 "chrome/browser/extensions/extension_apitest.h"
// Started failing with r29947. WebKit merge 49961:49992.
IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
<commit_msg>Um, do the disable right. TBR. Review URL: http://codereview.chromium.org/328015<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 "chrome/browser/extensions/extension_apitest.h"
// Started failing with r29947. WebKit merge 49961:49992.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
<|endoftext|> |
<commit_before><commit_msg>Sofa QtViewer: Fix axis display<commit_after><|endoftext|> |
<commit_before>#include "ext_mongo.h"
#include "bson_decode.h"
#include "contrib/encode.h"
namespace HPHP {
static ObjectData *
create_object(const StaticString * className, Array params) {
TypedValue ret;
Class * cls = Unit::loadClass(className -> get());
ObjectData * obj = ObjectData::newInstance(cls);
obj->incRefCount();
g_context->invokeFunc(
&ret,
cls->getCtor(),
params,
obj
);
return obj;
}
static mongoc_collection_t *get_collection(Object obj) {
mongoc_collection_t *collection;
auto db = obj->o_realProp("db", ObjectData::RealPropUnchecked, "MongoCollection")->toObject();
auto client = db->o_realProp("client", ObjectData::RealPropUnchecked, "MongoDB")->toObject();
String db_name = db->o_realProp("db_name", ObjectData::RealPropUnchecked, "MongoDB")->toString();
String collection_name = obj->o_realProp("name", ObjectData::RealPropUnchecked, "MongoCollection")->toString();
collection = mongoc_client_get_collection(get_client(client)->get(), db_name.c_str(), collection_name.c_str());
return collection;
}
////////////////////////////////////////////////////////////////////////////////
// class MongoCollection
/**
* Inserts a document into the collection
*
* @param array|object $a - a An array or object. If an object is
* used, it may not have protected or private properties. If the
* parameter does not have an _id key or property, a new MongoId
* instance will be created and assigned to it.
* @param array $options - options Options for the insert.
*
* @return bool|array - Returns an array containing the status of the
* insertion if the "w" option is set. Otherwise, returns TRUE if the
* inserted array is not empty (a MongoException will be thrown if the
* inserted array is empty).
*/
//public function insert(mixed $a, array $options = array()): mixed;
static Variant HHVM_METHOD(MongoCollection, insert, Variant a, Array options) {
mongoc_collection_t *collection;
bson_t doc;
bson_error_t error;
collection = get_collection(this_);
Array& doc_array = a.toArrRef();
if (!doc_array.exists(String("_id"))) {
const StaticString s_MongoId("MongoId");
char id[25];
bson_oid_t oid;
bson_oid_init(&oid, NULL);
bson_oid_to_string(&oid, id);
ObjectData * data = create_object(&s_MongoId, make_packed_array(String(id)));
doc_array.add(String("_id"), data);
}
encodeToBSON(doc_array, &doc);
int w_flag = MONGOC_WRITE_CONCERN_W_DEFAULT;
//如果传递了参数
mongoc_write_concern_t *write_concern;
write_concern = mongoc_write_concern_new();
mongoc_write_concern_set_w(write_concern, w_flag);
bool ret = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, &doc, write_concern, &error);
if (!ret) {
mongoThrow<MongoCursorException>((const char *) error.message);
}
mongoc_collection_destroy(collection);
bson_destroy(&doc);
return ret;
/*
bool mongoc_collection_insert (mongoc_collection_t *collection,
mongoc_insert_flags_t flags,
const bson_t *document,
const mongoc_write_concern_t *write_concern,
bson_error_t *error);
*/
}
/**
* Remove records from this collection
*
* @param array $criteria - criteria Description of records to
* remove.
* @param array $options - options Options for remove. "justOne"
* Remove at most one record matching this criteria.
*
* @return bool|array - Returns an array containing the status of the
* removal if the "w" option is set. Otherwise, returns TRUE.
*/
//public function remove(array $criteria = array(), array $options = array()): mixed;
static Variant HHVM_METHOD(MongoCollection, remove, Array criteria, Array options) {
mongoc_collection_t *collection;
bson_t criteria_b;
bson_error_t error;
collection = get_collection(this_);
encodeToBSON(criteria, &criteria_b);
mongoc_delete_flags_t delete_flag = MONGOC_DELETE_NONE;
int w_flag = MONGOC_WRITE_CONCERN_W_DEFAULT;
//如果传递了参数
if(!options.empty()){
//printf("multiple = %s\r\n",options[String("multiple")].toBoolean() ? "true":"false");
if(options[String("justOne")].toBoolean()==true){
delete_flag = MONGOC_DELETE_SINGLE_REMOVE;
}
}
mongoc_write_concern_t *write_concern;
write_concern = mongoc_write_concern_new();
mongoc_write_concern_set_w(write_concern, w_flag);
bool ret = mongoc_collection_delete(collection, delete_flag, &criteria_b, write_concern, &error);
if (!ret) {
mongoThrow<MongoCursorException>((const char *) error.message);
}
mongoc_collection_destroy(collection);
bson_destroy(&criteria_b);
return ret;
/*
bool mongoc_collection_delete (mongoc_collection_t *collection,
mongoc_delete_flags_t flags,
const bson_t *selector,
const mongoc_write_concern_t *write_concern,
bson_error_t *error);
*/
}
/*
public function update(array $criteria,
array $new_object,
array $options = array()): mixed;
*/
static Variant HHVM_METHOD(MongoCollection, update, Array criteria, Array new_object, Array options) {
mongoc_collection_t *collection;
bson_t selector; //selector is the criteria (which document to update)
bson_t update; //update is the new_object containing the new data
const bson_t * collection_error; //update is the new_object containing the new data
bson_error_t error;
collection = get_collection(this_);
encodeToBSON(criteria, &selector);
encodeToBSON(new_object, &update);
//先定义一些默认的参数
mongoc_update_flags_t update_flag = MONGOC_UPDATE_NONE;
//todo
int w_flag = MONGOC_WRITE_CONCERN_W_DEFAULT;
//如果传递了参数
if(!options.empty()){
//printf("multiple = %s\r\n",options[String("multiple")].toBoolean() ? "true":"false");
if(options[String("multiple")].toBoolean()==true){
update_flag = MONGOC_UPDATE_MULTI_UPDATE;
}
if(options[String("upsert")].toBoolean()==true){
update_flag = MONGOC_UPDATE_UPSERT;
}
}
mongoc_write_concern_t *write_concern;
write_concern = mongoc_write_concern_new();
mongoc_write_concern_set_w(write_concern, w_flag);
bool ret = mongoc_collection_update(collection, update_flag, &selector, &update, write_concern, &error);
bson_destroy(&update);
bson_destroy(&selector);
if (!ret) {
mongoThrow<MongoCursorException>((const char *) error.message);
}
collection_error = mongoc_collection_get_last_error(collection);
//char *str;
if (collection_error) {
//for debug
//str = bson_as_json(collection_error, NULL);
//printf("debug = %s\r\n",str);
//bson_free(str);
}
Array collectionReturn = Array();
Array ouput = Array();
collectionReturn = cbson_loads(collection_error);
mongoc_collection_destroy(collection);
ouput.add(String("ok"),1);
ouput.add(String("nModified"),collectionReturn[String("nModified")]);
ouput.add(String("n"),collectionReturn[String("nMatched")]);
ouput.add(String("updatedExisting"),true);//todo
ouput.add(String("err"),collectionReturn[String("writeErrors")]);
ouput.add(String("errmsg"),collectionReturn[String("writeErrors")]);
const StaticString s_MongoTimestamp("MongoTimestamp");
Array mongotimestampParam = Array();
ObjectData * data = create_object(&s_MongoTimestamp,mongotimestampParam);
ouput.add(String("lastOp"), data);
ouput.add(String("mongoRaw"),collectionReturn);
return ouput;
//return ret;
}
////////////////////////////////////////////////////////////////////////////////
void MongoExtension::_initMongoCollectionClass() {
HHVM_ME(MongoCollection, insert);
HHVM_ME(MongoCollection, remove);
HHVM_ME(MongoCollection, update);
}
} // namespace HPHP
<commit_msg>hhvm 的 mongo驱动, 格式兼容mongo-php-driver<commit_after>#include "ext_mongo.h"
#include "bson_decode.h"
#include "contrib/encode.h"
namespace HPHP {
static ObjectData *
create_object(const StaticString * className, Array params) {
TypedValue ret;
Class * cls = Unit::loadClass(className -> get());
ObjectData * obj = ObjectData::newInstance(cls);
obj->incRefCount();
g_context->invokeFunc(
&ret,
cls->getCtor(),
params,
obj
);
return obj;
}
static mongoc_collection_t *get_collection(Object obj) {
mongoc_collection_t *collection;
auto db = obj->o_realProp("db", ObjectData::RealPropUnchecked, "MongoCollection")->toObject();
auto client = db->o_realProp("client", ObjectData::RealPropUnchecked, "MongoDB")->toObject();
String db_name = db->o_realProp("db_name", ObjectData::RealPropUnchecked, "MongoDB")->toString();
String collection_name = obj->o_realProp("name", ObjectData::RealPropUnchecked, "MongoCollection")->toString();
collection = mongoc_client_get_collection(get_client(client)->get(), db_name.c_str(), collection_name.c_str());
return collection;
}
////////////////////////////////////////////////////////////////////////////////
// class MongoCollection
/**
* Inserts a document into the collection
*
* @param array|object $a - a An array or object. If an object is
* used, it may not have protected or private properties. If the
* parameter does not have an _id key or property, a new MongoId
* instance will be created and assigned to it.
* @param array $options - options Options for the insert.
*
* @return bool|array - Returns an array containing the status of the
* insertion if the "w" option is set. Otherwise, returns TRUE if the
* inserted array is not empty (a MongoException will be thrown if the
* inserted array is empty).
*/
//public function insert(mixed $a, array $options = array()): mixed;
static Variant HHVM_METHOD(MongoCollection, insert, Variant a, Array options) {
mongoc_collection_t *collection;
bson_t doc;
bson_error_t error;
collection = get_collection(this_);
Array& doc_array = a.toArrRef();
if (!doc_array.exists(String("_id"))) {
const StaticString s_MongoId("MongoId");
char id[25];
bson_oid_t oid;
bson_oid_init(&oid, NULL);
bson_oid_to_string(&oid, id);
ObjectData * data = create_object(&s_MongoId, make_packed_array(String(id)));
doc_array.add(String("_id"), data);
}
encodeToBSON(doc_array, &doc);
int w_flag = MONGOC_WRITE_CONCERN_W_DEFAULT;
//如果传递了参数
mongoc_write_concern_t *write_concern;
write_concern = mongoc_write_concern_new();
mongoc_write_concern_set_w(write_concern, w_flag);
bool ret = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, &doc, write_concern, &error);
if (!ret) {
mongoThrow<MongoCursorException>((const char *) error.message);
}
mongoc_collection_destroy(collection);
bson_destroy(&doc);
return ret;
/*
bool mongoc_collection_insert (mongoc_collection_t *collection,
mongoc_insert_flags_t flags,
const bson_t *document,
const mongoc_write_concern_t *write_concern,
bson_error_t *error);
*/
}
/**
* Remove records from this collection
*
* @param array $criteria - criteria Description of records to
* remove.
* @param array $options - options Options for remove. "justOne"
* Remove at most one record matching this criteria.
*
* @return bool|array - Returns an array containing the status of the
* removal if the "w" option is set. Otherwise, returns TRUE.
*/
//public function remove(array $criteria = array(), array $options = array()): mixed;
static Variant HHVM_METHOD(MongoCollection, remove, Array criteria, Array options) {
mongoc_collection_t *collection;
bson_t criteria_b;
bson_error_t error;
collection = get_collection(this_);
encodeToBSON(criteria, &criteria_b);
mongoc_delete_flags_t delete_flag = MONGOC_DELETE_NONE;
int w_flag = MONGOC_WRITE_CONCERN_W_DEFAULT;
//如果传递了参数
if(!options.empty()){
//printf("multiple = %s\r\n",options[String("multiple")].toBoolean() ? "true":"false");
if(options[String("justOne")].toBoolean()==true){
delete_flag = MONGOC_DELETE_SINGLE_REMOVE;
}
}
mongoc_write_concern_t *write_concern;
write_concern = mongoc_write_concern_new();
mongoc_write_concern_set_w(write_concern, w_flag);
bool ret = mongoc_collection_delete(collection, delete_flag, &criteria_b, write_concern, &error);
if (!ret) {
mongoThrow<MongoCursorException>((const char *) error.message);
}
mongoc_collection_destroy(collection);
bson_destroy(&criteria_b);
return ret;
/*
bool mongoc_collection_delete (mongoc_collection_t *collection,
mongoc_delete_flags_t flags,
const bson_t *selector,
const mongoc_write_concern_t *write_concern,
bson_error_t *error);
*/
}
/*
public function update(array $criteria,
array $new_object,
array $options = array()): mixed;
*/
static Variant HHVM_METHOD(MongoCollection, update, Array criteria, Array new_object, Array options) {
mongoc_collection_t *collection;
bson_t selector; //selector is the criteria (which document to update)
bson_t update; //update is the new_object containing the new data
const bson_t * collection_error; //update is the new_object containing the new data
bson_error_t error;
collection = get_collection(this_);
encodeToBSON(criteria, &selector);
encodeToBSON(new_object, &update);
//先定义一些默认的参数
mongoc_update_flags_t update_flag = MONGOC_UPDATE_NONE;
//todo
int w_flag = MONGOC_WRITE_CONCERN_W_DEFAULT;
//如果传递了参数
if(!options.empty()){
//printf("multiple = %s\r\n",options[String("multiple")].toBoolean() ? "true":"false");
if(options[String("multiple")].toBoolean()==true){
update_flag = MONGOC_UPDATE_MULTI_UPDATE;
}
if(options[String("upsert")].toBoolean()==true){
update_flag = MONGOC_UPDATE_UPSERT;
}
}
mongoc_write_concern_t *write_concern;
write_concern = mongoc_write_concern_new();
mongoc_write_concern_set_w(write_concern, w_flag);
bool ret = mongoc_collection_update(collection, update_flag, &selector, &update, write_concern, &error);
bson_destroy(&update);
bson_destroy(&selector);
if (!ret) {
mongoThrow<MongoCursorException>((const char *) error.message);
}
collection_error = mongoc_collection_get_last_error(collection);
//char *str;
//if (collection_error) {
//for debug
//str = bson_as_json(collection_error, NULL);
//printf("debug = %s\r\n",str);
//bson_free(str);
//}
Array collectionReturn = Array();
Array ouput = Array();
collectionReturn = cbson_loads(collection_error);
mongoc_collection_destroy(collection);
ouput.add(String("ok"),1);
ouput.add(String("nModified"),collectionReturn[String("nModified")]);
ouput.add(String("n"),collectionReturn[String("nMatched")]);
ouput.add(String("updatedExisting"),collectionReturn[String("nMatched")].toInt64() > 0 ?true:false);//todo
ouput.add(String("err"),collectionReturn[String("writeErrors")]);
ouput.add(String("errmsg"),collectionReturn[String("writeErrors")]);
const StaticString s_MongoTimestamp("MongoTimestamp");
Array mongotimestampParam = Array();
ObjectData * data = create_object(&s_MongoTimestamp,mongotimestampParam);
ouput.add(String("lastOp"), data);
ouput.add(String("mongoRaw"),collectionReturn);
return ouput;
//return ret;
}
////////////////////////////////////////////////////////////////////////////////
void MongoExtension::_initMongoCollectionClass() {
HHVM_ME(MongoCollection, insert);
HHVM_ME(MongoCollection, remove);
HHVM_ME(MongoCollection, update);
}
} // namespace HPHP
<|endoftext|> |
<commit_before>// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.
#include "stdafx.h"
#include "../PqaCore/BaseQuiz.h"
using namespace SRPlat;
namespace ProbQA {
BaseQuiz::BaseQuiz(BaseEngine *pEngine) : _pEngine(pEngine) {
const EngineDimensions& dims = _pEngine->GetDims();
const size_t nQuestions = SRPlat::SRCast::ToSizeT(dims._nQuestions);
SRMemTotal mtCommon;
SRMemItem<__m256i> miIsQAsked(SRPlat::SRSimd::VectsFromBits(nQuestions), SRPlat::SRMemPadding::Both, mtCommon);
// First allocate all the memory so to revert if anything fails.
SRSmartMPP<uint8_t> commonBuf(_pEngine->GetMemPool(), mtCommon._nBytes);
// Must be the first memory block, because it's used for releasing the memory
_isQAsked = miIsQAsked.Ptr(commonBuf);
// As all the memory is allocated, safely proceed with finishing construction of CEBaseQuiz object.
commonBuf.Detach();
}
BaseQuiz::~BaseQuiz() {
}
} // namespace ProbQA
<commit_msg>Fixed a memory leak in BaseQuiz.<commit_after>// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.
#include "stdafx.h"
#include "../PqaCore/BaseQuiz.h"
using namespace SRPlat;
namespace ProbQA {
BaseQuiz::BaseQuiz(BaseEngine *pEngine) : _pEngine(pEngine) {
const EngineDimensions& dims = _pEngine->GetDims();
const size_t nQuestions = SRPlat::SRCast::ToSizeT(dims._nQuestions);
SRMemTotal mtCommon;
SRMemItem<__m256i> miIsQAsked(SRPlat::SRSimd::VectsFromBits(nQuestions), SRPlat::SRMemPadding::Both, mtCommon);
// First allocate all the memory so to revert if anything fails.
SRSmartMPP<uint8_t> commonBuf(_pEngine->GetMemPool(), mtCommon._nBytes);
// Must be the first memory block, because it's used for releasing the memory
_isQAsked = miIsQAsked.Ptr(commonBuf);
// As all the memory is allocated, safely proceed with finishing construction of CEBaseQuiz object.
commonBuf.Detach();
}
BaseQuiz::~BaseQuiz() {
using namespace SRPlat;
//NOTE: engine dimensions must not change during lifetime of the quiz because below we must provide the same number
// of targets and questions.
const EngineDimensions& dims = _pEngine->GetDims();
const size_t nQuestions = SRPlat::SRCast::ToSizeT(dims._nQuestions);
SRMemTotal mtCommon;
SRMemItem<__m256i> miIsQAsked(SRPlat::SRSimd::VectsFromBits(nQuestions), SRPlat::SRMemPadding::Both, mtCommon);
_pEngine->GetMemPool().ReleaseMem(_isQAsked, mtCommon._nBytes);
}
} // namespace ProbQA
<|endoftext|> |
<commit_before>/**
* Unix Tools For Windows
* - cksum: write file checksums and sizes
*
* Written in 2013 by Ruben Van Boxem <vanboxem.ruben@gmail.com>
*
* To the extent possible under law, the author(s) have dedicated all copyright and related
* and neighboring rights to this software to the public domain worldwide. This software is
* distributed without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along with this software.
* If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*
*/
// Support include
#include "support.h"
// Boost includes
#include <boost/crc.hpp>
typedef boost::crc_optimal<32, 0x04C11DB7, 0, 0xFFFFFFFF, false, false> cksum_crc_type;
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
// C++ includes
#include <array>
using std::array;
#include <cstddef>
using std::size_t;
#include <iostream>
#include <string>
using std::string;
int main(int argc, char* argv[])
try
{
argv = support::commandline_arguments(argc, argv);
std::vector<std::string> input;
po::options_description options("Options");
options.add_options()("help", "Show this help output.");
po::options_description operands("Operands");
operands.add_options()("files", po::value(&input), "input");
po::options_description options_operands;
options_operands.add(options).add(operands);
po::positional_options_description file_options;
file_options.add("files", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(options_operands).positional(file_options).run(), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << "cksum: write file checksums and sizes\n"
"Usage: cksum [file...]\n"
<< options
<< "Operands:\n"
" file...\t\tA pathname of a file to be checked. If no file operands are specified, the standard input shall be used.";
return 0;
}
const std::size_t buffer_size = 1024;
array<char, buffer_size> buffer;
if(argc == 1)
{
size_t octets = 0;
cksum_crc_type crc;
while(true)
{
size_t bytes_read = support::standard_input.read_some(buffer_size, buffer.data());
octets += bytes_read;
crc.process_bytes(buffer.data(), bytes_read);
if(bytes_read < buffer_size)
break;
}
support::print(boost::lexical_cast<string>(crc.checksum()) + " " + boost::lexical_cast<string>(octets));
return 0;
}
for(int i = 1; i<argc; ++i)
{
support::file current(argv[i], support::file::access::read);
size_t octets = 0;
cksum_crc_type crc;
while(true)
{
size_t bytes_read = current.read_some(buffer_size, buffer.data());
octets += bytes_read;
crc.process_bytes(&buffer[0], bytes_read);
if(bytes_read < buffer_size)
break;
}
if(i>1)
support::print("\n");
support::print(boost::lexical_cast<string>(crc.checksum()) + " " + boost::lexical_cast<string>(octets) + " " + argv[i]);
}
}
catch(const std::exception& e)
{
std::cerr << e.what();
return 1; //TODO
}
<commit_msg>Not fix cksum<commit_after>/**
* Unix Tools For Windows
* - cksum: write file checksums and sizes
*
* Written in 2013 by Ruben Van Boxem <vanboxem.ruben@gmail.com>
*
* To the extent possible under law, the author(s) have dedicated all copyright and related
* and neighboring rights to this software to the public domain worldwide. This software is
* distributed without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along with this software.
* If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*
*/
// Support include
#include "support.h"
// Boost includes
#include <boost/crc.hpp>
typedef boost::crc_optimal<32, 0x04C11DB7, 0, 0xFFFFFFFF, false, false> cksum_crc_type; // closest to POSIX, not perfect per spec though...
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
// C++ includes
#include <array>
using std::array;
#include <cstddef>
using std::size_t;
#include <iostream>
#include <string>
using std::string;
int main(int argc, char* argv[])
try
{
argv = support::commandline_arguments(argc, argv);
std::vector<std::string> input;
po::options_description options("Options");
options.add_options()("help", "Show this help output.");
po::options_description operands("Operands");
operands.add_options()("files", po::value(&input), "input");
po::options_description options_operands;
options_operands.add(options).add(operands);
po::positional_options_description file_options;
file_options.add("files", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(options_operands).positional(file_options).run(), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << "cksum: write file checksums and sizes\n"
"Usage: cksum [file...]\n"
<< options
<< "Operands:\n"
" file...\t\tA pathname of a file to be checked. If no file operands are specified, the standard input shall be used.";
return 0;
}
const std::size_t buffer_size = 1024;
array<char, buffer_size> buffer;
if(argc == 1)
{
size_t octets = 0;
cksum_crc_type crc;
while(true)
{
size_t bytes_read = support::standard_input.read_some(buffer_size, buffer.data());
octets += bytes_read;
crc.process_bytes(buffer.data(), bytes_read);
if(bytes_read < buffer_size)
break;
}
support::print(boost::lexical_cast<string>(crc.checksum()) + " " + boost::lexical_cast<string>(octets));
return 0;
}
for(int i = 1; i<argc; ++i)
{
support::file current(argv[i], support::file::access::read);
size_t octets = 0;
cksum_crc_type crc;
while(true)
{
size_t bytes_read = current.read_some(buffer_size, buffer.data());
octets += bytes_read;
crc.process_bytes(&buffer[0], bytes_read);
if(bytes_read < buffer_size)
break;
}
if(i>1)
support::print("\n");
support::print(boost::lexical_cast<string>(crc.checksum()) + " " + boost::lexical_cast<string>(octets) + " " + argv[i]);
}
}
catch(const std::exception& e)
{
std::cerr << e.what();
return 1; //TODO
}
<|endoftext|> |
<commit_before>#include "TicTacToeBoard.h"
/**
* Class for representing a 3x3 Tic-Tac-Toe game board, using the Piece enum
* to represent the spaces on the board.
**/
//Constructor sets an empty board and specifies it is X's turn first
TicTacToeBoard::TicTacToeBoard()
{
turn = X;
for(int i=0; i<BOARDSIZE; i++)
for(int j=0; j<BOARDSIZE; j++)
board[i][j] = Blank;
}
/**
* Switches turn member variable to represent whether it's X's or O's turn
* and returns whose turn it is
**/
Piece TicTacToeBoard::toggleTurn()
{
return Invalid;
}
/**
* Places the piece of the current turn on the board, returns what
* piece is placed, and toggles which Piece's turn it is. placePiece does
* NOT allow to place a piece in a location where there is already a piece.
* In that case, placePiece just returns what is already at that location.
* Out of bounds coordinates return the Piece Invalid value. When the game
* is over, no more pieces can be placed so attempting to place a piece
* should neither change the board nor change whose turn it is.
**/
Piece TicTacToeBoard::placePiece(int row, int column)
{
return Invalid;
}
/**
* Returns what piece is at the provided coordinates, or Blank if there
* are no pieces there, or Invalid if the coordinates are out of bounds
**/
Piece TicTacToeBoard::getPiece(int row, int column)
{
return Invalid;
}
/**
* Returns which Piece has won, if there is a winner, Invalid if the game
* is not over, or Blank if the board is filled and no one has won.
**/
Piece TicTacToeBoard::getWinner()
{
return Invalid;
}
<commit_msg>completed toggleTurn and place Piece<commit_after>#include "TicTacToeBoard.h"
/**
* Class for representing a 3x3 Tic-Tac-Toe game board, using the Piece enum
* to represent the spaces on the board.
**/
//Constructor sets an empty board and specifies it is X's turn first
TicTacToeBoard::TicTacToeBoard()
{
turn = X;
for(int i=0; i<BOARDSIZE; i++)
for(int j=0; j<BOARDSIZE; j++)
board[i][j] = Blank;
}
/**
* Switches turn member variable to represent whether it's X's or O's turn
* and returns whose turn it is
**/
Piece TicTacToeBoard::toggleTurn()
{
Piece tempTurn;
if(turn == X)
{
tempTurn = O;
}
else
tempTurn = X;
return tempTurn;
}
/**
* Places the piece of the current turn on the board, returns what
* piece is placed, and toggles which Piece's turn it is. placePiece does
* NOT allow to place a piece in a location where there is already a piece.
* In that case, placePiece just returns what is already at that location.
* Out of bounds coordinates return the Piece Invalid value. When the game
* is over, no more pieces can be placed so attempting to place a piece
* should neither change the board nor change whose turn it is.
**/
Piece TicTacToeBoard::placePiece(int row, int column)
{
if(row > 2 || column > 2)
return Invalid;
else if (getWinner() != Invalid)
return turn;
else if(board[row][column] != Blank)
return board[row][column];
else
{
board[row][column] = turn;
turn = toggleTurn();
}
return board[row][column];
}
/**
* Returns what piece is at the provided coordinates, or Blank if there
* are no pieces there, or Invalid if the coordinates are out of bounds
**/
Piece TicTacToeBoard::getPiece(int row, int column)
{
return Invalid;
}
/**
* Returns which Piece has won, if there is a winner, Invalid if the game
* is not over, or Blank if the board is filled and no one has won.
**/
Piece TicTacToeBoard::getWinner()
{
return Invalid;
}
<|endoftext|> |
<commit_before><commit_msg>Unobserve the RenderView before DeleteSoon.<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_OTHER_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/File_Other.h"
#include "ZenLib/Utils.h"
using namespace ZenLib;
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Format
//***************************************************************************
//---------------------------------------------------------------------------
void File_Other::Read_Buffer_Continue()
{
//Integrity
if (Buffer_Size<16)
{
Element_WaitForMoreData();
return;
}
Ztring Format;
if (Buffer[0]==0xEA
&& Buffer[1]==0x22
&& Buffer[2]<=0x03)
{
Accept();
Stream_Prepare(Stream_Text);
Fill(Stream_Text, 0, Text_Format, "Cheetah");
Finish();
return;
}
if (Buffer[0]==0x4C
&& Buffer[1]==0x61
&& Buffer[2]==0x6D
&& Buffer[3]==0x62
&& Buffer[4]==0x64
&& Buffer[5]==0x61)
{
Accept();
Stream_Prepare(Stream_Text);
Fill(Stream_Text, 0, Text_Format, "Lambda");
Finish();
return;
}
if (CC4(Buffer)==0xC5C6CBC3) {Format=__T("RISC OS Chunk data");}
else if (CC4(Buffer)==0x110000EF) {Format=__T("RISC OS AIF executable");}
else if (CC4(Buffer)==CC4("Draw")) {Format=__T("RISC OS Draw");}
else if (CC4(Buffer)==CC4("FONT")) {Format=__T("RISC OS Font");}
else if (CC8(Buffer)==CC8("Maestro\r")) {Format=__T("RISC OS music file");}
else if (CC4(Buffer)==CC4("FC14")) {Format=__T("Amiga Future Composer");}
else if (CC4(Buffer)==CC4("SMOD")) {Format=__T("Amiga Future Composer");}
else if (CC4(Buffer)==CC4("AON4")) {Format=__T("Amiga Art Of Noise");}
else if (CC8(Buffer+1)==CC8("MUGICIAN")) {Format=__T("Amiga Mugician");}
else if (Buffer_Size>=66 && CC8(Buffer+58)==CC8("SIDMON I")) {Format=__T("Amiga Sidmon");}
else if (CC8(Buffer)==CC8("Synth4.0")) {Format=__T("Amiga Synthesis");}
else if (CC4(Buffer)==CC4("ARP.")) {Format=__T("Amiga Holy Noise");}
else if (CC4(Buffer)==CC4("BeEp")) {Format=__T("Amiga JamCracker");}
else if (CC4(Buffer)==CC4("COSO")) {Format=__T("Amiga Hippel-COSO");}
else if (CC3(Buffer)==CC3("LSX")) {Format=__T("Amiga LZX");}
else if (CC4(Buffer)==CC4("MOVI")) {Format=__T("Silicon Graphics movie");}
else if (CC4(Buffer+10)==CC4("Vivo")) {Format=__T("Vivo");}
else if (CC4(Buffer+1)==CC4("VRML")) {Format=__T("VRML");}
else if (CC5(Buffer)==CC5("HVQM4")) {Format=__T("GameCube Movie");}
else if (CC8(Buffer)==CC8("KW-DIRAC"))
{
Accept("Dirac");
Stream_Prepare(Stream_Video);
Fill(Stream_Video, 0, Video_Format, "Dirac");
Finish("Dirac");
return;
}
else if (CC5(Buffer)==CC5("ustar")) {Format=__T("Tar archive");}
//TODO: all archive magic numbers
else if (CC4(Buffer+1)==CC4("MSCB")) {Format=__T("MS Cabinet");}
else if (CC4(Buffer)==CC4(".snd")) {Format=__T("SUN Audio");}
else if (CC4(Buffer)==0x2E736400) {Format=__T("DEC Audio");}
else if (CC4(Buffer)==CC4("MThd")) {Format=__T("MIDI");}
else if (CC4(Buffer)==CC4("CTMF")) {Format=__T("CMF");}
else if (CC3(Buffer)==CC3("SBI")) {Format=__T("SoundBlaster");}
else if (CC4(Buffer)==CC4("EMOD")) {Format=__T("Ext. MOD");}
//TODO: Other Sound magic numbers
else if (CC7(Buffer)==CC7("BLENDER")) {Format=__T("Blender");}
else if (CC4(Buffer)==CC4("AC10")) {Format=__T("AutoCAD"); ;}
else if (CC2(Buffer)==0x1F9D) {Format=__T("Compress");}
else if (CC2(Buffer)==0x1F8B) {Format=__T("GZip");}
else if (CC2(Buffer)==0x1F1E) {Format=__T("Huffman");}
else if (CC3(Buffer)==CC3("BZh")) {Format=__T("BZip2");}
else if (CC2(Buffer)==CC2("BZ")) {Format=__T("BZip1");}
else if (CC3(Buffer)==CC3("NES")) {Format=__T("NES ROM");}
else if (Buffer_Size>=0x108 && CC4(Buffer+0x104)==0xCEED6666) {Format=__T("GameBoy");}
else if (Buffer_Size>=0x104 && CC4(Buffer+0x100)==CC4("SEGA")) {Format=__T("MegaDrive");}
else if (Buffer_Size>=0x284 && CC4(Buffer+0x280)==CC4("EAGN")) {Format=__T("SupeMegaDrive");}
else if (Buffer_Size>=0x284 && CC4(Buffer+0x280)==CC4("EAMG")) {Format=__T("SupeMegaDrive");}
else if (CC4(Buffer)==0x21068028) {Format=__T("Dreamcast");}
else if (CC4(Buffer)==CC4("LCDi")) {Format=__T("Dreamcast");}
else if (CC4(Buffer)==0x37804012) {Format=__T("Nintendo64");}
else if (CC8(Buffer)==CC8("PS-X EXE")) {Format=__T("Playstation");}
else if (CC4(Buffer)==CC4("LCDi")) {Format=__T("Dreamcast");}
else if (CC4(Buffer)==CC4("XBEH")) {Format=__T("X-Box");}
else if (CC4(Buffer)==CC4("XIP0")) {Format=__T("X-Box");}
else if (CC4(Buffer)==CC4("XTF0")) {Format=__T("X-Box");}
else if (CC2(Buffer)==0x8008) {Format=__T("Lynx");}
else if (CC7(Buffer)==CC7("\x01ZZZZZ\x01")) {Format=__T("");}
else if (CC6(Buffer)==CC6("1\x0A\x0D""00:"))
{
Accept("SRT");
Stream_Prepare(Stream_Text);
Fill(Stream_Text, 0, Text_Format, "SRT");
Finish("SRT");
return;
}
else if ((CC1(Buffer+0)==CC1("[") && CC1(Buffer+2)==CC1("S") && CC1(Buffer+22)==CC1("o") && CC1(Buffer+24)==CC1("]")) //Unicode Text is : "[Script Info]
|| (CC1(Buffer+2)==CC1("[") && CC1(Buffer+4)==CC1("S") && CC1(Buffer+24)==CC1("o") && CC1(Buffer+26)==CC1("]")))
{
Accept("SSA");
Stream_Prepare(Stream_Text);
Fill(Stream_Text, 0, Text_Format, "SSA");
Finish("SSA");
return;
}
else if (CC4(Buffer)==CC4("RIFF") && CC4(Buffer+8)==CC4("AMV ")) {Format=__T("AMV");}
else if (CC4(Buffer)==CC4("RIFF") && CC4(Buffer+8)==CC4("WEBP"))
{
Accept("WEBP");
Stream_Prepare(Stream_Image);
Fill(Stream_Image, 0, Image_Format, "WebP");
Finish("WEBP");
return;
}
else if (CC4(Buffer)==0x414D5697) {Format=__T("MTV");}
else if (CC6(Buffer)==CC6("Z\0W\0F\0"))
{
Accept("ZWF");
Stream_Prepare(Stream_Audio);
Fill(Stream_Audio, 0, Audio_Format, "ZWF");
Finish("ZWF");
return;
}
else if (CC4(Buffer)==0x616A6B67) //"ajkg"
{
Accept("Shorten");
Fill(Stream_General, 0, General_Format_Version, CC1(Buffer+4));
Stream_Prepare(Stream_Audio);
Fill(Stream_Audio, 0, Audio_Format, "Shorten");
Finish("Shorten");
return;
}
else if (CC4(Buffer)==0x504C5646) {Format=__T("PlayLater Video");}
else if (CC4(Buffer)==CC4("")) {Format=__T("");}
if (Format.empty())
{
Reject();
return;
}
Accept();
Element_Offset=File_Size-(File_Offset+Buffer_Offset);
Fill(Stream_General, 0, General_Format, Format);
Finish();
}
} //NameSpace
#endif //MEDIAINFO_OTHER_YES
<commit_msg>x Other: fix useless (and buggy) check<commit_after>/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_OTHER_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/File_Other.h"
#include "ZenLib/Utils.h"
using namespace ZenLib;
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Format
//***************************************************************************
//---------------------------------------------------------------------------
void File_Other::Read_Buffer_Continue()
{
//Integrity
if (Buffer_Size<16)
{
Element_WaitForMoreData();
return;
}
Ztring Format;
if (Buffer[0]==0xEA
&& Buffer[1]==0x22
&& Buffer[2]<=0x03)
{
Accept();
Stream_Prepare(Stream_Text);
Fill(Stream_Text, 0, Text_Format, "Cheetah");
Finish();
return;
}
if (Buffer[0]==0x4C
&& Buffer[1]==0x61
&& Buffer[2]==0x6D
&& Buffer[3]==0x62
&& Buffer[4]==0x64
&& Buffer[5]==0x61)
{
Accept();
Stream_Prepare(Stream_Text);
Fill(Stream_Text, 0, Text_Format, "Lambda");
Finish();
return;
}
if (CC4(Buffer)==0xC5C6CBC3) {Format=__T("RISC OS Chunk data");}
else if (CC4(Buffer)==0x110000EF) {Format=__T("RISC OS AIF executable");}
else if (CC4(Buffer)==CC4("Draw")) {Format=__T("RISC OS Draw");}
else if (CC4(Buffer)==CC4("FONT")) {Format=__T("RISC OS Font");}
else if (CC8(Buffer)==CC8("Maestro\r")) {Format=__T("RISC OS music file");}
else if (CC4(Buffer)==CC4("FC14")) {Format=__T("Amiga Future Composer");}
else if (CC4(Buffer)==CC4("SMOD")) {Format=__T("Amiga Future Composer");}
else if (CC4(Buffer)==CC4("AON4")) {Format=__T("Amiga Art Of Noise");}
else if (CC8(Buffer+1)==CC8("MUGICIAN")) {Format=__T("Amiga Mugician");}
else if (Buffer_Size>=66 && CC8(Buffer+58)==CC8("SIDMON I")) {Format=__T("Amiga Sidmon");}
else if (CC8(Buffer)==CC8("Synth4.0")) {Format=__T("Amiga Synthesis");}
else if (CC4(Buffer)==CC4("ARP.")) {Format=__T("Amiga Holy Noise");}
else if (CC4(Buffer)==CC4("BeEp")) {Format=__T("Amiga JamCracker");}
else if (CC4(Buffer)==CC4("COSO")) {Format=__T("Amiga Hippel-COSO");}
else if (CC3(Buffer)==CC3("LSX")) {Format=__T("Amiga LZX");}
else if (CC4(Buffer)==CC4("MOVI")) {Format=__T("Silicon Graphics movie");}
else if (CC4(Buffer+10)==CC4("Vivo")) {Format=__T("Vivo");}
else if (CC4(Buffer+1)==CC4("VRML")) {Format=__T("VRML");}
else if (CC5(Buffer)==CC5("HVQM4")) {Format=__T("GameCube Movie");}
else if (CC8(Buffer)==CC8("KW-DIRAC"))
{
Accept("Dirac");
Stream_Prepare(Stream_Video);
Fill(Stream_Video, 0, Video_Format, "Dirac");
Finish("Dirac");
return;
}
else if (CC5(Buffer)==CC5("ustar")) {Format=__T("Tar archive");}
//TODO: all archive magic numbers
else if (CC4(Buffer+1)==CC4("MSCB")) {Format=__T("MS Cabinet");}
else if (CC4(Buffer)==CC4(".snd")) {Format=__T("SUN Audio");}
else if (CC4(Buffer)==0x2E736400) {Format=__T("DEC Audio");}
else if (CC4(Buffer)==CC4("MThd")) {Format=__T("MIDI");}
else if (CC4(Buffer)==CC4("CTMF")) {Format=__T("CMF");}
else if (CC3(Buffer)==CC3("SBI")) {Format=__T("SoundBlaster");}
else if (CC4(Buffer)==CC4("EMOD")) {Format=__T("Ext. MOD");}
//TODO: Other Sound magic numbers
else if (CC7(Buffer)==CC7("BLENDER")) {Format=__T("Blender");}
else if (CC4(Buffer)==CC4("AC10")) {Format=__T("AutoCAD"); ;}
else if (CC2(Buffer)==0x1F9D) {Format=__T("Compress");}
else if (CC2(Buffer)==0x1F8B) {Format=__T("GZip");}
else if (CC2(Buffer)==0x1F1E) {Format=__T("Huffman");}
else if (CC3(Buffer)==CC3("BZh")) {Format=__T("BZip2");}
else if (CC2(Buffer)==CC2("BZ")) {Format=__T("BZip1");}
else if (CC3(Buffer)==CC3("NES")) {Format=__T("NES ROM");}
else if (Buffer_Size>=0x108 && CC4(Buffer+0x104)==0xCEED6666) {Format=__T("GameBoy");}
else if (Buffer_Size>=0x104 && CC4(Buffer+0x100)==CC4("SEGA")) {Format=__T("MegaDrive");}
else if (Buffer_Size>=0x284 && CC4(Buffer+0x280)==CC4("EAGN")) {Format=__T("SupeMegaDrive");}
else if (Buffer_Size>=0x284 && CC4(Buffer+0x280)==CC4("EAMG")) {Format=__T("SupeMegaDrive");}
else if (CC4(Buffer)==0x21068028) {Format=__T("Dreamcast");}
else if (CC4(Buffer)==CC4("LCDi")) {Format=__T("Dreamcast");}
else if (CC4(Buffer)==0x37804012) {Format=__T("Nintendo64");}
else if (CC8(Buffer)==CC8("PS-X EXE")) {Format=__T("Playstation");}
else if (CC4(Buffer)==CC4("LCDi")) {Format=__T("Dreamcast");}
else if (CC4(Buffer)==CC4("XBEH")) {Format=__T("X-Box");}
else if (CC4(Buffer)==CC4("XIP0")) {Format=__T("X-Box");}
else if (CC4(Buffer)==CC4("XTF0")) {Format=__T("X-Box");}
else if (CC2(Buffer)==0x8008) {Format=__T("Lynx");}
else if (CC7(Buffer)==CC7("\x01ZZZZZ\x01")) {Format=__T("");}
else if (CC6(Buffer)==CC6("1\x0A\x0D""00:"))
{
Accept("SRT");
Stream_Prepare(Stream_Text);
Fill(Stream_Text, 0, Text_Format, "SRT");
Finish("SRT");
return;
}
else if ((CC1(Buffer+0)==CC1("[") && CC1(Buffer+2)==CC1("S") && CC1(Buffer+22)==CC1("o") && CC1(Buffer+24)==CC1("]")) //Unicode Text is : "[Script Info]
|| (CC1(Buffer+2)==CC1("[") && CC1(Buffer+4)==CC1("S") && CC1(Buffer+24)==CC1("o") && CC1(Buffer+26)==CC1("]")))
{
Accept("SSA");
Stream_Prepare(Stream_Text);
Fill(Stream_Text, 0, Text_Format, "SSA");
Finish("SSA");
return;
}
else if (CC4(Buffer)==CC4("RIFF") && CC4(Buffer+8)==CC4("AMV ")) {Format=__T("AMV");}
else if (CC4(Buffer)==CC4("RIFF") && CC4(Buffer+8)==CC4("WEBP"))
{
Accept("WEBP");
Stream_Prepare(Stream_Image);
Fill(Stream_Image, 0, Image_Format, "WebP");
Finish("WEBP");
return;
}
else if (CC4(Buffer)==0x414D5697) {Format=__T("MTV");}
else if (CC6(Buffer)==CC6("Z\0W\0F\0"))
{
Accept("ZWF");
Stream_Prepare(Stream_Audio);
Fill(Stream_Audio, 0, Audio_Format, "ZWF");
Finish("ZWF");
return;
}
else if (CC4(Buffer)==0x616A6B67) //"ajkg"
{
Accept("Shorten");
Fill(Stream_General, 0, General_Format_Version, CC1(Buffer+4));
Stream_Prepare(Stream_Audio);
Fill(Stream_Audio, 0, Audio_Format, "Shorten");
Finish("Shorten");
return;
}
else if (CC4(Buffer)==0x504C5646) {Format=__T("PlayLater Video");}
if (Format.empty())
{
Reject();
return;
}
Accept();
Element_Offset=File_Size-(File_Offset+Buffer_Offset);
Fill(Stream_General, 0, General_Format, Format);
Finish();
}
} //NameSpace
#endif //MEDIAINFO_OTHER_YES
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef DATABASE_HH_
#define DATABASE_HH_
#include "core/sstring.hh"
#include "core/shared_ptr.hh"
#include "net/byteorder.hh"
#include "utils/UUID.hh"
#include "db_clock.hh"
#include "gc_clock.hh"
#include <functional>
#include <boost/any.hpp>
#include <cstdint>
#include <boost/variant.hpp>
#include <unordered_map>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <boost/functional/hash.hpp>
#include <experimental/optional>
#include <string.h>
#include "types.hh"
#include "tuple.hh"
#include "core/future.hh"
#include "cql3/column_specification.hh"
struct row;
struct paritition;
struct column_family;
struct row {
std::vector<bytes> cells;
};
struct partition {
explicit partition(column_family& cf);
row static_columns;
// row key within partition -> row
std::map<bytes, row, key_compare> rows;
};
using column_id = uint32_t;
class column_definition final {
private:
bytes _name;
public:
enum column_kind { PARTITION, CLUSTERING, REGULAR, STATIC };
column_definition(bytes name, data_type type, column_id id, column_kind kind);
data_type type;
column_id id; // unique within (kind, schema instance)
column_kind kind;
::shared_ptr<cql3::column_specification> column_specification;
bool is_static() const { return kind == column_kind::STATIC; }
const sstring& name_as_text() const;
const bytes& name() const;
};
struct thrift_schema {
shared_ptr<abstract_type> partition_key_type;
};
/*
* Keep this effectively immutable.
*/
class schema final {
private:
std::unordered_map<bytes, column_definition*> _columns_by_name;
std::map<bytes, column_definition*, serialized_compare> _regular_columns_by_name;
public:
struct column {
bytes name;
data_type type;
struct name_compare {
shared_ptr<abstract_type> type;
name_compare(shared_ptr<abstract_type> type) : type(type) {}
bool operator()(const column& cd1, const column& cd2) const {
return type->less(cd1.name, cd2.name);
}
};
};
private:
void build_columns(std::vector<column> columns, column_definition::column_kind kind, std::vector<column_definition>& dst);
::shared_ptr<cql3::column_specification> make_column_specification(column_definition& def);
public:
gc_clock::duration default_time_to_live = gc_clock::duration::zero();
const sstring ks_name;
const sstring cf_name;
std::vector<column_definition> partition_key;
std::vector<column_definition> clustering_key;
std::vector<column_definition> regular_columns; // sorted by name
shared_ptr<tuple_type<>> partition_key_type;
shared_ptr<tuple_type<>> clustering_key_type;
shared_ptr<tuple_prefix> clustering_key_prefix_type;
data_type regular_column_name_type;
thrift_schema thrift;
public:
schema(sstring ks_name, sstring cf_name,
std::vector<column> partition_key,
std::vector<column> clustering_key,
std::vector<column> regular_columns,
shared_ptr<abstract_type> regular_column_name_type);
bool is_dense() const {
return false;
}
bool is_counter() const {
return false;
}
column_definition* get_column_definition(const bytes& name);
auto regular_begin() {
return regular_columns.begin();
}
auto regular_end() {
return regular_columns.end();
}
auto regular_lower_bound(const bytes& name) {
// TODO: use regular_columns and a version of std::lower_bound() with heterogeneous comparator
auto i = _regular_columns_by_name.lower_bound(name);
if (i == _regular_columns_by_name.end()) {
return regular_end();
} else {
return regular_columns.begin() + i->second->id;
}
}
auto regular_upper_bound(const bytes& name) {
// TODO: use regular_columns and a version of std::upper_bound() with heterogeneous comparator
auto i = _regular_columns_by_name.upper_bound(name);
if (i == _regular_columns_by_name.end()) {
return regular_end();
} else {
return regular_columns.begin() + i->second->id;
}
}
column_id get_regular_columns_count() {
return regular_columns.size();
}
data_type column_name_type(column_definition& def) {
return def.kind == column_definition::REGULAR ? regular_column_name_type : utf8_type;
}
};
using schema_ptr = lw_shared_ptr<schema>;
struct column_family {
column_family(schema_ptr schema);
partition& find_or_create_partition(const bytes& key);
row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key);
partition* find_partition(const bytes& key);
row* find_row(const bytes& partition_key, const bytes& clustering_key);
schema_ptr _schema;
// partition key -> partition
std::map<bytes, partition, key_compare> partitions;
};
class keyspace {
public:
std::unordered_map<sstring, column_family> column_families;
static future<keyspace> populate(sstring datadir);
schema_ptr find_schema(sstring cf_name);
};
class database {
public:
std::unordered_map<sstring, keyspace> keyspaces;
static future<database> populate(sstring datadir);
keyspace* find_keyspace(sstring name);
};
#endif /* DATABASE_HH_ */
<commit_msg>schema: Add is_partition_key() tester<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef DATABASE_HH_
#define DATABASE_HH_
#include "core/sstring.hh"
#include "core/shared_ptr.hh"
#include "net/byteorder.hh"
#include "utils/UUID.hh"
#include "db_clock.hh"
#include "gc_clock.hh"
#include <functional>
#include <boost/any.hpp>
#include <cstdint>
#include <boost/variant.hpp>
#include <unordered_map>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <boost/functional/hash.hpp>
#include <experimental/optional>
#include <string.h>
#include "types.hh"
#include "tuple.hh"
#include "core/future.hh"
#include "cql3/column_specification.hh"
struct row;
struct paritition;
struct column_family;
struct row {
std::vector<bytes> cells;
};
struct partition {
explicit partition(column_family& cf);
row static_columns;
// row key within partition -> row
std::map<bytes, row, key_compare> rows;
};
using column_id = uint32_t;
class column_definition final {
private:
bytes _name;
public:
enum column_kind { PARTITION, CLUSTERING, REGULAR, STATIC };
column_definition(bytes name, data_type type, column_id id, column_kind kind);
data_type type;
column_id id; // unique within (kind, schema instance)
column_kind kind;
::shared_ptr<cql3::column_specification> column_specification;
bool is_static() const { return kind == column_kind::STATIC; }
bool is_partition_key() const { return kind == column_kind::PARTITION; }
const sstring& name_as_text() const;
const bytes& name() const;
};
struct thrift_schema {
shared_ptr<abstract_type> partition_key_type;
};
/*
* Keep this effectively immutable.
*/
class schema final {
private:
std::unordered_map<bytes, column_definition*> _columns_by_name;
std::map<bytes, column_definition*, serialized_compare> _regular_columns_by_name;
public:
struct column {
bytes name;
data_type type;
struct name_compare {
shared_ptr<abstract_type> type;
name_compare(shared_ptr<abstract_type> type) : type(type) {}
bool operator()(const column& cd1, const column& cd2) const {
return type->less(cd1.name, cd2.name);
}
};
};
private:
void build_columns(std::vector<column> columns, column_definition::column_kind kind, std::vector<column_definition>& dst);
::shared_ptr<cql3::column_specification> make_column_specification(column_definition& def);
public:
gc_clock::duration default_time_to_live = gc_clock::duration::zero();
const sstring ks_name;
const sstring cf_name;
std::vector<column_definition> partition_key;
std::vector<column_definition> clustering_key;
std::vector<column_definition> regular_columns; // sorted by name
shared_ptr<tuple_type<>> partition_key_type;
shared_ptr<tuple_type<>> clustering_key_type;
shared_ptr<tuple_prefix> clustering_key_prefix_type;
data_type regular_column_name_type;
thrift_schema thrift;
public:
schema(sstring ks_name, sstring cf_name,
std::vector<column> partition_key,
std::vector<column> clustering_key,
std::vector<column> regular_columns,
shared_ptr<abstract_type> regular_column_name_type);
bool is_dense() const {
return false;
}
bool is_counter() const {
return false;
}
column_definition* get_column_definition(const bytes& name);
auto regular_begin() {
return regular_columns.begin();
}
auto regular_end() {
return regular_columns.end();
}
auto regular_lower_bound(const bytes& name) {
// TODO: use regular_columns and a version of std::lower_bound() with heterogeneous comparator
auto i = _regular_columns_by_name.lower_bound(name);
if (i == _regular_columns_by_name.end()) {
return regular_end();
} else {
return regular_columns.begin() + i->second->id;
}
}
auto regular_upper_bound(const bytes& name) {
// TODO: use regular_columns and a version of std::upper_bound() with heterogeneous comparator
auto i = _regular_columns_by_name.upper_bound(name);
if (i == _regular_columns_by_name.end()) {
return regular_end();
} else {
return regular_columns.begin() + i->second->id;
}
}
column_id get_regular_columns_count() {
return regular_columns.size();
}
data_type column_name_type(column_definition& def) {
return def.kind == column_definition::REGULAR ? regular_column_name_type : utf8_type;
}
};
using schema_ptr = lw_shared_ptr<schema>;
struct column_family {
column_family(schema_ptr schema);
partition& find_or_create_partition(const bytes& key);
row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key);
partition* find_partition(const bytes& key);
row* find_row(const bytes& partition_key, const bytes& clustering_key);
schema_ptr _schema;
// partition key -> partition
std::map<bytes, partition, key_compare> partitions;
};
class keyspace {
public:
std::unordered_map<sstring, column_family> column_families;
static future<keyspace> populate(sstring datadir);
schema_ptr find_schema(sstring cf_name);
};
class database {
public:
std::unordered_map<sstring, keyspace> keyspaces;
static future<database> populate(sstring datadir);
keyspace* find_keyspace(sstring name);
};
#endif /* DATABASE_HH_ */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuobject/main.cc
#include <libport/cstdio>
#include <libport/unistd.h>
#include <libport/cerrno>
#include <iostream>
#include <list>
#include <sstream>
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <urbi/package-info.hh>
#include <urbi/uexternal.hh>
#include <urbi/umain.hh>
#include <urbi/umessage.hh>
#include <urbi/uobject.hh>
#include <urbi/urbi-root.hh>
#include <urbi/usyncclient.hh>
#include <libuobject/remote-ucontext-impl.hh>
using libport::program_name;
namespace urbi
{
static impl::RemoteUContextImpl* defaultContext;
UCallbackAction
debug(const UMessage& msg)
{
msg.client.printf("DEBUG: got a message: %s\n",
string_cast(msg).c_str());
return URBI_CONTINUE;
}
UCallbackAction
static
endProgram(const UMessage& msg)
{
msg.client.printf("ERROR: got a disconnection message: %s\n",
string_cast(msg).c_str());
exit(1);
return URBI_CONTINUE; //stupid gcc
}
static
void
usage()
{
std::cout <<
"usage:\n" << libport::program_name() << " [OPTION]...\n"
"\n"
"Options:\n"
" -b, --buffer SIZE input buffer size"
<< " [" << UAbstractClient::URBI_BUFLEN << "]\n"
" -h, --help display this message and exit\n"
" -H, --host ADDR server host name"
<< " [" << UClient::default_host() << "]\n"
" --server put remote in server mode\n"
" --no-sync-client Use UClient instead of USyncClient\n"
" -p, --port PORT tcp port URBI will listen to"
<< " [" << UAbstractClient::URBI_PORT << "]\n"
" -r, --port-file FILE file containing the port to listen to\n"
" -V, --version print version information and exit\n"
" -d, --disconnect exit program if disconnected(defaults)\n"
" -s, --stay-alive do not exit program if disconnected\n"
<< libport::exit (EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit (EX_OK);
}
typedef std::vector<std::string> files_type;
int
initialize(const std::string& host, int port, size_t buflen,
bool exitOnDisconnect, bool server, const files_type& files,
bool useSyncClient)
{
std::cerr << program_name()
<< ": " << urbi::package_info() << std::endl
<< program_name()
<< ": Remote Component Running on "
<< host << " " << port << std::endl;
if (useSyncClient)
{
USyncClient::options o;
o.server(server);
new USyncClient(host, port, buflen, o);
}
else
{
std::cerr << "#WARNING: the no-sync-client mode is dangerous.\n"
"Any attempt to use synchronous operation will crash your program."
<< std::endl;
UClient::options o;
o.server(server);
defaultClient = new UClient(host, port, buflen, o);
}
if (exitOnDisconnect)
{
if (!getDefaultClient() || getDefaultClient()->error())
std::cerr << "ERROR: failed to connect, exiting..." << std::endl
<< libport::exit(1);
getDefaultClient()->setClientErrorCallback(callback(&endProgram));
}
if (!getDefaultClient() || getDefaultClient()->error())
return 1;
defaultContext = new impl::RemoteUContextImpl(
(USyncClient*)dynamic_cast<UClient*>(getDefaultClient()));
#ifdef LIBURBIDEBUG
getDefaultClient()->setWildcardCallback(callback(&debug));
#else
getDefaultClient()->setErrorCallback(callback(&debug));
#endif
// Wait for client to be connected if in server mode.
while (getDefaultClient()
&& !getDefaultClient()->error()
&& !getDefaultClient()->init())
usleep(20000);
// Waiting for connectionID.
while (getDefaultClient()
&& getDefaultClient()->connectionID() == "")
usleep(5000);
defaultContext->init();
//baseURBIStarter::init();
// Send a ';' since UObject likely sent a serie of piped commands.
URBI_SEND_COMMAND("");
// Load initialization files.
foreach (const std::string& file, files)
getDefaultClient()->sendFile(file);
return 0;
}
namespace
{
static
void
argument_with_option(const char* longopt,
char shortopt,
const std::string& val)
{
std::cerr
<< program_name()
<< ": warning: arguments without options are deprecated"
<< std::endl
<< "use `-" << shortopt << ' ' << val << '\''
<< " or `--" << longopt << ' ' << val << "' instead"
<< std::endl
<< "Try `" << program_name() << " --help' for more information."
<< std::endl;
}
}
URBI_SDK_API int
main(const libport::cli_args_type& args, UrbiRoot&, bool block, bool)
{
std::string host = UClient::default_host();
bool exitOnDisconnect = true;
int port = UAbstractClient::URBI_PORT;
bool server = false;
bool useSyncClient = true;
size_t buflen = UAbstractClient::URBI_BUFLEN;
// Files to load
files_type files;
// The number of the next (non-option) argument.
unsigned argp = 1;
for (unsigned i = 1; i < args.size(); ++i)
{
const std::string& arg = args[i];
if (arg == "--buffer" || arg == "-b")
buflen = libport::convert_argument<size_t>(args, i++);
else if (arg == "--disconnect" || arg == "-d")
exitOnDisconnect = true;
else if (arg == "--file" || arg == "-f")
files.push_back(libport::convert_argument<const char*>(args, i++));
else if (arg == "--stay-alive" || arg == "-s")
exitOnDisconnect = false;
else if (arg == "--help" || arg == "-h")
usage();
else if (arg == "--host" || arg == "-H")
host = libport::convert_argument<std::string>(args, i++);
else if (arg == "--no-sync-client")
useSyncClient = false;
else if (arg == "--port" || arg == "-p")
port = libport::convert_argument<unsigned>(args, i++);
else if (arg == "--port-file" || arg == "-r")
port =
(libport::file_contents_get<int>
(libport::convert_argument<const char*>(args, i++)));
else if (arg == "--server")
server = true;
// FIXME: Remove -v some day.
else if (arg == "--version" || arg == "-V" || arg == "-v")
version();
else if (arg[0] == '-')
libport::invalid_option(arg);
else
// A genuine argument.
switch (argp++)
{
case 1:
argument_with_option("host", 'H', args[i]);
host = args[i];
break;
case 2:
argument_with_option("port", 'p', args[i]);
port = libport::convert_argument<unsigned> ("port", args[i].c_str());
break;
default:
std::cerr << "unexpected argument: " << arg << std::endl
<< libport::exit(EX_USAGE);
}
}
initialize(host, port, buflen, exitOnDisconnect, server, files,
useSyncClient);
if (block)
while (true)
usleep(30000000);
return 0;
}
}
<commit_msg>libuobject: use setDefaultClient instead of writing directly to defaultClient.<commit_after>/*
* Copyright (C) 2008-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuobject/main.cc
#include <libport/cstdio>
#include <libport/unistd.h>
#include <libport/cerrno>
#include <iostream>
#include <list>
#include <sstream>
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <urbi/package-info.hh>
#include <urbi/uexternal.hh>
#include <urbi/umain.hh>
#include <urbi/umessage.hh>
#include <urbi/uobject.hh>
#include <urbi/urbi-root.hh>
#include <urbi/usyncclient.hh>
#include <libuobject/remote-ucontext-impl.hh>
using libport::program_name;
namespace urbi
{
static impl::RemoteUContextImpl* defaultContext;
UCallbackAction
debug(const UMessage& msg)
{
msg.client.printf("DEBUG: got a message: %s\n",
string_cast(msg).c_str());
return URBI_CONTINUE;
}
UCallbackAction
static
endProgram(const UMessage& msg)
{
msg.client.printf("ERROR: got a disconnection message: %s\n",
string_cast(msg).c_str());
exit(1);
return URBI_CONTINUE; //stupid gcc
}
static
void
usage()
{
std::cout <<
"usage:\n" << libport::program_name() << " [OPTION]...\n"
"\n"
"Options:\n"
" -b, --buffer SIZE input buffer size"
<< " [" << UAbstractClient::URBI_BUFLEN << "]\n"
" -h, --help display this message and exit\n"
" -H, --host ADDR server host name"
<< " [" << UClient::default_host() << "]\n"
" --server put remote in server mode\n"
" --no-sync-client Use UClient instead of USyncClient\n"
" -p, --port PORT tcp port URBI will listen to"
<< " [" << UAbstractClient::URBI_PORT << "]\n"
" -r, --port-file FILE file containing the port to listen to\n"
" -V, --version print version information and exit\n"
" -d, --disconnect exit program if disconnected(defaults)\n"
" -s, --stay-alive do not exit program if disconnected\n"
<< libport::exit (EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit (EX_OK);
}
typedef std::vector<std::string> files_type;
int
initialize(const std::string& host, int port, size_t buflen,
bool exitOnDisconnect, bool server, const files_type& files,
bool useSyncClient)
{
std::cerr << program_name()
<< ": " << urbi::package_info() << std::endl
<< program_name()
<< ": Remote Component Running on "
<< host << " " << port << std::endl;
if (useSyncClient)
{
USyncClient::options o;
o.server(server);
new USyncClient(host, port, buflen, o);
}
else
{
std::cerr << "#WARNING: the no-sync-client mode is dangerous.\n"
"Any attempt to use synchronous operation will crash your program."
<< std::endl;
UClient::options o;
o.server(server);
setDefaultClient(new UClient(host, port, buflen, o));
}
if (exitOnDisconnect)
{
if (!getDefaultClient() || getDefaultClient()->error())
std::cerr << "ERROR: failed to connect, exiting..." << std::endl
<< libport::exit(1);
getDefaultClient()->setClientErrorCallback(callback(&endProgram));
}
if (!getDefaultClient() || getDefaultClient()->error())
return 1;
defaultContext = new impl::RemoteUContextImpl(
(USyncClient*)dynamic_cast<UClient*>(getDefaultClient()));
#ifdef LIBURBIDEBUG
getDefaultClient()->setWildcardCallback(callback(&debug));
#else
getDefaultClient()->setErrorCallback(callback(&debug));
#endif
// Wait for client to be connected if in server mode.
while (getDefaultClient()
&& !getDefaultClient()->error()
&& !getDefaultClient()->init())
usleep(20000);
// Waiting for connectionID.
while (getDefaultClient()
&& getDefaultClient()->connectionID() == "")
usleep(5000);
defaultContext->init();
//baseURBIStarter::init();
// Send a ';' since UObject likely sent a serie of piped commands.
URBI_SEND_COMMAND("");
// Load initialization files.
foreach (const std::string& file, files)
getDefaultClient()->sendFile(file);
return 0;
}
namespace
{
static
void
argument_with_option(const char* longopt,
char shortopt,
const std::string& val)
{
std::cerr
<< program_name()
<< ": warning: arguments without options are deprecated"
<< std::endl
<< "use `-" << shortopt << ' ' << val << '\''
<< " or `--" << longopt << ' ' << val << "' instead"
<< std::endl
<< "Try `" << program_name() << " --help' for more information."
<< std::endl;
}
}
URBI_SDK_API int
main(const libport::cli_args_type& args, UrbiRoot&, bool block, bool)
{
std::string host = UClient::default_host();
bool exitOnDisconnect = true;
int port = UAbstractClient::URBI_PORT;
bool server = false;
bool useSyncClient = true;
size_t buflen = UAbstractClient::URBI_BUFLEN;
// Files to load
files_type files;
// The number of the next (non-option) argument.
unsigned argp = 1;
for (unsigned i = 1; i < args.size(); ++i)
{
const std::string& arg = args[i];
if (arg == "--buffer" || arg == "-b")
buflen = libport::convert_argument<size_t>(args, i++);
else if (arg == "--disconnect" || arg == "-d")
exitOnDisconnect = true;
else if (arg == "--file" || arg == "-f")
files.push_back(libport::convert_argument<const char*>(args, i++));
else if (arg == "--stay-alive" || arg == "-s")
exitOnDisconnect = false;
else if (arg == "--help" || arg == "-h")
usage();
else if (arg == "--host" || arg == "-H")
host = libport::convert_argument<std::string>(args, i++);
else if (arg == "--no-sync-client")
useSyncClient = false;
else if (arg == "--port" || arg == "-p")
port = libport::convert_argument<unsigned>(args, i++);
else if (arg == "--port-file" || arg == "-r")
port =
(libport::file_contents_get<int>
(libport::convert_argument<const char*>(args, i++)));
else if (arg == "--server")
server = true;
// FIXME: Remove -v some day.
else if (arg == "--version" || arg == "-V" || arg == "-v")
version();
else if (arg[0] == '-')
libport::invalid_option(arg);
else
// A genuine argument.
switch (argp++)
{
case 1:
argument_with_option("host", 'H', args[i]);
host = args[i];
break;
case 2:
argument_with_option("port", 'p', args[i]);
port = libport::convert_argument<unsigned> ("port", args[i].c_str());
break;
default:
std::cerr << "unexpected argument: " << arg << std::endl
<< libport::exit(EX_USAGE);
}
}
initialize(host, port, buflen, exitOnDisconnect, server, files,
useSyncClient);
if (block)
while (true)
usleep(30000000);
return 0;
}
}
<|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/ui/views/extensions/extension_dialog.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/extensions/extension_dialog_observer.h"
#include "chrome/browser/ui/views/window.h" // CreateViewsWindow
#include "chrome/common/chrome_notification_types.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "googleurl/src/gurl.h"
#include "views/widget/widget.h"
ExtensionDialog::ExtensionDialog(Browser* browser, ExtensionHost* host,
int width, int height,
ExtensionDialogObserver* observer)
: extension_host_(host),
observer_(observer) {
AddRef(); // Balanced in DeleteDelegate();
gfx::NativeWindow parent = browser->window()->GetNativeHandle();
window_ = browser::CreateViewsWindow(
parent, gfx::Rect(), this /* views::WidgetDelegate */);
// Center the window over the browser.
gfx::Point center = browser->window()->GetBounds().CenterPoint();
int x = center.x() - width / 2;
int y = center.y() - height / 2;
window_->SetBounds(gfx::Rect(x, y, width, height));
host->view()->SetContainer(this /* ExtensionView::Container */);
// Listen for the containing view calling window.close();
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
Source<Profile>(host->profile()));
window_->Show();
}
ExtensionDialog::~ExtensionDialog() {
}
// static
ExtensionDialog* ExtensionDialog::Show(
const GURL& url,
Browser* browser,
int width,
int height,
ExtensionDialogObserver* observer) {
CHECK(browser);
ExtensionProcessManager* manager =
browser->profile()->GetExtensionProcessManager();
DCHECK(manager);
if (!manager)
return NULL;
ExtensionHost* host = manager->CreateDialogHost(url, browser);
DCHECK(host);
return new ExtensionDialog(browser, host, width, height, observer);
}
void ExtensionDialog::ObserverDestroyed() {
observer_ = NULL;
}
void ExtensionDialog::Close() {
if (!window_)
return;
if (observer_)
observer_->ExtensionDialogIsClosing(this);
window_->Close();
window_ = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// views::WidgetDelegate overrides.
bool ExtensionDialog::CanResize() const {
return false;
}
bool ExtensionDialog::IsModal() const {
return true;
}
bool ExtensionDialog::ShouldShowWindowTitle() const {
return false;
}
void ExtensionDialog::DeleteDelegate() {
// The window has finished closing. Allow ourself to be deleted.
Release();
}
views::Widget* ExtensionDialog::GetWidget() {
return extension_host_->view()->GetWidget();
}
const views::Widget* ExtensionDialog::GetWidget() const {
return extension_host_->view()->GetWidget();
}
views::View* ExtensionDialog::GetContentsView() {
return extension_host_->view();
}
/////////////////////////////////////////////////////////////////////////////
// ExtensionView::Container overrides.
void ExtensionDialog::OnExtensionMouseMove(ExtensionView* view) {
}
void ExtensionDialog::OnExtensionMouseLeave(ExtensionView* view) {
}
void ExtensionDialog::OnExtensionPreferredSizeChanged(ExtensionView* view) {
}
/////////////////////////////////////////////////////////////////////////////
// NotificationObserver overrides.
void ExtensionDialog::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
// If we aren't the host of the popup, then disregard the notification.
if (Details<ExtensionHost>(host()) != details)
return;
Close();
break;
default:
NOTREACHED() << L"Received unexpected notification";
break;
}
}
<commit_msg>CrOS - Fix escape key not closing file picker<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/ui/views/extensions/extension_dialog.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/extensions/extension_dialog_observer.h"
#include "chrome/browser/ui/views/window.h" // CreateViewsWindow
#include "chrome/common/chrome_notification_types.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "googleurl/src/gurl.h"
#include "views/widget/widget.h"
ExtensionDialog::ExtensionDialog(Browser* browser, ExtensionHost* host,
int width, int height,
ExtensionDialogObserver* observer)
: extension_host_(host),
observer_(observer) {
AddRef(); // Balanced in DeleteDelegate();
gfx::NativeWindow parent = browser->window()->GetNativeHandle();
window_ = browser::CreateViewsWindow(
parent, gfx::Rect(), this /* views::WidgetDelegate */);
// Center the window over the browser.
gfx::Point center = browser->window()->GetBounds().CenterPoint();
int x = center.x() - width / 2;
int y = center.y() - height / 2;
window_->SetBounds(gfx::Rect(x, y, width, height));
host->view()->SetContainer(this /* ExtensionView::Container */);
// Listen for the containing view calling window.close();
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
Source<Profile>(host->profile()));
window_->Show();
window_->Activate();
// Ensure the DOM JavaScript can respond immediately to keyboard shortcuts.
host->render_view_host()->view()->Focus();
}
ExtensionDialog::~ExtensionDialog() {
}
// static
ExtensionDialog* ExtensionDialog::Show(
const GURL& url,
Browser* browser,
int width,
int height,
ExtensionDialogObserver* observer) {
CHECK(browser);
ExtensionProcessManager* manager =
browser->profile()->GetExtensionProcessManager();
DCHECK(manager);
if (!manager)
return NULL;
ExtensionHost* host = manager->CreateDialogHost(url, browser);
DCHECK(host);
return new ExtensionDialog(browser, host, width, height, observer);
}
void ExtensionDialog::ObserverDestroyed() {
observer_ = NULL;
}
void ExtensionDialog::Close() {
if (!window_)
return;
if (observer_)
observer_->ExtensionDialogIsClosing(this);
window_->Close();
window_ = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// views::WidgetDelegate overrides.
bool ExtensionDialog::CanResize() const {
return false;
}
bool ExtensionDialog::IsModal() const {
return true;
}
bool ExtensionDialog::ShouldShowWindowTitle() const {
return false;
}
void ExtensionDialog::DeleteDelegate() {
// The window has finished closing. Allow ourself to be deleted.
Release();
}
views::Widget* ExtensionDialog::GetWidget() {
return extension_host_->view()->GetWidget();
}
const views::Widget* ExtensionDialog::GetWidget() const {
return extension_host_->view()->GetWidget();
}
views::View* ExtensionDialog::GetContentsView() {
return extension_host_->view();
}
/////////////////////////////////////////////////////////////////////////////
// ExtensionView::Container overrides.
void ExtensionDialog::OnExtensionMouseMove(ExtensionView* view) {
}
void ExtensionDialog::OnExtensionMouseLeave(ExtensionView* view) {
}
void ExtensionDialog::OnExtensionPreferredSizeChanged(ExtensionView* view) {
}
/////////////////////////////////////////////////////////////////////////////
// NotificationObserver overrides.
void ExtensionDialog::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
// If we aren't the host of the popup, then disregard the notification.
if (Details<ExtensionHost>(host()) != details)
return;
Close();
break;
default:
NOTREACHED() << L"Received unexpected notification";
break;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vtablefactory.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2008-02-27 10:02:58 $
*
* 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_bridges.hxx"
#if defined OS2
#define INCL_DOS
#define INCL_DOSMISC
#endif
#include "bridges/cpp_uno/shared/vtablefactory.hxx"
#include "guardedarray.hxx"
#include "bridges/cpp_uno/shared/vtables.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "rtl/alloc.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "typelib/typedescription.hxx"
#include <hash_map>
#include <new>
#include <vector>
#if defined SAL_UNX
#include <unistd.h>
#include <sys/mman.h>
#elif defined SAL_W32
#define WIN32_LEAN_AND_MEAN
#ifdef _MSC_VER
#pragma warning(push,1) // disable warnings within system headers
#endif
#include <windows.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#elif defined SAL_OS2
#define INCL_DOS
#define INCL_DOSMISC
#include <os2.h>
#else
#error Unsupported platform
#endif
using bridges::cpp_uno::shared::VtableFactory;
namespace {
extern "C" void * SAL_CALL allocExec(rtl_arena_type *, sal_Size * size) {
sal_Size pagesize;
#if defined SAL_UNX
#if defined FREEBSD || defined NETBSD
pagesize = getpagesize();
#else
pagesize = sysconf(_SC_PAGESIZE);
#endif
#elif defined SAL_W32
SYSTEM_INFO info;
GetSystemInfo(&info);
pagesize = info.dwPageSize;
#elif defined(SAL_OS2)
ULONG ulPageSize;
DosQuerySysInfo(QSV_PAGE_SIZE, QSV_PAGE_SIZE, &ulPageSize, sizeof(ULONG));
pagesize = (sal_Size)ulPageSize;
#else
#error Unsupported platform
#endif
sal_Size n = (*size + (pagesize - 1)) & ~(pagesize - 1);
void * p;
#if defined SAL_UNX
p = mmap(
0, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1,
0);
if (p == MAP_FAILED) {
p = 0;
}
else if (mprotect (static_cast<char*>(p), n, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
{
munmap (static_cast<char*>(p), n);
p = 0;
}
#elif defined SAL_W32
p = VirtualAlloc(0, n, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
#elif defined(SAL_OS2)
p = 0;
DosAllocMem( &p, n, PAG_COMMIT | PAG_READ | PAG_WRITE | OBJ_ANY);
#endif
if (p != 0) {
*size = n;
}
return p;
}
extern "C" void SAL_CALL freeExec(
rtl_arena_type *, void * address, sal_Size size)
{
#if defined SAL_UNX
munmap(static_cast< char * >(address), size);
#elif defined SAL_W32
(void) size; // unused
VirtualFree(address, 0, MEM_RELEASE);
#elif defined(SAL_OS2)
(void) DosFreeMem( address);
#endif
}
}
class VtableFactory::GuardedBlocks: public std::vector< Block > {
public:
GuardedBlocks(VtableFactory const & factory):
m_factory(factory), m_guarded(true) {}
~GuardedBlocks();
void unguard() { m_guarded = false; }
private:
GuardedBlocks(GuardedBlocks &); // not implemented
void operator =(GuardedBlocks); // not implemented
VtableFactory const & m_factory;
bool m_guarded;
};
VtableFactory::GuardedBlocks::~GuardedBlocks() {
if (m_guarded) {
for (iterator i(begin()); i != end(); ++i) {
m_factory.freeBlock(*i);
}
}
}
class VtableFactory::BaseOffset {
public:
BaseOffset(typelib_InterfaceTypeDescription * type) { calculate(type, 0); }
sal_Int32 getFunctionOffset(rtl::OUString const & name) const
{ return m_map.find(name)->second; }
private:
sal_Int32 calculate(
typelib_InterfaceTypeDescription * type, sal_Int32 offset);
typedef std::hash_map< rtl::OUString, sal_Int32, rtl::OUStringHash > Map;
Map m_map;
};
sal_Int32 VtableFactory::BaseOffset::calculate(
typelib_InterfaceTypeDescription * type, sal_Int32 offset)
{
rtl::OUString name(type->aBase.pTypeName);
if (m_map.find(name) == m_map.end()) {
for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) {
offset = calculate(type->ppBaseTypes[i], offset);
}
m_map.insert(Map::value_type(name, offset));
typelib_typedescription_complete(
reinterpret_cast< typelib_TypeDescription ** >(&type));
offset += bridges::cpp_uno::shared::getLocalFunctions(type);
}
return offset;
}
VtableFactory::VtableFactory(): m_arena(
rtl_arena_create(
"bridges::cpp_uno::shared::VtableFactory",
sizeof (void *), // to satisfy alignment requirements
0, reinterpret_cast< rtl_arena_type * >(-1), allocExec, freeExec, 0))
{
if (m_arena == 0) {
throw std::bad_alloc();
}
}
VtableFactory::~VtableFactory() {
{
osl::MutexGuard guard(m_mutex);
for (Map::iterator i(m_map.begin()); i != m_map.end(); ++i) {
for (sal_Int32 j = 0; j < i->second.count; ++j) {
freeBlock(i->second.blocks[j]);
}
delete[] i->second.blocks;
}
}
rtl_arena_destroy(m_arena);
}
VtableFactory::Vtables VtableFactory::getVtables(
typelib_InterfaceTypeDescription * type)
{
rtl::OUString name(type->aBase.pTypeName);
osl::MutexGuard guard(m_mutex);
Map::iterator i(m_map.find(name));
if (i == m_map.end()) {
GuardedBlocks blocks(*this);
createVtables(blocks, BaseOffset(type), type, true);
Vtables vtables;
OSL_ASSERT(blocks.size() <= SAL_MAX_INT32);
vtables.count = static_cast< sal_Int32 >(blocks.size());
bridges::cpp_uno::shared::GuardedArray< Block > guardedBlocks(
new Block[vtables.count]);
vtables.blocks = guardedBlocks.get();
for (sal_Int32 j = 0; j < vtables.count; ++j) {
vtables.blocks[j] = blocks[j];
}
i = m_map.insert(Map::value_type(name, vtables)).first;
guardedBlocks.release();
blocks.unguard();
}
return i->second;
}
void VtableFactory::freeBlock(Block const & block) const {
rtl_arena_free(m_arena, block.start, block.size);
}
void VtableFactory::createVtables(
GuardedBlocks & blocks, BaseOffset const & baseOffset,
typelib_InterfaceTypeDescription * type, bool includePrimary) const
{
if (includePrimary) {
sal_Int32 slotCount
= bridges::cpp_uno::shared::getPrimaryFunctions(type);
Block block;
block.size = getBlockSize(slotCount);
block.start = rtl_arena_alloc(m_arena, &block.size);
if (block.start == 0) {
throw std::bad_alloc();
}
try {
Slot * slots = initializeBlock(block.start, slotCount);
unsigned char * codeBegin =
reinterpret_cast< unsigned char * >(slots);
unsigned char * code = codeBegin;
sal_Int32 vtableOffset = blocks.size() * sizeof (Slot *);
for (typelib_InterfaceTypeDescription const * type2 = type;
type2 != 0; type2 = type2->pBaseTypeDescription)
{
code = addLocalFunctions(
&slots, code, type2,
baseOffset.getFunctionOffset(type2->aBase.pTypeName),
bridges::cpp_uno::shared::getLocalFunctions(type2),
vtableOffset);
}
flushCode(codeBegin, code);
blocks.push_back(block);
} catch (...) {
freeBlock(block);
throw;
}
}
for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) {
createVtables(blocks, baseOffset, type->ppBaseTypes[i], i != 0);
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.10.12); FILE MERGED 2008/03/28 16:30:41 rt 1.10.12.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: vtablefactory.cxx,v $
* $Revision: 1.11 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_bridges.hxx"
#if defined OS2
#define INCL_DOS
#define INCL_DOSMISC
#endif
#include "bridges/cpp_uno/shared/vtablefactory.hxx"
#include "guardedarray.hxx"
#include "bridges/cpp_uno/shared/vtables.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "rtl/alloc.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "typelib/typedescription.hxx"
#include <hash_map>
#include <new>
#include <vector>
#if defined SAL_UNX
#include <unistd.h>
#include <sys/mman.h>
#elif defined SAL_W32
#define WIN32_LEAN_AND_MEAN
#ifdef _MSC_VER
#pragma warning(push,1) // disable warnings within system headers
#endif
#include <windows.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#elif defined SAL_OS2
#define INCL_DOS
#define INCL_DOSMISC
#include <os2.h>
#else
#error Unsupported platform
#endif
using bridges::cpp_uno::shared::VtableFactory;
namespace {
extern "C" void * SAL_CALL allocExec(rtl_arena_type *, sal_Size * size) {
sal_Size pagesize;
#if defined SAL_UNX
#if defined FREEBSD || defined NETBSD
pagesize = getpagesize();
#else
pagesize = sysconf(_SC_PAGESIZE);
#endif
#elif defined SAL_W32
SYSTEM_INFO info;
GetSystemInfo(&info);
pagesize = info.dwPageSize;
#elif defined(SAL_OS2)
ULONG ulPageSize;
DosQuerySysInfo(QSV_PAGE_SIZE, QSV_PAGE_SIZE, &ulPageSize, sizeof(ULONG));
pagesize = (sal_Size)ulPageSize;
#else
#error Unsupported platform
#endif
sal_Size n = (*size + (pagesize - 1)) & ~(pagesize - 1);
void * p;
#if defined SAL_UNX
p = mmap(
0, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1,
0);
if (p == MAP_FAILED) {
p = 0;
}
else if (mprotect (static_cast<char*>(p), n, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
{
munmap (static_cast<char*>(p), n);
p = 0;
}
#elif defined SAL_W32
p = VirtualAlloc(0, n, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
#elif defined(SAL_OS2)
p = 0;
DosAllocMem( &p, n, PAG_COMMIT | PAG_READ | PAG_WRITE | OBJ_ANY);
#endif
if (p != 0) {
*size = n;
}
return p;
}
extern "C" void SAL_CALL freeExec(
rtl_arena_type *, void * address, sal_Size size)
{
#if defined SAL_UNX
munmap(static_cast< char * >(address), size);
#elif defined SAL_W32
(void) size; // unused
VirtualFree(address, 0, MEM_RELEASE);
#elif defined(SAL_OS2)
(void) DosFreeMem( address);
#endif
}
}
class VtableFactory::GuardedBlocks: public std::vector< Block > {
public:
GuardedBlocks(VtableFactory const & factory):
m_factory(factory), m_guarded(true) {}
~GuardedBlocks();
void unguard() { m_guarded = false; }
private:
GuardedBlocks(GuardedBlocks &); // not implemented
void operator =(GuardedBlocks); // not implemented
VtableFactory const & m_factory;
bool m_guarded;
};
VtableFactory::GuardedBlocks::~GuardedBlocks() {
if (m_guarded) {
for (iterator i(begin()); i != end(); ++i) {
m_factory.freeBlock(*i);
}
}
}
class VtableFactory::BaseOffset {
public:
BaseOffset(typelib_InterfaceTypeDescription * type) { calculate(type, 0); }
sal_Int32 getFunctionOffset(rtl::OUString const & name) const
{ return m_map.find(name)->second; }
private:
sal_Int32 calculate(
typelib_InterfaceTypeDescription * type, sal_Int32 offset);
typedef std::hash_map< rtl::OUString, sal_Int32, rtl::OUStringHash > Map;
Map m_map;
};
sal_Int32 VtableFactory::BaseOffset::calculate(
typelib_InterfaceTypeDescription * type, sal_Int32 offset)
{
rtl::OUString name(type->aBase.pTypeName);
if (m_map.find(name) == m_map.end()) {
for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) {
offset = calculate(type->ppBaseTypes[i], offset);
}
m_map.insert(Map::value_type(name, offset));
typelib_typedescription_complete(
reinterpret_cast< typelib_TypeDescription ** >(&type));
offset += bridges::cpp_uno::shared::getLocalFunctions(type);
}
return offset;
}
VtableFactory::VtableFactory(): m_arena(
rtl_arena_create(
"bridges::cpp_uno::shared::VtableFactory",
sizeof (void *), // to satisfy alignment requirements
0, reinterpret_cast< rtl_arena_type * >(-1), allocExec, freeExec, 0))
{
if (m_arena == 0) {
throw std::bad_alloc();
}
}
VtableFactory::~VtableFactory() {
{
osl::MutexGuard guard(m_mutex);
for (Map::iterator i(m_map.begin()); i != m_map.end(); ++i) {
for (sal_Int32 j = 0; j < i->second.count; ++j) {
freeBlock(i->second.blocks[j]);
}
delete[] i->second.blocks;
}
}
rtl_arena_destroy(m_arena);
}
VtableFactory::Vtables VtableFactory::getVtables(
typelib_InterfaceTypeDescription * type)
{
rtl::OUString name(type->aBase.pTypeName);
osl::MutexGuard guard(m_mutex);
Map::iterator i(m_map.find(name));
if (i == m_map.end()) {
GuardedBlocks blocks(*this);
createVtables(blocks, BaseOffset(type), type, true);
Vtables vtables;
OSL_ASSERT(blocks.size() <= SAL_MAX_INT32);
vtables.count = static_cast< sal_Int32 >(blocks.size());
bridges::cpp_uno::shared::GuardedArray< Block > guardedBlocks(
new Block[vtables.count]);
vtables.blocks = guardedBlocks.get();
for (sal_Int32 j = 0; j < vtables.count; ++j) {
vtables.blocks[j] = blocks[j];
}
i = m_map.insert(Map::value_type(name, vtables)).first;
guardedBlocks.release();
blocks.unguard();
}
return i->second;
}
void VtableFactory::freeBlock(Block const & block) const {
rtl_arena_free(m_arena, block.start, block.size);
}
void VtableFactory::createVtables(
GuardedBlocks & blocks, BaseOffset const & baseOffset,
typelib_InterfaceTypeDescription * type, bool includePrimary) const
{
if (includePrimary) {
sal_Int32 slotCount
= bridges::cpp_uno::shared::getPrimaryFunctions(type);
Block block;
block.size = getBlockSize(slotCount);
block.start = rtl_arena_alloc(m_arena, &block.size);
if (block.start == 0) {
throw std::bad_alloc();
}
try {
Slot * slots = initializeBlock(block.start, slotCount);
unsigned char * codeBegin =
reinterpret_cast< unsigned char * >(slots);
unsigned char * code = codeBegin;
sal_Int32 vtableOffset = blocks.size() * sizeof (Slot *);
for (typelib_InterfaceTypeDescription const * type2 = type;
type2 != 0; type2 = type2->pBaseTypeDescription)
{
code = addLocalFunctions(
&slots, code, type2,
baseOffset.getFunctionOffset(type2->aBase.pTypeName),
bridges::cpp_uno::shared::getLocalFunctions(type2),
vtableOffset);
}
flushCode(codeBegin, code);
blocks.push_back(block);
} catch (...) {
freeBlock(block);
throw;
}
}
for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) {
createVtables(blocks, baseOffset, type->ppBaseTypes[i], i != 0);
}
}
<|endoftext|> |
<commit_before>//Evan Sprecher & Ommaimah Hussein
#include "bits.h"
//-----------------------------------------------------------
// Constructor
//-----------------------------------------------------------
BitTwiddle::BitTwiddle(pagetable *table, std::ofstream *output)
{
AC=0;
PC=128; //PC starts at 0200o
link=false;
SR=0;
sumInstr = 0;
sumClk = 0;
AND_Count=0; //number of AND instruction
TAD_Count=0; //number of TAD instruction
ISZ_Count=0; //number of ISZ instruction
DCA_Count=0; //number of DCA instruction
JMS_Count=0; //number of JMS instruction
JMP_Count=0; //number of JMP instruction
IO_Count=0; //number of IO instruction
uInstr_Count=0; //number of micro instruction
memory = table;
outputTraceFile = output;
}
//-----------------------------------------------------------
// Destructor
//-----------------------------------------------------------
BitTwiddle::~BitTwiddle(){
}
//-----------------------------------------------------------
// Function for Logical AND
//-----------------------------------------------------------
void BitTwiddle::PDP_AND(bool addr_bit,bool mem_page,int offset){
++AND_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
AC=AC & MEM_LOAD(EAddr);
return;
}
//-----------------------------------------------------------
// Function for Two's Complement Add
//-----------------------------------------------------------
void BitTwiddle::PDP_TAD(bool addr_bit,bool mem_page,int offset){
++TAD_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
int adda = AC;
int addb = MEM_LOAD(EAddr);
int addc = adda + addb;
AC = addc & ((1 << pdp8::REGISTERSIZE) - 1);//carry and overflow are removed
if ((1 << pdp8::REGISTERSIZE) == (addc&(1 << pdp8::REGISTERSIZE))) link = !link;//compliment link if carry out
return;
}
//-----------------------------------------------------------
// Function for Increment and Skip on Zero
//-----------------------------------------------------------
void BitTwiddle::PDP_ISZ(bool addr_bit,bool mem_page,int offset){
++ISZ_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
int C_EAddr = MEM_LOAD(EAddr);
increment_PC();
int adda=AC;
int addc=adda + 1;
AC = addc & ((1 << pdp8::REGISTERSIZE) - 1);//carry and overflow are removed
if (!((C_EAddr + 1) & ((1 << pdp8::REGISTERSIZE) - 1))){
increment_PC(); //skip if zero
}
return;
}
//-----------------------------------------------------------
// Function for Deposit and Clear Accumulator
//-----------------------------------------------------------
void BitTwiddle::PDP_DCA(bool addr_bit,bool mem_page,int offset)
{
++DCA_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
// take AC and place into content of EAddr
MEM_STORE(EAddr,AC);
// store 0 into AC (clear AC)
AC = 0;
return;
}
//-----------------------------------------------------------
// Function for Jump to Subroutine
//-----------------------------------------------------------
void BitTwiddle::PDP_JMS(bool addr_bit,bool mem_page,int offset)
{
++JMS_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
// take contents of PC and place into content of EAddr
MEM_STORE(EAddr,PC);
// take EAddr, add 1, and store into PC
PC = (EAddr + 1) & ((1 << pdp8::REGISTERSIZE) - 1);//carry and overflow are removed
return;
}
//-----------------------------------------------------------
// Function for Jump
//-----------------------------------------------------------
void BitTwiddle::PDP_JMP(bool addr_bit,bool mem_page,int offset)
{
++JMP_Count;
++sumInstr;
sumClk = sumClk + 1; //takes 1 clk cycle
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
// take EAddr and store into PC
PC= EAddr;
return;
}
//-----------------------------------------------------------
// Forbidden IO functionality
//-----------------------------------------------------------
void BitTwiddle::PDP_IO(int device_num,int opcode){
++IO_Count;
++sumInstr;
increment_PC();
std::cout << "Warning: I/O instruction encountered.\n";
return;
}
//-----------------------------------------------------------
// Function for Micro Instructions
//-----------------------------------------------------------
int BitTwiddle::PDP_uintructions(bool bit3, bool bit4, int offset){
// TODO: add increment_PC() to specific uInst
++uInstr_Count;
++sumInstr;
sumClk = sumClk + 1; //takes 1 clk cycles
increment_PC();
bool bit5 = read_bit_x(offset, 5);
bool bit6 = read_bit_x(offset, 6);
bool bit7 = read_bit_x(offset, 7);
bool bit8 = read_bit_x(offset, 8);
bool bit9 = read_bit_x(offset, 9);
bool bit10 = read_bit_x(offset,10);
bool bit11 = read_bit_x(offset,11);
//*************GROUP 1*******************
if(!bit3){
if(bit4){ //clear accumulator
AC = 0;
}else if(bit5){ //clear link
link = 0;
}else if(bit6){ //complement accumulator
AC = ~AC;
}else if(bit7){ //complement link
link = ~link;
}else if(bit11){ //increment accumulator
++AC;
}else if(bit8){ //rotate accumulator, link right
char direction = 'R';
rotateBits(AC, link, direction);
if(bit10){ //rotate accumulator, link right twice (rotate once more)
rotateBits(AC, link, direction);
}
}else if(bit9){ //rotate accumulator, link left
char direction = 'L';
rotateBits(AC, link, direction);
if(bit10){ //rotate accumulator, link left twice (rotate once more)
rotateBits(AC, link, direction);
}
}else{ //no operation
return 0;
}
//*************GROUP 2*******************
}else if(!bit11){ //uinstructions
if(bit8){ //AND subgroup and SKP
bool cond5=1; //combinations will skip when all conditions are true.
bool cond6=1; //so we do not skip if any one condition is false.
bool cond7=1; //the idea is that these get flagged false when a bit is asserted and it is conditionally false
// cond 5 6 and 7 are then ANDed together at the end and if true, skip.
if(bit5){ //SPA
cond5=!read_bit_x(AC, 0);//is the 0th bit of AC a 0?
}
if(bit6){ //SNA
cond6=(AC!=0);//is AC not 0?
}
if(bit7){ //SZL
cond7=!link;//is link 0?
}
if(cond5 && cond6 && cond7){
increment_PC();
return 0; //the skip for SPA,SNA,SZL, and SKP
}
}else{ //OR subgroup
if(bit5 && read_bit_x(AC, 0)){//SMA
increment_PC();
return 0; //is the 0th bit of AC a 1?
}else if(bit6 && (AC==0)){ //SZA
increment_PC();
return 0; //is AC 0?
}else if(bit7 && link){ //SNL
increment_PC();
return 0; //is link 1?
}
}
//CLA OSR and HLT
if(bit4){ //CLA
AC=0;
}
if(bit9){ //OSR
AC=SR|AC;
}
if(bit10){ //HLT
return -1;
}
//*************GROUP 3*******************
}else{
std::cout << "Warning: Group 3 uInstruction encountered.\n";
}
return 0;
}
// display data from BitTwiddle class
void BitTwiddle::display()
{
//print out brief summary
std::cout << "-----------PDP-8 ISA Simulation Summary---------------\n\n";
std::cout << "Total number of Instructions executed: " << sumInstr << "\n";
std::cout << "Total number of clock cycles consumed: " << sumClk << "\n\n";
std::cout << "**Number of times each instruction type was executed**\n";
std::cout << "|-----------------------------------------------------\n";
std::cout << "| Mnemonic | Number of times executed \n";
std::cout << "|-----------------------------------------------------\n";
std::cout << "| AND | " << AND_Count << "\n";
std::cout << "| TAD | " << TAD_Count << "\n";
std::cout << "| ISZ | " << ISZ_Count << "\n";
std::cout << "| DCA | " << DCA_Count << "\n";
std::cout << "| JMS | " << JMS_Count << "\n";
std::cout << "| JMP | " << JMP_Count << "\n";
std::cout << "| <IO> | " << IO_Count << "\n";
std::cout << "| uInstructions | " << uInstr_Count << "\n";
std::cout << "------------------------------------------------------\n";
}
//-----------------------------------------------------------
// Function for rotating bits (used in uInstruction Group 1)
//-----------------------------------------------------------
void BitTwiddle::rotateBits(int accumulator, int link, char dir){
int lsb = 0; //value of lsb from accumulator
int msb = 0; //value of msb from accumulator
int templink = 0; //temporarily holds value of link
char direction = ' '; // temporarily holds value of dir
#ifndef rotatebit_DEBUG
std::cout << "Current accumulator value: " << (bitset<12>) accumulator << "\n";
std::cout << "Current link bit: " << link << "\n";
std::cout << "Current direction: " << dir << "\n\n";
#endif
if(dir == 'R'){ //ROTATE RIGHT
lsb = accumulator & 1; //save lsb of accumulator
#ifndef rotatebit_DEBUG
std::cout << "Value of lsb is:" << lsb << "\n\n";
#endif
accumulator = accumulator >> 1; //shift accumulator to right by 1
#ifndef rotatebit_DEBUG
std::cout << "Value of shifted accumulator: " << (bitset<12>)accumulator << "\n";
#endif
templink = link; //save value of link before we change it
link = lsb; //lsb will be shifted into the link
#ifndef rotatebit_DEBUG
std::cout << "New value of link: " << link << "\n";
#endif
templink = templink << 11; //put old value of link into accumulator MSB
accumulator = (accumulator | templink); //put MSB into the accumulator
#ifndef rotatebit_DEBUG
std::cout << "New value of accumulator: " << (bitset<12>)accumulator << "\n";
#endif
}else if(direction == 'L'){ //ROTATE LEFT
msb = (accumulator>>11) & 1; //save msb of accumulator
#ifndef rotatebit_DEBUG
std::cout << "Value of msb is:" << msb << "\n\n";
#endif
accumulator = accumulator << 1; //shift accumulator to left by 1
#ifndef rotatebit_DEBUG
std::cout << "Value of shifted accumulator: " << (bitset<12>)accumulator << "\n";
#endif
templink = link; //save value of link before we change it
#ifndef rotatebit_DEBUG
std::cout << "Value of templink: " << templink << "\n";
#endif
link = msb; //lsb will be shifted into the link
#ifndef rotatebit_DEBUG
std::cout << "New value of link: " << link << "\n";
#endif
accumulator = (accumulator | templink); //put MSB into the accumulator as MSB
#ifndef rotatebit_DEBUG
std::cout << "New value of accumulator: " << (bitset<12>)accumulator << "\n";
#endif
}else{
std::cout << "Error in reading direction of rotation.\n";
}
return;
}
//____________________________________________________________
// PRIVATE FUNCTIONS!
//____________________________________________________________
//-----------------------------------------------------------
// Function for finding the effective address
//-----------------------------------------------------------
int BitTwiddle::find_EAddr(bool addr_bit,bool mem_page,int offset){
if(!addr_bit){
if(!mem_page){//bit3=0 bit4=0
if(offset>=8 && offset<=15){ //autoindexing offset=010o-017o
sumClk += 2; //two additional clk cycle for autoindexing
int temp = MEM_LOAD(offset)+1; //load C(AutoIndex_Register)+1
temp=temp & ((1<<pdp8::REGISTERSIZE)-1); //scrub it to 12 bits
MEM_STORE(offset , temp); //store it into C(AutoIndex_Register)
return temp; //C(AutoIndex_Register) is our EAddr
}else{
return offset; //00000 cat Offset is our EAddr (zero page addressing)
}
}else{ //bit3=0 bit4=1 current page addresssing
return ((PC & (((1<<5)-1)<<7)) + offset);
}
}else{
if(!mem_page){//bit3=1 bit4=0 zero page indirect addressing
++sumClk; //one additional clk cycle for indirect addressing
return MEM_LOAD(offset);
}else{ //bit3=1 bit4=1 current page indirect addressing
++sumClk; //one additional clk cycle for indirect addressing
return MEM_LOAD((PC & (((1<<5)-1)<<7)) + offset);
}
}
}
//-----------------------------------------------------------
// Function for incrementing the PC
//----------------------------------------------------------
void BitTwiddle::increment_PC(){
PC = (PC + 1) & ((1 << pdp8::REGISTERSIZE) - 1);
return;
}
//-----------------------------------------------------------
// Function for reading a specific bit location
//----------------------------------------------------------
bool BitTwiddle::read_bit_x(int input,int x){
return 1 & (input >> (pdp8::REGISTERSIZE - (x + 1)));
}
//-----------------------------------------------------------
// Function for loading from memory
//----------------------------------------------------------
int BitTwiddle::MEM_LOAD(int address){
//*********IMPLEMENTING TRACE FILE****************
int type = 0; //1 - data read (load)
(*outputTraceFile) << type << " " << std::oct << address << std::endl;
//************************************************
return memory->load(address);
}
//-----------------------------------------------------------
// Function for storing to memory
//----------------------------------------------------------
void BitTwiddle::MEM_STORE(int address,int value){
//*********IMPLEMENTING TRACE FILE****************
int type = 1; //1 - data write (store)
(*outputTraceFile) << type << " " << std::oct << address << std::endl;
//************************************************
memory->store(address, value);
return;
}
<commit_msg>minor change<commit_after>//Evan Sprecher & Ommaimah Hussein
#include "bits.h"
//-----------------------------------------------------------
// Constructor
//-----------------------------------------------------------
BitTwiddle::BitTwiddle(pagetable *table, std::ofstream *output)
{
AC=0;
PC=128; //PC starts at 0200o
link=false;
SR=0;
sumInstr = 0;
sumClk = 0;
AND_Count=0; //number of AND instruction
TAD_Count=0; //number of TAD instruction
ISZ_Count=0; //number of ISZ instruction
DCA_Count=0; //number of DCA instruction
JMS_Count=0; //number of JMS instruction
JMP_Count=0; //number of JMP instruction
IO_Count=0; //number of IO instruction
uInstr_Count=0; //number of micro instruction
memory = table;
outputTraceFile = output;
}
//-----------------------------------------------------------
// Destructor
//-----------------------------------------------------------
BitTwiddle::~BitTwiddle(){
}
//-----------------------------------------------------------
// Function for Logical AND
//-----------------------------------------------------------
void BitTwiddle::PDP_AND(bool addr_bit,bool mem_page,int offset){
++AND_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
AC=AC & MEM_LOAD(EAddr);
return;
}
//-----------------------------------------------------------
// Function for Two's Complement Add
//-----------------------------------------------------------
void BitTwiddle::PDP_TAD(bool addr_bit,bool mem_page,int offset){
++TAD_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
int adda = AC;
int addb = MEM_LOAD(EAddr);
int addc = adda + addb;
AC = addc & ((1 << pdp8::REGISTERSIZE) - 1);//carry and overflow are removed
if ((1 << pdp8::REGISTERSIZE) == (addc&(1 << pdp8::REGISTERSIZE))) link = !link;//compliment link if carry out
return;
}
//-----------------------------------------------------------
// Function for Increment and Skip on Zero
//-----------------------------------------------------------
void BitTwiddle::PDP_ISZ(bool addr_bit,bool mem_page,int offset){
++ISZ_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
int C_EAddr = MEM_LOAD(EAddr);
increment_PC();
int adda=AC;
int addc=adda + 1;
AC = addc & ((1 << pdp8::REGISTERSIZE) - 1);//carry and overflow are removed
if (!((C_EAddr + 1) & ((1 << pdp8::REGISTERSIZE) - 1))){
increment_PC(); //skip if zero
}
return;
}
//-----------------------------------------------------------
// Function for Deposit and Clear Accumulator
//-----------------------------------------------------------
void BitTwiddle::PDP_DCA(bool addr_bit,bool mem_page,int offset)
{
++DCA_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
// take AC and place into content of EAddr
MEM_STORE(EAddr,AC);
// store 0 into AC (clear AC)
AC = 0;
return;
}
//-----------------------------------------------------------
// Function for Jump to Subroutine
//-----------------------------------------------------------
void BitTwiddle::PDP_JMS(bool addr_bit,bool mem_page,int offset)
{
++JMS_Count;
++sumInstr;
sumClk = sumClk + 2; //takes 2 clk cycles
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
// take contents of PC and place into content of EAddr
MEM_STORE(EAddr,PC);
// take EAddr, add 1, and store into PC
PC = (EAddr + 1) & ((1 << pdp8::REGISTERSIZE) - 1);//carry and overflow are removed
return;
}
//-----------------------------------------------------------
// Function for Jump
//-----------------------------------------------------------
void BitTwiddle::PDP_JMP(bool addr_bit,bool mem_page,int offset)
{
++JMP_Count;
++sumInstr;
sumClk = sumClk + 1; //takes 1 clk cycle
int EAddr = find_EAddr(addr_bit,mem_page,offset);
increment_PC();
// take EAddr and store into PC
PC= EAddr;
return;
}
//-----------------------------------------------------------
// Forbidden IO functionality
//-----------------------------------------------------------
void BitTwiddle::PDP_IO(int device_num,int opcode){
++IO_Count;
++sumInstr;
increment_PC();
std::cout << "Warning: I/O instruction encountered.\n";
return;
}
//-----------------------------------------------------------
// Function for Micro Instructions
//-----------------------------------------------------------
int BitTwiddle::PDP_uintructions(bool bit3, bool bit4, int offset){
// TODO: add increment_PC() to specific uInst
++uInstr_Count;
++sumInstr;
sumClk = sumClk + 1; //takes 1 clk cycles
increment_PC();
bool bit5 = read_bit_x(offset, 5);
bool bit6 = read_bit_x(offset, 6);
bool bit7 = read_bit_x(offset, 7);
bool bit8 = read_bit_x(offset, 8);
bool bit9 = read_bit_x(offset, 9);
bool bit10 = read_bit_x(offset,10);
bool bit11 = read_bit_x(offset,11);
//*************GROUP 1*******************
if(!bit3){
if(bit4){ //clear accumulator
AC = 0;
}else if(bit5){ //clear link
link = 0;
}else if(bit6){ //complement accumulator
AC = ~AC;
}else if(bit7){ //complement link
link = ~link;
}else if(bit11){ //increment accumulator
++AC;
}else if(bit8){ //rotate accumulator, link right
char direction = 'R';
rotateBits(AC, link, direction);
if(bit10){ //rotate accumulator, link right twice (rotate once more)
rotateBits(AC, link, direction);
}
}else if(bit9){ //rotate accumulator, link left
char direction = 'L';
rotateBits(AC, link, direction);
if(bit10){ //rotate accumulator, link left twice (rotate once more)
rotateBits(AC, link, direction);
}
}else{ //no operation
return 0;
}
//*************GROUP 2*******************
}else if(!bit11){ //uinstructions
if(bit8){ //AND subgroup and SKP
bool cond5=1; //combinations will skip when all conditions are true.
bool cond6=1; //so we do not skip if any one condition is false.
bool cond7=1; //the idea is that these get flagged false when a bit is asserted and it is conditionally false
// cond 5 6 and 7 are then ANDed together at the end and if true, skip.
if(bit5){ //SPA
cond5=!read_bit_x(AC, 0);//is the 0th bit of AC a 0?
}
if(bit6){ //SNA
cond6=(AC!=0);//is AC not 0?
}
if(bit7){ //SZL
cond7=!link;//is link 0?
}
if(cond5 && cond6 && cond7){
increment_PC();
return 0; //the skip for SPA,SNA,SZL, and SKP
}
}else{ //OR subgroup
if(bit5 && read_bit_x(AC, 0)){//SMA
increment_PC();
return 0; //is the 0th bit of AC a 1?
}else if(bit6 && (AC==0)){ //SZA
increment_PC();
return 0; //is AC 0?
}else if(bit7 && link){ //SNL
increment_PC();
return 0; //is link 1?
}
}
//CLA OSR and HLT
if(bit4){ //CLA
AC=0;
}
if(bit9){ //OSR
AC=SR|AC;
}
if(bit10){ //HLT
return -1;
}
//*************GROUP 3*******************
}else{
std::cout << "Warning: Group 3 uInstruction encountered.\n";
}
return 0;
}
// display data from BitTwiddle class
void BitTwiddle::display()
{
//print out brief summary
std::cout << "\n-----------PDP-8 ISA Simulation Summary---------------\n\n";
std::cout << "Total number of Instructions executed: " << sumInstr << "\n";
std::cout << "Total number of clock cycles consumed: " << sumClk << "\n\n";
std::cout << "**Number of times each instruction type was executed**\n";
std::cout << "|-----------------------------------------------------\n";
std::cout << "| Mnemonic | Number of times executed \n";
std::cout << "|-----------------------------------------------------\n";
std::cout << "| AND | " << AND_Count << "\n";
std::cout << "| TAD | " << TAD_Count << "\n";
std::cout << "| ISZ | " << ISZ_Count << "\n";
std::cout << "| DCA | " << DCA_Count << "\n";
std::cout << "| JMS | " << JMS_Count << "\n";
std::cout << "| JMP | " << JMP_Count << "\n";
std::cout << "| <IO> | " << IO_Count << "\n";
std::cout << "| uInstructions | " << uInstr_Count << "\n";
std::cout << "------------------------------------------------------\n";
}
//-----------------------------------------------------------
// Function for rotating bits (used in uInstruction Group 1)
//-----------------------------------------------------------
void BitTwiddle::rotateBits(int accumulator, int link, char dir){
int lsb = 0; //value of lsb from accumulator
int msb = 0; //value of msb from accumulator
int templink = 0; //temporarily holds value of link
char direction = ' '; // temporarily holds value of dir
#ifndef rotatebit_DEBUG
std::cout << "Current accumulator value: " << (bitset<12>) accumulator << "\n";
std::cout << "Current link bit: " << link << "\n";
std::cout << "Current direction: " << dir << "\n\n";
#endif
if(dir == 'R'){ //ROTATE RIGHT
lsb = accumulator & 1; //save lsb of accumulator
#ifndef rotatebit_DEBUG
std::cout << "Value of lsb is:" << lsb << "\n\n";
#endif
accumulator = accumulator >> 1; //shift accumulator to right by 1
#ifndef rotatebit_DEBUG
std::cout << "Value of shifted accumulator: " << (bitset<12>)accumulator << "\n";
#endif
templink = link; //save value of link before we change it
link = lsb; //lsb will be shifted into the link
#ifndef rotatebit_DEBUG
std::cout << "New value of link: " << link << "\n";
#endif
templink = templink << 11; //put old value of link into accumulator MSB
accumulator = (accumulator | templink); //put MSB into the accumulator
#ifndef rotatebit_DEBUG
std::cout << "New value of accumulator: " << (bitset<12>)accumulator << "\n";
#endif
}else if(direction == 'L'){ //ROTATE LEFT
msb = (accumulator>>11) & 1; //save msb of accumulator
#ifndef rotatebit_DEBUG
std::cout << "Value of msb is:" << msb << "\n\n";
#endif
accumulator = accumulator << 1; //shift accumulator to left by 1
#ifndef rotatebit_DEBUG
std::cout << "Value of shifted accumulator: " << (bitset<12>)accumulator << "\n";
#endif
templink = link; //save value of link before we change it
#ifndef rotatebit_DEBUG
std::cout << "Value of templink: " << templink << "\n";
#endif
link = msb; //lsb will be shifted into the link
#ifndef rotatebit_DEBUG
std::cout << "New value of link: " << link << "\n";
#endif
accumulator = (accumulator | templink); //put MSB into the accumulator as MSB
#ifndef rotatebit_DEBUG
std::cout << "New value of accumulator: " << (bitset<12>)accumulator << "\n";
#endif
}else{
std::cout << "Error in reading direction of rotation.\n";
}
return;
}
//____________________________________________________________
// PRIVATE FUNCTIONS!
//____________________________________________________________
//-----------------------------------------------------------
// Function for finding the effective address
//-----------------------------------------------------------
int BitTwiddle::find_EAddr(bool addr_bit,bool mem_page,int offset){
if(!addr_bit){
if(!mem_page){//bit3=0 bit4=0
if(offset>=8 && offset<=15){ //autoindexing offset=010o-017o
sumClk += 2; //two additional clk cycle for autoindexing
int temp = MEM_LOAD(offset)+1; //load C(AutoIndex_Register)+1
temp=temp & ((1<<pdp8::REGISTERSIZE)-1); //scrub it to 12 bits
MEM_STORE(offset , temp); //store it into C(AutoIndex_Register)
return temp; //C(AutoIndex_Register) is our EAddr
}else{
return offset; //00000 cat Offset is our EAddr (zero page addressing)
}
}else{ //bit3=0 bit4=1 current page addresssing
return ((PC & (((1<<5)-1)<<7)) + offset);
}
}else{
if(!mem_page){//bit3=1 bit4=0 zero page indirect addressing
++sumClk; //one additional clk cycle for indirect addressing
return MEM_LOAD(offset);
}else{ //bit3=1 bit4=1 current page indirect addressing
++sumClk; //one additional clk cycle for indirect addressing
return MEM_LOAD((PC & (((1<<5)-1)<<7)) + offset);
}
}
}
//-----------------------------------------------------------
// Function for incrementing the PC
//----------------------------------------------------------
void BitTwiddle::increment_PC(){
PC = (PC + 1) & ((1 << pdp8::REGISTERSIZE) - 1);
return;
}
//-----------------------------------------------------------
// Function for reading a specific bit location
//----------------------------------------------------------
bool BitTwiddle::read_bit_x(int input,int x){
return 1 & (input >> (pdp8::REGISTERSIZE - (x + 1)));
}
//-----------------------------------------------------------
// Function for loading from memory
//----------------------------------------------------------
int BitTwiddle::MEM_LOAD(int address){
//*********IMPLEMENTING TRACE FILE****************
int type = 0; //1 - data read (load)
(*outputTraceFile) << type << " " << std::oct << address << std::endl;
//************************************************
return memory->load(address);
}
//-----------------------------------------------------------
// Function for storing to memory
//----------------------------------------------------------
void BitTwiddle::MEM_STORE(int address,int value){
//*********IMPLEMENTING TRACE FILE****************
int type = 1; //1 - data write (store)
(*outputTraceFile) << type << " " << std::oct << address << std::endl;
//************************************************
memory->store(address, value);
return;
}
<|endoftext|> |
<commit_before>// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sessions/session_types.h"
#include <cstddef>
#include <string>
#include "base/basictypes.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
//#include "chrome/browser/search/search.h"
#include "components/sessions/serialized_navigation_entry_test_helper.h"
#include "sync/protocol/session_specifics.pb.h"
#include "sync/util/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
namespace {
// Create a typical SessionTab protocol buffer and set an existing
// SessionTab from it. The data from the protocol buffer should
// clobber the existing data.
TEST(SessionTab, FromSyncData) {
sync_pb::SessionTab sync_data;
sync_data.set_tab_id(5);
sync_data.set_window_id(10);
sync_data.set_tab_visual_index(13);
sync_data.set_current_navigation_index(3);
sync_data.set_pinned(true);
sync_data.set_extension_app_id("app_id");
for (int i = 0; i < 5; ++i) {
sync_pb::TabNavigation* navigation = sync_data.add_navigation();
navigation->set_virtual_url("http://foo/" + base::IntToString(i));
navigation->set_referrer("referrer");
navigation->set_title("title");
navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED);
}
sync_data.add_variation_id(3312238);
sync_data.add_variation_id(3312242);
sessions::SessionTab tab;
tab.window_id.set_id(100);
tab.tab_id.set_id(100);
tab.tab_visual_index = 100;
tab.current_navigation_index = 1000;
tab.pinned = false;
tab.extension_app_id = "fake";
tab.user_agent_override = "fake";
tab.timestamp = base::Time::FromInternalValue(100);
tab.navigations.resize(100);
tab.session_storage_persistent_id = "fake";
tab.SetFromSyncData(sync_data, base::Time::FromInternalValue(5u));
EXPECT_EQ(10, tab.window_id.id());
EXPECT_EQ(5, tab.tab_id.id());
EXPECT_EQ(13, tab.tab_visual_index);
EXPECT_EQ(3, tab.current_navigation_index);
EXPECT_TRUE(tab.pinned);
EXPECT_EQ("app_id", tab.extension_app_id);
EXPECT_TRUE(tab.user_agent_override.empty());
EXPECT_EQ(5u, tab.timestamp.ToInternalValue());
ASSERT_EQ(5u, tab.navigations.size());
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(i, tab.navigations[i].index());
EXPECT_EQ(GURL("referrer"), tab.navigations[i].referrer_url());
EXPECT_EQ(base::ASCIIToUTF16("title"),tab.navigations[i].title());
EXPECT_EQ(ui::PAGE_TRANSITION_TYPED,
tab.navigations[i].transition_type());
EXPECT_EQ(GURL("http://foo/" + base::IntToString(i)),
tab.navigations[i].virtual_url());
}
ASSERT_EQ(2u, tab.variation_ids.size());
EXPECT_EQ(3312238, tab.variation_ids[0]);
EXPECT_EQ(3312242, tab.variation_ids[1]);
EXPECT_TRUE(tab.session_storage_persistent_id.empty());
}
TEST(SessionTab, ToSyncData) {
sessions::SessionTab tab;
tab.window_id.set_id(10);
tab.tab_id.set_id(5);
tab.tab_visual_index = 13;
tab.current_navigation_index = 3;
tab.pinned = true;
tab.extension_app_id = "app_id";
tab.user_agent_override = "fake";
tab.timestamp = base::Time::FromInternalValue(100);
for (int i = 0; i < 5; ++i) {
tab.navigations.push_back(
sessions::SerializedNavigationEntryTestHelper::CreateNavigation(
"http://foo/" + base::IntToString(i), "title"));
}
tab.session_storage_persistent_id = "fake";
tab.variation_ids.push_back(3312238);
tab.variation_ids.push_back(3312242);
const sync_pb::SessionTab& sync_data = tab.ToSyncData();
EXPECT_EQ(5, sync_data.tab_id());
EXPECT_EQ(10, sync_data.window_id());
EXPECT_EQ(13, sync_data.tab_visual_index());
EXPECT_EQ(3, sync_data.current_navigation_index());
EXPECT_TRUE(sync_data.pinned());
EXPECT_EQ("app_id", sync_data.extension_app_id());
ASSERT_EQ(5, sync_data.navigation_size());
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(tab.navigations[i].virtual_url().spec(),
sync_data.navigation(i).virtual_url());
EXPECT_EQ(base::UTF16ToUTF8(tab.navigations[i].title()),
sync_data.navigation(i).title());
}
EXPECT_FALSE(sync_data.has_favicon());
EXPECT_FALSE(sync_data.has_favicon_type());
EXPECT_FALSE(sync_data.has_favicon_source());
ASSERT_EQ(2, sync_data.variation_id_size());
EXPECT_EQ(3312238u, sync_data.variation_id(0));
EXPECT_EQ(3312242u, sync_data.variation_id(1));
}
} // namespace
<commit_msg>Remove commented out #include in components/sessions/session_types_unittest.cc<commit_after>// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sessions/session_types.h"
#include <cstddef>
#include <string>
#include "base/basictypes.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "components/sessions/serialized_navigation_entry_test_helper.h"
#include "sync/protocol/session_specifics.pb.h"
#include "sync/util/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
namespace {
// Create a typical SessionTab protocol buffer and set an existing
// SessionTab from it. The data from the protocol buffer should
// clobber the existing data.
TEST(SessionTab, FromSyncData) {
sync_pb::SessionTab sync_data;
sync_data.set_tab_id(5);
sync_data.set_window_id(10);
sync_data.set_tab_visual_index(13);
sync_data.set_current_navigation_index(3);
sync_data.set_pinned(true);
sync_data.set_extension_app_id("app_id");
for (int i = 0; i < 5; ++i) {
sync_pb::TabNavigation* navigation = sync_data.add_navigation();
navigation->set_virtual_url("http://foo/" + base::IntToString(i));
navigation->set_referrer("referrer");
navigation->set_title("title");
navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED);
}
sync_data.add_variation_id(3312238);
sync_data.add_variation_id(3312242);
sessions::SessionTab tab;
tab.window_id.set_id(100);
tab.tab_id.set_id(100);
tab.tab_visual_index = 100;
tab.current_navigation_index = 1000;
tab.pinned = false;
tab.extension_app_id = "fake";
tab.user_agent_override = "fake";
tab.timestamp = base::Time::FromInternalValue(100);
tab.navigations.resize(100);
tab.session_storage_persistent_id = "fake";
tab.SetFromSyncData(sync_data, base::Time::FromInternalValue(5u));
EXPECT_EQ(10, tab.window_id.id());
EXPECT_EQ(5, tab.tab_id.id());
EXPECT_EQ(13, tab.tab_visual_index);
EXPECT_EQ(3, tab.current_navigation_index);
EXPECT_TRUE(tab.pinned);
EXPECT_EQ("app_id", tab.extension_app_id);
EXPECT_TRUE(tab.user_agent_override.empty());
EXPECT_EQ(5u, tab.timestamp.ToInternalValue());
ASSERT_EQ(5u, tab.navigations.size());
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(i, tab.navigations[i].index());
EXPECT_EQ(GURL("referrer"), tab.navigations[i].referrer_url());
EXPECT_EQ(base::ASCIIToUTF16("title"),tab.navigations[i].title());
EXPECT_EQ(ui::PAGE_TRANSITION_TYPED,
tab.navigations[i].transition_type());
EXPECT_EQ(GURL("http://foo/" + base::IntToString(i)),
tab.navigations[i].virtual_url());
}
ASSERT_EQ(2u, tab.variation_ids.size());
EXPECT_EQ(3312238, tab.variation_ids[0]);
EXPECT_EQ(3312242, tab.variation_ids[1]);
EXPECT_TRUE(tab.session_storage_persistent_id.empty());
}
TEST(SessionTab, ToSyncData) {
sessions::SessionTab tab;
tab.window_id.set_id(10);
tab.tab_id.set_id(5);
tab.tab_visual_index = 13;
tab.current_navigation_index = 3;
tab.pinned = true;
tab.extension_app_id = "app_id";
tab.user_agent_override = "fake";
tab.timestamp = base::Time::FromInternalValue(100);
for (int i = 0; i < 5; ++i) {
tab.navigations.push_back(
sessions::SerializedNavigationEntryTestHelper::CreateNavigation(
"http://foo/" + base::IntToString(i), "title"));
}
tab.session_storage_persistent_id = "fake";
tab.variation_ids.push_back(3312238);
tab.variation_ids.push_back(3312242);
const sync_pb::SessionTab& sync_data = tab.ToSyncData();
EXPECT_EQ(5, sync_data.tab_id());
EXPECT_EQ(10, sync_data.window_id());
EXPECT_EQ(13, sync_data.tab_visual_index());
EXPECT_EQ(3, sync_data.current_navigation_index());
EXPECT_TRUE(sync_data.pinned());
EXPECT_EQ("app_id", sync_data.extension_app_id());
ASSERT_EQ(5, sync_data.navigation_size());
for (int i = 0; i < 5; ++i) {
EXPECT_EQ(tab.navigations[i].virtual_url().spec(),
sync_data.navigation(i).virtual_url());
EXPECT_EQ(base::UTF16ToUTF8(tab.navigations[i].title()),
sync_data.navigation(i).title());
}
EXPECT_FALSE(sync_data.has_favicon());
EXPECT_FALSE(sync_data.has_favicon_type());
EXPECT_FALSE(sync_data.has_favicon_source());
ASSERT_EQ(2, sync_data.variation_id_size());
EXPECT_EQ(3312238u, sync_data.variation_id(0));
EXPECT_EQ(3312242u, sync_data.variation_id(1));
}
} // namespace
<|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 "base/command_line.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/debugger/devtools_client_host.h"
#include "content/browser/debugger/devtools_manager.h"
#include "content/browser/debugger/devtools_window.h"
#include "content/browser/debugger/worker_devtools_manager_io.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/worker_host/worker_process_host.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
const char kChunkedTestPage[] = "chunked";
const char kSlowTestPage[] =
"chunked?waitBeforeHeaders=100&waitBetweenChunks=100&chunksNumber=2";
const char kSharedWorkerTestPage[] =
"files/workers/workers_ui_shared_worker.html";
void RunTestFuntion(DevToolsWindow* window, const char* test_name) {
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window->GetRenderViewHost(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window->GetRenderViewHost(),
L"",
UTF8ToWide(base::StringPrintf("uiTests.runTest('%s')",
test_name)),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
}
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest()
: window_(NULL),
inspected_rvh_(NULL) {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
RunTestFuntion(window_, test_name.c_str());
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
window_ = DevToolsWindow::OpenDevToolsWindow(inspected_rvh_);
RenderViewHost* client_rvh = window_->GetRenderViewHost();
TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_LOADED:
case chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Used to block until a navigation completes.
class LoadStopObserver : public NotificationObserver {
public:
explicit LoadStopObserver(const NotificationSource& source) : done_(false) {
registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, source);
ui_test_utils::RunMessageLoop();
}
private:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == content::NOTIFICATION_LOAD_STOP) {
if (done_)
return;
done_ = true;
MessageLoopForUI::current()->Quit();
}
}
NotificationRegistrar registrar_;
bool done_;
DISALLOW_COPY_AND_ASSIGN(LoadStopObserver);
};
class WorkerDevToolsSanityTest : public InProcessBrowserTest {
public:
WorkerDevToolsSanityTest() : window_(NULL) {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const char* test_name, const char* test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
OpenDevToolsWindowForFirstSharedWorker();
RunTestFuntion(window_, test_name);
CloseDevToolsWindow();
}
static void OpenDevToolsWindowForFirstSharedWorkerOnIOThread(int attempt) {
BrowserChildProcessHost::Iterator iter(ChildProcessInfo::WORKER_PROCESS);
bool found = false;
for (; !iter.Done(); ++iter) {
WorkerProcessHost* worker = static_cast<WorkerProcessHost*>(*iter);
const WorkerProcessHost::Instances& instances = worker->instances();
for (WorkerProcessHost::Instances::const_iterator i = instances.begin();
i != instances.end(); ++i) {
if (!i->shared())
continue;
WorkerDevToolsManagerIO::GetInstance()->OpenDevToolsForWorker(
worker->id(), i->worker_route_id());
found = true;
break;
}
}
if (found) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
new MessageLoop::QuitTask);
} else if(attempt < 30) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
NewRunnableFunction(
&OpenDevToolsWindowForFirstSharedWorkerOnIOThread, attempt + 1),
100);
} else {
FAIL() << "Shared worker not found.";
}
}
void OpenDevToolsWindowForFirstSharedWorker() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableFunction(
&OpenDevToolsWindowForFirstSharedWorkerOnIOThread, 1));
ui_test_utils::RunMessageLoop();
window_ = DevToolsWindow::GetDevToolsWindowForTest();
ASSERT_TRUE(window_ != NULL);
RenderViewHost* client_rvh = window_->GetRenderViewHost();
TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
if (client_contents->is_loading()) {
LoadStopObserver(
Source<NavigationController>(&client_contents->controller()));
}
}
void CloseDevToolsWindow() {
Browser* browser = window_->browser();
browser->CloseAllTabs();
BrowserClosedObserver close_observer(browser);
}
DevToolsWindow* window_;
};
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
content::GetContentClient()->browser()->ClearInspectorSettings(
GetInspectedTab()->render_view_host());
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
// Flaky - http://crbug.com/69719.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests network timing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkTiming) {
RunTest("testNetworkTiming", kSlowTestPage);
}
// Tests network size.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSize) {
RunTest("testNetworkSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSyncSize) {
RunTest("testNetworkSyncSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkRawHeadersText) {
RunTest("testNetworkRawHeadersText", kChunkedTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPageWithNoJavaScript) {
OpenDevToolsWindow("about:blank");
std::string result;
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window_->GetRenderViewHost(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
ASSERT_EQ("function", result) << "DevTools front-end is broken.";
CloseDevToolsWindow();
}
IN_PROC_BROWSER_TEST_F(WorkerDevToolsSanityTest, InspectSharedWorker) {
RunTest("testSharedWorker", kSharedWorkerTestPage);
}
} // namespace
<commit_msg>The test fails due to a console messages arriving sometimes before the console evaluation result. See http://chromesshgw.corp.google.com/i/chromium/builders/Linux%20Builder%20%28ChromiumOS%29/builds/9891/steps/interactive_ui_tests/logs/InspectSharedWorker<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 "base/command_line.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/debugger/devtools_client_host.h"
#include "content/browser/debugger/devtools_manager.h"
#include "content/browser/debugger/devtools_window.h"
#include "content/browser/debugger/worker_devtools_manager_io.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/worker_host/worker_process_host.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
const char kChunkedTestPage[] = "chunked";
const char kSlowTestPage[] =
"chunked?waitBeforeHeaders=100&waitBetweenChunks=100&chunksNumber=2";
const char kSharedWorkerTestPage[] =
"files/workers/workers_ui_shared_worker.html";
void RunTestFuntion(DevToolsWindow* window, const char* test_name) {
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window->GetRenderViewHost(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window->GetRenderViewHost(),
L"",
UTF8ToWide(base::StringPrintf("uiTests.runTest('%s')",
test_name)),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
}
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest()
: window_(NULL),
inspected_rvh_(NULL) {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
RunTestFuntion(window_, test_name.c_str());
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
window_ = DevToolsWindow::OpenDevToolsWindow(inspected_rvh_);
RenderViewHost* client_rvh = window_->GetRenderViewHost();
TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_LOADED:
case chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Used to block until a navigation completes.
class LoadStopObserver : public NotificationObserver {
public:
explicit LoadStopObserver(const NotificationSource& source) : done_(false) {
registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, source);
ui_test_utils::RunMessageLoop();
}
private:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == content::NOTIFICATION_LOAD_STOP) {
if (done_)
return;
done_ = true;
MessageLoopForUI::current()->Quit();
}
}
NotificationRegistrar registrar_;
bool done_;
DISALLOW_COPY_AND_ASSIGN(LoadStopObserver);
};
class WorkerDevToolsSanityTest : public InProcessBrowserTest {
public:
WorkerDevToolsSanityTest() : window_(NULL) {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const char* test_name, const char* test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
OpenDevToolsWindowForFirstSharedWorker();
RunTestFuntion(window_, test_name);
CloseDevToolsWindow();
}
static void OpenDevToolsWindowForFirstSharedWorkerOnIOThread(int attempt) {
BrowserChildProcessHost::Iterator iter(ChildProcessInfo::WORKER_PROCESS);
bool found = false;
for (; !iter.Done(); ++iter) {
WorkerProcessHost* worker = static_cast<WorkerProcessHost*>(*iter);
const WorkerProcessHost::Instances& instances = worker->instances();
for (WorkerProcessHost::Instances::const_iterator i = instances.begin();
i != instances.end(); ++i) {
if (!i->shared())
continue;
WorkerDevToolsManagerIO::GetInstance()->OpenDevToolsForWorker(
worker->id(), i->worker_route_id());
found = true;
break;
}
}
if (found) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
new MessageLoop::QuitTask);
} else if(attempt < 30) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
NewRunnableFunction(
&OpenDevToolsWindowForFirstSharedWorkerOnIOThread, attempt + 1),
100);
} else {
FAIL() << "Shared worker not found.";
}
}
void OpenDevToolsWindowForFirstSharedWorker() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableFunction(
&OpenDevToolsWindowForFirstSharedWorkerOnIOThread, 1));
ui_test_utils::RunMessageLoop();
window_ = DevToolsWindow::GetDevToolsWindowForTest();
ASSERT_TRUE(window_ != NULL);
RenderViewHost* client_rvh = window_->GetRenderViewHost();
TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
if (client_contents->is_loading()) {
LoadStopObserver(
Source<NavigationController>(&client_contents->controller()));
}
}
void CloseDevToolsWindow() {
Browser* browser = window_->browser();
browser->CloseAllTabs();
BrowserClosedObserver close_observer(browser);
}
DevToolsWindow* window_;
};
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
content::GetContentClient()->browser()->ClearInspectorSettings(
GetInspectedTab()->render_view_host());
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
// Flaky - http://crbug.com/69719.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests network timing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkTiming) {
RunTest("testNetworkTiming", kSlowTestPage);
}
// Tests network size.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSize) {
RunTest("testNetworkSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSyncSize) {
RunTest("testNetworkSyncSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkRawHeadersText) {
RunTest("testNetworkRawHeadersText", kChunkedTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPageWithNoJavaScript) {
OpenDevToolsWindow("about:blank");
std::string result;
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
window_->GetRenderViewHost(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
ASSERT_EQ("function", result) << "DevTools front-end is broken.";
CloseDevToolsWindow();
}
// http://crbug.com/89845
IN_PROC_BROWSER_TEST_F(WorkerDevToolsSanityTest, DISABLED_InspectSharedWorker) {
RunTest("testSharedWorker", kSharedWorkerTestPage);
}
} // namespace
<|endoftext|> |
<commit_before>#ifndef SDK_REMOTE_TESTS_TESTS_HH
# define SDK_REMOTE_TESTS_TESTS_HH
# include <libport/debug.hh>
# include <libport/semaphore.hh>
# include <libport/program-name.hh>
# include <libport/unistd.h>
# include <urbi/uclient.hh>
# include <urbi/usyncclient.hh>
/* Liburbi test suite
= Architecture =
Each file corresponds to an 'atomic' test.
Test file layout
- #includes "tests.hh"
- write callbacks, ensure global unique names
- a call to BEGIN_TEST(testname, clientname, syncclientname),
testname must be filename-without-extension
- code of the test:
- setup callbacks, the callback function dump is provided: it displays the
message and increments dumpSem semaphore. Setting a Wildcard or at least
an error callback is recommended.
- c++ code using UClient & client, USyncClient &syncClient made available
- expected output in comments:
//= <expected output>
- a call to END_TEST
<expected output>
<type> <tag> <value>
<type>
D|E|S for data, error, system
*/
/// Display a debug message.
#define VERBOSE(S) \
do { \
GD_CATEGORY(TEST); \
std::ostringstream o; \
o << S; \
GD_INFO(o.str()); \
} while (0)
/// Send S to the Client.
#define SEND_(Client, S) \
do { \
VERBOSE("Sending: " << S); \
Client.send("%s\n", (std::string(S)).c_str()); \
} while (0)
/// Send S to client/syncclient.
#define SEND(S) SEND_(client, S)
#define SSEND(S) SEND_(syncClient, S)
/*----------.
| SyncGet. |
`----------*/
template <typename T>
inline
T
sget(urbi::USyncClient& c, const std::string& msg)
{
VERBOSE("syncGet: Asking " << msg);
T res;
assert(urbi::getValue(c.syncGet(msg), res));
return res;
}
/// syncGet E from the syncClient.
#define SGET(Type, E) \
sget<Type>(syncClient, E)
std::string sget_error(urbi::USyncClient& c, const std::string& msg);
/// Send a computation, expect an error.
#define SGET_ERROR(E) \
sget_error(syncClient, E)
extern libport::Semaphore dumpSem;
/// display the value, increment dumpSem.
urbi::UCallbackAction dump(const urbi::UMessage& msg);
/// display the value, incremente dumpSem remove callback if 0
urbi::UCallbackAction removeOnZero(const urbi::UMessage& msg);
#define BEGIN_TEST(Name, ClientName, SyncClientName) \
void \
Name(urbi::UClient& ClientName, \
urbi::USyncClient& SyncClientName) \
{ \
VERBOSE("starting test " << #Name);
#define END_TEST \
sleep(3); \
SSEND("quit;"); \
SEND("shutdown;"); \
}
void dispatch(const std::string& method, urbi::UClient& client,
urbi::USyncClient& syncClient);
/// \a Name is the base name of the C++ file containing the function
/// \a Name.
#define TESTS_RUN(Name) \
do { \
if (method == #Name) \
{ \
void Name(urbi::UClient&, urbi::USyncClient&); \
Name(client, syncClient); \
return; \
} \
} while (0)
#endif // SDK_REMOTE_TESTS_TESTS_HH
<commit_msg>tests: Simplify more.<commit_after>#ifndef SDK_REMOTE_TESTS_TESTS_HH
# define SDK_REMOTE_TESTS_TESTS_HH
# include <libport/debug.hh>
# include <libport/semaphore.hh>
# include <libport/program-name.hh>
# include <libport/unistd.h>
# include <urbi/uclient.hh>
# include <urbi/usyncclient.hh>
/* Liburbi test suite
= Architecture =
Each file corresponds to an 'atomic' test.
Test file layout
- #includes "tests.hh"
- write callbacks, ensure global unique names
- a call to BEGIN_TEST(testname, clientname, syncclientname),
testname must be filename-without-extension
- code of the test:
- setup callbacks, the callback function dump is provided: it displays the
message and increments dumpSem semaphore. Setting a Wildcard or at least
an error callback is recommended.
- c++ code using UClient & client, USyncClient &syncClient made available
- expected output in comments:
//= <expected output>
- a call to END_TEST
<expected output>
<type> <tag> <value>
<type>
D|E|S for data, error, system
*/
/// Display a debug message.
#define VERBOSE(S) \
do { \
GD_CATEGORY(TEST); \
std::ostringstream o; \
o << S; \
GD_INFO(o.str()); \
} while (0)
/// Send S to the Client.
#define SEND_(Client, S) \
do { \
VERBOSE("Sending: " << S); \
Client.send("%s\n", (S)); \
} while (0)
/// Send S to client/syncclient.
#define SEND(S) SEND_(client, S)
#define SSEND(S) SEND_(syncClient, S)
/*----------.
| SyncGet. |
`----------*/
template <typename T>
inline
T
sget(urbi::USyncClient& c, const std::string& msg)
{
VERBOSE("syncGet: Asking " << msg);
T res;
assert(urbi::getValue(c.syncGet(msg), res));
return res;
}
/// syncGet E from the syncClient.
#define SGET(Type, E) \
sget<Type>(syncClient, E)
std::string sget_error(urbi::USyncClient& c, const std::string& msg);
/// Send a computation, expect an error.
#define SGET_ERROR(E) \
sget_error(syncClient, E)
extern libport::Semaphore dumpSem;
/// display the value, increment dumpSem.
urbi::UCallbackAction dump(const urbi::UMessage& msg);
/// display the value, incremente dumpSem remove callback if 0
urbi::UCallbackAction removeOnZero(const urbi::UMessage& msg);
#define BEGIN_TEST(Name, ClientName, SyncClientName) \
void \
Name(urbi::UClient& ClientName, \
urbi::USyncClient& SyncClientName) \
{ \
VERBOSE("starting test " << #Name);
#define END_TEST \
sleep(3); \
SSEND("quit;"); \
SEND("shutdown;"); \
}
void dispatch(const std::string& method, urbi::UClient& client,
urbi::USyncClient& syncClient);
/// \a Name is the base name of the C++ file containing the function
/// \a Name.
#define TESTS_RUN(Name) \
do { \
if (method == #Name) \
{ \
void Name(urbi::UClient&, urbi::USyncClient&); \
Name(client, syncClient); \
return; \
} \
} while (0)
#endif // SDK_REMOTE_TESTS_TESTS_HH
<|endoftext|> |
<commit_before>#include "PlanetsGLWidget.h"
#include <FTGL/ftgl.h>
PlanetsGLWidget::PlanetsGLWidget(QWidget* const parent) :
AnimatedGLWidget(parent),
font("DejaVuSansMono.ttf"),
rotation(0)
{
}
void PlanetsGLWidget::initializeGL()
{
GLWidget::initializeGL();
setXRotation(90);
glEnable(GL_DEPTH_TEST);
}
void PlanetsGLWidget::tick(const float& elapsed)
{
rotation += 30 * elapsed;
while (rotation > 360) {
rotation -= 360;
}
}
void drawText(FTFont* const font, const char* text, int yOffset)
{
glPushMatrix();
const float width = font->BBox(text).Upper().X();
glTranslatef(-width/2, yOffset + 2 + font->FaceSize(), 0);
font->Render(text);
glPopMatrix();
}
void PlanetsGLWidget::render()
{
glClear(GL_DEPTH_BUFFER_BIT);
//
// original state, nothing is manipulated
//
glPushMatrix(); //begin object manipulation
{
glColor3f(1, 0, 0); // Red
glRotatef(-rotation,0,0,1); // the space this planet exists in will rotate on its z-axis
font.FaceSize(12);
drawText(&font, "Sun", 10);
glutWireSphere(20, 15, 15); // creates the planet, centered at the origin, so it rotates on its own z-axis
}
glPopMatrix(); // ends object manipulation, returns to the previous state -- in this case the original state
glPushMatrix(); // another object
{
glColor3f(1,1,0); // Yellow
glRotatef(90,1,0,0); // the space this object is in is rotated 90 degrees along the X-axis upon creation
glutWireSphere(15,15,15); // no translations happen so this sphere is built right on top of the previous one
// no variables are in the rotation so it will remain still
}
glPopMatrix(); // ends the second objects manipulation
glPushMatrix();
{
glColor3f(1, 0.5, 0); // Orange
glRotatef(90,1,0,0); // rotates the space this moon is in so that its equator will parallel its orbit around the planet
glRotatef(rotation, 0, 0, 1); // this space will rotate about its z-axis
glTranslatef(90, 0, 0); // moves the place point 90 x-units from the origin.
font.FaceSize(7);
drawText(&font, "Mercury", 6);
glutWireSphere(6, 15, 15); // places the moon at the place point, which will rotate about the origin
} // this moon is tide-locked
glPopMatrix();
glPushMatrix();
{
glColor3f(0,1,0); // Green
glRotatef(rotation, 0, 0, 1); // this space will rotate about its z-axis
glTranslatef(0, 80, 0); // moves the place point 80 y-units away from the origin
glRotatef(rotation, 0, 0, 1); // rotates the new space centered on the place point
glutWireSphere(15, 15, 15); // this moon will both orbit the origin and spin on its own axis
// this moon is not tide-locked
glPushMatrix();
{
glColor3f(0,1,1); // Cyan
glTranslatef(25,0,0); // moves the place point 25 x-units from the origin, which is the green moon's place point
font.FaceSize(5);
drawText(&font, "Nix", 3);
glutSolidSphere(3,15,15); // this mini-moon orbits entirely because of its on the rotating plane from the green moon
}
glPopMatrix();
glPushMatrix();
{
glColor3f(0,0,1); // Blue
glRotatef(rotation*2,0,0,1); // this mini-moon's space is rotating from its own power and that of the green moon's
glTranslatef(45,0,0); // since the place point is no longer on the origin the object will not orbit the origin
font.FaceSize(5);
drawText(&font, "Hydra", 3);
glutSolidSphere(3,15,15);
}
glPopMatrix();
glPushMatrix();
{
glColor3f(1,0,1); // Purple
glRotatef(-rotation,0,0,1); // this mini-moon is rotating against the green moon's space's rotation
glTranslatef(35,0,0); // making it appear that its actually orbiting the main planet
font.FaceSize(5);
drawText(&font, "Charon", 5);
glutWireSphere(3,15,15);
}
glPopMatrix();
// all of the mini-moons are tide-locked
}
glPopMatrix();
}
// vim: set ts=4 sw=4 :
<commit_msg>Planets: made Charon a bit bigger<commit_after>#include "PlanetsGLWidget.h"
#include <FTGL/ftgl.h>
PlanetsGLWidget::PlanetsGLWidget(QWidget* const parent) :
AnimatedGLWidget(parent),
font("DejaVuSansMono.ttf"),
rotation(0)
{
}
void PlanetsGLWidget::initializeGL()
{
GLWidget::initializeGL();
setXRotation(90);
glEnable(GL_DEPTH_TEST);
}
void PlanetsGLWidget::tick(const float& elapsed)
{
rotation += 30 * elapsed;
while (rotation > 360) {
rotation -= 360;
}
}
void drawText(FTFont* const font, const char* text, int yOffset)
{
glPushMatrix();
const float width = font->BBox(text).Upper().X();
glTranslatef(-width/2, yOffset + 2 + font->FaceSize(), 0);
font->Render(text);
glPopMatrix();
}
void PlanetsGLWidget::render()
{
glClear(GL_DEPTH_BUFFER_BIT);
//
// original state, nothing is manipulated
//
glPushMatrix(); //begin object manipulation
{
glColor3f(1, 0, 0); // Red
glRotatef(-rotation,0,0,1); // the space this planet exists in will rotate on its z-axis
font.FaceSize(12);
drawText(&font, "Sun", 10);
glutWireSphere(20, 15, 15); // creates the planet, centered at the origin, so it rotates on its own z-axis
}
glPopMatrix(); // ends object manipulation, returns to the previous state -- in this case the original state
glPushMatrix(); // another object
{
glColor3f(1,1,0); // Yellow
glRotatef(90,1,0,0); // the space this object is in is rotated 90 degrees along the X-axis upon creation
glutWireSphere(15,15,15); // no translations happen so this sphere is built right on top of the previous one
// no variables are in the rotation so it will remain still
}
glPopMatrix(); // ends the second objects manipulation
glPushMatrix();
{
glColor3f(1, 0.5, 0); // Orange
glRotatef(90,1,0,0); // rotates the space this moon is in so that its equator will parallel its orbit around the planet
glRotatef(rotation, 0, 0, 1); // this space will rotate about its z-axis
glTranslatef(90, 0, 0); // moves the place point 90 x-units from the origin.
font.FaceSize(7);
drawText(&font, "Mercury", 6);
glutWireSphere(6, 15, 15); // places the moon at the place point, which will rotate about the origin
} // this moon is tide-locked
glPopMatrix();
glPushMatrix();
{
glColor3f(0,1,0); // Green
glRotatef(rotation, 0, 0, 1); // this space will rotate about its z-axis
glTranslatef(0, 80, 0); // moves the place point 80 y-units away from the origin
glRotatef(rotation, 0, 0, 1); // rotates the new space centered on the place point
glutWireSphere(15, 15, 15); // this moon will both orbit the origin and spin on its own axis
// this moon is not tide-locked
glPushMatrix();
{
glColor3f(0,1,1); // Cyan
glTranslatef(25,0,0); // moves the place point 25 x-units from the origin, which is the green moon's place point
font.FaceSize(5);
drawText(&font, "Nix", 3);
glutSolidSphere(3,15,15); // this mini-moon orbits entirely because of its on the rotating plane from the green moon
}
glPopMatrix();
glPushMatrix();
{
glColor3f(0,0,1); // Blue
glRotatef(rotation*2,0,0,1); // this mini-moon's space is rotating from its own power and that of the green moon's
glTranslatef(45,0,0); // since the place point is no longer on the origin the object will not orbit the origin
font.FaceSize(5);
drawText(&font, "Hydra", 3);
glutSolidSphere(3,15,15);
}
glPopMatrix();
glPushMatrix();
{
glColor3f(1,0,1); // Purple
glRotatef(-rotation,0,0,1); // this mini-moon is rotating against the green moon's space's rotation
glTranslatef(35,0,0); // making it appear that its actually orbiting the main planet
font.FaceSize(5);
drawText(&font, "Charon", 5);
glutWireSphere(5,15,15);
}
glPopMatrix();
// all of the mini-moons are tide-locked
}
glPopMatrix();
}
// vim: set ts=4 sw=4 :
<|endoftext|> |
<commit_before>/*
==============================================================================
SamplePlayer.cpp
Author: Daniel Lindenfelser
==============================================================================
*/
#include "Player.h"
Player::Player(int index, const File &audioFile, AudioFormatManager *formatManager, AudioThumbnailCache *thumbnailCache)
: playerIndex(index),
timeSliceThread("Player: " + audioFile.getFileNameWithoutExtension()), title(audioFile.getFileNameWithoutExtension()),
playerState(Stopped),
fadeOutGain(1.0f),
fadeOutGainBackup(1.0f),
fadeOutGainSteps(0.1f),
fadeOutSeconds(4),
fadeOut(false),
process(0.0f),
audioFormatManager(formatManager),
thumbnailCache(thumbnailCache),
transportSource(new AudioTransportSource())
{
timeSliceThread.startThread(3);
audioSourcePlayer.setSource(transportSource);
loadFileIntoTransport(audioFile);
startTimer(UpdateTimerId, 50);
startTimer(FadeOutTimerId, 100);
}
Player::~Player()
{
thumbnail->removeAllChangeListeners();
thumbnail->clear();
removeAllChangeListeners();
stopTimer(UpdateTimerId);
stopTimer(FadeOutTimerId);
thumbnail->setSource(nullptr);
thumbnail = nullptr;
transportSource->setSource(nullptr);
audioSourcePlayer.setSource(nullptr);
transportSource->removeAllChangeListeners();
transportSource = nullptr;
}
void Player::loadFileIntoTransport(const File &audioFile)
{
transportSource->stop();
transportSource->setSource(nullptr);
currentAudioFileSource = nullptr;
auto reader = audioFormatManager->createReaderFor(audioFile);
if (reader != nullptr)
{
currentAudioFileSource = new AudioFormatReaderSource(reader, true);
transportSource->setSource(currentAudioFileSource, 32768, &timeSliceThread, reader->sampleRate);
thumbnail = new AudioThumbnail(1024, *audioFormatManager, *thumbnailCache);
thumbnail->setSource(new FileInputSource(audioFile));
playerState = Ready;
}
else
{
playerState = Error;
}
}
AudioThumbnail *Player::getThumbnail()
{
return thumbnail;
}
void Player::update()
{
process = static_cast<float>(transportSource->getCurrentPosition() / transportSource->getLengthInSeconds());
if (isPlaying()) {
sendChangeMessage();
}
if (process >= 1.0f)
{
process = 1.0f;
transportSource->stop();
transportSource->setPosition(0);
playerState = Played;
}
}
void Player::timerCallback(int timerID)
{
if (timerID == UpdateTimerId)
{
update();
return;
}
if (timerID == FadeOutTimerId)
{
if (fadeOut)
{
fadeOutGain = fadeOutGain - fadeOutGainSteps;
if (fadeOutGain <= 0)
{
fadeOut = false;
transportSource->stop();
transportSource->setPosition(0);
playerState = Played;
fadeOutGain = fadeOutGainBackup;
transportSource->setGain(fadeOutGainBackup);
update();
return;
}
transportSource->setGain(fadeOutGain);
}
}
}
void Player::startFadeOut()
{
if (isPlaying())
{
fadeOut = true;
fadeOutGainBackup = transportSource->getGain();
fadeOutGain = transportSource->getGain();
fadeOutGainSteps = fadeOutGainBackup / fadeOutSeconds / 10.0f;
}
}
void Player::stop()
{
if (isFadingOut())
{
stopTimer(FadeOutTimerId);
fadeOut = false;
fadeOutGain = fadeOutGainBackup;
transportSource->setGain(fadeOutGain);
}
transportSource->stop();
transportSource->setPosition(0);
playerState = Stopped;
update();
sendChangeMessage();
}
void Player::play()
{
if (!fadeOut)
{
transportSource->start();
playerState = Playing;
}
}
void Player::pause()
{
if (!fadeOut)
{
transportSource->stop();
playerState = Paused;
}
}
float Player::getProgress()
{
return process;
}
void Player::setFadeOutTime(int seconds)
{
fadeOutSeconds = seconds;
}
bool Player::isLooping()
{
return currentAudioFileSource->isLooping();
}
void Player::setLooping(bool value)
{
if (isPlaying() && !value)
{
auto nextReadPosition = transportSource->getNextReadPosition();
currentAudioFileSource->setLooping(false);
transportSource->setNextReadPosition(nextReadPosition);
return;
}
currentAudioFileSource->setLooping(value);
sendChangeMessage();
}
String Player::getTitle()
{
return title;
}
String Player::getProgressString(bool remaining)
{
if (!remaining)
{
Time time(1971, 0, 0, 0, 0, static_cast<int>(transportSource->getCurrentPosition()));
return time.toString(false, true, true, true);
}
Time
time(1971,
0,
0,
0,
0,
static_cast<int>(transportSource->getLengthInSeconds() - transportSource->getCurrentPosition()));
return "-" + time.toString(false, true, true, true);
}
float Player::getGain()
{
return transportSource->getGain();
}
void Player::setGain(float newGain)
{
transportSource->setGain(newGain);
}
Player::PlayerState Player::getState()
{
return playerState;
}
AudioSource *Player::getAudioSource()
{
return transportSource;
}
bool Player::isStopped()
{
return playerState == Stopped;
}
bool Player::isPlayed()
{
return playerState == Played;
}
bool Player::isPlaying()
{
return playerState == Playing;
}
bool Player::isPaused()
{
return playerState == Paused;
}
bool Player::isFadingOut()
{
return fadeOut;
}
void Player::setIndex(int value)
{
playerIndex = value;
}
int Player::getIndex()
{
return playerIndex;
}
#if JUCE_UNIT_TESTS
class PlayerTest : public UnitTest {
public:
PlayerTest() : UnitTest ("Ultraschall: Player") {}
void initialise() {
formatManager = new AudioFormatManager();
thumbnailCache = new AudioThumbnailCache(thumbnailCacheSize);
formatManager->registerBasicFormats();
}
void shutdown() {
formatManager = nullptr;
thumbnailCache = nullptr;
}
void initPlayerTest() {
beginTest("init player");
// ScopedPointer<File> dummy = new File();
// ScopedPointer<Player> player = new Player(1, *dummy, formatManager, thumbnailCache);
// player = nullptr;
// dummy = nullptr;
expect(false, "internal crash");
}
void loadFileTest() {
beginTest("load file");
expect(false, "Not implemented");
}
void playTest() {
beginTest("play player");
expect(false, "Not implemented");
}
void pauseTest() {
beginTest("pause player");
expect(false, "Not implemented");
}
void stopTest() {
beginTest("stop player");
expect(false, "Not implemented");
}
void runTest() {
// initPlayerTest();
//
// loadFileTest();
//
// playTest();
// pauseTest();
// stopTest();
}
private:
ScopedPointer<AudioFormatManager> formatManager;
ScopedPointer<AudioThumbnailCache> thumbnailCache;
const int thumbnailCacheSize = 5;
};
static PlayerTest playerTest;
#endif
<commit_msg>send change on fadeout done<commit_after>/*
==============================================================================
SamplePlayer.cpp
Author: Daniel Lindenfelser
==============================================================================
*/
#include "Player.h"
Player::Player(int index, const File &audioFile, AudioFormatManager *formatManager, AudioThumbnailCache *thumbnailCache)
: playerIndex(index),
timeSliceThread("Player: " + audioFile.getFileNameWithoutExtension()), title(audioFile.getFileNameWithoutExtension()),
playerState(Stopped),
fadeOutGain(1.0f),
fadeOutGainBackup(1.0f),
fadeOutGainSteps(0.1f),
fadeOutSeconds(4),
fadeOut(false),
process(0.0f),
audioFormatManager(formatManager),
thumbnailCache(thumbnailCache),
transportSource(new AudioTransportSource())
{
timeSliceThread.startThread(3);
audioSourcePlayer.setSource(transportSource);
loadFileIntoTransport(audioFile);
startTimer(UpdateTimerId, 50);
startTimer(FadeOutTimerId, 100);
}
Player::~Player()
{
thumbnail->removeAllChangeListeners();
thumbnail->clear();
removeAllChangeListeners();
stopTimer(UpdateTimerId);
stopTimer(FadeOutTimerId);
thumbnail->setSource(nullptr);
thumbnail = nullptr;
transportSource->setSource(nullptr);
audioSourcePlayer.setSource(nullptr);
transportSource->removeAllChangeListeners();
transportSource = nullptr;
}
void Player::loadFileIntoTransport(const File &audioFile)
{
transportSource->stop();
transportSource->setSource(nullptr);
currentAudioFileSource = nullptr;
auto reader = audioFormatManager->createReaderFor(audioFile);
if (reader != nullptr)
{
currentAudioFileSource = new AudioFormatReaderSource(reader, true);
transportSource->setSource(currentAudioFileSource, 32768, &timeSliceThread, reader->sampleRate);
thumbnail = new AudioThumbnail(1024, *audioFormatManager, *thumbnailCache);
thumbnail->setSource(new FileInputSource(audioFile));
playerState = Ready;
}
else
{
playerState = Error;
}
}
AudioThumbnail *Player::getThumbnail()
{
return thumbnail;
}
void Player::update()
{
process = static_cast<float>(transportSource->getCurrentPosition() / transportSource->getLengthInSeconds());
if (isPlaying()) {
sendChangeMessage();
}
if (process >= 1.0f)
{
process = 1.0f;
transportSource->stop();
transportSource->setPosition(0);
playerState = Played;
}
}
void Player::timerCallback(int timerID)
{
if (timerID == UpdateTimerId)
{
update();
return;
}
if (timerID == FadeOutTimerId)
{
if (fadeOut)
{
fadeOutGain = fadeOutGain - fadeOutGainSteps;
if (fadeOutGain <= 0)
{
fadeOut = false;
transportSource->stop();
transportSource->setPosition(0);
playerState = Played;
fadeOutGain = fadeOutGainBackup;
transportSource->setGain(fadeOutGainBackup);
update();
sendChangeMessage();
return;
}
transportSource->setGain(fadeOutGain);
}
}
}
void Player::startFadeOut()
{
if (isPlaying())
{
fadeOut = true;
fadeOutGainBackup = transportSource->getGain();
fadeOutGain = transportSource->getGain();
fadeOutGainSteps = fadeOutGainBackup / fadeOutSeconds / 10.0f;
}
}
void Player::stop()
{
if (isFadingOut())
{
stopTimer(FadeOutTimerId);
fadeOut = false;
fadeOutGain = fadeOutGainBackup;
transportSource->setGain(fadeOutGain);
}
transportSource->stop();
transportSource->setPosition(0);
playerState = Stopped;
update();
sendChangeMessage();
}
void Player::play()
{
if (!fadeOut)
{
transportSource->start();
playerState = Playing;
}
}
void Player::pause()
{
if (!fadeOut)
{
transportSource->stop();
playerState = Paused;
}
}
float Player::getProgress()
{
return process;
}
void Player::setFadeOutTime(int seconds)
{
fadeOutSeconds = seconds;
}
bool Player::isLooping()
{
return currentAudioFileSource->isLooping();
}
void Player::setLooping(bool value)
{
if (isPlaying() && !value)
{
auto nextReadPosition = transportSource->getNextReadPosition();
currentAudioFileSource->setLooping(false);
transportSource->setNextReadPosition(nextReadPosition);
return;
}
currentAudioFileSource->setLooping(value);
sendChangeMessage();
}
String Player::getTitle()
{
return title;
}
String Player::getProgressString(bool remaining)
{
if (!remaining)
{
Time time(1971, 0, 0, 0, 0, static_cast<int>(transportSource->getCurrentPosition()));
return time.toString(false, true, true, true);
}
Time
time(1971,
0,
0,
0,
0,
static_cast<int>(transportSource->getLengthInSeconds() - transportSource->getCurrentPosition()));
return "-" + time.toString(false, true, true, true);
}
float Player::getGain()
{
return transportSource->getGain();
}
void Player::setGain(float newGain)
{
transportSource->setGain(newGain);
}
Player::PlayerState Player::getState()
{
return playerState;
}
AudioSource *Player::getAudioSource()
{
return transportSource;
}
bool Player::isStopped()
{
return playerState == Stopped;
}
bool Player::isPlayed()
{
return playerState == Played;
}
bool Player::isPlaying()
{
return playerState == Playing;
}
bool Player::isPaused()
{
return playerState == Paused;
}
bool Player::isFadingOut()
{
return fadeOut;
}
void Player::setIndex(int value)
{
playerIndex = value;
}
int Player::getIndex()
{
return playerIndex;
}
#if JUCE_UNIT_TESTS
class PlayerTest : public UnitTest {
public:
PlayerTest() : UnitTest ("Ultraschall: Player") {}
void initialise() {
formatManager = new AudioFormatManager();
thumbnailCache = new AudioThumbnailCache(thumbnailCacheSize);
formatManager->registerBasicFormats();
}
void shutdown() {
formatManager = nullptr;
thumbnailCache = nullptr;
}
void initPlayerTest() {
beginTest("init player");
// ScopedPointer<File> dummy = new File();
// ScopedPointer<Player> player = new Player(1, *dummy, formatManager, thumbnailCache);
// player = nullptr;
// dummy = nullptr;
expect(false, "internal crash");
}
void loadFileTest() {
beginTest("load file");
expect(false, "Not implemented");
}
void playTest() {
beginTest("play player");
expect(false, "Not implemented");
}
void pauseTest() {
beginTest("pause player");
expect(false, "Not implemented");
}
void stopTest() {
beginTest("stop player");
expect(false, "Not implemented");
}
void runTest() {
// initPlayerTest();
//
// loadFileTest();
//
// playTest();
// pauseTest();
// stopTest();
}
private:
ScopedPointer<AudioFormatManager> formatManager;
ScopedPointer<AudioThumbnailCache> thumbnailCache;
const int thumbnailCacheSize = 5;
};
static PlayerTest playerTest;
#endif
<|endoftext|> |
<commit_before>/**
*
* @file compiled_plugin_base.cpp
*
* @date Jan 15, 2013
* @author partio
*/
#include "compiled_plugin_base.h"
#include <boost/thread.hpp>
#include "plugin_factory.h"
#define HIMAN_AUXILIARY_INCLUDE
#include "neons.h"
#include "writer.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace std;
using namespace himan::plugin;
const unsigned int MAX_THREADS = 12; //<! Max number of threads we allow
const double kInterpolatedValueEpsilon = 0.00001; //<! Max difference between two grid points (if smaller, points are considered the same)
mutex itsAdjustDimensionMutex;
unsigned short compiled_plugin_base::ThreadCount(short userThreadCount) const
{
unsigned int coreCount = boost::thread::hardware_concurrency(); // Number of cores
unsigned short threadCount = MAX_THREADS;
if (userThreadCount > 0)
{
threadCount = userThreadCount;
}
else if (MAX_THREADS > coreCount)
{
threadCount = static_cast<unsigned short> (coreCount);
}
return threadCount;
}
bool compiled_plugin_base::InterpolateToPoint(shared_ptr<const NFmiGrid> targetGrid, shared_ptr<NFmiGrid> sourceGrid, bool gridsAreEqual, double& value)
{
/*
* Logic of interpolating values:
*
* 1) If source and target grids are equal, meaning that the grid AND the area
* properties are effectively the same, do not interpolate. Instead return
* the value of the source grid point that matches the ordering number of the
* target grid point (ie. target grid point #1 --> source grid point #1 etc).
*
* 2) If actual interpolation is needed, first get the *grid* coordinates of the
* latlon target point. Then check if those grid coordinates are very close
* to a grid point -- if so, return the value of the grid point. This serves two
* purposes:
* - We don't need to interpolate if the distance between requested grid point
* and actual grid point is small enough, saving some CPU cycles
* - Sometimes when the requested grid point is close to grid edge, floating
* point inaccuracies might move it outside the grid. If this happens, the
* interpolation fails even though initially the grid point is valid.
*
* 3) If requested source grid point is not near and actual grid point, interpolate
* the value of the point.
*/
// Step 1)
if (gridsAreEqual)
{
value = sourceGrid->FloatValue(targetGrid->GridPoint());
return true;
}
const NFmiPoint targetLatLonPoint = targetGrid->LatLon();
const NFmiPoint sourceGridPoint = targetGrid->LatLonToGrid(targetLatLonPoint.X(), targetLatLonPoint.Y());
// Step 2)
bool noInterpolation = (fabs(sourceGridPoint.X() - round(sourceGridPoint.X())) < kInterpolatedValueEpsilon &&
fabs(sourceGridPoint.Y() - round(sourceGridPoint.Y())) < kInterpolatedValueEpsilon);
if (noInterpolation)
{
value = sourceGrid->FloatValue(sourceGridPoint);
return true;
}
// Step 3)
return sourceGrid->InterpolateToLatLonPoint(targetLatLonPoint, value);
}
bool compiled_plugin_base::AdjustLeadingDimension(shared_ptr<info> myTargetInfo)
{
lock_guard<mutex> lock(itsAdjustDimensionMutex);
// Leading dimension can be: time or level
if (itsLeadingDimension == kTimeDimension)
{
if (!itsFeederInfo->NextTime())
{
return false;
}
myTargetInfo->Time(itsFeederInfo->Time());
}
else if (itsLeadingDimension == kLevelDimension)
{
if (!itsFeederInfo->NextLevel())
{
return false;
}
myTargetInfo->Level(itsFeederInfo->Level());
}
else
{
throw runtime_error(ClassName() + ": Invalid dimension type: " + boost::lexical_cast<string> (itsLeadingDimension));
}
return true;
}
bool compiled_plugin_base::AdjustNonLeadingDimension(shared_ptr<info> myTargetInfo)
{
if (itsLeadingDimension == kTimeDimension)
{
return myTargetInfo->NextLevel();
}
else if (itsLeadingDimension == kLevelDimension)
{
return myTargetInfo->NextTime();
}
else
{
throw runtime_error(ClassName() + ": unsupported leading dimension: " + boost::lexical_cast<string> (itsLeadingDimension));
}
}
void compiled_plugin_base::ResetNonLeadingDimension(shared_ptr<info> myTargetInfo)
{
if (itsLeadingDimension == kTimeDimension)
{
myTargetInfo->ResetLevel();
}
else if (itsLeadingDimension == kLevelDimension)
{
myTargetInfo->ResetTime();
}
else
{
throw runtime_error(ClassName() + ": unsupported leading dimension: " + boost::lexical_cast<string> (itsLeadingDimension));
}
}
himan::level compiled_plugin_base::LevelTransform(const himan::producer& sourceProducer,
const himan::param& targetParam,
const himan::level& targetLevel) const
{
level sourceLevel;
if (sourceProducer.TableVersion() != kHPMissingInt)
{
shared_ptr<neons> n = dynamic_pointer_cast <neons> (plugin_factory::Instance()->Plugin("neons"));
string lvlName = n->NeonsDB().GetGridLevelName(targetParam.Name(), targetLevel.Type(), 204, sourceProducer.TableVersion());
HPLevelType lvlType = kUnknownLevel;
float lvlValue = targetLevel.Value();
if (lvlName == "GROUND")
{
lvlType = kGround;
lvlValue = 0;
}
else if (lvlName == "PRESSURE")
{
lvlType = kPressure;
}
else if (lvlName == "HYBRID")
{
lvlType = kHybrid;
}
else if (lvlName == "HEIGHT")
{
lvlType = kHeight;
}
else
{
throw runtime_error(ClassName() + ": Unknown level type: " + lvlName);
}
sourceLevel = level(lvlType, lvlValue, lvlName);
}
else
{
sourceLevel = targetLevel;
}
return sourceLevel;
}
bool compiled_plugin_base::SetAB(shared_ptr<info> myTargetInfo, shared_ptr<info> sourceInfo)
{
if (myTargetInfo->Level().Type() == kHybrid)
{
int index = myTargetInfo->ParamIndex();
myTargetInfo->Grid()->AB(sourceInfo->Grid()->AB());
myTargetInfo->ParamIndex(index);
}
return true;
}
bool compiled_plugin_base::SwapTo(shared_ptr<info> myTargetInfo, HPScanningMode targetScanningMode)
{
if (myTargetInfo->Grid()->ScanningMode() != targetScanningMode)
{
HPScanningMode originalMode = myTargetInfo->Grid()->ScanningMode();
myTargetInfo->Grid()->ScanningMode(targetScanningMode);
myTargetInfo->Grid()->Swap(originalMode);
}
return true;
}
void compiled_plugin_base::StoreGrib1ParameterDefinitions(vector<param> params, long table2Version)
{
shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons"));
for (unsigned int i = 0; i < params.size(); i++)
{
long parm_id = n->NeonsDB().GetGridParameterId(table2Version, params[i].Name());
params[i].GribIndicatorOfParameter(parm_id);
params[i].GribTableVersion(table2Version);
}
}
void compiled_plugin_base::WriteToFile(shared_ptr<const plugin_configuration> conf, shared_ptr<const info> targetInfo)
{
shared_ptr<writer> aWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer"));
// writing might modify iterator positions --> create a copy
shared_ptr<info> tempInfo(new info(*targetInfo));
if (conf->FileWriteOption() == kNeons || conf->FileWriteOption() == kMultipleFiles)
{
// if info holds multiple parameters, we must loop over them all
tempInfo->FirstParam();
for (; tempInfo->NextParam(); )
{
aWriter->ToFile(tempInfo, conf);
}
}
else if (conf->FileWriteOption() == kSingleFile)
{
aWriter->ToFile(tempInfo, conf, conf->ConfigurationFile());
}
}
<commit_msg>A better loop construct<commit_after>/**
*
* @file compiled_plugin_base.cpp
*
* @date Jan 15, 2013
* @author partio
*/
#include "compiled_plugin_base.h"
#include <boost/thread.hpp>
#include "plugin_factory.h"
#define HIMAN_AUXILIARY_INCLUDE
#include "neons.h"
#include "writer.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace std;
using namespace himan::plugin;
const unsigned int MAX_THREADS = 12; //<! Max number of threads we allow
const double kInterpolatedValueEpsilon = 0.00001; //<! Max difference between two grid points (if smaller, points are considered the same)
mutex itsAdjustDimensionMutex;
unsigned short compiled_plugin_base::ThreadCount(short userThreadCount) const
{
unsigned int coreCount = boost::thread::hardware_concurrency(); // Number of cores
unsigned short threadCount = MAX_THREADS;
if (userThreadCount > 0)
{
threadCount = userThreadCount;
}
else if (MAX_THREADS > coreCount)
{
threadCount = static_cast<unsigned short> (coreCount);
}
return threadCount;
}
bool compiled_plugin_base::InterpolateToPoint(shared_ptr<const NFmiGrid> targetGrid, shared_ptr<NFmiGrid> sourceGrid, bool gridsAreEqual, double& value)
{
/*
* Logic of interpolating values:
*
* 1) If source and target grids are equal, meaning that the grid AND the area
* properties are effectively the same, do not interpolate. Instead return
* the value of the source grid point that matches the ordering number of the
* target grid point (ie. target grid point #1 --> source grid point #1 etc).
*
* 2) If actual interpolation is needed, first get the *grid* coordinates of the
* latlon target point. Then check if those grid coordinates are very close
* to a grid point -- if so, return the value of the grid point. This serves two
* purposes:
* - We don't need to interpolate if the distance between requested grid point
* and actual grid point is small enough, saving some CPU cycles
* - Sometimes when the requested grid point is close to grid edge, floating
* point inaccuracies might move it outside the grid. If this happens, the
* interpolation fails even though initially the grid point is valid.
*
* 3) If requested source grid point is not near and actual grid point, interpolate
* the value of the point.
*/
// Step 1)
if (gridsAreEqual)
{
value = sourceGrid->FloatValue(targetGrid->GridPoint());
return true;
}
const NFmiPoint targetLatLonPoint = targetGrid->LatLon();
const NFmiPoint sourceGridPoint = targetGrid->LatLonToGrid(targetLatLonPoint.X(), targetLatLonPoint.Y());
// Step 2)
bool noInterpolation = (fabs(sourceGridPoint.X() - round(sourceGridPoint.X())) < kInterpolatedValueEpsilon &&
fabs(sourceGridPoint.Y() - round(sourceGridPoint.Y())) < kInterpolatedValueEpsilon);
if (noInterpolation)
{
value = sourceGrid->FloatValue(sourceGridPoint);
return true;
}
// Step 3)
return sourceGrid->InterpolateToLatLonPoint(targetLatLonPoint, value);
}
bool compiled_plugin_base::AdjustLeadingDimension(shared_ptr<info> myTargetInfo)
{
lock_guard<mutex> lock(itsAdjustDimensionMutex);
// Leading dimension can be: time or level
if (itsLeadingDimension == kTimeDimension)
{
if (!itsFeederInfo->NextTime())
{
return false;
}
myTargetInfo->Time(itsFeederInfo->Time());
}
else if (itsLeadingDimension == kLevelDimension)
{
if (!itsFeederInfo->NextLevel())
{
return false;
}
myTargetInfo->Level(itsFeederInfo->Level());
}
else
{
throw runtime_error(ClassName() + ": Invalid dimension type: " + boost::lexical_cast<string> (itsLeadingDimension));
}
return true;
}
bool compiled_plugin_base::AdjustNonLeadingDimension(shared_ptr<info> myTargetInfo)
{
if (itsLeadingDimension == kTimeDimension)
{
return myTargetInfo->NextLevel();
}
else if (itsLeadingDimension == kLevelDimension)
{
return myTargetInfo->NextTime();
}
else
{
throw runtime_error(ClassName() + ": unsupported leading dimension: " + boost::lexical_cast<string> (itsLeadingDimension));
}
}
void compiled_plugin_base::ResetNonLeadingDimension(shared_ptr<info> myTargetInfo)
{
if (itsLeadingDimension == kTimeDimension)
{
myTargetInfo->ResetLevel();
}
else if (itsLeadingDimension == kLevelDimension)
{
myTargetInfo->ResetTime();
}
else
{
throw runtime_error(ClassName() + ": unsupported leading dimension: " + boost::lexical_cast<string> (itsLeadingDimension));
}
}
himan::level compiled_plugin_base::LevelTransform(const himan::producer& sourceProducer,
const himan::param& targetParam,
const himan::level& targetLevel) const
{
level sourceLevel;
if (sourceProducer.TableVersion() != kHPMissingInt)
{
shared_ptr<neons> n = dynamic_pointer_cast <neons> (plugin_factory::Instance()->Plugin("neons"));
string lvlName = n->NeonsDB().GetGridLevelName(targetParam.Name(), targetLevel.Type(), 204, sourceProducer.TableVersion());
HPLevelType lvlType = kUnknownLevel;
float lvlValue = targetLevel.Value();
if (lvlName == "GROUND")
{
lvlType = kGround;
lvlValue = 0;
}
else if (lvlName == "PRESSURE")
{
lvlType = kPressure;
}
else if (lvlName == "HYBRID")
{
lvlType = kHybrid;
}
else if (lvlName == "HEIGHT")
{
lvlType = kHeight;
}
else
{
throw runtime_error(ClassName() + ": Unknown level type: " + lvlName);
}
sourceLevel = level(lvlType, lvlValue, lvlName);
}
else
{
sourceLevel = targetLevel;
}
return sourceLevel;
}
bool compiled_plugin_base::SetAB(shared_ptr<info> myTargetInfo, shared_ptr<info> sourceInfo)
{
if (myTargetInfo->Level().Type() == kHybrid)
{
int index = myTargetInfo->ParamIndex();
myTargetInfo->Grid()->AB(sourceInfo->Grid()->AB());
myTargetInfo->ParamIndex(index);
}
return true;
}
bool compiled_plugin_base::SwapTo(shared_ptr<info> myTargetInfo, HPScanningMode targetScanningMode)
{
if (myTargetInfo->Grid()->ScanningMode() != targetScanningMode)
{
HPScanningMode originalMode = myTargetInfo->Grid()->ScanningMode();
myTargetInfo->Grid()->ScanningMode(targetScanningMode);
myTargetInfo->Grid()->Swap(originalMode);
}
return true;
}
void compiled_plugin_base::StoreGrib1ParameterDefinitions(vector<param> params, long table2Version)
{
shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons"));
for (unsigned int i = 0; i < params.size(); i++)
{
long parm_id = n->NeonsDB().GetGridParameterId(table2Version, params[i].Name());
params[i].GribIndicatorOfParameter(parm_id);
params[i].GribTableVersion(table2Version);
}
}
void compiled_plugin_base::WriteToFile(shared_ptr<const plugin_configuration> conf, shared_ptr<const info> targetInfo)
{
shared_ptr<writer> aWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer"));
// writing might modify iterator positions --> create a copy
shared_ptr<info> tempInfo(new info(*targetInfo));
if (conf->FileWriteOption() == kNeons || conf->FileWriteOption() == kMultipleFiles)
{
// if info holds multiple parameters, we must loop over them all
tempInfo->ResetParam();
while (tempInfo->NextParam())
{
aWriter->ToFile(tempInfo, conf);
}
}
else if (conf->FileWriteOption() == kSingleFile)
{
aWriter->ToFile(tempInfo, conf, conf->ConfigurationFile());
}
tempInfo.reset();
}
<|endoftext|> |
<commit_before>//= GRState*cpp - Path-Sens. "State" for tracking valuues -----*- C++ -*--=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines SymbolRef, ExprBindKey, and GRState*
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/GRStateTrait.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
// Give the vtable for ConstraintManager somewhere to live.
ConstraintManager::~ConstraintManager() {}
GRStateManager::~GRStateManager() {
for (std::vector<GRState::Printer*>::iterator I=Printers.begin(),
E=Printers.end(); I!=E; ++I)
delete *I;
for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
I!=E; ++I)
I->second.second(I->second.first);
}
const GRState*
GRStateManager::RemoveDeadBindings(const GRState* state, Stmt* Loc,
SymbolReaper& SymReaper) {
// This code essentially performs a "mark-and-sweep" of the VariableBindings.
// The roots are any Block-level exprs and Decls that our liveness algorithm
// tells us are live. We then see what Decls they may reference, and keep
// those around. This code more than likely can be made faster, and the
// frequency of which this method is called should be experimented with
// for optimum performance.
llvm::SmallVector<const MemRegion*, 10> RegionRoots;
GRState NewState = *state;
NewState.Env = EnvMgr.RemoveDeadBindings(NewState.Env, Loc, SymReaper, *this,
state, RegionRoots);
// Clean up the store.
NewState.St = StoreMgr->RemoveDeadBindings(&NewState, Loc, SymReaper,
RegionRoots);
return ConstraintMgr->RemoveDeadBindings(getPersistentState(NewState),
SymReaper);
}
const GRState* GRStateManager::Unbind(const GRState* St, Loc LV) {
Store OldStore = St->getStore();
Store NewStore = StoreMgr->Remove(OldStore, LV);
if (NewStore == OldStore)
return St;
GRState NewSt = *St;
NewSt.St = NewStore;
return getPersistentState(NewSt);
}
const GRState* GRStateManager::getInitialState() {
GRState StateImpl(EnvMgr.getInitialEnvironment(),
StoreMgr->getInitialStore(),
GDMFactory.GetEmptyMap());
return getPersistentState(StateImpl);
}
const GRState* GRStateManager::getPersistentState(GRState& State) {
llvm::FoldingSetNodeID ID;
State.Profile(ID);
void* InsertPos;
if (GRState* I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
return I;
GRState* I = (GRState*) Alloc.Allocate<GRState>();
new (I) GRState(State);
StateSet.InsertNode(I, InsertPos);
return I;
}
const GRState* GRStateManager::MakeStateWithStore(const GRState* St,
Store store) {
GRState NewSt = *St;
NewSt.St = store;
return getPersistentState(NewSt);
}
//===----------------------------------------------------------------------===//
// State pretty-printing.
//===----------------------------------------------------------------------===//
void GRState::print(std::ostream& Out, StoreManager& StoreMgr,
ConstraintManager& ConstraintMgr,
Printer** Beg, Printer** End,
const char* nl, const char* sep) const {
// Print the store.
StoreMgr.print(getStore(), Out, nl, sep);
// Print Subexpression bindings.
bool isFirst = true;
for (seb_iterator I = seb_begin(), E = seb_end(); I != E; ++I) {
if (isFirst) {
Out << nl << nl << "Sub-Expressions:" << nl;
isFirst = false;
}
else { Out << nl; }
Out << " (" << (void*) I.getKey() << ") ";
llvm::raw_os_ostream OutS(Out);
I.getKey()->printPretty(OutS);
OutS.flush();
Out << " : ";
I.getData().print(Out);
}
// Print block-expression bindings.
isFirst = true;
for (beb_iterator I = beb_begin(), E = beb_end(); I != E; ++I) {
if (isFirst) {
Out << nl << nl << "Block-level Expressions:" << nl;
isFirst = false;
}
else { Out << nl; }
Out << " (" << (void*) I.getKey() << ") ";
llvm::raw_os_ostream OutS(Out);
I.getKey()->printPretty(OutS);
OutS.flush();
Out << " : ";
I.getData().print(Out);
}
ConstraintMgr.print(this, Out, nl, sep);
// Print checker-specific data.
for ( ; Beg != End ; ++Beg) (*Beg)->Print(Out, this, nl, sep);
}
void GRStateRef::printDOT(std::ostream& Out) const {
print(Out, "\\l", "\\|");
}
void GRStateRef::printStdErr() const {
print(*llvm::cerr);
}
void GRStateRef::print(std::ostream& Out, const char* nl, const char* sep)const{
GRState::Printer **beg = Mgr->Printers.empty() ? 0 : &Mgr->Printers[0];
GRState::Printer **end = !beg ? 0 : beg + Mgr->Printers.size();
St->print(Out, *Mgr->StoreMgr, *Mgr->ConstraintMgr, beg, end, nl, sep);
}
//===----------------------------------------------------------------------===//
// Generic Data Map.
//===----------------------------------------------------------------------===//
void* const* GRState::FindGDM(void* K) const {
return GDM.lookup(K);
}
void*
GRStateManager::FindGDMContext(void* K,
void* (*CreateContext)(llvm::BumpPtrAllocator&),
void (*DeleteContext)(void*)) {
std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
if (!p.first) {
p.first = CreateContext(Alloc);
p.second = DeleteContext;
}
return p.first;
}
const GRState* GRStateManager::addGDM(const GRState* St, void* Key, void* Data){
GRState::GenericDataMap M1 = St->getGDM();
GRState::GenericDataMap M2 = GDMFactory.Add(M1, Key, Data);
if (M1 == M2)
return St;
GRState NewSt = *St;
NewSt.GDM = M2;
return getPersistentState(NewSt);
}
//===----------------------------------------------------------------------===//
// Utility.
//===----------------------------------------------------------------------===//
namespace {
class VISIBILITY_HIDDEN ScanReachableSymbols : public SubRegionMap::Visitor {
typedef llvm::DenseSet<const MemRegion*> VisitedRegionsTy;
VisitedRegionsTy visited;
GRStateRef state;
SymbolVisitor &visitor;
llvm::OwningPtr<SubRegionMap> SRM;
public:
ScanReachableSymbols(GRStateManager* sm, const GRState *st, SymbolVisitor& v)
: state(st, *sm), visitor(v) {}
bool scan(nonloc::CompoundVal val);
bool scan(SVal val);
bool scan(const MemRegion *R);
// From SubRegionMap::Visitor.
bool Visit(const MemRegion* Parent, const MemRegion* SubRegion) {
return scan(SubRegion);
}
};
}
bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
if (!scan(*I))
return false;
return true;
}
bool ScanReachableSymbols::scan(SVal val) {
if (loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&val))
return scan(X->getRegion());
if (loc::SymbolVal *X = dyn_cast<loc::SymbolVal>(&val))
return visitor.VisitSymbol(X->getSymbol());
if (nonloc::SymbolVal *X = dyn_cast<nonloc::SymbolVal>(&val))
return visitor.VisitSymbol(X->getSymbol());
if (nonloc::CompoundVal *X = dyn_cast<nonloc::CompoundVal>(&val))
return scan(*X);
return true;
}
bool ScanReachableSymbols::scan(const MemRegion *R) {
if (visited.count(R))
return true;
visited.insert(R);
// If this is a symbolic region, visit the symbol for the region.
if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
if (!visitor.VisitSymbol(SR->getSymbol()))
return false;
// If this is a subregion, also visit the parent regions.
if (const SubRegion *SR = dyn_cast<SubRegion>(R))
if (!scan(SR->getSuperRegion()));
return false;
// Now look at the binding to this region (if any).
if (!scan(state.GetSVal(R)))
return false;
// Now look at the subregions.
if (!SRM.get())
SRM.reset(state.getManager().getStoreManager().getSubRegionMap(state).get());
return SRM->iterSubRegions(R, *this);
}
bool GRStateManager::scanReachableSymbols(SVal val, const GRState* state,
SymbolVisitor& visitor) {
ScanReachableSymbols S(this, state, visitor);
return S.scan(val);
}
//===----------------------------------------------------------------------===//
// Queries.
//===----------------------------------------------------------------------===//
bool GRStateManager::isEqual(const GRState* state, Expr* Ex,
const llvm::APSInt& Y) {
SVal V = GetSVal(state, Ex);
if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
return X->getValue() == Y;
if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
return X->getValue() == Y;
if (nonloc::SymbolVal* X = dyn_cast<nonloc::SymbolVal>(&V))
return ConstraintMgr->isEqual(state, X->getSymbol(), Y);
if (loc::SymbolVal* X = dyn_cast<loc::SymbolVal>(&V))
return ConstraintMgr->isEqual(state, X->getSymbol(), Y);
return false;
}
bool GRStateManager::isEqual(const GRState* state, Expr* Ex, uint64_t x) {
return isEqual(state, Ex, BasicVals.getValue(x, Ex->getType()));
}
//===----------------------------------------------------------------------===//
// Persistent values for indexing into the Generic Data Map.
int GRState::NullDerefTag::TagInt = 0;
<commit_msg>Fix extra ';' bug noticed by Mike Stump.<commit_after>//= GRState*cpp - Path-Sens. "State" for tracking valuues -----*- C++ -*--=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines SymbolRef, ExprBindKey, and GRState*
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/GRStateTrait.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
// Give the vtable for ConstraintManager somewhere to live.
ConstraintManager::~ConstraintManager() {}
GRStateManager::~GRStateManager() {
for (std::vector<GRState::Printer*>::iterator I=Printers.begin(),
E=Printers.end(); I!=E; ++I)
delete *I;
for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
I!=E; ++I)
I->second.second(I->second.first);
}
const GRState*
GRStateManager::RemoveDeadBindings(const GRState* state, Stmt* Loc,
SymbolReaper& SymReaper) {
// This code essentially performs a "mark-and-sweep" of the VariableBindings.
// The roots are any Block-level exprs and Decls that our liveness algorithm
// tells us are live. We then see what Decls they may reference, and keep
// those around. This code more than likely can be made faster, and the
// frequency of which this method is called should be experimented with
// for optimum performance.
llvm::SmallVector<const MemRegion*, 10> RegionRoots;
GRState NewState = *state;
NewState.Env = EnvMgr.RemoveDeadBindings(NewState.Env, Loc, SymReaper, *this,
state, RegionRoots);
// Clean up the store.
NewState.St = StoreMgr->RemoveDeadBindings(&NewState, Loc, SymReaper,
RegionRoots);
return ConstraintMgr->RemoveDeadBindings(getPersistentState(NewState),
SymReaper);
}
const GRState* GRStateManager::Unbind(const GRState* St, Loc LV) {
Store OldStore = St->getStore();
Store NewStore = StoreMgr->Remove(OldStore, LV);
if (NewStore == OldStore)
return St;
GRState NewSt = *St;
NewSt.St = NewStore;
return getPersistentState(NewSt);
}
const GRState* GRStateManager::getInitialState() {
GRState StateImpl(EnvMgr.getInitialEnvironment(),
StoreMgr->getInitialStore(),
GDMFactory.GetEmptyMap());
return getPersistentState(StateImpl);
}
const GRState* GRStateManager::getPersistentState(GRState& State) {
llvm::FoldingSetNodeID ID;
State.Profile(ID);
void* InsertPos;
if (GRState* I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
return I;
GRState* I = (GRState*) Alloc.Allocate<GRState>();
new (I) GRState(State);
StateSet.InsertNode(I, InsertPos);
return I;
}
const GRState* GRStateManager::MakeStateWithStore(const GRState* St,
Store store) {
GRState NewSt = *St;
NewSt.St = store;
return getPersistentState(NewSt);
}
//===----------------------------------------------------------------------===//
// State pretty-printing.
//===----------------------------------------------------------------------===//
void GRState::print(std::ostream& Out, StoreManager& StoreMgr,
ConstraintManager& ConstraintMgr,
Printer** Beg, Printer** End,
const char* nl, const char* sep) const {
// Print the store.
StoreMgr.print(getStore(), Out, nl, sep);
// Print Subexpression bindings.
bool isFirst = true;
for (seb_iterator I = seb_begin(), E = seb_end(); I != E; ++I) {
if (isFirst) {
Out << nl << nl << "Sub-Expressions:" << nl;
isFirst = false;
}
else { Out << nl; }
Out << " (" << (void*) I.getKey() << ") ";
llvm::raw_os_ostream OutS(Out);
I.getKey()->printPretty(OutS);
OutS.flush();
Out << " : ";
I.getData().print(Out);
}
// Print block-expression bindings.
isFirst = true;
for (beb_iterator I = beb_begin(), E = beb_end(); I != E; ++I) {
if (isFirst) {
Out << nl << nl << "Block-level Expressions:" << nl;
isFirst = false;
}
else { Out << nl; }
Out << " (" << (void*) I.getKey() << ") ";
llvm::raw_os_ostream OutS(Out);
I.getKey()->printPretty(OutS);
OutS.flush();
Out << " : ";
I.getData().print(Out);
}
ConstraintMgr.print(this, Out, nl, sep);
// Print checker-specific data.
for ( ; Beg != End ; ++Beg) (*Beg)->Print(Out, this, nl, sep);
}
void GRStateRef::printDOT(std::ostream& Out) const {
print(Out, "\\l", "\\|");
}
void GRStateRef::printStdErr() const {
print(*llvm::cerr);
}
void GRStateRef::print(std::ostream& Out, const char* nl, const char* sep)const{
GRState::Printer **beg = Mgr->Printers.empty() ? 0 : &Mgr->Printers[0];
GRState::Printer **end = !beg ? 0 : beg + Mgr->Printers.size();
St->print(Out, *Mgr->StoreMgr, *Mgr->ConstraintMgr, beg, end, nl, sep);
}
//===----------------------------------------------------------------------===//
// Generic Data Map.
//===----------------------------------------------------------------------===//
void* const* GRState::FindGDM(void* K) const {
return GDM.lookup(K);
}
void*
GRStateManager::FindGDMContext(void* K,
void* (*CreateContext)(llvm::BumpPtrAllocator&),
void (*DeleteContext)(void*)) {
std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
if (!p.first) {
p.first = CreateContext(Alloc);
p.second = DeleteContext;
}
return p.first;
}
const GRState* GRStateManager::addGDM(const GRState* St, void* Key, void* Data){
GRState::GenericDataMap M1 = St->getGDM();
GRState::GenericDataMap M2 = GDMFactory.Add(M1, Key, Data);
if (M1 == M2)
return St;
GRState NewSt = *St;
NewSt.GDM = M2;
return getPersistentState(NewSt);
}
//===----------------------------------------------------------------------===//
// Utility.
//===----------------------------------------------------------------------===//
namespace {
class VISIBILITY_HIDDEN ScanReachableSymbols : public SubRegionMap::Visitor {
typedef llvm::DenseSet<const MemRegion*> VisitedRegionsTy;
VisitedRegionsTy visited;
GRStateRef state;
SymbolVisitor &visitor;
llvm::OwningPtr<SubRegionMap> SRM;
public:
ScanReachableSymbols(GRStateManager* sm, const GRState *st, SymbolVisitor& v)
: state(st, *sm), visitor(v) {}
bool scan(nonloc::CompoundVal val);
bool scan(SVal val);
bool scan(const MemRegion *R);
// From SubRegionMap::Visitor.
bool Visit(const MemRegion* Parent, const MemRegion* SubRegion) {
return scan(SubRegion);
}
};
}
bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
if (!scan(*I))
return false;
return true;
}
bool ScanReachableSymbols::scan(SVal val) {
if (loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&val))
return scan(X->getRegion());
if (loc::SymbolVal *X = dyn_cast<loc::SymbolVal>(&val))
return visitor.VisitSymbol(X->getSymbol());
if (nonloc::SymbolVal *X = dyn_cast<nonloc::SymbolVal>(&val))
return visitor.VisitSymbol(X->getSymbol());
if (nonloc::CompoundVal *X = dyn_cast<nonloc::CompoundVal>(&val))
return scan(*X);
return true;
}
bool ScanReachableSymbols::scan(const MemRegion *R) {
if (visited.count(R))
return true;
visited.insert(R);
// If this is a symbolic region, visit the symbol for the region.
if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
if (!visitor.VisitSymbol(SR->getSymbol()))
return false;
// If this is a subregion, also visit the parent regions.
if (const SubRegion *SR = dyn_cast<SubRegion>(R))
if (!scan(SR->getSuperRegion()))
return false;
// Now look at the binding to this region (if any).
if (!scan(state.GetSVal(R)))
return false;
// Now look at the subregions.
if (!SRM.get())
SRM.reset(state.getManager().getStoreManager().getSubRegionMap(state).get());
return SRM->iterSubRegions(R, *this);
}
bool GRStateManager::scanReachableSymbols(SVal val, const GRState* state,
SymbolVisitor& visitor) {
ScanReachableSymbols S(this, state, visitor);
return S.scan(val);
}
//===----------------------------------------------------------------------===//
// Queries.
//===----------------------------------------------------------------------===//
bool GRStateManager::isEqual(const GRState* state, Expr* Ex,
const llvm::APSInt& Y) {
SVal V = GetSVal(state, Ex);
if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
return X->getValue() == Y;
if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
return X->getValue() == Y;
if (nonloc::SymbolVal* X = dyn_cast<nonloc::SymbolVal>(&V))
return ConstraintMgr->isEqual(state, X->getSymbol(), Y);
if (loc::SymbolVal* X = dyn_cast<loc::SymbolVal>(&V))
return ConstraintMgr->isEqual(state, X->getSymbol(), Y);
return false;
}
bool GRStateManager::isEqual(const GRState* state, Expr* Ex, uint64_t x) {
return isEqual(state, Ex, BasicVals.getValue(x, Ex->getType()));
}
//===----------------------------------------------------------------------===//
// Persistent values for indexing into the Generic Data Map.
int GRState::NullDerefTag::TagInt = 0;
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.