text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2008 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 <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.value().empty()) { command_line->AppendSwitchWithValue(switches::kLoadExtension, load_extension_.ToWStringHack()); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); ASSERT_EQ(static_cast<uint32>(num_expected_extensions), service->extensions()->size()); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result); EXPECT_EQ(expect_css, result); result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) { WaitForServicesToStart(4, true); // 1 component extension and 3 others. TestInjection(true, true); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; // Flaky (times out) on Mac/Windows. http://crbug.com/46301. #if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_Test FLAKY_Test #else #define MAYBE_Test Test #endif IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) { WaitForServicesToStart(1, false); TestInjection(true, true); } <commit_msg>Use correct platform #define to mark ExtensionsLoadTest as flaky (OS_MACOSX).<commit_after>// Copyright (c) 2008 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 <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.value().empty()) { command_line->AppendSwitchWithValue(switches::kLoadExtension, load_extension_.ToWStringHack()); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); ASSERT_EQ(static_cast<uint32>(num_expected_extensions), service->extensions()->size()); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result); EXPECT_EQ(expect_css, result); result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) { WaitForServicesToStart(4, true); // 1 component extension and 3 others. TestInjection(true, true); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; // Flaky (times out) on Mac/Windows. http://crbug.com/46301. #if defined(OS_MACOSX) || defined(OS_WIN) #define MAYBE_Test FLAKY_Test #else #define MAYBE_Test Test #endif IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) { WaitForServicesToStart(1, false); TestInjection(true, true); } <|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/touch/tabs/touch_tab_strip_controller.h" #include "chrome/browser/extensions/extension_tab_helper.h" #include "chrome/browser/favicon/favicon_tab_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/touch/tabs/touch_tab.h" #include "chrome/browser/ui/touch/tabs/touch_tab_strip.h" #include "chrome/browser/ui/views/tabs/tab_renderer_data.h" #include "skia/ext/image_operations.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/favicon_size.h" namespace { void CalcTouchIconTargetSize(int* width, int* height) { if (*width > TouchTab::kTouchTargetIconSize || *height > TouchTab::kTouchTargetIconSize) { // Too big, resize it maintaining the aspect ratio. float aspect_ratio = static_cast<float>(*width) / static_cast<float>(*height); *height = TouchTab::kTouchTargetIconSize; *width = static_cast<int>(aspect_ratio * *height); if (*width > TouchTab::kTouchTargetIconSize) { *width = TouchTab::kTouchTargetIconSize; *height = static_cast<int>(*width / aspect_ratio); } } } GURL GetURLWithoutFragment(const GURL& gurl) { url_canon::Replacements<char> replacements; replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearQuery(); replacements.ClearRef(); return gurl.ReplaceComponents(replacements); } } // namespace TouchTabStripController::TouchTabStripController(Browser* browser, TabStripModel* model) : BrowserTabStripController(browser, model) { } TouchTabStripController::~TouchTabStripController() { } void TouchTabStripController::TabDetachedAt(TabContentsWrapper* contents, int model_index) { if (consumer_.HasPendingRequests()) { TouchTab* touch_tab = tabstrip()->GetTouchTabAtModelIndex(model_index); consumer_.CancelAllRequestsForClientData(touch_tab); } } void TouchTabStripController::TabChangedAt(TabContentsWrapper* contents, int model_index, TabChangeType change_type) { // Clear the large icon if we are loading a different URL in the same tab. if (change_type == LOADING_ONLY) { TouchTab* touch_tab = tabstrip()->GetTouchTabAtModelIndex(model_index); if (!touch_tab->touch_icon().isNull()) { GURL existing_tab_url = GetURLWithoutFragment(touch_tab->data().url); GURL page_url = GetURLWithoutFragment(contents->tab_contents()->GetURL()); // Reset touch icon if the url are different. if (existing_tab_url != page_url) { touch_tab->set_touch_icon(SkBitmap()); consumer_.CancelAllRequestsForClientData(touch_tab); } } } // Always call parent's method. BrowserTabStripController::TabChangedAt(contents, model_index, change_type); } void TouchTabStripController::SetTabRendererDataFromModel( TabContents* contents, int model_index, TabRendererData* data, TabStatus tab_status) { // Call parent first. BrowserTabStripController::SetTabRendererDataFromModel(contents, model_index, data, tab_status); if (tab_status == NEW_TAB) return; // Use the touch icon if any. TouchTab* touch_tab = tabstrip()->GetTouchTabAtModelIndex(model_index); if (!touch_tab->touch_icon().isNull()) { data->favicon = touch_tab->touch_icon(); return; } // In the case where we do not have a touch icon we scale up the small // favicons (16x16) which originally are coming from NavigationEntry. if (data->favicon.width() == kFaviconSize && data->favicon.height() == kFaviconSize) { data->favicon = skia::ImageOperations::Resize(data->favicon, skia::ImageOperations::RESIZE_BEST, TouchTab::kTouchTargetIconSize, TouchTab::kTouchTargetIconSize); } // Check if we have an outstanding request for this tab. if (consumer_.HasPendingRequests()) consumer_.CancelAllRequestsForClientData(touch_tab); // Request touch icon. GURL page_url = GetURLWithoutFragment(contents->GetURL()); FaviconService* favicon_service = profile()->GetFaviconService( Profile::EXPLICIT_ACCESS); if (favicon_service) { CancelableRequestProvider::Handle h = favicon_service->GetFaviconForURL( page_url, history::TOUCH_ICON | history::TOUCH_PRECOMPOSED_ICON, &consumer_, NewCallback(this, &TouchTabStripController::OnTouchIconAvailable)); consumer_.SetClientData(favicon_service, h, touch_tab); } } const TouchTabStrip* TouchTabStripController::tabstrip() const { return static_cast<const TouchTabStrip*>( BrowserTabStripController::tabstrip()); } void TouchTabStripController::OnTouchIconAvailable( FaviconService::Handle h, history::FaviconData favicon) { // Abandon the request when there is no valid favicon. if (!favicon.is_valid()) return; // Retrieve the model_index from the TouchTab pointer received. TouchTab* touch_tab = consumer_.GetClientDataForCurrentRequest(); int model_index = tabstrip()->GetModelIndexOfBaseTab(touch_tab); if (!IsValidIndex(model_index)) return; // Try to decode the favicon, return on failure. SkBitmap bitmap; gfx::PNGCodec::Decode(favicon.image_data->front(), favicon.image_data->size(), &bitmap); if (bitmap.isNull()) return; // Rescale output, if needed, and assign to the TouchTab instance. int width = bitmap.width(); int height = bitmap.height(); if (width == TouchTab::kTouchTargetIconSize && height == TouchTab::kTouchTargetIconSize) { touch_tab->set_touch_icon(bitmap); } else { CalcTouchIconTargetSize(&width, &height); touch_tab->set_touch_icon(skia::ImageOperations::Resize(bitmap, skia::ImageOperations::RESIZE_BEST, width, height)); } // Refresh UI since favicon changed. browser()->GetTabContentsAt(model_index)->NotifyNavigationStateChanged( TabContents::INVALIDATE_TAB); } <commit_msg>touch tabstrip: Paint correctly when a tab is removed.<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/touch/tabs/touch_tab_strip_controller.h" #include "chrome/browser/extensions/extension_tab_helper.h" #include "chrome/browser/favicon/favicon_tab_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/touch/tabs/touch_tab.h" #include "chrome/browser/ui/touch/tabs/touch_tab_strip.h" #include "chrome/browser/ui/views/tabs/tab_renderer_data.h" #include "skia/ext/image_operations.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/favicon_size.h" namespace { void CalcTouchIconTargetSize(int* width, int* height) { if (*width > TouchTab::kTouchTargetIconSize || *height > TouchTab::kTouchTargetIconSize) { // Too big, resize it maintaining the aspect ratio. float aspect_ratio = static_cast<float>(*width) / static_cast<float>(*height); *height = TouchTab::kTouchTargetIconSize; *width = static_cast<int>(aspect_ratio * *height); if (*width > TouchTab::kTouchTargetIconSize) { *width = TouchTab::kTouchTargetIconSize; *height = static_cast<int>(*width / aspect_ratio); } } } GURL GetURLWithoutFragment(const GURL& gurl) { url_canon::Replacements<char> replacements; replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearQuery(); replacements.ClearRef(); return gurl.ReplaceComponents(replacements); } } // namespace TouchTabStripController::TouchTabStripController(Browser* browser, TabStripModel* model) : BrowserTabStripController(browser, model) { } TouchTabStripController::~TouchTabStripController() { } void TouchTabStripController::TabDetachedAt(TabContentsWrapper* contents, int model_index) { if (consumer_.HasPendingRequests()) { TouchTab* touch_tab = tabstrip()->GetTouchTabAtModelIndex(model_index); consumer_.CancelAllRequestsForClientData(touch_tab); } BrowserTabStripController::TabDetachedAt(contents, model_index); } void TouchTabStripController::TabChangedAt(TabContentsWrapper* contents, int model_index, TabChangeType change_type) { // Clear the large icon if we are loading a different URL in the same tab. if (change_type == LOADING_ONLY) { TouchTab* touch_tab = tabstrip()->GetTouchTabAtModelIndex(model_index); if (!touch_tab->touch_icon().isNull()) { GURL existing_tab_url = GetURLWithoutFragment(touch_tab->data().url); GURL page_url = GetURLWithoutFragment(contents->tab_contents()->GetURL()); // Reset touch icon if the url are different. if (existing_tab_url != page_url) { touch_tab->set_touch_icon(SkBitmap()); consumer_.CancelAllRequestsForClientData(touch_tab); } } } // Always call parent's method. BrowserTabStripController::TabChangedAt(contents, model_index, change_type); } void TouchTabStripController::SetTabRendererDataFromModel( TabContents* contents, int model_index, TabRendererData* data, TabStatus tab_status) { // Call parent first. BrowserTabStripController::SetTabRendererDataFromModel(contents, model_index, data, tab_status); if (tab_status == NEW_TAB) return; // Use the touch icon if any. TouchTab* touch_tab = tabstrip()->GetTouchTabAtModelIndex(model_index); if (!touch_tab->touch_icon().isNull()) { data->favicon = touch_tab->touch_icon(); return; } // In the case where we do not have a touch icon we scale up the small // favicons (16x16) which originally are coming from NavigationEntry. if (data->favicon.width() == kFaviconSize && data->favicon.height() == kFaviconSize) { data->favicon = skia::ImageOperations::Resize(data->favicon, skia::ImageOperations::RESIZE_BEST, TouchTab::kTouchTargetIconSize, TouchTab::kTouchTargetIconSize); } // Check if we have an outstanding request for this tab. if (consumer_.HasPendingRequests()) consumer_.CancelAllRequestsForClientData(touch_tab); // Request touch icon. GURL page_url = GetURLWithoutFragment(contents->GetURL()); FaviconService* favicon_service = profile()->GetFaviconService( Profile::EXPLICIT_ACCESS); if (favicon_service) { CancelableRequestProvider::Handle h = favicon_service->GetFaviconForURL( page_url, history::TOUCH_ICON | history::TOUCH_PRECOMPOSED_ICON, &consumer_, NewCallback(this, &TouchTabStripController::OnTouchIconAvailable)); consumer_.SetClientData(favicon_service, h, touch_tab); } } const TouchTabStrip* TouchTabStripController::tabstrip() const { return static_cast<const TouchTabStrip*>( BrowserTabStripController::tabstrip()); } void TouchTabStripController::OnTouchIconAvailable( FaviconService::Handle h, history::FaviconData favicon) { // Abandon the request when there is no valid favicon. if (!favicon.is_valid()) return; // Retrieve the model_index from the TouchTab pointer received. TouchTab* touch_tab = consumer_.GetClientDataForCurrentRequest(); int model_index = tabstrip()->GetModelIndexOfBaseTab(touch_tab); if (!IsValidIndex(model_index)) return; // Try to decode the favicon, return on failure. SkBitmap bitmap; gfx::PNGCodec::Decode(favicon.image_data->front(), favicon.image_data->size(), &bitmap); if (bitmap.isNull()) return; // Rescale output, if needed, and assign to the TouchTab instance. int width = bitmap.width(); int height = bitmap.height(); if (width == TouchTab::kTouchTargetIconSize && height == TouchTab::kTouchTargetIconSize) { touch_tab->set_touch_icon(bitmap); } else { CalcTouchIconTargetSize(&width, &height); touch_tab->set_touch_icon(skia::ImageOperations::Resize(bitmap, skia::ImageOperations::RESIZE_BEST, width, height)); } // Refresh UI since favicon changed. browser()->GetTabContentsAt(model_index)->NotifyNavigationStateChanged( TabContents::INVALIDATE_TAB); } <|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 <errno.h> #include <sys/file.h> #include "base/basictypes.h" #include "base/scoped_ptr.h" #include "chrome/browser/chromeos/external_metrics.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { // Need this because of the FRIEND_TEST class ExternalMetricsTest : public testing::Test { }; // Because the metrics service is not essential, errors will not cause the // program to terminate. However, the errors produce logs. #define MAXLENGTH ExternalMetrics::kMetricsMessageMaxLength static void SendMessage(const char* path, const char* name, const char* value) { int fd = open(path, O_CREAT | O_APPEND | O_WRONLY, 0666); int32 l = strlen(name) + strlen(value) + 2 + sizeof(l); write(fd, &l, sizeof(l)); write(fd, name, strlen(name) + 1); write(fd, value, strlen(value) + 1); close(fd); } static scoped_ptr<std::string> received_name; static scoped_ptr<std::string> received_value; int received_count = 0; static void ReceiveMessage(const char* name, const char* value) { received_name.reset(new std::string(name)); received_value.reset(new std::string(value)); received_count++; } static void CheckMessage(const char* name, const char* value, int count) { EXPECT_EQ(*received_name.get(), name); EXPECT_EQ(*received_value.get(), value); EXPECT_EQ(received_count, count); } TEST(ExternalMetricsTest, ParseExternalMetricsFile) { struct { const char* name; const char* value; } pairs[] = { {"BootTime", "9500"}, {"BootTime", "10000"}, {"BootTime", "9200"}, {"TabOverviewExitMouse", ""}, {"ConnmanIdle", "1000"}, {"ConnmanIdle", "1200"}, {"TabOverviewKeystroke", ""}, {"ConnmanDisconnect", "1000"}, {"ConnmanFailure", "1000"}, {"ConnmanFailure", "1300"}, {"ConnmanAssociation", "1000"}, {"ConnmanConfiguration", "1000"}, {"ConnmanOffline", "1000"}, {"ConnmanOnline", "1000"}, {"ConnmanOffline", "2000"}, {"ConnmanReady", "33000"}, {"ConnmanReady", "44000"}, {"ConnmanReady", "22000"}, }; int npairs = ARRAYSIZE_UNSAFE(pairs); int32 i; const char* path = "/tmp/.chromeos-metrics"; scoped_refptr<chromeos::ExternalMetrics> external_metrics(new chromeos::ExternalMetrics()); external_metrics->SetRecorder(&ReceiveMessage); EXPECT_TRUE(unlink(path) == 0 || errno == ENOENT); // Sends a few valid messages. Once in a while, collect them and check the // last message. We don't want to check every single message because we also // want to test the ability to deal with a file containing more than one // message. for (i = 0; i < npairs; i++) { SendMessage(path, pairs[i].name, pairs[i].value); if (i % 3 == 2) { external_metrics->CollectEvents(); CheckMessage(pairs[i].name, pairs[i].value, i + 1); } } // Sends a message that's too large. char b[MAXLENGTH + 100]; for (i = 0; i < MAXLENGTH + 99; i++) { b[i] = 'x'; } b[i] = '\0'; SendMessage(path, b, "yyy"); external_metrics->CollectEvents(); EXPECT_EQ(received_count, npairs); // Sends a malformed message (first string is not null-terminated). i = 100 + sizeof(i); int fd = open(path, O_CREAT | O_WRONLY); EXPECT_GT(fd, 0); EXPECT_EQ(write(fd, &i, sizeof(i)), static_cast<int>(sizeof(i))); EXPECT_EQ(write(fd, b, i), i); EXPECT_EQ(close(fd), 0); external_metrics->CollectEvents(); EXPECT_EQ(received_count, npairs); // Sends a malformed message (second string is not null-terminated). b[50] = '\0'; fd = open(path, O_CREAT | O_WRONLY); EXPECT_GT(fd, 0); EXPECT_EQ(write(fd, &i, sizeof(i)), static_cast<int>(sizeof(i))); EXPECT_EQ(write(fd, b, i), i); EXPECT_EQ(close(fd), 0); external_metrics->CollectEvents(); EXPECT_EQ(received_count, npairs); // Checks that we survive when file doesn't exist. EXPECT_EQ(unlink(path), 0); external_metrics->CollectEvents(); EXPECT_EQ(received_count, npairs); } } // namespace chromeos <commit_msg>Fix compile error : " error: open with O_CREAT in second argument needs 3 arguments"<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 <errno.h> #include <sys/file.h> #include "base/basictypes.h" #include "base/scoped_ptr.h" #include "chrome/browser/chromeos/external_metrics.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { // Need this because of the FRIEND_TEST class ExternalMetricsTest : public testing::Test { }; // Because the metrics service is not essential, errors will not cause the // program to terminate. However, the errors produce logs. #define MAXLENGTH ExternalMetrics::kMetricsMessageMaxLength static void SendMessage(const char* path, const char* name, const char* value) { int fd = open(path, O_CREAT | O_APPEND | O_WRONLY, 0666); int32 l = strlen(name) + strlen(value) + 2 + sizeof(l); write(fd, &l, sizeof(l)); write(fd, name, strlen(name) + 1); write(fd, value, strlen(value) + 1); close(fd); } static scoped_ptr<std::string> received_name; static scoped_ptr<std::string> received_value; int received_count = 0; static void ReceiveMessage(const char* name, const char* value) { received_name.reset(new std::string(name)); received_value.reset(new std::string(value)); received_count++; } static void CheckMessage(const char* name, const char* value, int count) { EXPECT_EQ(*received_name.get(), name); EXPECT_EQ(*received_value.get(), value); EXPECT_EQ(received_count, count); } TEST(ExternalMetricsTest, ParseExternalMetricsFile) { struct { const char* name; const char* value; } pairs[] = { {"BootTime", "9500"}, {"BootTime", "10000"}, {"BootTime", "9200"}, {"TabOverviewExitMouse", ""}, {"ConnmanIdle", "1000"}, {"ConnmanIdle", "1200"}, {"TabOverviewKeystroke", ""}, {"ConnmanDisconnect", "1000"}, {"ConnmanFailure", "1000"}, {"ConnmanFailure", "1300"}, {"ConnmanAssociation", "1000"}, {"ConnmanConfiguration", "1000"}, {"ConnmanOffline", "1000"}, {"ConnmanOnline", "1000"}, {"ConnmanOffline", "2000"}, {"ConnmanReady", "33000"}, {"ConnmanReady", "44000"}, {"ConnmanReady", "22000"}, }; int npairs = ARRAYSIZE_UNSAFE(pairs); int32 i; const char* path = "/tmp/.chromeos-metrics"; scoped_refptr<chromeos::ExternalMetrics> external_metrics(new chromeos::ExternalMetrics()); external_metrics->SetRecorder(&ReceiveMessage); EXPECT_TRUE(unlink(path) == 0 || errno == ENOENT); // Sends a few valid messages. Once in a while, collect them and check the // last message. We don't want to check every single message because we also // want to test the ability to deal with a file containing more than one // message. for (i = 0; i < npairs; i++) { SendMessage(path, pairs[i].name, pairs[i].value); if (i % 3 == 2) { external_metrics->CollectEvents(); CheckMessage(pairs[i].name, pairs[i].value, i + 1); } } // Sends a message that's too large. char b[MAXLENGTH + 100]; for (i = 0; i < MAXLENGTH + 99; i++) { b[i] = 'x'; } b[i] = '\0'; SendMessage(path, b, "yyy"); external_metrics->CollectEvents(); EXPECT_EQ(received_count, npairs); // Sends a malformed message (first string is not null-terminated). i = 100 + sizeof(i); int fd = open(path, O_CREAT | O_WRONLY, 0666); EXPECT_GT(fd, 0); EXPECT_EQ(write(fd, &i, sizeof(i)), static_cast<int>(sizeof(i))); EXPECT_EQ(write(fd, b, i), i); EXPECT_EQ(close(fd), 0); external_metrics->CollectEvents(); EXPECT_EQ(received_count, npairs); // Sends a malformed message (second string is not null-terminated). b[50] = '\0'; fd = open(path, O_CREAT | O_WRONLY, 0666); EXPECT_GT(fd, 0); EXPECT_EQ(write(fd, &i, sizeof(i)), static_cast<int>(sizeof(i))); EXPECT_EQ(write(fd, b, i), i); EXPECT_EQ(close(fd), 0); external_metrics->CollectEvents(); EXPECT_EQ(received_count, npairs); // Checks that we survive when file doesn't exist. EXPECT_EQ(unlink(path), 0); external_metrics->CollectEvents(); EXPECT_EQ(received_count, npairs); } } // namespace chromeos <|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/chromeos/gview_request_interceptor.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/url_request/url_request_job.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_redirect_job.h" #include "googleurl/src/gurl.h" namespace chromeos { // This is the list of mime types currently supported by the Google // Document Viewer. static const char* const supported_mime_type_list[] = { "application/pdf", "application/vnd.ms-powerpoint" }; static const char* const kGViewUrlPrefix = "http://docs.google.com/gview?url="; GViewRequestInterceptor::GViewRequestInterceptor() { URLRequest::RegisterRequestInterceptor(this); for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) { supported_mime_types_.insert(supported_mime_type_list[i]); } } GViewRequestInterceptor::~GViewRequestInterceptor() { URLRequest::UnregisterRequestInterceptor(this); } URLRequestJob* GViewRequestInterceptor::MaybeIntercept(URLRequest* request) { // Don't attempt to intercept here as we want to wait until the mime // type is fully determined. return NULL; } URLRequestJob* GViewRequestInterceptor::MaybeInterceptResponse( URLRequest* request) { // Do not intercept this request if it is a download. if (request->load_flags() & net::LOAD_IS_DOWNLOAD) { return NULL; } std::string mime_type; request->GetMimeType(&mime_type); // If supported, build the URL to the Google Document Viewer // including the origial document's URL, then create a new job that // will redirect the browser to this new URL. if (supported_mime_types_.count(mime_type) > 0) { std::string url(kGViewUrlPrefix); url += EscapePath(request->url().spec()); return new URLRequestRedirectJob(request, GURL(url)); } return NULL; } URLRequest::Interceptor* GViewRequestInterceptor::GetGViewRequestInterceptor() { return Singleton<GViewRequestInterceptor>::get(); } } // namespace chromeos <commit_msg>ChromeOS PDF handling: if the built-in PDF viewer plug-in is active, don't intercept PDF opening and forward to gView, but use the plug-in instead.<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/chromeos/gview_request_interceptor.h" #include "base/file_path.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/url_request/url_request_job.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_redirect_job.h" #include "googleurl/src/gurl.h" #include "webkit/glue/plugins/plugin_list.h" namespace chromeos { // The PDF mime type is treated special if the browser has a built-in // PDF viewer plug-in installed - we want to intercept only if we're // told to. static const char* const kPdfMimeType = "application/pdf"; // This is the list of mime types currently supported by the Google // Document Viewer. static const char* const supported_mime_type_list[] = { kPdfMimeType, "application/vnd.ms-powerpoint" }; static const char* const kGViewUrlPrefix = "http://docs.google.com/gview?url="; GViewRequestInterceptor::GViewRequestInterceptor() { URLRequest::RegisterRequestInterceptor(this); for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) { supported_mime_types_.insert(supported_mime_type_list[i]); } } GViewRequestInterceptor::~GViewRequestInterceptor() { URLRequest::UnregisterRequestInterceptor(this); } URLRequestJob* GViewRequestInterceptor::MaybeIntercept(URLRequest* request) { // Don't attempt to intercept here as we want to wait until the mime // type is fully determined. return NULL; } URLRequestJob* GViewRequestInterceptor::MaybeInterceptResponse( URLRequest* request) { // Do not intercept this request if it is a download. if (request->load_flags() & net::LOAD_IS_DOWNLOAD) { return NULL; } std::string mime_type; request->GetMimeType(&mime_type); // If the local PDF viewing plug-in is installed and enabled, don't // redirect PDF files to Google Document Viewer. if (mime_type == kPdfMimeType) { FilePath pdf_path; WebPluginInfo info; PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path); if (NPAPI::PluginList::Singleton()->GetPluginInfoByPath(pdf_path, &info) && info.enabled) return NULL; } // If supported, build the URL to the Google Document Viewer // including the origial document's URL, then create a new job that // will redirect the browser to this new URL. if (supported_mime_types_.count(mime_type) > 0) { std::string url(kGViewUrlPrefix); url += EscapePath(request->url().spec()); return new URLRequestRedirectJob(request, GURL(url)); } return NULL; } URLRequest::Interceptor* GViewRequestInterceptor::GetGViewRequestInterceptor() { return Singleton<GViewRequestInterceptor>::get(); } } // namespace chromeos <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // ycsb_workload.cpp // // Identification: src/main/ycsb/ycsb_workload.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <string> #include <unordered_map> #include <vector> #include <chrono> #include <iostream> #include <ctime> #include <thread> #include <algorithm> #include <random> #include <cstddef> #include <limits> #include "benchmark/ycsb/ycsb_workload.h" #include "benchmark/ycsb/ycsb_configuration.h" #include "benchmark/ycsb/ycsb_loader.h" #include "catalog/manager.h" #include "catalog/schema.h" #include "common/types.h" #include "common/value.h" #include "common/value_factory.h" #include "common/logger.h" #include "common/timer.h" #include "common/generator.h" #include "common/platform.h" #include "concurrency/transaction.h" #include "concurrency/transaction_manager_factory.h" #include "executor/executor_context.h" #include "executor/abstract_executor.h" #include "executor/logical_tile.h" #include "executor/logical_tile_factory.h" #include "executor/materialization_executor.h" #include "executor/update_executor.h" #include "executor/index_scan_executor.h" #include "expression/abstract_expression.h" #include "expression/constant_value_expression.h" #include "expression/tuple_value_expression.h" #include "expression/comparison_expression.h" #include "expression/expression_util.h" #include "index/index_factory.h" #include "logging/log_manager.h" #include "planner/abstract_plan.h" #include "planner/materialization_plan.h" #include "planner/insert_plan.h" #include "planner/update_plan.h" #include "planner/index_scan_plan.h" #include "storage/data_table.h" #include "storage/table_factory.h" namespace peloton { namespace benchmark { namespace ycsb { ///////////////////////////// ///// Random Generator ////// ///////////////////////////// // Fast random number generator class fast_random { public: fast_random(unsigned long seed) : seed(0) { set_seed0(seed); } inline unsigned long next() { return ((unsigned long)next(32) << 32) + next(32); } inline uint32_t next_u32() { return next(32); } inline uint16_t next_u16() { return (uint16_t)next(16); } /** [0.0, 1.0) */ inline double next_uniform() { return (((unsigned long)next(26) << 27) + next(27)) / (double)(1L << 53); } inline char next_char() { return next(8) % 256; } inline char next_readable_char() { static const char readables[] = "0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; return readables[next(6)]; } inline std::string next_string(size_t len) { std::string s(len, 0); for (size_t i = 0; i < len; i++) s[i] = next_char(); return s; } inline std::string next_readable_string(size_t len) { std::string s(len, 0); for (size_t i = 0; i < len; i++) s[i] = next_readable_char(); return s; } inline unsigned long get_seed() { return seed; } inline void set_seed(unsigned long seed) { this->seed = seed; } private: inline void set_seed0(unsigned long seed) { this->seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1); } inline unsigned long next(unsigned int bits) { seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); return (unsigned long)(seed >> (48 - bits)); } unsigned long seed; }; class ZipfDistribution { public: ZipfDistribution(const uint64_t &n, const double &theta) : rand_generator(rand()) { // range: 1-n the_n = n; zipf_theta = theta; zeta_2_theta = zeta(2, zipf_theta); denom = zeta(the_n, zipf_theta); } double zeta(uint64_t n, double theta) { double sum = 0; for (uint64_t i = 1; i <= n; i++) sum += pow(1.0 / i, theta); return sum; } int GenerateInteger(const int &min, const int &max) { return rand_generator.next() % (max - min + 1) + min; } uint64_t GetNextNumber() { double alpha = 1 / (1 - zipf_theta); double zetan = denom; double eta = (1 - pow(2.0 / the_n, 1 - zipf_theta)) / (1 - zeta_2_theta / zetan); double u = (double)(GenerateInteger(1, 10000000) % 10000000) / 10000000; double uz = u * zetan; if (uz < 1) return 1; if (uz < 1 + pow(0.5, zipf_theta)) return 2; return 1 + (uint64_t)(the_n * pow(eta * u - eta + 1, alpha)); } uint64_t the_n; double zipf_theta; double denom; double zeta_2_theta; fast_random rand_generator; }; ///////////////////////////////////////////////////////// // TRANSACTION TYPES ///////////////////////////////////////////////////////// bool RunRead(ZipfDistribution &zipf); bool RunInsert(ZipfDistribution &zipf, oid_t next_insert_key); ///////////////////////////////////////////////////////// // WORKLOAD ///////////////////////////////////////////////////////// // Used to control backend execution volatile bool run_backends = true; // Committed transaction counts std::vector<double> transaction_counts; void RunBackend(oid_t thread_id) { auto update_ratio = state.update_ratio; // Set zipfian skew auto zipf_theta = 0.0; if (state.skew_factor == SKEW_FACTOR_HIGH) { zipf_theta = 0.5; } fast_random rng(rand()); ZipfDistribution zipf((state.scale_factor * DEFAULT_TUPLES_PER_TILEGROUP) - 1, zipf_theta); auto committed_transaction_count = 0; // Partition the domain across backends auto insert_key_offset = state.scale_factor * DEFAULT_TUPLES_PER_TILEGROUP; auto next_insert_key = insert_key_offset + thread_id + 1; // Run these many transactions while (true) { // Check if the backend should stop if (run_backends == false) { break; } auto rng_val = rng.next_uniform(); auto transaction_status = false; // Run transaction if (rng_val < update_ratio) { next_insert_key += state.backend_count; transaction_status = RunInsert(zipf, next_insert_key); } else { transaction_status = RunRead(zipf); } // Update transaction count if it committed if (transaction_status == true) { committed_transaction_count++; } } // Set committed_transaction_count transaction_counts[thread_id] = committed_transaction_count; } void RunWorkload() { // Execute the workload to build the log std::vector<std::thread> thread_group; oid_t num_threads = state.backend_count; transaction_counts.resize(num_threads); // Launch a group of threads for (oid_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) { thread_group.push_back(std::move(std::thread(RunBackend, thread_itr))); } // Sleep for duration specified by user and then stop the backends auto sleep_period = std::chrono::milliseconds(state.duration); std::this_thread::sleep_for(sleep_period); run_backends = false; // Join the threads with the main thread for (oid_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) { thread_group[thread_itr].join(); } // Compute total committed transactions auto sum_transaction_count = 0; for (auto transaction_count : transaction_counts) { sum_transaction_count += transaction_count; } // Compute average throughput and latency state.throughput = (sum_transaction_count * 1000) / state.duration; state.latency = state.backend_count / state.throughput; } ///////////////////////////////////////////////////////// // HARNESS ///////////////////////////////////////////////////////// static void ExecuteTest(std::vector<executor::AbstractExecutor *> &executors) { bool status = false; // Run all the executors for (auto executor : executors) { status = executor->Init(); if (status == false) { throw Exception("Init failed"); } std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles; // Execute stuff while (executor->Execute() == true) { std::unique_ptr<executor::LogicalTile> result_tile(executor->GetOutput()); result_tiles.emplace_back(result_tile.release()); } } } static bool EndTransaction(concurrency::Transaction *txn) { auto result = txn->GetResult(); auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); // transaction passed execution. if (result == Result::RESULT_SUCCESS) { result = txn_manager.CommitTransaction(); if (result == Result::RESULT_SUCCESS) { // transaction committed return true; } else { // transaction aborted or failed PL_ASSERT(result == Result::RESULT_ABORTED || result == Result::RESULT_FAILURE); return false; } } // transaction aborted during execution. else { PL_ASSERT(result == Result::RESULT_ABORTED || result == Result::RESULT_FAILURE); result = txn_manager.AbortTransaction(); return false; } } ///////////////////////////////////////////////////////// // TRANSACTIONS ///////////////////////////////////////////////////////// bool RunRead(ZipfDistribution &zipf) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); ///////////////////////////////////////////////////////// // INDEX SCAN + PREDICATE ///////////////////////////////////////////////////////// std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); // Column ids to be added to logical tile after scan. std::vector<oid_t> column_ids; oid_t column_count = state.column_count + 1; for (oid_t col_itr = 0; col_itr < column_count; col_itr++) { column_ids.push_back(col_itr); } // Create and set up index scan executor std::vector<oid_t> key_column_ids; std::vector<ExpressionType> expr_types; std::vector<Value> values; std::vector<expression::AbstractExpression *> runtime_keys; auto lookup_key = zipf.GetNextNumber(); key_column_ids.push_back(0); expr_types.push_back(ExpressionType::EXPRESSION_TYPE_COMPARE_EQUAL); values.push_back(ValueFactory::GetIntegerValue(lookup_key)); auto ycsb_pkey_index = user_table->GetIndexWithOid(user_table_pkey_index_oid); planner::IndexScanPlan::IndexScanDesc index_scan_desc( ycsb_pkey_index, key_column_ids, expr_types, values, runtime_keys); // Create plan node. auto predicate = nullptr; planner::IndexScanPlan index_scan_node(user_table, predicate, column_ids, index_scan_desc); // Run the executor executor::IndexScanExecutor index_scan_executor(&index_scan_node, context.get()); ///////////////////////////////////////////////////////// // MATERIALIZE ///////////////////////////////////////////////////////// // Create and set up materialization executor bool physify_flag = true; // is going to create a physical tile planner::MaterializationPlan mat_node(physify_flag); executor::MaterializationExecutor mat_executor(&mat_node, nullptr); mat_executor.AddChild(&index_scan_executor); ///////////////////////////////////////////////////////// // EXECUTE ///////////////////////////////////////////////////////// std::vector<executor::AbstractExecutor *> executors; executors.push_back(&mat_executor); ExecuteTest(executors); auto txn_status = EndTransaction(txn); return txn_status; } bool RunInsert(UNUSED_ATTRIBUTE ZipfDistribution &zipf, oid_t next_insert_key) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); const oid_t col_count = state.column_count + 1; auto table_schema = user_table->GetSchema(); const bool allocate = true; std::string field_raw_value(ycsb_field_length - 1, 'o'); std::unique_ptr<VarlenPool> pool(new VarlenPool(BACKEND_TYPE_MM)); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); ///////////////////////////////////////////////////////// // INSERT ///////////////////////////////////////////////////////// std::unique_ptr<storage::Tuple> tuple( new storage::Tuple(table_schema, allocate)); auto key_value = ValueFactory::GetIntegerValue(next_insert_key); auto field_value = ValueFactory::GetStringValue(field_raw_value); tuple->SetValue(0, key_value, nullptr); for (oid_t col_itr = 1; col_itr < col_count; col_itr++) { tuple->SetValue(col_itr, field_value, pool.get()); } planner::InsertPlan insert_node(user_table, std::move(tuple)); executor::InsertExecutor insert_executor(&insert_node, context.get()); ///////////////////////////////////////////////////////// // EXECUTE ///////////////////////////////////////////////////////// std::vector<executor::AbstractExecutor *> executors; executors.push_back(&insert_executor); ExecuteTest(executors); auto txn_status = EndTransaction(txn); return txn_status; } } // namespace ycsb } // namespace benchmark } // namespace peloton <commit_msg>Refactoring read<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // ycsb_workload.cpp // // Identification: src/main/ycsb/ycsb_workload.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <string> #include <unordered_map> #include <vector> #include <chrono> #include <iostream> #include <ctime> #include <thread> #include <algorithm> #include <random> #include <cstddef> #include <limits> #include "benchmark/ycsb/ycsb_workload.h" #include "benchmark/ycsb/ycsb_configuration.h" #include "benchmark/ycsb/ycsb_loader.h" #include "catalog/manager.h" #include "catalog/schema.h" #include "common/types.h" #include "common/value.h" #include "common/value_factory.h" #include "common/logger.h" #include "common/timer.h" #include "common/generator.h" #include "common/platform.h" #include "concurrency/transaction.h" #include "concurrency/transaction_manager_factory.h" #include "executor/executor_context.h" #include "executor/abstract_executor.h" #include "executor/logical_tile.h" #include "executor/logical_tile_factory.h" #include "executor/materialization_executor.h" #include "executor/update_executor.h" #include "executor/index_scan_executor.h" #include "expression/abstract_expression.h" #include "expression/constant_value_expression.h" #include "expression/tuple_value_expression.h" #include "expression/comparison_expression.h" #include "expression/expression_util.h" #include "index/index_factory.h" #include "logging/log_manager.h" #include "planner/abstract_plan.h" #include "planner/materialization_plan.h" #include "planner/insert_plan.h" #include "planner/update_plan.h" #include "planner/index_scan_plan.h" #include "storage/data_table.h" #include "storage/table_factory.h" namespace peloton { namespace benchmark { namespace ycsb { ///////////////////////////// ///// Random Generator ////// ///////////////////////////// // Fast random number generator class fast_random { public: fast_random(unsigned long seed) : seed(0) { set_seed0(seed); } inline unsigned long next() { return ((unsigned long)next(32) << 32) + next(32); } inline uint32_t next_u32() { return next(32); } inline uint16_t next_u16() { return (uint16_t)next(16); } /** [0.0, 1.0) */ inline double next_uniform() { return (((unsigned long)next(26) << 27) + next(27)) / (double)(1L << 53); } inline char next_char() { return next(8) % 256; } inline char next_readable_char() { static const char readables[] = "0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; return readables[next(6)]; } inline std::string next_string(size_t len) { std::string s(len, 0); for (size_t i = 0; i < len; i++) s[i] = next_char(); return s; } inline std::string next_readable_string(size_t len) { std::string s(len, 0); for (size_t i = 0; i < len; i++) s[i] = next_readable_char(); return s; } inline unsigned long get_seed() { return seed; } inline void set_seed(unsigned long seed) { this->seed = seed; } private: inline void set_seed0(unsigned long seed) { this->seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1); } inline unsigned long next(unsigned int bits) { seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); return (unsigned long)(seed >> (48 - bits)); } unsigned long seed; }; class ZipfDistribution { public: ZipfDistribution(const uint64_t &n, const double &theta) : rand_generator(rand()) { // range: 1-n the_n = n; zipf_theta = theta; zeta_2_theta = zeta(2, zipf_theta); denom = zeta(the_n, zipf_theta); } double zeta(uint64_t n, double theta) { double sum = 0; for (uint64_t i = 1; i <= n; i++) sum += pow(1.0 / i, theta); return sum; } int GenerateInteger(const int &min, const int &max) { return rand_generator.next() % (max - min + 1) + min; } uint64_t GetNextNumber() { double alpha = 1 / (1 - zipf_theta); double zetan = denom; double eta = (1 - pow(2.0 / the_n, 1 - zipf_theta)) / (1 - zeta_2_theta / zetan); double u = (double)(GenerateInteger(1, 10000000) % 10000000) / 10000000; double uz = u * zetan; if (uz < 1) return 1; if (uz < 1 + pow(0.5, zipf_theta)) return 2; return 1 + (uint64_t)(the_n * pow(eta * u - eta + 1, alpha)); } uint64_t the_n; double zipf_theta; double denom; double zeta_2_theta; fast_random rand_generator; }; ///////////////////////////////////////////////////////// // TRANSACTION TYPES ///////////////////////////////////////////////////////// bool RunRead(ZipfDistribution &zipf); bool RunInsert(ZipfDistribution &zipf, oid_t next_insert_key); ///////////////////////////////////////////////////////// // WORKLOAD ///////////////////////////////////////////////////////// // Used to control backend execution volatile bool run_backends = true; // Committed transaction counts std::vector<double> transaction_counts; void RunBackend(oid_t thread_id) { auto update_ratio = state.update_ratio; // Set zipfian skew auto zipf_theta = 0.0; if (state.skew_factor == SKEW_FACTOR_HIGH) { zipf_theta = 0.5; } fast_random rng(rand()); ZipfDistribution zipf((state.scale_factor * DEFAULT_TUPLES_PER_TILEGROUP) - 1, zipf_theta); auto committed_transaction_count = 0; // Partition the domain across backends auto insert_key_offset = state.scale_factor * DEFAULT_TUPLES_PER_TILEGROUP; auto next_insert_key = insert_key_offset + thread_id + 1; // Run these many transactions while (true) { // Check if the backend should stop if (run_backends == false) { break; } auto rng_val = rng.next_uniform(); auto transaction_status = false; // Run transaction if (rng_val < update_ratio) { next_insert_key += state.backend_count; transaction_status = RunInsert(zipf, next_insert_key); } else { transaction_status = RunRead(zipf); } // Update transaction count if it committed if (transaction_status == true) { committed_transaction_count++; } } // Set committed_transaction_count transaction_counts[thread_id] = committed_transaction_count; } void RunWorkload() { // Execute the workload to build the log std::vector<std::thread> thread_group; oid_t num_threads = state.backend_count; transaction_counts.resize(num_threads); // Launch a group of threads for (oid_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) { thread_group.push_back(std::move(std::thread(RunBackend, thread_itr))); } // Sleep for duration specified by user and then stop the backends auto sleep_period = std::chrono::milliseconds(state.duration); std::this_thread::sleep_for(sleep_period); run_backends = false; // Join the threads with the main thread for (oid_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) { thread_group[thread_itr].join(); } // Compute total committed transactions auto sum_transaction_count = 0; for (auto transaction_count : transaction_counts) { sum_transaction_count += transaction_count; } // Compute average throughput and latency state.throughput = (sum_transaction_count * 1000) / state.duration; state.latency = state.backend_count / state.throughput; } ///////////////////////////////////////////////////////// // HARNESS ///////////////////////////////////////////////////////// static void ExecuteTest(std::vector<executor::AbstractExecutor *> &executors) { bool status = false; // Run all the executors for (auto executor : executors) { status = executor->Init(); if (status == false) { throw Exception("Init failed"); } std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles; // Execute stuff while (executor->Execute() == true) { std::unique_ptr<executor::LogicalTile> result_tile(executor->GetOutput()); result_tiles.emplace_back(result_tile.release()); } } } static bool EndTransaction(concurrency::Transaction *txn) { auto result = txn->GetResult(); auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); // transaction passed execution. if (result == Result::RESULT_SUCCESS) { result = txn_manager.CommitTransaction(); if (result == Result::RESULT_SUCCESS) { // transaction committed return true; } else { // transaction aborted or failed PL_ASSERT(result == Result::RESULT_ABORTED || result == Result::RESULT_FAILURE); return false; } } // transaction aborted during execution. else { PL_ASSERT(result == Result::RESULT_ABORTED || result == Result::RESULT_FAILURE); result = txn_manager.AbortTransaction(); return false; } } planner::AbstractPlan *read_plan = nullptr; const planner::AbstractPlan *GetReadPlanNode(ZipfDistribution &zipf){ if(read_plan != nullptr) { return read_plan; } // Column ids to be added to logical tile after scan. std::vector<oid_t> column_ids; oid_t column_count = state.column_count + 1; for (oid_t col_itr = 0; col_itr < column_count; col_itr++) { column_ids.push_back(col_itr); } // Create and set up index scan executor std::vector<oid_t> key_column_ids; std::vector<ExpressionType> expr_types; std::vector<Value> values; std::vector<expression::AbstractExpression *> runtime_keys; auto lookup_key = zipf.GetNextNumber(); key_column_ids.push_back(0); expr_types.push_back(ExpressionType::EXPRESSION_TYPE_COMPARE_EQUAL); values.push_back(ValueFactory::GetIntegerValue(lookup_key)); auto ycsb_pkey_index = user_table->GetIndexWithOid(user_table_pkey_index_oid); planner::IndexScanPlan::IndexScanDesc index_scan_desc( ycsb_pkey_index, key_column_ids, expr_types, values, runtime_keys); // Create plan node. auto predicate = nullptr; read_plan = new planner::IndexScanPlan(user_table, predicate, column_ids, index_scan_desc); return read_plan; } ///////////////////////////////////////////////////////// // TRANSACTIONS ///////////////////////////////////////////////////////// bool RunRead(ZipfDistribution &zipf) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); ///////////////////////////////////////////////////////// // INDEX SCAN + PREDICATE ///////////////////////////////////////////////////////// std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); auto index_scan_node = GetReadPlanNode(zipf); // Run the executor executor::IndexScanExecutor index_scan_executor(index_scan_node, context.get()); ///////////////////////////////////////////////////////// // MATERIALIZE ///////////////////////////////////////////////////////// // Create and set up materialization executor bool physify_flag = true; // is going to create a physical tile planner::MaterializationPlan mat_node(physify_flag); executor::MaterializationExecutor mat_executor(&mat_node, nullptr); mat_executor.AddChild(&index_scan_executor); ///////////////////////////////////////////////////////// // EXECUTE ///////////////////////////////////////////////////////// std::vector<executor::AbstractExecutor *> executors; executors.push_back(&mat_executor); ExecuteTest(executors); auto txn_status = EndTransaction(txn); return txn_status; } bool RunInsert(UNUSED_ATTRIBUTE ZipfDistribution &zipf, oid_t next_insert_key) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); const oid_t col_count = state.column_count + 1; auto table_schema = user_table->GetSchema(); const bool allocate = true; std::string field_raw_value(ycsb_field_length - 1, 'o'); std::unique_ptr<VarlenPool> pool(new VarlenPool(BACKEND_TYPE_MM)); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); ///////////////////////////////////////////////////////// // INSERT ///////////////////////////////////////////////////////// std::unique_ptr<storage::Tuple> tuple( new storage::Tuple(table_schema, allocate)); auto key_value = ValueFactory::GetIntegerValue(next_insert_key); auto field_value = ValueFactory::GetStringValue(field_raw_value); tuple->SetValue(0, key_value, nullptr); for (oid_t col_itr = 1; col_itr < col_count; col_itr++) { tuple->SetValue(col_itr, field_value, pool.get()); } planner::InsertPlan insert_node(user_table, std::move(tuple)); executor::InsertExecutor insert_executor(&insert_node, context.get()); ///////////////////////////////////////////////////////// // EXECUTE ///////////////////////////////////////////////////////// std::vector<executor::AbstractExecutor *> executors; executors.push_back(&insert_executor); ExecuteTest(executors); auto txn_status = EndTransaction(txn); return txn_status; } } // namespace ycsb } // namespace benchmark } // namespace peloton <|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/string16.h" #include "base/utf_string_conversions.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/automation_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Navigate to the settings tab and block until complete. const GURL& url = GURL(chrome::kChromeUISettingsURL); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURLBlockUntilNavigationsComplete(url, 1)) << url.spec(); // Verify that the page title is correct. // The only guarantee we can make about the title of a settings tab is that // it should contain IDS_SETTINGS_TITLE somewhere. std::wstring title; EXPECT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); EXPECT_NE(WideToUTF16Hack(title).find(expected_title), string16::npos); // Check navbar's existence. bool navbar_exist = false; EXPECT_TRUE(tab->ExecuteAndExtractBool(L"", L"domAutomationController.send(" L"!!document.getElementById('navbar'))", &navbar_exist)); EXPECT_EQ(true, navbar_exist); // Check section headers in navbar. // For ChromeOS, there should be 1 + 7: // Search, Basics, Personal, System, Internet, Under the Hood, // Users and Extensions. // For other platforms, there should 1 + 4: // Search, Basics, Personal, Under the Hood and Extensions. #if defined(OS_CHROMEOS) const int kExpectedSections = 1 + 7; #else const int kExpectedSections = 1 + 4; #endif int num_of_sections = 0; EXPECT_TRUE(tab->ExecuteAndExtractInt(L"", L"domAutomationController.send(" L"document.getElementById('navbar').children.length)", &num_of_sections)); EXPECT_EQ(kExpectedSections, num_of_sections); } } // namespace <commit_msg>Revert 101845 - [dom-ui options] Inline helper functions for OptionsUITest.LoadOptionsByURL.<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/string16.h" #include "base/utf_string_conversions.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/automation_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); // The only guarantee we can make about the title of a settings tab is that // it should contain IDS_SETTINGS_TITLE somewhere. ASSERT_FALSE(WideToUTF16Hack(title).find(expected_title) == string16::npos); } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); NavigateToURL(GURL(chrome::kChromeUISettingsURL)); AssertIsOptionsPage(tab); // Check navbar's existence. bool navbar_exist = false; ASSERT_TRUE(tab->ExecuteAndExtractBool(L"", L"domAutomationController.send(" L"!!document.getElementById('navbar'))", &navbar_exist)); ASSERT_EQ(true, navbar_exist); // Check section headers in navbar. // For ChromeOS, there should be 1 + 7: // Search, Basics, Personal, System, Internet, Under the Hood, // Users and Extensions. // For other platforms, there should 1 + 4: // Search, Basics, Personal, Under the Hood and Extensions. #if defined(OS_CHROMEOS) const int kExpectedSections = 1 + 7; #else const int kExpectedSections = 1 + 4; #endif int num_of_sections = 0; ASSERT_TRUE(tab->ExecuteAndExtractInt(L"", L"domAutomationController.send(" L"document.getElementById('navbar').children.length)", &num_of_sections)); ASSERT_EQ(kExpectedSections, num_of_sections); } } // namespace <|endoftext|>
<commit_before>#include "MessageBuilder.hpp" #include "Application.hpp" #include "common/LinkParser.hpp" #include "messages/Image.hpp" #include "messages/Message.hpp" #include "messages/MessageElement.hpp" #include "providers/LinkResolver.hpp" #include "providers/twitch/PubsubActions.hpp" #include "singletons/Emotes.hpp" #include "singletons/Resources.hpp" #include "singletons/Theme.hpp" #include "util/FormatTime.hpp" #include "util/IrcHelpers.hpp" #include <QDateTime> #include <QImageReader> namespace chatterino { MessagePtr makeSystemMessage(const QString &text) { return MessageBuilder(systemMessage, text).release(); } std::pair<MessagePtr, MessagePtr> makeAutomodMessage( const AutomodAction &action) { auto builder = MessageBuilder(); builder.emplace<TimestampElement>(); builder.message().flags.set(MessageFlag::PubSub); builder .emplace<ImageElement>( Image::fromPixmap(getApp()->resources->twitch.automod), MessageElementFlag::BadgeChannelAuthority) ->setTooltip("AutoMod"); builder.emplace<TextElement>("AutoMod:", MessageElementFlag::BoldUsername, MessageColor(QColor("blue")), FontStyle::ChatMediumBold); builder.emplace<TextElement>( "AutoMod:", MessageElementFlag::NonBoldUsername, MessageColor(QColor("blue"))); builder.emplace<TextElement>( ("Held a message for reason: " + action.reason + ". Allow will post it in chat. "), MessageElementFlag::Text, MessageColor::Text); builder .emplace<TextElement>("Allow", MessageElementFlag::Text, MessageColor(QColor("green")), FontStyle::ChatMediumBold) ->setLink({Link::AutoModAllow, action.msgID}); builder .emplace<TextElement>(" Deny", MessageElementFlag::Text, MessageColor(QColor("red")), FontStyle::ChatMediumBold) ->setLink({Link::AutoModDeny, action.msgID}); // builder.emplace<TextElement>(action.msgID, // MessageElementFlag::Text, // MessageColor::Text); builder.message().flags.set(MessageFlag::AutoMod); auto message1 = builder.release(); builder = MessageBuilder(); builder.emplace<TimestampElement>(); builder.message().flags.set(MessageFlag::PubSub); builder .emplace<TextElement>( action.target.name + ":", MessageElementFlag::BoldUsername, MessageColor(QColor("red")), FontStyle::ChatMediumBold) ->setLink({Link::UserInfo, action.target.name}); builder .emplace<TextElement>(action.target.name + ":", MessageElementFlag::NonBoldUsername, MessageColor(QColor("red"))) ->setLink({Link::UserInfo, action.target.name}); builder.emplace<TextElement>(action.message, MessageElementFlag::Text, MessageColor::Text); builder.message().flags.set(MessageFlag::AutoMod); auto message2 = builder.release(); return std::make_pair(message1, message2); } MessageBuilder::MessageBuilder() : message_(std::make_shared<Message>()) { } MessageBuilder::MessageBuilder(SystemMessageTag, const QString &text) : MessageBuilder() { this->emplace<TimestampElement>(); // check system message for links // (e.g. needed for sub ticket message in sub only mode) QStringList textFragments = text.split(QRegularExpression("\\s")); for (const auto &word : textFragments) { auto linkString = this->matchLink(word); if (linkString.isEmpty()) { this->emplace<TextElement>(word, MessageElementFlag::Text, MessageColor::System); } else { this->addLink(word, linkString); } } this->message().flags.set(MessageFlag::System); this->message().flags.set(MessageFlag::DoNotTriggerNotification); this->message().messageText = text; this->message().searchText = text; } MessageBuilder::MessageBuilder(TimeoutMessageTag, const QString &username, const QString &durationInSeconds, const QString &reason, bool multipleTimes) : MessageBuilder() { QString text; text.append(username); if (!durationInSeconds.isEmpty()) { text.append(" has been timed out"); // TODO: Implement who timed the user out text.append(" for "); bool ok = true; int timeoutSeconds = durationInSeconds.toInt(&ok); if (ok) { text.append(formatTime(timeoutSeconds)); } } else { text.append(" has been permanently banned"); } if (reason.length() > 0) { text.append(": \""); text.append(parseTagString(reason)); text.append("\""); } text.append("."); if (multipleTimes) { text.append(" (multiple times)"); } this->message().flags.set(MessageFlag::System); this->message().flags.set(MessageFlag::Timeout); this->message().flags.set(MessageFlag::DoNotTriggerNotification); this->message().timeoutUser = username; this->emplace<TimestampElement>(); this->emplace<TextElement>(text, MessageElementFlag::Text, MessageColor::System); this->message().messageText = text; this->message().searchText = text; } MessageBuilder::MessageBuilder(const BanAction &action, uint32_t count) : MessageBuilder() { this->emplace<TimestampElement>(); this->message().flags.set(MessageFlag::System); this->message().flags.set(MessageFlag::Timeout); this->message().timeoutUser = action.target.name; this->message().count = count; QString text; if (action.isBan()) { if (action.reason.isEmpty()) { text = QString("%1 banned %2.") // .arg(action.source.name) .arg(action.target.name); } else { text = QString("%1 banned %2: \"%3\".") // .arg(action.source.name) .arg(action.target.name) .arg(action.reason); } } else { if (action.reason.isEmpty()) { text = QString("%1 timed out %2 for %3.") // .arg(action.source.name) .arg(action.target.name) .arg(formatTime(action.duration)); } else { text = QString("%1 timed out %2 for %3: \"%4\".") // .arg(action.source.name) .arg(action.target.name) .arg(formatTime(action.duration)) .arg(action.reason); } if (count > 1) { text.append(QString(" (%1 times)").arg(count)); } } this->emplace<TextElement>(text, MessageElementFlag::Text, MessageColor::System); this->message().messageText = text; this->message().searchText = text; } MessageBuilder::MessageBuilder(const UnbanAction &action) : MessageBuilder() { this->emplace<TimestampElement>(); this->message().flags.set(MessageFlag::System); this->message().flags.set(MessageFlag::Untimeout); this->message().timeoutUser = action.target.name; QString text; if (action.wasBan()) { text = QString("%1 unbanned %2.") // .arg(action.source.name) .arg(action.target.name); } else { text = QString("%1 untimedout %2.") // .arg(action.source.name) .arg(action.target.name); } this->emplace<TextElement>(text, MessageElementFlag::Text, MessageColor::System); this->message().messageText = text; this->message().searchText = text; } MessageBuilder::MessageBuilder(const AutomodUserAction &action) : MessageBuilder() { this->emplace<TimestampElement>(); this->message().flags.set(MessageFlag::System); QString text; switch (action.type) { case AutomodUserAction::AddPermitted: { text = QString("%1 added %2 as a permitted term on AutoMod.") .arg(action.source.name) .arg(action.message); } break; case AutomodUserAction::AddBlocked: { text = QString("%1 added %2 as a blocked term on AutoMod.") .arg(action.source.name) .arg(action.message); } break; case AutomodUserAction::RemovePermitted: { text = QString("%1 removed %2 as a permitted term term on AutoMod.") .arg(action.source.name) .arg(action.message); } break; case AutomodUserAction::RemoveBlocked: { text = QString("%1 removed %2 as a blocked term on AutoMod.") .arg(action.source.name) .arg(action.message); } break; case AutomodUserAction::Properties: { text = QString("%1 modified the AutoMod properties.") .arg(action.source.name); } break; } this->emplace<TextElement>(text, MessageElementFlag::Text, MessageColor::System); } Message *MessageBuilder::operator->() { return this->message_.get(); } Message &MessageBuilder::message() { return *this->message_; } MessagePtr MessageBuilder::release() { std::shared_ptr<Message> ptr; this->message_.swap(ptr); return ptr; } std::weak_ptr<Message> MessageBuilder::weakOf() { return this->message_; } void MessageBuilder::append(std::unique_ptr<MessageElement> element) { this->message().elements.push_back(std::move(element)); } QString MessageBuilder::matchLink(const QString &string) { LinkParser linkParser(string); static QRegularExpression httpRegex( "\\bhttps?://", QRegularExpression::CaseInsensitiveOption); static QRegularExpression ftpRegex( "\\bftps?://", QRegularExpression::CaseInsensitiveOption); static QRegularExpression spotifyRegex( "\\bspotify:", QRegularExpression::CaseInsensitiveOption); if (!linkParser.hasMatch()) { return QString(); } QString captured = linkParser.getCaptured(); if (!captured.contains(httpRegex) && !captured.contains(ftpRegex) && !captured.contains(spotifyRegex)) { captured.insert(0, "http://"); } return captured; } void MessageBuilder::addLink(const QString &origLink, const QString &matchedLink) { static QRegularExpression domainRegex( R"(^(?:(?:ftp|http)s?:\/\/)?([^\/]+)(?:\/.*)?$)", QRegularExpression::CaseInsensitiveOption); QString lowercaseLinkString; auto match = domainRegex.match(origLink); if (match.isValid()) { lowercaseLinkString = origLink.mid(0, match.capturedStart(1)) + match.captured(1).toLower() + origLink.mid(match.capturedEnd(1)); } else { lowercaseLinkString = origLink; } auto linkElement = Link(Link::Url, matchedLink); auto textColor = MessageColor(MessageColor::Link); auto linkMELowercase = this->emplace<TextElement>(lowercaseLinkString, MessageElementFlag::LowercaseLink, textColor) ->setLink(linkElement); auto linkMEOriginal = this->emplace<TextElement>(origLink, MessageElementFlag::OriginalLink, textColor) ->setLink(linkElement); LinkResolver::getLinkInfo(matchedLink, [weakMessage = this->weakOf(), linkMELowercase, linkMEOriginal, matchedLink](QString tooltipText, Link originalLink) { auto shared = weakMessage.lock(); if (!shared) { return; } if (!tooltipText.isEmpty()) { linkMELowercase->setTooltip(tooltipText); linkMEOriginal->setTooltip(tooltipText); } if (originalLink.value != matchedLink && !originalLink.value.isEmpty()) { linkMELowercase->setLink(originalLink)->updateLink(); linkMEOriginal->setLink(originalLink)->updateLink(); } }); } } // namespace chatterino <commit_msg>changed some variables to const<commit_after>#include "MessageBuilder.hpp" #include "Application.hpp" #include "common/LinkParser.hpp" #include "messages/Image.hpp" #include "messages/Message.hpp" #include "messages/MessageElement.hpp" #include "providers/LinkResolver.hpp" #include "providers/twitch/PubsubActions.hpp" #include "singletons/Emotes.hpp" #include "singletons/Resources.hpp" #include "singletons/Theme.hpp" #include "util/FormatTime.hpp" #include "util/IrcHelpers.hpp" #include <QDateTime> #include <QImageReader> namespace chatterino { MessagePtr makeSystemMessage(const QString &text) { return MessageBuilder(systemMessage, text).release(); } std::pair<MessagePtr, MessagePtr> makeAutomodMessage( const AutomodAction &action) { auto builder = MessageBuilder(); builder.emplace<TimestampElement>(); builder.message().flags.set(MessageFlag::PubSub); builder .emplace<ImageElement>( Image::fromPixmap(getApp()->resources->twitch.automod), MessageElementFlag::BadgeChannelAuthority) ->setTooltip("AutoMod"); builder.emplace<TextElement>("AutoMod:", MessageElementFlag::BoldUsername, MessageColor(QColor("blue")), FontStyle::ChatMediumBold); builder.emplace<TextElement>( "AutoMod:", MessageElementFlag::NonBoldUsername, MessageColor(QColor("blue"))); builder.emplace<TextElement>( ("Held a message for reason: " + action.reason + ". Allow will post it in chat. "), MessageElementFlag::Text, MessageColor::Text); builder .emplace<TextElement>("Allow", MessageElementFlag::Text, MessageColor(QColor("green")), FontStyle::ChatMediumBold) ->setLink({Link::AutoModAllow, action.msgID}); builder .emplace<TextElement>(" Deny", MessageElementFlag::Text, MessageColor(QColor("red")), FontStyle::ChatMediumBold) ->setLink({Link::AutoModDeny, action.msgID}); // builder.emplace<TextElement>(action.msgID, // MessageElementFlag::Text, // MessageColor::Text); builder.message().flags.set(MessageFlag::AutoMod); auto message1 = builder.release(); builder = MessageBuilder(); builder.emplace<TimestampElement>(); builder.message().flags.set(MessageFlag::PubSub); builder .emplace<TextElement>( action.target.name + ":", MessageElementFlag::BoldUsername, MessageColor(QColor("red")), FontStyle::ChatMediumBold) ->setLink({Link::UserInfo, action.target.name}); builder .emplace<TextElement>(action.target.name + ":", MessageElementFlag::NonBoldUsername, MessageColor(QColor("red"))) ->setLink({Link::UserInfo, action.target.name}); builder.emplace<TextElement>(action.message, MessageElementFlag::Text, MessageColor::Text); builder.message().flags.set(MessageFlag::AutoMod); auto message2 = builder.release(); return std::make_pair(message1, message2); } MessageBuilder::MessageBuilder() : message_(std::make_shared<Message>()) { } MessageBuilder::MessageBuilder(SystemMessageTag, const QString &text) : MessageBuilder() { this->emplace<TimestampElement>(); // check system message for links // (e.g. needed for sub ticket message in sub only mode) const QStringList textFragments = text.split(QRegularExpression("\\s")); for (const auto &word : textFragments) { const auto linkString = this->matchLink(word); if (linkString.isEmpty()) { this->emplace<TextElement>(word, MessageElementFlag::Text, MessageColor::System); } else { this->addLink(word, linkString); } } this->message().flags.set(MessageFlag::System); this->message().flags.set(MessageFlag::DoNotTriggerNotification); this->message().messageText = text; this->message().searchText = text; } MessageBuilder::MessageBuilder(TimeoutMessageTag, const QString &username, const QString &durationInSeconds, const QString &reason, bool multipleTimes) : MessageBuilder() { QString text; text.append(username); if (!durationInSeconds.isEmpty()) { text.append(" has been timed out"); // TODO: Implement who timed the user out text.append(" for "); bool ok = true; int timeoutSeconds = durationInSeconds.toInt(&ok); if (ok) { text.append(formatTime(timeoutSeconds)); } } else { text.append(" has been permanently banned"); } if (reason.length() > 0) { text.append(": \""); text.append(parseTagString(reason)); text.append("\""); } text.append("."); if (multipleTimes) { text.append(" (multiple times)"); } this->message().flags.set(MessageFlag::System); this->message().flags.set(MessageFlag::Timeout); this->message().flags.set(MessageFlag::DoNotTriggerNotification); this->message().timeoutUser = username; this->emplace<TimestampElement>(); this->emplace<TextElement>(text, MessageElementFlag::Text, MessageColor::System); this->message().messageText = text; this->message().searchText = text; } MessageBuilder::MessageBuilder(const BanAction &action, uint32_t count) : MessageBuilder() { this->emplace<TimestampElement>(); this->message().flags.set(MessageFlag::System); this->message().flags.set(MessageFlag::Timeout); this->message().timeoutUser = action.target.name; this->message().count = count; QString text; if (action.isBan()) { if (action.reason.isEmpty()) { text = QString("%1 banned %2.") // .arg(action.source.name) .arg(action.target.name); } else { text = QString("%1 banned %2: \"%3\".") // .arg(action.source.name) .arg(action.target.name) .arg(action.reason); } } else { if (action.reason.isEmpty()) { text = QString("%1 timed out %2 for %3.") // .arg(action.source.name) .arg(action.target.name) .arg(formatTime(action.duration)); } else { text = QString("%1 timed out %2 for %3: \"%4\".") // .arg(action.source.name) .arg(action.target.name) .arg(formatTime(action.duration)) .arg(action.reason); } if (count > 1) { text.append(QString(" (%1 times)").arg(count)); } } this->emplace<TextElement>(text, MessageElementFlag::Text, MessageColor::System); this->message().messageText = text; this->message().searchText = text; } MessageBuilder::MessageBuilder(const UnbanAction &action) : MessageBuilder() { this->emplace<TimestampElement>(); this->message().flags.set(MessageFlag::System); this->message().flags.set(MessageFlag::Untimeout); this->message().timeoutUser = action.target.name; QString text; if (action.wasBan()) { text = QString("%1 unbanned %2.") // .arg(action.source.name) .arg(action.target.name); } else { text = QString("%1 untimedout %2.") // .arg(action.source.name) .arg(action.target.name); } this->emplace<TextElement>(text, MessageElementFlag::Text, MessageColor::System); this->message().messageText = text; this->message().searchText = text; } MessageBuilder::MessageBuilder(const AutomodUserAction &action) : MessageBuilder() { this->emplace<TimestampElement>(); this->message().flags.set(MessageFlag::System); QString text; switch (action.type) { case AutomodUserAction::AddPermitted: { text = QString("%1 added %2 as a permitted term on AutoMod.") .arg(action.source.name) .arg(action.message); } break; case AutomodUserAction::AddBlocked: { text = QString("%1 added %2 as a blocked term on AutoMod.") .arg(action.source.name) .arg(action.message); } break; case AutomodUserAction::RemovePermitted: { text = QString("%1 removed %2 as a permitted term term on AutoMod.") .arg(action.source.name) .arg(action.message); } break; case AutomodUserAction::RemoveBlocked: { text = QString("%1 removed %2 as a blocked term on AutoMod.") .arg(action.source.name) .arg(action.message); } break; case AutomodUserAction::Properties: { text = QString("%1 modified the AutoMod properties.") .arg(action.source.name); } break; } this->emplace<TextElement>(text, MessageElementFlag::Text, MessageColor::System); } Message *MessageBuilder::operator->() { return this->message_.get(); } Message &MessageBuilder::message() { return *this->message_; } MessagePtr MessageBuilder::release() { std::shared_ptr<Message> ptr; this->message_.swap(ptr); return ptr; } std::weak_ptr<Message> MessageBuilder::weakOf() { return this->message_; } void MessageBuilder::append(std::unique_ptr<MessageElement> element) { this->message().elements.push_back(std::move(element)); } QString MessageBuilder::matchLink(const QString &string) { LinkParser linkParser(string); static QRegularExpression httpRegex( "\\bhttps?://", QRegularExpression::CaseInsensitiveOption); static QRegularExpression ftpRegex( "\\bftps?://", QRegularExpression::CaseInsensitiveOption); static QRegularExpression spotifyRegex( "\\bspotify:", QRegularExpression::CaseInsensitiveOption); if (!linkParser.hasMatch()) { return QString(); } QString captured = linkParser.getCaptured(); if (!captured.contains(httpRegex) && !captured.contains(ftpRegex) && !captured.contains(spotifyRegex)) { captured.insert(0, "http://"); } return captured; } void MessageBuilder::addLink(const QString &origLink, const QString &matchedLink) { static QRegularExpression domainRegex( R"(^(?:(?:ftp|http)s?:\/\/)?([^\/]+)(?:\/.*)?$)", QRegularExpression::CaseInsensitiveOption); QString lowercaseLinkString; auto match = domainRegex.match(origLink); if (match.isValid()) { lowercaseLinkString = origLink.mid(0, match.capturedStart(1)) + match.captured(1).toLower() + origLink.mid(match.capturedEnd(1)); } else { lowercaseLinkString = origLink; } auto linkElement = Link(Link::Url, matchedLink); auto textColor = MessageColor(MessageColor::Link); auto linkMELowercase = this->emplace<TextElement>(lowercaseLinkString, MessageElementFlag::LowercaseLink, textColor) ->setLink(linkElement); auto linkMEOriginal = this->emplace<TextElement>(origLink, MessageElementFlag::OriginalLink, textColor) ->setLink(linkElement); LinkResolver::getLinkInfo(matchedLink, [weakMessage = this->weakOf(), linkMELowercase, linkMEOriginal, matchedLink](QString tooltipText, Link originalLink) { auto shared = weakMessage.lock(); if (!shared) { return; } if (!tooltipText.isEmpty()) { linkMELowercase->setTooltip(tooltipText); linkMEOriginal->setTooltip(tooltipText); } if (originalLink.value != matchedLink && !originalLink.value.isEmpty()) { linkMELowercase->setLink(originalLink)->updateLink(); linkMEOriginal->setLink(originalLink)->updateLink(); } }); } } // namespace chatterino <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of QMime ** ** Based on Qt Creator source code ** ** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #include "qmimeprovider_p.h" #include "mimetypeparser_p.h" #include <qstandardpaths.h> #include <QDir> #include <QFile> #include <QDebug> #include <qendian.h> QMimeProviderBase::QMimeProviderBase(QMimeDatabasePrivate *db) : m_db(db) { } QMimeBinaryProvider::QMimeBinaryProvider(QMimeDatabasePrivate *db) : QMimeProviderBase(db) { } #if defined(Q_OS_UNIX) && !defined(Q_OS_INTEGRITY) #define QT_USE_MMAP #endif struct QMimeBinaryProvider::CacheFile { CacheFile(QFile *file); ~CacheFile(); bool isValid() const { return m_valid; } inline quint16 getUint16(int offset) const { return qFromBigEndian(*reinterpret_cast<quint16 *>(data + offset)); } inline quint32 getUint32(int offset) const { return qFromBigEndian(*reinterpret_cast<quint32 *>(data + offset)); } inline const char* getCharStar(int offset) const { return reinterpret_cast<const char *>(data + offset); } QFile *file; uchar *data; bool m_valid; }; QMimeBinaryProvider::CacheFile::CacheFile(QFile *f) : file(f), m_valid(false) { data = file->map(0, file->size()); if (data) { const int major = getUint16(0); const int minor = getUint16(2); m_valid = (major == 1 && minor >= 1 && minor <= 2); } } QMimeBinaryProvider::CacheFile::~CacheFile() { delete file; } QMimeBinaryProvider::~QMimeBinaryProvider() { qDeleteAll(m_cacheFiles); } // Position of the "list offsets" values, at the beginning of the mime.cache file enum { PosAliasListOffset = 4, PosParentListOffset = 8, PosLiteralListOffset = 12, PosReverseSuffixTreeOffset = 16, PosGlobListOffset = 20, PosMagicListOffset = 24, // PosNamespaceListOffset = 28, PosIconsListOffset = 32, PosGenericIconsListOffset = 36 }; bool QMimeBinaryProvider::isValid() { #if defined(QT_USE_MMAP) return false; // HACK FOR NOW const QStringList cacheFilenames = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/mime.cache")); qDeleteAll(m_cacheFiles); m_cacheFiles.clear(); // Verify version foreach (const QString& cacheFile, cacheFilenames) { QFile *file = new QFile(cacheFile); if (file->open(QIODevice::ReadOnly)) { CacheFile *cacheFile = new CacheFile(file); if (cacheFile->isValid()) m_cacheFiles.append(cacheFile); else delete cacheFile; } else delete file; } if (m_cacheFiles.count() > 1) return true; if (m_cacheFiles.isEmpty()) return false; // We found exactly one file; is it the user-modified mimes, or a system file? const QString foundFile = m_cacheFiles.first()->file->fileName(); const QString localCacheFile = QStandardPaths::storageLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/mime.cache"); return foundFile != localCacheFile; #else return false; #endif } void QMimeBinaryProvider::ensureTypesLoaded() { } QStringList QMimeBinaryProvider::findByName(const QString &fileName, QString *foundSuffix) { GlobMatchResult result; result.m_weight = 0; result.m_matchingPatternLength = 0; foreach (CacheFile *cacheFile, m_cacheFiles) { matchGlobList(result, cacheFile, cacheFile->getUint32(PosLiteralListOffset), fileName); matchGlobList(result, cacheFile, cacheFile->getUint32(PosGlobListOffset), fileName); const int reverseSuffixTreeOffset = cacheFile->getUint32(PosReverseSuffixTreeOffset); const int numRoots = cacheFile->getUint32(reverseSuffixTreeOffset); const int firstRootOffset = cacheFile->getUint32(reverseSuffixTreeOffset + 4); matchSuffixTree(result, cacheFile, numRoots, firstRootOffset, fileName, fileName.length() - 1); } *foundSuffix = result.m_foundSuffix; return result.m_matchingMimeTypes; } void QMimeBinaryProvider::GlobMatchResult::addMatch(const QString &mimeType, int weight, const QString &pattern) { // Is this a lower-weight pattern than the last match? Skip this match then. if (weight < m_weight) return; bool replace = weight > m_weight; if (!replace) { // Compare the length of the match if (pattern.length() < m_matchingPatternLength) return; // too short, ignore else if (pattern.length() > m_matchingPatternLength) { // longer: clear any previous match (like *.bz2, when pattern is *.tar.bz2) replace = true; } } if (replace) { m_matchingMimeTypes.clear(); // remember the new "longer" length m_matchingPatternLength = pattern.length(); m_weight = weight; } m_matchingMimeTypes.append(mimeType); if (pattern.startsWith(QLatin1String("*."))) m_foundSuffix = pattern.mid(2); } void QMimeBinaryProvider::matchGlobList(GlobMatchResult& result, CacheFile *cacheFile, int off, const QString &fileName) { const int numGlobs = cacheFile->getUint32(off); //qDebug() << "Loading" << numGlobs << "globs from" << cacheFile->file->fileName() << "at offset" << cacheFile->globListOffset; for (int i = 0; i < numGlobs; ++i) { const int globOffset = cacheFile->getUint32(off + 4 + 12 * i); const int mimeTypeOffset = cacheFile->getUint32(off + 4 + 12 * i + 4); const int flagsAndWeight = cacheFile->getUint32(off + 4 + 12 * i + 8); const int weight = flagsAndWeight & 0xff; const bool caseSensitive = flagsAndWeight & 0x100; const Qt::CaseSensitivity qtCaseSensitive = caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive; const QString pattern = QLatin1String(cacheFile->getCharStar(globOffset)); const char* mimeType = cacheFile->getCharStar(mimeTypeOffset); qDebug() << pattern << mimeType << weight << caseSensitive; QMimeGlobPattern glob(pattern, QString() /*unused*/, weight, qtCaseSensitive); // TODO: this could be done faster for literals where a simple == would do. if (glob.matchFileName(fileName)) result.addMatch(QLatin1String(mimeType), weight, pattern); } } bool QMimeBinaryProvider::matchSuffixTree(GlobMatchResult& result, QMimeBinaryProvider::CacheFile *cacheFile, int numEntries, int firstOffset, const QString &fileName, int charPos) { QChar fileChar = fileName[charPos]; int min = 0; int max = numEntries - 1; while (min <= max) { const int mid = (min + max) / 2; const int off = firstOffset + 12 * mid; const QChar ch = cacheFile->getUint32(off); if (ch < fileChar) min = mid + 1; else if (ch > fileChar) max = mid - 1; else { --charPos; int numChildren = cacheFile->getUint32(off + 4); int childrenOffset = cacheFile->getUint32(off + 8); bool success = false; if (charPos > 0) success = matchSuffixTree(result, cacheFile, numChildren, childrenOffset, fileName, charPos); if (!success) { for (int i = 0; i < numChildren; ++i) { const int childOff = childrenOffset + 12 * i; const int mch = cacheFile->getUint32(childOff); if (mch != 0) break; const int mimeTypeOffset = cacheFile->getUint32(childOff + 4); const char* mimeType = cacheFile->getCharStar(mimeTypeOffset); const int flagsAndWeight = cacheFile->getUint32(childOff + 8); const int weight = flagsAndWeight & 0xff; //const bool caseSensitive = flagsAndWeight & 0x100; // TODO handle caseSensitive result.addMatch(QLatin1String(mimeType), weight, QLatin1String("*.") + fileName.mid(charPos)); success = true; } } return success; } } return false; } void QMimeBinaryProvider::ensureMagicLoaded() { } QMimeXMLProvider::QMimeXMLProvider(QMimeDatabasePrivate *db) : QMimeProviderBase(db), m_loaded(false) { } bool QMimeXMLProvider::isValid() { return true; } void QMimeXMLProvider::ensureTypesLoaded() { ensureLoaded(); } QStringList QMimeXMLProvider::findByName(const QString &fileName, QString *foundSuffix) { ensureLoaded(); const QStringList matchingMimeTypes = m_mimeTypeGlobs.matchingGlobs(fileName, foundSuffix); return matchingMimeTypes; } void QMimeXMLProvider::ensureMagicLoaded() { ensureLoaded(); } void QMimeXMLProvider::ensureLoaded() { if (!m_loaded) { bool fdoXmlFound = false; QStringList allFiles; const QStringList packageDirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/packages"), QStandardPaths::LocateDirectory); foreach (const QString &packageDir, packageDirs) { QDir dir(packageDir); const QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot); qDebug() << packageDir << files; if (!fdoXmlFound) fdoXmlFound = files.contains(QLatin1String("freedesktop.org.xml")); foreach (const QString& file, files) { allFiles.append(packageDir + QLatin1Char('/') + file); } } if (!fdoXmlFound) { // TODO: putting the xml file in the resource is a hack for now // We should instead install the file as part of installing Qt load(QLatin1String(":/qmime/freedesktop.org.xml")); } foreach (const QString& file, allFiles) load(file); } } void QMimeXMLProvider::load(const QString &fileName) { QString errorMessage; if (!load(fileName, &errorMessage)) qWarning("QMimeDatabase: Error loading %s\n%s", qPrintable(fileName), qPrintable(errorMessage)); } bool QMimeXMLProvider::load(const QString &fileName, QString *errorMessage) { m_loaded = true; QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { if (errorMessage) *errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(fileName, file.errorString()); return false; } if (errorMessage) errorMessage->clear(); MimeTypeParser parser(*this); return parser.parse(&file, fileName, errorMessage); } void QMimeXMLProvider::addGlobPattern(const QMimeGlobPattern& glob) { m_mimeTypeGlobs.addGlob(glob); } bool QMimeXMLProvider::addMimeType(const QMimeType &mt) { // HACK FOR NOW. The goal is to move all that code here. return m_db->addMimeType(mt); } <commit_msg>Updated a debug message that shows up in tests.<commit_after>/************************************************************************** ** ** This file is part of QMime ** ** Based on Qt Creator source code ** ** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #include "qmimeprovider_p.h" #include "mimetypeparser_p.h" #include <qstandardpaths.h> #include <QDir> #include <QFile> #include <QDebug> #include <qendian.h> QMimeProviderBase::QMimeProviderBase(QMimeDatabasePrivate *db) : m_db(db) { } QMimeBinaryProvider::QMimeBinaryProvider(QMimeDatabasePrivate *db) : QMimeProviderBase(db) { } #if defined(Q_OS_UNIX) && !defined(Q_OS_INTEGRITY) #define QT_USE_MMAP #endif struct QMimeBinaryProvider::CacheFile { CacheFile(QFile *file); ~CacheFile(); bool isValid() const { return m_valid; } inline quint16 getUint16(int offset) const { return qFromBigEndian(*reinterpret_cast<quint16 *>(data + offset)); } inline quint32 getUint32(int offset) const { return qFromBigEndian(*reinterpret_cast<quint32 *>(data + offset)); } inline const char* getCharStar(int offset) const { return reinterpret_cast<const char *>(data + offset); } QFile *file; uchar *data; bool m_valid; }; QMimeBinaryProvider::CacheFile::CacheFile(QFile *f) : file(f), m_valid(false) { data = file->map(0, file->size()); if (data) { const int major = getUint16(0); const int minor = getUint16(2); m_valid = (major == 1 && minor >= 1 && minor <= 2); } } QMimeBinaryProvider::CacheFile::~CacheFile() { delete file; } QMimeBinaryProvider::~QMimeBinaryProvider() { qDeleteAll(m_cacheFiles); } // Position of the "list offsets" values, at the beginning of the mime.cache file enum { PosAliasListOffset = 4, PosParentListOffset = 8, PosLiteralListOffset = 12, PosReverseSuffixTreeOffset = 16, PosGlobListOffset = 20, PosMagicListOffset = 24, // PosNamespaceListOffset = 28, PosIconsListOffset = 32, PosGenericIconsListOffset = 36 }; bool QMimeBinaryProvider::isValid() { #if defined(QT_USE_MMAP) return false; // HACK FOR NOW const QStringList cacheFilenames = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/mime.cache")); qDeleteAll(m_cacheFiles); m_cacheFiles.clear(); // Verify version foreach (const QString& cacheFile, cacheFilenames) { QFile *file = new QFile(cacheFile); if (file->open(QIODevice::ReadOnly)) { CacheFile *cacheFile = new CacheFile(file); if (cacheFile->isValid()) m_cacheFiles.append(cacheFile); else delete cacheFile; } else delete file; } if (m_cacheFiles.count() > 1) return true; if (m_cacheFiles.isEmpty()) return false; // We found exactly one file; is it the user-modified mimes, or a system file? const QString foundFile = m_cacheFiles.first()->file->fileName(); const QString localCacheFile = QStandardPaths::storageLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/mime.cache"); return foundFile != localCacheFile; #else return false; #endif } void QMimeBinaryProvider::ensureTypesLoaded() { } QStringList QMimeBinaryProvider::findByName(const QString &fileName, QString *foundSuffix) { GlobMatchResult result; result.m_weight = 0; result.m_matchingPatternLength = 0; foreach (CacheFile *cacheFile, m_cacheFiles) { matchGlobList(result, cacheFile, cacheFile->getUint32(PosLiteralListOffset), fileName); matchGlobList(result, cacheFile, cacheFile->getUint32(PosGlobListOffset), fileName); const int reverseSuffixTreeOffset = cacheFile->getUint32(PosReverseSuffixTreeOffset); const int numRoots = cacheFile->getUint32(reverseSuffixTreeOffset); const int firstRootOffset = cacheFile->getUint32(reverseSuffixTreeOffset + 4); matchSuffixTree(result, cacheFile, numRoots, firstRootOffset, fileName, fileName.length() - 1); } *foundSuffix = result.m_foundSuffix; return result.m_matchingMimeTypes; } void QMimeBinaryProvider::GlobMatchResult::addMatch(const QString &mimeType, int weight, const QString &pattern) { // Is this a lower-weight pattern than the last match? Skip this match then. if (weight < m_weight) return; bool replace = weight > m_weight; if (!replace) { // Compare the length of the match if (pattern.length() < m_matchingPatternLength) return; // too short, ignore else if (pattern.length() > m_matchingPatternLength) { // longer: clear any previous match (like *.bz2, when pattern is *.tar.bz2) replace = true; } } if (replace) { m_matchingMimeTypes.clear(); // remember the new "longer" length m_matchingPatternLength = pattern.length(); m_weight = weight; } m_matchingMimeTypes.append(mimeType); if (pattern.startsWith(QLatin1String("*."))) m_foundSuffix = pattern.mid(2); } void QMimeBinaryProvider::matchGlobList(GlobMatchResult& result, CacheFile *cacheFile, int off, const QString &fileName) { const int numGlobs = cacheFile->getUint32(off); //qDebug() << "Loading" << numGlobs << "globs from" << cacheFile->file->fileName() << "at offset" << cacheFile->globListOffset; for (int i = 0; i < numGlobs; ++i) { const int globOffset = cacheFile->getUint32(off + 4 + 12 * i); const int mimeTypeOffset = cacheFile->getUint32(off + 4 + 12 * i + 4); const int flagsAndWeight = cacheFile->getUint32(off + 4 + 12 * i + 8); const int weight = flagsAndWeight & 0xff; const bool caseSensitive = flagsAndWeight & 0x100; const Qt::CaseSensitivity qtCaseSensitive = caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive; const QString pattern = QLatin1String(cacheFile->getCharStar(globOffset)); const char* mimeType = cacheFile->getCharStar(mimeTypeOffset); qDebug() << pattern << mimeType << weight << caseSensitive; QMimeGlobPattern glob(pattern, QString() /*unused*/, weight, qtCaseSensitive); // TODO: this could be done faster for literals where a simple == would do. if (glob.matchFileName(fileName)) result.addMatch(QLatin1String(mimeType), weight, pattern); } } bool QMimeBinaryProvider::matchSuffixTree(GlobMatchResult& result, QMimeBinaryProvider::CacheFile *cacheFile, int numEntries, int firstOffset, const QString &fileName, int charPos) { QChar fileChar = fileName[charPos]; int min = 0; int max = numEntries - 1; while (min <= max) { const int mid = (min + max) / 2; const int off = firstOffset + 12 * mid; const QChar ch = cacheFile->getUint32(off); if (ch < fileChar) min = mid + 1; else if (ch > fileChar) max = mid - 1; else { --charPos; int numChildren = cacheFile->getUint32(off + 4); int childrenOffset = cacheFile->getUint32(off + 8); bool success = false; if (charPos > 0) success = matchSuffixTree(result, cacheFile, numChildren, childrenOffset, fileName, charPos); if (!success) { for (int i = 0; i < numChildren; ++i) { const int childOff = childrenOffset + 12 * i; const int mch = cacheFile->getUint32(childOff); if (mch != 0) break; const int mimeTypeOffset = cacheFile->getUint32(childOff + 4); const char* mimeType = cacheFile->getCharStar(mimeTypeOffset); const int flagsAndWeight = cacheFile->getUint32(childOff + 8); const int weight = flagsAndWeight & 0xff; //const bool caseSensitive = flagsAndWeight & 0x100; // TODO handle caseSensitive result.addMatch(QLatin1String(mimeType), weight, QLatin1String("*.") + fileName.mid(charPos)); success = true; } } return success; } } return false; } void QMimeBinaryProvider::ensureMagicLoaded() { } QMimeXMLProvider::QMimeXMLProvider(QMimeDatabasePrivate *db) : QMimeProviderBase(db), m_loaded(false) { } bool QMimeXMLProvider::isValid() { return true; } void QMimeXMLProvider::ensureTypesLoaded() { ensureLoaded(); } QStringList QMimeXMLProvider::findByName(const QString &fileName, QString *foundSuffix) { ensureLoaded(); const QStringList matchingMimeTypes = m_mimeTypeGlobs.matchingGlobs(fileName, foundSuffix); return matchingMimeTypes; } void QMimeXMLProvider::ensureMagicLoaded() { ensureLoaded(); } void QMimeXMLProvider::ensureLoaded() { if (!m_loaded) { bool fdoXmlFound = false; QStringList allFiles; const QStringList packageDirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/packages"), QStandardPaths::LocateDirectory); foreach (const QString &packageDir, packageDirs) { QDir dir(packageDir); const QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot); qDebug() << Q_FUNC_INFO << packageDir << files; if (!fdoXmlFound) fdoXmlFound = files.contains(QLatin1String("freedesktop.org.xml")); foreach (const QString& file, files) { allFiles.append(packageDir + QLatin1Char('/') + file); } } if (!fdoXmlFound) { // TODO: putting the xml file in the resource is a hack for now // We should instead install the file as part of installing Qt load(QLatin1String(":/qmime/freedesktop.org.xml")); } foreach (const QString& file, allFiles) load(file); } } void QMimeXMLProvider::load(const QString &fileName) { QString errorMessage; if (!load(fileName, &errorMessage)) qWarning("QMimeDatabase: Error loading %s\n%s", qPrintable(fileName), qPrintable(errorMessage)); } bool QMimeXMLProvider::load(const QString &fileName, QString *errorMessage) { m_loaded = true; QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { if (errorMessage) *errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(fileName, file.errorString()); return false; } if (errorMessage) errorMessage->clear(); MimeTypeParser parser(*this); return parser.parse(&file, fileName, errorMessage); } void QMimeXMLProvider::addGlobPattern(const QMimeGlobPattern& glob) { m_mimeTypeGlobs.addGlob(glob); } bool QMimeXMLProvider::addMimeType(const QMimeType &mt) { // HACK FOR NOW. The goal is to move all that code here. return m_db->addMimeType(mt); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ /* * This sample illustrates how you can create a DOM tree in memory. * It then prints the count of elements in the tree. */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/dom/DOM.hpp> #include <xercesc/util/OutOfMemoryException.hpp> #if defined(XERCES_NEW_IOSTREAMS) #include <iostream> #else #include <iostream.h> #endif XERCES_CPP_NAMESPACE_USE // --------------------------------------------------------------------------- // This is a simple class that lets us do easy (though not terribly efficient) // trancoding of char* data to XMLCh data. // --------------------------------------------------------------------------- class XStr { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- XStr(const char* const toTranscode) { // Call the private transcoding method fUnicodeForm = XMLString::transcode(toTranscode); } ~XStr() { XMLString::release(&fUnicodeForm); } // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- const XMLCh* unicodeForm() const { return fUnicodeForm; } private : // ----------------------------------------------------------------------- // Private data members // // fUnicodeForm // This is the Unicode XMLCh format of the string. // ----------------------------------------------------------------------- XMLCh* fUnicodeForm; }; #define X(str) XStr(str).unicodeForm() // --------------------------------------------------------------------------- // main // --------------------------------------------------------------------------- int main(int argC, char* /* argV[] */) { // Initialize the XML4C2 system. try { XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { char *pMsg = XMLString::transcode(toCatch.getMessage()); XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << pMsg; XMLString::release(&pMsg); return 1; } // Watch for special case help request int errorCode = 0; if (argC > 1) { XERCES_STD_QUALIFIER cout << "\nUsage:\n" " CreateDOMDocument\n\n" "This program creates a new DOM document from scratch in memory.\n" "It then prints the count of elements in the tree.\n" << XERCES_STD_QUALIFIER endl; errorCode = 1; } if(errorCode) { XMLPlatformUtils::Terminate(); return errorCode; } { // Nest entire test in an inner block. // The tree we create below is the same that the XercesDOMParser would // have created, except that no whitespace text nodes would be created. // <company> // <product>Xerces-C</product> // <category idea='great'>XML Parsing Tools</category> // <developedBy>Apache Software Foundation</developedBy> // </company> DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(X("Core")); if (impl != NULL) { try { DOMDocument* doc = impl->createDocument( 0, // root element namespace URI. X("company"), // root element name 0); // document type object (DTD). DOMElement* rootElem = doc->getDocumentElement(); DOMElement* prodElem = doc->createElement(X("product")); rootElem->appendChild(prodElem); DOMText* prodDataVal = doc->createTextNode(X("Xerces-C")); prodElem->appendChild(prodDataVal); DOMElement* catElem = doc->createElement(X("category")); rootElem->appendChild(catElem); catElem->setAttribute(X("idea"), X("great")); DOMText* catDataVal = doc->createTextNode(X("XML Parsing Tools")); catElem->appendChild(catDataVal); DOMElement* devByElem = doc->createElement(X("developedBy")); rootElem->appendChild(devByElem); DOMText* devByDataVal = doc->createTextNode(X("Apache Software Foundation")); devByElem->appendChild(devByDataVal); // // Now count the number of elements in the above DOM tree. // unsigned int elementCount = doc->getElementsByTagName(X("*"))->getLength(); XERCES_STD_QUALIFIER cout << "The tree just created contains: " << elementCount << " elements." << XERCES_STD_QUALIFIER endl; doc->release(); } catch (const OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; errorCode = 5; } catch (const DOMException& e) { XERCES_STD_QUALIFIER cerr << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl; errorCode = 2; } catch (...) { XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl; errorCode = 3; } } // (inpl != NULL) else { XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl; errorCode = 4; } } XMLPlatformUtils::Terminate(); return errorCode; } <commit_msg>Use proper signature for main<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ /* * This sample illustrates how you can create a DOM tree in memory. * It then prints the count of elements in the tree. */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/dom/DOM.hpp> #include <xercesc/util/OutOfMemoryException.hpp> #if defined(XERCES_NEW_IOSTREAMS) #include <iostream> #else #include <iostream.h> #endif XERCES_CPP_NAMESPACE_USE // --------------------------------------------------------------------------- // This is a simple class that lets us do easy (though not terribly efficient) // trancoding of char* data to XMLCh data. // --------------------------------------------------------------------------- class XStr { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- XStr(const char* const toTranscode) { // Call the private transcoding method fUnicodeForm = XMLString::transcode(toTranscode); } ~XStr() { XMLString::release(&fUnicodeForm); } // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- const XMLCh* unicodeForm() const { return fUnicodeForm; } private : // ----------------------------------------------------------------------- // Private data members // // fUnicodeForm // This is the Unicode XMLCh format of the string. // ----------------------------------------------------------------------- XMLCh* fUnicodeForm; }; #define X(str) XStr(str).unicodeForm() // --------------------------------------------------------------------------- // main // --------------------------------------------------------------------------- int main(int argC, char*[]) { // Initialize the XML4C2 system. try { XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { char *pMsg = XMLString::transcode(toCatch.getMessage()); XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << pMsg; XMLString::release(&pMsg); return 1; } // Watch for special case help request int errorCode = 0; if (argC > 1) { XERCES_STD_QUALIFIER cout << "\nUsage:\n" " CreateDOMDocument\n\n" "This program creates a new DOM document from scratch in memory.\n" "It then prints the count of elements in the tree.\n" << XERCES_STD_QUALIFIER endl; errorCode = 1; } if(errorCode) { XMLPlatformUtils::Terminate(); return errorCode; } { // Nest entire test in an inner block. // The tree we create below is the same that the XercesDOMParser would // have created, except that no whitespace text nodes would be created. // <company> // <product>Xerces-C</product> // <category idea='great'>XML Parsing Tools</category> // <developedBy>Apache Software Foundation</developedBy> // </company> DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(X("Core")); if (impl != NULL) { try { DOMDocument* doc = impl->createDocument( 0, // root element namespace URI. X("company"), // root element name 0); // document type object (DTD). DOMElement* rootElem = doc->getDocumentElement(); DOMElement* prodElem = doc->createElement(X("product")); rootElem->appendChild(prodElem); DOMText* prodDataVal = doc->createTextNode(X("Xerces-C")); prodElem->appendChild(prodDataVal); DOMElement* catElem = doc->createElement(X("category")); rootElem->appendChild(catElem); catElem->setAttribute(X("idea"), X("great")); DOMText* catDataVal = doc->createTextNode(X("XML Parsing Tools")); catElem->appendChild(catDataVal); DOMElement* devByElem = doc->createElement(X("developedBy")); rootElem->appendChild(devByElem); DOMText* devByDataVal = doc->createTextNode(X("Apache Software Foundation")); devByElem->appendChild(devByDataVal); // // Now count the number of elements in the above DOM tree. // unsigned int elementCount = doc->getElementsByTagName(X("*"))->getLength(); XERCES_STD_QUALIFIER cout << "The tree just created contains: " << elementCount << " elements." << XERCES_STD_QUALIFIER endl; doc->release(); } catch (const OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; errorCode = 5; } catch (const DOMException& e) { XERCES_STD_QUALIFIER cerr << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl; errorCode = 2; } catch (...) { XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl; errorCode = 3; } } // (inpl != NULL) else { XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl; errorCode = 4; } } XMLPlatformUtils::Terminate(); return errorCode; } <|endoftext|>
<commit_before><commit_msg>Surely we want closesocket() on Windows<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: PreviewValueSet.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-07-13 14:46:39 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "PreviewValueSet.hxx" #include <vcl/image.hxx> #include "../TaskPaneTreeNode.hxx" namespace sd { namespace toolpanel { namespace controls { PreviewValueSet::PreviewValueSet (TreeNode* pParent) : ValueSet (pParent->GetWindow(), WB_TABSTOP), mpParent(pParent), mnPreviewWidth(10), mnBorderWidth(3), mnBorderHeight(3) { SetStyle ( GetStyle() & ~(WB_ITEMBORDER)// | WB_MENUSTYLEVALUESET) // | WB_FLATVALUESET); ); SetColCount(2); SetLineCount(1); SetExtraSpacing (2); } PreviewValueSet::~PreviewValueSet (void) { } void PreviewValueSet::SetPreviewWidth (int nWidth) { mnPreviewWidth = nWidth; } void PreviewValueSet::SetRightMouseClickHandler (const Link& rLink) { maRightMouseClickHandler = rLink; } void PreviewValueSet::MouseButtonDown (const MouseEvent& rEvent) { if (rEvent.IsRight()) maRightMouseClickHandler.Call(reinterpret_cast<void*>( &const_cast<MouseEvent&>(rEvent))); else ValueSet::MouseButtonDown (rEvent); } void PreviewValueSet::Paint (const Rectangle& rRect) { SetBackground (GetSettings().GetStyleSettings().GetWindowColor()); ValueSet::Paint (rRect); SetBackground (Wallpaper()); } void PreviewValueSet::Resize (void) { ValueSet::Resize (); Size aWindowSize (GetOutputSizePixel()); if (aWindowSize.Width()>0 && aWindowSize.Height()>0) { Rearrange(); } } void PreviewValueSet::Rearrange (void) { USHORT nOldColumnCount (GetColCount()); USHORT nOldRowCount (GetLineCount()); USHORT nNewColumnCount (CalculateColumnCount ( GetOutputSizePixel().Width())); USHORT nNewRowCount (CalculateRowCount (nNewColumnCount)); SetColCount (nNewColumnCount); SetLineCount (nNewRowCount); if (nOldColumnCount != nNewColumnCount || nOldRowCount != nNewRowCount) mpParent->RequestResize(); } USHORT PreviewValueSet::CalculateColumnCount (int nWidth) const { int nColumnCount = 0; if (nWidth > 0) { nColumnCount = nWidth / (mnPreviewWidth + 2*mnBorderWidth); if (nColumnCount < 1) nColumnCount = 1; else if (nColumnCount > 4) nColumnCount = 4; } return nColumnCount; } USHORT PreviewValueSet::CalculateRowCount (USHORT nColumnCount) const { int nRowCount = 0; int nItemCount = GetItemCount(); if (nColumnCount > 0) { nRowCount = (nItemCount+nColumnCount-1) / nColumnCount; if (nRowCount < 1) nRowCount = 1; } return nRowCount; } sal_Int32 PreviewValueSet::GetPreferredWidth (sal_Int32 nHeight) { int nPreferredWidth = (mnPreviewWidth + 2*mnBorderWidth) * 1; // Get height of each row. int nItemHeight = mnPreviewWidth*100/141; if (GetItemCount() > 0) { Image aImage = GetItemImage(GetItemId(0)); Size aItemSize = CalcItemSizePixel (aImage.GetSizePixel()); if (aItemSize.Height() > 0) nItemHeight = aItemSize.Height(); } nItemHeight += 2*mnBorderHeight; // Calculate the row- and column count and from the later the preferred // width. int nRowCount = nHeight / nItemHeight; if (nRowCount > 0) { int nColumnCount = (GetItemCount()+nRowCount-1) / nRowCount; if (nColumnCount > 0) nPreferredWidth = (mnPreviewWidth + 2*mnBorderWidth) * nColumnCount; } return nPreferredWidth; } sal_Int32 PreviewValueSet::GetPreferredHeight (sal_Int32 nWidth) { int nRowCount (CalculateRowCount(CalculateColumnCount(nWidth))); int nItemHeight (mnPreviewWidth*100/141); if (GetItemCount() > 0) { Image aImage (GetItemImage(GetItemId(0))); Size aItemSize (CalcItemSizePixel (aImage.GetSizePixel())); if (aItemSize.Height() > 0) nItemHeight = aItemSize.Height(); } return nRowCount * (nItemHeight + 2*mnBorderHeight); } } } } // end of namespace ::sd::toolpanel::controls <commit_msg>INTEGRATION: CWS impress36 (1.2.248); FILE MERGED 2005/02/24 17:29:30 af 1.2.248.1: #i43335# Moved ILayoutableWindow.hxx to ../inc/taskpane.<commit_after>/************************************************************************* * * $RCSfile: PreviewValueSet.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-03-18 17:02:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "PreviewValueSet.hxx" #include <vcl/image.hxx> #include "taskpane/TaskPaneTreeNode.hxx" namespace sd { namespace toolpanel { namespace controls { PreviewValueSet::PreviewValueSet (TreeNode* pParent) : ValueSet (pParent->GetWindow(), WB_TABSTOP), mpParent(pParent), mnPreviewWidth(10), mnBorderWidth(3), mnBorderHeight(3) { SetStyle ( GetStyle() & ~(WB_ITEMBORDER)// | WB_MENUSTYLEVALUESET) // | WB_FLATVALUESET); ); SetColCount(2); SetLineCount(1); SetExtraSpacing (2); } PreviewValueSet::~PreviewValueSet (void) { } void PreviewValueSet::SetPreviewWidth (int nWidth) { mnPreviewWidth = nWidth; } void PreviewValueSet::SetRightMouseClickHandler (const Link& rLink) { maRightMouseClickHandler = rLink; } void PreviewValueSet::MouseButtonDown (const MouseEvent& rEvent) { if (rEvent.IsRight()) maRightMouseClickHandler.Call(reinterpret_cast<void*>( &const_cast<MouseEvent&>(rEvent))); else ValueSet::MouseButtonDown (rEvent); } void PreviewValueSet::Paint (const Rectangle& rRect) { SetBackground (GetSettings().GetStyleSettings().GetWindowColor()); ValueSet::Paint (rRect); SetBackground (Wallpaper()); } void PreviewValueSet::Resize (void) { ValueSet::Resize (); Size aWindowSize (GetOutputSizePixel()); if (aWindowSize.Width()>0 && aWindowSize.Height()>0) { Rearrange(); } } void PreviewValueSet::Rearrange (void) { USHORT nOldColumnCount (GetColCount()); USHORT nOldRowCount (GetLineCount()); USHORT nNewColumnCount (CalculateColumnCount ( GetOutputSizePixel().Width())); USHORT nNewRowCount (CalculateRowCount (nNewColumnCount)); SetColCount (nNewColumnCount); SetLineCount (nNewRowCount); if (nOldColumnCount != nNewColumnCount || nOldRowCount != nNewRowCount) mpParent->RequestResize(); } USHORT PreviewValueSet::CalculateColumnCount (int nWidth) const { int nColumnCount = 0; if (nWidth > 0) { nColumnCount = nWidth / (mnPreviewWidth + 2*mnBorderWidth); if (nColumnCount < 1) nColumnCount = 1; else if (nColumnCount > 4) nColumnCount = 4; } return nColumnCount; } USHORT PreviewValueSet::CalculateRowCount (USHORT nColumnCount) const { int nRowCount = 0; int nItemCount = GetItemCount(); if (nColumnCount > 0) { nRowCount = (nItemCount+nColumnCount-1) / nColumnCount; if (nRowCount < 1) nRowCount = 1; } return nRowCount; } sal_Int32 PreviewValueSet::GetPreferredWidth (sal_Int32 nHeight) { int nPreferredWidth = (mnPreviewWidth + 2*mnBorderWidth) * 1; // Get height of each row. int nItemHeight = mnPreviewWidth*100/141; if (GetItemCount() > 0) { Image aImage = GetItemImage(GetItemId(0)); Size aItemSize = CalcItemSizePixel (aImage.GetSizePixel()); if (aItemSize.Height() > 0) nItemHeight = aItemSize.Height(); } nItemHeight += 2*mnBorderHeight; // Calculate the row- and column count and from the later the preferred // width. int nRowCount = nHeight / nItemHeight; if (nRowCount > 0) { int nColumnCount = (GetItemCount()+nRowCount-1) / nRowCount; if (nColumnCount > 0) nPreferredWidth = (mnPreviewWidth + 2*mnBorderWidth) * nColumnCount; } return nPreferredWidth; } sal_Int32 PreviewValueSet::GetPreferredHeight (sal_Int32 nWidth) { int nRowCount (CalculateRowCount(CalculateColumnCount(nWidth))); int nItemHeight (mnPreviewWidth*100/141); if (GetItemCount() > 0) { Image aImage (GetItemImage(GetItemId(0))); Size aItemSize (CalcItemSizePixel (aImage.GetSizePixel())); if (aItemSize.Height() > 0) nItemHeight = aItemSize.Height(); } return nRowCount * (nItemHeight + 2*mnBorderHeight); } } } } // end of namespace ::sd::toolpanel::controls <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: PreviewValueSet.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-07-13 14:46:53 $ * * 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 SD_TOOLPANEL_PREVIEW_VALUE_SET_HXX #define SD_TOOLPANEL_PREVIEW_VALUE_SET_HXX #include <svtools/valueset.hxx> namespace sd { namespace toolpanel { class TreeNode; } } namespace sd { namespace toolpanel { namespace controls { class PreviewValueSet : public ValueSet { public: PreviewValueSet (TreeNode* pParent); ~PreviewValueSet (void); void SetRightMouseClickHandler (const Link& rLink); virtual void Paint (const Rectangle& rRect); virtual void Resize (void); void SetPreviewWidth (int nWidth); sal_Int32 GetPreferredWidth (sal_Int32 nHeight); sal_Int32 GetPreferredHeight (sal_Int32 nWidth); /** Set the number of rows and columns according to the current number of items. Call this method when new items have been inserted. */ void Rearrange (void); protected: virtual void MouseButtonDown (const MouseEvent& rEvent); private: Link maRightMouseClickHandler; TreeNode* mpParent; int mnPreviewWidth; const int mnBorderWidth; const int mnBorderHeight; USHORT CalculateColumnCount (int nWidth) const; USHORT CalculateRowCount (USHORT nColumnCount) const; }; } } } // end of namespace ::sd::toolpanel::controls #endif <commit_msg>INTEGRATION: CWS impress51 (1.2.320); FILE MERGED 2005/06/20 12:51:06 af 1.2.320.1: #i50712# Added support for keyboard driven context menu.<commit_after>/************************************************************************* * * $RCSfile: PreviewValueSet.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-07-14 10:26:23 $ * * 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 SD_TOOLPANEL_PREVIEW_VALUE_SET_HXX #define SD_TOOLPANEL_PREVIEW_VALUE_SET_HXX #include <svtools/valueset.hxx> namespace sd { namespace toolpanel { class TreeNode; } } namespace sd { namespace toolpanel { namespace controls { /** Adapt the svtools valueset to the needs of the master page controlls. */ class PreviewValueSet : public ValueSet { public: PreviewValueSet (TreeNode* pParent); ~PreviewValueSet (void); void SetRightMouseClickHandler (const Link& rLink); virtual void Paint (const Rectangle& rRect); virtual void Resize (void); /** When a request for the display of a context menu is made to this method then that request is forwarded via the ContextMenuCallback. This way the owning class can handle the context menu without having to be derived from this class. Use SetContextMenuCallback to set or rest the handler. */ virtual void Command (const CommandEvent& rEvent); void SetPreviewWidth (int nWidth); sal_Int32 GetPreferredWidth (sal_Int32 nHeight); sal_Int32 GetPreferredHeight (sal_Int32 nWidth); /** Set the number of rows and columns according to the current number of items. Call this method when new items have been inserted. */ void Rearrange (void); /** Set the callback function to which requests for context menus are forewarded. Call with an empty Link to reset the callback function. */ void SetContextMenuCallback (const Link& rLink); protected: virtual void MouseButtonDown (const MouseEvent& rEvent); private: Link maRightMouseClickHandler; Link maContextMenuCallback; TreeNode* mpParent; int mnPreviewWidth; const int mnBorderWidth; const int mnBorderHeight; USHORT CalculateColumnCount (int nWidth) const; USHORT CalculateRowCount (USHORT nColumnCount) const; }; } } } // end of namespace ::sd::toolpanel::controls #endif <|endoftext|>
<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 Dims dev-team // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "serialize.h" #include "sync.h" #include "util.h" #include <inttypes.h> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/assign.hpp> #include "monitor/reputationTracer.h" #include "monitor/rankingDatabase.h" namespace monitor { using namespace std; using namespace boost; CRankingDatabase * CRankingDatabase::ms_instance = NULL; CRankingDatabase* CRankingDatabase::getInstance() { if ( !ms_instance ) { ms_instance = new CRankingDatabase( "rankingData", "rc+" ); }; return ms_instance; } // // CRankingDatabase // bool CRankingDatabase::writeTrackerData( common::CTrackerData const& _trackerData ) { bool result = Write( std::make_pair( std::string("tracker"), _trackerData.m_publicKey.GetID() ), _trackerData, false ); Flush(); return result; } bool CRankingDatabase::eraseTrackerData( CPubKey const & _publicKey ) { return Erase(std::make_pair( std::string("tracker"), _publicKey.GetID() )); } bool ReadTrackerData( std::map< uint160, common::CTrackerData > & _trackerData, CDataStream& _stream, CDataStream& _ssValue, string& _strErr) { try { // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other std::string type; _stream >> type; if ( type == "tracker" ) { CKeyID keyId; _stream >> keyId; common::CTrackerData trackerData; _ssValue >> trackerData; if ( trackerData.m_publicKey.GetID() == keyId ) return false; _trackerData.insert( std::make_pair( keyId, trackerData ) ); } } catch (...) { return false; } return true; } DBErrors CRankingDatabase::loadIdentificationDatabase( std::map< uint160, common::CTrackerData > & _trackers ) { bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { //LOCK(pwallet->cs_wallet); do I need something like this ??? // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { LogPrintf("Error getting identification database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { LogPrintf("Error reading next record from tracker ranking database\n"); return DB_CORRUPT; } // Try to be tolerant of single corrupt records: string strErr; if ( !ReadTrackerData( _trackers, ssKey, ssValue, strErr ) ) { result = DB_CORRUPT; } if (!strErr.empty()) LogPrintf("%s\n", strErr); } pcursor->close(); } catch (boost::thread_interrupted) { throw; } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; // Any wallet corruption at all: skip any rewriting or // upgrading, we don't want to make it worse. if (result != DB_LOAD_OK) return result; return result; } } <commit_msg>small fix<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 Dims dev-team // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "serialize.h" #include "sync.h" #include "util.h" #include <inttypes.h> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/assign.hpp> #include "monitor/reputationTracer.h" #include "monitor/rankingDatabase.h" namespace monitor { using namespace std; using namespace boost; CRankingDatabase * CRankingDatabase::ms_instance = NULL; CRankingDatabase* CRankingDatabase::getInstance() { if ( !ms_instance ) { ms_instance = new CRankingDatabase( "rankingData", "rc+" ); }; return ms_instance; } // // CRankingDatabase // bool CRankingDatabase::writeTrackerData( common::CTrackerData const& _trackerData ) { bool result = Write( std::make_pair( std::string("tracker"), _trackerData.m_publicKey.GetID() ), _trackerData, false ); Flush(); return result; } bool CRankingDatabase::eraseTrackerData( CPubKey const & _publicKey ) { return Erase(std::make_pair( std::string("tracker"), _publicKey.GetID() )); } bool ReadTrackerData( std::map< uint160, common::CTrackerData > & _trackerData, CDataStream& _stream, CDataStream& _ssValue, string& _strErr) { try { // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other std::string type; _stream >> type; if ( type == "tracker" ) { CKeyID keyId; _stream >> keyId; common::CTrackerData trackerData; _ssValue >> trackerData; if ( trackerData.m_publicKey.GetID() != keyId ) return false; _trackerData.insert( std::make_pair( keyId, trackerData ) ); } } catch (...) { return false; } return true; } DBErrors CRankingDatabase::loadIdentificationDatabase( std::map< uint160, common::CTrackerData > & _trackers ) { bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { //LOCK(pwallet->cs_wallet); do I need something like this ??? // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { LogPrintf("Error getting identification database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { LogPrintf("Error reading next record from tracker ranking database\n"); return DB_CORRUPT; } // Try to be tolerant of single corrupt records: string strErr; if ( !ReadTrackerData( _trackers, ssKey, ssValue, strErr ) ) { result = DB_CORRUPT; } if (!strErr.empty()) LogPrintf("%s\n", strErr); } pcursor->close(); } catch (boost::thread_interrupted) { throw; } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; // Any wallet corruption at all: skip any rewriting or // upgrading, we don't want to make it worse. if (result != DB_LOAD_OK) return result; return result; } } <|endoftext|>
<commit_before>/* QtCurve (C) Craig Drummond, 2007 - 2010 craig.p.drummond@gmail.com ---- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "shortcuthandler.h" #include <QtGui> namespace QtCurve { ShortcutHandler::ShortcutHandler(QObject *parent) : QObject(parent) , itsAltDown(false) , itsHandlePopupsOnly(false) { } ShortcutHandler::~ShortcutHandler() { } bool ShortcutHandler::hasSeenAlt(const QWidget *widget) const { if(qobject_cast<const QMenu *>(widget)) { const QWidget *w=widget; while(w) { if(itsSeenAlt.contains((QWidget *)w)) return true; w=w->parentWidget(); } } if(itsHandlePopupsOnly) return false; widget = widget->window(); return itsSeenAlt.contains((QWidget *)widget); } bool ShortcutHandler::showShortcut(const QWidget *widget) const { return itsAltDown && hasSeenAlt(widget); } void ShortcutHandler::widgetDestroyed(QObject *o) { itsUpdated.remove(static_cast<QWidget *>(o)); } void ShortcutHandler::updateWidget(QWidget *w) { if(!itsUpdated.contains(w)) { itsUpdated.insert(w); w->update(); connect(w, SIGNAL(destroyed(QObject *)), this, SLOT(widgetDestroyed(QObject *))); } } bool ShortcutHandler::eventFilter(QObject *o, QEvent *e) { if (!o->isWidgetType()) return QObject::eventFilter(o, e); QWidget *widget = qobject_cast<QWidget*>(o); switch(e->type()) { case QEvent::KeyPress: if (static_cast<QKeyEvent *>(e)->key() == Qt::Key_Alt) { itsAltDown = true; if(qobject_cast<QMenu *>(widget)) { QWidget *w=widget; while(w) { itsSeenAlt.insert(w); updateWidget(w); w=w->parentWidget(); } if(!itsHandlePopupsOnly && !widget->parentWidget()) { itsSeenAlt.insert(QApplication::activeWindow()); updateWidget(QApplication::activeWindow()); } } if(!itsHandlePopupsOnly) { widget = widget->window(); itsSeenAlt.insert(widget); QList<QWidget *> l = qFindChildren<QWidget *>(widget); for (int pos=0 ; pos < l.size() ; ++pos) { QWidget *w = l.at(pos); if (!(w->isWindow() || !w->isVisible())) // || w->style()->styleHint(QStyle::SH_UnderlineShortcut, 0, w))) updateWidget(w); } QList<QMenuBar *> m = qFindChildren<QMenuBar *>(widget); for (int i = 0; i < m.size(); ++i) updateWidget(m.at(i)); } } break; case QEvent::KeyRelease: if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Alt) { itsAltDown = false; QSet<QWidget *>::ConstIterator it(itsUpdated.constBegin()), end(itsUpdated.constEnd()); for (; it!=end; ++it) (*it)->update(); itsSeenAlt.clear(); itsUpdated.clear(); // TODO: If menu is popuped up, it doesn't clear underlines... } break; case QEvent::WindowDeactivate: case QEvent::Close: // Reset widget when closing itsSeenAlt.remove(widget); itsUpdated.remove(widget); itsSeenAlt.remove(widget->window()); break; default: break; } return QObject::eventFilter(o, e); } } <commit_msg>Treat WindowDeactivate as if it as a ButtonRelease<commit_after>/* QtCurve (C) Craig Drummond, 2007 - 2010 craig.p.drummond@gmail.com ---- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "shortcuthandler.h" #include <QtGui> namespace QtCurve { ShortcutHandler::ShortcutHandler(QObject *parent) : QObject(parent) , itsAltDown(false) , itsHandlePopupsOnly(false) { } ShortcutHandler::~ShortcutHandler() { } bool ShortcutHandler::hasSeenAlt(const QWidget *widget) const { if(qobject_cast<const QMenu *>(widget)) { const QWidget *w=widget; while(w) { if(itsSeenAlt.contains((QWidget *)w)) return true; w=w->parentWidget(); } } if(itsHandlePopupsOnly) return false; widget = widget->window(); return itsSeenAlt.contains((QWidget *)widget); } bool ShortcutHandler::showShortcut(const QWidget *widget) const { return itsAltDown && hasSeenAlt(widget); } void ShortcutHandler::widgetDestroyed(QObject *o) { itsUpdated.remove(static_cast<QWidget *>(o)); } void ShortcutHandler::updateWidget(QWidget *w) { if(!itsUpdated.contains(w)) { itsUpdated.insert(w); w->update(); connect(w, SIGNAL(destroyed(QObject *)), this, SLOT(widgetDestroyed(QObject *))); } } bool ShortcutHandler::eventFilter(QObject *o, QEvent *e) { if (!o->isWidgetType()) return QObject::eventFilter(o, e); QWidget *widget = qobject_cast<QWidget*>(o); switch(e->type()) { case QEvent::KeyPress: if (Qt::Key_Alt==static_cast<QKeyEvent *>(e)->key()) { itsAltDown = true; if(qobject_cast<QMenu *>(widget)) { QWidget *w=widget; while(w) { itsSeenAlt.insert(w); updateWidget(w); w=w->parentWidget(); } if(!itsHandlePopupsOnly && !widget->parentWidget()) { itsSeenAlt.insert(QApplication::activeWindow()); updateWidget(QApplication::activeWindow()); } } if(!itsHandlePopupsOnly) { widget = widget->window(); itsSeenAlt.insert(widget); QList<QWidget *> l = qFindChildren<QWidget *>(widget); for (int pos=0 ; pos < l.size() ; ++pos) { QWidget *w = l.at(pos); if (!(w->isWindow() || !w->isVisible())) // || w->style()->styleHint(QStyle::SH_UnderlineShortcut, 0, w))) updateWidget(w); } QList<QMenuBar *> m = qFindChildren<QMenuBar *>(widget); for (int i = 0; i < m.size(); ++i) updateWidget(m.at(i)); } } break; case QEvent::WindowDeactivate: case QEvent::KeyRelease: if (QEvent::WindowDeactivate==e->type() || Qt::Key_Alt==static_cast<QKeyEvent*>(e)->key()) { itsAltDown = false; QSet<QWidget *>::ConstIterator it(itsUpdated.constBegin()), end(itsUpdated.constEnd()); for (; it!=end; ++it) (*it)->update(); itsSeenAlt.clear(); itsUpdated.clear(); // TODO: If menu is popuped up, it doesn't clear underlines... } break; case QEvent::Close: // Reset widget when closing itsSeenAlt.remove(widget); itsUpdated.remove(widget); itsSeenAlt.remove(widget->window()); break; default: break; } return QObject::eventFilter(o, e); } } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FlatFlyOnChip_HPP_ #define _FlatFlyOnChip_HPP_ #include "network.hpp" #include "routefunc.hpp" #include <cassert> class FlatFlyOnChip : public Network { int _m; int _n; int _r; int _k; int _c; int _radix; int _net_size; int _stageout; int _numinput; int _stages; int _num_of_switch; void _ComputeSize( const Configuration &config ); void _BuildNet( const Configuration &config ); int _OutChannel( int stage, int addr, int port, int outputs ) const; int _InChannel( int stage, int addr, int port ) const; public: FlatFlyOnChip( const Configuration &config, const string & name ); int GetN( ) const; int GetK( ) const; static void RegisterRoutingFunctions() ; double Capacity( ) const; void InsertRandomFaults( const Configuration &config ); static int half_vcs; }; void xyyx_flatfly( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); void min_flatfly( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); void ugal_xyyx_flatfly_onchip( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); void ugal_flatfly_onchip( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); void valiant_flatfly( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); int find_distance (int src, int dest); int find_ran_intm (int src, int dest); int flatfly_outport(int dest, int rID); int find_phy_distance(int src, int dest); int flatfly_transformation(int dest); int flatfly_outport_yx(int dest, int rID); #endif <commit_msg>remove unused, declared but not defined function<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FlatFlyOnChip_HPP_ #define _FlatFlyOnChip_HPP_ #include "network.hpp" #include "routefunc.hpp" #include <cassert> class FlatFlyOnChip : public Network { int _m; int _n; int _r; int _k; int _c; int _radix; int _net_size; int _stageout; int _numinput; int _stages; int _num_of_switch; void _ComputeSize( const Configuration &config ); void _BuildNet( const Configuration &config ); int _OutChannel( int stage, int addr, int port, int outputs ) const; int _InChannel( int stage, int addr, int port ) const; public: FlatFlyOnChip( const Configuration &config, const string & name ); int GetN( ) const; int GetK( ) const; static void RegisterRoutingFunctions() ; double Capacity( ) const; void InsertRandomFaults( const Configuration &config ); static int half_vcs; }; void xyyx_flatfly( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); void min_flatfly( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); void ugal_xyyx_flatfly_onchip( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); void ugal_flatfly_onchip( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); void valiant_flatfly( const Router *r, const Flit *f, int in_channel, OutputSet *outputs, bool inject ); int find_distance (int src, int dest); int find_ran_intm (int src, int dest); int flatfly_outport(int dest, int rID); int flatfly_transformation(int dest); int flatfly_outport_yx(int dest, int rID); #endif <|endoftext|>
<commit_before>#include <ros/ros.h> #include <boost/math/constants/constants.hpp> #include <pr2_controllers_msgs/JointTrajectoryAction.h> #include <pr2_mechanism_msgs/ListControllers.h> #include <actionlib/client/simple_action_client.h> #include <boost/math/constants/constants.hpp> using namespace std; using namespace ros; typedef actionlib::SimpleActionClient< pr2_controllers_msgs::JointTrajectoryAction > TrajClient; static const double pi = boost::math::constants::pi<double>(); class SetArmPositions { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; public: SetArmPositions() : pnh("~") { } void moveToBasePositions(){ ROS_INFO("Moving arms to base position"); const string listControllersServiceName = "/pr2_controller_manager/list_controllers"; ROS_INFO("Waiting for the list controllers service"); if (!ros::service::waitForService(listControllersServiceName, ros::Duration(60))) { ROS_WARN("List controllers service could not be found"); } ROS_INFO("List controllers service is up"); // wait for pr2 controllers ros::ServiceClient listControllersClient = nh.serviceClient<pr2_mechanism_msgs::ListControllers>(listControllersServiceName); pr2_mechanism_msgs::ListControllers listControllers; unsigned int controllersCount = 0; ros::Time start = ros::Time::now(); ros::Duration timeout = ros::Duration(60); while (ros::ok() && controllersCount != 2 && ros::Time::now() - start < timeout) { controllersCount = 0; if (!listControllersClient.call(listControllers)) { ROS_ERROR("List controllers call failed"); continue; } for (unsigned int i = 0; i < listControllers.response.controllers.size() ; ++i) { string name = listControllers.response.controllers[i]; string state = listControllers.response.state[i]; if ((name == "r_arm_controller" || name == "l_arm_controller") && state == "running") { controllersCount++; ROS_INFO("controller [%s] state [%s] count[%d]", name.c_str(), state.c_str(), controllersCount); } } } if (controllersCount!= 2) { ROS_WARN("Failed to find both running arm controllers"); } if (!ros::ok()) { ROS_WARN("Node shutdown detected"); return; } auto_ptr<TrajClient> lTrajectoryClient(new TrajClient("l_arm_controller/joint_trajectory_action", true)); auto_ptr<TrajClient> rTrajectoryClient(new TrajClient("r_arm_controller/joint_trajectory_action", true)); ROS_INFO("Waiting for the left joint_trajectory_action server"); if(!lTrajectoryClient->waitForServer(ros::Duration(30))){ ROS_WARN("left joint trajectory server could not be found"); } ROS_INFO("left joint_trajectory_action server is up"); ROS_INFO("Waiting for the right joint_trajectory_action server"); if(!rTrajectoryClient->waitForServer(ros::Duration(30))){ ROS_WARN("right joint trajectory server could not be found"); } ROS_INFO("right joint_trajectory_action server is up"); if (!ros::ok()) { ROS_WARN("Node shutdown detected"); return; } pr2_controllers_msgs::JointTrajectoryGoal lGoal; lGoal.trajectory.header.stamp = ros::Time::now(); lGoal.trajectory.joint_names.push_back("l_shoulder_pan_joint"); lGoal.trajectory.joint_names.push_back("l_shoulder_lift_joint"); lGoal.trajectory.joint_names.push_back("l_upper_arm_roll_joint"); lGoal.trajectory.joint_names.push_back("l_elbow_flex_joint"); lGoal.trajectory.joint_names.push_back("l_forearm_roll_joint"); lGoal.trajectory.joint_names.push_back("l_wrist_flex_joint"); lGoal.trajectory.joint_names.push_back("l_wrist_roll_joint"); lGoal.trajectory.points.resize(1); lGoal.trajectory.points[0].positions.resize(7); lGoal.trajectory.points[0].positions[0] = pi / 4.0; lGoal.trajectory.points[0].positions[1] = 0.0; lGoal.trajectory.points[0].positions[2] = pi / 2.0; lGoal.trajectory.points[0].positions[3] = -pi / 4.0; lGoal.trajectory.points[0].positions[4] = 0.0; lGoal.trajectory.points[0].positions[5] = 0.0; lGoal.trajectory.points[0].positions[6] = 0.0; lGoal.trajectory.points[0].velocities.resize(7); lGoal.trajectory.points[0].velocities[0] = 0.0; lGoal.trajectory.points[0].time_from_start = ros::Duration(1.0); lTrajectoryClient->sendGoal(lGoal); pr2_controllers_msgs::JointTrajectoryGoal rGoal; rGoal.trajectory.header.stamp = ros::Time::now(); rGoal.trajectory.joint_names.push_back("r_shoulder_pan_joint"); rGoal.trajectory.joint_names.push_back("r_shoulder_lift_joint"); rGoal.trajectory.joint_names.push_back("r_upper_arm_roll_joint"); rGoal.trajectory.joint_names.push_back("r_elbow_flex_joint"); rGoal.trajectory.joint_names.push_back("r_forearm_roll_joint"); rGoal.trajectory.joint_names.push_back("r_wrist_flex_joint"); rGoal.trajectory.joint_names.push_back("r_wrist_roll_joint"); rGoal.trajectory.points.resize(1); rGoal.trajectory.points[0].positions.resize(7); rGoal.trajectory.points[0].positions[0] = -pi / 4.0; rGoal.trajectory.points[0].positions[1] = 0.0; rGoal.trajectory.points[0].positions[2] = -pi / 2.0; rGoal.trajectory.points[0].positions[3] = -pi / 4.0; rGoal.trajectory.points[0].positions[4] = 0.0; rGoal.trajectory.points[0].positions[5] = 0.0; rGoal.trajectory.points[0].positions[6] = 0.0; rGoal.trajectory.points[0].velocities.resize(7); rGoal.trajectory.points[0].velocities[0] = 0.0; rGoal.trajectory.points[0].time_from_start = ros::Duration(1.0); rTrajectoryClient->sendGoal(rGoal); if (!ros::ok()) { ROS_WARN("Node shutdown detected"); return; } lTrajectoryClient->waitForResult(ros::Duration(5.0)); if (lTrajectoryClient->getState() != actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_ERROR("Left trajectory client failed"); } rTrajectoryClient->waitForResult(ros::Duration(5.0)); if (rTrajectoryClient->getState() != actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_ERROR("Right trajectory client failed"); } ROS_INFO("Setting initial position complete"); } }; int main(int argc, char** argv){ ros::init(argc, argv, "set_arm_positions"); SetArmPositions sap; sap.moveToBasePositions(); } <commit_msg>Correct error reported by trajectory clients<commit_after>#include <ros/ros.h> #include <boost/math/constants/constants.hpp> #include <pr2_controllers_msgs/JointTrajectoryAction.h> #include <pr2_mechanism_msgs/ListControllers.h> #include <actionlib/client/simple_action_client.h> #include <boost/math/constants/constants.hpp> using namespace std; using namespace ros; typedef actionlib::SimpleActionClient< pr2_controllers_msgs::JointTrajectoryAction > TrajClient; static const double pi = boost::math::constants::pi<double>(); class SetArmPositions { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; public: SetArmPositions() : pnh("~") { } void moveToBasePositions(){ ROS_INFO("Moving arms to base position"); const string listControllersServiceName = "/pr2_controller_manager/list_controllers"; ROS_INFO("Waiting for the list controllers service"); if (!ros::service::waitForService(listControllersServiceName, ros::Duration(60))) { ROS_ERROR("List controllers service could not be found"); return; } ROS_INFO("List controllers service is up"); // wait for pr2 controllers ros::ServiceClient listControllersClient = nh.serviceClient<pr2_mechanism_msgs::ListControllers>(listControllersServiceName); pr2_mechanism_msgs::ListControllers listControllers; unsigned int controllersCount = 0; ros::Time start = ros::Time::now(); ros::Duration timeout = ros::Duration(60); while (ros::ok() && controllersCount != 2 && ros::Time::now() - start < timeout) { controllersCount = 0; if (!listControllersClient.call(listControllers)) { ROS_ERROR("List controllers call failed"); continue; } for (unsigned int i = 0; i < listControllers.response.controllers.size() ; ++i) { string name = listControllers.response.controllers[i]; string state = listControllers.response.state[i]; if ((name == "r_arm_controller" || name == "l_arm_controller") && state == "running") { controllersCount++; ROS_INFO("controller [%s] state [%s] count[%d]", name.c_str(), state.c_str(), controllersCount); } } } if (controllersCount!= 2) { ROS_ERROR("Failed to find both running arm controllers"); return; } if (!ros::ok()) { ROS_WARN("Node shutdown detected"); return; } auto_ptr<TrajClient> lTrajectoryClient(new TrajClient("l_arm_controller/joint_trajectory_action", true)); auto_ptr<TrajClient> rTrajectoryClient(new TrajClient("r_arm_controller/joint_trajectory_action", true)); ROS_INFO("Waiting for the left joint_trajectory_action server"); if(!lTrajectoryClient->waitForServer(ros::Duration(30))){ ROS_ERROR("left joint trajectory server could not be found"); return; } ROS_INFO("left joint_trajectory_action server is up"); ROS_INFO("Waiting for the right joint_trajectory_action server"); if(!rTrajectoryClient->waitForServer(ros::Duration(30))){ ROS_ERROR("right joint trajectory server could not be found"); return; } ROS_INFO("right joint_trajectory_action server is up"); if (!ros::ok()) { ROS_WARN("Node shutdown detected"); return; } pr2_controllers_msgs::JointTrajectoryGoal lGoal; lGoal.trajectory.header.stamp = ros::Time::now(); lGoal.trajectory.joint_names.push_back("l_shoulder_pan_joint"); lGoal.trajectory.joint_names.push_back("l_shoulder_lift_joint"); lGoal.trajectory.joint_names.push_back("l_upper_arm_roll_joint"); lGoal.trajectory.joint_names.push_back("l_elbow_flex_joint"); lGoal.trajectory.joint_names.push_back("l_forearm_roll_joint"); lGoal.trajectory.joint_names.push_back("l_wrist_flex_joint"); lGoal.trajectory.joint_names.push_back("l_wrist_roll_joint"); lGoal.trajectory.points.resize(1); lGoal.trajectory.points[0].positions.resize(7); lGoal.trajectory.points[0].positions[0] = pi / 4.0; lGoal.trajectory.points[0].positions[1] = 0.0; lGoal.trajectory.points[0].positions[2] = pi / 2.0; lGoal.trajectory.points[0].positions[3] = -pi / 4.0; lGoal.trajectory.points[0].positions[4] = 0.0; lGoal.trajectory.points[0].positions[5] = 0.0; lGoal.trajectory.points[0].positions[6] = 0.0; lGoal.trajectory.points[0].velocities.resize(7); lGoal.trajectory.points[0].velocities[0] = 0.0; lGoal.trajectory.points[0].time_from_start = ros::Duration(2.0); lTrajectoryClient->sendGoal(lGoal); pr2_controllers_msgs::JointTrajectoryGoal rGoal; rGoal.trajectory.header.stamp = ros::Time::now(); rGoal.trajectory.joint_names.push_back("r_shoulder_pan_joint"); rGoal.trajectory.joint_names.push_back("r_shoulder_lift_joint"); rGoal.trajectory.joint_names.push_back("r_upper_arm_roll_joint"); rGoal.trajectory.joint_names.push_back("r_elbow_flex_joint"); rGoal.trajectory.joint_names.push_back("r_forearm_roll_joint"); rGoal.trajectory.joint_names.push_back("r_wrist_flex_joint"); rGoal.trajectory.joint_names.push_back("r_wrist_roll_joint"); rGoal.trajectory.points.resize(1); rGoal.trajectory.points[0].positions.resize(7); rGoal.trajectory.points[0].positions[0] = -pi / 4.0; rGoal.trajectory.points[0].positions[1] = 0.0; rGoal.trajectory.points[0].positions[2] = -pi / 2.0; rGoal.trajectory.points[0].positions[3] = -pi / 4.0; rGoal.trajectory.points[0].positions[4] = 0.0; rGoal.trajectory.points[0].positions[5] = 0.0; rGoal.trajectory.points[0].positions[6] = 0.0; rGoal.trajectory.points[0].velocities.resize(7); rGoal.trajectory.points[0].velocities[0] = 0.0; rGoal.trajectory.points[0].time_from_start = ros::Duration(2.0); rTrajectoryClient->sendGoal(rGoal); lTrajectoryClient->waitForResult(ros::Duration(5.0)); rTrajectoryClient->waitForResult(ros::Duration(5.0)); if (lTrajectoryClient->getState() != actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_WARN("Left trajectory client failed"); } if (rTrajectoryClient->getState() != actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_WARN("Right trajectory client failed"); } ROS_INFO("Setting initial position complete"); } }; int main(int argc, char** argv){ ros::init(argc, argv, "set_arm_positions"); SetArmPositions sap; sap.moveToBasePositions(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <DocumentDrawModelManager.hxx> #include <doc.hxx> #include <IDocumentUndoRedo.hxx> #include <IDocumentSettingAccess.hxx> #include <IDocumentDeviceAccess.hxx> #include <docsh.hxx> #include <swtypes.hxx> #include <swhints.hxx> #include <viewsh.hxx> #include <drawdoc.hxx> #include <rootfrm.hxx> #include <editeng/eeitem.hxx> #include <editeng/fhgtitem.hxx> #include <svx/svdmodel.hxx> #include <svx/svdlayer.hxx> #include <svx/svdoutl.hxx> #include <svx/svdpage.hxx> #include <svx/svdpagv.hxx> #include <svl/smplhint.hxx> #include <tools/link.hxx> class SdrOutliner; class XSpellChecker1; namespace sw { DocumentDrawModelManager::DocumentDrawModelManager( SwDoc& i_rSwdoc ) : m_rSwdoc(i_rSwdoc), mpDrawModel(0) {} // Is also called by the Sw3 Reader, if there was an error when reading the // drawing layer. If it is called by the Sw3 Reader the layer is rebuilt // from scratch. void DocumentDrawModelManager::InitDrawModel() { // !! Attention: there is similar code in the Sw3 Reader (sw3imp.cxx) that // also has to be maintained!! if ( mpDrawModel ) ReleaseDrawModel(); //UUUU // // Setup DrawPool and EditEnginePool. Ownership is ours and only gets passed // // to the Drawing. // // The pools are destroyed in the ReleaseDrawModel. // // for loading the drawing items. This must be loaded without RefCounts! // SfxItemPool *pSdrPool = new SdrItemPool( &GetAttrPool() ); // // change DefaultItems for the SdrEdgeObj distance items to TWIPS. // if(pSdrPool) // { // const long nDefEdgeDist = ((500 * 72) / 127); // 1/100th mm in twips // pSdrPool->SetPoolDefaultItem(SdrEdgeNode1HorzDistItem(nDefEdgeDist)); // pSdrPool->SetPoolDefaultItem(SdrEdgeNode1VertDistItem(nDefEdgeDist)); // pSdrPool->SetPoolDefaultItem(SdrEdgeNode2HorzDistItem(nDefEdgeDist)); // pSdrPool->SetPoolDefaultItem(SdrEdgeNode2VertDistItem(nDefEdgeDist)); // // // #i33700# // // Set shadow distance defaults as PoolDefaultItems. Details see bug. // pSdrPool->SetPoolDefaultItem(SdrShadowXDistItem((300 * 72) / 127)); // pSdrPool->SetPoolDefaultItem(SdrShadowYDistItem((300 * 72) / 127)); // } // SfxItemPool *pEEgPool = EditEngine::CreatePool( false ); // pSdrPool->SetSecondaryPool( pEEgPool ); // if ( !GetAttrPool().GetFrozenIdRanges () ) // GetAttrPool().FreezeIdRanges(); // else // pSdrPool->FreezeIdRanges(); // set FontHeight pool defaults without changing static SdrEngineDefaults m_rSwdoc.GetAttrPool().SetPoolDefaultItem(SvxFontHeightItem( 240, 100, EE_CHAR_FONTHEIGHT )); SAL_INFO( "sw.doc", "before create DrawDocument" ); // The document owns the SdrModel. We always have two layers and one page. mpDrawModel = new SwDrawDocument( &m_rSwdoc ); mpDrawModel->EnableUndo( m_rSwdoc.GetIDocumentUndoRedo().DoesUndo() ); OUString sLayerNm; sLayerNm = "Hell"; mnHell = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); sLayerNm = "Heaven"; mnHeaven = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); sLayerNm = "Controls"; mnControls = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); // add invisible layers corresponding to the visible ones. { sLayerNm = "InvisibleHell"; mnInvisibleHell = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); sLayerNm = "InvisibleHeaven"; mnInvisibleHeaven = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); sLayerNm = "InvisibleControls"; mnInvisibleControls = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); } SdrPage* pMasterPage = mpDrawModel->AllocPage( false ); mpDrawModel->InsertPage( pMasterPage ); SAL_INFO( "sw.doc", "after create DrawDocument" ); SAL_INFO( "sw.doc", "before create Spellchecker/Hyphenator" ); SdrOutliner& rOutliner = mpDrawModel->GetDrawOutliner(); ::com::sun::star::uno::Reference< com::sun::star::linguistic2::XSpellChecker1 > xSpell = ::GetSpellChecker(); rOutliner.SetSpeller( xSpell ); ::com::sun::star::uno::Reference< com::sun::star::linguistic2::XHyphenator > xHyphenator( ::GetHyphenator() ); rOutliner.SetHyphenator( xHyphenator ); SAL_INFO( "sw.doc", "after create Spellchecker/Hyphenator" ); m_rSwdoc.SetCalcFieldValueHdl(&rOutliner); m_rSwdoc.SetCalcFieldValueHdl(&mpDrawModel->GetHitTestOutliner()); // Set the LinkManager in the model so that linked graphics can be inserted. // The WinWord import needs it too. mpDrawModel->SetLinkManager( & m_rSwdoc.GetLinkManager() ); mpDrawModel->SetAddExtLeading( m_rSwdoc.getIDocumentSettingAccess().get(IDocumentSettingAccess::ADD_EXT_LEADING) ); OutputDevice* pRefDev = m_rSwdoc.getIDocumentDeviceAccess().getReferenceDevice( false ); if ( pRefDev ) mpDrawModel->SetRefDevice( pRefDev ); mpDrawModel->SetNotifyUndoActionHdl( LINK( &m_rSwdoc, SwDoc, AddDrawUndo )); if ( m_rSwdoc.GetCurrentViewShell() ) { SwViewShell* pViewSh = m_rSwdoc.GetCurrentViewShell(); do { SwRootFrm* pRoot = pViewSh->GetLayout(); if( pRoot && !pRoot->GetDrawPage() ) { // Disable "multiple layout" for the moment: // use pMasterPage instead of a new created SdrPage // mpDrawModel->AllocPage( FALSE ); // mpDrawModel->InsertPage( pDrawPage ); SdrPage* pDrawPage = pMasterPage; pRoot->SetDrawPage( pDrawPage ); pDrawPage->SetSize( pRoot->Frm().SSize() ); } pViewSh = (SwViewShell*)pViewSh->GetNext(); }while( pViewSh != m_rSwdoc.GetCurrentViewShell() ); } } void DocumentDrawModelManager::ReleaseDrawModel() { if ( mpDrawModel ) { // !! Also maintain the code in the sw3io for inserting documents!! delete mpDrawModel; mpDrawModel = 0; //UUUU // SfxItemPool *pSdrPool = GetAttrPool().GetSecondaryPool(); // // OSL_ENSURE( pSdrPool, "missing pool" ); // SfxItemPool *pEEgPool = pSdrPool->GetSecondaryPool(); // OSL_ENSURE( !pEEgPool->GetSecondaryPool(), "I don't accept additional pools"); // pSdrPool->Delete(); // First have the items destroyed, // // then destroy the chain! // GetAttrPool().SetSecondaryPool( 0 ); // This one's a must! // pSdrPool->SetSecondaryPool( 0 ); // That one's safer // SfxItemPool::Free(pSdrPool); // SfxItemPool::Free(pEEgPool); } } const SdrModel* DocumentDrawModelManager::GetDrawModel() const { return mpDrawModel; } SdrModel* DocumentDrawModelManager::GetDrawModel() { return mpDrawModel; } SdrModel* DocumentDrawModelManager::_MakeDrawModel() { OSL_ENSURE( !mpDrawModel, "_MakeDrawModel: Why?" ); InitDrawModel(); if ( m_rSwdoc.GetCurrentViewShell() ) { SwViewShell* pTmp = m_rSwdoc.GetCurrentViewShell(); do { pTmp->MakeDrawView(); pTmp = (SwViewShell*) pTmp->GetNext(); } while ( pTmp != m_rSwdoc.GetCurrentViewShell() ); // Broadcast, so that the FormShell can be connected to the DrawView if( m_rSwdoc.GetDocShell() ) { SfxSimpleHint aHnt( SW_BROADCAST_DRAWVIEWS_CREATED ); m_rSwdoc.GetDocShell()->Broadcast( aHnt ); } } return mpDrawModel; } SdrModel* DocumentDrawModelManager::GetOrCreateDrawModel() { return GetDrawModel() ? GetDrawModel() : _MakeDrawModel(); } SdrLayerID DocumentDrawModelManager::GetHeavenId() const { return mnHeaven; } SdrLayerID DocumentDrawModelManager::GetHellId() const { return mnHell; } SdrLayerID DocumentDrawModelManager::GetControlsId() const { return mnControls; } SdrLayerID DocumentDrawModelManager::GetInvisibleHeavenId() const { return mnInvisibleHeaven; } SdrLayerID DocumentDrawModelManager::GetInvisibleHellId() const { return mnInvisibleHell; } SdrLayerID DocumentDrawModelManager::GetInvisibleControlsId() const { return mnInvisibleControls; } void DocumentDrawModelManager::NotifyInvisibleLayers( SdrPageView& _rSdrPageView ) { OUString sLayerNm; sLayerNm = "InvisibleHell"; _rSdrPageView.SetLayerVisible( sLayerNm, false ); sLayerNm = "InvisibleHeaven"; _rSdrPageView.SetLayerVisible( sLayerNm, false ); sLayerNm = "InvisibleControls"; _rSdrPageView.SetLayerVisible( sLayerNm, false ); } bool DocumentDrawModelManager::IsVisibleLayerId( const SdrLayerID& _nLayerId ) const { bool bRetVal; if ( _nLayerId == GetHeavenId() || _nLayerId == GetHellId() || _nLayerId == GetControlsId() ) { bRetVal = true; } else if ( _nLayerId == GetInvisibleHeavenId() || _nLayerId == GetInvisibleHellId() || _nLayerId == GetInvisibleControlsId() ) { bRetVal = false; } else { OSL_FAIL( "<SwDoc::IsVisibleLayerId(..)> - unknown layer ID." ); bRetVal = false; } return bRetVal; } SdrLayerID DocumentDrawModelManager::GetVisibleLayerIdByInvisibleOne( const SdrLayerID& _nInvisibleLayerId ) { SdrLayerID nVisibleLayerId; if ( _nInvisibleLayerId == GetInvisibleHeavenId() ) { nVisibleLayerId = GetHeavenId(); } else if ( _nInvisibleLayerId == GetInvisibleHellId() ) { nVisibleLayerId = GetHellId(); } else if ( _nInvisibleLayerId == GetInvisibleControlsId() ) { nVisibleLayerId = GetControlsId(); } else if ( _nInvisibleLayerId == GetHeavenId() || _nInvisibleLayerId == GetHellId() || _nInvisibleLayerId == GetControlsId() ) { OSL_FAIL( "<SwDoc::GetVisibleLayerIdByInvisibleOne(..)> - given layer ID already an invisible one." ); nVisibleLayerId = _nInvisibleLayerId; } else { OSL_FAIL( "<SwDoc::GetVisibleLayerIdByInvisibleOne(..)> - given layer ID is unknown." ); nVisibleLayerId = _nInvisibleLayerId; } return nVisibleLayerId; } SdrLayerID DocumentDrawModelManager::GetInvisibleLayerIdByVisibleOne( const SdrLayerID& _nVisibleLayerId ) { SdrLayerID nInvisibleLayerId; if ( _nVisibleLayerId == GetHeavenId() ) { nInvisibleLayerId = GetInvisibleHeavenId(); } else if ( _nVisibleLayerId == GetHellId() ) { nInvisibleLayerId = GetInvisibleHellId(); } else if ( _nVisibleLayerId == GetControlsId() ) { nInvisibleLayerId = GetInvisibleControlsId(); } else if ( _nVisibleLayerId == GetInvisibleHeavenId() || _nVisibleLayerId == GetInvisibleHellId() || _nVisibleLayerId == GetInvisibleControlsId() ) { OSL_FAIL( "<SwDoc::GetInvisibleLayerIdByVisibleOne(..)> - given layer ID already an invisible one." ); nInvisibleLayerId = _nVisibleLayerId; } else { OSL_FAIL( "<SwDoc::GetInvisibleLayerIdByVisibleOne(..)> - given layer ID is unknown." ); nInvisibleLayerId = _nVisibleLayerId; } return nInvisibleLayerId; } void DocumentDrawModelManager::DrawNotifyUndoHdl() { mpDrawModel->SetNotifyUndoActionHdl( Link() ); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#1222244 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <DocumentDrawModelManager.hxx> #include <doc.hxx> #include <IDocumentUndoRedo.hxx> #include <IDocumentSettingAccess.hxx> #include <IDocumentDeviceAccess.hxx> #include <docsh.hxx> #include <swtypes.hxx> #include <swhints.hxx> #include <viewsh.hxx> #include <drawdoc.hxx> #include <rootfrm.hxx> #include <editeng/eeitem.hxx> #include <editeng/fhgtitem.hxx> #include <svx/svdmodel.hxx> #include <svx/svdlayer.hxx> #include <svx/svdoutl.hxx> #include <svx/svdpage.hxx> #include <svx/svdpagv.hxx> #include <svl/smplhint.hxx> #include <tools/link.hxx> class SdrOutliner; class XSpellChecker1; namespace sw { DocumentDrawModelManager::DocumentDrawModelManager(SwDoc& i_rSwdoc) : m_rSwdoc(i_rSwdoc) , mpDrawModel(0) , mnHeaven(0) , mnHell(0) , mnControls(0) , mnInvisibleHeaven(0) , mnInvisibleHell(0) , mnInvisibleControls(0) { } // Is also called by the Sw3 Reader, if there was an error when reading the // drawing layer. If it is called by the Sw3 Reader the layer is rebuilt // from scratch. void DocumentDrawModelManager::InitDrawModel() { // !! Attention: there is similar code in the Sw3 Reader (sw3imp.cxx) that // also has to be maintained!! if ( mpDrawModel ) ReleaseDrawModel(); //UUUU // // Setup DrawPool and EditEnginePool. Ownership is ours and only gets passed // // to the Drawing. // // The pools are destroyed in the ReleaseDrawModel. // // for loading the drawing items. This must be loaded without RefCounts! // SfxItemPool *pSdrPool = new SdrItemPool( &GetAttrPool() ); // // change DefaultItems for the SdrEdgeObj distance items to TWIPS. // if(pSdrPool) // { // const long nDefEdgeDist = ((500 * 72) / 127); // 1/100th mm in twips // pSdrPool->SetPoolDefaultItem(SdrEdgeNode1HorzDistItem(nDefEdgeDist)); // pSdrPool->SetPoolDefaultItem(SdrEdgeNode1VertDistItem(nDefEdgeDist)); // pSdrPool->SetPoolDefaultItem(SdrEdgeNode2HorzDistItem(nDefEdgeDist)); // pSdrPool->SetPoolDefaultItem(SdrEdgeNode2VertDistItem(nDefEdgeDist)); // // // #i33700# // // Set shadow distance defaults as PoolDefaultItems. Details see bug. // pSdrPool->SetPoolDefaultItem(SdrShadowXDistItem((300 * 72) / 127)); // pSdrPool->SetPoolDefaultItem(SdrShadowYDistItem((300 * 72) / 127)); // } // SfxItemPool *pEEgPool = EditEngine::CreatePool( false ); // pSdrPool->SetSecondaryPool( pEEgPool ); // if ( !GetAttrPool().GetFrozenIdRanges () ) // GetAttrPool().FreezeIdRanges(); // else // pSdrPool->FreezeIdRanges(); // set FontHeight pool defaults without changing static SdrEngineDefaults m_rSwdoc.GetAttrPool().SetPoolDefaultItem(SvxFontHeightItem( 240, 100, EE_CHAR_FONTHEIGHT )); SAL_INFO( "sw.doc", "before create DrawDocument" ); // The document owns the SdrModel. We always have two layers and one page. mpDrawModel = new SwDrawDocument( &m_rSwdoc ); mpDrawModel->EnableUndo( m_rSwdoc.GetIDocumentUndoRedo().DoesUndo() ); OUString sLayerNm; sLayerNm = "Hell"; mnHell = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); sLayerNm = "Heaven"; mnHeaven = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); sLayerNm = "Controls"; mnControls = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); // add invisible layers corresponding to the visible ones. { sLayerNm = "InvisibleHell"; mnInvisibleHell = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); sLayerNm = "InvisibleHeaven"; mnInvisibleHeaven = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); sLayerNm = "InvisibleControls"; mnInvisibleControls = mpDrawModel->GetLayerAdmin().NewLayer( sLayerNm )->GetID(); } SdrPage* pMasterPage = mpDrawModel->AllocPage( false ); mpDrawModel->InsertPage( pMasterPage ); SAL_INFO( "sw.doc", "after create DrawDocument" ); SAL_INFO( "sw.doc", "before create Spellchecker/Hyphenator" ); SdrOutliner& rOutliner = mpDrawModel->GetDrawOutliner(); ::com::sun::star::uno::Reference< com::sun::star::linguistic2::XSpellChecker1 > xSpell = ::GetSpellChecker(); rOutliner.SetSpeller( xSpell ); ::com::sun::star::uno::Reference< com::sun::star::linguistic2::XHyphenator > xHyphenator( ::GetHyphenator() ); rOutliner.SetHyphenator( xHyphenator ); SAL_INFO( "sw.doc", "after create Spellchecker/Hyphenator" ); m_rSwdoc.SetCalcFieldValueHdl(&rOutliner); m_rSwdoc.SetCalcFieldValueHdl(&mpDrawModel->GetHitTestOutliner()); // Set the LinkManager in the model so that linked graphics can be inserted. // The WinWord import needs it too. mpDrawModel->SetLinkManager( & m_rSwdoc.GetLinkManager() ); mpDrawModel->SetAddExtLeading( m_rSwdoc.getIDocumentSettingAccess().get(IDocumentSettingAccess::ADD_EXT_LEADING) ); OutputDevice* pRefDev = m_rSwdoc.getIDocumentDeviceAccess().getReferenceDevice( false ); if ( pRefDev ) mpDrawModel->SetRefDevice( pRefDev ); mpDrawModel->SetNotifyUndoActionHdl( LINK( &m_rSwdoc, SwDoc, AddDrawUndo )); if ( m_rSwdoc.GetCurrentViewShell() ) { SwViewShell* pViewSh = m_rSwdoc.GetCurrentViewShell(); do { SwRootFrm* pRoot = pViewSh->GetLayout(); if( pRoot && !pRoot->GetDrawPage() ) { // Disable "multiple layout" for the moment: // use pMasterPage instead of a new created SdrPage // mpDrawModel->AllocPage( FALSE ); // mpDrawModel->InsertPage( pDrawPage ); SdrPage* pDrawPage = pMasterPage; pRoot->SetDrawPage( pDrawPage ); pDrawPage->SetSize( pRoot->Frm().SSize() ); } pViewSh = (SwViewShell*)pViewSh->GetNext(); }while( pViewSh != m_rSwdoc.GetCurrentViewShell() ); } } void DocumentDrawModelManager::ReleaseDrawModel() { if ( mpDrawModel ) { // !! Also maintain the code in the sw3io for inserting documents!! delete mpDrawModel; mpDrawModel = 0; //UUUU // SfxItemPool *pSdrPool = GetAttrPool().GetSecondaryPool(); // // OSL_ENSURE( pSdrPool, "missing pool" ); // SfxItemPool *pEEgPool = pSdrPool->GetSecondaryPool(); // OSL_ENSURE( !pEEgPool->GetSecondaryPool(), "I don't accept additional pools"); // pSdrPool->Delete(); // First have the items destroyed, // // then destroy the chain! // GetAttrPool().SetSecondaryPool( 0 ); // This one's a must! // pSdrPool->SetSecondaryPool( 0 ); // That one's safer // SfxItemPool::Free(pSdrPool); // SfxItemPool::Free(pEEgPool); } } const SdrModel* DocumentDrawModelManager::GetDrawModel() const { return mpDrawModel; } SdrModel* DocumentDrawModelManager::GetDrawModel() { return mpDrawModel; } SdrModel* DocumentDrawModelManager::_MakeDrawModel() { OSL_ENSURE( !mpDrawModel, "_MakeDrawModel: Why?" ); InitDrawModel(); if ( m_rSwdoc.GetCurrentViewShell() ) { SwViewShell* pTmp = m_rSwdoc.GetCurrentViewShell(); do { pTmp->MakeDrawView(); pTmp = (SwViewShell*) pTmp->GetNext(); } while ( pTmp != m_rSwdoc.GetCurrentViewShell() ); // Broadcast, so that the FormShell can be connected to the DrawView if( m_rSwdoc.GetDocShell() ) { SfxSimpleHint aHnt( SW_BROADCAST_DRAWVIEWS_CREATED ); m_rSwdoc.GetDocShell()->Broadcast( aHnt ); } } return mpDrawModel; } SdrModel* DocumentDrawModelManager::GetOrCreateDrawModel() { return GetDrawModel() ? GetDrawModel() : _MakeDrawModel(); } SdrLayerID DocumentDrawModelManager::GetHeavenId() const { return mnHeaven; } SdrLayerID DocumentDrawModelManager::GetHellId() const { return mnHell; } SdrLayerID DocumentDrawModelManager::GetControlsId() const { return mnControls; } SdrLayerID DocumentDrawModelManager::GetInvisibleHeavenId() const { return mnInvisibleHeaven; } SdrLayerID DocumentDrawModelManager::GetInvisibleHellId() const { return mnInvisibleHell; } SdrLayerID DocumentDrawModelManager::GetInvisibleControlsId() const { return mnInvisibleControls; } void DocumentDrawModelManager::NotifyInvisibleLayers( SdrPageView& _rSdrPageView ) { OUString sLayerNm; sLayerNm = "InvisibleHell"; _rSdrPageView.SetLayerVisible( sLayerNm, false ); sLayerNm = "InvisibleHeaven"; _rSdrPageView.SetLayerVisible( sLayerNm, false ); sLayerNm = "InvisibleControls"; _rSdrPageView.SetLayerVisible( sLayerNm, false ); } bool DocumentDrawModelManager::IsVisibleLayerId( const SdrLayerID& _nLayerId ) const { bool bRetVal; if ( _nLayerId == GetHeavenId() || _nLayerId == GetHellId() || _nLayerId == GetControlsId() ) { bRetVal = true; } else if ( _nLayerId == GetInvisibleHeavenId() || _nLayerId == GetInvisibleHellId() || _nLayerId == GetInvisibleControlsId() ) { bRetVal = false; } else { OSL_FAIL( "<SwDoc::IsVisibleLayerId(..)> - unknown layer ID." ); bRetVal = false; } return bRetVal; } SdrLayerID DocumentDrawModelManager::GetVisibleLayerIdByInvisibleOne( const SdrLayerID& _nInvisibleLayerId ) { SdrLayerID nVisibleLayerId; if ( _nInvisibleLayerId == GetInvisibleHeavenId() ) { nVisibleLayerId = GetHeavenId(); } else if ( _nInvisibleLayerId == GetInvisibleHellId() ) { nVisibleLayerId = GetHellId(); } else if ( _nInvisibleLayerId == GetInvisibleControlsId() ) { nVisibleLayerId = GetControlsId(); } else if ( _nInvisibleLayerId == GetHeavenId() || _nInvisibleLayerId == GetHellId() || _nInvisibleLayerId == GetControlsId() ) { OSL_FAIL( "<SwDoc::GetVisibleLayerIdByInvisibleOne(..)> - given layer ID already an invisible one." ); nVisibleLayerId = _nInvisibleLayerId; } else { OSL_FAIL( "<SwDoc::GetVisibleLayerIdByInvisibleOne(..)> - given layer ID is unknown." ); nVisibleLayerId = _nInvisibleLayerId; } return nVisibleLayerId; } SdrLayerID DocumentDrawModelManager::GetInvisibleLayerIdByVisibleOne( const SdrLayerID& _nVisibleLayerId ) { SdrLayerID nInvisibleLayerId; if ( _nVisibleLayerId == GetHeavenId() ) { nInvisibleLayerId = GetInvisibleHeavenId(); } else if ( _nVisibleLayerId == GetHellId() ) { nInvisibleLayerId = GetInvisibleHellId(); } else if ( _nVisibleLayerId == GetControlsId() ) { nInvisibleLayerId = GetInvisibleControlsId(); } else if ( _nVisibleLayerId == GetInvisibleHeavenId() || _nVisibleLayerId == GetInvisibleHellId() || _nVisibleLayerId == GetInvisibleControlsId() ) { OSL_FAIL( "<SwDoc::GetInvisibleLayerIdByVisibleOne(..)> - given layer ID already an invisible one." ); nInvisibleLayerId = _nVisibleLayerId; } else { OSL_FAIL( "<SwDoc::GetInvisibleLayerIdByVisibleOne(..)> - given layer ID is unknown." ); nInvisibleLayerId = _nVisibleLayerId; } return nInvisibleLayerId; } void DocumentDrawModelManager::DrawNotifyUndoHdl() { mpDrawModel->SetNotifyUndoActionHdl( Link() ); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "Display.h" #include "InputValidator.h" #include "MetaParser.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <fstream> #include <cstdlib> #include <cctype> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #else #include <io.h> #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif using namespace clang; namespace cling { MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII( MetaProcessor* p) :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) { StringRef redirectionFile; if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); redirect(stdout, redirectionFile.str(), kSTDOUT); } if (!m_MetaProcessor->m_PrevStderrFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back(); // Deal with the case 2>&1 and 2&>1 if (strcmp(redirectionFile.data(), "_IO_2_1_stdout_") == 0) { // If out is redirected to a file. if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); } else { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } redirect(stderr, redirectionFile.str(), kSTDERR); } } void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file, const std::string& fileName, MetaProcessor::RedirectionScope scope) { if (!fileName.empty()) { FILE* redirectionFile = freopen(fileName.c_str(), "a", file); if (!redirectionFile) { llvm::errs()<<"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:" " Not succefully reopened the redirection file " << fileName.c_str() << "\n."; } else { m_isCurrentlyRedirecting |= scope; } } } void MetaProcessor::MaybeRedirectOutputRAII::pop() { if (m_isCurrentlyRedirecting & kSTDOUT) { unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout); } if (m_isCurrentlyRedirecting & kSTDERR) { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD, int expectedFD, FILE* file) { // Switch back to previous file after line is processed. // Flush the current content if there is any. if (!feof(file)) { fflush(file); } // Copy the original fd for the std. if (dup2(backupFD, expectedFD) != expectedFD) { llvm::errs() << "cling::MetaProcessor::unredirect " << "The unredirection file descriptor not valid " << backupFD << ".\n"; } } MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs) : m_Interp(interp), m_Outs(&outs) { m_InputValidator.reset(new InputValidator()); m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this))); m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO); m_backupFDStderr = copyFileDescriptor(STDERR_FILENO); } MetaProcessor::~MetaProcessor() {} int MetaProcessor::process(const char* input_text, Interpreter::CompilationResult& compRes, Value* result) { if (result) *result = Value(); compRes = Interpreter::kSuccess; int expectedIndent = m_InputValidator->getExpectedIndent(); if (expectedIndent) compRes = Interpreter::kMoreInputExpected; if (!input_text || !input_text[0]) { // nullptr / empty string, nothing to do. return expectedIndent; } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return expectedIndent; } // Check for and handle meta commands. m_MetaParser->enterNewInputLine(input_line); MetaSema::ActionResult actionResult = MetaSema::AR_Success; if (m_MetaParser->isMetaCommand(actionResult, result)) { if (m_MetaParser->isQuitRequested()) return -1; if (actionResult != MetaSema::AR_Success) compRes = Interpreter::kFailure; // ExpectedIndent might have changed after meta command. return m_InputValidator->getExpectedIndent(); } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) { compRes = Interpreter::kMoreInputExpected; return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input = m_InputValidator->getInput(); m_InputValidator->reset(); // if (m_Options.RawInput) // compResLocal = m_Interp.declare(input); // else compRes = m_Interp.process(input, result); return 0; } void MetaProcessor::cancelContinuation() const { m_InputValidator->reset(); } int MetaProcessor::getExpectedIndent() const { return m_InputValidator->getExpectedIndent(); } Interpreter::CompilationResult MetaProcessor::readInputFromFile(llvm::StringRef filename, Value* result, bool ignoreOutmostBlock /*=false*/) { { // check that it's not binary: std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary); char magic[1024] = {0}; in.read(magic, sizeof(magic)); size_t readMagic = in.gcount(); if (readMagic >= 4) { llvm::StringRef magicStr(magic,in.gcount()); llvm::sys::fs::file_magic fileType = llvm::sys::fs::identify_magic(magicStr); if (fileType != llvm::sys::fs::file_magic::unknown) { llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a binary file!\n"; return Interpreter::kFailure; } unsigned printable = 0; for (size_t i = 0; i < readMagic; ++i) if (isprint(magic[i])) ++printable; if (10 * printable < 5 * readMagic) { // 50% printable for ASCII files should be a safe guess. llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a (likely) binary file!\n" << printable; return Interpreter::kFailure; } } } std::ifstream in(filename.str().c_str()); in.seekg(0, std::ios::end); size_t size = in.tellg(); std::string content(size, ' '); in.seekg(0); in.read(&content[0], size); if (ignoreOutmostBlock && !content.empty()) { static const char whitespace[] = " \t\r\n"; std::string::size_type posNonWS = content.find_first_not_of(whitespace); // Handle comments before leading { while (posNonWS != std::string::npos && content[posNonWS] == '/' && content[posNonWS+1] == '/') { // Remove the comment line posNonWS = content.find_first_of('\n', posNonWS+2)+1; } std::string::size_type replaced = posNonWS; if (posNonWS != std::string::npos) { if (content[posNonWS] == '{') { // hide the curly brace: content[posNonWS] = ' '; // and the matching closing '}' posNonWS = content.find_last_not_of(whitespace); if (posNonWS != std::string::npos) { if (content[posNonWS] == ';' && content[posNonWS-1] == '}') { content[posNonWS--] = ' '; // replace ';' and enter next if } if (content[posNonWS] == '}') { content[posNonWS] = ' '; // replace '}' } else { std::string::size_type posBlockClose = content.find_last_of('}'); if (posBlockClose != std::string::npos) { content[posBlockClose] = ' '; // replace '}' } std::string::size_type posComment = content.find_first_not_of(whitespace, posComment); if (posComment != std::string::npos) { if (content[posComment] == '/' && content[posComment+1] == '/') { // More text (comments) are okay after the last '}', but // we can not easily find it to remove it (so we need to upgrade // this code to better handle the case with comments or // preprocessor code before and after the leading { and // trailing }) while (posComment <= posNonWS) { content[posComment++] = ' '; // replace '}' and comment } } else { content[replaced] = '{'; // By putting the '{' back, we keep the code as consistent as // the user wrote it ... but we should still warn that we not // goint to treat this file an unamed macro. llvm::errs() << "Warning in cling::MetaProcessor: can not find the closing '}', " << llvm::sys::path::filename(filename) << " is not handled as an unamed script!\n"; } // did not find '}'' } // no whitespace } // remove comments after the trailing '}' } // find '}' } // have '{' } // have non-whitespace } // ignore outmost block std::string strFilename(filename.str()); m_CurrentlyExecutingFile = strFilename; bool topmost = !m_TopExecutingFile.data(); if (topmost) m_TopExecutingFile = m_CurrentlyExecutingFile; Interpreter::CompilationResult ret; // We don't want to value print the results of a unnamed macro. content = "#line 2 \"" + filename.str() + "\" \n" + content; if (process((content + ";").c_str(), ret, result)) { // Input file has to be complete. llvm::errs() << "Error in cling::MetaProcessor: file " << llvm::sys::path::filename(filename) << " is incomplete (missing parenthesis or similar)!\n"; ret = Interpreter::kFailure; } m_CurrentlyExecutingFile = llvm::StringRef(); if (topmost) m_TopExecutingFile = llvm::StringRef(); return ret; } void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd, llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) { // If we have a fileName to redirect to store it. if (!file.empty()) { prevFileStack.push_back(file); // pop and push a null terminating 0. // SmallVectorImpl<T> does not have a c_str(), thus instead of casting to // a SmallString<T> we null terminate the data that we have and pop the // 0 char back. prevFileStack.back().push_back(0); prevFileStack.back().pop_back(); if (!append) { FILE * f; if (!(f = fopen(file.data(), "w"))) { llvm::errs() << "cling::MetaProcessor::setFileStream:" " The file path " << file.data() << "is not valid."; } else { fclose(f); } } // Else unredirection, so switch to the previous file. } else { // If there is no previous file on the stack we pop the file if (!prevFileStack.empty()) { prevFileStack.pop_back(); } } } void MetaProcessor::setStdStream(llvm::StringRef file, RedirectionScope stream, bool append) { if (stream & kSTDOUT) { setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName); } if (stream & kSTDERR) { setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName); } } int MetaProcessor::copyFileDescriptor(int fd) { int backupFD = dup(fd); if (backupFD < 0) { llvm::errs() << "MetaProcessor::copyFileDescriptor: Duplicating the file" " descriptor " << fd << "resulted in an error." " Will not be able to unredirect."; } return backupFD; } void MetaProcessor::registerUnloadPoint(const Transaction* T, llvm::StringRef filename) { m_MetaParser->getActions().registerUnloadPoint(T, filename); } } // end namespace cling <commit_msg>Fix var name typo in find_first_not_of; combine if-s.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "Display.h" #include "InputValidator.h" #include "MetaParser.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <fstream> #include <cstdlib> #include <cctype> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #else #include <io.h> #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif using namespace clang; namespace cling { MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII( MetaProcessor* p) :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) { StringRef redirectionFile; if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); redirect(stdout, redirectionFile.str(), kSTDOUT); } if (!m_MetaProcessor->m_PrevStderrFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back(); // Deal with the case 2>&1 and 2&>1 if (strcmp(redirectionFile.data(), "_IO_2_1_stdout_") == 0) { // If out is redirected to a file. if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); } else { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } redirect(stderr, redirectionFile.str(), kSTDERR); } } void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file, const std::string& fileName, MetaProcessor::RedirectionScope scope) { if (!fileName.empty()) { FILE* redirectionFile = freopen(fileName.c_str(), "a", file); if (!redirectionFile) { llvm::errs()<<"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:" " Not succefully reopened the redirection file " << fileName.c_str() << "\n."; } else { m_isCurrentlyRedirecting |= scope; } } } void MetaProcessor::MaybeRedirectOutputRAII::pop() { if (m_isCurrentlyRedirecting & kSTDOUT) { unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout); } if (m_isCurrentlyRedirecting & kSTDERR) { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD, int expectedFD, FILE* file) { // Switch back to previous file after line is processed. // Flush the current content if there is any. if (!feof(file)) { fflush(file); } // Copy the original fd for the std. if (dup2(backupFD, expectedFD) != expectedFD) { llvm::errs() << "cling::MetaProcessor::unredirect " << "The unredirection file descriptor not valid " << backupFD << ".\n"; } } MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs) : m_Interp(interp), m_Outs(&outs) { m_InputValidator.reset(new InputValidator()); m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this))); m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO); m_backupFDStderr = copyFileDescriptor(STDERR_FILENO); } MetaProcessor::~MetaProcessor() {} int MetaProcessor::process(const char* input_text, Interpreter::CompilationResult& compRes, Value* result) { if (result) *result = Value(); compRes = Interpreter::kSuccess; int expectedIndent = m_InputValidator->getExpectedIndent(); if (expectedIndent) compRes = Interpreter::kMoreInputExpected; if (!input_text || !input_text[0]) { // nullptr / empty string, nothing to do. return expectedIndent; } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return expectedIndent; } // Check for and handle meta commands. m_MetaParser->enterNewInputLine(input_line); MetaSema::ActionResult actionResult = MetaSema::AR_Success; if (m_MetaParser->isMetaCommand(actionResult, result)) { if (m_MetaParser->isQuitRequested()) return -1; if (actionResult != MetaSema::AR_Success) compRes = Interpreter::kFailure; // ExpectedIndent might have changed after meta command. return m_InputValidator->getExpectedIndent(); } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) { compRes = Interpreter::kMoreInputExpected; return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input = m_InputValidator->getInput(); m_InputValidator->reset(); // if (m_Options.RawInput) // compResLocal = m_Interp.declare(input); // else compRes = m_Interp.process(input, result); return 0; } void MetaProcessor::cancelContinuation() const { m_InputValidator->reset(); } int MetaProcessor::getExpectedIndent() const { return m_InputValidator->getExpectedIndent(); } Interpreter::CompilationResult MetaProcessor::readInputFromFile(llvm::StringRef filename, Value* result, bool ignoreOutmostBlock /*=false*/) { { // check that it's not binary: std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary); char magic[1024] = {0}; in.read(magic, sizeof(magic)); size_t readMagic = in.gcount(); if (readMagic >= 4) { llvm::StringRef magicStr(magic,in.gcount()); llvm::sys::fs::file_magic fileType = llvm::sys::fs::identify_magic(magicStr); if (fileType != llvm::sys::fs::file_magic::unknown) { llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a binary file!\n"; return Interpreter::kFailure; } unsigned printable = 0; for (size_t i = 0; i < readMagic; ++i) if (isprint(magic[i])) ++printable; if (10 * printable < 5 * readMagic) { // 50% printable for ASCII files should be a safe guess. llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a (likely) binary file!\n" << printable; return Interpreter::kFailure; } } } std::ifstream in(filename.str().c_str()); in.seekg(0, std::ios::end); size_t size = in.tellg(); std::string content(size, ' '); in.seekg(0); in.read(&content[0], size); if (ignoreOutmostBlock && !content.empty()) { static const char whitespace[] = " \t\r\n"; std::string::size_type posNonWS = content.find_first_not_of(whitespace); // Handle comments before leading { while (posNonWS != std::string::npos && content[posNonWS] == '/' && content[posNonWS+1] == '/') { // Remove the comment line posNonWS = content.find_first_of('\n', posNonWS+2)+1; } std::string::size_type replaced = posNonWS; if (posNonWS != std::string::npos && content[posNonWS] == '{') { // hide the curly brace: content[posNonWS] = ' '; // and the matching closing '}' posNonWS = content.find_last_not_of(whitespace); if (posNonWS != std::string::npos) { if (content[posNonWS] == ';' && content[posNonWS-1] == '}') { content[posNonWS--] = ' '; // replace ';' and enter next if } if (content[posNonWS] == '}') { content[posNonWS] = ' '; // replace '}' } else { std::string::size_type posBlockClose = content.find_last_of('}'); if (posBlockClose != std::string::npos) { content[posBlockClose] = ' '; // replace '}' } std::string::size_type posComment = content.find_first_not_of(whitespace, posBlockClose); if (posComment != std::string::npos && content[posComment] == '/' && content[posComment+1] == '/') { // More text (comments) are okay after the last '}', but // we can not easily find it to remove it (so we need to upgrade // this code to better handle the case with comments or // preprocessor code before and after the leading { and // trailing }) while (posComment <= posNonWS) { content[posComment++] = ' '; // replace '}' and comment } } else { content[replaced] = '{'; // By putting the '{' back, we keep the code as consistent as // the user wrote it ... but we should still warn that we not // goint to treat this file an unamed macro. llvm::errs() << "Warning in cling::MetaProcessor: can not find the closing '}', " << llvm::sys::path::filename(filename) << " is not handled as an unamed script!\n"; } // did not find "//" } // remove comments after the trailing '}' } // find '}' } // have '{' } // ignore outmost block std::string strFilename(filename.str()); m_CurrentlyExecutingFile = strFilename; bool topmost = !m_TopExecutingFile.data(); if (topmost) m_TopExecutingFile = m_CurrentlyExecutingFile; Interpreter::CompilationResult ret; // We don't want to value print the results of a unnamed macro. content = "#line 2 \"" + filename.str() + "\" \n" + content; if (process((content + ";").c_str(), ret, result)) { // Input file has to be complete. llvm::errs() << "Error in cling::MetaProcessor: file " << llvm::sys::path::filename(filename) << " is incomplete (missing parenthesis or similar)!\n"; ret = Interpreter::kFailure; } m_CurrentlyExecutingFile = llvm::StringRef(); if (topmost) m_TopExecutingFile = llvm::StringRef(); return ret; } void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd, llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) { // If we have a fileName to redirect to store it. if (!file.empty()) { prevFileStack.push_back(file); // pop and push a null terminating 0. // SmallVectorImpl<T> does not have a c_str(), thus instead of casting to // a SmallString<T> we null terminate the data that we have and pop the // 0 char back. prevFileStack.back().push_back(0); prevFileStack.back().pop_back(); if (!append) { FILE * f; if (!(f = fopen(file.data(), "w"))) { llvm::errs() << "cling::MetaProcessor::setFileStream:" " The file path " << file.data() << "is not valid."; } else { fclose(f); } } // Else unredirection, so switch to the previous file. } else { // If there is no previous file on the stack we pop the file if (!prevFileStack.empty()) { prevFileStack.pop_back(); } } } void MetaProcessor::setStdStream(llvm::StringRef file, RedirectionScope stream, bool append) { if (stream & kSTDOUT) { setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName); } if (stream & kSTDERR) { setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName); } } int MetaProcessor::copyFileDescriptor(int fd) { int backupFD = dup(fd); if (backupFD < 0) { llvm::errs() << "MetaProcessor::copyFileDescriptor: Duplicating the file" " descriptor " << fd << "resulted in an error." " Will not be able to unredirect."; } return backupFD; } void MetaProcessor::registerUnloadPoint(const Transaction* T, llvm::StringRef filename) { m_MetaParser->getActions().registerUnloadPoint(T, filename); } } // end namespace cling <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Alexander Rössler ** License: LGPL version 2.1 ** ** This file is part of QtQuickVcp. ** ** All rights reserved. This program and the accompanying materials ** are made available under the terms of the GNU Lesser General Public License ** (LGPL) version 2.1 which accompanies this distribution, and is available at ** http://www.gnu.org/licenses/lgpl-2.1.html ** ** 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. ** ** Contributors: ** Alexander Rössler @ The Cool Tool GmbH <mail DOT aroessler AT gmail DOT com> ** ****************************************************************************/ #include "qpreviewclient.h" #include "debughelper.h" QPreviewClient::QPreviewClient(QObject *parent) : AbstractServiceImplementation(parent), m_statusUri(""), m_previewUri(""), m_connectionState(Disconnected), m_connected(false), m_error(NoError), m_errorString(""), m_model(nullptr), m_interpreterState(InterpreterStateUnset), m_interpreterNote(""), m_context(nullptr), m_statusSocket(nullptr), m_previewSocket(nullptr), m_previewUpdated(false) { m_previewStatus.fileName = "test.ngc"; m_previewStatus.lineNumber = 0; } void QPreviewClient::start() { #ifdef QT_DEBUG DEBUG_TAG(1, "preview", "start") #endif updateState(Connecting); if (connectSockets()) { m_statusSocket->subscribeTo("status"); m_previewSocket->subscribeTo("preview"); updateState(Connected); //TODO: add something like a ping } } void QPreviewClient::stop() { #ifdef QT_DEBUG DEBUG_TAG(1, "preview", "stop") #endif cleanup(); updateState(Disconnected); // clears the error } void QPreviewClient::cleanup() { disconnectSockets(); } void QPreviewClient::updateState(QPreviewClient::State state) { updateState(state, NoError, ""); } void QPreviewClient::updateState(QPreviewClient::State state, QPreviewClient::ConnectionError error, QString errorString) { if (state != m_connectionState) { if (m_connected != (state == Connected)) { m_connected = (state == Connected); emit connectedChanged(m_connected); } m_connectionState = state; emit connectionStateChanged(m_connectionState); } updateError(error, errorString); } void QPreviewClient::updateError(QPreviewClient::ConnectionError error, QString errorString) { if (m_errorString != errorString) { m_errorString = errorString; emit errorStringChanged(m_errorString); } if (m_error != error) { if (error != NoError) { cleanup(); } m_error = error; emit errorChanged(m_error); } } /** Processes all message received on the status 0MQ socket */ void QPreviewClient::statusMessageReceived(QList<QByteArray> messageList) { QByteArray topic; topic = messageList.at(0); m_rx.ParseFromArray(messageList.at(1).data(), messageList.at(1).size()); #ifdef QT_DEBUG std::string s; gpb::TextFormat::PrintToString(m_rx, &s); DEBUG_TAG(3, "preview", "status update" << topic << QString::fromStdString(s)) #endif if (m_rx.type() == pb::MT_INTERP_STAT) { QStringList notes; m_interpreterState = (InterpreterState)m_rx.interp_state(); for (int i = 0; i< m_rx.note_size(); ++i) { notes.append(QString::fromStdString(m_rx.note(i))); } m_interpreterNote = notes.join("\n"); emit interpreterNoteChanged(m_interpreterNote); emit interpreterStateChanged(m_interpreterState); if ((m_interpreterState == InterpreterIdle) && m_previewUpdated && m_model) { m_model->endUpdate(); } } } /** Processes all message received on the preview 0MQ socket */ void QPreviewClient::previewMessageReceived(QList<QByteArray> messageList) { QByteArray topic; topic = messageList.at(0); m_rx.ParseFromArray(messageList.at(1).data(), messageList.at(1).size()); #ifdef QT_DEBUG std::string s; gpb::TextFormat::PrintToString(m_rx, &s); DEBUG_TAG(3, "preview", "preview update" << topic << QString::fromStdString(s)) #endif if (m_rx.type() == pb::MT_PREVIEW) { if (m_model == nullptr) { return; } for (int i = 0; i < m_rx.preview_size(); ++i) { pb::Preview preview; QModelIndex index; preview = m_rx.preview(i); if (preview.has_line_number()) { m_previewStatus.lineNumber = preview.line_number(); } if (preview.has_filename()) { m_previewStatus.fileName = QString::fromStdString(preview.filename()); } if (preview.has_first_axis()) { } if (preview.has_second_axis()) { } index = m_model->index(m_previewStatus.fileName, m_previewStatus.lineNumber); m_model->addPreviewItem(index, preview); m_previewUpdated = true; } } } void QPreviewClient::pollError(int errorNum, const QString &errorMsg) { QString errorString; errorString = QString("Error %1: ").arg(errorNum) + errorMsg; updateState(Error, SocketError, errorString); } /** Connects the 0MQ sockets */ bool QPreviewClient::connectSockets() { m_context = new PollingZMQContext(this, 1); connect(m_context, SIGNAL(pollError(int,QString)), this, SLOT(pollError(int,QString))); m_context->start(); m_statusSocket = m_context->createSocket(ZMQSocket::TYP_SUB, this); m_statusSocket->setLinger(0); m_previewSocket = m_context->createSocket(ZMQSocket::TYP_SUB, this); m_previewSocket->setLinger(0); try { m_statusSocket->connectTo(m_statusUri); m_previewSocket->connectTo(m_previewUri); } catch (const zmq::error_t &e) { QString errorString; errorString = QString("Error %1: ").arg(e.num()) + QString(e.what()); updateState(Error, SocketError, errorString); return false; } connect(m_statusSocket, SIGNAL(messageReceived(QList<QByteArray>)), this, SLOT(statusMessageReceived(QList<QByteArray>))); connect(m_previewSocket, SIGNAL(messageReceived(QList<QByteArray>)), this, SLOT(previewMessageReceived(QList<QByteArray>))); #ifdef QT_DEBUG DEBUG_TAG(1, "preview", "sockets connected" << m_statusUri << m_previewUri) #endif return true; } /** Disconnects the 0MQ sockets */ void QPreviewClient::disconnectSockets() { if (m_statusSocket != nullptr) { m_statusSocket->close(); m_statusSocket->deleteLater(); m_statusSocket = nullptr; } if (m_previewSocket != nullptr) { m_previewSocket->close(); m_previewSocket->deleteLater(); m_previewSocket = nullptr; } if (m_context != nullptr) { m_context->stop(); m_context->deleteLater(); m_context = nullptr; } } <commit_msg>PreviewClient: fix problem when line number = 0<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Alexander Rössler ** License: LGPL version 2.1 ** ** This file is part of QtQuickVcp. ** ** All rights reserved. This program and the accompanying materials ** are made available under the terms of the GNU Lesser General Public License ** (LGPL) version 2.1 which accompanies this distribution, and is available at ** http://www.gnu.org/licenses/lgpl-2.1.html ** ** 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. ** ** Contributors: ** Alexander Rössler @ The Cool Tool GmbH <mail DOT aroessler AT gmail DOT com> ** ****************************************************************************/ #include "qpreviewclient.h" #include "debughelper.h" QPreviewClient::QPreviewClient(QObject *parent) : AbstractServiceImplementation(parent), m_statusUri(""), m_previewUri(""), m_connectionState(Disconnected), m_connected(false), m_error(NoError), m_errorString(""), m_model(nullptr), m_interpreterState(InterpreterStateUnset), m_interpreterNote(""), m_context(nullptr), m_statusSocket(nullptr), m_previewSocket(nullptr), m_previewUpdated(false) { m_previewStatus.fileName = "test.ngc"; m_previewStatus.lineNumber = 0; } void QPreviewClient::start() { #ifdef QT_DEBUG DEBUG_TAG(1, "preview", "start") #endif updateState(Connecting); if (connectSockets()) { m_statusSocket->subscribeTo("status"); m_previewSocket->subscribeTo("preview"); updateState(Connected); //TODO: add something like a ping } } void QPreviewClient::stop() { #ifdef QT_DEBUG DEBUG_TAG(1, "preview", "stop") #endif cleanup(); updateState(Disconnected); // clears the error } void QPreviewClient::cleanup() { disconnectSockets(); } void QPreviewClient::updateState(QPreviewClient::State state) { updateState(state, NoError, ""); } void QPreviewClient::updateState(QPreviewClient::State state, QPreviewClient::ConnectionError error, QString errorString) { if (state != m_connectionState) { if (m_connected != (state == Connected)) { m_connected = (state == Connected); emit connectedChanged(m_connected); } m_connectionState = state; emit connectionStateChanged(m_connectionState); } updateError(error, errorString); } void QPreviewClient::updateError(QPreviewClient::ConnectionError error, QString errorString) { if (m_errorString != errorString) { m_errorString = errorString; emit errorStringChanged(m_errorString); } if (m_error != error) { if (error != NoError) { cleanup(); } m_error = error; emit errorChanged(m_error); } } /** Processes all message received on the status 0MQ socket */ void QPreviewClient::statusMessageReceived(QList<QByteArray> messageList) { QByteArray topic; topic = messageList.at(0); m_rx.ParseFromArray(messageList.at(1).data(), messageList.at(1).size()); #ifdef QT_DEBUG std::string s; gpb::TextFormat::PrintToString(m_rx, &s); DEBUG_TAG(3, "preview", "status update" << topic << QString::fromStdString(s)) #endif if (m_rx.type() == pb::MT_INTERP_STAT) { QStringList notes; m_interpreterState = (InterpreterState)m_rx.interp_state(); for (int i = 0; i< m_rx.note_size(); ++i) { notes.append(QString::fromStdString(m_rx.note(i))); } m_interpreterNote = notes.join("\n"); emit interpreterNoteChanged(m_interpreterNote); emit interpreterStateChanged(m_interpreterState); if ((m_interpreterState == InterpreterIdle) && m_previewUpdated && m_model) { m_model->endUpdate(); } } } /** Processes all message received on the preview 0MQ socket */ void QPreviewClient::previewMessageReceived(QList<QByteArray> messageList) { QByteArray topic; topic = messageList.at(0); m_rx.ParseFromArray(messageList.at(1).data(), messageList.at(1).size()); #ifdef QT_DEBUG std::string s; gpb::TextFormat::PrintToString(m_rx, &s); DEBUG_TAG(3, "preview", "preview update" << topic << QString::fromStdString(s)) #endif if (m_rx.type() == pb::MT_PREVIEW) { if (m_model == nullptr) { return; } for (int i = 0; i < m_rx.preview_size(); ++i) { pb::Preview preview; QModelIndex index; preview = m_rx.preview(i); if (preview.has_line_number()) { m_previewStatus.lineNumber = qMax(preview.line_number(), 1); // line number 0 == at beginning of file } if (preview.has_filename()) { m_previewStatus.fileName = QString::fromStdString(preview.filename()); } if (preview.has_first_axis()) { } if (preview.has_second_axis()) { } index = m_model->index(m_previewStatus.fileName, m_previewStatus.lineNumber); m_model->addPreviewItem(index, preview); m_previewUpdated = true; } } } void QPreviewClient::pollError(int errorNum, const QString &errorMsg) { QString errorString; errorString = QString("Error %1: ").arg(errorNum) + errorMsg; updateState(Error, SocketError, errorString); } /** Connects the 0MQ sockets */ bool QPreviewClient::connectSockets() { m_context = new PollingZMQContext(this, 1); connect(m_context, SIGNAL(pollError(int,QString)), this, SLOT(pollError(int,QString))); m_context->start(); m_statusSocket = m_context->createSocket(ZMQSocket::TYP_SUB, this); m_statusSocket->setLinger(0); m_previewSocket = m_context->createSocket(ZMQSocket::TYP_SUB, this); m_previewSocket->setLinger(0); try { m_statusSocket->connectTo(m_statusUri); m_previewSocket->connectTo(m_previewUri); } catch (const zmq::error_t &e) { QString errorString; errorString = QString("Error %1: ").arg(e.num()) + QString(e.what()); updateState(Error, SocketError, errorString); return false; } connect(m_statusSocket, SIGNAL(messageReceived(QList<QByteArray>)), this, SLOT(statusMessageReceived(QList<QByteArray>))); connect(m_previewSocket, SIGNAL(messageReceived(QList<QByteArray>)), this, SLOT(previewMessageReceived(QList<QByteArray>))); #ifdef QT_DEBUG DEBUG_TAG(1, "preview", "sockets connected" << m_statusUri << m_previewUri) #endif return true; } /** Disconnects the 0MQ sockets */ void QPreviewClient::disconnectSockets() { if (m_statusSocket != nullptr) { m_statusSocket->close(); m_statusSocket->deleteLater(); m_statusSocket = nullptr; } if (m_previewSocket != nullptr) { m_previewSocket->close(); m_previewSocket->deleteLater(); m_previewSocket = nullptr; } if (m_context != nullptr) { m_context->stop(); m_context->deleteLater(); m_context = nullptr; } } <|endoftext|>
<commit_before><commit_msg>resampling nodata -9999<commit_after><|endoftext|>
<commit_before>/* * PyClaw.cpp * * Created on: Feb 18, 2012 * Author: kristof */ #include <Python.h> #include <numpy/arrayobject.h> #include "peanoclaw/pyclaw/PyClaw.h" #include "peanoclaw/pyclaw/PyClawState.h" #include "peanoclaw/Patch.h" #include "peano/utils/Loop.h" #include "tarch/timing/Watch.h" #include "tarch/parallel/Node.h" #include "tarch/multicore/Lock.h" #include "tarch/Assertions.h" tarch::logging::Log peanoclaw::pyclaw::PyClaw::_log("peanoclaw::pyclaw::PyClaw"); peanoclaw::pyclaw::PyClaw::PyClaw( InitializationCallback initializationCallback, BoundaryConditionCallback boundaryConditionCallback, SolverCallback solverCallback, RefinementCriterionCallback refinementCriterionCallback, AddPatchToSolutionCallback addPatchToSolutionCallback, peanoclaw::interSubgridCommunication::DefaultTransfer* transfer, peanoclaw::interSubgridCommunication::Interpolation* interpolation, peanoclaw::interSubgridCommunication::Restriction* restriction, peanoclaw::interSubgridCommunication::FluxCorrection* fluxCorrection ) : Numerics(transfer, interpolation, restriction, fluxCorrection), _initializationCallback(initializationCallback), _boundaryConditionCallback(boundaryConditionCallback), _solverCallback(solverCallback), _refinementCriterionCallback(refinementCriterionCallback), _addPatchToSolutionCallback(addPatchToSolutionCallback), _totalSolverCallbackTime(0.0), _cachedDemandedMeshWidth(-1.0), _cachedSubgridPosition(0.0), _cachedSubgridLevel(-1) { //import_array(); } peanoclaw::pyclaw::PyClaw::~PyClaw() { } void peanoclaw::pyclaw::PyClaw::initializePatch( Patch& patch ) { logTraceIn( "initializePatch(...)"); tarch::multicore::Lock lock(_semaphore); PyClawState state(patch); double demandedMeshWidth = _initializationCallback( state._q, state._qbc, state._aux, patch.getSubdivisionFactor()(0), patch.getSubdivisionFactor()(1), #ifdef Dim3 patch.getSubdivisionFactor()(2), #else 0, #endif patch.getUnknownsPerSubcell(), patch.getNumberOfParametersWithoutGhostlayerPerSubcell(), patch.getSize()(0), patch.getSize()(1), #ifdef Dim3 patch.getSize()(2), #else 0, #endif patch.getPosition()(0), patch.getPosition()(1), #ifdef Dim3 patch.getPosition()(2) #else 0 #endif ); //Cache demanded mesh width _cachedSubgridPosition = patch.getPosition(); _cachedSubgridLevel = patch.getLevel(); _cachedDemandedMeshWidth = tarch::la::Vector<DIMENSIONS,double>(demandedMeshWidth); logTraceOutWith1Argument( "initializePatch(...)", demandedMeshWidth); } void peanoclaw::pyclaw::PyClaw::solveTimestep(Patch& patch, double maximumTimestepSize, bool useDimensionalSplitting) { logTraceInWith2Arguments( "solveTimestep(...)", maximumTimestepSize, useDimensionalSplitting); tarch::multicore::Lock lock(_semaphore); assertion2(tarch::la::greater(maximumTimestepSize, 0.0), "max. Timestepsize == 0 should be checked outside.", patch.getTimeIntervals().getMinimalNeighborTimeConstraint()); assertion3(!patch.containsNaN(), patch, patch.toStringUNew(), patch.toStringUOldWithGhostLayer()); PyClawState state(patch); tarch::timing::Watch pyclawWatch("", "", false); pyclawWatch.startTimer(); double dtAndEstimatedNextDt[2]; dtAndEstimatedNextDt[0] = 0.0; dtAndEstimatedNextDt[1] = 0.0; bool doDummyTimestep = false; double requiredMeshWidth; if(doDummyTimestep) { dtAndEstimatedNextDt[0] = std::min(maximumTimestepSize, patch.getTimeIntervals().getEstimatedNextTimestepSize()); dtAndEstimatedNextDt[1] = patch.getTimeIntervals().getEstimatedNextTimestepSize(); requiredMeshWidth = patch.getSubcellSize()(0); } else { requiredMeshWidth = _solverCallback( dtAndEstimatedNextDt, state._q, state._qbc, state._aux, patch.getSubdivisionFactor()(0), patch.getSubdivisionFactor()(1), #ifdef Dim3 patch.getSubdivisionFactor()(2), #else 0, #endif patch.getUnknownsPerSubcell(), // meqn = nvar patch.getNumberOfParametersWithoutGhostlayerPerSubcell(), // naux patch.getSize()(0), patch.getSize()(1), #ifdef Dim3 patch.getSize()(2), #else 0, #endif patch.getPosition()(0), patch.getPosition()(1), #ifdef Dim3 patch.getPosition()(2), #else 0, #endif patch.getTimeIntervals().getCurrentTime() + patch.getTimeIntervals().getTimestepSize(), maximumTimestepSize, patch.getTimeIntervals().getEstimatedNextTimestepSize(), useDimensionalSplitting ); } pyclawWatch.stopTimer(); _totalSolverCallbackTime += pyclawWatch.getCalendarTime(); assertion3(tarch::la::greater(dtAndEstimatedNextDt[0], 0.0), patch, patch.toStringUNew(), patch.toStringUOldWithGhostLayer()); assertion4( tarch::la::greater(patch.getTimeIntervals().getTimestepSize(), 0.0) || tarch::la::greater(dtAndEstimatedNextDt[1], 0.0) || tarch::la::equals(maximumTimestepSize, 0.0) || tarch::la::equals(patch.getTimeIntervals().getEstimatedNextTimestepSize(), 0.0), patch, maximumTimestepSize, dtAndEstimatedNextDt[1], patch.toStringUNew()); assertion(patch.getTimeIntervals().getTimestepSize() < std::numeric_limits<double>::infinity()); //Check for zeros in solution assertion3(!patch.containsNonPositiveNumberInUnknownInUNew(0), patch, patch.toStringUNew(), patch.toStringUOldWithGhostLayer()); patch.getTimeIntervals().advanceInTime(); patch.getTimeIntervals().setTimestepSize(dtAndEstimatedNextDt[0]); //Cache demanded mesh width _cachedSubgridPosition = patch.getPosition(); _cachedSubgridLevel = patch.getLevel(); _cachedDemandedMeshWidth = tarch::la::Vector<DIMENSIONS,double>(requiredMeshWidth); logTraceOutWith1Argument( "solveTimestep(...)", requiredMeshWidth); } tarch::la::Vector<DIMENSIONS, double> peanoclaw::pyclaw::PyClaw::getDemandedMeshWidth(Patch& patch, bool isInitializing) { if( tarch::la::equals(patch.getPosition(), _cachedSubgridPosition) && patch.getLevel() == _cachedSubgridLevel ) { return _cachedDemandedMeshWidth; } else { PyClawState state(patch); double demandedMeshWidth = _refinementCriterionCallback( state._q, state._qbc, state._aux, patch.getSubdivisionFactor()(0), patch.getSubdivisionFactor()(1), #ifdef Dim3 patch.getSubdivisionFactor()(2), #else 0, #endif patch.getUnknownsPerSubcell(), patch.getNumberOfParametersWithoutGhostlayerPerSubcell(), patch.getSize()(0), patch.getSize()(1), #ifdef Dim3 patch.getSize()(2), #else 0, #endif patch.getPosition()(0), patch.getPosition()(1), #ifdef Dim3 patch.getPosition()(2) #else 0 #endif ); //Cache demanded mesh width _cachedSubgridPosition = patch.getPosition(); _cachedSubgridLevel = patch.getLevel(); _cachedDemandedMeshWidth = tarch::la::Vector<DIMENSIONS,double>(demandedMeshWidth); return _cachedDemandedMeshWidth; } } void peanoclaw::pyclaw::PyClaw::addPatchToSolution(Patch& patch) { tarch::multicore::Lock lock(_semaphore); PyClawState state(patch); assertion(_addPatchToSolutionCallback != 0); _addPatchToSolutionCallback( state._q, state._qbc, patch.getGhostlayerWidth(), patch.getSize()(0), patch.getSize()(1), #ifdef Dim3 patch.getSize()(2), #else 0, #endif patch.getPosition()(0), patch.getPosition()(1), #ifdef Dim3 patch.getPosition()(2), #else 0, #endif patch.getTimeIntervals().getCurrentTime()+patch.getTimeIntervals().getTimestepSize() ); } void peanoclaw::pyclaw::PyClaw::fillBoundaryLayer(Patch& patch, int dimension, bool setUpper) { logTraceInWith3Arguments("fillBoundaryLayerInPyClaw", patch, dimension, setUpper); tarch::multicore::Lock lock(_semaphore); logDebug("fillBoundaryLayerInPyClaw", "Setting boundary for " << patch.getPosition() << ", dim=" << dimension << ", setUpper=" << setUpper); PyClawState state(patch); _boundaryConditionCallback(state._q, state._qbc, dimension, setUpper ? 1 : 0); logTraceOut("fillBoundaryLayerInPyClaw"); } void peanoclaw::pyclaw::PyClaw::update(Patch& finePatch) { } <commit_msg>fixed estimated timestep size for pyclaw<commit_after>/* * PyClaw.cpp * * Created on: Feb 18, 2012 * Author: kristof */ #include <Python.h> #include <numpy/arrayobject.h> #include "peanoclaw/pyclaw/PyClaw.h" #include "peanoclaw/pyclaw/PyClawState.h" #include "peanoclaw/Patch.h" #include "peano/utils/Loop.h" #include "tarch/timing/Watch.h" #include "tarch/parallel/Node.h" #include "tarch/multicore/Lock.h" #include "tarch/Assertions.h" tarch::logging::Log peanoclaw::pyclaw::PyClaw::_log("peanoclaw::pyclaw::PyClaw"); peanoclaw::pyclaw::PyClaw::PyClaw( InitializationCallback initializationCallback, BoundaryConditionCallback boundaryConditionCallback, SolverCallback solverCallback, RefinementCriterionCallback refinementCriterionCallback, AddPatchToSolutionCallback addPatchToSolutionCallback, peanoclaw::interSubgridCommunication::DefaultTransfer* transfer, peanoclaw::interSubgridCommunication::Interpolation* interpolation, peanoclaw::interSubgridCommunication::Restriction* restriction, peanoclaw::interSubgridCommunication::FluxCorrection* fluxCorrection ) : Numerics(transfer, interpolation, restriction, fluxCorrection), _initializationCallback(initializationCallback), _boundaryConditionCallback(boundaryConditionCallback), _solverCallback(solverCallback), _refinementCriterionCallback(refinementCriterionCallback), _addPatchToSolutionCallback(addPatchToSolutionCallback), _totalSolverCallbackTime(0.0), _cachedDemandedMeshWidth(-1.0), _cachedSubgridPosition(0.0), _cachedSubgridLevel(-1) { //import_array(); } peanoclaw::pyclaw::PyClaw::~PyClaw() { } void peanoclaw::pyclaw::PyClaw::initializePatch( Patch& patch ) { logTraceIn( "initializePatch(...)"); tarch::multicore::Lock lock(_semaphore); PyClawState state(patch); double demandedMeshWidth = _initializationCallback( state._q, state._qbc, state._aux, patch.getSubdivisionFactor()(0), patch.getSubdivisionFactor()(1), #ifdef Dim3 patch.getSubdivisionFactor()(2), #else 0, #endif patch.getUnknownsPerSubcell(), patch.getNumberOfParametersWithoutGhostlayerPerSubcell(), patch.getSize()(0), patch.getSize()(1), #ifdef Dim3 patch.getSize()(2), #else 0, #endif patch.getPosition()(0), patch.getPosition()(1), #ifdef Dim3 patch.getPosition()(2) #else 0 #endif ); //Cache demanded mesh width _cachedSubgridPosition = patch.getPosition(); _cachedSubgridLevel = patch.getLevel(); _cachedDemandedMeshWidth = tarch::la::Vector<DIMENSIONS,double>(demandedMeshWidth); logTraceOutWith1Argument( "initializePatch(...)", demandedMeshWidth); } void peanoclaw::pyclaw::PyClaw::solveTimestep(Patch& patch, double maximumTimestepSize, bool useDimensionalSplitting) { logTraceInWith2Arguments( "solveTimestep(...)", maximumTimestepSize, useDimensionalSplitting); tarch::multicore::Lock lock(_semaphore); assertion2(tarch::la::greater(maximumTimestepSize, 0.0), "max. Timestepsize == 0 should be checked outside.", patch.getTimeIntervals().getMinimalNeighborTimeConstraint()); assertion3(!patch.containsNaN(), patch, patch.toStringUNew(), patch.toStringUOldWithGhostLayer()); PyClawState state(patch); tarch::timing::Watch pyclawWatch("", "", false); pyclawWatch.startTimer(); double dtAndEstimatedNextDt[2]; dtAndEstimatedNextDt[0] = 0.0; dtAndEstimatedNextDt[1] = 0.0; bool doDummyTimestep = false; double requiredMeshWidth; if(doDummyTimestep) { dtAndEstimatedNextDt[0] = std::min(maximumTimestepSize, patch.getTimeIntervals().getEstimatedNextTimestepSize()); dtAndEstimatedNextDt[1] = patch.getTimeIntervals().getEstimatedNextTimestepSize(); requiredMeshWidth = patch.getSubcellSize()(0); } else { requiredMeshWidth = _solverCallback( dtAndEstimatedNextDt, state._q, state._qbc, state._aux, patch.getSubdivisionFactor()(0), patch.getSubdivisionFactor()(1), #ifdef Dim3 patch.getSubdivisionFactor()(2), #else 0, #endif patch.getUnknownsPerSubcell(), // meqn = nvar patch.getNumberOfParametersWithoutGhostlayerPerSubcell(), // naux patch.getSize()(0), patch.getSize()(1), #ifdef Dim3 patch.getSize()(2), #else 0, #endif patch.getPosition()(0), patch.getPosition()(1), #ifdef Dim3 patch.getPosition()(2), #else 0, #endif patch.getTimeIntervals().getCurrentTime() + patch.getTimeIntervals().getTimestepSize(), maximumTimestepSize, patch.getTimeIntervals().getEstimatedNextTimestepSize(), useDimensionalSplitting ); } pyclawWatch.stopTimer(); _totalSolverCallbackTime += pyclawWatch.getCalendarTime(); assertion3(tarch::la::greater(dtAndEstimatedNextDt[0], 0.0), patch, patch.toStringUNew(), patch.toStringUOldWithGhostLayer()); assertion4( tarch::la::greater(patch.getTimeIntervals().getTimestepSize(), 0.0) || tarch::la::greater(dtAndEstimatedNextDt[1], 0.0) || tarch::la::equals(maximumTimestepSize, 0.0) || tarch::la::equals(patch.getTimeIntervals().getEstimatedNextTimestepSize(), 0.0), patch, maximumTimestepSize, dtAndEstimatedNextDt[1], patch.toStringUNew()); assertion(patch.getTimeIntervals().getTimestepSize() < std::numeric_limits<double>::infinity()); //Check for zeros in solution assertion3(!patch.containsNonPositiveNumberInUnknownInUNew(0), patch, patch.toStringUNew(), patch.toStringUOldWithGhostLayer()); patch.getTimeIntervals().advanceInTime(); patch.getTimeIntervals().setTimestepSize(dtAndEstimatedNextDt[0]); patch.getTimeIntervals().setEstimatedNextTimestepSize(dtAndEstimatedNextDt[1]); //Cache demanded mesh width _cachedSubgridPosition = patch.getPosition(); _cachedSubgridLevel = patch.getLevel(); _cachedDemandedMeshWidth = tarch::la::Vector<DIMENSIONS,double>(requiredMeshWidth); logTraceOutWith1Argument( "solveTimestep(...)", requiredMeshWidth); } tarch::la::Vector<DIMENSIONS, double> peanoclaw::pyclaw::PyClaw::getDemandedMeshWidth(Patch& patch, bool isInitializing) { if( tarch::la::equals(patch.getPosition(), _cachedSubgridPosition) && patch.getLevel() == _cachedSubgridLevel ) { return _cachedDemandedMeshWidth; } else { PyClawState state(patch); double demandedMeshWidth = _refinementCriterionCallback( state._q, state._qbc, state._aux, patch.getSubdivisionFactor()(0), patch.getSubdivisionFactor()(1), #ifdef Dim3 patch.getSubdivisionFactor()(2), #else 0, #endif patch.getUnknownsPerSubcell(), patch.getNumberOfParametersWithoutGhostlayerPerSubcell(), patch.getSize()(0), patch.getSize()(1), #ifdef Dim3 patch.getSize()(2), #else 0, #endif patch.getPosition()(0), patch.getPosition()(1), #ifdef Dim3 patch.getPosition()(2) #else 0 #endif ); //Cache demanded mesh width _cachedSubgridPosition = patch.getPosition(); _cachedSubgridLevel = patch.getLevel(); _cachedDemandedMeshWidth = tarch::la::Vector<DIMENSIONS,double>(demandedMeshWidth); return _cachedDemandedMeshWidth; } } void peanoclaw::pyclaw::PyClaw::addPatchToSolution(Patch& patch) { tarch::multicore::Lock lock(_semaphore); PyClawState state(patch); assertion(_addPatchToSolutionCallback != 0); _addPatchToSolutionCallback( state._q, state._qbc, patch.getGhostlayerWidth(), patch.getSize()(0), patch.getSize()(1), #ifdef Dim3 patch.getSize()(2), #else 0, #endif patch.getPosition()(0), patch.getPosition()(1), #ifdef Dim3 patch.getPosition()(2), #else 0, #endif patch.getTimeIntervals().getCurrentTime()+patch.getTimeIntervals().getTimestepSize() ); } void peanoclaw::pyclaw::PyClaw::fillBoundaryLayer(Patch& patch, int dimension, bool setUpper) { logTraceInWith3Arguments("fillBoundaryLayerInPyClaw", patch, dimension, setUpper); tarch::multicore::Lock lock(_semaphore); logDebug("fillBoundaryLayerInPyClaw", "Setting boundary for " << patch.getPosition() << ", dim=" << dimension << ", setUpper=" << setUpper); PyClawState state(patch); _boundaryConditionCallback(state._q, state._qbc, dimension, setUpper ? 1 : 0); logTraceOut("fillBoundaryLayerInPyClaw"); } void peanoclaw::pyclaw::PyClaw::update(Patch& finePatch) { } <|endoftext|>
<commit_before>#include "HmmSet.hh" #include "conf.hh" #include "io.hh" #include "str.hh" #include "FeatureGenerator.hh" #include "FeatureModules.hh" #include "Recipe.hh" #include "SpeakerConfig.hh" #include "MllrTrainer.hh" #include "RegClassTree.hh" #include <iostream> #include <fstream> using namespace aku; int info; conf::Config config; Recipe recipe; HmmSet model; FeatureGenerator fea_gen; RegClassTree rtree; SpeakerConfig speaker_conf(fea_gen, &model); double total_log_likelihood = 0; bool global_transform = false; ConstrainedMllr* cmllr = NULL; LinTransformModule* ltm = NULL; MllrTrainer *cmllr_trainer = NULL; std::string cur_speaker; std::set<std::string> updated_speakers; void calculate_transform() { //make transformation matrix if(info > 0) { std::cout << cur_speaker << ": "; std::cerr << "Calculating transform for " << cur_speaker << std::endl; } if(global_transform) cmllr_trainer->calculate_transform(ltm); else cmllr_trainer->calculate_transform(cmllr, config["minframes"].get_double(), info); delete cmllr_trainer; cmllr_trainer = NULL; } void set_speaker(std::string new_speaker) { if (new_speaker == cur_speaker) return; if (cmllr_trainer != NULL) { calculate_transform(); } cur_speaker = new_speaker; updated_speakers.insert(cur_speaker); cmllr_trainer = new MllrTrainer(&rtree, &model); // Change speaker to FeatureGenerator speaker_conf.set_speaker(cur_speaker); } Segmentator* get_segmentator(Recipe::Info info) { Segmentator *segmentator = NULL; bool skip = false; if (config["hmmnet"].specified) { // Open files and configure HmmNetBaumWelch* lattice = info.init_hmmnet_files(&model, false, &fea_gen, NULL); lattice->set_pruning_thresholds(config["fw-beam"].get_float(), config["bw-beam"].get_float()); if (config["vit"].specified) lattice->set_mode( HmmNetBaumWelch::MODE_VITERBI); if (config["mpv"].specified) lattice->set_mode( HmmNetBaumWelch::MODE_MULTIPATH_VITERBI); double orig_beam = lattice->get_backward_beam(); int counter = 1; while (!lattice->init_utterance_segmentation()) { if (counter >= 5) { fprintf(stderr, "Could not run Baum-Welch for file %s\n", info.audio_path.c_str()); fprintf(stderr, "The HMM network may be incorrect or initial beam too low.\n"); skip = true; break; } fprintf(stderr, "Warning: Backward phase failed, increasing beam to %.1f\n", ++counter * orig_beam); lattice->set_pruning_thresholds(0, counter * orig_beam); } segmentator = lattice; } else { // Create phn_reader PhnReader *phn_reader = info.init_phn_files(&model, config["rsamp"].specified, config["snl"].specified, config["ophn"].specified, &fea_gen, NULL); if (!phn_reader->init_utterance_segmentation()) { fprintf(stderr, "Could not initialize the utterance for PhnReader."); fprintf(stderr, "Current file was: %s\n", info.audio_path.c_str()); skip = true; } segmentator = phn_reader; } if (skip) { delete segmentator; segmentator = NULL; } return segmentator; } void train_mllr(Segmentator *seg) { HmmState state; while (seg->next_frame()) { const Segmentator::IndexProbMap &pdfs = seg->pdf_probs(); FeatureVec fea_vec = fea_gen.generate(seg->current_frame()); if (fea_gen.eof()) break; // EOF in FeatureGenerator for (Segmentator::IndexProbMap::const_iterator it = pdfs.begin(); it != pdfs.end(); ++it) { state = model.state((*it).first); cmllr_trainer->collect_data((*it).second, &state, fea_vec); } } if (seg->computes_total_log_likelihood()) total_log_likelihood += seg->get_total_log_likelihood(); } int main(int argc, char *argv[]) { Segmentator *segmentator; try { config("usage: modelmllr [OPTION...]\n") ('h', "help", "", "", "display help") ('b', "base=BASENAME", "arg", "", "base filename for model files") ('g', "gk=FILE", "arg", "", "Mixture base distributions") ('m', "mc=FILE", "arg", "", "Mixture coefficients for the states") ('p', "ph=FILE", "arg", "", "HMM definitions") ('c', "config=FILE", "arg must", "", "feature configuration") ('r', "recipe=FILE", "arg must", "", "recipe file") ('O', "ophn", "", "", "use output phns for adaptation") ('H', "hmmnet", "", "", "use HMM networks for training") ('\0', "mpv", "", "", "Use Multipath Viterbi over HMM networks") ('\0', "vit", "", "", "Use Viterbi over HMM networks") ('M', "mllr=MODULE", "arg", "", "MLLR feature module name, if none given, a model transform is trained. Only for a model transform the regression tree options are used.") ('S', "speakers=FILE", "arg must", "", "speaker configuration input file") ('R', "regtree=FILE", "arg", "", "regression tree file, if ommitted, and the next tree options are given, a tree is generated. Otherwise no tree is used.") ('s', "mcs=FILE", "arg", "", "Mixture statistics file (necessary for generating a tree, if no tree file is given)") ('t', "terminalnodes=INT", "arg", "1", "Number of maximum terminal nodes (used for generating a tree, if no tree file is given)") ('u', "unit=STRING", "arg", "PHONE", "PHONE|MIX|GAUSSIAN type of units. Don't use MIX in case of shared gaussians between mixtures (used for generating a tree, if no tree file is given)") ('f', "minframes=DOUBLE", "arg", "1000", "minimum frames used for adaptation") ('o', "out=FILE", "arg", "", "output speaker configuration file") ('F', "fw-beam=FLOAT", "arg", "0", "Forward beam (for HMM networks)") ('W', "bw-beam=FLOAT", "arg", "0", "Backward beam (for HMM networks)") ('\0', "snl", "", "", "phn-files with state number labels") ('\0', "rsamp", "", "", "phn sample numbers are relative to start time") ('\0', "ords","", "", "OBSOLETE, does not have any function anymore") ('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe") ('I', "bindex=INT", "arg", "0", "batch process index") ('i', "info=INT", "arg", "0", "info level") ; config.default_parse(argc, argv); if(config["ords"].specified) std::cerr << "Warning: --ords is obsolete and does not have to be used anymore" << std::endl; info = config["info"].get_int(); fea_gen.load_configuration(io::Stream(config["config"].get_str())); if (config["base"].specified) { model.read_all(config["base"].get_str()); } else if (config["gk"].specified && config["mc"].specified && config["ph"].specified) { model.read_gk(config["gk"].get_str()); model.read_mc(config["mc"].get_str()); model.read_ph(config["ph"].get_str()); } else { throw std::string("Must give either --base or all --gk, --mc and --ph"); } if ((config["vit"].specified || config["extvit"].specified) && !config["hmmnet"].specified) throw std::string( "--vit and --extvit require --hmmnet"); // Read recipe file recipe.read(io::Stream(config["recipe"].get_str()), config["batch"].get_int(), config["bindex"].get_int(), true); recipe.sort_infos(); // Check the dimension if (model.dim() != fea_gen.dim()) { throw str::fmt(128, "gaussian dimension is %d but feature dimension is %d", model.dim(), fea_gen.dim()); } if(config["mllr"].specified) { global_transform = true; } if(config["regtree"].specified && !global_transform) { // Read tree std::ifstream in(config["regtree"].get_c_str()); rtree.read(&in, &model); } else { // generate tree if(config["mcs"].specified && config["terminalnodes"].get_int() > 1 && !global_transform) { model.accumulate_mc_from_dump(config["mcs"].get_str()); rtree.set_unit_mode(RegClassTree::UNIT_NO); if(config["unit"].get_str() == "PHONE") rtree.set_unit_mode(RegClassTree::UNIT_PHONE); if (config["unit"].get_str() == "MIX") rtree.set_unit_mode(RegClassTree::UNIT_MIX); if (config["unit"].get_str() == "GAUSSIAN") rtree.set_unit_mode(RegClassTree::UNIT_GAUSSIAN); if(rtree.get_unit_mode() == RegClassTree::UNIT_NO) throw std::string(config["unit"].get_str() + " is not a valid unit identifier"); rtree.initialize_root_node(&model); rtree.build_tree(config["terminalnodes"].get_int()); if(info > 0) std::cerr << "Created tree with " << config["terminalnodes"].get_int() << " terminal nodes" << std::endl; } else { // make global transform rtree.set_unit_mode(RegClassTree::UNIT_NO); rtree.initialize_root_node(&model); if(info > 0) std::cerr << "No regression tree used" << std::endl; } } speaker_conf.read_speaker_file(io::Stream(config["speakers"].get_str())); if(global_transform) { ltm = dynamic_cast<LinTransformModule*> (fea_gen.module(config["mllr"].get_str())); } else { cmllr = dynamic_cast<ConstrainedMllr*> (speaker_conf.get_model_transformer().module("cmllr")); cmllr->disable_loading(); cmllr->set_unit_mode(ConstrainedMllr::UNIT_PHONE); } // Process each recipe line for (int f = 0; f < (int) recipe.infos.size(); f++) { if (recipe.infos[f].speaker_id.size() == 0) throw std::string( "Speaker ID is missing"); set_speaker(recipe.infos[f].speaker_id); if (info > 0) { fprintf(stderr, "Processing file: %s (%d/%d)", recipe.infos[f].audio_path.c_str(), f+1, (int) recipe.infos.size()); if (recipe.infos[f].start_time || recipe.infos[f].end_time) fprintf( stderr, " (%.2f-%.2f)", recipe.infos[f].start_time, recipe.infos[f].end_time); fprintf(stderr, "\n"); } if (recipe.infos[f].utterance_id.size() > 0) speaker_conf.set_utterance( recipe.infos[f].utterance_id); segmentator = get_segmentator(recipe.infos[f]); if (segmentator != NULL) { train_mllr(segmentator); segmentator->close(); delete segmentator; } fea_gen.close(); } if (cmllr_trainer != NULL) { //make transformation matrix // if(global_transform) // cmllr_trainer->calculate_transform(ltm); // else // cmllr_trainer->calculate_transform(cmllr, config["minframes"].get_double()); // // delete cmllr_trainer; // cmllr_trainer = NULL; calculate_transform(); } // Write new speaker configuration if (config["out"].specified) { std::set<std::string> *speaker_set = NULL, *utterance_set = NULL; std::set<std::string> empty_ut; if (config["batch"].get_int() > 1) { if (config["bindex"].get_int() == 1) updated_speakers.insert( std::string("default")); speaker_set = &updated_speakers; utterance_set = &empty_ut; } speaker_conf.write_speaker_file(io::Stream(config["out"].get_str(), "w"), speaker_set, utterance_set); } if (info > 0 && total_log_likelihood != 0) { fprintf(stderr, "Total log likelihood: %f\n", total_log_likelihood); } } catch (HmmSet::UnknownHmm &e) { fprintf(stderr, "Unknown HMM in transcription\n"); abort(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <commit_msg>Segmentation mode switch fix<commit_after>#include "HmmSet.hh" #include "conf.hh" #include "io.hh" #include "str.hh" #include "FeatureGenerator.hh" #include "FeatureModules.hh" #include "Recipe.hh" #include "SpeakerConfig.hh" #include "MllrTrainer.hh" #include "RegClassTree.hh" #include <iostream> #include <fstream> using namespace aku; int info; conf::Config config; Recipe recipe; HmmSet model; FeatureGenerator fea_gen; RegClassTree rtree; SpeakerConfig speaker_conf(fea_gen, &model); double total_log_likelihood = 0; bool global_transform = false; ConstrainedMllr* cmllr = NULL; LinTransformModule* ltm = NULL; MllrTrainer *cmllr_trainer = NULL; std::string cur_speaker; std::set<std::string> updated_speakers; int segmentation_mode; void calculate_transform() { //make transformation matrix if(info > 0) { std::cout << cur_speaker << ": "; std::cerr << "Calculating transform for " << cur_speaker << std::endl; } if(global_transform) cmllr_trainer->calculate_transform(ltm); else cmllr_trainer->calculate_transform(cmllr, config["minframes"].get_double(), info); delete cmllr_trainer; cmllr_trainer = NULL; } void set_speaker(std::string new_speaker) { if (new_speaker == cur_speaker) return; if (cmllr_trainer != NULL) { calculate_transform(); } cur_speaker = new_speaker; updated_speakers.insert(cur_speaker); cmllr_trainer = new MllrTrainer(&rtree, &model); // Change speaker to FeatureGenerator speaker_conf.set_speaker(cur_speaker); } Segmentator* get_segmentator(Recipe::Info info) { Segmentator *segmentator = NULL; bool skip = false; if (config["hmmnet"].specified) { // Open files and configure HmmNetBaumWelch* lattice = info.init_hmmnet_files(&model, false, &fea_gen, NULL); lattice->set_pruning_thresholds(config["fw-beam"].get_float(), config["bw-beam"].get_float()); lattice->set_mode(segmentation_mode); double orig_beam = lattice->get_backward_beam(); int counter = 1; while (!lattice->init_utterance_segmentation()) { if (counter >= 5) { fprintf(stderr, "Could not run Baum-Welch for file %s\n", info.audio_path.c_str()); fprintf(stderr, "The HMM network may be incorrect or initial beam too low.\n"); skip = true; break; } fprintf(stderr, "Warning: Backward phase failed, increasing beam to %.1f\n", ++counter * orig_beam); lattice->set_pruning_thresholds(0, counter * orig_beam); } segmentator = lattice; } else { // Create phn_reader PhnReader *phn_reader = info.init_phn_files(&model, config["rsamp"].specified, config["snl"].specified, config["ophn"].specified, &fea_gen, NULL); if (!phn_reader->init_utterance_segmentation()) { fprintf(stderr, "Could not initialize the utterance for PhnReader."); fprintf(stderr, "Current file was: %s\n", info.audio_path.c_str()); skip = true; } segmentator = phn_reader; } if (skip) { delete segmentator; segmentator = NULL; } return segmentator; } void train_mllr(Segmentator *seg) { HmmState state; while (seg->next_frame()) { const Segmentator::IndexProbMap &pdfs = seg->pdf_probs(); FeatureVec fea_vec = fea_gen.generate(seg->current_frame()); if (fea_gen.eof()) break; // EOF in FeatureGenerator for (Segmentator::IndexProbMap::const_iterator it = pdfs.begin(); it != pdfs.end(); ++it) { state = model.state((*it).first); cmllr_trainer->collect_data((*it).second, &state, fea_vec); } } if (seg->computes_total_log_likelihood()) total_log_likelihood += seg->get_total_log_likelihood(); } int main(int argc, char *argv[]) { Segmentator *segmentator; try { config("usage: modelmllr [OPTION...]\n") ('h', "help", "", "", "display help") ('b', "base=BASENAME", "arg", "", "base filename for model files") ('g', "gk=FILE", "arg", "", "Mixture base distributions") ('m', "mc=FILE", "arg", "", "Mixture coefficients for the states") ('p', "ph=FILE", "arg", "", "HMM definitions") ('c', "config=FILE", "arg must", "", "feature configuration") ('r', "recipe=FILE", "arg must", "", "recipe file") ('O', "ophn", "", "", "use output phns for adaptation") ('H', "hmmnet", "", "", "use HMM networks for training") ('\0', "segmode=MODE", "arg", "bw", "Segmentation mode: bw(default)/vit/mpv") ('M', "mllr=MODULE", "arg", "", "MLLR feature module name, if none given, a model transform is trained. Only for a model transform the regression tree options are used.") ('S', "speakers=FILE", "arg must", "", "speaker configuration input file") ('R', "regtree=FILE", "arg", "", "regression tree file, if ommitted, and the next tree options are given, a tree is generated. Otherwise no tree is used.") ('s', "mcs=FILE", "arg", "", "Mixture statistics file (necessary for generating a tree, if no tree file is given)") ('t', "terminalnodes=INT", "arg", "1", "Number of maximum terminal nodes (used for generating a tree, if no tree file is given)") ('u', "unit=STRING", "arg", "PHONE", "PHONE|MIX|GAUSSIAN type of units. Don't use MIX in case of shared gaussians between mixtures (used for generating a tree, if no tree file is given)") ('f', "minframes=DOUBLE", "arg", "1000", "minimum frames used for adaptation") ('o', "out=FILE", "arg", "", "output speaker configuration file") ('F', "fw-beam=FLOAT", "arg", "0", "Forward beam (for HMM networks)") ('W', "bw-beam=FLOAT", "arg", "0", "Backward beam (for HMM networks)") ('\0', "snl", "", "", "phn-files with state number labels") ('\0', "rsamp", "", "", "phn sample numbers are relative to start time") ('\0', "ords","", "", "OBSOLETE, does not have any function anymore") ('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe") ('I', "bindex=INT", "arg", "0", "batch process index") ('i', "info=INT", "arg", "0", "info level") ; config.default_parse(argc, argv); if(config["ords"].specified) std::cerr << "Warning: --ords is obsolete and does not have to be used anymore" << std::endl; info = config["info"].get_int(); fea_gen.load_configuration(io::Stream(config["config"].get_str())); if (config["base"].specified) { model.read_all(config["base"].get_str()); } else if (config["gk"].specified && config["mc"].specified && config["ph"].specified) { model.read_gk(config["gk"].get_str()); model.read_mc(config["mc"].get_str()); model.read_ph(config["ph"].get_str()); } else { throw std::string("Must give either --base or all --gk, --mc and --ph"); } if (config["segmode"].specified && !config["hmmnet"].specified) throw std::string("Segmentation modes are supported only with --hmmnet"); conf::Choice segmode_choice; segmode_choice("bw", HmmNetBaumWelch::MODE_BAUM_WELCH) ("vit", HmmNetBaumWelch::MODE_VITERBI) ("mpv", HmmNetBaumWelch::MODE_MULTIPATH_VITERBI); segmentation_mode = HmmNetBaumWelch::MODE_BAUM_WELCH; if (!segmode_choice.parse(config["segmode"].get_str(), segmentation_mode)) throw std::string("Invalid segmentation mode ") + config["segmode"].get_str(); // Read recipe file recipe.read(io::Stream(config["recipe"].get_str()), config["batch"].get_int(), config["bindex"].get_int(), true); recipe.sort_infos(); // Check the dimension if (model.dim() != fea_gen.dim()) { throw str::fmt(128, "gaussian dimension is %d but feature dimension is %d", model.dim(), fea_gen.dim()); } if(config["mllr"].specified) { global_transform = true; } if(config["regtree"].specified && !global_transform) { // Read tree std::ifstream in(config["regtree"].get_c_str()); rtree.read(&in, &model); } else { // generate tree if(config["mcs"].specified && config["terminalnodes"].get_int() > 1 && !global_transform) { model.accumulate_mc_from_dump(config["mcs"].get_str()); rtree.set_unit_mode(RegClassTree::UNIT_NO); if(config["unit"].get_str() == "PHONE") rtree.set_unit_mode(RegClassTree::UNIT_PHONE); if (config["unit"].get_str() == "MIX") rtree.set_unit_mode(RegClassTree::UNIT_MIX); if (config["unit"].get_str() == "GAUSSIAN") rtree.set_unit_mode(RegClassTree::UNIT_GAUSSIAN); if(rtree.get_unit_mode() == RegClassTree::UNIT_NO) throw std::string(config["unit"].get_str() + " is not a valid unit identifier"); rtree.initialize_root_node(&model); rtree.build_tree(config["terminalnodes"].get_int()); if(info > 0) std::cerr << "Created tree with " << config["terminalnodes"].get_int() << " terminal nodes" << std::endl; } else { // make global transform rtree.set_unit_mode(RegClassTree::UNIT_NO); rtree.initialize_root_node(&model); if(info > 0) std::cerr << "No regression tree used" << std::endl; } } speaker_conf.read_speaker_file(io::Stream(config["speakers"].get_str())); if(global_transform) { ltm = dynamic_cast<LinTransformModule*> (fea_gen.module(config["mllr"].get_str())); } else { cmllr = dynamic_cast<ConstrainedMllr*> (speaker_conf.get_model_transformer().module("cmllr")); cmllr->disable_loading(); cmllr->set_unit_mode(ConstrainedMllr::UNIT_PHONE); } // Process each recipe line for (int f = 0; f < (int) recipe.infos.size(); f++) { if (recipe.infos[f].speaker_id.size() == 0) throw std::string( "Speaker ID is missing"); set_speaker(recipe.infos[f].speaker_id); if (info > 0) { fprintf(stderr, "Processing file: %s (%d/%d)", recipe.infos[f].audio_path.c_str(), f+1, (int) recipe.infos.size()); if (recipe.infos[f].start_time || recipe.infos[f].end_time) fprintf( stderr, " (%.2f-%.2f)", recipe.infos[f].start_time, recipe.infos[f].end_time); fprintf(stderr, "\n"); } if (recipe.infos[f].utterance_id.size() > 0) speaker_conf.set_utterance( recipe.infos[f].utterance_id); segmentator = get_segmentator(recipe.infos[f]); if (segmentator != NULL) { train_mllr(segmentator); segmentator->close(); delete segmentator; } fea_gen.close(); } if (cmllr_trainer != NULL) { //make transformation matrix // if(global_transform) // cmllr_trainer->calculate_transform(ltm); // else // cmllr_trainer->calculate_transform(cmllr, config["minframes"].get_double()); // // delete cmllr_trainer; // cmllr_trainer = NULL; calculate_transform(); } // Write new speaker configuration if (config["out"].specified) { std::set<std::string> *speaker_set = NULL, *utterance_set = NULL; std::set<std::string> empty_ut; if (config["batch"].get_int() > 1) { if (config["bindex"].get_int() == 1) updated_speakers.insert( std::string("default")); speaker_set = &updated_speakers; utterance_set = &empty_ut; } speaker_conf.write_speaker_file(io::Stream(config["out"].get_str(), "w"), speaker_set, utterance_set); } if (info > 0 && total_log_likelihood != 0) { fprintf(stderr, "Total log likelihood: %f\n", total_log_likelihood); } } catch (HmmSet::UnknownHmm &e) { fprintf(stderr, "Unknown HMM in transcription\n"); abort(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <|endoftext|>
<commit_before>/** * @file ns_model.hpp * @author Ryan Curtin * * This is a model for nearest or furthest neighbor search. It is useful in * that it provides an easy way to serialize a model, abstracts away the * different types of trees, and also reflects the NeighborSearch API and * automatically directs to the right tree type. */ #ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NS_MODEL_HPP #define __MLPACK_METHODS_NEIGHBOR_SEARCH_NS_MODEL_HPP #include <mlpack/core/tree/binary_space_tree.hpp> #include <mlpack/core/tree/cover_tree.hpp> #include <mlpack/core/tree/rectangle_tree.hpp> #include "neighbor_search.hpp" namespace mlpack { namespace neighbor { template<typename SortPolicy> struct NSModelName { static const std::string Name() { return "neighbor_search_model"; } }; template<> struct NSModelName<NearestNeighborSort> { static const std::string Name() { return "nearest_neighbor_search_model"; } }; template<> struct NSModelName<FurthestNeighborSort> { static const std::string Name() { return "furthest_neighbor_search_model"; } }; template<typename SortPolicy> class NSModel { public: enum TreeTypes { KD_TREE, COVER_TREE, R_TREE, R_STAR_TREE, BALL_TREE }; private: int treeType; size_t leafSize; // For random projections. bool randomBasis; arma::mat q; template<template<typename TreeMetricType, typename TreeStatType, typename TreeMatType> class TreeType> using NSType = NeighborSearch<SortPolicy, metric::EuclideanDistance, arma::mat, TreeType, TreeType<metric::EuclideanDistance, NeighborSearchStat<SortPolicy>,arma::mat>::template DualTreeTraverser>; // Only one of these pointers will be non-NULL. NSType<tree::KDTree>* kdTreeNS; NSType<tree::StandardCoverTree>* coverTreeNS; NSType<tree::RTree>* rTreeNS; NSType<tree::RStarTree>* rStarTreeNS; NSType<tree::BallTree>* ballTreeNS; public: /** * Initialize the NSModel with the given type and whether or not a random * basis should be used. */ NSModel(int treeType = TreeTypes::KD_TREE, bool randomBasis = false); //! Clean memory, if necessary. ~NSModel(); //! Serialize the neighbor search model. template<typename Archive> void Serialize(Archive& ar, const unsigned int /* version */); //! Expose the dataset. const arma::mat& Dataset() const; //! Expose singleMode. bool SingleMode() const; bool& SingleMode(); bool Naive() const; bool& Naive(); size_t LeafSize() const { return leafSize; } size_t& LeafSize() { return leafSize; } int TreeType() const { return treeType; } int& TreeType() { return treeType; } bool RandomBasis() const { return randomBasis; } bool& RandomBasis() { return randomBasis; } //! Build the reference tree. void BuildModel(arma::mat&& referenceSet, const size_t leafSize, const bool naive, const bool singleMode); //! Perform neighbor search. The query set will be reordered. void Search(arma::mat&& querySet, const size_t k, arma::Mat<size_t>& neighbors, arma::mat& distances); //! Perform neighbor search. void Search(const size_t k, arma::Mat<size_t>& neighbors, arma::mat& distances); std::string TreeName() const; }; } // namespace neighbor } // namespace mlpack // Include implementation. #include "ns_model_impl.hpp" #endif <commit_msg>Remove tab character; reformat.<commit_after>/** * @file ns_model.hpp * @author Ryan Curtin * * This is a model for nearest or furthest neighbor search. It is useful in * that it provides an easy way to serialize a model, abstracts away the * different types of trees, and also reflects the NeighborSearch API and * automatically directs to the right tree type. */ #ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NS_MODEL_HPP #define __MLPACK_METHODS_NEIGHBOR_SEARCH_NS_MODEL_HPP #include <mlpack/core/tree/binary_space_tree.hpp> #include <mlpack/core/tree/cover_tree.hpp> #include <mlpack/core/tree/rectangle_tree.hpp> #include "neighbor_search.hpp" namespace mlpack { namespace neighbor { template<typename SortPolicy> struct NSModelName { static const std::string Name() { return "neighbor_search_model"; } }; template<> struct NSModelName<NearestNeighborSort> { static const std::string Name() { return "nearest_neighbor_search_model"; } }; template<> struct NSModelName<FurthestNeighborSort> { static const std::string Name() { return "furthest_neighbor_search_model"; } }; template<typename SortPolicy> class NSModel { public: enum TreeTypes { KD_TREE, COVER_TREE, R_TREE, R_STAR_TREE, BALL_TREE }; private: int treeType; size_t leafSize; // For random projections. bool randomBasis; arma::mat q; template<template<typename TreeMetricType, typename TreeStatType, typename TreeMatType> class TreeType> using NSType = NeighborSearch<SortPolicy, metric::EuclideanDistance, arma::mat, TreeType, TreeType<metric::EuclideanDistance, NeighborSearchStat<SortPolicy>, arma::mat>::template DualTreeTraverser; // Only one of these pointers will be non-NULL. NSType<tree::KDTree>* kdTreeNS; NSType<tree::StandardCoverTree>* coverTreeNS; NSType<tree::RTree>* rTreeNS; NSType<tree::RStarTree>* rStarTreeNS; NSType<tree::BallTree>* ballTreeNS; public: /** * Initialize the NSModel with the given type and whether or not a random * basis should be used. */ NSModel(int treeType = TreeTypes::KD_TREE, bool randomBasis = false); //! Clean memory, if necessary. ~NSModel(); //! Serialize the neighbor search model. template<typename Archive> void Serialize(Archive& ar, const unsigned int /* version */); //! Expose the dataset. const arma::mat& Dataset() const; //! Expose singleMode. bool SingleMode() const; bool& SingleMode(); bool Naive() const; bool& Naive(); size_t LeafSize() const { return leafSize; } size_t& LeafSize() { return leafSize; } int TreeType() const { return treeType; } int& TreeType() { return treeType; } bool RandomBasis() const { return randomBasis; } bool& RandomBasis() { return randomBasis; } //! Build the reference tree. void BuildModel(arma::mat&& referenceSet, const size_t leafSize, const bool naive, const bool singleMode); //! Perform neighbor search. The query set will be reordered. void Search(arma::mat&& querySet, const size_t k, arma::Mat<size_t>& neighbors, arma::mat& distances); //! Perform neighbor search. void Search(const size_t k, arma::Mat<size_t>& neighbors, arma::mat& distances); std::string TreeName() const; }; } // namespace neighbor } // namespace mlpack // Include implementation. #include "ns_model_impl.hpp" #endif <|endoftext|>
<commit_before>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <robert.staudinger@gmail.com> * * 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 St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygensliderdemowidget.h" #include <iostream> #include <string> namespace Oxygen { //____________________________________________________ SliderDemoWidget::SliderDemoWidget( void ) { // main widget GtkWidget* mainWidget( gtk_hbox_new( false, 0 ) ); gtk_box_set_spacing( GTK_BOX( mainWidget ), 5 ); setWidget( mainWidget ); // setup setName( "Sliders" ); setComments( "Shows the appearance of sliders, progress bars and scrollbars" ); setIconName( "measure" ); realize(); // horizontal sliders { // frame GtkWidget* frame( gtk_frame_new( "Horizontal" ) ); gtk_box_pack_start( GTK_BOX( mainWidget ), frame, true, true, 0 ); gtk_widget_show( frame ); // container GtkWidget* box( gtk_vbox_new( false, 0 ) ); gtk_container_set_border_width( GTK_CONTAINER( box ), 5 ); gtk_box_set_spacing( GTK_BOX( box ), 2 ); gtk_widget_show( box ); gtk_container_add( GTK_CONTAINER( frame ), box ); // scale _horizontalSliders._scale = gtk_hscale_new_with_range( 0, 100, 1 ); gtk_scale_set_draw_value( GTK_SCALE( _horizontalSliders._scale ), false ); gtk_range_set_value( GTK_RANGE( _horizontalSliders._scale ), 25 ); gtk_box_pack_start( GTK_BOX( box ), _horizontalSliders._scale, false, true, 0 ); gtk_widget_show( _horizontalSliders._scale ); // progress bar _horizontalSliders._progressBar = gtk_progress_bar_new(); #if GTK_CHECK_VERSION(3, 0, 0) gtk_orientable_set_orientation( GTK_ORIENTABLE( _horizontalSliders._progressBar ), GTK_ORIENTATION_HORIZONTAL ); #else gtk_progress_bar_set_orientation( GTK_PROGRESS_BAR( _horizontalSliders._progressBar ), GTK_PROGRESS_LEFT_TO_RIGHT ); #endif // gtk_progress_set_show_text( GTK_PROGRESS( _horizontalSliders._progressBar ), true ); gtk_progress_bar_set_fraction( GTK_PROGRESS_BAR( _horizontalSliders._progressBar ), 0.25 ); gtk_box_pack_start( GTK_BOX( box ), _horizontalSliders._progressBar, false, true, 0 ); gtk_widget_show( _horizontalSliders._progressBar ); // pulse progressBar _pulseProgressBar = gtk_progress_bar_new(); #if GTK_CHECK_VERSION(3, 0, 0) gtk_orientable_set_orientation( GTK_ORIENTABLE( _pulseProgressBar ), GTK_ORIENTATION_HORIZONTAL ); #else gtk_progress_bar_set_orientation( GTK_PROGRESS_BAR( _pulseProgressBar ), GTK_PROGRESS_LEFT_TO_RIGHT ); #endif gtk_progress_bar_set_pulse_step( GTK_PROGRESS_BAR( _pulseProgressBar ), 0.01 ); gtk_box_pack_start( GTK_BOX( box ), _pulseProgressBar, false, true, 0 ); gtk_widget_show( _pulseProgressBar ); // scrollbar GtkAdjustment* adjustment( GTK_ADJUSTMENT( gtk_adjustment_new( 25, 0, 100, 1, 1, 10 ) ) ); _horizontalSliders._scrollBar = gtk_hscrollbar_new( adjustment ); gtk_box_pack_start( GTK_BOX( box ), _horizontalSliders._scrollBar, false, true, 0 ); gtk_widget_show( _horizontalSliders._scrollBar ); } // vertical sliders { // frame GtkWidget* frame( gtk_frame_new( "Vertical" ) ); gtk_box_pack_start( GTK_BOX( mainWidget ), frame, false, true, 0 ); gtk_widget_show( frame ); // container GtkWidget* box( gtk_hbox_new( false, 0 ) ); gtk_container_set_border_width( GTK_CONTAINER( box ), 5 ); gtk_box_set_spacing( GTK_BOX( box ), 5 ); gtk_widget_show( box ); gtk_container_add( GTK_CONTAINER( frame ), box ); // scale _verticalSliders._scale = gtk_vscale_new_with_range( 0, 100, 1 ); gtk_scale_set_draw_value( GTK_SCALE( _verticalSliders._scale ), false ); gtk_range_set_value( GTK_RANGE( _verticalSliders._scale ), 25 ); gtk_box_pack_start( GTK_BOX( box ), _verticalSliders._scale, false, true, 0 ); gtk_widget_show( _verticalSliders._scale ); // progress bar _verticalSliders._progressBar = gtk_progress_bar_new(); #if GTK_CHECK_VERSION(3, 0, 0) gtk_orientable_set_orientation( GTK_ORIENTABLE( _verticalSliders._progressBar ), GTK_ORIENTATION_VERTICAL ); #else gtk_progress_bar_set_orientation( GTK_PROGRESS_BAR( _verticalSliders._progressBar ), GTK_PROGRESS_BOTTOM_TO_TOP ); #endif // gtk_progress_set_show_text( GTK_PROGRESS( _verticalSliders._progressBar ), true ); gtk_progress_bar_set_fraction( GTK_PROGRESS_BAR( _verticalSliders._progressBar ), 0.25 ); gtk_box_pack_start( GTK_BOX( box ), _verticalSliders._progressBar, false, true, 0 ); gtk_widget_show( _verticalSliders._progressBar ); // scrollbar GtkAdjustment* adjustment( GTK_ADJUSTMENT( gtk_adjustment_new( 25, 0, 100, 1, 1, 10 ) ) ); _verticalSliders._scrollBar = gtk_vscrollbar_new( adjustment ); gtk_box_pack_start( GTK_BOX( box ), _verticalSliders._scrollBar, false, true, 0 ); gtk_widget_show( _verticalSliders._scrollBar ); } _horizontalSliders.connect( GCallback( valueChanged ), this ); _verticalSliders.connect( GCallback( valueChanged ), this ); } //____________________________________________________ SliderDemoWidget::~SliderDemoWidget( void ) {} //____________________________________________________ gboolean SliderDemoWidget::pulseProgressBar( gpointer pointer ) { SliderDemoWidget& demoWidget( *static_cast<SliderDemoWidget*>( pointer ) ); gtk_progress_bar_pulse( GTK_PROGRESS_BAR( demoWidget._pulseProgressBar ) ); return TRUE; } //____________________________________________________ void SliderDemoWidget::valueChanged( GtkRange* range, gpointer pointer ) { const double value( gtk_range_get_value( range ) ); SliderDemoWidget& data( *static_cast<SliderDemoWidget*>( pointer ) ); data._horizontalSliders.setValue( value ); data._verticalSliders.setValue( value ); } //____________________________________________________ void SliderDemoWidget::Sliders::setValue( const double& value ) const { gtk_range_set_value( GTK_RANGE( _scale ), value ); gtk_progress_bar_set_fraction( GTK_PROGRESS_BAR( _progressBar ), value/100 ); gtk_range_set_value( GTK_RANGE( _scrollBar ), value ); } } <commit_msg>adjust scrollbar max value so that full range matches slider and progressbar.<commit_after>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <robert.staudinger@gmail.com> * * 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 St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygensliderdemowidget.h" #include <iostream> #include <string> namespace Oxygen { //____________________________________________________ SliderDemoWidget::SliderDemoWidget( void ) { // main widget GtkWidget* mainWidget( gtk_hbox_new( false, 0 ) ); gtk_box_set_spacing( GTK_BOX( mainWidget ), 5 ); setWidget( mainWidget ); // setup setName( "Sliders" ); setComments( "Shows the appearance of sliders, progress bars and scrollbars" ); setIconName( "measure" ); realize(); // horizontal sliders { // frame GtkWidget* frame( gtk_frame_new( "Horizontal" ) ); gtk_box_pack_start( GTK_BOX( mainWidget ), frame, true, true, 0 ); gtk_widget_show( frame ); // container GtkWidget* box( gtk_vbox_new( false, 0 ) ); gtk_container_set_border_width( GTK_CONTAINER( box ), 5 ); gtk_box_set_spacing( GTK_BOX( box ), 2 ); gtk_widget_show( box ); gtk_container_add( GTK_CONTAINER( frame ), box ); // scale _horizontalSliders._scale = gtk_hscale_new_with_range( 0, 100, 1 ); gtk_scale_set_draw_value( GTK_SCALE( _horizontalSliders._scale ), false ); gtk_range_set_value( GTK_RANGE( _horizontalSliders._scale ), 25 ); gtk_box_pack_start( GTK_BOX( box ), _horizontalSliders._scale, false, true, 0 ); gtk_widget_show( _horizontalSliders._scale ); // progress bar _horizontalSliders._progressBar = gtk_progress_bar_new(); #if GTK_CHECK_VERSION(3, 0, 0) gtk_orientable_set_orientation( GTK_ORIENTABLE( _horizontalSliders._progressBar ), GTK_ORIENTATION_HORIZONTAL ); #else gtk_progress_bar_set_orientation( GTK_PROGRESS_BAR( _horizontalSliders._progressBar ), GTK_PROGRESS_LEFT_TO_RIGHT ); #endif // gtk_progress_set_show_text( GTK_PROGRESS( _horizontalSliders._progressBar ), true ); gtk_progress_bar_set_fraction( GTK_PROGRESS_BAR( _horizontalSliders._progressBar ), 0.25 ); gtk_box_pack_start( GTK_BOX( box ), _horizontalSliders._progressBar, false, true, 0 ); gtk_widget_show( _horizontalSliders._progressBar ); // pulse progressBar _pulseProgressBar = gtk_progress_bar_new(); #if GTK_CHECK_VERSION(3, 0, 0) gtk_orientable_set_orientation( GTK_ORIENTABLE( _pulseProgressBar ), GTK_ORIENTATION_HORIZONTAL ); #else gtk_progress_bar_set_orientation( GTK_PROGRESS_BAR( _pulseProgressBar ), GTK_PROGRESS_LEFT_TO_RIGHT ); #endif gtk_progress_bar_set_pulse_step( GTK_PROGRESS_BAR( _pulseProgressBar ), 0.01 ); gtk_box_pack_start( GTK_BOX( box ), _pulseProgressBar, false, true, 0 ); gtk_widget_show( _pulseProgressBar ); // scrollbar GtkAdjustment* adjustment( GTK_ADJUSTMENT( gtk_adjustment_new( 25, 0, 110, 1, 1, 10 ) ) ); _horizontalSliders._scrollBar = gtk_hscrollbar_new( adjustment ); gtk_box_pack_start( GTK_BOX( box ), _horizontalSliders._scrollBar, false, true, 0 ); gtk_widget_show( _horizontalSliders._scrollBar ); } // vertical sliders { // frame GtkWidget* frame( gtk_frame_new( "Vertical" ) ); gtk_box_pack_start( GTK_BOX( mainWidget ), frame, false, true, 0 ); gtk_widget_show( frame ); // container GtkWidget* box( gtk_hbox_new( false, 0 ) ); gtk_container_set_border_width( GTK_CONTAINER( box ), 5 ); gtk_box_set_spacing( GTK_BOX( box ), 5 ); gtk_widget_show( box ); gtk_container_add( GTK_CONTAINER( frame ), box ); // scale _verticalSliders._scale = gtk_vscale_new_with_range( 0, 100, 1 ); gtk_scale_set_draw_value( GTK_SCALE( _verticalSliders._scale ), false ); gtk_range_set_value( GTK_RANGE( _verticalSliders._scale ), 25 ); gtk_box_pack_start( GTK_BOX( box ), _verticalSliders._scale, false, true, 0 ); gtk_widget_show( _verticalSliders._scale ); // progress bar _verticalSliders._progressBar = gtk_progress_bar_new(); #if GTK_CHECK_VERSION(3, 0, 0) gtk_orientable_set_orientation( GTK_ORIENTABLE( _verticalSliders._progressBar ), GTK_ORIENTATION_VERTICAL ); #else gtk_progress_bar_set_orientation( GTK_PROGRESS_BAR( _verticalSliders._progressBar ), GTK_PROGRESS_BOTTOM_TO_TOP ); #endif // gtk_progress_set_show_text( GTK_PROGRESS( _verticalSliders._progressBar ), true ); gtk_progress_bar_set_fraction( GTK_PROGRESS_BAR( _verticalSliders._progressBar ), 0.25 ); gtk_box_pack_start( GTK_BOX( box ), _verticalSliders._progressBar, false, true, 0 ); gtk_widget_show( _verticalSliders._progressBar ); // scrollbar GtkAdjustment* adjustment( GTK_ADJUSTMENT( gtk_adjustment_new( 25, 0, 110, 1, 1, 10 ) ) ); _verticalSliders._scrollBar = gtk_vscrollbar_new( adjustment ); gtk_box_pack_start( GTK_BOX( box ), _verticalSliders._scrollBar, false, true, 0 ); gtk_widget_show( _verticalSliders._scrollBar ); } _horizontalSliders.connect( GCallback( valueChanged ), this ); _verticalSliders.connect( GCallback( valueChanged ), this ); } //____________________________________________________ SliderDemoWidget::~SliderDemoWidget( void ) {} //____________________________________________________ gboolean SliderDemoWidget::pulseProgressBar( gpointer pointer ) { SliderDemoWidget& demoWidget( *static_cast<SliderDemoWidget*>( pointer ) ); gtk_progress_bar_pulse( GTK_PROGRESS_BAR( demoWidget._pulseProgressBar ) ); return TRUE; } //____________________________________________________ void SliderDemoWidget::valueChanged( GtkRange* range, gpointer pointer ) { const double value( gtk_range_get_value( range ) ); SliderDemoWidget& data( *static_cast<SliderDemoWidget*>( pointer ) ); data._horizontalSliders.setValue( value ); data._verticalSliders.setValue( value ); } //____________________________________________________ void SliderDemoWidget::Sliders::setValue( const double& value ) const { gtk_range_set_value( GTK_RANGE( _scale ), value ); gtk_progress_bar_set_fraction( GTK_PROGRESS_BAR( _progressBar ), value/100 ); gtk_range_set_value( GTK_RANGE( _scrollBar ), value ); } } <|endoftext|>
<commit_before>/* * Arduino Solar Controller * * by karldm, March 2016 * * ascdata.cpp * * Data management & memory accesses (EEPROM&FLASH) * * TODO: * - check access in getParVal() and setParVal() * - modif _indextype[] to include type (byte-int-ulong) + format + units? byte[3] * e.g. TEMP will define int & f4.2 * should define several quantities : * basic: byte - int - ULONG - F4.2 - STRING10 * App customized: TEMP - HUMID - PRES - SWITCH - IPV4 * - suppress _lastLindexSearch * - compatibility with REST library to define 2016/05/31 - added bridge link to store data with: bridge.put bridge.get {key,value} in : getParVal / setParVal - values are stored in 'datastore' on Lininino part - two functions to sync datastore: bridgeGetAll() bridgePutAll() 2016/09/29 - add the request data: BridgePutRequest(), BridgeGetRequest(), ifRequest() 2016/10/01 - store two values in EEPROM a) the last saved for re-power b) the default */ #include "ascdata.h" //+++++++1+++++++++2+++++++++3+++++++++4+++++++++5+++++++++6+++++++++7+++++++++8 /* * Ascdata * declare Ascdata ascdata() * */ Ascdata::Ascdata() { _npar = 0; _lastIndexSearch = -1; // last index found in data list } /* * par_F() * * Parameter declaration * * access = "rws" byte coded * * r = read * w = write * s = saved in EEPROM * */ int Ascdata::par_F( byte * ppar, const __FlashStringHelper * label, const __FlashStringHelper * options ) { int err = 0; if ( _npar < NPARMAX ) { // add the parameter _P[_npar] = (byte *) ppar; _indextype[_npar] = TYPEBYTE; // encode _indextype info datalabels[_npar] = (char *)label; dataoptions[_npar] = (char *)options; _npar++; err = _npar; } else { //Serial.print("> Failed to add "); //Serial.println(label); err = -1; // no more space available -- how to print it? } return(err); } int Ascdata::par_F( int * ppar, const __FlashStringHelper * label, const __FlashStringHelper * options ) { int err = 0; if ( _npar < NPARMAX ) { // add the parameter _P[_npar] = (int *) ppar; _indextype[_npar] = TYPEINT; // encode _indextype info datalabels[_npar] = (char *)label; dataoptions[_npar] = (char *)options; _npar++; err = _npar; } else { //Serial.print("> Failed to add "); //Serial.println(label); err = -1; // no more space available -- how to print it? } return(err); } int Ascdata::par_F( unsigned long * ppar, const __FlashStringHelper * label, const __FlashStringHelper * options ) { int err = 0; if ( _npar < NPARMAX ) { // add the parameter _P[_npar] = (unsigned long *) ppar; _indextype[_npar] = TYPEULONG; // encode _indextype info datalabels[_npar] = (char *)label; dataoptions[_npar] = (char *)options; _npar++; err = _npar; } else { //Serial.print("> Failed to add "); //Serial.println(label); err = -1; // no more space available -- how to print it? } return(err); } /* * GetNpar() * * Get the number of declared parameters * Info in console about data usage */ int Ascdata::getNpar() { // PrintInfoDataUsage( _npar, NPARMAX ); return(_npar); } /* * getParIndex() => searchPar() -- internal? * * Get the index, return -1 if not found * & set _lastLindexSearch */ int Ascdata::getParIndex(const char * label) { int err = -1; int index = 0; // find the parameter index // look in the byte list while ( err == -1 && index < _npar ) { if ( strcmp_P( label, datalabels[index]) ==0 ) { err = index; } index++; _lastIndexSearch = err; } return(err); } /* * checkParAccess( char access ) * * check par access of the current parameter * return true if ok */ boolean Ascdata::checkParAccess( char access ) { char options[BUFFERVALUE]; int type; char * fmt; strcpy_P( options, dataoptions[_lastIndexSearch]); // copy into options fmt = strtok( options, " "); // locate the format string return( strchr( fmt, access) != NULL ); } /* * getParVal() * * Get the value into a string with format adaptation * */ void Ascdata::getParVal( char * svalue ) { // use _lastLindexSearch & _lastIndexSearch; char options[BUFFERVALUE]; char * fmt; strcpy_P( options, dataoptions[_lastIndexSearch]); // copy into options fmt = strchr( options, ' ')+1; // locate the format string switch ( _indextype[_lastIndexSearch] ) { case TYPEBYTE : // copy the value with format transformation sprintf( svalue, "%d", * (byte *)_P[_lastIndexSearch] ); break; case TYPEINT : // copy the value with format transformation if ( strcmp( fmt, "f4.2") == 0 ) { // see http://stackoverflow.com/questions/27651012/arduino-sprintf-float-not-formatting dtostrf( ((float)*(int *)_P[_lastIndexSearch] )/100, 4, 2, svalue); sprintf( svalue, "%s", svalue); } else { sprintf( svalue, "%i", * (int *)_P[_lastIndexSearch] ); } break; case TYPEULONG : // copy the value with format transformation sprintf( svalue, "%lu", * (unsigned long *)_P[_lastIndexSearch] ); break; } } int Ascdata::getParVal( char * svalue, const char * label ) { // a direct usage with label int index; // search index = this->getParIndex( label ); if (index != -1) this->getParVal( svalue ); return( index ); } /* * SetParVal() * * Set the par value from a string with format adaptation * Should be called only of a valid parameter is found! * * return * true if the value is modified (old != current) * false otherwise */ boolean Ascdata::setParVal( const char * svalue ) { // use _lastLindexSearch char options[BUFFERVALUE]; char strval[13] = ""; // a twelve digits string char *fmt; char *pvalue; int ivalue = 0; boolean updated; strcpy_P( options, dataoptions[_lastIndexSearch]); // copy into options fmt = strchr(options, ' ')+1; // locate the format string switch ( _indextype[_lastIndexSearch] ) { case TYPEBYTE : // copy the value with format transformation updated = (* (byte *)_P[_lastIndexSearch] != (byte) atoi(svalue)); * (byte *)_P[_lastIndexSearch] = (byte) atoi(svalue); break; case TYPEINT : // copy the value with format transformation if ( strcmp( fmt, "f4.2") == 0 ) { // we should copy the string in XXX.XX format // // sscanf doesn't work properly with %x on Arduino (x!=i)... // // add two '0' with append // locate the '.' // remove '.' and move two digits + '\0', // that's it // strcpy( strval, svalue ); // strval is a working string strcat( strval, "00\0" ); // add two '0' pvalue = strchr(strval, '.'); // locate the . if ( pvalue != NULL) { // move and get only two digits pvalue[0] = pvalue[1]; pvalue[1] = pvalue[2]; pvalue[2] = '\0'; } updated = (* (int *)_P[_lastIndexSearch] != atoi(strval)); * (int *)_P[_lastIndexSearch] = atoi(strval); } else { updated = (* (int *)_P[_lastIndexSearch] != atoi(svalue)); * (int *)_P[_lastIndexSearch] = atoi(svalue); } break; case TYPEULONG : // copy the value with format transformation updated = (* (unsigned long *)_P[_lastIndexSearch] != atol(svalue)); * (unsigned long *)_P[_lastIndexSearch] = atol(svalue); break; } return( updated ); } int Ascdata::setParVal( const char * svalue, const char * label ) { // a direct usage with label int index; // search index = this->getParIndex( label ); if (index != -1) this->setParVal( svalue ); return( index ); } /* * A simple mechanism to loop into the data * * === usage =========================================== * index = mydata.loopIndex(-1) // first call with -1 * * while (index != -1) { * do_with_index (_lastLindexSearch is updated) * index = mydata.loopIndex(index); // don't forget it! * } * ===================================================== */ int Ascdata::loopIndex(int index) { int nxtindx; // First call with -1 if ( index == -1 ) { nxtindx = 0; } else if ( index >= _npar-1 ) { // last element done nxtindx = -1; } else { nxtindx = index+1; } _lastIndexSearch = nxtindx; return( nxtindx ); } /* * Return a string with the label of _lastIndexSearch */ char * Ascdata::loopLabel() { strcpy_P( labelbuf, datalabels[_lastIndexSearch] ); // Achtung return( labelbuf ); } /* * Return a string with the svalue of _lastIndexSearch */ char * Ascdata::loopSvalue() { this->getParVal( labelbuf ); return( labelbuf ); } /* * ####################################### * Synchronization with datastore (bridge) * ####################################### */ /* * bridgeGet() * * access = '*' to retrieve all the data from datastore * else, only the data with the selected acces are copied * In a classical use, the access in 'g' (get) * * return the number of saved updated parameters */ int Ascdata::bridgeGet( char access ) { // int index; int updates; char bufval[BUFFERVALUE]; // a BUFFERVALUE-1 chars buffer char buflab[BUFFERLABEL]; // a BUFFERLABEL-1 chars buffer updates = 0; index = this->loopIndex(-1); // first call with -1 while (index != -1) { // we only get the selected data or 'all' if access == '*' strcpy_P( buflab, datalabels[_lastIndexSearch] ); // Achtung if ( this->checkParAccess(access) || access == '*' ) { // get the data from datastore Bridge.get( buflab, bufval, BUFFERVALUE-1 ); if ( setParVal( bufval ) & checkParAccess('s') ) updates += 1; // check for 's' option } index = this->loopIndex(index); // don't forget it! } return( updates ); } /* * bridgePut() * * access = '*' to copy all the data into datastore * else, only the data with the selected acces are copied * In a classical use, the access in 'p' (put) */ int Ascdata::bridgePut( char access ) { // int index; char bufval[BUFFERVALUE]; // a BUFFERVALUE-1 chars buffer index = this->loopIndex(-1); // first call with -1 while (index != -1) { // we only put the selected data or 'all' if access == '*' if ( this->checkParAccess(access) || access == '*' ) { // put the data into datastore strcpy_P( labelbuf, datalabels[_lastIndexSearch] ); // Achtung getParVal( bufval ); Bridge.put( labelbuf, bufval ); } index = this->loopIndex(index); // don't forget it! } return( 0 ); } /* * bridgePutVersion() * * put the version info into datastore */ void Ascdata::bridgePutVersion( const char * sversion ) { Bridge.put( "version", sversion ); } /* * bridgePutRequest() * * put the request data into datastore */ void Ascdata::bridgePutRequest( const char * srequest ) { Bridge.put( "request", srequest ); } /* * bridgeGetRequest() * * get the current request and store it in _lastrequest * return true if != 'none' //i.e. if there is a new request */ boolean Ascdata::bridgeGetRequest() { Bridge.get( "request", _lastrequest, REQUESTBUF_SIZE-1 ); // get the current request return( ( strcmp( "none", _lastrequest ) != 0 ) ); } /* * isRequest() * * true if srequest == _lastrequest */ boolean Ascdata::isRequest(const char * srequest) { return( ( strcmp( srequest, _lastrequest ) == 0 ) ); } /* * ################# * EEPROM Management * ################# * * loop in the par list and write if s or u are slected * only the modified values will be writen * (put and get functions of EEPROM.h) * * Two values are stored for each 's' data * a) the last saved data (value = 0) * b) the default value (defined in the main sktech) (value = 1) */ int Ascdata::EEPROM_put( char* tag10, int value ) { int err = 0; int index; int eeaddress = 10*sizeof(byte); // begin at the first location -- 10 bytes for info // write the tag for ( int i = 0; i<10; i++ ) { EEPROM.put( i*sizeof(byte), tag10[i] ); } index = this->loopIndex(-1); while( index != -1 && err == 0 ) { // get the access of current parameter if ( this->checkParAccess('s') ) { switch ( _indextype[_lastIndexSearch] ) { case TYPEBYTE : eeaddress = eeaddress + value*sizeof(byte); // access to the default value if value == 1 EEPROM.put(eeaddress, * (byte *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(byte); // skip 2 if value == 0 break; case TYPEINT : eeaddress = eeaddress + value*sizeof(int); // access to the default value if value == 1 EEPROM.put(eeaddress, * (int *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(int); // skip 2 if value == 0 break; case TYPEULONG : //EEPROM.put(eeaddress, * (unsigned long *)_P[_lastIndexSearch] ); eeaddress = eeaddress + value*sizeof(unsigned long); // access to the default value if value == 1 EEPROMWritelong( eeaddress, * (unsigned long *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(unsigned long); // skip 2 if value == 0 break; } if (eeaddress >= EEPROM.length()) err = -1; } index = this->loopIndex( index ); } return( err ); } /* * Get the data from EEPROM in the same way than updateEEPROM() * share the same looping mechanism * * Two values are stored for each 's' data * a) the last saved data (value = 0) * b) the default value (defined in the main sktech) (value = 1) * * WARNING: * on YUN, EEPROM is erased on sketch upload * to modify this behaviours, we need to modify the bootloader * see http://forum.arduino.cc/index.php?topic=204656.0 and * http://www.engbedded.com/fusecalc/ * */ int Ascdata::EEPROM_get( char* tag10, int value ) { int err = 0; int index; int eeaddress = 10*sizeof(byte); // begin at the first location -- 10 bytes for info char cur; // read and check first 10 bytes for ( int i = 0; i<10; i++ ) { EEPROM.get( i*sizeof(byte), cur ); if ( cur != tag10[i] ) err = -1; } index = this->loopIndex(-1); while( index != -1 && err == 0 ) { // get the access of current parameter if ( this->checkParAccess('s') ) { switch ( _indextype[_lastIndexSearch] ) { case TYPEBYTE : eeaddress = eeaddress + value*sizeof(byte); // access to the default value if value == 1 EEPROM.get(eeaddress, * (byte *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(byte); // skip 2 if value == 0 break; case TYPEINT : eeaddress = eeaddress + value*sizeof(int); // access to the default value if value == 1 EEPROM.get(eeaddress, * (int *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(int); // skip 2 if value == 0 break; case TYPEULONG : //EEPROM.get(eeaddress, * (unsigned long *)_P[_lastIndexSearch] ); eeaddress = eeaddress + value*sizeof(unsigned long); // access to the default value if value == 1 * (unsigned long *)_P[_lastIndexSearch] = EEPROMReadlong( eeaddress ); eeaddress = eeaddress + (2-value)*sizeof(unsigned long); // skip 2 if value == 0 break; } if (eeaddress >= EEPROM.length()) err = -1; } index = this->loopIndex( index ); } return( err ); } /* * Added utilities for EEPROM management * see : http://playground.arduino.cc/Code/EEPROMReadWriteLong * * Write a 4 byte (32bit) long to the EEPROM */ void EEPROMWritelong(int address, long value) { //Decomposition from a long to 4 bytes by using bitshift. //One = Most significant -> Four = Least significant byte byte four = (value & 0xFF); byte three = ((value >> 8) & 0xFF); byte two = ((value >> 16) & 0xFF); byte one = ((value >> 24) & 0xFF); //Write the 4 bytes into the eeprom memory. EEPROM.write(address, four); EEPROM.write(address + 1, three); EEPROM.write(address + 2, two); EEPROM.write(address + 3, one); } /* * Read a 4 byte (32bit) long from the EEPROM */ unsigned long EEPROMReadlong(int address) { //Read the 4 bytes from the eeprom memory. unsigned long four = EEPROM.read(address); unsigned long three = EEPROM.read(address + 1); unsigned long two = EEPROM.read(address + 2); unsigned long one = EEPROM.read(address + 3); //Return the recomposed long by using bitshift. return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF); } <commit_msg>Delete ascdata.cpp<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** CommonFunctions.cpp ** ** Copyright (C) February 2016 Hotride ** ** 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. ** ***************************************************************************** */ //--------------------------------------------------------------------------- #include "stdafx.h" //--------------------------------------------------------------------------- const char *GetReagentName(WORD ID) { switch (ID) { case 0x0F7A: return "Black pearl"; case 0x0F7B: return "Bloodmoss"; case 0x0F84: return "Garlic"; case 0x0F85: return "Ginseng"; case 0x0F86: return "Mandrake root"; case 0x0F88: return "Nightshade"; case 0x0F8C: return "Sulfurous ash"; case 0x0F8D: return "Spiders silk"; default: break; } return ""; } //-------------------------------------------------------------------------- int CalculateSphereOffset(int max, int current, int maxValue, float divizor) { if (max > 0) { max = (int)((current / divizor) * (float)max); max = (maxValue * max) / 100; if (max < 0) max = 0; } return max; } //-------------------------------------------------------------------------- int CalculatePercents(int max, int current, int maxValue) { if (max > 0) { max = (current * 100) / max; if (max > 100) max = 100; if (max > 1) max = (maxValue * max) / 100; } return max; } //--------------------------------------------------------------------------- void TileOffsetOnMonitorToXY(int &ofsX, int &ofsY, int &x, int &y) { if (!ofsX) x = y = ofsY / 2; else if (!ofsY) { x = ofsX / 2; y = -x; } else //if (ofsX && ofsY) { int absX = abs(ofsX); int absY = abs(ofsY); x = ofsX; if (ofsY > ofsX) { if (ofsX < 0 && ofsY < 0) y = absX - absY; else if (ofsX > 0 && ofsY > 0) y = absY - absX; } else if (ofsX > ofsY) { if (ofsX < 0 && ofsY < 0) y = -(absY - absX); else if (ofsX > 0 && ofsY > 0) y = -(absX - absY); } if (!y && ofsY != ofsX) { if (ofsY < 0) y = -(absX + absY); else y = absX + absY; } y /= 2; x += y; } } //--------------------------------------------------------------------------- void UnuseShader() { glUseProgramObjectARB(0); ShaderTexture = 0; ShaderColorTable = 0; ShaderDrawMode = 0; CurrentShader = NULL; } //--------------------------------------------------------------------------- string FilePath(const string &fName) { return g_DirectoryPath + "\\" + fName; } //--------------------------------------------------------------------------- string EncodeUTF8(const wstring &wstr) { int size = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); string result = ""; if (size > 0) { result.resize(size + 1); WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &result[0], size, NULL, NULL); result[size] = 0; } return result; } //--------------------------------------------------------------------------- wstring DecodeUTF8(const string &str) { int size = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); wstring result = L""; if (size > 0) { result.resize(size + 1); MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &result[0], size); result[size] = 0; } return result; } //--------------------------------------------------------------------------- string ToString(const wstring &wstr) { string str = ""; int size = wstr.length(); int newSize = ::WideCharToMultiByte(GetACP(), 0, wstr.c_str(), size, NULL, 0, NULL, NULL); if (newSize > 0) { str.resize(newSize + 1); ::WideCharToMultiByte(GetACP(), 0, wstr.c_str(), size, &str[0], newSize, NULL, NULL); str[newSize] = 0; } return str; } //--------------------------------------------------------------------------- wstring ToWString(const string &str) { int size = str.length(); wstring wstr = L""; if (size > 0) { wstr.resize(size + 1); MultiByteToWideChar(GetACP(), 0, str.c_str(), size, &wstr[0], size); wstr[size] = 0; } return wstr; } //--------------------------------------------------------------------------- /*string ToString(wstring wstr) { int size = wstr.length(); string str = ""; if (size > 0) { char *text = new char[size + 1]; int len = uucode2str(wstr.c_str(), size, &text[0], size); text[size] = 0; str = text; delete text; } return str; } //--------------------------------------------------------------------------- wstring ToWString(string str) { int size = str.length(); wstring wstr = L""; if (size) { wchar_t *wbuf = new wchar_t[size + 1]; MultiByteToWideChar(GetACP(), 0, str.c_str(), size, &wbuf[0], size); wbuf[size] = 0; wstr = wbuf; delete wbuf; } return wstr; }*/ //--------------------------------------------------------------------------- string ToLowerA(string str) { _strlwr(&str[0]); return str; } //--------------------------------------------------------------------------- string ToUpperA(string str) { _strupr(&str[0]); return str; } //--------------------------------------------------------------------------- wstring ToLowerW(wstring str) { _wcslwr(&str[0]); return str; } //--------------------------------------------------------------------------- wstring ToUpperW(wstring str) { _wcsupr(&str[0]); return str; } //--------------------------------------------------------------------------- bool ToBool(const string &str) { string data = ToLowerA(str); const int countOfTrue = 3; const string m_TrueValues[countOfTrue] = { "on", "yes", "true" }; bool result = false; IFOR(i, 0, countOfTrue && !result) result = (data == m_TrueValues[i]); return result; } //--------------------------------------------------------------------------- int GetDistance(TGameObject *current, TGameObject *target) { if (current != NULL && target != NULL) { int distx = abs(target->X - current->X); int disty = abs(target->Y - current->Y); if (disty > distx) distx = disty; return distx; } return 100500; } //--------------------------------------------------------------------------- int GetDistance(TGameObject *current, POINT target) { if (current != NULL) { int distx = abs(target.x - current->X); int disty = abs(target.y - current->Y); if (disty > distx) distx = disty; return distx; } return 100500; } //--------------------------------------------------------------------------- int GetDistance(POINT current, TGameObject *target) { if (target != NULL) { int distx = abs(target->X - current.x); int disty = abs(target->Y - current.y); if (disty > distx) distx = disty; return distx; } return 100500; } //--------------------------------------------------------------------------- int GetMultiDistance(POINT current, TGameObject *target) { int result = 100500; if (target != NULL && target->Graphic >= 0x4000 && target->m_Items != NULL) { TMulti *multi = (TMulti*)target->m_Items; int multiDistance = abs(multi->MinX); int testDistance = abs(multi->MinY); if (multiDistance < testDistance) multiDistance = testDistance; testDistance = abs(multi->MaxX); if (multiDistance < testDistance) multiDistance = testDistance; testDistance = abs(multi->MaxY); if (multiDistance < testDistance) multiDistance = testDistance; multiDistance--; int distX = abs(target->X - current.x) - multiDistance; int distY = abs(target->Y - current.y) - multiDistance; if (distY > distX) distX = distY; if (distX < result) result = distX; } return result; } //--------------------------------------------------------------------------- int GetDistance(POINT current, POINT target) { int distx = abs(target.x - current.x); int disty = abs(target.y - current.y); if (disty > distx) distx = disty; return distx; } //--------------------------------------------------------------------------- int GetTopObjDistance(TGameObject *current, TGameObject *target) { if (current != NULL && target != NULL) { while (target != NULL && target->Container != 0xFFFFFFFF) target = World->FindWorldObject(target->Container); if (target != NULL) { int distx = abs(target->X - current->X); int disty = abs(target->Y - current->Y); if (disty > distx) distx = disty; return distx; } } return 100500; } //--------------------------------------------------------------------------- int gumpuucode2str(const wchar_t* wstr, int wlength, LPSTR receiver, int maxsize) { if (!wlength || wlength < -1 || maxsize < 1) return 0; int msize = ((wlength < 0) ? (maxsize * 2 + 2) : (wlength * 2 + 2)); PBYTE buf = new BYTE[msize]; memcpy(buf, wstr, msize - 2); int len = 0; PBYTE p = buf + 1; while (len < maxsize) { if (wlength < 0) if (!*(p - 1) && !*p) { len++; break; } else; if (len >= wlength) break; BYTE c = *(p - 1); *(p - 1) = *p; *p = c; len++; p += 2; } len = WideCharToMultiByte(GetACP(), 0, (LPCWSTR)buf, len, receiver, maxsize, 0, 0); delete buf; if (len < maxsize && len && receiver[len - 1]) receiver[len++] = 0; return len; } //--------------------------------------------------------------------------- int uucode2str(const wchar_t* wstr, int wlength, LPSTR receiver, int maxsize) { if (!wlength || wlength < -1 || maxsize < 1) return 0; int msize = ((wlength < 0) ? (maxsize * 2 + 2) : (wlength * 2 + 2)); int len = lstrlenW(wstr); len = WideCharToMultiByte(GetACP(), 0, wstr, len, receiver, maxsize, 0, 0); if (len < maxsize && len && receiver[len - 1]) receiver[len++] = 0; return len; } //-------------------------------------------------------------------------- int str2uucode(const char* str, int length, wchar_t* wreceiver, int wmaxsize) { if (!length || length < -1 || wmaxsize < 1 || !wreceiver) return 0; int len = 0, i; wreceiver[0] = 0; len = MultiByteToWideChar(GetACP(), 0, str, length, wreceiver, wmaxsize); PBYTE p = (PBYTE)wreceiver + 1; for (i = 0; i < len && (*(p - 1) || *p) && i < wmaxsize; i++, p += 2) { BYTE c = *(p - 1); *(p - 1) = *p; *p = c; } if (i < wmaxsize && i && wreceiver[i - 1]) wreceiver[i] = 0; return i; } //---------------------------------------------------------------------------<commit_msg>Почистил мусор.<commit_after>/**************************************************************************** ** ** CommonFunctions.cpp ** ** Copyright (C) February 2016 Hotride ** ** 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. ** ***************************************************************************** */ //--------------------------------------------------------------------------- #include "stdafx.h" //--------------------------------------------------------------------------- const char *GetReagentName(WORD ID) { switch (ID) { case 0x0F7A: return "Black pearl"; case 0x0F7B: return "Bloodmoss"; case 0x0F84: return "Garlic"; case 0x0F85: return "Ginseng"; case 0x0F86: return "Mandrake root"; case 0x0F88: return "Nightshade"; case 0x0F8C: return "Sulfurous ash"; case 0x0F8D: return "Spiders silk"; default: break; } return ""; } //-------------------------------------------------------------------------- int CalculateSphereOffset(int max, int current, int maxValue, float divizor) { if (max > 0) { max = (int)((current / divizor) * (float)max); max = (maxValue * max) / 100; if (max < 0) max = 0; } return max; } //-------------------------------------------------------------------------- int CalculatePercents(int max, int current, int maxValue) { if (max > 0) { max = (current * 100) / max; if (max > 100) max = 100; if (max > 1) max = (maxValue * max) / 100; } return max; } //--------------------------------------------------------------------------- void TileOffsetOnMonitorToXY(int &ofsX, int &ofsY, int &x, int &y) { if (!ofsX) x = y = ofsY / 2; else if (!ofsY) { x = ofsX / 2; y = -x; } else //if (ofsX && ofsY) { int absX = abs(ofsX); int absY = abs(ofsY); x = ofsX; if (ofsY > ofsX) { if (ofsX < 0 && ofsY < 0) y = absX - absY; else if (ofsX > 0 && ofsY > 0) y = absY - absX; } else if (ofsX > ofsY) { if (ofsX < 0 && ofsY < 0) y = -(absY - absX); else if (ofsX > 0 && ofsY > 0) y = -(absX - absY); } if (!y && ofsY != ofsX) { if (ofsY < 0) y = -(absX + absY); else y = absX + absY; } y /= 2; x += y; } } //--------------------------------------------------------------------------- void UnuseShader() { glUseProgramObjectARB(0); ShaderTexture = 0; ShaderColorTable = 0; ShaderDrawMode = 0; CurrentShader = NULL; } //--------------------------------------------------------------------------- string FilePath(const string &fName) { return g_DirectoryPath + "\\" + fName; } //--------------------------------------------------------------------------- string EncodeUTF8(const wstring &wstr) { int size = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); string result = ""; if (size > 0) { result.resize(size + 1); WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &result[0], size, NULL, NULL); result.resize(size); // result[size] = 0; } return result; } //--------------------------------------------------------------------------- wstring DecodeUTF8(const string &str) { int size = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); wstring result = L""; if (size > 0) { result.resize(size + 1); MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &result[0], size); result.resize(size); // result[size] = 0; } return result; } //--------------------------------------------------------------------------- string ToString(const wstring &wstr) { string str = ""; int size = wstr.length(); int newSize = ::WideCharToMultiByte(GetACP(), 0, wstr.c_str(), size, NULL, 0, NULL, NULL); if (newSize > 0) { str.resize(newSize + 1); ::WideCharToMultiByte(GetACP(), 0, wstr.c_str(), size, &str[0], newSize, NULL, NULL); str.resize(newSize); // str[newSize] = 0; } return str; } //--------------------------------------------------------------------------- wstring ToWString(const string &str) { int size = str.length(); wstring wstr = L""; if (size > 0) { wstr.resize(size + 1); MultiByteToWideChar(GetACP(), 0, str.c_str(), size, &wstr[0], size); wstr.resize(size); // wstr[size] = 0; } return wstr; } //--------------------------------------------------------------------------- string ToLowerA(string str) { _strlwr(&str[0]); return str; } //--------------------------------------------------------------------------- string ToUpperA(string str) { _strupr(&str[0]); return str; } //--------------------------------------------------------------------------- wstring ToLowerW(wstring str) { _wcslwr(&str[0]); return str; } //--------------------------------------------------------------------------- wstring ToUpperW(wstring str) { _wcsupr(&str[0]); return str; } //--------------------------------------------------------------------------- bool ToBool(const string &str) { string data = ToLowerA(str); const int countOfTrue = 3; const string m_TrueValues[countOfTrue] = { "on", "yes", "true" }; bool result = false; IFOR(i, 0, countOfTrue && !result) result = (data == m_TrueValues[i]); return result; } //--------------------------------------------------------------------------- int GetDistance(TGameObject *current, TGameObject *target) { if (current != NULL && target != NULL) { int distx = abs(target->X - current->X); int disty = abs(target->Y - current->Y); if (disty > distx) distx = disty; return distx; } return 100500; } //--------------------------------------------------------------------------- int GetDistance(TGameObject *current, POINT target) { if (current != NULL) { int distx = abs(target.x - current->X); int disty = abs(target.y - current->Y); if (disty > distx) distx = disty; return distx; } return 100500; } //--------------------------------------------------------------------------- int GetDistance(POINT current, TGameObject *target) { if (target != NULL) { int distx = abs(target->X - current.x); int disty = abs(target->Y - current.y); if (disty > distx) distx = disty; return distx; } return 100500; } //--------------------------------------------------------------------------- int GetMultiDistance(POINT current, TGameObject *target) { int result = 100500; if (target != NULL && target->Graphic >= 0x4000 && target->m_Items != NULL) { TMulti *multi = (TMulti*)target->m_Items; int multiDistance = abs(multi->MinX); int testDistance = abs(multi->MinY); if (multiDistance < testDistance) multiDistance = testDistance; testDistance = abs(multi->MaxX); if (multiDistance < testDistance) multiDistance = testDistance; testDistance = abs(multi->MaxY); if (multiDistance < testDistance) multiDistance = testDistance; multiDistance--; int distX = abs(target->X - current.x) - multiDistance; int distY = abs(target->Y - current.y) - multiDistance; if (distY > distX) distX = distY; if (distX < result) result = distX; } return result; } //--------------------------------------------------------------------------- int GetDistance(POINT current, POINT target) { int distx = abs(target.x - current.x); int disty = abs(target.y - current.y); if (disty > distx) distx = disty; return distx; } //--------------------------------------------------------------------------- int GetTopObjDistance(TGameObject *current, TGameObject *target) { if (current != NULL && target != NULL) { while (target != NULL && target->Container != 0xFFFFFFFF) target = World->FindWorldObject(target->Container); if (target != NULL) { int distx = abs(target->X - current->X); int disty = abs(target->Y - current->Y); if (disty > distx) distx = disty; return distx; } } return 100500; } //--------------------------------------------------------------------------- int gumpuucode2str(const wchar_t* wstr, int wlength, LPSTR receiver, int maxsize) { if (!wlength || wlength < -1 || maxsize < 1) return 0; int msize = ((wlength < 0) ? (maxsize * 2 + 2) : (wlength * 2 + 2)); PBYTE buf = new BYTE[msize]; memcpy(buf, wstr, msize - 2); int len = 0; PBYTE p = buf + 1; while (len < maxsize) { if (wlength < 0) if (!*(p - 1) && !*p) { len++; break; } else; if (len >= wlength) break; BYTE c = *(p - 1); *(p - 1) = *p; *p = c; len++; p += 2; } len = WideCharToMultiByte(GetACP(), 0, (LPCWSTR)buf, len, receiver, maxsize, 0, 0); delete buf; if (len < maxsize && len && receiver[len - 1]) receiver[len++] = 0; return len; } //--------------------------------------------------------------------------- int uucode2str(const wchar_t* wstr, int wlength, LPSTR receiver, int maxsize) { if (!wlength || wlength < -1 || maxsize < 1) return 0; int msize = ((wlength < 0) ? (maxsize * 2 + 2) : (wlength * 2 + 2)); int len = lstrlenW(wstr); len = WideCharToMultiByte(GetACP(), 0, wstr, len, receiver, maxsize, 0, 0); if (len < maxsize && len && receiver[len - 1]) receiver[len++] = 0; return len; } //-------------------------------------------------------------------------- int str2uucode(const char* str, int length, wchar_t* wreceiver, int wmaxsize) { if (!length || length < -1 || wmaxsize < 1 || !wreceiver) return 0; int len = 0, i; wreceiver[0] = 0; len = MultiByteToWideChar(GetACP(), 0, str, length, wreceiver, wmaxsize); PBYTE p = (PBYTE)wreceiver + 1; for (i = 0; i < len && (*(p - 1) || *p) && i < wmaxsize; i++, p += 2) { BYTE c = *(p - 1); *(p - 1) = *p; *p = c; } if (i < wmaxsize && i && wreceiver[i - 1]) wreceiver[i] = 0; return i; } //---------------------------------------------------------------------------<|endoftext|>
<commit_before>#ifndef K3_UNIQPOLYBUF #define K3_UNIQPOLYBUF #include <unordered_set> #if HAS_LIBDYNAMIC #include <boost/serialization/array.hpp> #include <boost/serialization/string.hpp> #include <boost/functional/hash.hpp> #include <yaml-cpp/yaml.h> #include <rapidjson/document.h> #include <csvpp/csv.h> #include "serialization/Json.hpp" #include "Common.hpp" #include "collections/STLDataspace.hpp" #include "collections/Collection.hpp" #include "collections/FlatPolyBuffer.hpp" namespace K3 { namespace Libdynamic { // Forward declaration. template<class Ignore, class Derived> class UniquePolyBuffer; ////////////////////////////////////////// // // Buffer functors. struct UPBValueProxy { UPBValueProxy(size_t o) : asOffset(true), offset(o) {} UPBValueProxy(char* p) : asOffset(false), elem(p) {} bool asOffset; union { char* elem; size_t offset; }; }; template<typename Tag> using UPBKey = std::pair<Tag, UPBValueProxy>; template<class Ignore, class T, typename Tag> struct UPBEqual : std::binary_function<UPBKey<Tag>, UPBKey<Tag>, bool> { using UPB = UniquePolyBuffer<Ignore, T>; using ExternalizerT = BufferExternalizer; using InternalizerT = BufferInternalizer; UPB* container; ExternalizerT etl; InternalizerT itl; UPBEqual(UPB* c) : container(c), etl(container->variable(), ExternalizerT::ExternalizeOp::Reuse), itl(container->variable()) {} bool operator()(const UPBKey<Tag>& left, const UPBKey<Tag>& right) const { auto buffer = container->fixed(); char* lp = left.second.asOffset? buffer_data(buffer) + left.second.offset : left.second.elem; char* rp = right.second.asOffset? buffer_data(buffer) + right.second.offset : right.second.elem; if ( !container->isInternalized() ) { if ( left.second.asOffset ) { T::internalize(const_cast<InternalizerT&>(itl), left.first, lp); } if ( right.second.asOffset ) { T::internalize(const_cast<InternalizerT&>(itl), right.first, rp); } } bool r = T::equalelem(left.first, lp, right.first, rp); if ( !container->isInternalized() ) { if ( left.second.asOffset ) { T::externalize(const_cast<ExternalizerT&>(etl), left.first, lp); } if ( right.second.asOffset ) { T::externalize(const_cast<ExternalizerT&>(etl), right.first, rp); } } return r; } }; template<typename Ignore, typename T, typename Tag> struct UPBHash : std::unary_function<UPBKey<Tag>, std::size_t> { using UPB = UniquePolyBuffer<Ignore, T>; using ExternalizerT = BufferExternalizer; using InternalizerT = BufferInternalizer; UPB* container; ExternalizerT etl; InternalizerT itl; UPBHash(UPB* c) : container(c), etl(container->variable(), ExternalizerT::ExternalizeOp::Reuse), itl(container->variable()) {} std::size_t operator()(const UPBKey<Tag>& k) const { std::hash<Tag> hash; size_t h1 = hash(k.first); auto buffer = container->fixed(); char* p = k.second.asOffset? buffer_data(buffer) + k.second.offset : k.second.elem; if ( !container->isInternalized() && k.second.asOffset ) { T::internalize(const_cast<InternalizerT&>(itl), k.first, p); } boost::hash_combine(h1, T::hashelem(k.first, p)); if ( !container->isInternalized() && k.second.asOffset ) { T::externalize(const_cast<ExternalizerT&>(etl), k.first, p); } return h1; } }; ////////////////////////////////////////// // // UniquePolyBuffer template<class Ignore, class Derived> class UniquePolyBuffer : public FlatPolyBuffer<Ignore, Derived> { public: using Super = FlatPolyBuffer<Ignore, Derived>; using Tag = typename Super::Tag; using FContainer = typename Super::FContainer; using VContainer = typename Super::VContainer; using TContainer = typename Super::TContainer; UniquePolyBuffer() : Super(), comparator(this), hasher(this), keys(10, hasher, comparator) {} UniquePolyBuffer(const UniquePolyBuffer& other) : Super(other), comparator(this), hasher(this), keys(10, hasher, comparator) { std::copy(other.keys.begin(), other.keys.end(), std::inserter(keys, keys.begin())); } UniquePolyBuffer(UniquePolyBuffer&& other) : Super(std::move(other)), comparator(this), hasher(this), keys(10, hasher, comparator) { rebuildKeys(); } UniquePolyBuffer& operator=(const UniquePolyBuffer& other) { Super::operator=(other); std::copy(other.keys.begin(), other.keys.end(), std::inserter(keys, keys.begin())); return *this; } UniquePolyBuffer& operator=(UniquePolyBuffer&& other) { Super::operator=(std::move(other)); keys.clear(); rebuildKeys(); return *this; } ~UniquePolyBuffer() {} void rebuildKeys() { size_t foffset = 0, sz = Super::size(unit_t{}); for (size_t i = 0; i < sz; ++i) { Tag tg = Super::tag_at(i); keys.insert(std::make_pair(tg, std::move(UPBValueProxy { foffset }))); foffset += this->elemsize(tg); } } ////////////////////////////////// // // Tag-specific accessors. template<typename T> unit_t append(Tag tg, const T& t) { UPBValueProxy probe { reinterpret_cast<char*>(const_cast<T*>(&t)) }; if ( keys.find(std::make_pair(tg, probe)) == keys.end() ) { FContainer* ncf = const_cast<FContainer*>(Super::fixedc()); size_t offset = buffer_size(ncf); Super::append(tg, t); keys.insert(std::make_pair(tg, std::move(UPBValueProxy { offset }))); } return unit_t{}; } // Clears a container, deleting any backing buffer. unit_t clear(unit_t) { keys.clear(); return Super::clear(unit_t{}); } unit_t load(const base_string& str) { return load(base_string(str)); } // Restores a flat poly buffer from a string. unit_t load(base_string&& str) { Super::load(std::forward<base_string>(str)); rebuildKeys(); return unit_t{}; } template <class archive> void save(archive& a, const unsigned int) const { a << boost::serialization::base_object<const Super>(*this); } template <class archive> void load(archive& a, const unsigned int) { a >> boost::serialization::base_object<Super>(*this); rebuildKeys(); } template <class archive> void serialize(archive& a) const { Super::serialize(a); } template <class archive> void serialize(archive& a) { Super::serialize(a); rebuildKeys(); } BOOST_SERIALIZATION_SPLIT_MEMBER() private: friend class UPBEqual<Ignore, Derived, Tag>; friend class UPBHash<Ignore, Derived, Tag>; UPBEqual<Ignore, Derived, Tag> comparator; UPBHash<Ignore, Derived, Tag> hasher; std::unordered_set<UPBKey<Tag>, UPBHash<Ignore, Derived, Tag>, UPBEqual<Ignore, Derived, Tag>> keys; }; }; // end namespace Libdynamic template<class Ignored, class Derived> using UniquePolyBuffer = Libdynamic::UniquePolyBuffer<Ignored, Derived>; }; // end namespace K3 namespace YAML { template <class E, class Derived> struct convert<K3::UniquePolyBuffer<E, Derived>> { using Tag = typename K3::UniquePolyBuffer<E, Derived>::Tag; static Node encode(const K3::UniquePolyBuffer<E, Derived>& c) { Node node; bool flag = true; c.iterate([&c, &node, &flag](Tag tg, size_t idx, size_t offset){ if (flag) { flag = false; } node.push_back(c.yamlencode(tg, idx, offset)); }); if (flag) { node = YAML::Load("[]"); } return node; } static bool decode(const Node& node, K3::UniquePolyBuffer<E, Derived>& c) { for (auto i : node) { c.yamldecode(i); } return true; } }; } // namespace YAML namespace JSON { using namespace rapidjson; template <class E, class Derived> struct convert<K3::UniquePolyBuffer<E, Derived>> { using Tag = typename K3::UniquePolyBuffer<E, Derived>::Tag; template <class Allocator> static Value encode(const K3::UniquePolyBuffer<E, Derived>& c, Allocator& al) { Value v; v.SetObject(); v.AddMember("type", Value("UniquePolyBuffer"), al); Value inner; inner.SetArray(); c.iterate([&c, &inner, &al](Tag tg, size_t idx, size_t offset){ inner.PushBack(c.jsonencode(tg, idx, offset, al), al); }); v.AddMember("value", inner.Move(), al); return v; } }; } // namespace JSON #endif // HAS_LIBDYNAMIC #endif <commit_msg>Reverting to element-wise move for UPB, with additional clear in move assignment<commit_after>#ifndef K3_UNIQPOLYBUF #define K3_UNIQPOLYBUF #include <unordered_set> #if HAS_LIBDYNAMIC #include <boost/serialization/array.hpp> #include <boost/serialization/string.hpp> #include <boost/functional/hash.hpp> #include <yaml-cpp/yaml.h> #include <rapidjson/document.h> #include <csvpp/csv.h> #include "serialization/Json.hpp" #include "Common.hpp" #include "collections/STLDataspace.hpp" #include "collections/Collection.hpp" #include "collections/FlatPolyBuffer.hpp" namespace K3 { namespace Libdynamic { // Forward declaration. template<class Ignore, class Derived> class UniquePolyBuffer; ////////////////////////////////////////// // // Buffer functors. struct UPBValueProxy { UPBValueProxy(size_t o) : asOffset(true), offset(o) {} UPBValueProxy(char* p) : asOffset(false), elem(p) {} bool asOffset; union { char* elem; size_t offset; }; }; template<typename Tag> using UPBKey = std::pair<Tag, UPBValueProxy>; template<class Ignore, class T, typename Tag> struct UPBEqual : std::binary_function<UPBKey<Tag>, UPBKey<Tag>, bool> { using UPB = UniquePolyBuffer<Ignore, T>; using ExternalizerT = BufferExternalizer; using InternalizerT = BufferInternalizer; UPB* container; ExternalizerT etl; InternalizerT itl; UPBEqual(UPB* c) : container(c), etl(container->variable(), ExternalizerT::ExternalizeOp::Reuse), itl(container->variable()) {} bool operator()(const UPBKey<Tag>& left, const UPBKey<Tag>& right) const { auto buffer = container->fixed(); char* lp = left.second.asOffset? buffer_data(buffer) + left.second.offset : left.second.elem; char* rp = right.second.asOffset? buffer_data(buffer) + right.second.offset : right.second.elem; if ( !container->isInternalized() ) { if ( left.second.asOffset ) { T::internalize(const_cast<InternalizerT&>(itl), left.first, lp); } if ( right.second.asOffset ) { T::internalize(const_cast<InternalizerT&>(itl), right.first, rp); } } bool r = T::equalelem(left.first, lp, right.first, rp); if ( !container->isInternalized() ) { if ( left.second.asOffset ) { T::externalize(const_cast<ExternalizerT&>(etl), left.first, lp); } if ( right.second.asOffset ) { T::externalize(const_cast<ExternalizerT&>(etl), right.first, rp); } } return r; } }; template<typename Ignore, typename T, typename Tag> struct UPBHash : std::unary_function<UPBKey<Tag>, std::size_t> { using UPB = UniquePolyBuffer<Ignore, T>; using ExternalizerT = BufferExternalizer; using InternalizerT = BufferInternalizer; UPB* container; ExternalizerT etl; InternalizerT itl; UPBHash(UPB* c) : container(c), etl(container->variable(), ExternalizerT::ExternalizeOp::Reuse), itl(container->variable()) {} std::size_t operator()(const UPBKey<Tag>& k) const { std::hash<Tag> hash; size_t h1 = hash(k.first); auto buffer = container->fixed(); char* p = k.second.asOffset? buffer_data(buffer) + k.second.offset : k.second.elem; if ( !container->isInternalized() && k.second.asOffset ) { T::internalize(const_cast<InternalizerT&>(itl), k.first, p); } boost::hash_combine(h1, T::hashelem(k.first, p)); if ( !container->isInternalized() && k.second.asOffset ) { T::externalize(const_cast<ExternalizerT&>(etl), k.first, p); } return h1; } }; ////////////////////////////////////////// // // UniquePolyBuffer template<class Ignore, class Derived> class UniquePolyBuffer : public FlatPolyBuffer<Ignore, Derived> { public: using Super = FlatPolyBuffer<Ignore, Derived>; using Tag = typename Super::Tag; using FContainer = typename Super::FContainer; using VContainer = typename Super::VContainer; using TContainer = typename Super::TContainer; UniquePolyBuffer() : Super(), comparator(this), hasher(this), keys(10, hasher, comparator) {} UniquePolyBuffer(const UniquePolyBuffer& other) : Super(other), comparator(this), hasher(this), keys(10, hasher, comparator) { std::copy(other.keys.begin(), other.keys.end(), std::inserter(keys, keys.begin())); } UniquePolyBuffer(UniquePolyBuffer&& other) : Super(std::move(other)), comparator(this), hasher(this), keys(10, hasher, comparator) { for (auto&& elem : other.keys) { keys.insert(std::move(elem)); } } UniquePolyBuffer& operator=(const UniquePolyBuffer& other) { Super::operator=(other); std::copy(other.keys.begin(), other.keys.end(), std::inserter(keys, keys.begin())); return *this; } UniquePolyBuffer& operator=(UniquePolyBuffer&& other) { Super::operator=(std::move(other)); keys.clear(); for (auto&& elem : other.keys) { keys.insert(std::move(elem)); } return *this; } ~UniquePolyBuffer() {} void rebuildKeys() { size_t foffset = 0, sz = Super::size(unit_t{}); for (size_t i = 0; i < sz; ++i) { Tag tg = Super::tag_at(i); keys.insert(std::make_pair(tg, std::move(UPBValueProxy { foffset }))); foffset += this->elemsize(tg); } } ////////////////////////////////// // // Tag-specific accessors. template<typename T> unit_t append(Tag tg, const T& t) { UPBValueProxy probe { reinterpret_cast<char*>(const_cast<T*>(&t)) }; if ( keys.find(std::make_pair(tg, probe)) == keys.end() ) { FContainer* ncf = const_cast<FContainer*>(Super::fixedc()); size_t offset = buffer_size(ncf); Super::append(tg, t); keys.insert(std::make_pair(tg, std::move(UPBValueProxy { offset }))); } return unit_t{}; } // Clears a container, deleting any backing buffer. unit_t clear(unit_t) { keys.clear(); return Super::clear(unit_t{}); } unit_t load(const base_string& str) { return load(base_string(str)); } // Restores a flat poly buffer from a string. unit_t load(base_string&& str) { Super::load(std::forward<base_string>(str)); rebuildKeys(); return unit_t{}; } template <class archive> void save(archive& a, const unsigned int) const { a << boost::serialization::base_object<const Super>(*this); } template <class archive> void load(archive& a, const unsigned int) { a >> boost::serialization::base_object<Super>(*this); rebuildKeys(); } template <class archive> void serialize(archive& a) const { Super::serialize(a); } template <class archive> void serialize(archive& a) { Super::serialize(a); rebuildKeys(); } BOOST_SERIALIZATION_SPLIT_MEMBER() private: friend class UPBEqual<Ignore, Derived, Tag>; friend class UPBHash<Ignore, Derived, Tag>; UPBEqual<Ignore, Derived, Tag> comparator; UPBHash<Ignore, Derived, Tag> hasher; std::unordered_set<UPBKey<Tag>, UPBHash<Ignore, Derived, Tag>, UPBEqual<Ignore, Derived, Tag>> keys; }; }; // end namespace Libdynamic template<class Ignored, class Derived> using UniquePolyBuffer = Libdynamic::UniquePolyBuffer<Ignored, Derived>; }; // end namespace K3 namespace YAML { template <class E, class Derived> struct convert<K3::UniquePolyBuffer<E, Derived>> { using Tag = typename K3::UniquePolyBuffer<E, Derived>::Tag; static Node encode(const K3::UniquePolyBuffer<E, Derived>& c) { Node node; bool flag = true; c.iterate([&c, &node, &flag](Tag tg, size_t idx, size_t offset){ if (flag) { flag = false; } node.push_back(c.yamlencode(tg, idx, offset)); }); if (flag) { node = YAML::Load("[]"); } return node; } static bool decode(const Node& node, K3::UniquePolyBuffer<E, Derived>& c) { for (auto i : node) { c.yamldecode(i); } return true; } }; } // namespace YAML namespace JSON { using namespace rapidjson; template <class E, class Derived> struct convert<K3::UniquePolyBuffer<E, Derived>> { using Tag = typename K3::UniquePolyBuffer<E, Derived>::Tag; template <class Allocator> static Value encode(const K3::UniquePolyBuffer<E, Derived>& c, Allocator& al) { Value v; v.SetObject(); v.AddMember("type", Value("UniquePolyBuffer"), al); Value inner; inner.SetArray(); c.iterate([&c, &inner, &al](Tag tg, size_t idx, size_t offset){ inner.PushBack(c.jsonencode(tg, idx, offset, al), al); }); v.AddMember("value", inner.Move(), al); return v; } }; } // namespace JSON #endif // HAS_LIBDYNAMIC #endif <|endoftext|>
<commit_before>#ifndef VEXCL_TEMPORARY_HPP #define VEXCL_TEMPORARY_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru> 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. */ /** * \file vexcl/temporary.hpp * \author Denis Demidov <ddemidov@ksu.ru> * \brief Container for intermediate results. */ #include <set> #include <vexcl/operations.hpp> namespace vex { /// \cond INTERNAL struct temporary_terminal {}; typedef vector_expression< typename boost::proto::terminal< temporary_terminal >::type > temporary_terminal_expression; template <typename T, size_t Tag, class Expr> struct temporary : public temporary_terminal_expression { typedef T value_type; const Expr expr; temporary(const Expr &expr) : expr(expr) {} }; /// \endcond /// Create temporary to be reused in a vector expression. /** The type of the temporary is explicitly specified. */ template <size_t Tag, typename T, class Expr> auto make_temp(const Expr &expr) -> temporary<T, Tag, decltype(boost::proto::as_child<vector_domain>(expr))> { static_assert( boost::proto::matches< typename boost::proto::result_of::as_expr< Expr >::type, vector_expr_grammar >::value, "Unsupported expression in make_temp()" ); return temporary< T, Tag, decltype(boost::proto::as_child<vector_domain>(expr)) >(boost::proto::as_child<vector_domain>(expr)); } /// Create temporary to be reused in a vector expression. /** The type of the temporary is automatically deduced from the supplied * expression. */ template <size_t Tag, class Expr> auto make_temp(const Expr &expr) -> temporary< typename detail::return_type<Expr>::type, Tag, decltype(boost::proto::as_child<vector_domain>(expr)) > { static_assert( boost::proto::matches< typename boost::proto::result_of::as_expr< Expr >::type, vector_expr_grammar >::value, "Unsupported expression in make_temp()" ); return temporary< typename detail::return_type<Expr>::type, Tag, decltype(boost::proto::as_child<vector_domain>(expr)) >(boost::proto::as_child<vector_domain>(expr)); } #ifdef VEXCL_MULTIVECTOR_HPP /// \cond INTERNAL struct mv_temporary_terminal {}; typedef multivector_expression< typename boost::proto::terminal< mv_temporary_terminal >::type > mv_temporary_terminal_expression; template <typename T, size_t Tag, class Expr> struct mv_temporary : public mv_temporary_terminal_expression { const Expr expr; mv_temporary(const Expr &expr) : expr(expr) {} }; /// \endcond /// Create temporary to be reused in a multivector expression. template <size_t Tag, typename T, class Expr> typename std::enable_if< boost::proto::matches< typename boost::proto::result_of::as_expr< Expr >::type, multivector_expr_grammar >::value, mv_temporary<T, Tag, Expr> >::type make_temp(const Expr &expr) { return mv_temporary<T, Tag, Expr>(expr); } #endif /// \cond INTERNAL namespace traits { template <> struct is_vector_expr_terminal< temporary_terminal > : std::true_type {}; template <> struct proto_terminal_is_value< temporary_terminal > : std::true_type {}; template <typename T, size_t Tag, class Expr> struct terminal_preamble< temporary<T, Tag, Expr> > { static std::string get(const temporary<T, Tag, Expr> &term, const cl::Device &dev, const std::string &prm_name, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::set<size_t>()) )).first; } auto &pos = boost::any_cast< std::set<size_t>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { pos.insert(Tag); std::ostringstream s; detail::output_terminal_preamble termpream(s, dev, 1, prm_name + "_"); boost::proto::eval(boost::proto::as_child(term.expr), termpream); return s.str(); } else { return ""; } } }; template <typename T, size_t Tag, class Expr> struct kernel_param_declaration< temporary<T, Tag, Expr> > { static std::string get(const temporary<T, Tag, Expr> &term, const cl::Device &dev, const std::string &prm_name, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::set<size_t>()) )).first; } auto &pos = boost::any_cast< std::set<size_t>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { pos.insert(Tag); std::ostringstream s; detail::declare_expression_parameter declare(s, dev, 1, prm_name + "_"); detail::extract_terminals()(boost::proto::as_child(term.expr), declare); return s.str(); } else { return ""; } } }; template <typename T, size_t Tag, class Expr> struct local_terminal_init< temporary<T, Tag, Expr> > { static std::string get(const temporary<T, Tag, Expr> &term, const cl::Device &dev, const std::string &prm_name, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::set<size_t>()) )).first; } auto &pos = boost::any_cast< std::set<size_t>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { pos.insert(Tag); std::ostringstream s; s << "\t\t" << type_name<T>() << " temp_" << Tag << " = "; detail::vector_expr_context expr_ctx(s, dev, 1, prm_name + "_"); boost::proto::eval(boost::proto::as_child(term.expr), expr_ctx); s << ";\n"; return s.str(); } else { return ""; } } }; template <typename T, size_t Tag, class Expr> struct partial_vector_expr< temporary<T, Tag, Expr> > { static std::string get(const temporary<T, Tag, Expr>&, const cl::Device&, const std::string &/*prm_name*/, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::map<size_t, std::string>()) )).first; } auto &pos = boost::any_cast< std::map<size_t, std::string>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { return (pos[Tag] = std::string("temp_") + std::to_string(Tag)); } else { return p->second; } } }; template <typename T, size_t Tag, class Expr> struct kernel_arg_setter< temporary<T, Tag, Expr> > { static void set(const temporary<T, Tag, Expr> &term, cl::Kernel &kernel, unsigned device, size_t index_offset, unsigned &position, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::set<size_t>()) )).first; } auto &pos = boost::any_cast< std::set<size_t>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { pos.insert(Tag); detail::set_expression_argument setarg(kernel, device, position, index_offset); detail::extract_terminals()( boost::proto::as_child(term.expr), setarg); } } }; template <typename T, size_t Tag, class Expr> struct expression_properties< temporary<T, Tag, Expr> > { static void get(const temporary<T, Tag, Expr> &term, std::vector<cl::CommandQueue> &queue_list, std::vector<size_t> &partition, size_t &size ) { detail::get_expression_properties prop; detail::extract_terminals()(boost::proto::as_child(term.expr), prop); queue_list = prop.queue; partition = prop.part; size = prop.size; } }; #ifdef VEXCL_MULTIVECTOR_HPP template <> struct proto_terminal_is_value< mv_temporary_terminal > : std::true_type { }; template <> struct is_multivector_expr_terminal< mv_temporary_terminal > : std::true_type { }; template <size_t Tag, size_t C> struct temporary_component_tag { static const size_t value = 1000 * Tag + C; }; template <size_t I, typename T, size_t Tag, class Expr> struct component< I, mv_temporary<T, Tag, Expr> > { typedef temporary<T, temporary_component_tag<Tag, I>::value, decltype( detail::subexpression<I>::get( *static_cast<Expr*>(0) ) ) > type; }; #endif } // namespace traits #ifdef VEXCL_MULTIVECTOR_HPP template <size_t I, typename T, size_t Tag, class Expr> typename traits::component< I, mv_temporary<T, Tag, Expr> >::type get(const mv_temporary<T, Tag, Expr> &t) { return make_temp<traits::temporary_component_tag<Tag, I>::value, T>( detail::subexpression<I>::get(t.expr) ); } #endif /// \endcond } // namespace vex #endif <commit_msg>Disambiguation for vex::make_temp variants<commit_after>#ifndef VEXCL_TEMPORARY_HPP #define VEXCL_TEMPORARY_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru> 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. */ /** * \file vexcl/temporary.hpp * \author Denis Demidov <ddemidov@ksu.ru> * \brief Container for intermediate results. */ #include <set> #include <vexcl/operations.hpp> namespace vex { /// \cond INTERNAL struct temporary_terminal {}; typedef vector_expression< typename boost::proto::terminal< temporary_terminal >::type > temporary_terminal_expression; template <typename T, size_t Tag, class Expr> struct temporary : public temporary_terminal_expression { typedef T value_type; const Expr expr; temporary(const Expr &expr) : expr(expr) {} }; /// \endcond /// Create temporary to be reused in a vector expression. /** The type of the temporary is explicitly specified. */ template <size_t Tag, typename T, class Expr> typename std::enable_if< boost::proto::matches< typename boost::proto::result_of::as_expr< Expr >::type, vector_expr_grammar >::value, temporary<T, Tag, typename boost::proto::result_of::as_child<Expr, vector_domain>::type > >::type make_temp(const Expr &expr) { return temporary< T, Tag, typename boost::proto::result_of::as_child<Expr, vector_domain>::type >(boost::proto::as_child<vector_domain>(expr)); } /// Create temporary to be reused in a vector expression. /** The type of the temporary is automatically deduced from the supplied * expression. */ template <size_t Tag, class Expr> typename std::enable_if< boost::proto::matches< typename boost::proto::result_of::as_expr< Expr >::type, vector_expr_grammar >::value, temporary< typename detail::return_type<Expr>::type, Tag, typename boost::proto::result_of::as_child<Expr, vector_domain>::type > >::type make_temp(const Expr &expr) { return temporary< typename detail::return_type<Expr>::type, Tag, typename boost::proto::result_of::as_child<Expr, vector_domain>::type >(boost::proto::as_child<vector_domain>(expr)); } #ifdef VEXCL_MULTIVECTOR_HPP /// \cond INTERNAL struct mv_temporary_terminal {}; typedef multivector_expression< typename boost::proto::terminal< mv_temporary_terminal >::type > mv_temporary_terminal_expression; template <typename T, size_t Tag, class Expr> struct mv_temporary : public mv_temporary_terminal_expression { const Expr expr; mv_temporary(const Expr &expr) : expr(expr) {} }; /// \endcond /// Create temporary to be reused in a multivector expression. template <size_t Tag, typename T, class Expr> typename std::enable_if< boost::proto::matches< typename boost::proto::result_of::as_expr< Expr >::type, multivector_expr_grammar >::value, mv_temporary<T, Tag, Expr> >::type make_temp(const Expr &expr) { return mv_temporary<T, Tag, Expr>(expr); } #endif /// \cond INTERNAL namespace traits { template <> struct is_vector_expr_terminal< temporary_terminal > : std::true_type {}; template <> struct proto_terminal_is_value< temporary_terminal > : std::true_type {}; template <typename T, size_t Tag, class Expr> struct terminal_preamble< temporary<T, Tag, Expr> > { static std::string get(const temporary<T, Tag, Expr> &term, const cl::Device &dev, const std::string &prm_name, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::set<size_t>()) )).first; } auto &pos = boost::any_cast< std::set<size_t>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { pos.insert(Tag); std::ostringstream s; detail::output_terminal_preamble termpream(s, dev, 1, prm_name + "_"); boost::proto::eval(boost::proto::as_child(term.expr), termpream); return s.str(); } else { return ""; } } }; template <typename T, size_t Tag, class Expr> struct kernel_param_declaration< temporary<T, Tag, Expr> > { static std::string get(const temporary<T, Tag, Expr> &term, const cl::Device &dev, const std::string &prm_name, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::set<size_t>()) )).first; } auto &pos = boost::any_cast< std::set<size_t>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { pos.insert(Tag); std::ostringstream s; detail::declare_expression_parameter declare(s, dev, 1, prm_name + "_"); detail::extract_terminals()(boost::proto::as_child(term.expr), declare); return s.str(); } else { return ""; } } }; template <typename T, size_t Tag, class Expr> struct local_terminal_init< temporary<T, Tag, Expr> > { static std::string get(const temporary<T, Tag, Expr> &term, const cl::Device &dev, const std::string &prm_name, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::set<size_t>()) )).first; } auto &pos = boost::any_cast< std::set<size_t>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { pos.insert(Tag); std::ostringstream s; s << "\t\t" << type_name<T>() << " temp_" << Tag << " = "; detail::vector_expr_context expr_ctx(s, dev, 1, prm_name + "_"); boost::proto::eval(boost::proto::as_child(term.expr), expr_ctx); s << ";\n"; return s.str(); } else { return ""; } } }; template <typename T, size_t Tag, class Expr> struct partial_vector_expr< temporary<T, Tag, Expr> > { static std::string get(const temporary<T, Tag, Expr>&, const cl::Device&, const std::string &/*prm_name*/, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::map<size_t, std::string>()) )).first; } auto &pos = boost::any_cast< std::map<size_t, std::string>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { return (pos[Tag] = std::string("temp_") + std::to_string(Tag)); } else { return p->second; } } }; template <typename T, size_t Tag, class Expr> struct kernel_arg_setter< temporary<T, Tag, Expr> > { static void set(const temporary<T, Tag, Expr> &term, cl::Kernel &kernel, unsigned device, size_t index_offset, unsigned &position, detail::kernel_generator_state &state) { auto s = state.find("temporary"); if (s == state.end()) { s = state.insert(std::make_pair( std::string("temporary"), boost::any(std::set<size_t>()) )).first; } auto &pos = boost::any_cast< std::set<size_t>& >(s->second); auto p = pos.find(Tag); if (p == pos.end()) { pos.insert(Tag); detail::set_expression_argument setarg(kernel, device, position, index_offset); detail::extract_terminals()( boost::proto::as_child(term.expr), setarg); } } }; template <typename T, size_t Tag, class Expr> struct expression_properties< temporary<T, Tag, Expr> > { static void get(const temporary<T, Tag, Expr> &term, std::vector<cl::CommandQueue> &queue_list, std::vector<size_t> &partition, size_t &size ) { detail::get_expression_properties prop; detail::extract_terminals()(boost::proto::as_child(term.expr), prop); queue_list = prop.queue; partition = prop.part; size = prop.size; } }; #ifdef VEXCL_MULTIVECTOR_HPP template <> struct proto_terminal_is_value< mv_temporary_terminal > : std::true_type { }; template <> struct is_multivector_expr_terminal< mv_temporary_terminal > : std::true_type { }; template <size_t Tag, size_t C> struct temporary_component_tag { static const size_t value = 1000 * Tag + C; }; template <size_t I, typename T, size_t Tag, class Expr> struct component< I, mv_temporary<T, Tag, Expr> > { typedef temporary<T, temporary_component_tag<Tag, I>::value, decltype( detail::subexpression<I>::get( *static_cast<Expr*>(0) ) ) > type; }; #endif } // namespace traits #ifdef VEXCL_MULTIVECTOR_HPP template <size_t I, typename T, size_t Tag, class Expr> typename traits::component< I, mv_temporary<T, Tag, Expr> >::type get(const mv_temporary<T, Tag, Expr> &t) { return make_temp<traits::temporary_component_tag<Tag, I>::value, T>( detail::subexpression<I>::get(t.expr) ); } #endif /// \endcond } // namespace vex #endif <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <gecode/minimodel.hh> namespace gameai { namespace gecode { class lab4 : public Gecode::Space { private: const int count = 2; Gecode::IntVarArray xy; public: lab4() : xy(*this, count, -5, 4) { Gecode::IntVar x(xy[0]), y(xy[1]); Gecode::rel(*this, x + 2 * y == 0); Gecode::branch(*this, xy, Gecode::INT_VAR_SIZE_MIN(), Gecode::INT_VAL_MIN()); } lab4(const bool share, lab4 &s) : Gecode::Space(share, s) { xy.update(*this, share, s.xy); } Gecode::Space * copy (const bool share) { return new lab4(share, *this); } std::ostream & print(std::ostream &os) { return os << "lab4 { xy = " << xy << " }" << std::endl; } }; } } <commit_msg>lab4: do a circle<commit_after>#pragma once #include <iostream> #include <gecode/minimodel.hh> namespace gameai { namespace gecode { class lab4 : public Gecode::Space { private: const int count = 2; Gecode::IntVarArray xy; public: lab4() : xy(*this, count, -30, 30) { Gecode::IntVar x(xy[0]), y(xy[1]); Gecode::rel(*this, x * x + y * y == 5 * 5); Gecode::branch(*this, xy, Gecode::INT_VAR_SIZE_MIN(), Gecode::INT_VAL_MIN()); } lab4(const bool share, lab4 &s) : Gecode::Space(share, s) { xy.update(*this, share, s.xy); } Gecode::Space * copy (const bool share) { return new lab4(share, *this); } std::ostream & print(std::ostream &os) { return os << "lab4 { xy = " << xy << " }" << std::endl; } }; } } <|endoftext|>
<commit_before>/** * @file distribution_test.cpp * @author Ryan Curtin * * Test for the mlpack::distribution::DiscreteDistribution class. */ #include <mlpack/core.h> #include <mlpack/methods/hmm/distributions/discrete_distribution.hpp> #include <boost/test/unit_test.hpp> using namespace mlpack; using namespace mlpack::distribution; BOOST_AUTO_TEST_SUITE(DistributionTest) /** * Make sure we initialize correctly. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionConstructorTest) { DiscreteDistribution d(5); BOOST_REQUIRE_EQUAL(d.Probabilities().n_elem, 5); BOOST_REQUIRE_CLOSE(d.Probability(0), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(1), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(2), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(3), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(4), 0.2, 1e-5); } /** * Make sure we get the probabilities of observations right. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionProbabilityTest) { DiscreteDistribution d(5); d.Probabilities("0.2 0.4 0.1 0.1 0.2"); BOOST_REQUIRE_CLOSE(d.Probability(0), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(1), 0.4, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(2), 0.1, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(3), 0.1, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(4), 0.2, 1e-5); } /** * Make sure we get random observations correct. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionRandomTest) { DiscreteDistribution d(3); d.Probabilities("0.3 0.6 0.1"); arma::vec actualProb(3); for (size_t i = 0; i < 10000; i++) actualProb(d.Random())++; // Normalize. actualProb /= accu(actualProb); // 5% tolerance, because this can be a noisy process. BOOST_REQUIRE_CLOSE(actualProb(0), 0.3, 5.0); BOOST_REQUIRE_CLOSE(actualProb(1), 0.6, 5.0); BOOST_REQUIRE_CLOSE(actualProb(2), 0.1, 5.0); } /** * Make sure we can estimate from observations correctly. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionEstimateTest) { DiscreteDistribution d(4); std::vector<size_t> obs; obs.push_back(0); obs.push_back(0); obs.push_back(1); obs.push_back(1); obs.push_back(2); obs.push_back(2); obs.push_back(2); obs.push_back(3); d.Estimate(obs); BOOST_REQUIRE_CLOSE(d.Probability(0), 0.25, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(1), 0.25, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(2), 0.375, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(3), 0.125, 1e-5); } /** * Estimate from observations with probabilities. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionEstimateProbTest) { DiscreteDistribution d(3); std::vector<size_t> obs; obs.push_back(0); obs.push_back(0); obs.push_back(1); obs.push_back(2); std::vector<double> prob; prob.push_back(0.25); prob.push_back(0.25); prob.push_back(0.5); prob.push_back(1.0); d.Estimate(obs, prob); BOOST_REQUIRE_CLOSE(d.Probability(0), 0.25, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(1), 0.25, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(2), 0.5, 1e-5); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>I am really frustrated by tests that don't always have a deterministic outcome.<commit_after>/** * @file distribution_test.cpp * @author Ryan Curtin * * Test for the mlpack::distribution::DiscreteDistribution class. */ #include <mlpack/core.h> #include <mlpack/methods/hmm/distributions/discrete_distribution.hpp> #include <boost/test/unit_test.hpp> using namespace mlpack; using namespace mlpack::distribution; BOOST_AUTO_TEST_SUITE(DistributionTest) /** * Make sure we initialize correctly. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionConstructorTest) { DiscreteDistribution d(5); BOOST_REQUIRE_EQUAL(d.Probabilities().n_elem, 5); BOOST_REQUIRE_CLOSE(d.Probability(0), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(1), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(2), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(3), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(4), 0.2, 1e-5); } /** * Make sure we get the probabilities of observations right. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionProbabilityTest) { DiscreteDistribution d(5); d.Probabilities("0.2 0.4 0.1 0.1 0.2"); BOOST_REQUIRE_CLOSE(d.Probability(0), 0.2, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(1), 0.4, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(2), 0.1, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(3), 0.1, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(4), 0.2, 1e-5); } /** * Make sure we get random observations correct. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionRandomTest) { DiscreteDistribution d(3); d.Probabilities("0.3 0.6 0.1"); arma::vec actualProb(3); for (size_t i = 0; i < 10000; i++) actualProb(d.Random())++; // Normalize. actualProb /= accu(actualProb); // 8% tolerance, because this can be a noisy process. BOOST_REQUIRE_CLOSE(actualProb(0), 0.3, 8.0); BOOST_REQUIRE_CLOSE(actualProb(1), 0.6, 8.0); BOOST_REQUIRE_CLOSE(actualProb(2), 0.1, 8.0); } /** * Make sure we can estimate from observations correctly. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionEstimateTest) { DiscreteDistribution d(4); std::vector<size_t> obs; obs.push_back(0); obs.push_back(0); obs.push_back(1); obs.push_back(1); obs.push_back(2); obs.push_back(2); obs.push_back(2); obs.push_back(3); d.Estimate(obs); BOOST_REQUIRE_CLOSE(d.Probability(0), 0.25, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(1), 0.25, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(2), 0.375, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(3), 0.125, 1e-5); } /** * Estimate from observations with probabilities. */ BOOST_AUTO_TEST_CASE(DiscreteDistributionEstimateProbTest) { DiscreteDistribution d(3); std::vector<size_t> obs; obs.push_back(0); obs.push_back(0); obs.push_back(1); obs.push_back(2); std::vector<double> prob; prob.push_back(0.25); prob.push_back(0.25); prob.push_back(0.5); prob.push_back(1.0); d.Estimate(obs, prob); BOOST_REQUIRE_CLOSE(d.Probability(0), 0.25, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(1), 0.25, 1e-5); BOOST_REQUIRE_CLOSE(d.Probability(2), 0.5, 1e-5); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>#include "GameData.h" #include <string> #include <sstream> #include <algorithm> #include <map> #include <zlib/zlib.h> #include "bparse.h" #include "DatCat.h" #include "File.h" namespace { // Relation between category number and category name // These names are taken straight from the exe, it helps resolve dispatching when getting files by path std::unordered_map< std::string, uint32_t > categoryNameToIdMap = {{"common", 0x00}, {"bgcommon", 0x01}, {"bg", 0x02}, {"cut", 0x03}, {"chara", 0x04}, {"shader", 0x05}, {"ui", 0x06}, {"sound", 0x07}, {"vfx", 0x08}, {"ui_script", 0x09}, {"exd", 0x0A}, {"game_script", 0x0B}, {"music", 0x0C} }; std::unordered_map< uint32_t, std::string > categoryIdToNameMap = {{0x00, "common"}, {0x01, "bgcommon"}, {0x02, "bg"}, {0x03, "cut"}, {0x04, "chara"}, {0x05, "shader"}, {0x06, "ui"}, {0x07, "sound"}, {0x08, "vfx"}, {0x09, "ui_script"}, {0x0A, "exd"}, {0x0B, "game_script"}, {0x0C, "music"}}; } namespace xiv { namespace dat { GameData::GameData(const std::experimental::filesystem::path& path) try : m_path(path) { int maxExLevel = 0; auto sep = std::experimental::filesystem::path::preferred_separator; // Determine which expansions are available while( std::experimental::filesystem::exists( std::experimental::filesystem::path( m_path.string() + sep + "ex" + std::to_string( maxExLevel + 1 ) + sep + "ex" + std::to_string( maxExLevel + 1 ) + ".ver" ) ) ) { maxExLevel++; } // Iterate over the files in path for( auto it = std::experimental::filesystem::directory_iterator( m_path.string() + "//ffxiv" ); it != std::experimental::filesystem::directory_iterator(); ++it ) { // Get the filename of the current element auto filename = it->path().filename().string(); // If it contains ".win32.index" this is most likely a hit for a category if( filename.find( ".win32.index" ) != std::string::npos && filename.find( ".win32.index2" ) == std::string::npos ) { // Format of indexes is XX0000.win32.index, so fetch the hex number for category number std::istringstream iss( filename.substr( 0, 2 ) ); uint32_t cat_nb; iss >> std::hex >> cat_nb; // Add to the list of category number // creates the empty category in the cats map // instantiate the creation mutex for this category m_catNums.push_back( cat_nb ); m_cats[cat_nb] = std::unique_ptr<Cat>(); m_catCreationMutexes[cat_nb] = std::unique_ptr<std::mutex>( new std::mutex() ); // Check for expansion for( int exNum = 1; exNum <= maxExLevel; exNum++ ) { const std::string path = m_path.string() + sep + buildDatStr( "ex" + std::to_string( exNum ), cat_nb, exNum, 0, "win32", "index" ); if( std::experimental::filesystem::exists( std::experimental::filesystem::path( path ) ) ) { int chunkCount = 0; for(int chunkTest = 0; chunkTest < 256; chunkTest++ ) { if( std::experimental::filesystem::exists( m_path.string() + sep + buildDatStr( "ex" + std::to_string( exNum ), cat_nb, exNum, chunkTest, "win32", "index" ) ) ) { m_exCats[cat_nb].exNumToChunkMap[exNum].chunkToCatMap[chunkTest] = std::unique_ptr<Cat>(); chunkCount++; } } } } } } } catch( std::exception& e ) { // In case of failure here, client is supposed to catch the exception because it is not recoverable on our side throw std::runtime_error( "GameData initialization failed: " + std::string( e.what() ) ); } GameData::~GameData() { } const std::string GameData::buildDatStr( const std::string folder, const int cat, const int exNum, const int chunk, const std::string platform, const std::string type ) { char dat[1024]; sprintf( dat, "%s/%02x%02x%02x.%s.%s", folder.c_str(), cat, exNum, chunk, platform.c_str(), type.c_str() ); return std::string( dat ); } const std::vector<uint32_t>& GameData::getCatNumbers() const { return m_catNums; } std::unique_ptr<File> GameData::getFile(const std::string& path) { // Get the hashes, the category from the path then call the getFile of the category uint32_t dirHash; uint32_t filenameHash; getHashes( path, dirHash, filenameHash ); return getCategoryFromPath( path ).getFile( dirHash, filenameHash ); } bool GameData::doesFileExist(const std::string& path) { uint32_t dirHash; uint32_t filenameHash; getHashes( path, dirHash, filenameHash ); return getCategoryFromPath( path ).doesFileExist( dirHash, filenameHash ); } bool GameData::doesDirExist(const std::string& i_path) { uint32_t dirHash; uint32_t filenameHash; getHashes( i_path, dirHash, filenameHash ); return getCategoryFromPath( i_path ).doesDirExist( dirHash ); } const Cat& GameData::getCategory(uint32_t catNum) { // Check that the category number exists auto catIt = m_cats.find( catNum ); if( catIt == m_cats.end() ) { throw std::runtime_error( "Category not found: " + std::to_string( catNum ) ); } // If it exists and already instantiated return it if( catIt->second ) { return *( catIt->second ); } else { // Else create it and return it createCategory( catNum ); return *( m_cats[catNum] ); } } const Cat& GameData::getCategory(const std::string& catName) { // Find the category number from the name auto categoryNameToIdMapIt = ::categoryNameToIdMap.find( catName ); if( categoryNameToIdMapIt == ::categoryNameToIdMap.end() ) { throw std::runtime_error( "Category not found: " + catName ); } // From the category number return the category return getCategory( categoryNameToIdMapIt->second ); } const Cat& GameData::getExCategory( const std::string& catName, uint32_t exNum, const std::string& path ) { // Find the category number from the name auto categoryMapIt = ::categoryNameToIdMap.find( catName ); if( categoryMapIt == ::categoryNameToIdMap.end() ) { throw std::runtime_error( "Category not found: " + catName ); } uint32_t dirHash; uint32_t filenameHash; getHashes( path, dirHash, filenameHash ); for( auto const& chunk : m_exCats[categoryMapIt->second].exNumToChunkMap[exNum].chunkToCatMap ) { if( !chunk.second ) createExCategory( categoryMapIt->second ); if( chunk.second->doesFileExist( dirHash, filenameHash ) ) { return *( chunk.second ); } } throw std::runtime_error( "Chunk not found for path: " + path ); } const Cat& GameData::getCategoryFromPath(const std::string& path) { // Find the first / in the string, paths are in the format CAT_NAME/..../.../../.... auto firstSlashPos = path.find( '/' ); if( firstSlashPos == std::string::npos ) { throw std::runtime_error( "Path does not have a / char: " + path ); } if( path.substr( firstSlashPos + 1, 2) == "ex" ) { return getExCategory( path.substr( 0, firstSlashPos ), std::stoi( path.substr( firstSlashPos + 3, 1 ) ), path ); } else { // From the sub string found beforethe first / get the category return getCategory( path.substr( 0, firstSlashPos ) ); } } void GameData::getHashes(const std::string& path, uint32_t& dirHash, uint32_t& filenameHash) const { // Convert the path to lowercase before getting the hashes std::string pathLower; pathLower.resize( path.size() ); std::transform( path.begin(), path.end(), pathLower.begin(), ::tolower ); // Find last / to separate dir from filename auto lastSlashPos = pathLower.rfind( '/' ); if( lastSlashPos == std::string::npos ) { throw std::runtime_error( "Path does not have a / char: " + path ); } std::string dirPart = pathLower.substr( 0, lastSlashPos ); std::string filenamePart = pathLower.substr( lastSlashPos + 1 ); // Get the crc32 values from zlib, to compensate the final XOR 0xFFFFFFFF that isnot done in the exe we just reXOR dirHash = crc32( 0, reinterpret_cast<const uint8_t*>( dirPart.data() ), dirPart.size() ) ^ 0xFFFFFFFF; filenameHash = crc32( 0, reinterpret_cast<const uint8_t*>( filenamePart.data() ), filenamePart.size() ) ^ 0xFFFFFFFF; } void GameData::createCategory(uint32_t catNum) { // Lock mutex in this scope std::lock_guard<std::mutex> lock( *( m_catCreationMutexes[catNum] ) ); // Maybe after unlocking it has already been created, so check (most likely if it blocked) if( !m_cats[catNum] ) { // Get the category name if we have it std::string catName; auto categoryMapIt = ::categoryIdToNameMap.find( catNum ); if( categoryMapIt != ::categoryIdToNameMap.end() ) { catName = categoryMapIt->second; } // Actually creates the category m_cats[catNum] = std::unique_ptr<Cat>( new Cat( m_path, catNum, catName ) ); } } void GameData::createExCategory( uint32_t catNum ) { // Maybe after unlocking it has already been created, so check (most likely if it blocked) if( !m_exCats[catNum].exNumToChunkMap[1].chunkToCatMap[0] ) { // Get the category name if we have it std::string catName; auto categoryMapIt = ::categoryIdToNameMap.find( catNum ); if( categoryMapIt != ::categoryIdToNameMap.end() ) { catName = categoryMapIt->second; } for( auto const& ex : m_exCats[catNum].exNumToChunkMap ) { for( auto const& chunk : m_exCats[catNum].exNumToChunkMap[ex.first].chunkToCatMap ) { // Actually creates the category m_exCats[catNum].exNumToChunkMap[ex.first].chunkToCatMap[chunk.first] = std::unique_ptr<Cat>( new Cat( m_path, catNum, catName, ex.first, chunk.first ) ); } } } } } } <commit_msg>fix fs::path::preferred_separator not working with string concat on msvc<commit_after>#include "GameData.h" #include <string> #include <sstream> #include <algorithm> #include <map> #include <zlib/zlib.h> #include "bparse.h" #include "DatCat.h" #include "File.h" namespace { // Relation between category number and category name // These names are taken straight from the exe, it helps resolve dispatching when getting files by path std::unordered_map< std::string, uint32_t > categoryNameToIdMap = {{"common", 0x00}, {"bgcommon", 0x01}, {"bg", 0x02}, {"cut", 0x03}, {"chara", 0x04}, {"shader", 0x05}, {"ui", 0x06}, {"sound", 0x07}, {"vfx", 0x08}, {"ui_script", 0x09}, {"exd", 0x0A}, {"game_script", 0x0B}, {"music", 0x0C} }; std::unordered_map< uint32_t, std::string > categoryIdToNameMap = {{0x00, "common"}, {0x01, "bgcommon"}, {0x02, "bg"}, {0x03, "cut"}, {0x04, "chara"}, {0x05, "shader"}, {0x06, "ui"}, {0x07, "sound"}, {0x08, "vfx"}, {0x09, "ui_script"}, {0x0A, "exd"}, {0x0B, "game_script"}, {0x0C, "music"}}; } namespace xiv { namespace dat { GameData::GameData(const std::experimental::filesystem::path& path) try : m_path(path) { int maxExLevel = 0; // msvc has retarded stdlib implementation #ifdef _WIN32 static constexpr auto sep = "\\"; #else static constexpr auto sep = std::experimental::filesystem::path::preferred_separator; #endif // Determine which expansions are available while( std::experimental::filesystem::exists( std::experimental::filesystem::path( m_path.string() + sep + "ex" + std::to_string( maxExLevel + 1 ) + sep + "ex" + std::to_string( maxExLevel + 1 ) + ".ver" ) ) ) { maxExLevel++; } // Iterate over the files in path for( auto it = std::experimental::filesystem::directory_iterator( m_path.string() + "//ffxiv" ); it != std::experimental::filesystem::directory_iterator(); ++it ) { // Get the filename of the current element auto filename = it->path().filename().string(); // If it contains ".win32.index" this is most likely a hit for a category if( filename.find( ".win32.index" ) != std::string::npos && filename.find( ".win32.index2" ) == std::string::npos ) { // Format of indexes is XX0000.win32.index, so fetch the hex number for category number std::istringstream iss( filename.substr( 0, 2 ) ); uint32_t cat_nb; iss >> std::hex >> cat_nb; // Add to the list of category number // creates the empty category in the cats map // instantiate the creation mutex for this category m_catNums.push_back( cat_nb ); m_cats[cat_nb] = std::unique_ptr<Cat>(); m_catCreationMutexes[cat_nb] = std::unique_ptr<std::mutex>( new std::mutex() ); // Check for expansion for( int exNum = 1; exNum <= maxExLevel; exNum++ ) { const std::string path = m_path.string() + sep + buildDatStr( "ex" + std::to_string( exNum ), cat_nb, exNum, 0, "win32", "index" ); if( std::experimental::filesystem::exists( std::experimental::filesystem::path( path ) ) ) { int chunkCount = 0; for(int chunkTest = 0; chunkTest < 256; chunkTest++ ) { if( std::experimental::filesystem::exists( m_path.string() + sep + buildDatStr( "ex" + std::to_string( exNum ), cat_nb, exNum, chunkTest, "win32", "index" ) ) ) { m_exCats[cat_nb].exNumToChunkMap[exNum].chunkToCatMap[chunkTest] = std::unique_ptr<Cat>(); chunkCount++; } } } } } } } catch( std::exception& e ) { // In case of failure here, client is supposed to catch the exception because it is not recoverable on our side throw std::runtime_error( "GameData initialization failed: " + std::string( e.what() ) ); } GameData::~GameData() { } const std::string GameData::buildDatStr( const std::string folder, const int cat, const int exNum, const int chunk, const std::string platform, const std::string type ) { char dat[1024]; sprintf( dat, "%s/%02x%02x%02x.%s.%s", folder.c_str(), cat, exNum, chunk, platform.c_str(), type.c_str() ); return std::string( dat ); } const std::vector<uint32_t>& GameData::getCatNumbers() const { return m_catNums; } std::unique_ptr<File> GameData::getFile(const std::string& path) { // Get the hashes, the category from the path then call the getFile of the category uint32_t dirHash; uint32_t filenameHash; getHashes( path, dirHash, filenameHash ); return getCategoryFromPath( path ).getFile( dirHash, filenameHash ); } bool GameData::doesFileExist(const std::string& path) { uint32_t dirHash; uint32_t filenameHash; getHashes( path, dirHash, filenameHash ); return getCategoryFromPath( path ).doesFileExist( dirHash, filenameHash ); } bool GameData::doesDirExist(const std::string& i_path) { uint32_t dirHash; uint32_t filenameHash; getHashes( i_path, dirHash, filenameHash ); return getCategoryFromPath( i_path ).doesDirExist( dirHash ); } const Cat& GameData::getCategory(uint32_t catNum) { // Check that the category number exists auto catIt = m_cats.find( catNum ); if( catIt == m_cats.end() ) { throw std::runtime_error( "Category not found: " + std::to_string( catNum ) ); } // If it exists and already instantiated return it if( catIt->second ) { return *( catIt->second ); } else { // Else create it and return it createCategory( catNum ); return *( m_cats[catNum] ); } } const Cat& GameData::getCategory(const std::string& catName) { // Find the category number from the name auto categoryNameToIdMapIt = ::categoryNameToIdMap.find( catName ); if( categoryNameToIdMapIt == ::categoryNameToIdMap.end() ) { throw std::runtime_error( "Category not found: " + catName ); } // From the category number return the category return getCategory( categoryNameToIdMapIt->second ); } const Cat& GameData::getExCategory( const std::string& catName, uint32_t exNum, const std::string& path ) { // Find the category number from the name auto categoryMapIt = ::categoryNameToIdMap.find( catName ); if( categoryMapIt == ::categoryNameToIdMap.end() ) { throw std::runtime_error( "Category not found: " + catName ); } uint32_t dirHash; uint32_t filenameHash; getHashes( path, dirHash, filenameHash ); for( auto const& chunk : m_exCats[categoryMapIt->second].exNumToChunkMap[exNum].chunkToCatMap ) { if( !chunk.second ) createExCategory( categoryMapIt->second ); if( chunk.second->doesFileExist( dirHash, filenameHash ) ) { return *( chunk.second ); } } throw std::runtime_error( "Chunk not found for path: " + path ); } const Cat& GameData::getCategoryFromPath(const std::string& path) { // Find the first / in the string, paths are in the format CAT_NAME/..../.../../.... auto firstSlashPos = path.find( '/' ); if( firstSlashPos == std::string::npos ) { throw std::runtime_error( "Path does not have a / char: " + path ); } if( path.substr( firstSlashPos + 1, 2) == "ex" ) { return getExCategory( path.substr( 0, firstSlashPos ), std::stoi( path.substr( firstSlashPos + 3, 1 ) ), path ); } else { // From the sub string found beforethe first / get the category return getCategory( path.substr( 0, firstSlashPos ) ); } } void GameData::getHashes(const std::string& path, uint32_t& dirHash, uint32_t& filenameHash) const { // Convert the path to lowercase before getting the hashes std::string pathLower; pathLower.resize( path.size() ); std::transform( path.begin(), path.end(), pathLower.begin(), ::tolower ); // Find last / to separate dir from filename auto lastSlashPos = pathLower.rfind( '/' ); if( lastSlashPos == std::string::npos ) { throw std::runtime_error( "Path does not have a / char: " + path ); } std::string dirPart = pathLower.substr( 0, lastSlashPos ); std::string filenamePart = pathLower.substr( lastSlashPos + 1 ); // Get the crc32 values from zlib, to compensate the final XOR 0xFFFFFFFF that isnot done in the exe we just reXOR dirHash = crc32( 0, reinterpret_cast<const uint8_t*>( dirPart.data() ), dirPart.size() ) ^ 0xFFFFFFFF; filenameHash = crc32( 0, reinterpret_cast<const uint8_t*>( filenamePart.data() ), filenamePart.size() ) ^ 0xFFFFFFFF; } void GameData::createCategory(uint32_t catNum) { // Lock mutex in this scope std::lock_guard<std::mutex> lock( *( m_catCreationMutexes[catNum] ) ); // Maybe after unlocking it has already been created, so check (most likely if it blocked) if( !m_cats[catNum] ) { // Get the category name if we have it std::string catName; auto categoryMapIt = ::categoryIdToNameMap.find( catNum ); if( categoryMapIt != ::categoryIdToNameMap.end() ) { catName = categoryMapIt->second; } // Actually creates the category m_cats[catNum] = std::unique_ptr<Cat>( new Cat( m_path, catNum, catName ) ); } } void GameData::createExCategory( uint32_t catNum ) { // Maybe after unlocking it has already been created, so check (most likely if it blocked) if( !m_exCats[catNum].exNumToChunkMap[1].chunkToCatMap[0] ) { // Get the category name if we have it std::string catName; auto categoryMapIt = ::categoryIdToNameMap.find( catNum ); if( categoryMapIt != ::categoryIdToNameMap.end() ) { catName = categoryMapIt->second; } for( auto const& ex : m_exCats[catNum].exNumToChunkMap ) { for( auto const& chunk : m_exCats[catNum].exNumToChunkMap[ex.first].chunkToCatMap ) { // Actually creates the category m_exCats[catNum].exNumToChunkMap[ex.first].chunkToCatMap[chunk.first] = std::unique_ptr<Cat>( new Cat( m_path, catNum, catName, ex.first, chunk.first ) ); } } } } } } <|endoftext|>
<commit_before><commit_msg>Update FONLL5andMCatSHQoverLHC20g2b high-pt weights<commit_after><|endoftext|>
<commit_before>#ifndef MENU_HPP #define MENU_HPP #include <QMainWindow> #include <QApplication> class Menu : public QMainWindow { public: Menu(QWidget *parent = 0); }; #endif <commit_msg>Delete menu.hpp<commit_after><|endoftext|>
<commit_before>#pragma once #include "common.hpp" namespace cp { class CP_EXPORT gnuplot { FILE* fp; public: gnuplot(std::string gnuplotpath); void cmd(std::string name); ~gnuplot(); }; class CP_EXPORT Plot { protected: std::string font = "Times New Roman";//"Consolas" int fontSize = 20; int fontSize2 = 18; int foregroundIndex = 0; struct PlotInfo { std::vector<cv::Point2d> data; cv::Scalar color; int symbolType; int lineType; int lineWidth; std::string title; }; std::vector<PlotInfo> pinfo; std::string xlabel = "x"; std::string ylabel = "y"; int data_max = 1; cv::Scalar background_color = COLOR_WHITE; int gridLevel = 0; bool isDrawMousePosition = true; cv::Size plotsize; cv::Point origin; bool isSetXRange = false; bool isSetYRange = false; double xmin_plotwindow;//x max of plot window double xmax_plotwindow;//x min of plot window double ymin_plotwindow;//y max of plot window double ymax_plotwindow;//y min of plot window double xmax_data;//x max of data double xmin_data;//x min of data double ymax_data;//y max of data double ymin_data;//y min of data int keyPosition = RIGHT_TOP; bool isZeroCross; bool isXYMAXMIN; bool isXYCenter; bool isLogScaleX = false; bool isLogScaleY = false; cv::Mat plotImage; cv::Mat keyImage; void init(cv::Size imsize); void point2val(cv::Point pt, double* valx, double* valy); cv::Scalar getPseudoColor(uchar val); void plotGrid(int level); void renderingOutsideInformation(bool isFont); void computeDataMaxMin(); void computeWindowXRangeMAXMIN(bool isCenter = false, double margin_rate = 0.9, int rounding_value = 0); void computeWindowYRangeMAXMIN(bool isCenter = false, double margin_rate = 0.9, int rounding_value = 0); public: void recomputeXYRangeMAXMIN(bool isCenter = false, double margin_rate = 0.9, int rounding_balue = 0); //symbolType enum SYMBOL { NOPOINT = 0, PLUS, TIMES, ASTERISK, CIRCLE, RECTANGLE, CIRCLE_FILL, RECTANGLE_FILL, TRIANGLE, TRIANGLE_FILL, TRIANGLE_INV, TRIANGLE_INV_FILL, DIAMOND, DIAMOND_FILL, PENTAGON, PENTAGON_FILL, }; enum LINE { NOLINE, LINEAR, H2V, V2H, LINE_METHOD_SIZE }; enum KEY { NOKEY, RIGHT_TOP, LEFT_TOP, LEFT_BOTTOM, RIGHT_BOTTOM, FLOATING, KEY_METHOD_SIZE }; cv::Mat render; cv::Mat graphImage; Plot(cv::Size window_size);//cv::Size(1024, 768) Plot(); ~Plot(); void setXYOriginZERO(); void setXOriginZERO(); void setYOriginZERO(); void setPlotProfile(bool isXYCenter_, bool isXYMAXMIN_, bool isZeroCross_); void setImageSize(cv::Size s); void setXYRange(double xmin, double xmax, double ymin, double ymax); void setXRange(double xmin, double xmax); void setYRange(double ymin, double ymax); void setLogScaleX(const bool flag); void setLogScaleY(const bool flag); //NOKEY, //RIGHT_TOP, //LEFT_TOP, //LEFT_BOTTOM, //RIGHT_BOTTOM, //FLOATING, void setKey(int key_method); void setXLabel(std::string xlabel); void setYLabel(std::string ylabel); void setGrid(int level = 0);//0: no grid, 1: div 4, 2: div 16 void setBackGoundColor(cv::Scalar cl); void setPlot(int plotnum, cv::Scalar color = COLOR_RED, int symbol_type = PLUS, int line_type = LINEAR, int line_width = 1); void setPlotLineWidth(int plotnum, int line_width); void setPlotLineWidthALL(int line_width); void setPlotColor(int plotnum, cv::Scalar color); //NOPOINT = 0, //PLUS, //TIMES, //ASTERISK, //CIRCLE, //RECTANGLE, //CIRCLE_FILL, //RECTANGLE_FILL, //TRIANGLE, //TRIANGLE_FILL, //TRIANGLE_INV, //TRIANGLE_INV_FILL, //DIAMOND, //DIAMOND_FILL, //PENTAGON, //PENTAGON_FILL, void setPlotSymbol(int plotnum, int symbol_type); void setPlotSymbolALL(int symbol_type); //Plot::LINE::NONE, //Plot::LINE::LINEAR, //Plot::LINE::H2V, //Plot::LINE::V2H void setPlotLineType(int plotnum, int line_type); void setPlotLineTypeALL(int line_type); void setPlotTitle(int plotnum, std::string name); void setPlotForeground(int plotnum); void setIsDrawMousePosition(const bool flag); void plotPoint(cv::Point2d = cv::Point2d(0.0, 0.0), cv::Scalar color = COLOR_BLACK, int thickness_ = 1, int linetype = LINEAR); void plotData(int gridlevel = 0); void plotMat(cv::InputArray src, std::string name = "Plot", bool isWait = true, std::string gnuplotpath = "pgnuplot.exe"); void plot(std::string name = "Plot", bool isWait = true, std::string gnuplotpath = "pgnuplot.exe", std::string message = ""); void generateKeyImage(int num); void save(std::string name); void push_back(std::vector<cv::Point> point, int plotIndex = 0); void push_back(std::vector<cv::Point2d> point, int plotIndex = 0); void push_back(double x, double y, int plotIndex = 0); void erase(int sampleIndex, int plotIndex = 0); void insert(cv::Point2d v, int sampleIndex, int plotIndex = 0); void insert(cv::Point v, int sampleIndex, int plotIndex = 0); void insert(double x, double y, int sampleIndex, int plotIndex = 0); void clear(int datanum = -1); void swapPlot(int plotIndex1, int plotIndex2); }; enum { PLOT_ARG_MAX = 1, PLOT_ARG_MIN = -1 }; class CP_EXPORT Plot2D { cv::Scalar background_color = cv::Scalar(255, 255, 255, 0); std::string font = "Times New Roman";//"Consolas" int fontSize = 20; int fontSize2 = 18; std::vector<std::vector<double>> data; cv::Mat labelxImage; cv::Mat labelyImage; cv::Mat gridData; int w; int h; void createPlot(); void setMinMaxX(double minv, double maxv, double interval); void setMinMaxY(double minv, double maxv, double interval); void addLabelToGraph(); public: std::string labelx=""; std::string labely=""; cv::Mat show; cv::Mat graph; cv::Size plotImageSize; double x_min; double x_max; double x_interval; int x_size; double y_min; double y_max; double y_interval; int y_size; Plot2D(cv::Size graph_size, double xmin, double xmax, double xstep, double ymin, double ymax, double ystep); void setFont(std::string font); void setFontSize(const int size); void setFontSize2(const int size); void setMinMax(double xmin, double xmax, double xstep, double ymin, double ymax, double ystep); void add(int x, int y, double val); void writeGraph(bool isColor, int arg_min_max, double minvalue = 0, double maxvalue = 0, bool isMinMaxSet = false); void setLabel(std::string namex, std::string namey); //void plot(CSV& result); void plot(std::string wname = "plot2D"); }; CP_EXPORT void plotGraph(cv::OutputArray graphImage, std::vector<cv::Point2d>& data, double xmin, double xmax, double ymin, double ymax, cv::Scalar color = COLOR_RED, int lt = Plot::PLUS, int isLine = Plot::LINEAR, int thickness = 1, int ps = 4, bool isLogX = false, bool isLogY = false); class CP_EXPORT RGBHistogram { private: cv::Size size = cv::Size(512, 512); cv::Mat k = cv::Mat::eye(3, 3, CV_64F); cv::Mat R = cv::Mat::eye(3, 3, CV_64F); cv::Mat t = cv::Mat::zeros(3, 1, CV_64F); void projectPointsParallel(const cv::Mat& xyz, const cv::Mat& R, const cv::Mat& t, const cv::Mat& K, std::vector<cv::Point2f>& dest, const bool isRotationThenTranspose); void projectPoints(const cv::Mat& xyz, const cv::Mat& R, const cv::Mat& t, const cv::Mat& K, std::vector<cv::Point2f>& dest, const bool isRotationThenTranspose); void projectPoint(cv::Point3d& xyz, const cv::Mat& R, const cv::Mat& t, const cv::Mat& K, cv::Point2d& dest); void convertRGBto3D(cv::Mat& src, cv::Mat& rgb); cv::Mat additionalPoints; cv::Mat additionalPointsDest; cv::Mat center; public: RGBHistogram(); void setCenter(cv::Mat& src); void push_back(cv::Mat& src); void push_back(cv::Vec3f src); void push_back(const float b, const float g, const float r); void clear(); void plot(cv::Mat& src, bool isWait = true, std::string wname = "RGB histogram"); }; } <commit_msg>Update plot.hpp<commit_after>#pragma once #include "common.hpp" namespace cp { class CP_EXPORT gnuplot { FILE* fp; public: gnuplot(std::string gnuplotpath); void cmd(std::string name); ~gnuplot(); }; class CP_EXPORT Plot { protected: std::string font = "Times New Roman";//"Consolas" int fontSize = 20; int fontSize2 = 18; int foregroundIndex = 0; struct PlotInfo { std::vector<cv::Point2d> data; cv::Scalar color; int symbolType; int lineType; int lineWidth; std::string title; }; std::vector<PlotInfo> pinfo; std::string xlabel = "x"; std::string ylabel = "y"; int data_max = 1; cv::Scalar background_color = COLOR_WHITE; int gridLevel = 0; bool isDrawMousePosition = true; cv::Size plotsize; cv::Point origin; bool isSetXRange = false; bool isSetYRange = false; double xmin_plotwindow;//x max of plot window double xmax_plotwindow;//x min of plot window double ymin_plotwindow;//y max of plot window double ymax_plotwindow;//y min of plot window double xmax_data;//x max of data double xmin_data;//x min of data double ymax_data;//y max of data double ymin_data;//y min of data int keyPosition = RIGHT_TOP; bool isZeroCross; bool isXYMAXMIN; bool isXYCenter; bool isLogScaleX = false; bool isLogScaleY = false; cv::Mat plotImage; cv::Mat keyImage; void init(cv::Size imsize); void point2val(cv::Point pt, double* valx, double* valy); cv::Scalar getPseudoColor(uchar val); void plotGrid(int level); void renderingOutsideInformation(bool isFont); void computeDataMaxMin(); void computeWindowXRangeMAXMIN(bool isCenter = false, double margin_rate = 0.9, int rounding_value = 0); void computeWindowYRangeMAXMIN(bool isCenter = false, double margin_rate = 0.9, int rounding_value = 0); public: void recomputeXYRangeMAXMIN(bool isCenter = false, double margin_rate = 0.9, int rounding_balue = 0); //symbolType enum SYMBOL { NOPOINT = 0, PLUS, TIMES, ASTERISK, CIRCLE, RECTANGLE, CIRCLE_FILL, RECTANGLE_FILL, TRIANGLE, TRIANGLE_FILL, TRIANGLE_INV, TRIANGLE_INV_FILL, DIAMOND, DIAMOND_FILL, PENTAGON, PENTAGON_FILL, }; enum LINE { NOLINE, LINEAR, H2V, V2H, LINE_METHOD_SIZE }; enum KEY { NOKEY, RIGHT_TOP, LEFT_TOP, LEFT_BOTTOM, RIGHT_BOTTOM, FLOATING, KEY_METHOD_SIZE }; cv::Mat render; cv::Mat graphImage; Plot(cv::Size window_size);//cv::Size(1024, 768) Plot(); ~Plot(); void setXYOriginZERO(); void setXOriginZERO(); void setYOriginZERO(); void setPlotProfile(bool isXYCenter_, bool isXYMAXMIN_, bool isZeroCross_); void setImageSize(cv::Size s); void setXYRange(double xmin, double xmax, double ymin, double ymax); void setXRange(double xmin, double xmax); void setYRange(double ymin, double ymax); void setLogScaleX(const bool flag); void setLogScaleY(const bool flag); //NOKEY, //RIGHT_TOP, //LEFT_TOP, //LEFT_BOTTOM, //RIGHT_BOTTOM, //FLOATING, void setKey(int key_method); void setXLabel(std::string xlabel); void setYLabel(std::string ylabel); void setGrid(int level = 0);//0: no grid, 1: div 4, 2: div 16 void setBackGoundColor(cv::Scalar cl); void setPlot(int plotnum, cv::Scalar color = COLOR_RED, int symbol_type = PLUS, int line_type = LINEAR, int line_width = 1); void setPlotLineWidth(int plotnum, int line_width); void setPlotLineWidthALL(int line_width); void setPlotColor(int plotnum, cv::Scalar color); //NOPOINT = 0, //PLUS, //TIMES, //ASTERISK, //CIRCLE, //RECTANGLE, //CIRCLE_FILL, //RECTANGLE_FILL, //TRIANGLE, //TRIANGLE_FILL, //TRIANGLE_INV, //TRIANGLE_INV_FILL, //DIAMOND, //DIAMOND_FILL, //PENTAGON, //PENTAGON_FILL, void setPlotSymbol(int plotnum, int symbol_type); void setPlotSymbolALL(int symbol_type); //Plot::LINE::NONE, //Plot::LINE::LINEAR, //Plot::LINE::H2V, //Plot::LINE::V2H void setPlotLineType(int plotnum, int line_type); void setPlotLineTypeALL(int line_type); void setPlotTitle(int plotnum, std::string name); void setPlotForeground(int plotnum); void setIsDrawMousePosition(const bool flag); void plotPoint(cv::Point2d = cv::Point2d(0.0, 0.0), cv::Scalar color = COLOR_BLACK, int thickness_ = 1, int linetype = LINEAR); void plotData(int gridlevel = 0); void plotMat(cv::InputArray src, std::string name = "Plot", bool isWait = true, std::string gnuplotpath = "pgnuplot.exe"); void plot(std::string name = "Plot", bool isWait = true, std::string gnuplotpath = "pgnuplot.exe", std::string message = ""); void generateKeyImage(int num); void save(std::string name); void push_back(std::vector<cv::Point> point, int plotIndex = 0); void push_back(std::vector<cv::Point2d> point, int plotIndex = 0); void push_back(double x, double y, int plotIndex = 0); void erase(int sampleIndex, int plotIndex = 0); void insert(cv::Point2d v, int sampleIndex, int plotIndex = 0); void insert(cv::Point v, int sampleIndex, int plotIndex = 0); void insert(double x, double y, int sampleIndex, int plotIndex = 0); void clear(int datanum = -1); void swapPlot(int plotIndex1, int plotIndex2); }; class CP_EXPORT Plot2D { cv::Size plotImageSize; cv::Scalar background_color = cv::Scalar(255, 255, 255, 0); std::vector<cv::Scalar> colorIndex; std::string font = "Times New Roman"; //std::string font = "Computer Modern"; //std::string font = "Consolas"; int fontSize = 20; int fontSize2 = 18; void createPlot(); void setYMinMax(double minv, double maxv, double interval); void setXMinMax(double minv, double maxv, double interval); double x_min; double x_max; double x_interval; int x_size; double y_min; double y_max; double y_interval; int y_size; double z_min = 0.0; double z_max = 0.0; bool isSetZMinMax = false; bool isLabelXGreekLetter = false; bool isLabelYGreekLetter = false; bool isLabelZGreekLetter = false; cv::Point z_min_point; cv::Point z_max_point; cv::Mat gridData; cv::Mat gridDataRes; int colormap = 2; cv::Mat graph; void plotGraph(bool isColor); std::vector<std::string> contourLabels; std::vector<double> contourThresh; void drawContoursZ(double threth, cv::Scalar color, int lineWidth); cv::Mat barImage; int barWidth = 25; int barSpace = 5; int keyState = 1; cv::Mat keyImage; void generateKeyImage(int lineWidthBB = 1, int lineWidthKey = 2); std::string labelx = "x"; std::string labelx_subscript = ""; std::string labely = "y"; std::string labely_subscript = ""; std::string labelz = "z"; std::string labelz_subscript = ""; cv::Mat labelxImage; cv::Mat labelyImage; cv::Mat labelzImage; void addLabelToGraph(); bool isPlotMax = false; bool isPlotMin = false; int maxColorIndex = 0; int minColorIndex = 0; public: Plot2D(cv::Size graph_size, double xmin, double xmax, double xstep, double ymin, double ymax, double ystep); void add(double x, double y, double val); cv::Mat show; void plot(std::string wname = "plot2D"); void setFont(std::string font); void setFontSize(const int size); void setFontSize2(const int size); void setLabel(std::string namex, std::string namey, std::string namez); void setZMinMax(double minv, double maxv); void setPlotContours(std::string label, double thresh, int index); void setPlotMaxMin(bool plot_max, bool plot_min); void setLabelXGreekLetter(std::string greeksymbol, std::string subscript); void setLabelYGreekLetter(std::string greeksymbol, std::string subscript); void setLabelZGreekLetter(std::string greeksymbol, std::string subscript); void setMinMax(double xmin, double xmax, double xstep, double ymin, double ymax, double ystep); }; CP_EXPORT void plotGraph(cv::OutputArray graphImage, std::vector<cv::Point2d>& data, double xmin, double xmax, double ymin, double ymax, cv::Scalar color = COLOR_RED, int lt = Plot::PLUS, int isLine = Plot::LINEAR, int thickness = 1, int ps = 4, bool isLogX = false, bool isLogY = false); class CP_EXPORT RGBHistogram { private: cv::Size size = cv::Size(512, 512); cv::Mat k = cv::Mat::eye(3, 3, CV_64F); cv::Mat R = cv::Mat::eye(3, 3, CV_64F); cv::Mat t = cv::Mat::zeros(3, 1, CV_64F); void projectPointsParallel(const cv::Mat& xyz, const cv::Mat& R, const cv::Mat& t, const cv::Mat& K, std::vector<cv::Point2f>& dest, const bool isRotationThenTranspose); void projectPoints(const cv::Mat& xyz, const cv::Mat& R, const cv::Mat& t, const cv::Mat& K, std::vector<cv::Point2f>& dest, const bool isRotationThenTranspose); void projectPoint(cv::Point3d& xyz, const cv::Mat& R, const cv::Mat& t, const cv::Mat& K, cv::Point2d& dest); void convertRGBto3D(cv::Mat& src, cv::Mat& rgb); cv::Mat additionalPoints; cv::Mat additionalPointsDest; cv::Mat center; public: RGBHistogram(); void setCenter(cv::Mat& src); void push_back(cv::Mat& src); void push_back(cv::Vec3f src); void push_back(const float b, const float g, const float r); void clear(); void plot(cv::Mat& src, bool isWait = true, std::string wname = "RGB histogram"); }; } <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // 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 <https://www.gnu.org/licenses/>. #include "registry.hpp" #include "generic_parent_module.hpp" #include "parent_of_shaders_module.hpp" #include "entity.hpp" #include "shader.hpp" #include "family_templates.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <string> // std::string namespace yli::ontology { void ParentOfShadersModule::bind_child(yli::ontology::Entity* const shader_child) { if (this->entity == nullptr || shader_child == nullptr) { return; } yli::ontology::bind_child_to_parent<yli::ontology::Entity*>( shader_child, this->child_pointer_vector, this->free_childID_queue, this->number_of_children, this->entity->registry); // `shader` needs to be added to the priority queue as well. this->shader_priority_queue.push(static_cast<yli::ontology::Shader*>(shader_child)); } void ParentOfShadersModule::unbind_child(std::size_t childID) { if (this->entity == nullptr) { std::cerr << "ERROR: `ParentOfShadersModule::unbind_child`: `this->entity` is `nullptr`!\n"; return; } if (childID >= this->child_pointer_vector.size()) { std::cerr << "ERROR: `ParentOfShadersModule::unbind_child`: the value of `childID` is too big!\n"; return; } yli::ontology::Entity* const child = this->child_pointer_vector.at(childID); if (child == nullptr) { std::cerr << "ERROR: `ParentOfShadersModule::unbind_child`: `child` is `nullptr`!\n"; return; } // `shader` needs to be removed from the priority queue as well. this->shader_priority_queue.remove(childID); const std::string name = child->get_local_name(); yli::ontology::unbind_child_from_parent<yli::ontology::Entity*>( childID, name, this->child_pointer_vector, this->free_childID_queue, this->number_of_children, this->entity->registry); } ParentOfShadersModule::ParentOfShadersModule(yli::ontology::Entity* const entity, yli::ontology::Registry* const registry, const std::string& name) : GenericParentModule(entity, registry, name) { // constructor. } ParentOfShadersModule::~ParentOfShadersModule() { // destructor. } } <commit_msg>Refactor `ParentOfShadersModule` code.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // 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 <https://www.gnu.org/licenses/>. #include "registry.hpp" #include "generic_parent_module.hpp" #include "parent_of_shaders_module.hpp" #include "entity.hpp" #include "shader.hpp" // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <string> // std::string namespace yli::ontology { void ParentOfShadersModule::bind_child(yli::ontology::Entity* const shader_child) { if (this->entity == nullptr || shader_child == nullptr) { return; } this->GenericParentModule::bind_child(shader_child); // `shader` needs to be added to the priority queue as well. this->shader_priority_queue.push(static_cast<yli::ontology::Shader*>(shader_child)); } void ParentOfShadersModule::unbind_child(std::size_t childID) { if (this->entity == nullptr) { std::cerr << "ERROR: `ParentOfShadersModule::unbind_child`: `this->entity` is `nullptr`!\n"; return; } if (childID >= this->child_pointer_vector.size()) { std::cerr << "ERROR: `ParentOfShadersModule::unbind_child`: the value of `childID` is too big!\n"; return; } yli::ontology::Entity* const child = this->child_pointer_vector.at(childID); if (child == nullptr) { std::cerr << "ERROR: `ParentOfShadersModule::unbind_child`: `child` is `nullptr`!\n"; return; } // `shader` needs to be removed from the priority queue as well. this->shader_priority_queue.remove(childID); this->GenericParentModule::unbind_child(childID); } ParentOfShadersModule::ParentOfShadersModule(yli::ontology::Entity* const entity, yli::ontology::Registry* const registry, const std::string& name) : GenericParentModule(entity, registry, name) { // constructor. } ParentOfShadersModule::~ParentOfShadersModule() { // destructor. } } <|endoftext|>
<commit_before> #include <gtest/gtest.h> #include <zinc/zincconfigure.h> #include <zinc/context.h> #include <zinc/core.h> #include <zinc/field.h> #include <zinc/fieldcache.h> #include <zinc/fieldcomposite.h> #include <zinc/fieldconstant.h> #include <zinc/fieldimage.h> #include <zinc/fieldimageprocessing.h> #include <zinc/fieldmodule.h> #include <zinc/region.h> #include <zinc/status.h> #include <zinc/stream.h> #include "zinctestsetup.hpp" #include "test_resources.h" TEST(cmzn_fieldmodule_create_field_imagefilter_connected_threshold, invalid_args) { const double values[] = { 0.3, 0.1, 0.7 }; ZincTestSetup zinc; cmzn_field_id f1 = cmzn_fieldmodule_create_field_imagefilter_curvature_anisotropic_diffusion(zinc.fm, 0, 0.2, 1.0, 1); EXPECT_EQ((cmzn_field_id)0, f1); cmzn_field_id f2 = cmzn_fieldmodule_create_field_imagefilter_connected_threshold(zinc.fm, 0, 0.2, 1.0, 1.0, 1, 3, values); EXPECT_EQ((cmzn_field_id)0, f2); } TEST(cmzn_fieldmodule_create_field_imagefilter_curvature_anisotropic_diffusion, valid_args) { ZincTestSetup zinc; // Create empty image field cmzn_field_id f1 = cmzn_fieldmodule_create_field_image(zinc.fm); EXPECT_NE(static_cast<cmzn_field_id>(0), f1); cmzn_field_image_id im = cmzn_field_cast_image(f1); cmzn_streaminformation_id si = cmzn_field_image_create_streaminformation(im); EXPECT_NE(static_cast<cmzn_streaminformation_id>(0), si); cmzn_streamresource_id sr = cmzn_streaminformation_create_streamresource_file(si, TestResources::getLocation(TestResources::TESTIMAGE_GRAY_JPG_RESOURCE)); cmzn_streaminformation_image_id si_image = cmzn_streaminformation_cast_image(si); EXPECT_NE(static_cast<cmzn_streaminformation_image_id>(0), si_image); EXPECT_EQ(CMZN_OK, cmzn_field_image_read(im, si_image)); cmzn_field_id f2 = cmzn_fieldmodule_create_field_imagefilter_curvature_anisotropic_diffusion(zinc.fm, cmzn_field_image_base_cast(im), 0.1, 1.0, 1); EXPECT_NE((cmzn_field_id)0, f2); // cmzn_field_id f2 = cmzn_fieldmodule_create_field_connected_threshold_image_filter(zinc.fm, f1, 0.2, 1.0, 1.0, 1, 3, values); // EXPECT_NE((cmzn_field_id)0, f2); cmzn_field_id xi = cmzn_field_image_get_domain_field(im); EXPECT_NE((cmzn_field_id)0, xi); cmzn_fieldcache_id cache = cmzn_fieldmodule_create_fieldcache(zinc.fm); double location[] = { 0.7, 0.2}; double value = 0.0; EXPECT_EQ(CMZN_OK, cmzn_fieldcache_set_field_real(cache, xi, 2, location)); // EXPECT_EQ(CMZN_OK, cmzn_field_evaluate_real(cmzn_field_image_base_cast(im), cache, 1, &value)); EXPECT_EQ(CMZN_OK, cmzn_field_evaluate_real(f2, cache, 1, &value)); EXPECT_NEAR(0.211765, value, 1e-6); cmzn_fieldcache_destroy(&cache); cmzn_field_destroy(&xi); cmzn_field_destroy(&f1); cmzn_field_destroy(&f2); cmzn_streamresource_destroy(&sr); cmzn_streaminformation_image_destroy(&si_image); cmzn_streaminformation_destroy(&si); cmzn_field_image_destroy(&im); } TEST(cmzn_fieldmodule_create_field_imagefilter_connected_threshold, valid_args) { ZincTestSetup zinc; double location[] = { 0.7, 0.2}; // Create empty image field cmzn_field_id f1 = cmzn_fieldmodule_create_field_image(zinc.fm); EXPECT_NE(static_cast<cmzn_field_id>(0), f1); cmzn_field_image_id im = cmzn_field_cast_image(f1); cmzn_streaminformation_id si = cmzn_field_image_create_streaminformation(im); EXPECT_NE(static_cast<cmzn_streaminformation_id>(0), si); cmzn_streaminformation_image_id si_image = cmzn_streaminformation_cast_image(si); EXPECT_NE(static_cast<cmzn_streaminformation_image_id>(0), si_image); cmzn_streamresource_id sr = cmzn_streaminformation_create_streamresource_file(si, TestResources::getLocation(TestResources::TESTIMAGE_GRAY_JPG_RESOURCE)); EXPECT_EQ(CMZN_OK, cmzn_field_image_read(im, si_image)); cmzn_field_id f2 = cmzn_fieldmodule_create_field_imagefilter_connected_threshold(zinc.fm, cmzn_field_image_base_cast(im), 0.2, 0.22, 0.33, 1, 2, location); EXPECT_NE((cmzn_field_id)0, f2); cmzn_field_id xi = cmzn_field_image_get_domain_field(im); EXPECT_NE((cmzn_field_id)0, xi); cmzn_fieldcache_id cache = cmzn_fieldmodule_create_fieldcache(zinc.fm); double value = 0.0; EXPECT_EQ(CMZN_OK, cmzn_fieldcache_set_field_real(cache, xi, 2, location)); // EXPECT_EQ(CMZN_OK, cmzn_field_evaluate_real(cmzn_field_image_base_cast(im), cache, 1, &value)); EXPECT_EQ(CMZN_OK, cmzn_field_evaluate_real(f2, cache, 1, &value)); EXPECT_NEAR(0.33, value, 1e-6); cmzn_fieldcache_destroy(&cache); cmzn_field_destroy(&xi); cmzn_field_destroy(&f1); cmzn_field_destroy(&f2); cmzn_streamresource_destroy(&sr); cmzn_streaminformation_image_destroy(&si_image); cmzn_streaminformation_destroy(&si); cmzn_field_image_destroy(&im); } <commit_msg>Create unit tests for threshold image filter field API. Issue 3662.<commit_after> #include <gtest/gtest.h> #include <zinc/zincconfigure.h> #include <zinc/context.h> #include <zinc/core.h> #include <zinc/field.h> #include <zinc/fieldcache.h> #include <zinc/fieldcomposite.h> #include <zinc/fieldconstant.h> #include <zinc/fieldimage.h> #include <zinc/fieldimageprocessing.h> #include <zinc/fieldmodule.h> #include <zinc/region.h> #include <zinc/status.h> #include <zinc/stream.h> #include "zinctestsetup.hpp" #include "test_resources.h" TEST(cmzn_fieldmodule_create_field_imagefilter_connected_threshold, invalid_args) { const double values[] = { 0.3, 0.1, 0.7 }; ZincTestSetup zinc; cmzn_field_id f1 = cmzn_fieldmodule_create_field_imagefilter_curvature_anisotropic_diffusion(zinc.fm, 0, 0.2, 1.0, 1); EXPECT_EQ((cmzn_field_id)0, f1); cmzn_field_id f2 = cmzn_fieldmodule_create_field_imagefilter_connected_threshold(zinc.fm, 0, 0.2, 1.0, 1.0, 1, 3, values); EXPECT_EQ((cmzn_field_id)0, f2); } TEST(cmzn_fieldmodule_create_field_imagefilter_curvature_anisotropic_diffusion, valid_args) { ZincTestSetup zinc; // Create empty image field cmzn_field_id f1 = cmzn_fieldmodule_create_field_image(zinc.fm); EXPECT_NE(static_cast<cmzn_field_id>(0), f1); cmzn_field_image_id im = cmzn_field_cast_image(f1); cmzn_streaminformation_id si = cmzn_field_image_create_streaminformation(im); EXPECT_NE(static_cast<cmzn_streaminformation_id>(0), si); cmzn_streamresource_id sr = cmzn_streaminformation_create_streamresource_file(si, TestResources::getLocation(TestResources::TESTIMAGE_GRAY_JPG_RESOURCE)); cmzn_streaminformation_image_id si_image = cmzn_streaminformation_cast_image(si); EXPECT_NE(static_cast<cmzn_streaminformation_image_id>(0), si_image); EXPECT_EQ(CMZN_OK, cmzn_field_image_read(im, si_image)); cmzn_field_id f2 = cmzn_fieldmodule_create_field_imagefilter_curvature_anisotropic_diffusion(zinc.fm, cmzn_field_image_base_cast(im), 0.1, 1.0, 1); EXPECT_NE((cmzn_field_id)0, f2); // cmzn_field_id f2 = cmzn_fieldmodule_create_field_connected_threshold_image_filter(zinc.fm, f1, 0.2, 1.0, 1.0, 1, 3, values); // EXPECT_NE((cmzn_field_id)0, f2); cmzn_field_id xi = cmzn_field_image_get_domain_field(im); EXPECT_NE((cmzn_field_id)0, xi); cmzn_fieldcache_id cache = cmzn_fieldmodule_create_fieldcache(zinc.fm); double location[] = { 0.7, 0.2}; double value = 0.0; EXPECT_EQ(CMZN_OK, cmzn_fieldcache_set_field_real(cache, xi, 2, location)); // EXPECT_EQ(CMZN_OK, cmzn_field_evaluate_real(cmzn_field_image_base_cast(im), cache, 1, &value)); EXPECT_EQ(CMZN_OK, cmzn_field_evaluate_real(f2, cache, 1, &value)); EXPECT_NEAR(0.211765, value, 1e-6); cmzn_fieldcache_destroy(&cache); cmzn_field_destroy(&xi); cmzn_field_destroy(&f1); cmzn_field_destroy(&f2); cmzn_streamresource_destroy(&sr); cmzn_streaminformation_image_destroy(&si_image); cmzn_streaminformation_destroy(&si); cmzn_field_image_destroy(&im); } TEST(cmzn_fieldmodule_create_field_imagefilter_connected_threshold, valid_args) { ZincTestSetup zinc; double location[] = { 0.7, 0.2}; // Create empty image field cmzn_field_id f1 = cmzn_fieldmodule_create_field_image(zinc.fm); EXPECT_NE(static_cast<cmzn_field_id>(0), f1); cmzn_field_image_id im = cmzn_field_cast_image(f1); cmzn_streaminformation_id si = cmzn_field_image_create_streaminformation(im); EXPECT_NE(static_cast<cmzn_streaminformation_id>(0), si); cmzn_streaminformation_image_id si_image = cmzn_streaminformation_cast_image(si); EXPECT_NE(static_cast<cmzn_streaminformation_image_id>(0), si_image); cmzn_streamresource_id sr = cmzn_streaminformation_create_streamresource_file(si, TestResources::getLocation(TestResources::TESTIMAGE_GRAY_JPG_RESOURCE)); EXPECT_EQ(CMZN_OK, cmzn_field_image_read(im, si_image)); cmzn_field_id f2 = cmzn_fieldmodule_create_field_imagefilter_connected_threshold(zinc.fm, cmzn_field_image_base_cast(im), 0.2, 0.22, 0.33, 1, 2, location); EXPECT_NE((cmzn_field_id)0, f2); cmzn_field_id xi = cmzn_field_image_get_domain_field(im); EXPECT_NE((cmzn_field_id)0, xi); cmzn_fieldcache_id cache = cmzn_fieldmodule_create_fieldcache(zinc.fm); double value = 0.0; EXPECT_EQ(CMZN_OK, cmzn_fieldcache_set_field_real(cache, xi, 2, location)); // EXPECT_EQ(CMZN_OK, cmzn_field_evaluate_real(cmzn_field_image_base_cast(im), cache, 1, &value)); EXPECT_EQ(CMZN_OK, cmzn_field_evaluate_real(f2, cache, 1, &value)); EXPECT_NEAR(0.33, value, 1e-6); cmzn_fieldcache_destroy(&cache); cmzn_field_destroy(&xi); cmzn_field_destroy(&f1); cmzn_field_destroy(&f2); cmzn_streamresource_destroy(&sr); cmzn_streaminformation_image_destroy(&si_image); cmzn_streaminformation_destroy(&si); cmzn_field_image_destroy(&im); } TEST(cmzn_field_imagefilter_threshold, api) { ZincTestSetup zinc; int result; cmzn_field_id f1 = cmzn_fieldmodule_create_field_image(zinc.fm); EXPECT_NE(static_cast<cmzn_field_id>(0), f1); cmzn_field_image_id im = cmzn_field_cast_image(f1); EXPECT_EQ(CMZN_OK, result = cmzn_field_image_read_file(im, TestResources::getLocation(TestResources::TESTIMAGE_GRAY_JPG_RESOURCE))); cmzn_field_id f2 = cmzn_fieldmodule_create_field_imagefilter_threshold(zinc.fm, f1); cmzn_field_imagefilter_threshold_id th = cmzn_field_cast_imagefilter_threshold(f2); cmzn_field_imagefilter_threshold_condition condition; EXPECT_EQ(CMZN_FIELD_IMAGEFILTER_THRESHOLD_CONDITION_BELOW, condition = cmzn_field_imagefilter_threshold_get_condition(th)); EXPECT_EQ(CMZN_OK, result = cmzn_field_imagefilter_threshold_set_condition(th, CMZN_FIELD_IMAGEFILTER_THRESHOLD_CONDITION_OUTSIDE)); EXPECT_EQ(CMZN_FIELD_IMAGEFILTER_THRESHOLD_CONDITION_OUTSIDE, condition = cmzn_field_imagefilter_threshold_get_condition(th)); double value; ASSERT_DOUBLE_EQ(0.0, value = cmzn_field_imagefilter_threshold_get_outside_value(th)); EXPECT_EQ(CMZN_OK, result = cmzn_field_imagefilter_threshold_set_outside_value(th, 1.0)); ASSERT_DOUBLE_EQ(1.0, value = cmzn_field_imagefilter_threshold_get_outside_value(th)); ASSERT_DOUBLE_EQ(0.5, value = cmzn_field_imagefilter_threshold_get_lower_threshold(th)); EXPECT_EQ(CMZN_OK, result = cmzn_field_imagefilter_threshold_set_lower_threshold(th, 0.2)); ASSERT_DOUBLE_EQ(0.2, value = cmzn_field_imagefilter_threshold_get_lower_threshold(th)); ASSERT_DOUBLE_EQ(0.5, value = cmzn_field_imagefilter_threshold_get_upper_threshold(th)); EXPECT_EQ(CMZN_OK, result = cmzn_field_imagefilter_threshold_set_upper_threshold(th, 0.8)); ASSERT_DOUBLE_EQ(0.8, value = cmzn_field_imagefilter_threshold_get_upper_threshold(th)); cmzn_field_imagefilter_threshold_destroy(&th); cmzn_field_destroy(&f1); cmzn_field_destroy(&f2); cmzn_field_image_destroy(&im); } <|endoftext|>
<commit_before>#include <plasp/sas/TranslatorASP.h> #include <plasp/sas/TranslatorException.h> #include <plasp/utils/Parsing.h> namespace plasp { namespace sas { //////////////////////////////////////////////////////////////////////////////////////////////////// // // TranslatorASP // //////////////////////////////////////////////////////////////////////////////////////////////////// TranslatorASP::TranslatorASP(const Description &description) : m_description(description) { } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translate(std::ostream &ostream) const { const auto usesActionCosts = m_description.usesActionCosts(); const auto usesAxiomRules = m_description.usesAxiomRules(); const auto usesConditionalEffects = m_description.usesConditionalEffects(); ostream << "% feature requirements" << std::endl; if (usesActionCosts) ostream << "requiresFeature(actionCosts)." << std::endl; if (usesAxiomRules) ostream << "requiresFeature(axiomRules)." << std::endl; if (usesConditionalEffects) ostream << "requiresFeature(conditionalEffects)." << std::endl; ostream << std::endl; ostream << "% initial state" << std::endl; const auto &initialStateFacts = m_description.initialState().facts(); std::for_each(initialStateFacts.cbegin(), initialStateFacts.cend(), [&](const auto &fact) { ostream << "initialState("; fact.variable().printNameAsASPPredicate(ostream); ostream << ", "; fact.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); ostream << std::endl; ostream << "% goal" << std::endl; const auto &goalFacts = m_description.goal().facts(); std::for_each(goalFacts.cbegin(), goalFacts.cend(), [&](const auto &fact) { ostream << "goal("; fact.variable().printNameAsASPPredicate(ostream); ostream << ", "; fact.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); ostream << std::endl; ostream << "% variables"; const auto &variables = m_description.variables(); std::for_each(variables.cbegin(), variables.cend(), [&](const auto &variable) { const auto &values = variable.values(); BOOST_ASSERT(!values.empty()); ostream << std::endl; variable.printNameAsASPPredicate(ostream); ostream << "." << std::endl; std::for_each(values.cbegin(), values.cend(), [&](const auto &value) { ostream << "contains("; variable.printNameAsASPPredicate(ostream); ostream << ", "; value.printAsASPPredicate(ostream); ostream << ")." << std::endl; }); }); ostream << std::endl; ostream << "% actions"; const auto &operators = m_description.operators(); std::for_each(operators.cbegin(), operators.cend(), [&](const auto &operator_) { ostream << std::endl; operator_.printPredicateAsASP(ostream); ostream << "." << std::endl; const auto &preconditions = operator_.preconditions(); std::for_each(preconditions.cbegin(), preconditions.cend(), [&](const auto &precondition) { ostream << "precondition("; operator_.printPredicateAsASP(ostream); ostream << ", "; precondition.variable().printNameAsASPPredicate(ostream); ostream << ", "; precondition.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); const auto &effects = operator_.effects(); size_t currentEffectID = 0; std::for_each(effects.cbegin(), effects.cend(), [&](const auto &effect) { const auto &conditions = effect.conditions(); std::for_each(conditions.cbegin(), conditions.cend(), [&](const auto &condition) { ostream << "effectCondition("; operator_.printPredicateAsASP(ostream); ostream << ", effect(" << currentEffectID << "), "; condition.variable().printNameAsASPPredicate(ostream); ostream << ", "; condition.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); ostream << "postcondition("; operator_.printPredicateAsASP(ostream); ostream << ", effect(" << currentEffectID << "), "; effect.postcondition().variable().printNameAsASPPredicate(ostream); ostream << ", "; effect.postcondition().value().printAsASPPredicate(ostream); ostream << ")." << std::endl; currentEffectID++; }); if (usesActionCosts) { ostream << "costs("; operator_.printPredicateAsASP(ostream); ostream << ", " << operator_.costs() << ")." << std::endl; } }); ostream << std::endl; ostream << "% mutex groups"; const auto &mutexGroups = m_description.mutexGroups(); size_t currentMutexGroupID = 0; std::for_each(mutexGroups.cbegin(), mutexGroups.cend(), [&](const auto &mutexGroup) { const auto mutexGroupID = std::to_string(currentMutexGroupID); currentMutexGroupID++; ostream << std::endl << "mutexGroup(" << mutexGroupID << ")." << std::endl; const auto &facts = mutexGroup.facts(); std::for_each(facts.cbegin(), facts.cend(), [&](const auto &fact) { ostream << "contains(mutexGroup(" << mutexGroupID << "), "; fact.variable().printNameAsASPPredicate(ostream); ostream << ", "; fact.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); }); if (usesAxiomRules) { ostream << std::endl; ostream << "% axiom rules"; const auto &axiomRules = m_description.axiomRules(); size_t currentAxiomRuleID = 0; std::for_each(axiomRules.cbegin(), axiomRules.cend(), [&](const auto &axiomRule) { const auto axiomRuleID = std::to_string(currentAxiomRuleID); currentAxiomRuleID++; ostream << std::endl << "axiomRule(" << axiomRuleID << ")." << std::endl; const auto &conditions = axiomRule.conditions(); std::for_each(conditions.cbegin(), conditions.cend(), [&](const auto &condition) { ostream << "condition(axiomRule(" << axiomRuleID << "), "; condition.variable().printNameAsASPPredicate(ostream); ostream << ", "; condition.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); const auto &postcondition = axiomRule.postcondition(); ostream << "postcondition(axiomRule(axiomRule" << axiomRuleID << "), "; postcondition.variable().printNameAsASPPredicate(ostream); ostream << ", "; postcondition.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); } } //////////////////////////////////////////////////////////////////////////////////////////////////// } } <commit_msg>Showing action cost predicates unconditionally for easier handling in meta encodings.<commit_after>#include <plasp/sas/TranslatorASP.h> #include <plasp/sas/TranslatorException.h> #include <plasp/utils/Parsing.h> namespace plasp { namespace sas { //////////////////////////////////////////////////////////////////////////////////////////////////// // // TranslatorASP // //////////////////////////////////////////////////////////////////////////////////////////////////// TranslatorASP::TranslatorASP(const Description &description) : m_description(description) { } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translate(std::ostream &ostream) const { const auto usesActionCosts = m_description.usesActionCosts(); const auto usesAxiomRules = m_description.usesAxiomRules(); const auto usesConditionalEffects = m_description.usesConditionalEffects(); ostream << "% feature requirements" << std::endl; if (usesActionCosts) ostream << "requiresFeature(actionCosts)." << std::endl; if (usesAxiomRules) ostream << "requiresFeature(axiomRules)." << std::endl; if (usesConditionalEffects) ostream << "requiresFeature(conditionalEffects)." << std::endl; ostream << std::endl; ostream << "% initial state" << std::endl; const auto &initialStateFacts = m_description.initialState().facts(); std::for_each(initialStateFacts.cbegin(), initialStateFacts.cend(), [&](const auto &fact) { ostream << "initialState("; fact.variable().printNameAsASPPredicate(ostream); ostream << ", "; fact.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); ostream << std::endl; ostream << "% goal" << std::endl; const auto &goalFacts = m_description.goal().facts(); std::for_each(goalFacts.cbegin(), goalFacts.cend(), [&](const auto &fact) { ostream << "goal("; fact.variable().printNameAsASPPredicate(ostream); ostream << ", "; fact.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); ostream << std::endl; ostream << "% variables"; const auto &variables = m_description.variables(); std::for_each(variables.cbegin(), variables.cend(), [&](const auto &variable) { const auto &values = variable.values(); BOOST_ASSERT(!values.empty()); ostream << std::endl; variable.printNameAsASPPredicate(ostream); ostream << "." << std::endl; std::for_each(values.cbegin(), values.cend(), [&](const auto &value) { ostream << "contains("; variable.printNameAsASPPredicate(ostream); ostream << ", "; value.printAsASPPredicate(ostream); ostream << ")." << std::endl; }); }); ostream << std::endl; ostream << "% actions"; const auto &operators = m_description.operators(); std::for_each(operators.cbegin(), operators.cend(), [&](const auto &operator_) { ostream << std::endl; operator_.printPredicateAsASP(ostream); ostream << "." << std::endl; const auto &preconditions = operator_.preconditions(); std::for_each(preconditions.cbegin(), preconditions.cend(), [&](const auto &precondition) { ostream << "precondition("; operator_.printPredicateAsASP(ostream); ostream << ", "; precondition.variable().printNameAsASPPredicate(ostream); ostream << ", "; precondition.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); const auto &effects = operator_.effects(); size_t currentEffectID = 0; std::for_each(effects.cbegin(), effects.cend(), [&](const auto &effect) { const auto &conditions = effect.conditions(); std::for_each(conditions.cbegin(), conditions.cend(), [&](const auto &condition) { ostream << "effectCondition("; operator_.printPredicateAsASP(ostream); ostream << ", effect(" << currentEffectID << "), "; condition.variable().printNameAsASPPredicate(ostream); ostream << ", "; condition.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); ostream << "postcondition("; operator_.printPredicateAsASP(ostream); ostream << ", effect(" << currentEffectID << "), "; effect.postcondition().variable().printNameAsASPPredicate(ostream); ostream << ", "; effect.postcondition().value().printAsASPPredicate(ostream); ostream << ")." << std::endl; currentEffectID++; }); ostream << "costs("; operator_.printPredicateAsASP(ostream); ostream << ", " << operator_.costs() << ")." << std::endl; }); ostream << std::endl; ostream << "% mutex groups"; const auto &mutexGroups = m_description.mutexGroups(); size_t currentMutexGroupID = 0; std::for_each(mutexGroups.cbegin(), mutexGroups.cend(), [&](const auto &mutexGroup) { const auto mutexGroupID = std::to_string(currentMutexGroupID); currentMutexGroupID++; ostream << std::endl << "mutexGroup(" << mutexGroupID << ")." << std::endl; const auto &facts = mutexGroup.facts(); std::for_each(facts.cbegin(), facts.cend(), [&](const auto &fact) { ostream << "contains(mutexGroup(" << mutexGroupID << "), "; fact.variable().printNameAsASPPredicate(ostream); ostream << ", "; fact.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); }); if (usesAxiomRules) { ostream << std::endl; ostream << "% axiom rules"; const auto &axiomRules = m_description.axiomRules(); size_t currentAxiomRuleID = 0; std::for_each(axiomRules.cbegin(), axiomRules.cend(), [&](const auto &axiomRule) { const auto axiomRuleID = std::to_string(currentAxiomRuleID); currentAxiomRuleID++; ostream << std::endl << "axiomRule(" << axiomRuleID << ")." << std::endl; const auto &conditions = axiomRule.conditions(); std::for_each(conditions.cbegin(), conditions.cend(), [&](const auto &condition) { ostream << "condition(axiomRule(" << axiomRuleID << "), "; condition.variable().printNameAsASPPredicate(ostream); ostream << ", "; condition.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); const auto &postcondition = axiomRule.postcondition(); ostream << "postcondition(axiomRule(axiomRule" << axiomRuleID << "), "; postcondition.variable().printNameAsASPPredicate(ostream); ostream << ", "; postcondition.value().printAsASPPredicate(ostream); ostream << ")." << std::endl; }); } } //////////////////////////////////////////////////////////////////////////////////////////////////// } } <|endoftext|>
<commit_before>/* See Project chip LICENSE file for licensing information. */ #include <platform/logging/LogV.h> #include <support/logging/Constants.h> #include <core/CHIPConfig.h> #include <support/logging/Constants.h> #include <os/log.h> #include <inttypes.h> #include <pthread.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <sys/time.h> namespace chip { namespace Logging { namespace Platform { void LogV(const char * module, uint8_t category, const char * msg, va_list v) { timeval time; gettimeofday(&time, NULL); long ms = (time.tv_sec * 1000) + (time.tv_usec / 1000); uint64_t ktid; pthread_threadid_np(NULL, &ktid); char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; int32_t prefixLen = snprintf(formattedMsg, sizeof(formattedMsg), "[%ld] [%lld:%lld] CHIP: [%s] ", ms, (long long) getpid(), (long long) ktid, module); static os_log_t log = os_log_create("com.zigbee.chip", "all"); if (prefixLen < 0) { // This should not happen return; } if (static_cast<size_t>(prefixLen) >= sizeof(formattedMsg)) { prefixLen = sizeof(formattedMsg) - 1; } vsnprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - static_cast<size_t>(prefixLen), msg, v); switch (category) { case kLogCategory_Error: os_log_with_type(log, OS_LOG_TYPE_ERROR, "🔴 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[1;31m"); #endif break; case kLogCategory_Progress: os_log_with_type(log, OS_LOG_TYPE_DEFAULT, "🔵 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[0;32m"); #endif break; case kLogCategory_Detail: os_log_with_type(log, OS_LOG_TYPE_DEBUG, "🟢 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[0;34m"); #endif break; } #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "%s\033[0m\n", formattedMsg); #endif } } // namespace Platform } // namespace Logging } // namespace chip <commit_msg>[Darwin] Fix log level for CHIP Detail logging so that all logs are persisted (#8588)<commit_after>/* See Project chip LICENSE file for licensing information. */ #include <platform/logging/LogV.h> #include <support/logging/Constants.h> #include <core/CHIPConfig.h> #include <support/logging/Constants.h> #include <os/log.h> #include <inttypes.h> #include <pthread.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <sys/time.h> namespace chip { namespace Logging { namespace Platform { void LogV(const char * module, uint8_t category, const char * msg, va_list v) { timeval time; gettimeofday(&time, NULL); long ms = (time.tv_sec * 1000) + (time.tv_usec / 1000); uint64_t ktid; pthread_threadid_np(NULL, &ktid); char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; int32_t prefixLen = snprintf(formattedMsg, sizeof(formattedMsg), "[%ld] [%lld:%lld] CHIP: [%s] ", ms, (long long) getpid(), (long long) ktid, module); static os_log_t log = os_log_create("com.zigbee.chip", "all"); if (prefixLen < 0) { // This should not happen return; } if (static_cast<size_t>(prefixLen) >= sizeof(formattedMsg)) { prefixLen = sizeof(formattedMsg) - 1; } vsnprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - static_cast<size_t>(prefixLen), msg, v); switch (category) { case kLogCategory_Error: os_log_with_type(log, OS_LOG_TYPE_ERROR, "🔴 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[1;31m"); #endif break; case kLogCategory_Progress: os_log_with_type(log, OS_LOG_TYPE_DEFAULT, "🔵 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[0;32m"); #endif break; case kLogCategory_Detail: os_log_with_type(log, OS_LOG_TYPE_DEFAULT, "🟢 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[0;34m"); #endif break; } #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "%s\033[0m\n", formattedMsg); #endif } } // namespace Platform } // namespace Logging } // namespace chip <|endoftext|>
<commit_before>// Copyright (c) 2013-2016 mogemimi. Distributed under the MIT license. #include <Pomdog/Utility/StringHelper.hpp> #include <gtest/iutest_switch.hpp> using Pomdog::StringHelper; TEST(StringHelper, FirstCase) { EXPECT_EQ("1 + 2 = 3", StringHelper::Format("%d + %d = %d", 1, 2, 1+2)); EXPECT_EQ("A + B = AB", StringHelper::Format("%s + %s = %s", "A", "B", "AB")); EXPECT_EQ("A + B = AB", StringHelper::Format("%c + %c = %c%c", 'A', 'B', 'A', 'B')); EXPECT_EQ("201103", StringHelper::Format("%ld", 201103L)); EXPECT_EQ(" 6543210", StringHelper::Format("%8d", 6543210)); EXPECT_EQ(" 43210", StringHelper::Format("%8d", 43210)); EXPECT_EQ("06543210", StringHelper::Format("%08d", 6543210)); EXPECT_EQ("00043210", StringHelper::Format("%08d", 43210)); EXPECT_EQ("100", StringHelper::Format("%d", 100)); EXPECT_EQ("64", StringHelper::Format("%x", 100)); EXPECT_EQ("144", StringHelper::Format("%o", 100)); EXPECT_EQ("0x64", StringHelper::Format("%#x", 100)); EXPECT_EQ("0144", StringHelper::Format("%#o", 100)); EXPECT_EQ("3.142", StringHelper::Format("%4.3f", 3.14159265f)); EXPECT_EQ("3.141", StringHelper::Format("%4.3f", 3.1410f)); EXPECT_EQ("3.142", StringHelper::Format("%4.3lf", 3.14159265)); EXPECT_EQ("3.141", StringHelper::Format("%4.3lf", 3.1410)); //EXPECT_EQ("42", StringHelper::Format("%*d", 3, 42)); } TEST(StringHelper, LongString) { std::string const source(1024, 'A'); EXPECT_EQ(std::string("42+") + source + "+72", StringHelper::Format("42+%s+72", source.c_str())); } <commit_msg>Fix test case<commit_after>// Copyright (c) 2013-2016 mogemimi. Distributed under the MIT license. #include <Pomdog/Utility/StringHelper.hpp> #include <gtest/iutest_switch.hpp> namespace StringHelper = Pomdog::StringHelper; TEST(StringHelper, FirstCase) { EXPECT_EQ("1 + 2 = 3", StringHelper::Format("%d + %d = %d", 1, 2, 1+2)); EXPECT_EQ("A + B = AB", StringHelper::Format("%s + %s = %s", "A", "B", "AB")); EXPECT_EQ("A + B = AB", StringHelper::Format("%c + %c = %c%c", 'A', 'B', 'A', 'B')); EXPECT_EQ("201103", StringHelper::Format("%ld", 201103L)); EXPECT_EQ(" 6543210", StringHelper::Format("%8d", 6543210)); EXPECT_EQ(" 43210", StringHelper::Format("%8d", 43210)); EXPECT_EQ("06543210", StringHelper::Format("%08d", 6543210)); EXPECT_EQ("00043210", StringHelper::Format("%08d", 43210)); EXPECT_EQ("100", StringHelper::Format("%d", 100)); EXPECT_EQ("64", StringHelper::Format("%x", 100)); EXPECT_EQ("144", StringHelper::Format("%o", 100)); EXPECT_EQ("0x64", StringHelper::Format("%#x", 100)); EXPECT_EQ("0144", StringHelper::Format("%#o", 100)); EXPECT_EQ("3.142", StringHelper::Format("%4.3f", 3.14159265f)); EXPECT_EQ("3.141", StringHelper::Format("%4.3f", 3.1410f)); EXPECT_EQ("3.142", StringHelper::Format("%4.3lf", 3.14159265)); EXPECT_EQ("3.141", StringHelper::Format("%4.3lf", 3.1410)); //EXPECT_EQ("42", StringHelper::Format("%*d", 3, 42)); } TEST(StringHelper, LongString) { std::string const source(1024, 'A'); EXPECT_EQ(std::string("42+") + source + "+72", StringHelper::Format("42+%s+72", source.c_str())); } <|endoftext|>
<commit_before>#ifndef K3_RUNTIME_BUILTINS_H #define K3_RUNTIME_BUILTINS_H #include <ctime> #include <chrono> #include <climits> #include <fstream> #include <sstream> #include <string> #include <functional> #include "BaseTypes.hpp" namespace K3 { //class Builtins: public __k3_context { // public: // Builtins() { // // seed the random number generator // std::srand(std::time(0)); // } // int random(int x) { return std::rand(x); } // double randomFraction(unit_t) { return (double)rand() / RAND_MAX; } // <template t> // int hash(t x) { return static_cast<int>std::hash<t>(x); } // int truncate(double x) { return (int)x; } // double real_of_int(int x) { return (double)x; } // int get_max_int(unit_t x) { return INT_MAX; } //}; F<F<unit_t(const string&)>(const string&)> openBuiltin(const string& chan_id); F<F<F<unit_t(const string&)>(const string&)>(const string&)> openFile(const string& chan_id); unit_t close(std::string chan_id); unit_t printLine(std::string message); std::string itos(int i); std::string rtos(double d); unit_t haltEngine(unit_t); F<F<string(const int&)>(const int&)> substring(const string& s); F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> vector_add(const Collection<R_elem<double>>& c1); F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> vector_sub(const Collection<R_elem<double>>& c1); F<double(const Collection<R_elem<double>>&)> dot(const Collection<R_elem<double>>& c1); F<double(const Collection<R_elem<double>>&)> squared_distance(const Collection<R_elem<double>>& c1); Collection<R_elem<double>> zero_vector(int n); F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> scalar_mult(const double& d); // ms int now(unit_t); // Map-specific template function to look up template <class Key, class Value> F<shared_ptr<Value>(const Key&)> lookup(Map<R_key_value<Key, Value> >& map) { return [&] (const Key& key) { const auto &container(map.getContainer()); const auto it(container.find(key)); if (it != container.end()) { return make_shared<Value>(it->second); } else { return shared_ptr<Value>(); } }; } template <class E> F<F<F<unit_t(F<typename E::ValueType(const typename E::ValueType&)>)>(const typename E::ValueType&)>(const typename E::KeyType&)> insert_with(Map<E>& map) { return [&] (const typename E::KeyType& key) { return [&] (const typename E::ValueType& value) { return [&] (std::function<typename E::ValueType(const typename E::ValueType&)> f) { auto &c = map.getContainer(); auto it(c.find(key)); if (it == map.end()) { map.insert(E(key, value)); } else { map.insert(E(key, f(value))); } return unit_t(); }; }; }; } // Split a std::string by substrings F<Seq<R_elem<std::string> >(const std::string&)> splitString(const std::string& s); } // namespace K3 #endif /* K3_RUNTIME_BUILTINS_H */ <commit_msg>added declarations for eigen to builtin header<commit_after>#ifndef K3_RUNTIME_BUILTINS_H #define K3_RUNTIME_BUILTINS_H #include <ctime> #include <chrono> #include <climits> #include <fstream> #include <sstream> #include <string> #include <functional> #include "BaseTypes.hpp" namespace K3 { //class Builtins: public __k3_context { // public: // Builtins() { // // seed the random number generator // std::srand(std::time(0)); // } // int random(int x) { return std::rand(x); } // double randomFraction(unit_t) { return (double)rand() / RAND_MAX; } // <template t> // int hash(t x) { return static_cast<int>std::hash<t>(x); } // int truncate(double x) { return (int)x; } // double real_of_int(int x) { return (double)x; } // int get_max_int(unit_t x) { return INT_MAX; } //}; F<F<unit_t(const string&)>(const string&)> openBuiltin(const string& chan_id); F<F<F<unit_t(const string&)>(const string&)>(const string&)> openFile(const string& chan_id); unit_t close(std::string chan_id); unit_t printLine(std::string message); std::string itos(int i); std::string rtos(double d); unit_t haltEngine(unit_t); F<F<string(const int&)>(const int&)> substring(const string& s); F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> vector_add(const Collection<R_elem<double>>& c1); F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> vector_sub(const Collection<R_elem<double>>& c1); F<double(const Collection<R_elem<double>>&)> dot(const Collection<R_elem<double>>& c1); F<double(const Collection<R_elem<double>>&)> squared_distance(const Collection<R_elem<double>>& c1); Collection<R_elem<double>> zero_vector(int n); F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> scalar_mult(const double& d); //*********Ricky's Eigen stuff********** // F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> vector_add_eigen(const Collection<R_elem<double>>& c1); // //F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> vector_sub_eigen(const Collection<R_elem<double>>& c1); // F<double(const Collection<R_elem<double>>&)> dot_eigen(const Collection<R_elem<double>>& c1); // F<double(const Collection<R_elem<double>>&)> squared_distance_eigen(const Collection<R_elem<double>>& c1); // Collection<R_elem<double>> zero_vector_eigen(int n); // F<Collection<R_elem<double>>(const Collection<R_elem<double>>&)> scalar_mult_eigen(const double& d); // ms int now(unit_t); // Map-specific template function to look up template <class Key, class Value> F<shared_ptr<Value>(const Key&)> lookup(Map<R_key_value<Key, Value> >& map) { return [&] (const Key& key) { const auto &container(map.getContainer()); const auto it(container.find(key)); if (it != container.end()) { return make_shared<Value>(it->second); } else { return shared_ptr<Value>(); } }; } template <class E> F<F<F<unit_t(F<typename E::ValueType(const typename E::ValueType&)>)>(const typename E::ValueType&)>(const typename E::KeyType&)> insert_with(Map<E>& map) { return [&] (const typename E::KeyType& key) { return [&] (const typename E::ValueType& value) { return [&] (std::function<typename E::ValueType(const typename E::ValueType&)> f) { auto &c = map.getContainer(); auto it(c.find(key)); if (it == map.end()) { map.insert(E(key, value)); } else { map.insert(E(key, f(value))); } return unit_t(); }; }; }; } // Split a std::string by substrings F<Seq<R_elem<std::string> >(const std::string&)> splitString(const std::string& s); } // namespace K3 #endif /* K3_RUNTIME_BUILTINS_H */ <|endoftext|>
<commit_before>#ifndef K3_RUNTIME_LISTENER_H #define K3_RUNTIME_LISTENER_H #include <atomic> #include <memory> #include <unordered_set> #include <boost/array.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/lock_types.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/thread.hpp> #include <runtime/cpp/Common.hpp> #include <runtime/cpp/Queue.hpp> #include <runtime/cpp/IOHandle.hpp> #include <runtime/cpp/Endpoint.hpp> namespace K3 { using namespace std; using std::atomic_uint; using boost::condition_variable; using boost::lock_guard; using boost::mutex; using boost::unique_lock; //-------------------------------------------- // A reference counter for listener instances. class ListenerCounter : public atomic_uint { public: ListenerCounter() : atomic_uint(0) {} void registerListener() { this->fetch_add(1); } void deregisterListener() { this->fetch_sub(1); } unsigned int operator()() { return this->load(); } }; //--------------------------------------------------------------- // Control data structures for multi-threaded listener execution. class ListenerControl { public: ListenerControl(shared_ptr<mutex> m, shared_ptr<condition_variable> c, shared_ptr<ListenerCounter> i) : listenerCounter(i), msgAvailable(false), msgAvailMutex(m), msgAvailCondition(c) {} // Waits on the message available condition variable. void waitForMessage() { unique_lock<mutex> lock(*msgAvailMutex); while ( !msgAvailable ) { msgAvailCondition->wait(lock); } } // Notifies one waiter on the message available condition variable. void messageAvailable() { { lock_guard<mutex> lock(*msgAvailMutex); msgAvailable = true; } msgAvailCondition->notify_one(); } shared_ptr<ListenerCounter> counter() { return listenerCounter; } shared_ptr<mutex> msgMutex() { return msgAvailMutex; } shared_ptr<condition_variable> msgCondition() { return msgAvailCondition; } protected: shared_ptr<ListenerCounter> listenerCounter; bool msgAvailable; shared_ptr<mutex> msgAvailMutex; shared_ptr<condition_variable> msgAvailCondition; }; //------------------------------- // Listener processor base class. /* class ListenerProcessor : public virtual LogMT { public: ListenerProcessor(shared_ptr<ListenerControl> c, shared_ptr<Endpoint> e) : LogMT("ListenerProcessor"), control(c), endpoint(e) {} // A callable processing function that must be implemented by subclasses. virtual void operator()() = 0; protected: shared_ptr<ListenerControl> control; shared_ptr<Endpoint> endpoint; }; //------------------------------------ // Listener processor implementations. class InternalListenerProcessor : public ListenerProcessor { public: InternalListenerProcessor(shared_ptr<MessageQueues> q, shared_ptr<ListenerControl> c, shared_ptr<Endpoint> e) : ListenerProcessor<Message, EventValue>(c, e), engineQueues(q) {} void operator()() { if ( this->control && this->endpoint && engineQueues ) { // Enqueue from the endpoint's buffer into the engine queues, // and signal message availability. this->endpoint->buffer()->enqueue(engineQueues); this->control->messageAvailable(); } else { this->logAt(boost::log::trivial::error, "Invalid listener processor members"); } } protected: shared_ptr<MessageQueues> engineQueues; }; class ExternalListenerProcessor : public ListenerProcessor { public: ExternalListenerProcessor(shared_ptr<ListenerControl> c, shared_ptr<Endpoint> e) : ListenerProcessor(c, e) {} void operator()() { if ( this->control && this->endpoint ) { // Notify the endpoint's subscribers of a socket data event, // and signal message availability. this->endpoint->subscribers()->notifyEvent(EndpointNotification::SocketData); this->control->messageAvailable(); } else { this->logAt(boost::log::trivial::error, "Invalid listener processor members"); } } }; */ //------------ // Listeners // Abstract base class for listeners. template<typename NContext, typename NEndpoint> class Listener : public virtual LogMT { public: Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<ListenerProcessor> p) : LogMT("Listener_"+n), name(n), ctxt_(ctxt), endpoint_(ep), control_(ctrl), processor_(p) { if ( endpoint_ ) { typename IOHandle::SourceDetails source = ep->handle()->networkSource(); nEndpoint_ = get<0>(source); codec_ = get<1>(source); } } protected: Identifier name; shared_ptr<NContext> ctxt_; shared_ptr<Endpoint> endpoint_; shared_ptr<NEndpoint> nEndpoint_; shared_ptr<Codec> codec_; // We assume this wire description performs the framing necessary // for partial network messages. shared_ptr<ListenerControl> control_; shared_ptr<ListenerProcessor> processor_; }; namespace Asio { using namespace boost::asio; using namespace boost::log; using namespace boost::system; using boost::system::error_code; template<typename NContext, typename NEndpoint> using BaseListener = ::K3::Listener<NContext, NEndpoint>; // TODO: close method, terminating all incoming connections to this acceptor. class Listener : public BaseListener<NContext, NEndpoint>, public basic_lockable_adapter<mutex> { public: typedef basic_lockable_adapter<mutex> llockable; typedef list<shared_ptr<NConnection> > ConnectionList; typedef externally_locked<shared_ptr<ConnectionList>, Listener> ConcurrentConnectionList; Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<ListenerProcessor> p) : BaseListener<NContext, NEndpoint>(n, ctxt, ep, ctrl, p), llockable(), connections_(emptyConnections()) { if ( this->nEndpoint_ && this->codec_ && this->ctxt_ && this->ctxt_->service_threads ) { acceptConnection(); thread_ = shared_ptr<thread>(this->ctxt_->service_threads->create_thread(*(this->ctxt_))); } else { this->logAt(trivial::error, "Invalid listener arguments."); } } protected: shared_ptr<thread> thread_; shared_ptr<externally_locked<shared_ptr<ConnectionList>, Listener> > connections_; //--------- // Helpers. shared_ptr<ConcurrentConnectionList> emptyConnections() { shared_ptr<ConnectionList> l = shared_ptr<ConnectionList>(new ConnectionList()); return shared_ptr<ConcurrentConnectionList>(new ConcurrentConnectionList(*this, l)); } //--------------------- // Endpoint execution. void acceptConnection() { if ( this->endpoint_ && this->codec_ ) { shared_ptr<NConnection> nextConnection = shared_ptr<NConnection>(new NConnection(this->ctxt_)); this->nEndpoint_->acceptor()->async_accept(nextConnection, [=] (const error_code& ec) { if ( !ec ) { registerConnection(nextConnection); } else { this->logAt(trivial::error, string("Failed to accept a connection: ")+ec.message()); } }); acceptConnection(); } else { this->logAt(trivial::error, "Invalid listener endpoint or wire description"); } } void registerConnection(shared_ptr<NConnection> c) { if ( connections_ ) { { strict_lock<Listener> guard(*this); connections_->get(guard)->push_back(c); } // Notify subscribers of socket accept event. if ( this->endpoint_ ) { this->endpoint_->subscribers()->notifyEvent(EndpointNotification::SocketAccept); } // Start connection. receiveMessages(c); } } void deregisterConnection(shared_ptr<NConnection> c) { if ( connections_ ) { strict_lock<Listener> guard(*this); connections_->get(guard)->remove(c); } } void receiveMessages(shared_ptr<NConnection> c) { if ( c && c->socket() && this->processor_ ) { // TODO: extensible buffer size. // We use a local variable for the socket buffer since multiple threads // may invoke this handler simultaneously (i.e. for different connections). typedef boost::array<char, 8192> SocketBuffer; shared_ptr<SocketBuffer> buffer_(new SocketBuffer()); async_read(c->socket(), buffer(buffer_->c_array(), buffer_->size()), [=](const error_code& ec, std::size_t bytes_transferred) { if ( !ec ) { // Unpack buffer, check if it returns a valid message, and pass that to the processor. // We assume the processor notifies subscribers regarding socket data events. shared_ptr<Value> v = this->codec_->unpack(string(buffer_->c_array(), buffer_->size())); if ( v ) { // Add the value to the endpoint's buffer, and invoke the listener processor. //this->endpoint_->buffer()->append(v); this->endpoint_->enqueueToEndpoint(v); // TODO: deprecated with the revised endpoint design. //(*(this->processor_))(); } // Recursive invocation for the next message. receiveMessages(c); } else { deregisterConnection(c); this->logAt(trivial::error, string("Connection error: ")+ec.message()); } }); } else { this->logAt(trivial::error, "Invalid listener connection"); } } }; } namespace Nanomsg { using std::atomic_bool; template<typename NContext, typename NEndpoint> using BaseListener = ::K3::Listener<NContext, NEndpoint>; class Listener : public BaseListener<NContext, NEndpoint> { public: Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<ListenerProcessor> p) : BaseListener<NContext, NEndpoint>(n, ctxt, ep, ctrl, p) { if ( this->nEndpoint_ && this->codec_ && this->ctxt_ && this->ctxt_->listenerThreads ) { // Instantiate a new thread to listen for messages on the nanomsg // socket, tracking it in the network context. terminated_ = false; thread_ = shared_ptr<thread>(this->ctxt_->listenerThreads->create_thread(*this)); } else { this->logAt(trivial::error, "Invalid listener arguments."); } } void operator()() { typedef boost::array<char, 8192> SocketBuffer; SocketBuffer buffer_; while ( !terminated_ ) { // Receive a message. int bytes = nn_recv(this->endpoint_->acceptor(), buffer_.c_array(), buffer_.static_size, 0); if ( bytes >= 0 ) { // Unpack, process. shared_ptr<Value> v = this->codec_->unpack(string(buffer_.c_array(), buffer_.static_size)); if ( v ) { // Simulate accept events for nanomsg. refreshSenders(v); // Add the value to the endpoint's buffer, and invoke the listener processor. this->endpoint_->buffer()->append(v); (*(this->processor_))(); } } else { this->logAt(trivial::error, string("Error receiving message: ") + nn_strerror(nn_errno())); terminate(); } } } void terminate() { terminated_ = true; } protected: shared_ptr<thread> thread_; atomic_bool terminated_; unordered_set<string> senders; // TODO: simulate socket accept notifications. Since nanomsg is not connection-oriented, // we simulate connections based on the arrival of messages from unseen addresses. // TODO: break assumption that value is a Message. void refreshSenders(shared_ptr<Value> v) { /* if ( senders.find(v->address()) == senders.end() ) { senders.insert(v->address()); endpoint_->subscribers()->notifyEvent(EndpointNotification::SocketAccept); } // TODO: remove addresses from the recipients pool based on a timeout. // TODO: time out stale senders. */ } }; } } #endif <commit_msg>Update ListenerProcessors to use codecs.<commit_after>#ifndef K3_RUNTIME_LISTENER_H #define K3_RUNTIME_LISTENER_H #include <atomic> #include <memory> #include <unordered_set> #include <boost/array.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/lock_types.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/thread.hpp> #include <runtime/cpp/Common.hpp> #include <runtime/cpp/Queue.hpp> #include <runtime/cpp/IOHandle.hpp> #include <runtime/cpp/Endpoint.hpp> namespace K3 { using namespace std; using std::atomic_uint; using boost::condition_variable; using boost::lock_guard; using boost::mutex; using boost::unique_lock; //-------------------------------------------- // A reference counter for listener instances. class ListenerCounter : public atomic_uint { public: ListenerCounter() : atomic_uint(0) {} void registerListener() { this->fetch_add(1); } void deregisterListener() { this->fetch_sub(1); } unsigned int operator()() { return this->load(); } }; //--------------------------------------------------------------- // Control data structures for multi-threaded listener execution. class ListenerControl { public: ListenerControl(shared_ptr<mutex> m, shared_ptr<condition_variable> c, shared_ptr<ListenerCounter> i) : listenerCounter(i), msgAvailable(false), msgAvailMutex(m), msgAvailCondition(c) {} // Waits on the message available condition variable. void waitForMessage() { unique_lock<mutex> lock(*msgAvailMutex); while ( !msgAvailable ) { msgAvailCondition->wait(lock); } } // Notifies one waiter on the message available condition variable. void messageAvailable() { { lock_guard<mutex> lock(*msgAvailMutex); msgAvailable = true; } msgAvailCondition->notify_one(); } shared_ptr<ListenerCounter> counter() { return listenerCounter; } shared_ptr<mutex> msgMutex() { return msgAvailMutex; } shared_ptr<condition_variable> msgCondition() { return msgAvailCondition; } protected: shared_ptr<ListenerCounter> listenerCounter; bool msgAvailable; shared_ptr<mutex> msgAvailMutex; shared_ptr<condition_variable> msgAvailCondition; }; // Listener Processors // ------------------- // // These are callbacks which listeners register with their endpoints, to handle asynchronous // notification. class ListenerProcessor: public virtual LogMT { public: ListenerProcessor(shared_ptr<ListenerControl> c, shared_ptr<Endpoint> e): control(c), endpoint(e) {} virtual void operator()() = 0; private: shared_ptr<ListenerControl> control; shared_ptr<Endpoint> endpoint; }; // Internal Listener Processors are intended for internal endpoints, namely those whose messages // themselves contain dispatch information. class InternalListenerProcessor: public ListenerProcessor { public: InternalListenerProcessor( shared_ptr<ListenerControl> c, shared_ptr<Endpoint> e, shared_ptr<MessageQueues> q, shared_ptr<InternalCodec> d ): ListenerProcessor(c, e), engine_queues(q), codec(d) {} void operator()(shared_ptr<Value> payload) { this->endpoint->subscribers()->notifyEvent(EndpointNotification::SocketData, payload); engine_queues->enqueue(codec->read_message(*payload)); } private: shared_ptr<MessageQueues> engine_queues; shared_ptr<InternalCodec> codec; }; // ExternalListenerPrc class ExternalListenerProcessor: public ListenerProcessor { public: void operator()(shared_ptr<Value> payload) { if (this->control && this->endpoint) { this->endpoint->subscribers()->notifyEvent(EndpointNotification::SocketData, payload); this->control->messageAvailable(); } } }; //------------ // Listeners // Abstract base class for listeners. template<typename NContext, typename NEndpoint> class Listener : public virtual LogMT { public: Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<ListenerProcessor> p) : LogMT("Listener_"+n), name(n), ctxt_(ctxt), endpoint_(ep), control_(ctrl), processor_(p) { if ( endpoint_ ) { typename IOHandle::SourceDetails source = ep->handle()->networkSource(); nEndpoint_ = get<0>(source); codec_ = get<1>(source); } } protected: Identifier name; shared_ptr<NContext> ctxt_; shared_ptr<Endpoint> endpoint_; shared_ptr<NEndpoint> nEndpoint_; shared_ptr<Codec> codec_; // We assume this wire description performs the framing necessary // for partial network messages. shared_ptr<ListenerControl> control_; shared_ptr<ListenerProcessor> processor_; }; namespace Asio { using namespace boost::asio; using namespace boost::log; using namespace boost::system; using boost::system::error_code; using boost::thread; template<typename NContext, typename NEndpoint> using BaseListener = ::K3::Listener<NContext, NEndpoint>; // TODO: close method, terminating all incoming connections to this acceptor. class Listener : public BaseListener<NContext, NEndpoint>, public basic_lockable_adapter<mutex> { public: typedef basic_lockable_adapter<mutex> llockable; typedef list<shared_ptr<NConnection> > ConnectionList; typedef externally_locked<shared_ptr<ConnectionList>, Listener> ConcurrentConnectionList; Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<ListenerProcessor> p) : BaseListener<NContext, NEndpoint>(n, ctxt, ep, ctrl, p), llockable(), connections_(emptyConnections()) { if ( this->nEndpoint_ && this->codec_ && this->ctxt_ && this->ctxt_->service_threads ) { acceptConnection(); thread_ = shared_ptr<thread>(this->ctxt_->service_threads->create_thread(*(this->ctxt_))); } else { this->logAt(trivial::error, "Invalid listener arguments."); } } protected: shared_ptr<thread> thread_; shared_ptr<externally_locked<shared_ptr<ConnectionList>, Listener> > connections_; //--------- // Helpers. shared_ptr<ConcurrentConnectionList> emptyConnections() { shared_ptr<ConnectionList> l = shared_ptr<ConnectionList>(new ConnectionList()); return shared_ptr<ConcurrentConnectionList>(new ConcurrentConnectionList(*this, l)); } //--------------------- // Endpoint execution. void acceptConnection() { if ( this->endpoint_ && this->codec_ ) { shared_ptr<NConnection> nextConnection = shared_ptr<NConnection>(new NConnection(this->ctxt_)); this->nEndpoint_->acceptor()->async_accept(nextConnection, [=] (const error_code& ec) { if ( !ec ) { registerConnection(nextConnection); } else { this->logAt(trivial::error, string("Failed to accept a connection: ")+ec.message()); } }); acceptConnection(); } else { this->logAt(trivial::error, "Invalid listener endpoint or wire description"); } } void registerConnection(shared_ptr<NConnection> c) { if ( connections_ ) { { strict_lock<Listener> guard(*this); connections_->get(guard)->push_back(c); } // Notify subscribers of socket accept event. if ( this->endpoint_ ) { this->endpoint_->subscribers()->notifyEvent(EndpointNotification::SocketAccept); } // Start connection. receiveMessages(c); } } void deregisterConnection(shared_ptr<NConnection> c) { if ( connections_ ) { strict_lock<Listener> guard(*this); connections_->get(guard)->remove(c); } } void receiveMessages(shared_ptr<NConnection> c) { if ( c && c->socket() && this->processor_ ) { // TODO: extensible buffer size. // We use a local variable for the socket buffer since multiple threads // may invoke this handler simultaneously (i.e. for different connections). typedef boost::array<char, 8192> SocketBuffer; shared_ptr<SocketBuffer> buffer_(new SocketBuffer()); async_read(c->socket(), buffer(buffer_->c_array(), buffer_->size()), [=](const error_code& ec, std::size_t bytes_transferred) { if ( !ec ) { // Unpack buffer, check if it returns a valid message, and pass that to the processor. // We assume the processor notifies subscribers regarding socket data events. shared_ptr<Value> v = this->codec_->encode(string(buffer_->c_array(), buffer_->size())); if ( v ) { // Add the value to the endpoint's buffer, and invoke the listener processor. //this->endpoint_->buffer()->append(v); this->endpoint_->enqueueToEndpoint(v); // TODO: deprecated with the revised endpoint design. //(*(this->processor_))(); } // Recursive invocation for the next message. receiveMessages(c); } else { deregisterConnection(c); this->logAt(trivial::error, string("Connection error: ")+ec.message()); } }); } else { this->logAt(trivial::error, "Invalid listener connection"); } } }; } namespace Nanomsg { using std::atomic_bool; template<typename NContext, typename NEndpoint> using BaseListener = ::K3::Listener<NContext, NEndpoint>; class Listener : public BaseListener<NContext, NEndpoint> { public: Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<ListenerProcessor> p) : BaseListener<NContext, NEndpoint>(n, ctxt, ep, ctrl, p) { if ( this->nEndpoint_ && this->codec_ && this->ctxt_ && this->ctxt_->listenerThreads ) { // Instantiate a new thread to listen for messages on the nanomsg // socket, tracking it in the network context. terminated_ = false; thread_ = shared_ptr<thread>(this->ctxt_->listenerThreads->create_thread(*this)); } else { this->logAt(trivial::error, "Invalid listener arguments."); } } void operator()() { typedef boost::array<char, 8192> SocketBuffer; SocketBuffer buffer_; while ( !terminated_ ) { // Receive a message. int bytes = nn_recv(this->endpoint_->acceptor(), buffer_.c_array(), buffer_.static_size, 0); if ( bytes >= 0 ) { // Unpack, process. shared_ptr<Value> v = this->codec_->unpack(string(buffer_.c_array(), buffer_.static_size)); if ( v ) { // Simulate accept events for nanomsg. refreshSenders(v); // Add the value to the endpoint's buffer, and invoke the listener processor. this->endpoint_->buffer()->append(v); (*(this->processor_))(); } } else { this->logAt(trivial::error, string("Error receiving message: ") + nn_strerror(nn_errno())); terminate(); } } } void terminate() { terminated_ = true; } protected: shared_ptr<thread> thread_; atomic_bool terminated_; unordered_set<string> senders; // TODO: simulate socket accept notifications. Since nanomsg is not connection-oriented, // we simulate connections based on the arrival of messages from unseen addresses. // TODO: break assumption that value is a Message. void refreshSenders(shared_ptr<Value> v) { /* if ( senders.find(v->address()) == senders.end() ) { senders.insert(v->address()); endpoint_->subscribers()->notifyEvent(EndpointNotification::SocketAccept); } // TODO: remove addresses from the recipients pool based on a timeout. // TODO: time out stale senders. */ } }; } } #endif // vim:set sw=2 ts=2 sts=2: <|endoftext|>
<commit_before>#include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; int main() { vector<int> vec1{0, 1, 1, 2}; vector<int> vec2{0, 1, 1, 2, 3, 5, 8}; auto size = vec1.size() < vec2.size() ? vec1.size() : vec2.size(); for (decltype(vec1.size()) i = 0; i != size; ++i) { if (vec1[i] != vec2[i]) { cout << "false" << endl; break; } if (i == size - 1) cout << "true" << endl; } return 0; } <commit_msg>Update ex5_17.cpp<commit_after>#include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; int main() { vector<int> vec1{0, 1, 1, 2}; vector<int> vec2{0, 1, 1, 2, 3, 5, 8}; auto size = (vec1.size() < vec2.size()) ? vec1.size() : vec2.size(); for (decltype(vec1.size()) i = 0; i != size; ++i) { if (vec1[i] != vec2[i]) { cout << "false" << endl; break; } if (i == size - 1) cout << "true" << endl; } return 0; } <|endoftext|>
<commit_before><commit_msg>account for zero radius in parallel plane check<commit_after><|endoftext|>
<commit_before> #include <gloperate-qt/viewer/UpdateManager.h> #include <QTime> #include <gloperate/viewer/ViewerContext.h> #include <globjects/base/baselogging.h> namespace gloperate_qt { UpdateManager::UpdateManager(gloperate::ViewerContext * viewerContext) : m_viewerContext(viewerContext) { // Connect update timer QObject::connect( &m_timer, &QTimer::timeout, this, &UpdateManager::onTimer ); // Setup timer m_timer.setSingleShot(true); m_timer.start(0); // Start time measurement m_time.start(); } UpdateManager::~UpdateManager() { } void UpdateManager::wakeTimer() { m_timer.start(0); } void UpdateManager::onTimer() { // Get time delta float delta = m_time.elapsed() / 1000.0f; m_time.restart(); // Update timing if (m_viewerContext->update(delta)) { m_timer.start(0); } } } // namespace gloperate_qt <commit_msg>Reverse timer logic in qt/qtquick-backend<commit_after> #include <gloperate-qt/viewer/UpdateManager.h> #include <QTime> #include <gloperate/viewer/ViewerContext.h> #include <globjects/base/baselogging.h> namespace gloperate_qt { UpdateManager::UpdateManager(gloperate::ViewerContext * viewerContext) : m_viewerContext(viewerContext) { // Connect update timer QObject::connect( &m_timer, &QTimer::timeout, this, &UpdateManager::onTimer ); // Setup timer m_timer.setSingleShot(false); m_timer.start(0); // Start time measurement m_time.start(); } UpdateManager::~UpdateManager() { } void UpdateManager::wakeTimer() { m_timer.start(0); } void UpdateManager::onTimer() { // Get time delta float delta = m_time.elapsed() / 1000.0f; m_time.restart(); // Update timing if (!m_viewerContext->update(delta)) { m_timer.stop(); } } } // namespace gloperate_qt <|endoftext|>
<commit_before>#include "PositionModule.hpp" #include <assert.h> #include <sys/stat.h> #include <errno.h> #include <stdlib.h> #include <string> #include <algorithm> #include <iostream> #include <ros/console.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> #include "sensor_msgs/Image.h" #include "api_application/Ping.h" #include "api_application/Announce.h" #include "../matlab/Vector.h" // Use this to test if images are saved properly, when you only have one camera. //#define SINGLE_CAMERA_CALIBRATION PositionModule::PositionModule(IPositionReceiver* receiver) : pictureCache(50), // Assume we never have 50 or more modules running on the network. pictureTimes(50) { assert(receiver != 0); this->receiver = receiver; ROS_DEBUG("Initializing PositionModule"); _isInitialized = true; isCalibrating = false; isRunning = false; ros::NodeHandle n; this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4); this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4); this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this); this->systemSubscriber = n.subscribe("System", 4, &PositionModule::systemCallback, this); this->rawPositionSubscriber = n.subscribe("RawPosition", 1024, &PositionModule::rawPositionCallback, this); this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this); this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this); this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this); // Advertise myself to API ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("announce"); api_application::Announce announce; announce.request.type = 3; // 3 means position module if (announceClient.call(announce)) { rosId = announce.response.id; if (rosId == ~0 /* -1 */) { ROS_ERROR("Error! Got id -1"); _isInitialized = false; } else { ROS_INFO("Position module successfully announced. Got id %d", rosId); } } else { ROS_ERROR("Error! Could not announce myself to API!"); _isInitialized = false; } msg = new KitrokopterMessages(rosId); if (_isInitialized) { ROS_DEBUG("PositionModule initialized"); } else { ROS_ERROR("Could not initialize PositionModule!"); } } PositionModule::~PositionModule() { msg->~KitrokopterMessages(); // TODO: Free picture cache. ROS_DEBUG("PositionModule destroyed"); } // Service bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res) { res.ok = !isCalibrating; if (!isCalibrating) { ROS_INFO("Starting multi camera calibration process"); system("rm -rf /tmp/calibrationImages/*"); setPictureSendingActivated(true); calibrationPictureCount = 0; boardSize = cv::Size(req.chessboardWidth, req.chessboardHeight); realSize = cv::Size(req.chessboardRealWidth, req.chessboardRealHeight); } isCalibrating = true; return true; } // Service bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res) { ROS_DEBUG("Taking calibration picture. Have %ld cameras.", camNoToNetId.size()); pictureCacheMutex.lock(); // Build net id -> cam no map. if (camNoToNetId.size() != netIdToCamNo.size()) { // If already built, there are already images on the disk with wrong ids, so return an error. if (netIdToCamNo.size() != 0) { ROS_ERROR("Got new cameras after taking first calibration picture!"); return false; } std::sort(camNoToNetId.begin(), camNoToNetId.end()); netIdToCamNo.clear(); for (int i = 0; i < camNoToNetId.size(); i++) { netIdToCamNo[camNoToNetId[i]] = i; } ROS_INFO("Got %ld cameras", netIdToCamNo.size()); } int id = 0; std::map<int, cv::Mat*> pictureMap; int goodPictures = 0; for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++, id++) { if (*it != 0) { std::vector<cv::Point2f> corners; bool foundAllCorners = cv::findChessboardCorners(**it, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE); if (!foundAllCorners) { ROS_INFO("Took bad picture (id %d)", id); } else { ROS_INFO("Took good picture (id %d)", id); goodPictures++; } pictureMap[id] = *it; // Remove image from image cache. *it = 0; } } pictureCacheMutex.unlock(); #ifdef SINGLE_CAMERA_CALIBRATION if (goodPictures >= 1) { #else if (goodPictures >= 2) { #endif // Create directory for images. int error = mkdir("/tmp/calibrationImages", 0777); if (error != 0 && errno != EEXIST) { ROS_ERROR("Could not create directory for calibration images (/tmp/calibrationImages): %d", errno); // Delete images. for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) { delete it->second; } return false; } error = mkdir("/tmp/calibrationResult", 0777); if (error != 0 && errno != EEXIST) { ROS_ERROR("Could not create directory for calibration images (/tmp/calibrationResult): %d", errno); // Delete images. for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) { delete it->second; } return false; } for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) { std::stringstream ss; ss << "/tmp/calibrationImages/cam" << netIdToCamNo[it->first] << "_image" << calibrationPictureCount << ".png"; // Save picture on disk for amcctoolbox. std::cout << "Saving picture: " << cv::imwrite(ss.str(), *(it->second)) << std::endl; sensor_msgs::Image img; img.width = 640; img.height = 480; img.step = 3 * 640; img.data.reserve(img.step * img.height); for (int i = 0; i < 640 * 480 * 3; i++) { img.data[i] = it->second->data[i]; } res.images.push_back(img); res.ids.push_back(it->first); delete it->second; } calibrationPictureCount++; } return true; } // Service bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res) { /*if (!isCalibrating) { ROS_ERROR("Cannot calculate calibration! Start calibration first!"); return false; } if (netIdToCamNo.size() < 2) { ROS_ERROR("Have not enough images for calibration (Have %ld)!", netIdToCamNo.size()); }*/ ROS_INFO("Calculating multi camera calibration. This could take up to 2 hours"); ChessboardData data(boardSize.width, boardSize.height, realSize.width, realSize.height); pictureCacheMutex.lock(); int camNumber = 3; //camNoToNetId.size(); pictureCacheMutex.unlock(); // Delete old calibration results. system("rm -rf /tmp/calibrationResult/*"); bool ok = tracker.calibrate(&data, camNumber); if (ok) { ROS_INFO("Finished multi camera calibration"); } else { ROS_ERROR("Calibration failed!"); } isCalibrating = false; return ok; } // Topic void PositionModule::pictureCallback(const camera_application::Picture &msg) { assert(msg.ID < 50); pictureCacheMutex.lock(); bool idKnown = false; // Insert camera id, if not already there. for (int i = 0; i < camNoToNetId.size(); i++) { if (camNoToNetId[i] == msg.ID) { idKnown = true; break; } } if (!idKnown) { camNoToNetId.push_back(msg.ID); } if (isCalibrating) { // Will crash here, if more than 49 modules are used. if (pictureCache[msg.ID] != 0) { delete pictureCache[msg.ID]; pictureCache[msg.ID] = 0; } cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3); for (int i = 0; i < 640 * 480 * 3; i++) { image->data[i] = msg.image[i]; } pictureCache[msg.ID] = image; pictureTimes[msg.ID] = msg.timestamp; } pictureCacheMutex.unlock(); } // Topic void PositionModule::systemCallback(const api_application::System &msg) { isRunning = msg.command == 1; if (isRunning) { ROS_INFO("Tracking started"); } else { ROS_INFO("Tracking stopped"); } if (!isRunning) { ros::shutdown(); } } // Topic void PositionModule::rawPositionCallback(const camera_application::RawPosition &msg) { // TODO: Calculate position in our coordinate system. // TODO: Is this coordinate change correct for amcctoolbox? Vector cameraVector(msg.xPosition, msg.yPosition, 1); ROS_DEBUG("msg.ID: %d netIdToCamNo[msg.ID]: %d msg.quadcopterId: %d", msg.ID, netIdToCamNo[msg.ID], msg.quadcopterId); Vector result = tracker.updatePosition(cameraVector, netIdToCamNo[msg.ID], msg.quadcopterId); std::vector<Vector> positions; std::vector<int> ids; std::vector<int> updates; positions.push_back(result); ids.push_back(msg.quadcopterId); updates.push_back(1); if (result.isValid()) { receiver->updatePositions(positions, ids, updates); } else { ROS_DEBUG("Not enough information to get position of quadcopter %d", msg.quadcopterId); } } void PositionModule::setPictureSendingActivated(bool activated) { camera_application::PictureSendingActivation msg; msg.ID = 0; msg.active = activated; pictureSendingActivationPublisher.publish(msg); } void PositionModule::sendPing() { api_application::Ping msg; msg.ID = rosId; pingPublisher.publish(msg); } bool PositionModule::isInitialized() { return _isInitialized; }<commit_msg>Made it unnecessary to call start calibration<commit_after>#include "PositionModule.hpp" #include <assert.h> #include <sys/stat.h> #include <errno.h> #include <stdlib.h> #include <string> #include <algorithm> #include <iostream> #include <ros/console.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> #include "sensor_msgs/Image.h" #include "api_application/Ping.h" #include "api_application/Announce.h" #include "../matlab/Vector.h" // Use this to test if images are saved properly, when you only have one camera. //#define SINGLE_CAMERA_CALIBRATION PositionModule::PositionModule(IPositionReceiver* receiver) : pictureCache(50), // Assume we never have 50 or more modules running on the network. pictureTimes(50) { assert(receiver != 0); this->receiver = receiver; ROS_DEBUG("Initializing PositionModule"); _isInitialized = true; isCalibrating = false; isRunning = false; ros::NodeHandle n; this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4); this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4); this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this); this->systemSubscriber = n.subscribe("System", 4, &PositionModule::systemCallback, this); this->rawPositionSubscriber = n.subscribe("RawPosition", 1024, &PositionModule::rawPositionCallback, this); this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this); this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this); this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this); // Advertise myself to API ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("announce"); api_application::Announce announce; announce.request.type = 3; // 3 means position module if (announceClient.call(announce)) { rosId = announce.response.id; if (rosId == ~0 /* -1 */) { ROS_ERROR("Error! Got id -1"); _isInitialized = false; } else { ROS_INFO("Position module successfully announced. Got id %d", rosId); } } else { ROS_ERROR("Error! Could not announce myself to API!"); _isInitialized = false; } msg = new KitrokopterMessages(rosId); if (_isInitialized) { ROS_DEBUG("PositionModule initialized"); } else { ROS_ERROR("Could not initialize PositionModule!"); } } PositionModule::~PositionModule() { msg->~KitrokopterMessages(); // TODO: Free picture cache. ROS_DEBUG("PositionModule destroyed"); } // Service bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res) { res.ok = !isCalibrating; if (!isCalibrating) { ROS_INFO("Starting multi camera calibration process"); system("rm -rf /tmp/calibrationImages/*"); setPictureSendingActivated(true); calibrationPictureCount = 0; boardSize = cv::Size(req.chessboardWidth, req.chessboardHeight); realSize = cv::Size(req.chessboardRealWidth, req.chessboardRealHeight); } isCalibrating = true; return true; } // Service bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res) { ROS_DEBUG("Taking calibration picture. Have %ld cameras.", camNoToNetId.size()); pictureCacheMutex.lock(); // Build net id -> cam no map. if (camNoToNetId.size() != netIdToCamNo.size()) { // If already built, there are already images on the disk with wrong ids, so return an error. if (netIdToCamNo.size() != 0) { ROS_ERROR("Got new cameras after taking first calibration picture!"); return false; } std::sort(camNoToNetId.begin(), camNoToNetId.end()); netIdToCamNo.clear(); for (int i = 0; i < camNoToNetId.size(); i++) { netIdToCamNo[camNoToNetId[i]] = i; } ROS_INFO("Got %ld cameras", netIdToCamNo.size()); } int id = 0; std::map<int, cv::Mat*> pictureMap; int goodPictures = 0; for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++, id++) { if (*it != 0) { std::vector<cv::Point2f> corners; bool foundAllCorners = cv::findChessboardCorners(**it, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE); if (!foundAllCorners) { ROS_INFO("Took bad picture (id %d)", id); } else { ROS_INFO("Took good picture (id %d)", id); goodPictures++; } pictureMap[id] = *it; // Remove image from image cache. *it = 0; } } pictureCacheMutex.unlock(); #ifdef SINGLE_CAMERA_CALIBRATION if (goodPictures >= 1) { #else if (goodPictures >= 2) { #endif // Create directory for images. int error = mkdir("/tmp/calibrationImages", 0777); if (error != 0 && errno != EEXIST) { ROS_ERROR("Could not create directory for calibration images (/tmp/calibrationImages): %d", errno); // Delete images. for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) { delete it->second; } return false; } error = mkdir("/tmp/calibrationResult", 0777); if (error != 0 && errno != EEXIST) { ROS_ERROR("Could not create directory for calibration images (/tmp/calibrationResult): %d", errno); // Delete images. for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) { delete it->second; } return false; } for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) { std::stringstream ss; ss << "/tmp/calibrationImages/cam" << netIdToCamNo[it->first] << "_image" << calibrationPictureCount << ".png"; // Save picture on disk for amcctoolbox. std::cout << "Saving picture: " << cv::imwrite(ss.str(), *(it->second)) << std::endl; sensor_msgs::Image img; img.width = 640; img.height = 480; img.step = 3 * 640; img.data.reserve(img.step * img.height); for (int i = 0; i < 640 * 480 * 3; i++) { img.data[i] = it->second->data[i]; } res.images.push_back(img); res.ids.push_back(it->first); delete it->second; } calibrationPictureCount++; } return true; } // Service bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res) { /*if (!isCalibrating) { ROS_ERROR("Cannot calculate calibration! Start calibration first!"); return false; } if (netIdToCamNo.size() < 2) { ROS_ERROR("Have not enough images for calibration (Have %ld)!", netIdToCamNo.size()); }*/ ROS_INFO("Calculating multi camera calibration. This could take up to 2 hours"); // ChessboardData data(boardSize.width, boardSize.height, realSize.width, realSize.height); ChessboardData data(7, 7, 57, 57); pictureCacheMutex.lock(); int camNumber = 3; //camNoToNetId.size(); pictureCacheMutex.unlock(); // Delete old calibration results. system("rm -rf /tmp/calibrationResult/*"); bool ok = tracker.calibrate(&data, camNumber); if (ok) { ROS_INFO("Finished multi camera calibration"); } else { ROS_ERROR("Calibration failed!"); } isCalibrating = false; return ok; } // Topic void PositionModule::pictureCallback(const camera_application::Picture &msg) { assert(msg.ID < 50); pictureCacheMutex.lock(); bool idKnown = false; // Insert camera id, if not already there. for (int i = 0; i < camNoToNetId.size(); i++) { if (camNoToNetId[i] == msg.ID) { idKnown = true; break; } } if (!idKnown) { camNoToNetId.push_back(msg.ID); } if (isCalibrating) { // Will crash here, if more than 49 modules are used. if (pictureCache[msg.ID] != 0) { delete pictureCache[msg.ID]; pictureCache[msg.ID] = 0; } cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3); for (int i = 0; i < 640 * 480 * 3; i++) { image->data[i] = msg.image[i]; } pictureCache[msg.ID] = image; pictureTimes[msg.ID] = msg.timestamp; } pictureCacheMutex.unlock(); } // Topic void PositionModule::systemCallback(const api_application::System &msg) { isRunning = msg.command == 1; if (isRunning) { ROS_INFO("Tracking started"); } else { ROS_INFO("Tracking stopped"); } if (!isRunning) { ros::shutdown(); } } // Topic void PositionModule::rawPositionCallback(const camera_application::RawPosition &msg) { // TODO: Calculate position in our coordinate system. // TODO: Is this coordinate change correct for amcctoolbox? Vector cameraVector(msg.xPosition, msg.yPosition, 1); ROS_DEBUG("msg.ID: %d netIdToCamNo[msg.ID]: %d msg.quadcopterId: %d", msg.ID, netIdToCamNo[msg.ID], msg.quadcopterId); Vector result = tracker.updatePosition(cameraVector, netIdToCamNo[msg.ID], msg.quadcopterId); std::vector<Vector> positions; std::vector<int> ids; std::vector<int> updates; positions.push_back(result); ids.push_back(msg.quadcopterId); updates.push_back(1); if (result.isValid()) { receiver->updatePositions(positions, ids, updates); } else { ROS_DEBUG("Not enough information to get position of quadcopter %d", msg.quadcopterId); } } void PositionModule::setPictureSendingActivated(bool activated) { camera_application::PictureSendingActivation msg; msg.ID = 0; msg.active = activated; pictureSendingActivationPublisher.publish(msg); } void PositionModule::sendPing() { api_application::Ping msg; msg.ID = rosId; pingPublisher.publish(msg); } bool PositionModule::isInitialized() { return _isInitialized; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsCacheCompactor.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 06:09:56 $ * * 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 SD_SLIDESORTER_CACHE_COMPACTOR_HXX #define SD_SLIDESORTER_CACHE_COMPACTOR_HXX #include <sal/types.h> namespace sd { namespace slidesorter { namespace cache { class BitmapCache; /** This trivial compaction operation does not do anything. It especially does not remove or scale down older bitmaps. Use this operator for debugging, experiments, or when memory consumption is of no concern. */ class NoCompaction { public: void operator() (BitmapCache& rCache, sal_Int32 nMaximalSize); }; /** Make room for new bitmaps by removing seldomly used ones. */ class CompactionByRemoval { public: void operator() (BitmapCache& rCache, sal_Int32 nMaximalSize); }; /** Make room for new new bitmaps by reducing the resolution of old ones. */ class CompactionByReduction { public: void operator() (BitmapCache& rCache, sal_Int32 nMaximalSize); }; } } } // end of namespace ::sd::slidesorter::cache #endif <commit_msg>INTEGRATION: CWS impress69 (1.2.434); FILE MERGED 2005/10/14 11:01:29 af 1.2.434.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/21 15:49:25 af 1.2.434.1: #i54916# Support for bitmap compression.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsCacheCompactor.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-10-24 07:40:12 $ * * 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 SD_SLIDESORTER_CACHE_COMPACTOR_HXX #define SD_SLIDESORTER_CACHE_COMPACTOR_HXX #include <sal/types.h> #include <vcl/timer.hxx> #include <memory> namespace sd { namespace slidesorter { namespace cache { class BitmapCache; class BitmapCompressor; /** This is an interface class whose implementations are created via the Create() factory method. */ class CacheCompactor { public: virtual ~CacheCompactor (void) {}; /** Create a new instance of the CacheCompactor interface class. The type of compaction algorithm used depends on values from the configuration: the SlideSorter/PreviewCache/CompactionPolicy property of the Impress.xcs file currently supports the values "None" and "Compress". With the later the CompressionPolicy property is evaluated which implementation of the BitmapCompress interface class to use as bitmap compressor. @param rCache The bitmap cache on which to operate. @param nMaximalCacheSize The total number of bytes the off-screen bitmaps in the cache may have. When the Run() method is (indirectly) called the compactor tries to reduce that summed size of off-screen bitmaps under this number. However, it is not guaranteed that this works in all cases. */ static ::std::auto_ptr<CacheCompactor> Create ( BitmapCache& rCache, sal_Int32 nMaximalCacheSize); /** Request a compaction of the off-screen previews in the bitmap cache. This calls via a timer the Run() method. */ virtual void RequestCompaction (void); protected: BitmapCache& mrCache; sal_Int32 mnMaximalCacheSize; CacheCompactor( BitmapCache& rCache, sal_Int32 nMaximalCacheSize); /** This method actually tries to reduce the total number of bytes used by the off-screen preview bitmaps. */ virtual void Run (void) = 0; private: /** This timer is used to collect calles to RequestCompaction() and eventually call Run(). */ Timer maCompactionTimer; bool mbIsCompactionRunning; DECL_LINK(CompactionCallback, Timer*); }; } } } // end of namespace ::sd::slidesorter::cache #endif <|endoftext|>
<commit_before>#include "road_graph_builder.hpp" #include "../../base/logging.hpp" #include "../../std/algorithm.hpp" using namespace routing; namespace routing_test { void RoadInfo::Swap(RoadInfo & r) { m_points.swap(r.m_points); std::swap(m_speedMS, r.m_speedMS); std::swap(m_bidirectional, r.m_bidirectional); } void RoadGraphMockSource::AddRoad(RoadInfo & rd) { /// @todo Do ASSERT for RoadInfo params. uint32_t const roadId = m_roads.size(); if (rd.m_points.size() < 2) { LOG(LERROR, ("Empty road")); return; } size_t const numSegments = rd.m_points.size() - 1; ASSERT_GREATER(numSegments, 0, ()); for (size_t segId = 0; segId < numSegments; ++segId) { PossibleTurn t; t.m_startPoint = rd.m_points.front(); t.m_endPoint = rd.m_points.back(); t.m_speed = rd.m_speedMS; t.m_pos = RoadPos(roadId, true /* forward */, segId, rd.m_points[segId + 1] /* segEndPoint */); m_turns[t.m_pos.GetSegEndpoint()].push_back(t); if (rd.m_bidirectional) { t.m_pos = RoadPos(roadId, false /* forward */, segId, rd.m_points[segId] /* segEndPoint */); m_turns[t.m_pos.GetSegEndpoint()].push_back(t); } } m_roads.push_back(RoadInfo()); m_roads.back().Swap(rd); } void RoadGraphMockSource::GetPossibleTurns(RoadPos const & pos, TurnsVectorT & turns, bool /*noOptimize = true*/) { uint32_t const fID = pos.GetFeatureId(); ASSERT_LESS(fID, m_roads.size(), ()); vector<m2::PointD> const & points = m_roads[fID].m_points; int const inc = pos.IsForward() ? -1 : 1; int startID = pos.GetSegId(); int const count = static_cast<int>(points.size()); if (!pos.IsForward()) ++startID; double const speed = m_roads[fID].m_speedMS; double distance = 0.0; double time = 0.0; for (int i = startID; i >= 0 && i < count; i += inc) { double const len = points[i - inc].Length(points[i]); distance += len; time += len / speed; TurnsMapT::const_iterator j = m_turns.find(points[i]); if (j != m_turns.end()) { vector<PossibleTurn> const & vec = j->second; for (size_t k = 0; k < vec.size(); ++k) { if (vec[k].m_pos.GetFeatureId() != pos.GetFeatureId() || vec[k].m_pos.IsForward() == pos.IsForward()) { PossibleTurn t = vec[k]; t.m_metersCovered = distance; t.m_secondsCovered = time; turns.push_back(t); } } } } } void RoadGraphMockSource::ReconstructPath(RoadPosVectorT const &, routing::Route &) {} void InitRoadGraphMockSourceWithTest1(RoadGraphMockSource & src) { { RoadInfo ri; ri.m_bidirectional = true; ri.m_speedMS = 40; ri.m_points.push_back(m2::PointD(0, 0)); ri.m_points.push_back(m2::PointD(5, 0)); ri.m_points.push_back(m2::PointD(10, 0)); ri.m_points.push_back(m2::PointD(15, 0)); ri.m_points.push_back(m2::PointD(20, 0)); src.AddRoad(ri); } { RoadInfo ri; ri.m_bidirectional = true; ri.m_speedMS = 40; ri.m_points.push_back(m2::PointD(10, -10)); ri.m_points.push_back(m2::PointD(10, -5)); ri.m_points.push_back(m2::PointD(10, 0)); ri.m_points.push_back(m2::PointD(10, 5)); ri.m_points.push_back(m2::PointD(10, 10)); src.AddRoad(ri); } { RoadInfo ri; ri.m_bidirectional = true; ri.m_speedMS = 40; ri.m_points.push_back(m2::PointD(15, -5)); ri.m_points.push_back(m2::PointD(15, 0)); src.AddRoad(ri); } { RoadInfo ri; ri.m_bidirectional = true; ri.m_speedMS = 40; ri.m_points.push_back(m2::PointD(20, 0)); ri.m_points.push_back(m2::PointD(25, 5)); ri.m_points.push_back(m2::PointD(15, 5)); ri.m_points.push_back(m2::PointD(20, 0)); src.AddRoad(ri); } } void InitRoadGraphMockSourceWithTest2(RoadGraphMockSource & graph) { RoadInfo ri0; ri0.m_bidirectional = true; ri0.m_speedMS = 40; ri0.m_points.push_back(m2::PointD(0, 0)); ri0.m_points.push_back(m2::PointD(10, 0)); ri0.m_points.push_back(m2::PointD(25, 0)); ri0.m_points.push_back(m2::PointD(35, 0)); ri0.m_points.push_back(m2::PointD(70, 0)); ri0.m_points.push_back(m2::PointD(80, 0)); RoadInfo ri1; ri1.m_bidirectional = false; ri1.m_speedMS = 40; ri1.m_points.push_back(m2::PointD(0, 0)); ri1.m_points.push_back(m2::PointD(5, 10)); ri1.m_points.push_back(m2::PointD(5, 40)); RoadInfo ri2; ri2.m_bidirectional = false; ri2.m_speedMS = 40; ri2.m_points.push_back(m2::PointD(12, 25)); ri2.m_points.push_back(m2::PointD(10, 10)); ri2.m_points.push_back(m2::PointD(10, 0)); RoadInfo ri3; ri3.m_bidirectional = true; ri3.m_speedMS = 40; ri3.m_points.push_back(m2::PointD(5, 10)); ri3.m_points.push_back(m2::PointD(10, 10)); ri3.m_points.push_back(m2::PointD(70, 10)); ri3.m_points.push_back(m2::PointD(80, 10)); RoadInfo ri4; ri4.m_bidirectional = true; ri4.m_speedMS = 40; ri4.m_points.push_back(m2::PointD(25, 0)); ri4.m_points.push_back(m2::PointD(27, 25)); RoadInfo ri5; ri5.m_bidirectional = true; ri5.m_speedMS = 40; ri5.m_points.push_back(m2::PointD(35, 0)); ri5.m_points.push_back(m2::PointD(37, 30)); ri5.m_points.push_back(m2::PointD(70, 30)); ri5.m_points.push_back(m2::PointD(80, 30)); RoadInfo ri6; ri6.m_bidirectional = true; ri6.m_speedMS = 40; ri6.m_points.push_back(m2::PointD(70, 0)); ri6.m_points.push_back(m2::PointD(70, 10)); ri6.m_points.push_back(m2::PointD(70, 30)); RoadInfo ri7; ri7.m_bidirectional = true; ri7.m_speedMS = 40; ri7.m_points.push_back(m2::PointD(39, 55)); ri7.m_points.push_back(m2::PointD(80, 55)); RoadInfo ri8; ri8.m_bidirectional = false; ri8.m_speedMS = 40; ri8.m_points.push_back(m2::PointD(5, 40)); ri8.m_points.push_back(m2::PointD(18, 55)); ri8.m_points.push_back(m2::PointD(39, 55)); ri8.m_points.push_back(m2::PointD(37, 30)); ri8.m_points.push_back(m2::PointD(27, 25)); ri8.m_points.push_back(m2::PointD(12, 25)); ri8.m_points.push_back(m2::PointD(5, 40)); graph.AddRoad(ri0); graph.AddRoad(ri1); graph.AddRoad(ri2); graph.AddRoad(ri3); graph.AddRoad(ri4); graph.AddRoad(ri5); graph.AddRoad(ri6); graph.AddRoad(ri7); graph.AddRoad(ri8); } } // namespace routing_test <commit_msg>Review fixes.<commit_after>#include "road_graph_builder.hpp" #include "../../base/logging.hpp" #include "../../std/algorithm.hpp" using namespace routing; namespace routing_test { void RoadInfo::Swap(RoadInfo & r) { m_points.swap(r.m_points); std::swap(m_speedMS, r.m_speedMS); std::swap(m_bidirectional, r.m_bidirectional); } void RoadGraphMockSource::AddRoad(RoadInfo & rd) { /// @todo Do ASSERT for RoadInfo params. uint32_t const roadId = m_roads.size(); ASSERT_GREATER_OR_EQUAL(rd.m_points.size(), 2, ("Empty road")); size_t const numSegments = rd.m_points.size() - 1; for (size_t segId = 0; segId < numSegments; ++segId) { PossibleTurn t; t.m_startPoint = rd.m_points.front(); t.m_endPoint = rd.m_points.back(); t.m_speed = rd.m_speedMS; t.m_pos = RoadPos(roadId, true /* forward */, segId, rd.m_points[segId + 1] /* segEndPoint */); m_turns[t.m_pos.GetSegEndpoint()].push_back(t); if (rd.m_bidirectional) { t.m_pos = RoadPos(roadId, false /* forward */, segId, rd.m_points[segId] /* segEndPoint */); m_turns[t.m_pos.GetSegEndpoint()].push_back(t); } } m_roads.push_back(RoadInfo()); m_roads.back().Swap(rd); } void RoadGraphMockSource::GetPossibleTurns(RoadPos const & pos, TurnsVectorT & turns, bool /*noOptimize = true*/) { uint32_t const fID = pos.GetFeatureId(); ASSERT_LESS(fID, m_roads.size(), ()); vector<m2::PointD> const & points = m_roads[fID].m_points; int const inc = pos.IsForward() ? -1 : 1; int startID = pos.GetSegId(); int const count = static_cast<int>(points.size()); if (!pos.IsForward()) ++startID; double const speed = m_roads[fID].m_speedMS; double distance = 0.0; double time = 0.0; for (int i = startID; i >= 0 && i < count; i += inc) { double const len = points[i - inc].Length(points[i]); distance += len; time += len / speed; TurnsMapT::const_iterator j = m_turns.find(points[i]); if (j != m_turns.end()) { vector<PossibleTurn> const & vec = j->second; for (size_t k = 0; k < vec.size(); ++k) { if (vec[k].m_pos.GetFeatureId() != pos.GetFeatureId() || vec[k].m_pos.IsForward() == pos.IsForward()) { PossibleTurn t = vec[k]; t.m_metersCovered = distance; t.m_secondsCovered = time; turns.push_back(t); } } } } } void RoadGraphMockSource::ReconstructPath(RoadPosVectorT const &, routing::Route &) {} void InitRoadGraphMockSourceWithTest1(RoadGraphMockSource & src) { { RoadInfo ri; ri.m_bidirectional = true; ri.m_speedMS = 40; ri.m_points.push_back(m2::PointD(0, 0)); ri.m_points.push_back(m2::PointD(5, 0)); ri.m_points.push_back(m2::PointD(10, 0)); ri.m_points.push_back(m2::PointD(15, 0)); ri.m_points.push_back(m2::PointD(20, 0)); src.AddRoad(ri); } { RoadInfo ri; ri.m_bidirectional = true; ri.m_speedMS = 40; ri.m_points.push_back(m2::PointD(10, -10)); ri.m_points.push_back(m2::PointD(10, -5)); ri.m_points.push_back(m2::PointD(10, 0)); ri.m_points.push_back(m2::PointD(10, 5)); ri.m_points.push_back(m2::PointD(10, 10)); src.AddRoad(ri); } { RoadInfo ri; ri.m_bidirectional = true; ri.m_speedMS = 40; ri.m_points.push_back(m2::PointD(15, -5)); ri.m_points.push_back(m2::PointD(15, 0)); src.AddRoad(ri); } { RoadInfo ri; ri.m_bidirectional = true; ri.m_speedMS = 40; ri.m_points.push_back(m2::PointD(20, 0)); ri.m_points.push_back(m2::PointD(25, 5)); ri.m_points.push_back(m2::PointD(15, 5)); ri.m_points.push_back(m2::PointD(20, 0)); src.AddRoad(ri); } } void InitRoadGraphMockSourceWithTest2(RoadGraphMockSource & graph) { RoadInfo ri0; ri0.m_bidirectional = true; ri0.m_speedMS = 40; ri0.m_points.push_back(m2::PointD(0, 0)); ri0.m_points.push_back(m2::PointD(10, 0)); ri0.m_points.push_back(m2::PointD(25, 0)); ri0.m_points.push_back(m2::PointD(35, 0)); ri0.m_points.push_back(m2::PointD(70, 0)); ri0.m_points.push_back(m2::PointD(80, 0)); RoadInfo ri1; ri1.m_bidirectional = false; ri1.m_speedMS = 40; ri1.m_points.push_back(m2::PointD(0, 0)); ri1.m_points.push_back(m2::PointD(5, 10)); ri1.m_points.push_back(m2::PointD(5, 40)); RoadInfo ri2; ri2.m_bidirectional = false; ri2.m_speedMS = 40; ri2.m_points.push_back(m2::PointD(12, 25)); ri2.m_points.push_back(m2::PointD(10, 10)); ri2.m_points.push_back(m2::PointD(10, 0)); RoadInfo ri3; ri3.m_bidirectional = true; ri3.m_speedMS = 40; ri3.m_points.push_back(m2::PointD(5, 10)); ri3.m_points.push_back(m2::PointD(10, 10)); ri3.m_points.push_back(m2::PointD(70, 10)); ri3.m_points.push_back(m2::PointD(80, 10)); RoadInfo ri4; ri4.m_bidirectional = true; ri4.m_speedMS = 40; ri4.m_points.push_back(m2::PointD(25, 0)); ri4.m_points.push_back(m2::PointD(27, 25)); RoadInfo ri5; ri5.m_bidirectional = true; ri5.m_speedMS = 40; ri5.m_points.push_back(m2::PointD(35, 0)); ri5.m_points.push_back(m2::PointD(37, 30)); ri5.m_points.push_back(m2::PointD(70, 30)); ri5.m_points.push_back(m2::PointD(80, 30)); RoadInfo ri6; ri6.m_bidirectional = true; ri6.m_speedMS = 40; ri6.m_points.push_back(m2::PointD(70, 0)); ri6.m_points.push_back(m2::PointD(70, 10)); ri6.m_points.push_back(m2::PointD(70, 30)); RoadInfo ri7; ri7.m_bidirectional = true; ri7.m_speedMS = 40; ri7.m_points.push_back(m2::PointD(39, 55)); ri7.m_points.push_back(m2::PointD(80, 55)); RoadInfo ri8; ri8.m_bidirectional = false; ri8.m_speedMS = 40; ri8.m_points.push_back(m2::PointD(5, 40)); ri8.m_points.push_back(m2::PointD(18, 55)); ri8.m_points.push_back(m2::PointD(39, 55)); ri8.m_points.push_back(m2::PointD(37, 30)); ri8.m_points.push_back(m2::PointD(27, 25)); ri8.m_points.push_back(m2::PointD(12, 25)); ri8.m_points.push_back(m2::PointD(5, 40)); graph.AddRoad(ri0); graph.AddRoad(ri1); graph.AddRoad(ri2); graph.AddRoad(ri3); graph.AddRoad(ri4); graph.AddRoad(ri5); graph.AddRoad(ri6); graph.AddRoad(ri7); graph.AddRoad(ri8); } } // namespace routing_test <|endoftext|>
<commit_before> // Note - python_bindings_common.h must be included before condor_common to avoid // re-definition warnings. #include "python_bindings_common.h" #include "condor_common.h" #include "daemon.h" #include "daemon_types.h" #include "condor_commands.h" #include "condor_attributes.h" #include "compat_classad.h" #include "condor_config.h" #include "subsystem_info.h" #include "classad_wrapper.h" #include "old_boost.h" #include "module_lock.h" using namespace boost::python; enum DaemonCommands { DDAEMONS_OFF = DAEMONS_OFF, DDAEMONS_OFF_FAST = DAEMONS_OFF_FAST, DDAEMONS_OFF_PEACEFUL = DAEMONS_OFF_PEACEFUL, DDAEMON_OFF = DAEMON_OFF, DDAEMON_OFF_FAST = DAEMON_OFF_FAST, DDAEMON_OFF_PEACEFUL = DAEMON_OFF_PEACEFUL, DDC_OFF_FAST = DC_OFF_FAST, DDC_OFF_PEACEFUL = DC_OFF_PEACEFUL, DDC_OFF_GRACEFUL = DC_OFF_GRACEFUL, DDC_SET_PEACEFUL_SHUTDOWN = DC_SET_PEACEFUL_SHUTDOWN, DDC_SET_FORCE_SHUTDOWN = DC_SET_FORCE_SHUTDOWN, DDC_OFF_FORCE = DC_OFF_FORCE, DDC_RECONFIG_FULL = DC_RECONFIG_FULL, DRESTART = RESTART, DRESTART_PEACEFUL = RESTART_PEACEFUL }; enum LogLevel { DALWAYS = D_ALWAYS, DERROR = D_ERROR, DSTATUS = D_STATUS, DJOB = D_JOB, DMACHINE = D_MACHINE, DCONFIG = D_CONFIG, DPROTOCOL = D_PROTOCOL, DPRIV = D_PRIV, DDAEMONCORE = D_DAEMONCORE, DSECURITY = D_SECURITY, DNETWORK = D_NETWORK, DHOSTNAME = D_HOSTNAME, DAUDIT = D_AUDIT, DTERSE = D_TERSE, DVERBOSE = D_VERBOSE, DFULLDEBUG = D_FULLDEBUG, DBACKTRACE = D_BACKTRACE, DIDENT = D_IDENT, DSUBSECOND = D_SUB_SECOND, DTIMESTAMP = D_TIMESTAMP, DPID = D_PID, DNOHEADER = D_NOHEADER }; void send_command(const ClassAdWrapper & ad, DaemonCommands dc, const std::string &target="") { std::string addr; if (!ad.EvaluateAttrString(ATTR_MY_ADDRESS, addr)) { PyErr_SetString(PyExc_ValueError, "Address not available in location ClassAd."); throw_error_already_set(); } std::string ad_type_str; if (!ad.EvaluateAttrString(ATTR_MY_TYPE, ad_type_str)) { PyErr_SetString(PyExc_ValueError, "Daemon type not available in location ClassAd."); throw_error_already_set(); } int ad_type = AdTypeFromString(ad_type_str.c_str()); if (ad_type == NO_AD) { printf("ad type %s.\n", ad_type_str.c_str()); PyErr_SetString(PyExc_ValueError, "Unknown ad type."); throw_error_already_set(); } daemon_t d_type; switch (ad_type) { case MASTER_AD: d_type = DT_MASTER; break; case STARTD_AD: d_type = DT_STARTD; break; case SCHEDD_AD: d_type = DT_SCHEDD; break; case NEGOTIATOR_AD: d_type = DT_NEGOTIATOR; break; case COLLECTOR_AD: d_type = DT_COLLECTOR; break; default: d_type = DT_NONE; PyErr_SetString(PyExc_ValueError, "Unknown daemon type."); throw_error_already_set(); } ClassAd ad_copy; ad_copy.CopyFrom(ad); Daemon d(&ad_copy, d_type, NULL); bool result; { condor::ModuleLock ml; result = !d.locate(); } if (result) { PyErr_SetString(PyExc_RuntimeError, "Unable to locate daemon."); throw_error_already_set(); } ReliSock sock; { condor::ModuleLock ml; result = !sock.connect(d.addr()); } if (result) { PyErr_SetString(PyExc_RuntimeError, "Unable to connect to the remote daemon"); throw_error_already_set(); } { condor::ModuleLock ml; result = !d.startCommand(dc, &sock, 0, NULL); } if (result) { PyErr_SetString(PyExc_RuntimeError, "Failed to start command."); throw_error_already_set(); } if (target.size()) { std::string target_to_send = target; if (!sock.code(target_to_send)) { PyErr_SetString(PyExc_RuntimeError, "Failed to send target."); throw_error_already_set(); } if (!sock.end_of_message()) { PyErr_SetString(PyExc_RuntimeError, "Failed to send end-of-message."); throw_error_already_set(); } } sock.close(); } void send_alive(boost::python::object ad_obj=boost::python::object(), boost::python::object pid_obj=boost::python::object(), boost::python::object timeout_obj=boost::python::object()) { std::string addr; if (ad_obj.ptr() == Py_None) { char *inherit_var = getenv("CONDOR_INHERIT"); if (!inherit_var) {THROW_EX(RuntimeError, "No location specified and $CONDOR_INHERIT not in Unix environment.");} std::string inherit(inherit_var); boost::python::object inherit_obj(inherit); boost::python::object inherit_split = inherit_obj.attr("split")(); if (py_len(inherit_split) < 2) {THROW_EX(RuntimeError, "$CONDOR_INHERIT Unix environment variable malformed.");} addr = boost::python::extract<std::string>(inherit_split[1]); } else { const ClassAdWrapper ad = boost::python::extract<ClassAdWrapper>(ad_obj); if (!ad.EvaluateAttrString(ATTR_MY_ADDRESS, addr)) { THROW_EX(ValueError, "Address not available in location ClassAd."); } } int pid = getpid(); if (pid_obj.ptr() != Py_None) { pid = boost::python::extract<int>(pid_obj); } int timeout; if (timeout_obj.ptr() == Py_None) { timeout = param_integer("NOT_RESPONDING_TIMEOUT"); } else { timeout = boost::python::extract<int>(timeout_obj); } if (timeout < 1) {timeout = 1;} classy_counted_ptr<Daemon> daemon = new Daemon(DT_ANY, addr.c_str()); classy_counted_ptr<ChildAliveMsg> msg = new ChildAliveMsg(pid, timeout, 0, 0, true); { condor::ModuleLock ml; daemon->sendBlockingMsg(msg.get()); } if (msg->deliveryStatus() != DCMsg::DELIVERY_SUCCEEDED) { THROW_EX(RuntimeError, "Failed to deliver keepalive message."); } } void enable_debug() { dprintf_set_tool_debug(get_mySubSystem()->getName(), 0); } void enable_log() { dprintf_config(get_mySubSystem()->getName()); } void set_subsystem(std::string subsystem, SubsystemType type=SUBSYSTEM_TYPE_AUTO) { set_mySubSystem(subsystem.c_str(), type); } static void dprintf_wrapper2(int level, const char *fmt, ...) { va_list args; va_start(args, fmt); _condor_dprintf_va(level, static_cast<DPF_IDENT>(0), fmt, args); va_end(args); } void dprintf_wrapper(int level, std::string msg) { dprintf_wrapper2(level, "%s\n", msg.c_str()); } BOOST_PYTHON_FUNCTION_OVERLOADS(send_command_overloads, send_command, 2, 3); void export_dc_tool() { enum_<DaemonCommands>("DaemonCommands") .value("DaemonsOff", DDAEMONS_OFF) .value("DaemonsOffFast", DDAEMONS_OFF_FAST) .value("DaemonsOffPeaceful", DDAEMONS_OFF_PEACEFUL) .value("DaemonOff", DDAEMON_OFF) .value("DaemonOffFast", DDAEMON_OFF_FAST) .value("DaemonOffPeaceful", DDAEMON_OFF_PEACEFUL) .value("OffGraceful", DDC_OFF_GRACEFUL) .value("OffPeaceful", DDC_OFF_PEACEFUL) .value("OffFast", DDC_OFF_FAST) .value("OffForce", DDC_OFF_FORCE) .value("SetPeacefulShutdown", DDC_SET_PEACEFUL_SHUTDOWN) .value("SetForceShutdown", DDC_SET_FORCE_SHUTDOWN) .value("Reconfig", DDC_RECONFIG_FULL) .value("Restart", DRESTART) .value("RestartPeacful", DRESTART_PEACEFUL) ; enum_<SubsystemType>("SubsystemType") .value("Master", SUBSYSTEM_TYPE_MASTER) .value("Collector", SUBSYSTEM_TYPE_COLLECTOR) .value("Negotiator", SUBSYSTEM_TYPE_NEGOTIATOR) .value("Schedd", SUBSYSTEM_TYPE_SCHEDD) .value("Shadow", SUBSYSTEM_TYPE_SHADOW) .value("Startd", SUBSYSTEM_TYPE_STARTD) .value("Starter", SUBSYSTEM_TYPE_STARTER) .value("GAHP", SUBSYSTEM_TYPE_GAHP) .value("Dagman", SUBSYSTEM_TYPE_DAGMAN) .value("SharedPort", SUBSYSTEM_TYPE_SHARED_PORT) .value("Daemon", SUBSYSTEM_TYPE_DAEMON) .value("Tool", SUBSYSTEM_TYPE_TOOL) .value("Submit", SUBSYSTEM_TYPE_SUBMIT) .value("Job", SUBSYSTEM_TYPE_JOB) ; enum_<LogLevel>("LogLevel") .value("Always", DALWAYS) .value("Error", DERROR) .value("Status", DSTATUS) .value("Job", DJOB) .value("Machine", DMACHINE) .value("Config", DCONFIG) .value("Protocol", DPROTOCOL) .value("Priv", DPRIV) .value("DaemonCore", DDAEMONCORE) .value("Security", DSECURITY) .value("Network", DNETWORK) .value("Hostname", DHOSTNAME) .value("Audit", DAUDIT) .value("Terse", DTERSE) .value("Verbose", DVERBOSE) .value("FullDebug", DFULLDEBUG) .value("SubSecond", DSUBSECOND) .value("Timestamp", DTIMESTAMP) .value("PID", DPID) .value("NoHeader", DNOHEADER) ; def("send_command", send_command, send_command_overloads("Send a command to a HTCondor daemon specified by a location ClassAd\n" ":param ad: An ad specifying the location of the daemon; typically, found by using Collector.locate(...).\n" ":param dc: A command type; must be a member of the enum DaemonCommands.\n" ":param target: Some commands require additional arguments; for example, sending DaemonOff to a master requires one to specify which subsystem to turn off." " If this parameter is given, the daemon is sent an additional argument.")) ; def("send_alive", send_alive, "Send a keepalive to a HTCondor daemon\n" ":param ad: An ad specifying the location of the daemon; typically, found by using Collector.locate(...).\n" ":param pid: A process identifier for the keepalive. Defaults to None, which indicates to utilize the value of os.getpid().\n" ":param timeout: The number of seconds this keepalive is valid. After that time, if the condor_master has not\nreceived a new .keepalive for this process, it will be terminated. Defaults is controlled by the parameter NOT_RESPONDING_TIMEOUT.\n", (boost::python::arg("ad") = boost::python::object(), boost::python::arg("pid")=boost::python::object(), boost::python::arg("timeout")=boost::python::object()) ) ; def("set_subsystem", set_subsystem, "Set the subsystem name for configuration.\n" ":param name: The used for the config subsystem.\n" ":param type: The daemon type for configuration. Defaults to Auto, which indicates to determine the type from the parameter name.\n", (boost::python::arg("subsystem"), boost::python::arg("type")=SUBSYSTEM_TYPE_AUTO)) ; def("enable_debug", enable_debug, "Turn on debug logging output from HTCondor. Logs to stderr."); def("enable_log", enable_log, "Turn on logging output from HTCondor. Logs to the file specified by the parameter TOOL_LOG."); def("log", dprintf_wrapper, "Log a message to the HTCondor logging subsystem.\n" ":param level: Log category and formatting indicator; use the LogLevel enum for a list of these (may be OR'd together).\n" ":param msg: String message to log.\n") ; set_subsystem("TOOL", SUBSYSTEM_TYPE_TOOL); } <commit_msg>Pause dprintf() in-memory buffering when python bindings are loaded. #6227<commit_after> // Note - python_bindings_common.h must be included before condor_common to avoid // re-definition warnings. #include "python_bindings_common.h" #include "condor_common.h" #include "daemon.h" #include "daemon_types.h" #include "condor_commands.h" #include "condor_attributes.h" #include "compat_classad.h" #include "condor_config.h" #include "subsystem_info.h" #include "classad_wrapper.h" #include "old_boost.h" #include "module_lock.h" using namespace boost::python; enum DaemonCommands { DDAEMONS_OFF = DAEMONS_OFF, DDAEMONS_OFF_FAST = DAEMONS_OFF_FAST, DDAEMONS_OFF_PEACEFUL = DAEMONS_OFF_PEACEFUL, DDAEMON_OFF = DAEMON_OFF, DDAEMON_OFF_FAST = DAEMON_OFF_FAST, DDAEMON_OFF_PEACEFUL = DAEMON_OFF_PEACEFUL, DDC_OFF_FAST = DC_OFF_FAST, DDC_OFF_PEACEFUL = DC_OFF_PEACEFUL, DDC_OFF_GRACEFUL = DC_OFF_GRACEFUL, DDC_SET_PEACEFUL_SHUTDOWN = DC_SET_PEACEFUL_SHUTDOWN, DDC_SET_FORCE_SHUTDOWN = DC_SET_FORCE_SHUTDOWN, DDC_OFF_FORCE = DC_OFF_FORCE, DDC_RECONFIG_FULL = DC_RECONFIG_FULL, DRESTART = RESTART, DRESTART_PEACEFUL = RESTART_PEACEFUL }; enum LogLevel { DALWAYS = D_ALWAYS, DERROR = D_ERROR, DSTATUS = D_STATUS, DJOB = D_JOB, DMACHINE = D_MACHINE, DCONFIG = D_CONFIG, DPROTOCOL = D_PROTOCOL, DPRIV = D_PRIV, DDAEMONCORE = D_DAEMONCORE, DSECURITY = D_SECURITY, DNETWORK = D_NETWORK, DHOSTNAME = D_HOSTNAME, DAUDIT = D_AUDIT, DTERSE = D_TERSE, DVERBOSE = D_VERBOSE, DFULLDEBUG = D_FULLDEBUG, DBACKTRACE = D_BACKTRACE, DIDENT = D_IDENT, DSUBSECOND = D_SUB_SECOND, DTIMESTAMP = D_TIMESTAMP, DPID = D_PID, DNOHEADER = D_NOHEADER }; void send_command(const ClassAdWrapper & ad, DaemonCommands dc, const std::string &target="") { std::string addr; if (!ad.EvaluateAttrString(ATTR_MY_ADDRESS, addr)) { PyErr_SetString(PyExc_ValueError, "Address not available in location ClassAd."); throw_error_already_set(); } std::string ad_type_str; if (!ad.EvaluateAttrString(ATTR_MY_TYPE, ad_type_str)) { PyErr_SetString(PyExc_ValueError, "Daemon type not available in location ClassAd."); throw_error_already_set(); } int ad_type = AdTypeFromString(ad_type_str.c_str()); if (ad_type == NO_AD) { printf("ad type %s.\n", ad_type_str.c_str()); PyErr_SetString(PyExc_ValueError, "Unknown ad type."); throw_error_already_set(); } daemon_t d_type; switch (ad_type) { case MASTER_AD: d_type = DT_MASTER; break; case STARTD_AD: d_type = DT_STARTD; break; case SCHEDD_AD: d_type = DT_SCHEDD; break; case NEGOTIATOR_AD: d_type = DT_NEGOTIATOR; break; case COLLECTOR_AD: d_type = DT_COLLECTOR; break; default: d_type = DT_NONE; PyErr_SetString(PyExc_ValueError, "Unknown daemon type."); throw_error_already_set(); } ClassAd ad_copy; ad_copy.CopyFrom(ad); Daemon d(&ad_copy, d_type, NULL); bool result; { condor::ModuleLock ml; result = !d.locate(); } if (result) { PyErr_SetString(PyExc_RuntimeError, "Unable to locate daemon."); throw_error_already_set(); } ReliSock sock; { condor::ModuleLock ml; result = !sock.connect(d.addr()); } if (result) { PyErr_SetString(PyExc_RuntimeError, "Unable to connect to the remote daemon"); throw_error_already_set(); } { condor::ModuleLock ml; result = !d.startCommand(dc, &sock, 0, NULL); } if (result) { PyErr_SetString(PyExc_RuntimeError, "Failed to start command."); throw_error_already_set(); } if (target.size()) { std::string target_to_send = target; if (!sock.code(target_to_send)) { PyErr_SetString(PyExc_RuntimeError, "Failed to send target."); throw_error_already_set(); } if (!sock.end_of_message()) { PyErr_SetString(PyExc_RuntimeError, "Failed to send end-of-message."); throw_error_already_set(); } } sock.close(); } void send_alive(boost::python::object ad_obj=boost::python::object(), boost::python::object pid_obj=boost::python::object(), boost::python::object timeout_obj=boost::python::object()) { std::string addr; if (ad_obj.ptr() == Py_None) { char *inherit_var = getenv("CONDOR_INHERIT"); if (!inherit_var) {THROW_EX(RuntimeError, "No location specified and $CONDOR_INHERIT not in Unix environment.");} std::string inherit(inherit_var); boost::python::object inherit_obj(inherit); boost::python::object inherit_split = inherit_obj.attr("split")(); if (py_len(inherit_split) < 2) {THROW_EX(RuntimeError, "$CONDOR_INHERIT Unix environment variable malformed.");} addr = boost::python::extract<std::string>(inherit_split[1]); } else { const ClassAdWrapper ad = boost::python::extract<ClassAdWrapper>(ad_obj); if (!ad.EvaluateAttrString(ATTR_MY_ADDRESS, addr)) { THROW_EX(ValueError, "Address not available in location ClassAd."); } } int pid = getpid(); if (pid_obj.ptr() != Py_None) { pid = boost::python::extract<int>(pid_obj); } int timeout; if (timeout_obj.ptr() == Py_None) { timeout = param_integer("NOT_RESPONDING_TIMEOUT"); } else { timeout = boost::python::extract<int>(timeout_obj); } if (timeout < 1) {timeout = 1;} classy_counted_ptr<Daemon> daemon = new Daemon(DT_ANY, addr.c_str()); classy_counted_ptr<ChildAliveMsg> msg = new ChildAliveMsg(pid, timeout, 0, 0, true); { condor::ModuleLock ml; daemon->sendBlockingMsg(msg.get()); } if (msg->deliveryStatus() != DCMsg::DELIVERY_SUCCEEDED) { THROW_EX(RuntimeError, "Failed to deliver keepalive message."); } } void enable_debug() { dprintf_set_tool_debug(get_mySubSystem()->getName(), 0); } void enable_log() { dprintf_config(get_mySubSystem()->getName()); } void set_subsystem(std::string subsystem, SubsystemType type=SUBSYSTEM_TYPE_AUTO) { set_mySubSystem(subsystem.c_str(), type); } static void dprintf_wrapper2(int level, const char *fmt, ...) { va_list args; va_start(args, fmt); _condor_dprintf_va(level, static_cast<DPF_IDENT>(0), fmt, args); va_end(args); } void dprintf_wrapper(int level, std::string msg) { dprintf_wrapper2(level, "%s\n", msg.c_str()); } BOOST_PYTHON_FUNCTION_OVERLOADS(send_command_overloads, send_command, 2, 3); void export_dc_tool() { enum_<DaemonCommands>("DaemonCommands") .value("DaemonsOff", DDAEMONS_OFF) .value("DaemonsOffFast", DDAEMONS_OFF_FAST) .value("DaemonsOffPeaceful", DDAEMONS_OFF_PEACEFUL) .value("DaemonOff", DDAEMON_OFF) .value("DaemonOffFast", DDAEMON_OFF_FAST) .value("DaemonOffPeaceful", DDAEMON_OFF_PEACEFUL) .value("OffGraceful", DDC_OFF_GRACEFUL) .value("OffPeaceful", DDC_OFF_PEACEFUL) .value("OffFast", DDC_OFF_FAST) .value("OffForce", DDC_OFF_FORCE) .value("SetPeacefulShutdown", DDC_SET_PEACEFUL_SHUTDOWN) .value("SetForceShutdown", DDC_SET_FORCE_SHUTDOWN) .value("Reconfig", DDC_RECONFIG_FULL) .value("Restart", DRESTART) .value("RestartPeacful", DRESTART_PEACEFUL) ; enum_<SubsystemType>("SubsystemType") .value("Master", SUBSYSTEM_TYPE_MASTER) .value("Collector", SUBSYSTEM_TYPE_COLLECTOR) .value("Negotiator", SUBSYSTEM_TYPE_NEGOTIATOR) .value("Schedd", SUBSYSTEM_TYPE_SCHEDD) .value("Shadow", SUBSYSTEM_TYPE_SHADOW) .value("Startd", SUBSYSTEM_TYPE_STARTD) .value("Starter", SUBSYSTEM_TYPE_STARTER) .value("GAHP", SUBSYSTEM_TYPE_GAHP) .value("Dagman", SUBSYSTEM_TYPE_DAGMAN) .value("SharedPort", SUBSYSTEM_TYPE_SHARED_PORT) .value("Daemon", SUBSYSTEM_TYPE_DAEMON) .value("Tool", SUBSYSTEM_TYPE_TOOL) .value("Submit", SUBSYSTEM_TYPE_SUBMIT) .value("Job", SUBSYSTEM_TYPE_JOB) ; enum_<LogLevel>("LogLevel") .value("Always", DALWAYS) .value("Error", DERROR) .value("Status", DSTATUS) .value("Job", DJOB) .value("Machine", DMACHINE) .value("Config", DCONFIG) .value("Protocol", DPROTOCOL) .value("Priv", DPRIV) .value("DaemonCore", DDAEMONCORE) .value("Security", DSECURITY) .value("Network", DNETWORK) .value("Hostname", DHOSTNAME) .value("Audit", DAUDIT) .value("Terse", DTERSE) .value("Verbose", DVERBOSE) .value("FullDebug", DFULLDEBUG) .value("SubSecond", DSUBSECOND) .value("Timestamp", DTIMESTAMP) .value("PID", DPID) .value("NoHeader", DNOHEADER) ; def("send_command", send_command, send_command_overloads("Send a command to a HTCondor daemon specified by a location ClassAd\n" ":param ad: An ad specifying the location of the daemon; typically, found by using Collector.locate(...).\n" ":param dc: A command type; must be a member of the enum DaemonCommands.\n" ":param target: Some commands require additional arguments; for example, sending DaemonOff to a master requires one to specify which subsystem to turn off." " If this parameter is given, the daemon is sent an additional argument.")) ; def("send_alive", send_alive, "Send a keepalive to a HTCondor daemon\n" ":param ad: An ad specifying the location of the daemon; typically, found by using Collector.locate(...).\n" ":param pid: A process identifier for the keepalive. Defaults to None, which indicates to utilize the value of os.getpid().\n" ":param timeout: The number of seconds this keepalive is valid. After that time, if the condor_master has not\nreceived a new .keepalive for this process, it will be terminated. Defaults is controlled by the parameter NOT_RESPONDING_TIMEOUT.\n", (boost::python::arg("ad") = boost::python::object(), boost::python::arg("pid")=boost::python::object(), boost::python::arg("timeout")=boost::python::object()) ) ; def("set_subsystem", set_subsystem, "Set the subsystem name for configuration.\n" ":param name: The used for the config subsystem.\n" ":param type: The daemon type for configuration. Defaults to Auto, which indicates to determine the type from the parameter name.\n", (boost::python::arg("subsystem"), boost::python::arg("type")=SUBSYSTEM_TYPE_AUTO)) ; def("enable_debug", enable_debug, "Turn on debug logging output from HTCondor. Logs to stderr."); def("enable_log", enable_log, "Turn on logging output from HTCondor. Logs to the file specified by the parameter TOOL_LOG."); def("log", dprintf_wrapper, "Log a message to the HTCondor logging subsystem.\n" ":param level: Log category and formatting indicator; use the LogLevel enum for a list of these (may be OR'd together).\n" ":param msg: String message to log.\n") ; set_subsystem("TOOL", SUBSYSTEM_TYPE_TOOL); dprintf_pause_buffering(); } <|endoftext|>
<commit_before>/* * ctapdev.cc * * Created on: 24.06.2013 * Author: andreas */ #include "ctapdev.hpp" using namespace rofcore; extern int errno; ctapdev::ctapdev( cnetdev_owner *netdev_owner, const rofl::cdpid& dpid, std::string const& devname, uint16_t pvid, rofl::cmacaddr const& hwaddr, pthread_t tid) : cnetdev(netdev_owner, devname, tid), fd(-1), dpid(dpid), devname(devname), pvid(pvid), hwaddr(hwaddr) { try { tap_open(devname, hwaddr); } catch (...) { port_open_timer_id = register_timer(CTAPDEV_TIMER_OPEN_PORT, 1); } } ctapdev::~ctapdev() { tap_close(); } void ctapdev::tap_open(std::string const& devname, rofl::cmacaddr const& hwaddr) { try { struct ifreq ifr; int rc; if (fd > -1) { tap_close(); } if ((fd = open("/dev/net/tun", O_RDWR|O_NONBLOCK)) < 0) { throw eTapDevOpenFailed("ctapdev::tap_open() opening /dev/net/tun failed"); } memset(&ifr, 0, sizeof(ifr)); /* Flags: IFF_TUN - TUN device (no Ethernet headers) * IFF_TAP - TAP device * * IFF_NO_PI - Do not provide packet information */ ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, devname.c_str(), IFNAMSIZ); if ((rc = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) { close(fd); throw eTapDevIoctlFailed("ctapdev::tap_open() setting flags IFF_TAP | IFF_NO_PI on /dev/net/tun failed"); } set_hwaddr(hwaddr); enable_interface(); //netdev_owner->netdev_open(this); register_filedesc_r(fd); } catch (eTapDevOpenFailed& e) { rofcore::logging::error << "ctapdev::tap_open() open() failed: dev:" << devname << std::endl; throw eNetDevCritical(e.what()); } catch (eTapDevIoctlFailed& e) { rofcore::logging::error << "ctapdev::tap_open() open() failed: dev:" << devname << std::endl; throw eNetDevCritical(e.what()); } catch (eNetDevIoctl& e) { rofcore::logging::error << "ctapdev::tap_open() open() failed: dev:" << devname << std::endl; throw eNetDevCritical(e.what()); } } void ctapdev::tap_close() { try { if (fd == -1) { return; } //netdev_owner->netdev_close(this); disable_interface(); deregister_filedesc_r(fd); } catch (eNetDevIoctl& e) { rofcore::logging::error << "ctapdev::tap_close() failed: dev:" << devname << std::endl; } close(fd); fd = -1; } void ctapdev::enqueue(rofl::cpacket *pkt) { if (fd == -1) { cpacketpool::get_instance().release_pkt(pkt); return; } // store pkt in outgoing queue pout_queue.push_back(pkt); register_filedesc_w(fd); } void ctapdev::enqueue(std::vector<rofl::cpacket*> pkts) { if (fd == -1) { for (std::vector<rofl::cpacket*>::iterator it = pkts.begin(); it != pkts.end(); ++it) { cpacketpool::get_instance().release_pkt((*it)); } return; } // store pkts in outgoing queue for (std::vector<rofl::cpacket*>::iterator it = pkts.begin(); it != pkts.end(); ++it) { pout_queue.push_back(*it); } register_filedesc_w(fd); } void ctapdev::handle_revent(int fd) { rofl::cpacket *pkt = (rofl::cpacket*)0; try { rofl::cmemory mem(1518); int rc = read(fd, mem.somem(), mem.memlen()); // error occured (or non-blocking) if (rc < 0) { switch (errno) { case EAGAIN: throw eNetDevAgain("ctapdev::handle_revent() EAGAIN when reading from /dev/net/tun"); default: throw eNetDevCritical("ctapdev::handle_revent() error when reading from /dev/net/tun"); } } else { pkt = cpacketpool::get_instance().acquire_pkt(); pkt->unpack(mem.somem(), rc); netdev_owner->enqueue(this, pkt); } } catch (ePacketPoolExhausted& e) { rofcore::logging::error << "ctapdev::handle_revent() packet pool exhausted, no idle slots available" << std::endl; } catch (eNetDevAgain& e) { rofcore::logging::error << "ctapdev::handle_revent() EAGAIN, retrying later" << std::endl; cpacketpool::get_instance().release_pkt(pkt); } catch (eNetDevCritical& e) { rofcore::logging::error << "ctapdev::handle_revent() error occured" << std::endl; cpacketpool::get_instance().release_pkt(pkt); delete this; return; } } void ctapdev::handle_wevent(int fd) { rofl::cpacket * pkt = (rofl::cpacket*)0; try { while (not pout_queue.empty()) { pkt = pout_queue.front(); int rc = 0; if ((rc = write(fd, pkt->soframe(), pkt->length())) < 0) { switch (errno) { case EAGAIN: throw eNetDevAgain("ctapdev::handle_wevent() EAGAIN"); default: throw eNetDevCritical("ctapdev::handle_wevent() error occured"); } } cpacketpool::get_instance().release_pkt(pkt); pout_queue.pop_front(); } if (pout_queue.empty()) { deregister_filedesc_w(fd); } } catch (eNetDevAgain& e) { // keep fd in wfds rofcore::logging::error << "ctapdev::handle_wevent() EAGAIN, retrying later" << std::endl; } catch (eNetDevCritical& e) { rofcore::logging::error << "ctapdev::handle_wevent() critical error occured" << std::endl; cpacketpool::get_instance().release_pkt(pkt); throw; //delete this; return; } } void ctapdev::handle_timeout(int opaque, void* data) { switch (opaque) { case CTAPDEV_TIMER_OPEN_PORT: { try { tap_open(devname, hwaddr); } catch (...) { port_open_timer_id = register_timer(CTAPDEV_TIMER_OPEN_PORT, 1); } } break; } } <commit_msg>cnetlink => method route_link_cb() => added catch clause for exception crtlink::eRtLinkNotFound<commit_after>/* * ctapdev.cc * * Created on: 24.06.2013 * Author: andreas */ #include "ctapdev.hpp" using namespace rofcore; extern int errno; ctapdev::ctapdev( cnetdev_owner *netdev_owner, const rofl::cdpid& dpid, std::string const& devname, uint16_t pvid, rofl::cmacaddr const& hwaddr, pthread_t tid) : cnetdev(netdev_owner, devname, tid), fd(-1), dpid(dpid), devname(devname), pvid(pvid), hwaddr(hwaddr) { try { tap_open(devname, hwaddr); } catch (...) { port_open_timer_id = register_timer(CTAPDEV_TIMER_OPEN_PORT, 1); } } ctapdev::~ctapdev() { tap_close(); } void ctapdev::tap_open(std::string const& devname, rofl::cmacaddr const& hwaddr) { try { struct ifreq ifr; int rc; if (fd > -1) { tap_close(); } if ((fd = open("/dev/net/tun", O_RDWR|O_NONBLOCK)) < 0) { throw eTapDevOpenFailed("ctapdev::tap_open() opening /dev/net/tun failed"); } memset(&ifr, 0, sizeof(ifr)); /* Flags: IFF_TUN - TUN device (no Ethernet headers) * IFF_TAP - TAP device * * IFF_NO_PI - Do not provide packet information */ ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, devname.c_str(), IFNAMSIZ); if ((rc = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) { close(fd); throw eTapDevIoctlFailed("ctapdev::tap_open() setting flags IFF_TAP | IFF_NO_PI on /dev/net/tun failed"); } set_hwaddr(hwaddr); enable_interface(); //netdev_owner->netdev_open(this); register_filedesc_r(fd); } catch (eTapDevOpenFailed& e) { rofcore::logging::error << "ctapdev::tap_open() open() failed, dev:" << devname << std::endl; throw eNetDevCritical(rofl::eSysCall("open")); } catch (eTapDevIoctlFailed& e) { rofcore::logging::error << "ctapdev::tap_open() open() failed, dev:" << devname << std::endl; throw eNetDevCritical(rofl::eSysCall("ctapdev ioctl")); } catch (eNetDevIoctl& e) { rofcore::logging::error << "ctapdev::tap_open() open() failed, dev:" << devname << std::endl; throw eNetDevCritical(rofl::eSysCall("cnetdev open")); } } void ctapdev::tap_close() { try { if (fd == -1) { return; } //netdev_owner->netdev_close(this); disable_interface(); deregister_filedesc_r(fd); } catch (eNetDevIoctl& e) { rofcore::logging::error << "ctapdev::tap_close() failed: dev:" << devname << std::endl; } close(fd); fd = -1; } void ctapdev::enqueue(rofl::cpacket *pkt) { if (fd == -1) { cpacketpool::get_instance().release_pkt(pkt); return; } // store pkt in outgoing queue pout_queue.push_back(pkt); register_filedesc_w(fd); } void ctapdev::enqueue(std::vector<rofl::cpacket*> pkts) { if (fd == -1) { for (std::vector<rofl::cpacket*>::iterator it = pkts.begin(); it != pkts.end(); ++it) { cpacketpool::get_instance().release_pkt((*it)); } return; } // store pkts in outgoing queue for (std::vector<rofl::cpacket*>::iterator it = pkts.begin(); it != pkts.end(); ++it) { pout_queue.push_back(*it); } register_filedesc_w(fd); } void ctapdev::handle_revent(int fd) { rofl::cpacket *pkt = (rofl::cpacket*)0; try { rofl::cmemory mem(1518); int rc = read(fd, mem.somem(), mem.memlen()); // error occured (or non-blocking) if (rc < 0) { switch (errno) { case EAGAIN: throw eNetDevAgain("ctapdev::handle_revent() EAGAIN when reading from /dev/net/tun"); default: throw eNetDevCritical("ctapdev::handle_revent() error when reading from /dev/net/tun"); } } else { pkt = cpacketpool::get_instance().acquire_pkt(); pkt->unpack(mem.somem(), rc); netdev_owner->enqueue(this, pkt); } } catch (ePacketPoolExhausted& e) { rofcore::logging::error << "ctapdev::handle_revent() packet pool exhausted, no idle slots available" << std::endl; } catch (eNetDevAgain& e) { rofcore::logging::error << "ctapdev::handle_revent() EAGAIN, retrying later" << std::endl; cpacketpool::get_instance().release_pkt(pkt); } catch (eNetDevCritical& e) { rofcore::logging::error << "ctapdev::handle_revent() error occured" << std::endl; cpacketpool::get_instance().release_pkt(pkt); delete this; return; } } void ctapdev::handle_wevent(int fd) { rofl::cpacket * pkt = (rofl::cpacket*)0; try { while (not pout_queue.empty()) { pkt = pout_queue.front(); int rc = 0; if ((rc = write(fd, pkt->soframe(), pkt->length())) < 0) { switch (errno) { case EAGAIN: throw eNetDevAgain("ctapdev::handle_wevent() EAGAIN"); default: throw eNetDevCritical("ctapdev::handle_wevent() error occured"); } } cpacketpool::get_instance().release_pkt(pkt); pout_queue.pop_front(); } if (pout_queue.empty()) { deregister_filedesc_w(fd); } } catch (eNetDevAgain& e) { // keep fd in wfds rofcore::logging::error << "ctapdev::handle_wevent() EAGAIN, retrying later" << std::endl; } catch (eNetDevCritical& e) { rofcore::logging::error << "ctapdev::handle_wevent() critical error occured" << std::endl; cpacketpool::get_instance().release_pkt(pkt); throw; //delete this; return; } } void ctapdev::handle_timeout(int opaque, void* data) { switch (opaque) { case CTAPDEV_TIMER_OPEN_PORT: { try { tap_open(devname, hwaddr); } catch (...) { port_open_timer_id = register_timer(CTAPDEV_TIMER_OPEN_PORT, 1); } } break; } } <|endoftext|>
<commit_before>#include "BulletsConverter.h" #include "StylesWriter.h" using namespace PPT_FORMAT; BulletsConverter::BulletsConverter(CRelsGenerator* pRels) : m_pRels(pRels) {} void BulletsConverter::FillPPr(PPTX::Logic::TextParagraphPr &oPPr, CParagraph &paragraph) { oPPr.lvl = paragraph.m_lTextLevel; auto* pPF = &(paragraph.m_oPFRun); if (pPF) ConvertPFRun(oPPr, pPF); } void BulletsConverter::ConvertPFRun(PPTX::Logic::TextParagraphPr &oPPr, CTextPFRun *pPF) { int leftMargin = 0; if (pPF->leftMargin.is_init()) { leftMargin = pPF->leftMargin.get(); oPPr.marL = leftMargin; } if (pPF->indent.is_init()) { if (pPF->hasBullet.get_value_or(false)) oPPr.indent = pPF->indent.get(); else oPPr.indent = pPF->indent.get() - leftMargin; } if (pPF->textAlignment.is_init()) { oPPr.algn = new PPTX::Limit::TextAlign; oPPr.algn->set(CStylesWriter::GetTextAlign(pPF->textAlignment.get())); } if (pPF->defaultTabSize.is_init()) { oPPr.defTabSz = pPF->defaultTabSize.get(); } if (pPF->textDirection.is_init()) { if (pPF->textDirection.get() == 1) oPPr.rtl = true; else oPPr.rtl = false; } if (pPF->fontAlign.is_init()) { oPPr.fontAlgn = new PPTX::Limit::FontAlign; oPPr.fontAlgn->set(CStylesWriter::GetFontAlign(pPF->fontAlign.get())); } ConvertTabStops(oPPr.tabLst, pPF->tabStops); if (pPF->lineSpacing.is_init()) { LONG val = pPF->lineSpacing.get(); auto pLnSpc = new PPTX::Logic::TextSpacing; pLnSpc->m_name = L"a:lnSpc"; if (val > 0) pLnSpc->spcPct = val * 12.5; else if (val < 0 && val > -13200) pLnSpc->spcPct = val * -1000; oPPr.lnSpc = pLnSpc; } if (pPF->spaceAfter.is_init()) { LONG val = pPF->spaceAfter.get(); auto pSpcAft = new PPTX::Logic::TextSpacing; pSpcAft->m_name = L"a:spcAft"; if (val > 0) pSpcAft->spcPts = round(12.5 * pPF->spaceAfter.get()); else if (val < 0 && val > -13200) pSpcAft->spcPts = val * -1000; oPPr.spcAft = pSpcAft; } if (pPF->spaceBefore.is_init()) { LONG val = pPF->spaceBefore.get(); auto pSpcBef = new PPTX::Logic::TextSpacing; pSpcBef->m_name = L"a:spcBef"; if (val > 0) pSpcBef->spcPts = round(12.5 * pPF->spaceBefore.get()); else if (val < 0 && val > -13200) pSpcBef->spcPct = val * -1000; oPPr.spcBef = pSpcBef; } ConvertAllBullets(oPPr, pPF); } void BulletsConverter::ConvertTabStops(std::vector<PPTX::Logic::Tab> &arrTabs, std::vector<std::pair<int, int> > &arrTabStops) { for (size_t t = 0 ; t < arrTabStops.size(); t++) { PPTX::Logic::Tab tab; tab.pos = arrTabStops[t].first; auto pAlgn = new PPTX::Limit::TextTabAlignType; switch (arrTabStops[t].second) { case 1: pAlgn->set(L"ctr"); break; case 2: pAlgn->set(L"r"); break; case 3: pAlgn->set(L"dec"); break; default: pAlgn->set(L"l"); } tab.algn = pAlgn; arrTabs.push_back(tab); } } void BulletsConverter::FillBuChar(PPTX::Logic::Bullet &oBullet, WCHAR symbol) { auto pBuChar = new PPTX::Logic::BuChar; pBuChar->Char.clear(); pBuChar->Char.push_back(symbol); oBullet.m_Bullet.reset(pBuChar); } void BulletsConverter::ConvertAllBullets(PPTX::Logic::TextParagraphPr &oPPr, CTextPFRun *pPF) { if (pPF->hasBullet.is_init()) { if (pPF->hasBullet.get()) { if (pPF->bulletColor.is_init()) { FillBuClr(oPPr.buColor, pPF->bulletColor.get()); } if (pPF->bulletSize.is_init()) { PPTX::WrapperWritingElement* pBuSize; if (pPF->bulletSize.get() > 24 && pPF->bulletSize.get() < 401) { pBuSize = new PPTX::Logic::BuSzPct; static_cast<PPTX::Logic::BuSzPct*>(pBuSize)->val = pPF->bulletSize.get() * 1000 ; } if (pPF->bulletSize.get() < 0 && pPF->bulletSize.get() > -4001) { pBuSize = new PPTX::Logic::BuSzPts; static_cast<PPTX::Logic::BuSzPts*>(pBuSize)->val = - (pPF->bulletSize.get()); } oPPr.buSize.m_Size = pBuSize; } if (pPF->bulletFontProperties.is_init()) { auto pBuFont = new PPTX::Logic::TextFont; pBuFont->m_name = L"a:buFont"; pBuFont->typeface = pPF->bulletFontProperties->Name; if ( pPF->bulletFontProperties->PitchFamily > 0) pBuFont->pitchFamily = std::to_wstring(pPF->bulletFontProperties->PitchFamily); if ( pPF->bulletFontProperties->Charset > 0) pBuFont->charset = std::to_wstring(pPF->bulletFontProperties->Charset); oPPr.buTypeface.m_Typeface.reset(pBuFont); } // Bullets (numbering, else picture, else char, else default) if (pPF->bulletBlip.is_init() && pPF->bulletBlip->tmpImagePath.size() && m_pRels != nullptr) { auto strRID = m_pRels->WriteImage(pPF->bulletBlip->tmpImagePath); if (strRID.empty()) FillBuChar(oPPr.ParagraphBullet, L'\x2022'); // error rId else { auto pBuBlip = new PPTX::Logic::BuBlip; pBuBlip->blip.embed = new OOX::RId(strRID); oPPr.ParagraphBullet.m_Bullet.reset(pBuBlip); } } else if (pPF->bulletChar.is_init() && (pPF->bulletAutoNum.is_init() ? pPF->bulletAutoNum->isDefault() : true)) { FillBuChar(oPPr.ParagraphBullet, pPF->bulletChar.get()); } else if (pPF->bulletAutoNum.is_init()) { auto pBuAutoNum = new PPTX::Logic::BuAutoNum; oPPr.ParagraphBullet.m_Bullet.reset(pBuAutoNum); if (pPF->bulletAutoNum->startAt.is_init() && pPF->bulletAutoNum->startAt.get() != 1) pBuAutoNum->startAt = pPF->bulletAutoNum->startAt.get(); if (pPF->bulletAutoNum->type.is_init()) pBuAutoNum->type = pPF->bulletAutoNum->type.get(); } else { FillBuChar(oPPr.ParagraphBullet, L'\x2022'); } } else { oPPr.buTypeface.m_Typeface.reset(new PPTX::Logic::BuNone); } } } void BulletsConverter::FillBuClr(PPTX::Logic::BulletColor &oBuClr, CColor &oColor) { auto pBuClr = new PPTX::Logic::BuClr; pBuClr->Color.SetRGBColor(oColor.GetR(), oColor.GetG(), oColor.GetB()); oBuClr.m_Color.reset(pBuClr); } <commit_msg>fix bug #55290<commit_after>#include "BulletsConverter.h" #include "StylesWriter.h" using namespace PPT_FORMAT; BulletsConverter::BulletsConverter(CRelsGenerator* pRels) : m_pRels(pRels) {} void BulletsConverter::FillPPr(PPTX::Logic::TextParagraphPr &oPPr, CParagraph &paragraph) { oPPr.lvl = paragraph.m_lTextLevel; auto* pPF = &(paragraph.m_oPFRun); if (pPF) ConvertPFRun(oPPr, pPF); } void BulletsConverter::ConvertPFRun(PPTX::Logic::TextParagraphPr &oPPr, CTextPFRun *pPF) { int leftMargin = 0; if (pPF->leftMargin.is_init()) { leftMargin = pPF->leftMargin.get(); oPPr.marL = leftMargin; } if (pPF->indent.is_init()) { if (pPF->hasBullet.get_value_or(false)) oPPr.indent = pPF->indent.get(); else oPPr.indent = pPF->indent.get() - leftMargin; } if (pPF->textAlignment.is_init()) { oPPr.algn = new PPTX::Limit::TextAlign; oPPr.algn->set(CStylesWriter::GetTextAlign(pPF->textAlignment.get())); } if (pPF->defaultTabSize.is_init()) { oPPr.defTabSz = pPF->defaultTabSize.get(); } if (pPF->textDirection.is_init()) { if (pPF->textDirection.get() == 1) oPPr.rtl = true; else oPPr.rtl = false; } if (pPF->fontAlign.is_init()) { oPPr.fontAlgn = new PPTX::Limit::FontAlign; oPPr.fontAlgn->set(CStylesWriter::GetFontAlign(pPF->fontAlign.get())); } ConvertTabStops(oPPr.tabLst, pPF->tabStops); if (pPF->lineSpacing.is_init()) { LONG val = pPF->lineSpacing.get(); auto pLnSpc = new PPTX::Logic::TextSpacing; pLnSpc->m_name = L"a:lnSpc"; if (val > 0) pLnSpc->spcPct = val * 12.5; else if (val < 0 && val > -13200) pLnSpc->spcPct = val * -1000; oPPr.lnSpc = pLnSpc; } if (pPF->spaceAfter.is_init()) { LONG val = pPF->spaceAfter.get(); auto pSpcAft = new PPTX::Logic::TextSpacing; pSpcAft->m_name = L"a:spcAft"; if (val > 0) pSpcAft->spcPts = round(12.5 * pPF->spaceAfter.get()); else if (val < 0 && val > -13200) pSpcAft->spcPts = val * -1000; oPPr.spcAft = pSpcAft; } if (pPF->spaceBefore.is_init()) { LONG val = pPF->spaceBefore.get(); auto pSpcBef = new PPTX::Logic::TextSpacing; pSpcBef->m_name = L"a:spcBef"; if (val > 0) pSpcBef->spcPts = round(12.5 * pPF->spaceBefore.get()); else if (val < 0 && val > -13200) pSpcBef->spcPct = val * -1000; oPPr.spcBef = pSpcBef; } ConvertAllBullets(oPPr, pPF); } void BulletsConverter::ConvertTabStops(std::vector<PPTX::Logic::Tab> &arrTabs, std::vector<std::pair<int, int> > &arrTabStops) { for (size_t t = 0 ; t < arrTabStops.size(); t++) { PPTX::Logic::Tab tab; tab.pos = arrTabStops[t].first; auto pAlgn = new PPTX::Limit::TextTabAlignType; switch (arrTabStops[t].second) { case 1: pAlgn->set(L"ctr"); break; case 2: pAlgn->set(L"r"); break; case 3: pAlgn->set(L"dec"); break; default: pAlgn->set(L"l"); } tab.algn = pAlgn; arrTabs.push_back(tab); } } void BulletsConverter::FillBuChar(PPTX::Logic::Bullet &oBullet, WCHAR symbol) { auto pBuChar = new PPTX::Logic::BuChar; pBuChar->Char.clear(); pBuChar->Char.push_back(symbol); oBullet.m_Bullet.reset(pBuChar); } void BulletsConverter::ConvertAllBullets(PPTX::Logic::TextParagraphPr &oPPr, CTextPFRun *pPF) { if (pPF->hasBullet.is_init()) { if (pPF->hasBullet.get()) { if (pPF->bulletColor.is_init()) { FillBuClr(oPPr.buColor, pPF->bulletColor.get()); } if (pPF->bulletSize.is_init()) { PPTX::WrapperWritingElement* pBuSize(nullptr); if (pPF->bulletSize.get() > 24 && pPF->bulletSize.get() < 401) { pBuSize = new PPTX::Logic::BuSzPct; static_cast<PPTX::Logic::BuSzPct*>(pBuSize)->val = pPF->bulletSize.get() * 1000 ; } if (pPF->bulletSize.get() < 0 && pPF->bulletSize.get() > -4001) { pBuSize = new PPTX::Logic::BuSzPts; static_cast<PPTX::Logic::BuSzPts*>(pBuSize)->val = - (pPF->bulletSize.get()); } if (pBuSize != nullptr) oPPr.buSize.m_Size = pBuSize; } if (pPF->bulletFontProperties.is_init()) { auto pBuFont = new PPTX::Logic::TextFont; pBuFont->m_name = L"a:buFont"; pBuFont->typeface = pPF->bulletFontProperties->Name; if ( pPF->bulletFontProperties->PitchFamily > 0) pBuFont->pitchFamily = std::to_wstring(pPF->bulletFontProperties->PitchFamily); if ( pPF->bulletFontProperties->Charset > 0) pBuFont->charset = std::to_wstring(pPF->bulletFontProperties->Charset); oPPr.buTypeface.m_Typeface.reset(pBuFont); } // Bullets (numbering, else picture, else char, else default) if (pPF->bulletBlip.is_init() && pPF->bulletBlip->tmpImagePath.size() && m_pRels != nullptr) { auto strRID = m_pRels->WriteImage(pPF->bulletBlip->tmpImagePath); if (strRID.empty()) FillBuChar(oPPr.ParagraphBullet, L'\x2022'); // error rId else { auto pBuBlip = new PPTX::Logic::BuBlip; pBuBlip->blip.embed = new OOX::RId(strRID); oPPr.ParagraphBullet.m_Bullet.reset(pBuBlip); } } else if (pPF->bulletChar.is_init() && (pPF->bulletAutoNum.is_init() ? pPF->bulletAutoNum->isDefault() : true)) { FillBuChar(oPPr.ParagraphBullet, pPF->bulletChar.get()); } else if (pPF->bulletAutoNum.is_init()) { auto pBuAutoNum = new PPTX::Logic::BuAutoNum; oPPr.ParagraphBullet.m_Bullet.reset(pBuAutoNum); if (pPF->bulletAutoNum->startAt.is_init() && pPF->bulletAutoNum->startAt.get() != 1) pBuAutoNum->startAt = pPF->bulletAutoNum->startAt.get(); if (pPF->bulletAutoNum->type.is_init()) pBuAutoNum->type = pPF->bulletAutoNum->type.get(); } else { FillBuChar(oPPr.ParagraphBullet, L'\x2022'); } } else { oPPr.buTypeface.m_Typeface.reset(new PPTX::Logic::BuNone); } } } void BulletsConverter::FillBuClr(PPTX::Logic::BulletColor &oBuClr, CColor &oColor) { auto pBuClr = new PPTX::Logic::BuClr; pBuClr->Color.SetRGBColor(oColor.GetR(), oColor.GetG(), oColor.GetB()); oBuClr.m_Color.reset(pBuClr); } <|endoftext|>
<commit_before>/* Copyright (C) 2010-present, Zhenkai Zhu <zhenkai@cs.ucla.edu> 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 Mumble Developers 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 FOUNDATION 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 "murmur_pch.h" #include "RemoteUser.h" #define REFRESH_INTERVAL 10 #define REMOVE_INTERVAL 21 RemoteUser::RemoteUser(QString prefix, QString name) : remoteUserPrefix(prefix) { qsName = name; timestamp = QDateTime::currentDateTime(); left = false; } void RemoteUser::refreshReceived() { timestamp = QDateTime::currentDateTime(); } bool RemoteUser::needRefresh() { QDateTime now = QDateTime::currentDateTime(); if (timestamp.secsTo(now) > REFRESH_INTERVAL) { return true; } return false; } bool RemoteUser::isStaled() { if (left) return true; QDateTime now = QDateTime::currentDateTime(); if (timestamp.isNull()) { /* fprintf(stderr, "timestamp is null, will initialize one"); timestamp = QDateTime::currentDateTime(); */ // Null time: this RU is weird, remote it; return true; } if (timestamp.secsTo(now) > REMOVE_INTERVAL) { return true; } return false; } void RemoteUser::setPrefix(QString prefix) { this->remoteUserPrefix = prefix; } <commit_msg>do not remove user from GM as soon as leave interest comes instead, remove it from mumble asap, but wait for timeout to clean from GM<commit_after>/* Copyright (C) 2010-present, Zhenkai Zhu <zhenkai@cs.ucla.edu> 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 Mumble Developers 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 FOUNDATION 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 "murmur_pch.h" #include "RemoteUser.h" #define REFRESH_INTERVAL 10 #define REMOVE_INTERVAL 21 RemoteUser::RemoteUser(QString prefix, QString name) : remoteUserPrefix(prefix) { qsName = name; timestamp = QDateTime::currentDateTime(); left = false; } void RemoteUser::refreshReceived() { timestamp = QDateTime::currentDateTime(); } bool RemoteUser::needRefresh() { QDateTime now = QDateTime::currentDateTime(); if (timestamp.secsTo(now) > REFRESH_INTERVAL) { return true; } return false; } bool RemoteUser::isStaled() { /* if (left) return true; */ QDateTime now = QDateTime::currentDateTime(); if (timestamp.isNull()) { /* fprintf(stderr, "timestamp is null, will initialize one"); timestamp = QDateTime::currentDateTime(); */ // Null time: this RU is weird, remote it; return true; } if (timestamp.secsTo(now) > REMOVE_INTERVAL) { return true; } return false; } void RemoteUser::setPrefix(QString prefix) { this->remoteUserPrefix = prefix; } <|endoftext|>
<commit_before>// formatxx - C++ string formatting library. // // This is free and unencumbered software released into the public domain. // // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non - commercial, and by any // means. // // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // // For more information, please refer to <http://unlicense.org/> // // Authors: // Sean Middleditch <sean@middleditch.us> #include <limits> namespace formatxx { namespace { void write_integer_prefix(format_writer& out, format_spec const& spec, bool negative); template <typename T> void write_decimal(format_writer& out, T value); template <typename T> void write_hexadecimal(format_writer& out, T value, bool lower); template <typename T> void write_octal(format_writer& out, T value); template <typename T> void write_binary(format_writer& out, T value); template <typename T> void write_integer(format_writer& out, T value, string_view spec); void write_integer_prefix(format_writer& out, format_spec const& spec, bool negative) { char prefix_buffer[3]; // sign, type prefix char* prefix = prefix_buffer; // add sign if (negative) *(prefix++) = '-'; else if (spec.sign == format_spec::sign_always) *(prefix++) = '+'; else if (spec.sign == format_spec::sign_space) *(prefix++) = ' '; // add numeric type prefix if (spec.type_prefix) { *(prefix++) = '0'; *(prefix++) = spec.code ? spec.code : 'd'; } // write the prefix out, if any if (prefix != prefix_buffer) out.write({prefix_buffer, prefix}); } template <typename T> void write_decimal(format_writer& out, T value) { // we'll work on every two decimal digits (groups of 100). notes taken from cppformat, // which took the notes from Alexandrescu from "Three Optimization Tips for C++" constexpr char sDecimalTable[] = "00010203040506070809" "10111213141516171819" "20212223242526272829" "30313233343536373839" "40414243444546474849" "50515253545556575859" "60616263646566676869" "70717273747576777879" "80818283848586878889" "90919293949596979899"; // buffer must be one larger than digits10, as that trait is the maximum number of // base-10 digits represented by the type in their entirety, e.g. 8-bits can store // 99 but not 999, so its digits10 is 2, even though the value 255 could be stored // and has 3 digits. char buffer[std::numeric_limits<decltype(value)>::digits10 + 1]; char* end = buffer + sizeof(buffer); // work on every two decimal digits (groups of 100). notes taken from cppformat, // which took the notes from Alexandrescu from "Three Optimization Tips for C++" while (value >= 100) { // I feel like we could do the % and / better... somehow // we multiply the index by two to find the pair of digits to index unsigned const digit = (value % 100) << 1; value /= 100; // write out both digits of the given index *--end = sDecimalTable[digit + 1]; *--end = sDecimalTable[digit]; } if (value >= 10) { // we have two digits left; this is identical to the above loop, but without the division unsigned const digit = static_cast<unsigned>(value << 1); *--end = sDecimalTable[digit + 1]; *--end = sDecimalTable[digit]; } else { // we have but a single digit left, so this is easy *--end = '0' + static_cast<char>(value); } out.write({end, sizeof(buffer) - (end - buffer)}); } template <typename T> void write_hexadecimal(format_writer& out, T value, bool lower) { char buffer[2 * sizeof(value)]; // 2 hex digits per octet char* end = buffer + sizeof(buffer); char const* const alphabet = lower ? "0123456789abcdef" : "0123456789ABCDEF"; do { *--end = alphabet[value & 0xF]; } while ((value >>= 4) != 0); out.write({end, sizeof(buffer) - (end - buffer)}); } template <typename T> void write_octal(format_writer& out, T value) { char buffer[3 * sizeof(value)]; // 3 octal digits per octet char* end = buffer + sizeof(buffer); char const alphabet[] = "01234567"; do { *--end = alphabet[value & 0x7]; } while ((value >>= 3) != 0); out.write({end, sizeof(buffer) - (end - buffer)}); } template <typename T> void write_binary(format_writer& out, T value) { char buffer[CHAR_BIT * sizeof(value)]; // bits per octet char* end = buffer + sizeof(buffer); do { *--end = '0' + (value & 1); } while ((value >>= 1) != 0); out.write({end, sizeof(buffer) - (end - buffer)}); } template <typename T> void write_integer(format_writer& out, T raw, string_view spec_string) { // subtract from 0 _after_ converting to deal with 2's complement format (abs(min) > abs(max)) std::make_unsigned_t<T> const value = raw >= 0 ? raw : 0 - static_cast<std::make_unsigned_t<T>>(raw); format_spec const spec = parse_format_spec(spec_string); // format any prefix onto the number write_integer_prefix(out, spec, /*negative=*/raw < 0); switch (spec.code) { case 0: case 'd': case 'D': write_decimal(out, value); break; case 'x': write_hexadecimal(out, value, /*lower=*/true); break; case 'X': write_hexadecimal(out, value, /*lower=*/false); break; case 'o': case 'O': write_octal(out, value); break; case 'b': case 'B': write_binary(out, value); break; } } } // anonymous namespace } // namespace formatxx<commit_msg>CHAR_BIT isn't pulled in for libstdc++/libc++ so use numeric_limits instead.<commit_after>// formatxx - C++ string formatting library. // // This is free and unencumbered software released into the public domain. // // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non - commercial, and by any // means. // // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // // For more information, please refer to <http://unlicense.org/> // // Authors: // Sean Middleditch <sean@middleditch.us> #include <limits> namespace formatxx { namespace { void write_integer_prefix(format_writer& out, format_spec const& spec, bool negative); template <typename T> void write_decimal(format_writer& out, T value); template <typename T> void write_hexadecimal(format_writer& out, T value, bool lower); template <typename T> void write_octal(format_writer& out, T value); template <typename T> void write_binary(format_writer& out, T value); template <typename T> void write_integer(format_writer& out, T value, string_view spec); void write_integer_prefix(format_writer& out, format_spec const& spec, bool negative) { char prefix_buffer[3]; // sign, type prefix char* prefix = prefix_buffer; // add sign if (negative) *(prefix++) = '-'; else if (spec.sign == format_spec::sign_always) *(prefix++) = '+'; else if (spec.sign == format_spec::sign_space) *(prefix++) = ' '; // add numeric type prefix if (spec.type_prefix) { *(prefix++) = '0'; *(prefix++) = spec.code ? spec.code : 'd'; } // write the prefix out, if any if (prefix != prefix_buffer) out.write({prefix_buffer, prefix}); } template <typename T> void write_decimal(format_writer& out, T value) { // we'll work on every two decimal digits (groups of 100). notes taken from cppformat, // which took the notes from Alexandrescu from "Three Optimization Tips for C++" constexpr char sDecimalTable[] = "00010203040506070809" "10111213141516171819" "20212223242526272829" "30313233343536373839" "40414243444546474849" "50515253545556575859" "60616263646566676869" "70717273747576777879" "80818283848586878889" "90919293949596979899"; // buffer must be one larger than digits10, as that trait is the maximum number of // base-10 digits represented by the type in their entirety, e.g. 8-bits can store // 99 but not 999, so its digits10 is 2, even though the value 255 could be stored // and has 3 digits. char buffer[std::numeric_limits<decltype(value)>::digits10 + 1]; char* end = buffer + sizeof(buffer); // work on every two decimal digits (groups of 100). notes taken from cppformat, // which took the notes from Alexandrescu from "Three Optimization Tips for C++" while (value >= 100) { // I feel like we could do the % and / better... somehow // we multiply the index by two to find the pair of digits to index unsigned const digit = (value % 100) << 1; value /= 100; // write out both digits of the given index *--end = sDecimalTable[digit + 1]; *--end = sDecimalTable[digit]; } if (value >= 10) { // we have two digits left; this is identical to the above loop, but without the division unsigned const digit = static_cast<unsigned>(value << 1); *--end = sDecimalTable[digit + 1]; *--end = sDecimalTable[digit]; } else { // we have but a single digit left, so this is easy *--end = '0' + static_cast<char>(value); } out.write({end, sizeof(buffer) - (end - buffer)}); } template <typename T> void write_hexadecimal(format_writer& out, T value, bool lower) { char buffer[2 * sizeof(value)]; // 2 hex digits per octet char* end = buffer + sizeof(buffer); char const* const alphabet = lower ? "0123456789abcdef" : "0123456789ABCDEF"; do { *--end = alphabet[value & 0xF]; } while ((value >>= 4) != 0); out.write({end, sizeof(buffer) - (end - buffer)}); } template <typename T> void write_octal(format_writer& out, T value) { char buffer[3 * sizeof(value)]; // 3 octal digits per octet char* end = buffer + sizeof(buffer); char const alphabet[] = "01234567"; do { *--end = alphabet[value & 0x7]; } while ((value >>= 3) != 0); out.write({end, sizeof(buffer) - (end - buffer)}); } template <typename T> void write_binary(format_writer& out, T value) { char buffer[std::numeric_limits<unsigned char>::digits * sizeof(value)]; char* end = buffer + sizeof(buffer); do { *--end = '0' + (value & 1); } while ((value >>= 1) != 0); out.write({end, sizeof(buffer) - (end - buffer)}); } template <typename T> void write_integer(format_writer& out, T raw, string_view spec_string) { // subtract from 0 _after_ converting to deal with 2's complement format (abs(min) > abs(max)) std::make_unsigned_t<T> const value = raw >= 0 ? raw : 0 - static_cast<std::make_unsigned_t<T>>(raw); format_spec const spec = parse_format_spec(spec_string); // format any prefix onto the number write_integer_prefix(out, spec, /*negative=*/raw < 0); switch (spec.code) { case 0: case 'd': case 'D': write_decimal(out, value); break; case 'x': write_hexadecimal(out, value, /*lower=*/true); break; case 'X': write_hexadecimal(out, value, /*lower=*/false); break; case 'o': case 'O': write_octal(out, value); break; case 'b': case 'B': write_binary(out, value); break; } } } // anonymous namespace } // namespace formatxx<|endoftext|>
<commit_before>/* Copyright (C) 2003-2008 Grame Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France research@grame.fr This file is provided as an example of the MusicXML Library use. */ #ifdef VC6 # pragma warning (disable : 4786) #endif #include <iomanip> // setw()), set::precision(), ... #include <fstream> // ofstream, ofstream::open(), ofstream::close() #include "libmusicxml.h" #include "version.h" #include "utilities.h" #include "generalOptions.h" #include "mxmlOptions.h" #include "msrOptions.h" #include "lpsrOptions.h" #include "lilypondOptions.h" #include "xml2lilypondOptionsHandling.h" #include "mxmlTree2MsrSkeletonBuilderInterface.h" #include "mxmlTree2MsrTranslatorInterface.h" #include "msr2LpsrInterface.h" #include "lpsr2LilypondInterface.h" using namespace std; using namespace MusicXML2; #define TRACE_OPTIONS 0 //_______________________________________________________________________________ vector<string> handleOptionsAndArguments ( S_xml2lilypondOptionsHandler optionsHandler, int argc, char* argv [], indentedOstream& logIndentedOutputStream) { // analyse the options vector<string> argumentsVector = optionsHandler-> decipherOptionsAndArguments ( argc, argv); if (TRACE_OPTIONS) { // print the options values logIndentedOutputStream << "Options values:" << endl; gIndenter++; optionsHandler-> printOptionsValues ( logIndentedOutputStream); logIndentedOutputStream << endl; gIndenter--; } return argumentsVector; } S_msrScore runPass2a ( string inputSourceName, string outputFileName) { int outputFileNameSize = outputFileName.size (); S_msrScore mScore; if (inputSourceName == "-") { // input comes from standard input if (outputFileNameSize) mScore = mxmlFd2MsrSkeleton ( stdin, gMsrOptions, gLogIOstream); else mScore = mxmlFd2MsrSkeleton ( stdin, gMsrOptions, gLogIOstream); } else { // input comes from a file if (outputFileNameSize) { mScore = mxmlFile2MsrSkeleton ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } else { mScore = mxmlFile2MsrSkeleton ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } } return mScore; } void runPass2b ( string inputSourceName, string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); if (inputSourceName == "-") { // input comes from standard input if (outputFileNameSize) mScore = mxmlFd2Msr ( stdin, gMsrOptions, gLogIOstream); else mScore = mxmlFd2Msr ( stdin, gMsrOptions, gLogIOstream); } else { // input comes from a file if (outputFileNameSize) { mScore = mxmlFile2Msr ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } else { mScore = mxmlFile2Msr ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } } /* JMI if (! mScore) { gLogIOstream << "### Conversion from MusicCML to MSR failed ###" << endl << endl; // JMI return false; } */ // JMI return true; } S_lpsrScore runPass3 ( string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); S_lpsrScore lpScore; if (! gLilypondOptions->fNoLilypondCode) { if (outputFileNameSize) { lpScore = msr2Lpsr ( mScore, gMsrOptions, gLpsrOptions, gLogIOstream); } else { lpScore = msr2Lpsr ( mScore, gMsrOptions, gLpsrOptions, gLogIOstream); } } return lpScore; } void runPass4 ( string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); if (! gLilypondOptions->fNoLilypondCode) { // open output file if need be // ------------------------------------------------------ ofstream outFileStream; if (outputFileNameSize) { if (gGeneralOptions->fTraceGeneral) gLogIOstream << endl << "Opening file '" << outputFileName << "' for writing" << endl; outFileStream.open ( outputFileName.c_str(), ofstream::out); // create an indented output stream for the LilyPond code // to be written to outFileStream indentedOstream lilypondCodeFileOutputStream ( outFileStream, gIndenter); // convert the LPSR score to LilyPond code lpsr2Lilypond ( lpScore, gMsrOptions, gLpsrOptions, gLogIOstream, lilypondCodeFileOutputStream); } else { // create an indented output stream for the LilyPond code // to be written to cout indentedOstream lilypondCodeCoutOutputStream ( cout, gIndenter); lpsr2Lilypond ( lpScore, gMsrOptions, gLpsrOptions, gLogIOstream, lilypondCodeCoutOutputStream); } if (outputFileNameSize) { if (gGeneralOptions->fTraceGeneral) gLogIOstream << endl << "Closing file '" << outputFileName << "'" << endl; outFileStream.close (); } } } //_______________________________________________________________________________ int main (int argc, char *argv[]) { /* JMI cerr << "argc = " << argc << endl; for (int i = 0; i < argc ; i++ ) { cerr << "argv[ " << i << "] = " << argv[i] << endl; } */ // initialize the components of MSR that we'll be using // ------------------------------------------------------ initializeMSR (); initializeLPSR (); // create the options handler // ------------------------------------------------------ S_xml2lilypondOptionsHandler optionsHandler = xml2lilypondOptionsHandler::create ( gLogIOstream); // analyze the command line options and arguments // ------------------------------------------------------ vector<string> argumentsVector = handleOptionsAndArguments ( optionsHandler, argc, argv, gLogIOstream); // print the resulting options if (TRACE_OPTIONS) { gLogIOstream << optionsHandler << endl << endl; } string inputSourceName = gGeneralOptions->fInputSourceName; string outputFileName = gGeneralOptions->fOutputFileName; int outputFileNameSize = outputFileName.size (); // welcome message // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { gLogIOstream << "This is xml2Lilypond v" << currentVersionNumber () << " from libmusicxml2 v" << musicxmllibVersionStr () << endl; gLogIOstream << "Launching conversion of "; if (inputSourceName == "-") gLogIOstream << "standard input"; else gLogIOstream << "\"" << inputSourceName << "\""; gLogIOstream << " to LilyPond" << endl; gLogIOstream << "Time is " << gGeneralOptions->fTranslationDate << endl; gLogIOstream << "LilyPond code will be written to "; if (outputFileNameSize) { gLogIOstream << outputFileName; } else { gLogIOstream << "standard output"; } gLogIOstream << endl << endl; gLogIOstream << "The command line is:" << endl; gIndenter++; gLogIOstream << optionsHandler-> getCommandLineWithLongOptions () << endl; gIndenter--; gLogIOstream << "or:" << endl; gIndenter++; gLogIOstream << optionsHandler-> getCommandLineWithShortOptions () << endl << endl; gIndenter--; } // print the chosen LilyPond options // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { optionsHandler-> printOptionsValues ( gLogIOstream); } // acknoledge end of command line analysis // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { gLogIOstream << endl << "The command line options and arguments have been analyzed" << endl; } // create the MSR skeleton from MusicXML contents (pass 2a) // ------------------------------------------------------ S_msrScore mScore = runPass2a ( inputSourceName, outputFileName); if (! mScore) { gLogIOstream << "### Conversion from MusicCML to an MSR skeleton failed ###" << endl << endl; exit (1); } else if (! gGeneralOptions->fExit2a) { // create the MSR from MusicXML contents (pass 2b) // ------------------------------------------------------ runPass2b ( inputSourceName, outputFileName, mScore); if (! gGeneralOptions->fExit2b) { // create the LPSR from the MSR (pass 3) // ------------------------------------------------------ S_lpsrScore lpScore = runPass3 ( outputFileName, mScore); if (! lpScore) { gLogIOstream << "### Conversion from MSR to LPSR failed ###" << endl << endl; return 1; } else if (! gGeneralOptions->fExit3) { // generate LilyPond code from the LPSR (pass 4) // ------------------------------------------------------ runPass4 ( outputFileName, lpScore); } } } // print timing information // ------------------------------------------------------ if (gGeneralOptions->fDisplayCPUusage) timing::gTiming.print ( gLogIOstream); // over! // ------------------------------------------------------ if (! true) { // JMI gLogIOstream << "### Conversion from LPSR to LilyPond code failed ###" << endl << endl; return 1; } return 0; } <commit_msg>skeleton 36<commit_after>/* Copyright (C) 2003-2008 Grame Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France research@grame.fr This file is provided as an example of the MusicXML Library use. */ #ifdef VC6 # pragma warning (disable : 4786) #endif #include <iomanip> // setw()), set::precision(), ... #include <fstream> // ofstream, ofstream::open(), ofstream::close() #include "libmusicxml.h" #include "version.h" #include "utilities.h" #include "generalOptions.h" #include "mxmlOptions.h" #include "msrOptions.h" #include "lpsrOptions.h" #include "lilypondOptions.h" #include "xml2lilypondOptionsHandling.h" #include "mxmlTree2MsrSkeletonBuilderInterface.h" #include "mxmlTree2MsrTranslatorInterface.h" #include "msr2LpsrInterface.h" #include "lpsr2LilypondInterface.h" using namespace std; using namespace MusicXML2; #define TRACE_OPTIONS 0 //_______________________________________________________________________________ vector<string> handleOptionsAndArguments ( S_xml2lilypondOptionsHandler optionsHandler, int argc, char* argv [], indentedOstream& logIndentedOutputStream) { // analyse the options vector<string> argumentsVector = optionsHandler-> decipherOptionsAndArguments ( argc, argv); if (TRACE_OPTIONS) { // print the options values logIndentedOutputStream << "Options values:" << endl; gIndenter++; optionsHandler-> printOptionsValues ( logIndentedOutputStream); logIndentedOutputStream << endl; gIndenter--; } return argumentsVector; } S_msrScore runPass2a ( string inputSourceName, string outputFileName) { int outputFileNameSize = outputFileName.size (); S_msrScore mScore; if (inputSourceName == "-") { // input comes from standard input if (outputFileNameSize) mScore = mxmlFd2MsrSkeleton ( stdin, gMsrOptions, gLogIOstream); else mScore = mxmlFd2MsrSkeleton ( stdin, gMsrOptions, gLogIOstream); } else { // input comes from a file if (outputFileNameSize) { mScore = mxmlFile2MsrSkeleton ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } else { mScore = mxmlFile2MsrSkeleton ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } } return mScore; } void runPass2b ( string inputSourceName, string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); if (inputSourceName == "-") { // input comes from standard input if (outputFileNameSize) mScore = mxmlFd2Msr ( stdin, gMsrOptions, gLogIOstream); else mScore = mxmlFd2Msr ( stdin, gMsrOptions, gLogIOstream); } else { // input comes from a file if (outputFileNameSize) { mScore = mxmlFile2Msr ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } else { mScore = mxmlFile2Msr ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } } /* JMI if (! mScore) { gLogIOstream << "### Conversion from MusicCML to MSR failed ###" << endl << endl; // JMI return false; } */ // JMI return true; } S_lpsrScore runPass3 ( string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); S_lpsrScore lpScore; if (! gLilypondOptions->fNoLilypondCode) { if (outputFileNameSize) { lpScore = msr2Lpsr ( mScore, gMsrOptions, gLpsrOptions, gLogIOstream); } else { lpScore = msr2Lpsr ( mScore, gMsrOptions, gLpsrOptions, gLogIOstream); } } return lpScore; } void runPass4 ( string outputFileName, S_lpsrScore lpScore) { int outputFileNameSize = outputFileName.size (); if (! gLilypondOptions->fNoLilypondCode) { // open output file if need be // ------------------------------------------------------ ofstream outFileStream; if (outputFileNameSize) { if (gGeneralOptions->fTraceGeneral) gLogIOstream << endl << "Opening file '" << outputFileName << "' for writing" << endl; outFileStream.open ( outputFileName.c_str(), ofstream::out); // create an indented output stream for the LilyPond code // to be written to outFileStream indentedOstream lilypondCodeFileOutputStream ( outFileStream, gIndenter); // convert the LPSR score to LilyPond code lpsr2Lilypond ( lpScore, gMsrOptions, gLpsrOptions, gLogIOstream, lilypondCodeFileOutputStream); } else { // create an indented output stream for the LilyPond code // to be written to cout indentedOstream lilypondCodeCoutOutputStream ( cout, gIndenter); lpsr2Lilypond ( lpScore, gMsrOptions, gLpsrOptions, gLogIOstream, lilypondCodeCoutOutputStream); } if (outputFileNameSize) { if (gGeneralOptions->fTraceGeneral) gLogIOstream << endl << "Closing file '" << outputFileName << "'" << endl; outFileStream.close (); } } } //_______________________________________________________________________________ int main (int argc, char *argv[]) { /* JMI cerr << "argc = " << argc << endl; for (int i = 0; i < argc ; i++ ) { cerr << "argv[ " << i << "] = " << argv[i] << endl; } */ // initialize the components of MSR that we'll be using // ------------------------------------------------------ initializeMSR (); initializeLPSR (); // create the options handler // ------------------------------------------------------ S_xml2lilypondOptionsHandler optionsHandler = xml2lilypondOptionsHandler::create ( gLogIOstream); // analyze the command line options and arguments // ------------------------------------------------------ vector<string> argumentsVector = handleOptionsAndArguments ( optionsHandler, argc, argv, gLogIOstream); // print the resulting options if (TRACE_OPTIONS) { gLogIOstream << optionsHandler << endl << endl; } string inputSourceName = gGeneralOptions->fInputSourceName; string outputFileName = gGeneralOptions->fOutputFileName; int outputFileNameSize = outputFileName.size (); // welcome message // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { gLogIOstream << "This is xml2Lilypond v" << currentVersionNumber () << " from libmusicxml2 v" << musicxmllibVersionStr () << endl; gLogIOstream << "Launching conversion of "; if (inputSourceName == "-") gLogIOstream << "standard input"; else gLogIOstream << "\"" << inputSourceName << "\""; gLogIOstream << " to LilyPond" << endl; gLogIOstream << "Time is " << gGeneralOptions->fTranslationDate << endl; gLogIOstream << "LilyPond code will be written to "; if (outputFileNameSize) { gLogIOstream << outputFileName; } else { gLogIOstream << "standard output"; } gLogIOstream << endl << endl; gLogIOstream << "The command line is:" << endl; gIndenter++; gLogIOstream << optionsHandler-> getCommandLineWithLongOptions () << endl; gIndenter--; gLogIOstream << "or:" << endl; gIndenter++; gLogIOstream << optionsHandler-> getCommandLineWithShortOptions () << endl << endl; gIndenter--; } // print the chosen LilyPond options // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { optionsHandler-> printOptionsValues ( gLogIOstream); } // acknoledge end of command line analysis // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { gLogIOstream << endl << "The command line options and arguments have been analyzed" << endl; } // create the MSR skeleton from MusicXML contents (pass 2a) // ------------------------------------------------------ S_msrScore mScore = runPass2a ( inputSourceName, outputFileName); if (! mScore) { gLogIOstream << "### Conversion from MusicCML to an MSR skeleton failed ###" << endl << endl; exit (1); } else if (! gGeneralOptions->fExit2a) { // create the MSR from MusicXML contents (pass 2b) // ------------------------------------------------------ runPass2b ( inputSourceName, outputFileName, mScore); if (! gGeneralOptions->fExit2b) { // create the LPSR from the MSR (pass 3) // ------------------------------------------------------ S_lpsrScore lpScore = runPass3 ( outputFileName, mScore); if (! lpScore) { gLogIOstream << "### Conversion from MSR to LPSR failed ###" << endl << endl; return 1; } else if (! gGeneralOptions->fExit3) { // generate LilyPond code from the LPSR (pass 4) // ------------------------------------------------------ runPass4 ( outputFileName, lpScore); } } } // print timing information // ------------------------------------------------------ if (gGeneralOptions->fDisplayCPUusage) timing::gTiming.print ( gLogIOstream); // over! // ------------------------------------------------------ if (! true) { // JMI gLogIOstream << "### Conversion from LPSR to LilyPond code failed ###" << endl << endl; return 1; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "UIManager.h" #include <react/core/ShadowNodeFragment.h> #include <react/debug/SystraceSection.h> #include <react/graphics/Geometry.h> #include <glog/logging.h> namespace facebook { namespace react { UIManager::~UIManager() { LOG(WARNING) << "UIManager::~UIManager() was called (address: " << this << ")."; } SharedShadowNode UIManager::createNode( Tag tag, std::string const &name, SurfaceId surfaceId, const RawProps &rawProps, SharedEventTarget eventTarget) const { SystraceSection s("UIManager::createNode"); auto &componentDescriptor = componentDescriptorRegistry_->at(name); auto fallbackDescriptor = componentDescriptorRegistry_->getFallbackComponentDescriptor(); auto family = componentDescriptor.createFamily( ShadowNodeFamilyFragment{tag, surfaceId, nullptr}, std::move(eventTarget)); auto const props = componentDescriptor.cloneProps(nullptr, rawProps); auto const state = componentDescriptor.createInitialState(ShadowNodeFragment{props}, family); auto shadowNode = componentDescriptor.createShadowNode( ShadowNodeFragment{ /* .props = */ fallbackDescriptor != nullptr && fallbackDescriptor->getComponentHandle() == componentDescriptor.getComponentHandle() ? componentDescriptor.cloneProps( props, RawProps(folly::dynamic::object("name", name))) : props, /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .state = */ state, }, family); if (delegate_) { delegate_->uiManagerDidCreateShadowNode(shadowNode); } return shadowNode; } SharedShadowNode UIManager::cloneNode( const ShadowNode::Shared &shadowNode, const SharedShadowNodeSharedList &children, const RawProps *rawProps) const { SystraceSection s("UIManager::cloneNode"); auto &componentDescriptor = shadowNode->getComponentDescriptor(); auto clonedShadowNode = componentDescriptor.cloneShadowNode( *shadowNode, { /* .props = */ rawProps ? componentDescriptor.cloneProps( shadowNode->getProps(), *rawProps) : ShadowNodeFragment::propsPlaceholder(), /* .children = */ children, }); return clonedShadowNode; } void UIManager::appendChild( const ShadowNode::Shared &parentShadowNode, const ShadowNode::Shared &childShadowNode) const { SystraceSection s("UIManager::appendChild"); auto &componentDescriptor = parentShadowNode->getComponentDescriptor(); componentDescriptor.appendChild(parentShadowNode, childShadowNode); } void UIManager::completeSurface( SurfaceId surfaceId, const SharedShadowNodeUnsharedList &rootChildren) const { SystraceSection s("UIManager::completeSurface"); shadowTreeRegistry_.visit(surfaceId, [&](ShadowTree const &shadowTree) { shadowTree.commit( [&](RootShadowNode::Shared const &oldRootShadowNode) { return std::make_shared<RootShadowNode>( *oldRootShadowNode, ShadowNodeFragment{ /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .children = */ rootChildren, }); }, true); }); } void UIManager::setJSResponder( const ShadowNode::Shared &shadowNode, const bool blockNativeResponder) const { if (delegate_) { delegate_->uiManagerDidSetJSResponder( shadowNode->getSurfaceId(), shadowNode, blockNativeResponder); } } void UIManager::clearJSResponder() const { if (delegate_) { delegate_->uiManagerDidClearJSResponder(); } } ShadowNode::Shared UIManager::getNewestCloneOfShadowNode( ShadowNode const &shadowNode) const { auto findNewestChildInParent = [&](auto const &parentNode) -> ShadowNode::Shared { for (auto const &child : parentNode.getChildren()) { if (ShadowNode::sameFamily(*child, shadowNode)) { return child; } } return nullptr; }; ShadowNode const *ancestorShadowNode; shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { ancestorShadowNode = oldRootShadowNode.get(); return nullptr; }, true); }); auto ancestors = shadowNode.getFamily().getAncestors(*ancestorShadowNode); return findNewestChildInParent(ancestors.rbegin()->first.get()); } ShadowNode::Shared UIManager::findNodeAtPoint( ShadowNode::Shared const &node, Point point) const { return LayoutableShadowNode::findNodeAtPoint( getNewestCloneOfShadowNode(*node), point); } void UIManager::setNativeProps( ShadowNode const &shadowNode, RawProps const &rawProps) const { SystraceSection s("UIManager::setNativeProps"); auto &componentDescriptor = shadowNode.getComponentDescriptor(); auto props = componentDescriptor.cloneProps(shadowNode.getProps(), rawProps); shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { return std::static_pointer_cast<RootShadowNode>( oldRootShadowNode->cloneTree( shadowNode.getFamily(), [&](ShadowNode const &oldShadowNode) { return oldShadowNode.clone({ /* .props = */ props, }); })); }, true); }); } LayoutMetrics UIManager::getRelativeLayoutMetrics( ShadowNode const &shadowNode, ShadowNode const *ancestorShadowNode, LayoutableShadowNode::LayoutInspectingPolicy policy) const { SystraceSection s("UIManager::getRelativeLayoutMetrics"); if (!ancestorShadowNode) { shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { ancestorShadowNode = oldRootShadowNode.get(); return nullptr; }, true); }); } else { ancestorShadowNode = getNewestCloneOfShadowNode(*ancestorShadowNode).get(); } // Get latest version of both the ShadowNode and its ancestor. // It is possible for JS (or other callers) to have a reference // to a previous version of ShadowNodes, but we enforce that // metrics are only calculated on most recently committed versions. auto newestShadowNode = getNewestCloneOfShadowNode(shadowNode); auto layoutableShadowNode = traitCast<LayoutableShadowNode const *>(newestShadowNode.get()); auto layoutableAncestorShadowNode = traitCast<LayoutableShadowNode const *>(ancestorShadowNode); if (!layoutableShadowNode || !layoutableAncestorShadowNode) { return EmptyLayoutMetrics; } return layoutableShadowNode->getRelativeLayoutMetrics( *layoutableAncestorShadowNode, policy); } void UIManager::updateState(StateUpdate const &stateUpdate) const { auto &callback = stateUpdate.callback; auto &family = stateUpdate.family; auto &componentDescriptor = family->getComponentDescriptor(); shadowTreeRegistry_.visit( family->getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit([&](RootShadowNode::Shared const &oldRootShadowNode) { return std::static_pointer_cast< RootShadowNode>(oldRootShadowNode->cloneTree( *family, [&](ShadowNode const &oldShadowNode) { auto newData = callback(oldShadowNode.getState()->getDataPointer()); auto newState = componentDescriptor.createState(*family, newData); return oldShadowNode.clone({ /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .state = */ newState, }); })); }); }); } void UIManager::dispatchCommand( const ShadowNode::Shared &shadowNode, std::string const &commandName, folly::dynamic const args) const { if (delegate_) { delegate_->uiManagerDidDispatchCommand(shadowNode, commandName, args); } } void UIManager::configureNextLayoutAnimation( const folly::dynamic config, SharedEventTarget successCallback, SharedEventTarget errorCallback) const {} void UIManager::setComponentDescriptorRegistry( const SharedComponentDescriptorRegistry &componentDescriptorRegistry) { componentDescriptorRegistry_ = componentDescriptorRegistry; } void UIManager::setDelegate(UIManagerDelegate *delegate) { delegate_ = delegate; } UIManagerDelegate *UIManager::getDelegate() { return delegate_; } void UIManager::visitBinding( std::function<void(UIManagerBinding const &uiManagerBinding)> callback) const { if (!uiManagerBinding_) { return; } callback(*uiManagerBinding_); } ShadowTreeRegistry const &UIManager::getShadowTreeRegistry() const { return shadowTreeRegistry_; } #pragma mark - ShadowTreeDelegate void UIManager::shadowTreeDidFinishTransaction( ShadowTree const &shadowTree, MountingCoordinator::Shared const &mountingCoordinator) const { SystraceSection s("UIManager::shadowTreeDidFinishTransaction"); if (delegate_) { delegate_->uiManagerDidFinishTransaction(mountingCoordinator); } } } // namespace react } // namespace facebook <commit_msg>Fabric: Making `UIManager::getRelativeLayoutMetrics` safer<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "UIManager.h" #include <react/core/ShadowNodeFragment.h> #include <react/debug/SystraceSection.h> #include <react/graphics/Geometry.h> #include <glog/logging.h> namespace facebook { namespace react { UIManager::~UIManager() { LOG(WARNING) << "UIManager::~UIManager() was called (address: " << this << ")."; } SharedShadowNode UIManager::createNode( Tag tag, std::string const &name, SurfaceId surfaceId, const RawProps &rawProps, SharedEventTarget eventTarget) const { SystraceSection s("UIManager::createNode"); auto &componentDescriptor = componentDescriptorRegistry_->at(name); auto fallbackDescriptor = componentDescriptorRegistry_->getFallbackComponentDescriptor(); auto family = componentDescriptor.createFamily( ShadowNodeFamilyFragment{tag, surfaceId, nullptr}, std::move(eventTarget)); auto const props = componentDescriptor.cloneProps(nullptr, rawProps); auto const state = componentDescriptor.createInitialState(ShadowNodeFragment{props}, family); auto shadowNode = componentDescriptor.createShadowNode( ShadowNodeFragment{ /* .props = */ fallbackDescriptor != nullptr && fallbackDescriptor->getComponentHandle() == componentDescriptor.getComponentHandle() ? componentDescriptor.cloneProps( props, RawProps(folly::dynamic::object("name", name))) : props, /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .state = */ state, }, family); if (delegate_) { delegate_->uiManagerDidCreateShadowNode(shadowNode); } return shadowNode; } SharedShadowNode UIManager::cloneNode( const ShadowNode::Shared &shadowNode, const SharedShadowNodeSharedList &children, const RawProps *rawProps) const { SystraceSection s("UIManager::cloneNode"); auto &componentDescriptor = shadowNode->getComponentDescriptor(); auto clonedShadowNode = componentDescriptor.cloneShadowNode( *shadowNode, { /* .props = */ rawProps ? componentDescriptor.cloneProps( shadowNode->getProps(), *rawProps) : ShadowNodeFragment::propsPlaceholder(), /* .children = */ children, }); return clonedShadowNode; } void UIManager::appendChild( const ShadowNode::Shared &parentShadowNode, const ShadowNode::Shared &childShadowNode) const { SystraceSection s("UIManager::appendChild"); auto &componentDescriptor = parentShadowNode->getComponentDescriptor(); componentDescriptor.appendChild(parentShadowNode, childShadowNode); } void UIManager::completeSurface( SurfaceId surfaceId, const SharedShadowNodeUnsharedList &rootChildren) const { SystraceSection s("UIManager::completeSurface"); shadowTreeRegistry_.visit(surfaceId, [&](ShadowTree const &shadowTree) { shadowTree.commit( [&](RootShadowNode::Shared const &oldRootShadowNode) { return std::make_shared<RootShadowNode>( *oldRootShadowNode, ShadowNodeFragment{ /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .children = */ rootChildren, }); }, true); }); } void UIManager::setJSResponder( const ShadowNode::Shared &shadowNode, const bool blockNativeResponder) const { if (delegate_) { delegate_->uiManagerDidSetJSResponder( shadowNode->getSurfaceId(), shadowNode, blockNativeResponder); } } void UIManager::clearJSResponder() const { if (delegate_) { delegate_->uiManagerDidClearJSResponder(); } } ShadowNode::Shared UIManager::getNewestCloneOfShadowNode( ShadowNode const &shadowNode) const { auto findNewestChildInParent = [&](auto const &parentNode) -> ShadowNode::Shared { for (auto const &child : parentNode.getChildren()) { if (ShadowNode::sameFamily(*child, shadowNode)) { return child; } } return nullptr; }; ShadowNode const *ancestorShadowNode; shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { ancestorShadowNode = oldRootShadowNode.get(); return nullptr; }, true); }); auto ancestors = shadowNode.getFamily().getAncestors(*ancestorShadowNode); return findNewestChildInParent(ancestors.rbegin()->first.get()); } ShadowNode::Shared UIManager::findNodeAtPoint( ShadowNode::Shared const &node, Point point) const { return LayoutableShadowNode::findNodeAtPoint( getNewestCloneOfShadowNode(*node), point); } void UIManager::setNativeProps( ShadowNode const &shadowNode, RawProps const &rawProps) const { SystraceSection s("UIManager::setNativeProps"); auto &componentDescriptor = shadowNode.getComponentDescriptor(); auto props = componentDescriptor.cloneProps(shadowNode.getProps(), rawProps); shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { return std::static_pointer_cast<RootShadowNode>( oldRootShadowNode->cloneTree( shadowNode.getFamily(), [&](ShadowNode const &oldShadowNode) { return oldShadowNode.clone({ /* .props = */ props, }); })); }, true); }); } LayoutMetrics UIManager::getRelativeLayoutMetrics( ShadowNode const &shadowNode, ShadowNode const *ancestorShadowNode, LayoutableShadowNode::LayoutInspectingPolicy policy) const { SystraceSection s("UIManager::getRelativeLayoutMetrics"); // We might store here an owning pointer to `ancestorShadowNode` to ensure // that the node is not deallocated during method execution lifetime. auto owningAncestorShadowNode = ShadowNode::Shared{}; if (!ancestorShadowNode) { shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { ancestorShadowNode = oldRootShadowNode.get(); return nullptr; }, true); }); } else { owningAncestorShadowNode = getNewestCloneOfShadowNode(*ancestorShadowNode); ancestorShadowNode = owningAncestorShadowNode.get(); } // Get latest version of both the ShadowNode and its ancestor. // It is possible for JS (or other callers) to have a reference // to a previous version of ShadowNodes, but we enforce that // metrics are only calculated on most recently committed versions. auto newestShadowNode = getNewestCloneOfShadowNode(shadowNode); auto layoutableShadowNode = traitCast<LayoutableShadowNode const *>(newestShadowNode.get()); auto layoutableAncestorShadowNode = traitCast<LayoutableShadowNode const *>(ancestorShadowNode); if (!layoutableShadowNode || !layoutableAncestorShadowNode) { return EmptyLayoutMetrics; } return layoutableShadowNode->getRelativeLayoutMetrics( *layoutableAncestorShadowNode, policy); } void UIManager::updateState(StateUpdate const &stateUpdate) const { auto &callback = stateUpdate.callback; auto &family = stateUpdate.family; auto &componentDescriptor = family->getComponentDescriptor(); shadowTreeRegistry_.visit( family->getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit([&](RootShadowNode::Shared const &oldRootShadowNode) { return std::static_pointer_cast< RootShadowNode>(oldRootShadowNode->cloneTree( *family, [&](ShadowNode const &oldShadowNode) { auto newData = callback(oldShadowNode.getState()->getDataPointer()); auto newState = componentDescriptor.createState(*family, newData); return oldShadowNode.clone({ /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .state = */ newState, }); })); }); }); } void UIManager::dispatchCommand( const ShadowNode::Shared &shadowNode, std::string const &commandName, folly::dynamic const args) const { if (delegate_) { delegate_->uiManagerDidDispatchCommand(shadowNode, commandName, args); } } void UIManager::configureNextLayoutAnimation( const folly::dynamic config, SharedEventTarget successCallback, SharedEventTarget errorCallback) const {} void UIManager::setComponentDescriptorRegistry( const SharedComponentDescriptorRegistry &componentDescriptorRegistry) { componentDescriptorRegistry_ = componentDescriptorRegistry; } void UIManager::setDelegate(UIManagerDelegate *delegate) { delegate_ = delegate; } UIManagerDelegate *UIManager::getDelegate() { return delegate_; } void UIManager::visitBinding( std::function<void(UIManagerBinding const &uiManagerBinding)> callback) const { if (!uiManagerBinding_) { return; } callback(*uiManagerBinding_); } ShadowTreeRegistry const &UIManager::getShadowTreeRegistry() const { return shadowTreeRegistry_; } #pragma mark - ShadowTreeDelegate void UIManager::shadowTreeDidFinishTransaction( ShadowTree const &shadowTree, MountingCoordinator::Shared const &mountingCoordinator) const { SystraceSection s("UIManager::shadowTreeDidFinishTransaction"); if (delegate_) { delegate_->uiManagerDidFinishTransaction(mountingCoordinator); } } } // namespace react } // namespace facebook <|endoftext|>
<commit_before>#include "clang/Basic/FileManager.h" #include "clang/Index/IndexUnitReader.h" #include "clang/Index/IndexUnitWriter.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <cstdlib> #include <regex> #include <set> #include <string> #include <vector> #include <copyfile.h> using namespace llvm; using namespace llvm::sys; using namespace clang; using namespace clang::index; using namespace clang::index::writer; static cl::list<std::string> PathRemaps("remap", cl::OneOrMore, cl::desc("Path remapping substitution"), cl::value_desc("regex=replacement")); static cl::alias PathRemapsAlias("r", cl::aliasopt(PathRemaps)); static cl::opt<std::string> InputIndexPath(cl::Positional, cl::Required, cl::desc("<input-indexstore>")); static cl::opt<std::string> OutputIndexPath(cl::Positional, cl::Required, cl::desc("<output-indexstore>")); static cl::opt<bool> Verbose("verbose", cl::desc("Print path remapping results")); static cl::alias VerboseAlias("V", cl::aliasopt(Verbose)); struct Remapper { public: // Parse the the path remapping command line flags. This converts strings of // "X=Y" into a (regex, string) pair. Another way of looking at it: each remap // is equivalent to the s/pattern/replacement/ operator. static Remapper createFromCommandLine(const cl::list<std::string> &remaps) { Remapper remapper; for (const auto &remap : remaps) { auto divider = remap.find('='); std::regex pattern{remap.substr(0, divider)}; auto replacement = remap.substr(divider + 1); remapper.addRemap(pattern, replacement); } return remapper; } std::string remap(const std::string &input) const { for (const auto &remap : this->_remaps) { const auto &pattern = std::get<std::regex>(remap); const auto &replacement = std::get<std::string>(remap); std::smatch match; if (std::regex_search(input, match, pattern)) { // I haven't seen this design in other regex APIs, and is worth some // explanation. The replacement string is conceptually a format string. // The format() function takes no explicit arguments, instead it gets // the values from the match object. auto substitution = match.format(replacement); return match.prefix().str() + substitution + match.suffix().str(); } } // No patterns matched, return the input unaltered. return input; } private: void addRemap(const std::regex &pattern, const std::string &replacement) { this->_remaps.emplace_back(pattern, replacement); } std::vector<std::pair<std::regex, std::string>> _remaps; }; // Helper for working with index::writer::OpaqueModule. Provides the following: // 1. Storage for module name StringRef values // 2. Function to store module names, and return an OpaqueModule handle // 3. Implementation of ModuleInfoWriterCallback struct ModuleNameScope { // Stores a copy of `moduleName` and returns a handle. OpaqueModule getReference(StringRef moduleName) { const auto insertion = this->_moduleNames.insert(moduleName); return &(*insertion.first); } // Implementation of ModuleInfoWriterCallback, which is an unusual API. When // adding dependencies to Units, the module name is passed not as a string, // but instead as an opaque pointer. This callback then maps the opaque // pointer to a module name string. static ModuleInfo getModuleInfo(OpaqueModule ref, SmallVectorImpl<char> &) { // In this implementation, `mod` is a pointer into `_moduleNames`. auto moduleName = static_cast<const StringRef *>(ref); return {*moduleName}; } private: std::set<StringRef> _moduleNames; }; static IndexUnitWriter remapUnit(const std::unique_ptr<IndexUnitReader> &reader, const Remapper &remapper, FileManager &fileMgr, ModuleNameScope &moduleNames) { // The set of remapped paths. auto workingDir = remapper.remap(reader->getWorkingDirectory()); auto outputFile = remapper.remap(reader->getOutputFile()); auto mainFilePath = remapper.remap(reader->getMainFilePath()); auto sysrootPath = remapper.remap(reader->getSysrootPath()); if (Verbose) { llvm::outs() << "MainFilePath: " << mainFilePath << "\n" << "OutputFile: " << outputFile << "\n" << "WorkingDir: " << workingDir << "\n" << "SysrootPath: " << sysrootPath << "\n"; } auto &fsOpts = fileMgr.getFileSystemOpts(); fsOpts.WorkingDir = workingDir; auto writer = IndexUnitWriter( fileMgr, OutputIndexPath, reader->getProviderIdentifier(), reader->getProviderVersion(), outputFile, reader->getModuleName(), fileMgr.getFile(mainFilePath), reader->isSystemUnit(), reader->isModuleUnit(), reader->isDebugCompilation(), reader->getTarget(), sysrootPath, moduleNames.getModuleInfo); reader->foreachDependency([&](const IndexUnitReader::DependencyInfo &info) { const auto name = info.UnitOrRecordName; const auto moduleNameRef = moduleNames.getReference(info.ModuleName); const auto isSystem = info.IsSystem; const auto filePath = remapper.remap(info.FilePath); auto file = fileMgr.getFile(filePath); // The unit may reference a file that does not exist, for example if a build // was cleaned. This can cause assertions, or lead to missing file paths in // the unit file. When a file does not exist, fall back to getVirtualFile(), // which accepts missing files. if (not file) { file = fileMgr.getVirtualFile(filePath, /*size*/ 0, /*mod time*/ 0); } if (Verbose) { llvm::outs() << "DependencyFilePath: " << filePath << "\n"; } switch (info.Kind) { case IndexUnitReader::DependencyKind::Unit: { // The UnitOrRecordName from the input is not used. This is because the // unit name must be computed from the new (remapped) file path. // // However, a name is only computed if the input has a name. If the // input does not have a name, then don't write a name to the output. SmallString<128> unitName; if (name != "") { writer.getUnitNameForOutputFile(filePath, unitName); if (Verbose) { llvm::outs() << "DependencyUnitName: " << unitName << "\n"; } } writer.addUnitDependency(unitName, file, isSystem, moduleNameRef); break; } case IndexUnitReader::DependencyKind::Record: writer.addRecordFile(name, file, isSystem, moduleNameRef); break; case IndexUnitReader::DependencyKind::File: { writer.addFileDependency(file, isSystem, moduleNameRef); break; } } return true; }); reader->foreachInclude([&](const IndexUnitReader::IncludeInfo &info) { // Note this isn't revelevnt to Swift. writer.addInclude(fileMgr.getFile(info.SourcePath), info.SourceLine, fileMgr.getFile(info.TargetPath)); return true; }); return writer; } static bool cloneRecords(StringRef recordsDirectory, const std::string &inputIndexPath, const std::string &outputIndexPath) { bool success = true; std::error_code dirError; fs::recursive_directory_iterator dir{recordsDirectory, dirError}; fs::recursive_directory_iterator end; for (; dir != end && !dirError; dir.increment(dirError)) { const auto status = dir->status(); if (status.getError()) { success = false; llvm::errs() << "error: Could not access file status of path " << dir->path() << "\n"; continue; } auto inputPath = dir->path(); SmallString<128> outputPath{inputPath}; path::replace_path_prefix(outputPath, inputIndexPath, outputIndexPath); std::error_code failed; if (status->type() == fs::file_type::directory_file) { if (not fs::exists(outputPath)) { failed = fs::create_directory(outputPath); } } else if (status->type() == fs::file_type::regular_file) { // Two record files of the same name are guaranteed to have the same // contents (because they include a hash of their contents in their // file name). If the destination record file already exists, it // doesn't need to be cloned or copied. if (not fs::exists(outputPath)) { failed = fs::copy_file(inputPath, outputPath); } } if (failed) { success = false; llvm::errs() << "error: " << strerror(errno) << "\n" << "\tcould not copy record file: " << inputPath << "\n"; } } if (dirError) { success = false; llvm::errs() << "error: aborted while reading from records directory: " << dirError.message() << "\n"; } return success; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); auto remapper = Remapper::createFromCommandLine(PathRemaps); std::string initOutputIndexError; if (IndexUnitWriter::initIndexDirectory(OutputIndexPath, initOutputIndexError)) { llvm::errs() << "error: failed to initialize index store; " << initOutputIndexError << "\n"; return EXIT_FAILURE; } SmallString<256> unitDirectory; path::append(unitDirectory, InputIndexPath, "v5", "units"); SmallString<256> recordsDirectory; path::append(recordsDirectory, InputIndexPath, "v5", "records"); if (not fs::is_directory(unitDirectory) || not fs::is_directory(recordsDirectory)) { llvm::errs() << "error: invalid index store directory " << InputIndexPath << "\n"; return EXIT_FAILURE; } bool success = true; if (not cloneRecords(recordsDirectory, InputIndexPath, OutputIndexPath)) { success = false; } FileSystemOptions fsOpts; FileManager fileMgr{fsOpts}; std::error_code dirError; fs::directory_iterator dir{unitDirectory, dirError}; fs::directory_iterator end; while (dir != end && !dirError) { const auto unitPath = dir->path(); dir.increment(dirError); if (unitPath.empty()) { // The directory iterator returns a single empty path, ignore it. continue; } std::string unitReadError; auto reader = IndexUnitReader::createWithFilePath(unitPath, unitReadError); if (not reader) { llvm::errs() << "error: failed to read unit file " << unitPath << "\n" << unitReadError; success = false; continue; } ModuleNameScope moduleNames; auto writer = remapUnit(reader, remapper, fileMgr, moduleNames); std::string unitWriteError; if (writer.write(unitWriteError)) { llvm::errs() << "error: failed to write index store; " << unitWriteError << "\n"; success = false; } } if (dirError) { llvm::errs() << "error: aborted while reading from unit directory: " << dirError.message() << "\n"; success = false; } return success ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>Remove unnecessary {} around case body (#10)<commit_after>#include "clang/Basic/FileManager.h" #include "clang/Index/IndexUnitReader.h" #include "clang/Index/IndexUnitWriter.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <cstdlib> #include <regex> #include <set> #include <string> #include <vector> #include <copyfile.h> using namespace llvm; using namespace llvm::sys; using namespace clang; using namespace clang::index; using namespace clang::index::writer; static cl::list<std::string> PathRemaps("remap", cl::OneOrMore, cl::desc("Path remapping substitution"), cl::value_desc("regex=replacement")); static cl::alias PathRemapsAlias("r", cl::aliasopt(PathRemaps)); static cl::opt<std::string> InputIndexPath(cl::Positional, cl::Required, cl::desc("<input-indexstore>")); static cl::opt<std::string> OutputIndexPath(cl::Positional, cl::Required, cl::desc("<output-indexstore>")); static cl::opt<bool> Verbose("verbose", cl::desc("Print path remapping results")); static cl::alias VerboseAlias("V", cl::aliasopt(Verbose)); struct Remapper { public: // Parse the the path remapping command line flags. This converts strings of // "X=Y" into a (regex, string) pair. Another way of looking at it: each remap // is equivalent to the s/pattern/replacement/ operator. static Remapper createFromCommandLine(const cl::list<std::string> &remaps) { Remapper remapper; for (const auto &remap : remaps) { auto divider = remap.find('='); std::regex pattern{remap.substr(0, divider)}; auto replacement = remap.substr(divider + 1); remapper.addRemap(pattern, replacement); } return remapper; } std::string remap(const std::string &input) const { for (const auto &remap : this->_remaps) { const auto &pattern = std::get<std::regex>(remap); const auto &replacement = std::get<std::string>(remap); std::smatch match; if (std::regex_search(input, match, pattern)) { // I haven't seen this design in other regex APIs, and is worth some // explanation. The replacement string is conceptually a format string. // The format() function takes no explicit arguments, instead it gets // the values from the match object. auto substitution = match.format(replacement); return match.prefix().str() + substitution + match.suffix().str(); } } // No patterns matched, return the input unaltered. return input; } private: void addRemap(const std::regex &pattern, const std::string &replacement) { this->_remaps.emplace_back(pattern, replacement); } std::vector<std::pair<std::regex, std::string>> _remaps; }; // Helper for working with index::writer::OpaqueModule. Provides the following: // 1. Storage for module name StringRef values // 2. Function to store module names, and return an OpaqueModule handle // 3. Implementation of ModuleInfoWriterCallback struct ModuleNameScope { // Stores a copy of `moduleName` and returns a handle. OpaqueModule getReference(StringRef moduleName) { const auto insertion = this->_moduleNames.insert(moduleName); return &(*insertion.first); } // Implementation of ModuleInfoWriterCallback, which is an unusual API. When // adding dependencies to Units, the module name is passed not as a string, // but instead as an opaque pointer. This callback then maps the opaque // pointer to a module name string. static ModuleInfo getModuleInfo(OpaqueModule ref, SmallVectorImpl<char> &) { // In this implementation, `mod` is a pointer into `_moduleNames`. auto moduleName = static_cast<const StringRef *>(ref); return {*moduleName}; } private: std::set<StringRef> _moduleNames; }; static IndexUnitWriter remapUnit(const std::unique_ptr<IndexUnitReader> &reader, const Remapper &remapper, FileManager &fileMgr, ModuleNameScope &moduleNames) { // The set of remapped paths. auto workingDir = remapper.remap(reader->getWorkingDirectory()); auto outputFile = remapper.remap(reader->getOutputFile()); auto mainFilePath = remapper.remap(reader->getMainFilePath()); auto sysrootPath = remapper.remap(reader->getSysrootPath()); if (Verbose) { llvm::outs() << "MainFilePath: " << mainFilePath << "\n" << "OutputFile: " << outputFile << "\n" << "WorkingDir: " << workingDir << "\n" << "SysrootPath: " << sysrootPath << "\n"; } auto &fsOpts = fileMgr.getFileSystemOpts(); fsOpts.WorkingDir = workingDir; auto writer = IndexUnitWriter( fileMgr, OutputIndexPath, reader->getProviderIdentifier(), reader->getProviderVersion(), outputFile, reader->getModuleName(), fileMgr.getFile(mainFilePath), reader->isSystemUnit(), reader->isModuleUnit(), reader->isDebugCompilation(), reader->getTarget(), sysrootPath, moduleNames.getModuleInfo); reader->foreachDependency([&](const IndexUnitReader::DependencyInfo &info) { const auto name = info.UnitOrRecordName; const auto moduleNameRef = moduleNames.getReference(info.ModuleName); const auto isSystem = info.IsSystem; const auto filePath = remapper.remap(info.FilePath); auto file = fileMgr.getFile(filePath); // The unit may reference a file that does not exist, for example if a build // was cleaned. This can cause assertions, or lead to missing file paths in // the unit file. When a file does not exist, fall back to getVirtualFile(), // which accepts missing files. if (not file) { file = fileMgr.getVirtualFile(filePath, /*size*/ 0, /*mod time*/ 0); } if (Verbose) { llvm::outs() << "DependencyFilePath: " << filePath << "\n"; } switch (info.Kind) { case IndexUnitReader::DependencyKind::Unit: { // The UnitOrRecordName from the input is not used. This is because the // unit name must be computed from the new (remapped) file path. // // However, a name is only computed if the input has a name. If the // input does not have a name, then don't write a name to the output. SmallString<128> unitName; if (name != "") { writer.getUnitNameForOutputFile(filePath, unitName); if (Verbose) { llvm::outs() << "DependencyUnitName: " << unitName << "\n"; } } writer.addUnitDependency(unitName, file, isSystem, moduleNameRef); break; } case IndexUnitReader::DependencyKind::Record: writer.addRecordFile(name, file, isSystem, moduleNameRef); break; case IndexUnitReader::DependencyKind::File: writer.addFileDependency(file, isSystem, moduleNameRef); break; } return true; }); reader->foreachInclude([&](const IndexUnitReader::IncludeInfo &info) { // Note this isn't revelevnt to Swift. writer.addInclude(fileMgr.getFile(info.SourcePath), info.SourceLine, fileMgr.getFile(info.TargetPath)); return true; }); return writer; } static bool cloneRecords(StringRef recordsDirectory, const std::string &inputIndexPath, const std::string &outputIndexPath) { bool success = true; std::error_code dirError; fs::recursive_directory_iterator dir{recordsDirectory, dirError}; fs::recursive_directory_iterator end; for (; dir != end && !dirError; dir.increment(dirError)) { const auto status = dir->status(); if (status.getError()) { success = false; llvm::errs() << "error: Could not access file status of path " << dir->path() << "\n"; continue; } auto inputPath = dir->path(); SmallString<128> outputPath{inputPath}; path::replace_path_prefix(outputPath, inputIndexPath, outputIndexPath); std::error_code failed; if (status->type() == fs::file_type::directory_file) { if (not fs::exists(outputPath)) { failed = fs::create_directory(outputPath); } } else if (status->type() == fs::file_type::regular_file) { // Two record files of the same name are guaranteed to have the same // contents (because they include a hash of their contents in their // file name). If the destination record file already exists, it // doesn't need to be cloned or copied. if (not fs::exists(outputPath)) { failed = fs::copy_file(inputPath, outputPath); } } if (failed) { success = false; llvm::errs() << "error: " << strerror(errno) << "\n" << "\tcould not copy record file: " << inputPath << "\n"; } } if (dirError) { success = false; llvm::errs() << "error: aborted while reading from records directory: " << dirError.message() << "\n"; } return success; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); auto remapper = Remapper::createFromCommandLine(PathRemaps); std::string initOutputIndexError; if (IndexUnitWriter::initIndexDirectory(OutputIndexPath, initOutputIndexError)) { llvm::errs() << "error: failed to initialize index store; " << initOutputIndexError << "\n"; return EXIT_FAILURE; } SmallString<256> unitDirectory; path::append(unitDirectory, InputIndexPath, "v5", "units"); SmallString<256> recordsDirectory; path::append(recordsDirectory, InputIndexPath, "v5", "records"); if (not fs::is_directory(unitDirectory) || not fs::is_directory(recordsDirectory)) { llvm::errs() << "error: invalid index store directory " << InputIndexPath << "\n"; return EXIT_FAILURE; } bool success = true; if (not cloneRecords(recordsDirectory, InputIndexPath, OutputIndexPath)) { success = false; } FileSystemOptions fsOpts; FileManager fileMgr{fsOpts}; std::error_code dirError; fs::directory_iterator dir{unitDirectory, dirError}; fs::directory_iterator end; while (dir != end && !dirError) { const auto unitPath = dir->path(); dir.increment(dirError); if (unitPath.empty()) { // The directory iterator returns a single empty path, ignore it. continue; } std::string unitReadError; auto reader = IndexUnitReader::createWithFilePath(unitPath, unitReadError); if (not reader) { llvm::errs() << "error: failed to read unit file " << unitPath << "\n" << unitReadError; success = false; continue; } ModuleNameScope moduleNames; auto writer = remapUnit(reader, remapper, fileMgr, moduleNames); std::string unitWriteError; if (writer.write(unitWriteError)) { llvm::errs() << "error: failed to write index store; " << unitWriteError << "\n"; success = false; } } if (dirError) { llvm::errs() << "error: aborted while reading from unit directory: " << dirError.message() << "\n"; success = false; } return success ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>#include <rtos.h> #include <vector> #include <memory> #include <CommModule.hpp> #include <CommPort.hpp> #include <CC1201Radio.hpp> #include <helper-funcs.hpp> #include <logger.hpp> #include <assert.hpp> #include "robot-devices.hpp" #include "task-signals.hpp" #include "task-globals.hpp" #include "io-expander.hpp" #include "fpga.hpp" using namespace std; /* * Information about the radio protocol can be found at: * https://www.overleaf.com/2187548nsfdps */ void loopback_ack_pck(rtp::packet* p) { rtp::packet ack_pck = *p; CommModule::Instance()->send(ack_pck); } void legacy_rx_cb(rtp::packet* p) { if (p->payload.size()) { LOG(OK, "Legacy rx successful!\r\n" " Received: %u bytes\r\n", p->payload.size()); } else { LOG(WARN, "Received empty packet on Legacy interface"); } } void loopback_rx_cb(rtp::packet* p) { vector<uint16_t> duty_cycles; duty_cycles.assign(5, 100); for (size_t i = 0; i < duty_cycles.size(); ++i) duty_cycles.at(i) = 100 + 206 * i; if (p->payload.size()) { LOG(OK, "Loopback rx successful!\r\n" " Received: %u bytes", p->payload.size()); /* if (p->subclass() == 1) { uint16_t status_byte = FPGA::Instance()->set_duty_cycles( duty_cycles.data(), duty_cycles.size()); // grab the bottom 4 bits status_byte &= 0x000F; // flip bits 1 & 2 status_byte = (status_byte & 0x000C) | ((status_byte >> 1) & 0x0001) | ((status_byte << 1) & 0x0002); // bit 3 goes to the 6th position status_byte |= ((status_byte >> 2) << 5) & 0x0023; // bit 4 goes to the 8th position status_byte |= ((status_byte >> 3) << 7); // shift it all up a byte status_byte <<= 8; // All motors error LEDs MCP23017::Instance()->writeMask(status_byte, 0xA300); // M1 error LED // MCP23017::Instance()->writeMask(~(1 << (8 + 1)), 0xFF00); // M2 error LED // MCP23017::Instance()->writeMask(~(1 << (8 + 0)), 0xFF00); // M3 error LED // MCP23017::Instance()->writeMask(~(1 << (8 + 5)), 0xFF00); // M4 error LED // MCP23017::Instance()->writeMask(~(1 << (8 + 7)), 0xFF00); } */ } else { LOG(WARN, "Received empty packet on loopback interface"); } } void loopback_tx_cb(rtp::packet* p) { if (p->payload.size()) { LOG(OK, "Loopback tx successful!\r\n" " Sent: %u bytes\r\n", p->payload.size()); } else { LOG(WARN, "Sent empty packet on loopback interface"); } CommModule::Instance()->receive(*p); } /* Uncomment the below DigitalOut lines and comment out the * ones above to use the mbed's on-board LEDs. */ // static DigitalOut tx_led(LED3, 0); // static DigitalOut rx_led(LED2, 0); // Setup some lights that will blink whenever we send/receive packets const DigitalInOut tx_led(RJ_TX_LED, PIN_OUTPUT, OpenDrain, 1); const DigitalInOut rx_led(RJ_RX_LED, PIN_OUTPUT, OpenDrain, 1); shared_ptr<RtosTimer> rx_led_ticker; shared_ptr<RtosTimer> tx_led_ticker; void InitializeCommModule() { // Startup the CommModule interface shared_ptr<CommModule> commModule = CommModule::Instance(); // initialize and start LED ticker timers rx_led_ticker = make_shared<RtosTimer>(commLightsTask_RX, osTimerPeriodic, (void*)&rx_led); tx_led_ticker = make_shared<RtosTimer>(commLightsTask_TX, osTimerPeriodic, (void*)&tx_led); rx_led_ticker->start(80); tx_led_ticker->start(80); // TODO(justin): remove this // Create a new physical hardware communication link global_radio = new CC1201(RJ_SPI_BUS, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings, sizeof(preferredSettings) / sizeof(registerSetting_t)); // Open a socket for running tests across the link layer // The LINK port handlers are always active, regardless of whether or not a // working radio is connected. commModule->setRxHandler(&loopback_rx_cb, rtp::port::LINK); commModule->setTxHandler(&loopback_tx_cb, rtp::port::LINK); /* * Ports are always displayed in ascending (lowest -> highest) order * according to its port number when using the console. */ if (global_radio->isConnected() == true) { LOG(INIT, "Radio interface ready on %3.2fMHz!\r\n", global_radio->freq()); // The usual way of opening a port. commModule->setRxHandler(&loopback_rx_cb, rtp::port::DISCOVER); commModule->setTxHandler((CommLink*)global_radio, &CommLink::sendPacket, rtp::port::DISCOVER); // This port won't open since there's no RX callback to invoke. The // packets are simply dropped. commModule->setRxHandler(&loopback_rx_cb, rtp::port::LOGGER); commModule->setTxHandler((CommLink*)global_radio, &CommLink::sendPacket, rtp::port::LOGGER); // Legacy port commModule->setTxHandler((CommLink*)global_radio, &CommLink::sendPacket, rtp::port::LEGACY); commModule->setRxHandler(&legacy_rx_cb, rtp::port::LEGACY); LOG(INIT, "%u sockets opened", commModule->numOpenSockets()); // Wait until the threads with the commModule->lass are all started up // and ready while (!commModule->isReady()) { Thread::wait(50); } MCP23017::Instance()->writeMask(1 << (8 + 2), 1 << (8 + 2)); // Set the error code's valid bit comm_err |= 1 << 0; } else { LOG(FATAL, "No radio interface found!\r\n"); // Set the error flag - bit positions are pretty arbitruary as of now comm_err |= 1 << 1; // Set the error code's valid bit comm_err |= 1 << 0; // Wait until the threads with the commModule->lass are all started up // and ready while (!commModule->isReady()) { Thread::wait(50); } // Radio error LED MCP23017::Instance()->writeMask(~(1 << (8 + 2)), 1 << (8 + 2)); } } <commit_msg>rm newline<commit_after>#include <rtos.h> #include <vector> #include <memory> #include <CommModule.hpp> #include <CommPort.hpp> #include <CC1201Radio.hpp> #include <helper-funcs.hpp> #include <logger.hpp> #include <assert.hpp> #include "robot-devices.hpp" #include "task-signals.hpp" #include "task-globals.hpp" #include "io-expander.hpp" #include "fpga.hpp" using namespace std; /* * Information about the radio protocol can be found at: * https://www.overleaf.com/2187548nsfdps */ void loopback_ack_pck(rtp::packet* p) { rtp::packet ack_pck = *p; CommModule::Instance()->send(ack_pck); } void legacy_rx_cb(rtp::packet* p) { if (p->payload.size()) { LOG(OK, "Legacy rx successful!\r\n" " Received: %u bytes\r\n", p->payload.size()); } else { LOG(WARN, "Received empty packet on Legacy interface"); } } void loopback_rx_cb(rtp::packet* p) { vector<uint16_t> duty_cycles; duty_cycles.assign(5, 100); for (size_t i = 0; i < duty_cycles.size(); ++i) duty_cycles.at(i) = 100 + 206 * i; if (p->payload.size()) { LOG(OK, "Loopback rx successful!\r\n" " Received: %u bytes", p->payload.size()); /* if (p->subclass() == 1) { uint16_t status_byte = FPGA::Instance()->set_duty_cycles( duty_cycles.data(), duty_cycles.size()); // grab the bottom 4 bits status_byte &= 0x000F; // flip bits 1 & 2 status_byte = (status_byte & 0x000C) | ((status_byte >> 1) & 0x0001) | ((status_byte << 1) & 0x0002); // bit 3 goes to the 6th position status_byte |= ((status_byte >> 2) << 5) & 0x0023; // bit 4 goes to the 8th position status_byte |= ((status_byte >> 3) << 7); // shift it all up a byte status_byte <<= 8; // All motors error LEDs MCP23017::Instance()->writeMask(status_byte, 0xA300); // M1 error LED // MCP23017::Instance()->writeMask(~(1 << (8 + 1)), 0xFF00); // M2 error LED // MCP23017::Instance()->writeMask(~(1 << (8 + 0)), 0xFF00); // M3 error LED // MCP23017::Instance()->writeMask(~(1 << (8 + 5)), 0xFF00); // M4 error LED // MCP23017::Instance()->writeMask(~(1 << (8 + 7)), 0xFF00); } */ } else { LOG(WARN, "Received empty packet on loopback interface"); } } void loopback_tx_cb(rtp::packet* p) { if (p->payload.size()) { LOG(OK, "Loopback tx successful!\r\n" " Sent: %u bytes\r\n", p->payload.size()); } else { LOG(WARN, "Sent empty packet on loopback interface"); } CommModule::Instance()->receive(*p); } /* Uncomment the below DigitalOut lines and comment out the * ones above to use the mbed's on-board LEDs. */ // static DigitalOut tx_led(LED3, 0); // static DigitalOut rx_led(LED2, 0); // Setup some lights that will blink whenever we send/receive packets const DigitalInOut tx_led(RJ_TX_LED, PIN_OUTPUT, OpenDrain, 1); const DigitalInOut rx_led(RJ_RX_LED, PIN_OUTPUT, OpenDrain, 1); shared_ptr<RtosTimer> rx_led_ticker; shared_ptr<RtosTimer> tx_led_ticker; void InitializeCommModule() { // Startup the CommModule interface shared_ptr<CommModule> commModule = CommModule::Instance(); // initialize and start LED ticker timers rx_led_ticker = make_shared<RtosTimer>(commLightsTask_RX, osTimerPeriodic, (void*)&rx_led); tx_led_ticker = make_shared<RtosTimer>(commLightsTask_TX, osTimerPeriodic, (void*)&tx_led); rx_led_ticker->start(80); tx_led_ticker->start(80); // TODO(justin): remove this // Create a new physical hardware communication link global_radio = new CC1201(RJ_SPI_BUS, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings, sizeof(preferredSettings) / sizeof(registerSetting_t)); // Open a socket for running tests across the link layer // The LINK port handlers are always active, regardless of whether or not a // working radio is connected. commModule->setRxHandler(&loopback_rx_cb, rtp::port::LINK); commModule->setTxHandler(&loopback_tx_cb, rtp::port::LINK); /* * Ports are always displayed in ascending (lowest -> highest) order * according to its port number when using the console. */ if (global_radio->isConnected() == true) { LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq()); // The usual way of opening a port. commModule->setRxHandler(&loopback_rx_cb, rtp::port::DISCOVER); commModule->setTxHandler((CommLink*)global_radio, &CommLink::sendPacket, rtp::port::DISCOVER); // This port won't open since there's no RX callback to invoke. The // packets are simply dropped. commModule->setRxHandler(&loopback_rx_cb, rtp::port::LOGGER); commModule->setTxHandler((CommLink*)global_radio, &CommLink::sendPacket, rtp::port::LOGGER); // Legacy port commModule->setTxHandler((CommLink*)global_radio, &CommLink::sendPacket, rtp::port::LEGACY); commModule->setRxHandler(&legacy_rx_cb, rtp::port::LEGACY); LOG(INIT, "%u sockets opened", commModule->numOpenSockets()); // Wait until the threads with the commModule->lass are all started up // and ready while (!commModule->isReady()) { Thread::wait(50); } MCP23017::Instance()->writeMask(1 << (8 + 2), 1 << (8 + 2)); // Set the error code's valid bit comm_err |= 1 << 0; } else { LOG(FATAL, "No radio interface found!\r\n"); // Set the error flag - bit positions are pretty arbitruary as of now comm_err |= 1 << 1; // Set the error code's valid bit comm_err |= 1 << 0; // Wait until the threads with the commModule->lass are all started up // and ready while (!commModule->isReady()) { Thread::wait(50); } // Radio error LED MCP23017::Instance()->writeMask(~(1 << (8 + 2)), 1 << (8 + 2)); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: table.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: fs $ $Date: 2000-10-18 16:08:52 $ * * 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 _DBA_CORE_TABLE_HXX_ #define _DBA_CORE_TABLE_HXX_ #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XDATADESCRIPTORFACTORY_HPP_ #include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XINDEXESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XIndexesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XKeysSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XRENAME_HPP_ #include <com/sun/star/sdbcx/XRename.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XALTERTABLE_HPP_ #include <com/sun/star/sdbcx/XAlterTable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase7.hxx> #endif #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef _DBA_CORE_DATASETTINGS_HXX_ #include "datasettings.hxx" #endif #ifndef _DBA_COREAPI_COLUMN_HXX_ #include <column.hxx> #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include <connectivity/CommonTools.hxx> #endif #ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_ #include <connectivity/sdbcx/VTable.hxx> #endif using namespace dbaccess; typedef ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection > OWeakConnection; class OServerComponent; //========================================================================== //= OTables //========================================================================== //typedef ::cppu::WeakComponentImplHelper7< ::com::sun::star::sdbcx::XColumnsSupplier, // ::com::sun::star::sdbcx::XDataDescriptorFactory, // ::com::sun::star::sdbcx::XIndexesSupplier, // ::com::sun::star::sdbcx::XKeysSupplier, // ::com::sun::star::sdbcx::XRename, // ::com::sun::star::sdbcx::XAlterTable, // ::com::sun::star::lang::XServiceInfo > OTable_Base; class ODBTable; typedef ::comphelper::OPropertyArrayUsageHelper < ODBTable > ODBTable_PROP; typedef connectivity::sdbcx::OTable OTable_Base; class ODBTable :public ODataSettings_Base ,public ODBTable_PROP ,public OTable_Base { protected: OWeakConnection m_aConnection; ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier > m_xTable; // OColumns m_aColumns; // <properties> sal_Int32 m_nPrivileges; // </properties> void refreshPrimaryKeys(std::vector< ::rtl::OUString>& _rKeys); void refreshForgeinKeys(std::vector< ::rtl::OUString>& _rKeys); DECLARE_CTY_PROPERTY(ODBTable_PROP,OTable_Base) public: /** constructs a wrapper supporting the com.sun.star.sdb.Table service.<BR> @param _rxConn the connection the table belongs to @param _rxTable the table from the driver can be null @param _rCatalog the name of the catalog the table belongs to. May be empty. @param _rSchema the name of the schema the table belongs to. May be empty. @param _rName the name of the table @param _rType the type of the table, as supplied by the driver @param _rDesc the description of the table, as supplied by the driver */ ODBTable( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier >& _rxTable, const ::rtl::OUString& _rCatalog, const ::rtl::OUString& _rSchema, const ::rtl::OUString& _rName, const ::rtl::OUString& _rType, const ::rtl::OUString& _rDesc) throw(::com::sun::star::sdbc::SQLException); virtual ~ODBTable(); // ODescriptor virtual void construct(); //XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // com::sun::star::lang::XTypeProvider // virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException); // com::sun::star::uno::XInterface // virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(void); // ::com::sun::star::lang::XServiceInfo DECLARE_SERVICE_INFO(); // com::sun::star::beans::XPropertySet // virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const; // ::com::sun::star::sdbcx::XRename, virtual void SAL_CALL rename( const ::rtl::OUString& _rNewName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException); // ::com::sun::star::sdbcx::XAlterTable, virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& _rName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL alterColumnByIndex( sal_Int32 _nIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // virtual SdbObj* getImplObj() const = 0; // const OColumns& getImplColumns(void) const {return m_aColumns;} ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection() const { return m_aConnection; } virtual void refreshColumns(); virtual void refreshKeys(); virtual void refreshIndexes(); }; #endif // _DBA_CORE_TABLE_HXX_ <commit_msg>descriptors inserted<commit_after>/************************************************************************* * * $RCSfile: table.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: oj $ $Date: 2000-10-30 09:25: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 _DBA_CORE_TABLE_HXX_ #define _DBA_CORE_TABLE_HXX_ #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XDATADESCRIPTORFACTORY_HPP_ #include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XINDEXESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XIndexesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XKeysSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XRENAME_HPP_ #include <com/sun/star/sdbcx/XRename.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XALTERTABLE_HPP_ #include <com/sun/star/sdbcx/XAlterTable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase7.hxx> #endif #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef _DBA_CORE_DATASETTINGS_HXX_ #include "datasettings.hxx" #endif #ifndef _DBA_COREAPI_COLUMN_HXX_ #include <column.hxx> #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include <connectivity/CommonTools.hxx> #endif #ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_ #include <connectivity/sdbcx/VTable.hxx> #endif using namespace dbaccess; typedef ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection > OWeakConnection; class OServerComponent; //========================================================================== //= OTables //========================================================================== //typedef ::cppu::WeakComponentImplHelper7< ::com::sun::star::sdbcx::XColumnsSupplier, // ::com::sun::star::sdbcx::XDataDescriptorFactory, // ::com::sun::star::sdbcx::XIndexesSupplier, // ::com::sun::star::sdbcx::XKeysSupplier, // ::com::sun::star::sdbcx::XRename, // ::com::sun::star::sdbcx::XAlterTable, // ::com::sun::star::lang::XServiceInfo > OTable_Base; class ODBTable; typedef ::comphelper::OPropertyArrayUsageHelper < ODBTable > ODBTable_PROP; typedef connectivity::sdbcx::OTable OTable_Base; class ODBTable :public ODataSettings_Base ,public ODBTable_PROP ,public OTable_Base { protected: OWeakConnection m_aConnection; ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier > m_xTable; // OColumns m_aColumns; // <properties> sal_Int32 m_nPrivileges; // </properties> void refreshPrimaryKeys(std::vector< ::rtl::OUString>& _rKeys); void refreshForgeinKeys(std::vector< ::rtl::OUString>& _rKeys); DECLARE_CTY_PROPERTY(ODBTable_PROP,OTable_Base) public: /** constructs a wrapper supporting the com.sun.star.sdb.Table service.<BR> @param _rxConn the connection the table belongs to @param _rxTable the table from the driver can be null @param _rCatalog the name of the catalog the table belongs to. May be empty. @param _rSchema the name of the schema the table belongs to. May be empty. @param _rName the name of the table @param _rType the type of the table, as supplied by the driver @param _rDesc the description of the table, as supplied by the driver */ ODBTable( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier >& _rxTable, const ::rtl::OUString& _rCatalog, const ::rtl::OUString& _rSchema, const ::rtl::OUString& _rName, const ::rtl::OUString& _rType, const ::rtl::OUString& _rDesc) throw(::com::sun::star::sdbc::SQLException); virtual ~ODBTable(); // ODescriptor virtual void construct(); //XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // com::sun::star::lang::XTypeProvider // virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException); // com::sun::star::uno::XInterface // virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(void); // ::com::sun::star::lang::XServiceInfo DECLARE_SERVICE_INFO(); // com::sun::star::beans::XPropertySet // virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const; // ::com::sun::star::sdbcx::XRename, virtual void SAL_CALL rename( const ::rtl::OUString& _rNewName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException); // ::com::sun::star::sdbcx::XAlterTable, virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& _rName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL alterColumnByIndex( sal_Int32 _nIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // virtual SdbObj* getImplObj() const = 0; // const OColumns& getImplColumns(void) const {return m_aColumns;} ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection() const { return m_aConnection; } virtual void refreshColumns(); virtual void refreshKeys(); virtual void refreshIndexes(); }; #endif // _DBA_CORE_TABLE_HXX_ <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2013-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef PCL_TRAJKOVIC_KEYPOINT_3D_IMPL_H_ #define PCL_TRAJKOVIC_KEYPOINT_3D_IMPL_H_ #include <pcl/features/integral_image_normal.h> template <typename PointInT, typename PointOutT, typename NormalT> bool pcl::TrajkovicKeypoint3D<PointInT, PointOutT, NormalT>::initCompute () { if (!PCLBase<PointInT>::initCompute ()) return (false); keypoints_indices_.reset (new pcl::PointIndices); keypoints_indices_->indices.reserve (input_->size ()); if (indices_->size () != input_->size ()) { PCL_ERROR ("[pcl::%s::initCompute] %s doesn't support setting indices!\n", name_.c_str ()); return (false); } if ((window_size_%2) == 0) { PCL_ERROR ("[pcl::%s::initCompute] Window size must be odd!\n", name_.c_str ()); return (false); } if (window_size_ < 3) { PCL_ERROR ("[pcl::%s::initCompute] Window size must be >= 3x3!\n", name_.c_str ()); return (false); } half_window_size_ = window_size_ / 2; if (!normals_) { NormalsPtr normals (new Normals ()); pcl::IntegralImageNormalEstimation<PointInT, NormalT> normal_estimation; normal_estimation.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointInT, NormalT>::SIMPLE_3D_GRADIENT); normal_estimation.setInputCloud (input_); normal_estimation.setNormalSmoothingSize (5.0); normal_estimation.compute (*normals); normals_ = normals; } if (normals_->size () != input_->size ()) { PCL_ERROR ("[pcl::%s::initCompute] normals given, but the number of normals does not match the number of input points!\n", name_.c_str ()); return (false); } return (true); } ///////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT, typename NormalT> void pcl::TrajkovicKeypoint3D<PointInT, PointOutT, NormalT>::detectKeypoints (PointCloudOut &output) { response_.reset (new pcl::PointCloud<float> (input_->width, input_->height)); const Normals &normals = *normals_; const PointCloudIn &input = *input_; pcl::PointCloud<float>& response = *response_; const int w = static_cast<int> (input_->width) - half_window_size_; const int h = static_cast<int> (input_->height) - half_window_size_; if (method_ == FOUR_CORNERS) { #ifdef _OPENMP #pragma omp parallel for num_threads (threads_) #endif for(int j = half_window_size_; j < h; ++j) { for(int i = half_window_size_; i < w; ++i) { if (!isFinite (input (i,j))) continue; const NormalT &center = normals (i,j); if (!isFinite (center)) continue; int count = 0; const NormalT &up = getNormalOrNull (i, j-half_window_size_, count); const NormalT &down = getNormalOrNull (i, j+half_window_size_, count); const NormalT &left = getNormalOrNull (i-half_window_size_, j, count); const NormalT &right = getNormalOrNull (i+half_window_size_, j, count); // Get rid of isolated points if (!count) continue; float sn1 = squaredNormalsDiff (up, center); float sn2 = squaredNormalsDiff (down, center); float r1 = sn1 + sn2; float r2 = squaredNormalsDiff (right, center) + squaredNormalsDiff (left, center); float d = std::min (r1, r2); if (d < first_threshold_) continue; sn1 = sqrt (sn1); sn2 = sqrt (sn2); float b1 = normalsDiff (right, up) * sn1; b1+= normalsDiff (left, down) * sn2; float b2 = normalsDiff (right, down) * sn2; b2+= normalsDiff (left, up) * sn1; float B = std::min (b1, b2); float A = r2 - r1 - 2*B; response (i,j) = ((B < 0) && ((B + A) > 0)) ? r1 - ((B*B)/A) : d; } } } else { #ifdef _OPENMP #pragma omp parallel for num_threads (threads_) #endif for(int j = half_window_size_; j < h; ++j) { for(int i = half_window_size_; i < w; ++i) { if (!isFinite (input (i,j))) continue; const NormalT &center = normals (i,j); if (!isFinite (center)) continue; int count = 0; const NormalT &up = getNormalOrNull (i, j-half_window_size_, count); const NormalT &down = getNormalOrNull (i, j+half_window_size_, count); const NormalT &left = getNormalOrNull (i-half_window_size_, j, count); const NormalT &right = getNormalOrNull (i+half_window_size_, j, count); const NormalT &upleft = getNormalOrNull (i-half_window_size_, j-half_window_size_, count); const NormalT &upright = getNormalOrNull (i+half_window_size_, j-half_window_size_, count); const NormalT &downleft = getNormalOrNull (i-half_window_size_, j+half_window_size_, count); const NormalT &downright = getNormalOrNull (i+half_window_size_, j+half_window_size_, count); // Get rid of isolated points if (!count) continue; std::vector<float> r (4,0); r[0] = squaredNormalsDiff (up, center); r[0]+= squaredNormalsDiff (down, center); r[1] = squaredNormalsDiff (upright, center); r[1]+= squaredNormalsDiff (downleft, center); r[2] = squaredNormalsDiff (right, center); r[2]+= squaredNormalsDiff (left, center); r[3] = squaredNormalsDiff (downright, center); r[3]+= squaredNormalsDiff (upleft, center); float d = *(std::min_element (r.begin (), r.end ())); if (d < first_threshold_) continue; std::vector<float> B (4,0); std::vector<float> A (4,0); std::vector<float> sumAB (4,0); B[0] = normalsDiff (upright, up) * normalsDiff (up, center); B[0]+= normalsDiff (downleft, down) * normalsDiff (down, center); B[1] = normalsDiff (right, upright) * normalsDiff (upright, center); B[1]+= normalsDiff (left, downleft) * normalsDiff (downleft, center); B[2] = normalsDiff (downright, right) * normalsDiff (downright, center); B[2]+= normalsDiff (upleft, left) * normalsDiff (upleft, center); B[3] = normalsDiff (down, downright) * normalsDiff (downright, center); B[3]+= normalsDiff (up, upleft) * normalsDiff (upleft, center); A[0] = r[1] - r[0] - B[0] - B[0]; A[1] = r[2] - r[1] - B[1] - B[1]; A[2] = r[3] - r[2] - B[2] - B[2]; A[3] = r[0] - r[3] - B[3] - B[3]; sumAB[0] = A[0] + B[0]; sumAB[1] = A[1] + B[1]; sumAB[2] = A[2] + B[2]; sumAB[3] = A[3] + B[3]; if ((*std::max_element (B.begin (), B.end ()) < 0) && (*std::min_element (sumAB.begin (), sumAB.end ()) > 0)) { std::vector<float> D (4,0); D[0] = B[0] * B[0] / A[0]; D[1] = B[1] * B[1] / A[1]; D[2] = B[2] * B[2] / A[2]; D[3] = B[3] * B[3] / A[3]; response (i,j) = *(std::min (D.begin (), D.end ())); } else response (i,j) = d; } } } // Non maximas suppression std::vector<int> indices = *indices_; std::sort (indices.begin (), indices.end (), boost::bind (&TrajkovicKeypoint3D::greaterCornernessAtIndices, this, _1, _2)); output.clear (); output.reserve (input_->size ()); std::vector<bool> occupency_map (indices.size (), false); const int width (input_->width); const int height (input_->height); #ifdef _OPENMP #pragma omp parallel for shared (output) num_threads (threads_) #endif for (int i = 0; i < indices.size (); ++i) { int idx = indices[i]; if ((response_->points[idx] < second_threshold_) || occupency_map[idx]) continue; PointOutT p; p.getVector3fMap () = input_->points[idx].getVector3fMap (); p.intensity = response_->points [idx]; #ifdef _OPENMP #pragma omp critical #endif { output.push_back (p); keypoints_indices_->indices.push_back (idx); } const int x = idx % width; const int y = idx / width; const int u_end = std::min (width, x + half_window_size_); const int v_end = std::min (height, y + half_window_size_); for(int v = std::max (0, y - half_window_size_); v < v_end; ++v) for(int u = std::max (0, x - half_window_size_); u < u_end; ++u) occupency_map[v*width + u] = true; } output.height = 1; output.width = static_cast<uint32_t> (output.size()); // we don not change the denseness output.is_dense = true; } #define PCL_INSTANTIATE_TrajkovicKeypoint3D(T,U,N) template class PCL_EXPORTS pcl::TrajkovicKeypoint3D<T,U,N>; #endif <commit_msg>Fix warnings in keypoints/trajkovic_3d.hpp<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2013-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef PCL_TRAJKOVIC_KEYPOINT_3D_IMPL_H_ #define PCL_TRAJKOVIC_KEYPOINT_3D_IMPL_H_ #include <pcl/features/integral_image_normal.h> template <typename PointInT, typename PointOutT, typename NormalT> bool pcl::TrajkovicKeypoint3D<PointInT, PointOutT, NormalT>::initCompute () { if (!PCLBase<PointInT>::initCompute ()) return (false); keypoints_indices_.reset (new pcl::PointIndices); keypoints_indices_->indices.reserve (input_->size ()); if (indices_->size () != input_->size ()) { PCL_ERROR ("[pcl::%s::initCompute] %s doesn't support setting indices!\n", name_.c_str ()); return (false); } if ((window_size_%2) == 0) { PCL_ERROR ("[pcl::%s::initCompute] Window size must be odd!\n", name_.c_str ()); return (false); } if (window_size_ < 3) { PCL_ERROR ("[pcl::%s::initCompute] Window size must be >= 3x3!\n", name_.c_str ()); return (false); } half_window_size_ = window_size_ / 2; if (!normals_) { NormalsPtr normals (new Normals ()); pcl::IntegralImageNormalEstimation<PointInT, NormalT> normal_estimation; normal_estimation.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointInT, NormalT>::SIMPLE_3D_GRADIENT); normal_estimation.setInputCloud (input_); normal_estimation.setNormalSmoothingSize (5.0); normal_estimation.compute (*normals); normals_ = normals; } if (normals_->size () != input_->size ()) { PCL_ERROR ("[pcl::%s::initCompute] normals given, but the number of normals does not match the number of input points!\n", name_.c_str ()); return (false); } return (true); } ///////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT, typename NormalT> void pcl::TrajkovicKeypoint3D<PointInT, PointOutT, NormalT>::detectKeypoints (PointCloudOut &output) { response_.reset (new pcl::PointCloud<float> (input_->width, input_->height)); const Normals &normals = *normals_; const PointCloudIn &input = *input_; pcl::PointCloud<float>& response = *response_; const int w = static_cast<int> (input_->width) - half_window_size_; const int h = static_cast<int> (input_->height) - half_window_size_; if (method_ == FOUR_CORNERS) { #ifdef _OPENMP #pragma omp parallel for num_threads (threads_) #endif for(int j = half_window_size_; j < h; ++j) { for(int i = half_window_size_; i < w; ++i) { if (!isFinite (input (i,j))) continue; const NormalT &center = normals (i,j); if (!isFinite (center)) continue; int count = 0; const NormalT &up = getNormalOrNull (i, j-half_window_size_, count); const NormalT &down = getNormalOrNull (i, j+half_window_size_, count); const NormalT &left = getNormalOrNull (i-half_window_size_, j, count); const NormalT &right = getNormalOrNull (i+half_window_size_, j, count); // Get rid of isolated points if (!count) continue; float sn1 = squaredNormalsDiff (up, center); float sn2 = squaredNormalsDiff (down, center); float r1 = sn1 + sn2; float r2 = squaredNormalsDiff (right, center) + squaredNormalsDiff (left, center); float d = std::min (r1, r2); if (d < first_threshold_) continue; sn1 = sqrt (sn1); sn2 = sqrt (sn2); float b1 = normalsDiff (right, up) * sn1; b1+= normalsDiff (left, down) * sn2; float b2 = normalsDiff (right, down) * sn2; b2+= normalsDiff (left, up) * sn1; float B = std::min (b1, b2); float A = r2 - r1 - 2*B; response (i,j) = ((B < 0) && ((B + A) > 0)) ? r1 - ((B*B)/A) : d; } } } else { #ifdef _OPENMP #pragma omp parallel for num_threads (threads_) #endif for(int j = half_window_size_; j < h; ++j) { for(int i = half_window_size_; i < w; ++i) { if (!isFinite (input (i,j))) continue; const NormalT &center = normals (i,j); if (!isFinite (center)) continue; int count = 0; const NormalT &up = getNormalOrNull (i, j-half_window_size_, count); const NormalT &down = getNormalOrNull (i, j+half_window_size_, count); const NormalT &left = getNormalOrNull (i-half_window_size_, j, count); const NormalT &right = getNormalOrNull (i+half_window_size_, j, count); const NormalT &upleft = getNormalOrNull (i-half_window_size_, j-half_window_size_, count); const NormalT &upright = getNormalOrNull (i+half_window_size_, j-half_window_size_, count); const NormalT &downleft = getNormalOrNull (i-half_window_size_, j+half_window_size_, count); const NormalT &downright = getNormalOrNull (i+half_window_size_, j+half_window_size_, count); // Get rid of isolated points if (!count) continue; std::vector<float> r (4,0); r[0] = squaredNormalsDiff (up, center); r[0]+= squaredNormalsDiff (down, center); r[1] = squaredNormalsDiff (upright, center); r[1]+= squaredNormalsDiff (downleft, center); r[2] = squaredNormalsDiff (right, center); r[2]+= squaredNormalsDiff (left, center); r[3] = squaredNormalsDiff (downright, center); r[3]+= squaredNormalsDiff (upleft, center); float d = *(std::min_element (r.begin (), r.end ())); if (d < first_threshold_) continue; std::vector<float> B (4,0); std::vector<float> A (4,0); std::vector<float> sumAB (4,0); B[0] = normalsDiff (upright, up) * normalsDiff (up, center); B[0]+= normalsDiff (downleft, down) * normalsDiff (down, center); B[1] = normalsDiff (right, upright) * normalsDiff (upright, center); B[1]+= normalsDiff (left, downleft) * normalsDiff (downleft, center); B[2] = normalsDiff (downright, right) * normalsDiff (downright, center); B[2]+= normalsDiff (upleft, left) * normalsDiff (upleft, center); B[3] = normalsDiff (down, downright) * normalsDiff (downright, center); B[3]+= normalsDiff (up, upleft) * normalsDiff (upleft, center); A[0] = r[1] - r[0] - B[0] - B[0]; A[1] = r[2] - r[1] - B[1] - B[1]; A[2] = r[3] - r[2] - B[2] - B[2]; A[3] = r[0] - r[3] - B[3] - B[3]; sumAB[0] = A[0] + B[0]; sumAB[1] = A[1] + B[1]; sumAB[2] = A[2] + B[2]; sumAB[3] = A[3] + B[3]; if ((*std::max_element (B.begin (), B.end ()) < 0) && (*std::min_element (sumAB.begin (), sumAB.end ()) > 0)) { std::vector<float> D (4,0); D[0] = B[0] * B[0] / A[0]; D[1] = B[1] * B[1] / A[1]; D[2] = B[2] * B[2] / A[2]; D[3] = B[3] * B[3] / A[3]; response (i,j) = *(std::min (D.begin (), D.end ())); } else response (i,j) = d; } } } // Non maximas suppression std::vector<int> indices = *indices_; std::sort (indices.begin (), indices.end (), boost::bind (&TrajkovicKeypoint3D::greaterCornernessAtIndices, this, _1, _2)); output.clear (); output.reserve (input_->size ()); std::vector<bool> occupency_map (indices.size (), false); const int width (input_->width); const int height (input_->height); #ifdef _OPENMP #pragma omp parallel for shared (output) num_threads (threads_) #endif for (size_t i = 0; i < indices.size (); ++i) { int idx = indices[i]; if ((response_->points[idx] < second_threshold_) || occupency_map[idx]) continue; PointOutT p; p.getVector3fMap () = input_->points[idx].getVector3fMap (); p.intensity = response_->points [idx]; #ifdef _OPENMP #pragma omp critical #endif { output.push_back (p); keypoints_indices_->indices.push_back (idx); } const int x = idx % width; const int y = idx / width; const int u_end = std::min (width, x + half_window_size_); const int v_end = std::min (height, y + half_window_size_); for(int v = std::max (0, y - half_window_size_); v < v_end; ++v) for(int u = std::max (0, x - half_window_size_); u < u_end; ++u) occupency_map[v*width + u] = true; } output.height = 1; output.width = static_cast<uint32_t> (output.size()); // we don not change the denseness output.is_dense = true; } #define PCL_INSTANTIATE_TrajkovicKeypoint3D(T,U,N) template class PCL_EXPORTS pcl::TrajkovicKeypoint3D<T,U,N>; #endif <|endoftext|>
<commit_before>/* * Copyright 2014 (c) Lei Xu <eddyxu@gmail.com> * * 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. */ /** * \file vobla/hash_test.cpp * \brief Unit tests for Hash Digests. */ #include <gtest/gtest.h> #include <string> #include "vobla/hash.h" using std::string; namespace vobla { TEST(HashDigestTest, MD5Create) { const string buf("This is a buffer."); MD5Digest md5_0(buf); MD5Digest md5_3; md5_3.Reset(buf); EXPECT_EQ(md5_3, md5_0); MD5Digest md5_2("abcdefg\n"); EXPECT_EQ(md5_2.hexdigest(), "020861c8c3fe177da19a7e9539a5dbac"); } TEST(HashDigestTest, SHA1Create) { const string buf("SHA1's buffer"); SHA1Digest sha1_0(buf); SHA1Digest sha1_1; sha1_1.Reset(buf); EXPECT_EQ(sha1_0, sha1_1); SHA1Digest sha1_2("abcdefg\n"); EXPECT_EQ(sha1_2.hexdigest(), "69bca99b923859f2dc486b55b87f49689b7358c7"); } } // namespace vobla <commit_msg> remove unused comments<commit_after>/* * Copyright 2014 (c) Lei Xu <eddyxu@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <string> #include "vobla/hash.h" using std::string; namespace vobla { TEST(HashDigestTest, MD5Create) { const string buf("This is a buffer."); MD5Digest md5_0(buf); MD5Digest md5_3; md5_3.Reset(buf); EXPECT_EQ(md5_3, md5_0); MD5Digest md5_2("abcdefg\n"); EXPECT_EQ(md5_2.hexdigest(), "020861c8c3fe177da19a7e9539a5dbac"); } TEST(HashDigestTest, SHA1Create) { const string buf("SHA1's buffer"); SHA1Digest sha1_0(buf); SHA1Digest sha1_1; sha1_1.Reset(buf); EXPECT_EQ(sha1_0, sha1_1); SHA1Digest sha1_2("abcdefg\n"); EXPECT_EQ(sha1_2.hexdigest(), "69bca99b923859f2dc486b55b87f49689b7358c7"); } } // namespace vobla <|endoftext|>
<commit_before>// Copyright (c) 2015 cpichard. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #if HAVE_ALEMBIC #include "AlembicImporter.hpp" #include <Alembic/AbcGeom/All.h> #include <Alembic/AbcCoreFactory/All.h> using namespace Alembic::Abc; namespace AbcG = Alembic::AbcGeom; using namespace AbcG; namespace openMVG { namespace dataio { /** * @brief Retrieve an Abc property. * Maya convert everything into arrays. So here we made a trick * to retrieve the element directly or the first element * if it's an array. * @param userProps * @param id * @param sampleTime * @return value */ template<class AbcProperty> typename AbcProperty::traits_type::value_type getAbcProp(ICompoundProperty& userProps, const Alembic::Abc::PropertyHeader& propHeader, const std::string& id, chrono_t sampleTime) { typedef typename AbcProperty::traits_type traits_type; typedef typename traits_type::value_type value_type; typedef typename Alembic::Abc::ITypedArrayProperty<traits_type> array_type; typedef typename array_type::sample_ptr_type array_sample_ptr_type; // Maya transforms everything into arrays if(propHeader.isArray()) { Alembic::Abc::ITypedArrayProperty<traits_type> prop(userProps, id); array_sample_ptr_type sample; prop.get(sample, ISampleSelector(sampleTime)); return (*sample)[0]; } else { value_type v; AbcProperty prop(userProps, id); prop.get(v, ISampleSelector(sampleTime)); return v; } } template<class ABCSCHEMA> inline ICompoundProperty getAbcUserProperties(ABCSCHEMA& schema) { ICompoundProperty userProps = schema.getUserProperties(); if(userProps && userProps.getNumProperties() != 0) return userProps; // Maya always use ArbGeomParams instead of user properties. return schema.getArbGeomParams(); } bool AlembicImporter::readPointCloud(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part) { using namespace openMVG::geometry; using namespace openMVG::sfm; IPoints points(iObj, kWrapExisting); IPointsSchema& ms = points.getSchema(); P3fArraySamplePtr positions = ms.getValue().getPositions(); ICompoundProperty userProps = getAbcUserProperties(ms); // Number of points before adding the Alembic data const std::size_t nbPointsInit = sfmdata.structure.size(); // Number of points with all the new Alembic data std::size_t nbPointsAll = nbPointsInit + positions->size(); for(std::size_t point3d_i = nbPointsInit; point3d_i < nbPointsAll; ++point3d_i) { const P3fArraySamplePtr::element_type::value_type & pos_i = positions->get()[point3d_i]; Landmark& landmark = sfmdata.structure[point3d_i] = Landmark(Vec3(pos_i.x, pos_i.y, pos_i.z)); } if(userProps.getPropertyHeader("mvg_visibilitySize") && userProps.getPropertyHeader("mvg_visibilityIds") && userProps.getPropertyHeader("mvg_visibilityFeatPos") ) { IUInt32ArrayProperty propVisibilitySize(userProps, "mvg_visibilitySize"); std::shared_ptr<UInt32ArraySample> sampleVisibilitySize; propVisibilitySize.get(sampleVisibilitySize); IUInt32ArrayProperty propVisibilityIds(userProps, "mvg_visibilityIds"); std::shared_ptr<UInt32ArraySample> sampleVisibilityIds; propVisibilityIds.get(sampleVisibilityIds); IFloatArrayProperty propFeatPos2d(userProps, "mvg_visibilityFeatPos"); std::shared_ptr<FloatArraySample> sampleFeatPos2d; propFeatPos2d.get(sampleFeatPos2d); if( positions->size() != sampleVisibilitySize->size() ) { std::cerr << "ABC Error: number of observations per 3D point should be identical to the number of 2D features." << std::endl; std::cerr << "Number of observations per 3D point size is " << sampleVisibilitySize->size() << std::endl; std::cerr << "Number of 3D points is " << positions->size() << std::endl; return false; } if( sampleVisibilityIds->size() != sampleFeatPos2d->size() ) { std::cerr << "ABC Error: visibility Ids and features 2D pos should have the same size." << std::endl; std::cerr << "Visibility Ids size is " << sampleVisibilityIds->size() << std::endl; std::cerr << "Features 2d Pos size is " << sampleFeatPos2d->size() << std::endl; return false; } std::size_t obsGlobal_i = 0; for(std::size_t point3d_i = nbPointsInit; point3d_i < nbPointsAll; ++point3d_i) { Landmark& landmark = sfmdata.structure[point3d_i]; // Number of observation for this 3d point const std::size_t visibilitySize = (*sampleVisibilitySize)[point3d_i]; for(std::size_t obs_i = 0; obs_i < visibilitySize*2; obs_i+=2, obsGlobal_i+=2) { const int viewID = (*sampleVisibilityIds)[obsGlobal_i]; const int featID = (*sampleVisibilityIds)[obsGlobal_i+1]; Observation& obs = landmark.obs[viewID]; obs.id_feat = featID; const float posX = (*sampleFeatPos2d)[obsGlobal_i]; const float posY = (*sampleFeatPos2d)[obsGlobal_i+1]; obs.x[0] = posX; obs.x[1] = posY; } } } return true; } bool AlembicImporter::readCamera(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part, chrono_t sampleTime) { using namespace openMVG::geometry; using namespace openMVG::cameras; using namespace openMVG::sfm; ICamera camera(iObj, kWrapExisting); ICameraSchema cs = camera.getSchema(); CameraSample camSample; if(sampleTime == 0) camSample = cs.getValue(); else camSample = cs.getValue(ISampleSelector(sampleTime)); // Check if we have an associated image plane ICompoundProperty userProps = getAbcUserProperties(cs); std::string imagePath; float sensorWidth_pix = 2048.0; std::string mvg_intrinsicType = "PINHOLE_CAMERA"; std::vector<double> mvg_intrinsicParams; IndexT id_view = sfmdata.GetViews().size(); IndexT id_intrinsic = sfmdata.GetIntrinsics().size(); if(userProps) { if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_imagePath")) { imagePath = getAbcProp<Alembic::Abc::IStringProperty>(userProps, *propHeader, "mvg_imagePath", sampleTime); } if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_sensorWidth_pix")) { try { sensorWidth_pix = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_sensorWidth_pix", sampleTime); } catch(Alembic::Util::v7::Exception&) { sensorWidth_pix = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_sensorWidth_pix", sampleTime); } } if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_intrinsicType")) { mvg_intrinsicType = getAbcProp<Alembic::Abc::IStringProperty>(userProps, *propHeader, "mvg_intrinsicType", sampleTime); } if(userProps.getPropertyHeader("mvg_intrinsicParams")) { Alembic::Abc::IDoubleArrayProperty prop(userProps, "mvg_intrinsicParams"); std::shared_ptr<DoubleArraySample> sample; prop.get(sample, ISampleSelector(sampleTime)); mvg_intrinsicParams.assign(sample->get(), sample->get()+sample->size()); } if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_viewId")) { try { id_view = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_viewId", sampleTime); } catch(Alembic::Util::v7::Exception&) { id_view = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_viewId", sampleTime); } } if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_intrinsicId")) { try { id_intrinsic = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_intrinsicId", sampleTime); } catch(Alembic::Util::v7::Exception&) { id_intrinsic = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_intrinsicId", sampleTime); } } } // OpenMVG Camera Mat3 cam_r; cam_r(0,0) = mat[0][0]; cam_r(0,1) = mat[0][1]; cam_r(0,2) = mat[0][2]; cam_r(1,0) = mat[1][0]; cam_r(1,1) = mat[1][1]; cam_r(1,2) = mat[1][2]; cam_r(2,0) = mat[2][0]; cam_r(2,1) = mat[2][1]; cam_r(2,2) = mat[2][2]; Vec3 cam_t; cam_t(0) = mat[3][0]; cam_t(1) = mat[3][1]; cam_t(2) = mat[3][2]; // Correct camera orientation from alembic Mat3 scale; scale(0,0) = 1; scale(1,1) = -1; scale(2,2) = -1; cam_r = scale*cam_r; Pose3 pose(cam_r, cam_t); // Get known values from alembic const float haperture_cm = camSample.getHorizontalAperture(); const float vaperture_cm = camSample.getVerticalAperture(); const float hoffset_cm = camSample.getHorizontalFilmOffset(); const float voffset_cm = camSample.getVerticalFilmOffset(); const float focalLength_mm = camSample.getFocalLength(); // Compute other needed values const float sensorWidth_mm = std::max(vaperture_cm, haperture_cm) * 10.0; const float mm2pix = sensorWidth_pix / sensorWidth_mm; const float imgWidth = haperture_cm * 10.0 * mm2pix; const float imgHeight = vaperture_cm * 10.0 * mm2pix; const float focalLength_pix = focalLength_mm * mm2pix; // Following values are in cm, hence the 10.0 multiplier const float hoffset_pix = (imgWidth*0.5) - (10.0 * hoffset_cm * mm2pix); const float voffset_pix = (imgHeight*0.5) + (10.0 * voffset_cm * mm2pix); // Create intrinsic parameters object std::shared_ptr<Pinhole_Intrinsic> pinholeIntrinsic = createPinholeIntrinsic(EINTRINSIC_stringToEnum(mvg_intrinsicType)); pinholeIntrinsic->setWidth(imgWidth); pinholeIntrinsic->setHeight(imgHeight); pinholeIntrinsic->setK(focalLength_pix, hoffset_pix, voffset_pix); pinholeIntrinsic->updateFromParams(mvg_intrinsicParams); // Add imported data to the SfM_Data container TODO use UID sfmdata.views.emplace(id_view, std::make_shared<View>(imagePath, id_view, id_intrinsic, id_view, imgWidth, imgHeight)); sfmdata.poses.emplace(id_view, pose); sfmdata.intrinsics.emplace(id_intrinsic, pinholeIntrinsic); return true; } // Top down read of 3d objects void AlembicImporter::visitObject(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part) { // std::cout << "ABC visit: " << iObj.getFullName() << std::endl; const MetaData& md = iObj.getMetaData(); if(IPoints::matches(md) && (flags_part & sfm::ESfM_Data::STRUCTURE)) { readPointCloud(iObj, mat, sfmdata, flags_part); } // This case in when we have an animated camera : we handle both xform and camera here else if(IXform::matches(md) && iObj.getName().find("animxform") != std::string::npos) { IXform xform(iObj, kWrapExisting); XformSample xs; std::cout << xform.getSchema().getNumSamples() << " samples found in this animated xform." << std::endl; float timebase = 1.0 / 24.0; float timestep = 1.0 / 24.0; for(int frame = 0; frame < xform.getSchema().getNumSamples(); ++frame) { xform.getSchema().get(xs, ISampleSelector(frame * timestep + timebase)); readCamera(iObj.getChild(0), mat*xs.getMatrix(), sfmdata, flags_part, frame * timestep + timebase); } } else if(IXform::matches(md)) { IXform xform(iObj, kWrapExisting); XformSample xs; xform.getSchema().get(xs); mat *= xs.getMatrix(); } // If it's an animated camera, no need to add it, we handled the thing upper else if(ICamera::matches(md) && (flags_part & sfm::ESfM_Data::EXTRINSICS) && iObj.getName().find("animcam") == std::string::npos) { readCamera(iObj, mat, sfmdata, flags_part); } // Recurse for(size_t i = 0; i < iObj.getNumChildren(); i++) { visitObject(iObj.getChild(i), mat, sfmdata, flags_part); } } AlembicImporter::AlembicImporter(const std::string &filename) { Alembic::AbcCoreFactory::IFactory factory; Alembic::AbcCoreFactory::IFactory::CoreType coreType; Abc::IArchive archive = factory.getArchive(filename, coreType); // TODO : test if archive is correctly opened _rootEntity = archive.getTop(); } void AlembicImporter::populate(sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part) { // TODO : handle the case where the archive wasn't correctly opened M44d xformMat; visitObject(_rootEntity, xformMat, sfmdata, flags_part); // TODO: fusion of common intrinsics } } // namespace data_io } // namespace openMVG #endif // WITH_ALEMBIC <commit_msg>[dataio] improve conditions to determine if a camera is animated or not<commit_after>// Copyright (c) 2015 cpichard. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #if HAVE_ALEMBIC #include "AlembicImporter.hpp" #include <Alembic/AbcGeom/All.h> #include <Alembic/AbcCoreFactory/All.h> using namespace Alembic::Abc; namespace AbcG = Alembic::AbcGeom; using namespace AbcG; namespace openMVG { namespace dataio { /** * @brief Retrieve an Abc property. * Maya convert everything into arrays. So here we made a trick * to retrieve the element directly or the first element * if it's an array. * @param userProps * @param id * @param sampleTime * @return value */ template<class AbcProperty> typename AbcProperty::traits_type::value_type getAbcProp(ICompoundProperty& userProps, const Alembic::Abc::PropertyHeader& propHeader, const std::string& id, chrono_t sampleTime) { typedef typename AbcProperty::traits_type traits_type; typedef typename traits_type::value_type value_type; typedef typename Alembic::Abc::ITypedArrayProperty<traits_type> array_type; typedef typename array_type::sample_ptr_type array_sample_ptr_type; // Maya transforms everything into arrays if(propHeader.isArray()) { Alembic::Abc::ITypedArrayProperty<traits_type> prop(userProps, id); array_sample_ptr_type sample; prop.get(sample, ISampleSelector(sampleTime)); return (*sample)[0]; } else { value_type v; AbcProperty prop(userProps, id); prop.get(v, ISampleSelector(sampleTime)); return v; } } template<class ABCSCHEMA> inline ICompoundProperty getAbcUserProperties(ABCSCHEMA& schema) { ICompoundProperty userProps = schema.getUserProperties(); if(userProps && userProps.getNumProperties() != 0) return userProps; // Maya always use ArbGeomParams instead of user properties. return schema.getArbGeomParams(); } bool AlembicImporter::readPointCloud(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part) { using namespace openMVG::geometry; using namespace openMVG::sfm; IPoints points(iObj, kWrapExisting); IPointsSchema& ms = points.getSchema(); P3fArraySamplePtr positions = ms.getValue().getPositions(); ICompoundProperty userProps = getAbcUserProperties(ms); // Number of points before adding the Alembic data const std::size_t nbPointsInit = sfmdata.structure.size(); // Number of points with all the new Alembic data std::size_t nbPointsAll = nbPointsInit + positions->size(); for(std::size_t point3d_i = nbPointsInit; point3d_i < nbPointsAll; ++point3d_i) { const P3fArraySamplePtr::element_type::value_type & pos_i = positions->get()[point3d_i]; Landmark& landmark = sfmdata.structure[point3d_i] = Landmark(Vec3(pos_i.x, pos_i.y, pos_i.z)); } if(userProps.getPropertyHeader("mvg_visibilitySize") && userProps.getPropertyHeader("mvg_visibilityIds") && userProps.getPropertyHeader("mvg_visibilityFeatPos") ) { IUInt32ArrayProperty propVisibilitySize(userProps, "mvg_visibilitySize"); std::shared_ptr<UInt32ArraySample> sampleVisibilitySize; propVisibilitySize.get(sampleVisibilitySize); IUInt32ArrayProperty propVisibilityIds(userProps, "mvg_visibilityIds"); std::shared_ptr<UInt32ArraySample> sampleVisibilityIds; propVisibilityIds.get(sampleVisibilityIds); IFloatArrayProperty propFeatPos2d(userProps, "mvg_visibilityFeatPos"); std::shared_ptr<FloatArraySample> sampleFeatPos2d; propFeatPos2d.get(sampleFeatPos2d); if( positions->size() != sampleVisibilitySize->size() ) { std::cerr << "ABC Error: number of observations per 3D point should be identical to the number of 2D features." << std::endl; std::cerr << "Number of observations per 3D point size is " << sampleVisibilitySize->size() << std::endl; std::cerr << "Number of 3D points is " << positions->size() << std::endl; return false; } if( sampleVisibilityIds->size() != sampleFeatPos2d->size() ) { std::cerr << "ABC Error: visibility Ids and features 2D pos should have the same size." << std::endl; std::cerr << "Visibility Ids size is " << sampleVisibilityIds->size() << std::endl; std::cerr << "Features 2d Pos size is " << sampleFeatPos2d->size() << std::endl; return false; } std::size_t obsGlobal_i = 0; for(std::size_t point3d_i = nbPointsInit; point3d_i < nbPointsAll; ++point3d_i) { Landmark& landmark = sfmdata.structure[point3d_i]; // Number of observation for this 3d point const std::size_t visibilitySize = (*sampleVisibilitySize)[point3d_i]; for(std::size_t obs_i = 0; obs_i < visibilitySize*2; obs_i+=2, obsGlobal_i+=2) { const int viewID = (*sampleVisibilityIds)[obsGlobal_i]; const int featID = (*sampleVisibilityIds)[obsGlobal_i+1]; Observation& obs = landmark.obs[viewID]; obs.id_feat = featID; const float posX = (*sampleFeatPos2d)[obsGlobal_i]; const float posY = (*sampleFeatPos2d)[obsGlobal_i+1]; obs.x[0] = posX; obs.x[1] = posY; } } } return true; } bool AlembicImporter::readCamera(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part, chrono_t sampleTime) { using namespace openMVG::geometry; using namespace openMVG::cameras; using namespace openMVG::sfm; ICamera camera(iObj, kWrapExisting); ICameraSchema cs = camera.getSchema(); CameraSample camSample; if(sampleTime == 0) camSample = cs.getValue(); else camSample = cs.getValue(ISampleSelector(sampleTime)); // Check if we have an associated image plane ICompoundProperty userProps = getAbcUserProperties(cs); std::string imagePath; float sensorWidth_pix = 2048.0; std::string mvg_intrinsicType = "PINHOLE_CAMERA"; std::vector<double> mvg_intrinsicParams; IndexT id_view = sfmdata.GetViews().size(); IndexT id_intrinsic = sfmdata.GetIntrinsics().size(); if(userProps) { if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_imagePath")) { imagePath = getAbcProp<Alembic::Abc::IStringProperty>(userProps, *propHeader, "mvg_imagePath", sampleTime); } if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_sensorWidth_pix")) { try { sensorWidth_pix = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_sensorWidth_pix", sampleTime); } catch(Alembic::Util::v7::Exception&) { sensorWidth_pix = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_sensorWidth_pix", sampleTime); } } if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_intrinsicType")) { mvg_intrinsicType = getAbcProp<Alembic::Abc::IStringProperty>(userProps, *propHeader, "mvg_intrinsicType", sampleTime); } if(userProps.getPropertyHeader("mvg_intrinsicParams")) { Alembic::Abc::IDoubleArrayProperty prop(userProps, "mvg_intrinsicParams"); std::shared_ptr<DoubleArraySample> sample; prop.get(sample, ISampleSelector(sampleTime)); mvg_intrinsicParams.assign(sample->get(), sample->get()+sample->size()); } if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_viewId")) { try { id_view = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_viewId", sampleTime); } catch(Alembic::Util::v7::Exception&) { id_view = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_viewId", sampleTime); } } if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_intrinsicId")) { try { id_intrinsic = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_intrinsicId", sampleTime); } catch(Alembic::Util::v7::Exception&) { id_intrinsic = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_intrinsicId", sampleTime); } } } // OpenMVG Camera Mat3 cam_r; cam_r(0,0) = mat[0][0]; cam_r(0,1) = mat[0][1]; cam_r(0,2) = mat[0][2]; cam_r(1,0) = mat[1][0]; cam_r(1,1) = mat[1][1]; cam_r(1,2) = mat[1][2]; cam_r(2,0) = mat[2][0]; cam_r(2,1) = mat[2][1]; cam_r(2,2) = mat[2][2]; Vec3 cam_t; cam_t(0) = mat[3][0]; cam_t(1) = mat[3][1]; cam_t(2) = mat[3][2]; // Correct camera orientation from alembic Mat3 scale; scale(0,0) = 1; scale(1,1) = -1; scale(2,2) = -1; cam_r = scale*cam_r; Pose3 pose(cam_r, cam_t); // Get known values from alembic const float haperture_cm = camSample.getHorizontalAperture(); const float vaperture_cm = camSample.getVerticalAperture(); const float hoffset_cm = camSample.getHorizontalFilmOffset(); const float voffset_cm = camSample.getVerticalFilmOffset(); const float focalLength_mm = camSample.getFocalLength(); // Compute other needed values const float sensorWidth_mm = std::max(vaperture_cm, haperture_cm) * 10.0; const float mm2pix = sensorWidth_pix / sensorWidth_mm; const float imgWidth = haperture_cm * 10.0 * mm2pix; const float imgHeight = vaperture_cm * 10.0 * mm2pix; const float focalLength_pix = focalLength_mm * mm2pix; // Following values are in cm, hence the 10.0 multiplier const float hoffset_pix = (imgWidth*0.5) - (10.0 * hoffset_cm * mm2pix); const float voffset_pix = (imgHeight*0.5) + (10.0 * voffset_cm * mm2pix); // Create intrinsic parameters object std::shared_ptr<Pinhole_Intrinsic> pinholeIntrinsic = createPinholeIntrinsic(EINTRINSIC_stringToEnum(mvg_intrinsicType)); pinholeIntrinsic->setWidth(imgWidth); pinholeIntrinsic->setHeight(imgHeight); pinholeIntrinsic->setK(focalLength_pix, hoffset_pix, voffset_pix); pinholeIntrinsic->updateFromParams(mvg_intrinsicParams); // Add imported data to the SfM_Data container TODO use UID sfmdata.views.emplace(id_view, std::make_shared<View>(imagePath, id_view, id_intrinsic, id_view, imgWidth, imgHeight)); sfmdata.poses.emplace(id_view, pose); sfmdata.intrinsics.emplace(id_intrinsic, pinholeIntrinsic); return true; } // Top down read of 3d objects void AlembicImporter::visitObject(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part) { // std::cout << "ABC visit: " << iObj.getFullName() << std::endl; const MetaData& md = iObj.getMetaData(); if(IPoints::matches(md) && (flags_part & sfm::ESfM_Data::STRUCTURE)) { readPointCloud(iObj, mat, sfmdata, flags_part); } else if(IXform::matches(md)) { IXform xform(iObj, kWrapExisting); XformSample xs; if(xform.getSchema().getNumSamples() == 1) { xform.getSchema().get(xs); mat *= xs.getMatrix(); } // If we have an animated camera we handle it with the xform here else { std::cout << xform.getSchema().getNumSamples() << " samples found in this animated xform." << std::endl; float timebase = 1.0 / 24.0; float timestep = 1.0 / 24.0; for(int frame = 0; frame < xform.getSchema().getNumSamples(); ++frame) { xform.getSchema().get(xs, ISampleSelector(frame * timestep + timebase)); readCamera(iObj.getChild(0), mat * xs.getMatrix(), sfmdata, flags_part, frame * timestep + timebase); } } } else if(ICamera::matches(md) && (flags_part & sfm::ESfM_Data::EXTRINSICS)) { ICamera check_cam(iObj, kWrapExisting); // If it's not an animated camera we add it here if(check_cam.getSchema().getNumSamples() == 1) { readCamera(iObj, mat, sfmdata, flags_part); } } // Recurse for(size_t i = 0; i < iObj.getNumChildren(); i++) { visitObject(iObj.getChild(i), mat, sfmdata, flags_part); } } AlembicImporter::AlembicImporter(const std::string &filename) { Alembic::AbcCoreFactory::IFactory factory; Alembic::AbcCoreFactory::IFactory::CoreType coreType; Abc::IArchive archive = factory.getArchive(filename, coreType); // TODO : test if archive is correctly opened _rootEntity = archive.getTop(); } void AlembicImporter::populate(sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part) { // TODO : handle the case where the archive wasn't correctly opened M44d xformMat; visitObject(_rootEntity, xformMat, sfmdata, flags_part); // TODO: fusion of common intrinsics } } // namespace data_io } // namespace openMVG #endif // WITH_ALEMBIC <|endoftext|>
<commit_before>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "operators/validate_url_encoding.h" #include <string> #include "operators/operator.h" namespace ModSecurity { namespace operators { int ValidateUrlEncoding::validate_url_encoding(const char *input, uint64_t input_length) { int i; if ((input == NULL) || (input_length <= 0)) { return -1; } i = 0; while (i < input_length) { if (input[i] == '%') { if (i + 2 >= input_length) { /* Not enough bytes. */ return -3; } else { /* Here we only decode a %xx combination if it is valid, * leaving it as is otherwise. */ char c1 = input[i + 1]; char c2 = input[i + 2]; if ( (((c1 >= '0') && (c1 <= '9')) || ((c1 >= 'a') && (c1 <= 'f')) || ((c1 >= 'A') && (c1 <= 'F'))) && (((c2 >= '0') && (c2 <= '9')) || ((c2 >= 'a') && (c2 <= 'f')) || ((c2 >= 'A') && (c2 <= 'F'))) ) { i += 3; } else { /* Non-hexadecimal characters used in encoding. */ return -2; } } } else { i++; } } return 1; } bool ValidateUrlEncoding::evaluate(Assay *assay, const std::string &input) { bool res = false; int rc = validate_url_encoding(input.c_str(), input.size()); switch (rc) { case 1 : /* Encoding is valid */ if (assay) { assay->debug(7, "Valid URL Encoding at '" +input + "'"); } res = false; break; case -2 : if (assay) { assay->debug(7, "Invalid URL Encoding: Non-hexadecimal " "digits used at '" + input + "'"); } res = true; /* Invalid match. */ break; case -3 : if (assay) { assay->debug(7, "Invalid URL Encoding: Not enough characters " "at the end of input at '" + input + "'"); } res = true; /* Invalid match. */ break; case -1 : default : if (assay) { assay->debug(7, "Invalid URL Encoding: Internal Error (rc = " + std::to_string(rc) + ") at '" + input + "'"); } res = true; break; } if (negation) { return !res; } return res; } } // namespace operators } // namespace ModSecurity <commit_msg>Fix ValidateUrlEncoding corner case<commit_after>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "operators/validate_url_encoding.h" #include <string> #include "operators/operator.h" namespace ModSecurity { namespace operators { int ValidateUrlEncoding::validate_url_encoding(const char *input, uint64_t input_length) { int i; if ((input == NULL) || (input_length <= 0)) { return -1; } i = 0; while (i < input_length) { if (input[i] == '%') { if (i + 2 >= input_length) { /* Not enough bytes. */ return -3; } else { /* Here we only decode a %xx combination if it is valid, * leaving it as is otherwise. */ char c1 = input[i + 1]; char c2 = input[i + 2]; if ( (((c1 >= '0') && (c1 <= '9')) || ((c1 >= 'a') && (c1 <= 'f')) || ((c1 >= 'A') && (c1 <= 'F'))) && (((c2 >= '0') && (c2 <= '9')) || ((c2 >= 'a') && (c2 <= 'f')) || ((c2 >= 'A') && (c2 <= 'F'))) ) { i += 3; } else { /* Non-hexadecimal characters used in encoding. */ return -2; } } } else { i++; } } return 1; } bool ValidateUrlEncoding::evaluate(Assay *assay, const std::string &input) { bool res = false; if (input.empty() == true) { return res; } int rc = validate_url_encoding(input.c_str(), input.size()); switch (rc) { case 1 : /* Encoding is valid */ if (assay) { assay->debug(7, "Valid URL Encoding at '" +input + "'"); } res = false; break; case -2 : if (assay) { assay->debug(7, "Invalid URL Encoding: Non-hexadecimal " "digits used at '" + input + "'"); } res = true; /* Invalid match. */ break; case -3 : if (assay) { assay->debug(7, "Invalid URL Encoding: Not enough characters " "at the end of input at '" + input + "'"); } res = true; /* Invalid match. */ break; case -1 : default : if (assay) { assay->debug(7, "Invalid URL Encoding: Internal Error (rc = " + std::to_string(rc) + ") at '" + input + "'"); } res = true; break; } if (negation) { return !res; } return res; } } // namespace operators } // namespace ModSecurity <|endoftext|>
<commit_before>#include "genetico.cpp" #include <gnuplot-iostream.h> int main() { arma_rng::set_seed_random(); Gnuplot gp; // ------------------------------- // Inciso a // ------------------------------- { const array<double, 2> limites = {{-512, 512}}; auto fitness = [](array<double, 1> fenotipo) -> double { double x = fenotipo.at(0); return x * sin(sqrt(abs(x))); }; Poblacion<8, 1> p{limites, fitness, /*individuos =*/40, /*generaciones =*/500, /*umbral =*/50}; p.evaluarPoblacion(); cout << "Función x * sin(sqrt(abs(x)))" << endl << "=============================" << endl << "Antes de iniciar el entrenamiento" << endl << "Mejor individuo: x = " << p.mejorIndividuo().fenotipo().at(0) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl; { const vector<Individuo<8, 1>> individuos = p.individuos(); mat puntos(individuos.size(), 2); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = fitness(individuos.at(i).fenotipo()); } gp << "set xrange [-512:512]" << endl << "set grid" << endl << "set samples 500" << endl << "plot x * sin(sqrt(abs(x))) notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; getchar(); } int generacion; string stopChar = ""; for (generacion = 0; generacion < 500 && !p.termino(); ++generacion) { p.evolucionar(1); if (stopChar != "s" || p.termino()) { const vector<Individuo<8, 1>> individuos = p.individuos(); mat puntos(individuos.size(), 2); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = fitness(individuos.at(i).fenotipo()); } gp << "set xrange [-512:512]" << endl << "set grid" << endl << "plot x * sin(sqrt(abs(x))) notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; if (!p.termino()) getline(cin, stopChar); } } cout << "\nLuego de finalizar el entrenamiento" << endl << "Mejor individuo: x = " << p.mejorIndividuo().fenotipo().at(0) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl << "Generaciones evolucionadas: " << generacion << endl; getchar(); } // ------------------------------- // Inciso b // ------------------------------- { const array<double, 2> limites = {{0, 20}}; auto fitness = [](array<double, 1> fenotipo) -> double { double x = fenotipo.at(0); return -x - 5 * sin(3 * x) - 8 * cos(5 * x); }; Poblacion<8, 1> p{limites, fitness, /*individuos =*/40, /*generaciones =*/500, /*umbral =*/100}; p.evaluarPoblacion(); cout << "\nFunción -x - 5 * sin(3 * x) - 8 * cos(5 * x)" << endl << "=============================" << endl << "Antes de iniciar el entrenamiento" << endl << "Mejor individuo: x = " << p.mejorIndividuo().fenotipo().at(0) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl; { const vector<Individuo<8, 1>> individuos = p.individuos(); mat puntos(individuos.size(), 2); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = fitness(individuos.at(i).fenotipo()); } gp << "set xrange [0:20]" << endl << "set grid" << endl << "plot -x - 5 * sin(3 * x) - 8 * cos(5 * x) notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; getchar(); } int generacion; string stopChar = ""; for (generacion = 0; generacion < 500 && !p.termino(); ++generacion) { p.evolucionar(1); if (stopChar != "s" || p.termino()) { const vector<Individuo<8, 1>> individuos = p.individuos(); mat puntos(individuos.size(), 2); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = fitness(individuos.at(i).fenotipo()); } gp << "set xrange [0:20]" << endl << "set grid" << endl << "plot -x - 5 * sin(3 * x) - 8 * cos(5 * x) notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; if (!p.termino()) getline(cin, stopChar); } } cout << "\nLuego de finalizar el entrenamiento" << endl << "Mejor individuo: x = " << p.mejorIndividuo().fenotipo().at(0) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl << "Generaciones evolucionadas: " << generacion << endl; } // ------------------------------- // Inciso c // ------------------------------- { const array<double, 4> limites = {{-100, 100, -100, 100}}; auto fitness = [](array<double, 2> fenotipo) -> double { double x = fenotipo.at(0); double y = fenotipo.at(1); double parte1 = pow(x * x + y * y, 0.25); double parte2 = pow(sin(50 * pow(x * x + y * y, 0.1)), 2) + 1; return -parte1 * parte2; }; Poblacion<10, 2> p{limites, fitness, /*individuos =*/100, /*generaciones =*/1000, /*umbral =*/100}; p.evaluarPoblacion(); cout << "\n-(pow(x * x + y * y, 0.25) * (pow(sin(50 * pow(x * x + y * y, 0.1)), 2)) + 1)" << endl << "===============================================================================" << endl << "Antes de iniciar el entrenamiento" << endl << "Mejor individuo: " << "x = " << p.mejorIndividuo().fenotipo().at(0) << " y = " << p.mejorIndividuo().fenotipo().at(1) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl; { const vector<Individuo<10, 2>> individuos = p.individuos(); mat puntos(individuos.size(), 3); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = individuos.at(i).fenotipo().at(1); puntos.at(i, 2) = fitness(individuos.at(i).fenotipo()); } gp << "set xlabel 'x' font ',10'" << endl << "set ylabel 'y' font ',10'" << endl << "set xrange [-100:100]" << endl << "set yrange [-100:100]" << endl << "set grid" << endl << "set samples 60" << endl << "set isosamples 60" << endl << "set hidden3d" << endl << "splot (-((x * x + y * y)**(0.25) * (sin(50 * (x * x + y * y)**(0.1))**2 + 1))) palette notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; getchar(); } int generacion; string stopChar = ""; for (generacion = 0; generacion < 500 && !p.termino(); ++generacion) { p.evolucionar(1); if (stopChar != "s" || p.termino()) { const vector<Individuo<10, 2>> individuos = p.individuos(); mat puntos(individuos.size(), 3); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = individuos.at(i).fenotipo().at(1); puntos.at(i, 2) = fitness(individuos.at(i).fenotipo()); } gp << "set xrange [-100:100]" << endl << "set yrange [-100:100]" << endl << "set grid" << endl << "set samples 60" << endl << "set isosamples 60" << endl << "splot (-((x * x + y * y)**(0.25) * (sin(50 * (x * x + y * y)**(0.1))**2 + 1))) palette notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; if (!p.termino()) getline(cin, stopChar); } } cout << "\nLuego de finalizar el entrenamiento" << endl << "Mejor individuo: " << "x = " << p.mejorIndividuo().fenotipo().at(0) << " y = " << p.mejorIndividuo().fenotipo().at(1) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl << "Cantidad de generaciones evolucionadas: " << generacion << endl; getchar(); } return 0; } <commit_msg>Guia 4 - Ejercicio 1: Pequeñas correcciones<commit_after>#include "genetico.cpp" #include <gnuplot-iostream.h> int main() { arma_rng::set_seed_random(); Gnuplot gp; // ------------------------------- // Inciso a // ------------------------------- { const array<double, 2> limites = {{-512, 512}}; auto fitness = [](array<double, 1> fenotipo) -> double { double x = fenotipo.at(0); return x * sin(sqrt(abs(x))); }; Poblacion<8, 1> p{limites, fitness, /*individuos =*/40, /*generaciones =*/500, /*umbral =*/100}; p.evaluarPoblacion(); cout << "Función x * sin(sqrt(abs(x)))" << endl << "=============================" << endl << "Antes de iniciar el entrenamiento" << endl << "Mejor individuo: x = " << p.mejorIndividuo().fenotipo().at(0) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl; { const auto& individuos = p.individuos(); mat puntos(individuos.size(), 2); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = fitness(individuos.at(i).fenotipo()); } gp << "set xrange [-512:512]" << endl << "set grid" << endl << "set samples 500" << endl << "plot x * sin(sqrt(abs(x))) notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; getchar(); } int generacion; string stopChar = ""; for (generacion = 0; generacion < 500 && !p.termino(); ++generacion) { p.evolucionar(1); if (stopChar != "s" || p.termino()) { const auto& individuos = p.individuos(); mat puntos(individuos.size(), 2); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = fitness(individuos.at(i).fenotipo()); } gp << "plot x * sin(sqrt(abs(x))) notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; if (!p.termino()) getline(cin, stopChar); } } cout << "\nLuego de finalizar el entrenamiento" << endl << "Mejor individuo: x = " << p.mejorIndividuo().fenotipo().at(0) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl << "Generaciones evolucionadas: " << generacion << endl; getchar(); } // ------------------------------- // Inciso b // ------------------------------- { const array<double, 2> limites = {{0, 20}}; auto fitness = [](array<double, 1> fenotipo) -> double { double x = fenotipo.at(0); return -x - 5 * sin(3 * x) - 8 * cos(5 * x); }; Poblacion<8, 1> p{limites, fitness, /*individuos =*/40, /*generaciones =*/500, /*umbral =*/100}; p.evaluarPoblacion(); cout << "\nFunción -x - 5 * sin(3 * x) - 8 * cos(5 * x)" << endl << "=============================" << endl << "Antes de iniciar el entrenamiento" << endl << "Mejor individuo: x = " << p.mejorIndividuo().fenotipo().at(0) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl; { const auto& individuos = p.individuos(); mat puntos(individuos.size(), 2); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = fitness(individuos.at(i).fenotipo()); } gp << "set xrange [0:20]" << endl << "set grid" << endl << "plot -x - 5 * sin(3 * x) - 8 * cos(5 * x) notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; getchar(); } int generacion; string stopChar = ""; for (generacion = 0; generacion < 500 && !p.termino(); ++generacion) { p.evolucionar(1); if (stopChar != "s" || p.termino()) { const auto& individuos = p.individuos(); mat puntos(individuos.size(), 2); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = fitness(individuos.at(i).fenotipo()); } gp << "plot -x - 5 * sin(3 * x) - 8 * cos(5 * x) notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; if (!p.termino()) getline(cin, stopChar); } } cout << "\nLuego de finalizar el entrenamiento" << endl << "Mejor individuo: x = " << p.mejorIndividuo().fenotipo().at(0) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl << "Generaciones evolucionadas: " << generacion << endl; getchar(); } // ------------------------------- // Inciso c // ------------------------------- { const array<double, 4> limites = {{-100, 100, -100, 100}}; auto fitness = [](array<double, 2> fenotipo) -> double { double x = fenotipo.at(0); double y = fenotipo.at(1); double parte1 = pow(x * x + y * y, 0.25); double parte2 = pow(sin(50 * pow(x * x + y * y, 0.1)), 2) + 1; return -parte1 * parte2; }; Poblacion<14, 2> p{limites, fitness, /*individuos =*/300, /*generaciones =*/1000, /*umbral =*/200}; p.evaluarPoblacion(); cout << "\n-(pow(x * x + y * y, 0.25) * (pow(sin(50 * pow(x * x + y * y, 0.1)), 2)) + 1)" << endl << "===============================================================================" << endl << "Antes de iniciar el entrenamiento" << endl << "Mejor individuo: " << "x = " << p.mejorIndividuo().fenotipo().at(0) << " y = " << p.mejorIndividuo().fenotipo().at(1) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl; { const auto& individuos = p.individuos(); mat puntos(individuos.size(), 3); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = individuos.at(i).fenotipo().at(1); puntos.at(i, 2) = fitness(individuos.at(i).fenotipo()); } gp << "set xlabel 'x' font ',10'" << endl << "set ylabel 'y' font ',10'" << endl << "set xrange [-100:100]" << endl << "set yrange [-100:100]" << endl << "set grid lw 2" << endl << "set samples 60" << endl << "set isosamples 60" << endl << "set pm3d depthorder hidden3d" << endl << "splot (-((x * x + y * y)**(0.25) * (sin(50 * (x * x + y * y)**(0.1))**2 + 1))) palette notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; getchar(); } int generacion; string stopChar = ""; for (generacion = 0; generacion < 500 && !p.termino(); ++generacion) { p.evolucionar(1); if (stopChar != "s" || p.termino()) { const auto& individuos = p.individuos(); mat puntos(individuos.size(), 3); for (unsigned int i = 0; i < puntos.n_rows; ++i) { puntos.at(i, 0) = individuos.at(i).fenotipo().at(0); puntos.at(i, 1) = individuos.at(i).fenotipo().at(1); puntos.at(i, 2) = fitness(individuos.at(i).fenotipo()); } gp << "splot (-((x * x + y * y)**(0.25) * (sin(50 * (x * x + y * y)**(0.1))**2 + 1))) palette notitle, " << gp.file1d(puntos) << " notitle with points lw 1.5" << endl; if (!p.termino()) getline(cin, stopChar); } } cout << "\nLuego de finalizar el entrenamiento" << endl << "Mejor individuo: " << "x = " << p.mejorIndividuo().fenotipo().at(0) << " y = " << p.mejorIndividuo().fenotipo().at(1) << endl << "Mejor fitness: " << p.mejorFitness() << endl << "Fitness promedio: " << p.fitnessPromdedio() << endl << "Cantidad de generaciones evolucionadas: " << generacion << endl; getchar(); } return 0; } <|endoftext|>
<commit_before>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2014-2022 Vaclav Slavik * * 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 "syntaxhighlighter.h" #include "catalog.h" #include "str_helpers.h" #include <unicode/uchar.h> #include <regex> namespace { class BasicSyntaxHighlighter : public SyntaxHighlighter { public: void Highlight(const std::wstring& s, const CallbackType& highlight) override { if (s.empty()) return; const int length = int(s.length()); // Leading whitespace: for (auto i = s.begin(); i != s.end(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.begin()); if (wlen) highlight(0, wlen, LeadingWhitespace); break; } } // Trailing whitespace: for (auto i = s.rbegin(); i != s.rend(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.rbegin()); if (wlen) highlight(length - wlen, length, LeadingWhitespace); break; } } int blank_block_pos = -1; for (auto i = s.begin(); i != s.end(); ++i) { // Some special whitespace characters should always be highlighted: if (*i == 0x00A0 /*non-breakable space*/) { int pos = int(i - s.begin()); highlight(pos, pos + 1, LeadingWhitespace); } // Duplicate whitespace (2+ spaces etc.): else if (u_isblank(*i)) { if (blank_block_pos == -1) blank_block_pos = int(i - s.begin()); } else if (blank_block_pos != -1) { int endpos = int(i - s.begin()); if (endpos - blank_block_pos >= 2) highlight(blank_block_pos, endpos, LeadingWhitespace); blank_block_pos = -1; } // Escape sequences: if (*i == '\\') { int pos = int(i - s.begin()); if (++i == s.end()) break; // Note: this must match AnyTranslatableTextCtrl::EscapePlainText() switch (*i) { case '0': case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case '\\': highlight(pos, pos + 2, Escape); break; default: break; } } } } }; /// Highlighter that runs multiple sub-highlighters class CompositeSyntaxHighlighter : public SyntaxHighlighter { public: void Add(std::shared_ptr<SyntaxHighlighter> h) { m_sub.push_back(h); } void Highlight(const std::wstring& s, const CallbackType& highlight) override { for (auto h : m_sub) h->Highlight(s, highlight); } private: std::vector<std::shared_ptr<SyntaxHighlighter>> m_sub; }; /// Match regular expressions for highlighting class RegexSyntaxHighlighter : public SyntaxHighlighter { public: static const std::wregex::flag_type flags = std::regex_constants::ECMAScript | std::regex_constants::optimize; RegexSyntaxHighlighter(const wchar_t *regex, TextKind kind) : m_re(regex, flags), m_kind(kind) {} RegexSyntaxHighlighter(const std::wregex& regex, TextKind kind) : m_re(regex), m_kind(kind) {} void Highlight(const std::wstring& s, const CallbackType& highlight) override { try { std::wsregex_iterator next(s.begin(), s.end(), m_re); std::wsregex_iterator end; while (next != end) { auto match = *next++; if (match.empty()) continue; int pos = static_cast<int>(match.position()); highlight(pos, pos + static_cast<int>(match.length()), m_kind); } } catch (std::regex_error& e) { switch (e.code()) { case std::regex_constants::error_complexity: case std::regex_constants::error_stack: // MSVC version of std::regex in particular can fail to match // e.g. HTML regex with backreferences on insanely large strings; // in that case, don't highlight instead of failing outright. return; default: throw; } } } private: std::wregex m_re; TextKind m_kind; }; std::wregex REOBJ_HTML_MARKUP(LR"((<\/?[a-zA-Z0-9:-]+(\s+[-:\w]+(=([-:\w+]|"[^"]*"|'[^']*'))?)*\s*\/?>)|(&[^ ;]+;))", RegexSyntaxHighlighter::flags); // variables expansion for various template languages std::wregex REOBJ_COMMON_PLACEHOLDERS( // // | | LR"(%[\w.-]+%|%?\{[\w.-]+\}|\{\{[\w.-]+\}\})", // | | | | | // | | | // | | +----------------------- {{var}} // | | // | +--------------------------------------- %{var} (Ruby) and {var} // | // +--------------------------------------------------- %var% (Twig) // RegexSyntaxHighlighter::flags); // php-format per http://php.net/manual/en/function.sprintf.php plus positionals const wchar_t* RE_PHP_FORMAT = LR"(%(\d+\$)?[-+]{0,2}([ 0]|'.)?-?\d*(\..?\d+)?[%bcdeEfFgGosuxX])"; // c-format per http://en.cppreference.com/w/cpp/io/c/fprintf, // http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html const wchar_t* RE_C_FORMAT = LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])"; // python-format old style https://docs.python.org/2/library/stdtypes.html#string-formatting // new style https://docs.python.org/3/library/string.html#format-string-syntax const wchar_t* RE_PYTHON_FORMAT = LR"((%(\(\w+\))?[-+ #0]?(\d+|\*)?(\.(\d+|\*))?[hlL]?[diouxXeEfFgGcrs%]))" // old style "|" LR"((\{([^{}])*\}))"; // new style, being permissive // ruby-format per https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-sprintf const wchar_t* RE_RUBY_FORMAT = LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])"; } // anonymous namespace SyntaxHighlighterPtr SyntaxHighlighter::ForItem(const CatalogItem& item, int kindsMask) { auto fmt = item.GetFormatFlag(); bool needsHTML = (kindsMask & Markup); if (needsHTML) { needsHTML = std::regex_search(str::to_wstring(item.GetString()), REOBJ_HTML_MARKUP) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), REOBJ_HTML_MARKUP)); } bool needsGenericPlaceholders = (kindsMask & Placeholder); if (needsGenericPlaceholders) { needsGenericPlaceholders = std::regex_search(str::to_wstring(item.GetString()), REOBJ_COMMON_PLACEHOLDERS) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), REOBJ_COMMON_PLACEHOLDERS)); } static auto basic = std::make_shared<BasicSyntaxHighlighter>(); if (!needsHTML && !needsGenericPlaceholders && fmt.empty()) { if (kindsMask & (LeadingWhitespace | Escape)) return basic; else return nullptr; } auto all = std::make_shared<CompositeSyntaxHighlighter>(); // HTML goes first, has lowest priority than special-purpose stuff like format strings: if (needsHTML) { static auto html = std::make_shared<RegexSyntaxHighlighter>(REOBJ_HTML_MARKUP, TextKind::Markup); all->Add(html); } if (needsGenericPlaceholders) { // If no format specified, heuristically apply highlighting of common variable markers static auto placeholders = std::make_shared<RegexSyntaxHighlighter>(REOBJ_COMMON_PLACEHOLDERS, TextKind::Placeholder); all->Add(placeholders); } if (kindsMask & Placeholder) { if (fmt == "php") { static auto php_format = std::make_shared<RegexSyntaxHighlighter>(RE_PHP_FORMAT, TextKind::Placeholder); all->Add(php_format); } else if (fmt == "c") { static auto c_format = std::make_shared<RegexSyntaxHighlighter>(RE_C_FORMAT, TextKind::Placeholder); all->Add(c_format); } else if (fmt == "python") { static auto python_format = std::make_shared<RegexSyntaxHighlighter>(RE_PYTHON_FORMAT, TextKind::Placeholder); all->Add(python_format); } else if (fmt == "ruby") { static auto ruby_format = std::make_shared<RegexSyntaxHighlighter>(RE_RUBY_FORMAT, TextKind::Placeholder); all->Add(ruby_format); } } // basic highlighting has highest priority, so should come last in the order: if (kindsMask & (LeadingWhitespace | Escape)) all->Add(basic); return all; } <commit_msg>Optimize format flag check when it is empty<commit_after>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2014-2022 Vaclav Slavik * * 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 "syntaxhighlighter.h" #include "catalog.h" #include "str_helpers.h" #include <unicode/uchar.h> #include <regex> namespace { class BasicSyntaxHighlighter : public SyntaxHighlighter { public: void Highlight(const std::wstring& s, const CallbackType& highlight) override { if (s.empty()) return; const int length = int(s.length()); // Leading whitespace: for (auto i = s.begin(); i != s.end(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.begin()); if (wlen) highlight(0, wlen, LeadingWhitespace); break; } } // Trailing whitespace: for (auto i = s.rbegin(); i != s.rend(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.rbegin()); if (wlen) highlight(length - wlen, length, LeadingWhitespace); break; } } int blank_block_pos = -1; for (auto i = s.begin(); i != s.end(); ++i) { // Some special whitespace characters should always be highlighted: if (*i == 0x00A0 /*non-breakable space*/) { int pos = int(i - s.begin()); highlight(pos, pos + 1, LeadingWhitespace); } // Duplicate whitespace (2+ spaces etc.): else if (u_isblank(*i)) { if (blank_block_pos == -1) blank_block_pos = int(i - s.begin()); } else if (blank_block_pos != -1) { int endpos = int(i - s.begin()); if (endpos - blank_block_pos >= 2) highlight(blank_block_pos, endpos, LeadingWhitespace); blank_block_pos = -1; } // Escape sequences: if (*i == '\\') { int pos = int(i - s.begin()); if (++i == s.end()) break; // Note: this must match AnyTranslatableTextCtrl::EscapePlainText() switch (*i) { case '0': case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case '\\': highlight(pos, pos + 2, Escape); break; default: break; } } } } }; /// Highlighter that runs multiple sub-highlighters class CompositeSyntaxHighlighter : public SyntaxHighlighter { public: void Add(std::shared_ptr<SyntaxHighlighter> h) { m_sub.push_back(h); } void Highlight(const std::wstring& s, const CallbackType& highlight) override { for (auto h : m_sub) h->Highlight(s, highlight); } private: std::vector<std::shared_ptr<SyntaxHighlighter>> m_sub; }; /// Match regular expressions for highlighting class RegexSyntaxHighlighter : public SyntaxHighlighter { public: static const std::wregex::flag_type flags = std::regex_constants::ECMAScript | std::regex_constants::optimize; RegexSyntaxHighlighter(const wchar_t *regex, TextKind kind) : m_re(regex, flags), m_kind(kind) {} RegexSyntaxHighlighter(const std::wregex& regex, TextKind kind) : m_re(regex), m_kind(kind) {} void Highlight(const std::wstring& s, const CallbackType& highlight) override { try { std::wsregex_iterator next(s.begin(), s.end(), m_re); std::wsregex_iterator end; while (next != end) { auto match = *next++; if (match.empty()) continue; int pos = static_cast<int>(match.position()); highlight(pos, pos + static_cast<int>(match.length()), m_kind); } } catch (std::regex_error& e) { switch (e.code()) { case std::regex_constants::error_complexity: case std::regex_constants::error_stack: // MSVC version of std::regex in particular can fail to match // e.g. HTML regex with backreferences on insanely large strings; // in that case, don't highlight instead of failing outright. return; default: throw; } } } private: std::wregex m_re; TextKind m_kind; }; std::wregex REOBJ_HTML_MARKUP(LR"((<\/?[a-zA-Z0-9:-]+(\s+[-:\w]+(=([-:\w+]|"[^"]*"|'[^']*'))?)*\s*\/?>)|(&[^ ;]+;))", RegexSyntaxHighlighter::flags); // variables expansion for various template languages std::wregex REOBJ_COMMON_PLACEHOLDERS( // // | | LR"(%[\w.-]+%|%?\{[\w.-]+\}|\{\{[\w.-]+\}\})", // | | | | | // | | | // | | +----------------------- {{var}} // | | // | +--------------------------------------- %{var} (Ruby) and {var} // | // +--------------------------------------------------- %var% (Twig) // RegexSyntaxHighlighter::flags); // php-format per http://php.net/manual/en/function.sprintf.php plus positionals const wchar_t* RE_PHP_FORMAT = LR"(%(\d+\$)?[-+]{0,2}([ 0]|'.)?-?\d*(\..?\d+)?[%bcdeEfFgGosuxX])"; // c-format per http://en.cppreference.com/w/cpp/io/c/fprintf, // http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html const wchar_t* RE_C_FORMAT = LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])"; // python-format old style https://docs.python.org/2/library/stdtypes.html#string-formatting // new style https://docs.python.org/3/library/string.html#format-string-syntax const wchar_t* RE_PYTHON_FORMAT = LR"((%(\(\w+\))?[-+ #0]?(\d+|\*)?(\.(\d+|\*))?[hlL]?[diouxXeEfFgGcrs%]))" // old style "|" LR"((\{([^{}])*\}))"; // new style, being permissive // ruby-format per https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-sprintf const wchar_t* RE_RUBY_FORMAT = LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])"; } // anonymous namespace SyntaxHighlighterPtr SyntaxHighlighter::ForItem(const CatalogItem& item, int kindsMask) { auto fmt = item.GetFormatFlag(); bool needsHTML = (kindsMask & Markup); if (needsHTML) { needsHTML = std::regex_search(str::to_wstring(item.GetString()), REOBJ_HTML_MARKUP) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), REOBJ_HTML_MARKUP)); } bool needsGenericPlaceholders = (kindsMask & Placeholder); if (needsGenericPlaceholders) { needsGenericPlaceholders = std::regex_search(str::to_wstring(item.GetString()), REOBJ_COMMON_PLACEHOLDERS) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), REOBJ_COMMON_PLACEHOLDERS)); } static auto basic = std::make_shared<BasicSyntaxHighlighter>(); if (!needsHTML && !needsGenericPlaceholders && fmt.empty()) { if (kindsMask & (LeadingWhitespace | Escape)) return basic; else return nullptr; } auto all = std::make_shared<CompositeSyntaxHighlighter>(); // HTML goes first, has lowest priority than special-purpose stuff like format strings: if (needsHTML) { static auto html = std::make_shared<RegexSyntaxHighlighter>(REOBJ_HTML_MARKUP, TextKind::Markup); all->Add(html); } if (needsGenericPlaceholders) { // If no format specified, heuristically apply highlighting of common variable markers static auto placeholders = std::make_shared<RegexSyntaxHighlighter>(REOBJ_COMMON_PLACEHOLDERS, TextKind::Placeholder); all->Add(placeholders); } if (!fmt.empty() && (kindsMask & Placeholder)) { if (fmt == "php") { static auto php_format = std::make_shared<RegexSyntaxHighlighter>(RE_PHP_FORMAT, TextKind::Placeholder); all->Add(php_format); } else if (fmt == "c") { static auto c_format = std::make_shared<RegexSyntaxHighlighter>(RE_C_FORMAT, TextKind::Placeholder); all->Add(c_format); } else if (fmt == "python") { static auto python_format = std::make_shared<RegexSyntaxHighlighter>(RE_PYTHON_FORMAT, TextKind::Placeholder); all->Add(python_format); } else if (fmt == "ruby") { static auto ruby_format = std::make_shared<RegexSyntaxHighlighter>(RE_RUBY_FORMAT, TextKind::Placeholder); all->Add(ruby_format); } } // basic highlighting has highest priority, so should come last in the order: if (kindsMask & (LeadingWhitespace | Escape)) all->Add(basic); return all; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief ST7565(R) LCD ドライバー @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief ST7565 テンプレートクラス @param[in] CSI_IO CSI(SPI) 制御クラス @param[in] CS デバイス選択、レジスター選択、制御クラス @param[in] A0 制御切り替え、レジスター選択、制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CSI_IO, class CS, class A0> class ST7565 { CSI_IO& csi_; enum class CMD : uint8_t { DISPLAY_OFF = 0xAE, DISPLAY_ON = 0xAF, SET_DISP_START_LINE = 0x40, SET_PAGE = 0xB0, SET_COLUMN_UPPER = 0x10, SET_COLUMN_LOWER = 0x00, SET_ADC_NORMAL = 0xA0, SET_ADC_REVERSE = 0xA1, SET_DISP_NORMAL = 0xA6, SET_DISP_REVERSE = 0xA7, SET_ALLPTS_NORMAL = 0xA4, SET_ALLPTS_ON = 0xA5, SET_BIAS_9 = 0xA2, SET_BIAS_7 = 0xA3, RMW = 0xE0, RMW_CLEAR = 0xEE, INTERNAL_RESET = 0xE2, SET_COM_NORMAL = 0xC0, SET_COM_REVERSE = 0xC8, SET_POWER_CONTROL = 0x28, SET_RESISTOR_RATIO = 0x20, SET_VOLUME_FIRST = 0x81, SET_VOLUME_SECOND = 0x00, SET_STATIC_OFF = 0xAC, SET_STATIC_ON = 0xAD, SET_STATIC_REG = 0x00, SET_BOOSTER_FIRST = 0xF8, SET_BOOSTER_234 = 0, SET_BOOSTER_5 = 1, SET_BOOSTER_6 = 3, NOP = 0xE3, TEST = 0xF0, }; inline void write_(CMD cmd) { csi_.xchg(static_cast<uint8_t>(cmd)); } inline void write_(CMD cmd, uint8_t ord) { csi_.xchg(static_cast<uint8_t>(cmd) | ord); } inline void chip_enable_(bool f = true) const { CS::P = !f; } inline void reg_select_(bool f) const { A0::P = f; } void init_(bool comrvs) { reg_select_(0); chip_enable_(); // toggle RST low to reset; CS low so it'll listen to us // if (cs > 0) // digitalWrite(cs, LOW); // digitalWrite(rst, LOW); // _delay_ms(500); // digitalWrite(rst, HIGH); write_(CMD::DISPLAY_OFF); // LCD bias select write_(CMD::SET_BIAS_7); // ADC select write_(CMD::SET_ADC_NORMAL); // SHL select if(comrvs) { write_(CMD::SET_COM_REVERSE); } else { write_(CMD::SET_COM_NORMAL); } // Initial display line write_(CMD::SET_DISP_START_LINE); // turn on voltage converter (VC=1, VR=0, VF=0) write_(CMD::SET_POWER_CONTROL, 0x4); // wait for 50% rising utils::delay::milli_second(50); // turn on voltage regulator (VC=1, VR=1, VF=0) write_(CMD::SET_POWER_CONTROL, 0x6); // wait >=50ms utils::delay::milli_second(50); // turn on voltage follower (VC=1, VR=1, VF=1) write_(CMD::SET_POWER_CONTROL, 0x7); // wait 10ms utils::delay::milli_second(10); // set lcd operating voltage (regulator resistor, ref voltage resistor) write_(CMD::SET_RESISTOR_RATIO, 0x6); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// ST7565(CSI_IO& csi) : csi_(csi) { } //-----------------------------------------------------------------// /*! @brief ブライトネス設定 @param[in] val ブライトネス値 */ //-----------------------------------------------------------------// void set_brightness(uint8_t val) { write_(CMD::SET_VOLUME_FIRST); write_(CMD::SET_VOLUME_SECOND, (val & 0x3f)); } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] contrast コントラスト @param[in] comrvs コモンライン・リバースの場合:true */ //-----------------------------------------------------------------// void start(uint8_t contrast, bool comrvs = false) { CS::DIR = 1; // (/CS) output A0::DIR = 1; // (A0) output reg_select_(0); chip_enable_(false); utils::delay::milli_second(100); init_(comrvs); write_(CMD::DISPLAY_ON); write_(CMD::SET_ALLPTS_NORMAL); set_brightness(contrast); chip_enable_(false); } //-----------------------------------------------------------------// /*! @brief コピー @param[in] src フレームバッファソース @param[in] num 転送ページ数 */ //-----------------------------------------------------------------// void copy(const uint8_t* src, uint8_t num) { chip_enable_(); uint8_t ofs = 0x00; for(uint8_t page = 0; page < num; ++page) { reg_select_(0); write_(CMD::SET_PAGE, page); write_(CMD::SET_COLUMN_LOWER, ofs & 0x0f); write_(CMD::SET_COLUMN_UPPER, ofs >> 4); write_(CMD::RMW); reg_select_(1); csi_.send(src, 128); src += 128; } reg_select_(0); chip_enable_(false); } }; } <commit_msg>update page offset<commit_after>#pragma once //=====================================================================// /*! @file @brief ST7565(R) LCD ドライバー @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief ST7565 テンプレートクラス @param[in] CSI_IO CSI(SPI) 制御クラス @param[in] CS デバイス選択、レジスター選択、制御クラス @param[in] A0 制御切り替え、レジスター選択、制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CSI_IO, class CS, class A0> class ST7565 { CSI_IO& csi_; enum class CMD : uint8_t { DISPLAY_OFF = 0xAE, DISPLAY_ON = 0xAF, SET_DISP_START_LINE = 0x40, SET_PAGE = 0xB0, SET_COLUMN_UPPER = 0x10, SET_COLUMN_LOWER = 0x00, SET_ADC_NORMAL = 0xA0, SET_ADC_REVERSE = 0xA1, SET_DISP_NORMAL = 0xA6, SET_DISP_REVERSE = 0xA7, SET_ALLPTS_NORMAL = 0xA4, SET_ALLPTS_ON = 0xA5, SET_BIAS_9 = 0xA2, SET_BIAS_7 = 0xA3, RMW = 0xE0, RMW_CLEAR = 0xEE, INTERNAL_RESET = 0xE2, SET_COM_NORMAL = 0xC0, SET_COM_REVERSE = 0xC8, SET_POWER_CONTROL = 0x28, SET_RESISTOR_RATIO = 0x20, SET_VOLUME_FIRST = 0x81, SET_VOLUME_SECOND = 0x00, SET_STATIC_OFF = 0xAC, SET_STATIC_ON = 0xAD, SET_STATIC_REG = 0x00, SET_BOOSTER_FIRST = 0xF8, SET_BOOSTER_234 = 0, SET_BOOSTER_5 = 1, SET_BOOSTER_6 = 3, NOP = 0xE3, TEST = 0xF0, }; inline void write_(CMD cmd) { csi_.xchg(static_cast<uint8_t>(cmd)); } inline void write_(CMD cmd, uint8_t ord) { csi_.xchg(static_cast<uint8_t>(cmd) | ord); } inline void chip_enable_(bool f = true) const { CS::P = !f; } inline void reg_select_(bool f) const { A0::P = f; } void init_(bool comrvs) { reg_select_(0); chip_enable_(); // toggle RST low to reset; CS low so it'll listen to us // if (cs > 0) // digitalWrite(cs, LOW); // digitalWrite(rst, LOW); // _delay_ms(500); // digitalWrite(rst, HIGH); write_(CMD::DISPLAY_OFF); // LCD bias select write_(CMD::SET_BIAS_7); // ADC select write_(CMD::SET_ADC_NORMAL); // SHL select if(comrvs) { write_(CMD::SET_COM_REVERSE); } else { write_(CMD::SET_COM_NORMAL); } // Initial display line write_(CMD::SET_DISP_START_LINE); // turn on voltage converter (VC=1, VR=0, VF=0) write_(CMD::SET_POWER_CONTROL, 0x4); // wait for 50% rising utils::delay::milli_second(50); // turn on voltage regulator (VC=1, VR=1, VF=0) write_(CMD::SET_POWER_CONTROL, 0x6); // wait >=50ms utils::delay::milli_second(50); // turn on voltage follower (VC=1, VR=1, VF=1) write_(CMD::SET_POWER_CONTROL, 0x7); // wait 10ms utils::delay::milli_second(10); // set lcd operating voltage (regulator resistor, ref voltage resistor) write_(CMD::SET_RESISTOR_RATIO, 0x6); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// ST7565(CSI_IO& csi) : csi_(csi) { } //-----------------------------------------------------------------// /*! @brief ブライトネス設定 @param[in] val ブライトネス値 */ //-----------------------------------------------------------------// void set_brightness(uint8_t val) { write_(CMD::SET_VOLUME_FIRST); write_(CMD::SET_VOLUME_SECOND, (val & 0x3f)); } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] contrast コントラスト @param[in] comrvs コモンライン・リバースの場合:true */ //-----------------------------------------------------------------// void start(uint8_t contrast, bool comrvs = false) { CS::DIR = 1; // (/CS) output A0::DIR = 1; // (A0) output reg_select_(0); chip_enable_(false); utils::delay::milli_second(100); init_(comrvs); write_(CMD::DISPLAY_ON); write_(CMD::SET_ALLPTS_NORMAL); set_brightness(contrast); chip_enable_(false); } //-----------------------------------------------------------------// /*! @brief コピー @param[in] src フレームバッファソース @param[in] num 転送ページ数 @param[in] ofs 転送オフセット */ //-----------------------------------------------------------------// void copy(const uint8_t* src, uint8_t num, uint8_t ofs = 0) { chip_enable_(); uint8_t o = 0x00; for(uint8_t page = ofs; page < (ofs + num); ++page) { reg_select_(0); write_(CMD::SET_PAGE, page); write_(CMD::SET_COLUMN_LOWER, o & 0x0f); write_(CMD::SET_COLUMN_UPPER, o >> 4); write_(CMD::RMW); reg_select_(1); csi_.send(src, 128); src += 128; } reg_select_(0); chip_enable_(false); } }; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/framework/prune.h" #include <algorithm> #include <set> #include <string> #include <vector> #include <glog/logging.h> namespace paddle { namespace framework { const std::string kFeedOpType = "feed"; const std::string kFetchOpType = "fetch"; const std::string kDropOutOpType = "dropout"; const std::string kBatchNormOpType = "batch_norm"; bool HasDependentVar(const proto::OpDesc& op_desc, const std::set<std::string>& dependent_vars) { for (auto& var : op_desc.outputs()) { for (auto& argu : var.arguments()) { if (dependent_vars.count(argu) != 0) { return true; } } } return false; } bool IsTarget(const proto::OpDesc& op_desc) { if (op_desc.has_is_target()) { return op_desc.is_target(); } return false; } void prune_impl(const proto::ProgramDesc& input, proto::ProgramDesc* output, int block_id) { // TODO(tonyyang-svail): // - will change to use multiple blocks for RNN op and Cond Op auto& block = input.blocks(block_id); auto& ops = block.ops(); bool expect_feed = true; for (auto& op_desc : ops) { PADDLE_ENFORCE(op_desc.type() != kFeedOpType || expect_feed, "All FeedOps are at the beginning of the ProgramDesc"); expect_feed = (op_desc.type() == kFeedOpType); } bool expect_fetch = true; for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) { auto& op_desc = *op_iter; PADDLE_ENFORCE(op_desc.type() != kFetchOpType || expect_fetch, "All FetchOps must at the end of the ProgramDesc"); expect_fetch = (op_desc.type() == kFetchOpType); } std::set<std::string> dependent_vars; std::vector<bool> should_run; for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) { auto& op_desc = *op_iter; if (IsTarget(op_desc) || HasDependentVar(op_desc, dependent_vars)) { // insert its input to the dependency graph for (auto& var : op_desc.inputs()) { for (auto& argu : var.arguments()) { dependent_vars.insert(argu); } } should_run.push_back(true); } else { should_run.push_back(false); } } // since we are traversing the ProgramDesc in reverse order // we reverse the should_run vector std::reverse(should_run.begin(), should_run.end()); *output = input; auto* op_field = output->mutable_blocks(block_id)->mutable_ops(); op_field->Clear(); for (size_t i = 0; i < should_run.size(); ++i) { if (should_run[i]) { *op_field->Add() = input.blocks(block_id).ops(i); } } } // TODO(fengjiayi): Prune() could be inplaced to avoid unnecessary copies void Prune(const proto::ProgramDesc& input, proto::ProgramDesc* output) { prune_impl(input, output, 0); } void inference_optimize_impl(const proto::ProgramDesc& input, proto::ProgramDesc* output, int block_id) { *output = input; auto* op_field = output->mutable_blocks(block_id)->mutable_ops(); for (auto& op_desc : *op_field) { if (op_desc.type() == kDropOutOpType || op_desc.type() == kBatchNormOpType) { for (auto& attr : *op_desc.mutable_attrs()) { if (attr.name() == "is_test") { attr.set_b(true); break; } } } } } void InferenceOptimize(const proto::ProgramDesc& input, proto::ProgramDesc* output) { inference_optimize_impl(input, output, 0); } } // namespace framework } // namespace paddle <commit_msg>initial commit<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/framework/prune.h" #include <algorithm> #include <set> #include <string> #include <vector> #include <glog/logging.h> namespace paddle { namespace framework { const std::string kFeedOpType = "feed"; const std::string kFetchOpType = "fetch"; const std::string kDropOutOpType = "dropout"; const std::string kBatchNormOpType = "batch_norm"; bool HasDependentVar(const proto::OpDesc& op_desc, const std::set<std::string>& dependent_vars) { for (auto& var : op_desc.outputs()) { for (auto& argu : var.arguments()) { if (dependent_vars.count(argu) != 0) { return true; } } } return false; } bool IsTarget(const proto::OpDesc& op_desc) { if (op_desc.has_is_target()) { return op_desc.is_target(); } return false; } void prune_impl(const proto::ProgramDesc& input, proto::ProgramDesc* output, int block_id) { // TODO(tonyyang-svail): // - will change to use multiple blocks for RNN op and Cond Op auto& block = input.blocks(block_id); auto& ops = block.ops(); bool expect_feed = true; for (auto& op_desc : ops) { PADDLE_ENFORCE(op_desc.type() != kFeedOpType || expect_feed, "All FeedOps are at the beginning of the ProgramDesc"); expect_feed = (op_desc.type() == kFeedOpType); } bool expect_fetch = true; for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) { auto& op_desc = *op_iter; PADDLE_ENFORCE(op_desc.type() != kFetchOpType || expect_fetch, "All FetchOps must at the end of the ProgramDesc"); expect_fetch = (op_desc.type() == kFetchOpType); } std::set<std::string> dependent_vars; std::vector<bool> should_run; for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) { auto& op_desc = *op_iter; if (IsTarget(op_desc) || HasDependentVar(op_desc, dependent_vars)) { // insert its input to the dependency graph for (auto& var : op_desc.inputs()) { for (auto& argu : var.arguments()) { dependent_vars.insert(argu); } } should_run.push_back(true); } else { should_run.push_back(false); } } // since we are traversing the ProgramDesc in reverse order // we reverse the should_run vector std::reverse(should_run.begin(), should_run.end()); *output = input; auto* op_field = output->mutable_blocks(block_id)->mutable_ops(); op_field->Clear(); for (size_t i = 0; i < should_run.size(); ++i) { if (should_run[i]) { *op_field->Add() = input.blocks(block_id).ops(i); } } // remove the vars in ProgramDesc that are not referenced in // the pruned ops std::unordered_map<std::string name, proto::VarDesc> var_map; auto* var_field = output->mutable_blocks(block_id)->mutable_vars(); for (auto* var : *var_field) { var_map[var->name()] = *var; } // for (size_t i = 0; i < var_field->size(); ++i) { // auto* var = (*var_field)[i]; // var_map[var->name()] = *var; // } // var_field->Clear(); // for (size_t i = 0; i < op_field->size(); ++i) { // auto* op = (*op_field)[i]; // auto* input_field = op->mutable_inputs(); // for (size_t j = 0; j < input_field->size(); ++j) { // auto* input_names = (*input_field)[j]->arguments(); // for () // *var_field->Add() = var_map[] // } // auto* ouput_field = op->mutable_outputs(); // for (size_t k = 0; k < output_field->size(); ++k) { // } // } } // TODO(fengjiayi): Prune() could be inplaced to avoid unnecessary copies void Prune(const proto::ProgramDesc& input, proto::ProgramDesc* output) { prune_impl(input, output, 0); } void inference_optimize_impl(const proto::ProgramDesc& input, proto::ProgramDesc* output, int block_id) { *output = input; auto* op_field = output->mutable_blocks(block_id)->mutable_ops(); for (auto& op_desc : *op_field) { if (op_desc.type() == kDropOutOpType || op_desc.type() == kBatchNormOpType) { for (auto& attr : *op_desc.mutable_attrs()) { if (attr.name() == "is_test") { attr.set_b(true); break; } } } } } void InferenceOptimize(const proto::ProgramDesc& input, proto::ProgramDesc* output) { inference_optimize_impl(input, output, 0); } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>#include <osgGA/AnimationPathManipulator> #include <fstream> using namespace osgGA; AnimationPathManipulator::AnimationPathManipulator(osg::AnimationPath* animationPath) { _printOutTimingInfo = true; _animationPath = animationPath; _timeOffset = 0.0; _timeScale = 1.0; _isPaused = false; _realStartOfTimedPeriod = 0.0; _animStartOfTimedPeriod = 0.0; _numOfFramesSinceStartOfTimedPeriod = -1; // need to init. } AnimationPathManipulator::AnimationPathManipulator( const std::string& filename ) { _printOutTimingInfo = true; _animationPath = new osg::AnimationPath; _animationPath->setLoopMode(osg::AnimationPath::LOOP); _timeOffset = 0.0f; _timeScale = 1.0f; _isPaused = false; std::ifstream in(filename.c_str()); if (!in) { osg::notify(osg::WARN) << "AnimationPathManipulator: Cannot open animation path file \"" << filename << "\".\n"; _valid = false; return; } _animationPath->read(in); in.close(); } void AnimationPathManipulator::home(double currentTime) { if (_animationPath.valid()) { _timeOffset = _animationPath->getFirstTime()-currentTime; } // reset the timing of the animation. _numOfFramesSinceStartOfTimedPeriod=-1; } void AnimationPathManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter&) { home(ea.getTime()); } void AnimationPathManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& aa) { home(ea,aa); } bool AnimationPathManipulator::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us) { if( !valid() ) return false; switch( ea.getEventType() ) { case GUIEventAdapter::FRAME: if( _isPaused ) { handleFrame( _pauseTime ); } else { handleFrame( ea.getTime() ); } return false; case GUIEventAdapter::KEYDOWN: if (ea.getKey()==' ') { _isPaused = false; home(ea,us); us.requestRedraw(); us.requestContinuousUpdate(false); return true; } else if(ea.getKey() == 'p') { if( _isPaused ) { _isPaused = false; _timeOffset -= ea.getTime() - _pauseTime; } else { _isPaused = true; _pauseTime = ea.getTime(); } us.requestRedraw(); us.requestContinuousUpdate(false); return true; } break; default: break; } return false; } void AnimationPathManipulator::getUsage(osg::ApplicationUsage& usage) const { usage.addKeyboardMouseBinding("AnimationPath: Space","Reset the viewing position to start of animation"); usage.addKeyboardMouseBinding("AnimationPath: p","Pause/resume animation."); } void AnimationPathManipulator::handleFrame( double time ) { osg::AnimationPath::ControlPoint cp; double animTime = (time+_timeOffset)*_timeScale; _animationPath->getInterpolatedControlPoint( animTime, cp ); if (_numOfFramesSinceStartOfTimedPeriod==-1) { _realStartOfTimedPeriod = time; _animStartOfTimedPeriod = animTime; } ++_numOfFramesSinceStartOfTimedPeriod; if (_printOutTimingInfo) { double delta = (animTime-_animStartOfTimedPeriod); if (delta>=_animationPath->getPeriod()) { double frameRate = (double)_numOfFramesSinceStartOfTimedPeriod/delta; osg::notify(osg::NOTICE) <<"AnimatonPath completed in "<<delta<<" seconds, completing "<<_numOfFramesSinceStartOfTimedPeriod<<" frames,"<<std::endl; osg::notify(osg::NOTICE) <<" average frame rate = "<<frameRate<<std::endl; // reset counters for next loop. _realStartOfTimedPeriod = time; _animStartOfTimedPeriod = animTime; _numOfFramesSinceStartOfTimedPeriod = 0; } } cp.getMatrix( _matrix ); } <commit_msg>Added < and > key bindings to allow the speed to be animation speed to be increased or decreased.<commit_after>#include <osgGA/AnimationPathManipulator> #include <fstream> using namespace osgGA; AnimationPathManipulator::AnimationPathManipulator(osg::AnimationPath* animationPath) { _printOutTimingInfo = true; _animationPath = animationPath; _timeOffset = 0.0; _timeScale = 1.0; _isPaused = false; _realStartOfTimedPeriod = 0.0; _animStartOfTimedPeriod = 0.0; _numOfFramesSinceStartOfTimedPeriod = -1; // need to init. } AnimationPathManipulator::AnimationPathManipulator( const std::string& filename ) { _printOutTimingInfo = true; _animationPath = new osg::AnimationPath; _animationPath->setLoopMode(osg::AnimationPath::LOOP); _timeOffset = 0.0f; _timeScale = 1.0f; _isPaused = false; std::ifstream in(filename.c_str()); if (!in) { osg::notify(osg::WARN) << "AnimationPathManipulator: Cannot open animation path file \"" << filename << "\".\n"; _valid = false; return; } _animationPath->read(in); in.close(); } void AnimationPathManipulator::home(double currentTime) { if (_animationPath.valid()) { _timeOffset = _animationPath->getFirstTime()-currentTime; } // reset the timing of the animation. _numOfFramesSinceStartOfTimedPeriod=-1; } void AnimationPathManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter&) { home(ea.getTime()); } void AnimationPathManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& aa) { home(ea,aa); } bool AnimationPathManipulator::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us) { if( !valid() ) return false; switch( ea.getEventType() ) { case GUIEventAdapter::FRAME: if( _isPaused ) { handleFrame( _pauseTime ); } else { handleFrame( ea.getTime() ); } return false; case GUIEventAdapter::KEYDOWN: if (ea.getKey()==' ') { _isPaused = false; _timeScale = 1.0; home(ea,us); us.requestRedraw(); us.requestContinuousUpdate(false); return true; } else if (ea.getKey()=='>') { double time = _isPaused ? _pauseTime : ea.getTime(); double animationTime = (time+_timeOffset)*_timeScale; _timeScale *= 1.1; osg::notify(osg::NOTICE)<<"Animation speed = "<<_timeScale*100<<"%"<<std::endl; // adjust timeOffset so the current animationTime does change. _timeOffset = animationTime/_timeScale - time; return true; } else if (ea.getKey()=='<') { double time = _isPaused ? _pauseTime : ea.getTime(); double animationTime = (time+_timeOffset)*_timeScale; _timeScale /= 1.1; osg::notify(osg::NOTICE)<<"Animation speed = "<<_timeScale*100<<"%"<<std::endl; // adjust timeOffset so the current animationTime does change. _timeOffset = animationTime/_timeScale - time; return true; } else if(ea.getKey() == 'p') { if( _isPaused ) { _isPaused = false; _timeOffset -= ea.getTime() - _pauseTime; } else { _isPaused = true; _pauseTime = ea.getTime(); } us.requestRedraw(); us.requestContinuousUpdate(false); return true; } break; default: break; } return false; } void AnimationPathManipulator::getUsage(osg::ApplicationUsage& usage) const { usage.addKeyboardMouseBinding("AnimationPath: Space","Reset the viewing position to start of animation"); usage.addKeyboardMouseBinding("AnimationPath: p","Pause/resume animation."); usage.addKeyboardMouseBinding("AnimationPath: <","Slow down animation speed."); usage.addKeyboardMouseBinding("AnimationPath: <","Speed up animation speed."); } void AnimationPathManipulator::handleFrame( double time ) { osg::AnimationPath::ControlPoint cp; double animTime = (time+_timeOffset)*_timeScale; _animationPath->getInterpolatedControlPoint( animTime, cp ); if (_numOfFramesSinceStartOfTimedPeriod==-1) { _realStartOfTimedPeriod = time; _animStartOfTimedPeriod = animTime; } ++_numOfFramesSinceStartOfTimedPeriod; if (_printOutTimingInfo) { double delta = (animTime-_animStartOfTimedPeriod); if (delta>=_animationPath->getPeriod()) { double frameRate = (double)_numOfFramesSinceStartOfTimedPeriod/delta; osg::notify(osg::NOTICE) <<"AnimatonPath completed in "<<delta<<" seconds, completing "<<_numOfFramesSinceStartOfTimedPeriod<<" frames,"<<std::endl; osg::notify(osg::NOTICE) <<" average frame rate = "<<frameRate<<std::endl; // reset counters for next loop. _realStartOfTimedPeriod = time; _animStartOfTimedPeriod = animTime; _numOfFramesSinceStartOfTimedPeriod = 0; } } cp.getMatrix( _matrix ); } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 2007 Cedric Pinson * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commercial and non commercial * applications, as long as this copyright notice is maintained. * * This application 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. * * Authors: * Cedric Pinson <mornifle@plopbyte.net> * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef DATADIR #define DATADIR "." #endif // DATADIR #include <osg/GraphicsContext> #include "RenderSurface.h" #include "CameraConfig.h" #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osg/io_utils> using namespace osgProducer; static osg::GraphicsContext::Traits* buildTrait(RenderSurface& rs) { VisualChooser& vc = *rs.getVisualChooser(); osg::GraphicsContext::Traits* traits = new osg::GraphicsContext::Traits; for (std::vector<VisualChooser::VisualAttribute>::iterator it = vc._visual_attributes.begin(); it != vc._visual_attributes.end(); it++) { switch(it->_attribute) { case(VisualChooser::UseGL): break; // on by default in osgViewer case(VisualChooser::BufferSize): break; // no present mapping case(VisualChooser::Level): traits->level = it->_parameter; break; case(VisualChooser::RGBA): break; // automatically set in osgViewer case(VisualChooser::DoubleBuffer): traits->doubleBuffer = true; break; case(VisualChooser::Stereo): traits->quadBufferStereo = true; break; case(VisualChooser::AuxBuffers): break; // no present mapping case(VisualChooser::RedSize): traits->red = it->_parameter; break; case(VisualChooser::GreenSize): traits->green = it->_parameter; break; case(VisualChooser::BlueSize): traits->blue = it->_parameter; break; case(VisualChooser::AlphaSize): traits->alpha = it->_parameter; break; case(VisualChooser::DepthSize): traits->depth = it->_parameter; break; case(VisualChooser::StencilSize): traits->stencil = it->_parameter; break; case(VisualChooser::AccumRedSize): break; // no present mapping case(VisualChooser::AccumGreenSize): break; // no present mapping case(VisualChooser::AccumBlueSize): break; // no present mapping case(VisualChooser::AccumAlphaSize): break; // no present mapping case(VisualChooser::Samples): traits->samples = it->_parameter; break; case(VisualChooser::SampleBuffers): traits->sampleBuffers = 1; break; } } OSG_INFO<<"ReaderWriterCFG buildTrait traits->depth="<<traits->depth<<std::endl; OSG_INFO<<"ReaderWriterCFG buildTrait traits->samples="<<traits->samples<<std::endl; OSG_INFO<<"ReaderWriterCFG buildTrait traits->sampleBuffers="<<traits->sampleBuffers<<std::endl; traits->hostName = rs.getHostName(); traits->displayNum = rs.getDisplayNum(); traits->screenNum = rs.getScreenNum(); traits->windowName = rs.getWindowName(); traits->x = rs.getWindowOriginX(); traits->y = rs.getWindowOriginY(); traits->width = rs.getWindowWidth(); traits->height = rs.getWindowHeight(); traits->windowDecoration = rs.usesBorder(); traits->sharedContext = 0; traits->pbuffer = (rs.getDrawableType()==osgProducer::RenderSurface::DrawableType_PBuffer); traits->overrideRedirect = rs.usesOverrideRedirect(); return traits; } static osgViewer::View* load(const std::string& file, const osgDB::ReaderWriter::Options* option) { osg::ref_ptr<CameraConfig> config = new CameraConfig; //std::cout << "Parse file " << file << std::endl; config->parseFile(file); RenderSurface* rs = 0; Camera* cm = 0; std::map<RenderSurface*,osg::ref_ptr<osg::GraphicsContext> > surfaces; osg::ref_ptr<osgViewer::View> _view = new osgViewer::View; for (int i = 0; i < (int)config->getNumberOfCameras(); i++) { cm = config->getCamera(i); rs = cm->getRenderSurface(); if (rs->getDrawableType() != osgProducer::RenderSurface::DrawableType_Window) continue; osg::ref_ptr<const osg::GraphicsContext::Traits> traits; osg::ref_ptr<osg::GraphicsContext> gc; if (surfaces.find(rs) != surfaces.end()) { gc = surfaces[rs]; traits = gc.valid() ? gc->getTraits() : 0; } else { osg::GraphicsContext::Traits* newtraits = buildTrait(*rs); #if 0 osg::GraphicsContext::ScreenIdentifier si; si.readDISPLAY(); if (si.displayNum>=0) newtraits->displayNum = si.displayNum; if (si.screenNum>=0) newtraits->screenNum = si.screenNum; #endif gc = osg::GraphicsContext::createGraphicsContext(newtraits); surfaces[rs] = gc.get(); traits = gc.valid() ? gc->getTraits() : 0; } // std::cout << rs->getWindowName() << " " << rs->getWindowOriginX() << " " << rs->getWindowOriginY() << " " << rs->getWindowWidth() << " " << rs->getWindowHeight() << std::endl; if (gc.valid()) { OSG_INFO<<" GraphicsWindow has been created successfully."<<std::endl; osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setGraphicsContext(gc.get()); int x,y; unsigned int width,height; cm->applyLens(); cm->getProjectionRectangle(x, y, width, height); camera->setViewport(new osg::Viewport(x, y, width, height)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); osg::Matrix projection(cm->getProjectionMatrix()); osg::Matrix offset = osg::Matrix::identity(); cm->setViewByMatrix(offset); osg::Matrix view = osg::Matrix(cm->getPositionAndAttitudeMatrix()); // setup projection from parent osg::Matrix offsetProjection = osg::Matrix::inverse(_view->getCamera()->getProjectionMatrix()) * projection; _view->addSlave(camera.get(), offsetProjection, view); #if 0 std::cout << "Matrix Projection " << projection << std::endl; std::cout << "Matrix Projection master " << _view->getCamera()->getProjectionMatrix() << std::endl; // will work only if it's a post multyply in the producer camera std::cout << "Matrix View " << view << std::endl; std::cout << _view->getCamera()->getProjectionMatrix() * offsetProjection << std::endl; #endif } else { OSG_INFO<<" GraphicsWindow has not been created successfully."<<std::endl; return 0; } } // std::cout << "done" << std::endl; return _view.release(); } // // OSG interface to read/write from/to a file. // class ReaderWriterProducerCFG : public osgDB::ReaderWriter { public: ReaderWriterProducerCFG() { supportsExtension("cfg","Producer camera configuration file"); } virtual const char* className() { return "Producer cfg object reader"; } virtual ReadResult readObject(const std::string& fileName, const Options* options = NULL) const { std::string ext = osgDB::getLowerCaseFileExtension(fileName); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; osgDB::FilePathList* filePathList = 0; if(options) { filePathList = const_cast<osgDB::FilePathList*>(&(options->getDatabasePathList())); filePathList->push_back(DATADIR); } std::string path = osgDB::findDataFile(fileName); if(path.empty()) return ReadResult::FILE_NOT_FOUND; ReadResult result; osg::ref_ptr<osg::View> view = load(path, options); if(! view.valid()) result = ReadResult("Error: could not load " + path); else result = ReadResult(view.get()); if(options && filePathList) filePathList->pop_back(); return result; } }; REGISTER_OSGPLUGIN(cfg, ReaderWriterProducerCFG) <commit_msg>Changed the handling of single window configurations so that simply reuse the View::getCamera() instead of creating a slave.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 2007 Cedric Pinson * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commercial and non commercial * applications, as long as this copyright notice is maintained. * * This application 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. * * Authors: * Cedric Pinson <mornifle@plopbyte.net> * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef DATADIR #define DATADIR "." #endif // DATADIR #include <osg/GraphicsContext> #include "RenderSurface.h" #include "CameraConfig.h" #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osg/io_utils> using namespace osgProducer; static osg::GraphicsContext::Traits* buildTrait(RenderSurface& rs) { VisualChooser& vc = *rs.getVisualChooser(); osg::GraphicsContext::Traits* traits = new osg::GraphicsContext::Traits; for (std::vector<VisualChooser::VisualAttribute>::iterator it = vc._visual_attributes.begin(); it != vc._visual_attributes.end(); it++) { switch(it->_attribute) { case(VisualChooser::UseGL): break; // on by default in osgViewer case(VisualChooser::BufferSize): break; // no present mapping case(VisualChooser::Level): traits->level = it->_parameter; break; case(VisualChooser::RGBA): break; // automatically set in osgViewer case(VisualChooser::DoubleBuffer): traits->doubleBuffer = true; break; case(VisualChooser::Stereo): traits->quadBufferStereo = true; break; case(VisualChooser::AuxBuffers): break; // no present mapping case(VisualChooser::RedSize): traits->red = it->_parameter; break; case(VisualChooser::GreenSize): traits->green = it->_parameter; break; case(VisualChooser::BlueSize): traits->blue = it->_parameter; break; case(VisualChooser::AlphaSize): traits->alpha = it->_parameter; break; case(VisualChooser::DepthSize): traits->depth = it->_parameter; break; case(VisualChooser::StencilSize): traits->stencil = it->_parameter; break; case(VisualChooser::AccumRedSize): break; // no present mapping case(VisualChooser::AccumGreenSize): break; // no present mapping case(VisualChooser::AccumBlueSize): break; // no present mapping case(VisualChooser::AccumAlphaSize): break; // no present mapping case(VisualChooser::Samples): traits->samples = it->_parameter; break; case(VisualChooser::SampleBuffers): traits->sampleBuffers = 1; break; } } OSG_INFO<<"ReaderWriterCFG buildTrait traits->depth="<<traits->depth<<std::endl; OSG_INFO<<"ReaderWriterCFG buildTrait traits->samples="<<traits->samples<<std::endl; OSG_INFO<<"ReaderWriterCFG buildTrait traits->sampleBuffers="<<traits->sampleBuffers<<std::endl; traits->hostName = rs.getHostName(); traits->displayNum = rs.getDisplayNum(); traits->screenNum = rs.getScreenNum(); traits->windowName = rs.getWindowName(); traits->x = rs.getWindowOriginX(); traits->y = rs.getWindowOriginY(); traits->width = rs.getWindowWidth(); traits->height = rs.getWindowHeight(); traits->windowDecoration = rs.usesBorder(); traits->sharedContext = 0; traits->pbuffer = (rs.getDrawableType()==osgProducer::RenderSurface::DrawableType_PBuffer); traits->overrideRedirect = rs.usesOverrideRedirect(); return traits; } static osgViewer::View* load(const std::string& file, const osgDB::ReaderWriter::Options* option) { osg::ref_ptr<CameraConfig> config = new CameraConfig; //std::cout << "Parse file " << file << std::endl; config->parseFile(file); RenderSurface* rs = 0; Camera* cm = 0; std::map<RenderSurface*,osg::ref_ptr<osg::GraphicsContext> > surfaces; osg::ref_ptr<osgViewer::View> _view = new osgViewer::View; if (config->getNumberOfCameras()==1) { cm = config->getCamera(0); rs = cm->getRenderSurface(); if (rs->getDrawableType() != osgProducer::RenderSurface::DrawableType_Window) return 0; osg::ref_ptr<const osg::GraphicsContext::Traits> traits; osg::ref_ptr<osg::GraphicsContext> gc; if (surfaces.find(rs) != surfaces.end()) { gc = surfaces[rs]; traits = gc.valid() ? gc->getTraits() : 0; } else { osg::GraphicsContext::Traits* newtraits = buildTrait(*rs); #if 0 osg::GraphicsContext::ScreenIdentifier si; si.readDISPLAY(); if (si.displayNum>=0) newtraits->displayNum = si.displayNum; if (si.screenNum>=0) newtraits->screenNum = si.screenNum; #endif gc = osg::GraphicsContext::createGraphicsContext(newtraits); surfaces[rs] = gc.get(); traits = gc.valid() ? gc->getTraits() : 0; } // std::cout << rs->getWindowName() << " " << rs->getWindowOriginX() << " " << rs->getWindowOriginY() << " " << rs->getWindowWidth() << " " << rs->getWindowHeight() << std::endl; if (gc.valid()) { OSG_INFO<<" GraphicsWindow has been created successfully."<<std::endl; osg::ref_ptr<osg::Camera> camera = _view->getCamera(); camera->setGraphicsContext(gc.get()); int x,y; unsigned int width,height; cm->applyLens(); cm->getProjectionRectangle(x, y, width, height); camera->setViewport(new osg::Viewport(x, y, width, height)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); camera->setProjectionMatrix(osg::Matrixd(cm->getProjectionMatrix())); camera->setViewMatrix(osg::Matrixd(cm->getPositionAndAttitudeMatrix())); #if 0 std::cout << "Matrix Projection " << projection << std::endl; std::cout << "Matrix Projection master " << _view->getCamera()->getProjectionMatrix() << std::endl; // will work only if it's a post multyply in the producer camera std::cout << "Matrix View " << view << std::endl; std::cout << _view->getCamera()->getProjectionMatrix() * offsetProjection << std::endl; #endif } else { OSG_INFO<<" GraphicsWindow has not been created successfully."<<std::endl; return 0; } } else { for (int i = 0; i < (int)config->getNumberOfCameras(); i++) { cm = config->getCamera(i); rs = cm->getRenderSurface(); if (rs->getDrawableType() != osgProducer::RenderSurface::DrawableType_Window) continue; osg::ref_ptr<const osg::GraphicsContext::Traits> traits; osg::ref_ptr<osg::GraphicsContext> gc; if (surfaces.find(rs) != surfaces.end()) { gc = surfaces[rs]; traits = gc.valid() ? gc->getTraits() : 0; } else { osg::GraphicsContext::Traits* newtraits = buildTrait(*rs); #if 0 osg::GraphicsContext::ScreenIdentifier si; si.readDISPLAY(); if (si.displayNum>=0) newtraits->displayNum = si.displayNum; if (si.screenNum>=0) newtraits->screenNum = si.screenNum; #endif gc = osg::GraphicsContext::createGraphicsContext(newtraits); surfaces[rs] = gc.get(); traits = gc.valid() ? gc->getTraits() : 0; } // std::cout << rs->getWindowName() << " " << rs->getWindowOriginX() << " " << rs->getWindowOriginY() << " " << rs->getWindowWidth() << " " << rs->getWindowHeight() << std::endl; if (gc.valid()) { OSG_INFO<<" GraphicsWindow has been created successfully."<<std::endl; osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setGraphicsContext(gc.get()); int x,y; unsigned int width,height; cm->applyLens(); cm->getProjectionRectangle(x, y, width, height); camera->setViewport(new osg::Viewport(x, y, width, height)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); osg::Matrix projection(cm->getProjectionMatrix()); osg::Matrix offset = osg::Matrix::identity(); cm->setViewByMatrix(offset); osg::Matrix view = osg::Matrix(cm->getPositionAndAttitudeMatrix()); // setup projection from parent osg::Matrix offsetProjection = osg::Matrix::inverse(_view->getCamera()->getProjectionMatrix()) * projection; _view->addSlave(camera.get(), offsetProjection, view); #if 0 std::cout << "Matrix Projection " << projection << std::endl; std::cout << "Matrix Projection master " << _view->getCamera()->getProjectionMatrix() << std::endl; // will work only if it's a post multyply in the producer camera std::cout << "Matrix View " << view << std::endl; std::cout << _view->getCamera()->getProjectionMatrix() * offsetProjection << std::endl; #endif } else { OSG_INFO<<" GraphicsWindow has not been created successfully."<<std::endl; return 0; } } } // std::cout << "done" << std::endl; return _view.release(); } // // OSG interface to read/write from/to a file. // class ReaderWriterProducerCFG : public osgDB::ReaderWriter { public: ReaderWriterProducerCFG() { supportsExtension("cfg","Producer camera configuration file"); } virtual const char* className() { return "Producer cfg object reader"; } virtual ReadResult readObject(const std::string& fileName, const Options* options = NULL) const { std::string ext = osgDB::getLowerCaseFileExtension(fileName); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; osgDB::FilePathList* filePathList = 0; if(options) { filePathList = const_cast<osgDB::FilePathList*>(&(options->getDatabasePathList())); filePathList->push_back(DATADIR); } std::string path = osgDB::findDataFile(fileName); if(path.empty()) return ReadResult::FILE_NOT_FOUND; ReadResult result; osg::ref_ptr<osg::View> view = load(path, options); if(! view.valid()) result = ReadResult("Error: could not load " + path); else result = ReadResult(view.get()); if(options && filePathList) filePathList->pop_back(); return result; } }; REGISTER_OSGPLUGIN(cfg, ReaderWriterProducerCFG) <|endoftext|>
<commit_before><commit_msg>Nothing much<commit_after><|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2016 * * * * 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 <openspace/performance/performancemanager.h> #include <openspace/scene/scenegraphnode.h> #include <openspace/performance/performancelayout.h> #include <ghoul/logging/logmanager.h> #include <ghoul/misc/sharedmemory.h> #include <ghoul/misc/onscopeexit.h> namespace { const std::string _loggerCat = "PerformanceManager"; const std::string GlobalSharedMemoryName = "OpenSpacePerformanceMeasurementData"; // Probably 255 performance blocks per node are enough, so we can get away with // 4 bytes (one uint8_t for the number, one uint8_t for the reference count to keep // the global memory alive, and 2 bytes to enforce alignment) const size_t GlobalSharedMemorySize = 4; const int MaximumNumber = 256; struct GlobalMemory { uint8_t number; uint8_t referenceCount; std::array<uint8_t, 2> alignment; }; const std::string LocalSharedMemoryNameBase = "PerformanceMeasurement_"; } namespace openspace { namespace performance { // The Performance Manager will use a level of indirection in order to support multiple // PerformanceManagers running in parallel: // The ghoul::SharedData block addressed by OpenSpacePerformanceMeasurementSharedData // will only get allocated once and contains the total number of allocated shared memory // blocks alongside a list of names of these blocks // void PerformanceManager::createGlobalSharedMemory() { static_assert( sizeof(GlobalMemory) == GlobalSharedMemorySize, "The global memory struct does not fit the allocated global memory space" ); using ghoul::SharedMemory; if (SharedMemory::exists(GlobalSharedMemoryName)) { SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); ++(m->referenceCount); LINFO( "Using global shared memory block for performance measurements. " "Reference count: " << int(m->referenceCount) ); sharedMemory.releaseLock(); } else { LINFO("Creating global shared memory block for performance measurements"); SharedMemory::create(GlobalSharedMemoryName, GlobalSharedMemorySize); // Initialize the data SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); new (sharedMemory.memory()) GlobalMemory; GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); m->number = 0; m->referenceCount = 1; sharedMemory.releaseLock(); } } void PerformanceManager::destroyGlobalSharedMemory() { using ghoul::SharedMemory; if (!SharedMemory::exists(GlobalSharedMemoryName)) { LWARNING("Global shared memory for Performance measurements did not exist"); return; } SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); --(m->referenceCount); LINFO("Global shared performance memory reference count: " << int(m->referenceCount)); if (m->referenceCount == 0) { LINFO("Removing global shared performance memory"); // When the global memory is deleted, we have to get rid of all local memory as // well. In principle, none should be left, but OpenSpace crashing might leave // some of the memory orphaned for (int i = 0; i < std::numeric_limits<uint8_t>::max(); ++i) { std::string localName = LocalSharedMemoryNameBase + std::to_string(i); if (SharedMemory::exists(localName)) { LINFO("Removing shared memory: " << localName); SharedMemory::remove(localName); } } SharedMemory::remove(GlobalSharedMemoryName); } sharedMemory.releaseLock(); } PerformanceManager::PerformanceManager() : _performanceMemory(nullptr) { using ghoul::SharedMemory; PerformanceManager::createGlobalSharedMemory(); SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); OnExit([&](){sharedMemory.releaseLock();}); GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); // The the first free block (which also coincides with the number of blocks uint8_t blockIndex = m->number; ++(m->number); std::string localName = LocalSharedMemoryNameBase + std::to_string(blockIndex); // Compute the total size const int totalSize = sizeof(PerformanceLayout); LINFO("Create shared memory '" + localName + "' of " << totalSize << " bytes"); if (SharedMemory::exists(localName)) { throw ghoul::RuntimeError( "Shared Memory '" + localName + "' block already existed" ); } ghoul::SharedMemory::create(localName, totalSize); _performanceMemory = std::make_unique<ghoul::SharedMemory>(localName); // Using the placement-new to create a PerformanceLayout in the shared memory new (_performanceMemory->memory()) PerformanceLayout; } PerformanceManager::~PerformanceManager() { if (_performanceMemory) { ghoul::SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); --(m->number); sharedMemory.releaseLock(); LINFO("Remove shared memory '" << _performanceMemory->name() << "'"); ghoul::SharedMemory::remove(_performanceMemory->name()); } PerformanceManager::destroyGlobalSharedMemory(); } void PerformanceManager::resetPerformanceMeasurements() { // Using the placement-new to create a PerformanceLayout in the shared memory _performanceMemory->acquireLock(); void* ptr = _performanceMemory->memory(); new (ptr) PerformanceLayout; _performanceMemory->releaseLock(); individualPerformanceLocations.clear(); } bool PerformanceManager::isMeasuringPerformance() const { return _doPerformanceMeasurements; } PerformanceLayout* PerformanceManager::performanceData() { void* ptr = _performanceMemory->memory(); return reinterpret_cast<PerformanceLayout*>(ptr); } void PerformanceManager::storeIndividualPerformanceMeasurement (std::string identifier, long long microseconds) { PerformanceLayout* layout = performanceData(); _performanceMemory->acquireLock(); auto it = individualPerformanceLocations.find(identifier); PerformanceLayout::FunctionPerformanceLayout* p = nullptr; if (it == individualPerformanceLocations.end()) { p = &(layout->functionEntries[layout->nFunctionEntries]); individualPerformanceLocations[identifier] = layout->nFunctionEntries; ++(layout->nFunctionEntries); } else { p = &(layout->functionEntries[it->second]); } #ifdef _MSC_VER strcpy_s(p->name, identifier.length() + 1, identifier.c_str()); #else strcpy(p->name, identifier.c_str()); #endif std::rotate( std::begin(p->time), std::next(std::begin(p->time)), std::end(p->time) ); p->time[PerformanceLayout::NumberValues - 1] = static_cast<float>(microseconds); _performanceMemory->releaseLock(); } void PerformanceManager::storeScenePerformanceMeasurements( const std::vector<SceneGraphNode*>& sceneNodes) { using namespace performance; PerformanceLayout* layout = performanceData(); _performanceMemory->acquireLock(); int nNodes = static_cast<int>(sceneNodes.size()); layout->nScaleGraphEntries = nNodes; for (int i = 0; i < nNodes; ++i) { SceneGraphNode* node = sceneNodes[i]; memset(layout->sceneGraphEntries[i].name, 0, PerformanceLayout::LengthName); #ifdef _MSC_VER strcpy_s(layout->sceneGraphEntries[i].name, node->name().length() + 1, node->name().c_str()); #else strcpy(layout->sceneGraphEntries[i].name, node->name().c_str()); #endif SceneGraphNode::PerformanceRecord r = node->performanceRecord(); PerformanceLayout::SceneGraphPerformanceLayout& entry = layout->sceneGraphEntries[i]; std::rotate( std::begin(entry.renderTime), std::next(std::begin(entry.renderTime)), std::end(entry.renderTime) ); entry.renderTime[PerformanceLayout::NumberValues - 1] = r.renderTime / 1000.f; std::rotate( std::begin(entry.updateEphemeris), std::next(std::begin(entry.updateEphemeris)), std::end(entry.updateEphemeris) ); entry.updateEphemeris[PerformanceLayout::NumberValues - 1] = r.updateTimeEphemeris / 1000.f; std::rotate( std::begin(entry.updateRenderable), std::next(std::begin(entry.updateRenderable)), std::end(entry.updateRenderable) ); entry.updateRenderable[PerformanceLayout::NumberValues - 1] = r.updateTimeRenderable / 1000.f; } _performanceMemory->releaseLock(); } } // namespace performance } // namespace openspace <commit_msg>Making PerformanceMeasurement not crash when memory is deallocated<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2016 * * * * 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 <openspace/performance/performancemanager.h> #include <openspace/scene/scenegraphnode.h> #include <openspace/performance/performancelayout.h> #include <ghoul/logging/logmanager.h> #include <ghoul/misc/sharedmemory.h> #include <ghoul/misc/onscopeexit.h> namespace { const std::string _loggerCat = "PerformanceManager"; const std::string GlobalSharedMemoryName = "OpenSpacePerformanceMeasurementData"; // Probably 255 performance blocks per node are enough, so we can get away with // 4 bytes (one uint8_t for the number, one uint8_t for the reference count to keep // the global memory alive, and 2 bytes to enforce alignment) const size_t GlobalSharedMemorySize = 4; const int MaximumNumber = 256; struct GlobalMemory { uint8_t number; uint8_t referenceCount; std::array<uint8_t, 2> alignment; }; const std::string LocalSharedMemoryNameBase = "PerformanceMeasurement_"; } namespace openspace { namespace performance { // The Performance Manager will use a level of indirection in order to support multiple // PerformanceManagers running in parallel: // The ghoul::SharedData block addressed by OpenSpacePerformanceMeasurementSharedData // will only get allocated once and contains the total number of allocated shared memory // blocks alongside a list of names of these blocks // void PerformanceManager::createGlobalSharedMemory() { static_assert( sizeof(GlobalMemory) == GlobalSharedMemorySize, "The global memory struct does not fit the allocated global memory space" ); using ghoul::SharedMemory; if (SharedMemory::exists(GlobalSharedMemoryName)) { SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); ++(m->referenceCount); LINFO( "Using global shared memory block for performance measurements. " "Reference count: " << int(m->referenceCount) ); sharedMemory.releaseLock(); } else { LINFO("Creating global shared memory block for performance measurements"); SharedMemory::create(GlobalSharedMemoryName, GlobalSharedMemorySize); // Initialize the data SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); new (sharedMemory.memory()) GlobalMemory; GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); m->number = 0; m->referenceCount = 1; sharedMemory.releaseLock(); } } void PerformanceManager::destroyGlobalSharedMemory() { using ghoul::SharedMemory; if (!SharedMemory::exists(GlobalSharedMemoryName)) { LWARNING("Global shared memory for Performance measurements did not exist"); return; } SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); --(m->referenceCount); LINFO("Global shared performance memory reference count: " << int(m->referenceCount)); if (m->referenceCount == 0) { LINFO("Removing global shared performance memory"); // When the global memory is deleted, we have to get rid of all local memory as // well. In principle, none should be left, but OpenSpace crashing might leave // some of the memory orphaned for (int i = 0; i < std::numeric_limits<uint8_t>::max(); ++i) { std::string localName = LocalSharedMemoryNameBase + std::to_string(i); if (SharedMemory::exists(localName)) { LINFO("Removing shared memory: " << localName); SharedMemory::remove(localName); } } SharedMemory::remove(GlobalSharedMemoryName); } sharedMemory.releaseLock(); } PerformanceManager::PerformanceManager() : _performanceMemory(nullptr) { using ghoul::SharedMemory; PerformanceManager::createGlobalSharedMemory(); SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); OnExit([&](){sharedMemory.releaseLock();}); GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); // The the first free block (which also coincides with the number of blocks uint8_t blockIndex = m->number; ++(m->number); std::string localName = LocalSharedMemoryNameBase + std::to_string(blockIndex); // Compute the total size const int totalSize = sizeof(PerformanceLayout); LINFO("Create shared memory '" + localName + "' of " << totalSize << " bytes"); if (SharedMemory::exists(localName)) { throw ghoul::RuntimeError( "Shared Memory '" + localName + "' block already existed" ); } ghoul::SharedMemory::create(localName, totalSize); _performanceMemory = std::make_unique<ghoul::SharedMemory>(localName); // Using the placement-new to create a PerformanceLayout in the shared memory new (_performanceMemory->memory()) PerformanceLayout; } PerformanceManager::~PerformanceManager() { if (_performanceMemory) { ghoul::SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); GlobalMemory* m = reinterpret_cast<GlobalMemory*>(sharedMemory.memory()); --(m->number); sharedMemory.releaseLock(); LINFO("Remove shared memory '" << _performanceMemory->name() << "'"); ghoul::SharedMemory::remove(_performanceMemory->name()); _performanceMemory = nullptr; } PerformanceManager::destroyGlobalSharedMemory(); } void PerformanceManager::resetPerformanceMeasurements() { // Using the placement-new to create a PerformanceLayout in the shared memory _performanceMemory->acquireLock(); void* ptr = _performanceMemory->memory(); new (ptr) PerformanceLayout; _performanceMemory->releaseLock(); individualPerformanceLocations.clear(); } bool PerformanceManager::isMeasuringPerformance() const { return _doPerformanceMeasurements; } PerformanceLayout* PerformanceManager::performanceData() { void* ptr = _performanceMemory->memory(); return reinterpret_cast<PerformanceLayout*>(ptr); } void PerformanceManager::storeIndividualPerformanceMeasurement (std::string identifier, long long microseconds) { PerformanceLayout* layout = performanceData(); _performanceMemory->acquireLock(); auto it = individualPerformanceLocations.find(identifier); PerformanceLayout::FunctionPerformanceLayout* p = nullptr; if (it == individualPerformanceLocations.end()) { p = &(layout->functionEntries[layout->nFunctionEntries]); individualPerformanceLocations[identifier] = layout->nFunctionEntries; ++(layout->nFunctionEntries); } else { p = &(layout->functionEntries[it->second]); } #ifdef _MSC_VER strcpy_s(p->name, identifier.length() + 1, identifier.c_str()); #else strcpy(p->name, identifier.c_str()); #endif std::rotate( std::begin(p->time), std::next(std::begin(p->time)), std::end(p->time) ); p->time[PerformanceLayout::NumberValues - 1] = static_cast<float>(microseconds); _performanceMemory->releaseLock(); } void PerformanceManager::storeScenePerformanceMeasurements( const std::vector<SceneGraphNode*>& sceneNodes) { using namespace performance; PerformanceLayout* layout = performanceData(); _performanceMemory->acquireLock(); int nNodes = static_cast<int>(sceneNodes.size()); layout->nScaleGraphEntries = nNodes; for (int i = 0; i < nNodes; ++i) { SceneGraphNode* node = sceneNodes[i]; memset(layout->sceneGraphEntries[i].name, 0, PerformanceLayout::LengthName); #ifdef _MSC_VER strcpy_s(layout->sceneGraphEntries[i].name, node->name().length() + 1, node->name().c_str()); #else strcpy(layout->sceneGraphEntries[i].name, node->name().c_str()); #endif SceneGraphNode::PerformanceRecord r = node->performanceRecord(); PerformanceLayout::SceneGraphPerformanceLayout& entry = layout->sceneGraphEntries[i]; std::rotate( std::begin(entry.renderTime), std::next(std::begin(entry.renderTime)), std::end(entry.renderTime) ); entry.renderTime[PerformanceLayout::NumberValues - 1] = r.renderTime / 1000.f; std::rotate( std::begin(entry.updateEphemeris), std::next(std::begin(entry.updateEphemeris)), std::end(entry.updateEphemeris) ); entry.updateEphemeris[PerformanceLayout::NumberValues - 1] = r.updateTimeEphemeris / 1000.f; std::rotate( std::begin(entry.updateRenderable), std::next(std::begin(entry.updateRenderable)), std::end(entry.updateRenderable) ); entry.updateRenderable[PerformanceLayout::NumberValues - 1] = r.updateTimeRenderable / 1000.f; } _performanceMemory->releaseLock(); } } // namespace performance } // namespace openspace <|endoftext|>
<commit_before>#include "aio_private.h" #define AIO_DEPTH 128 void aio_callback(io_context_t ctx, struct iocb* iocb, struct io_callback_s *cb, long res, long res2) { thread_callback_s *tcb = (thread_callback_s *) cb; memcpy(cb->buf, ((char *) iocb->u.c.buf) + (cb->offset - ROUND_PAGE(cb->offset)), cb->size); // if(*(unsigned long *) cb->buf != cb->offset / sizeof(long)) // printf("%ld %ld\n", *(unsigned long *) cb->buf, cb->offset / sizeof(long)); // assert(*(unsigned long *) cb->buf == cb->offset / sizeof(long)); tcb->thread->return_cb(tcb); tcb->thread->read_bytes += cb->size; } void aio_callback1(io_context_t ctx, struct iocb* iocb, struct io_callback_s *cb, long res, long res2) { thread_callback_s *tcb = (thread_callback_s *) cb; memcpy(cb->buf, ((char *) iocb->u.c.buf) + (cb->offset - ROUND_PAGE(cb->offset)), cb->size); // if(*(unsigned long *) cb->buf != cb->offset / sizeof(long)) // printf("%ld %ld\n", *(unsigned long *) cb->buf, cb->offset / sizeof(long)); // assert(*(unsigned long *) cb->buf == cb->offset / sizeof(long)); tcb->thread->return_cb1(tcb); tcb->thread->read_bytes += cb->size; } aio_private::aio_private(const char *names[], int num, long size, int idx, int entry_size): read_private(names, num, size, idx, entry_size, O_DIRECT | O_RDWR) { printf("aio is used\n"); pages = (char *) valloc(PAGE_SIZE * 4096); buf_idx = 0; ctx = create_aio_ctx(AIO_DEPTH); for (int i = 0; i < AIO_DEPTH * 5; i++) { cbs.push_back(new thread_callback_s()); } reqs_array = new std::deque<io_request>[this->num_open_files()]; } aio_private::~aio_private() { int slot = max_io_slot(ctx); while (slot < AIO_DEPTH) { io_wait(ctx, NULL); slot = max_io_slot(ctx); } } struct iocb *aio_private::construct_req(char *buf, off_t offset, ssize_t size, int access_method, callback_t cb_func) { struct iocb *req; if (cbs.empty()) { fprintf(stderr, "no callback object left\n"); return NULL; } thread_callback_s *tcb = cbs.front(); io_callback_s *cb = (io_callback_s *) tcb; cbs.pop_front(); cb->buf = buf; cb->offset = offset; cb->size = size; cb->func = cb_func; tcb->thread = this; /* for simplicity, I assume all request sizes are smaller than a page size */ assert(size <= PAGE_SIZE); if (ROUND_PAGE(offset) == offset && (long) buf == ROUND_PAGE(buf) && size == PAGE_SIZE) { req = make_io_request(ctx, get_fd(offset), PAGE_SIZE, offset, buf, A_READ, cb); } else { buf_idx++; if (buf_idx == 4096) buf_idx = 0; char *page = pages + buf_idx * PAGE_SIZE; req = make_io_request(ctx, get_fd(offset), PAGE_SIZE, ROUND_PAGE(offset), page, A_READ, cb); } return req; } ssize_t aio_private::access(char *buf, off_t offset, ssize_t size, int access_method) { struct iocb *req; int slot = max_io_slot(ctx); assert(access_method == READ); if (slot == 0) { io_wait(ctx, NULL); } req = construct_req(buf, offset, size, access_method, aio_callback); submit_io_request(ctx, &req, 1); return 0; } void aio_private::buffer_reqs(io_request *requests, int num) { for (int i = 0; i < num; i++) { int fd_idx = get_fd_idx(requests->get_offset()); reqs_array[fd_idx].push_back(*requests); requests++; } } ssize_t aio_private::process_reqs(io_request *requests, int num) { ssize_t ret = 0; while (num > 0) { int slot = max_io_slot(ctx); if (slot == 0) { io_wait(ctx, NULL, 10); slot = max_io_slot(ctx); } struct iocb *reqs[slot]; int min = slot > num ? num : slot; for (int i = 0; i < min; i++) { reqs[i] = construct_req(requests->get_buf(), requests->get_offset(), requests->get_size(), requests->get_access_method(), aio_callback1); requests++; ret += requests->get_size(); } submit_io_request(ctx, reqs, min); num -= min; min = min / 2; if (min == 0) min = 1; } return ret; } const int MAX_REQ_SIZE = 128; /** * Random workload may cause some load imbalance at some particular moments * when the requests are distributed to multiple files. * If there is only one file to read, simply submit requests with AIO. * Otherwise, before submitting requests to AIO, I need to rebalance them first. * The way to rebalance requests is to have a queue for each file, and buffer * all requests in queues according to the files where they are submitted to. * Fetch requests from queues in a round-robin fashion, so it's guaranteed that * all requests will be distributed to files evenly. * * If num is 0, the invocation processes up to num_open_files() reuqests. * This is good, so the number of requests in each queue won't be extremely * large if the distribution is highly skewed. */ ssize_t aio_private::access(io_request *requests, int num, int access_method) { if (num_open_files() == 1) return process_reqs(requests, num); ssize_t ret = 0; int one_empty = false; buffer_reqs(requests, num); io_request req_buf[MAX_REQ_SIZE]; int req_buf_size = 0; /* if a request queue for a file is empty, stop processing. */ while (!one_empty) { for (int i = 0; i < num_open_files(); i++) { if (reqs_array[i].empty()) { one_empty = true; continue; } req_buf[req_buf_size++] = reqs_array[i].front(); reqs_array[i].pop_front(); /* * if the temporary request buffer is full, * process all requests. */ if (req_buf_size == MAX_REQ_SIZE) { ret += process_reqs(req_buf, req_buf_size); req_buf_size = 0; } } } /* process the remaining requests in the buffer. */ if (req_buf_size > 0) ret += process_reqs(req_buf, req_buf_size); return ret; } /* process remaining requests in the queues. */ void aio_private::cleanup() { read_private::cleanup(); for (int i = 0; i < num_open_files(); i++) { for (unsigned int j = 0; j < reqs_array[i].size(); j++) { io_request req = reqs_array[i][j]; access(req.get_buf(), req.get_offset(), req.get_size(), req.get_access_method()); } } } <commit_msg>fix minor bugs in aio_private.<commit_after>#include "aio_private.h" #define AIO_DEPTH 128 void aio_callback(io_context_t ctx, struct iocb* iocb, struct io_callback_s *cb, long res, long res2) { thread_callback_s *tcb = (thread_callback_s *) cb; memcpy(cb->buf, ((char *) iocb->u.c.buf) + (cb->offset - ROUND_PAGE(cb->offset)), cb->size); // if(*(unsigned long *) cb->buf != cb->offset / sizeof(long)) // printf("%ld %ld\n", *(unsigned long *) cb->buf, cb->offset / sizeof(long)); // assert(*(unsigned long *) cb->buf == cb->offset / sizeof(long)); tcb->thread->return_cb(tcb); tcb->thread->read_bytes += cb->size; } void aio_callback1(io_context_t ctx, struct iocb* iocb, struct io_callback_s *cb, long res, long res2) { thread_callback_s *tcb = (thread_callback_s *) cb; memcpy(cb->buf, ((char *) iocb->u.c.buf) + (cb->offset - ROUND_PAGE(cb->offset)), cb->size); // if(*(unsigned long *) cb->buf != cb->offset / sizeof(long)) // printf("%ld %ld\n", *(unsigned long *) cb->buf, cb->offset / sizeof(long)); // assert(*(unsigned long *) cb->buf == cb->offset / sizeof(long)); tcb->thread->return_cb1(tcb); tcb->thread->read_bytes += cb->size; } aio_private::aio_private(const char *names[], int num, long size, int idx, int entry_size): read_private(names, num, size, idx, entry_size, O_DIRECT | O_RDWR) { printf("aio is used\n"); pages = (char *) valloc(PAGE_SIZE * 4096); buf_idx = 0; ctx = create_aio_ctx(AIO_DEPTH); for (int i = 0; i < AIO_DEPTH * 5; i++) { cbs.push_back(new thread_callback_s()); } reqs_array = new std::deque<io_request>[this->num_open_files()]; } aio_private::~aio_private() { int slot = max_io_slot(ctx); while (slot < AIO_DEPTH) { io_wait(ctx, NULL); slot = max_io_slot(ctx); } delete [] reqs_array; } struct iocb *aio_private::construct_req(char *buf, off_t offset, ssize_t size, int access_method, callback_t cb_func) { struct iocb *req; if (cbs.empty()) { fprintf(stderr, "no callback object left\n"); return NULL; } thread_callback_s *tcb = cbs.front(); io_callback_s *cb = (io_callback_s *) tcb; cbs.pop_front(); cb->buf = buf; cb->offset = offset; cb->size = size; cb->func = cb_func; tcb->thread = this; /* for simplicity, I assume all request sizes are smaller than a page size */ assert(size <= PAGE_SIZE); if (ROUND_PAGE(offset) == offset && (long) buf == ROUND_PAGE(buf) && size == PAGE_SIZE) { req = make_io_request(ctx, get_fd(offset), PAGE_SIZE, offset, buf, A_READ, cb); } else { buf_idx++; if (buf_idx == 4096) buf_idx = 0; char *page = pages + buf_idx * PAGE_SIZE; req = make_io_request(ctx, get_fd(offset), PAGE_SIZE, ROUND_PAGE(offset), page, A_READ, cb); } return req; } ssize_t aio_private::access(char *buf, off_t offset, ssize_t size, int access_method) { struct iocb *req; int slot = max_io_slot(ctx); assert(access_method == READ); if (slot == 0) { io_wait(ctx, NULL); } req = construct_req(buf, offset, size, access_method, aio_callback); submit_io_request(ctx, &req, 1); return 0; } void aio_private::buffer_reqs(io_request *requests, int num) { for (int i = 0; i < num; i++) { int fd_idx = get_fd_idx(requests->get_offset()); reqs_array[fd_idx].push_back(*requests); requests++; } } ssize_t aio_private::process_reqs(io_request *requests, int num) { ssize_t ret = 0; while (num > 0) { int slot = max_io_slot(ctx); if (slot == 0) { io_wait(ctx, NULL, 10); slot = max_io_slot(ctx); } struct iocb *reqs[slot]; int min = slot > num ? num : slot; for (int i = 0; i < min; i++) { reqs[i] = construct_req(requests->get_buf(), requests->get_offset(), requests->get_size(), requests->get_access_method(), aio_callback1); ret += requests->get_size(); requests++; } submit_io_request(ctx, reqs, min); num -= min; } return ret; } const int MAX_REQ_SIZE = 128; /** * Random workload may cause some load imbalance at some particular moments * when the requests are distributed to multiple files. * If there is only one file to read, simply submit requests with AIO. * Otherwise, before submitting requests to AIO, I need to rebalance them first. * The way to rebalance requests is to have a queue for each file, and buffer * all requests in queues according to the files where they are submitted to. * Fetch requests from queues in a round-robin fashion, so it's guaranteed that * all requests will be distributed to files evenly. * * If num is 0, the invocation processes up to num_open_files() reuqests. * This is good, so the number of requests in each queue won't be extremely * large if the distribution is highly skewed. */ ssize_t aio_private::access(io_request *requests, int num, int access_method) { if (num_open_files() == 1) return process_reqs(requests, num); ssize_t ret = 0; int one_empty = false; buffer_reqs(requests, num); io_request req_buf[MAX_REQ_SIZE]; int req_buf_size = 0; /* if a request queue for a file is empty, stop processing. */ while (!one_empty) { for (int i = 0; i < num_open_files(); i++) { if (reqs_array[i].empty()) { one_empty = true; continue; } req_buf[req_buf_size++] = reqs_array[i].front(); reqs_array[i].pop_front(); /* * if the temporary request buffer is full, * process all requests. */ if (req_buf_size == MAX_REQ_SIZE) { ret += process_reqs(req_buf, req_buf_size); req_buf_size = 0; } } } /* process the remaining requests in the buffer. */ if (req_buf_size > 0) ret += process_reqs(req_buf, req_buf_size); return ret; } /* process remaining requests in the queues. */ void aio_private::cleanup() { read_private::cleanup(); for (int i = 0; i < num_open_files(); i++) { for (unsigned int j = 0; j < reqs_array[i].size(); j++) { io_request req = reqs_array[i][j]; access(req.get_buf(), req.get_offset(), req.get_size(), req.get_access_method()); } } } <|endoftext|>
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/builtin.h" #include "bin/dartutils.h" #include "include/dart_api.h" namespace dart { namespace bin { void FUNCTION_NAME(SecureSocket_Init)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_Connect)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_Destroy)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_Handshake)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_RegisterHandshakeCompleteCallback)( Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_RegisterBadCertificateCallback)( Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_ProcessBuffer)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_InitializeLibrary) (Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_PeerCertificate) (Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_FilterPointer)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_NewServicePort)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } } // namespace bin } // namespace dart <commit_msg>Add dummy implementation of SecureSocket_Renegotiate to Android platform.<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/builtin.h" #include "bin/dartutils.h" #include "include/dart_api.h" namespace dart { namespace bin { void FUNCTION_NAME(SecureSocket_Init)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_Connect)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_Destroy)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_Handshake)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_RegisterHandshakeCompleteCallback)( Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_RegisterBadCertificateCallback)( Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_ProcessBuffer)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_InitializeLibrary) (Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_PeerCertificate) (Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_FilterPointer)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_Renegotiate)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } void FUNCTION_NAME(SecureSocket_NewServicePort)(Dart_NativeArguments args) { Dart_EnterScope(); Dart_ThrowException(DartUtils::NewDartArgumentError( "Secure Sockets unsupported on this platform")); Dart_ExitScope(); } } // namespace bin } // namespace dart <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/memory/allocation/legacy_allocator.h" #include <string> #include <vector> #include "glog/logging.h" #include "paddle/fluid/memory/detail/buddy_allocator.h" #include "paddle/fluid/memory/detail/system_allocator.h" #include "paddle/fluid/platform/gpu_info.h" #include "paddle/fluid/string/printf.h" #include "paddle/fluid/string/split.h" DEFINE_bool(init_allocated_mem, false, "It is a mistake that the values of the memory allocated by " "BuddyAllocator are always zeroed in some op's implementation. " "To find this error in time, we use init_allocated_mem to indicate " "that initializing the allocated memory with a small value " "during unit testing."); DECLARE_double(fraction_of_gpu_memory_to_use); namespace paddle { namespace memory { namespace legacy { template <typename Place> void *Alloc(const Place &place, size_t size); template <typename Place> void Free(const Place &place, void *p); template <typename Place> size_t Used(const Place &place); struct Usage : public boost::static_visitor<size_t> { size_t operator()(const platform::CPUPlace &cpu) const; size_t operator()(const platform::CUDAPlace &gpu) const; size_t operator()(const platform::CUDAPinnedPlace &cuda_pinned) const; }; size_t memory_usage(const platform::Place &p); using BuddyAllocator = detail::BuddyAllocator; BuddyAllocator *GetCPUBuddyAllocator() { // We tried thread_local for inference::RNN1 model, but that not works much // for multi-thread test. static std::once_flag init_flag; static detail::BuddyAllocator *a = nullptr; std::call_once(init_flag, []() { a = new detail::BuddyAllocator( std::unique_ptr<detail::SystemAllocator>(new detail::CPUAllocator), platform::CpuMinChunkSize(), platform::CpuMaxChunkSize()); }); return a; } // We compared the NaiveAllocator with BuddyAllocator in CPU memory allocation, // seems they are almost the same overhead. struct NaiveAllocator { void *Alloc(size_t size) { return malloc(size); } void Free(void *p) { PADDLE_ENFORCE(p); free(p); } static NaiveAllocator *Instance() { static NaiveAllocator x; return &x; } private: std::mutex lock_; }; template <> void *Alloc<platform::CPUPlace>(const platform::CPUPlace &place, size_t size) { VLOG(10) << "Allocate " << size << " bytes on " << platform::Place(place); void *p = GetCPUBuddyAllocator()->Alloc(size); if (FLAGS_init_allocated_mem) { memset(p, 0xEF, size); } VLOG(10) << " pointer=" << p; return p; } template <> void Free<platform::CPUPlace>(const platform::CPUPlace &place, void *p) { VLOG(10) << "Free pointer=" << p << " on " << platform::Place(place); GetCPUBuddyAllocator()->Free(p); } template <> size_t Used<platform::CPUPlace>(const platform::CPUPlace &place) { return GetCPUBuddyAllocator()->Used(); } #ifdef PADDLE_WITH_CUDA BuddyAllocator *GetGPUBuddyAllocator(int gpu_id) { static std::once_flag init_flag; static detail::BuddyAllocator **a_arr = nullptr; static std::vector<int> devices; std::call_once(init_flag, [gpu_id]() { devices = platform::GetSelectedDevices(); int gpu_num = devices.size(); a_arr = new BuddyAllocator *[gpu_num]; for (size_t i = 0; i < devices.size(); ++i) { int dev_id = devices[i]; a_arr[i] = nullptr; platform::SetDeviceId(dev_id); a_arr[i] = new BuddyAllocator(std::unique_ptr<detail::SystemAllocator>( new detail::GPUAllocator(dev_id)), platform::GpuMinChunkSize(), platform::GpuMaxChunkSize()); VLOG(10) << "\n\nNOTE: each GPU device use " << FLAGS_fraction_of_gpu_memory_to_use * 100 << "% of GPU memory.\n" << "You can set GFlags environment variable '" << "FLAGS_fraction_of_gpu_memory_to_use" << "' to change the fraction of GPU usage.\n\n"; } }); platform::SetDeviceId(gpu_id); auto pos = std::distance(devices.begin(), std::find(devices.begin(), devices.end(), gpu_id)); return a_arr[pos]; } #endif template <> size_t Used<platform::CUDAPlace>(const platform::CUDAPlace &place) { #ifdef PADDLE_WITH_CUDA return GetGPUBuddyAllocator(place.device)->Used(); #else PADDLE_THROW("'CUDAPlace' is not supported in CPU only device."); #endif } template <> void *Alloc<platform::CUDAPlace>(const platform::CUDAPlace &place, size_t size) { #ifdef PADDLE_WITH_CUDA auto *buddy_allocator = GetGPUBuddyAllocator(place.device); auto *ptr = buddy_allocator->Alloc(size); if (ptr == nullptr) { int cur_dev = platform::GetCurrentDeviceId(); platform::SetDeviceId(place.device); size_t avail, total; platform::GpuMemoryUsage(&avail, &total); LOG(WARNING) << "Cannot allocate " << string::HumanReadableSize(size) << " in GPU " << place.device << ", available " << string::HumanReadableSize(avail); LOG(WARNING) << "total " << total; LOG(WARNING) << "GpuMinChunkSize " << string::HumanReadableSize( buddy_allocator->GetMinChunkSize()); LOG(WARNING) << "GpuMaxChunkSize " << string::HumanReadableSize( buddy_allocator->GetMaxChunkSize()); LOG(WARNING) << "GPU memory used: " << string::HumanReadableSize(Used<platform::CUDAPlace>(place)); platform::SetDeviceId(cur_dev); } if (FLAGS_init_allocated_mem) { cudaMemset(ptr, 0xEF, size); } return ptr; #else PADDLE_THROW("'CUDAPlace' is not supported in CPU only device."); #endif } template <> void Free<platform::CUDAPlace>(const platform::CUDAPlace &place, void *p) { #ifdef PADDLE_WITH_CUDA GetGPUBuddyAllocator(place.device)->Free(p); #else PADDLE_THROW("'CUDAPlace' is not supported in CPU only device."); #endif } #ifdef PADDLE_WITH_CUDA BuddyAllocator *GetCUDAPinnedBuddyAllocator() { static std::once_flag init_flag; static BuddyAllocator *ba = nullptr; std::call_once(init_flag, []() { ba = new BuddyAllocator(std::unique_ptr<detail::SystemAllocator>( new detail::CUDAPinnedAllocator), platform::CUDAPinnedMinChunkSize(), platform::CUDAPinnedMaxChunkSize()); }); return ba; } #endif template <> size_t Used<platform::CUDAPinnedPlace>(const platform::CUDAPinnedPlace &place) { #ifdef PADDLE_WITH_CUDA return GetCUDAPinnedBuddyAllocator()->Used(); #else PADDLE_THROW("'CUDAPinnedPlace' is not supported in CPU only device."); #endif } template <> void *Alloc<platform::CUDAPinnedPlace>(const platform::CUDAPinnedPlace &place, size_t size) { #ifdef PADDLE_WITH_CUDA auto *buddy_allocator = GetCUDAPinnedBuddyAllocator(); void *ptr = buddy_allocator->Alloc(size); if (ptr == nullptr) { LOG(WARNING) << "cudaMallocHost Cannot allocate " << size << " bytes in CUDAPinnedPlace"; } if (FLAGS_init_allocated_mem) { memset(ptr, 0xEF, size); } return ptr; #else PADDLE_THROW("'CUDAPinnedPlace' is not supported in CPU only device."); #endif } template <> void Free<platform::CUDAPinnedPlace>(const platform::CUDAPinnedPlace &place, void *p) { #ifdef PADDLE_WITH_CUDA GetCUDAPinnedBuddyAllocator()->Free(p); #else PADDLE_THROW("'CUDAPinnedPlace' is not supported in CPU only device."); #endif } struct AllocVisitor : public boost::static_visitor<void *> { inline explicit AllocVisitor(size_t size) : size_(size) {} template <typename Place> inline void *operator()(const Place &place) const { return Alloc<Place>(place, size_); } private: size_t size_; }; struct FreeVisitor : public boost::static_visitor<void> { inline explicit FreeVisitor(void *ptr) : ptr_(ptr) {} template <typename Place> inline void operator()(const Place &place) const { Free<Place>(place, ptr_); } private: void *ptr_; }; size_t Usage::operator()(const platform::CPUPlace &cpu) const { return Used(cpu); } size_t Usage::operator()(const platform::CUDAPlace &gpu) const { #ifdef PADDLE_WITH_CUDA return Used(gpu); #else PADDLE_THROW("'CUDAPlace' is not supported in CPU only device."); #endif } size_t Usage::operator()(const platform::CUDAPinnedPlace &cuda_pinned) const { #ifdef PADDLE_WITH_CUDA return Used(cuda_pinned); #else PADDLE_THROW("'CUDAPinnedPlace' is not supported in CPU only device."); #endif } } // namespace legacy namespace allocation { Allocation *LegacyAllocator::AllocateImpl(size_t size, Allocator::Attr attr) { void *ptr = boost::apply_visitor(legacy::AllocVisitor(size), place_); return new Allocation(ptr, size, place_); } void LegacyAllocator::Free(Allocation *allocation) { boost::apply_visitor(legacy::FreeVisitor(allocation->ptr()), allocation->place()); delete allocation; } } // namespace allocation } // namespace memory } // namespace paddle <commit_msg>Use malloc and free in JeMalloc<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/memory/allocation/legacy_allocator.h" #include <string> #include <vector> #ifdef WITH_JEMALLOC #include <jemalloc/jemalloc.h> #endif #include "glog/logging.h" #include "paddle/fluid/memory/detail/buddy_allocator.h" #include "paddle/fluid/memory/detail/system_allocator.h" #include "paddle/fluid/platform/gpu_info.h" #include "paddle/fluid/string/printf.h" #include "paddle/fluid/string/split.h" DEFINE_bool(init_allocated_mem, false, "It is a mistake that the values of the memory allocated by " "BuddyAllocator are always zeroed in some op's implementation. " "To find this error in time, we use init_allocated_mem to indicate " "that initializing the allocated memory with a small value " "during unit testing."); DECLARE_double(fraction_of_gpu_memory_to_use); namespace paddle { namespace memory { namespace legacy { template <typename Place> void *Alloc(const Place &place, size_t size); template <typename Place> void Free(const Place &place, void *p); template <typename Place> size_t Used(const Place &place); struct Usage : public boost::static_visitor<size_t> { size_t operator()(const platform::CPUPlace &cpu) const; size_t operator()(const platform::CUDAPlace &gpu) const; size_t operator()(const platform::CUDAPinnedPlace &cuda_pinned) const; }; size_t memory_usage(const platform::Place &p); using BuddyAllocator = detail::BuddyAllocator; BuddyAllocator *GetCPUBuddyAllocator() { // We tried thread_local for inference::RNN1 model, but that not works much // for multi-thread test. static std::once_flag init_flag; static detail::BuddyAllocator *a = nullptr; std::call_once(init_flag, []() { a = new detail::BuddyAllocator( std::unique_ptr<detail::SystemAllocator>(new detail::CPUAllocator), platform::CpuMinChunkSize(), platform::CpuMaxChunkSize()); }); return a; } // We compared the NaiveAllocator with BuddyAllocator in CPU memory allocation, // seems they are almost the same overhead. struct NaiveAllocator { void *Alloc(size_t size) { return malloc(size); } void Free(void *p) { PADDLE_ENFORCE(p); free(p); } static NaiveAllocator *Instance() { static NaiveAllocator x; return &x; } private: std::mutex lock_; }; template <> void *Alloc<platform::CPUPlace>(const platform::CPUPlace &place, size_t size) { VLOG(10) << "Allocate " << size << " bytes on " << platform::Place(place); #ifdef WITH_JEMALLOC void *p = malloc(size); #else void *p = GetCPUBuddyAllocator()->Alloc(size); #endif if (FLAGS_init_allocated_mem) { memset(p, 0xEF, size); } VLOG(10) << " pointer=" << p; return p; } template <> void Free<platform::CPUPlace>(const platform::CPUPlace &place, void *p) { VLOG(10) << "Free pointer=" << p << " on " << platform::Place(place); #ifdef WITH_JEMALLOC free(p); #else GetCPUBuddyAllocator()->Free(p); #endif } template <> size_t Used<platform::CPUPlace>(const platform::CPUPlace &place) { #ifdef WITH_JEMALLOC // fake the result of used memory when WITH_JEMALLOC is ON return 0U; #else return GetCPUBuddyAllocator()->Used(); #endif } #ifdef PADDLE_WITH_CUDA BuddyAllocator *GetGPUBuddyAllocator(int gpu_id) { static std::once_flag init_flag; static detail::BuddyAllocator **a_arr = nullptr; static std::vector<int> devices; std::call_once(init_flag, [gpu_id]() { devices = platform::GetSelectedDevices(); int gpu_num = devices.size(); a_arr = new BuddyAllocator *[gpu_num]; for (size_t i = 0; i < devices.size(); ++i) { int dev_id = devices[i]; a_arr[i] = nullptr; platform::SetDeviceId(dev_id); a_arr[i] = new BuddyAllocator(std::unique_ptr<detail::SystemAllocator>( new detail::GPUAllocator(dev_id)), platform::GpuMinChunkSize(), platform::GpuMaxChunkSize()); VLOG(10) << "\n\nNOTE: each GPU device use " << FLAGS_fraction_of_gpu_memory_to_use * 100 << "% of GPU memory.\n" << "You can set GFlags environment variable '" << "FLAGS_fraction_of_gpu_memory_to_use" << "' to change the fraction of GPU usage.\n\n"; } }); platform::SetDeviceId(gpu_id); auto pos = std::distance(devices.begin(), std::find(devices.begin(), devices.end(), gpu_id)); return a_arr[pos]; } #endif template <> size_t Used<platform::CUDAPlace>(const platform::CUDAPlace &place) { #ifdef PADDLE_WITH_CUDA return GetGPUBuddyAllocator(place.device)->Used(); #else PADDLE_THROW("'CUDAPlace' is not supported in CPU only device."); #endif } template <> void *Alloc<platform::CUDAPlace>(const platform::CUDAPlace &place, size_t size) { #ifdef PADDLE_WITH_CUDA auto *buddy_allocator = GetGPUBuddyAllocator(place.device); auto *ptr = buddy_allocator->Alloc(size); if (ptr == nullptr) { int cur_dev = platform::GetCurrentDeviceId(); platform::SetDeviceId(place.device); size_t avail, total; platform::GpuMemoryUsage(&avail, &total); LOG(WARNING) << "Cannot allocate " << string::HumanReadableSize(size) << " in GPU " << place.device << ", available " << string::HumanReadableSize(avail); LOG(WARNING) << "total " << total; LOG(WARNING) << "GpuMinChunkSize " << string::HumanReadableSize( buddy_allocator->GetMinChunkSize()); LOG(WARNING) << "GpuMaxChunkSize " << string::HumanReadableSize( buddy_allocator->GetMaxChunkSize()); LOG(WARNING) << "GPU memory used: " << string::HumanReadableSize(Used<platform::CUDAPlace>(place)); platform::SetDeviceId(cur_dev); } if (FLAGS_init_allocated_mem) { cudaMemset(ptr, 0xEF, size); } return ptr; #else PADDLE_THROW("'CUDAPlace' is not supported in CPU only device."); #endif } template <> void Free<platform::CUDAPlace>(const platform::CUDAPlace &place, void *p) { #ifdef PADDLE_WITH_CUDA GetGPUBuddyAllocator(place.device)->Free(p); #else PADDLE_THROW("'CUDAPlace' is not supported in CPU only device."); #endif } #ifdef PADDLE_WITH_CUDA BuddyAllocator *GetCUDAPinnedBuddyAllocator() { static std::once_flag init_flag; static BuddyAllocator *ba = nullptr; std::call_once(init_flag, []() { ba = new BuddyAllocator(std::unique_ptr<detail::SystemAllocator>( new detail::CUDAPinnedAllocator), platform::CUDAPinnedMinChunkSize(), platform::CUDAPinnedMaxChunkSize()); }); return ba; } #endif template <> size_t Used<platform::CUDAPinnedPlace>(const platform::CUDAPinnedPlace &place) { #ifdef PADDLE_WITH_CUDA return GetCUDAPinnedBuddyAllocator()->Used(); #else PADDLE_THROW("'CUDAPinnedPlace' is not supported in CPU only device."); #endif } template <> void *Alloc<platform::CUDAPinnedPlace>(const platform::CUDAPinnedPlace &place, size_t size) { #ifdef PADDLE_WITH_CUDA auto *buddy_allocator = GetCUDAPinnedBuddyAllocator(); void *ptr = buddy_allocator->Alloc(size); if (ptr == nullptr) { LOG(WARNING) << "cudaMallocHost Cannot allocate " << size << " bytes in CUDAPinnedPlace"; } if (FLAGS_init_allocated_mem) { memset(ptr, 0xEF, size); } return ptr; #else PADDLE_THROW("'CUDAPinnedPlace' is not supported in CPU only device."); #endif } template <> void Free<platform::CUDAPinnedPlace>(const platform::CUDAPinnedPlace &place, void *p) { #ifdef PADDLE_WITH_CUDA GetCUDAPinnedBuddyAllocator()->Free(p); #else PADDLE_THROW("'CUDAPinnedPlace' is not supported in CPU only device."); #endif } struct AllocVisitor : public boost::static_visitor<void *> { inline explicit AllocVisitor(size_t size) : size_(size) {} template <typename Place> inline void *operator()(const Place &place) const { return Alloc<Place>(place, size_); } private: size_t size_; }; struct FreeVisitor : public boost::static_visitor<void> { inline explicit FreeVisitor(void *ptr) : ptr_(ptr) {} template <typename Place> inline void operator()(const Place &place) const { Free<Place>(place, ptr_); } private: void *ptr_; }; size_t Usage::operator()(const platform::CPUPlace &cpu) const { return Used(cpu); } size_t Usage::operator()(const platform::CUDAPlace &gpu) const { #ifdef PADDLE_WITH_CUDA return Used(gpu); #else PADDLE_THROW("'CUDAPlace' is not supported in CPU only device."); #endif } size_t Usage::operator()(const platform::CUDAPinnedPlace &cuda_pinned) const { #ifdef PADDLE_WITH_CUDA return Used(cuda_pinned); #else PADDLE_THROW("'CUDAPinnedPlace' is not supported in CPU only device."); #endif } } // namespace legacy namespace allocation { Allocation *LegacyAllocator::AllocateImpl(size_t size, Allocator::Attr attr) { void *ptr = boost::apply_visitor(legacy::AllocVisitor(size), place_); return new Allocation(ptr, size, place_); } void LegacyAllocator::Free(Allocation *allocation) { boost::apply_visitor(legacy::FreeVisitor(allocation->ptr()), allocation->place()); delete allocation; } } // namespace allocation } // namespace memory } // namespace paddle <|endoftext|>
<commit_before>#include <cstdint> #include "immintrin.h" #include "/home/christoph/intel/iaca/include/iacaMarks.h" inline void _permute_and_store(std::uint32_t* dst, __m512i k, __m512i a, __m512i b) { _mm512_storeu_si512(dst, _mm512_permutex2var_epi32(a, k, b)); } inline __m512i _rank_get(__m512i bits, __m512i rank, __m512i indice) { // we store (bits+bits) to save a cycle (we never count the highest bit) indice = _mm512_andnot_si512(indice, _mm512_set1_epi32(0x1F)); bits = _mm512_srlv_epi32 (bits , indice); #ifndef __AVX512VPOPCNTDQ__ // constants const auto lut = _mm512_set_epi32( 0x04030302, 0x03020201, 0x03020201, 0x2010100, 0x04030302, 0x03020201, 0x03020201, 0x2010100, 0x04030302, 0x03020201, 0x03020201, 0x2010100, 0x04030302, 0x03020201, 0x03020201, 0x2010100 ); // uint8_t popcount auto bitsh = _mm512_srli_epi32(bits, 4); auto bitsl = _mm512_and_si512(bits , _mm512_set1_epi8(0x0F)); bitsh = _mm512_and_si512(bitsh, _mm512_set1_epi8(0x0F)); bitsl = _mm512_shuffle_epi8(lut, bitsl); bitsh = _mm512_shuffle_epi8(lut, bitsh); bits = _mm512_add_epi32(bitsl, bitsh); // uint32_t popcount bits = _mm512_maskz_dbsad_epu8(0x5555, bits, _mm512_setzero_si512(), 0); #else bits = _mm512_popcnt_epi32(bits); #endif return _mm512_add_epi32(rank, bits); } template<class T> inline T* _addr(T* base, std::size_t byte_step) { return reinterpret_cast<T*>( reinterpret_cast<std::uint8_t*>(base) + byte_step ); } void encode_main ( // The queues // current std::uint32_t* queue_iter, // start of the queue std::uint32_t* queue_last, // end of the queue // next (queue_out0 MAY BE queue_iter) std::uint32_t* queue_out0, // where to write out the queue (zero) std::uint32_t* queue_out1, // where to write out the queue (ones) // cached values (should probably fit L1 or L2) std::uint32_t* cache_iter, // start of the cached values std::uint32_t* cache_next, // where to write the next cached values std::size_t cache_step, // step between the cache columns in BYTES // columns: c_i, c_k, r1_i, unused/coder, r1_k // we dont use column 3 to save registers (addressing doesn't allow *3) // L1/L2 shouldn't be effected by this // unused memory overhead is not that big // if we interleave all 8 caches we can use // that one big free chunk for the coder ! // the rank dictionary std::uint32_t* rdict_base, // base address of the dictionary std::uint32_t count_zero, // number of zeros in this dictionary // stream of the filter masks std::uint16_t* fmask_iter, std::uint16_t* fmask_out0, std::uint16_t* fmask_out1, // where to store the coder information std::uint32_t* coder_iter, // should use the free column in the cache __mmask16 k0 // we need the compiler to assume this // might not be -1 but in fact it needs to be ) { // constants constexpr std::size_t m512i_size = sizeof(__m512i); // loop invariants auto cX_z = _mm512_set1_epi32(count_zero); // broadcast the amount of zeros // software pipelining preload auto cX_j_pipe = _mm512_load_si512(queue_iter ); auto offsets = _mm512_srli_epi32(cX_j_pipe , 5); auto bits_pipe = _mm512_i64gather_epi64(offsets, rdict_base + 0, 8); auto rank_pipe = _mm512_i64gather_epi64(offsets, rdict_base + 1, 8); // this is based on // Computing the longest common prefix array based on the Burrows–Wheeler transform - Uwe Baier // this describes the iteration over the BWT in order to do // a breath-first search on the (virtual) suffix tree // Lossless data compression via substring enumeration - D Dube // this describes the actual compression algorithm // it basically recursively refines a markov model // Improving Compression via Substring Enumeration by Explicit Phase Awareness. - M Béliveau // this explains why the dictionary is actually done // on 8 dictionaries. This implementation uses a wavelet matrix // rather than a regular wavelet tree. while (queue_iter < queue_last) { IACA_START // pipeline cX_j auto cX_j = cX_j_pipe; cX_j_pipe = _mm512_load_si512(queue_iter); queue_iter = _addr(queue_iter, m512i_size); // load from cache (queue and ranks) auto cX_i = _mm512_load_si512(_addr(cache_iter, 0 * cache_step)); auto cX_k = _mm512_load_si512(_addr(cache_iter, 1 * cache_step)); auto r1_i = _mm512_load_si512(_addr(cache_iter, 2 * cache_step)); auto r1_k = _mm512_load_si512(_addr(cache_iter, 4 * cache_step)); // start preload offsets = _mm512_srli_epi32(cX_j_pipe, 5); auto bits = bits_pipe; bits_pipe = _mm512_mask_i64gather_epi64(bits_pipe, k0, offsets, rdict_base + 0, 8); auto rank = rank_pipe; rank_pipe = _mm512_mask_i64gather_epi64(rank_pipe, k0, offsets, rdict_base + 1, 8); // calculate the rank auto r1_j = _rank_get(bits, rank, cX_j); // calculate some butterflies vars auto n_1w_ = _mm512_sub_epi32(cX_k, cX_j); // calculate the number of zeros before each point auto r0_i = _mm512_sub_epi32(cX_i, r1_i); auto r0_j = _mm512_sub_epi32(cX_j, r1_j); auto r0_k = _mm512_sub_epi32(cX_k, r1_k); // calculate the rest of the butterfly vars auto n__w1 = _mm512_sub_epi32(r1_k, r1_i); auto n__w0 = _mm512_sub_epi32(r0_k, r0_i); auto n_1w1 = _mm512_sub_epi32(r1_k, r1_j); __mmask16 filter_mask; // write out the queue (zero part) filter_mask = _mm512_cmpgt_epi32_mask(r0_j, r0_i); filter_mask = _mm512_mask_cmpgt_epi32_mask(filter_mask, r0_k, r0_j); _mm512_mask_compressstoreu_epi32(queue_out0, filter_mask, r0_j); queue_out0 += _mm_popcnt_u64(filter_mask); *fmask_out0++ = filter_mask; // write out the queue (zero part) filter_mask = _mm512_cmpgt_epi32_mask(r1_j, r1_i); filter_mask = _mm512_mask_cmpgt_epi32_mask(filter_mask, r1_k, r1_j); _mm512_mask_compressstoreu_epi32(queue_out1, filter_mask, r1_j); queue_out1 += _mm_popcnt_u64(filter_mask); *fmask_out1++ = filter_mask; // calculate the limits from the butterfly __m512i min = _mm512_maskz_sub_epi32(_mm512_cmpgt_epi32_mask(n_1w_, n__w0), n_1w_, n__w0); __m512i max = _mm512_min_epi32(n_1w_, n__w1); // calculate the digit and the base auto digit = _mm512_sub_epi32(n_1w1, min); auto base = _mm512_add_epi32(_mm512_sub_epi32(max, min), _mm512_set1_epi32(1)); // store the limits for the coder _mm512_storeu_si512(_addr(coder_iter, 0 * m512i_size), digit); _mm512_storeu_si512(_addr(coder_iter, 1 * m512i_size), base ); coder_iter = _addr(coder_iter, 2 * m512i_size); // interleave loads and ranks // write out only the used ones (lo part) auto mask_lo = *fmask_iter++; auto shuffle_masklo = _mm512_set_epi32(23, 7,22, 6,21, 5,20, 4,19, 3,18, 2,17, 1,16, 0); shuffle_masklo = _mm512_maskz_compress_epi32(mask_lo, shuffle_masklo); auto cache_next_tmp = cache_next + _mm_popcnt_u64(mask_lo); _permute_and_store(_addr(cache_next, 0 * cache_step), shuffle_masklo, cX_i, cX_j); _permute_and_store(_addr(cache_next, 1 * cache_step), shuffle_masklo, cX_j, cX_k); _permute_and_store(_addr(cache_next, 2 * cache_step), shuffle_masklo, r1_i, r1_j); _permute_and_store(_addr(cache_next, 4 * cache_step), shuffle_masklo, r1_j, r1_k); // write out only the used ones (hi part) auto mask_hi = *fmask_iter++; auto shuffle_maskhi = _mm512_set_epi32(31,15,30,14,29,13,28,12,27,11,26,10,25, 9,24, 8); shuffle_maskhi = _mm512_maskz_compress_epi32(mask_hi, shuffle_maskhi); cache_next = cache_next_tmp + _mm_popcnt_u64(mask_hi); _permute_and_store(_addr(cache_next_tmp, 0 * cache_step), shuffle_maskhi, cX_i, cX_j); _permute_and_store(_addr(cache_next_tmp, 1 * cache_step), shuffle_maskhi, cX_j, cX_k); _permute_and_store(_addr(cache_next_tmp, 2 * cache_step), shuffle_maskhi, r1_i, r1_j); _permute_and_store(_addr(cache_next_tmp, 4 * cache_step), shuffle_maskhi, r1_j, r1_k); } IACA_END } int main() {} <commit_msg>Corrected the gather<commit_after>#include <cstdint> #include "immintrin.h" #include "/home/christoph/intel/iaca/include/iacaMarks.h" inline void _permute_and_store(std::uint32_t* dst, __m512i k, __m512i a, __m512i b) { _mm512_storeu_si512(dst, _mm512_permutex2var_epi32(a, k, b)); } inline __m512i _rank_get(__m512i bits, __m512i rank, __m512i indice) { // we store (bits+bits) to save a cycle (we never count the highest bit) indice = _mm512_andnot_si512(indice, _mm512_set1_epi32(0x1F)); bits = _mm512_srlv_epi32 (bits , indice); #ifndef __AVX512VPOPCNTDQ__ // constants const auto lut = _mm512_set_epi32( 0x04030302, 0x03020201, 0x03020201, 0x2010100, 0x04030302, 0x03020201, 0x03020201, 0x2010100, 0x04030302, 0x03020201, 0x03020201, 0x2010100, 0x04030302, 0x03020201, 0x03020201, 0x2010100 ); // uint8_t popcount auto bitsh = _mm512_srli_epi32(bits, 4); auto bitsl = _mm512_and_si512(bits , _mm512_set1_epi8(0x0F)); bitsh = _mm512_and_si512(bitsh, _mm512_set1_epi8(0x0F)); bitsl = _mm512_shuffle_epi8(lut, bitsl); bitsh = _mm512_shuffle_epi8(lut, bitsh); bits = _mm512_add_epi32(bitsl, bitsh); // uint32_t popcount bits = _mm512_maskz_dbsad_epu8(0x5555, bits, _mm512_setzero_si512(), 0); #else bits = _mm512_popcnt_epi32(bits); #endif return _mm512_add_epi32(rank, bits); } template<class T> inline T* _addr(T* base, std::size_t byte_step) { return reinterpret_cast<T*>( reinterpret_cast<std::uint8_t*>(base) + byte_step ); } void encode_main ( // The queues // current std::uint32_t* queue_iter, // start of the queue std::uint32_t* queue_last, // end of the queue // next (queue_out0 MAY BE queue_iter) std::uint32_t* queue_out0, // where to write out the queue (zero) std::uint32_t* queue_out1, // where to write out the queue (ones) // cached values (should probably fit L1 or L2) std::uint32_t* cache_iter, // start of the cached values std::uint32_t* cache_next, // where to write the next cached values std::size_t cache_step, // step between the cache columns in BYTES // columns: c_i, c_k, r1_i, unused/coder, r1_k // we dont use column 3 to save registers (addressing doesn't allow *3) // L1/L2 shouldn't be effected by this // unused memory overhead is not that big // if we interleave all 8 caches we can use // that one big free chunk for the coder ! // the rank dictionary std::uint32_t* rdict_base, // base address of the dictionary std::uint32_t count_zero, // number of zeros in this dictionary // stream of the filter masks std::uint16_t* fmask_iter, std::uint16_t* fmask_out0, std::uint16_t* fmask_out1, // where to store the coder information std::uint32_t* coder_iter, // should use the free column in the cache __mmask16 k0 // we need the compiler to assume this // might not be -1 but in fact it needs to be ) { // constants constexpr std::size_t m512i_size = sizeof(__m512i); // loop invariants auto cX_z = _mm512_set1_epi32(count_zero); // broadcast the amount of zeros // software pipelining preload auto cX_j_pipe = _mm512_load_si512(queue_iter ); auto offsets = _mm512_srli_epi32(cX_j_pipe , 5); auto bits_pipe = _mm512_i64gather_epi64(offsets, rdict_base + 0, 8); auto rank_pipe = _mm512_i64gather_epi64(offsets, rdict_base + 1, 8); // this is based on // Computing the longest common prefix array based on the Burrows–Wheeler transform - Uwe Baier // this describes the iteration over the BWT in order to do // a breath-first search on the (virtual) suffix tree // Lossless data compression via substring enumeration - D Dube // this describes the actual compression algorithm // it basically recursively refines a markov model // Improving Compression via Substring Enumeration by Explicit Phase Awareness. - M Béliveau // this explains why the dictionary is actually done // on 8 dictionaries. This implementation uses a wavelet matrix // rather than a regular wavelet tree. while (queue_iter < queue_last) { IACA_START // pipeline cX_j auto cX_j = cX_j_pipe; cX_j_pipe = _mm512_load_si512(queue_iter); queue_iter = _addr(queue_iter, m512i_size); // load from cache (queue and ranks) auto cX_i = _mm512_load_si512(_addr(cache_iter, 0 * cache_step)); auto cX_k = _mm512_load_si512(_addr(cache_iter, 1 * cache_step)); auto r1_i = _mm512_load_si512(_addr(cache_iter, 2 * cache_step)); auto r1_k = _mm512_load_si512(_addr(cache_iter, 4 * cache_step)); // start preload offsets = _mm512_srli_epi32(cX_j_pipe, 5); auto bits = bits_pipe; bits_pipe = _mm512_mask_i32gather_epi32(bits_pipe, k0, offsets, rdict_base + 0, 8); auto rank = rank_pipe; rank_pipe = _mm512_mask_i32gather_epi32(rank_pipe, k0, offsets, rdict_base + 1, 8); // calculate the rank auto r1_j = _rank_get(bits, rank, cX_j); // calculate some butterflies vars auto n_1w_ = _mm512_sub_epi32(cX_k, cX_j); // calculate the number of zeros before each point auto r0_i = _mm512_sub_epi32(cX_i, r1_i); auto r0_j = _mm512_sub_epi32(cX_j, r1_j); auto r0_k = _mm512_sub_epi32(cX_k, r1_k); // calculate the rest of the butterfly vars auto n__w1 = _mm512_sub_epi32(r1_k, r1_i); auto n__w0 = _mm512_sub_epi32(r0_k, r0_i); auto n_1w1 = _mm512_sub_epi32(r1_k, r1_j); __mmask16 filter_mask; // write out the queue (zero part) filter_mask = _mm512_cmpgt_epi32_mask(r0_j, r0_i); filter_mask = _mm512_mask_cmpgt_epi32_mask(filter_mask, r0_k, r0_j); _mm512_mask_compressstoreu_epi32(queue_out0, filter_mask, r0_j); queue_out0 += _mm_popcnt_u64(filter_mask); *fmask_out0++ = filter_mask; // write out the queue (zero part) filter_mask = _mm512_cmpgt_epi32_mask(r1_j, r1_i); filter_mask = _mm512_mask_cmpgt_epi32_mask(filter_mask, r1_k, r1_j); _mm512_mask_compressstoreu_epi32(queue_out1, filter_mask, r1_j); queue_out1 += _mm_popcnt_u64(filter_mask); *fmask_out1++ = filter_mask; // calculate the limits from the butterfly __m512i min = _mm512_maskz_sub_epi32(_mm512_cmpgt_epi32_mask(n_1w_, n__w0), n_1w_, n__w0); __m512i max = _mm512_min_epi32(n_1w_, n__w1); // calculate the digit and the base auto digit = _mm512_sub_epi32(n_1w1, min); auto base = _mm512_add_epi32(_mm512_sub_epi32(max, min), _mm512_set1_epi32(1)); // store the limits for the coder _mm512_storeu_si512(_addr(coder_iter, 0 * m512i_size), digit); _mm512_storeu_si512(_addr(coder_iter, 1 * m512i_size), base ); coder_iter = _addr(coder_iter, 2 * m512i_size); // interleave loads and ranks // write out only the used ones (lo part) auto mask_lo = *fmask_iter++; auto shuffle_masklo = _mm512_set_epi32(23, 7,22, 6,21, 5,20, 4,19, 3,18, 2,17, 1,16, 0); shuffle_masklo = _mm512_maskz_compress_epi32(mask_lo, shuffle_masklo); auto cache_next_tmp = cache_next + _mm_popcnt_u64(mask_lo); _permute_and_store(_addr(cache_next, 0 * cache_step), shuffle_masklo, cX_i, cX_j); _permute_and_store(_addr(cache_next, 1 * cache_step), shuffle_masklo, cX_j, cX_k); _permute_and_store(_addr(cache_next, 2 * cache_step), shuffle_masklo, r1_i, r1_j); _permute_and_store(_addr(cache_next, 4 * cache_step), shuffle_masklo, r1_j, r1_k); // write out only the used ones (hi part) auto mask_hi = *fmask_iter++; auto shuffle_maskhi = _mm512_set_epi32(31,15,30,14,29,13,28,12,27,11,26,10,25, 9,24, 8); shuffle_maskhi = _mm512_maskz_compress_epi32(mask_hi, shuffle_maskhi); cache_next = cache_next_tmp + _mm_popcnt_u64(mask_hi); _permute_and_store(_addr(cache_next_tmp, 0 * cache_step), shuffle_maskhi, cX_i, cX_j); _permute_and_store(_addr(cache_next_tmp, 1 * cache_step), shuffle_maskhi, cX_j, cX_k); _permute_and_store(_addr(cache_next_tmp, 2 * cache_step), shuffle_maskhi, r1_i, r1_j); _permute_and_store(_addr(cache_next_tmp, 4 * cache_step), shuffle_maskhi, r1_j, r1_k); } IACA_END } int main() {} <|endoftext|>
<commit_before>// Win32Lib.cpp // This file is part of the EScript programming language (https://github.com/EScript) // // Copyright (C) 2011-2013 Claudius Jähn <ClaudiusJ@live.de> // Copyright (C) 2012 Benjamin Eikel <benjamin@eikel.org> // // Licensed under the MIT License. See LICENSE file for details. // --------------------------------------------------------------------------------- #ifdef _WIN32 #include "../EScript/EScript.h" #include "Win32Lib.h" #include <windows.h> namespace EScript{ //! (static) void Win32Lib::init(EScript::Namespace * globals) { Namespace * lib = new Namespace; declareConstant(globals,"Win32",lib); //! [ESF] void setClipboard( string ) ES_FUN(lib,"setClipboard",1,1,(Win32Lib::setClipboard(parameter[0].toString()),RtValue(nullptr))) //! [ESF] string getClipboard( ) ES_FUN(lib,"getClipboard",0,0,Win32Lib::getClipboard()) //! [ESF] bool loadLibrary(string ) ES_FUNCTION(lib,"loadLibrary",1,1, { HINSTANCE hDLL; libInitFunction * f; // Function pointer hDLL = LoadLibrary(parameter[0].toString().c_str()); if(hDLL == nullptr) return false; f = reinterpret_cast<libInitFunction*>(GetProcAddress(hDLL,"init")); if(!f) { // handle the error FreeLibrary(hDLL); return false; } EScript::initLibrary(f); return true; }) } //! (static) void Win32Lib::setClipboard(const std::string & s){ if(OpenClipboard(nullptr)) { EmptyClipboard(); HGLOBAL hClipboardData; hClipboardData = GlobalAlloc(GMEM_DDESHARE, s.size()+1); // strData.GetLength()+1); char * pchData; pchData = reinterpret_cast<char*>(GlobalLock(hClipboardData)); strncpy(pchData, s.c_str(),s.size());// LPCSTR(strData)); GlobalUnlock(hClipboardData); SetClipboardData(CF_TEXT,hClipboardData); CloseClipboard(); } else std::cout << "Could not open Clipboard!\n"; } //! (static) std::string Win32Lib::getClipboard(){ if(!OpenClipboard(nullptr)) { std::cout << "Could not open Clipboard!\n"; return ""; } HGLOBAL hClipboardData; char * lpstr; hClipboardData = GetClipboardData(CF_TEXT); lpstr = reinterpret_cast<char*>(GlobalLock(hClipboardData)); std::string s = std::string(lpstr); //std::cout << s; // ... GlobalUnlock(hClipboardData); CloseClipboard(); return s; } } #endif <commit_msg>Win32Lib: Add missing include.<commit_after>// Win32Lib.cpp // This file is part of the EScript programming language (https://github.com/EScript) // // Copyright (C) 2011-2013 Claudius Jähn <ClaudiusJ@live.de> // Copyright (C) 2012 Benjamin Eikel <benjamin@eikel.org> // // Licensed under the MIT License. See LICENSE file for details. // --------------------------------------------------------------------------------- #ifdef _WIN32 #include "../EScript/EScript.h" #include "Win32Lib.h" #include <windows.h> #include <iostream> namespace EScript{ //! (static) void Win32Lib::init(EScript::Namespace * globals) { Namespace * lib = new Namespace; declareConstant(globals,"Win32",lib); //! [ESF] void setClipboard( string ) ES_FUN(lib,"setClipboard",1,1,(Win32Lib::setClipboard(parameter[0].toString()),RtValue(nullptr))) //! [ESF] string getClipboard( ) ES_FUN(lib,"getClipboard",0,0,Win32Lib::getClipboard()) //! [ESF] bool loadLibrary(string ) ES_FUNCTION(lib,"loadLibrary",1,1, { HINSTANCE hDLL; libInitFunction * f; // Function pointer hDLL = LoadLibrary(parameter[0].toString().c_str()); if(hDLL == nullptr) return false; f = reinterpret_cast<libInitFunction*>(GetProcAddress(hDLL,"init")); if(!f) { // handle the error FreeLibrary(hDLL); return false; } EScript::initLibrary(f); return true; }) } //! (static) void Win32Lib::setClipboard(const std::string & s){ if(OpenClipboard(nullptr)) { EmptyClipboard(); HGLOBAL hClipboardData; hClipboardData = GlobalAlloc(GMEM_DDESHARE, s.size()+1); // strData.GetLength()+1); char * pchData; pchData = reinterpret_cast<char*>(GlobalLock(hClipboardData)); strncpy(pchData, s.c_str(),s.size());// LPCSTR(strData)); GlobalUnlock(hClipboardData); SetClipboardData(CF_TEXT,hClipboardData); CloseClipboard(); } else std::cout << "Could not open Clipboard!\n"; } //! (static) std::string Win32Lib::getClipboard(){ if(!OpenClipboard(nullptr)) { std::cout << "Could not open Clipboard!\n"; return ""; } HGLOBAL hClipboardData; char * lpstr; hClipboardData = GetClipboardData(CF_TEXT); lpstr = reinterpret_cast<char*>(GlobalLock(hClipboardData)); std::string s = std::string(lpstr); //std::cout << s; // ... GlobalUnlock(hClipboardData); CloseClipboard(); return s; } } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "basefilefilter.h" #include <coreplugin/editormanager/editormanager.h> #include <utils/fileutils.h> #include <QDir> #include <QStringMatcher> using namespace Core; using namespace Locator; using namespace Utils; BaseFileFilter::BaseFileFilter() : m_forceNewSearchList(false) { } QList<FilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &origEntry) { updateFiles(); QList<FilterEntry> matches; QList<FilterEntry> badMatches; QString needle = trimWildcards(origEntry); const QString lineNoSuffix = EditorManager::splitLineNumber(&needle); QStringMatcher matcher(needle, Qt::CaseInsensitive); const QChar asterisk = QLatin1Char('*'); QRegExp regexp(asterisk + needle+ asterisk, Qt::CaseInsensitive, QRegExp::Wildcard); if (!regexp.isValid()) return matches; const bool hasWildcard = needle.contains(asterisk) || needle.contains(QLatin1Char('?')); QStringList searchListPaths; QStringList searchListNames; if (!m_previousEntry.isEmpty() && !m_forceNewSearchList && needle.contains(m_previousEntry)) { searchListPaths = m_previousResultPaths; searchListNames = m_previousResultNames; } else { searchListPaths = m_files; searchListNames = m_fileNames; } m_previousResultPaths.clear(); m_previousResultNames.clear(); m_forceNewSearchList = false; m_previousEntry = needle; const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(needle); QStringListIterator paths(searchListPaths); QStringListIterator names(searchListNames); while (paths.hasNext() && names.hasNext()) { if (future.isCanceled()) break; QString path = paths.next(); QString name = names.next(); if ((hasWildcard && regexp.exactMatch(name)) || (!hasWildcard && matcher.indexIn(name) != -1)) { QFileInfo fi(path); FilterEntry entry(this, fi.fileName(), QString(path + lineNoSuffix)); entry.extraInfo = FileUtils::shortNativePath(FileName(fi)); entry.fileName = path; if (name.startsWith(needle, caseSensitivityForPrefix)) matches.append(entry); else badMatches.append(entry); m_previousResultPaths.append(path); m_previousResultNames.append(name); } } matches.append(badMatches); return matches; } void BaseFileFilter::accept(Locator::FilterEntry selection) const { EditorManager::openEditor(selection.internalData.toString(), Id(), EditorManager::CanContainLineNumber); } void BaseFileFilter::generateFileNames() { m_fileNames.clear(); foreach (const QString &fileName, m_files) { QFileInfo fi(fileName); m_fileNames.append(fi.fileName()); } m_forceNewSearchList = true; } void BaseFileFilter::updateFiles() { } <commit_msg>Locator: Rename variables for consistency<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "basefilefilter.h" #include <coreplugin/editormanager/editormanager.h> #include <utils/fileutils.h> #include <QDir> #include <QStringMatcher> using namespace Core; using namespace Locator; using namespace Utils; BaseFileFilter::BaseFileFilter() : m_forceNewSearchList(false) { } QList<FilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &origEntry) { updateFiles(); QList<FilterEntry> betterEntries; QList<FilterEntry> goodEntries; QString needle = trimWildcards(origEntry); const QString lineNoSuffix = EditorManager::splitLineNumber(&needle); QStringMatcher matcher(needle, Qt::CaseInsensitive); const QChar asterisk = QLatin1Char('*'); QRegExp regexp(asterisk + needle+ asterisk, Qt::CaseInsensitive, QRegExp::Wildcard); if (!regexp.isValid()) return betterEntries; const bool hasWildcard = needle.contains(asterisk) || needle.contains(QLatin1Char('?')); QStringList searchListPaths; QStringList searchListNames; if (!m_previousEntry.isEmpty() && !m_forceNewSearchList && needle.contains(m_previousEntry)) { searchListPaths = m_previousResultPaths; searchListNames = m_previousResultNames; } else { searchListPaths = m_files; searchListNames = m_fileNames; } m_previousResultPaths.clear(); m_previousResultNames.clear(); m_forceNewSearchList = false; m_previousEntry = needle; const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(needle); QStringListIterator paths(searchListPaths); QStringListIterator names(searchListNames); while (paths.hasNext() && names.hasNext()) { if (future.isCanceled()) break; QString path = paths.next(); QString name = names.next(); if ((hasWildcard && regexp.exactMatch(name)) || (!hasWildcard && matcher.indexIn(name) != -1)) { QFileInfo fi(path); FilterEntry entry(this, fi.fileName(), QString(path + lineNoSuffix)); entry.extraInfo = FileUtils::shortNativePath(FileName(fi)); entry.fileName = path; if (name.startsWith(needle, caseSensitivityForPrefix)) betterEntries.append(entry); else goodEntries.append(entry); m_previousResultPaths.append(path); m_previousResultNames.append(name); } } betterEntries.append(goodEntries); return betterEntries; } void BaseFileFilter::accept(Locator::FilterEntry selection) const { EditorManager::openEditor(selection.internalData.toString(), Id(), EditorManager::CanContainLineNumber); } void BaseFileFilter::generateFileNames() { m_fileNames.clear(); foreach (const QString &fileName, m_files) { QFileInfo fi(fileName); m_fileNames.append(fi.fileName()); } m_forceNewSearchList = true; } void BaseFileFilter::updateFiles() { } <|endoftext|>
<commit_before>// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <addrdb.h> #include <addrman.h> #include <addrman_impl.h> #include <chainparams.h> #include <merkleblock.h> #include <random.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <time.h> #include <util/asmap.h> #include <cassert> #include <cstdint> #include <optional> #include <string> #include <vector> void initialize_addrman() { SelectParams(CBaseChainParams::REGTEST); } FUZZ_TARGET_INIT(data_stream_addr_man, initialize_addrman) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; CDataStream data_stream = ConsumeDataStream(fuzzed_data_provider); AddrMan addr_man(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0); try { ReadFromStream(addr_man, data_stream); } catch (const std::exception&) { } } /** * Generate a random address. Always returns a valid address. */ CNetAddr RandAddr(FuzzedDataProvider& fuzzed_data_provider, FastRandomContext& fast_random_context) { CNetAddr addr; if (fuzzed_data_provider.remaining_bytes() > 1 && fuzzed_data_provider.ConsumeBool()) { addr = ConsumeNetAddr(fuzzed_data_provider); } else { // The networks [1..6] correspond to CNetAddr::BIP155Network (private). static const std::map<uint8_t, uint8_t> net_len_map = {{1, ADDR_IPV4_SIZE}, {2, ADDR_IPV6_SIZE}, {4, ADDR_TORV3_SIZE}, {5, ADDR_I2P_SIZE}, {6, ADDR_CJDNS_SIZE}}; uint8_t net = fast_random_context.randrange(5) + 1; // [1..5] if (net == 3) { net = 6; } CDataStream s(SER_NETWORK, PROTOCOL_VERSION | ADDRV2_FORMAT); s << net; s << fast_random_context.randbytes(net_len_map.at(net)); s >> addr; } // Return a dummy IPv4 5.5.5.5 if we generated an invalid address. if (!addr.IsValid()) { in_addr v4_addr = {}; v4_addr.s_addr = 0x05050505; addr = CNetAddr{v4_addr}; } return addr; } class AddrManDeterministic : public AddrMan { public: explicit AddrManDeterministic(std::vector<bool> asmap, FuzzedDataProvider& fuzzed_data_provider) : AddrMan(std::move(asmap), /* deterministic */ true, /* consistency_check_ratio */ 0) { WITH_LOCK(m_impl->cs, m_impl->insecure_rand = FastRandomContext{ConsumeUInt256(fuzzed_data_provider)}); } /** * Fill this addrman with lots of addresses from lots of sources. */ void Fill(FuzzedDataProvider& fuzzed_data_provider) { LOCK(m_impl->cs); // Add some of the addresses directly to the "tried" table. // 0, 1, 2, 3 corresponding to 0%, 100%, 50%, 33% const size_t n = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 3); const size_t num_sources = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 50); CNetAddr prev_source; // Generate a FastRandomContext seed to use inside the loops instead of // fuzzed_data_provider. When fuzzed_data_provider is exhausted it // just returns 0. FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)}; for (size_t i = 0; i < num_sources; ++i) { const auto source = RandAddr(fuzzed_data_provider, fast_random_context); const size_t num_addresses = fast_random_context.randrange(500) + 1; // [1..500] for (size_t j = 0; j < num_addresses; ++j) { const auto addr = CAddress{CService{RandAddr(fuzzed_data_provider, fast_random_context), 8333}, NODE_NETWORK}; const auto time_penalty = fast_random_context.randrange(100000001); m_impl->Add_(addr, source, time_penalty); if (n > 0 && m_impl->mapInfo.size() % n == 0) { m_impl->Good_(addr, false, GetTime()); } // Add 10% of the addresses from more than one source. if (fast_random_context.randrange(10) == 0 && prev_source.IsValid()) { m_impl->Add_(addr, prev_source, time_penalty); } } prev_source = source; } } /** * Compare with another AddrMan. * This compares: * - the values in `mapInfo` (the keys aka ids are ignored) * - vvNew entries refer to the same addresses * - vvTried entries refer to the same addresses */ bool operator==(const AddrManDeterministic& other) { LOCK2(m_impl->cs, other.m_impl->cs); if (m_impl->mapInfo.size() != other.m_impl->mapInfo.size() || m_impl->nNew != other.m_impl->nNew || m_impl->nTried != other.m_impl->nTried) { return false; } // Check that all values in `mapInfo` are equal to all values in `other.mapInfo`. // Keys may be different. using AddrInfoHasher = std::function<size_t(const AddrInfo&)>; using AddrInfoEq = std::function<bool(const AddrInfo&, const AddrInfo&)>; CNetAddrHash netaddr_hasher; AddrInfoHasher addrinfo_hasher = [&netaddr_hasher](const AddrInfo& a) { return netaddr_hasher(static_cast<CNetAddr>(a)) ^ netaddr_hasher(a.source) ^ a.nLastSuccess ^ a.nAttempts ^ a.nRefCount ^ a.fInTried; }; AddrInfoEq addrinfo_eq = [](const AddrInfo& lhs, const AddrInfo& rhs) { return static_cast<CNetAddr>(lhs) == static_cast<CNetAddr>(rhs) && lhs.source == rhs.source && lhs.nLastSuccess == rhs.nLastSuccess && lhs.nAttempts == rhs.nAttempts && lhs.nRefCount == rhs.nRefCount && lhs.fInTried == rhs.fInTried; }; using Addresses = std::unordered_set<AddrInfo, AddrInfoHasher, AddrInfoEq>; const size_t num_addresses{m_impl->mapInfo.size()}; Addresses addresses{num_addresses, addrinfo_hasher, addrinfo_eq}; for (const auto& [id, addr] : m_impl->mapInfo) { addresses.insert(addr); } Addresses other_addresses{num_addresses, addrinfo_hasher, addrinfo_eq}; for (const auto& [id, addr] : other.m_impl->mapInfo) { other_addresses.insert(addr); } if (addresses != other_addresses) { return false; } auto IdsReferToSameAddress = [&](int id, int other_id) EXCLUSIVE_LOCKS_REQUIRED(m_impl->cs, other.m_impl->cs) { if (id == -1 && other_id == -1) { return true; } if ((id == -1 && other_id != -1) || (id != -1 && other_id == -1)) { return false; } return m_impl->mapInfo.at(id) == other.m_impl->mapInfo.at(other_id); }; // Check that `vvNew` contains the same addresses as `other.vvNew`. Notice - `vvNew[i][j]` // contains just an id and the address is to be found in `mapInfo.at(id)`. The ids // themselves may differ between `vvNew` and `other.vvNew`. for (size_t i = 0; i < ADDRMAN_NEW_BUCKET_COUNT; ++i) { for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) { if (!IdsReferToSameAddress(m_impl->vvNew[i][j], other.m_impl->vvNew[i][j])) { return false; } } } // Same for `vvTried`. for (size_t i = 0; i < ADDRMAN_TRIED_BUCKET_COUNT; ++i) { for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) { if (!IdsReferToSameAddress(m_impl->vvTried[i][j], other.m_impl->vvTried[i][j])) { return false; } } } return true; } }; [[nodiscard]] inline std::vector<bool> ConsumeAsmap(FuzzedDataProvider& fuzzed_data_provider) noexcept { std::vector<bool> asmap = ConsumeRandomLengthBitVector(fuzzed_data_provider); if (!SanityCheckASMap(asmap, 128)) asmap.clear(); return asmap; } FUZZ_TARGET_INIT(addrman, initialize_addrman) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); SetMockTime(ConsumeTime(fuzzed_data_provider)); std::vector<bool> asmap = ConsumeAsmap(fuzzed_data_provider); auto addr_man_ptr = std::make_unique<AddrManDeterministic>(asmap, fuzzed_data_provider); if (fuzzed_data_provider.ConsumeBool()) { const std::vector<uint8_t> serialized_data{ConsumeRandomLengthByteVector(fuzzed_data_provider)}; CDataStream ds(serialized_data, SER_DISK, INIT_PROTO_VERSION); const auto ser_version{fuzzed_data_provider.ConsumeIntegral<int32_t>()}; ds.SetVersion(ser_version); try { ds >> *addr_man_ptr; } catch (const std::ios_base::failure&) { addr_man_ptr = std::make_unique<AddrManDeterministic>(asmap, fuzzed_data_provider); } } AddrManDeterministic& addr_man = *addr_man_ptr; while (fuzzed_data_provider.ConsumeBool()) { CallOneOf( fuzzed_data_provider, [&] { addr_man.ResolveCollisions(); }, [&] { (void)addr_man.SelectTriedCollision(); }, [&] { std::vector<CAddress> addresses; while (fuzzed_data_provider.ConsumeBool()) { const std::optional<CAddress> opt_address = ConsumeDeserializable<CAddress>(fuzzed_data_provider); if (!opt_address) { break; } addresses.push_back(*opt_address); } const std::optional<CNetAddr> opt_net_addr = ConsumeDeserializable<CNetAddr>(fuzzed_data_provider); if (opt_net_addr) { addr_man.Add(addresses, *opt_net_addr, fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 100000000)); } }, [&] { const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider); if (opt_service) { addr_man.Good(*opt_service, ConsumeTime(fuzzed_data_provider)); } }, [&] { const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider); if (opt_service) { addr_man.Attempt(*opt_service, fuzzed_data_provider.ConsumeBool(), ConsumeTime(fuzzed_data_provider)); } }, [&] { const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider); if (opt_service) { addr_man.Connected(*opt_service, ConsumeTime(fuzzed_data_provider)); } }, [&] { const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider); if (opt_service) { addr_man.SetServices(*opt_service, ConsumeWeakEnum(fuzzed_data_provider, ALL_SERVICE_FLAGS)); } }); } const AddrMan& const_addr_man{addr_man}; (void)const_addr_man.GetAddr( /* max_addresses */ fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096), /* max_pct */ fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096), /* network */ std::nullopt); (void)const_addr_man.Select(fuzzed_data_provider.ConsumeBool()); (void)const_addr_man.size(); CDataStream data_stream(SER_NETWORK, PROTOCOL_VERSION); data_stream << const_addr_man; } // Check that serialize followed by unserialize produces the same addrman. FUZZ_TARGET_INIT(addrman_serdeser, initialize_addrman) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); SetMockTime(ConsumeTime(fuzzed_data_provider)); std::vector<bool> asmap = ConsumeAsmap(fuzzed_data_provider); AddrManDeterministic addr_man1{asmap, fuzzed_data_provider}; AddrManDeterministic addr_man2{asmap, fuzzed_data_provider}; CDataStream data_stream(SER_NETWORK, PROTOCOL_VERSION); addr_man1.Fill(fuzzed_data_provider); data_stream << addr_man1; data_stream >> addr_man2; assert(addr_man1 == addr_man2); } <commit_msg>[fuzz] Make Fill() a free function in fuzz/addrman.cpp<commit_after>// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <addrdb.h> #include <addrman.h> #include <addrman_impl.h> #include <chainparams.h> #include <merkleblock.h> #include <random.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <time.h> #include <util/asmap.h> #include <cassert> #include <cstdint> #include <optional> #include <string> #include <vector> void initialize_addrman() { SelectParams(CBaseChainParams::REGTEST); } FUZZ_TARGET_INIT(data_stream_addr_man, initialize_addrman) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; CDataStream data_stream = ConsumeDataStream(fuzzed_data_provider); AddrMan addr_man(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0); try { ReadFromStream(addr_man, data_stream); } catch (const std::exception&) { } } /** * Generate a random address. Always returns a valid address. */ CNetAddr RandAddr(FuzzedDataProvider& fuzzed_data_provider, FastRandomContext& fast_random_context) { CNetAddr addr; if (fuzzed_data_provider.remaining_bytes() > 1 && fuzzed_data_provider.ConsumeBool()) { addr = ConsumeNetAddr(fuzzed_data_provider); } else { // The networks [1..6] correspond to CNetAddr::BIP155Network (private). static const std::map<uint8_t, uint8_t> net_len_map = {{1, ADDR_IPV4_SIZE}, {2, ADDR_IPV6_SIZE}, {4, ADDR_TORV3_SIZE}, {5, ADDR_I2P_SIZE}, {6, ADDR_CJDNS_SIZE}}; uint8_t net = fast_random_context.randrange(5) + 1; // [1..5] if (net == 3) { net = 6; } CDataStream s(SER_NETWORK, PROTOCOL_VERSION | ADDRV2_FORMAT); s << net; s << fast_random_context.randbytes(net_len_map.at(net)); s >> addr; } // Return a dummy IPv4 5.5.5.5 if we generated an invalid address. if (!addr.IsValid()) { in_addr v4_addr = {}; v4_addr.s_addr = 0x05050505; addr = CNetAddr{v4_addr}; } return addr; } /** Fill addrman with lots of addresses from lots of sources. */ void FillAddrman(AddrMan& addrman, FuzzedDataProvider& fuzzed_data_provider) { // Add some of the addresses directly to the "tried" table. // 0, 1, 2, 3 corresponding to 0%, 100%, 50%, 33% const size_t n = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 3); const size_t num_sources = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 50); CNetAddr prev_source; // Generate a FastRandomContext seed to use inside the loops instead of // fuzzed_data_provider. When fuzzed_data_provider is exhausted it // just returns 0. FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)}; for (size_t i = 0; i < num_sources; ++i) { const auto source = RandAddr(fuzzed_data_provider, fast_random_context); const size_t num_addresses = fast_random_context.randrange(500) + 1; // [1..500] for (size_t j = 0; j < num_addresses; ++j) { const auto addr = CAddress{CService{RandAddr(fuzzed_data_provider, fast_random_context), 8333}, NODE_NETWORK}; const auto time_penalty = fast_random_context.randrange(100000001); addrman.Add({addr}, source, time_penalty); if (n > 0 && addrman.size() % n == 0) { addrman.Good(addr, GetTime()); } // Add 10% of the addresses from more than one source. if (fast_random_context.randrange(10) == 0 && prev_source.IsValid()) { addrman.Add({addr}, prev_source, time_penalty); } } prev_source = source; } } class AddrManDeterministic : public AddrMan { public: explicit AddrManDeterministic(std::vector<bool> asmap, FuzzedDataProvider& fuzzed_data_provider) : AddrMan(std::move(asmap), /* deterministic */ true, /* consistency_check_ratio */ 0) { WITH_LOCK(m_impl->cs, m_impl->insecure_rand = FastRandomContext{ConsumeUInt256(fuzzed_data_provider)}); } /** * Compare with another AddrMan. * This compares: * - the values in `mapInfo` (the keys aka ids are ignored) * - vvNew entries refer to the same addresses * - vvTried entries refer to the same addresses */ bool operator==(const AddrManDeterministic& other) { LOCK2(m_impl->cs, other.m_impl->cs); if (m_impl->mapInfo.size() != other.m_impl->mapInfo.size() || m_impl->nNew != other.m_impl->nNew || m_impl->nTried != other.m_impl->nTried) { return false; } // Check that all values in `mapInfo` are equal to all values in `other.mapInfo`. // Keys may be different. using AddrInfoHasher = std::function<size_t(const AddrInfo&)>; using AddrInfoEq = std::function<bool(const AddrInfo&, const AddrInfo&)>; CNetAddrHash netaddr_hasher; AddrInfoHasher addrinfo_hasher = [&netaddr_hasher](const AddrInfo& a) { return netaddr_hasher(static_cast<CNetAddr>(a)) ^ netaddr_hasher(a.source) ^ a.nLastSuccess ^ a.nAttempts ^ a.nRefCount ^ a.fInTried; }; AddrInfoEq addrinfo_eq = [](const AddrInfo& lhs, const AddrInfo& rhs) { return static_cast<CNetAddr>(lhs) == static_cast<CNetAddr>(rhs) && lhs.source == rhs.source && lhs.nLastSuccess == rhs.nLastSuccess && lhs.nAttempts == rhs.nAttempts && lhs.nRefCount == rhs.nRefCount && lhs.fInTried == rhs.fInTried; }; using Addresses = std::unordered_set<AddrInfo, AddrInfoHasher, AddrInfoEq>; const size_t num_addresses{m_impl->mapInfo.size()}; Addresses addresses{num_addresses, addrinfo_hasher, addrinfo_eq}; for (const auto& [id, addr] : m_impl->mapInfo) { addresses.insert(addr); } Addresses other_addresses{num_addresses, addrinfo_hasher, addrinfo_eq}; for (const auto& [id, addr] : other.m_impl->mapInfo) { other_addresses.insert(addr); } if (addresses != other_addresses) { return false; } auto IdsReferToSameAddress = [&](int id, int other_id) EXCLUSIVE_LOCKS_REQUIRED(m_impl->cs, other.m_impl->cs) { if (id == -1 && other_id == -1) { return true; } if ((id == -1 && other_id != -1) || (id != -1 && other_id == -1)) { return false; } return m_impl->mapInfo.at(id) == other.m_impl->mapInfo.at(other_id); }; // Check that `vvNew` contains the same addresses as `other.vvNew`. Notice - `vvNew[i][j]` // contains just an id and the address is to be found in `mapInfo.at(id)`. The ids // themselves may differ between `vvNew` and `other.vvNew`. for (size_t i = 0; i < ADDRMAN_NEW_BUCKET_COUNT; ++i) { for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) { if (!IdsReferToSameAddress(m_impl->vvNew[i][j], other.m_impl->vvNew[i][j])) { return false; } } } // Same for `vvTried`. for (size_t i = 0; i < ADDRMAN_TRIED_BUCKET_COUNT; ++i) { for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) { if (!IdsReferToSameAddress(m_impl->vvTried[i][j], other.m_impl->vvTried[i][j])) { return false; } } } return true; } }; [[nodiscard]] inline std::vector<bool> ConsumeAsmap(FuzzedDataProvider& fuzzed_data_provider) noexcept { std::vector<bool> asmap = ConsumeRandomLengthBitVector(fuzzed_data_provider); if (!SanityCheckASMap(asmap, 128)) asmap.clear(); return asmap; } FUZZ_TARGET_INIT(addrman, initialize_addrman) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); SetMockTime(ConsumeTime(fuzzed_data_provider)); std::vector<bool> asmap = ConsumeAsmap(fuzzed_data_provider); auto addr_man_ptr = std::make_unique<AddrManDeterministic>(asmap, fuzzed_data_provider); if (fuzzed_data_provider.ConsumeBool()) { const std::vector<uint8_t> serialized_data{ConsumeRandomLengthByteVector(fuzzed_data_provider)}; CDataStream ds(serialized_data, SER_DISK, INIT_PROTO_VERSION); const auto ser_version{fuzzed_data_provider.ConsumeIntegral<int32_t>()}; ds.SetVersion(ser_version); try { ds >> *addr_man_ptr; } catch (const std::ios_base::failure&) { addr_man_ptr = std::make_unique<AddrManDeterministic>(asmap, fuzzed_data_provider); } } AddrManDeterministic& addr_man = *addr_man_ptr; while (fuzzed_data_provider.ConsumeBool()) { CallOneOf( fuzzed_data_provider, [&] { addr_man.ResolveCollisions(); }, [&] { (void)addr_man.SelectTriedCollision(); }, [&] { std::vector<CAddress> addresses; while (fuzzed_data_provider.ConsumeBool()) { const std::optional<CAddress> opt_address = ConsumeDeserializable<CAddress>(fuzzed_data_provider); if (!opt_address) { break; } addresses.push_back(*opt_address); } const std::optional<CNetAddr> opt_net_addr = ConsumeDeserializable<CNetAddr>(fuzzed_data_provider); if (opt_net_addr) { addr_man.Add(addresses, *opt_net_addr, fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 100000000)); } }, [&] { const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider); if (opt_service) { addr_man.Good(*opt_service, ConsumeTime(fuzzed_data_provider)); } }, [&] { const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider); if (opt_service) { addr_man.Attempt(*opt_service, fuzzed_data_provider.ConsumeBool(), ConsumeTime(fuzzed_data_provider)); } }, [&] { const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider); if (opt_service) { addr_man.Connected(*opt_service, ConsumeTime(fuzzed_data_provider)); } }, [&] { const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider); if (opt_service) { addr_man.SetServices(*opt_service, ConsumeWeakEnum(fuzzed_data_provider, ALL_SERVICE_FLAGS)); } }); } const AddrMan& const_addr_man{addr_man}; (void)const_addr_man.GetAddr( /* max_addresses */ fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096), /* max_pct */ fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096), /* network */ std::nullopt); (void)const_addr_man.Select(fuzzed_data_provider.ConsumeBool()); (void)const_addr_man.size(); CDataStream data_stream(SER_NETWORK, PROTOCOL_VERSION); data_stream << const_addr_man; } // Check that serialize followed by unserialize produces the same addrman. FUZZ_TARGET_INIT(addrman_serdeser, initialize_addrman) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); SetMockTime(ConsumeTime(fuzzed_data_provider)); std::vector<bool> asmap = ConsumeAsmap(fuzzed_data_provider); AddrManDeterministic addr_man1{asmap, fuzzed_data_provider}; AddrManDeterministic addr_man2{asmap, fuzzed_data_provider}; CDataStream data_stream(SER_NETWORK, PROTOCOL_VERSION); FillAddrman(addr_man1, fuzzed_data_provider); data_stream << addr_man1; data_stream >> addr_man2; assert(addr_man1 == addr_man2); } <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * * This 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. See file COPYING. * */ #include "common/perf_counters.h" #include "common/admin_socket_client.h" #include "common/ceph_context.h" #include "common/config.h" #include "common/errno.h" #include "common/safe_io.h" #include "test/unit.h" #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <map> #include <poll.h> #include <sstream> #include <stdint.h> #include <string.h> #include <string> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <time.h> #include <unistd.h> TEST(PerfCounters, SimpleTest) { g_ceph_context->_conf->set_val_or_die("admin_socket", get_rand_socket_path()); g_ceph_context->_conf->apply_changes(NULL); AdminSocketClient client(get_rand_socket_path()); std::string message; ASSERT_EQ("", client.get_message(&message)); ASSERT_EQ("{}", message); } enum { TEST_PERFCOUNTERS1_ELEMENT_FIRST = 200, TEST_PERFCOUNTERS1_ELEMENT_1, TEST_PERFCOUNTERS1_ELEMENT_2, TEST_PERFCOUNTERS1_ELEMENT_3, TEST_PERFCOUNTERS1_ELEMENT_LAST, }; std::string sd(const char *c) { std::string ret(c); std::string::size_type sz = ret.size(); for (std::string::size_type i = 0; i < sz; ++i) { if (ret[i] == '\'') { ret[i] = '\"'; } } return ret; } static PerfCounters* setup_test_perfcounters1(CephContext *cct) { PerfCountersBuilder bld(cct, "test_perfcounter_1", TEST_PERFCOUNTERS1_ELEMENT_FIRST, TEST_PERFCOUNTERS1_ELEMENT_LAST); bld.add_u64(TEST_PERFCOUNTERS1_ELEMENT_1, "element1"); bld.add_fl(TEST_PERFCOUNTERS1_ELEMENT_2, "element2"); bld.add_fl_avg(TEST_PERFCOUNTERS1_ELEMENT_3, "element3"); return bld.create_perf_counters(); } TEST(PerfCounters, SinglePerfCounters) { PerfCountersCollection *coll = g_ceph_context->GetPerfCountersCollection(); PerfCounters* fake_pf = setup_test_perfcounters1(g_ceph_context); coll->logger_add(fake_pf); g_ceph_context->_conf->set_val_or_die("admin_socket", get_rand_socket_path()); g_ceph_context->_conf->apply_changes(NULL); AdminSocketClient client(get_rand_socket_path()); std::string msg; ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':0," "'element2':0,'element3':{'avgcount':0,'sum':0}}}"), msg); fake_pf->inc(TEST_PERFCOUNTERS1_ELEMENT_1); fake_pf->fset(TEST_PERFCOUNTERS1_ELEMENT_2, 0.5); fake_pf->finc(TEST_PERFCOUNTERS1_ELEMENT_3, 100.0); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':1," "'element2':0.5,'element3':{'avgcount':1,'sum':100}}}"), msg); fake_pf->finc(TEST_PERFCOUNTERS1_ELEMENT_3, 0.0); fake_pf->finc(TEST_PERFCOUNTERS1_ELEMENT_3, 25.0); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':1,'element2':0.5," "'element3':{'avgcount':3,'sum':125}}}"), msg); } enum { TEST_PERFCOUNTERS2_ELEMENT_FIRST = 400, TEST_PERFCOUNTERS2_ELEMENT_FOO, TEST_PERFCOUNTERS2_ELEMENT_BAR, TEST_PERFCOUNTERS2_ELEMENT_LAST, }; static PerfCounters* setup_test_perfcounter2(CephContext *cct) { PerfCountersBuilder bld(cct, "test_perfcounter_2", TEST_PERFCOUNTERS2_ELEMENT_FIRST, TEST_PERFCOUNTERS2_ELEMENT_LAST); bld.add_u64(TEST_PERFCOUNTERS2_ELEMENT_FOO, "foo"); bld.add_fl(TEST_PERFCOUNTERS2_ELEMENT_BAR, "bar"); return bld.create_perf_counters(); } TEST(PerfCounters, MultiplePerfCounters) { PerfCountersCollection *coll = g_ceph_context->GetPerfCountersCollection(); coll->logger_clear(); PerfCounters* fake_pf1 = setup_test_perfcounters1(g_ceph_context); PerfCounters* fake_pf2 = setup_test_perfcounter2(g_ceph_context); coll->logger_add(fake_pf1); coll->logger_add(fake_pf2); g_ceph_context->_conf->set_val_or_die("admin_socket", get_rand_socket_path()); g_ceph_context->_conf->apply_changes(NULL); AdminSocketClient client(get_rand_socket_path()); std::string msg; ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':0,'element2':0,'element3':" "{'avgcount':0,'sum':0}},'test_perfcounter_2':{'foo':0,'bar':0}}"), msg); fake_pf1->inc(TEST_PERFCOUNTERS1_ELEMENT_1); fake_pf1->inc(TEST_PERFCOUNTERS1_ELEMENT_1, 5); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':6,'element2':0,'element3':" "{'avgcount':0,'sum':0}},'test_perfcounter_2':{'foo':0,'bar':0}}"), msg); coll->logger_remove(fake_pf2); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':6,'element2':0," "'element3':{'avgcount':0,'sum':0}}}"), msg); ASSERT_EQ("", client.get_schema(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':{'type':2}," "'element2':{'type':1},'element3':{'type':5}}}"), msg); coll->logger_clear(); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ("{}", msg); } <commit_msg>perfcounters: fix unit test<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * * This 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. See file COPYING. * */ #include "common/perf_counters.h" #include "common/admin_socket_client.h" #include "common/ceph_context.h" #include "common/config.h" #include "common/errno.h" #include "common/safe_io.h" #include "test/unit.h" #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <map> #include <poll.h> #include <sstream> #include <stdint.h> #include <string.h> #include <string> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <time.h> #include <unistd.h> TEST(PerfCounters, SimpleTest) { g_ceph_context->_conf->set_val_or_die("admin_socket", get_rand_socket_path()); g_ceph_context->_conf->apply_changes(NULL); AdminSocketClient client(get_rand_socket_path()); std::string message; ASSERT_EQ("", client.get_message(&message)); ASSERT_EQ("{}", message); } enum { TEST_PERFCOUNTERS1_ELEMENT_FIRST = 200, TEST_PERFCOUNTERS1_ELEMENT_1, TEST_PERFCOUNTERS1_ELEMENT_2, TEST_PERFCOUNTERS1_ELEMENT_3, TEST_PERFCOUNTERS1_ELEMENT_LAST, }; std::string sd(const char *c) { std::string ret(c); std::string::size_type sz = ret.size(); for (std::string::size_type i = 0; i < sz; ++i) { if (ret[i] == '\'') { ret[i] = '\"'; } } return ret; } static PerfCounters* setup_test_perfcounters1(CephContext *cct) { PerfCountersBuilder bld(cct, "test_perfcounter_1", TEST_PERFCOUNTERS1_ELEMENT_FIRST, TEST_PERFCOUNTERS1_ELEMENT_LAST); bld.add_u64(TEST_PERFCOUNTERS1_ELEMENT_1, "element1"); bld.add_fl(TEST_PERFCOUNTERS1_ELEMENT_2, "element2"); bld.add_fl_avg(TEST_PERFCOUNTERS1_ELEMENT_3, "element3"); return bld.create_perf_counters(); } TEST(PerfCounters, SinglePerfCounters) { PerfCountersCollection *coll = g_ceph_context->GetPerfCountersCollection(); PerfCounters* fake_pf = setup_test_perfcounters1(g_ceph_context); coll->add(fake_pf); g_ceph_context->_conf->set_val_or_die("admin_socket", get_rand_socket_path()); g_ceph_context->_conf->apply_changes(NULL); AdminSocketClient client(get_rand_socket_path()); std::string msg; ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':0," "'element2':0,'element3':{'avgcount':0,'sum':0}}}"), msg); fake_pf->inc(TEST_PERFCOUNTERS1_ELEMENT_1); fake_pf->fset(TEST_PERFCOUNTERS1_ELEMENT_2, 0.5); fake_pf->finc(TEST_PERFCOUNTERS1_ELEMENT_3, 100.0); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':1," "'element2':0.5,'element3':{'avgcount':1,'sum':100}}}"), msg); fake_pf->finc(TEST_PERFCOUNTERS1_ELEMENT_3, 0.0); fake_pf->finc(TEST_PERFCOUNTERS1_ELEMENT_3, 25.0); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':1,'element2':0.5," "'element3':{'avgcount':3,'sum':125}}}"), msg); } enum { TEST_PERFCOUNTERS2_ELEMENT_FIRST = 400, TEST_PERFCOUNTERS2_ELEMENT_FOO, TEST_PERFCOUNTERS2_ELEMENT_BAR, TEST_PERFCOUNTERS2_ELEMENT_LAST, }; static PerfCounters* setup_test_perfcounter2(CephContext *cct) { PerfCountersBuilder bld(cct, "test_perfcounter_2", TEST_PERFCOUNTERS2_ELEMENT_FIRST, TEST_PERFCOUNTERS2_ELEMENT_LAST); bld.add_u64(TEST_PERFCOUNTERS2_ELEMENT_FOO, "foo"); bld.add_fl(TEST_PERFCOUNTERS2_ELEMENT_BAR, "bar"); return bld.create_perf_counters(); } TEST(PerfCounters, MultiplePerfCounters) { PerfCountersCollection *coll = g_ceph_context->GetPerfCountersCollection(); coll->clear(); PerfCounters* fake_pf1 = setup_test_perfcounters1(g_ceph_context); PerfCounters* fake_pf2 = setup_test_perfcounter2(g_ceph_context); coll->add(fake_pf1); coll->add(fake_pf2); g_ceph_context->_conf->set_val_or_die("admin_socket", get_rand_socket_path()); g_ceph_context->_conf->apply_changes(NULL); AdminSocketClient client(get_rand_socket_path()); std::string msg; ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':0,'element2':0,'element3':" "{'avgcount':0,'sum':0}},'test_perfcounter_2':{'foo':0,'bar':0}}"), msg); fake_pf1->inc(TEST_PERFCOUNTERS1_ELEMENT_1); fake_pf1->inc(TEST_PERFCOUNTERS1_ELEMENT_1, 5); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':6,'element2':0,'element3':" "{'avgcount':0,'sum':0}},'test_perfcounter_2':{'foo':0,'bar':0}}"), msg); coll->remove(fake_pf2); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':6,'element2':0," "'element3':{'avgcount':0,'sum':0}}}"), msg); ASSERT_EQ("", client.get_schema(&msg)); ASSERT_EQ(sd("{'test_perfcounter_1':{'element1':{'type':2}," "'element2':{'type':1},'element3':{'type':5}}}"), msg); coll->clear(); ASSERT_EQ("", client.get_message(&msg)); ASSERT_EQ("{}", msg); } <|endoftext|>
<commit_before>/* Copyright (c) 2012, Paul Houx All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cinder/app/AppBasic.h" #include "cinder/app/RendererGl.h" #include "cinder/AxisAlignedBox.h" #include "cinder/Frustum.h" #include "cinder/MayaCamUI.h" #include "cinder/ObjLoader.h" #include "cinder/Text.h" #include "cinder/Rand.h" #include "cinder/Timeline.h" #include "cinder/gl/GlslProg.h" #include "cinder/gl/Batch.h" #include "cinder/gl/Context.h" #include "CullableObject.h" using namespace ci; using namespace ci::app; using namespace std; class FrustumCullingReduxApp : public AppBasic { public: void prepareSettings( Settings *settings ); void setup(); void update(); void draw(); void toggleCullableFov(); void drawCullableFov(); void mouseDown( MouseEvent event ); void mouseDrag( MouseEvent event ); void keyDown( KeyEvent event ); protected: //! load the heart shaped mesh void loadObject(); //! draws a grid to visualize the ground plane void drawGrid( float size = 100.0f, float step = 10.0f ); //! toggles vertical sync on both Windows and Macs void toggleVerticalSync(); //! renders the help text void renderHelpToTexture(); protected: static const int NUM_OBJECTS = 1500; //! keep track of time double mCurrentSeconds; //! flags bool bPerformCulling; bool bDrawEstimatedBoundingBoxes; bool bDrawPreciseBoundingBoxes; bool bShowHelp; bool mShowRevealingFov; Anim<float> mCullingFov; ci::TriMeshRef mTriMesh; gl::BatchRef mBatch; //! caches the heart's bounding box in object space coordinates AxisAlignedBox3f mObjectBoundingBox; //! render assets gl::GlslProgRef mShader; //! objects std::list<CullableObjectRef> mObjects; //! camera MayaCamUI mMayaCam; CameraPersp mRenderCam; //! help text gl::Texture2dRef mHelp; }; void FrustumCullingReduxApp::prepareSettings(Settings *settings) { //! setup our window settings->setWindowSize( 1200, 675 ); settings->setTitle( "Frustum Culling Redux" ); //! set the frame rate to something very high, so we can //! easily see the effect frustum culling has on performance. //! Disable vertical sync to achieve the actual frame rate. settings->setFrameRate( 300 ); } void FrustumCullingReduxApp::setup() { //! intialize settings bPerformCulling = true; bDrawEstimatedBoundingBoxes = false; bDrawPreciseBoundingBoxes = false; mShowRevealingFov = false; bShowHelp = true; //! render help texture renderHelpToTexture(); //! load and compile shader try { mShader = gl::GlslProg::create( loadAsset("shaders/phong.vert"), loadAsset("shaders/phong.frag") ); } catch( const std::exception &e ) { app::console() << "Could not load and compile shader:" << e.what() << std::endl; } //! setup material // we set it up once because all of our objects will // share the same values mShader->uniform( "uDiffuse", Color( 1.0f, 0.0f, 0.0f ) ); mShader->uniform( "uSpecular", Color( 1.0f, 1.0f, 1.0f ) ); mShader->uniform( "uShininess", 50.0f ); //! load assets loadObject(); //! create a few hearts Rand::randomize(); mObjects.resize( NUM_OBJECTS ); for( auto & obj : mObjects ) { vec3 p( Rand::randFloat( -2000.0f, 2000.0f ), 0.0f, Rand::randFloat( -2000.0f, 2000.0f ) ); vec3 r( 0.0f, Rand::randFloat( -360.0f, 360.0f ), 0.0f ); vec3 s( 50.10f, 50.10f, 50.10f ); obj = CullableObjectRef( new CullableObject( mBatch ) ); obj->setTransform( p, r, s ); } //! setup cameras mCullingFov = 60; mRenderCam.setPerspective( mCullingFov, getWindowAspectRatio(), 10.0f, 10000.0f ); mRenderCam.lookAt( vec3( 200.0f ), vec3( 0.0f ) ); mMayaCam.setCurrentCam( mRenderCam ); //! track current time so we can calculate elapsed time mCurrentSeconds = getElapsedSeconds(); } void FrustumCullingReduxApp::update() { //! calculate elapsed time double elapsed = getElapsedSeconds() - mCurrentSeconds; mCurrentSeconds += elapsed; //! perform frustum culling ********************************************************************************** // Set the current culling field of view. float originalFov = mRenderCam.getFov(); // If mShowRevealingFov = true, this will narrow the cam's FOV so that you can see the culling effect mRenderCam.setFov( mCullingFov ); Frustumf visibleWorld( mRenderCam ); for( auto & obj : mObjects ) { // update object (so it rotates slowly around its axis) obj->update(elapsed); if(bPerformCulling) { // create a fast approximation of the world space bounding box by transforming the // eight corners of the object space bounding box and using them to create a new axis aligned bounding box AxisAlignedBox3f worldBoundingBox = mObjectBoundingBox.transformed( obj->getTransform() ); // check if the bounding box intersects the visible world obj->setCulled( ! visibleWorld.intersects( worldBoundingBox ) ); } else { obj->setCulled( false ); } } // Set FOV to original mRenderCam.setFov( originalFov ); } void FrustumCullingReduxApp::draw() { // clear the window gl::clear( Color(0.25f, 0.25f, 0.25f) ); { // setup camera gl::ScopedMatrices scopeMatrix; gl::setMatrices( mRenderCam ); gl::ScopedState scopeState( GL_CULL_FACE, true ); gl::enableDepthRead(); gl::enableDepthWrite(); { gl::ScopedGlslProg scopeGlsl( mShader ); for( auto & obj : mObjects ) obj->draw(); } // draw helper objects gl::drawCoordinateFrame(100.0f, 5.0f, 2.0f); AxisAlignedBox3f worldBoundingBox; for( auto & obj : mObjects ) { if(bDrawEstimatedBoundingBoxes) { // create a fast approximation of the world space bounding box by transforming the // eight corners and using them to create a new axis aligned bounding box worldBoundingBox = mObjectBoundingBox.transformed( obj->getTransform() ); if( ! obj->isCulled() ) gl::color( Color( 0, 1, 1 ) ); else gl::color( Color( 1, 0.5f, 0 ) ); gl::drawStrokedCube( worldBoundingBox ); } if(bDrawPreciseBoundingBoxes && ! obj->isCulled()) { // you can see how much the approximated bounding boxes differ // from the precise ones by enabling this code worldBoundingBox = mTriMesh->calcBoundingBox( obj->getTransform() ); gl::color( Color(1, 1, 0) ); gl::drawStrokedCube( worldBoundingBox ); } } drawGrid(2000.0f, 25.0f); drawCullableFov(); // disable 3D rendering gl::disableDepthWrite(); gl::disableDepthRead(); } // render help if(bShowHelp && mHelp) { gl::enableAlphaBlending(); gl::color( Color::white() ); gl::draw( mHelp ); gl::disableAlphaBlending(); } } void FrustumCullingReduxApp::mouseDown( MouseEvent event ) { mMayaCam.mouseDown( event.getPos() ); } void FrustumCullingReduxApp::mouseDrag( MouseEvent event ) { mMayaCam.mouseDrag( event.getPos(), event.isLeftDown(), event.isMiddleDown(), event.isRightDown() ); mRenderCam = mMayaCam.getCamera(); } void FrustumCullingReduxApp::keyDown( KeyEvent event ) { switch( event.getCode() ) { case KeyEvent::KEY_ESCAPE: quit(); break; case KeyEvent::KEY_b: if(event.isShiftDown()) bDrawPreciseBoundingBoxes = ! bDrawPreciseBoundingBoxes; else bDrawEstimatedBoundingBoxes = ! bDrawEstimatedBoundingBoxes; break; case KeyEvent::KEY_c: bPerformCulling = !bPerformCulling; break; case KeyEvent::KEY_f: { bool verticalSyncEnabled = gl::isVerticalSyncEnabled(); setFullScreen( ! isFullScreen() ); gl::enableVerticalSync( verticalSyncEnabled ); } break; case KeyEvent::KEY_h: bShowHelp = !bShowHelp; break; case KeyEvent::KEY_v: toggleVerticalSync(); break; case KeyEvent::KEY_SPACE: toggleCullableFov(); break; } // update info renderHelpToTexture(); } void FrustumCullingReduxApp::toggleCullableFov() { // when this is on, it reduces the field of view for culling only, so that you can see the culling in action. mShowRevealingFov = ! mShowRevealingFov; float fov = mShowRevealingFov ? 40 : 60; timeline().apply( &mCullingFov, fov, 0.6f, EaseInOutCubic() ); } void FrustumCullingReduxApp::drawCullableFov() { // Reset the field of view once again to visualize // the actual window we're using to cull with. gl::color( Color(1, 1, 1) ); gl::clear( GL_DEPTH_BUFFER_BIT ); // This visualizes the camera's viewport change for the culling field of view. float cullable = mCullingFov / 60.0f; gl::ScopedMatrices scopeMat; gl::setMatricesWindow( getWindowSize() ); gl::translate( getWindowCenter() ); gl::scale( vec3( cullable * getWindowCenter().x, cullable * getWindowCenter().y, 1.0 ) ); gl::drawStrokedRect( Rectf( -1, -1, 1, 1 )); } void FrustumCullingReduxApp::loadObject() { // We first convert our obj to a trimesh mTriMesh = TriMesh::create( ObjLoader( loadAsset("models/heart.obj") ) ); // Then use our trimesh and our shader to create a batch mBatch = gl::Batch::create( *mTriMesh, mShader ); // We then use trimesh to calculate the Bounding Box mObjectBoundingBox = mTriMesh->calcBoundingBox(); } void FrustumCullingReduxApp::drawGrid(float size, float step) { gl::color( Colorf( 0.2f, 0.2f, 0.2f ) ); gl::begin( GL_LINES ); for(float i=-size;i<=size;i+=step) { gl::vertex( vec3( i, 0.0f, -size ) ); gl::vertex( vec3( i, 0.0f, size ) ); gl::vertex( vec3( -size, 0.0f, i ) ); gl::vertex( vec3( size, 0.0f, i ) ); } gl::end(); } void FrustumCullingReduxApp::toggleVerticalSync() { gl::enableVerticalSync( ! gl::isVerticalSyncEnabled() ); } void FrustumCullingReduxApp::renderHelpToTexture() { TextLayout layout; layout.setFont( Font("Arial", 18) ); layout.setColor( ColorA( 1.0f, 1.0f, 1.0f, 1.0f ) ); layout.setLeadingOffset( 3.0f ); layout.clear( ColorA::gray( 0.2f, 0.5f ) ); if( bPerformCulling ) layout.addLine( "(C) Toggle culling (currently ON)" ); else layout.addLine( "(C) Toggle culling (currently OFF)" ); if( bDrawEstimatedBoundingBoxes ) layout.addLine( "(B) Toggle estimated bounding boxes (currently ON)" ); else layout.addLine( "(B) Toggle estimated bounding boxes (currently OFF)" ); if( bDrawPreciseBoundingBoxes ) layout.addLine( "(B)+(Shift) Toggle precise bounding boxes (currently ON)" ); else layout.addLine( "(B)+(Shift) Toggle precise bounding boxes (currently OFF)" ); if( mShowRevealingFov ) layout.addLine("(Space) Toggle reveal culling (currently ON)"); else layout.addLine("(Space) Toggle reveal culling (currently OFF)"); if( gl::isVerticalSyncEnabled() ) layout.addLine( "(V) Toggle vertical sync (currently ON)" ); else layout.addLine( "(V) Toggle vertical sync (currently OFF)" ); layout.addLine( "(H) Toggle this help panel" ); mHelp = gl::Texture::create( layout.render( true, false ) ); } CINDER_APP_BASIC( FrustumCullingReduxApp, RendererGl )<commit_msg>removed gl::drawCoordinateFrame() call; it wasn’t very effective amongst the crowded hearts, caused flickering, and light + grid was a good indication of the orientation anyway<commit_after>/* Copyright (c) 2012, Paul Houx All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cinder/app/AppBasic.h" #include "cinder/app/RendererGl.h" #include "cinder/AxisAlignedBox.h" #include "cinder/Frustum.h" #include "cinder/MayaCamUI.h" #include "cinder/ObjLoader.h" #include "cinder/Text.h" #include "cinder/Rand.h" #include "cinder/Timeline.h" #include "cinder/gl/GlslProg.h" #include "cinder/gl/Batch.h" #include "cinder/gl/Context.h" #include "CullableObject.h" using namespace ci; using namespace ci::app; using namespace std; class FrustumCullingReduxApp : public AppBasic { public: void prepareSettings( Settings *settings ); void setup(); void update(); void draw(); void toggleCullableFov(); void drawCullableFov(); void mouseDown( MouseEvent event ); void mouseDrag( MouseEvent event ); void keyDown( KeyEvent event ); protected: //! load the heart shaped mesh void loadObject(); //! draws a grid to visualize the ground plane void drawGrid( float size = 100.0f, float step = 10.0f ); //! toggles vertical sync on both Windows and Macs void toggleVerticalSync(); //! renders the help text void renderHelpToTexture(); protected: static const int NUM_OBJECTS = 1500; //! keep track of time double mCurrentSeconds; //! flags bool bPerformCulling; bool bDrawEstimatedBoundingBoxes; bool bDrawPreciseBoundingBoxes; bool bShowHelp; bool mShowRevealingFov; Anim<float> mCullingFov; ci::TriMeshRef mTriMesh; gl::BatchRef mBatch; //! caches the heart's bounding box in object space coordinates AxisAlignedBox3f mObjectBoundingBox; //! render assets gl::GlslProgRef mShader; //! objects std::list<CullableObjectRef> mObjects; //! camera MayaCamUI mMayaCam; CameraPersp mRenderCam; //! help text gl::Texture2dRef mHelp; }; void FrustumCullingReduxApp::prepareSettings(Settings *settings) { //! setup our window settings->setWindowSize( 1200, 675 ); settings->setTitle( "Frustum Culling Redux" ); //! set the frame rate to something very high, so we can //! easily see the effect frustum culling has on performance. //! Disable vertical sync to achieve the actual frame rate. settings->setFrameRate( 300 ); } void FrustumCullingReduxApp::setup() { //! intialize settings bPerformCulling = true; bDrawEstimatedBoundingBoxes = false; bDrawPreciseBoundingBoxes = false; mShowRevealingFov = false; bShowHelp = true; //! render help texture renderHelpToTexture(); //! load and compile shader try { mShader = gl::GlslProg::create( loadAsset("shaders/phong.vert"), loadAsset("shaders/phong.frag") ); } catch( const std::exception &e ) { app::console() << "Could not load and compile shader:" << e.what() << std::endl; } //! setup material // we set it up once because all of our objects will // share the same values mShader->uniform( "uDiffuse", Color( 1.0f, 0.0f, 0.0f ) ); mShader->uniform( "uSpecular", Color( 1.0f, 1.0f, 1.0f ) ); mShader->uniform( "uShininess", 50.0f ); //! load assets loadObject(); //! create a few hearts Rand::randomize(); mObjects.resize( NUM_OBJECTS ); for( auto & obj : mObjects ) { vec3 p( Rand::randFloat( -2000.0f, 2000.0f ), 0.0f, Rand::randFloat( -2000.0f, 2000.0f ) ); vec3 r( 0.0f, Rand::randFloat( -360.0f, 360.0f ), 0.0f ); vec3 s( 50.10f, 50.10f, 50.10f ); obj = CullableObjectRef( new CullableObject( mBatch ) ); obj->setTransform( p, r, s ); } //! setup cameras mCullingFov = 60; mRenderCam.setPerspective( mCullingFov, getWindowAspectRatio(), 10.0f, 10000.0f ); mRenderCam.lookAt( vec3( 200.0f ), vec3( 0.0f ) ); mMayaCam.setCurrentCam( mRenderCam ); //! track current time so we can calculate elapsed time mCurrentSeconds = getElapsedSeconds(); } void FrustumCullingReduxApp::update() { //! calculate elapsed time double elapsed = getElapsedSeconds() - mCurrentSeconds; mCurrentSeconds += elapsed; //! perform frustum culling ********************************************************************************** // Set the current culling field of view. float originalFov = mRenderCam.getFov(); // If mShowRevealingFov = true, this will narrow the cam's FOV so that you can see the culling effect mRenderCam.setFov( mCullingFov ); Frustumf visibleWorld( mRenderCam ); for( auto & obj : mObjects ) { // update object (so it rotates slowly around its axis) obj->update(elapsed); if(bPerformCulling) { // create a fast approximation of the world space bounding box by transforming the // eight corners of the object space bounding box and using them to create a new axis aligned bounding box AxisAlignedBox3f worldBoundingBox = mObjectBoundingBox.transformed( obj->getTransform() ); // check if the bounding box intersects the visible world obj->setCulled( ! visibleWorld.intersects( worldBoundingBox ) ); } else { obj->setCulled( false ); } } // Set FOV to original mRenderCam.setFov( originalFov ); } void FrustumCullingReduxApp::draw() { // clear the window gl::clear( Color(0.25f, 0.25f, 0.25f) ); { // setup camera gl::ScopedMatrices scopeMatrix; gl::setMatrices( mRenderCam ); gl::ScopedState scopeState( GL_CULL_FACE, true ); gl::enableDepthRead(); gl::enableDepthWrite(); { gl::ScopedGlslProg scopeGlsl( mShader ); for( auto & obj : mObjects ) obj->draw(); } AxisAlignedBox3f worldBoundingBox; for( auto & obj : mObjects ) { if(bDrawEstimatedBoundingBoxes) { // create a fast approximation of the world space bounding box by transforming the // eight corners and using them to create a new axis aligned bounding box worldBoundingBox = mObjectBoundingBox.transformed( obj->getTransform() ); if( ! obj->isCulled() ) gl::color( Color( 0, 1, 1 ) ); else gl::color( Color( 1, 0.5f, 0 ) ); gl::drawStrokedCube( worldBoundingBox ); } if(bDrawPreciseBoundingBoxes && ! obj->isCulled()) { // you can see how much the approximated bounding boxes differ // from the precise ones by enabling this code worldBoundingBox = mTriMesh->calcBoundingBox( obj->getTransform() ); gl::color( Color(1, 1, 0) ); gl::drawStrokedCube( worldBoundingBox ); } } drawGrid(2000.0f, 25.0f); drawCullableFov(); // disable 3D rendering gl::disableDepthWrite(); gl::disableDepthRead(); } // render help if(bShowHelp && mHelp) { gl::enableAlphaBlending(); gl::color( Color::white() ); gl::draw( mHelp ); gl::disableAlphaBlending(); } } void FrustumCullingReduxApp::mouseDown( MouseEvent event ) { mMayaCam.mouseDown( event.getPos() ); } void FrustumCullingReduxApp::mouseDrag( MouseEvent event ) { mMayaCam.mouseDrag( event.getPos(), event.isLeftDown(), event.isMiddleDown(), event.isRightDown() ); mRenderCam = mMayaCam.getCamera(); } void FrustumCullingReduxApp::keyDown( KeyEvent event ) { switch( event.getCode() ) { case KeyEvent::KEY_ESCAPE: quit(); break; case KeyEvent::KEY_b: if(event.isShiftDown()) bDrawPreciseBoundingBoxes = ! bDrawPreciseBoundingBoxes; else bDrawEstimatedBoundingBoxes = ! bDrawEstimatedBoundingBoxes; break; case KeyEvent::KEY_c: bPerformCulling = !bPerformCulling; break; case KeyEvent::KEY_f: { bool verticalSyncEnabled = gl::isVerticalSyncEnabled(); setFullScreen( ! isFullScreen() ); gl::enableVerticalSync( verticalSyncEnabled ); } break; case KeyEvent::KEY_h: bShowHelp = !bShowHelp; break; case KeyEvent::KEY_v: toggleVerticalSync(); break; case KeyEvent::KEY_SPACE: toggleCullableFov(); break; } // update info renderHelpToTexture(); } void FrustumCullingReduxApp::toggleCullableFov() { // when this is on, it reduces the field of view for culling only, so that you can see the culling in action. mShowRevealingFov = ! mShowRevealingFov; float fov = mShowRevealingFov ? 40 : 60; timeline().apply( &mCullingFov, fov, 0.6f, EaseInOutCubic() ); } void FrustumCullingReduxApp::drawCullableFov() { // Reset the field of view once again to visualize // the actual window we're using to cull with. gl::color( Color(1, 1, 1) ); gl::clear( GL_DEPTH_BUFFER_BIT ); // This visualizes the camera's viewport change for the culling field of view. float cullable = mCullingFov / 60.0f; gl::ScopedMatrices scopeMat; gl::setMatricesWindow( getWindowSize() ); gl::translate( getWindowCenter() ); gl::scale( vec3( cullable * getWindowCenter().x, cullable * getWindowCenter().y, 1.0 ) ); gl::drawStrokedRect( Rectf( -1, -1, 1, 1 )); } void FrustumCullingReduxApp::loadObject() { // We first convert our obj to a trimesh mTriMesh = TriMesh::create( ObjLoader( loadAsset("models/heart.obj") ) ); // Then use our trimesh and our shader to create a batch mBatch = gl::Batch::create( *mTriMesh, mShader ); // We then use trimesh to calculate the Bounding Box mObjectBoundingBox = mTriMesh->calcBoundingBox(); } void FrustumCullingReduxApp::drawGrid(float size, float step) { gl::color( Colorf( 0.2f, 0.2f, 0.2f ) ); gl::begin( GL_LINES ); for(float i=-size;i<=size;i+=step) { gl::vertex( vec3( i, 0.0f, -size ) ); gl::vertex( vec3( i, 0.0f, size ) ); gl::vertex( vec3( -size, 0.0f, i ) ); gl::vertex( vec3( size, 0.0f, i ) ); } gl::end(); } void FrustumCullingReduxApp::toggleVerticalSync() { gl::enableVerticalSync( ! gl::isVerticalSyncEnabled() ); } void FrustumCullingReduxApp::renderHelpToTexture() { TextLayout layout; layout.setFont( Font("Arial", 18) ); layout.setColor( ColorA( 1.0f, 1.0f, 1.0f, 1.0f ) ); layout.setLeadingOffset( 3.0f ); layout.clear( ColorA::gray( 0.2f, 0.5f ) ); if( bPerformCulling ) layout.addLine( "(C) Toggle culling (currently ON)" ); else layout.addLine( "(C) Toggle culling (currently OFF)" ); if( bDrawEstimatedBoundingBoxes ) layout.addLine( "(B) Toggle estimated bounding boxes (currently ON)" ); else layout.addLine( "(B) Toggle estimated bounding boxes (currently OFF)" ); if( bDrawPreciseBoundingBoxes ) layout.addLine( "(B)+(Shift) Toggle precise bounding boxes (currently ON)" ); else layout.addLine( "(B)+(Shift) Toggle precise bounding boxes (currently OFF)" ); if( mShowRevealingFov ) layout.addLine("(Space) Toggle reveal culling (currently ON)"); else layout.addLine("(Space) Toggle reveal culling (currently OFF)"); if( gl::isVerticalSyncEnabled() ) layout.addLine( "(V) Toggle vertical sync (currently ON)" ); else layout.addLine( "(V) Toggle vertical sync (currently OFF)" ); layout.addLine( "(H) Toggle this help panel" ); mHelp = gl::Texture::create( layout.render( true, false ) ); } CINDER_APP_BASIC( FrustumCullingReduxApp, RendererGl )<|endoftext|>
<commit_before>#include "cinder/app/AppBasic.h" #include "cinder/app/RendererGl.h" #include "cinder/Path2d.h" #include "cinder/gl/gl.h" #include <vector> using namespace ci; using namespace ci::app; using namespace std; class Path2dApp : public AppBasic { public: Path2dApp() : mTrackedPoint( -1 ) {} void mouseDown( MouseEvent event ); void mouseUp( MouseEvent event ); void mouseDrag( MouseEvent event ); void keyDown( KeyEvent event ); void draw(); Path2d mPath; int mTrackedPoint; }; void Path2dApp::mouseDown( MouseEvent event ) { if( event.isLeftDown() ) { // line if( mPath.empty() ) { mPath.moveTo( event.getPos() ); mTrackedPoint = 0; } else mPath.lineTo( event.getPos() ); } console() << mPath << std::endl; console() << "Length: " << mPath.calcLength() << std::endl; } void Path2dApp::mouseDrag( MouseEvent event ) { if( mTrackedPoint >= 0 ) { mPath.setPoint( mTrackedPoint, event.getPos() ); } else { // first bit of dragging, so switch our line to a cubic or a quad if Shift is down // we want to preserve the end of our current line, because it will still be the end of our curve Vec2f endPt = mPath.getPoint( mPath.getNumPoints() - 1 ); // and now we'll delete that line and replace it with a curve mPath.removeSegment( mPath.getNumSegments() - 1 ); Path2d::SegmentType prevType = ( mPath.getNumSegments() == 0 ) ? Path2d::MOVETO : mPath.getSegmentType( mPath.getNumSegments() - 1 ); if( event.isShiftDown() || prevType == Path2d::MOVETO ) { // add a quadratic curve segment mPath.quadTo( event.getPos(), endPt ); } else { // add a cubic curve segment Vec2f tan1; if( prevType == Path2d::CUBICTO ) { // if the segment before was cubic, let's replicate and reverse its tangent Vec2f prevDelta = mPath.getPoint( mPath.getNumPoints() - 2 ) - mPath.getPoint( mPath.getNumPoints() - 1 ); tan1 = mPath.getPoint( mPath.getNumPoints() - 1 ) - prevDelta; } else if( prevType == Path2d::QUADTO ) { // we can figure out what the equivalent cubic tangent would be using a little math Vec2f quadTangent = mPath.getPoint( mPath.getNumPoints() - 2 ); Vec2f quadEnd = mPath.getPoint( mPath.getNumPoints() - 1 ); Vec2f prevDelta = ( quadTangent + ( quadEnd - quadTangent ) / 3 ) - quadEnd; tan1 = quadEnd - prevDelta; } else tan1 = mPath.getPoint( mPath.getNumPoints() - 1 ); mPath.curveTo( tan1, event.getPos(), endPt ); } // our second-to-last point is the tangent next to the end, and we'll track that mTrackedPoint = mPath.getNumPoints() - 2; } console() << mPath << std::endl; console() << "Length: " << mPath.calcLength() << std::endl; } void Path2dApp::mouseUp( MouseEvent event ) { mTrackedPoint = -1; } void Path2dApp::keyDown( KeyEvent event ) { if( event.getChar() == 'x' ) mPath.clear(); } void Path2dApp::draw() { gl::clear( Color( 0.0f, 0.1f, 0.2f ) ); gl::enableAlphaBlending(); // draw the control points gl::color( Color( 1, 1, 0 ) ); for( size_t p = 0; p < mPath.getNumPoints(); ++p ) gl::drawSolidCircle( mPath.getPoint( p ), 2.5f ); // draw the precise bounding box if( mPath.getNumSegments() > 1 ) { gl::color( ColorA( 0, 1, 1, 0.2f ) ); gl::drawSolidRect( mPath.calcPreciseBoundingBox() ); } // draw the curve itself gl::color( Color( 1.0f, 0.5f, 0.25f ) ); gl::draw( mPath ); if( mPath.getNumSegments() > 1 ) { // draw some tangents gl::color( Color( 0.2f, 0.9f, 0.2f ) ); for( float t = 0; t < 1; t += 0.2f ) gl::drawLine( mPath.getPosition( t ), mPath.getPosition( t ) + mPath.getTangent( t ).normalized() * 80 ); // draw circles at 1/4, 2/4 and 3/4 the length gl::color( ColorA( 0.2f, 0.9f, 0.9f, 0.5f ) ); for( float t = 0.25f; t < 1.0f; t += 0.25f ) gl::drawSolidCircle( mPath.getPosition( mPath.calcNormalizedTime( t ) ), 5.0f ); } } CINDER_APP_BASIC( Path2dApp, RendererGl ) <commit_msg>Math changes to bezierPath sample.<commit_after>#include "cinder/app/AppBasic.h" #include "cinder/app/RendererGl.h" #include "cinder/Path2d.h" #include "cinder/gl/gl.h" #include <vector> using namespace ci; using namespace ci::app; using namespace std; class Path2dApp : public AppBasic { public: Path2dApp() : mTrackedPoint( -1 ) {} void mouseDown( MouseEvent event ); void mouseUp( MouseEvent event ); void mouseDrag( MouseEvent event ); void keyDown( KeyEvent event ); void draw(); Path2d mPath; int mTrackedPoint; }; void Path2dApp::mouseDown( MouseEvent event ) { if( event.isLeftDown() ) { // line if( mPath.empty() ) { mPath.moveTo( event.getPos() ); mTrackedPoint = 0; } else mPath.lineTo( event.getPos() ); } console() << mPath << std::endl; console() << "Length: " << mPath.calcLength() << std::endl; } void Path2dApp::mouseDrag( MouseEvent event ) { if( mTrackedPoint >= 0 ) { mPath.setPoint( mTrackedPoint, event.getPos() ); } else { // first bit of dragging, so switch our line to a cubic or a quad if Shift is down // we want to preserve the end of our current line, because it will still be the end of our curve Vec2f endPt = mPath.getPoint( mPath.getNumPoints() - 1 ); // and now we'll delete that line and replace it with a curve mPath.removeSegment( mPath.getNumSegments() - 1 ); Path2d::SegmentType prevType = ( mPath.getNumSegments() == 0 ) ? Path2d::MOVETO : mPath.getSegmentType( mPath.getNumSegments() - 1 ); if( event.isShiftDown() || prevType == Path2d::MOVETO ) { // add a quadratic curve segment mPath.quadTo( event.getPos(), endPt ); } else { // add a cubic curve segment Vec2f tan1; if( prevType == Path2d::CUBICTO ) { // if the segment before was cubic, let's replicate and reverse its tangent Vec2f prevDelta = mPath.getPoint( mPath.getNumPoints() - 2 ) - mPath.getPoint( mPath.getNumPoints() - 1 ); tan1 = mPath.getPoint( mPath.getNumPoints() - 1 ) - prevDelta; } else if( prevType == Path2d::QUADTO ) { // we can figure out what the equivalent cubic tangent would be using a little math Vec2f quadTangent = mPath.getPoint( mPath.getNumPoints() - 2 ); Vec2f quadEnd = mPath.getPoint( mPath.getNumPoints() - 1 ); Vec2f prevDelta = ( quadTangent + ( quadEnd - quadTangent ) / 3.0f ) - quadEnd; tan1 = quadEnd - prevDelta; } else tan1 = mPath.getPoint( mPath.getNumPoints() - 1 ); mPath.curveTo( tan1, event.getPos(), endPt ); } // our second-to-last point is the tangent next to the end, and we'll track that mTrackedPoint = mPath.getNumPoints() - 2; } console() << mPath << std::endl; console() << "Length: " << mPath.calcLength() << std::endl; } void Path2dApp::mouseUp( MouseEvent event ) { mTrackedPoint = -1; } void Path2dApp::keyDown( KeyEvent event ) { if( event.getChar() == 'x' ) mPath.clear(); } void Path2dApp::draw() { gl::clear( Color( 0.0f, 0.1f, 0.2f ) ); gl::enableAlphaBlending(); // draw the control points gl::color( Color( 1, 1, 0 ) ); for( size_t p = 0; p < mPath.getNumPoints(); ++p ) gl::drawSolidCircle( mPath.getPoint( p ), 2.5f ); // draw the precise bounding box if( mPath.getNumSegments() > 1 ) { gl::color( ColorA( 0, 1, 1, 0.2f ) ); gl::drawSolidRect( mPath.calcPreciseBoundingBox() ); } // draw the curve itself gl::color( Color( 1.0f, 0.5f, 0.25f ) ); gl::draw( mPath ); if( mPath.getNumSegments() > 1 ) { // draw some tangents gl::color( Color( 0.2f, 0.9f, 0.2f ) ); for( float t = 0; t < 1; t += 0.2f ) gl::drawLine( mPath.getPosition( t ), mPath.getPosition( t ) + normalize( mPath.getTangent( t ) ) * 80.0f ); // draw circles at 1/4, 2/4 and 3/4 the length gl::color( ColorA( 0.2f, 0.9f, 0.9f, 0.5f ) ); for( float t = 0.25f; t < 1.0f; t += 0.25f ) gl::drawSolidCircle( mPath.getPosition( mPath.calcNormalizedTime( t ) ), 5.0f ); } } CINDER_APP_BASIC( Path2dApp, RendererGl ) <|endoftext|>
<commit_before>/* Copyright 2016 Andreas Bjerkeholt 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 <iostream> #include <SDL.h> #include <SDL_ttf.h> #include <SDL_mixer.h> #include "ScreenSystem/ScreenManager.h" #include "Screens/ScreenBackgroundImage.h" #include "Screens/ScreenMenu.h" #include "Screens/ScreenTest.h" #include "Screens/ScreenMessageDialog.h" #include "Screens/ScreenError.h" #include "ThemeManager.h" #include "global.h" #include "HomeDirectory.h" #include <string> #include "utils.h" #ifdef UNIX #include <unistd.h> #include <stdlib.h> #endif using namespace std; bool SDLInited = false; SDL_Window *win = NULL; SDL_Renderer *ren = NULL; ScreenManager* screenManager = NULL; bool _resetFrameSkip = false; bool debugViewBounds = false; bool isLauncher = false; bool launchFailed = false; bool dontUseThemeInConfig = false; bool initializeSDL() { #ifdef UNIX // Avoid the framebuffer being cleared on exit on the GCW Zero setenv("SDL_FBCON_DONT_CLEAR", "1", 0); #endif if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "SDL_Init error: " << SDL_GetError() << std::endl; return false; } SDLInited = true; win = SDL_CreateWindow("ExLauncher", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 320, 240, SDL_WINDOW_SHOWN); if (win == NULL) { std::cout << SDL_GetError() << std::endl; return false; } ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE); if (ren == NULL) { std::cout << SDL_GetError() << std::endl; return false; } SDL_RendererInfo renInfo; if (SDL_GetRendererInfo(ren, &renInfo) < 0) { std::cout << "Unable to query renderer" << std::endl; return false; } /*if ((renInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) { std::cout << "Renderer does not support render targets" << std::endl; return false; }*/ if (TTF_Init() != 0) { std::cout << TTF_GetError() << std::endl; return false; } int mixFlags = MIX_INIT_OGG; if ((Mix_Init(mixFlags) & mixFlags) != mixFlags) { std::cout << Mix_GetError() << std::endl; return false; } if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) == -1) { std::cout << Mix_GetError() << std::endl; return false; } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"); return true; } void terminateSDL() { int audioTimesOpened, frequency, channels; Uint16 format; audioTimesOpened = Mix_QuerySpec(&frequency, &format, &channels); while (audioTimesOpened > 0) { Mix_CloseAudio(); audioTimesOpened--; } while (Mix_Init(0)) Mix_Quit(); if (TTF_WasInit()) { TTF_Quit(); } if (ren != NULL) { SDL_DestroyRenderer(ren); ren = NULL; } if (win != NULL) { SDL_DestroyWindow(win); win = NULL; } //if (SDL_WasInit(0) > 0) // FIXME TEST if (SDLInited) { SDL_Quit(); SDLInited = false; } #ifdef UNIX unsetenv("SDL_FBCON_DONT_CLEAR"); #endif } void setKeyBindings() { int gameKeys[GAMEKEY_MAX]; gameKeys[GAMEKEY_UP] = SDL_SCANCODE_UP; gameKeys[GAMEKEY_LEFT] = SDL_SCANCODE_LEFT; gameKeys[GAMEKEY_RIGHT] = SDL_SCANCODE_RIGHT; gameKeys[GAMEKEY_DOWN] = SDL_SCANCODE_DOWN; gameKeys[GAMEKEY_A] = SDL_SCANCODE_LCTRL; gameKeys[GAMEKEY_B] = SDL_SCANCODE_LALT; gameKeys[GAMEKEY_X] = SDL_SCANCODE_SPACE; gameKeys[GAMEKEY_Y] = SDL_SCANCODE_LSHIFT; gameKeys[GAMEKEY_START] = SDL_SCANCODE_RETURN; gameKeys[GAMEKEY_SELECT] = SDL_SCANCODE_ESCAPE; gameKeys[GAMEKEY_TRIGGER_L] = SDL_SCANCODE_TAB; gameKeys[GAMEKEY_TRIGGER_R] = SDL_SCANCODE_BACKSPACE; screenManager->SetGameKeyBindings(gameKeys, GAMEKEY_MAX); } void parseArguments(int argc, char **argv) { for (int i = 1; i < argc; i++) { string arg = argv[i]; if (arg == "--launcher") isLauncher = true; else if (arg == "--debugViewBounds") debugViewBounds = true; else if (arg.substr(0, 8) == "--theme=") { ThemeManager::SetTheme(arg.substr(8)); dontUseThemeInConfig = true; } } } int main(int argc, char **argv) { parseArguments(argc, argv); mainStart: std::cout << "main()" << std::endl; std::cout << "Initializing SDL... " << std::endl; if (!initializeSDL()) { terminateSDL(); return 1; } std::cout << "SDL is init!!" << std::endl; std::cout << "Initializing ScreenManager... "; screenManager = new ScreenManager(); if (!screenManager->Init()) { std::cout << "FAILED" << std::endl; terminateSDL(); return 1; } std::cout << "OK" << std::endl; screenManager->SetRenderer(ren); std::cout << "Loading resources... "; if (!screenManager->LoadGlobalResources()) { std::cout << "FAILED" << std::endl; std::cout << screenManager->GetLastError() << std::endl; terminateSDL(); return 1; } std::cout << "OK" << std::endl; screenManager->GetAppManager()->SetResourceManager(screenManager->GetResourceManager()); if (!HomeDirectory::InitAndCreateDirectories()) { std::cout << "Failed to init config / data directory paths" << std::endl; return 1; } measureTimeStart(); if (!screenManager->GetAppManager()->LoadApps()) { std::cout << "Failed to load apps" << std::endl; return 1; } double timeLoadApps = measureTimeFinish(); std::cout << "Loaded " << screenManager->GetAppManager()->GetNumberOfApps() << " apps in " << timeLoadApps << "s." << std::endl; if (!screenManager->GetAppManager()->LoadRecentList()) { std::cout << "Failed to load recent list" << std::endl; return 1; } setKeyBindings(); screenManager->GetThemeManager()->LoadThemes(); if (!dontUseThemeInConfig) screenManager->GetThemeManager()->LoadSettings(); Theme* theme = screenManager->GetThemeManager()->GetTheme(ThemeManager::GetCurrentThemeId()); string themeEntryPoint = ""; if (theme != nullptr) themeEntryPoint = string("@theme/") + theme->GetEntryPoint(); std::cout << "APP IS START" << std::endl; // TEMP TEMP TEMP! screenManager->GetResourceManager()->LoadImage("SnowCloseUp", "data/wallpapers/SnowCloseUp.jpg"); screenManager->GetResourceManager()->LoadImage("GothenburgNight", "data/wallpapers/GothenburgNight.jpg"); screenManager->GetResourceManager()->LoadImage("Bug", "data/wallpapers/Bug.jpg"); screenManager->GetResourceManager()->LoadImage("Circuit", "data/wallpapers/Circuit.jpg"); screenManager->GetResourceManager()->LoadImage("Leaves", "data/wallpapers/Leaves.jpg"); screenManager->GetResourceManager()->LoadImage("IconApplications", "data/graphics/icon_applications.png"); screenManager->GetResourceManager()->LoadImage("IconEmulators", "data/graphics/icon_emulators.png"); screenManager->GetResourceManager()->LoadImage("IconGames", "data/graphics/icon_games.png"); screenManager->GetResourceManager()->LoadImage("IconSettings", "data/graphics/icon_settings.png"); ScreenBackgroundImage* bgScreen = new ScreenBackgroundImage(); screenManager->AddScreen(bgScreen); if (themeEntryPoint.empty()) screenManager->AddScreen(new ScreenError("Failed to load theme")); else screenManager->AddScreen(new ScreenMenu(themeEntryPoint)); if (launchFailed) { launchFailed = false; ScreenMessageDialog* dialog = new ScreenMessageDialog(); dialog->SetText("An unknown error occured while launching application."); screenManager->AddScreen(dialog); } bgScreen->AddImage("Circuit"); bgScreen->AddImage("Bug"); bgScreen->AddImage("SnowCloseUp"); bgScreen->AddImage("GothenburgNight"); bgScreen->AddImage("Leaves"); _resetFrameSkip = false; int currentTime = SDL_GetTicks(); double accumulator = 0; double frameTime = 1000.0/(double)FPS; int newTime; int deltaTime; int shouldDraw = 0; vector<string> commandToLaunchOnExit = vector<string>(); while(!screenManager->HasExit()) { newTime = SDL_GetTicks(); deltaTime = newTime - currentTime; currentTime = newTime; accumulator += deltaTime; #if defined(NO_FPS_LIMIT) accumulator = frameTime; #endif if(_resetFrameSkip) { accumulator = frameTime; _resetFrameSkip = false; } while (accumulator >= frameTime && !screenManager->HasExit()) { accumulator -= frameTime; screenManager->Update(); shouldDraw = 1; } if (shouldDraw) { screenManager->Draw(); shouldDraw = 0; } else { SDL_Delay(1); } } commandToLaunchOnExit = screenManager->GetAppManager()->GetCommandToLaunch(); screenManager->GetAppManager()->ClearCommandToLaunch(); delete screenManager; screenManager = NULL; terminateSDL(); fflush(NULL); // If we should launch an app, do it now. if (!commandToLaunchOnExit.empty()) { #ifdef UNIX vector<const char *> args; args.reserve(commandToLaunchOnExit.size() + 1); for (auto arg : commandToLaunchOnExit) { args.push_back(arg.c_str()); } args.push_back(nullptr); execvp(commandToLaunchOnExit[0].c_str(), (char* const*)&args[0]); #endif // If we ended up here, execution failed. Restart. launchFailed = true; goto mainStart; } return 0; } <commit_msg>Restore framebuffer hack for GCW Zero<commit_after>/* Copyright 2016 Andreas Bjerkeholt 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 <iostream> #include <SDL.h> #include <SDL_ttf.h> #include <SDL_mixer.h> #include "ScreenSystem/ScreenManager.h" #include "Screens/ScreenBackgroundImage.h" #include "Screens/ScreenMenu.h" #include "Screens/ScreenTest.h" #include "Screens/ScreenMessageDialog.h" #include "Screens/ScreenError.h" #include "ThemeManager.h" #include "global.h" #include "HomeDirectory.h" #include <string> #include "utils.h" #ifdef UNIX #include <unistd.h> #include <stdlib.h> #endif #ifdef PLATFORM_GCW0 #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/fb.h> #endif using namespace std; bool SDLInited = false; SDL_Window *win = NULL; SDL_Renderer *ren = NULL; ScreenManager* screenManager = NULL; bool _resetFrameSkip = false; bool debugViewBounds = false; bool isLauncher = false; bool launchFailed = false; bool dontUseThemeInConfig = false; bool initializeSDL() { #ifdef PLATFORM_GCW0 // Avoid the framebuffer being cleared on exit on the GCW Zero setenv("SDL_FBCON_DONT_CLEAR", "1", 0); #endif if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "SDL_Init error: " << SDL_GetError() << std::endl; return false; } SDLInited = true; win = SDL_CreateWindow("ExLauncher", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 320, 240, SDL_WINDOW_SHOWN); if (win == NULL) { std::cout << SDL_GetError() << std::endl; return false; } ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE); if (ren == NULL) { std::cout << SDL_GetError() << std::endl; return false; } SDL_RendererInfo renInfo; if (SDL_GetRendererInfo(ren, &renInfo) < 0) { std::cout << "Unable to query renderer" << std::endl; return false; } /*if ((renInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) { std::cout << "Renderer does not support render targets" << std::endl; return false; }*/ if (TTF_Init() != 0) { std::cout << TTF_GetError() << std::endl; return false; } int mixFlags = MIX_INIT_OGG; if ((Mix_Init(mixFlags) & mixFlags) != mixFlags) { std::cout << Mix_GetError() << std::endl; return false; } if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) == -1) { std::cout << Mix_GetError() << std::endl; return false; } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"); return true; } void RestoreFb() { #ifdef PLATFORM_GCW0 fb_var_screeninfo varInfo; int fd = open("/dev/fb0", O_RDWR); ioctl(fd, FBIOGET_VSCREENINFO, &varInfo); varInfo.yoffset = varInfo.xoffset = 0; ioctl(fd, FBIOPUT_VSCREENINFO, &varInfo); #endif } void terminateSDL() { int audioTimesOpened, frequency, channels; Uint16 format; audioTimesOpened = Mix_QuerySpec(&frequency, &format, &channels); while (audioTimesOpened > 0) { Mix_CloseAudio(); audioTimesOpened--; } while (Mix_Init(0)) Mix_Quit(); if (TTF_WasInit()) { TTF_Quit(); } if (ren != NULL) { SDL_DestroyRenderer(ren); ren = NULL; } if (win != NULL) { SDL_DestroyWindow(win); win = NULL; } //if (SDL_WasInit(0) > 0) // FIXME TEST if (SDLInited) { SDL_Quit(); SDLInited = false; } #ifdef PLATFORM_GCW0 unsetenv("SDL_FBCON_DONT_CLEAR"); #endif RestoreFb(); } void setKeyBindings() { int gameKeys[GAMEKEY_MAX]; gameKeys[GAMEKEY_UP] = SDL_SCANCODE_UP; gameKeys[GAMEKEY_LEFT] = SDL_SCANCODE_LEFT; gameKeys[GAMEKEY_RIGHT] = SDL_SCANCODE_RIGHT; gameKeys[GAMEKEY_DOWN] = SDL_SCANCODE_DOWN; gameKeys[GAMEKEY_A] = SDL_SCANCODE_LCTRL; gameKeys[GAMEKEY_B] = SDL_SCANCODE_LALT; gameKeys[GAMEKEY_X] = SDL_SCANCODE_SPACE; gameKeys[GAMEKEY_Y] = SDL_SCANCODE_LSHIFT; gameKeys[GAMEKEY_START] = SDL_SCANCODE_RETURN; gameKeys[GAMEKEY_SELECT] = SDL_SCANCODE_ESCAPE; gameKeys[GAMEKEY_TRIGGER_L] = SDL_SCANCODE_TAB; gameKeys[GAMEKEY_TRIGGER_R] = SDL_SCANCODE_BACKSPACE; screenManager->SetGameKeyBindings(gameKeys, GAMEKEY_MAX); } void parseArguments(int argc, char **argv) { for (int i = 1; i < argc; i++) { string arg = argv[i]; if (arg == "--launcher") isLauncher = true; else if (arg == "--debugViewBounds") debugViewBounds = true; else if (arg.substr(0, 8) == "--theme=") { ThemeManager::SetTheme(arg.substr(8)); dontUseThemeInConfig = true; } } } int main(int argc, char **argv) { parseArguments(argc, argv); mainStart: std::cout << "main()" << std::endl; std::cout << "Initializing SDL... " << std::endl; if (!initializeSDL()) { terminateSDL(); return 1; } std::cout << "SDL is init!!" << std::endl; std::cout << "Initializing ScreenManager... "; screenManager = new ScreenManager(); if (!screenManager->Init()) { std::cout << "FAILED" << std::endl; terminateSDL(); return 1; } std::cout << "OK" << std::endl; screenManager->SetRenderer(ren); std::cout << "Loading resources... "; if (!screenManager->LoadGlobalResources()) { std::cout << "FAILED" << std::endl; std::cout << screenManager->GetLastError() << std::endl; terminateSDL(); return 1; } std::cout << "OK" << std::endl; screenManager->GetAppManager()->SetResourceManager(screenManager->GetResourceManager()); if (!HomeDirectory::InitAndCreateDirectories()) { std::cout << "Failed to init config / data directory paths" << std::endl; return 1; } measureTimeStart(); if (!screenManager->GetAppManager()->LoadApps()) { std::cout << "Failed to load apps" << std::endl; return 1; } double timeLoadApps = measureTimeFinish(); std::cout << "Loaded " << screenManager->GetAppManager()->GetNumberOfApps() << " apps in " << timeLoadApps << "s." << std::endl; if (!screenManager->GetAppManager()->LoadRecentList()) { std::cout << "Failed to load recent list" << std::endl; return 1; } setKeyBindings(); screenManager->GetThemeManager()->LoadThemes(); if (!dontUseThemeInConfig) screenManager->GetThemeManager()->LoadSettings(); Theme* theme = screenManager->GetThemeManager()->GetTheme(ThemeManager::GetCurrentThemeId()); string themeEntryPoint = ""; if (theme != nullptr) themeEntryPoint = string("@theme/") + theme->GetEntryPoint(); std::cout << "APP IS START" << std::endl; // TEMP TEMP TEMP! screenManager->GetResourceManager()->LoadImage("SnowCloseUp", "data/wallpapers/SnowCloseUp.jpg"); screenManager->GetResourceManager()->LoadImage("GothenburgNight", "data/wallpapers/GothenburgNight.jpg"); screenManager->GetResourceManager()->LoadImage("Bug", "data/wallpapers/Bug.jpg"); screenManager->GetResourceManager()->LoadImage("Circuit", "data/wallpapers/Circuit.jpg"); screenManager->GetResourceManager()->LoadImage("Leaves", "data/wallpapers/Leaves.jpg"); screenManager->GetResourceManager()->LoadImage("IconApplications", "data/graphics/icon_applications.png"); screenManager->GetResourceManager()->LoadImage("IconEmulators", "data/graphics/icon_emulators.png"); screenManager->GetResourceManager()->LoadImage("IconGames", "data/graphics/icon_games.png"); screenManager->GetResourceManager()->LoadImage("IconSettings", "data/graphics/icon_settings.png"); ScreenBackgroundImage* bgScreen = new ScreenBackgroundImage(); screenManager->AddScreen(bgScreen); if (themeEntryPoint.empty()) screenManager->AddScreen(new ScreenError("Failed to load theme")); else screenManager->AddScreen(new ScreenMenu(themeEntryPoint)); if (launchFailed) { launchFailed = false; ScreenMessageDialog* dialog = new ScreenMessageDialog(); dialog->SetText("An unknown error occured while launching application."); screenManager->AddScreen(dialog); } bgScreen->AddImage("Circuit"); bgScreen->AddImage("Bug"); bgScreen->AddImage("SnowCloseUp"); bgScreen->AddImage("GothenburgNight"); bgScreen->AddImage("Leaves"); _resetFrameSkip = false; int currentTime = SDL_GetTicks(); double accumulator = 0; double frameTime = 1000.0/(double)FPS; int newTime; int deltaTime; int shouldDraw = 0; vector<string> commandToLaunchOnExit = vector<string>(); while(!screenManager->HasExit()) { newTime = SDL_GetTicks(); deltaTime = newTime - currentTime; currentTime = newTime; accumulator += deltaTime; #if defined(NO_FPS_LIMIT) accumulator = frameTime; #endif if(_resetFrameSkip) { accumulator = frameTime; _resetFrameSkip = false; } while (accumulator >= frameTime && !screenManager->HasExit()) { accumulator -= frameTime; screenManager->Update(); shouldDraw = 1; } if (shouldDraw) { screenManager->Draw(); shouldDraw = 0; } else { SDL_Delay(1); } } commandToLaunchOnExit = screenManager->GetAppManager()->GetCommandToLaunch(); screenManager->GetAppManager()->ClearCommandToLaunch(); delete screenManager; screenManager = NULL; terminateSDL(); fflush(NULL); // If we should launch an app, do it now. if (!commandToLaunchOnExit.empty()) { #ifdef UNIX vector<const char *> args; args.reserve(commandToLaunchOnExit.size() + 1); for (auto arg : commandToLaunchOnExit) { args.push_back(arg.c_str()); } args.push_back(nullptr); execvp(commandToLaunchOnExit[0].c_str(), (char* const*)&args[0]); #endif // If we ended up here, execution failed. Restart. launchFailed = true; goto mainStart; } return 0; } <|endoftext|>
<commit_before>#include "headers.h" // initialize the library with the numbers of the interface pins LiquidCrystal lcd(P40, P39, P38, P37, P36, P35); int main() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("hello, world!"); while(1) { // Turn off the cursor: lcd.noCursor(); delay(500); // Turn on the cursor: lcd.cursor(); delay(500); } } <commit_msg>Update Cursor.cpp<commit_after>#include "headers.h" // initialize the library with the numbers of the interface pins LiquidCrystal lcd(P40, P39, P38, P37, P36, P35); int main() { vusb_enable(); // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("hello, world!"); while(1) { // Turn off the cursor: lcd.noCursor(); delay(500); // Turn on the cursor: lcd.cursor(); delay(500); } } <|endoftext|>
<commit_before>#include <jpl-tags/fiducial_stereo.h> #include <opencv2/opencv.hpp> #include <drc_utils/LcmWrapper.hpp> #include <drc_utils/BotWrapper.hpp> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/multisense/images_t.hpp> #include <lcmtypes/bot_core/image_t.hpp> #include <lcmtypes/drc/tag_detection_t.hpp> #include <lcmtypes/drc/tag_detection_list_t.hpp> #include <bot_core/camtrans.h> #include <bot_param/param_util.h> #include <zlib.h> struct State { drc::BotWrapper::Ptr mBotWrapper; drc::LcmWrapper::Ptr mLcmWrapper; BotCamTrans* mCamTransLeft; BotCamTrans* mCamTransRight; fiducial_detector_t* mDetector; fiducial_stereo_t* mStereoDetector; double mStereoBaseline; Eigen::Matrix3d mCalibLeft; Eigen::Matrix3d mCalibLeftInv; std::string mCameraChannel; std::string mTagChannel; bool mRunStereoAlgorithm; State() { mDetector = NULL; mStereoDetector = NULL; mCamTransLeft = NULL; mCamTransRight = NULL; mCameraChannel = "CAMERA"; mTagChannel = "JPL_TAGS"; mRunStereoAlgorithm = true; } ~State() { if (mDetector != NULL) fiducial_detector_free(mDetector); if (mStereoDetector != NULL) fiducial_stereo_free(mStereoDetector); } void populate(BotCamTrans* iCam, fiducial_stereo_cam_model_t& oCam) { oCam.cols = bot_camtrans_get_width(iCam); oCam.rows = bot_camtrans_get_height(iCam); oCam.focal_length_x = bot_camtrans_get_focal_length_x(iCam); oCam.focal_length_y = bot_camtrans_get_focal_length_y(iCam); oCam.image_center_x = bot_camtrans_get_principal_x(iCam); oCam.image_center_y = bot_camtrans_get_principal_y(iCam); } void populate(BotCamTrans* iCam, Eigen::Matrix3d& oK) { oK(0,0) = bot_camtrans_get_focal_length_x(iCam); oK(1,1) = bot_camtrans_get_focal_length_y(iCam); oK(0,2) = bot_camtrans_get_principal_x(iCam); oK(1,2) = bot_camtrans_get_principal_y(iCam); oK(0,1) = bot_camtrans_get_skew(iCam); } void copyTransform(const Eigen::Isometry3d& iTransform, double oTransform[4][4]) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { oTransform[i][j] = iTransform(i,j); } } } void setup() { mBotWrapper.reset(new drc::BotWrapper()); mLcmWrapper.reset(new drc::LcmWrapper(mBotWrapper->getLcm())); mLcmWrapper->get()->subscribe(mCameraChannel, &State::onCamera, this); mDetector = fiducial_detector_alloc(); fiducial_detector_init(mDetector); fiducial_params_t params; fiducial_detector_get_params(mDetector, &params); // TODO: can set parameters here if desired //params.search_size = 40; // image search radius in pixels //params.min_viewing_angle = 20; // angle of view of fiducial in degrees //params.dist_thresh = 0.05; // max allowed distance in meters between initial and estimated fiducial positions fiducial_detector_set_params(mDetector, &params); mStereoDetector = fiducial_stereo_alloc(); fiducial_stereo_init(mStereoDetector); // populate camera data fiducial_stereo_cam_model_t leftModel, rightModel; mCamTransLeft = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_LEFT").c_str()); mCamTransRight = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_RIGHT").c_str()); populate(mCamTransLeft, leftModel); populate(mCamTransRight, rightModel); copyTransform(Eigen::Isometry3d::Identity(), leftModel.transform); copyTransform(Eigen::Isometry3d::Identity(), leftModel.inv_transform); Eigen::Isometry3d rightToLeft; mBotWrapper->getTransform(mCameraChannel + "_RIGHT", mCameraChannel + "_LEFT", rightToLeft); copyTransform(rightToLeft, rightModel.transform); copyTransform(rightToLeft.inverse(), rightModel.inv_transform); // set detector camera models fiducial_detector_set_camera_models(mDetector, &leftModel); fiducial_stereo_set_camera_models(mStereoDetector, &leftModel, &rightModel); // set internal values for stereo depth computation populate(mCamTransLeft, mCalibLeft); mCalibLeftInv = mCalibLeft.inverse(); mStereoBaseline = rightToLeft.translation().norm(); } void start() { mLcmWrapper->startHandleThread(true); } bool decodeImages(const multisense::images_t* iMessage, cv::Mat& oLeft, cv::Mat& oRight, cv::Mat& oDisp) { bot_core::image_t* leftImage = NULL; bot_core::image_t* rightImage = NULL; bot_core::image_t* dispImage = NULL; // grab image pointers for (int i = 0; i < iMessage->n_images; ++i) { switch (iMessage->image_types[i]) { case multisense::images_t::LEFT: leftImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::RIGHT: rightImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::DISPARITY_ZIPPED: case multisense::images_t::DISPARITY: dispImage = (bot_core::image_t*)(&iMessage->images[i]); break; default: break; } } // decode left image if (leftImage == NULL) { std::cout << "error: no left image available!" << std::endl; return false; } oLeft = leftImage->pixelformat == leftImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(leftImage->data), -1) : cv::Mat(leftImage->height, leftImage->width, CV_8UC1, leftImage->data.data()); if (oLeft.channels() < 3) cv::cvtColor(oLeft, oLeft, CV_GRAY2RGB); // decode right image if necessary for stereo algorithm if (mRunStereoAlgorithm) { if (rightImage == NULL) { std::cout << "error: no right image available!" << std::endl; return false; } oRight = rightImage->pixelformat == rightImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(rightImage->data), -1) : cv::Mat(rightImage->height, rightImage->width, CV_8UC1, rightImage->data.data()); if (oRight.channels() < 3) cv::cvtColor(oRight, oRight, CV_GRAY2RGB); } // otherwise decode disparity; we will compute depth from left image only else { if (dispImage == NULL) { std::cout << "error: no disparity image available!" << std::endl; return false; } int numPix = dispImage->width*dispImage->height; if ((int)dispImage->data.size() != numPix*2) { std::vector<uint8_t> buf(numPix*2); unsigned long len = buf.size(); uncompress(buf.data(), &len, dispImage->data.data(), dispImage->data.size()); oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, buf.data()); } else { oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, dispImage->data.data()); } } return true; } void onCamera(const lcm::ReceiveBuffer* iBuffer, const std::string& iChannel, const multisense::images_t* iMessage) { std::cout << "GOT IMAGE " << std::endl; // grab camera pose Eigen::Isometry3d cameraToLocal, localToCamera; mBotWrapper->getTransform(mCameraChannel + "_LEFT", "local", cameraToLocal, iMessage->utime); localToCamera = cameraToLocal.inverse(); cv::Mat left, right, disp; if (!decodeImages(iMessage, left, right, disp)) return; // set up tag detections message drc::tag_detection_list_t msg; msg.utime = iMessage->utime; msg.num_detections = 0; // TODO: initialize with number of tags from config int numTags = 1; for (int i = 0; i < numTags; ++i) { // TODO: populate from config id int tagId = i; fiducial_pose_t poseInit, poseFinal; // TODO: populate initial pose wrt left cam using fk and config location // can also initialize with previous pose (tracking) poseInit = fiducial_pose_ident(); poseInit.pos.z = 1; poseInit.rot = fiducial_rot_from_rpy(0,2*M_PI/2,0); fiducial_detector_error_t status; if (mRunStereoAlgorithm) { float leftScore(0), rightScore(0); status = fiducial_stereo_process(mStereoDetector, left.data, right.data, left.cols, left.rows, left.channels(), poseInit, &poseFinal, &leftScore, &rightScore, false); } else { float score = 0; status = fiducial_detector_match_subpixel(mDetector, left.data, left.cols, left.rows, left.channels(), poseInit, &score); if (status == FIDUCIAL_DETECTOR_OK) { float x = mDetector->fiducial_location.x; float y = mDetector->fiducial_location.y; int xInt(x), yInt(y); if ((xInt < 0) || (yInt < 0) || (xInt >= disp.cols-1) || (yInt >= disp.rows-1)) { status = FIDUCIAL_DETECTOR_ERR; } else { // interpolate disparity float xFrac(x-xInt), yFrac(y-yInt); int d00 = disp.at<uint16_t>(xInt, yInt); int d10 = disp.at<uint16_t>(xInt+1, yInt); int d01 = disp.at<uint16_t>(xInt, yInt+1); int d11 = disp.at<uint16_t>(xInt+1, yInt+1); float d = (1-xFrac)*(1-yFrac)*d00 + xFrac*(1-yFrac)*d10 + (1-xFrac)*yFrac*d01 + xFrac*yFrac*d11; // compute depth and 3d point float z = mStereoBaseline*mCalibLeft(0,0) / d; Eigen::Vector3d pos = z*mCalibLeftInv*Eigen::Vector3d(x,y,1); poseFinal.pos.x = pos[0]; poseFinal.pos.y = pos[1]; poseFinal.pos.z = pos[2]; // TODO: what about orientation? } } } if (status == FIDUCIAL_DETECTOR_OK) { // populate this tag detection message drc::tag_detection_t detection; detection.utime = msg.utime; detection.id = tagId; // put tag into local frame Eigen::Vector3d pos(poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z); pos = cameraToLocal*pos; for (int k = 0; k < 3; ++k) detection.pos[k] = pos[k]; Eigen::Quaterniond q(poseFinal.rot.u, poseFinal.rot.x, poseFinal.rot.y, poseFinal.rot.z); q = cameraToLocal.rotation()*q; detection.orientation[0] = q.w(); detection.orientation[1] = q.x(); detection.orientation[2] = q.y(); detection.orientation[3] = q.z(); // find pixel position of tag double p[] = {poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z}; double pix[3]; bot_camtrans_project_point(mCamTransLeft, p, pix); detection.cxy[0] = pix[0]; detection.cxy[1] = pix[1]; // four corners are irrelevant; set them all to tag center for (int k = 0; k < 4; ++k) { for (int m = 0; m < 2; ++m) detection.p[k][m] = pix[m]; } // add this detection to list msg.detections.push_back(detection); msg.num_detections = msg.detections.size(); std::cout << "PROCESSED " << status << std::endl; std::cout << "POSE: " << poseFinal.pos.x << " " << poseFinal.pos.y << " " << poseFinal.pos.z << std::endl; } else { std::cout << "warning: could not detect tag " << tagId << std::endl; } } mLcmWrapper->get()->publish(mTagChannel, &msg); } }; int main(const int iArgc, const char** iArgv) { State state; state.setup(); state.start(); return -1; } <commit_msg>added command line options, validated single-image + disparity method<commit_after>#include <jpl-tags/fiducial_stereo.h> #include <opencv2/opencv.hpp> #include <drc_utils/LcmWrapper.hpp> #include <drc_utils/BotWrapper.hpp> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/multisense/images_t.hpp> #include <lcmtypes/bot_core/image_t.hpp> #include <lcmtypes/drc/tag_detection_t.hpp> #include <lcmtypes/drc/tag_detection_list_t.hpp> #include <bot_core/camtrans.h> #include <bot_param/param_util.h> #include <zlib.h> #include <chrono> #include <ConciseArgs> struct TagInfo { int64_t mId; // unique id std::string mLink; // link coordinate frame name Eigen::Isometry3d mLinkPose; // with respect to link Eigen::Isometry3d mCurPose; // tracked pose in local frame bool mTracked; TagInfo() { mId = 0; mLinkPose = Eigen::Isometry3d::Identity(); mCurPose = Eigen::Isometry3d::Identity(); mTracked = false; } }; struct State { drc::BotWrapper::Ptr mBotWrapper; drc::LcmWrapper::Ptr mLcmWrapper; BotCamTrans* mCamTransLeft; BotCamTrans* mCamTransRight; fiducial_detector_t* mDetector; fiducial_stereo_t* mStereoDetector; double mStereoBaseline; Eigen::Matrix3d mCalibLeft; Eigen::Matrix3d mCalibLeftInv; std::vector<TagInfo> mTags; std::string mCameraChannel; std::string mTagChannel; bool mRunStereoAlgorithm; bool mDoTracking; State() { mDetector = NULL; mStereoDetector = NULL; mCamTransLeft = NULL; mCamTransRight = NULL; mCameraChannel = "CAMERA"; mTagChannel = "JPL_TAGS"; mRunStereoAlgorithm = true; mDoTracking = true; } ~State() { if (mDetector != NULL) fiducial_detector_free(mDetector); if (mStereoDetector != NULL) fiducial_stereo_free(mStereoDetector); } void populate(BotCamTrans* iCam, fiducial_stereo_cam_model_t& oCam) { oCam.cols = bot_camtrans_get_width(iCam); oCam.rows = bot_camtrans_get_height(iCam); oCam.focal_length_x = bot_camtrans_get_focal_length_x(iCam); oCam.focal_length_y = bot_camtrans_get_focal_length_y(iCam); oCam.image_center_x = bot_camtrans_get_principal_x(iCam); oCam.image_center_y = bot_camtrans_get_principal_y(iCam); } void populate(BotCamTrans* iCam, Eigen::Matrix3d& oK) { oK = Eigen::Matrix3d::Identity(); oK(0,0) = bot_camtrans_get_focal_length_x(iCam); oK(1,1) = bot_camtrans_get_focal_length_y(iCam); oK(0,2) = bot_camtrans_get_principal_x(iCam); oK(1,2) = bot_camtrans_get_principal_y(iCam); oK(0,1) = bot_camtrans_get_skew(iCam); } void copyTransform(const Eigen::Isometry3d& iTransform, double oTransform[4][4]) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { oTransform[i][j] = iTransform(i,j); } } } void setup() { mBotWrapper.reset(new drc::BotWrapper()); mLcmWrapper.reset(new drc::LcmWrapper(mBotWrapper->getLcm())); mLcmWrapper->get()->subscribe(mCameraChannel, &State::onCamera, this); mDetector = fiducial_detector_alloc(); fiducial_detector_init(mDetector); fiducial_params_t params; fiducial_detector_get_params(mDetector, &params); // TODO: can set parameters here if desired //params.search_size = 40; // image search radius in pixels //params.min_viewing_angle = 20; // angle of view of fiducial in degrees //params.dist_thresh = 0.05; // max allowed distance in meters between initial and estimated fiducial positions fiducial_detector_set_params(mDetector, &params); mStereoDetector = fiducial_stereo_alloc(); fiducial_stereo_init(mStereoDetector); // populate camera data fiducial_stereo_cam_model_t leftModel, rightModel; mCamTransLeft = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_LEFT").c_str()); mCamTransRight = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_RIGHT").c_str()); populate(mCamTransLeft, leftModel); populate(mCamTransRight, rightModel); copyTransform(Eigen::Isometry3d::Identity(), leftModel.transform); copyTransform(Eigen::Isometry3d::Identity(), leftModel.inv_transform); Eigen::Isometry3d rightToLeft; mBotWrapper->getTransform(mCameraChannel + "_RIGHT", mCameraChannel + "_LEFT", rightToLeft); copyTransform(rightToLeft, rightModel.transform); copyTransform(rightToLeft.inverse(), rightModel.inv_transform); // set detector camera models fiducial_detector_set_camera_models(mDetector, &leftModel); fiducial_stereo_set_camera_models(mStereoDetector, &leftModel, &rightModel); // set internal values for stereo depth computation populate(mCamTransLeft, mCalibLeft); mCalibLeftInv = mCalibLeft.inverse(); mStereoBaseline = rightToLeft.translation().norm(); // populate tag data from config // TODO: this is temporary mTags.clear(); for (int i = 0; i < 1; ++i) { TagInfo tag; tag.mId = 99; mTags.push_back(tag); } } void start() { mLcmWrapper->startHandleThread(true); } bool decodeImages(const multisense::images_t* iMessage, cv::Mat& oLeft, cv::Mat& oRight, cv::Mat& oDisp) { bot_core::image_t* leftImage = NULL; bot_core::image_t* rightImage = NULL; bot_core::image_t* dispImage = NULL; // grab image pointers for (int i = 0; i < iMessage->n_images; ++i) { switch (iMessage->image_types[i]) { case multisense::images_t::LEFT: leftImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::RIGHT: rightImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::DISPARITY_ZIPPED: case multisense::images_t::DISPARITY: dispImage = (bot_core::image_t*)(&iMessage->images[i]); break; default: break; } } // decode left image if (leftImage == NULL) { std::cout << "error: no left image available!" << std::endl; return false; } oLeft = leftImage->pixelformat == leftImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(leftImage->data), -1) : cv::Mat(leftImage->height, leftImage->width, CV_8UC1, leftImage->data.data()); if (oLeft.channels() < 3) cv::cvtColor(oLeft, oLeft, CV_GRAY2RGB); // decode right image if necessary for stereo algorithm if (mRunStereoAlgorithm) { if (rightImage == NULL) { std::cout << "error: no right image available!" << std::endl; return false; } oRight = rightImage->pixelformat == rightImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(rightImage->data), -1) : cv::Mat(rightImage->height, rightImage->width, CV_8UC1, rightImage->data.data()); if (oRight.channels() < 3) cv::cvtColor(oRight, oRight, CV_GRAY2RGB); } // otherwise decode disparity; we will compute depth from left image only else { if (dispImage == NULL) { std::cout << "error: no disparity image available!" << std::endl; return false; } int numPix = dispImage->width*dispImage->height; if ((int)dispImage->data.size() != numPix*2) { std::vector<uint8_t> buf(numPix*2); unsigned long len = buf.size(); uncompress(buf.data(), &len, dispImage->data.data(), dispImage->data.size()); oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, buf.data()).clone(); } else { oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, dispImage->data.data()).clone(); } } return true; } void onCamera(const lcm::ReceiveBuffer* iBuffer, const std::string& iChannel, const multisense::images_t* iMessage) { auto t1 = std::chrono::high_resolution_clock::now(); // grab camera pose Eigen::Isometry3d cameraToLocal, localToCamera; mBotWrapper->getTransform(mCameraChannel + "_LEFT", "local", cameraToLocal, iMessage->utime); localToCamera = cameraToLocal.inverse(); // decode images cv::Mat left, right, disp; if (!decodeImages(iMessage, left, right, disp)) return; // set up tag detections message drc::tag_detection_list_t msg; msg.utime = iMessage->utime; msg.num_detections = 0; for (int i = 0; i < (int)mTags.size(); ++i) { // initialize pose fiducial_pose_t poseInit, poseFinal; poseInit = fiducial_pose_ident(); // use previous tracked position if available if (mDoTracking && mTags[i].mTracked) { Eigen::Isometry3d pose = localToCamera*mTags[i].mCurPose; poseInit.pos.x = pose.translation()[0]; poseInit.pos.y = pose.translation()[1]; poseInit.pos.z = pose.translation()[2]; Eigen::Quaterniond q(pose.rotation()); poseInit.rot.u = q.w(); poseInit.rot.x = q.x(); poseInit.rot.y = q.y(); poseInit.rot.z = q.z(); } // TODO: use fk wrt left cam else { // TOOD: this is temp poseInit.pos.x = 0.028; poseInit.pos.y = 0.002; poseInit.pos.z = 0.56; poseInit.rot = fiducial_rot_from_rpy(0,2*M_PI/2,0); } mTags[i].mTracked = false; fiducial_detector_error_t status; // run stereo detector if (mRunStereoAlgorithm) { float leftScore(0), rightScore(0); status = fiducial_stereo_process(mStereoDetector, left.data, right.data, left.cols, left.rows, left.channels(), poseInit, &poseFinal, &leftScore, &rightScore, false); } // run mono detector and use disparity to infer 3d else { float score = 0; status = fiducial_detector_match_subpixel(mDetector, left.data, left.cols, left.rows, left.channels(), poseInit, &score); if (status == FIDUCIAL_DETECTOR_OK) { float x = mDetector->fiducial_location.x; float y = mDetector->fiducial_location.y; int xInt(x), yInt(y); if ((xInt < 0) || (yInt < 0) || (xInt >= disp.cols-1) || (yInt >= disp.rows-1)) { status = FIDUCIAL_DETECTOR_ERR; } else { // interpolate disparity float xFrac(x-xInt), yFrac(y-yInt); int d00 = disp.at<uint16_t>(yInt, xInt); int d10 = disp.at<uint16_t>(yInt, xInt+1); int d01 = disp.at<uint16_t>(yInt+1, xInt); int d11 = disp.at<uint16_t>(yInt+1, xInt+1); float d = (1-xFrac)*(1-yFrac)*d00 + xFrac*(1-yFrac)*d10 + (1-xFrac)*yFrac*d01 + xFrac*yFrac*d11; // compute depth and 3d point float z = 16*mStereoBaseline*mCalibLeft(0,0) / d; Eigen::Vector3d pos = z*mCalibLeftInv*Eigen::Vector3d(x,y,1); poseFinal.pos.x = pos[0]; poseFinal.pos.y = pos[1]; poseFinal.pos.z = pos[2]; poseFinal.rot = poseInit.rot; // TODO: fill in correct orientation } } } if (status == FIDUCIAL_DETECTOR_OK) { // populate this tag detection message drc::tag_detection_t detection; detection.utime = msg.utime; detection.id = mTags[i].mId; // put tag into local frame Eigen::Vector3d pos(poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z); pos = cameraToLocal*pos; for (int k = 0; k < 3; ++k) detection.pos[k] = pos[k]; Eigen::Quaterniond q(poseFinal.rot.u, poseFinal.rot.x, poseFinal.rot.y, poseFinal.rot.z); q = cameraToLocal.rotation()*q; detection.orientation[0] = q.w(); detection.orientation[1] = q.x(); detection.orientation[2] = q.y(); detection.orientation[3] = q.z(); // find pixel position of tag double p[] = {poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z}; double pix[3]; bot_camtrans_project_point(mCamTransLeft, p, pix); detection.cxy[0] = pix[0]; detection.cxy[1] = pix[1]; // four corners are irrelevant; set them all to tag center for (int k = 0; k < 4; ++k) { for (int m = 0; m < 2; ++m) detection.p[k][m] = pix[m]; } // add this detection to list msg.detections.push_back(detection); msg.num_detections = msg.detections.size(); // tracked successfully mTags[i].mCurPose.linear() = q.matrix(); mTags[i].mCurPose.translation() = pos; mTags[i].mTracked = true; } else { std::cout << "warning: could not detect tag " << mTags[i].mId << std::endl; } } mLcmWrapper->get()->publish(mTagChannel, &msg); auto t2 = std::chrono::high_resolution_clock::now(); auto dt = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1); std::cout << "PROCESSED IN " << dt.count()/1e6 << " SEC" << std::endl; } }; int main(const int iArgc, const char** iArgv) { State state; ConciseArgs opt(iArgc, (char**)iArgv); opt.add(state.mCameraChannel, "c", "camera_channel", "channel containing stereo image data"); opt.add(state.mTagChannel, "d", "detection_channel", "channel on which to publish tag detections"); opt.add(state.mRunStereoAlgorithm, "s", "stereo", "whether to run stereo-based detector"); opt.add(state.mDoTracking, "t", "tracking", "whether to use previous detection to initialize current detection"); opt.parse(); state.setup(); state.start(); return -1; } <|endoftext|>
<commit_before>#include "qif" using std::cout; using std::vector; using std::string; using namespace qif; void compute_optimal(string method) { lp::Defaults::method = lp::method_t::simplex_dual; lp::Defaults::glp_msg_level = lp::msg_level_t::all; lp::Defaults::glp_presolve = true; double unit = 1; double eps = std::log(2) / (2*unit); uint width = 8, n_inputs = width * width, n_outputs = n_inputs; double R = 2.2 * unit; // the R and rho for double rho = unit * std::sqrt(2)/2; // Kostas' method auto d_grid = unit * metric::grid<double>(width); // d_grid(i, j) = euclidean distance between cell indices i,j auto d_loss = d_grid; // loss metric = euclidean Metric<double, uint> dx; // privacy metric, depends on the method if(method == "direct") { dx = d_grid; // the real deal } else { dx = metric::threshold_inf(d_grid, R); // inf if above threshold R // Catuscia's crazy formula double R2 = R * R; double rho2 = rho * rho; double delta = (R - rho) / std::sqrt( R2 - 2*rho*R - 3*rho2 + 4*rho*rho2/R + rho2*rho2/R2 ); cout << "delta: " << delta << "\n"; eps /= delta; // update eps to compensate for the use of a bigger dx } prob pi = probab::uniform<double>(n_inputs); // uniform prior chan opt = mechanism::optimal_utility(pi, n_outputs, eps * dx, d_loss); cout << "size: " << opt.n_rows << "\n"; cout << "proper: " << channel::is_proper(opt) << "\n"; cout << "util : " << l::post_entropy(d_loss, pi, opt) << "\n"; // expected d_loss between x and y } int main(int argc, char *argv[]) { vector<string> args(argv+1, argv + argc); // compute_optimal("direct"); compute_optimal("kostas"); } <commit_msg>ValueTools17: add geometric, disable optimization<commit_after>#include "qif" using std::cout; using std::vector; using std::string; using namespace qif; void compute_optimal(string method) { if(method != "direct" && method != "kostas" && method != "geometric") throw std::runtime_error("invalid method: " + method); lp::Defaults::method = lp::method_t::simplex_dual; lp::Defaults::glp_msg_level = lp::msg_level_t::all; lp::Defaults::glp_presolve = true; double unit = 1; double eps = std::log(2) / (2*unit); uint width = 8, n_inputs = width * width, n_outputs = n_inputs; double R = 2.2 * unit; // the R and rho for double rho = unit * std::sqrt(2)/2; // Kostas' method auto d_grid = unit * metric::grid<double>(width); // d_grid(i, j) = euclidean distance between cell indices i,j auto d_loss = d_grid; // loss metric = euclidean auto dx = d_grid; // privacy metric // this disables the removal of constraints that are reduntant due to transitivity dx.chainable = [](const uint&, const uint&) -> bool { return false; }; if(method == "kostas") { // use more relexed dx and update eps // dx = metric::threshold_inf(d_grid, R); // inf if above threshold R // Catuscia's crazy formula double c = R / rho; double c2 = c * c; double delta = (c - 1) / std::sqrt( c2 - 2*c - 3 + 4/c + 1/c2 ); cout << "delta: " << delta << "\n"; eps /= delta; // update eps to compensate for the use of a bigger dx } prob pi = probab::uniform<double>(n_inputs); // uniform prior chan C = method == "geometric" ? mechanism::planar_geometric_grid<double>(width, width, unit, eps) : mechanism::optimal_utility(pi, n_outputs, eps * dx, d_loss); cout << "size: " << C.n_rows << "\n"; cout << "proper: " << channel::is_proper(C) << "\n"; cout << "util : " << l::post_entropy(d_loss, pi, C) << "\n"; // expected d_loss between x and y // apply optimal remap (probably does nothing for uniform priors) mat Loss = l::metric_to_mat(d_loss, n_inputs); chan Remap = channel::deterministic<double>(l::strategy(Loss, pi, C), Loss.n_rows); // compute remap cout << "util after remap : " << l::post_entropy(d_loss, pi, (chan)(C*Remap)) << "\n"; } int main(int argc, char *argv[]) { vector<string> args(argv+1, argv + argc); // compute_optimal("direct"); // compute_optimal("geometric"); compute_optimal("kostas"); } <|endoftext|>
<commit_before>#ifndef STAN__MATH__ERROR_HANDLING_CHECK_POSITIVE_HPP #define STAN__MATH__ERROR_HANDLING_CHECK_POSITIVE_HPP #include <stan/math/error_handling/dom_err.hpp> #include <stan/math/error_handling/dom_err_vec.hpp> #include <boost/type_traits/is_unsigned.hpp> #include <stan/meta/traits.hpp> namespace stan { namespace math { namespace { template <typename T_y, typename T_result, bool is_vec> struct positive { static bool check(const char* function, const T_y& y, const char* name, T_result* result) { // have to use not is_unsigned. is_signed will be false // floating point types that have no unsigned versions. if (!boost::is_unsigned<T_y>::value && !(y > 0)) return dom_err(function,y,name, " is %1%, but must be > 0!","", result); return true; } }; template <typename T_y, typename T_result> struct positive<T_y, T_result, true> { static bool check(const char* function, const T_y& y, const char* name, T_result* result) { using stan::length; for (size_t n = 0; n < length(y); n++) { if (!boost::is_unsigned<typename T_y::value_type>::value && !(stan::get(y,n) > 0)) return dom_err_vec(n,function,y,name, " is %1%, but must be > 0!","", result); } return true; } }; } template <typename T_y, typename T_result> inline bool check_positive(const char* function, const T_y& y, const char* name, T_result* result) { return positive<T_y,T_result,is_vector_like<T_y>::value> ::check(function, y, name, result); } } } #endif <commit_msg>added doc in code for check_positive<commit_after>#ifndef STAN__MATH__ERROR_HANDLING_CHECK_POSITIVE_HPP #define STAN__MATH__ERROR_HANDLING_CHECK_POSITIVE_HPP #include <stan/math/error_handling/dom_err.hpp> #include <stan/math/error_handling/dom_err_vec.hpp> #include <boost/type_traits/is_unsigned.hpp> #include <stan/meta/traits.hpp> namespace stan { namespace math { namespace { template <typename T_y, typename T_result, bool is_vec> struct positive { static bool check(const char* function, const T_y& y, const char* name, T_result* result) { // have to use not is_unsigned. is_signed will be false // floating point types that have no unsigned versions. if (!boost::is_unsigned<T_y>::value && !(y > 0)) return dom_err(function,y,name, " is %1%, but must be > 0!","", result); return true; } }; template <typename T_y, typename T_result> struct positive<T_y, T_result, true> { static bool check(const char* function, const T_y& y, const char* name, T_result* result) { using stan::length; for (size_t n = 0; n < length(y); n++) { if (!boost::is_unsigned<typename T_y::value_type>::value && !(stan::get(y,n) > 0)) return dom_err_vec(n,function,y,name, " is %1%, but must be > 0!","", result); } return true; } }; } // throws if any element in y is nan template <typename T_y, typename T_result> inline bool check_positive(const char* function, const T_y& y, const char* name, T_result* result) { return positive<T_y,T_result,is_vector_like<T_y>::value> ::check(function, y, name, result); } } } #endif <|endoftext|>
<commit_before>#ifndef STAN_SERVICES_UTIL_GENERATE_TRANSITIONS_HPP #define STAN_SERVICES_UTIL_GENERATE_TRANSITIONS_HPP #include <stan/interface_callbacks/writer/base_writer.hpp> #include <stan/interface_callbacks/interrupt/base_interrupt.hpp> #include <stan/mcmc/base_mcmc.hpp> #include <stan/services/util/mcmc_writer.hpp> #include <stan/old_services/sample/progress.hpp> #include <string> namespace stan { namespace services { namespace util { template <class Model, class RNG> void generate_transitions(stan::mcmc::base_mcmc& sampler, const int num_iterations, const int start, const int finish, const int num_thin, const int refresh, const bool save, const bool warmup, stan::services::sample::mcmc_writer& mcmc_writer, stan::mcmc::sample& init_s, Model& model, RNG& base_rng, stan::interface_callbacks::interrupt::base_interrupt& callback, interface_callbacks::writer::base_writer& info_writer, interface_callbacks::writer::base_writer& error_writer) { for (int m = 0; m < num_iterations; ++m) { callback(); if (refresh > 0 && (start + m + 1 == finish || m == 0 || (m + 1) % refresh == 0)) info_writer(sample::progress(m, start, finish, refresh, warmup)); init_s = sampler.transition(init_s, info_writer, error_writer); if ( save && ( (m % num_thin) == 0) ) { mcmc_writer.write_sample_params(base_rng, init_s, sampler, model); mcmc_writer.write_diagnostic_params(init_s, sampler); } } } } } } #endif <commit_msg>removing progress call from services<commit_after>#ifndef STAN_SERVICES_UTIL_GENERATE_TRANSITIONS_HPP #define STAN_SERVICES_UTIL_GENERATE_TRANSITIONS_HPP #include <stan/interface_callbacks/writer/base_writer.hpp> #include <stan/interface_callbacks/interrupt/base_interrupt.hpp> #include <stan/mcmc/base_mcmc.hpp> #include <stan/services/util/mcmc_writer.hpp> #include <string> namespace stan { namespace services { namespace util { template <class Model, class RNG> void generate_transitions(stan::mcmc::base_mcmc& sampler, const int num_iterations, const int start, const int finish, const int num_thin, const int refresh, const bool save, const bool warmup, stan::services::sample::mcmc_writer& mcmc_writer, stan::mcmc::sample& init_s, Model& model, RNG& base_rng, stan::interface_callbacks::interrupt::base_interrupt& callback, interface_callbacks::writer::base_writer& info_writer, interface_callbacks::writer::base_writer& error_writer) { for (int m = 0; m < num_iterations; ++m) { callback(); if (refresh > 0 && (start + m + 1 == finish || m == 0 || (m + 1) % refresh == 0)) { int it_print_width = std::ceil(std::log10(static_cast<double>(finish))); std::stringstream message; message << "Iteration: "; message << std::setw(it_print_width) << m + 1 + start << " / " << finish; message << " [" << std::setw(3) << static_cast<int>( (100.0 * (start + m + 1)) / finish ) << "%] "; message << (warmup ? " (Warmup)" : " (Sampling)"); info_writer(message.str()); } init_s = sampler.transition(init_s, info_writer, error_writer); if ( save && ( (m % num_thin) == 0) ) { mcmc_writer.write_sample_params(base_rng, init_s, sampler, model); mcmc_writer.write_diagnostic_params(init_s, sampler); } } } } } } #endif <|endoftext|>
<commit_before> #include "Shader.h" #include "Utilities.h" #include <GL/glew.h> namespace ion { namespace GL { //////////// // Shader // //////////// void Shader::Source(std::vector<std::string> const & Source) { c8 const ** Lines = new c8 const *[Source.size()]; for (u32 i = 0; i < Source.size(); ++ i) Lines[i] = Source[i].c_str(); CheckedGLCall(glShaderSource(Handle, Source.size(), Lines, 0)); } void Shader::Source(std::string const & Source) { c8 const * Line = Source.c_str(); CheckedGLCall(glShaderSource(Handle, 1, & Line, 0)); } bool Shader::Compile() { CheckedGLCall(glCompileShader(Handle)); s32 Compiled; CheckedGLCall(glGetShaderiv(Handle, GL_COMPILE_STATUS, & Compiled)); return Compiled != 0; } std::string Shader::InfoLog() const { std::string Log; int InfoLogLength = 0; int CharsWritten = 0; CheckExistingErrors(Shader::InfoLog); glGetShaderiv(Handle, GL_INFO_LOG_LENGTH, & InfoLogLength); if (OpenGLError()) { cerr << "Error occured during glGetShaderiv: " << GetOpenGLError() << endl; cerr << "Handle is " << Handle << endl; cerr << endl; } else if (InfoLogLength > 0) { GLchar * InfoLog = new GLchar[InfoLogLength]; glGetShaderInfoLog(Handle, InfoLogLength, & CharsWritten, InfoLog); Log = InfoLog; delete[] InfoLog; } return Log; } void Shader::Delete() { delete this; } Shader::~Shader() { glDeleteShader(Handle); } Shader::Shader(u32 const handle) : Handle(handle) {} ////////////// // Variants // ////////////// #ifdef GL_COMPUTE_SHADER ComputeShader::ComputeShader() : Shader(glCreateShader(GL_COMPUTE_SHADER)) {} #endif VertexShader::VertexShader() : Shader(glCreateShader(GL_VERTEX_SHADER)) {} TesselationControlShader::TesselationControlShader() : Shader(glCreateShader(GL_TESS_CONTROL_SHADER)) {} TesselationEvaluationShader::TesselationEvaluationShader() : Shader(glCreateShader(GL_TESS_EVALUATION_SHADER)) {} GeometryShader::GeometryShader() : Shader(glCreateShader(GL_GEOMETRY_SHADER)) {} FragmentShader::FragmentShader() : Shader(glCreateShader(GL_FRAGMENT_SHADER)) {} } } <commit_msg>Fix types warning in GL related to 32->64 change<commit_after> #include "Shader.h" #include "Utilities.h" #include <GL/glew.h> namespace ion { namespace GL { //////////// // Shader // //////////// void Shader::Source(std::vector<std::string> const & Source) { c8 const ** Lines = new c8 const *[Source.size()]; for (u32 i = 0; i < Source.size(); ++ i) Lines[i] = Source[i].c_str(); CheckedGLCall(glShaderSource(Handle, (int) Source.size(), Lines, 0)); } void Shader::Source(std::string const & Source) { c8 const * Line = Source.c_str(); CheckedGLCall(glShaderSource(Handle, 1, & Line, 0)); } bool Shader::Compile() { CheckedGLCall(glCompileShader(Handle)); s32 Compiled; CheckedGLCall(glGetShaderiv(Handle, GL_COMPILE_STATUS, & Compiled)); return Compiled != 0; } std::string Shader::InfoLog() const { std::string Log; int InfoLogLength = 0; int CharsWritten = 0; CheckExistingErrors(Shader::InfoLog); glGetShaderiv(Handle, GL_INFO_LOG_LENGTH, & InfoLogLength); if (OpenGLError()) { cerr << "Error occured during glGetShaderiv: " << GetOpenGLError() << endl; cerr << "Handle is " << Handle << endl; cerr << endl; } else if (InfoLogLength > 0) { GLchar * InfoLog = new GLchar[InfoLogLength]; glGetShaderInfoLog(Handle, InfoLogLength, & CharsWritten, InfoLog); Log = InfoLog; delete[] InfoLog; } return Log; } void Shader::Delete() { delete this; } Shader::~Shader() { glDeleteShader(Handle); } Shader::Shader(u32 const handle) : Handle(handle) {} ////////////// // Variants // ////////////// #ifdef GL_COMPUTE_SHADER ComputeShader::ComputeShader() : Shader(glCreateShader(GL_COMPUTE_SHADER)) {} #endif VertexShader::VertexShader() : Shader(glCreateShader(GL_VERTEX_SHADER)) {} TesselationControlShader::TesselationControlShader() : Shader(glCreateShader(GL_TESS_CONTROL_SHADER)) {} TesselationEvaluationShader::TesselationEvaluationShader() : Shader(glCreateShader(GL_TESS_EVALUATION_SHADER)) {} GeometryShader::GeometryShader() : Shader(glCreateShader(GL_GEOMETRY_SHADER)) {} FragmentShader::FragmentShader() : Shader(glCreateShader(GL_FRAGMENT_SHADER)) {} } } <|endoftext|>
<commit_before>#include "Mocks.hpp" using namespace blackhole; TEST(logger_base_t, CanBeEnabled) { logger_base_t log; log.enable(); EXPECT_TRUE(log.enabled()); } TEST(logger_base_t, CanBeDisabled) { logger_base_t log; log.disable(); EXPECT_FALSE(log.enabled()); } TEST(logger_base_t, EnabledByDefault) { logger_base_t log; EXPECT_TRUE(log.enabled()); } TEST(logger_base_t, OpenRecordByDefault) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); EXPECT_TRUE(log.open_record().valid()); } TEST(logger_base_t, DoNotOpenRecordIfDisabled) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.disable(); EXPECT_FALSE(log.open_record().valid()); } namespace blackhole { namespace keyword { DECLARE_KEYWORD(urgent, std::uint8_t) } } TEST(logger_base_t, OpensRecordWhenAttributeFilterSucceed) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.set_filter(expr::has_attr(keyword::urgent())); log.add_attribute(keyword::urgent() = 1); EXPECT_TRUE(log.open_record().valid()); } TEST(logger_base_t, DoNotOpenRecordWhenAttributeFilterFailed) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.set_filter(expr::has_attr(keyword::urgent())); EXPECT_FALSE(log.open_record().valid()); } TEST(logger_base_t, OpenRecordWhenComplexFilterSucceed) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.set_filter(expr::has_attr(keyword::urgent()) && keyword::urgent() == 1); log.add_attribute(keyword::urgent() = 1); EXPECT_TRUE(log.open_record().valid()); } TEST(logger_base_t, DoNotOpenRecordWhenComplexFilterFailed) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.set_filter(expr::has_attr(keyword::urgent()) && keyword::urgent() == 1); log.add_attribute(keyword::urgent() = 2); EXPECT_FALSE(log.open_record().valid()); } TEST(logger_base_t, DoNotOpenRecordIfThereAreNoFrontends) { logger_base_t log; EXPECT_FALSE(log.open_record().valid()); } <commit_msg>Today plans.<commit_after>#include "Mocks.hpp" using namespace blackhole; TEST(logger_base_t, CanBeEnabled) { logger_base_t log; log.enable(); EXPECT_TRUE(log.enabled()); } TEST(logger_base_t, CanBeDisabled) { logger_base_t log; log.disable(); EXPECT_FALSE(log.enabled()); } TEST(logger_base_t, EnabledByDefault) { logger_base_t log; EXPECT_TRUE(log.enabled()); } TEST(logger_base_t, OpenRecordByDefault) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); EXPECT_TRUE(log.open_record().valid()); } TEST(logger_base_t, DoNotOpenRecordIfDisabled) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.disable(); EXPECT_FALSE(log.open_record().valid()); } namespace blackhole { namespace keyword { DECLARE_KEYWORD(urgent, std::uint8_t) } } TEST(logger_base_t, OpensRecordWhenAttributeFilterSucceed) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.set_filter(expr::has_attr(keyword::urgent())); log.add_attribute(keyword::urgent() = 1); EXPECT_TRUE(log.open_record().valid()); } TEST(logger_base_t, DoNotOpenRecordWhenAttributeFilterFailed) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.set_filter(expr::has_attr(keyword::urgent())); EXPECT_FALSE(log.open_record().valid()); } TEST(logger_base_t, OpenRecordWhenComplexFilterSucceed) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.set_filter(expr::has_attr(keyword::urgent()) && keyword::urgent() == 1); log.add_attribute(keyword::urgent() = 1); EXPECT_TRUE(log.open_record().valid()); } TEST(logger_base_t, DoNotOpenRecordWhenComplexFilterFailed) { std::unique_ptr<mock::frontend_t> frontend; logger_base_t log; log.add_frontend(std::move(frontend)); log.set_filter(expr::has_attr(keyword::urgent()) && keyword::urgent() == 1); log.add_attribute(keyword::urgent() = 2); EXPECT_FALSE(log.open_record().valid()); } TEST(logger_base_t, DoNotOpenRecordIfThereAreNoFrontends) { logger_base_t log; EXPECT_FALSE(log.open_record().valid()); } //!@todo: TestCustomAttributes: setting, //! filtering, //! implement inspect::getattr function(attr) and (string), //! overload inspect::has_attr(string) //! make || operations in filtering //! implement %(...A)s handling in formatter::string //! implement %(...L)s handling for only local other attributes in format::string <|endoftext|>
<commit_before>/* Copyright © 2001-2019, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: 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/>. Stay tuned using twitter @navitia channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE access_point_test #include <boost/test/unit_test.hpp> #include "ed/build_helper.h" #include "access_point/access_point_api.h" #include "utils/logger.h" #include "tests/utils_test.h" #include <string> #include <vector> #include <map> #include <set> using namespace navitia; using boost::posix_time::time_period; using std::string; using std::vector; struct logger_initialized { logger_initialized() { navitia::init_logger(); } }; BOOST_GLOBAL_FIXTURE(logger_initialized); namespace { class AccessPointTestFixture { public: ed::builder b; const type::Data& data; AccessPointTestFixture() : b("20190101"), data(*b.data) { b.sa("saA", 2.361795, 48.871871)("spA", 2.361795, 48.871871); b.sa("saB", 2.362795, 48.872871)("spB", 2.362795, 48.872871); b.sa("saC", 2.363795, 48.873871)("spC", 2.363795, 48.873871); b.vj("A")("spA", "08:00"_t)("spB", "10:00"_t); b.vj("B")("spC", "09:00"_t)("spD", "11:00"_t); b.vj("C")("spA", "10:00"_t)("spC", "12:00"_t); b.data->complete(); b.make(); b.add_access_point("spA", "AP1", true, true, 10, 23, 48.874871, 2.364795); b.add_access_point("spA", "AP2", true, false, 13, 26, 48.875871, 2.365795); b.add_access_point("spC", "AP3", true, false, 12, 36, 48.876871, 2.366795); b.add_access_point("spC", "AP2", true, false, 13, 26, 48.875871, 2.365795); } }; void complete_pb_creator(navitia::PbCreator& pb_creator, const type::Data& data) { const ptime since = "20190101T000000"_dt; const ptime until = "21190101T000000"_dt; pb_creator.init(&data, since, time_period(since, until)); } bool ap_comp(pbnavitia::AccessPoint& ap1, pbnavitia::AccessPoint& ap2) { return ap1.uri() < ap2.uri(); } BOOST_FIXTURE_TEST_CASE(test_access_point_reading, AccessPointTestFixture) { string filter = ""; int count = 20; int depth = 0; int start_page = 0; vector<string> forbidden_uris = {}; navitia::PbCreator pb_creator; complete_pb_creator(pb_creator, data); access_point::access_points(pb_creator, filter, count, depth, start_page, forbidden_uris); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.access_points().size(), 3); auto access_points = resp.access_points(); sort(access_points.begin(), access_points.end(), ap_comp); auto ap = access_points[0]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP1"); BOOST_REQUIRE_EQUAL(ap.is_entrance(), true); BOOST_REQUIRE_EQUAL(ap.is_exit(), true); BOOST_REQUIRE_EQUAL(ap.length(), 10); BOOST_REQUIRE_EQUAL(ap.traversal_time(), 23); ap = access_points[1]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP2"); BOOST_REQUIRE_EQUAL(ap.is_entrance(), true); BOOST_REQUIRE_EQUAL(ap.is_exit(), false); BOOST_REQUIRE_EQUAL(ap.length(), 13); BOOST_REQUIRE_EQUAL(ap.traversal_time(), 26); ap = access_points[2]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP3"); BOOST_REQUIRE_EQUAL(ap.is_entrance(), true); BOOST_REQUIRE_EQUAL(ap.is_exit(), false); BOOST_REQUIRE_EQUAL(ap.length(), 12); BOOST_REQUIRE_EQUAL(ap.traversal_time(), 36); } BOOST_FIXTURE_TEST_CASE(test_access_point_filtering, AccessPointTestFixture) { { string filter = "stop_point.uri=spA"; int count = 20; int depth = 0; int start_page = 0; vector<string> forbidden_uris = {}; navitia::PbCreator pb_creator; complete_pb_creator(pb_creator, data); access_point::access_points(pb_creator, filter, count, depth, start_page, forbidden_uris); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.access_points().size(), 2); auto access_points = resp.access_points(); sort(access_points.begin(), access_points.end(), ap_comp); auto ap = access_points[0]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP1"); ap = access_points[1]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP2"); } { string filter = "stop_point.uri=spB"; int count = 20; int depth = 0; int start_page = 0; vector<string> forbidden_uris = {}; navitia::PbCreator pb_creator; complete_pb_creator(pb_creator, data); access_point::access_points(pb_creator, filter, count, depth, start_page, forbidden_uris); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.access_points().size(), 0); } { string filter = "stop_area.uri=saC"; int count = 20; int depth = 0; int start_page = 0; vector<string> forbidden_uris = {}; navitia::PbCreator pb_creator; complete_pb_creator(pb_creator, data); access_point::access_points(pb_creator, filter, count, depth, start_page, forbidden_uris); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.access_points().size(), 2); auto access_points = resp.access_points(); sort(access_points.begin(), access_points.end(), ap_comp); auto ap = access_points[0]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP2"); ap = access_points[1]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP3"); } } } // namespace <commit_msg>did you mean std::sort ?<commit_after>/* Copyright © 2001-2019, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: 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/>. Stay tuned using twitter @navitia channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE access_point_test #include <boost/test/unit_test.hpp> #include "ed/build_helper.h" #include "access_point/access_point_api.h" #include "utils/logger.h" #include "tests/utils_test.h" #include <string> #include <vector> #include <map> #include <set> using namespace std; using namespace navitia; using boost::posix_time::time_period; using std::string; using std::vector; struct logger_initialized { logger_initialized() { navitia::init_logger(); } }; BOOST_GLOBAL_FIXTURE(logger_initialized); namespace { class AccessPointTestFixture { public: ed::builder b; const type::Data& data; AccessPointTestFixture() : b("20190101"), data(*b.data) { b.sa("saA", 2.361795, 48.871871)("spA", 2.361795, 48.871871); b.sa("saB", 2.362795, 48.872871)("spB", 2.362795, 48.872871); b.sa("saC", 2.363795, 48.873871)("spC", 2.363795, 48.873871); b.vj("A")("spA", "08:00"_t)("spB", "10:00"_t); b.vj("B")("spC", "09:00"_t)("spD", "11:00"_t); b.vj("C")("spA", "10:00"_t)("spC", "12:00"_t); b.data->complete(); b.make(); b.add_access_point("spA", "AP1", true, true, 10, 23, 48.874871, 2.364795); b.add_access_point("spA", "AP2", true, false, 13, 26, 48.875871, 2.365795); b.add_access_point("spC", "AP3", true, false, 12, 36, 48.876871, 2.366795); b.add_access_point("spC", "AP2", true, false, 13, 26, 48.875871, 2.365795); } }; void complete_pb_creator(navitia::PbCreator& pb_creator, const type::Data& data) { const ptime since = "20190101T000000"_dt; const ptime until = "21190101T000000"_dt; pb_creator.init(&data, since, time_period(since, until)); } bool ap_comp(pbnavitia::AccessPoint& ap1, pbnavitia::AccessPoint& ap2) { return ap1.uri() < ap2.uri(); } BOOST_FIXTURE_TEST_CASE(test_access_point_reading, AccessPointTestFixture) { string filter = ""; int count = 20; int depth = 0; int start_page = 0; vector<string> forbidden_uris = {}; navitia::PbCreator pb_creator; complete_pb_creator(pb_creator, data); access_point::access_points(pb_creator, filter, count, depth, start_page, forbidden_uris); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.access_points().size(), 3); auto access_points = resp.access_points(); sort(access_points.begin(), access_points.end(), ap_comp); auto ap = access_points[0]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP1"); BOOST_REQUIRE_EQUAL(ap.is_entrance(), true); BOOST_REQUIRE_EQUAL(ap.is_exit(), true); BOOST_REQUIRE_EQUAL(ap.length(), 10); BOOST_REQUIRE_EQUAL(ap.traversal_time(), 23); ap = access_points[1]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP2"); BOOST_REQUIRE_EQUAL(ap.is_entrance(), true); BOOST_REQUIRE_EQUAL(ap.is_exit(), false); BOOST_REQUIRE_EQUAL(ap.length(), 13); BOOST_REQUIRE_EQUAL(ap.traversal_time(), 26); ap = access_points[2]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP3"); BOOST_REQUIRE_EQUAL(ap.is_entrance(), true); BOOST_REQUIRE_EQUAL(ap.is_exit(), false); BOOST_REQUIRE_EQUAL(ap.length(), 12); BOOST_REQUIRE_EQUAL(ap.traversal_time(), 36); } BOOST_FIXTURE_TEST_CASE(test_access_point_filtering, AccessPointTestFixture) { { string filter = "stop_point.uri=spA"; int count = 20; int depth = 0; int start_page = 0; vector<string> forbidden_uris = {}; navitia::PbCreator pb_creator; complete_pb_creator(pb_creator, data); access_point::access_points(pb_creator, filter, count, depth, start_page, forbidden_uris); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.access_points().size(), 2); auto access_points = resp.access_points(); sort(access_points.begin(), access_points.end(), ap_comp); auto ap = access_points[0]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP1"); ap = access_points[1]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP2"); } { string filter = "stop_point.uri=spB"; int count = 20; int depth = 0; int start_page = 0; vector<string> forbidden_uris = {}; navitia::PbCreator pb_creator; complete_pb_creator(pb_creator, data); access_point::access_points(pb_creator, filter, count, depth, start_page, forbidden_uris); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.access_points().size(), 0); } { string filter = "stop_area.uri=saC"; int count = 20; int depth = 0; int start_page = 0; vector<string> forbidden_uris = {}; navitia::PbCreator pb_creator; complete_pb_creator(pb_creator, data); access_point::access_points(pb_creator, filter, count, depth, start_page, forbidden_uris); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.access_points().size(), 2); auto access_points = resp.access_points(); sort(access_points.begin(), access_points.end(), ap_comp); auto ap = access_points[0]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP2"); ap = access_points[1]; BOOST_REQUIRE_EQUAL(ap.uri(), "AP3"); } } } // namespace <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief R8C ADC メイン @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "main.hpp" #include "system.hpp" #include "clock.hpp" #include "port.hpp" #include "common/format.hpp" static void wait_(uint16_t n) { while(n > 0) { asm("nop"); --n; } } static timer_b timer_b_; static uart0 uart0_; static flash flash_; void putch_(char ch) { uart0_.putch(ch); } static adc adc_; extern "C" { const void* variable_vectors_[] __attribute__ ((section (".vvec"))) = { (void*)brk_inst_, nullptr, // (0) (void*)null_task_, nullptr, // (1) flash_ready (void*)null_task_, nullptr, // (2) (void*)null_task_, nullptr, // (3) (void*)null_task_, nullptr, // (4) コンパレーターB1 (void*)null_task_, nullptr, // (5) コンパレーターB3 (void*)null_task_, nullptr, // (6) (void*)null_task_, nullptr, // (7) タイマRC (void*)null_task_, nullptr, // (8) (void*)null_task_, nullptr, // (9) (void*)null_task_, nullptr, // (10) (void*)null_task_, nullptr, // (11) (void*)null_task_, nullptr, // (12) (void*)null_task_, nullptr, // (13) キー入力 (void*)null_task_, nullptr, // (14) A/D 変換 (void*)null_task_, nullptr, // (15) (void*)null_task_, nullptr, // (16) (void*)uart0_.send_task, nullptr, // (17) UART0 送信 (void*)uart0_.recv_task, nullptr, // (18) UART0 受信 (void*)null_task_, nullptr, // (19) (void*)null_task_, nullptr, // (20) (void*)null_task_, nullptr, // (21) /INT2 (void*)null_task_, nullptr, // (22) タイマRJ2 (void*)null_task_, nullptr, // (23) 周期タイマ (void*)timer_b_.trb_task, nullptr, // (24) タイマRB2 (void*)null_task_, nullptr, // (25) /INT1 (void*)null_task_, nullptr, // (26) /INT3 (void*)null_task_, nullptr, // (27) (void*)null_task_, nullptr, // (28) (void*)null_task_, nullptr, // (29) /INT0 (void*)null_task_, nullptr, // (30) (void*)null_task_, nullptr, // (31) }; } int main(int argc, char *ragv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; wait_(1000); SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(60, ir_level); } // UART の設定 (P1_4: TXD0[in], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { PMH1E.P14SEL2 = 0; PMH1.P14SEL = 1; PMH1E.P15SEL2 = 0; PMH1.P15SEL = 1; uint8_t ir_level = 1; uart0_.start(19200, ir_level); } uart0_.puts("Start R8C ADC\n"); // ADC の設定(CH1のサイクルモード) // port1.b1 の A/D 変換 { PD1.B1 = 0; adc_.setup(true, device::adc_io::cnv_type::chanel1, 0); adc_.start(); } // L チカ・メイン PD1.B0 = 1; uint8_t cnt = 0; uint32_t nnn = 0; while(1) { timer_b_.sync(); ++cnt; if(cnt >= 30) { cnt = 0; if(adc_.get_state()) { uint16_t v = adc_.get_value(1); utils::format("(%d): %1.2:8y[V], %d\n") % static_cast<uint32_t>(nnn) % static_cast<uint32_t>(((v + 1) * 10) >> 3) % static_cast<uint32_t>(v); adc_.start(); } ++nnn; } if(cnt < 10) P1.B0 = 1; else P1.B0 = 0; if(uart0_.length()) { // UART のレシーブデータがあるか? char ch = uart0_.getch(); uart0_.putch(ch); } } } <commit_msg>コマンドライン部追加<commit_after>//=====================================================================// /*! @file @brief R8C ADC メイン @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "main.hpp" #include "system.hpp" #include "clock.hpp" #include "port.hpp" #include "common/command.hpp" static void wait_(uint16_t n) { while(n > 0) { asm("nop"); --n; } } static timer_b timer_b_; static uart0 uart0_; static flash flash_; extern "C" { void sci_putch(char ch) { uart0_.putch(ch); } char sci_getch(void) { return uart0_.getch(); } uint16_t sci_length() { return uart0_.length(); } void sci_puts(const char* str) { uart0_.puts(str); } } static utils::command<64> command_; extern "C" { const void* variable_vectors_[] __attribute__ ((section (".vvec"))) = { (void*)brk_inst_, nullptr, // (0) (void*)null_task_, nullptr, // (1) flash_ready (void*)null_task_, nullptr, // (2) (void*)null_task_, nullptr, // (3) (void*)null_task_, nullptr, // (4) コンパレーターB1 (void*)null_task_, nullptr, // (5) コンパレーターB3 (void*)null_task_, nullptr, // (6) (void*)null_task_, nullptr, // (7) タイマRC (void*)null_task_, nullptr, // (8) (void*)null_task_, nullptr, // (9) (void*)null_task_, nullptr, // (10) (void*)null_task_, nullptr, // (11) (void*)null_task_, nullptr, // (12) (void*)null_task_, nullptr, // (13) キー入力 (void*)null_task_, nullptr, // (14) A/D 変換 (void*)null_task_, nullptr, // (15) (void*)null_task_, nullptr, // (16) (void*)uart0_.send_task, nullptr, // (17) UART0 送信 (void*)uart0_.recv_task, nullptr, // (18) UART0 受信 (void*)null_task_, nullptr, // (19) (void*)null_task_, nullptr, // (20) (void*)null_task_, nullptr, // (21) /INT2 (void*)null_task_, nullptr, // (22) タイマRJ2 (void*)null_task_, nullptr, // (23) 周期タイマ (void*)timer_b_.trb_task, nullptr, // (24) タイマRB2 (void*)null_task_, nullptr, // (25) /INT1 (void*)null_task_, nullptr, // (26) /INT3 (void*)null_task_, nullptr, // (27) (void*)null_task_, nullptr, // (28) (void*)null_task_, nullptr, // (29) /INT0 (void*)null_task_, nullptr, // (30) (void*)null_task_, nullptr, // (31) }; } int main(int argc, char *ragv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; wait_(1000); SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(60, ir_level); } // UART の設定 (P1_4: TXD0[in], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { PMH1E.P14SEL2 = 0; PMH1.P14SEL = 1; PMH1E.P15SEL2 = 0; PMH1.P15SEL = 1; uint8_t ir_level = 1; uart0_.start(19200, ir_level); } sci_puts("Start R8C FLASH monitor\n"); command_.set_prompt("# "); // LED シグナル用ポートを出力 PD1.B0 = 1; uint8_t cnt = 0; while(1) { timer_b_.sync(); if(command_.service()) { // char cmd[16]; // if(command_.get_word(0, sizeof(cmd), cmd)) { // } } ++cnt; if(cnt >= 30) { cnt = 0; } if(cnt < 10) P1.B0 = 1; else P1.B0 = 0; } } <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/COutputHandler.cpp,v $ $Revision: 1.19 $ $Name: $ $Author: shoops $ $Date: 2006/08/07 19:27:10 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "copasi.h" #include "COutputHandler.h" #include "CCopasiTask.h" #include "report/CCopasiTimer.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "model/CModel.h" COutputHandler::COutputHandler(): COutputInterface(), mInterfaces(), mpMaster(NULL), mObjectRefreshes() {} COutputHandler::COutputHandler(const COutputHandler & src): COutputInterface(src), mInterfaces(src.mInterfaces), mpMaster(src.mpMaster), mObjectRefreshes(src.mObjectRefreshes) {} COutputHandler::~COutputHandler() {}; bool COutputHandler::compile(std::vector< CCopasiContainer * > listOfContainer) { bool success = true; mObjects.clear(); std::set< COutputInterface *>::iterator it = mInterfaces.begin(); std::set< COutputInterface *>::iterator end = mInterfaces.end(); std::set< const CCopasiObject * >::const_iterator itObj; std::set< const CCopasiObject * >::const_iterator endObj; for (; it != end; ++it) { success &= (*it)->compile(listOfContainer); // Assure that this is the only one master. COutputHandler * pHandler = dynamic_cast< COutputHandler * >(*it); if (pHandler != NULL) pHandler->setMaster(this); // Collect the list of objects const std::set< const CCopasiObject * > & Objects = (*it)->getObjects(); for (itObj = Objects.begin(), endObj = Objects.end(); itObj != endObj; ++itObj) mObjects.insert(*itObj); } if (mpMaster == NULL) success &= compileRefresh(listOfContainer); return success; } void COutputHandler::output(const Activity & activity) { if (mpMaster == NULL) refresh(); std::set< COutputInterface *>::iterator it = mInterfaces.begin(); std::set< COutputInterface *>::iterator end = mInterfaces.end(); for (; it != end; ++it) (*it)->output(activity); return; } void COutputHandler::separate(const Activity & activity) { std::set< COutputInterface *>::iterator it = mInterfaces.begin(); std::set< COutputInterface *>::iterator end = mInterfaces.end(); for (; it != end; ++it) (*it)->separate(activity); return; } void COutputHandler::finish() { std::set< COutputInterface *>::iterator it = mInterfaces.begin(); std::set< COutputInterface *>::iterator end = mInterfaces.end(); // This hack is necessary as the reverse iterator behaves strangely // under Visual C++ 6.0, i.e., removing an object advances the iterator. std::vector< COutputInterface * > ToBeRemoved; for (; it != end; ++it) { (*it)->finish(); if (dynamic_cast< CReport * >(*it) != NULL) ToBeRemoved.push_back(*it); } std::vector< COutputInterface * >::iterator itRemove = ToBeRemoved.begin(); std::vector< COutputInterface * >::iterator endRemove = ToBeRemoved.end(); for (; itRemove != endRemove; ++itRemove) removeInterface(*itRemove); return; } void COutputHandler::addInterface(COutputInterface * pInterface) { mInterfaces.insert(pInterface); // Assure that this is the only one master. COutputHandler * pHandler = dynamic_cast< COutputHandler * >(pInterface); if (pHandler != NULL) pHandler->setMaster(this); } void COutputHandler::removeInterface(COutputInterface * pInterface) { mInterfaces.erase(pInterface); // Assure that the removed handler is its own master. COutputHandler * pHandler = dynamic_cast< COutputHandler * >(pInterface); if (pHandler != NULL) pHandler->setMaster(NULL); } void COutputHandler::setMaster(COutputHandler * pMaster) {mpMaster = pMaster;} const bool COutputHandler::isMaster() const {return (mpMaster == NULL);} void COutputHandler::refresh() { std::vector< Refresh * >::iterator it = mObjectRefreshes.begin(); std::vector< Refresh * >::iterator end = mObjectRefreshes.end(); for (;it != end; ++it) (**it)(); } bool COutputHandler::compileRefresh(const std::vector< CCopasiContainer * > & listOfContainer) { CModel * pModel = dynamic_cast< CModel * >(CCopasiContainer::ObjectFromName(listOfContainer, CCopasiObjectName("Model=" + CCopasiDataModel::Global->getModel()->getObjectName()))); mObjectRefreshes = CCopasiObject::buildUpdateSequence(mObjects, pModel); std::set< const CCopasiObject * >::const_iterator it = mObjects.begin(); std::set< const CCopasiObject * >::const_iterator end = mObjects.end(); // Timers are treated differently they are started during compilation. for (; it != end; ++it) if (dynamic_cast< const CCopasiTimer * >(*it)) const_cast< CCopasiTimer * >(static_cast< const CCopasiTimer * >(*it))->start(); return true; } <commit_msg>Fixed assertion violation reported in Bug 630 for the snapshot 200608024.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/COutputHandler.cpp,v $ $Revision: 1.20 $ $Name: $ $Author: shoops $ $Date: 2006/08/25 19:13:52 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "copasi.h" #include "COutputHandler.h" #include "CCopasiTask.h" #include "report/CCopasiTimer.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "model/CModel.h" COutputHandler::COutputHandler(): COutputInterface(), mInterfaces(), mpMaster(NULL), mObjectRefreshes() {} COutputHandler::COutputHandler(const COutputHandler & src): COutputInterface(src), mInterfaces(src.mInterfaces), mpMaster(src.mpMaster), mObjectRefreshes(src.mObjectRefreshes) {} COutputHandler::~COutputHandler() {}; bool COutputHandler::compile(std::vector< CCopasiContainer * > listOfContainer) { bool success = true; mObjects.clear(); std::set< COutputInterface *>::iterator it = mInterfaces.begin(); std::set< COutputInterface *>::iterator end = mInterfaces.end(); std::set< const CCopasiObject * >::const_iterator itObj; std::set< const CCopasiObject * >::const_iterator endObj; for (; it != end; ++it) { success &= (*it)->compile(listOfContainer); // Assure that this is the only one master. COutputHandler * pHandler = dynamic_cast< COutputHandler * >(*it); if (pHandler != NULL) pHandler->setMaster(this); // Collect the list of objects const std::set< const CCopasiObject * > & Objects = (*it)->getObjects(); for (itObj = Objects.begin(), endObj = Objects.end(); itObj != endObj; ++itObj) mObjects.insert(*itObj); } if (mpMaster == NULL) success &= compileRefresh(listOfContainer); return success; } void COutputHandler::output(const Activity & activity) { if (mpMaster == NULL) refresh(); std::set< COutputInterface *>::iterator it = mInterfaces.begin(); std::set< COutputInterface *>::iterator end = mInterfaces.end(); for (; it != end; ++it) (*it)->output(activity); return; } void COutputHandler::separate(const Activity & activity) { std::set< COutputInterface *>::iterator it = mInterfaces.begin(); std::set< COutputInterface *>::iterator end = mInterfaces.end(); for (; it != end; ++it) (*it)->separate(activity); return; } void COutputHandler::finish() { std::set< COutputInterface *>::iterator it = mInterfaces.begin(); std::set< COutputInterface *>::iterator end = mInterfaces.end(); // This hack is necessary as the reverse iterator behaves strangely // under Visual C++ 6.0, i.e., removing an object advances the iterator. std::vector< COutputInterface * > ToBeRemoved; for (; it != end; ++it) { (*it)->finish(); if (dynamic_cast< CReport * >(*it) != NULL) ToBeRemoved.push_back(*it); } std::vector< COutputInterface * >::iterator itRemove = ToBeRemoved.begin(); std::vector< COutputInterface * >::iterator endRemove = ToBeRemoved.end(); for (; itRemove != endRemove; ++itRemove) removeInterface(*itRemove); return; } void COutputHandler::addInterface(COutputInterface * pInterface) { mInterfaces.insert(pInterface); // Assure that this is the only one master. COutputHandler * pHandler = dynamic_cast< COutputHandler * >(pInterface); if (pHandler != NULL) pHandler->setMaster(this); } void COutputHandler::removeInterface(COutputInterface * pInterface) { mInterfaces.erase(pInterface); // Assure that the removed handler is its own master. COutputHandler * pHandler = dynamic_cast< COutputHandler * >(pInterface); if (pHandler != NULL) pHandler->setMaster(NULL); } void COutputHandler::setMaster(COutputHandler * pMaster) {mpMaster = pMaster;} const bool COutputHandler::isMaster() const {return (mpMaster == NULL);} void COutputHandler::refresh() { std::vector< Refresh * >::iterator it = mObjectRefreshes.begin(); std::vector< Refresh * >::iterator end = mObjectRefreshes.end(); for (;it != end; ++it) (**it)(); } bool COutputHandler::compileRefresh(const std::vector< CCopasiContainer * > & listOfContainer) { CModel * pModel = dynamic_cast< CModel * >(CCopasiContainer::ObjectFromName(listOfContainer, CCopasiDataModel::Global->getModel()->getCN())); mObjectRefreshes = CCopasiObject::buildUpdateSequence(mObjects, pModel); std::set< const CCopasiObject * >::const_iterator it = mObjects.begin(); std::set< const CCopasiObject * >::const_iterator end = mObjects.end(); // Timers are treated differently they are started during compilation. for (; it != end; ++it) if (dynamic_cast< const CCopasiTimer * >(*it)) const_cast< CCopasiTimer * >(static_cast< const CCopasiTimer * >(*it))->start(); return true; } <|endoftext|>
<commit_before>#include <set> #include <errno.h> #include <string.h> #include "ModuleConfig.hh" #include "str.hh" #include "FeatureGenerator.hh" namespace aku { FeatureGenerator::FeatureGenerator(void) : m_base_module(NULL), m_last_module(NULL), m_file(NULL), m_dont_fclose(false), m_eof_on_last_frame(false) { } FeatureGenerator::~FeatureGenerator() { for (int i = 0; i < (int)m_modules.size(); i++) delete m_modules[i]; } void FeatureGenerator::open(const std::string &filename) { if (m_file != NULL) close(); FILE *file = fopen(filename.c_str(), "rb"); if (file == NULL) throw std::string("could not open file ") + filename + ": " + strerror(errno); open(file, false); } void FeatureGenerator::open(FILE *file, bool dont_fclose, bool stream) { if (m_file != NULL) close(); m_file = file; m_dont_fclose = dont_fclose; for (int i = 0; i < (int)m_modules.size(); i++) m_modules[i]->reset(); assert( m_base_module != NULL ); m_base_module->set_file(m_file, stream); } void FeatureGenerator::close(void) { if (m_file != NULL) { m_base_module->discard_file(); if (!m_dont_fclose) fclose(m_file); m_file = NULL; } } void FeatureGenerator::load_configuration(FILE *file) { assert(m_modules.empty()); std::string line; int lineno = 0; while (str::read_line(&line, file, true)) { lineno++; str::clean(&line, " \t"); if (line.empty()) continue; if (line != "module") throw str::fmt(256, "expected keyword 'module' on line %d: ", lineno) + line; // Read module config // ModuleConfig config; try { config.read(file); } catch (std::string &str) { lineno += config.num_lines_read(); throw str::fmt(256, "failed reading feature module around line %d: ", lineno) + str; } lineno += config.num_lines_read(); // Create module // std::string type; std::string name; if (!config.get("type", type)) throw str::fmt(256, "type not defined for module ending on line %d", lineno); if (!config.get("name", name)) throw str::fmt(256, "name not defined for module ending on line %d", lineno); assert(!name.empty()); if (name.find_first_of(" \t\n") != std::string::npos) throw std::string("module name may not contain whitespaces"); FeatureModule *module = NULL; if (type == AudioFileModule::type_str()) module = new AudioFileModule(this); else if (type == FFTModule::type_str()) module = new FFTModule(); else if (type == PreModule::type_str()) module = new PreModule(); else if (type == MelModule::type_str()) module = new MelModule(this); else if (type == PowerModule::type_str()) module = new PowerModule(); else if (type == MelPowerModule::type_str()) module = new MelPowerModule(); else if (type == DCTModule::type_str()) module = new DCTModule(); else if (type == DeltaModule::type_str()) module = new DeltaModule(); else if (type == NormalizationModule::type_str()) module = new NormalizationModule(); else if (type == LinTransformModule::type_str()) module = new LinTransformModule(); else if (type == MergerModule::type_str()) module = new MergerModule(); else if (type == MeanSubtractorModule::type_str()) module = new MeanSubtractorModule(); else if (type == ConcatModule::type_str()) module = new ConcatModule(); else if (type == VtlnModule::type_str()) module = new VtlnModule(); else if (type == SRNormModule::type_str()) module = new SRNormModule(); else if (type == QuantEqModule::type_str()) module = new QuantEqModule(); else throw std::string("Unknown module type '") + type + std::string("'"); module->set_name(name); // Insert module in module structures // if (m_modules.empty()) { m_base_module = dynamic_cast<BaseFeaModule*>(module); if (m_base_module == NULL) throw std::string("first module should be a base module"); } m_last_module = module; m_modules.push_back(module); if (m_module_map.find(name) != m_module_map.end()) throw std::string("multiple definitions of module name: ") + name; m_module_map[name] = module; // Create source links // bool has_sources = config.exists("sources"); if (m_base_module == module && has_sources) throw std::string("can not define sources for the first module"); if (m_base_module != module && !has_sources) throw std::string("sources not defined for module: ") + name; if (has_sources) { std::vector<std::string> sources; config.get("sources", sources); assert(!sources.empty()); for (int i = 0; i < (int)sources.size(); i++) { ModuleMap::iterator it = m_module_map.find(sources[i]); if (it == m_module_map.end()) throw std::string("unknown source module: ") + sources[i]; module->add_source(it->second); } } module->set_config(config); } compute_init_buffers(); check_model_structure(); } void FeatureGenerator::write_configuration(FILE *file) { assert(!m_modules.empty()); for (int i = 0; i < (int)m_modules.size(); i++) { FeatureModule *module = m_modules[i]; ModuleConfig config; module->get_config(config); if (!module->sources().empty()) { std::vector<std::string> sources; for (int i = 0; i < (int)module->sources().size(); i++) sources.push_back(module->sources().at(i)->name()); config.set("sources", sources); } fputs("module\n", file); config.write(file, 0); fputs("\n", file); } } FeatureModule* FeatureGenerator::module(const std::string &name) { ModuleMap::iterator it = m_module_map.find(name); if (it == m_module_map.end()) throw std::string("unknown module requested: ") + name; return it->second; } void // private FeatureGenerator::compute_init_buffers() { // Compute number of targets for each module. // std::vector<int> target_counts(m_modules.size(), 0); std::map<FeatureModule*, int> index_map; for (int i = 0; i < (int)m_modules.size(); i++) index_map[m_modules[i]] = i; for (int i = 0; i < (int)m_modules.size(); i++) { FeatureModule *module = m_modules[i]; for (int j = 0; j < (int)module->sources().size(); j++) { int src_index = index_map[module->sources()[j]]; target_counts[src_index]++; } } // Find bottle-neck modules, i.e. modules that are not in a branch. // Below it is assumed that m_modules is sorted topologically so // that sources are always before targets. // std::vector<bool> bottle_neck(m_modules.size(), false); int cur_branch_level = 0; for (int i = m_modules.size() - 1; i >= 0; i--) { FeatureModule *module = m_modules[i]; if (target_counts.at(i) >= 2) cur_branch_level -= target_counts.at(i) - 1; assert(cur_branch_level >= 0); if (cur_branch_level == 0) bottle_neck.at(i) = true; if (module->sources().size() >= 2) cur_branch_level += module->sources().size() - 1; } // Every target-branching module M must have a buffer offsets that // include the largest offsets between M and the next bottle-neck // module. Otherwise, duplicated computation is done when buffers // are filled for the first time (thus the name init_offset_left and // right). Some target-branching modules could actually have // smaller buffers, but it would be more complicated to compute the // minimal size. // for (int i = m_modules.size() - 1; i >= 0; i--) { FeatureModule *module = m_modules[i]; if (!bottle_neck[i]) { for (int j = 0; j < (int)module->sources().size(); j++) { FeatureModule *src_module = module->sources()[j]; src_module->update_init_offsets(*module); } } } } void // private FeatureGenerator::check_model_structure() { if (m_modules.empty()) throw std::string("no feature modules defined"); std::set<FeatureModule*> reached; std::vector<FeatureModule*> stack; stack.push_back(m_last_module); while (!stack.empty()) { FeatureModule *module = stack.back(); stack.pop_back(); for (int i = 0; i < (int)module->sources().size(); i++) { FeatureModule *source = module->sources().at(i); std::pair<std::set<FeatureModule*>::iterator, bool> ret = reached.insert(source); if (ret.second) stack.push_back(source); } } assert(!m_modules.empty()); for (int i = 0; i < (int)m_modules.size() - 1; i++) if (reached.find(m_modules[i]) == reached.end()) fprintf(stderr, "WARNING: module %s (type %s) not used as input\n", m_modules[i]->name().c_str(), m_modules[i]->type_str().c_str()); } void FeatureGenerator::print_dot_graph(FILE *file) { fprintf(file, "digraph features {\n"); fprintf(file, "rankdir=RL;\n"); for (int i = 0; i < (int)m_modules.size(); i++) { FeatureModule *module = m_modules[i]; module->print_dot_node(file); } for (int i = 0; i < (int)m_modules.size(); i++) { FeatureModule *module = m_modules[i]; for (int j = 0; j < (int)module->sources().size(); j++) { fprintf(file, "\t%s -> %s;\n", module->name().c_str(), module->sources()[j]->name().c_str()); } } fprintf(file, "}\n"); } } <commit_msg>*** empty log message ***<commit_after>#include <set> #include <errno.h> #include <string.h> #include "ModuleConfig.hh" #include "str.hh" #include "FeatureGenerator.hh" namespace aku { FeatureGenerator::FeatureGenerator(void) : m_base_module(NULL), m_last_module(NULL), m_file(NULL), m_dont_fclose(false), m_eof_on_last_frame(false) { } FeatureGenerator::~FeatureGenerator() { for (int i = 0; i < (int)m_modules.size(); i++) delete m_modules[i]; } void FeatureGenerator::open(const std::string &filename) { if (m_file != NULL) close(); FILE *file = fopen(filename.c_str(), "rb"); if (file == NULL) throw std::string("could not open file ") + filename + ": " + strerror(errno); open(file, false); } void FeatureGenerator::open(FILE *file, bool dont_fclose, bool stream) { if (m_file != NULL) close(); m_file = file; m_dont_fclose = dont_fclose; for (int i = 0; i < (int)m_modules.size(); i++) m_modules[i]->reset(); assert( m_base_module != NULL ); m_base_module->set_file(m_file, stream); } void FeatureGenerator::close(void) { if (m_file != NULL) { m_base_module->discard_file(); if (!m_dont_fclose) fclose(m_file); m_file = NULL; } } void FeatureGenerator::load_configuration(FILE *file) { assert(m_modules.empty()); std::string line; int lineno = 0; while (str::read_line(&line, file, true)) { lineno++; str::clean(&line, " \t"); if (line.empty()) continue; if (line != "module") throw str::fmt(256, "expected keyword 'module' on line %d: ", lineno) + line; // Read module config // ModuleConfig config; try { config.read(file); } catch (std::string &str) { lineno += config.num_lines_read(); throw str::fmt(256, "failed reading feature module around line %d: ", lineno) + str; } lineno += config.num_lines_read(); // Create module // std::string type; std::string name; if (!config.get("type", type)) throw str::fmt(256, "type not defined for module ending on line %d", lineno); if (!config.get("name", name)) throw str::fmt(256, "name not defined for module ending on line %d", lineno); assert(!name.empty()); if (name.find_first_of(" \t\n") != std::string::npos) throw std::string("module name may not contain whitespaces"); FeatureModule *module = NULL; if (type == AudioFileModule::type_str()) module = new AudioFileModule(this); else if (type == FFTModule::type_str()) module = new FFTModule(); else if (type == PreModule::type_str()) module = new PreModule(); else if (type == MelModule::type_str()) module = new MelModule(this); else if (type == PowerModule::type_str()) module = new PowerModule(); else if (type == MelPowerModule::type_str()) module = new MelPowerModule(); else if (type == DCTModule::type_str()) module = new DCTModule(); else if (type == DeltaModule::type_str()) module = new DeltaModule(); else if (type == NormalizationModule::type_str()) module = new NormalizationModule(); else if (type == LinTransformModule::type_str()) module = new LinTransformModule(); else if (type == MergerModule::type_str()) module = new MergerModule(); else if (type == MeanSubtractorModule::type_str()) module = new MeanSubtractorModule(); else if (type == ConcatModule::type_str()) module = new ConcatModule(); else if (type == VtlnModule::type_str()) module = new VtlnModule(); else if (type == SRNormModule::type_str()) module = new SRNormModule(); else if (type == QuantEqModule::type_str()) module = new QuantEqModule(); else throw std::string("Unknown module type '") + type + std::string("'"); module->set_name(name); // Insert module in module structures // if (m_modules.empty()) { m_base_module = dynamic_cast<BaseFeaModule*>(module); if (m_base_module == NULL) throw std::string("first module should be a base module"); } m_last_module = module; m_modules.push_back(module); if (m_module_map.find(name) != m_module_map.end()) throw std::string("multiple definitions of module name: ") + name; m_module_map[name] = module; // Create source links // bool has_sources = config.exists("sources"); if (m_base_module == module && has_sources) throw std::string("can not define sources for the first module"); if (m_base_module != module && !has_sources) throw std::string("sources not defined for module: ") + name; if (has_sources) { std::vector<std::string> sources; config.get("sources", sources); assert(!sources.empty()); for (int i = 0; i < (int)sources.size(); i++) { ModuleMap::iterator it = m_module_map.find(sources[i]); if (it == m_module_map.end()) throw std::string("unknown source module: ") + sources[i]; module->add_source(it->second); } } module->set_config(config); } compute_init_buffers(); check_model_structure(); } void FeatureGenerator::write_configuration(FILE *file) { assert(!m_modules.empty()); for (int i = 0; i < (int)m_modules.size(); i++) { FeatureModule *module = m_modules[i]; ModuleConfig config; module->get_config(config); if (!module->sources().empty()) { std::vector<std::string> sources; for (int i = 0; i < (int)module->sources().size(); i++) sources.push_back(module->sources().at(i)->name()); config.set("sources", sources); } fputs("module\n", file); config.write(file, 0); fputs("\n", file); } } FeatureModule* FeatureGenerator::module(const std::string &name) { ModuleMap::iterator it = m_module_map.find(name); if (it == m_module_map.end()) throw std::string("unknown module requested: ") + name; return it->second; } void // private FeatureGenerator::compute_init_buffers() { // Compute number of targets for each module. // std::vector<int> target_counts(m_modules.size(), 0); std::map<FeatureModule*, int> index_map; for (int i = 0; i < (int)m_modules.size(); i++) index_map[m_modules[i]] = i; for (int i = 0; i < (int)m_modules.size(); i++) { FeatureModule *module = m_modules[i]; for (int j = 0; j < (int)module->sources().size(); j++) { int src_index = index_map[module->sources()[j]]; target_counts[src_index]++; } } // Find bottle-neck modules, i.e. modules that are not in a branch. // Below it is assumed that m_modules is sorted topologically so // that sources are always before targets. // std::vector<bool> bottle_neck(m_modules.size(), false); int cur_branch_level = 0; for (int i = m_modules.size() - 1; i >= 0; i--) { FeatureModule *module = m_modules[i]; if (target_counts.at(i) >= 2) cur_branch_level -= target_counts.at(i) - 1; assert(cur_branch_level >= 0); if (cur_branch_level == 0) bottle_neck.at(i) = true; if (module->sources().size() >= 2) cur_branch_level += module->sources().size() - 1; } // Every target-branching module M must have buffer offsets that // include the largest offsets between M and the next bottle-neck // module. Otherwise, duplicated computation is done when buffers // are filled for the first time (thus the name init_offset_left and // right). Some target-branching modules could actually have // smaller buffers, but it would be more complicated to compute the // minimal size. // for (int i = m_modules.size() - 1; i >= 0; i--) { FeatureModule *module = m_modules[i]; if (!bottle_neck[i]) { for (int j = 0; j < (int)module->sources().size(); j++) { FeatureModule *src_module = module->sources()[j]; src_module->update_init_offsets(*module); } } } } void // private FeatureGenerator::check_model_structure() { if (m_modules.empty()) throw std::string("no feature modules defined"); std::set<FeatureModule*> reached; std::vector<FeatureModule*> stack; stack.push_back(m_last_module); while (!stack.empty()) { FeatureModule *module = stack.back(); stack.pop_back(); for (int i = 0; i < (int)module->sources().size(); i++) { FeatureModule *source = module->sources().at(i); std::pair<std::set<FeatureModule*>::iterator, bool> ret = reached.insert(source); if (ret.second) stack.push_back(source); } } assert(!m_modules.empty()); for (int i = 0; i < (int)m_modules.size() - 1; i++) if (reached.find(m_modules[i]) == reached.end()) fprintf(stderr, "WARNING: module %s (type %s) not used as input\n", m_modules[i]->name().c_str(), m_modules[i]->type_str().c_str()); } void FeatureGenerator::print_dot_graph(FILE *file) { fprintf(file, "digraph features {\n"); fprintf(file, "rankdir=RL;\n"); for (int i = 0; i < (int)m_modules.size(); i++) { FeatureModule *module = m_modules[i]; module->print_dot_node(file); } for (int i = 0; i < (int)m_modules.size(); i++) { FeatureModule *module = m_modules[i]; for (int j = 0; j < (int)module->sources().size(); j++) { fprintf(file, "\t%s -> %s;\n", module->name().c_str(), module->sources()[j]->name().c_str()); } } fprintf(file, "}\n"); } } <|endoftext|>
<commit_before>#include "constant.h" #include "function.h" #include "module.h" #include "module_p.h" #include "modulemap_p.h" static void moduleNotFound(int number) { zend_error( E_WARNING, "Unable to find the module by number %d. Probably phpcxx::Module instance has been destroyed too early", number ); } phpcxx::ModulePrivate::ModulePrivate(phpcxx::Module* const q, const char* name, const char* version) : q_ptr(q) { this->entry.name = name; this->entry.version = version; this->entry.globals_size = sizeof(zend_phpcxx_globals); #ifdef ZTS this->entry.globals_id_ptr = &this->phpcxx_globals_id; #else this->entry.globals_ptr = &this->globals; this->globals.phpcxx_globals = nullptr; #endif ModuleMap::instance().add(this); } phpcxx::ModulePrivate::~ModulePrivate() { ModuleMap::instance().remove(this->entry.module_number); } zend_module_entry* phpcxx::ModulePrivate::module() { static zend_function_entry empty; assert(empty.fname == nullptr && empty.handler == nullptr && empty.arg_info == nullptr); if (!this->entry.functions) { this->m_funcs = this->q_ptr->functions(); this->m_zf.reset(new zend_function_entry[this->m_funcs.size()+1]); zend_function_entry* ptr = this->m_zf.get(); for (auto&& f : this->m_funcs) { *ptr++ = f.getFE(); } *ptr = empty; this->entry.functions = this->m_zf.get(); } return &this->entry; } int phpcxx::ModulePrivate::moduleStartup(INIT_FUNC_ARGS) { ModuleMap::instance().onGINIT(); zend_module_entry* me = EG(current_module); assert(me != nullptr); phpcxx::ModulePrivate* e = ModuleMap::instance().mapIdToModule(me->name, module_number); if (EXPECTED(e)) { #ifdef ZTS ZEND_TSRMG(e->phpcxx_globals_id, zend_phpcxx_globals*, globals) = e->q_ptr->globalsConstructor(); #else e->phpcxx_globals.globals = e->q_ptr->globalsConstructor(); #endif // e->registerIniEntries(); // e->registerClasses(); e->registerConstants(); e->registerOtherModules(); try { return e->q_ptr->moduleStartup() ? SUCCESS : FAILURE; } catch (const std::exception& e) { zend_error(E_ERROR, "%s", e.what()); return FAILURE; } } moduleNotFound(module_number); return SUCCESS; } int phpcxx::ModulePrivate::moduleShutdown(SHUTDOWN_FUNC_ARGS) { zend_unregister_ini_entries(module_number); phpcxx::ModulePrivate* e = ModuleMap::instance().byId(module_number); ModuleMap::instance().remove(module_number); int retcode; if (EXPECTED(e)) { try { retcode = e->q_ptr->moduleShutdown() ? SUCCESS : FAILURE; } catch (const std::exception& e) { retcode = FAILURE; } e->q_ptr->globalsDestructor(e->globals()); } else { moduleNotFound(module_number); retcode = SUCCESS; } ModuleMap::instance().onGSHUTDOWN(); return retcode; } int phpcxx::ModulePrivate::requestStartup(INIT_FUNC_ARGS) { phpcxx::ModulePrivate* e = ModuleMap::instance().byId(module_number); if (EXPECTED(e)) { try { return e->q_ptr->requestStartup() ? SUCCESS : FAILURE; } catch (const std::exception& e) { zend_error(E_ERROR, "%s", e.what()); return FAILURE; } } moduleNotFound(module_number); return SUCCESS; } int phpcxx::ModulePrivate::requestShutdown(SHUTDOWN_FUNC_ARGS) { phpcxx::ModulePrivate* e = ModuleMap::instance().byId(module_number); if (EXPECTED(e)) { try { return e->q_ptr->requestShutdown() ? SUCCESS : FAILURE; } catch (const std::exception& e) { zend_error(E_ERROR, "%s", e.what()); return FAILURE; } } moduleNotFound(module_number); return SUCCESS; } void phpcxx::ModulePrivate::moduleInfo(ZEND_MODULE_INFO_FUNC_ARGS) { phpcxx::ModulePrivate* e = ModuleMap::instance().byId(zend_module->module_number); if (EXPECTED(e)) { e->q_ptr->moduleInfo(); } else { moduleNotFound(zend_module->module_number); } } void phpcxx::ModulePrivate::registerOtherModules() { std::vector<Module*> others = this->q_ptr->otherModules(); for (auto&& m : others) { /// TODO check if return value is SUCCESS zend_startup_module(m->module()); } } void phpcxx::ModulePrivate::registerConstants() { std::vector<phpcxx::Constant> constants = std::move(this->q_ptr->constants()); for (auto&& c : constants) { zend_constant& zc = c.get(); zc.module_number = this->entry.module_number; if (FAILURE == zend_register_constant(&zc)) { // Zend calls zend_string_release() for constant name upon failure zval_ptr_dtor(&zc.value); } } } <commit_msg>moving a temporary object prevents copy elision<commit_after>#include "constant.h" #include "function.h" #include "module.h" #include "module_p.h" #include "modulemap_p.h" static void moduleNotFound(int number) { zend_error( E_WARNING, "Unable to find the module by number %d. Probably phpcxx::Module instance has been destroyed too early", number ); } phpcxx::ModulePrivate::ModulePrivate(phpcxx::Module* const q, const char* name, const char* version) : q_ptr(q) { this->entry.name = name; this->entry.version = version; this->entry.globals_size = sizeof(zend_phpcxx_globals); #ifdef ZTS this->entry.globals_id_ptr = &this->phpcxx_globals_id; #else this->entry.globals_ptr = &this->globals; this->globals.phpcxx_globals = nullptr; #endif ModuleMap::instance().add(this); } phpcxx::ModulePrivate::~ModulePrivate() { ModuleMap::instance().remove(this->entry.module_number); } zend_module_entry* phpcxx::ModulePrivate::module() { static zend_function_entry empty; assert(empty.fname == nullptr && empty.handler == nullptr && empty.arg_info == nullptr); if (!this->entry.functions) { this->m_funcs = this->q_ptr->functions(); this->m_zf.reset(new zend_function_entry[this->m_funcs.size()+1]); zend_function_entry* ptr = this->m_zf.get(); for (auto&& f : this->m_funcs) { *ptr++ = f.getFE(); } *ptr = empty; this->entry.functions = this->m_zf.get(); } return &this->entry; } int phpcxx::ModulePrivate::moduleStartup(INIT_FUNC_ARGS) { ModuleMap::instance().onGINIT(); zend_module_entry* me = EG(current_module); assert(me != nullptr); phpcxx::ModulePrivate* e = ModuleMap::instance().mapIdToModule(me->name, module_number); if (EXPECTED(e)) { #ifdef ZTS ZEND_TSRMG(e->phpcxx_globals_id, zend_phpcxx_globals*, globals) = e->q_ptr->globalsConstructor(); #else e->phpcxx_globals.globals = e->q_ptr->globalsConstructor(); #endif // e->registerIniEntries(); // e->registerClasses(); e->registerConstants(); e->registerOtherModules(); try { return e->q_ptr->moduleStartup() ? SUCCESS : FAILURE; } catch (const std::exception& e) { zend_error(E_ERROR, "%s", e.what()); return FAILURE; } } moduleNotFound(module_number); return SUCCESS; } int phpcxx::ModulePrivate::moduleShutdown(SHUTDOWN_FUNC_ARGS) { zend_unregister_ini_entries(module_number); phpcxx::ModulePrivate* e = ModuleMap::instance().byId(module_number); ModuleMap::instance().remove(module_number); int retcode; if (EXPECTED(e)) { try { retcode = e->q_ptr->moduleShutdown() ? SUCCESS : FAILURE; } catch (const std::exception& e) { retcode = FAILURE; } e->q_ptr->globalsDestructor(e->globals()); } else { moduleNotFound(module_number); retcode = SUCCESS; } ModuleMap::instance().onGSHUTDOWN(); return retcode; } int phpcxx::ModulePrivate::requestStartup(INIT_FUNC_ARGS) { phpcxx::ModulePrivate* e = ModuleMap::instance().byId(module_number); if (EXPECTED(e)) { try { return e->q_ptr->requestStartup() ? SUCCESS : FAILURE; } catch (const std::exception& e) { zend_error(E_ERROR, "%s", e.what()); return FAILURE; } } moduleNotFound(module_number); return SUCCESS; } int phpcxx::ModulePrivate::requestShutdown(SHUTDOWN_FUNC_ARGS) { phpcxx::ModulePrivate* e = ModuleMap::instance().byId(module_number); if (EXPECTED(e)) { try { return e->q_ptr->requestShutdown() ? SUCCESS : FAILURE; } catch (const std::exception& e) { zend_error(E_ERROR, "%s", e.what()); return FAILURE; } } moduleNotFound(module_number); return SUCCESS; } void phpcxx::ModulePrivate::moduleInfo(ZEND_MODULE_INFO_FUNC_ARGS) { phpcxx::ModulePrivate* e = ModuleMap::instance().byId(zend_module->module_number); if (EXPECTED(e)) { e->q_ptr->moduleInfo(); } else { moduleNotFound(zend_module->module_number); } } void phpcxx::ModulePrivate::registerOtherModules() { std::vector<Module*> others = this->q_ptr->otherModules(); for (auto&& m : others) { /// TODO check if return value is SUCCESS zend_startup_module(m->module()); } } void phpcxx::ModulePrivate::registerConstants() { std::vector<phpcxx::Constant> constants = this->q_ptr->constants(); for (auto&& c : constants) { zend_constant& zc = c.get(); zc.module_number = this->entry.module_number; if (FAILURE == zend_register_constant(&zc)) { // Zend calls zend_string_release() for constant name upon failure zval_ptr_dtor(&zc.value); } } } <|endoftext|>
<commit_before>/* This file is part of the KDE libraries Copyright (C) 2001-2004 Christoph Cullmann <cullmann@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 version 2 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 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 "katefactory.h" #include "katedocument.h" #include "kateview.h" #include "katerenderer.h" #include "katecmds.h" #include "katefiletype.h" #include "kateschema.h" #include "kateconfig.h" #include "../interfaces/katecmd.h" #include <klocale.h> #include <kdirwatch.h> #include <kstaticdeleter.h> /** * dummy wrapper factory to be sure nobody external deletes our katefactory */ class KateFactoryPublic : public KParts::Factory { public: /** * reimplemented create object method * @param parentWidget parent widget * @param widgetName widget name * @param parent QObject parent * @param name object name * @param args additional arguments * @return constructed part object */ KParts::Part *createPartObject ( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const char *classname, const QStringList &args ) { return KateFactory::self()->createPartObject (parentWidget, widgetName, parent, name, classname, args); } }; extern "C" { void *init_libkatepart() { return new KateFactoryPublic (); } } KateFactory *KateFactory::s_self = 0; KateFactory::KateFactory () : m_aboutData ("katepart", I18N_NOOP("Kate Part"), "2.2", I18N_NOOP( "Embeddable editor component" ), KAboutData::License_LGPL_V2, I18N_NOOP( "(c) 2000-2004 The Kate Authors" ), 0, "http://kate.kde.org") , m_instance (&m_aboutData) , m_plugins (KTrader::self()->query("KTextEditor/Plugin")) { // set s_self s_self = this; // // fill about data // m_aboutData.addAuthor ("Christoph Cullmann", I18N_NOOP("Maintainer"), "cullmann@kde.org", "http://www.babylon2k.de"); m_aboutData.addAuthor ("Anders Lund", I18N_NOOP("Core Developer"), "anders@alweb.dk", "http://www.alweb.dk"); m_aboutData.addAuthor ("Joseph Wenninger", I18N_NOOP("Core Developer"), "jowenn@kde.org","http://stud3.tuwien.ac.at/~e9925371"); m_aboutData.addAuthor ("Hamish Rodda",I18N_NOOP("Core Developer"), "rodda@kde.org"); m_aboutData.addAuthor ("Waldo Bastian", I18N_NOOP( "The cool buffersystem" ), "bastian@kde.org" ); m_aboutData.addAuthor ("Charles Samuels", I18N_NOOP("The Editing Commands"), "charles@kde.org"); m_aboutData.addAuthor ("Matt Newell", I18N_NOOP("Testing, ..."), "newellm@proaxis.com"); m_aboutData.addAuthor ("Michael Bartl", I18N_NOOP("Former Core Developer"), "michael.bartl1@chello.at"); m_aboutData.addAuthor ("Michael McCallum", I18N_NOOP("Core Developer"), "gholam@xtra.co.nz"); m_aboutData.addAuthor ("Jochen Wilhemly", I18N_NOOP( "KWrite Author" ), "digisnap@cs.tu-berlin.de" ); m_aboutData.addAuthor ("Michael Koch",I18N_NOOP("KWrite port to KParts"), "koch@kde.org"); m_aboutData.addAuthor ("Christian Gebauer", 0, "gebauer@kde.org" ); m_aboutData.addAuthor ("Simon Hausmann", 0, "hausmann@kde.org" ); m_aboutData.addAuthor ("Glen Parker",I18N_NOOP("KWrite Undo History, Kspell integration"), "glenebob@nwlink.com"); m_aboutData.addAuthor ("Scott Manson",I18N_NOOP("KWrite XML Syntax highlighting support"), "sdmanson@alltel.net"); m_aboutData.addAuthor ("John Firebaugh",I18N_NOOP("Patches and more"), "jfirebaugh@kde.org"); m_aboutData.addAuthor ("Dominik Haumann", I18N_NOOP("Developer & Highlight wizard"), "dhdev@gmx.de"); m_aboutData.addCredit ("Matteo Merli",I18N_NOOP("Highlighting for RPM Spec-Files, Perl, Diff and more"), "merlim@libero.it"); m_aboutData.addCredit ("Rocky Scaletta",I18N_NOOP("Highlighting for VHDL"), "rocky@purdue.edu"); m_aboutData.addCredit ("Yury Lebedev",I18N_NOOP("Highlighting for SQL"),""); m_aboutData.addCredit ("Chris Ross",I18N_NOOP("Highlighting for Ferite"),""); m_aboutData.addCredit ("Nick Roux",I18N_NOOP("Highlighting for ILERPG"),""); m_aboutData.addCredit ("Carsten Niehaus", I18N_NOOP("Highlighting for LaTeX"),""); m_aboutData.addCredit ("Per Wigren", I18N_NOOP("Highlighting for Makefiles, Python"),""); m_aboutData.addCredit ("Jan Fritz", I18N_NOOP("Highlighting for Python"),""); m_aboutData.addCredit ("Daniel Naber","",""); m_aboutData.addCredit ("Roland Pabel",I18N_NOOP("Highlighting for Scheme"),""); m_aboutData.addCredit ("Cristi Dumitrescu",I18N_NOOP("PHP Keyword/Datatype list"),""); m_aboutData.addCredit ("Carsten Pfeiffer", I18N_NOOP("Very nice help"), ""); m_aboutData.addCredit (I18N_NOOP("All people who have contributed and I have forgotten to mention"),"",""); m_aboutData.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails")); // // dir watch // m_dirWatch = new KDirWatch (); // // filetype man // m_fileTypeManager = new KateFileTypeManager (); // // schema man // m_schemaManager = new KateSchemaManager (); // config objects m_documentConfig = new KateDocumentConfig (); m_viewConfig = new KateViewConfig (); m_rendererConfig = new KateRendererConfig (); // // init the cmds // KateCmd::self()->registerCommand (new KateCommands::CoreCommands()); KateCmd::self()->registerCommand (new KateCommands::SedReplace ()); KateCmd::self()->registerCommand (new KateCommands::Character ()); KateCmd::self()->registerCommand (new KateCommands::Goto ()); KateCmd::self()->registerCommand (new KateCommands::Date ()); } KateFactory::~KateFactory() { delete m_documentConfig; delete m_viewConfig; delete m_rendererConfig; delete m_fileTypeManager; delete m_schemaManager; delete m_dirWatch; } static KStaticDeleter<KateFactory> sdFactory; KateFactory *KateFactory::self () { if (!s_self) sdFactory.setObject(s_self, new KateFactory ()); return s_self; } KParts::Part *KateFactory::createPartObject ( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const char *_classname, const QStringList & ) { QCString classname( _classname ); bool bWantSingleView = ( classname != "KTextEditor::Document" && classname != "Kate::Document" ); bool bWantBrowserView = ( classname == "Browser/View" ); bool bWantReadOnly = (bWantBrowserView || ( classname == "KParts::ReadOnlyPart" )); KParts::ReadWritePart *part = new KateDocument (bWantSingleView, bWantBrowserView, bWantReadOnly, parentWidget, widgetName, parent, name); part->setReadWrite( !bWantReadOnly ); return part; } void KateFactory::registerDocument ( KateDocument *doc ) { m_documents.append( doc ); } void KateFactory::deregisterDocument ( KateDocument *doc ) { m_documents.removeRef( doc ); } void KateFactory::registerView ( KateView *view ) { m_views.append( view ); } void KateFactory::deregisterView ( KateView *view ) { m_views.removeRef( view ); } void KateFactory::registerRenderer ( KateRenderer *renderer ) { m_renderers.append( renderer ); } void KateFactory::deregisterRenderer ( KateRenderer *renderer ) { m_renderers.removeRef( renderer ); } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>kate part version 2.2 => 2.3, not that I would know any place where you can look that up atm ;)<commit_after>/* This file is part of the KDE libraries Copyright (C) 2001-2004 Christoph Cullmann <cullmann@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 version 2 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 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 "katefactory.h" #include "katedocument.h" #include "kateview.h" #include "katerenderer.h" #include "katecmds.h" #include "katefiletype.h" #include "kateschema.h" #include "kateconfig.h" #include "../interfaces/katecmd.h" #include <klocale.h> #include <kdirwatch.h> #include <kstaticdeleter.h> /** * dummy wrapper factory to be sure nobody external deletes our katefactory */ class KateFactoryPublic : public KParts::Factory { public: /** * reimplemented create object method * @param parentWidget parent widget * @param widgetName widget name * @param parent QObject parent * @param name object name * @param args additional arguments * @return constructed part object */ KParts::Part *createPartObject ( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const char *classname, const QStringList &args ) { return KateFactory::self()->createPartObject (parentWidget, widgetName, parent, name, classname, args); } }; extern "C" { void *init_libkatepart() { return new KateFactoryPublic (); } } KateFactory *KateFactory::s_self = 0; KateFactory::KateFactory () : m_aboutData ("katepart", I18N_NOOP("Kate Part"), "2.3", I18N_NOOP( "Embeddable editor component" ), KAboutData::License_LGPL_V2, I18N_NOOP( "(c) 2000-2004 The Kate Authors" ), 0, "http://kate.kde.org") , m_instance (&m_aboutData) , m_plugins (KTrader::self()->query("KTextEditor/Plugin")) { // set s_self s_self = this; // // fill about data // m_aboutData.addAuthor ("Christoph Cullmann", I18N_NOOP("Maintainer"), "cullmann@kde.org", "http://www.babylon2k.de"); m_aboutData.addAuthor ("Anders Lund", I18N_NOOP("Core Developer"), "anders@alweb.dk", "http://www.alweb.dk"); m_aboutData.addAuthor ("Joseph Wenninger", I18N_NOOP("Core Developer"), "jowenn@kde.org","http://stud3.tuwien.ac.at/~e9925371"); m_aboutData.addAuthor ("Hamish Rodda",I18N_NOOP("Core Developer"), "rodda@kde.org"); m_aboutData.addAuthor ("Waldo Bastian", I18N_NOOP( "The cool buffersystem" ), "bastian@kde.org" ); m_aboutData.addAuthor ("Charles Samuels", I18N_NOOP("The Editing Commands"), "charles@kde.org"); m_aboutData.addAuthor ("Matt Newell", I18N_NOOP("Testing, ..."), "newellm@proaxis.com"); m_aboutData.addAuthor ("Michael Bartl", I18N_NOOP("Former Core Developer"), "michael.bartl1@chello.at"); m_aboutData.addAuthor ("Michael McCallum", I18N_NOOP("Core Developer"), "gholam@xtra.co.nz"); m_aboutData.addAuthor ("Jochen Wilhemly", I18N_NOOP( "KWrite Author" ), "digisnap@cs.tu-berlin.de" ); m_aboutData.addAuthor ("Michael Koch",I18N_NOOP("KWrite port to KParts"), "koch@kde.org"); m_aboutData.addAuthor ("Christian Gebauer", 0, "gebauer@kde.org" ); m_aboutData.addAuthor ("Simon Hausmann", 0, "hausmann@kde.org" ); m_aboutData.addAuthor ("Glen Parker",I18N_NOOP("KWrite Undo History, Kspell integration"), "glenebob@nwlink.com"); m_aboutData.addAuthor ("Scott Manson",I18N_NOOP("KWrite XML Syntax highlighting support"), "sdmanson@alltel.net"); m_aboutData.addAuthor ("John Firebaugh",I18N_NOOP("Patches and more"), "jfirebaugh@kde.org"); m_aboutData.addAuthor ("Dominik Haumann", I18N_NOOP("Developer & Highlight wizard"), "dhdev@gmx.de"); m_aboutData.addCredit ("Matteo Merli",I18N_NOOP("Highlighting for RPM Spec-Files, Perl, Diff and more"), "merlim@libero.it"); m_aboutData.addCredit ("Rocky Scaletta",I18N_NOOP("Highlighting for VHDL"), "rocky@purdue.edu"); m_aboutData.addCredit ("Yury Lebedev",I18N_NOOP("Highlighting for SQL"),""); m_aboutData.addCredit ("Chris Ross",I18N_NOOP("Highlighting for Ferite"),""); m_aboutData.addCredit ("Nick Roux",I18N_NOOP("Highlighting for ILERPG"),""); m_aboutData.addCredit ("Carsten Niehaus", I18N_NOOP("Highlighting for LaTeX"),""); m_aboutData.addCredit ("Per Wigren", I18N_NOOP("Highlighting for Makefiles, Python"),""); m_aboutData.addCredit ("Jan Fritz", I18N_NOOP("Highlighting for Python"),""); m_aboutData.addCredit ("Daniel Naber","",""); m_aboutData.addCredit ("Roland Pabel",I18N_NOOP("Highlighting for Scheme"),""); m_aboutData.addCredit ("Cristi Dumitrescu",I18N_NOOP("PHP Keyword/Datatype list"),""); m_aboutData.addCredit ("Carsten Pfeiffer", I18N_NOOP("Very nice help"), ""); m_aboutData.addCredit (I18N_NOOP("All people who have contributed and I have forgotten to mention"),"",""); m_aboutData.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails")); // // dir watch // m_dirWatch = new KDirWatch (); // // filetype man // m_fileTypeManager = new KateFileTypeManager (); // // schema man // m_schemaManager = new KateSchemaManager (); // config objects m_documentConfig = new KateDocumentConfig (); m_viewConfig = new KateViewConfig (); m_rendererConfig = new KateRendererConfig (); // // init the cmds // KateCmd::self()->registerCommand (new KateCommands::CoreCommands()); KateCmd::self()->registerCommand (new KateCommands::SedReplace ()); KateCmd::self()->registerCommand (new KateCommands::Character ()); KateCmd::self()->registerCommand (new KateCommands::Goto ()); KateCmd::self()->registerCommand (new KateCommands::Date ()); } KateFactory::~KateFactory() { delete m_documentConfig; delete m_viewConfig; delete m_rendererConfig; delete m_fileTypeManager; delete m_schemaManager; delete m_dirWatch; } static KStaticDeleter<KateFactory> sdFactory; KateFactory *KateFactory::self () { if (!s_self) sdFactory.setObject(s_self, new KateFactory ()); return s_self; } KParts::Part *KateFactory::createPartObject ( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const char *_classname, const QStringList & ) { QCString classname( _classname ); bool bWantSingleView = ( classname != "KTextEditor::Document" && classname != "Kate::Document" ); bool bWantBrowserView = ( classname == "Browser/View" ); bool bWantReadOnly = (bWantBrowserView || ( classname == "KParts::ReadOnlyPart" )); KParts::ReadWritePart *part = new KateDocument (bWantSingleView, bWantBrowserView, bWantReadOnly, parentWidget, widgetName, parent, name); part->setReadWrite( !bWantReadOnly ); return part; } void KateFactory::registerDocument ( KateDocument *doc ) { m_documents.append( doc ); } void KateFactory::deregisterDocument ( KateDocument *doc ) { m_documents.removeRef( doc ); } void KateFactory::registerView ( KateView *view ) { m_views.append( view ); } void KateFactory::deregisterView ( KateView *view ) { m_views.removeRef( view ); } void KateFactory::registerRenderer ( KateRenderer *renderer ) { m_renderers.append( renderer ); } void KateFactory::deregisterRenderer ( KateRenderer *renderer ) { m_renderers.removeRef( renderer ); } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before><commit_msg>fix switches (--) and typos<commit_after><|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" #include "kernel/ffinit.h" #include "kernel/ff.h" #include "kernel/mem.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct Clk2fflogicPass : public Pass { Clk2fflogicPass() : Pass("clk2fflogic", "convert clocked FFs to generic $ff cells") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" clk2fflogic [options] [selection]\n"); log("\n"); log("This command replaces clocked flip-flops with generic $ff cells that use the\n"); log("implicit global clock. This is useful for formal verification of designs with\n"); log("multiple clocks.\n"); log("\n"); } SigSpec wrap_async_control(Module *module, SigSpec sig, bool polarity, bool is_fine, IdString past_sig_id) { if (!is_fine) return wrap_async_control(module, sig, polarity, past_sig_id); return wrap_async_control_gate(module, sig, polarity, past_sig_id); } SigSpec wrap_async_control(Module *module, SigSpec sig, bool polarity, IdString past_sig_id) { Wire *past_sig = module->addWire(past_sig_id, GetSize(sig)); past_sig->attributes[ID::init] = RTLIL::Const(polarity ? State::S0 : State::S1, GetSize(sig)); module->addFf(NEW_ID, sig, past_sig); if (polarity) sig = module->Or(NEW_ID, sig, past_sig); else sig = module->And(NEW_ID, sig, past_sig); if (polarity) return sig; else return module->Not(NEW_ID, sig); } SigSpec wrap_async_control_gate(Module *module, SigSpec sig, bool polarity, IdString past_sig_id) { Wire *past_sig = module->addWire(past_sig_id); past_sig->attributes[ID::init] = polarity ? State::S0 : State::S1; module->addFfGate(NEW_ID, sig, past_sig); if (polarity) sig = module->OrGate(NEW_ID, sig, past_sig); else sig = module->AndGate(NEW_ID, sig, past_sig); if (polarity) return sig; else return module->NotGate(NEW_ID, sig); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { // bool flag_noinit = false; log_header(design, "Executing CLK2FFLOGIC pass (convert clocked FFs to generic $ff cells).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-noinit") { // flag_noinit = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) { SigMap sigmap(module); FfInitVals initvals(&sigmap, module); for (auto &mem : Mem::get_selected_memories(module)) { for (int i = 0; i < GetSize(mem.rd_ports); i++) { auto &port = mem.rd_ports[i]; if (port.clk_enable) log_error("Read port %d of memory %s.%s is clocked. This is not supported by \"clk2fflogic\"! " "Call \"memory\" with -nordff to avoid this error.\n", i, log_id(mem.memid), log_id(module)); } for (int i = 0; i < GetSize(mem.wr_ports); i++) { auto &port = mem.wr_ports[i]; if (!port.clk_enable) continue; log("Modifying write port %d on memory %s.%s: CLK=%s, A=%s, D=%s\n", i, log_id(module), log_id(mem.memid), log_signal(port.clk), log_signal(port.addr), log_signal(port.data)); Wire *past_clk = module->addWire(NEW_ID_SUFFIX(stringf("%s#%d#past_clk#%s", log_id(mem.memid), i, log_signal(port.clk)))); past_clk->attributes[ID::init] = port.clk_polarity ? State::S1 : State::S0; module->addFf(NEW_ID, port.clk, past_clk); SigSpec clock_edge_pattern; if (port.clk_polarity) { clock_edge_pattern.append(State::S0); clock_edge_pattern.append(State::S1); } else { clock_edge_pattern.append(State::S1); clock_edge_pattern.append(State::S0); } SigSpec clock_edge = module->Eqx(NEW_ID, {port.clk, SigSpec(past_clk)}, clock_edge_pattern); SigSpec en_q = module->addWire(NEW_ID_SUFFIX(stringf("%s#%d#en_q", log_id(mem.memid), i)), GetSize(port.en)); module->addFf(NEW_ID, port.en, en_q); SigSpec addr_q = module->addWire(NEW_ID_SUFFIX(stringf("%s#%d#addr_q", log_id(mem.memid), i)), GetSize(port.addr)); module->addFf(NEW_ID, port.addr, addr_q); SigSpec data_q = module->addWire(NEW_ID_SUFFIX(stringf("%s#%d#data_q", log_id(mem.memid), i)), GetSize(port.data)); module->addFf(NEW_ID, port.data, data_q); port.clk = State::S0; port.en = module->Mux(NEW_ID, Const(0, GetSize(en_q)), en_q, clock_edge); port.addr = addr_q; port.data = data_q; port.clk_enable = false; port.clk_polarity = false; } mem.emit(); } for (auto cell : vector<Cell*>(module->selected_cells())) { SigSpec qval; if (RTLIL::builtin_ff_cell_types().count(cell->type)) { FfData ff(&initvals, cell); if (ff.has_gclk) { // Already a $ff or $_FF_ cell. continue; } if (ff.has_clk) { log("Replacing %s.%s (%s): CLK=%s, D=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(ff.sig_clk), log_signal(ff.sig_d), log_signal(ff.sig_q)); } else if (ff.has_aload) { log("Replacing %s.%s (%s): EN=%s, D=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(ff.sig_aload), log_signal(ff.sig_ad), log_signal(ff.sig_q)); } else { // $sr. log("Replacing %s.%s (%s): SET=%s, CLR=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(ff.sig_set), log_signal(ff.sig_clr), log_signal(ff.sig_q)); } ff.remove(); // Strip spaces from signal name, since Yosys IDs can't contain spaces // Spaces only occur when we have a signal that's a slice of a larger bus, // e.g. "\myreg [5:0]", so removing spaces shouldn't result in loss of uniqueness std::string sig_q_str = log_signal(ff.sig_q); sig_q_str.erase(std::remove(sig_q_str.begin(), sig_q_str.end(), ' '), sig_q_str.end()); Wire *past_q = module->addWire(NEW_ID_SUFFIX(stringf("%s#past_q_wire", sig_q_str.c_str())), ff.width); if (!ff.is_fine) { module->addFf(NEW_ID, ff.sig_q, past_q); } else { module->addFfGate(NEW_ID, ff.sig_q, past_q); } if (!ff.val_init.is_fully_undef()) initvals.set_init(past_q, ff.val_init); if (ff.has_clk) { ff.unmap_ce_srst(); Wire *past_clk = module->addWire(NEW_ID_SUFFIX(stringf("%s#past_clk#%s", sig_q_str.c_str(), log_signal(ff.sig_clk)))); initvals.set_init(past_clk, ff.pol_clk ? State::S1 : State::S0); if (!ff.is_fine) module->addFf(NEW_ID, ff.sig_clk, past_clk); else module->addFfGate(NEW_ID, ff.sig_clk, past_clk); SigSpec clock_edge_pattern; if (ff.pol_clk) { clock_edge_pattern.append(State::S0); clock_edge_pattern.append(State::S1); } else { clock_edge_pattern.append(State::S1); clock_edge_pattern.append(State::S0); } SigSpec clock_edge = module->Eqx(NEW_ID, {ff.sig_clk, SigSpec(past_clk)}, clock_edge_pattern); Wire *past_d = module->addWire(NEW_ID_SUFFIX(stringf("%s#past_d_wire", sig_q_str.c_str())), ff.width); if (!ff.is_fine) module->addFf(NEW_ID, ff.sig_d, past_d); else module->addFfGate(NEW_ID, ff.sig_d, past_d); if (!ff.val_init.is_fully_undef()) initvals.set_init(past_d, ff.val_init); if (!ff.is_fine) qval = module->Mux(NEW_ID, past_q, past_d, clock_edge); else qval = module->MuxGate(NEW_ID, past_q, past_d, clock_edge); } else { qval = past_q; } if (ff.has_aload) { SigSpec sig_aload = wrap_async_control(module, ff.sig_aload, ff.pol_aload, ff.is_fine, NEW_ID); if (!ff.is_fine) qval = module->Mux(NEW_ID, qval, ff.sig_ad, sig_aload); else qval = module->MuxGate(NEW_ID, qval, ff.sig_ad, sig_aload); } if (ff.has_sr) { SigSpec setval = wrap_async_control(module, ff.sig_set, ff.pol_set, ff.is_fine, NEW_ID); SigSpec clrval = wrap_async_control(module, ff.sig_clr, ff.pol_clr, ff.is_fine, NEW_ID); if (!ff.is_fine) { clrval = module->Not(NEW_ID, clrval); qval = module->Or(NEW_ID, qval, setval); module->addAnd(NEW_ID, qval, clrval, ff.sig_q); } else { clrval = module->NotGate(NEW_ID, clrval); qval = module->OrGate(NEW_ID, qval, setval); module->addAndGate(NEW_ID, qval, clrval, ff.sig_q); } } else if (ff.has_arst) { IdString id = NEW_ID_SUFFIX(stringf("%s#past_arst#%s", sig_q_str.c_str(), log_signal(ff.sig_arst))); SigSpec arst = wrap_async_control(module, ff.sig_arst, ff.pol_arst, ff.is_fine, id); if (!ff.is_fine) module->addMux(NEW_ID, qval, ff.val_arst, arst, ff.sig_q); else module->addMuxGate(NEW_ID, qval, ff.val_arst[0], arst, ff.sig_q); } else { module->connect(ff.sig_q, qval); } } } } } } Clk2fflogicPass; PRIVATE_NAMESPACE_END <commit_msg>clk2fflogic: Generate less unused logic when using verific<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" #include "kernel/ffinit.h" #include "kernel/ff.h" #include "kernel/mem.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct Clk2fflogicPass : public Pass { Clk2fflogicPass() : Pass("clk2fflogic", "convert clocked FFs to generic $ff cells") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" clk2fflogic [options] [selection]\n"); log("\n"); log("This command replaces clocked flip-flops with generic $ff cells that use the\n"); log("implicit global clock. This is useful for formal verification of designs with\n"); log("multiple clocks.\n"); log("\n"); } SigSpec wrap_async_control(Module *module, SigSpec sig, bool polarity, bool is_fine, IdString past_sig_id) { if (!is_fine) return wrap_async_control(module, sig, polarity, past_sig_id); return wrap_async_control_gate(module, sig, polarity, past_sig_id); } SigSpec wrap_async_control(Module *module, SigSpec sig, bool polarity, IdString past_sig_id) { Wire *past_sig = module->addWire(past_sig_id, GetSize(sig)); past_sig->attributes[ID::init] = RTLIL::Const(polarity ? State::S0 : State::S1, GetSize(sig)); module->addFf(NEW_ID, sig, past_sig); if (polarity) sig = module->Or(NEW_ID, sig, past_sig); else sig = module->And(NEW_ID, sig, past_sig); if (polarity) return sig; else return module->Not(NEW_ID, sig); } SigSpec wrap_async_control_gate(Module *module, SigSpec sig, bool polarity, IdString past_sig_id) { Wire *past_sig = module->addWire(past_sig_id); past_sig->attributes[ID::init] = polarity ? State::S0 : State::S1; module->addFfGate(NEW_ID, sig, past_sig); if (polarity) sig = module->OrGate(NEW_ID, sig, past_sig); else sig = module->AndGate(NEW_ID, sig, past_sig); if (polarity) return sig; else return module->NotGate(NEW_ID, sig); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { // bool flag_noinit = false; log_header(design, "Executing CLK2FFLOGIC pass (convert clocked FFs to generic $ff cells).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-noinit") { // flag_noinit = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) { SigMap sigmap(module); FfInitVals initvals(&sigmap, module); for (auto &mem : Mem::get_selected_memories(module)) { for (int i = 0; i < GetSize(mem.rd_ports); i++) { auto &port = mem.rd_ports[i]; if (port.clk_enable) log_error("Read port %d of memory %s.%s is clocked. This is not supported by \"clk2fflogic\"! " "Call \"memory\" with -nordff to avoid this error.\n", i, log_id(mem.memid), log_id(module)); } for (int i = 0; i < GetSize(mem.wr_ports); i++) { auto &port = mem.wr_ports[i]; if (!port.clk_enable) continue; log("Modifying write port %d on memory %s.%s: CLK=%s, A=%s, D=%s\n", i, log_id(module), log_id(mem.memid), log_signal(port.clk), log_signal(port.addr), log_signal(port.data)); Wire *past_clk = module->addWire(NEW_ID_SUFFIX(stringf("%s#%d#past_clk#%s", log_id(mem.memid), i, log_signal(port.clk)))); past_clk->attributes[ID::init] = port.clk_polarity ? State::S1 : State::S0; module->addFf(NEW_ID, port.clk, past_clk); SigSpec clock_edge_pattern; if (port.clk_polarity) { clock_edge_pattern.append(State::S0); clock_edge_pattern.append(State::S1); } else { clock_edge_pattern.append(State::S1); clock_edge_pattern.append(State::S0); } SigSpec clock_edge = module->Eqx(NEW_ID, {port.clk, SigSpec(past_clk)}, clock_edge_pattern); SigSpec en_q = module->addWire(NEW_ID_SUFFIX(stringf("%s#%d#en_q", log_id(mem.memid), i)), GetSize(port.en)); module->addFf(NEW_ID, port.en, en_q); SigSpec addr_q = module->addWire(NEW_ID_SUFFIX(stringf("%s#%d#addr_q", log_id(mem.memid), i)), GetSize(port.addr)); module->addFf(NEW_ID, port.addr, addr_q); SigSpec data_q = module->addWire(NEW_ID_SUFFIX(stringf("%s#%d#data_q", log_id(mem.memid), i)), GetSize(port.data)); module->addFf(NEW_ID, port.data, data_q); port.clk = State::S0; port.en = module->Mux(NEW_ID, Const(0, GetSize(en_q)), en_q, clock_edge); port.addr = addr_q; port.data = data_q; port.clk_enable = false; port.clk_polarity = false; } mem.emit(); } for (auto cell : vector<Cell*>(module->selected_cells())) { SigSpec qval; if (RTLIL::builtin_ff_cell_types().count(cell->type)) { FfData ff(&initvals, cell); if (ff.has_gclk) { // Already a $ff or $_FF_ cell. continue; } if (ff.has_clk) { log("Replacing %s.%s (%s): CLK=%s, D=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(ff.sig_clk), log_signal(ff.sig_d), log_signal(ff.sig_q)); } else if (ff.has_aload) { log("Replacing %s.%s (%s): EN=%s, D=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(ff.sig_aload), log_signal(ff.sig_ad), log_signal(ff.sig_q)); } else { // $sr. log("Replacing %s.%s (%s): SET=%s, CLR=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(ff.sig_set), log_signal(ff.sig_clr), log_signal(ff.sig_q)); } ff.remove(); // Strip spaces from signal name, since Yosys IDs can't contain spaces // Spaces only occur when we have a signal that's a slice of a larger bus, // e.g. "\myreg [5:0]", so removing spaces shouldn't result in loss of uniqueness std::string sig_q_str = log_signal(ff.sig_q); sig_q_str.erase(std::remove(sig_q_str.begin(), sig_q_str.end(), ' '), sig_q_str.end()); Wire *past_q = module->addWire(NEW_ID_SUFFIX(stringf("%s#past_q_wire", sig_q_str.c_str())), ff.width); if (!ff.is_fine) { module->addFf(NEW_ID, ff.sig_q, past_q); } else { module->addFfGate(NEW_ID, ff.sig_q, past_q); } if (!ff.val_init.is_fully_undef()) initvals.set_init(past_q, ff.val_init); if (ff.has_clk) { ff.unmap_ce_srst(); Wire *past_clk = module->addWire(NEW_ID_SUFFIX(stringf("%s#past_clk#%s", sig_q_str.c_str(), log_signal(ff.sig_clk)))); initvals.set_init(past_clk, ff.pol_clk ? State::S1 : State::S0); if (!ff.is_fine) module->addFf(NEW_ID, ff.sig_clk, past_clk); else module->addFfGate(NEW_ID, ff.sig_clk, past_clk); SigSpec clock_edge_pattern; if (ff.pol_clk) { clock_edge_pattern.append(State::S0); clock_edge_pattern.append(State::S1); } else { clock_edge_pattern.append(State::S1); clock_edge_pattern.append(State::S0); } SigSpec clock_edge = module->Eqx(NEW_ID, {ff.sig_clk, SigSpec(past_clk)}, clock_edge_pattern); Wire *past_d = module->addWire(NEW_ID_SUFFIX(stringf("%s#past_d_wire", sig_q_str.c_str())), ff.width); if (!ff.is_fine) module->addFf(NEW_ID, ff.sig_d, past_d); else module->addFfGate(NEW_ID, ff.sig_d, past_d); if (!ff.val_init.is_fully_undef()) initvals.set_init(past_d, ff.val_init); if (!ff.is_fine) qval = module->Mux(NEW_ID, past_q, past_d, clock_edge); else qval = module->MuxGate(NEW_ID, past_q, past_d, clock_edge); } else { qval = past_q; } // The check for a constant sig_aload is also done by opt_dff, but when using verific and running // clk2fflogic before opt_dff (which does more and possibly unwanted optimizations) this check avoids // generating a lot of extra logic. if (ff.has_aload && ff.sig_aload != (ff.pol_aload ? State::S0 : State::S1)) { SigSpec sig_aload = wrap_async_control(module, ff.sig_aload, ff.pol_aload, ff.is_fine, NEW_ID); if (!ff.is_fine) qval = module->Mux(NEW_ID, qval, ff.sig_ad, sig_aload); else qval = module->MuxGate(NEW_ID, qval, ff.sig_ad, sig_aload); } if (ff.has_sr) { SigSpec setval = wrap_async_control(module, ff.sig_set, ff.pol_set, ff.is_fine, NEW_ID); SigSpec clrval = wrap_async_control(module, ff.sig_clr, ff.pol_clr, ff.is_fine, NEW_ID); if (!ff.is_fine) { clrval = module->Not(NEW_ID, clrval); qval = module->Or(NEW_ID, qval, setval); module->addAnd(NEW_ID, qval, clrval, ff.sig_q); } else { clrval = module->NotGate(NEW_ID, clrval); qval = module->OrGate(NEW_ID, qval, setval); module->addAndGate(NEW_ID, qval, clrval, ff.sig_q); } } else if (ff.has_arst) { IdString id = NEW_ID_SUFFIX(stringf("%s#past_arst#%s", sig_q_str.c_str(), log_signal(ff.sig_arst))); SigSpec arst = wrap_async_control(module, ff.sig_arst, ff.pol_arst, ff.is_fine, id); if (!ff.is_fine) module->addMux(NEW_ID, qval, ff.val_arst, arst, ff.sig_q); else module->addMuxGate(NEW_ID, qval, ff.val_arst[0], arst, ff.sig_q); } else { module->connect(ff.sig_q, qval); } } } } } } Clk2fflogicPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pages.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2008-01-29 16:30:51 $ * * 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 _PAGES_HXX_ #define _PAGES_HXX_ #include <vcl/tabpage.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/dialog.hxx> #include <vcl/scrbar.hxx> #include <svtools/wizardmachine.hxx> #include <svtools/svmedit.hxx> #include <svtools/lstner.hxx> #include <svtools/xtextedt.hxx> namespace desktop { class WelcomePage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; svt::OWizardMachine *m_pParent; sal_Bool m_bLicenseNeedsAcceptance; enum OEMType { OEM_NONE, OEM_NORMAL, OEM_EXTENDED }; OEMType checkOEM(); bool bIsEvalVersion; bool bNoEvalText; void checkEval(); public: WelcomePage( svt::OWizardMachine* parent, const ResId& resid, sal_Bool bLicenseNeedsAcceptance ); protected: virtual void ActivatePage(); }; class LicenseView : public MultiLineEdit, public SfxListener { BOOL mbEndReached; Link maEndReachedHdl; Link maScrolledHdl; public: LicenseView( Window* pParent, const ResId& rResId ); ~LicenseView(); void ScrollDown( ScrollType eScroll ); BOOL IsEndReached() const; BOOL EndReached() const { return mbEndReached; } void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; } void SetEndReachedHdl( const Link& rHdl ) { maEndReachedHdl = rHdl; } const Link& GetAutocompleteHdl() const { return maEndReachedHdl; } void SetScrolledHdl( const Link& rHdl ) { maScrolledHdl = rHdl; } const Link& GetScrolledHdl() const { return maScrolledHdl; } virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); protected: using MultiLineEdit::Notify; }; class LicensePage : public svt::OWizardPage { private: svt::OWizardMachine *m_pParent; FixedText m_ftHead; FixedText m_ftBody1; FixedText m_ftBody1Txt; FixedText m_ftBody2; FixedText m_ftBody2Txt; LicenseView m_mlLicense; PushButton m_pbDown; sal_Bool m_bLicenseRead; public: LicensePage( svt::OWizardMachine* parent, const ResId& resid, const rtl::OUString &rLicensePath ); private: DECL_LINK(PageDownHdl, PushButton*); DECL_LINK(EndReachedHdl, LicenseView*); DECL_LINK(ScrolledHdl, LicenseView*); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); }; class MigrationPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; CheckBox m_cbMigration; sal_Bool m_bMigrationDone; public: MigrationPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class UserPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; FixedText m_ftFirst; Edit m_edFirst; FixedText m_ftLast; Edit m_edLast; FixedText m_ftInitials; Edit m_edInitials; FixedText m_ftFather; Edit m_edFather; LanguageType m_lang; public: UserPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class UpdateCheckPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; CheckBox m_cbUpdateCheck; public: UpdateCheckPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class RegistrationPage : public svt::OWizardPage { private: FixedText m_ftHeader; FixedText m_ftBody; FixedImage m_fiImage; RadioButton m_rbNow; RadioButton m_rbLater; RadioButton m_rbNever; RadioButton m_rbReg; FixedLine m_flSeparator; FixedText m_ftEnd; sal_Bool m_bNeverVisible; void updateButtonStates(); void impl_retrieveConfigurationData(); public: RegistrationPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); }; } #endif <commit_msg>INTEGRATION: CWS registerlater_SRC680 (1.9.318); FILE MERGED 2008/02/01 10:00:01 pb 1.9.318.2: RESYNC: (1.9-1.9.292.1); FILE MERGED 2008/01/24 09:07:22 pb 1.9.318.1: fix: #i85445# RegistrationPage: added support for SfxSingleTabDialog-Mode<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pages.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2008-02-04 15:47:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PAGES_HXX_ #define _PAGES_HXX_ #include <vcl/tabpage.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/dialog.hxx> #include <vcl/scrbar.hxx> #include <svtools/wizardmachine.hxx> #include <svtools/svmedit.hxx> #include <svtools/lstner.hxx> #include <svtools/xtextedt.hxx> namespace desktop { class WelcomePage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; svt::OWizardMachine *m_pParent; sal_Bool m_bLicenseNeedsAcceptance; enum OEMType { OEM_NONE, OEM_NORMAL, OEM_EXTENDED }; OEMType checkOEM(); bool bIsEvalVersion; bool bNoEvalText; void checkEval(); public: WelcomePage( svt::OWizardMachine* parent, const ResId& resid, sal_Bool bLicenseNeedsAcceptance ); protected: virtual void ActivatePage(); }; class LicenseView : public MultiLineEdit, public SfxListener { BOOL mbEndReached; Link maEndReachedHdl; Link maScrolledHdl; public: LicenseView( Window* pParent, const ResId& rResId ); ~LicenseView(); void ScrollDown( ScrollType eScroll ); BOOL IsEndReached() const; BOOL EndReached() const { return mbEndReached; } void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; } void SetEndReachedHdl( const Link& rHdl ) { maEndReachedHdl = rHdl; } const Link& GetAutocompleteHdl() const { return maEndReachedHdl; } void SetScrolledHdl( const Link& rHdl ) { maScrolledHdl = rHdl; } const Link& GetScrolledHdl() const { return maScrolledHdl; } virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); protected: using MultiLineEdit::Notify; }; class LicensePage : public svt::OWizardPage { private: svt::OWizardMachine *m_pParent; FixedText m_ftHead; FixedText m_ftBody1; FixedText m_ftBody1Txt; FixedText m_ftBody2; FixedText m_ftBody2Txt; LicenseView m_mlLicense; PushButton m_pbDown; sal_Bool m_bLicenseRead; public: LicensePage( svt::OWizardMachine* parent, const ResId& resid, const rtl::OUString &rLicensePath ); private: DECL_LINK(PageDownHdl, PushButton*); DECL_LINK(EndReachedHdl, LicenseView*); DECL_LINK(ScrolledHdl, LicenseView*); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); }; class MigrationPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; CheckBox m_cbMigration; sal_Bool m_bMigrationDone; public: MigrationPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class UserPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; FixedText m_ftFirst; Edit m_edFirst; FixedText m_ftLast; Edit m_edLast; FixedText m_ftInitials; Edit m_edInitials; FixedText m_ftFather; Edit m_edFather; LanguageType m_lang; public: UserPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class UpdateCheckPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; CheckBox m_cbUpdateCheck; public: UpdateCheckPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class RegistrationPage : public svt::OWizardPage { private: FixedText m_ftHeader; FixedText m_ftBody; FixedImage m_fiImage; RadioButton m_rbNow; RadioButton m_rbLater; RadioButton m_rbNever; RadioButton m_rbReg; FixedLine m_flSeparator; FixedText m_ftEnd; sal_Bool m_bNeverVisible; void updateButtonStates(); void impl_retrieveConfigurationData(); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); public: RegistrationPage( Window* pParent, const ResId& rResid ); virtual sal_Bool commitPage( COMMIT_REASON eReason ); enum RegistrationMode { rmNow, // register now rmLater, // register later rmNever, // register never rmAlready // already registered }; RegistrationMode getRegistrationMode() const; void prepareSingleMode(); inline String getSingleModeTitle() const { return m_ftHeader.GetText(); } static bool hasReminderDateCome(); static void executeSingleMode(); }; } // namespace desktop #endif // #ifndef _PAGES_HXX_ <|endoftext|>
<commit_before><commit_msg>This is not needed.<commit_after><|endoftext|>
<commit_before>#include <stdlib.h> #include <string.h> #include <string> #include <realm/util/features.h> #include <realm/util/basic_system_errors.hpp> using namespace realm::util; namespace { class system_category: public std::error_category { const char* name() const REALM_NOEXCEPT override; std::string message(int) const override; }; system_category g_system_category; const char* system_category::name() const REALM_NOEXCEPT { return "realm.basic_system"; } std::string system_category::message(int value) const { const size_t max_msg_size = 256; char buffer[max_msg_size+1]; #ifdef _WIN32 // Windows version if (REALM_LIKELY(strerror_s(buffer, max_msg_size, value) == 0)) { return buffer; // Guaranteed to be truncated } #elif defined __APPLE__ && defined __MACH__ // OSX, iOS and WatchOS version { int result = strerror_r(value, buffer, max_msg_size); if (REALM_LIKELY(result == 0 || result == ERANGE)) { return buffer; // Guaranteed to be truncated } } #elif (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE // XSI-compliant version if (REALM_LIKELY(strerror_r(value, buffer, max_msg_size) == 0)) { buffer[max_msg_size] = 0; // For safety's sake, not guaranteed to be truncated by POSIX return buffer; } #else // GNU specific version { char* msg = nullptr; if (REALM_LIKELY((msg = strerror_r(value, buffer, max_msg_size)) != nullptr)) { return msg; // Guaranteed to be truncated } } #endif return "Unknown error"; } } // anonymous namespace namespace realm { namespace util { namespace error { std::error_code make_error_code(basic_system_errors err) { return std::error_code(err, g_system_category); } } // namespace error } // namespace util } // namespace realm <commit_msg>Put POSIX strerror_r as default version<commit_after>#include <stdlib.h> #include <string.h> #include <string> #include <realm/util/features.h> #include <realm/util/basic_system_errors.hpp> using namespace realm::util; namespace { class system_category: public std::error_category { const char* name() const REALM_NOEXCEPT override; std::string message(int) const override; }; system_category g_system_category; const char* system_category::name() const REALM_NOEXCEPT { return "realm.basic_system"; } std::string system_category::message(int value) const { const size_t max_msg_size = 256; char buffer[max_msg_size+1]; #ifdef _WIN32 // Windows version if (REALM_LIKELY(strerror_s(buffer, max_msg_size, value) == 0)) { return buffer; // Guaranteed to be truncated } #elif defined __APPLE__ && defined __MACH__ // OSX, iOS and WatchOS version { int result = strerror_r(value, buffer, max_msg_size); if (REALM_LIKELY(result == 0 || result == ERANGE)) { return buffer; // Guaranteed to be truncated } } #elif ! ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE) // GNU specific version { char* msg = nullptr; if (REALM_LIKELY((msg = strerror_r(value, buffer, max_msg_size)) != nullptr)) { return msg; // Guaranteed to be truncated } } #else // XSI-compliant version, used by Android if (REALM_LIKELY(strerror_r(value, buffer, max_msg_size) == 0)) { buffer[max_msg_size] = 0; // For safety's sake, not guaranteed to be truncated by POSIX return buffer; } #endif return "Unknown error"; } } // anonymous namespace namespace realm { namespace util { namespace error { std::error_code make_error_code(basic_system_errors err) { return std::error_code(err, g_system_category); } } // namespace error } // namespace util } // namespace realm <|endoftext|>
<commit_before><commit_msg>Don't output idiotic comments in the generated OpenCL<commit_after><|endoftext|>
<commit_before>/* * Copyright 2006-2011 The FLWOR Foundation. * * 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 "json_loader.h" #include "util/json_parser.h" #include "json_items.h" #include "simple_item_factory.h" #include "store_defs.h" #include "simple_store.h" #include "diagnostics/diagnostic.h" #include <cassert> #include <vector> namespace zorba { namespace simplestore { namespace json { /****************************************************************************** *******************************************************************************/ JSONLoader::JSONLoader( std::istream& s, internal::diagnostic::location* relative_error_loc ) : in(s), theRelativeLoc(relative_error_loc) { } /****************************************************************************** *******************************************************************************/ JSONLoader::~JSONLoader() { } #define RAISE_JSON_ERROR_NO_PARAM(msg) \ if (theRelativeLoc) \ { \ throw XQUERY_EXCEPTION( \ jerr::JSDY0040, \ ERROR_PARAMS( \ ZED(msg), \ "" \ ), \ ERROR_LOC(e.get_loc()) \ ); \ } \ else \ { \ throw ZORBA_EXCEPTION( \ jerr::JSDY0040, \ ERROR_PARAMS( \ ZED(msg), \ BUILD_STRING("line ", e.get_loc().line(), ", column ", e.get_loc().column()) \ ) \ ); \ } #define RAISE_JSON_ERROR_WITH_PARAM(msg, param) \ if (theRelativeLoc) \ { \ throw XQUERY_EXCEPTION( \ jerr::JSDY0040, \ ERROR_PARAMS( \ ZED(msg), \ param, \ "" \ ), \ ERROR_LOC(e.get_loc()) \ ); \ } \ else \ { \ throw ZORBA_EXCEPTION( \ jerr::JSDY0040, \ ERROR_PARAMS( \ ZED(msg), \ param, \ BUILD_STRING("line ", e.get_loc().line(), ", column ", e.get_loc().column()) \ ) \ ); \ } /****************************************************************************** *******************************************************************************/ store::Item_t JSONLoader::next( ) { using namespace zorba::json; using namespace zorba::simplestore; using namespace zorba::simplestore::json; try { BasicItemFactory& lFactory = GET_FACTORY(); JSONItem_t lRootItem; // stack of objects, arrays, and object pairs std::vector<store::Item_t> lStack; parser lParser(in); if (theRelativeLoc) { lParser.set_loc(theRelativeLoc->file(), theRelativeLoc->line(), theRelativeLoc->column()+1); } token lToken; while (lParser.next(&lToken)) { switch (lToken.get_type()) { case token::begin_array: lStack.push_back(new SimpleJSONArray()); break; case token::begin_object: lStack.push_back(new SimpleJSONObject()); break; case token::end_array: case token::end_object: { store::Item_t lItem = lStack.back(); lStack.pop_back(); if (lStack.empty()) { lRootItem = lItem.cast<JSONItem>(); } else { addValue(lStack, lItem); } break; } case token::name_separator: case token::value_separator: break; case token::string: { store::Item_t lValue; zstring s = lToken.get_value(); lFactory.createString(lValue, s); addValue(lStack, lValue); break; } case token::number: { store::Item_t lValue; zstring s = lToken.get_value(); lFactory.createJSONNumber(lValue, s); // todo check return type addValue(lStack, lValue); break; } case token::json_false: { store::Item_t lValue; lFactory.createBoolean(lValue, false); addValue(lStack, lValue); break; } case token::json_true: { store::Item_t lValue; lFactory.createBoolean(lValue, true); addValue(lStack, lValue); break; } case token::json_null: { store::Item_t lValue; lFactory.createJSONNull(lValue); addValue(lStack, lValue); break; } default: assert(false); } } return lRootItem; } catch (zorba::json::unterminated_string& e) { RAISE_JSON_ERROR_NO_PARAM(JSON_UNTERMINATED_STRING) } catch (zorba::json::unexpected_token& e) { RAISE_JSON_ERROR_WITH_PARAM(JSON_UNEXPECTED_TOKEN, e.get_token()) } catch (zorba::json::illegal_number& e) { RAISE_JSON_ERROR_NO_PARAM(JSON_ILLEGAL_NUMBER) } catch (zorba::json::illegal_literal& e) { RAISE_JSON_ERROR_NO_PARAM(JSON_ILLEGAL_LITERAL) } catch (zorba::json::illegal_escape& e) { RAISE_JSON_ERROR_WITH_PARAM(JSON_ILLEGAL_ESCAPE, e.get_escape()) } catch (zorba::json::illegal_codepoint& e) { RAISE_JSON_ERROR_WITH_PARAM(JSON_ILLEGAL_CODEPOINT, e.get_codepoint()) } catch (zorba::json::illegal_character& e) { RAISE_JSON_ERROR_WITH_PARAM(JSON_ILLEGAL_CHARACTER, e.get_char()) } return NULL; } #undef RAISE_JSON_ERROR_WITH_PARAM #undef RAISE_JSON_ERROR_NO_PARAM void JSONLoader::addValue( std::vector<store::Item_t>& aStack, const store::Item_t& aValue) { store::Item_t lLast = aStack.back(); JSONObject* lObject = dynamic_cast<JSONObject*>(lLast.getp()); if (lObject) { // if the top of the stack is an object, then // the value must be a string which is the name // of the object's next name/value pair aStack.push_back(aValue); return; } JSONArray* lArray = dynamic_cast<JSONArray*>(lLast.getp()); if (lArray) { // if the top of the stack is an array, then // the value must be appended to it lArray->push_back(aValue); return; } // Otherwise, the top of the stack must be a string, which means // that the second-to-top must be an object awaiting a value associated with // this name. store::Item_t lString = aStack.back(); aStack.pop_back(); lLast = aStack.back(); lObject = dynamic_cast<JSONObject*>(lLast.getp()); assert(lObject); lObject->add(lString, aValue, false); } template<typename T> T* JSONLoader::cast(const JSONItem_t& j) { #ifndef NDEBUG T* t = dynamic_cast<T*>(j.getp()); assert(t); #else T* t = static_cast<T*>(j.getp()); #endif return t; } } /* namespace json */ } /* namespace simplestore */ } /* namespace zorba */ /* * Local variables: * mode: c++ * End: */ /* vim:set et sw=2 ts=2: */ <commit_msg>removed some hardcoded english words from error messages raised by the json parser Approved: Paul J. Lucas, Matthias Brantner<commit_after>/* * Copyright 2006-2011 The FLWOR Foundation. * * 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 "json_loader.h" #include "util/json_parser.h" #include "json_items.h" #include "simple_item_factory.h" #include "store_defs.h" #include "simple_store.h" #include "diagnostics/diagnostic.h" #include <cassert> #include <vector> namespace zorba { namespace simplestore { namespace json { /****************************************************************************** *******************************************************************************/ JSONLoader::JSONLoader( std::istream& s, internal::diagnostic::location* relative_error_loc ) : in(s), theRelativeLoc(relative_error_loc) { } /****************************************************************************** *******************************************************************************/ JSONLoader::~JSONLoader() { } #define RAISE_JSON_ERROR_NO_PARAM(msg) \ if (theRelativeLoc) \ { \ throw XQUERY_EXCEPTION( \ jerr::JSDY0040, \ ERROR_PARAMS( \ ZED(msg), \ "" \ ), \ ERROR_LOC(e.get_loc()) \ ); \ } \ else \ { \ throw ZORBA_EXCEPTION( \ jerr::JSDY0040, \ ERROR_PARAMS( \ ZED(msg), \ BUILD_STRING(e.get_loc().line(), ", ", e.get_loc().column()) \ ) \ ); \ } #define RAISE_JSON_ERROR_WITH_PARAM(msg, param) \ if (theRelativeLoc) \ { \ throw XQUERY_EXCEPTION( \ jerr::JSDY0040, \ ERROR_PARAMS( \ ZED(msg), \ param, \ "" \ ), \ ERROR_LOC(e.get_loc()) \ ); \ } \ else \ { \ throw ZORBA_EXCEPTION( \ jerr::JSDY0040, \ ERROR_PARAMS( \ ZED(msg), \ param, \ BUILD_STRING(e.get_loc().line(), ", ", e.get_loc().column()) \ ) \ ); \ } /****************************************************************************** *******************************************************************************/ store::Item_t JSONLoader::next( ) { using namespace zorba::json; using namespace zorba::simplestore; using namespace zorba::simplestore::json; try { BasicItemFactory& lFactory = GET_FACTORY(); JSONItem_t lRootItem; // stack of objects, arrays, and object pairs std::vector<store::Item_t> lStack; parser lParser(in); if (theRelativeLoc) { lParser.set_loc(theRelativeLoc->file(), theRelativeLoc->line(), theRelativeLoc->column()+1); } token lToken; while (lParser.next(&lToken)) { switch (lToken.get_type()) { case token::begin_array: lStack.push_back(new SimpleJSONArray()); break; case token::begin_object: lStack.push_back(new SimpleJSONObject()); break; case token::end_array: case token::end_object: { store::Item_t lItem = lStack.back(); lStack.pop_back(); if (lStack.empty()) { lRootItem = lItem.cast<JSONItem>(); } else { addValue(lStack, lItem); } break; } case token::name_separator: case token::value_separator: break; case token::string: { store::Item_t lValue; zstring s = lToken.get_value(); lFactory.createString(lValue, s); addValue(lStack, lValue); break; } case token::number: { store::Item_t lValue; zstring s = lToken.get_value(); lFactory.createJSONNumber(lValue, s); // todo check return type addValue(lStack, lValue); break; } case token::json_false: { store::Item_t lValue; lFactory.createBoolean(lValue, false); addValue(lStack, lValue); break; } case token::json_true: { store::Item_t lValue; lFactory.createBoolean(lValue, true); addValue(lStack, lValue); break; } case token::json_null: { store::Item_t lValue; lFactory.createJSONNull(lValue); addValue(lStack, lValue); break; } default: assert(false); } } return lRootItem; } catch (zorba::json::unterminated_string& e) { RAISE_JSON_ERROR_NO_PARAM(JSON_UNTERMINATED_STRING) } catch (zorba::json::unexpected_token& e) { RAISE_JSON_ERROR_WITH_PARAM(JSON_UNEXPECTED_TOKEN, e.get_token()) } catch (zorba::json::illegal_number& e) { RAISE_JSON_ERROR_NO_PARAM(JSON_ILLEGAL_NUMBER) } catch (zorba::json::illegal_literal& e) { RAISE_JSON_ERROR_NO_PARAM(JSON_ILLEGAL_LITERAL) } catch (zorba::json::illegal_escape& e) { RAISE_JSON_ERROR_WITH_PARAM(JSON_ILLEGAL_ESCAPE, e.get_escape()) } catch (zorba::json::illegal_codepoint& e) { RAISE_JSON_ERROR_WITH_PARAM(JSON_ILLEGAL_CODEPOINT, e.get_codepoint()) } catch (zorba::json::illegal_character& e) { RAISE_JSON_ERROR_WITH_PARAM(JSON_ILLEGAL_CHARACTER, e.get_char()) } return NULL; } #undef RAISE_JSON_ERROR_WITH_PARAM #undef RAISE_JSON_ERROR_NO_PARAM void JSONLoader::addValue( std::vector<store::Item_t>& aStack, const store::Item_t& aValue) { store::Item_t lLast = aStack.back(); JSONObject* lObject = dynamic_cast<JSONObject*>(lLast.getp()); if (lObject) { // if the top of the stack is an object, then // the value must be a string which is the name // of the object's next name/value pair aStack.push_back(aValue); return; } JSONArray* lArray = dynamic_cast<JSONArray*>(lLast.getp()); if (lArray) { // if the top of the stack is an array, then // the value must be appended to it lArray->push_back(aValue); return; } // Otherwise, the top of the stack must be a string, which means // that the second-to-top must be an object awaiting a value associated with // this name. store::Item_t lString = aStack.back(); aStack.pop_back(); lLast = aStack.back(); lObject = dynamic_cast<JSONObject*>(lLast.getp()); assert(lObject); lObject->add(lString, aValue, false); } template<typename T> T* JSONLoader::cast(const JSONItem_t& j) { #ifndef NDEBUG T* t = dynamic_cast<T*>(j.getp()); assert(t); #else T* t = static_cast<T*>(j.getp()); #endif return t; } } /* namespace json */ } /* namespace simplestore */ } /* namespace zorba */ /* * Local variables: * mode: c++ * End: */ /* vim:set et sw=2 ts=2: */ <|endoftext|>