text
stringlengths
54
60.6k
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkBooleanOperationsWidget.h" #include "../../Common/QmitkDataSelectionWidget.h" #include <mitkException.h> #include <mitkSliceNavigationController.h> #include <cassert> static const char* const HelpText = "Select two different segmentations above"; std::string GetPrefix(mitk::BooleanOperation::Type type) { switch (type) { case mitk::BooleanOperation::Difference: return "DifferenceFrom_"; case mitk::BooleanOperation::Intersection: return "IntersectionWith_"; case mitk::BooleanOperation::Union: return "UnionWith_"; default: assert(false && "Unknown boolean operation type"); return "UNKNOWN_BOOLEAN_OPERATION_WITH_"; } } void AddToDataStorage(mitk::DataStorage::Pointer dataStorage, mitk::Image::Pointer segmentation, const std::string& name, mitk::DataNode::Pointer parent = NULL) { mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); dataNode->SetBoolProperty("binary", true); dataNode->SetName(name); dataNode->SetData(segmentation); dataStorage->Add(dataNode, parent); } QmitkBooleanOperationsWidget::QmitkBooleanOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) : QmitkSegmentationUtilityWidget(timeNavigationController, parent) { m_Controls.setupUi(this); m_Controls.dataSelectionWidget->AddDataStorageComboBox(QmitkDataSelectionWidget::SegmentationPredicate); m_Controls.dataSelectionWidget->AddDataStorageComboBox(QmitkDataSelectionWidget::SegmentationPredicate); m_Controls.dataSelectionWidget->SetHelpText(HelpText); connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*))); connect(m_Controls.differenceButton, SIGNAL(clicked()), this, SLOT(OnDifferenceButtonClicked())); connect(m_Controls.intersectionButton, SIGNAL(clicked()), this, SLOT(OnIntersectionButtonClicked())); connect(m_Controls.unionButton, SIGNAL(clicked()), this, SLOT(OnUnionButtonClicked())); } QmitkBooleanOperationsWidget::~QmitkBooleanOperationsWidget() { } void QmitkBooleanOperationsWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection) { QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; mitk::DataNode::Pointer node0 = dataSelectionWidget->GetSelection(0); mitk::DataNode::Pointer node1 = dataSelectionWidget->GetSelection(1); if (node0.IsNotNull() && node1.IsNotNull() && node0 != node1) { dataSelectionWidget->SetHelpText(""); this->EnableButtons(); } else { dataSelectionWidget->SetHelpText(HelpText); this->EnableButtons(false); } } void QmitkBooleanOperationsWidget::EnableButtons(bool enable) { m_Controls.differenceButton->setEnabled(enable); m_Controls.intersectionButton->setEnabled(enable); m_Controls.unionButton->setEnabled(enable); } void QmitkBooleanOperationsWidget::OnDifferenceButtonClicked() { this->DoBooleanOperation(mitk::BooleanOperation::Difference); } void QmitkBooleanOperationsWidget::OnIntersectionButtonClicked() { this->DoBooleanOperation(mitk::BooleanOperation::Intersection); } void QmitkBooleanOperationsWidget::OnUnionButtonClicked() { this->DoBooleanOperation(mitk::BooleanOperation::Union); } void QmitkBooleanOperationsWidget::DoBooleanOperation(mitk::BooleanOperation::Type type) { mitk::SliceNavigationController* timeNavigationController = this->GetTimeNavigationController(); assert(timeNavigationController != NULL); mitk::Image::Pointer segmentation0 = static_cast<mitk::Image*>(m_Controls.dataSelectionWidget->GetSelection(0)->GetData()); mitk::Image::Pointer segmentation1 = static_cast<mitk::Image*>(m_Controls.dataSelectionWidget->GetSelection(1)->GetData()); mitk::Image::Pointer result; try { mitk::BooleanOperation booleanOperation(type, segmentation0, segmentation1, timeNavigationController->GetTime()->GetPos()); result = booleanOperation.GetResult(); } catch (const mitk::Exception &exception) { MITK_ERROR << "Boolean operation failed: " << exception.GetDescription(); } assert(result.IsNotNull()); QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; AddToDataStorage( dataSelectionWidget->GetDataStorage(), result, GetPrefix(type) + dataSelectionWidget->GetSelection(1)->GetName(), dataSelectionWidget->GetSelection(0)); } <commit_msg>moved everything in try-catch block. added qt message popup if exception thrown<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkBooleanOperationsWidget.h" #include "../../Common/QmitkDataSelectionWidget.h" #include <mitkException.h> #include <mitkSliceNavigationController.h> #include <cassert> #include <QMessageBox> static const char* const HelpText = "Select two different segmentations above"; std::string GetPrefix(mitk::BooleanOperation::Type type) { switch (type) { case mitk::BooleanOperation::Difference: return "DifferenceFrom_"; case mitk::BooleanOperation::Intersection: return "IntersectionWith_"; case mitk::BooleanOperation::Union: return "UnionWith_"; default: assert(false && "Unknown boolean operation type"); return "UNKNOWN_BOOLEAN_OPERATION_WITH_"; } } void AddToDataStorage(mitk::DataStorage::Pointer dataStorage, mitk::Image::Pointer segmentation, const std::string& name, mitk::DataNode::Pointer parent = NULL) { mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); dataNode->SetBoolProperty("binary", true); dataNode->SetName(name); dataNode->SetData(segmentation); dataStorage->Add(dataNode, parent); } QmitkBooleanOperationsWidget::QmitkBooleanOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) : QmitkSegmentationUtilityWidget(timeNavigationController, parent) { m_Controls.setupUi(this); m_Controls.dataSelectionWidget->AddDataStorageComboBox(QmitkDataSelectionWidget::SegmentationPredicate); m_Controls.dataSelectionWidget->AddDataStorageComboBox(QmitkDataSelectionWidget::SegmentationPredicate); m_Controls.dataSelectionWidget->SetHelpText(HelpText); connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*))); connect(m_Controls.differenceButton, SIGNAL(clicked()), this, SLOT(OnDifferenceButtonClicked())); connect(m_Controls.intersectionButton, SIGNAL(clicked()), this, SLOT(OnIntersectionButtonClicked())); connect(m_Controls.unionButton, SIGNAL(clicked()), this, SLOT(OnUnionButtonClicked())); } QmitkBooleanOperationsWidget::~QmitkBooleanOperationsWidget() { } void QmitkBooleanOperationsWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection) { QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; mitk::DataNode::Pointer node0 = dataSelectionWidget->GetSelection(0); mitk::DataNode::Pointer node1 = dataSelectionWidget->GetSelection(1); if (node0.IsNotNull() && node1.IsNotNull() && node0 != node1) { dataSelectionWidget->SetHelpText(""); this->EnableButtons(); } else { dataSelectionWidget->SetHelpText(HelpText); this->EnableButtons(false); } } void QmitkBooleanOperationsWidget::EnableButtons(bool enable) { m_Controls.differenceButton->setEnabled(enable); m_Controls.intersectionButton->setEnabled(enable); m_Controls.unionButton->setEnabled(enable); } void QmitkBooleanOperationsWidget::OnDifferenceButtonClicked() { this->DoBooleanOperation(mitk::BooleanOperation::Difference); } void QmitkBooleanOperationsWidget::OnIntersectionButtonClicked() { this->DoBooleanOperation(mitk::BooleanOperation::Intersection); } void QmitkBooleanOperationsWidget::OnUnionButtonClicked() { this->DoBooleanOperation(mitk::BooleanOperation::Union); } void QmitkBooleanOperationsWidget::DoBooleanOperation(mitk::BooleanOperation::Type type) { mitk::SliceNavigationController* timeNavigationController = this->GetTimeNavigationController(); assert(timeNavigationController != NULL); mitk::Image::Pointer segmentation0 = static_cast<mitk::Image*>(m_Controls.dataSelectionWidget->GetSelection(0)->GetData()); mitk::Image::Pointer segmentation1 = static_cast<mitk::Image*>(m_Controls.dataSelectionWidget->GetSelection(1)->GetData()); mitk::Image::Pointer result; try { mitk::BooleanOperation booleanOperation(type, segmentation0, segmentation1, timeNavigationController->GetTime()->GetPos()); result = booleanOperation.GetResult(); assert(result.IsNotNull()); QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; AddToDataStorage( dataSelectionWidget->GetDataStorage(), result, GetPrefix(type) + dataSelectionWidget->GetSelection(1)->GetName(), dataSelectionWidget->GetSelection(0)); } catch (const mitk::Exception &exception) { MITK_ERROR << "Boolean operation failed: " << exception.GetDescription(); QMessageBox::information(0, "Boolean operation failed", exception.GetDescription()); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2004-2006 Trolltech ASA. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** Licensees holding a valid Qt License Agreement may use this file in ** accordance with the rights, responsibilities and obligations ** contained therein. Please consult your licensing agreement or ** contact [email protected] if any conditions of this licensing ** agreement are not clear to you. ** ** Further information about Qt licensing is available at: ** http://www.trolltech.com/products/qt/licensing.html or by ** contacting [email protected]. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include <QApplication> #include <QSplashScreen> #include <QPixmap> #include "mainwindow.h" int main(int argc, char *argv[]) { Q_INIT_RESOURCE(application); QApplication app(argc, argv); QPixmap pixmap(":/images/splash.png"); QSplashScreen splash(pixmap); splash.show(); // sleep(1); // QIcon icon(":images/app.icns"); MainWindow mainWin(app, splash); mainWin.setUnifiedTitleAndToolBarOnMac(true); // mainWin.setWindowIcon(icon); return app.exec(); } <commit_msg>force splash screen to be repainted:<commit_after>/**************************************************************************** ** ** Copyright (C) 2004-2006 Trolltech ASA. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** Licensees holding a valid Qt License Agreement may use this file in ** accordance with the rights, responsibilities and obligations ** contained therein. Please consult your licensing agreement or ** contact [email protected] if any conditions of this licensing ** agreement are not clear to you. ** ** Further information about Qt licensing is available at: ** http://www.trolltech.com/products/qt/licensing.html or by ** contacting [email protected]. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include <QApplication> #include <QSplashScreen> #include <QPixmap> #include "mainwindow.h" int main(int argc, char *argv[]) { Q_INIT_RESOURCE(application); QApplication app(argc, argv); QPixmap pixmap(":/images/splash.png"); QSplashScreen splash(pixmap); splash.show(); // sleep(1); splash.repaint(); // QIcon icon(":images/app.icns"); MainWindow mainWin(app, splash); mainWin.setUnifiedTitleAndToolBarOnMac(true); // mainWin.setWindowIcon(icon); return app.exec(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android Open Source Project * * 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 "perfetto/base/unix_task_runner.h" #include "perfetto/traced/traced.h" #include "perfetto/tracing/ipc/service_ipc_host.h" namespace perfetto { int __attribute__((visibility("default"))) ServiceMain(int argc, char** argv) { base::UnixTaskRunner task_runner; std::unique_ptr<ServiceIPCHost> svc; svc = ServiceIPCHost::CreateInstance(&task_runner); // When built as part of the Android tree, the two socket are created and // bonund by init and their fd number is passed in two env variables. // See libcutils' android_get_control_socket(). const char* env_prod = getenv("ANDROID_SOCKET_traced_producer"); const char* env_cons = getenv("ANDROID_SOCKET_traced_consumer"); PERFETTO_CHECK((!env_prod && !env_prod) || (env_prod && env_cons)); if (env_prod) { base::ScopedFile producer_fd(atoi(env_prod)); base::ScopedFile consumer_fd(atoi(env_cons)); svc->Start(std::move(producer_fd), std::move(consumer_fd)); } else { unlink(PERFETTO_PRODUCER_SOCK_NAME); unlink(PERFETTO_CONSUMER_SOCK_NAME); svc->Start(PERFETTO_PRODUCER_SOCK_NAME, PERFETTO_CONSUMER_SOCK_NAME); } PERFETTO_ILOG("Started traced, listening on %s %s", PERFETTO_PRODUCER_SOCK_NAME, PERFETTO_CONSUMER_SOCK_NAME); task_runner.Run(); return 0; } } // namespace perfetto <commit_msg>Fix incorrect CHECK.<commit_after>/* * Copyright (C) 2017 The Android Open Source Project * * 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 "perfetto/base/unix_task_runner.h" #include "perfetto/traced/traced.h" #include "perfetto/tracing/ipc/service_ipc_host.h" namespace perfetto { int __attribute__((visibility("default"))) ServiceMain(int argc, char** argv) { base::UnixTaskRunner task_runner; std::unique_ptr<ServiceIPCHost> svc; svc = ServiceIPCHost::CreateInstance(&task_runner); // When built as part of the Android tree, the two socket are created and // bonund by init and their fd number is passed in two env variables. // See libcutils' android_get_control_socket(). const char* env_prod = getenv("ANDROID_SOCKET_traced_producer"); const char* env_cons = getenv("ANDROID_SOCKET_traced_consumer"); PERFETTO_CHECK((!env_prod && !env_cons) || (env_prod && env_cons)); if (env_prod) { base::ScopedFile producer_fd(atoi(env_prod)); base::ScopedFile consumer_fd(atoi(env_cons)); svc->Start(std::move(producer_fd), std::move(consumer_fd)); } else { unlink(PERFETTO_PRODUCER_SOCK_NAME); unlink(PERFETTO_CONSUMER_SOCK_NAME); svc->Start(PERFETTO_PRODUCER_SOCK_NAME, PERFETTO_CONSUMER_SOCK_NAME); } PERFETTO_ILOG("Started traced, listening on %s %s", PERFETTO_PRODUCER_SOCK_NAME, PERFETTO_CONSUMER_SOCK_NAME); task_runner.Run(); return 0; } } // namespace perfetto <|endoftext|>
<commit_before>/*********************************************************************** * filename: Element.cpp * created: 28/10/2011 * author: Martin Preisler *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/Element.h" #include <boost/test/unit_test.hpp> #include <boost/timer.hpp> BOOST_AUTO_TEST_SUITE(Element) BOOST_AUTO_TEST_CASE(RelativeSizing) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::percent(), 25.0f * CEGUI::UDim::percent())); root->addChild(child); BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100.0f, 100.0f)); BOOST_CHECK_EQUAL(child->getPixelSize(), CEGUI::Sizef(50.0f, 25.0f)); CEGUI::Element* innerChild = new CEGUI::Element(); child->addChild(innerChild); innerChild->setSize(CEGUI::USize(200.0f * CEGUI::UDim::percent(), 100.0f * CEGUI::UDim::percent())); BOOST_CHECK_EQUAL(innerChild->getPixelSize(), CEGUI::Sizef(100.0f, 25.0f)); delete innerChild; delete child; delete root; } BOOST_AUTO_TEST_CASE(RelativePositioning) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setPosition(CEGUI::UVector2(50.0f * CEGUI::UDim::percent(), 50.0f * CEGUI::UDim::percent())); child->setSize(CEGUI::USize(10.0f * CEGUI::UDim::px(), 10 * CEGUI::UDim::px())); root->addChild(child); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(50.0f, 50.0f, 60.0f, 60.0f)); delete child; delete root; } // TODO: RelativeRotation! BOOST_AUTO_TEST_CASE(HorizontalLeftAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT); BOOST_CHECK_EQUAL(child->getHorizontalAlignment(), CEGUI::HA_LEFT); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 50, 0)); child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(10, 0, 60, 0)); delete child; delete root; } BOOST_AUTO_TEST_CASE(HorizontalCentreAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT); child->setHorizontalAlignment(CEGUI::HA_CENTRE); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(25, 0, 75, 0)); child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(35, 0, 85, 0)); delete child; delete root; } BOOST_AUTO_TEST_CASE(HorizontalRightAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT); child->setHorizontalAlignment(CEGUI::HA_RIGHT); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(50, 0, 100, 0)); child->setPosition(CEGUI::UVector2(-10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(40, 0, 90, 0)); delete child; delete root; } BOOST_AUTO_TEST_CASE(VerticalTopAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP); BOOST_CHECK_EQUAL(child->getVerticalAlignment(), CEGUI::VA_TOP); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 50)); child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 5, 0, 55)); delete child; delete root; } BOOST_AUTO_TEST_CASE(VerticalCentreAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP); child->setVerticalAlignment(CEGUI::VA_CENTRE); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 25, 0, 75)); child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 30, 0, 80)); delete child; delete root; } BOOST_AUTO_TEST_CASE(VerticalBottomAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP); child->setVerticalAlignment(CEGUI::VA_BOTTOM); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 50, 0, 100)); child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), -5.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 45, 0, 95)); delete child; delete root; } BOOST_AUTO_TEST_CASE(AspectLocking) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getAspectMode(), CEGUI::AM_IGNORE); BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100, 100)); root->setAspectMode(CEGUI::AM_SHRINK); root->setAspectRatio(1.0f / 2.0f); // todo: should have tolerances or something, or does boost do that automatically? BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(50, 100)); root->setAspectMode(CEGUI::AM_EXPAND); root->setAspectRatio(1.0f / 2.0f); // todo: should have tolerances or something, or does boost do that automatically? BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100, 200)); delete root; } BOOST_AUTO_TEST_CASE(PixelAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setPosition(CEGUI::UVector2(0.2f * CEGUI::UDim::px(), 0.2f * CEGUI::UDim::px())); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100.0f * CEGUI::UDim::px())); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK(root->isPixelAligned()); // todo: should have tolerances or something, or does boost do that automatically? BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 100)); root->setPixelAligned(false); // todo: should have tolerances or something, or does boost do that automatically? BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0.2f, 0.2f, 100.2f, 100.2f)); delete root; } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Added test case for min/max size in Element<commit_after>/*********************************************************************** * filename: Element.cpp * created: 28/10/2011 * author: Martin Preisler *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/Element.h" #include <boost/test/unit_test.hpp> #include <boost/timer.hpp> BOOST_AUTO_TEST_SUITE(Element) BOOST_AUTO_TEST_CASE(RelativeSizing) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::percent(), 25.0f * CEGUI::UDim::percent())); root->addChild(child); BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100.0f, 100.0f)); BOOST_CHECK_EQUAL(child->getPixelSize(), CEGUI::Sizef(50.0f, 25.0f)); CEGUI::Element* innerChild = new CEGUI::Element(); child->addChild(innerChild); innerChild->setSize(CEGUI::USize(200.0f * CEGUI::UDim::percent(), 100.0f * CEGUI::UDim::percent())); BOOST_CHECK_EQUAL(innerChild->getPixelSize(), CEGUI::Sizef(100.0f, 25.0f)); delete innerChild; delete child; delete root; } BOOST_AUTO_TEST_CASE(RelativePositioning) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setPosition(CEGUI::UVector2(50.0f * CEGUI::UDim::percent(), 50.0f * CEGUI::UDim::percent())); child->setSize(CEGUI::USize(10.0f * CEGUI::UDim::px(), 10 * CEGUI::UDim::px())); root->addChild(child); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(50.0f, 50.0f, 60.0f, 60.0f)); delete child; delete root; } // TODO: RelativeRotation! BOOST_AUTO_TEST_CASE(MinMaxSize) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); root->setMaxSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 50 * CEGUI::UDim::px()));; BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(50.0f, 50.0f)); root->setMaxSize(CEGUI::USize(75.0f * CEGUI::UDim::px(), 75.0f * CEGUI::UDim::px()));; BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(75.0f, 75.0f)); root->setMaxSize(CEGUI::USize(1000.0f * CEGUI::UDim::px(), 1000 * CEGUI::UDim::px()));; root->setMinSize(CEGUI::USize(125.0f * CEGUI::UDim::px(), 125.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(125.0f, 125.0f)); delete root; } BOOST_AUTO_TEST_CASE(HorizontalLeftAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT); BOOST_CHECK_EQUAL(child->getHorizontalAlignment(), CEGUI::HA_LEFT); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 50, 0)); child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(10, 0, 60, 0)); delete child; delete root; } BOOST_AUTO_TEST_CASE(HorizontalCentreAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT); child->setHorizontalAlignment(CEGUI::HA_CENTRE); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(25, 0, 75, 0)); child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(35, 0, 85, 0)); delete child; delete root; } BOOST_AUTO_TEST_CASE(HorizontalRightAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT); child->setHorizontalAlignment(CEGUI::HA_RIGHT); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(50, 0, 100, 0)); child->setPosition(CEGUI::UVector2(-10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(40, 0, 90, 0)); delete child; delete root; } BOOST_AUTO_TEST_CASE(VerticalTopAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP); BOOST_CHECK_EQUAL(child->getVerticalAlignment(), CEGUI::VA_TOP); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 50)); child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 5, 0, 55)); delete child; delete root; } BOOST_AUTO_TEST_CASE(VerticalCentreAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP); child->setVerticalAlignment(CEGUI::VA_CENTRE); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 25, 0, 75)); child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 30, 0, 80)); delete child; delete root; } BOOST_AUTO_TEST_CASE(VerticalBottomAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); CEGUI::Element* child = new CEGUI::Element(); child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px())); root->addChild(child); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP); child->setVerticalAlignment(CEGUI::VA_BOTTOM); BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100)); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 50, 0, 100)); child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), -5.0f * CEGUI::UDim::px())); BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 45, 0, 95)); delete child; delete root; } BOOST_AUTO_TEST_CASE(AspectLocking) { CEGUI::Element* root = new CEGUI::Element(); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px())); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK_EQUAL(root->getAspectMode(), CEGUI::AM_IGNORE); BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100, 100)); root->setAspectMode(CEGUI::AM_SHRINK); root->setAspectRatio(1.0f / 2.0f); // todo: should have tolerances or something, or does boost do that automatically? BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(50, 100)); root->setAspectMode(CEGUI::AM_EXPAND); root->setAspectRatio(1.0f / 2.0f); // todo: should have tolerances or something, or does boost do that automatically? BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100, 200)); delete root; } BOOST_AUTO_TEST_CASE(PixelAlignment) { CEGUI::Element* root = new CEGUI::Element(); root->setPosition(CEGUI::UVector2(0.2f * CEGUI::UDim::px(), 0.2f * CEGUI::UDim::px())); root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100.0f * CEGUI::UDim::px())); // even though it is the default at the point of writing the test, we have to make sure this fact doesn't change! BOOST_CHECK(root->isPixelAligned()); // todo: should have tolerances or something, or does boost do that automatically? BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 100)); root->setPixelAligned(false); // todo: should have tolerances or something, or does boost do that automatically? BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0.2f, 0.2f, 100.2f, 100.2f)); delete root; } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <queue> #include <qi/log.hpp> #include <cerrno> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include <qimessaging/transportserver.hpp> #include <qimessaging/transportsocket.hpp> #include "tcptransportsocket.hpp" #include <qi/eventloop.hpp> #include "transportserver_p.hpp" #include "transportserverasio_p.hpp" namespace qi { void TransportServerAsioPrivate::onAccept(const boost::system::error_code& erc, boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s, boost::shared_ptr<bool> live) { qiLogDebug("qimessaging.server.listen") << this << " onAccept"; if (!(*live)) { delete s; return; } if (erc) { qiLogDebug("qimessaging.server.listen") << "accept error " << erc.message(); delete s; self->acceptError(erc.value()); return; } qi::TransportSocketPtr socket = qi::TcpTransportSocketPtr(new TcpTransportSocket(s, context, _ssl)); self->newConnection(socket); s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext); _acceptor.async_accept(s->lowest_layer(), boost::bind(&TransportServerAsioPrivate::onAccept, this, _1, s, live)); } void TransportServerAsioPrivate::close() { qiLogDebug("qimessaging.server.listen") << this << " close"; *_live = false; _acceptor.close(); } qi::Future<void> TransportServerAsioPrivate::listen(const qi::Url& url) { qi::Url listenUrl = url; using namespace boost::asio; // resolve endpoint ip::tcp::resolver r(_acceptor.get_io_service()); ip::tcp::resolver::query q(listenUrl.host(), boost::lexical_cast<std::string>(listenUrl.port())); ip::tcp::resolver::iterator it = r.resolve(q); if (it == ip::tcp::resolver::iterator()) { const char* s = "Listen error: no endpoint."; qiLogError("qimessaging.server.listen") << s; return qi::makeFutureError<void>(s); } ip::tcp::endpoint ep = *it; qiLogDebug("qimessaging.server.listen") <<"Will listen on " << ep.address().to_string() << ' ' << ep.port(); _acceptor.open(ep.protocol()); #ifdef _WIN32 boost::asio::socket_base::reuse_address option(false); #else boost::asio::socket_base::reuse_address option(true); #endif _acceptor.set_option(option); _acceptor.bind(ep); boost::system::error_code ec; _acceptor.listen(socket_base::max_connections, ec); if (ec) { qiLogError("qimessaging.server.listen") << ec.message(); return qi::makeFutureError<void>(ec.message()); } unsigned port = _acceptor.local_endpoint().port();// already in host byte orde qiLogDebug("qimessaging.server.listen") << "Effective port io_service" << port; if (listenUrl.port() == 0) { listenUrl = Url(listenUrl.protocol() + "://" + listenUrl.host() + ":" + boost::lexical_cast<std::string>(port)); } /* Set endpoints */ if (listenUrl.host() != "0.0.0.0") { qiLogDebug("qimessaging.server.listen") << "Adding endpoint : " << listenUrl.str(); _endpoints.push_back(listenUrl.str()); } if (listenUrl.host() == "0.0.0.0") // need available ip addresses { std::string protocol; std::map<std::string, std::vector<std::string> > ifsMap = qi::os::hostIPAddrs(); if (ifsMap.empty()) { const char* s = "Cannot get host addresses"; qiLogWarning("qimessaging.server.listen") << s; return qi::makeFutureError<void>(s); } #ifdef WIN32 // hostIPAddrs doesn't return loopback on windows ifsMap["Loopback"].push_back("127.0.0.1"); #endif _ssl = listenUrl.protocol() == "tcps"; protocol = _ssl ? "tcps://" : "tcp://"; for (std::map<std::string, std::vector<std::string> >::iterator interfaceIt = ifsMap.begin(); interfaceIt != ifsMap.end(); ++interfaceIt) { for (std::vector<std::string>::iterator addressIt = (*interfaceIt).second.begin(); addressIt != (*interfaceIt).second.end(); ++addressIt) { std::stringstream ss; ss << protocol; ss << (*addressIt); ss << ":"; ss << port; qiLogVerbose("qimessaging.server.listen") << "Adding endpoint : " << ss.str(); _endpoints.push_back(ss.str()); } } } if (_ssl) { if (self->_p->_identityCertificate.empty() || self->_p->_identityKey.empty()) { const char* s = "SSL certificates missing, please call Session::setIdentity first"; qiLogError("qimessaging.server.listen") << s; return qi::makeFutureError<void>(s); } _sslContext.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2); _sslContext.use_certificate_chain_file(self->_p->_identityCertificate.c_str()); _sslContext.use_private_key_file(self->_p->_identityKey.c_str(), boost::asio::ssl::context::pem); } boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext); _acceptor.async_accept(s->lowest_layer(), boost::bind(&TransportServerAsioPrivate::onAccept, this, _1, s, _live)); _connectionPromise.setValue(0); return _connectionPromise.future(); } void TransportServerAsioPrivate::destroy() { *_live = false; close(); // We no longuer hold the eventLoop, so we cannot use post. // But synchronous deletion of this is safe, since async callback uses _live delete this; } TransportServerAsioPrivate::TransportServerAsioPrivate(TransportServer* self, EventLoop* ctx) : TransportServerImplPrivate(self, ctx) , _acceptor(*(boost::asio::io_service*)ctx->nativeHandle()) , _live(new bool(true)) , _sslContext(*(boost::asio::io_service*)ctx->nativeHandle(), boost::asio::ssl::context::sslv23) , _ssl(false) { } TransportServerAsioPrivate::~TransportServerAsioPrivate() { *_live = false; } } <commit_msg>Fix misplaced if<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <queue> #include <qi/log.hpp> #include <cerrno> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include <qimessaging/transportserver.hpp> #include <qimessaging/transportsocket.hpp> #include "tcptransportsocket.hpp" #include <qi/eventloop.hpp> #include "transportserver_p.hpp" #include "transportserverasio_p.hpp" namespace qi { void TransportServerAsioPrivate::onAccept(const boost::system::error_code& erc, boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s, boost::shared_ptr<bool> live) { qiLogDebug("qimessaging.server.listen") << this << " onAccept"; if (!(*live)) { delete s; return; } if (erc) { qiLogDebug("qimessaging.server.listen") << "accept error " << erc.message(); delete s; self->acceptError(erc.value()); return; } qi::TransportSocketPtr socket = qi::TcpTransportSocketPtr(new TcpTransportSocket(s, context, _ssl)); self->newConnection(socket); s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext); _acceptor.async_accept(s->lowest_layer(), boost::bind(&TransportServerAsioPrivate::onAccept, this, _1, s, live)); } void TransportServerAsioPrivate::close() { qiLogDebug("qimessaging.server.listen") << this << " close"; *_live = false; _acceptor.close(); } qi::Future<void> TransportServerAsioPrivate::listen(const qi::Url& url) { qi::Url listenUrl = url; _ssl = listenUrl.protocol() == "tcps"; using namespace boost::asio; // resolve endpoint ip::tcp::resolver r(_acceptor.get_io_service()); ip::tcp::resolver::query q(listenUrl.host(), boost::lexical_cast<std::string>(listenUrl.port())); ip::tcp::resolver::iterator it = r.resolve(q); if (it == ip::tcp::resolver::iterator()) { const char* s = "Listen error: no endpoint."; qiLogError("qimessaging.server.listen") << s; return qi::makeFutureError<void>(s); } ip::tcp::endpoint ep = *it; qiLogDebug("qimessaging.server.listen") <<"Will listen on " << ep.address().to_string() << ' ' << ep.port(); _acceptor.open(ep.protocol()); #ifdef _WIN32 boost::asio::socket_base::reuse_address option(false); #else boost::asio::socket_base::reuse_address option(true); #endif _acceptor.set_option(option); _acceptor.bind(ep); boost::system::error_code ec; _acceptor.listen(socket_base::max_connections, ec); if (ec) { qiLogError("qimessaging.server.listen") << ec.message(); return qi::makeFutureError<void>(ec.message()); } unsigned port = _acceptor.local_endpoint().port();// already in host byte orde qiLogDebug("qimessaging.server.listen") << "Effective port io_service" << port; if (listenUrl.port() == 0) { listenUrl = Url(listenUrl.protocol() + "://" + listenUrl.host() + ":" + boost::lexical_cast<std::string>(port)); } /* Set endpoints */ if (listenUrl.host() != "0.0.0.0") { qiLogDebug("qimessaging.server.listen") << "Adding endpoint : " << listenUrl.str(); _endpoints.push_back(listenUrl.str()); } if (listenUrl.host() == "0.0.0.0") // need available ip addresses { std::string protocol; std::map<std::string, std::vector<std::string> > ifsMap = qi::os::hostIPAddrs(); if (ifsMap.empty()) { const char* s = "Cannot get host addresses"; qiLogWarning("qimessaging.server.listen") << s; return qi::makeFutureError<void>(s); } #ifdef WIN32 // hostIPAddrs doesn't return loopback on windows ifsMap["Loopback"].push_back("127.0.0.1"); #endif protocol = _ssl ? "tcps://" : "tcp://"; for (std::map<std::string, std::vector<std::string> >::iterator interfaceIt = ifsMap.begin(); interfaceIt != ifsMap.end(); ++interfaceIt) { for (std::vector<std::string>::iterator addressIt = (*interfaceIt).second.begin(); addressIt != (*interfaceIt).second.end(); ++addressIt) { std::stringstream ss; ss << protocol; ss << (*addressIt); ss << ":"; ss << port; qiLogVerbose("qimessaging.server.listen") << "Adding endpoint : " << ss.str(); _endpoints.push_back(ss.str()); } } } if (_ssl) { if (self->_p->_identityCertificate.empty() || self->_p->_identityKey.empty()) { const char* s = "SSL certificates missing, please call Session::setIdentity first"; qiLogError("qimessaging.server.listen") << s; return qi::makeFutureError<void>(s); } _sslContext.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2); _sslContext.use_certificate_chain_file(self->_p->_identityCertificate.c_str()); _sslContext.use_private_key_file(self->_p->_identityKey.c_str(), boost::asio::ssl::context::pem); } boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext); _acceptor.async_accept(s->lowest_layer(), boost::bind(&TransportServerAsioPrivate::onAccept, this, _1, s, _live)); _connectionPromise.setValue(0); return _connectionPromise.future(); } void TransportServerAsioPrivate::destroy() { *_live = false; close(); // We no longuer hold the eventLoop, so we cannot use post. // But synchronous deletion of this is safe, since async callback uses _live delete this; } TransportServerAsioPrivate::TransportServerAsioPrivate(TransportServer* self, EventLoop* ctx) : TransportServerImplPrivate(self, ctx) , _acceptor(*(boost::asio::io_service*)ctx->nativeHandle()) , _live(new bool(true)) , _sslContext(*(boost::asio::io_service*)ctx->nativeHandle(), boost::asio::ssl::context::sslv23) , _ssl(false) { } TransportServerAsioPrivate::~TransportServerAsioPrivate() { *_live = false; } } <|endoftext|>
<commit_before><commit_msg>Fix linux views build.<commit_after><|endoftext|>
<commit_before>// Copyright 2012 Alessio Sclocco <[email protected]> // // 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> using std::cout; using std::cerr; using std::endl; #include <string> using std::string; #include <vector> using std::vector; #include <exception> using std::exception; #include <iomanip> using std::fixed; using std::setprecision; #include <limits> using std::numeric_limits; #include <cmath> #include <ctime> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <Observation.hpp> using AstroData::Observation; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::same; #include <Folding.hpp> using PulsarSearch::Folding; #include <FoldingCPU.hpp> using PulsarSearch::folding; #include <Bins.hpp> using PulsarSearch::getNrSamplesPerBin; typedef float dataType; const string typeName("float"); const unsigned int padding = 32; // LOFAR //const unsigned int nrSamplesPerSecond = 200000; // Apertif const unsigned int nrSamplesPerSecond = 20000; // DMs const unsigned int nrDMs = 256; // Periods const unsigned int nrPeriods = 128; const unsigned int nrBins = 256; const unsigned int periodStep = 64; int main(int argc, char *argv[]) { unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; long long unsigned int wrongValues = 0; Observation< dataType > observation("FoldingTest", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true); CLData< unsigned int > * readCounterData = new CLData< unsigned int >("ReadCounterData", true); CLData< unsigned int > * writeCounterData = new CLData< unsigned int >("WriteCounterData", true); CLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >("NrSamplesPerBin", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); } catch ( exception &err ) { cerr << err.what() << endl; return 1; } // Setup of the observation observation.setPadding(padding); observation.setNrSamplesPerSecond(nrSamplesPerSecond); observation.setNrDMs(nrDMs); observation.setNrPeriods(nrPeriods); observation.setFirstPeriod(nrBins); observation.setPeriodStep(periodStep); observation.setNrBins(nrBins); cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); // Allocate memory dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); foldedData->blankHostData(); readCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins()); readCounterData->blankHostData(); writeCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins()); writeCounterData->blankHostData(); vector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation); nrSamplesPerBin->allocateHostData(*nrSamplesPerBinData); dedispersedData->setCLContext(clContext); dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); readCounterData->setCLContext(clContext); readCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); writeCounterData->setCLContext(clContext); writeCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); nrSamplesPerBin->setCLContext(clContext); nrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); nrSamplesPerBin->setDeviceReadOnly(); try { dedispersedData->allocateDeviceData(); foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); readCounterData->allocateDeviceData(); readCounterData->copyHostToDevice(); writeCounterData->allocateDeviceData(); writeCounterData->copyHostToDevice(); nrSamplesPerBin->allocateDeviceData(); nrSamplesPerBin->copyHostToDevice(); } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } srand(time(NULL)); for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100); } } // Test try { // Generate kernel Folding< dataType > clFold("clFold", typeName); clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clFold.setObservation(&observation); clFold.setNrSamplesPerBin(nrSamplesPerBin); clFold.setNrDMsPerBlock(128); clFold.setNrPeriodsPerBlock(2); clFold.setNrBinsPerBlock(1); clFold.setNrDMsPerThread(2); clFold.setNrPeriodsPerThread(2); clFold.setNrBinsPerThread(4); clFold.generateCode(); dedispersedData->copyHostToDevice(); clFold(0, dedispersedData, foldedData, readCounterData, writeCounterData); foldedData->copyDeviceToHost(); } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } // Check CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true); CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true); CPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs()); CPUCounter->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins()); CPUCounter->blankHostData(); folding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData()); for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { long long unsigned int wrongValuesBin = 0; for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM; if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) { wrongValues++; wrongValuesBin++; } } } if ( wrongValuesBin > 0 ) { cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl; } } cout << endl; cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl; cout << endl; return 0; } <commit_msg>Reading the arguments from command line.<commit_after>// Copyright 2012 Alessio Sclocco <[email protected]> // // 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> using std::cout; using std::cerr; using std::endl; #include <string> using std::string; #include <vector> using std::vector; #include <exception> using std::exception; #include <iomanip> using std::fixed; using std::setprecision; #include <limits> using std::numeric_limits; #include <cmath> #include <ctime> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <Observation.hpp> using AstroData::Observation; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::same; #include <Folding.hpp> using PulsarSearch::Folding; #include <FoldingCPU.hpp> using PulsarSearch::folding; #include <Bins.hpp> using PulsarSearch::getNrSamplesPerBin; typedef float dataType; const string typeName("float"); const unsigned int padding = 32; int main(int argc, char *argv[]) { unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; long long unsigned int wrongValues = 0; Observation< dataType > observation("FoldingTest", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true); CLData< unsigned int > * readCounterData = new CLData< unsigned int >("ReadCounterData", true); CLData< unsigned int > * writeCounterData = new CLData< unsigned int >("WriteCounterData", true); CLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >("NrSamplesPerBin", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods")); observation.setFirstPeriod(args.getSwitchArgument< unsigned int >("-period_first")); observation.setPeriodStep(args.getSwitchArgument< unsigned int >("-period_step")); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } catch ( exception &err ) { cerr << err.what() << endl; return 1; } // Setup of the observation observation.setPadding(padding); observation.setNrSamplesPerSecond(nrSamplesPerSecond); observation.setNrDMs(nrDMs); observation.setNrPeriods(nrPeriods); observation.setFirstPeriod(nrBins); observation.setPeriodStep(periodStep); observation.setNrBins(nrBins); cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); // Allocate memory dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); foldedData->blankHostData(); readCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins()); readCounterData->blankHostData(); writeCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins()); writeCounterData->blankHostData(); vector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation); nrSamplesPerBin->allocateHostData(*nrSamplesPerBinData); dedispersedData->setCLContext(clContext); dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); readCounterData->setCLContext(clContext); readCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); writeCounterData->setCLContext(clContext); writeCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); nrSamplesPerBin->setCLContext(clContext); nrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); nrSamplesPerBin->setDeviceReadOnly(); try { dedispersedData->allocateDeviceData(); foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); readCounterData->allocateDeviceData(); readCounterData->copyHostToDevice(); writeCounterData->allocateDeviceData(); writeCounterData->copyHostToDevice(); nrSamplesPerBin->allocateDeviceData(); nrSamplesPerBin->copyHostToDevice(); } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } srand(time(NULL)); for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100); } } // Test try { // Generate kernel Folding< dataType > clFold("clFold", typeName); clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clFold.setObservation(&observation); clFold.setNrSamplesPerBin(nrSamplesPerBin); clFold.setNrDMsPerBlock(128); clFold.setNrPeriodsPerBlock(2); clFold.setNrBinsPerBlock(1); clFold.setNrDMsPerThread(2); clFold.setNrPeriodsPerThread(2); clFold.setNrBinsPerThread(4); clFold.generateCode(); dedispersedData->copyHostToDevice(); clFold(0, dedispersedData, foldedData, readCounterData, writeCounterData); foldedData->copyDeviceToHost(); } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } // Check CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true); CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true); CPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs()); CPUCounter->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins()); CPUCounter->blankHostData(); folding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData()); for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { long long unsigned int wrongValuesBin = 0; for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM; if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) { wrongValues++; wrongValuesBin++; } } } if ( wrongValuesBin > 0 ) { cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl; } } cout << endl; cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl; cout << endl; return 0; } <|endoftext|>
<commit_before><commit_msg>Fix build.<commit_after><|endoftext|>
<commit_before><commit_msg>Fix the compile for TOOLKIT_VIEWS.<commit_after><|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Matrix> #include <osg/Quat> #include <osg/Notify> #include <osg/Math> #include <stdlib.h> using namespace osg; #define SET_ROW(row, v1, v2, v3, v4 ) \ _mat[(row)][0] = (v1); \ _mat[(row)][1] = (v2); \ _mat[(row)][2] = (v3); \ _mat[(row)][3] = (v4); #define INNER_PRODUCT(a,b,r,c) \ ((a)._mat[r][0] * (b)._mat[0][c]) \ +((a)._mat[r][1] * (b)._mat[1][c]) \ +((a)._mat[r][2] * (b)._mat[2][c]) \ +((a)._mat[r][3] * (b)._mat[3][c]) Matrix::Matrix() { makeIdentity(); } Matrix::Matrix( const Matrix& other) { set( (const float *) other._mat ); } Matrix::Matrix( const float * const def ) { set( def ); } Matrix::Matrix( float a00, float a01, float a02, float a03, float a10, float a11, float a12, float a13, float a20, float a21, float a22, float a23, float a30, float a31, float a32, float a33) { SET_ROW(0, a00, a01, a02, a03 ) SET_ROW(1, a10, a11, a12, a13 ) SET_ROW(2, a20, a21, a22, a23 ) SET_ROW(3, a30, a31, a32, a33 ) } void Matrix::set( float a00, float a01, float a02, float a03, float a10, float a11, float a12, float a13, float a20, float a21, float a22, float a23, float a30, float a31, float a32, float a33) { SET_ROW(0, a00, a01, a02, a03 ) SET_ROW(1, a10, a11, a12, a13 ) SET_ROW(2, a20, a21, a22, a23 ) SET_ROW(3, a30, a31, a32, a33 ) } void Matrix::setTrans( float tx, float ty, float tz ) { _mat[3][0] = tx; _mat[3][1] = ty; _mat[3][2] = tz; } void Matrix::setTrans( const Vec3& v ) { _mat[3][0] = v[0]; _mat[3][1] = v[1]; _mat[3][2] = v[2]; } void Matrix::makeIdentity() { SET_ROW(0, 1, 0, 0, 0 ) SET_ROW(1, 0, 1, 0, 0 ) SET_ROW(2, 0, 0, 1, 0 ) SET_ROW(3, 0, 0, 0, 1 ) } void Matrix::makeScale( const Vec3& v ) { makeScale(v[0], v[1], v[2] ); } void Matrix::makeScale( float x, float y, float z ) { SET_ROW(0, x, 0, 0, 0 ) SET_ROW(1, 0, y, 0, 0 ) SET_ROW(2, 0, 0, z, 0 ) SET_ROW(3, 0, 0, 0, 1 ) } void Matrix::makeTranslate( const Vec3& v ) { makeTranslate( v[0], v[1], v[2] ); } void Matrix::makeTranslate( float x, float y, float z ) { SET_ROW(0, 1, 0, 0, 0 ) SET_ROW(1, 0, 1, 0, 0 ) SET_ROW(2, 0, 0, 1, 0 ) SET_ROW(3, x, y, z, 1 ) } void Matrix::makeRotate( const Vec3& from, const Vec3& to ) { Quat quat; quat.makeRotate(from,to); quat.get(*this); } void Matrix::makeRotate( float angle, const Vec3& axis ) { Quat quat; quat.makeRotate( angle, axis); quat.get(*this); } void Matrix::makeRotate( float angle, float x, float y, float z ) { Quat quat; quat.makeRotate( angle, x, y, z); quat.get(*this); } void Matrix::makeRotate( const Quat& q ) { q.get(*this); } void Matrix::makeRotate( float angle1, const Vec3& axis1, float angle2, const Vec3& axis2, float angle3, const Vec3& axis3) { Quat quat; quat.makeRotate(angle1, axis1, angle2, axis2, angle3, axis3); quat.get(*this); } void Matrix::mult( const Matrix& lhs, const Matrix& rhs ) { if (&lhs==this) { postMult(rhs); return; } if (&rhs==this) { preMult(lhs); return; } // PRECONDITION: We assume neither &lhs nor &rhs == this // if it did, use preMult or postMult instead _mat[0][0] = INNER_PRODUCT(lhs, rhs, 0, 0); _mat[0][1] = INNER_PRODUCT(lhs, rhs, 0, 1); _mat[0][2] = INNER_PRODUCT(lhs, rhs, 0, 2); _mat[0][3] = INNER_PRODUCT(lhs, rhs, 0, 3); _mat[1][0] = INNER_PRODUCT(lhs, rhs, 1, 0); _mat[1][1] = INNER_PRODUCT(lhs, rhs, 1, 1); _mat[1][2] = INNER_PRODUCT(lhs, rhs, 1, 2); _mat[1][3] = INNER_PRODUCT(lhs, rhs, 1, 3); _mat[2][0] = INNER_PRODUCT(lhs, rhs, 2, 0); _mat[2][1] = INNER_PRODUCT(lhs, rhs, 2, 1); _mat[2][2] = INNER_PRODUCT(lhs, rhs, 2, 2); _mat[2][3] = INNER_PRODUCT(lhs, rhs, 2, 3); _mat[3][0] = INNER_PRODUCT(lhs, rhs, 3, 0); _mat[3][1] = INNER_PRODUCT(lhs, rhs, 3, 1); _mat[3][2] = INNER_PRODUCT(lhs, rhs, 3, 2); _mat[3][3] = INNER_PRODUCT(lhs, rhs, 3, 3); } void Matrix::preMult( const Matrix& other ) { // brute force method requiring a copy //Matrix tmp(other* *this); // *this = tmp; // more efficient method just use a float[4] for temporary storage. float t[4]; for(int col=0; col<4; ++col) { t[0] = INNER_PRODUCT( other, *this, 0, col ); t[1] = INNER_PRODUCT( other, *this, 1, col ); t[2] = INNER_PRODUCT( other, *this, 2, col ); t[3] = INNER_PRODUCT( other, *this, 3, col ); _mat[0][col] = t[0]; _mat[1][col] = t[1]; _mat[2][col] = t[2]; _mat[3][col] = t[3]; } } void Matrix::postMult( const Matrix& other ) { // brute force method requiring a copy //Matrix tmp(*this * other); // *this = tmp; // more efficient method just use a float[4] for temporary storage. float t[4]; for(int row=0; row<4; ++row) { t[0] = INNER_PRODUCT( *this, other, row, 0 ); t[1] = INNER_PRODUCT( *this, other, row, 1 ); t[2] = INNER_PRODUCT( *this, other, row, 2 ); t[3] = INNER_PRODUCT( *this, other, row, 3 ); SET_ROW(row, t[0], t[1], t[2], t[3] ) } } #undef INNER_PRODUCT template <class T> inline T SGL_ABS(T a) { return (a >= 0 ? a : -a); } #ifndef SGL_SWAP #define SGL_SWAP(a,b,temp) ((temp)=(a),(a)=(b),(b)=(temp)) #endif bool Matrix::invert( const Matrix& mat ) { if (&mat==this) { Matrix tm(mat); return invert(tm); } unsigned int indxc[4], indxr[4], ipiv[4]; unsigned int i,j,k,l,ll; unsigned int icol = 0; unsigned int irow = 0; float temp, pivinv, dum, big; // copy in place this may be unnecessary *this = mat; for (j=0; j<4; j++) ipiv[j]=0; for(i=0;i<4;i++) { big=(float)0.0; for (j=0; j<4; j++) if (ipiv[j] != 1) for (k=0; k<4; k++) { if (ipiv[k] == 0) { if (SGL_ABS(operator()(j,k)) >= big) { big = SGL_ABS(operator()(j,k)); irow=j; icol=k; } } else if (ipiv[k] > 1) return false; } ++(ipiv[icol]); if (irow != icol) for (l=0; l<4; l++) SGL_SWAP(operator()(irow,l), operator()(icol,l), temp); indxr[i]=irow; indxc[i]=icol; if (operator()(icol,icol) == 0) return false; pivinv = 1.0/operator()(icol,icol); operator()(icol,icol) = 1; for (l=0; l<4; l++) operator()(icol,l) *= pivinv; for (ll=0; ll<4; ll++) if (ll != icol) { dum=operator()(ll,icol); operator()(ll,icol) = 0; for (l=0; l<4; l++) operator()(ll,l) -= operator()(icol,l)*dum; } } for (int lx=4; lx>0; --lx) { if (indxr[lx-1] != indxc[lx-1]) for (k=0; k<4; k++) SGL_SWAP(operator()(k,indxr[lx-1]), operator()(k,indxc[lx-1]),temp); } return true; } void Matrix::makeOrtho(double left, double right, double bottom, double top, double zNear, double zFar) { // note transpose of Matrix wr.t OpenGL documentation, since the OSG use post multiplication rather than pre. double tx = -(right+left)/(right-left); double ty = -(top+bottom)/(top-bottom); double tz = -(zFar+zNear)/(zFar-zNear); SET_ROW(0, 2.0f/(right-left), 0.0f, 0.0f, 0.0f ) SET_ROW(1, 0.0f, 2.0f/(top-bottom), 0.0f, 0.0f ) SET_ROW(2, 0.0f, 0.0f, -2.0f/(zFar-zNear), 0.0f ) SET_ROW(3, tx, ty, tz, 1.0f ) } void Matrix::makeFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { // note transpose of Matrix wr.t OpenGL documentation, since the OSG use post multiplication rather than pre. double A = (right+left)/(right-left); double B = (top+bottom)/(top-bottom); double C = -(zFar+zNear)/(zFar-zNear); double D = -2.0*zFar*zNear/(zFar-zNear); SET_ROW(0, 2.0f*zNear/(right-left), 0.0f, 0.0f, 0.0f ) SET_ROW(1, 0.0f, 2.0f*zNear/(top-bottom), 0.0f, 0.0f ) SET_ROW(2, A, B, C, -1.0f ) SET_ROW(3, 0.0f, 0.0f, D, 0.0f ) } void Matrix::makePerspective(double fovy,double aspectRatio, double zNear, double zFar) { // calculate the appropriate left, right etc. double tan_fovy = tan(DegreesToRadians(fovy*0.5)); double right = tan_fovy * aspectRatio * zNear; double left = -right; double top = tan_fovy * zNear; double bottom = -top; makeFrustum(left,right,bottom,top,zNear,zFar); } void Matrix::makeLookAt(const Vec3& eye,const Vec3& center,const Vec3& up) { Vec3 f(center-eye); f.normalize(); Vec3 s(f^up); s.normalize(); Vec3 u(s^f); u.normalize(); set( s[0], u[0], -f[0], 0.0f, s[1], u[1], -f[1], 0.0f, s[2], u[2], -f[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); preMult(Matrix::translate(-eye)); } #undef SET_ROW <commit_msg>From Ben, promoted floats to doubles to produce better stability in the invert method.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Matrix> #include <osg/Quat> #include <osg/Notify> #include <osg/Math> #include <stdlib.h> using namespace osg; #define SET_ROW(row, v1, v2, v3, v4 ) \ _mat[(row)][0] = (v1); \ _mat[(row)][1] = (v2); \ _mat[(row)][2] = (v3); \ _mat[(row)][3] = (v4); #define INNER_PRODUCT(a,b,r,c) \ ((a)._mat[r][0] * (b)._mat[0][c]) \ +((a)._mat[r][1] * (b)._mat[1][c]) \ +((a)._mat[r][2] * (b)._mat[2][c]) \ +((a)._mat[r][3] * (b)._mat[3][c]) Matrix::Matrix() { makeIdentity(); } Matrix::Matrix( const Matrix& other) { set( (const float *) other._mat ); } Matrix::Matrix( const float * const def ) { set( def ); } Matrix::Matrix( float a00, float a01, float a02, float a03, float a10, float a11, float a12, float a13, float a20, float a21, float a22, float a23, float a30, float a31, float a32, float a33) { SET_ROW(0, a00, a01, a02, a03 ) SET_ROW(1, a10, a11, a12, a13 ) SET_ROW(2, a20, a21, a22, a23 ) SET_ROW(3, a30, a31, a32, a33 ) } void Matrix::set( float a00, float a01, float a02, float a03, float a10, float a11, float a12, float a13, float a20, float a21, float a22, float a23, float a30, float a31, float a32, float a33) { SET_ROW(0, a00, a01, a02, a03 ) SET_ROW(1, a10, a11, a12, a13 ) SET_ROW(2, a20, a21, a22, a23 ) SET_ROW(3, a30, a31, a32, a33 ) } void Matrix::setTrans( float tx, float ty, float tz ) { _mat[3][0] = tx; _mat[3][1] = ty; _mat[3][2] = tz; } void Matrix::setTrans( const Vec3& v ) { _mat[3][0] = v[0]; _mat[3][1] = v[1]; _mat[3][2] = v[2]; } void Matrix::makeIdentity() { SET_ROW(0, 1, 0, 0, 0 ) SET_ROW(1, 0, 1, 0, 0 ) SET_ROW(2, 0, 0, 1, 0 ) SET_ROW(3, 0, 0, 0, 1 ) } void Matrix::makeScale( const Vec3& v ) { makeScale(v[0], v[1], v[2] ); } void Matrix::makeScale( float x, float y, float z ) { SET_ROW(0, x, 0, 0, 0 ) SET_ROW(1, 0, y, 0, 0 ) SET_ROW(2, 0, 0, z, 0 ) SET_ROW(3, 0, 0, 0, 1 ) } void Matrix::makeTranslate( const Vec3& v ) { makeTranslate( v[0], v[1], v[2] ); } void Matrix::makeTranslate( float x, float y, float z ) { SET_ROW(0, 1, 0, 0, 0 ) SET_ROW(1, 0, 1, 0, 0 ) SET_ROW(2, 0, 0, 1, 0 ) SET_ROW(3, x, y, z, 1 ) } void Matrix::makeRotate( const Vec3& from, const Vec3& to ) { Quat quat; quat.makeRotate(from,to); quat.get(*this); } void Matrix::makeRotate( float angle, const Vec3& axis ) { Quat quat; quat.makeRotate( angle, axis); quat.get(*this); } void Matrix::makeRotate( float angle, float x, float y, float z ) { Quat quat; quat.makeRotate( angle, x, y, z); quat.get(*this); } void Matrix::makeRotate( const Quat& q ) { q.get(*this); } void Matrix::makeRotate( float angle1, const Vec3& axis1, float angle2, const Vec3& axis2, float angle3, const Vec3& axis3) { Quat quat; quat.makeRotate(angle1, axis1, angle2, axis2, angle3, axis3); quat.get(*this); } void Matrix::mult( const Matrix& lhs, const Matrix& rhs ) { if (&lhs==this) { postMult(rhs); return; } if (&rhs==this) { preMult(lhs); return; } // PRECONDITION: We assume neither &lhs nor &rhs == this // if it did, use preMult or postMult instead _mat[0][0] = INNER_PRODUCT(lhs, rhs, 0, 0); _mat[0][1] = INNER_PRODUCT(lhs, rhs, 0, 1); _mat[0][2] = INNER_PRODUCT(lhs, rhs, 0, 2); _mat[0][3] = INNER_PRODUCT(lhs, rhs, 0, 3); _mat[1][0] = INNER_PRODUCT(lhs, rhs, 1, 0); _mat[1][1] = INNER_PRODUCT(lhs, rhs, 1, 1); _mat[1][2] = INNER_PRODUCT(lhs, rhs, 1, 2); _mat[1][3] = INNER_PRODUCT(lhs, rhs, 1, 3); _mat[2][0] = INNER_PRODUCT(lhs, rhs, 2, 0); _mat[2][1] = INNER_PRODUCT(lhs, rhs, 2, 1); _mat[2][2] = INNER_PRODUCT(lhs, rhs, 2, 2); _mat[2][3] = INNER_PRODUCT(lhs, rhs, 2, 3); _mat[3][0] = INNER_PRODUCT(lhs, rhs, 3, 0); _mat[3][1] = INNER_PRODUCT(lhs, rhs, 3, 1); _mat[3][2] = INNER_PRODUCT(lhs, rhs, 3, 2); _mat[3][3] = INNER_PRODUCT(lhs, rhs, 3, 3); } void Matrix::preMult( const Matrix& other ) { // brute force method requiring a copy //Matrix tmp(other* *this); // *this = tmp; // more efficient method just use a float[4] for temporary storage. float t[4]; for(int col=0; col<4; ++col) { t[0] = INNER_PRODUCT( other, *this, 0, col ); t[1] = INNER_PRODUCT( other, *this, 1, col ); t[2] = INNER_PRODUCT( other, *this, 2, col ); t[3] = INNER_PRODUCT( other, *this, 3, col ); _mat[0][col] = t[0]; _mat[1][col] = t[1]; _mat[2][col] = t[2]; _mat[3][col] = t[3]; } } void Matrix::postMult( const Matrix& other ) { // brute force method requiring a copy //Matrix tmp(*this * other); // *this = tmp; // more efficient method just use a float[4] for temporary storage. float t[4]; for(int row=0; row<4; ++row) { t[0] = INNER_PRODUCT( *this, other, row, 0 ); t[1] = INNER_PRODUCT( *this, other, row, 1 ); t[2] = INNER_PRODUCT( *this, other, row, 2 ); t[3] = INNER_PRODUCT( *this, other, row, 3 ); SET_ROW(row, t[0], t[1], t[2], t[3] ) } } #undef INNER_PRODUCT template <class T> inline T SGL_ABS(T a) { return (a >= 0 ? a : -a); } #ifndef SGL_SWAP #define SGL_SWAP(a,b,temp) ((temp)=(a),(a)=(b),(b)=(temp)) #endif bool Matrix::invert( const Matrix& mat ) { if (&mat==this) { Matrix tm(mat); return invert(tm); } unsigned int indxc[4], indxr[4], ipiv[4]; unsigned int i,j,k,l,ll; unsigned int icol = 0; unsigned int irow = 0; double temp, pivinv, dum, big; // copy in place this may be unnecessary *this = mat; for (j=0; j<4; j++) ipiv[j]=0; for(i=0;i<4;i++) { big=(float)0.0; for (j=0; j<4; j++) if (ipiv[j] != 1) for (k=0; k<4; k++) { if (ipiv[k] == 0) { if (SGL_ABS(operator()(j,k)) >= big) { big = SGL_ABS(operator()(j,k)); irow=j; icol=k; } } else if (ipiv[k] > 1) return false; } ++(ipiv[icol]); if (irow != icol) for (l=0; l<4; l++) SGL_SWAP(operator()(irow,l), operator()(icol,l), temp); indxr[i]=irow; indxc[i]=icol; if (operator()(icol,icol) == 0) return false; pivinv = 1.0/operator()(icol,icol); operator()(icol,icol) = 1; for (l=0; l<4; l++) operator()(icol,l) *= pivinv; for (ll=0; ll<4; ll++) if (ll != icol) { dum=operator()(ll,icol); operator()(ll,icol) = 0; for (l=0; l<4; l++) operator()(ll,l) -= operator()(icol,l)*dum; } } for (int lx=4; lx>0; --lx) { if (indxr[lx-1] != indxc[lx-1]) for (k=0; k<4; k++) SGL_SWAP(operator()(k,indxr[lx-1]), operator()(k,indxc[lx-1]),temp); } return true; } void Matrix::makeOrtho(double left, double right, double bottom, double top, double zNear, double zFar) { // note transpose of Matrix wr.t OpenGL documentation, since the OSG use post multiplication rather than pre. double tx = -(right+left)/(right-left); double ty = -(top+bottom)/(top-bottom); double tz = -(zFar+zNear)/(zFar-zNear); SET_ROW(0, 2.0f/(right-left), 0.0f, 0.0f, 0.0f ) SET_ROW(1, 0.0f, 2.0f/(top-bottom), 0.0f, 0.0f ) SET_ROW(2, 0.0f, 0.0f, -2.0f/(zFar-zNear), 0.0f ) SET_ROW(3, tx, ty, tz, 1.0f ) } void Matrix::makeFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { // note transpose of Matrix wr.t OpenGL documentation, since the OSG use post multiplication rather than pre. double A = (right+left)/(right-left); double B = (top+bottom)/(top-bottom); double C = -(zFar+zNear)/(zFar-zNear); double D = -2.0*zFar*zNear/(zFar-zNear); SET_ROW(0, 2.0f*zNear/(right-left), 0.0f, 0.0f, 0.0f ) SET_ROW(1, 0.0f, 2.0f*zNear/(top-bottom), 0.0f, 0.0f ) SET_ROW(2, A, B, C, -1.0f ) SET_ROW(3, 0.0f, 0.0f, D, 0.0f ) } void Matrix::makePerspective(double fovy,double aspectRatio, double zNear, double zFar) { // calculate the appropriate left, right etc. double tan_fovy = tan(DegreesToRadians(fovy*0.5)); double right = tan_fovy * aspectRatio * zNear; double left = -right; double top = tan_fovy * zNear; double bottom = -top; makeFrustum(left,right,bottom,top,zNear,zFar); } void Matrix::makeLookAt(const Vec3& eye,const Vec3& center,const Vec3& up) { Vec3 f(center-eye); f.normalize(); Vec3 s(f^up); s.normalize(); Vec3 u(s^f); u.normalize(); set( s[0], u[0], -f[0], 0.0f, s[1], u[1], -f[1], 0.0f, s[2], u[2], -f[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); preMult(Matrix::translate(-eye)); } #undef SET_ROW <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImageMathematics.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImageMathematics.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include <math.h> vtkCxxRevisionMacro(vtkImageMathematics, "1.36"); vtkStandardNewMacro(vtkImageMathematics); //---------------------------------------------------------------------------- vtkImageMathematics::vtkImageMathematics() { this->Operation = VTK_ADD; this->ConstantK = 1.0; this->ConstantC = 0.0; this->DivideByZeroToC = 0; } //---------------------------------------------------------------------------- // The output extent is the intersection. void vtkImageMathematics::ExecuteInformation(vtkImageData **inDatas, vtkImageData *outData) { int ext[6], *ext2, idx; inDatas[0]->GetWholeExtent(ext); // two input take intersection if (this->Operation == VTK_ADD || this->Operation == VTK_SUBTRACT || this->Operation == VTK_MULTIPLY || this->Operation == VTK_DIVIDE || this->Operation == VTK_MIN || this->Operation == VTK_MAX || this->Operation == VTK_ATAN2) { ext2 = this->GetInput(1)->GetWholeExtent(); for (idx = 0; idx < 3; ++idx) { if (ext2[idx*2] > ext[idx*2]) { ext[idx*2] = ext2[idx*2]; } if (ext2[idx*2+1] < ext[idx*2+1]) { ext[idx*2+1] = ext2[idx*2+1]; } } } outData->SetWholeExtent(ext); } //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. // Handles the one input operations template <class T> static void vtkImageMathematicsExecute1(vtkImageMathematics *self, vtkImageData *in1Data, T *in1Ptr, vtkImageData *outData, T *outPtr, int outExt[6], int id) { int idxR, idxY, idxZ; int maxY, maxZ; int inIncX, inIncY, inIncZ; int outIncX, outIncY, outIncZ; int rowLength; unsigned long count = 0; unsigned long target; int op = self->GetOperation(); // find the region to loop over rowLength = (outExt[1] - outExt[0]+1)*in1Data->GetNumberOfScalarComponents(); // What a pain. Maybe I should just make another filter. if (op == VTK_CONJUGATE) { rowLength = (outExt[1] - outExt[0]+1); } maxY = outExt[3] - outExt[2]; maxZ = outExt[5] - outExt[4]; target = (unsigned long)((maxZ+1)*(maxY+1)/50.0); target++; // Get increments to march through data in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); double constantk = self->GetConstantK(); double constantc = self->GetConstantC(); // Loop through ouput pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { for (idxY = 0; idxY <= maxY; idxY++) { if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; } for (idxR = 0; idxR < rowLength; idxR++) { // Pixel operaton switch (op) { case VTK_INVERT: *outPtr = (T)(1.0 / *in1Ptr); break; case VTK_SIN: *outPtr = (T)(sin((double)*in1Ptr)); break; case VTK_COS: *outPtr = (T)(cos((double)*in1Ptr)); break; case VTK_EXP: *outPtr = (T)(exp((double)*in1Ptr)); break; case VTK_LOG: *outPtr = (T)(log((double)*in1Ptr)); break; case VTK_ABS: *outPtr = (T)(fabs((double)*in1Ptr)); break; case VTK_SQR: *outPtr = (T)(*in1Ptr * *in1Ptr); break; case VTK_SQRT: *outPtr = (T)(sqrt((double)*in1Ptr)); break; case VTK_ATAN: *outPtr = (T)(atan((double)*in1Ptr)); break; case VTK_MULTIPLYBYK: *outPtr = (T)(constantk*(double)*in1Ptr); break; case VTK_ADDC: *outPtr = (T)((T)constantc + *in1Ptr); break; case VTK_REPLACECBYK: *outPtr = (*in1Ptr == (T)constantc)?((T)constantk):(*in1Ptr); break; case VTK_CONJUGATE: outPtr[0] = in1Ptr[0]; outPtr[1] = (T)(-1.0*(double)(in1Ptr[1])); // Why bother trtying to figure out the continuous increments. outPtr++; in1Ptr++; break; } outPtr++; in1Ptr++; } outPtr += outIncY; in1Ptr += inIncY; } outPtr += outIncZ; in1Ptr += inIncZ; } } //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. // Handles the two input operations template <class T> static void vtkImageMathematicsExecute2(vtkImageMathematics *self, vtkImageData *in1Data, T *in1Ptr, vtkImageData *in2Data, T *in2Ptr, vtkImageData *outData, T *outPtr, int outExt[6], int id) { int idxR, idxY, idxZ; int maxY, maxZ; int inIncX, inIncY, inIncZ; int in2IncX, in2IncY, in2IncZ; int outIncX, outIncY, outIncZ; int rowLength; unsigned long count = 0; unsigned long target; int op = self->GetOperation(); int DivideByZeroToC = self->GetDivideByZeroToC(); double constantc = self->GetConstantC(); // find the region to loop over rowLength = (outExt[1] - outExt[0]+1)*in1Data->GetNumberOfScalarComponents(); // What a pain. Maybe I should just make another filter. if (op == VTK_COMPLEX_MULTIPLY) { rowLength = (outExt[1] - outExt[0]+1); } maxY = outExt[3] - outExt[2]; maxZ = outExt[5] - outExt[4]; target = (unsigned long)((maxZ+1)*(maxY+1)/50.0); target++; // Get increments to march through data in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); in2Data->GetContinuousIncrements(outExt, in2IncX, in2IncY, in2IncZ); outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); // Loop through ouput pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++) { if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; } for (idxR = 0; idxR < rowLength; idxR++) { // Pixel operation switch (op) { case VTK_ADD: *outPtr = *in1Ptr + *in2Ptr; break; case VTK_SUBTRACT: *outPtr = *in1Ptr - *in2Ptr; break; case VTK_MULTIPLY: *outPtr = *in1Ptr * *in2Ptr; break; case VTK_DIVIDE: if (*in2Ptr) { *outPtr = *in1Ptr / *in2Ptr; } else { if ( DivideByZeroToC ) { *outPtr = (T) constantc; } else { *outPtr = (T)(*in1Ptr / 0.00001); } } break; case VTK_MIN: if (*in1Ptr < *in2Ptr) { *outPtr = *in1Ptr; } else { *outPtr = *in2Ptr; } break; case VTK_MAX: if (*in1Ptr > *in2Ptr) { *outPtr = *in1Ptr; } else { *outPtr = *in2Ptr; } break; case VTK_ATAN2: if (*in1Ptr == 0.0 && *in2Ptr == 0.0) { *outPtr = 0; } else { *outPtr = (T)atan2((double)*in1Ptr,(double)*in2Ptr); } break; case VTK_COMPLEX_MULTIPLY: outPtr[0] = in1Ptr[0] * in2Ptr[0] - in1Ptr[1] * in2Ptr[1]; outPtr[1] = in1Ptr[1] * in2Ptr[0] + in1Ptr[0] * in2Ptr[1]; // Why bother trtying to figure out the continuous increments. outPtr++; in1Ptr++; in2Ptr++; break; } outPtr++; in1Ptr++; in2Ptr++; } outPtr += outIncY; in1Ptr += inIncY; in2Ptr += in2IncY; } outPtr += outIncZ; in1Ptr += inIncZ; in2Ptr += in2IncZ; } } //---------------------------------------------------------------------------- // This method is passed a input and output datas, and executes the filter // algorithm to fill the output from the inputs. // It just executes a switch statement to call the correct function for // the datas data types. void vtkImageMathematics::ThreadedExecute(vtkImageData **inData, vtkImageData *outData, int outExt[6], int id) { void *inPtr1; void *outPtr; vtkDebugMacro(<< "Execute: inData = " << inData << ", outData = " << outData); if (inData[0] == NULL) { vtkErrorMacro(<< "Input " << 0 << " must be specified."); return; } inPtr1 = inData[0]->GetScalarPointerForExtent(outExt); outPtr = outData->GetScalarPointerForExtent(outExt); if (this->Operation == VTK_ADD || this->Operation == VTK_SUBTRACT || this->Operation == VTK_MULTIPLY || this->Operation == VTK_DIVIDE || this->Operation == VTK_MIN || this->Operation == VTK_MAX || this->Operation == VTK_ATAN2 || this->Operation == VTK_COMPLEX_MULTIPLY) { void *inPtr2; if (inData[1] == NULL) { vtkErrorMacro(<< "Input " << 1 << " must be specified."); return; } if ( this->Operation == VTK_COMPLEX_MULTIPLY ) { if (inData[0]->GetNumberOfScalarComponents() != 2 || inData[1]->GetNumberOfScalarComponents() != 2) { vtkErrorMacro("Complex inputs must have two components."); return; } } inPtr2 = inData[1]->GetScalarPointerForExtent(outExt); // this filter expects that input is the same type as output. if (inData[0]->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input1 ScalarType, " << inData[0]->GetScalarType() << ", must match output ScalarType " << outData->GetScalarType()); return; } if (inData[1]->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input2 ScalarType, " << inData[1]->GetScalarType() << ", must match output ScalarType " << outData->GetScalarType()); return; } // this filter expects that inputs that have the same number of components if (inData[0]->GetNumberOfScalarComponents() != inData[1]->GetNumberOfScalarComponents()) { vtkErrorMacro(<< "Execute: input1 NumberOfScalarComponents, " << inData[0]->GetNumberOfScalarComponents() << ", must match out input2 NumberOfScalarComponents " << inData[1]->GetNumberOfScalarComponents()); return; } switch (inData[0]->GetScalarType()) { vtkTemplateMacro9(vtkImageMathematicsExecute2, this,inData[0], (VTK_TT *)(inPtr1), inData[1], (VTK_TT *)(inPtr2), outData, (VTK_TT *)(outPtr), outExt, id); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } else { // this filter expects that input is the same type as output. if (inData[0]->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input ScalarType, " << inData[0]->GetScalarType() << ", must match out ScalarType " << outData->GetScalarType()); return; } if ( this->Operation == VTK_CONJUGATE ) { if (inData[0]->GetNumberOfScalarComponents() != 2) { vtkErrorMacro("Complex inputs must have two components."); return; } } switch (inData[0]->GetScalarType()) { vtkTemplateMacro7(vtkImageMathematicsExecute1, this, inData[0], (VTK_TT *)(inPtr1), outData, (VTK_TT *)(outPtr), outExt, id); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } } void vtkImageMathematics::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Operation: " << this->Operation << "\n"; os << indent << "ConstantK: " << this->ConstantK << "\n"; os << indent << "ConstantC: " << this->ConstantC << "\n"; } <commit_msg>FIX: Print self defect<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImageMathematics.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImageMathematics.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include <math.h> vtkCxxRevisionMacro(vtkImageMathematics, "1.37"); vtkStandardNewMacro(vtkImageMathematics); //---------------------------------------------------------------------------- vtkImageMathematics::vtkImageMathematics() { this->Operation = VTK_ADD; this->ConstantK = 1.0; this->ConstantC = 0.0; this->DivideByZeroToC = 0; } //---------------------------------------------------------------------------- // The output extent is the intersection. void vtkImageMathematics::ExecuteInformation(vtkImageData **inDatas, vtkImageData *outData) { int ext[6], *ext2, idx; inDatas[0]->GetWholeExtent(ext); // two input take intersection if (this->Operation == VTK_ADD || this->Operation == VTK_SUBTRACT || this->Operation == VTK_MULTIPLY || this->Operation == VTK_DIVIDE || this->Operation == VTK_MIN || this->Operation == VTK_MAX || this->Operation == VTK_ATAN2) { ext2 = this->GetInput(1)->GetWholeExtent(); for (idx = 0; idx < 3; ++idx) { if (ext2[idx*2] > ext[idx*2]) { ext[idx*2] = ext2[idx*2]; } if (ext2[idx*2+1] < ext[idx*2+1]) { ext[idx*2+1] = ext2[idx*2+1]; } } } outData->SetWholeExtent(ext); } //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. // Handles the one input operations template <class T> static void vtkImageMathematicsExecute1(vtkImageMathematics *self, vtkImageData *in1Data, T *in1Ptr, vtkImageData *outData, T *outPtr, int outExt[6], int id) { int idxR, idxY, idxZ; int maxY, maxZ; int inIncX, inIncY, inIncZ; int outIncX, outIncY, outIncZ; int rowLength; unsigned long count = 0; unsigned long target; int op = self->GetOperation(); // find the region to loop over rowLength = (outExt[1] - outExt[0]+1)*in1Data->GetNumberOfScalarComponents(); // What a pain. Maybe I should just make another filter. if (op == VTK_CONJUGATE) { rowLength = (outExt[1] - outExt[0]+1); } maxY = outExt[3] - outExt[2]; maxZ = outExt[5] - outExt[4]; target = (unsigned long)((maxZ+1)*(maxY+1)/50.0); target++; // Get increments to march through data in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); double constantk = self->GetConstantK(); double constantc = self->GetConstantC(); // Loop through ouput pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { for (idxY = 0; idxY <= maxY; idxY++) { if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; } for (idxR = 0; idxR < rowLength; idxR++) { // Pixel operaton switch (op) { case VTK_INVERT: *outPtr = (T)(1.0 / *in1Ptr); break; case VTK_SIN: *outPtr = (T)(sin((double)*in1Ptr)); break; case VTK_COS: *outPtr = (T)(cos((double)*in1Ptr)); break; case VTK_EXP: *outPtr = (T)(exp((double)*in1Ptr)); break; case VTK_LOG: *outPtr = (T)(log((double)*in1Ptr)); break; case VTK_ABS: *outPtr = (T)(fabs((double)*in1Ptr)); break; case VTK_SQR: *outPtr = (T)(*in1Ptr * *in1Ptr); break; case VTK_SQRT: *outPtr = (T)(sqrt((double)*in1Ptr)); break; case VTK_ATAN: *outPtr = (T)(atan((double)*in1Ptr)); break; case VTK_MULTIPLYBYK: *outPtr = (T)(constantk*(double)*in1Ptr); break; case VTK_ADDC: *outPtr = (T)((T)constantc + *in1Ptr); break; case VTK_REPLACECBYK: *outPtr = (*in1Ptr == (T)constantc)?((T)constantk):(*in1Ptr); break; case VTK_CONJUGATE: outPtr[0] = in1Ptr[0]; outPtr[1] = (T)(-1.0*(double)(in1Ptr[1])); // Why bother trtying to figure out the continuous increments. outPtr++; in1Ptr++; break; } outPtr++; in1Ptr++; } outPtr += outIncY; in1Ptr += inIncY; } outPtr += outIncZ; in1Ptr += inIncZ; } } //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. // Handles the two input operations template <class T> static void vtkImageMathematicsExecute2(vtkImageMathematics *self, vtkImageData *in1Data, T *in1Ptr, vtkImageData *in2Data, T *in2Ptr, vtkImageData *outData, T *outPtr, int outExt[6], int id) { int idxR, idxY, idxZ; int maxY, maxZ; int inIncX, inIncY, inIncZ; int in2IncX, in2IncY, in2IncZ; int outIncX, outIncY, outIncZ; int rowLength; unsigned long count = 0; unsigned long target; int op = self->GetOperation(); int DivideByZeroToC = self->GetDivideByZeroToC(); double constantc = self->GetConstantC(); // find the region to loop over rowLength = (outExt[1] - outExt[0]+1)*in1Data->GetNumberOfScalarComponents(); // What a pain. Maybe I should just make another filter. if (op == VTK_COMPLEX_MULTIPLY) { rowLength = (outExt[1] - outExt[0]+1); } maxY = outExt[3] - outExt[2]; maxZ = outExt[5] - outExt[4]; target = (unsigned long)((maxZ+1)*(maxY+1)/50.0); target++; // Get increments to march through data in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); in2Data->GetContinuousIncrements(outExt, in2IncX, in2IncY, in2IncZ); outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); // Loop through ouput pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++) { if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; } for (idxR = 0; idxR < rowLength; idxR++) { // Pixel operation switch (op) { case VTK_ADD: *outPtr = *in1Ptr + *in2Ptr; break; case VTK_SUBTRACT: *outPtr = *in1Ptr - *in2Ptr; break; case VTK_MULTIPLY: *outPtr = *in1Ptr * *in2Ptr; break; case VTK_DIVIDE: if (*in2Ptr) { *outPtr = *in1Ptr / *in2Ptr; } else { if ( DivideByZeroToC ) { *outPtr = (T) constantc; } else { *outPtr = (T)(*in1Ptr / 0.00001); } } break; case VTK_MIN: if (*in1Ptr < *in2Ptr) { *outPtr = *in1Ptr; } else { *outPtr = *in2Ptr; } break; case VTK_MAX: if (*in1Ptr > *in2Ptr) { *outPtr = *in1Ptr; } else { *outPtr = *in2Ptr; } break; case VTK_ATAN2: if (*in1Ptr == 0.0 && *in2Ptr == 0.0) { *outPtr = 0; } else { *outPtr = (T)atan2((double)*in1Ptr,(double)*in2Ptr); } break; case VTK_COMPLEX_MULTIPLY: outPtr[0] = in1Ptr[0] * in2Ptr[0] - in1Ptr[1] * in2Ptr[1]; outPtr[1] = in1Ptr[1] * in2Ptr[0] + in1Ptr[0] * in2Ptr[1]; // Why bother trtying to figure out the continuous increments. outPtr++; in1Ptr++; in2Ptr++; break; } outPtr++; in1Ptr++; in2Ptr++; } outPtr += outIncY; in1Ptr += inIncY; in2Ptr += in2IncY; } outPtr += outIncZ; in1Ptr += inIncZ; in2Ptr += in2IncZ; } } //---------------------------------------------------------------------------- // This method is passed a input and output datas, and executes the filter // algorithm to fill the output from the inputs. // It just executes a switch statement to call the correct function for // the datas data types. void vtkImageMathematics::ThreadedExecute(vtkImageData **inData, vtkImageData *outData, int outExt[6], int id) { void *inPtr1; void *outPtr; vtkDebugMacro(<< "Execute: inData = " << inData << ", outData = " << outData); if (inData[0] == NULL) { vtkErrorMacro(<< "Input " << 0 << " must be specified."); return; } inPtr1 = inData[0]->GetScalarPointerForExtent(outExt); outPtr = outData->GetScalarPointerForExtent(outExt); if (this->Operation == VTK_ADD || this->Operation == VTK_SUBTRACT || this->Operation == VTK_MULTIPLY || this->Operation == VTK_DIVIDE || this->Operation == VTK_MIN || this->Operation == VTK_MAX || this->Operation == VTK_ATAN2 || this->Operation == VTK_COMPLEX_MULTIPLY) { void *inPtr2; if (inData[1] == NULL) { vtkErrorMacro(<< "Input " << 1 << " must be specified."); return; } if ( this->Operation == VTK_COMPLEX_MULTIPLY ) { if (inData[0]->GetNumberOfScalarComponents() != 2 || inData[1]->GetNumberOfScalarComponents() != 2) { vtkErrorMacro("Complex inputs must have two components."); return; } } inPtr2 = inData[1]->GetScalarPointerForExtent(outExt); // this filter expects that input is the same type as output. if (inData[0]->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input1 ScalarType, " << inData[0]->GetScalarType() << ", must match output ScalarType " << outData->GetScalarType()); return; } if (inData[1]->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input2 ScalarType, " << inData[1]->GetScalarType() << ", must match output ScalarType " << outData->GetScalarType()); return; } // this filter expects that inputs that have the same number of components if (inData[0]->GetNumberOfScalarComponents() != inData[1]->GetNumberOfScalarComponents()) { vtkErrorMacro(<< "Execute: input1 NumberOfScalarComponents, " << inData[0]->GetNumberOfScalarComponents() << ", must match out input2 NumberOfScalarComponents " << inData[1]->GetNumberOfScalarComponents()); return; } switch (inData[0]->GetScalarType()) { vtkTemplateMacro9(vtkImageMathematicsExecute2, this,inData[0], (VTK_TT *)(inPtr1), inData[1], (VTK_TT *)(inPtr2), outData, (VTK_TT *)(outPtr), outExt, id); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } else { // this filter expects that input is the same type as output. if (inData[0]->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input ScalarType, " << inData[0]->GetScalarType() << ", must match out ScalarType " << outData->GetScalarType()); return; } if ( this->Operation == VTK_CONJUGATE ) { if (inData[0]->GetNumberOfScalarComponents() != 2) { vtkErrorMacro("Complex inputs must have two components."); return; } } switch (inData[0]->GetScalarType()) { vtkTemplateMacro7(vtkImageMathematicsExecute1, this, inData[0], (VTK_TT *)(inPtr1), outData, (VTK_TT *)(outPtr), outExt, id); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } } void vtkImageMathematics::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Operation: " << this->Operation << "\n"; os << indent << "ConstantK: " << this->ConstantK << "\n"; os << indent << "ConstantC: " << this->ConstantC << "\n"; os << indent << "DivideByZeroToC: "; if ( this->DivideByZeroToC ) { os << "On\n"; } else { os << "Off\n"; } } <|endoftext|>
<commit_before>/* Copyright (c) 2015-2019 Max Krasnyansky <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <stdint.h> #include <pthread.h> #include <stdlib.h> #include <limits.h> #include <string.h> #include <sys/types.h> #include <sys/uio.h> #include <string> #include <sstream> #include <iomanip> #include "hogl/detail/ostrbuf-fd.hpp" #include "hogl/platform.hpp" #include "hogl/output-file.hpp" __HOGL_PRIV_NS_OPEN__ namespace hogl { class ostrbuf_file : public ostrbuf { private: output_file &_of; void do_flush(const uint8_t *data, size_t len) { struct iovec iov[2]; unsigned int i = 0; // Flush buffered data if (_size) { iov[i].iov_base = (void *) _data; iov[i].iov_len = _size; i++; } // Flush un-buffered data if (len) { iov[i].iov_base = (void *) data; iov[i].iov_len = len; i++; } if (i) { int r = _of.writev(iov, i); if (r < 0) ostrbuf::failure(strerror(errno)); } this->reset(); } public: ostrbuf_file(output_file &of, unsigned int buffer_capacity) : ostrbuf(buffer_capacity), _of(of) { } }; output_file::options output_file::default_options = { .perms = 0666, .max_size = 1 * 1024 * 1024 * 1024, /// 1GB .max_count = 128, .buffer_capacity = 8192 }; std::string output_file::name() const { // Actuall file name of the current file is unstable // because rotation thread can change it at any time. // We'd need to lock rotation mutex make a copy, etc. // For now just return the symlink name which should // be good enough for most apps. return _symlink; } unsigned int output_file::index() const { return _name_index; } // Generate file name using prefix, index and suffix. void output_file::update_name() { std::ostringstream ss; ss << _name_pref << std::setfill('0') << std::setw(_index_width) << _name_index << std::setw(0) << _name_sufx; _name = ss.str(); } // Update symlink. // Creates a temp symlink that points to the new file and renames it // on top of the old symlink. void output_file::update_link() { std::string link = _symlink + "$"; remove(link.c_str()); int err = symlink(_name.c_str(), link.c_str()); if (err < 0) fprintf(stderr, "hogl::output_file: failed to create symlink %s -> %s. %s(%d)\n", _name.c_str(), _symlink.c_str(), strerror(errno), errno); rename(link.c_str(), _symlink.c_str()); } // Read the symlink and return the index it is pointing to. // This is used to initialize the index when the file is reopened. // If the symlink does not exist or is invalid the index starts from zero. unsigned int output_file::read_link() { unsigned int len = _symlink.size() + _index_width + 1; char cstr[len]; ssize_t rlen = readlink(_symlink.c_str(), cstr, len); if (rlen < 0) { if (errno == ENOENT) return 0; fprintf(stderr, "hogl::output_file: failed to read symlink %s. %s(%d)\n", _symlink.c_str(), strerror(errno), errno); return 0; } std::string str(cstr, rlen); size_t pos; // Validate and strip prefix pos = str.find(_name_pref); if (pos != 0) { // Prefix does not match. // Looks like the link is pointing to something else. // Ignore, we'll fix it during update. return 0; } str = str.substr(_name_pref.size()); // Validate and strip suffix if (_name_sufx.size()) { pos = str.find(_name_sufx); if (_name_sufx.size() && pos == str.npos) { // Suffix does not match. // Ignore, we'll fix it during update. return 0; } str = str.substr(0, pos); } // Convert to integer unsigned long index = strtoul(str.c_str(), NULL, 10); if (index == ULONG_MAX) { // Hmm, conversion failed. Ignore for now. return 0; } if (index >= _max_count) { // Index is outside valid range. User must've reused the // name with different settings. Ignore and restart numbering. return 0; } if (++index >= _max_count) index = 0; return index; } // Initialize file name. // Parses the name, figures out the location of the seqno, etc. void output_file::init_name(const char *filename) { const std::string str(filename); // Reset everything first because we might be moving to the new // output location with totally different naming. _name_sufx.clear(); _name_pref.clear(); // Split file name into prefix and suffix size_t split = str.find('#'); if (split != str.npos) { _name_sufx = str.substr(split + 1); _name_pref = str.substr(0, split); // Remove duplicate (if any) character from symlink if (split > 0 && str[split - 1] == str[split + 1]) --split; _symlink = str.substr(0, split) + _name_sufx; } else { // No suffix _name_pref = str + "."; _symlink = str; } // Figure out index width for zero-padding unsigned int step = 10; _index_width = 1; while (step < _max_count) { step *= 10; _index_width++; } _name_index = read_link(); update_name(); } // Format of the filename // /location/preffix.#.suffix // # will be replaced by the file index // Currently active file will have the following name // /location/prefix.suffix output_file::output_file(const char *filename, format &fmt, const options &opts) : output(fmt), _max_size(opts.max_size), _max_count(opts.max_count), _mode(opts.perms), _fd(-1), _size(0), _running(false), _killed(false), _rotate_pending(false), _rotate_schedparam(opts.schedparam) { pthread_mutex_init(&_write_mutex, NULL); pthread_mutex_init(&_rotate_mutex, NULL); pthread_cond_init(&_rotate_cond, NULL); // Start helper thread int err = pthread_create(&_rotate_thread, NULL, thread_entry, (void *) this); if (err) { fprintf(stderr, "hogl::output_file: failed to start helper thread. %d\n", err); abort(); } init_name(filename); _fd = open(_name.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, _mode); if (_fd < 0) { fprintf(stderr, "hogl::output_file: failed open file %s. %s (%d)\n", _name.c_str(), strerror(errno), errno); abort(); } output::init(new ostrbuf_file(*this, opts.buffer_capacity)); // Write format header output::header(_name.c_str()); update_link(); } output_file::~output_file() { _killed = true; // Wakeup rotation thread and wait for it to exit pthread_mutex_lock(&_rotate_mutex); pthread_cond_signal(&_rotate_cond); pthread_mutex_unlock(&_rotate_mutex); pthread_join(_rotate_thread, NULL); // Write format footer and flush the buffer output::footer(); // Delete and zero out ostrbuf explicitly. // Just to make sure that parent doesn't touch this instance. delete _ostrbuf; _ostrbuf = 0; // Close current descriptor close(_fd); // Delete everything else pthread_mutex_destroy(&_write_mutex); pthread_mutex_destroy(&_rotate_mutex); pthread_cond_destroy(&_rotate_cond); } ssize_t output_file::writev(const struct iovec *iov, int iovcnt) { ssize_t n; pthread_mutex_lock(&_write_mutex); n = ::writev(_fd, iov, iovcnt); if (n > 0) { _size += n; if (_size >= _max_size && !_rotate_pending) { // Try to wakeup rotation thread. // If we can't lock the mutex that means the rotation thread // is still busy rotating things. So we'll just retry next // time arround. if (pthread_mutex_trylock(&_rotate_mutex) == 0) { _rotate_pending = true; pthread_cond_signal(&_rotate_cond); pthread_mutex_unlock(&_rotate_mutex); } } } pthread_mutex_unlock(&_write_mutex); return n; } ssize_t output_file::write(const void *data, size_t size) { struct iovec iv; iv.iov_base = (void *) data; iv.iov_len = size; return this->writev(&iv, 1); } void output_file::do_rotate() { int ofd = _fd; _name_index++; if (_name_index >= _max_count) _name_index = 0; update_name(); // Open a new chunk int nfd = open(_name.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, _mode); if (nfd < 0) { // Retry later. Let the writer thread wake us up again. return; } // Generate header and write it out directly. We can't use our own write() // path here in the rotation thread, and we need to allocate a temporary // buffer for the same reason. ostrbuf_fd nsb(nfd, 0, 128); _format.header(nsb, _name.c_str(), false /* not first */); nsb.flush(); if (nsb.failed()) { // Failed to write. Retry later. close(nfd); return; } // Swap the fd pthread_mutex_lock(&_write_mutex); _fd = nfd; _size = 0; pthread_mutex_unlock(&_write_mutex); //printf("rotate: switched fds - new %u old %u\n", nfd, ofd); update_link(); // Generate footer, write it out and close the old chunk. // Note that we don't check for write errors here because we // can't do much about them. ostrbuf_fd osb(ofd, 0, 128); _format.footer(osb, _name.c_str()); osb.flush(); close(ofd); } void *output_file::thread_entry(void *_self) { output_file *self = (output_file *) _self; std::ostringstream ss; ss << "hogl::output_file helper (" << self->_symlink << ")"; platform::set_thread_title(ss.str().c_str()); // Apply scheduler params if (self->_rotate_schedparam) self->_rotate_schedparam->thread_enter(ss.str().c_str()); // Run the loop self->thread_loop(); // Apply scheduler params if (self->_rotate_schedparam) self->_rotate_schedparam->thread_exit(); return 0; } void output_file::thread_loop() { _running = true; pthread_mutex_lock(&_rotate_mutex); while (1) { pthread_cond_wait(&_rotate_cond, &_rotate_mutex); if (_killed) break; if (_rotate_pending) { do_rotate(); _rotate_pending = false; } } pthread_mutex_unlock(&_rotate_mutex); _running = false; } bool output_file::switch_name(const char *filename) { // FIXME: need to add at last some basic validation // We have to make sure the rotation thread is not racing with us // which means we need to hold rotation_mutex. pthread_mutex_lock(&_rotate_mutex); // Reinit filename bits (sufx, etc) init_name(filename); // Trigger rotation _rotate_pending = true; pthread_cond_signal(&_rotate_cond); pthread_mutex_unlock(&_rotate_mutex); return true; } } // namespace hogl __HOGL_PRIV_NS_CLOSE__ <commit_msg>Init .schedparam in output_file::default_options<commit_after>/* Copyright (c) 2015-2019 Max Krasnyansky <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <stdint.h> #include <pthread.h> #include <stdlib.h> #include <limits.h> #include <string.h> #include <sys/types.h> #include <sys/uio.h> #include <string> #include <sstream> #include <iomanip> #include "hogl/detail/ostrbuf-fd.hpp" #include "hogl/platform.hpp" #include "hogl/output-file.hpp" __HOGL_PRIV_NS_OPEN__ namespace hogl { class ostrbuf_file : public ostrbuf { private: output_file &_of; void do_flush(const uint8_t *data, size_t len) { struct iovec iov[2]; unsigned int i = 0; // Flush buffered data if (_size) { iov[i].iov_base = (void *) _data; iov[i].iov_len = _size; i++; } // Flush un-buffered data if (len) { iov[i].iov_base = (void *) data; iov[i].iov_len = len; i++; } if (i) { int r = _of.writev(iov, i); if (r < 0) ostrbuf::failure(strerror(errno)); } this->reset(); } public: ostrbuf_file(output_file &of, unsigned int buffer_capacity) : ostrbuf(buffer_capacity), _of(of) { } }; output_file::options output_file::default_options = { .perms = 0666, .max_size = 1 * 1024 * 1024 * 1024, /// 1GB .max_count = 128, .buffer_capacity = 8192, .schedparam = 0 }; std::string output_file::name() const { // Actuall file name of the current file is unstable // because rotation thread can change it at any time. // We'd need to lock rotation mutex make a copy, etc. // For now just return the symlink name which should // be good enough for most apps. return _symlink; } unsigned int output_file::index() const { return _name_index; } // Generate file name using prefix, index and suffix. void output_file::update_name() { std::ostringstream ss; ss << _name_pref << std::setfill('0') << std::setw(_index_width) << _name_index << std::setw(0) << _name_sufx; _name = ss.str(); } // Update symlink. // Creates a temp symlink that points to the new file and renames it // on top of the old symlink. void output_file::update_link() { std::string link = _symlink + "$"; remove(link.c_str()); int err = symlink(_name.c_str(), link.c_str()); if (err < 0) fprintf(stderr, "hogl::output_file: failed to create symlink %s -> %s. %s(%d)\n", _name.c_str(), _symlink.c_str(), strerror(errno), errno); rename(link.c_str(), _symlink.c_str()); } // Read the symlink and return the index it is pointing to. // This is used to initialize the index when the file is reopened. // If the symlink does not exist or is invalid the index starts from zero. unsigned int output_file::read_link() { unsigned int len = _symlink.size() + _index_width + 1; char cstr[len]; ssize_t rlen = readlink(_symlink.c_str(), cstr, len); if (rlen < 0) { if (errno == ENOENT) return 0; fprintf(stderr, "hogl::output_file: failed to read symlink %s. %s(%d)\n", _symlink.c_str(), strerror(errno), errno); return 0; } std::string str(cstr, rlen); size_t pos; // Validate and strip prefix pos = str.find(_name_pref); if (pos != 0) { // Prefix does not match. // Looks like the link is pointing to something else. // Ignore, we'll fix it during update. return 0; } str = str.substr(_name_pref.size()); // Validate and strip suffix if (_name_sufx.size()) { pos = str.find(_name_sufx); if (_name_sufx.size() && pos == str.npos) { // Suffix does not match. // Ignore, we'll fix it during update. return 0; } str = str.substr(0, pos); } // Convert to integer unsigned long index = strtoul(str.c_str(), NULL, 10); if (index == ULONG_MAX) { // Hmm, conversion failed. Ignore for now. return 0; } if (index >= _max_count) { // Index is outside valid range. User must've reused the // name with different settings. Ignore and restart numbering. return 0; } if (++index >= _max_count) index = 0; return index; } // Initialize file name. // Parses the name, figures out the location of the seqno, etc. void output_file::init_name(const char *filename) { const std::string str(filename); // Reset everything first because we might be moving to the new // output location with totally different naming. _name_sufx.clear(); _name_pref.clear(); // Split file name into prefix and suffix size_t split = str.find('#'); if (split != str.npos) { _name_sufx = str.substr(split + 1); _name_pref = str.substr(0, split); // Remove duplicate (if any) character from symlink if (split > 0 && str[split - 1] == str[split + 1]) --split; _symlink = str.substr(0, split) + _name_sufx; } else { // No suffix _name_pref = str + "."; _symlink = str; } // Figure out index width for zero-padding unsigned int step = 10; _index_width = 1; while (step < _max_count) { step *= 10; _index_width++; } _name_index = read_link(); update_name(); } // Format of the filename // /location/preffix.#.suffix // # will be replaced by the file index // Currently active file will have the following name // /location/prefix.suffix output_file::output_file(const char *filename, format &fmt, const options &opts) : output(fmt), _max_size(opts.max_size), _max_count(opts.max_count), _mode(opts.perms), _fd(-1), _size(0), _running(false), _killed(false), _rotate_pending(false), _rotate_schedparam(opts.schedparam) { pthread_mutex_init(&_write_mutex, NULL); pthread_mutex_init(&_rotate_mutex, NULL); pthread_cond_init(&_rotate_cond, NULL); // Start helper thread int err = pthread_create(&_rotate_thread, NULL, thread_entry, (void *) this); if (err) { fprintf(stderr, "hogl::output_file: failed to start helper thread. %d\n", err); abort(); } init_name(filename); _fd = open(_name.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, _mode); if (_fd < 0) { fprintf(stderr, "hogl::output_file: failed open file %s. %s (%d)\n", _name.c_str(), strerror(errno), errno); abort(); } output::init(new ostrbuf_file(*this, opts.buffer_capacity)); // Write format header output::header(_name.c_str()); update_link(); } output_file::~output_file() { _killed = true; // Wakeup rotation thread and wait for it to exit pthread_mutex_lock(&_rotate_mutex); pthread_cond_signal(&_rotate_cond); pthread_mutex_unlock(&_rotate_mutex); pthread_join(_rotate_thread, NULL); // Write format footer and flush the buffer output::footer(); // Delete and zero out ostrbuf explicitly. // Just to make sure that parent doesn't touch this instance. delete _ostrbuf; _ostrbuf = 0; // Close current descriptor close(_fd); // Delete everything else pthread_mutex_destroy(&_write_mutex); pthread_mutex_destroy(&_rotate_mutex); pthread_cond_destroy(&_rotate_cond); } ssize_t output_file::writev(const struct iovec *iov, int iovcnt) { ssize_t n; pthread_mutex_lock(&_write_mutex); n = ::writev(_fd, iov, iovcnt); if (n > 0) { _size += n; if (_size >= _max_size && !_rotate_pending) { // Try to wakeup rotation thread. // If we can't lock the mutex that means the rotation thread // is still busy rotating things. So we'll just retry next // time arround. if (pthread_mutex_trylock(&_rotate_mutex) == 0) { _rotate_pending = true; pthread_cond_signal(&_rotate_cond); pthread_mutex_unlock(&_rotate_mutex); } } } pthread_mutex_unlock(&_write_mutex); return n; } ssize_t output_file::write(const void *data, size_t size) { struct iovec iv; iv.iov_base = (void *) data; iv.iov_len = size; return this->writev(&iv, 1); } void output_file::do_rotate() { int ofd = _fd; _name_index++; if (_name_index >= _max_count) _name_index = 0; update_name(); // Open a new chunk int nfd = open(_name.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, _mode); if (nfd < 0) { // Retry later. Let the writer thread wake us up again. return; } // Generate header and write it out directly. We can't use our own write() // path here in the rotation thread, and we need to allocate a temporary // buffer for the same reason. ostrbuf_fd nsb(nfd, 0, 128); _format.header(nsb, _name.c_str(), false /* not first */); nsb.flush(); if (nsb.failed()) { // Failed to write. Retry later. close(nfd); return; } // Swap the fd pthread_mutex_lock(&_write_mutex); _fd = nfd; _size = 0; pthread_mutex_unlock(&_write_mutex); //printf("rotate: switched fds - new %u old %u\n", nfd, ofd); update_link(); // Generate footer, write it out and close the old chunk. // Note that we don't check for write errors here because we // can't do much about them. ostrbuf_fd osb(ofd, 0, 128); _format.footer(osb, _name.c_str()); osb.flush(); close(ofd); } void *output_file::thread_entry(void *_self) { output_file *self = (output_file *) _self; std::ostringstream ss; ss << "hogl::output_file helper (" << self->_symlink << ")"; platform::set_thread_title(ss.str().c_str()); // Apply scheduler params if (self->_rotate_schedparam) self->_rotate_schedparam->thread_enter(ss.str().c_str()); // Run the loop self->thread_loop(); // Apply scheduler params if (self->_rotate_schedparam) self->_rotate_schedparam->thread_exit(); return 0; } void output_file::thread_loop() { _running = true; pthread_mutex_lock(&_rotate_mutex); while (1) { pthread_cond_wait(&_rotate_cond, &_rotate_mutex); if (_killed) break; if (_rotate_pending) { do_rotate(); _rotate_pending = false; } } pthread_mutex_unlock(&_rotate_mutex); _running = false; } bool output_file::switch_name(const char *filename) { // FIXME: need to add at last some basic validation // We have to make sure the rotation thread is not racing with us // which means we need to hold rotation_mutex. pthread_mutex_lock(&_rotate_mutex); // Reinit filename bits (sufx, etc) init_name(filename); // Trigger rotation _rotate_pending = true; pthread_cond_signal(&_rotate_cond); pthread_mutex_unlock(&_rotate_mutex); return true; } } // namespace hogl __HOGL_PRIV_NS_CLOSE__ <|endoftext|>
<commit_before>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_GAME_HPP #define ROSETTASTONE_GAME_HPP #include <Rosetta/Enums/CardEnums.hpp> #include <Rosetta/Games/GameConfig.hpp> #include <Rosetta/Games/TriggerManager.hpp> #include <Rosetta/Models/Player.hpp> #include <Rosetta/Tasks/TaskQueue.hpp> #include <Rosetta/Tasks/TaskStack.hpp> #include <map> namespace RosettaStone { //! //! \brief Game class. //! //! This class stores Hearthstone game states which consists of information of //! both players. //! class Game { public: //! Deleted default constructor. Game() = delete; //! Constructs account with given \p gameConfig. //! \param gameConfig The game config holds all configuration values. explicit Game(GameConfig& gameConfig); //! Default destructor. ~Game() = default; //! Deleted copy constructor. Game(const Game&) = delete; //! Deleted move constructor. Game(Game&&) = delete; //! Deleted copy assignment operator. Game& operator=(const Game&) = delete; //! Deleted move assignment operator. Game& operator=(Game&&) = delete; //! Returns the first player. //! \return The first player. Player& GetPlayer1(); //! Returns the second player. //! \return The second player. Player& GetPlayer2(); //! Returns the player controlling the current turn. //! \return The player controlling the current turn. Player& GetCurrentPlayer() const; //! Returns the opponent player. //! \return The opponent player. Player& GetOpponentPlayer() const; //! Gets the next entity identifier. //! \return The next entity ID. std::size_t GetNextID(); //! Gets the next order of play index. //! \return The next order of play index. std::size_t GetNextOOP(); //! Part of the game state. void BeginFirst(); //! Part of the game state. void BeginShuffle(); //! Part of the game state. void BeginDraw(); //! Part of the game state. void BeginMulligan(); //! Part of the game state. void MainBegin(); //! Part of the game state. void MainReady(); //! Part of the game state. void MainStartTriggers(); //! Part of the game state. void MainResource(); //! Part of the game state. void MainDraw(); //! Part of the game state. void MainStart(); //! Part of the game state. void MainAction(); //! Part of the game state. void MainEnd(); //! Part of the game state. void MainCleanUp(); //! Part of the game state. void MainNext(); //! Part of the game state. void FinalWrapUp(); //! Part of the game state. void FinalGameOver(); //! Starts the game. void StartGame(); // Processes task queue. void ProcessTasks(); //! Processes destroy and updates aura. void ProcessDestroyAndUpdateAura(); //! Processes graveyard. void ProcessGraveyard(); //! Updates aura. void UpdateAura(); //! Process the specified task. //! \param player A player to run task. //! \param task The game task to execute. void Process(Player& player, ITask* task); //! Process the specified task. //! \param player A player to run task. //! \param task The game task to execute. void Process(Player& player, ITask&& task); //! Process game until given step arriving. //! \param step The game step to process until arrival. void ProcessUntil(Step step); //! Plays policy based game. void PlayPolicy(); State state = State::INVALID; Step step = Step::INVALID; Step nextStep = Step::INVALID; TaskQueue taskQueue; TaskStack taskStack; TriggerManager triggerManager; std::vector<Aura*> auras; std::vector<Trigger*> triggers; std::vector<std::pair<Entity*, Effect*>> oneTurnEffects; std::vector<Minion*> summonedMinions; std::map<std::size_t, Minion*> deadMinions; private: //! Checks whether the game is over. void CheckGameOver(); GameConfig m_gameConfig; std::array<Player, 2> m_players; std::size_t m_turn = 0; std::size_t m_entityID = 0; std::size_t m_oopIndex = 0; Player* m_firstPlayer = nullptr; Player* m_currentPlayer = nullptr; }; } // namespace RosettaStone #endif // ROSETTASTONE_GAME_HPP <commit_msg>feat(card-impl): Change type of 'auras' to std::vector<IAura*><commit_after>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_GAME_HPP #define ROSETTASTONE_GAME_HPP #include <Rosetta/Enums/CardEnums.hpp> #include <Rosetta/Games/GameConfig.hpp> #include <Rosetta/Games/TriggerManager.hpp> #include <Rosetta/Models/Player.hpp> #include <Rosetta/Tasks/TaskQueue.hpp> #include <Rosetta/Tasks/TaskStack.hpp> #include <map> namespace RosettaStone { //! //! \brief Game class. //! //! This class stores Hearthstone game states which consists of information of //! both players. //! class Game { public: //! Deleted default constructor. Game() = delete; //! Constructs account with given \p gameConfig. //! \param gameConfig The game config holds all configuration values. explicit Game(GameConfig& gameConfig); //! Default destructor. ~Game() = default; //! Deleted copy constructor. Game(const Game&) = delete; //! Deleted move constructor. Game(Game&&) = delete; //! Deleted copy assignment operator. Game& operator=(const Game&) = delete; //! Deleted move assignment operator. Game& operator=(Game&&) = delete; //! Returns the first player. //! \return The first player. Player& GetPlayer1(); //! Returns the second player. //! \return The second player. Player& GetPlayer2(); //! Returns the player controlling the current turn. //! \return The player controlling the current turn. Player& GetCurrentPlayer() const; //! Returns the opponent player. //! \return The opponent player. Player& GetOpponentPlayer() const; //! Gets the next entity identifier. //! \return The next entity ID. std::size_t GetNextID(); //! Gets the next order of play index. //! \return The next order of play index. std::size_t GetNextOOP(); //! Part of the game state. void BeginFirst(); //! Part of the game state. void BeginShuffle(); //! Part of the game state. void BeginDraw(); //! Part of the game state. void BeginMulligan(); //! Part of the game state. void MainBegin(); //! Part of the game state. void MainReady(); //! Part of the game state. void MainStartTriggers(); //! Part of the game state. void MainResource(); //! Part of the game state. void MainDraw(); //! Part of the game state. void MainStart(); //! Part of the game state. void MainAction(); //! Part of the game state. void MainEnd(); //! Part of the game state. void MainCleanUp(); //! Part of the game state. void MainNext(); //! Part of the game state. void FinalWrapUp(); //! Part of the game state. void FinalGameOver(); //! Starts the game. void StartGame(); // Processes task queue. void ProcessTasks(); //! Processes destroy and updates aura. void ProcessDestroyAndUpdateAura(); //! Processes graveyard. void ProcessGraveyard(); //! Updates aura. void UpdateAura(); //! Process the specified task. //! \param player A player to run task. //! \param task The game task to execute. void Process(Player& player, ITask* task); //! Process the specified task. //! \param player A player to run task. //! \param task The game task to execute. void Process(Player& player, ITask&& task); //! Process game until given step arriving. //! \param step The game step to process until arrival. void ProcessUntil(Step step); //! Plays policy based game. void PlayPolicy(); State state = State::INVALID; Step step = Step::INVALID; Step nextStep = Step::INVALID; TaskQueue taskQueue; TaskStack taskStack; TriggerManager triggerManager; std::vector<IAura*> auras; std::vector<Trigger*> triggers; std::vector<std::pair<Entity*, Effect*>> oneTurnEffects; std::vector<Minion*> summonedMinions; std::map<std::size_t, Minion*> deadMinions; private: //! Checks whether the game is over. void CheckGameOver(); GameConfig m_gameConfig; std::array<Player, 2> m_players; std::size_t m_turn = 0; std::size_t m_entityID = 0; std::size_t m_oopIndex = 0; Player* m_firstPlayer = nullptr; Player* m_currentPlayer = nullptr; }; } // namespace RosettaStone #endif // ROSETTASTONE_GAME_HPP <|endoftext|>
<commit_before><commit_msg>AutoFill: Use FormManager::WebFormControlElementToFormField directly instead of finding the form field in FindFormWithFormControlElement.<commit_after><|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/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "content/common/content_switches.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); // Smooth scrolling confuses the scrollbar test. launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sets a series of numbered cookies. The value of "..." means // it's still working and we should continue to wait, any other value // indicates completion (in this case it will start with "PASS" or "FAIL"). // This keeps us from timing out on cookie waits for long tests. int progress_number = 0; std::string progress; while (true) { std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d", progress_number); progress = WaitUntilCookieNonEmpty(tab.get(), test_url, cookie_name.c_str(), TestTimeouts::large_test_timeout_ms()); if (progress != "...") break; progress_number++; } if (progress_number == 0) { // Failing the first time probably means the plugin wasn't loaded. ASSERT_FALSE(progress.empty()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; } else { ASSERT_FALSE(progress.empty()) << "Test timed out."; } EXPECT_STREQ("PASS", progress.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 #if defined(OS_WIN) // It often takes too long time (and fails otherwise) on Windows. #define MAYBE_URLLoader DISABLED_URLLoader #else #define MAYBE_URLLoader FAILS_URLLoader #endif TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) #if !defined(OS_WIN) // Times out on Windows XP: http://crbug.com/95557 TEST_PPAPI_OUT_OF_PROCESS(PostMessage) #endif TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(QueryPolicy) //TEST_PPAPI_OUT_OF_PROCESS(QueryPolicy) TEST_PPAPI_IN_PROCESS(VideoDecoder) TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem) #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84294 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } <commit_msg>Add out-of-process test for Graphics2D.<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/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "content/common/content_switches.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); // Smooth scrolling confuses the scrollbar test. launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sets a series of numbered cookies. The value of "..." means // it's still working and we should continue to wait, any other value // indicates completion (in this case it will start with "PASS" or "FAIL"). // This keeps us from timing out on cookie waits for long tests. int progress_number = 0; std::string progress; while (true) { std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d", progress_number); progress = WaitUntilCookieNonEmpty(tab.get(), test_url, cookie_name.c_str(), TestTimeouts::large_test_timeout_ms()); if (progress != "...") break; progress_number++; } if (progress_number == 0) { // Failing the first time probably means the plugin wasn't loaded. ASSERT_FALSE(progress.empty()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; } else { ASSERT_FALSE(progress.empty()) << "Test timed out."; } EXPECT_STREQ("PASS", progress.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 #if defined(OS_WIN) // It often takes too long time (and fails otherwise) on Windows. #define MAYBE_URLLoader DISABLED_URLLoader #else #define MAYBE_URLLoader FAILS_URLLoader #endif TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) #if !defined(OS_WIN) // Times out on Windows XP: http://crbug.com/95557 TEST_PPAPI_OUT_OF_PROCESS(PostMessage) #endif TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(QueryPolicy) //TEST_PPAPI_OUT_OF_PROCESS(QueryPolicy) TEST_PPAPI_IN_PROCESS(VideoDecoder) TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem) #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84294 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } <|endoftext|>
<commit_before><commit_msg>Shard WorkerFastLayoutTests to avoid Flakiness.<commit_after><|endoftext|>
<commit_before><commit_msg>Mark WorkerTest.LimitPerPage as flaky on Windows<commit_after><|endoftext|>
<commit_before><commit_msg>Disable worker-cloneport.html. This is to avoid needlessly accumulating flakiness reports. We know it's flaky and are looking for the race condition. Landing for prasadt, original CR: http://codereview.chromium.org/1566006 BUG=35965 TEST=none<commit_after><|endoftext|>
<commit_before>#include <cpr/cpr.h> #include "command.h" #include "../CommandHandler.h" #include "../OptionParser.h" /* full name of the command */ CMDNAME("cml"); /* description of the command */ CMDDESCR("interact with crystalmathlabs trackers"); /* command usage synopsis */ CMDUSAGE("$cml [-s] [-nu] [RSN]"); static const std::string CML_HOST = "https://crystalmathlabs.com"; static const std::string CML_USER = "/tracker/track.php?player="; static const std::string CML_SCALC = "/tracker/suppliescalc.php"; static const std::string CML_UPDATE = "/tracker/api.php?type=update&player="; static int updatecml(const std::string &rsn, std::string &err); /* cml: interact with crystalmathlabs trackers */ std::string CommandHandler::cml(struct cmdinfo *c) { std::string output = "@" + c->nick + ", "; std::string rsn, err; bool usenick, update, scalc; OptionParser op(c->fullCmd, "nsu"); int opt; static struct OptionParser::option long_opts[] = { { "help", NO_ARG, 'h' }, { "nick", NO_ARG, 'n' }, { "suppliescalc", NO_ARG, 's' }, { "update", NO_ARG, 'u' }, { 0, 0, 0 } }; usenick = update = scalc = false; while ((opt = op.getopt_long(long_opts)) != EOF) { switch (opt) { case 'h': return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR); case 'n': usenick = true; break; case 's': scalc = true; break; case 'u': update = true; break; case '?': return std::string(op.opterr()); default: return ""; } } if (op.optind() == c->fullCmd.length()) { if (scalc) { if (update || usenick) return CMDNAME + ": cannot use other options " "with -s"; return "[CML] " + CML_HOST + CML_SCALC; } if (update) return CMDNAME + ": must provide RSN to update"; if (usenick) return CMDNAME + ": no Twitch nick given"; return "[CML] " + CML_HOST; } else if (scalc) { return USAGEMSG(CMDNAME, CMDUSAGE); } /* get the rsn of the queried player */ if ((rsn = getRSN(c->fullCmd.substr(op.optind()), c->nick, err, usenick)).empty()) return CMDNAME + ": " + err; if (rsn.find(' ') != std::string::npos) return USAGEMSG(CMDNAME, CMDUSAGE); if (update) { if (updatecml(rsn, err) == 1) return output + rsn + "'s CML tracker has been updated"; else return CMDNAME + ": " + err; } else { return "[CML] " + CML_HOST + CML_USER + rsn; } } /* updatecml: update the cml tracker of player rsn */ static int updatecml(const std::string &rsn, std::string &err) { int i; cpr::Response resp; resp = cpr::Get(cpr::Url(CML_HOST + CML_UPDATE + rsn), cpr::Header{{ "Connection", "close" }}); i = std::stoi(resp.text); switch (i) { case 1: /* success */ break; case 2: err = "'" + rsn + "' could not be found on the hiscores"; case 3: err = "'" + rsn + "' has had a negative XP gain"; case 4: err = "unknown error, try again"; case 5: err = "'" + rsn + "' has been updated within the last 30s"; case 6: err = "'" + rsn + "' is an invalid RSN"; default: err = "could not reach CML API, try again"; } return i; } <commit_msg>break;<commit_after>#include <cpr/cpr.h> #include "command.h" #include "../CommandHandler.h" #include "../OptionParser.h" /* full name of the command */ CMDNAME("cml"); /* description of the command */ CMDDESCR("interact with crystalmathlabs trackers"); /* command usage synopsis */ CMDUSAGE("$cml [-s] [-nu] [RSN]"); static const std::string CML_HOST = "https://crystalmathlabs.com"; static const std::string CML_USER = "/tracker/track.php?player="; static const std::string CML_SCALC = "/tracker/suppliescalc.php"; static const std::string CML_UPDATE = "/tracker/api.php?type=update&player="; static int updatecml(const std::string &rsn, std::string &err); /* cml: interact with crystalmathlabs trackers */ std::string CommandHandler::cml(struct cmdinfo *c) { std::string output = "@" + c->nick + ", "; std::string rsn, err; bool usenick, update, scalc; OptionParser op(c->fullCmd, "nsu"); int opt; static struct OptionParser::option long_opts[] = { { "help", NO_ARG, 'h' }, { "nick", NO_ARG, 'n' }, { "suppliescalc", NO_ARG, 's' }, { "update", NO_ARG, 'u' }, { 0, 0, 0 } }; usenick = update = scalc = false; while ((opt = op.getopt_long(long_opts)) != EOF) { switch (opt) { case 'h': return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR); case 'n': usenick = true; break; case 's': scalc = true; break; case 'u': update = true; break; case '?': return std::string(op.opterr()); default: return ""; } } if (op.optind() == c->fullCmd.length()) { if (scalc) { if (update || usenick) return CMDNAME + ": cannot use other options " "with -s"; return "[CML] " + CML_HOST + CML_SCALC; } if (update) return CMDNAME + ": must provide RSN to update"; if (usenick) return CMDNAME + ": no Twitch nick given"; return "[CML] " + CML_HOST; } else if (scalc) { return USAGEMSG(CMDNAME, CMDUSAGE); } /* get the rsn of the queried player */ if ((rsn = getRSN(c->fullCmd.substr(op.optind()), c->nick, err, usenick)).empty()) return CMDNAME + ": " + err; if (rsn.find(' ') != std::string::npos) return USAGEMSG(CMDNAME, CMDUSAGE); if (update) { if (updatecml(rsn, err) == 1) return output + rsn + "'s CML tracker has been updated"; else return CMDNAME + ": " + err; } else { return "[CML] " + CML_HOST + CML_USER + rsn; } } /* updatecml: update the cml tracker of player rsn */ static int updatecml(const std::string &rsn, std::string &err) { int i; cpr::Response resp; resp = cpr::Get(cpr::Url(CML_HOST + CML_UPDATE + rsn), cpr::Header{{ "Connection", "close" }}); i = std::stoi(resp.text); switch (i) { case 1: /* success */ break; case 2: err = "'" + rsn + "' could not be found on the hiscores"; break; case 3: err = "'" + rsn + "' has had a negative XP gain"; break; case 4: err = "unknown error, try again"; break; case 5: err = "'" + rsn + "' has been updated within the last 30s"; break; case 6: err = "'" + rsn + "' is an invalid RSN"; break; default: err = "could not reach CML API, try again"; break; } return i; } <|endoftext|>
<commit_before>// Copyright 2014, Max Planck Institute for Intelligent Systems. // Distributed under the BSD 3-Clause license. // (See accompanying file LICENSE.txt or copy at // http://opensource.org/licenses/BSD-3-Clause) //!@file //! Mex wrapper file for robust PCA #include "mex.h" #include <boost/numeric/ublas/storage.hpp> #include <include/robust_pca.hpp> #include <include/private/boost_ublas_matlab_helper.hpp> #include <include/private/boost_ublas_matrix_helper.hpp> //! Implements allocate and free. template <class T> struct matlab_matrix_allocation; template <> struct matlab_matrix_allocation<double> { static mxArray * allocate(size_t s) { return mxCreateDoubleMatrix(s, 1, mxREAL); } static void free(mxArray *mat) { mxDestroyArray(mat); } }; //! An helper class that implements the storage concept of boost::ublas //! and performs the allocation on matlab side. It is also possible //! to provide a matlab array. template <class T> class matlab_matrix_storage { typedef T& reference; //! Default constructible matlab_matrix_storage() : pData(0) { } //! Size constructible matlab_matrix_storage(size_t s) : pData(0) { mxArray *v = matlab_matrix_allocation<T>::allocate(s); } //! Random access container reference operator[](size_t i) { return pData[i]; } private: T* pData; }; template <class output_type, class input_type> output_type get_matlab_array_value_dispatch(mxArray const* array_, size_t index_row, size_t index_column) { input_type* p_array = static_cast<input_type*>(mxGetData(array_)); if(p_array == 0) { throw std::runtime_error("Unable to retrieve a pointer to the typed array"); } // column major return p_array[index_row + mxGetN(array_) * index_column]; } template <class output_type> output_type get_matlab_array_value(mxArray const* array_, size_t index_row, size_t index_column) { assert(index_row < mxGetM(array_)); assert(index_column < mxGetN(array_)); mxClassID classId = mxGetClassID(array_); switch(classId) { case mxDOUBLE_CLASS: return get_matlab_array_value_dispatch<output_type, double>(array_, index_row, index_column); case mxSINGLE_CLASS: return get_matlab_array_value_dispatch<output_type, float>(array_, index_row, index_column); default: throw std::runtime_error("Unable to dispatch to the correct type"); } } struct s_algorithm_configuration { size_t rows; size_t columns; size_t max_dimension; size_t max_iterations; size_t max_chunk_size; size_t nb_processors; double trimming_percentage; // we should also add the initial value of the eigen vectors }; template <class input_array_type> bool robust_pca_dispatch( mxArray const* X, s_algorithm_configuration const& algorithm_configuration, mxArray *outputMatrix) { namespace ub = boost::numeric::ublas; using namespace robust_pca; using namespace robust_pca::ublas_adaptor; using namespace robust_pca::ublas_matlab_helper; typedef external_storage_adaptor<input_array_type> input_storage_t; typedef ub::matrix<input_array_type, ub::column_major, input_storage_t> input_matrix_t; typedef external_storage_adaptor<double> output_storage_t; typedef ub::matrix<double, ub::column_major, output_storage_t> output_matrix_t; const size_t &columns = algorithm_configuration.columns; const size_t &rows = algorithm_configuration.rows; const size_t &max_dimension = algorithm_configuration.max_dimension; const size_t &max_iterations = algorithm_configuration.max_iterations; const size_t dimension = columns; // input data matrix, external storage. input_storage_t input_storage(rows*columns, mxGetPr(X)); input_matrix_t input_data(rows, columns, input_storage); // output data matrix, also external storage for uBlas output_storage_t storageOutput(dimension * max_dimension, mxGetPr(outputMatrix)); output_matrix_t output_eigen_vectors(max_dimension, dimension, storageOutput); // this is the form of the data extracted from the storage typedef ub::vector<double> data_t; typedef robust_pca_impl< data_t > robust_pca_t; typedef row_iter<const input_matrix_t> const_input_row_iter_t; typedef row_iter<output_matrix_t> output_row_iter_t; // should be matlab style std::vector<data_t> temporary_data(rows); // main instance robust_pca_t instance; if(algorithm_configuration.nb_processors > 0) { if(!instance.set_nb_processors(algorithm_configuration.nb_processors)) { mexWarnMsgTxt("Incorrect number of processors. Please consult the documentation."); return false; } } if(algorithm_configuration.nb_processors > 0) { if(!instance.set_max_chunk_size(algorithm_configuration.max_chunk_size)) { mexWarnMsgTxt("Incorrect chunk size. Please consult the documentation."); return false; } } return instance.batch_process( max_iterations, max_dimension, const_input_row_iter_t(input_data, 0), const_input_row_iter_t(input_data, input_data.size1()), temporary_data.begin(), output_row_iter_t(output_eigen_vectors, 0)); } template <class input_array_type> bool robust_pca_trimming_dispatch( mxArray const* X, s_algorithm_configuration const& algorithm_configuration, mxArray *outputMatrix) { namespace ub = boost::numeric::ublas; using namespace robust_pca; using namespace robust_pca::ublas_adaptor; using namespace robust_pca::ublas_matlab_helper; typedef external_storage_adaptor<input_array_type> input_storage_t; typedef ub::matrix<input_array_type, ub::column_major, input_storage_t> input_matrix_t; typedef external_storage_adaptor<double> output_storage_t; typedef ub::matrix<double, ub::column_major, output_storage_t> output_matrix_t; const size_t &columns = algorithm_configuration.columns; const size_t &rows = algorithm_configuration.rows; const size_t &max_dimension = algorithm_configuration.max_dimension; const size_t &max_iterations = algorithm_configuration.max_iterations; const size_t dimension = columns; // input data matrix, external storage. input_storage_t input_storage(rows*columns, mxGetPr(X)); input_matrix_t input_data(rows, columns, input_storage); // output data matrix, also external storage for uBlas output_storage_t storageOutput(dimension * max_dimension, mxGetPr(outputMatrix)); output_matrix_t output_eigen_vectors(max_dimension, dimension, storageOutput); // this is the form of the data extracted from the storage typedef ub::vector<double> data_t; typedef robust_pca_with_trimming_impl< data_t > robust_pca_t; typedef row_iter<const input_matrix_t> const_input_row_iter_t; typedef row_iter<output_matrix_t> output_row_iter_t; // should be matlab style std::vector<data_t> temporary_data(rows); // main instance robust_pca_t instance(algorithm_configuration.trimming_percentage / 200, 1 - algorithm_configuration.trimming_percentage / 200); return instance.batch_process( max_iterations, max_dimension, const_input_row_iter_t(input_data, 0), const_input_row_iter_t(input_data, input_data.size1()), temporary_data.begin(), output_row_iter_t(output_eigen_vectors, 0)); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // arguments checking if (nrhs < 1 || nrhs > 4) { mexErrMsgTxt("Incorrect number of arguments. Please consult the documentation."); } const mxArray* const X = prhs[0]; assert(X); // checking the format of the data if (!mxIsDouble(X) && !mxIsSingle(X)) { mexErrMsgTxt("Unsupported input format (floating point required)"); } if(mxIsComplex(X)) { mexErrMsgTxt("Unsupported format (scalar data required)"); } s_algorithm_configuration config; // Check the dimensions of inputs config.rows = mxGetM(X); config.columns = mxGetN(X); const size_t &rows = config.rows; const size_t &columns = config.columns; size_t &max_dimension = config.max_dimension; double &trimming_percentage = config.trimming_percentage; size_t &max_chunk_size = config.max_chunk_size; size_t &nb_iterations_max = config.max_iterations; size_t &nb_processing_threads = config.nb_processors; size_t dimension = columns; #if 0 // second argument is the maximum numbers of dimensions if (nrhs >= 2) { const mxArray* const maxDimArray = prhs[1]; if(!mxIsNumeric(maxDimArray)) { mexErrMsgTxt("Erroneous argument for the maximal dimension specification (non numeric argument)"); } if(mxIsEmpty(maxDimArray)) { mexErrMsgTxt("Erroneous argument for the maximal dimension specification (empty value)"); } if(mxGetNumberOfElements(maxDimArray) > 1) { mexErrMsgTxt("Erroneous argument for the maximal dimension specification (non scalar)"); } mxClassID classId = mxGetClassID(maxDimArray); if(classId == mxDOUBLE_CLASS || classId == mxSINGLE_CLASS) { //mexErrMsgTxt("Erroneous argument for the maximal dimension specification (floating point type)"); } max_dimension = static_cast<size_t>(mxGetScalar(maxDimArray) + 0.5); if(max_dimension >= dimension) { mexErrMsgTxt("Erroneous argument for the maximal dimension specification (exceeds the dimension of the data)"); } } #endif // third argument is the optional trimming percentage bool b_trimming = false; trimming_percentage = -1; if(nrhs >= 2) { const mxArray* const trimmingArray = prhs[1]; if(!mxIsNumeric(trimmingArray)) { mexErrMsgTxt("Erroneous argument for the trimming percentage (non numeric argument)"); } if(mxIsEmpty(trimmingArray)) { mexErrMsgTxt("Erroneous argument for the trimming percentage (empty value)"); } if(mxGetNumberOfElements(trimmingArray) > 1) { mexErrMsgTxt("Erroneous argument for the trimming percentage (non scalar)"); } mxClassID classId = mxGetClassID(trimmingArray); if(classId == mxDOUBLE_CLASS || classId == mxSINGLE_CLASS) { //mexErrMsgTxt("Erroneous argument for the maximal dimension specification (floating point type)"); } b_trimming = true; trimming_percentage = mxGetScalar(trimmingArray); if(trimming_percentage < 0 || trimming_percentage > 100) { mexErrMsgTxt("Erroneous argument for the trimming percentage (not within the range [0, 100])"); } } nb_iterations_max = 1000; max_chunk_size = std::numeric_limits<size_t>::max(); nb_processing_threads = 1; max_dimension = dimension; if(nrhs == 3) { const mxArray* const algorithmConfiguration = prhs[2]; if(!mxIsStruct(algorithmConfiguration)) { mexErrMsgTxt("Erroneous argument for the algorithm configuration (not a structure)"); } mxArray *nb_iteration_array = mxGetField(algorithmConfiguration, 0, "nb_iterations_max"); if(nb_iteration_array != 0) { nb_iterations_max = static_cast<int>(mxGetScalar(nb_iteration_array) + 0.5); } mxArray *max_chunk_size_array = mxGetField(algorithmConfiguration, 0, "max_chunk_size"); if(max_chunk_size_array != 0) { max_chunk_size = static_cast<size_t>(mxGetScalar(max_chunk_size_array) + 0.5); } mxArray *nb_processing_threads_array = mxGetField(algorithmConfiguration, 0, "nb_processing_threads"); if(nb_processing_threads_array != 0) { nb_processing_threads = static_cast<size_t>(mxGetScalar(nb_processing_threads_array) + 0.5); } mxArray *nb_max_dimensions = mxGetField(algorithmConfiguration, 0, "max_dimensions"); if(nb_max_dimensions != 0) { max_dimension = static_cast<size_t>(mxGetScalar(nb_max_dimensions) + 0.5); } } // TODO put the dimension // for the library to work, we need to allocate some temporary storage // we also allocate the output if given plhs[0] = mxCreateDoubleMatrix(dimension, max_dimension, mxREAL); mxArray *outputMatrix = plhs[0]; assert(outputMatrix); bool result = false; switch(mxGetClassID(X)) { case mxDOUBLE_CLASS: { if(!b_trimming) { result = robust_pca_dispatch<double>(X, config, outputMatrix); } else { result = robust_pca_trimming_dispatch<double>(X, config, outputMatrix); } break; } default: break; } if(!result) { mexErrMsgTxt("Robust PCA: an error occurred in the call of the function."); } }<commit_msg>RP-39<commit_after>// Copyright 2014, Max Planck Institute for Intelligent Systems. // Distributed under the BSD 3-Clause license. // (See accompanying file LICENSE.txt or copy at // http://opensource.org/licenses/BSD-3-Clause) //!@file //! Mex wrapper file for robust PCA #include "mex.h" #include <boost/numeric/ublas/storage.hpp> #include <include/robust_pca.hpp> #include <include/private/boost_ublas_matlab_helper.hpp> #include <include/private/boost_ublas_matrix_helper.hpp> //! Implements allocate and free. template <class T> struct matlab_matrix_allocation; template <> struct matlab_matrix_allocation<double> { static mxArray * allocate(size_t s) { return mxCreateDoubleMatrix(s, 1, mxREAL); } static void free(mxArray *mat) { mxDestroyArray(mat); } }; //! An helper class that implements the storage concept of boost::ublas //! and performs the allocation on matlab side. It is also possible //! to provide a matlab array. template <class T> class matlab_matrix_storage { typedef T& reference; //! Default constructible matlab_matrix_storage() : pData(0) { } //! Size constructible matlab_matrix_storage(size_t s) : pData(0) { mxArray *v = matlab_matrix_allocation<T>::allocate(s); } //! Random access container reference operator[](size_t i) { return pData[i]; } private: T* pData; }; template <class output_type, class input_type> output_type get_matlab_array_value_dispatch(mxArray const* array_, size_t index_row, size_t index_column) { input_type* p_array = static_cast<input_type*>(mxGetData(array_)); if(p_array == 0) { throw std::runtime_error("Unable to retrieve a pointer to the typed array"); } // column major return p_array[index_row + mxGetN(array_) * index_column]; } template <class output_type> output_type get_matlab_array_value(mxArray const* array_, size_t index_row, size_t index_column) { assert(index_row < mxGetM(array_)); assert(index_column < mxGetN(array_)); mxClassID classId = mxGetClassID(array_); switch(classId) { case mxDOUBLE_CLASS: return get_matlab_array_value_dispatch<output_type, double>(array_, index_row, index_column); case mxSINGLE_CLASS: return get_matlab_array_value_dispatch<output_type, float>(array_, index_row, index_column); default: throw std::runtime_error("Unable to dispatch to the correct type"); } } struct s_algorithm_configuration { size_t rows; size_t columns; size_t max_dimension; size_t max_iterations; size_t max_chunk_size; size_t nb_processors; double trimming_percentage; // we should also add the initial value of the eigen vectors }; template <class input_array_type> bool robust_pca_dispatch( mxArray const* X, s_algorithm_configuration const& algorithm_configuration, mxArray *outputMatrix) { namespace ub = boost::numeric::ublas; using namespace robust_pca; using namespace robust_pca::ublas_adaptor; using namespace robust_pca::ublas_matlab_helper; typedef external_storage_adaptor<input_array_type> input_storage_t; typedef ub::matrix<input_array_type, ub::column_major, input_storage_t> input_matrix_t; typedef external_storage_adaptor<double> output_storage_t; typedef ub::matrix<double, ub::column_major, output_storage_t> output_matrix_t; const size_t &columns = algorithm_configuration.columns; const size_t &rows = algorithm_configuration.rows; const size_t &max_dimension = algorithm_configuration.max_dimension; const size_t &max_iterations = algorithm_configuration.max_iterations; const size_t dimension = columns; // input data matrix, external storage. input_storage_t input_storage(rows*columns, mxGetPr(X)); input_matrix_t input_data(rows, columns, input_storage); // output data matrix, also external storage for uBlas output_storage_t storageOutput(dimension * max_dimension, mxGetPr(outputMatrix)); output_matrix_t output_eigen_vectors(max_dimension, dimension, storageOutput); // this is the form of the data extracted from the storage typedef ub::vector<double> data_t; typedef robust_pca_impl< data_t > robust_pca_t; typedef row_iter<const input_matrix_t> const_input_row_iter_t; typedef row_iter<output_matrix_t> output_row_iter_t; // should be matlab style std::vector<data_t> temporary_data(rows); // main instance robust_pca_t instance; if(algorithm_configuration.nb_processors > 0) { if(!instance.set_nb_processors(algorithm_configuration.nb_processors)) { mexWarnMsgTxt("Incorrect number of processors. Please consult the documentation."); return false; } } if(algorithm_configuration.nb_processors > 0) { if(!instance.set_max_chunk_size(algorithm_configuration.max_chunk_size)) { mexWarnMsgTxt("Incorrect chunk size. Please consult the documentation."); return false; } } return instance.batch_process( max_iterations, max_dimension, const_input_row_iter_t(input_data, 0), const_input_row_iter_t(input_data, input_data.size1()), temporary_data.begin(), output_row_iter_t(output_eigen_vectors, 0)); } template <class input_array_type> bool robust_pca_trimming_dispatch( mxArray const* X, s_algorithm_configuration const& algorithm_configuration, mxArray *outputMatrix) { namespace ub = boost::numeric::ublas; using namespace robust_pca; using namespace robust_pca::ublas_adaptor; using namespace robust_pca::ublas_matlab_helper; typedef external_storage_adaptor<input_array_type> input_storage_t; typedef ub::matrix<input_array_type, ub::column_major, input_storage_t> input_matrix_t; typedef external_storage_adaptor<double> output_storage_t; typedef ub::matrix<double, ub::column_major, output_storage_t> output_matrix_t; const size_t &columns = algorithm_configuration.columns; const size_t &rows = algorithm_configuration.rows; const size_t &max_dimension = algorithm_configuration.max_dimension; const size_t &max_iterations = algorithm_configuration.max_iterations; const size_t dimension = columns; // input data matrix, external storage. input_storage_t input_storage(rows*columns, mxGetPr(X)); input_matrix_t input_data(rows, columns, input_storage); // output data matrix, also external storage for uBlas output_storage_t storageOutput(dimension * max_dimension, mxGetPr(outputMatrix)); output_matrix_t output_eigen_vectors(max_dimension, dimension, storageOutput); // this is the form of the data extracted from the storage typedef ub::vector<double> data_t; typedef robust_pca_with_trimming_impl< data_t > robust_pca_t; typedef row_iter<const input_matrix_t> const_input_row_iter_t; typedef row_iter<output_matrix_t> output_row_iter_t; // should be matlab style std::vector<data_t> temporary_data(rows); // main instance robust_pca_t instance(algorithm_configuration.trimming_percentage / 200, 1 - algorithm_configuration.trimming_percentage / 200); return instance.batch_process( max_iterations, max_dimension, const_input_row_iter_t(input_data, 0), const_input_row_iter_t(input_data, input_data.size1()), temporary_data.begin(), output_row_iter_t(output_eigen_vectors, 0)); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // arguments checking if (nrhs < 1 || nrhs > 4) { mexErrMsgTxt("Incorrect number of arguments. Please consult the documentation."); } const mxArray* const X = prhs[0]; assert(X); // checking the format of the data if (!mxIsDouble(X) && !mxIsSingle(X)) { mexErrMsgTxt("Unsupported input format (floating point required)"); } if(mxIsComplex(X)) { mexErrMsgTxt("Unsupported format (scalar data required)"); } s_algorithm_configuration config; // Check the dimensions of inputs config.rows = mxGetM(X); config.columns = mxGetN(X); const size_t &rows = config.rows; const size_t &columns = config.columns; size_t &max_dimension = config.max_dimension; double &trimming_percentage = config.trimming_percentage; size_t &max_chunk_size = config.max_chunk_size; size_t &nb_iterations_max = config.max_iterations; size_t &nb_processing_threads = config.nb_processors; size_t dimension = columns; // third argument is the optional trimming percentage bool b_trimming = false; trimming_percentage = -1; if(nrhs >= 2) { const mxArray* const trimmingArray = prhs[1]; if(!mxIsNumeric(trimmingArray)) { mexErrMsgTxt("Erroneous argument for the trimming percentage (non numeric argument)"); } if(mxIsEmpty(trimmingArray)) { mexErrMsgTxt("Erroneous argument for the trimming percentage (empty value)"); } if(mxGetNumberOfElements(trimmingArray) > 1) { mexErrMsgTxt("Erroneous argument for the trimming percentage (non scalar)"); } mxClassID classId = mxGetClassID(trimmingArray); if(classId == mxDOUBLE_CLASS || classId == mxSINGLE_CLASS) { //mexErrMsgTxt("Erroneous argument for the maximal dimension specification (floating point type)"); } b_trimming = true; trimming_percentage = mxGetScalar(trimmingArray); if(trimming_percentage < 0 || trimming_percentage > 100) { mexErrMsgTxt("Erroneous argument for the trimming percentage (not within the range [0, 100])"); } b_trimming = trimming_percentage > 0 && trimming_percentage < 100; } nb_iterations_max = 1000; max_chunk_size = std::numeric_limits<size_t>::max(); nb_processing_threads = 1; max_dimension = dimension; if(nrhs == 3) { const mxArray* const algorithmConfiguration = prhs[2]; if(!mxIsStruct(algorithmConfiguration)) { mexErrMsgTxt("Erroneous argument for the algorithm configuration (not a structure)"); } mxArray *nb_iteration_array = mxGetField(algorithmConfiguration, 0, "nb_iterations_max"); if(nb_iteration_array != 0) { nb_iterations_max = static_cast<int>(mxGetScalar(nb_iteration_array) + 0.5); } mxArray *max_chunk_size_array = mxGetField(algorithmConfiguration, 0, "max_chunk_size"); if(max_chunk_size_array != 0) { max_chunk_size = static_cast<size_t>(mxGetScalar(max_chunk_size_array) + 0.5); } mxArray *nb_processing_threads_array = mxGetField(algorithmConfiguration, 0, "nb_processing_threads"); if(nb_processing_threads_array != 0) { nb_processing_threads = static_cast<size_t>(mxGetScalar(nb_processing_threads_array) + 0.5); } mxArray *nb_max_dimensions = mxGetField(algorithmConfiguration, 0, "max_dimensions"); if(nb_max_dimensions != 0) { max_dimension = static_cast<size_t>(mxGetScalar(nb_max_dimensions) + 0.5); } } // TODO put the dimension // for the library to work, we need to allocate some temporary storage // we also allocate the output if given plhs[0] = mxCreateDoubleMatrix(dimension, max_dimension, mxREAL); mxArray *outputMatrix = plhs[0]; assert(outputMatrix); bool result = false; switch(mxGetClassID(X)) { case mxDOUBLE_CLASS: { if(!b_trimming) { result = robust_pca_dispatch<double>(X, config, outputMatrix); } else { result = robust_pca_trimming_dispatch<double>(X, config, outputMatrix); } break; } default: break; } if(!result) { mexErrMsgTxt("Robust PCA: an error occurred in the call of the function."); } }<|endoftext|>
<commit_before>/* Copyright (c) 2018 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/fluid/operators/cvm_op.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; class CVMOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should be not null."); PADDLE_ENFORCE(ctx->HasInput("CVM"), "Input(CVM) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("Y"), "Output(Y) should be not null."); auto x_dims = ctx->GetInputDim("X"); auto cvm_dims = ctx->GetInputDim("CVM"); PADDLE_ENFORCE_EQ(x_dims.size(), 2UL, "Input(X)'s rank should be 2."); PADDLE_ENFORCE_EQ(cvm_dims.size(), 2UL, "Input(CVM)'s rank should be 2."); PADDLE_ENFORCE_EQ(cvm_dims[1], 2UL, "The 2nd dimension of " "Input(CVM) should be 2."); if (ctx->Attrs().Get<bool>("use_cvm")) { ctx->SetOutputDim("Y", {x_dims[0], x_dims[1]}); } else { ctx->SetOutputDim("Y", {x_dims[0], x_dims[1] - 2}); } ctx->ShareLoD("X", /*->*/ "Y"); } protected: // Explicitly set that the data type of computation kernel of // cvm // is determined by its input "X". framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(ctx.Input<Tensor>("X")->type(), ctx.device_context()); } }; class CVMGradientOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should be not null."); PADDLE_ENFORCE(ctx->HasInput("CVM"), "Input(CVM) should be not null."); PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Y")), "Input(Y@GRAD) should be not null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")), "Output(X@GRAD) should be not null."); auto x_dims = ctx->GetInputDim("X"); auto cvm_dims = ctx->GetInputDim("CVM"); auto dy_dims = ctx->GetInputDim(framework::GradVarName("Y")); PADDLE_ENFORCE_EQ(x_dims.size(), 2, "Input(X)'s rank should be 2."); PADDLE_ENFORCE_EQ(dy_dims.size(), 2, "Input(Y@Grad)'s rank should be 2."); PADDLE_ENFORCE_EQ(cvm_dims.size(), 2, "Input(CVM)'s rank should be 2."); PADDLE_ENFORCE_EQ(x_dims[0], dy_dims[0], "The 1st dimension of Input(X) and Input(Y@Grad) should " "be equal."); PADDLE_ENFORCE_EQ(cvm_dims[1], 2, "When Attr(soft_label) == false, the 2nd dimension of " "Input(CVM) should be 2."); ctx->SetOutputDim(framework::GradVarName("X"), x_dims); ctx->ShareLoD("X", framework::GradVarName("X")); } protected: // Explicitly set that the data type of computation kernel of // cvm // is determined by its input "X". framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(ctx.Input<Tensor>("X")->type(), ctx.device_context()); } }; class CVMOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(LodTensor, default LodTensor<float>), a 2-D tensor with shape " "[N x D]," " where N is the batch size and D is the emebdding dim. "); AddInput("CVM", "(Tensor), a 2-D Tensor with shape [N x 2], where N is the batch " "size, 2 is show and click."); AddOutput("Y", "(LodTensor, default LodTensor<float>), a 2-D tensor with shape " "[N x K]."); AddAttr<bool>("use_cvm", "bool, use cvm or not").SetDefault(true); AddComment(R"DOC( CVM Operator. example: input = fluid.layers.data(name=\"input\", shape=[-1, 1], lod_level=1, append_batch_size=False, dtype=\"int64\") label = fluid.layers.data(name=\"label\", shape=[-1, 1], append_batch_size=False, dtype=\"int64\") embed = fluid.layers.embedding( input=input, size=[100, 11], dtype='float32') ones = fluid.layers.fill_constant_batch_size_like(input=label, shape=[-1, 1], dtype=\"int64\", value=1) show_clk = fluid.layers.cast(fluid.layers.concat([ones, label], axis=1), dtype='float32') show_clk.stop_gradient = True input_with_cvm = fluid.layers.continuous_value_model(embed, show_clk, True) )DOC"); } }; class CVMGradOpDescMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDesc> Apply() const override { std::unique_ptr<framework::OpDesc> op(new framework::OpDesc()); op->SetType("cvm_grad"); op->SetInput("X", Input("X")); op->SetInput("CVM", Input("CVM")); op->SetInput(framework::GradVarName("Y"), OutputGrad("Y")); op->SetOutput(framework::GradVarName("X"), InputGrad("X")); op->SetOutput(framework::GradVarName("CVM"), InputGrad("CVM")); op->SetAttrMap(Attrs()); return op; } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(cvm, ops::CVMOp, ops::CVMOpMaker, ops::CVMGradOpDescMaker); REGISTER_OPERATOR(cvm_grad, ops::CVMGradientOp); REGISTER_OP_CPU_KERNEL(cvm, ops::CVMOpKernel<float>, ops::CVMOpKernel<double>); REGISTER_OP_CPU_KERNEL(cvm_grad, ops::CVMGradOpKernel<float>, ops::CVMGradOpKernel<double>); <commit_msg>add continuous value model op test=develop<commit_after>/* Copyright (c) 2018 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/fluid/operators/cvm_op.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; class CVMOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should be not null."); PADDLE_ENFORCE(ctx->HasInput("CVM"), "Input(CVM) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("Y"), "Output(Y) should be not null."); auto x_dims = ctx->GetInputDim("X"); auto cvm_dims = ctx->GetInputDim("CVM"); PADDLE_ENFORCE_EQ(x_dims.size(), 2UL, "Input(X)'s rank should be 2."); PADDLE_ENFORCE_EQ(cvm_dims.size(), 2UL, "Input(CVM)'s rank should be 2."); PADDLE_ENFORCE_EQ(cvm_dims[1], 2UL, "The 2nd dimension of " "Input(CVM) should be 2."); if (ctx->Attrs().Get<bool>("use_cvm")) { ctx->SetOutputDim("Y", {x_dims[0], x_dims[1]}); } else { ctx->SetOutputDim("Y", {x_dims[0], x_dims[1] - 2}); } ctx->ShareLoD("X", /*->*/ "Y"); } protected: // Explicitly set that the data type of computation kernel of // cvm // is determined by its input "X". framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(ctx.Input<Tensor>("X")->type(), ctx.device_context()); } }; class CVMGradientOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should be not null."); PADDLE_ENFORCE(ctx->HasInput("CVM"), "Input(CVM) should be not null."); PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Y")), "Input(Y@GRAD) should be not null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")), "Output(X@GRAD) should be not null."); auto x_dims = ctx->GetInputDim("X"); auto cvm_dims = ctx->GetInputDim("CVM"); auto dy_dims = ctx->GetInputDim(framework::GradVarName("Y")); PADDLE_ENFORCE_EQ(x_dims.size(), 2, "Input(X)'s rank should be 2."); PADDLE_ENFORCE_EQ(dy_dims.size(), 2, "Input(Y@Grad)'s rank should be 2."); PADDLE_ENFORCE_EQ(cvm_dims.size(), 2, "Input(CVM)'s rank should be 2."); PADDLE_ENFORCE_EQ(x_dims[0], dy_dims[0], "The 1st dimension of Input(X) and Input(Y@Grad) should " "be equal."); PADDLE_ENFORCE_EQ(cvm_dims[1], 2, "When Attr(soft_label) == false, the 2nd dimension of " "Input(CVM) should be 2."); ctx->SetOutputDim(framework::GradVarName("X"), x_dims); ctx->ShareLoD("X", framework::GradVarName("X")); } protected: // Explicitly set that the data type of computation kernel of // cvm // is determined by its input "X". framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(ctx.Input<Tensor>("X")->type(), ctx.device_context()); } }; class CVMOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(LodTensor, default LodTensor<float>), a 2-D tensor with shape " "[N x D]," " where N is the batch size and D is the emebdding dim. "); AddInput("CVM", "(Tensor), a 2-D Tensor with shape [N x 2], where N is the batch " "size, 2 is show and click."); AddOutput("Y", "(LodTensor, default LodTensor<float>), a 2-D tensor with shape " "[N x K]."); AddAttr<bool>("use_cvm", "bool, use cvm or not").SetDefault(true); AddComment(R"DOC( CVM Operator. example: input = fluid.layers.data(name=\"input\", shape=[-1, 1], lod_level=1, append_batch_size=False, dtype=\"int64\") label = fluid.layers.data(name=\"label\", shape=[-1, 1], append_batch_size=False, dtype=\"int64\") embed = fluid.layers.embedding( input=input, size=[100, 11], dtype='float32') ones = fluid.layers.fill_constant_batch_size_like(input=label, shape=[-1, 1], dtype=\"int64\", value=1) show_clk = fluid.layers.cast(fluid.layers.concat([ones, label], axis=1), dtype='float32') show_clk.stop_gradient = True input_with_cvm = fluid.layers.continuous_value_model(embed, show_clk, True) )DOC"); } }; class CVMGradOpDescMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDesc> Apply() const override { std::unique_ptr<framework::OpDesc> op(new framework::OpDesc()); op->SetType("cvm_grad"); op->SetInput("X", Input("X")); op->SetInput("CVM", Input("CVM")); op->SetInput(framework::GradVarName("Y"), OutputGrad("Y")); op->SetOutput(framework::GradVarName("X"), InputGrad("X")); op->SetOutput(framework::GradVarName("CVM"), InputGrad("CVM")); op->SetAttrMap(Attrs()); return op; } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(cvm, ops::CVMOp, ops::CVMOpMaker, ops::CVMGradOpDescMaker); REGISTER_OPERATOR(cvm_grad, ops::CVMGradientOp); REGISTER_OP_CPU_KERNEL(cvm, ops::CVMOpKernel<float>, ops::CVMOpKernel<double>); REGISTER_OP_CPU_KERNEL(cvm_grad, ops::CVMGradOpKernel<float>, ops::CVMGradOpKernel<double>); <|endoftext|>
<commit_before><commit_msg>[FIXED] fetch symbol exception<commit_after><|endoftext|>
<commit_before>// Filename: odeContactGeom.cxx // Created by: joswilso (27Dec06) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "config_ode.h" #include "odeContactGeom.h" TypeHandle OdeContactGeom::_type_handle; OdeContactGeom:: OdeContactGeom() : _contact_geom() { } OdeContactGeom:: OdeContactGeom(const OdeContactGeom &copy) : _contact_geom() { *this = copy._contact_geom; } OdeContactGeom:: OdeContactGeom(const dContactGeom &copy) : _contact_geom() { *this = _contact_geom; } OdeContactGeom:: ~OdeContactGeom() { } const dContactGeom* OdeContactGeom:: get_contact_geom_ptr() const { return &_contact_geom; } void OdeContactGeom:: operator = (const OdeContactGeom &copy) { *this = copy._contact_geom; } void OdeContactGeom:: operator = (const dContactGeom &contact_geom) { _contact_geom.pos[0] = contact_geom.pos[0]; _contact_geom.pos[1] = contact_geom.pos[1]; _contact_geom.pos[2] = contact_geom.pos[2]; _contact_geom.normal[0] = contact_geom.normal[0]; _contact_geom.normal[1] = contact_geom.normal[1]; _contact_geom.normal[2] = contact_geom.normal[2]; _contact_geom.depth = contact_geom.depth; _contact_geom.g1 = contact_geom.g1; _contact_geom.g2 = contact_geom.g2; _contact_geom.side1 = contact_geom.side1; _contact_geom.side2 = contact_geom.side2; } <commit_msg>Fix empty contact geoms with OdeUtil.collide<commit_after>// Filename: odeContactGeom.cxx // Created by: joswilso (27Dec06) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "config_ode.h" #include "odeContactGeom.h" TypeHandle OdeContactGeom::_type_handle; OdeContactGeom:: OdeContactGeom() : _contact_geom() { } OdeContactGeom:: OdeContactGeom(const OdeContactGeom &copy) : _contact_geom() { *this = copy._contact_geom; } OdeContactGeom:: OdeContactGeom(const dContactGeom &copy) : _contact_geom() { *this = copy; } OdeContactGeom:: ~OdeContactGeom() { } const dContactGeom* OdeContactGeom:: get_contact_geom_ptr() const { return &_contact_geom; } void OdeContactGeom:: operator = (const OdeContactGeom &copy) { *this = copy._contact_geom; } void OdeContactGeom:: operator = (const dContactGeom &contact_geom) { _contact_geom.pos[0] = contact_geom.pos[0]; _contact_geom.pos[1] = contact_geom.pos[1]; _contact_geom.pos[2] = contact_geom.pos[2]; _contact_geom.normal[0] = contact_geom.normal[0]; _contact_geom.normal[1] = contact_geom.normal[1]; _contact_geom.normal[2] = contact_geom.normal[2]; _contact_geom.depth = contact_geom.depth; _contact_geom.g1 = contact_geom.g1; _contact_geom.g2 = contact_geom.g2; _contact_geom.side1 = contact_geom.side1; _contact_geom.side2 = contact_geom.side2; } <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrVkCopyManager.h" #include "GrSamplerParams.h" #include "GrShaderCaps.h" #include "GrSurface.h" #include "GrTexturePriv.h" #include "GrVkCommandBuffer.h" #include "GrVkCopyPipeline.h" #include "GrVkDescriptorSet.h" #include "GrVkGpu.h" #include "GrVkImageView.h" #include "GrVkRenderTarget.h" #include "GrVkResourceProvider.h" #include "GrVkSampler.h" #include "GrVkTexture.h" #include "GrVkUniformBuffer.h" #include "GrVkVertexBuffer.h" #include "SkPoint.h" #include "SkRect.h" GrVkCopyManager::GrVkCopyManager() : fVertShaderModule(VK_NULL_HANDLE) , fFragShaderModule(VK_NULL_HANDLE) , fPipelineLayout(VK_NULL_HANDLE) {} GrVkCopyManager::~GrVkCopyManager() {} bool GrVkCopyManager::createCopyProgram(GrVkGpu* gpu) { const GrShaderCaps* shaderCaps = gpu->caps()->shaderCaps(); const char* version = shaderCaps->versionDeclString(); SkString vertShaderText(version); vertShaderText.append( "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout(set = 0, binding = 0) uniform vertexUniformBuffer {" "mediump vec4 uPosXform;" "mediump vec4 uTexCoordXform;" "};" "layout(location = 0) in highp vec2 inPosition;" "layout(location = 1) out mediump vec2 vTexCoord;" "// Copy Program VS\n" "void main() {" "vTexCoord = inPosition * uTexCoordXform.xy + uTexCoordXform.zw;" "gl_Position.xy = inPosition * uPosXform.xy + uPosXform.zw;" "gl_Position.zw = vec2(0, 1);" "}" ); SkString fragShaderText(version); fragShaderText.append( "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "precision mediump float;" "layout(set = 1, binding = 0) uniform mediump sampler2D uTextureSampler;" "layout(location = 1) in mediump vec2 vTexCoord;" "layout(location = 0, index = 0) out mediump vec4 fsColorOut;" "// Copy Program FS\n" "void main() {" "fsColorOut = texture(uTextureSampler, vTexCoord);" "}" ); SkSL::Program::Settings settings; SkSL::Program::Inputs inputs; if (!GrCompileVkShaderModule(gpu, vertShaderText.c_str(), VK_SHADER_STAGE_VERTEX_BIT, &fVertShaderModule, &fShaderStageInfo[0], settings, &inputs)) { this->destroyResources(gpu); return false; } SkASSERT(inputs.isEmpty()); if (!GrCompileVkShaderModule(gpu, fragShaderText.c_str(), VK_SHADER_STAGE_FRAGMENT_BIT, &fFragShaderModule, &fShaderStageInfo[1], settings, &inputs)) { this->destroyResources(gpu); return false; } SkASSERT(inputs.isEmpty()); VkDescriptorSetLayout dsLayout[2]; GrVkResourceProvider& resourceProvider = gpu->resourceProvider(); dsLayout[GrVkUniformHandler::kUniformBufferDescSet] = resourceProvider.getUniformDSLayout(); uint32_t samplerVisibility = kFragment_GrShaderFlag; SkTArray<uint32_t> visibilityArray(&samplerVisibility, 1); resourceProvider.getSamplerDescriptorSetHandle(visibilityArray, &fSamplerDSHandle); dsLayout[GrVkUniformHandler::kSamplerDescSet] = resourceProvider.getSamplerDSLayout(fSamplerDSHandle); // Create the VkPipelineLayout VkPipelineLayoutCreateInfo layoutCreateInfo; memset(&layoutCreateInfo, 0, sizeof(VkPipelineLayoutCreateFlags)); layoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; layoutCreateInfo.pNext = 0; layoutCreateInfo.flags = 0; layoutCreateInfo.setLayoutCount = 2; layoutCreateInfo.pSetLayouts = dsLayout; layoutCreateInfo.pushConstantRangeCount = 0; layoutCreateInfo.pPushConstantRanges = nullptr; VkResult err = GR_VK_CALL(gpu->vkInterface(), CreatePipelineLayout(gpu->device(), &layoutCreateInfo, nullptr, &fPipelineLayout)); if (err) { this->destroyResources(gpu); return false; } static const float vdata[] = { 0, 0, 0, 1, 1, 0, 1, 1 }; fVertexBuffer.reset(GrVkVertexBuffer::Create(gpu, sizeof(vdata), false)); SkASSERT(fVertexBuffer.get()); fVertexBuffer->updateData(vdata, sizeof(vdata)); // We use 2 vec4's for uniforms fUniformBuffer.reset(GrVkUniformBuffer::Create(gpu, 8 * sizeof(float))); SkASSERT(fUniformBuffer.get()); return true; } bool GrVkCopyManager::copySurfaceAsDraw(GrVkGpu* gpu, GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { if (!gpu->vkCaps().supportsCopiesAsDraws()) { return false; } GrVkRenderTarget* rt = static_cast<GrVkRenderTarget*>(dst->asRenderTarget()); if (!rt) { return false; } GrVkTexture* srcTex = static_cast<GrVkTexture*>(src->asTexture()); if (!srcTex) { return false; } if (VK_NULL_HANDLE == fVertShaderModule) { SkASSERT(VK_NULL_HANDLE == fFragShaderModule && VK_NULL_HANDLE == fPipelineLayout && nullptr == fVertexBuffer.get() && nullptr == fUniformBuffer.get()); if (!this->createCopyProgram(gpu)) { SkDebugf("Failed to create copy program.\n"); return false; } } GrVkResourceProvider& resourceProv = gpu->resourceProvider(); GrVkCopyPipeline* pipeline = resourceProv.findOrCreateCopyPipeline(rt, fShaderStageInfo, fPipelineLayout); if (!pipeline) { return false; } // UPDATE UNIFORM DESCRIPTOR SET int w = srcRect.width(); int h = srcRect.height(); // dst rect edges in NDC (-1 to 1) int dw = dst->width(); int dh = dst->height(); float dx0 = 2.f * dstPoint.fX / dw - 1.f; float dx1 = 2.f * (dstPoint.fX + w) / dw - 1.f; float dy0 = 2.f * dstPoint.fY / dh - 1.f; float dy1 = 2.f * (dstPoint.fY + h) / dh - 1.f; if (kBottomLeft_GrSurfaceOrigin == dst->origin()) { dy0 = -dy0; dy1 = -dy1; } float sx0 = (float)srcRect.fLeft; float sx1 = (float)(srcRect.fLeft + w); float sy0 = (float)srcRect.fTop; float sy1 = (float)(srcRect.fTop + h); int sh = src->height(); if (kBottomLeft_GrSurfaceOrigin == src->origin()) { sy0 = sh - sy0; sy1 = sh - sy1; } // src rect edges in normalized texture space (0 to 1). int sw = src->width(); sx0 /= sw; sx1 /= sw; sy0 /= sh; sy1 /= sh; float uniData[] = { dx1 - dx0, dy1 - dy0, dx0, dy0, // posXform sx1 - sx0, sy1 - sy0, sx0, sy0 }; // texCoordXform fUniformBuffer->updateData(gpu, uniData, sizeof(uniData), nullptr); const GrVkDescriptorSet* uniformDS = resourceProv.getUniformDescriptorSet(); SkASSERT(uniformDS); VkDescriptorBufferInfo uniBufferInfo; uniBufferInfo.buffer = fUniformBuffer->buffer(); uniBufferInfo.offset = fUniformBuffer->offset(); uniBufferInfo.range = fUniformBuffer->size(); VkWriteDescriptorSet descriptorWrites; descriptorWrites.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites.pNext = nullptr; descriptorWrites.dstSet = uniformDS->descriptorSet(); descriptorWrites.dstBinding = GrVkUniformHandler::kVertexBinding; descriptorWrites.dstArrayElement = 0; descriptorWrites.descriptorCount = 1; descriptorWrites.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrites.pImageInfo = nullptr; descriptorWrites.pBufferInfo = &uniBufferInfo; descriptorWrites.pTexelBufferView = nullptr; GR_VK_CALL(gpu->vkInterface(), UpdateDescriptorSets(gpu->device(), 1, &descriptorWrites, 0, nullptr)); // UPDATE SAMPLER DESCRIPTOR SET const GrVkDescriptorSet* samplerDS = gpu->resourceProvider().getSamplerDescriptorSet(fSamplerDSHandle); GrSamplerParams params(SkShader::kClamp_TileMode, GrSamplerParams::kNone_FilterMode); GrVkSampler* sampler = resourceProv.findOrCreateCompatibleSampler(params, srcTex->texturePriv().maxMipMapLevel()); VkDescriptorImageInfo imageInfo; memset(&imageInfo, 0, sizeof(VkDescriptorImageInfo)); imageInfo.sampler = sampler->sampler(); imageInfo.imageView = srcTex->textureView(true)->imageView(); imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkWriteDescriptorSet writeInfo; memset(&writeInfo, 0, sizeof(VkWriteDescriptorSet)); writeInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeInfo.pNext = nullptr; writeInfo.dstSet = samplerDS->descriptorSet(); writeInfo.dstBinding = 0; writeInfo.dstArrayElement = 0; writeInfo.descriptorCount = 1; writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeInfo.pImageInfo = &imageInfo; writeInfo.pBufferInfo = nullptr; writeInfo.pTexelBufferView = nullptr; GR_VK_CALL(gpu->vkInterface(), UpdateDescriptorSets(gpu->device(), 1, &writeInfo, 0, nullptr)); VkDescriptorSet vkDescSets[] = { uniformDS->descriptorSet(), samplerDS->descriptorSet() }; GrVkRenderTarget* texRT = static_cast<GrVkRenderTarget*>(srcTex->asRenderTarget()); if (texRT) { gpu->onResolveRenderTarget(texRT); } GrVkPrimaryCommandBuffer* cmdBuffer = gpu->currentCommandBuffer(); // TODO: Make tighter bounds and then adjust bounds for origin and granularity if we see // any perf issues with using the whole bounds SkIRect bounds = SkIRect::MakeWH(rt->width(), rt->height()); // Change layouts of rt and texture GrVkImage* targetImage = rt->msaaImage() ? rt->msaaImage() : rt; targetImage->setImageLayout(gpu, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, false); srcTex->setImageLayout(gpu, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, false); GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_STORE); GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_STORE); const GrVkRenderPass* renderPass; const GrVkResourceProvider::CompatibleRPHandle& rpHandle = rt->compatibleRenderPassHandle(); if (rpHandle.isValid()) { renderPass = gpu->resourceProvider().findRenderPass(rpHandle, vkColorOps, vkStencilOps); } else { renderPass = gpu->resourceProvider().findRenderPass(*rt, vkColorOps, vkStencilOps); } SkASSERT(renderPass->isCompatible(*rt->simpleRenderPass())); cmdBuffer->beginRenderPass(gpu, renderPass, nullptr, *rt, bounds, false); cmdBuffer->bindPipeline(gpu, pipeline); // Uniform DescriptorSet, Sampler DescriptorSet, and vertex shader uniformBuffer SkSTArray<3, const GrVkRecycledResource*> descriptorRecycledResources; descriptorRecycledResources.push_back(uniformDS); descriptorRecycledResources.push_back(samplerDS); descriptorRecycledResources.push_back(fUniformBuffer->resource()); // One sampler, texture view, and texture SkSTArray<3, const GrVkResource*> descriptorResources; descriptorResources.push_back(sampler); descriptorResources.push_back(srcTex->textureView(true)); descriptorResources.push_back(srcTex->resource()); cmdBuffer->bindDescriptorSets(gpu, descriptorRecycledResources, descriptorResources, fPipelineLayout, 0, 2, vkDescSets, 0, nullptr); // Set Dynamic viewport and stencil // We always use one viewport the size of the RT VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = SkIntToScalar(rt->width()); viewport.height = SkIntToScalar(rt->height()); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; cmdBuffer->setViewport(gpu, 0, 1, &viewport); // We assume the scissor is not enabled so just set it to the whole RT VkRect2D scissor; scissor.extent.width = rt->width(); scissor.extent.height = rt->height(); scissor.offset.x = 0; scissor.offset.y = 0; cmdBuffer->setScissor(gpu, 0, 1, &scissor); cmdBuffer->bindVertexBuffer(gpu, fVertexBuffer.get()); cmdBuffer->draw(gpu, 4, 1, 0, 0); cmdBuffer->endRenderPass(gpu); // Release all temp resources which should now be reffed by the cmd buffer pipeline->unref(gpu); uniformDS->unref(gpu); samplerDS->unref(gpu); sampler->unref(gpu); renderPass->unref(gpu); return true; } void GrVkCopyManager::destroyResources(GrVkGpu* gpu) { if (VK_NULL_HANDLE != fVertShaderModule) { GR_VK_CALL(gpu->vkInterface(), DestroyShaderModule(gpu->device(), fVertShaderModule, nullptr)); fVertShaderModule = VK_NULL_HANDLE; } if (VK_NULL_HANDLE != fFragShaderModule) { GR_VK_CALL(gpu->vkInterface(), DestroyShaderModule(gpu->device(), fFragShaderModule, nullptr)); fFragShaderModule = VK_NULL_HANDLE; } if (VK_NULL_HANDLE != fPipelineLayout) { GR_VK_CALL(gpu->vkInterface(), DestroyPipelineLayout(gpu->device(), fPipelineLayout, nullptr)); fPipelineLayout = VK_NULL_HANDLE; } if (fUniformBuffer) { fUniformBuffer->release(gpu); fUniformBuffer.reset(); } } void GrVkCopyManager::abandonResources() { fVertShaderModule = VK_NULL_HANDLE; fFragShaderModule = VK_NULL_HANDLE; fPipelineLayout = VK_NULL_HANDLE; if (fUniformBuffer) { fUniformBuffer->abandon(); fUniformBuffer.reset(); } } <commit_msg>Make sure to preserve stencil on vulkan copy as draws<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrVkCopyManager.h" #include "GrSamplerParams.h" #include "GrShaderCaps.h" #include "GrSurface.h" #include "GrTexturePriv.h" #include "GrVkCommandBuffer.h" #include "GrVkCopyPipeline.h" #include "GrVkDescriptorSet.h" #include "GrVkGpu.h" #include "GrVkImageView.h" #include "GrVkRenderTarget.h" #include "GrVkResourceProvider.h" #include "GrVkSampler.h" #include "GrVkTexture.h" #include "GrVkUniformBuffer.h" #include "GrVkVertexBuffer.h" #include "SkPoint.h" #include "SkRect.h" GrVkCopyManager::GrVkCopyManager() : fVertShaderModule(VK_NULL_HANDLE) , fFragShaderModule(VK_NULL_HANDLE) , fPipelineLayout(VK_NULL_HANDLE) {} GrVkCopyManager::~GrVkCopyManager() {} bool GrVkCopyManager::createCopyProgram(GrVkGpu* gpu) { const GrShaderCaps* shaderCaps = gpu->caps()->shaderCaps(); const char* version = shaderCaps->versionDeclString(); SkString vertShaderText(version); vertShaderText.append( "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout(set = 0, binding = 0) uniform vertexUniformBuffer {" "mediump vec4 uPosXform;" "mediump vec4 uTexCoordXform;" "};" "layout(location = 0) in highp vec2 inPosition;" "layout(location = 1) out mediump vec2 vTexCoord;" "// Copy Program VS\n" "void main() {" "vTexCoord = inPosition * uTexCoordXform.xy + uTexCoordXform.zw;" "gl_Position.xy = inPosition * uPosXform.xy + uPosXform.zw;" "gl_Position.zw = vec2(0, 1);" "}" ); SkString fragShaderText(version); fragShaderText.append( "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "precision mediump float;" "layout(set = 1, binding = 0) uniform mediump sampler2D uTextureSampler;" "layout(location = 1) in mediump vec2 vTexCoord;" "layout(location = 0, index = 0) out mediump vec4 fsColorOut;" "// Copy Program FS\n" "void main() {" "fsColorOut = texture(uTextureSampler, vTexCoord);" "}" ); SkSL::Program::Settings settings; SkSL::Program::Inputs inputs; if (!GrCompileVkShaderModule(gpu, vertShaderText.c_str(), VK_SHADER_STAGE_VERTEX_BIT, &fVertShaderModule, &fShaderStageInfo[0], settings, &inputs)) { this->destroyResources(gpu); return false; } SkASSERT(inputs.isEmpty()); if (!GrCompileVkShaderModule(gpu, fragShaderText.c_str(), VK_SHADER_STAGE_FRAGMENT_BIT, &fFragShaderModule, &fShaderStageInfo[1], settings, &inputs)) { this->destroyResources(gpu); return false; } SkASSERT(inputs.isEmpty()); VkDescriptorSetLayout dsLayout[2]; GrVkResourceProvider& resourceProvider = gpu->resourceProvider(); dsLayout[GrVkUniformHandler::kUniformBufferDescSet] = resourceProvider.getUniformDSLayout(); uint32_t samplerVisibility = kFragment_GrShaderFlag; SkTArray<uint32_t> visibilityArray(&samplerVisibility, 1); resourceProvider.getSamplerDescriptorSetHandle(visibilityArray, &fSamplerDSHandle); dsLayout[GrVkUniformHandler::kSamplerDescSet] = resourceProvider.getSamplerDSLayout(fSamplerDSHandle); // Create the VkPipelineLayout VkPipelineLayoutCreateInfo layoutCreateInfo; memset(&layoutCreateInfo, 0, sizeof(VkPipelineLayoutCreateFlags)); layoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; layoutCreateInfo.pNext = 0; layoutCreateInfo.flags = 0; layoutCreateInfo.setLayoutCount = 2; layoutCreateInfo.pSetLayouts = dsLayout; layoutCreateInfo.pushConstantRangeCount = 0; layoutCreateInfo.pPushConstantRanges = nullptr; VkResult err = GR_VK_CALL(gpu->vkInterface(), CreatePipelineLayout(gpu->device(), &layoutCreateInfo, nullptr, &fPipelineLayout)); if (err) { this->destroyResources(gpu); return false; } static const float vdata[] = { 0, 0, 0, 1, 1, 0, 1, 1 }; fVertexBuffer.reset(GrVkVertexBuffer::Create(gpu, sizeof(vdata), false)); SkASSERT(fVertexBuffer.get()); fVertexBuffer->updateData(vdata, sizeof(vdata)); // We use 2 vec4's for uniforms fUniformBuffer.reset(GrVkUniformBuffer::Create(gpu, 8 * sizeof(float))); SkASSERT(fUniformBuffer.get()); return true; } bool GrVkCopyManager::copySurfaceAsDraw(GrVkGpu* gpu, GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { if (!gpu->vkCaps().supportsCopiesAsDraws()) { return false; } GrVkRenderTarget* rt = static_cast<GrVkRenderTarget*>(dst->asRenderTarget()); if (!rt) { return false; } GrVkTexture* srcTex = static_cast<GrVkTexture*>(src->asTexture()); if (!srcTex) { return false; } if (VK_NULL_HANDLE == fVertShaderModule) { SkASSERT(VK_NULL_HANDLE == fFragShaderModule && VK_NULL_HANDLE == fPipelineLayout && nullptr == fVertexBuffer.get() && nullptr == fUniformBuffer.get()); if (!this->createCopyProgram(gpu)) { SkDebugf("Failed to create copy program.\n"); return false; } } GrVkResourceProvider& resourceProv = gpu->resourceProvider(); GrVkCopyPipeline* pipeline = resourceProv.findOrCreateCopyPipeline(rt, fShaderStageInfo, fPipelineLayout); if (!pipeline) { return false; } // UPDATE UNIFORM DESCRIPTOR SET int w = srcRect.width(); int h = srcRect.height(); // dst rect edges in NDC (-1 to 1) int dw = dst->width(); int dh = dst->height(); float dx0 = 2.f * dstPoint.fX / dw - 1.f; float dx1 = 2.f * (dstPoint.fX + w) / dw - 1.f; float dy0 = 2.f * dstPoint.fY / dh - 1.f; float dy1 = 2.f * (dstPoint.fY + h) / dh - 1.f; if (kBottomLeft_GrSurfaceOrigin == dst->origin()) { dy0 = -dy0; dy1 = -dy1; } float sx0 = (float)srcRect.fLeft; float sx1 = (float)(srcRect.fLeft + w); float sy0 = (float)srcRect.fTop; float sy1 = (float)(srcRect.fTop + h); int sh = src->height(); if (kBottomLeft_GrSurfaceOrigin == src->origin()) { sy0 = sh - sy0; sy1 = sh - sy1; } // src rect edges in normalized texture space (0 to 1). int sw = src->width(); sx0 /= sw; sx1 /= sw; sy0 /= sh; sy1 /= sh; float uniData[] = { dx1 - dx0, dy1 - dy0, dx0, dy0, // posXform sx1 - sx0, sy1 - sy0, sx0, sy0 }; // texCoordXform fUniformBuffer->updateData(gpu, uniData, sizeof(uniData), nullptr); const GrVkDescriptorSet* uniformDS = resourceProv.getUniformDescriptorSet(); SkASSERT(uniformDS); VkDescriptorBufferInfo uniBufferInfo; uniBufferInfo.buffer = fUniformBuffer->buffer(); uniBufferInfo.offset = fUniformBuffer->offset(); uniBufferInfo.range = fUniformBuffer->size(); VkWriteDescriptorSet descriptorWrites; descriptorWrites.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites.pNext = nullptr; descriptorWrites.dstSet = uniformDS->descriptorSet(); descriptorWrites.dstBinding = GrVkUniformHandler::kVertexBinding; descriptorWrites.dstArrayElement = 0; descriptorWrites.descriptorCount = 1; descriptorWrites.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrites.pImageInfo = nullptr; descriptorWrites.pBufferInfo = &uniBufferInfo; descriptorWrites.pTexelBufferView = nullptr; GR_VK_CALL(gpu->vkInterface(), UpdateDescriptorSets(gpu->device(), 1, &descriptorWrites, 0, nullptr)); // UPDATE SAMPLER DESCRIPTOR SET const GrVkDescriptorSet* samplerDS = gpu->resourceProvider().getSamplerDescriptorSet(fSamplerDSHandle); GrSamplerParams params(SkShader::kClamp_TileMode, GrSamplerParams::kNone_FilterMode); GrVkSampler* sampler = resourceProv.findOrCreateCompatibleSampler(params, srcTex->texturePriv().maxMipMapLevel()); VkDescriptorImageInfo imageInfo; memset(&imageInfo, 0, sizeof(VkDescriptorImageInfo)); imageInfo.sampler = sampler->sampler(); imageInfo.imageView = srcTex->textureView(true)->imageView(); imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkWriteDescriptorSet writeInfo; memset(&writeInfo, 0, sizeof(VkWriteDescriptorSet)); writeInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeInfo.pNext = nullptr; writeInfo.dstSet = samplerDS->descriptorSet(); writeInfo.dstBinding = 0; writeInfo.dstArrayElement = 0; writeInfo.descriptorCount = 1; writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeInfo.pImageInfo = &imageInfo; writeInfo.pBufferInfo = nullptr; writeInfo.pTexelBufferView = nullptr; GR_VK_CALL(gpu->vkInterface(), UpdateDescriptorSets(gpu->device(), 1, &writeInfo, 0, nullptr)); VkDescriptorSet vkDescSets[] = { uniformDS->descriptorSet(), samplerDS->descriptorSet() }; GrVkRenderTarget* texRT = static_cast<GrVkRenderTarget*>(srcTex->asRenderTarget()); if (texRT) { gpu->onResolveRenderTarget(texRT); } GrVkPrimaryCommandBuffer* cmdBuffer = gpu->currentCommandBuffer(); // TODO: Make tighter bounds and then adjust bounds for origin and granularity if we see // any perf issues with using the whole bounds SkIRect bounds = SkIRect::MakeWH(rt->width(), rt->height()); // Change layouts of rt and texture GrVkImage* targetImage = rt->msaaImage() ? rt->msaaImage() : rt; targetImage->setImageLayout(gpu, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, false); srcTex->setImageLayout(gpu, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, false); GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_STORE); GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE); const GrVkRenderPass* renderPass; const GrVkResourceProvider::CompatibleRPHandle& rpHandle = rt->compatibleRenderPassHandle(); if (rpHandle.isValid()) { renderPass = gpu->resourceProvider().findRenderPass(rpHandle, vkColorOps, vkStencilOps); } else { renderPass = gpu->resourceProvider().findRenderPass(*rt, vkColorOps, vkStencilOps); } SkASSERT(renderPass->isCompatible(*rt->simpleRenderPass())); cmdBuffer->beginRenderPass(gpu, renderPass, nullptr, *rt, bounds, false); cmdBuffer->bindPipeline(gpu, pipeline); // Uniform DescriptorSet, Sampler DescriptorSet, and vertex shader uniformBuffer SkSTArray<3, const GrVkRecycledResource*> descriptorRecycledResources; descriptorRecycledResources.push_back(uniformDS); descriptorRecycledResources.push_back(samplerDS); descriptorRecycledResources.push_back(fUniformBuffer->resource()); // One sampler, texture view, and texture SkSTArray<3, const GrVkResource*> descriptorResources; descriptorResources.push_back(sampler); descriptorResources.push_back(srcTex->textureView(true)); descriptorResources.push_back(srcTex->resource()); cmdBuffer->bindDescriptorSets(gpu, descriptorRecycledResources, descriptorResources, fPipelineLayout, 0, 2, vkDescSets, 0, nullptr); // Set Dynamic viewport and stencil // We always use one viewport the size of the RT VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = SkIntToScalar(rt->width()); viewport.height = SkIntToScalar(rt->height()); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; cmdBuffer->setViewport(gpu, 0, 1, &viewport); // We assume the scissor is not enabled so just set it to the whole RT VkRect2D scissor; scissor.extent.width = rt->width(); scissor.extent.height = rt->height(); scissor.offset.x = 0; scissor.offset.y = 0; cmdBuffer->setScissor(gpu, 0, 1, &scissor); cmdBuffer->bindVertexBuffer(gpu, fVertexBuffer.get()); cmdBuffer->draw(gpu, 4, 1, 0, 0); cmdBuffer->endRenderPass(gpu); // Release all temp resources which should now be reffed by the cmd buffer pipeline->unref(gpu); uniformDS->unref(gpu); samplerDS->unref(gpu); sampler->unref(gpu); renderPass->unref(gpu); return true; } void GrVkCopyManager::destroyResources(GrVkGpu* gpu) { if (VK_NULL_HANDLE != fVertShaderModule) { GR_VK_CALL(gpu->vkInterface(), DestroyShaderModule(gpu->device(), fVertShaderModule, nullptr)); fVertShaderModule = VK_NULL_HANDLE; } if (VK_NULL_HANDLE != fFragShaderModule) { GR_VK_CALL(gpu->vkInterface(), DestroyShaderModule(gpu->device(), fFragShaderModule, nullptr)); fFragShaderModule = VK_NULL_HANDLE; } if (VK_NULL_HANDLE != fPipelineLayout) { GR_VK_CALL(gpu->vkInterface(), DestroyPipelineLayout(gpu->device(), fPipelineLayout, nullptr)); fPipelineLayout = VK_NULL_HANDLE; } if (fUniformBuffer) { fUniformBuffer->release(gpu); fUniformBuffer.reset(); } } void GrVkCopyManager::abandonResources() { fVertShaderModule = VK_NULL_HANDLE; fFragShaderModule = VK_NULL_HANDLE; fPipelineLayout = VK_NULL_HANDLE; if (fUniformBuffer) { fUniformBuffer->abandon(); fUniformBuffer.reset(); } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ #include "AliAnalysisTaskDiJets.h" #include "AliAODEvent.h" #include "AliAODJet.h" #include "AliAODDiJet.h" #include <TClonesArray.h> #include <TLorentzVector.h> ClassImp(AliAnalysisTaskDiJets) //////////////////////////////////////////////////////////////////////// AliAnalysisTaskDiJets::AliAnalysisTaskDiJets(): AliAnalysisTaskSE(), fDiJets(0), fDiJetsIn(0) { // Default constructor } AliAnalysisTaskDiJets::AliAnalysisTaskDiJets(const char* name): AliAnalysisTaskSE(name), fDiJets(0), fDiJetsIn(0) { // Default constructor } void AliAnalysisTaskDiJets::UserCreateOutputObjects() { // Create the output container // if (fDebug > 1) printf("AnalysisTaskDiJets::CreateOutPutData() \n"); fDiJets = new TClonesArray("AliAODDiJet", 0); fDiJets->SetName("Dijets"); AddAODBranch("TClonesArray", &fDiJets); } void AliAnalysisTaskDiJets::Init() { // Initialization if (fDebug > 1) printf("AnalysisTaskDiJets::Init() \n"); } void AliAnalysisTaskDiJets::UserExec(Option_t */*option*/) { // Execute analysis for current event // fDiJets->Delete(); AliAODEvent* aod = dynamic_cast<AliAODEvent*> (InputEvent()); TClonesArray* jets = aod->GetJets(); fDiJetsIn = (TClonesArray*) (aod->GetList()->FindObject("Dijets")); if (fDiJetsIn) { printf("Found %d dijets in old list \n", fDiJetsIn->GetEntries()); AliAODJet* jj1, *jj2; AliAODDiJet* testJ; if (fDiJetsIn->GetEntries() > 0) { testJ = (AliAODDiJet*) (fDiJetsIn->At(0)); jj1 = testJ->Jet(0); jj1->Print(""); jj2 = testJ->Jet(1); jj2->Print(""); } } Int_t nj = jets->GetEntriesFast(); printf("There are %5d jets in the event \n", nj); if (nj > 1) { AliAODJet* jet1 = (AliAODJet*) (jets->At(0)); TLorentzVector v1 = *(jet1->MomentumVector()); AliAODJet* jet2 = (AliAODJet*) (jets->At(1)); TLorentzVector v2 = *(jet2->MomentumVector()); TLorentzVector v = v1 + v2; Int_t ndi = fDiJets->GetEntriesFast(); TClonesArray &lref = *fDiJets; new(lref[ndi]) AliAODDiJet(v);; AliAODDiJet* dijet = (AliAODDiJet*) (fDiJets->At(ndi)); dijet->SetJetRefs(jet1, jet2); } } void AliAnalysisTaskDiJets::Terminate(Option_t */*option*/) { // Terminate analysis // if (fDebug > 1) printf("AnalysisDiJets: Terminate() \n"); } <commit_msg>Take into account > 2 jets per event. (D. Perrino)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ #include "AliAnalysisTaskDiJets.h" #include "AliAODEvent.h" #include "AliAODJet.h" #include "AliAODDiJet.h" #include <TClonesArray.h> #include <TLorentzVector.h> ClassImp(AliAnalysisTaskDiJets) //////////////////////////////////////////////////////////////////////// AliAnalysisTaskDiJets::AliAnalysisTaskDiJets(): AliAnalysisTaskSE(), fDiJets(0), fDiJetsIn(0) { // Default constructor } AliAnalysisTaskDiJets::AliAnalysisTaskDiJets(const char* name): AliAnalysisTaskSE(name), fDiJets(0), fDiJetsIn(0) { // Default constructor } void AliAnalysisTaskDiJets::UserCreateOutputObjects() { // Create the output container // if (fDebug > 1) printf("AnalysisTaskDiJets::CreateOutPutData() \n"); fDiJets = new TClonesArray("AliAODDiJet", 0); fDiJets->SetName("Dijets"); AddAODBranch("TClonesArray", &fDiJets); } void AliAnalysisTaskDiJets::Init() { // Initialization if (fDebug > 1) printf("AnalysisTaskDiJets::Init() \n"); } void AliAnalysisTaskDiJets::UserExec(Option_t */*option*/) { // Execute analysis for current event // fDiJets->Delete(); AliAODEvent* aod = dynamic_cast<AliAODEvent*> (InputEvent()); TClonesArray* jets = aod->GetJets(); fDiJetsIn = (TClonesArray*) (aod->GetList()->FindObject("Dijets")); if (fDiJetsIn) { printf("Found %d dijets in old list \n", fDiJetsIn->GetEntries()); AliAODJet* jj1, *jj2; AliAODDiJet* testJ; if (fDiJetsIn->GetEntries() > 0) { testJ = (AliAODDiJet*) (fDiJetsIn->At(0)); jj1 = testJ->Jet(0); jj1->Print(""); jj2 = testJ->Jet(1); jj2->Print(""); } } Int_t nj = jets->GetEntriesFast(); printf("There are %5d jets in the event \n", nj); if (nj > 1) { for (Int_t iJet1=0; iJet1<nj; iJet1++){ AliAODJet* jet1 = (AliAODJet*) (jets->At(iJet1)); TLorentzVector v1 = *(jet1->MomentumVector()); for (Int_t iJet2=iJet1+1; iJet2<nj; iJet2++){ AliAODJet* jet2 = (AliAODJet*) (jets->At(iJet2)); TLorentzVector v2 = *(jet2->MomentumVector()); TLorentzVector v = v1 + v2; Int_t ndi = fDiJets->GetEntriesFast(); TClonesArray &lref = *fDiJets; new(lref[ndi]) AliAODDiJet(v);; AliAODDiJet* dijet = (AliAODDiJet*) (fDiJets->At(ndi)); dijet->SetJetRefs(jet1, jet2); } } } } void AliAnalysisTaskDiJets::Terminate(Option_t */*option*/) { // Terminate analysis // if (fDebug > 1) printf("AnalysisDiJets: Terminate() \n"); } <|endoftext|>
<commit_before>#include "FunctionNameMangler.h" #include <boost/algorithm/string.hpp> #include <llvm/IR/IRBuilder.h> namespace Helen { string FunctionNameMangler::mangleName(string name, vector<Type*> args, string style, string className) { if(style == "C") return name; if(style == "Helen") { string cls = !className.empty() ? className + "-" : ""; string mangledName = "_" + cls + name; if(args.empty()) mangledName += "_v"; for(Type* t : args) { mangledName += "_"; if(t->isArrayTy()) { mangledName += "a"; t = t->getArrayElementType(); } if(t->isPointerTy()) { PointerType* pt = (PointerType*)t; Type* et = pt->getElementType(); if(et->isStructTy()) { mangledName += "type." + string(((StructType*)et)->getName()); } else { mangledName += "p"; t = et; } } if(t == Type::getInt64Ty(getGlobalContext())) mangledName += "i"; if(t == Type::getDoubleTy(getGlobalContext())) mangledName += "r"; if(t == Type::getInt8Ty(getGlobalContext())) mangledName += "c"; if(t == Type::getInt8PtrTy(getGlobalContext())) mangledName += "s"; } return mangledName; } return ""; // error } string FunctionNameMangler::humanReadableName(string mangledName) { if(mangledName[0] != '_') return mangledName; string name = ""; mangledName = mangledName.substr(1); const int BUILTIN_UNDERSCORES = 2; if(mangledName[1] == '_') { mangledName = mangledName.substr(BUILTIN_UNDERSCORES); name = "<built-in> "; } vector<string> strs; boost::split(strs, mangledName, boost::is_any_of("_")); name = strs[0] + "("; for(int i = 1; i < strs.size(); i++) { if(strs[i][0] == 'v') { name += "array "; strs[i] = strs[i].substr(1); } if(strs[i] == "i") name += "int"; if(strs[i] == "r") name += "real"; if(strs[i] == "c") name += "char"; if(strs[i] == "s") name += "string"; if(strs[i] == "v") name += "no arguments"; if(i < strs.size() - 1) name += ", "; } name += ")"; return name; } } <commit_msg>changed name mangler's behavior<commit_after>#include "FunctionNameMangler.h" #include <boost/algorithm/string.hpp> #include <llvm/IR/IRBuilder.h> namespace Helen { string FunctionNameMangler::mangleName(string name, vector<Type*> args, string style, string className) { if(style == "C") return name; if(style == "Helen") { string cls = !className.empty() ? className + "-" : ""; string mangledName = "_" + cls + name; if(args.empty()) mangledName += "_v"; for(Type* t : args) { mangledName += "_"; if(t->isArrayTy()) { mangledName += "a"; t = t->getArrayElementType(); } if(t->isPointerTy()) { PointerType* pt = (PointerType*)t; Type* et = pt->getElementType(); if(et->isStructTy()) { mangledName += "type." + string(((StructType*)et)->getName()); } else { mangledName += "p"; t = et; } } if(t->isIntegerTy()) mangledName += "i" + std::to_string(t->getPrimitiveSizeInBits()); if(t == Type::getDoubleTy(getGlobalContext())) mangledName += "r"; if(t == Type::getInt8PtrTy(getGlobalContext())) mangledName += "s"; } return mangledName; } return ""; // error } string FunctionNameMangler::humanReadableName(string mangledName) { if(mangledName[0] != '_') return mangledName; string name = ""; mangledName = mangledName.substr(1); const int BUILTIN_UNDERSCORES = 2; if(mangledName[1] == '_') { mangledName = mangledName.substr(BUILTIN_UNDERSCORES); name = "<built-in> "; } vector<string> strs; boost::split(strs, mangledName, boost::is_any_of("_")); name = strs[0] + "("; for(int i = 1; i < strs.size(); i++) { if(strs[i][0] == 'v') { name += "array "; strs[i] = strs[i].substr(1); } if(strs[i][0] == 'i') name += "int"; if(strs[i] == "r") name += "real"; if(strs[i] == "s") name += "string"; if(strs[i] == "v") name += "no arguments"; if(i < strs.size() - 1) name += ", "; } name += ")"; return name; } } <|endoftext|>
<commit_before>#include "userselect.h" #include "newuser.h" #include <vector> #include <QVBoxLayout> #include <QtWidgets> #include "newuser.h" UserSelect::UserSelect(QStackedWidget *pages_in, std::vector<User*> users_in, LogIn* parent_in) { QFrame(); pages = pages_in; users = users_in; parent = parent_in; QVBoxLayout* layout = new QVBoxLayout(); QHBoxLayout* topBar = new QHBoxLayout(); QPushButton* backButton = new QPushButton("Back"); connect(backButton, SIGNAL(clicked()), this, SLOT(goBackCallback())); QLabel* title = new QLabel("Current Users"); QFont naxa, naxa2, naxa3; QFontDatabase db; naxa = db.font("Nexa Light","Normal", 64); naxa2= db.font("Nexa Light", "Normal", 18); naxa3= db.font("Nexa Light", "Normal", 24); title->setFont(naxa); title->setMaximumHeight(70); backButton->setFont(naxa2); backButton->setMinimumWidth(100); topBar->addWidget(backButton, 0, Qt::AlignLeft); topBar->addSpacerItem(new QSpacerItem((title->width()/2), title->height(),QSizePolicy::Expanding)); topBar->addWidget(title, 0, Qt::AlignHCenter); topBar->addSpacerItem(new QSpacerItem((title->width()/2), title->height(), QSizePolicy::Expanding)); topBar->setAlignment(layout, Qt::AlignTop); layout->addLayout(topBar); QSplitter *splitter = new QSplitter(); QFrame *rightWidget = new QFrame(); rightWidget->setLayout(layout); rightWidget->setStyleSheet("QFrame { background-color: rgb(191, 197, 255); }"); QScrollArea *scrollArea = new QScrollArea(); scrollArea->setWidgetResizable(1); scrollArea->setWidget(rightWidget); splitter->addWidget(scrollArea); QGridLayout *lay = new QGridLayout(); lay->addWidget(splitter); this->setLayout(lay); userButtons = new QButtonGroup(); connect(userButtons, SIGNAL(buttonClicked(int)), this, SLOT(openClickedUser(int))); for(int i=0; i < users.size(); i++){ QPushButton *btn = new QPushButton(users.at(i)->username.toStdString().c_str()); btn->setMinimumSize(250,75); btn->setMaximumSize(300,100); btn->setStyleSheet("background-color: rgb(250,236,191);"); btn->setFont(naxa3); userButtons->addButton(btn); userButtons->setId(btn,i); layout->addWidget(btn, 0, Qt::AlignHCenter); } QPushButton* newUserButton = new QPushButton("Create New User"); connect(newUserButton, SIGNAL(clicked()), this, SLOT(newUserCallback())); newUserButton->setMinimumSize(250,75); newUserButton->setMaximumSize(300,100); newUserButton->setFont(naxa3); layout->addWidget(newUserButton, 0, Qt::AlignHCenter); } UserSelect::~UserSelect(){} void UserSelect::goBackCallback() { int index = pages->currentIndex(); pages->removeWidget(this); pages->setCurrentIndex(index - 1); } void UserSelect::newUserCallback() { //pages->removeWidget(this); int index = pages->addWidget(new NewUser(pages, parent, this)); pages->setCurrentIndex(index); } void UserSelect::openClickedUser(int id) { users[id]->goToDecksView(pages); } void UserSelect::updateUserSelect() { UserSelect* refreshed = new UserSelect(this->pages, parent->curUsers, this->parent); pages->removeWidget(this); int index = pages->addWidget(refreshed); pages->setCurrentIndex(index); } <commit_msg>only user section scrolls, used to scroll whole w<commit_after>#include "userselect.h" #include "newuser.h" #include <vector> #include <QVBoxLayout> #include <QtWidgets> #include "newuser.h" UserSelect::UserSelect(QStackedWidget *pages_in, std::vector<User*> users_in, LogIn* parent_in) { QFrame(); pages = pages_in; users = users_in; parent = parent_in; QVBoxLayout* layout = new QVBoxLayout(); QHBoxLayout* topBar = new QHBoxLayout(); QPushButton* backButton = new QPushButton("Back"); connect(backButton, SIGNAL(clicked()), this, SLOT(goBackCallback())); QLabel* title = new QLabel("Current Users"); QFont naxa, naxa2, naxa3; QFontDatabase db; naxa = db.font("Nexa Light","Normal", 64); naxa2= db.font("Nexa Light", "Normal", 18); naxa3= db.font("Nexa Light", "Normal", 24); title->setFont(naxa); title->setMaximumHeight(70); backButton->setFont(naxa2); backButton->setMinimumWidth(100); topBar->addWidget(backButton, 0, Qt::AlignLeft); topBar->addSpacerItem(new QSpacerItem((title->width()/2), title->height(),QSizePolicy::Expanding)); topBar->addWidget(title, 0, Qt::AlignHCenter); topBar->addSpacerItem(new QSpacerItem((title->width()/2), title->height(), QSizePolicy::Expanding)); topBar->setAlignment(layout, Qt::AlignTop); //layout->addLayout(topBar); QWidget *userList = new QWidget(); userList->setLayout(layout); QScrollArea *scrollArea = new QScrollArea(); scrollArea->setWidgetResizable(true); scrollArea->setWidget(userList); QVBoxLayout *lay = new QVBoxLayout(); lay->addSpacing(10); lay->addLayout(topBar); lay->addSpacing(40); lay->addWidget(scrollArea); this->setLayout(lay); this->setStyleSheet("QFrame { background-color: rgb(191, 197, 255); }"); scrollArea->setStyleSheet("background-color:rgb(191,197,255);"); userButtons = new QButtonGroup(); connect(userButtons, SIGNAL(buttonClicked(int)), this, SLOT(openClickedUser(int))); for(int i=0; i < users.size(); i++){ QPushButton *btn = new QPushButton(users.at(i)->username.toStdString().c_str()); btn->setMinimumSize(250,75); btn->setMaximumSize(300,100); btn->setStyleSheet("background-color: rgb(250,236,191);"); btn->setFont(naxa3); userButtons->addButton(btn); userButtons->setId(btn,i); layout->addWidget(btn, 0, Qt::AlignHCenter); } QPushButton* newUserButton = new QPushButton("Create New User"); connect(newUserButton, SIGNAL(clicked()), this, SLOT(newUserCallback())); newUserButton->setMinimumSize(250,75); newUserButton->setMaximumSize(300,100); newUserButton->setFont(naxa3); newUserButton->setStyleSheet("background-color: rgb(240,240,200);"); layout->addWidget(newUserButton, 0, Qt::AlignHCenter); } UserSelect::~UserSelect(){} void UserSelect::goBackCallback() { int index = pages->currentIndex(); pages->removeWidget(this); pages->setCurrentIndex(index - 1); } void UserSelect::newUserCallback() { //pages->removeWidget(this); int index = pages->addWidget(new NewUser(pages, parent, this)); pages->setCurrentIndex(index); } void UserSelect::openClickedUser(int id) { users[id]->goToDecksView(pages); } void UserSelect::updateUserSelect() { UserSelect* refreshed = new UserSelect(this->pages, parent->curUsers, this->parent); pages->removeWidget(this); int index = pages->addWidget(refreshed); pages->setCurrentIndex(index); } <|endoftext|>
<commit_before>// Copyright (c) 2014, Salesforce.com, 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 Salesforce.com nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <cstddef> #include <cstdint> #include <cstdlib> #include <limits> #include <new> #include <distributions/common.hpp> #if __GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 7 #define DIST_ASSUME_ALIGNED_TO(data, alignment) \ (decltype(data))__builtin_assume_aligned((data), (alignment)) #else #define DIST_ASSUME_ALIGNED_TO(data, alignment) (data) #endif #define DIST_ASSUME_ALIGNED(data) \ (DIST_ASSUME_ALIGNED_TO((data), ::distributions::default_alignment)) #define DIST_ASSERT_ALIGNED_TO(data, alignment) { \ decltype((data)) base = nullptr; \ const size_t mask = (alignment) - 1UL; \ const size_t offset = ((data) - base) & mask; \ DIST_ASSERT(offset == 0, \ "expected " << (alignment) << "-byte-aligned data," \ "actual offset = " << offset); \ } #define DIST_ASSERT_ALIGNED(data) \ { DIST_ASSERT_ALIGNED_TO((data), ::distributions::default_alignment); } namespace distributions { // sse instructions require alignment of 16 bytes // avx instructions require alignment of 32 bytes static const size_t default_alignment = 32; template<class T, size_t alignment = default_alignment> class aligned_allocator { public: typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T * pointer; typedef const T * const_pointer; typedef T & reference; typedef const T & const_reference; template <class U> aligned_allocator (const aligned_allocator<U, alignment> &) throw() {} aligned_allocator (const aligned_allocator &) throw() {} aligned_allocator () throw() {} ~aligned_allocator () throw() {} template<class U> struct rebind { typedef aligned_allocator<U, alignment> other; }; pointer address (reference r) const { return & r; } const_pointer address (const_reference r) const { return & r; } pointer allocate (size_t n, const void * /* hint */ = 0) { void * result = nullptr; if (posix_memalign(& result, alignment, n * sizeof(T))) { throw std::bad_alloc(); } if (DIST_DEBUG_LEVEL >= 3) { DIST_ASSERT_ALIGNED_TO(static_cast<pointer>(result), alignment); } return static_cast<pointer>(result); } void deallocate (pointer p, size_type /* count */ ) { free(p); } void construct (pointer p, const T & val) { new (p) T(val); } void destroy (pointer p) { p->~T(); } size_type max_size () const throw() { return std::numeric_limits<size_t>::max() / sizeof(T); } }; template<class T1, class T2> inline bool operator== ( const aligned_allocator<T1> &, const aligned_allocator<T2> &) throw() { return true; } template<class T1, class T2> inline bool operator!= ( const aligned_allocator<T1> &, const aligned_allocator<T2> &) throw() { return false; } } // namespace distributions <commit_msg>Fix DIST_ASSERT_ALIGNED_TO<commit_after>// Copyright (c) 2014, Salesforce.com, 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 Salesforce.com nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <cstddef> #include <cstdint> #include <cstdlib> #include <limits> #include <new> #include <distributions/common.hpp> #if __GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 7 #define DIST_ASSUME_ALIGNED_TO(data, alignment) \ (decltype(data))__builtin_assume_aligned((data), (alignment)) #else #define DIST_ASSUME_ALIGNED_TO(data, alignment) (data) #endif #define DIST_ASSUME_ALIGNED(data) \ (DIST_ASSUME_ALIGNED_TO((data), ::distributions::default_alignment)) #define DIST_ASSERT_ALIGNED_TO(data, alignment) { \ size_t mask = (alignment) - 1UL; \ size_t offset = reinterpret_cast<size_t>(data) & mask; \ DIST_ASSERT(offset == 0, \ "expected " << (alignment) << "-byte-aligned data," \ "actual offset = " << offset); \ } #define DIST_ASSERT_ALIGNED(data) \ { DIST_ASSERT_ALIGNED_TO((data), ::distributions::default_alignment); } namespace distributions { // sse instructions require alignment of 16 bytes // avx instructions require alignment of 32 bytes static const size_t default_alignment = 32; template<class T, size_t alignment = default_alignment> class aligned_allocator { public: typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T * pointer; typedef const T * const_pointer; typedef T & reference; typedef const T & const_reference; template <class U> aligned_allocator (const aligned_allocator<U, alignment> &) throw() {} aligned_allocator (const aligned_allocator &) throw() {} aligned_allocator () throw() {} ~aligned_allocator () throw() {} template<class U> struct rebind { typedef aligned_allocator<U, alignment> other; }; pointer address (reference r) const { return & r; } const_pointer address (const_reference r) const { return & r; } pointer allocate (size_t n, const void * /* hint */ = 0) { void * result = nullptr; if (posix_memalign(& result, alignment, n * sizeof(T))) { throw std::bad_alloc(); } if (DIST_DEBUG_LEVEL >= 3) { DIST_ASSERT_ALIGNED_TO(static_cast<pointer>(result), alignment); } return static_cast<pointer>(result); } void deallocate (pointer p, size_type /* count */ ) { free(p); } void construct (pointer p, const T & val) { new (p) T(val); } void destroy (pointer p) { p->~T(); } size_type max_size () const throw() { return std::numeric_limits<size_t>::max() / sizeof(T); } }; template<class T1, class T2> inline bool operator== ( const aligned_allocator<T1> &, const aligned_allocator<T2> &) throw() { return true; } template<class T1, class T2> inline bool operator!= ( const aligned_allocator<T1> &, const aligned_allocator<T2> &) throw() { return false; } } // namespace distributions <|endoftext|>
<commit_before>/** * Copyright (C) 2015 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <gtest/gtest.h> #include <repo/manipulator/modeloptimizer/repo_optimizer_multipart.h> using namespace repo::manipulator::modeloptimizer; TEST(MultipartOptimizer, ConstructorTest) { MultipartOptimizer(); } TEST(MultipartOptimizer, DeconstructorTest) { auto ptr = new TransformationReductionOptimizer(); delete ptr; } TEST(MultipartOptimizer, ApplyOptimizationTest) { auto opt = TransformationReductionOptimizer(); repo::core::model::RepoScene *empty = nullptr; repo::core::model::RepoScene *empty2 = new repo::core::model::RepoScene(); EXPECT_FALSE(opt.apply(empty)); EXPECT_FALSE(opt.apply(empty2)); //FIXME: to finish. need to construct a scene to test this properly. } <commit_msg>ISSUE #352 fixes<commit_after>/** * Copyright (C) 2015 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <gtest/gtest.h> #include <repo/manipulator/modeloptimizer/repo_optimizer_multipart.h> using namespace repo::manipulator::modeloptimizer; TEST(MultipartOptimizer, ConstructorTest) { MultipartOptimizer(); } TEST(MultipartOptimizer, DeconstructorTest) { auto ptr = new MultipartOptimizer(); delete ptr; } TEST(MultipartOptimizer, ApplyOptimizationTestEmpty) { auto opt = MultipartOptimizer(); repo::core::model::RepoScene *empty = nullptr; repo::core::model::RepoScene *empty2 = new repo::core::model::RepoScene(); EXPECT_FALSE(opt.apply(empty)); EXPECT_FALSE(opt.apply(empty2)); } TEST(MultipartOptimizer, TestAllMerged) { } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Andreas Fett. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <cassert> #include <cstring> #include "parser-impl.h" #include "error.h" #include "token-stream.h" #include "utf8stream.h" namespace { template <typename State> struct Transition { const char *match; State state; }; template <typename T> class StateEngine : public T { public: StateEngine(Json::TokenStream & tokenizer_, size_t depth) : T(tokenizer_, depth) { } Json::Value parse() { typename T::State state(T::SSTART); do { T::tokenizer.scan(); typename T::State nstate( transition(T::tokenizer.token.type, state)); if (nstate == T::SERROR) { T::throw_error(state); JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } T::build(nstate); state = nstate; } while (state != T::SEND); return T::result; } private: typename T::State transition(Json::Token::Type token, typename T::State state) const { for (size_t t(0); t < T::SMAX; ++t) { if (is_match(token, T::transitions[state][t].match)) { return T::transitions[state][t].state; } } return T::SERROR; } bool is_match(Json::Token::Type token, const char *match) const { return !match || (!match[0] && token == Json::Token::END) || strchr(match, token); } }; class ParserState { protected: ParserState(Json::TokenStream & tokenizer_, size_t depth) : tokenizer(tokenizer_), depth_(depth + 1) { if (depth > 255) { JSONCC_THROW(PARSER_OVERFLOW); } } Json::Value parse_value(); Json::TokenStream & tokenizer; private: size_t depth_; }; class ArrayState : public ParserState { protected: ArrayState(Json::TokenStream & tokenizer_, size_t depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SVALUE, SNEXT, SEND, SMAX, }; void build(State state) { switch (state) { case SVALUE: result << parse_value(); break; case SNEXT: break; case SEND: break; case SMAX: assert(false); // LCOV_EXCL_LINE case SERROR: assert(false); // LCOV_EXCL_LINE case SSTART: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_ARRAY_START); case SVALUE: JSONCC_THROW(BAD_TOKEN_ARRAY_VALUE); case SNEXT: JSONCC_THROW(BAD_TOKEN_ARRAY_NEXT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } Json::Array result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<ArrayState::State> ArrayState::transitions[SMAX][SMAX] = { /* SERROR */ { {0, SERROR}}, /* SSTART */ {{"[{tfn\"0", SVALUE}, {"]", SEND}, {0, SERROR}}, /* SVALUE */ {{",", SNEXT}, {"]", SEND}, {0, SERROR}}, /* SNEXT */ {{"[{tfn\"0", SVALUE}, {"]", SEND}, {0, SERROR}}, /* SEND */ { {0, SERROR}}, }; class ObjectState : public ParserState { protected: ObjectState(Json::TokenStream & tokenizer_, size_t depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SNAME, SSEP, SVALUE, SNEXT, SEND, SMAX, }; void build(State state) { switch (state) { case SNAME: key = tokenizer.token.str_value; break; case SVALUE: result << Json::Member(key, parse_value()); break; case SNEXT: break; case SEND: break; case SSEP: break; case SERROR: assert(false); // LCOV_EXCL_LINE case SSTART: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_OBJECT_START); case SNAME: JSONCC_THROW(BAD_TOKEN_OBJECT_NAME); case SSEP: JSONCC_THROW(BAD_TOKEN_OBJECT_SEP); case SVALUE: JSONCC_THROW(BAD_TOKEN_OBJECT_VALUE); case SNEXT: JSONCC_THROW(BAD_TOKEN_OBJECT_NEXT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } std::string key; Json::Object result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<ObjectState::State> ObjectState::transitions[SMAX][SMAX] = { /* SO_ERROR */ { {0, SERROR}}, /* SO_START */ {{"\"", SNAME}, {"}", SEND}, {0, SERROR}}, /* SO_NAME */ {{":", SSEP}, {0, SERROR}}, /* SO_SEP */ {{"[{tfn\"0", SVALUE}, {0, SERROR}}, /* SO_VALUE */ {{",", SNEXT}, {"}", SEND}, {0, SERROR}}, /* SO_NEXT */ {{"\"", SNAME}, {0, SERROR}}, /* SO_END */ { {0, SERROR}}, }; class DocState : public ParserState { protected: DocState(Json::TokenStream & tokenizer_, size_t & depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SVALUE, SEND, SMAX, }; void build(State state) { switch (state) { case SVALUE: result = parse_value(); break; case SEND: break; case SSTART: assert(false); // LCOV_EXCL_LINE case SERROR: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_DOCUMENT); case SVALUE: JSONCC_THROW(BAD_TOKEN_DOCUMENT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } Json::Value result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<DocState::State> DocState::transitions[SMAX][SMAX] = { /* SERROR */ { {0, SERROR}}, /* SSTART */ {{"[{", SVALUE}, {"", SEND}, {0, SERROR}}, /* SVALUE */ { {"", SEND}, {0, SERROR}}, /* SEND */ { {0, SERROR}}, }; Json::Value ParserState::parse_value() { switch (tokenizer.token.type) { case Json::Token::TRUE_LITERAL: return Json::True(); case Json::Token::FALSE_LITERAL: return Json::False(); case Json::Token::NULL_LITERAL: return Json::Null(); case Json::Token::STRING: return tokenizer.token.str_value; case Json::Token::NUMBER: if (tokenizer.token.number_type == Json::Token::FLOAT) { return Json::Number(tokenizer.token.float_value); } else { return Json::Number(tokenizer.token.int_value); } break; case Json::Token::BEGIN_ARRAY: return StateEngine<ArrayState>(tokenizer, depth_).parse(); case Json::Token::BEGIN_OBJECT: return StateEngine<ObjectState>(tokenizer, depth_).parse(); case Json::Token::END: assert(false); // LCOV_EXCL_LINE case Json::Token::INVALID: assert(false); // LCOV_EXCL_LINE case Json::Token::END_ARRAY: assert(false); // LCOV_EXCL_LINE case Json::Token::END_OBJECT: assert(false); // LCOV_EXCL_LINE case Json::Token::NAME_SEPARATOR: assert(false); // LCOV_EXCL_LINE case Json::Token::VALUE_SEPARATOR: assert(false); // LCOV_EXCL_LINE } JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE return Json::Value(); } } namespace Json { Value ParserImpl::parse(char const * data, size_t size) { Utf8Stream utf8stream(data, size); TokenStream tokenizer(utf8stream); try { return StateEngine<DocState>(tokenizer, 0).parse(); } catch (Error & e) { throw; } } } <commit_msg>Parser: move error handling to transition<commit_after>/* Copyright (c) 2015, Andreas Fett. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <cassert> #include <cstring> #include "parser-impl.h" #include "error.h" #include "token-stream.h" #include "utf8stream.h" namespace { template <typename State> struct Transition { const char *match; State state; }; template <typename T> class StateEngine : public T { public: StateEngine(Json::TokenStream & tokenizer_, size_t depth) : T(tokenizer_, depth) { } Json::Value parse() { typename T::State state(T::SSTART); do { T::tokenizer.scan(); state = transition(T::tokenizer.token.type, state); } while (state != T::SEND); return T::result; } private: typename T::State transition(Json::Token::Type token, typename T::State state) { for (size_t t(0); t < T::SMAX; ++t) { if (!is_match(token, T::transitions[state][t].match)) { continue; } typename T::State nstate(T::transitions[state][t].state); if (nstate == T::SERROR) { T::throw_error(state); JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } else { T::build(nstate); } return nstate; } return T::SERROR; } bool is_match(Json::Token::Type token, const char *match) const { return !match || (!match[0] && token == Json::Token::END) || strchr(match, token); } }; class ParserState { protected: ParserState(Json::TokenStream & tokenizer_, size_t depth) : tokenizer(tokenizer_), depth_(depth + 1) { if (depth > 255) { JSONCC_THROW(PARSER_OVERFLOW); } } Json::Value parse_value(); Json::TokenStream & tokenizer; private: size_t depth_; }; class ArrayState : public ParserState { protected: ArrayState(Json::TokenStream & tokenizer_, size_t depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SVALUE, SNEXT, SEND, SMAX, }; void build(State state) { switch (state) { case SVALUE: result << parse_value(); break; case SNEXT: break; case SEND: break; case SMAX: assert(false); // LCOV_EXCL_LINE case SERROR: assert(false); // LCOV_EXCL_LINE case SSTART: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_ARRAY_START); case SVALUE: JSONCC_THROW(BAD_TOKEN_ARRAY_VALUE); case SNEXT: JSONCC_THROW(BAD_TOKEN_ARRAY_NEXT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } Json::Array result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<ArrayState::State> ArrayState::transitions[SMAX][SMAX] = { /* SERROR */ { {0, SERROR}}, /* SSTART */ {{"[{tfn\"0", SVALUE}, {"]", SEND}, {0, SERROR}}, /* SVALUE */ {{",", SNEXT}, {"]", SEND}, {0, SERROR}}, /* SNEXT */ {{"[{tfn\"0", SVALUE}, {"]", SEND}, {0, SERROR}}, /* SEND */ { {0, SERROR}}, }; class ObjectState : public ParserState { protected: ObjectState(Json::TokenStream & tokenizer_, size_t depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SNAME, SSEP, SVALUE, SNEXT, SEND, SMAX, }; void build(State state) { switch (state) { case SNAME: key = tokenizer.token.str_value; break; case SVALUE: result << Json::Member(key, parse_value()); break; case SNEXT: break; case SEND: break; case SSEP: break; case SERROR: assert(false); // LCOV_EXCL_LINE case SSTART: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_OBJECT_START); case SNAME: JSONCC_THROW(BAD_TOKEN_OBJECT_NAME); case SSEP: JSONCC_THROW(BAD_TOKEN_OBJECT_SEP); case SVALUE: JSONCC_THROW(BAD_TOKEN_OBJECT_VALUE); case SNEXT: JSONCC_THROW(BAD_TOKEN_OBJECT_NEXT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } std::string key; Json::Object result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<ObjectState::State> ObjectState::transitions[SMAX][SMAX] = { /* SO_ERROR */ { {0, SERROR}}, /* SO_START */ {{"\"", SNAME}, {"}", SEND}, {0, SERROR}}, /* SO_NAME */ {{":", SSEP}, {0, SERROR}}, /* SO_SEP */ {{"[{tfn\"0", SVALUE}, {0, SERROR}}, /* SO_VALUE */ {{",", SNEXT}, {"}", SEND}, {0, SERROR}}, /* SO_NEXT */ {{"\"", SNAME}, {0, SERROR}}, /* SO_END */ { {0, SERROR}}, }; class DocState : public ParserState { protected: DocState(Json::TokenStream & tokenizer_, size_t & depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SVALUE, SEND, SMAX, }; void build(State state) { switch (state) { case SVALUE: result = parse_value(); break; case SEND: break; case SSTART: assert(false); // LCOV_EXCL_LINE case SERROR: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_DOCUMENT); case SVALUE: JSONCC_THROW(BAD_TOKEN_DOCUMENT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } Json::Value result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<DocState::State> DocState::transitions[SMAX][SMAX] = { /* SERROR */ { {0, SERROR}}, /* SSTART */ {{"[{", SVALUE}, {"", SEND}, {0, SERROR}}, /* SVALUE */ { {"", SEND}, {0, SERROR}}, /* SEND */ { {0, SERROR}}, }; Json::Value ParserState::parse_value() { switch (tokenizer.token.type) { case Json::Token::TRUE_LITERAL: return Json::True(); case Json::Token::FALSE_LITERAL: return Json::False(); case Json::Token::NULL_LITERAL: return Json::Null(); case Json::Token::STRING: return tokenizer.token.str_value; case Json::Token::NUMBER: if (tokenizer.token.number_type == Json::Token::FLOAT) { return Json::Number(tokenizer.token.float_value); } else { return Json::Number(tokenizer.token.int_value); } break; case Json::Token::BEGIN_ARRAY: return StateEngine<ArrayState>(tokenizer, depth_).parse(); case Json::Token::BEGIN_OBJECT: return StateEngine<ObjectState>(tokenizer, depth_).parse(); case Json::Token::END: assert(false); // LCOV_EXCL_LINE case Json::Token::INVALID: assert(false); // LCOV_EXCL_LINE case Json::Token::END_ARRAY: assert(false); // LCOV_EXCL_LINE case Json::Token::END_OBJECT: assert(false); // LCOV_EXCL_LINE case Json::Token::NAME_SEPARATOR: assert(false); // LCOV_EXCL_LINE case Json::Token::VALUE_SEPARATOR: assert(false); // LCOV_EXCL_LINE } JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE return Json::Value(); } } namespace Json { Value ParserImpl::parse(char const * data, size_t size) { Utf8Stream utf8stream(data, size); TokenStream tokenizer(utf8stream); try { return StateEngine<DocState>(tokenizer, 0).parse(); } catch (Error & e) { throw; } } } <|endoftext|>
<commit_before>/* This file is part of the KDE libraries Copyright (C) 2001 Joseph Wenninger <[email protected]> Copyright (C) 2002 John Firebaugh <[email protected]> Copyright (C) 2001 by Victor Röder <[email protected]> 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. */ /******** Partly based on the ArgHintWidget of Qt3 by Trolltech AS *********/ /* Trolltech doesn't mind, if we license that piece of code as LGPL, because there isn't much * left from the desigener code */ #include "katecodecompletion.h" #include "katecodecompletion.moc" #include "katecodecompletion_arghint.h" #include "katedocument.h" #include "kateview.h" #include "katerenderer.h" #include "kateconfig.h" #include <kdebug.h> #include <qwhatsthis.h> #include <qvbox.h> #include <qlistbox.h> #include <qtimer.h> #include <qtooltip.h> #include <qapplication.h> #include <qsizegrip.h> /** *This class is used for providing a codecompletionbox with the same size in all editorwindows. *Therefor the size is stored statically and provided over sizeHint(). *@short Listbox showing codecompletion */ class CCListBox : public QListBox{ public: CCListBox(QWidget* parent = 0, const char* name = 0, WFlags f = 0):QListBox(parent, name, f){ resize(m_size); }; QSize sizeHint() const { return m_size; }; protected: void resizeEvent(QResizeEvent* rev){ m_size = rev->size(); QListBox::resizeEvent(rev); }; private: static QSize m_size; }; QSize CCListBox::m_size = QSize(300,200); class CompletionItem : public QListBoxText { public: CompletionItem( QListBox* lb, KTextEditor::CompletionEntry entry ) : QListBoxText( lb ) , m_entry( entry ) { if( entry.postfix == "()" ) { // should be configurable setText( entry.prefix + " " + entry.text + entry.postfix ); } else { setText( entry.prefix + " " + entry.text + " " + entry.postfix); } } KTextEditor::CompletionEntry m_entry; }; KateCodeCompletion::KateCodeCompletion( KateView* view ) : QObject( view, "Kate Code Completion" ) , m_view( view ) , m_commentLabel( 0 ) { m_completionPopup = new QVBox( 0, 0, WType_Popup ); m_completionPopup->setFrameStyle( QFrame::Box | QFrame::Plain ); m_completionPopup->setLineWidth( 1 ); m_completionListBox = new CCListBox( m_completionPopup ); m_completionListBox->setFrameStyle( QFrame::NoFrame ); m_completionListBox->setCornerWidget( new QSizeGrip( m_completionListBox) ); m_completionListBox->installEventFilter( this ); m_completionPopup->resize(m_completionListBox->sizeHint() + QSize(2,2)); m_completionPopup->installEventFilter( this ); m_completionPopup->setFocusProxy( m_completionListBox ); m_pArgHint = new KDevArgHint( m_view ); connect( m_pArgHint, SIGNAL(argHintHidden()), this, SIGNAL(argHintHidden()) ); connect( m_view, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPosChanged()) ); } bool KateCodeCompletion::codeCompletionVisible () { return m_completionPopup->isVisible(); } void KateCodeCompletion::showCompletionBox( QValueList<KTextEditor::CompletionEntry> complList, int offset, bool casesensitive ) { kdDebug(13035) << "showCompletionBox " << endl; m_caseSensitive = casesensitive; m_complList = complList; m_offset = offset; m_view->cursorPositionReal( &m_lineCursor, &m_colCursor ); m_colCursor -= offset; updateBox( true ); } bool KateCodeCompletion::eventFilter( QObject *o, QEvent *e ) { if ( o != m_completionPopup && o != m_completionListBox && o != m_completionListBox->viewport() ) return false; if ( e->type() == QEvent::MouseButtonDblClick ) { doComplete(); return false; } if ( e->type() == QEvent::MouseButtonPress ) { QTimer::singleShot(0, this, SLOT(showComment())); return false; } if ( e->type() == QEvent::KeyPress ) { QKeyEvent *ke = (QKeyEvent*)e; if( /*(ke->key() == Key_Left) || (ke->key() == Key_Right) ||*///what are <- and -> used for?? (ke->key() == Key_Up) || (ke->key() == Key_Down ) || (ke->key() == Key_Home ) || (ke->key() == Key_End) || (ke->key() == Key_Prior) || (ke->key() == Key_Next )) { QTimer::singleShot(0,this,SLOT(showComment())); return false; } if( ke->key() == Key_Enter || ke->key() == Key_Return ) { doComplete(); return false; } if( ke->key() == Key_Escape ) { abortCompletion(); m_view->setFocus(); return false; } // redirect the event to the editor if( ke->key() == Key_Backspace) { m_view->backspace(); } else { QApplication::sendEvent( m_view->m_viewInternal, e ); } if( m_colCursor > m_view->cursorColumnReal() ) { // the cursor is too far left kdDebug(13035) << "Aborting Codecompletion after sendEvent" << endl; kdDebug(13035) << m_view->cursorColumnReal() << endl; abortCompletion(); m_view->setFocus(); return true; } updateBox(); return true; } if( e->type() == QEvent::FocusOut ) abortCompletion(); return false; } void KateCodeCompletion::doComplete() { CompletionItem* item = static_cast<CompletionItem*>( m_completionListBox->item(m_completionListBox->currentItem())); if( item == 0 ) return; QString text = item->m_entry.text; QString currentLine = m_view->currentTextLine(); int len = m_view->cursorColumnReal() - m_colCursor; QString currentComplText = currentLine.mid(m_colCursor,len); QString add = text.mid(currentComplText.length()); if( item->m_entry.postfix == "()" ) add += "("; emit filterInsertString(&(item->m_entry),&add); m_view->insertText(add); complete( item->m_entry ); m_view->setFocus(); } void KateCodeCompletion::abortCompletion() { m_completionPopup->hide(); delete m_commentLabel; m_commentLabel = 0; emit completionAborted(); } void KateCodeCompletion::complete( KTextEditor::CompletionEntry entry ) { m_completionPopup->hide(); delete m_commentLabel; m_commentLabel = 0; emit completionDone( entry ); emit completionDone(); } void KateCodeCompletion::updateBox( bool newCoordinate ) { m_completionListBox->clear(); QString currentLine = m_view->currentTextLine(); int len = m_view->cursorColumnReal() - m_colCursor; QString currentComplText = currentLine.mid(m_colCursor,len); /* Noone really badly wants those, or? kdDebug(13035) << "Column: " << m_colCursor << endl; kdDebug(13035) << "Line: " << currentLine << endl; kdDebug(13035) << "CurrentColumn: " << m_view->cursorColumnReal() << endl; kdDebug(13035) << "Len: " << len << endl; kdDebug(13035) << "Text: '" << currentComplText << "'" << endl; kdDebug(13035) << "Count: " << m_complList.count() << endl; */ QValueList<KTextEditor::CompletionEntry>::Iterator it; if( m_caseSensitive ) { for( it = m_complList.begin(); it != m_complList.end(); ++it ) { if( (*it).text.startsWith(currentComplText) ) { new CompletionItem(m_completionListBox,*it); } } } else { currentComplText = currentComplText.upper(); for( it = m_complList.begin(); it != m_complList.end(); ++it ) { if( (*it).text.upper().startsWith(currentComplText) ) { new CompletionItem(m_completionListBox,*it); } } } if( m_completionListBox->count() == 0 || ( m_completionListBox->count() == 1 && // abort if we equaled the last item currentComplText == m_completionListBox->text(0).stripWhiteSpace() ) ) { abortCompletion(); m_view->setFocus(); return; } if( newCoordinate ) { kdDebug(13035)<<"KateCodeCompletion::updateBox: Resizing widget"<<endl; m_completionPopup->resize(m_completionListBox->sizeHint() + QSize(2,2)); QPoint p = m_view->mapToGlobal( m_view->cursorCoordinates() ); int x = p.x(); int y = p.y() ; if ( y + m_completionPopup->height() + m_view->renderer()->config()->fontMetrics( KateRendererConfig::ViewFont )->height() > QApplication::desktop()->height() ) y -= (m_completionPopup->height() ); else y += m_view->renderer()->config()->fontMetrics( KateRendererConfig::ViewFont )->height(); if (x + m_completionPopup->width() > QApplication::desktop()->width()) x = QApplication::desktop()->width() - m_completionPopup->width(); m_completionPopup->move( QPoint(x,y) ); } m_completionListBox->setCurrentItem( 0 ); m_completionListBox->setSelected( 0, true ); m_completionListBox->setFocus(); m_completionPopup->show(); QTimer::singleShot(0,this,SLOT(showComment())); } void KateCodeCompletion::showArgHint ( QStringList functionList, const QString& strWrapping, const QString& strDelimiter ) { unsigned int line, col; m_view->cursorPositionReal( &line, &col ); m_pArgHint->reset( line, col ); m_pArgHint->setArgMarkInfos( strWrapping, strDelimiter ); int nNum = 0; for( QStringList::Iterator it = functionList.begin(); it != functionList.end(); it++ ) { kdDebug(13035) << "Insert function text: " << *it << endl; m_pArgHint->addFunction( nNum, ( *it ) ); nNum++; } m_pArgHint->move(m_view->mapToGlobal(m_view->cursorCoordinates() + QPoint(0,m_view->renderer()->config()->fontMetrics( KateRendererConfig::ViewFont )->height())) ); m_pArgHint->show(); } void KateCodeCompletion::slotCursorPosChanged() { m_pArgHint->cursorPositionChanged ( m_view, m_view->cursorLine(), m_view->cursorColumnReal() ); } void KateCodeCompletion::showComment() { CompletionItem* item = static_cast<CompletionItem*>(m_completionListBox->item(m_completionListBox->currentItem())); if( !item ) return; if( item->m_entry.comment.isEmpty() ) return; delete m_commentLabel; m_commentLabel = new KateCodeCompletionCommentLabel( 0, item->m_entry.comment ); m_commentLabel->setFont(QToolTip::font()); m_commentLabel->setPalette(QToolTip::palette()); QPoint rightPoint = m_completionPopup->mapToGlobal(QPoint(m_completionPopup->width(),0)); QPoint leftPoint = m_completionPopup->mapToGlobal(QPoint(0,0)); QRect screen = QApplication::desktop()->screenGeometry( m_commentLabel->x11Screen() ); QPoint finalPoint; if (rightPoint.x()+m_commentLabel->width() > screen.x() + screen.width()) finalPoint.setX(leftPoint.x()-m_commentLabel->width()); else finalPoint.setX(rightPoint.x()); m_completionListBox->ensureCurrentVisible(); finalPoint.setY( m_completionListBox->viewport()->mapToGlobal(m_completionListBox->itemRect( m_completionListBox->item(m_completionListBox->currentItem())).topLeft()).y()); m_commentLabel->move(finalPoint); m_commentLabel->show(); } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>The completion box now resizes itself to reflect the content size, patch from Jonas B. Jacobi<commit_after>/* This file is part of the KDE libraries Copyright (C) 2001 Joseph Wenninger <[email protected]> Copyright (C) 2002 John Firebaugh <[email protected]> Copyright (C) 2001 by Victor Röder <[email protected]> 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. */ /******** Partly based on the ArgHintWidget of Qt3 by Trolltech AS *********/ /* Trolltech doesn't mind, if we license that piece of code as LGPL, because there isn't much * left from the desigener code */ #include "katecodecompletion.h" #include "katecodecompletion.moc" #include "katecodecompletion_arghint.h" #include "katedocument.h" #include "kateview.h" #include "katerenderer.h" #include "kateconfig.h" #include <kdebug.h> #include <qwhatsthis.h> #include <qvbox.h> #include <qlistbox.h> #include <qtimer.h> #include <qtooltip.h> #include <qapplication.h> #include <qsizegrip.h> #include <qfontmetrics.h> /** * This class is used as the codecompletion listbox. It can be resized according to its contents, * therfor the needed size is provided by sizeHint(); *@short Listbox showing codecompletion *@author Jonas B. Jacobi <[email protected]> */ class CCListBox : public QListBox{ public: /** @short Create a new CCListBox @param view The KateView, CCListBox is displayed in */ CCListBox(KateView* view, QWidget* parent = 0, const char* name = 0, WFlags f = 0):QListBox(parent, name, f), m_view(view){ }; QSize sizeHint() const { int count = this->count(); int height = 20; int tmpwidth = 8; //FIXME the height is for some reasons at least 3 items heigh, even if there is only one item in the list if (count > 0) if(count < 11) height = count * itemHeight(0); else { height = 10 * itemHeight(0); tmpwidth += verticalScrollBar()->width(); } int maxcount = 0, tmpcount = 0; const QFontMetrics* metrics = m_view->renderer()->currentFontMetrics(); for (int i = 0; i < count; ++i) if ( (tmpcount = metrics->width(text(i)) ) > maxcount) maxcount = tmpcount; if (maxcount > QApplication::desktop()->width()){ tmpwidth = QApplication::desktop()->width() - 5; height += horizontalScrollBar()->height(); } else tmpwidth += maxcount; return QSize(tmpwidth,height); }; private: KateView* m_view; }; class CompletionItem : public QListBoxText { public: CompletionItem( QListBox* lb, KTextEditor::CompletionEntry entry ) : QListBoxText( lb ) , m_entry( entry ) { if( entry.postfix == "()" ) { // should be configurable setText( entry.prefix + " " + entry.text + entry.postfix ); } else { setText( entry.prefix + " " + entry.text + " " + entry.postfix); } } KTextEditor::CompletionEntry m_entry; }; KateCodeCompletion::KateCodeCompletion( KateView* view ) : QObject( view, "Kate Code Completion" ) , m_view( view ) , m_commentLabel( 0 ) { m_completionPopup = new QVBox( 0, 0, WType_Popup ); m_completionPopup->setFrameStyle( QFrame::Box | QFrame::Plain ); m_completionPopup->setLineWidth( 1 ); m_completionListBox = new CCListBox( view, m_completionPopup ); m_completionListBox->setFrameStyle( QFrame::NoFrame ); m_completionListBox->setCornerWidget( new QSizeGrip( m_completionListBox) ); m_completionListBox->installEventFilter( this ); m_completionPopup->resize(m_completionListBox->sizeHint() + QSize(2,2)); m_completionPopup->installEventFilter( this ); m_completionPopup->setFocusProxy( m_completionListBox ); m_pArgHint = new KDevArgHint( m_view ); connect( m_pArgHint, SIGNAL(argHintHidden()), this, SIGNAL(argHintHidden()) ); connect( m_view, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPosChanged()) ); } bool KateCodeCompletion::codeCompletionVisible () { return m_completionPopup->isVisible(); } void KateCodeCompletion::showCompletionBox( QValueList<KTextEditor::CompletionEntry> complList, int offset, bool casesensitive ) { kdDebug(13035) << "showCompletionBox " << endl; m_caseSensitive = casesensitive; m_complList = complList; m_offset = offset; m_view->cursorPositionReal( &m_lineCursor, &m_colCursor ); m_colCursor -= offset; updateBox( true ); } bool KateCodeCompletion::eventFilter( QObject *o, QEvent *e ) { if ( o != m_completionPopup && o != m_completionListBox && o != m_completionListBox->viewport() ) return false; if ( e->type() == QEvent::MouseButtonDblClick ) { doComplete(); return false; } if ( e->type() == QEvent::MouseButtonPress ) { QTimer::singleShot(0, this, SLOT(showComment())); return false; } if ( e->type() == QEvent::KeyPress ) { QKeyEvent *ke = (QKeyEvent*)e; if( /*(ke->key() == Key_Left) || (ke->key() == Key_Right) ||*///what are <- and -> used for?? (ke->key() == Key_Up) || (ke->key() == Key_Down ) || (ke->key() == Key_Home ) || (ke->key() == Key_End) || (ke->key() == Key_Prior) || (ke->key() == Key_Next )) { QTimer::singleShot(0,this,SLOT(showComment())); return false; } if( ke->key() == Key_Enter || ke->key() == Key_Return ) { doComplete(); return false; } if( ke->key() == Key_Escape ) { abortCompletion(); m_view->setFocus(); return false; } // redirect the event to the editor if( ke->key() == Key_Backspace) { m_view->backspace(); } else { QApplication::sendEvent( m_view->m_viewInternal, e ); } if( m_colCursor > m_view->cursorColumnReal() ) { // the cursor is too far left kdDebug(13035) << "Aborting Codecompletion after sendEvent" << endl; kdDebug(13035) << m_view->cursorColumnReal() << endl; abortCompletion(); m_view->setFocus(); return true; } updateBox(); return true; } if( e->type() == QEvent::FocusOut ) abortCompletion(); return false; } void KateCodeCompletion::doComplete() { CompletionItem* item = static_cast<CompletionItem*>( m_completionListBox->item(m_completionListBox->currentItem())); if( item == 0 ) return; QString text = item->m_entry.text; QString currentLine = m_view->currentTextLine(); int len = m_view->cursorColumnReal() - m_colCursor; QString currentComplText = currentLine.mid(m_colCursor,len); QString add = text.mid(currentComplText.length()); if( item->m_entry.postfix == "()" ) add += "("; emit filterInsertString(&(item->m_entry),&add); m_view->insertText(add); complete( item->m_entry ); m_view->setFocus(); } void KateCodeCompletion::abortCompletion() { m_completionPopup->hide(); delete m_commentLabel; m_commentLabel = 0; emit completionAborted(); } void KateCodeCompletion::complete( KTextEditor::CompletionEntry entry ) { m_completionPopup->hide(); delete m_commentLabel; m_commentLabel = 0; emit completionDone( entry ); emit completionDone(); } void KateCodeCompletion::updateBox( bool newCoordinate ) { m_completionListBox->clear(); QString currentLine = m_view->currentTextLine(); int len = m_view->cursorColumnReal() - m_colCursor; QString currentComplText = currentLine.mid(m_colCursor,len); /* Noone really badly wants those, or? kdDebug(13035) << "Column: " << m_colCursor << endl; kdDebug(13035) << "Line: " << currentLine << endl; kdDebug(13035) << "CurrentColumn: " << m_view->cursorColumnReal() << endl; kdDebug(13035) << "Len: " << len << endl; kdDebug(13035) << "Text: '" << currentComplText << "'" << endl; kdDebug(13035) << "Count: " << m_complList.count() << endl; */ QValueList<KTextEditor::CompletionEntry>::Iterator it; if( m_caseSensitive ) { for( it = m_complList.begin(); it != m_complList.end(); ++it ) { if( (*it).text.startsWith(currentComplText) ) { new CompletionItem(m_completionListBox,*it); } } } else { currentComplText = currentComplText.upper(); for( it = m_complList.begin(); it != m_complList.end(); ++it ) { if( (*it).text.upper().startsWith(currentComplText) ) { new CompletionItem(m_completionListBox,*it); } } } if( m_completionListBox->count() == 0 || ( m_completionListBox->count() == 1 && // abort if we equaled the last item currentComplText == m_completionListBox->text(0).stripWhiteSpace() ) ) { abortCompletion(); m_view->setFocus(); return; } kdDebug(13035)<<"KateCodeCompletion::updateBox: Resizing widget"<<endl; m_completionPopup->resize(m_completionListBox->sizeHint() + QSize(2,2)); QPoint p = m_view->mapToGlobal( m_view->cursorCoordinates() ); int x = p.x(); int y = p.y() ; if ( y + m_completionPopup->height() + m_view->renderer()->config()->fontMetrics( KateRendererConfig::ViewFont )->height() > QApplication::desktop()->height() ) y -= (m_completionPopup->height() ); else y += m_view->renderer()->config()->fontMetrics( KateRendererConfig::ViewFont )->height(); if (x + m_completionPopup->width() > QApplication::desktop()->width()) x = QApplication::desktop()->width() - m_completionPopup->width(); m_completionPopup->move( QPoint(x,y) ); m_completionListBox->setCurrentItem( 0 ); m_completionListBox->setSelected( 0, true ); m_completionListBox->setFocus(); m_completionPopup->show(); QTimer::singleShot(0,this,SLOT(showComment())); } void KateCodeCompletion::showArgHint ( QStringList functionList, const QString& strWrapping, const QString& strDelimiter ) { unsigned int line, col; m_view->cursorPositionReal( &line, &col ); m_pArgHint->reset( line, col ); m_pArgHint->setArgMarkInfos( strWrapping, strDelimiter ); int nNum = 0; for( QStringList::Iterator it = functionList.begin(); it != functionList.end(); it++ ) { kdDebug(13035) << "Insert function text: " << *it << endl; m_pArgHint->addFunction( nNum, ( *it ) ); nNum++; } m_pArgHint->move(m_view->mapToGlobal(m_view->cursorCoordinates() + QPoint(0,m_view->renderer()->config()->fontMetrics( KateRendererConfig::ViewFont )->height())) ); m_pArgHint->show(); } void KateCodeCompletion::slotCursorPosChanged() { m_pArgHint->cursorPositionChanged ( m_view, m_view->cursorLine(), m_view->cursorColumnReal() ); } void KateCodeCompletion::showComment() { CompletionItem* item = static_cast<CompletionItem*>(m_completionListBox->item(m_completionListBox->currentItem())); if( !item ) return; if( item->m_entry.comment.isEmpty() ) return; delete m_commentLabel; m_commentLabel = new KateCodeCompletionCommentLabel( 0, item->m_entry.comment ); m_commentLabel->setFont(QToolTip::font()); m_commentLabel->setPalette(QToolTip::palette()); QPoint rightPoint = m_completionPopup->mapToGlobal(QPoint(m_completionPopup->width(),0)); QPoint leftPoint = m_completionPopup->mapToGlobal(QPoint(0,0)); QRect screen = QApplication::desktop()->screenGeometry( m_commentLabel->x11Screen() ); QPoint finalPoint; if (rightPoint.x()+m_commentLabel->width() > screen.x() + screen.width()) finalPoint.setX(leftPoint.x()-m_commentLabel->width()); else finalPoint.setX(rightPoint.x()); m_completionListBox->ensureCurrentVisible(); finalPoint.setY( m_completionListBox->viewport()->mapToGlobal(m_completionListBox->itemRect( m_completionListBox->item(m_completionListBox->currentItem())).topLeft()).y()); m_commentLabel->move(finalPoint); m_commentLabel->show(); } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>/* This file is part of the KDE libraries * Copyright (C) 2008 Erlend Hamberg <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) version 3. * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "katevivisualmode.h" #include "katesmartrange.h" #include "katevirange.h" KateViVisualMode::KateViVisualMode( KateViInputModeManager* viInputModeManager, KateView *view, KateViewInternal *viewInternal ) : KateViNormalMode( viInputModeManager, view, viewInternal ) { m_start.setPosition( -1, -1 ); m_topRange = m_doc->newSmartRange(m_doc->documentRange()); static_cast<KateSmartRange*>(m_topRange)->setInternal(); m_topRange->setInsertBehavior(KTextEditor::SmartRange::ExpandLeft | KTextEditor::SmartRange::ExpandRight); m_view->addInternalHighlight(m_topRange); m_visualLine = false; KTextEditor::Range r; highlightRange = m_doc->newSmartRange( r, m_topRange ); attribute = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); attribute->setBackground( m_viewInternal->palette().highlight() ); attribute->setForeground( m_viewInternal->palette().highlightedText() ); highlightRange->setInsertBehavior(KTextEditor::SmartRange::DoNotExpand); initializeCommands(); } KateViVisualMode::~KateViVisualMode() { } void KateViVisualMode::highlight() const { // FIXME: HACK to avoid highlight bug: remove highlighing and re-set it highlightRange->setAttribute(static_cast<KTextEditor::Attribute::Ptr>(0)); highlightRange->setAttribute(attribute); KTextEditor::Cursor c1 = m_start; KTextEditor::Cursor c2 = m_view->cursorPosition(); if ( m_visualLine ) { c1.setColumn( ( c1 < c2 ) ? 0 : getLine( m_start.line() ).length() ); c2.setColumn( ( c1 < c2 ? getLine().length() : 0 ) ); } else if ( c1 > c2 && c1.column() != 0 ) { c1.setColumn( c1.column()+1 ); } highlightRange->setRange( KTextEditor::Range( c1, c2 ) ); } void KateViVisualMode::goToPos( const KateViRange &r ) { KTextEditor::Cursor c = m_view->cursorPosition(); if ( r.startLine != -1 && r.startColumn != -1 && c == m_start ) { m_start.setLine( r.startLine ); m_start.setColumn( r.startColumn ); c.setLine( r.endLine ); c.setColumn( r.endColumn ); } else if ( r.startLine != -1 && r.startColumn != -1 && c < m_start ) { c.setLine( r.startLine ); c.setColumn( r.startColumn ); } else { c.setLine( r.endLine ); c.setColumn( r.endColumn ); } if ( c.line() >= m_doc->lines() ) { c.setLine( m_doc->lines()-1 ); } updateCursor( c ); m_commandRange.startLine = m_start.line(); m_commandRange.startColumn = m_start.column(); m_commandRange.endLine = r.endLine; m_commandRange.endColumn = r.endColumn; highlight(); } void KateViVisualMode::reset() { // remove highlighting highlightRange->setAttribute(static_cast<KTextEditor::Attribute::Ptr>(0)); m_awaitingMotionOrTextObject.push_back( 0 ); // search for text objects/motion from char 0 m_visualLine = false; // only switch to normal mode if still in visual mode. commands like c, s, ... // can have switched to insert mode if ( m_viInputModeManager->getCurrentViMode() == VisualMode || m_viInputModeManager->getCurrentViMode() == VisualLineMode ) { m_viInputModeManager->viEnterNormalMode(); } } void KateViVisualMode::init() { m_start = m_view->cursorPosition(); highlightRange->setRange( KTextEditor::Range( m_start, m_view->cursorPosition() ) ); highlightRange->setAttribute(attribute); highlight(); m_awaitingMotionOrTextObject.push_back( 0 ); // search for text objects/motion from char 0 } void KateViVisualMode::setVisualLine( bool l ) { m_visualLine = l; highlight(); } void KateViVisualMode::switchStartEnd() { KTextEditor::Cursor c = m_start; m_start = m_view->cursorPosition(); updateCursor( c ); highlight(); } void KateViVisualMode::initializeCommands() { m_commands.clear(); m_motions.clear(); m_commands.push_back( new KateViCommand( this, "J", &KateViNormalMode::commandJoinLines, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "c", &KateViNormalMode::commandChange, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "C", &KateViNormalMode::commandChangeToEOL, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "d", &KateViNormalMode::commandDelete, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "D", &KateViNormalMode::commandDeleteToEOL, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "x", &KateViNormalMode::commandDeleteChar, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "X", &KateViNormalMode::commandDeleteCharBackward, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "gq", &KateViNormalMode::commandFormatLines, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "gu", &KateViNormalMode::commandMakeLowercase, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "gU", &KateViNormalMode::commandMakeUppercase, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "y", &KateViNormalMode::commandYank ) ); m_commands.push_back( new KateViCommand( this, "Y", &KateViNormalMode::commandYankToEOL ) ); m_commands.push_back( new KateViCommand( this, "p", &KateViNormalMode::commandPaste, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "P", &KateViNormalMode::commandPasteBefore, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "r.", &KateViNormalMode::commandReplaceCharacter, IS_CHANGE | REGEX_PATTERN ) ); m_commands.push_back( new KateViCommand( this, ":", &KateViNormalMode::commandSwitchToCmdLine ) ); m_commands.push_back( new KateViCommand( this, "/", &KateViNormalMode::commandSearch ) ); m_commands.push_back( new KateViCommand( this, "u", &KateViNormalMode::commandUndo ) ); m_commands.push_back( new KateViCommand( this, "U", &KateViNormalMode::commandRedo ) ); m_commands.push_back( new KateViCommand( this, "m.", &KateViNormalMode::commandSetMark, REGEX_PATTERN ) ); m_commands.push_back( new KateViCommand( this, "n", &KateViNormalMode::commandFindNext ) ); m_commands.push_back( new KateViCommand( this, "N", &KateViNormalMode::commandFindPrev ) ); m_commands.push_back( new KateViCommand( this, ">", &KateViNormalMode::commandIndentLines ) ); m_commands.push_back( new KateViCommand( this, "<", &KateViNormalMode::commandUnindentLines ) ); m_commands.push_back( new KateViCommand( this, "<c-c>", &KateViNormalMode::commandAbort ) ); m_commands.push_back( new KateViCommand( this, "ga", &KateViNormalMode::commandPrintCharacterCode, SHOULD_NOT_RESET ) ); m_commands.push_back( new KateViCommand( this, "v", &KateViNormalMode::commandEnterVisualMode, SHOULD_NOT_RESET ) ); m_commands.push_back( new KateViCommand( this, "V", &KateViNormalMode::commandEnterVisualLineMode, SHOULD_NOT_RESET ) ); m_commands.push_back( new KateViCommand( this, "o", &KateViNormalMode::commandToOtherEnd, SHOULD_NOT_RESET ) ); m_commands.push_back( new KateViCommand( this, "=", &KateViNormalMode::commandAlignLines, SHOULD_NOT_RESET ) ); // regular motions m_motions.push_back( new KateViMotion( this, "h", &KateViNormalMode::motionLeft ) ); m_motions.push_back( new KateViMotion( this, "<left>", &KateViNormalMode::motionLeft ) ); m_motions.push_back( new KateViMotion( this, "<backspace>", &KateViNormalMode::motionLeft ) ); m_motions.push_back( new KateViMotion( this, "j", &KateViNormalMode::motionDown ) ); m_motions.push_back( new KateViMotion( this, "<down>", &KateViNormalMode::motionDown ) ); m_motions.push_back( new KateViMotion( this, "k", &KateViNormalMode::motionUp ) ); m_motions.push_back( new KateViMotion( this, "<up>", &KateViNormalMode::motionUp ) ); m_motions.push_back( new KateViMotion( this, "l", &KateViNormalMode::motionRight ) ); m_motions.push_back( new KateViMotion( this, "<right>", &KateViNormalMode::motionRight ) ); m_motions.push_back( new KateViMotion( this, " ", &KateViNormalMode::motionRight ) ); m_motions.push_back( new KateViMotion( this, "$", &KateViNormalMode::motionToEOL ) ); m_motions.push_back( new KateViMotion( this, "<end>", &KateViNormalMode::motionToEOL ) ); m_motions.push_back( new KateViMotion( this, "0", &KateViNormalMode::motionToColumn0 ) ); m_motions.push_back( new KateViMotion( this, "<home>", &KateViNormalMode::motionToColumn0 ) ); m_motions.push_back( new KateViMotion( this, "^", &KateViNormalMode::motionToFirstCharacterOfLine ) ); m_motions.push_back( new KateViMotion( this, "f.", &KateViNormalMode::motionFindChar, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "F.", &KateViNormalMode::motionFindCharBackward, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "t.", &KateViNormalMode::motionToChar, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "T.", &KateViNormalMode::motionToCharBackward, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "gg", &KateViNormalMode::motionToLineFirst ) ); m_motions.push_back( new KateViMotion( this, "G", &KateViNormalMode::motionToLineLast ) ); m_motions.push_back( new KateViMotion( this, "w", &KateViNormalMode::motionWordForward ) ); m_motions.push_back( new KateViMotion( this, "W", &KateViNormalMode::motionWORDForward ) ); m_motions.push_back( new KateViMotion( this, "b", &KateViNormalMode::motionWordBackward ) ); m_motions.push_back( new KateViMotion( this, "B", &KateViNormalMode::motionWORDBackward ) ); m_motions.push_back( new KateViMotion( this, "e", &KateViNormalMode::motionToEndOfWord ) ); m_motions.push_back( new KateViMotion( this, "E", &KateViNormalMode::motionToEndOfWORD ) ); m_motions.push_back( new KateViMotion( this, "|", &KateViNormalMode::motionToScreenColumn ) ); m_motions.push_back( new KateViMotion( this, "%", &KateViNormalMode::motionToMatchingItem ) ); m_motions.push_back( new KateViMotion( this, "`.", &KateViNormalMode::motionToMark, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "'.", &KateViNormalMode::motionToMarkLine, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "[[", &KateViNormalMode::motionToPreviousBraceBlockStart ) ); m_motions.push_back( new KateViMotion( this, "]]", &KateViNormalMode::motionToNextBraceBlockStart ) ); m_motions.push_back( new KateViMotion( this, "[]", &KateViNormalMode::motionToPreviousBraceBlockEnd ) ); m_motions.push_back( new KateViMotion( this, "][", &KateViNormalMode::motionToNextBraceBlockEnd ) ); // text objects m_motions.push_back( new KateViMotion( this, "iw", &KateViNormalMode::textObjectInnerWord ) ); m_motions.push_back( new KateViMotion( this, "aw", &KateViNormalMode::textObjectAWord ) ); m_motions.push_back( new KateViMotion( this, "i\"", &KateViNormalMode::textObjectInnerQuoteDouble ) ); m_motions.push_back( new KateViMotion( this, "a\"", &KateViNormalMode::textObjectAQuoteDouble ) ); m_motions.push_back( new KateViMotion( this, "i'", &KateViNormalMode::textObjectInnerQuoteSingle ) ); m_motions.push_back( new KateViMotion( this, "a'", &KateViNormalMode::textObjectAQuoteSingle ) ); m_motions.push_back( new KateViMotion( this, "i[()]", &KateViNormalMode::textObjectInnerParen, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "a[()]", &KateViNormalMode::textObjectAParen, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "i[\\[\\]]", &KateViNormalMode::textObjectInnerBracket, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "a[\\[\\]]", &KateViNormalMode::textObjectABracket, REGEX_PATTERN ) ); } <commit_msg>make sure the command range is always valid when using visual mode<commit_after>/* This file is part of the KDE libraries * Copyright (C) 2008 Erlend Hamberg <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) version 3. * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "katevivisualmode.h" #include "katesmartrange.h" #include "katevirange.h" KateViVisualMode::KateViVisualMode( KateViInputModeManager* viInputModeManager, KateView *view, KateViewInternal *viewInternal ) : KateViNormalMode( viInputModeManager, view, viewInternal ) { m_start.setPosition( -1, -1 ); m_topRange = m_doc->newSmartRange(m_doc->documentRange()); static_cast<KateSmartRange*>(m_topRange)->setInternal(); m_topRange->setInsertBehavior(KTextEditor::SmartRange::ExpandLeft | KTextEditor::SmartRange::ExpandRight); m_view->addInternalHighlight(m_topRange); m_visualLine = false; KTextEditor::Range r; highlightRange = m_doc->newSmartRange( r, m_topRange ); attribute = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); attribute->setBackground( m_viewInternal->palette().highlight() ); attribute->setForeground( m_viewInternal->palette().highlightedText() ); highlightRange->setInsertBehavior(KTextEditor::SmartRange::DoNotExpand); initializeCommands(); } KateViVisualMode::~KateViVisualMode() { } void KateViVisualMode::highlight() const { // FIXME: HACK to avoid highlight bug: remove highlighing and re-set it highlightRange->setAttribute(static_cast<KTextEditor::Attribute::Ptr>(0)); highlightRange->setAttribute(attribute); KTextEditor::Cursor c1 = m_start; KTextEditor::Cursor c2 = m_view->cursorPosition(); if ( m_visualLine ) { c1.setColumn( ( c1 < c2 ) ? 0 : getLine( m_start.line() ).length() ); c2.setColumn( ( c1 < c2 ? getLine().length() : 0 ) ); } else if ( c1 > c2 && c1.column() != 0 ) { c1.setColumn( c1.column()+1 ); } highlightRange->setRange( KTextEditor::Range( c1, c2 ) ); } void KateViVisualMode::goToPos( const KateViRange &r ) { KTextEditor::Cursor c = m_view->cursorPosition(); if ( r.startLine != -1 && r.startColumn != -1 && c == m_start ) { m_start.setLine( r.startLine ); m_start.setColumn( r.startColumn ); c.setLine( r.endLine ); c.setColumn( r.endColumn ); } else if ( r.startLine != -1 && r.startColumn != -1 && c < m_start ) { c.setLine( r.startLine ); c.setColumn( r.startColumn ); } else { c.setLine( r.endLine ); c.setColumn( r.endColumn ); } if ( c.line() >= m_doc->lines() ) { c.setLine( m_doc->lines()-1 ); } updateCursor( c ); m_commandRange.startLine = m_start.line(); m_commandRange.startColumn = m_start.column(); m_commandRange.endLine = r.endLine; m_commandRange.endColumn = r.endColumn; highlight(); } void KateViVisualMode::reset() { // remove highlighting highlightRange->setAttribute(static_cast<KTextEditor::Attribute::Ptr>(0)); m_awaitingMotionOrTextObject.push_back( 0 ); // search for text objects/motion from char 0 m_visualLine = false; // only switch to normal mode if still in visual mode. commands like c, s, ... // can have switched to insert mode if ( m_viInputModeManager->getCurrentViMode() == VisualMode || m_viInputModeManager->getCurrentViMode() == VisualLineMode ) { m_viInputModeManager->viEnterNormalMode(); } } void KateViVisualMode::init() { m_start = m_view->cursorPosition(); highlightRange->setRange( KTextEditor::Range( m_start, m_view->cursorPosition() ) ); highlightRange->setAttribute(attribute); highlight(); m_awaitingMotionOrTextObject.push_back( 0 ); // search for text objects/motion from char 0 m_commandRange.startLine = m_commandRange.endLine = m_start.line(); m_commandRange.startColumn = m_commandRange.endColumn = m_start.column(); } void KateViVisualMode::setVisualLine( bool l ) { m_visualLine = l; highlight(); } void KateViVisualMode::switchStartEnd() { KTextEditor::Cursor c = m_start; m_start = m_view->cursorPosition(); updateCursor( c ); highlight(); } void KateViVisualMode::initializeCommands() { m_commands.clear(); m_motions.clear(); m_commands.push_back( new KateViCommand( this, "J", &KateViNormalMode::commandJoinLines, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "c", &KateViNormalMode::commandChange, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "C", &KateViNormalMode::commandChangeToEOL, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "d", &KateViNormalMode::commandDelete, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "D", &KateViNormalMode::commandDeleteToEOL, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "x", &KateViNormalMode::commandDeleteChar, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "X", &KateViNormalMode::commandDeleteCharBackward, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "gq", &KateViNormalMode::commandFormatLines, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "gu", &KateViNormalMode::commandMakeLowercase, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "gU", &KateViNormalMode::commandMakeUppercase, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "y", &KateViNormalMode::commandYank ) ); m_commands.push_back( new KateViCommand( this, "Y", &KateViNormalMode::commandYankToEOL ) ); m_commands.push_back( new KateViCommand( this, "p", &KateViNormalMode::commandPaste, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "P", &KateViNormalMode::commandPasteBefore, IS_CHANGE ) ); m_commands.push_back( new KateViCommand( this, "r.", &KateViNormalMode::commandReplaceCharacter, IS_CHANGE | REGEX_PATTERN ) ); m_commands.push_back( new KateViCommand( this, ":", &KateViNormalMode::commandSwitchToCmdLine ) ); m_commands.push_back( new KateViCommand( this, "/", &KateViNormalMode::commandSearch ) ); m_commands.push_back( new KateViCommand( this, "u", &KateViNormalMode::commandUndo ) ); m_commands.push_back( new KateViCommand( this, "U", &KateViNormalMode::commandRedo ) ); m_commands.push_back( new KateViCommand( this, "m.", &KateViNormalMode::commandSetMark, REGEX_PATTERN ) ); m_commands.push_back( new KateViCommand( this, "n", &KateViNormalMode::commandFindNext ) ); m_commands.push_back( new KateViCommand( this, "N", &KateViNormalMode::commandFindPrev ) ); m_commands.push_back( new KateViCommand( this, ">", &KateViNormalMode::commandIndentLines ) ); m_commands.push_back( new KateViCommand( this, "<", &KateViNormalMode::commandUnindentLines ) ); m_commands.push_back( new KateViCommand( this, "<c-c>", &KateViNormalMode::commandAbort ) ); m_commands.push_back( new KateViCommand( this, "ga", &KateViNormalMode::commandPrintCharacterCode, SHOULD_NOT_RESET ) ); m_commands.push_back( new KateViCommand( this, "v", &KateViNormalMode::commandEnterVisualMode, SHOULD_NOT_RESET ) ); m_commands.push_back( new KateViCommand( this, "V", &KateViNormalMode::commandEnterVisualLineMode, SHOULD_NOT_RESET ) ); m_commands.push_back( new KateViCommand( this, "o", &KateViNormalMode::commandToOtherEnd, SHOULD_NOT_RESET ) ); m_commands.push_back( new KateViCommand( this, "=", &KateViNormalMode::commandAlignLines, SHOULD_NOT_RESET ) ); // regular motions m_motions.push_back( new KateViMotion( this, "h", &KateViNormalMode::motionLeft ) ); m_motions.push_back( new KateViMotion( this, "<left>", &KateViNormalMode::motionLeft ) ); m_motions.push_back( new KateViMotion( this, "<backspace>", &KateViNormalMode::motionLeft ) ); m_motions.push_back( new KateViMotion( this, "j", &KateViNormalMode::motionDown ) ); m_motions.push_back( new KateViMotion( this, "<down>", &KateViNormalMode::motionDown ) ); m_motions.push_back( new KateViMotion( this, "k", &KateViNormalMode::motionUp ) ); m_motions.push_back( new KateViMotion( this, "<up>", &KateViNormalMode::motionUp ) ); m_motions.push_back( new KateViMotion( this, "l", &KateViNormalMode::motionRight ) ); m_motions.push_back( new KateViMotion( this, "<right>", &KateViNormalMode::motionRight ) ); m_motions.push_back( new KateViMotion( this, " ", &KateViNormalMode::motionRight ) ); m_motions.push_back( new KateViMotion( this, "$", &KateViNormalMode::motionToEOL ) ); m_motions.push_back( new KateViMotion( this, "<end>", &KateViNormalMode::motionToEOL ) ); m_motions.push_back( new KateViMotion( this, "0", &KateViNormalMode::motionToColumn0 ) ); m_motions.push_back( new KateViMotion( this, "<home>", &KateViNormalMode::motionToColumn0 ) ); m_motions.push_back( new KateViMotion( this, "^", &KateViNormalMode::motionToFirstCharacterOfLine ) ); m_motions.push_back( new KateViMotion( this, "f.", &KateViNormalMode::motionFindChar, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "F.", &KateViNormalMode::motionFindCharBackward, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "t.", &KateViNormalMode::motionToChar, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "T.", &KateViNormalMode::motionToCharBackward, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "gg", &KateViNormalMode::motionToLineFirst ) ); m_motions.push_back( new KateViMotion( this, "G", &KateViNormalMode::motionToLineLast ) ); m_motions.push_back( new KateViMotion( this, "w", &KateViNormalMode::motionWordForward ) ); m_motions.push_back( new KateViMotion( this, "W", &KateViNormalMode::motionWORDForward ) ); m_motions.push_back( new KateViMotion( this, "b", &KateViNormalMode::motionWordBackward ) ); m_motions.push_back( new KateViMotion( this, "B", &KateViNormalMode::motionWORDBackward ) ); m_motions.push_back( new KateViMotion( this, "e", &KateViNormalMode::motionToEndOfWord ) ); m_motions.push_back( new KateViMotion( this, "E", &KateViNormalMode::motionToEndOfWORD ) ); m_motions.push_back( new KateViMotion( this, "|", &KateViNormalMode::motionToScreenColumn ) ); m_motions.push_back( new KateViMotion( this, "%", &KateViNormalMode::motionToMatchingItem ) ); m_motions.push_back( new KateViMotion( this, "`.", &KateViNormalMode::motionToMark, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "'.", &KateViNormalMode::motionToMarkLine, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "[[", &KateViNormalMode::motionToPreviousBraceBlockStart ) ); m_motions.push_back( new KateViMotion( this, "]]", &KateViNormalMode::motionToNextBraceBlockStart ) ); m_motions.push_back( new KateViMotion( this, "[]", &KateViNormalMode::motionToPreviousBraceBlockEnd ) ); m_motions.push_back( new KateViMotion( this, "][", &KateViNormalMode::motionToNextBraceBlockEnd ) ); // text objects m_motions.push_back( new KateViMotion( this, "iw", &KateViNormalMode::textObjectInnerWord ) ); m_motions.push_back( new KateViMotion( this, "aw", &KateViNormalMode::textObjectAWord ) ); m_motions.push_back( new KateViMotion( this, "i\"", &KateViNormalMode::textObjectInnerQuoteDouble ) ); m_motions.push_back( new KateViMotion( this, "a\"", &KateViNormalMode::textObjectAQuoteDouble ) ); m_motions.push_back( new KateViMotion( this, "i'", &KateViNormalMode::textObjectInnerQuoteSingle ) ); m_motions.push_back( new KateViMotion( this, "a'", &KateViNormalMode::textObjectAQuoteSingle ) ); m_motions.push_back( new KateViMotion( this, "i[()]", &KateViNormalMode::textObjectInnerParen, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "a[()]", &KateViNormalMode::textObjectAParen, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "i[\\[\\]]", &KateViNormalMode::textObjectInnerBracket, REGEX_PATTERN ) ); m_motions.push_back( new KateViMotion( this, "a[\\[\\]]", &KateViNormalMode::textObjectABracket, REGEX_PATTERN ) ); } <|endoftext|>
<commit_before>#include "internal.hpp" #include "external.hpp" #include "macros.hpp" #include "message.hpp" namespace CaDiCaL { /*------------------------------------------------------------------------*/ // Compactifying removes holes generated by inactive variables (fixed, // eliminated or substituted) by mapping active variables indices down to a // contiguous interval of indices. /*------------------------------------------------------------------------*/ bool Internal::compactifying () { if (level) return false; if (!opts.compact) return false; if (stats.conflicts < lim.compact) return false; int inactive = max_var - active_variables (); assert (inactive >= 0); if (!inactive) return false; return inactive >= opts.compactlim * max_var; } /*------------------------------------------------------------------------*/ // Map data in old array 'NAME' to new position as given by 'map'. #define MAP_ARRAY(TYPE,NAME) \ do { \ TYPE * TMP = new TYPE [new_vsize]; \ for (int SRC = 1; SRC <= max_var; SRC++) { \ const int DST = map[SRC]; \ if (!DST) continue; \ TMP[DST] = NAME[SRC]; \ } \ memset (TMP, 0, sizeof TMP[0]); \ delete [] NAME; \ NAME = TMP; \ } while (0) /*------------------------------------------------------------------------*/ // Same as 'MAP_ARRAY' but two sided (positive & negative literal). #define MAP2_ARRAY(TYPE,NAME) \ do { \ TYPE * TMP = new TYPE [2*new_vsize]; \ for (int SRC = 1; SRC <= max_var; SRC++) { \ const int DST = map[SRC]; \ if (!DST) continue; \ TMP[2*DST] = NAME[2*SRC]; \ TMP[2*DST+1] = NAME[2*SRC+1]; \ } \ memset (TMP, 0, sizeof TMP[0]); \ delete [] NAME; \ NAME = TMP; \ } while (0) /*------------------------------------------------------------------------*/ // Map a 'vector<int>' of literals, flush inactive literals, resize and // shrink it to fit its new size after flushing. #define MAP_AND_FLUSH_INT_VECTOR(V) \ do { \ const const_int_iterator end = V.end (); \ int_iterator j = V.begin (); \ const_int_iterator i; \ for (i = j; i != end; i++) { \ const int SRC = *i; \ int DST = map[abs (SRC)]; \ if (!DST) continue; \ if (SRC < 0) DST = -DST; \ *j++ = DST; \ } \ V.resize (j - V.begin ()); \ shrink_vector (V); \ } while (0) /*------------------------------------------------------------------------*/ void Internal::compact () { START (compact); stats.compacts++; assert (!level); assert (!conflict); assert (clause.empty ()); assert (levels.empty ()); assert (analyzed.empty ()); assert (minimized.empty ()); assert (control.size () == 1); assert (resolved.empty ()); // We produce a compactifying garbage collector like map of old 'src' to // new 'dst' variables. Inactive variables are just skipped except for // fixed ones which will be mapped to the first fixed variable (in the // appropriate phase). This avoids to handle the case 'fixed value' // seperately as it is done in Lingeling, where fixed variables are // mapped to the internal variable '1'. // int * map, dst = 0, first_fixed = 0; NEW (map, int, max_var + 1); map[0] = 0; for (int src = 1; src <= max_var; src++) { const Flags & f = flags (src); if (f.active ()) map[src] = ++dst; else if (!f.fixed () || first_fixed) map[src] = 0; else map[first_fixed = src] = ++dst; } if (first_fixed) LOG ("found first fixed %d", first_fixed); else LOG ("no variable fixed"); const int new_max_var = dst; const size_t new_vsize = dst + 1; // Adjust to fit 'new_max_var'. /*----------------------------------------------------------------------*/ // In this first part we only map stuff without reallocation. /*----------------------------------------------------------------------*/ // Flush the external indices. This has to occur before we map 'vals'. { const int first_fixed_val = first_fixed ? val (first_fixed) : 0; for (int eidx = 1; eidx <= external->max_var; eidx++) { const int src = external->e2i[eidx]; if (!src) dst = 0; else { dst = map[abs (src)]; if (src < 0) dst = -dst; const int tmp = val (src); if (tmp) { assert (first_fixed_val); dst = map[first_fixed]; if (tmp != first_fixed_val) dst = -dst; } } LOG ("compact %ld maps external %d to internal %d", stats.compacts, eidx, dst); external->e2i[eidx] = dst; } } // Map the literals in all clauses. { const const_clause_iterator end = clauses.end (); const_clause_iterator i; for (i = clauses.begin (); i != end; i++) { Clause * c = *i; assert (!c->garbage); const const_literal_iterator eoc = c->end (); literal_iterator j; for (j = c->begin (); j != eoc; j++) { const int lit = *j; assert (active (lit)); int dst = map[abs (lit)]; if (lit < 0) dst = -dst; assert (dst); *j = dst; } } } // Map the blocking literals in all watches. // if (watches ()) { for (int idx = 1; idx <= max_var; idx++) { for (int sign = -1; sign <= 1; sign += 2) { const int lit = sign*idx; Watches & ws = watches (lit); assert (active (lit) || ws.empty ()); const const_watch_iterator end = ws.end (); watch_iterator i; for (i = ws.begin (); i != end; i++) { const int blit = i->blit; assert (active (blit)); int dst = map[abs (blit)]; if (blit < 0) dst = -dst; assert (dst); i->blit = dst; } } } } // We first flush inactive variables and map the links in the queue. This // has to be done before we map the actual links data structure 'ltab'. { int prev = 0, mapped_prev = 0, next; for (int idx = queue.first; idx; idx = next) { Link * l = ltab + idx; next = l->next; if (idx == first_fixed) continue; const int dst = map[idx]; if (!dst) continue; assert (active (idx)); if (prev) ltab[prev].next = dst; else queue.first = dst; l->prev = mapped_prev; mapped_prev = dst; prev = idx; } if (prev) ltab[prev].next = 0; else queue.first = 0; queue.unassigned = queue.last = mapped_prev; } /*----------------------------------------------------------------------*/ // In this second part we not only map stuff but also reallocate memory. /*----------------------------------------------------------------------*/ // Now we continue in reverse order of allocated bytes, e.g., see // 'Internal::enlarge' which reallocates in order of allocated bytes. MAP_ARRAY (Flags, ftab); MAP_ARRAY (signed char, marks); MAP_ARRAY (signed char, phases); // Special case for 'val' as always since for 'val' we trade branch less // code for memory and always allocated an [-maxvar,...,maxvar] array. { signed char * new_vals = new signed char [2*new_vsize]; new_vals += new_vsize; for (int src = -max_var; src <= -1; src++) new_vals[-map[-src]] = vals[src]; for (int src = 1; src <= max_var; src++) new_vals[map[src]] = vals[src]; new_vals[0] = 0; vals -= vsize; delete [] vals; vals = new_vals; } MAP_ARRAY (int, i2e); MAP2_ARRAY (int, ptab); MAP_ARRAY (long, btab); if (ntab2) MAP_ARRAY (long, ntab2); MAP_ARRAY (Link, ltab); MAP_ARRAY (Var, vtab); if (ntab) MAP2_ARRAY (long, ntab); if (wtab) MAP2_ARRAY (Watches, wtab); if (otab) MAP2_ARRAY (Occs, otab); if (big) MAP2_ARRAY (Bins, big); assert (propagated == trail.size ()); MAP_AND_FLUSH_INT_VECTOR (trail); propagated = trail.size (); if (!probes.empty ()) MAP_AND_FLUSH_INT_VECTOR (probes); // The simplest way to map the elimination schedule is to get all elements // from the heap and reinsert them. This could be slightly improved in // terms of speed if we add a 'flush (int * map)' function to 'Heap', but // is pretty complicated and would require that the 'Heap' knows that // mapped elements with 'zero' destination should be flushed. Note that // we use stable heap sorting. // if (!esched.empty ()) { vector<int> saved; while (!esched.empty ()) { const int src = esched.front (); esched.pop_front (); const int dst = map [src]; if (dst && src != first_fixed) saved.push_back (dst); } esched.clear (); const const_int_iterator end = saved.end (); const_int_iterator i; for (i = saved.begin (); i != end; i++) esched.push_back (*i); esched.shrink (); } /*----------------------------------------------------------------------*/ DEL (map, int, max_var); VRB ("compact", stats.compacts, "reducing internal variables from %d to %d", max_var, new_max_var); max_var = new_max_var; vsize = new_vsize; stats.now.fixed = first_fixed ? 1 : 0; stats.now.substituted = stats.now.eliminated = 0; inc.compact += opts.compactint; lim.compact = stats.conflicts + inc.compact; report ('c'); STOP (compact); } }; <commit_msg>more compact<commit_after>#include "internal.hpp" #include "external.hpp" #include "macros.hpp" #include "message.hpp" namespace CaDiCaL { /*------------------------------------------------------------------------*/ // Compactifying removes holes generated by inactive variables (fixed, // eliminated or substituted) by mapping active variables indices down to a // contiguous interval of indices. /*------------------------------------------------------------------------*/ bool Internal::compactifying () { if (level) return false; if (!opts.compact) return false; if (stats.conflicts < lim.compact) return false; int inactive = max_var - active_variables (); assert (inactive >= 0); if (!inactive) return false; return inactive >= opts.compactlim * max_var; } /*------------------------------------------------------------------------*/ // Map old internal literal 'SRC' to new internal literal 'DST'. This would // be trivially just a look up into the 'map' created in 'compact' (caring // about signedness of 'SRC' though), except that fixed variables have all // to be mapped to the first fixed variable 'first_fixed', which makes it // more tricky. // #define MAP_LIT(SRC,DST) \ do { \ int OLD = (SRC); \ assert (OLD), assert (abs (OLD) <= max_var); \ int RES = map[abs (OLD)]; \ if (!RES) { \ assert (!level); \ const int TMP = val (OLD); \ assert (TMP); \ assert (first_fixed); \ RES = first_fixed; \ if (TMP != first_fixed_val) RES = -RES; \ } else if ((OLD) < 0) RES = -RES; \ assert (RES), assert (abs (RES) <= new_max_var); \ (DST) = RES; \ } while (0) // Map data in old array 'NAME' to new position as given by 'map'. // #define MAP_ARRAY(TYPE,NAME) \ do { \ TYPE * TMP = new TYPE [new_vsize]; \ for (int SRC = 1; SRC <= max_var; SRC++) { \ const int DST = map[SRC]; \ if (!DST) continue; \ TMP[DST] = NAME[SRC]; \ } \ memset (TMP, 0, sizeof TMP[0]); \ delete [] NAME; \ NAME = TMP; \ } while (0) // Same as 'MAP_ARRAY' but two sided (positive & negative literal). // #define MAP2_ARRAY(TYPE,NAME) \ do { \ TYPE * TMP = new TYPE [2*new_vsize]; \ for (int SRC = 1; SRC <= max_var; SRC++) { \ const int DST = map[SRC]; \ if (!DST) continue; \ TMP[2*DST] = NAME[2*SRC]; \ TMP[2*DST+1] = NAME[2*SRC+1]; \ } \ memset (TMP, 0, sizeof TMP[0]); \ delete [] NAME; \ NAME = TMP; \ } while (0) // Map a 'vector<int>' of literals, flush inactive literals, resize and // shrink it to fit its new size after flushing. // #define MAP_AND_FLUSH_INT_VECTOR(V) \ do { \ const const_int_iterator end = V.end (); \ int_iterator j = V.begin (); \ const_int_iterator i; \ for (i = j; i != end; i++) { \ const int SRC = *i; \ int DST = map[abs (SRC)]; \ if (!DST) continue; \ if (SRC < 0) DST = -DST; \ *j++ = DST; \ } \ V.resize (j - V.begin ()); \ shrink_vector (V); \ } while (0) /*------------------------------------------------------------------------*/ void Internal::compact () { START (compact); stats.compacts++; assert (!level); assert (!conflict); assert (clause.empty ()); assert (levels.empty ()); assert (analyzed.empty ()); assert (minimized.empty ()); assert (control.size () == 1); assert (resolved.empty ()); // We produce a compactifying garbage collector like map of old 'src' to // new 'dst' variables. Inactive variables are just skipped except for // fixed ones which will be mapped to the first fixed variable (in the // appropriate phase). This avoids to handle the case 'fixed value' // seperately as it is done in Lingeling, where fixed variables are // mapped to the internal variable '1'. // int * map, new_max_var = 0, first_fixed = 0; NEW (map, int, max_var + 1); map[0] = 0; for (int src = 1; src <= max_var; src++) { const Flags & f = flags (src); if (f.active ()) map[src] = ++new_max_var; else if (!f.fixed () || first_fixed) map[src] = 0; else map[first_fixed = src] = ++new_max_var; } const int first_fixed_val = first_fixed ? val (first_fixed) : 0; if (first_fixed) LOG ("found first fixed %d", sign (first_fixed_val)*first_fixed); else LOG ("no variable fixed"); const size_t new_vsize = new_max_var + 1; // Adjust to fit 'new_max_var'. /*----------------------------------------------------------------------*/ // In this first part we only map stuff without reallocation. /*----------------------------------------------------------------------*/ // Flush the external indices. This has to occur before we map 'vals'. { for (int eidx = 1; eidx <= external->max_var; eidx++) { const int src = external->e2i[eidx]; int dst = 0; if (src) MAP_LIT (src, dst); LOG ("compact %ld maps external %d to internal %d from %d", stats.compacts, eidx, dst, src); external->e2i[eidx] = dst; } } // Map the literals in all clauses. { const const_clause_iterator end = clauses.end (); const_clause_iterator i; for (i = clauses.begin (); i != end; i++) { Clause * c = *i; const const_literal_iterator eoc = c->end (); literal_iterator j; for (j = c->begin (); j != eoc; j++) MAP_LIT (*j, *j); } } // Map the blocking literals in all watches. // if (watches ()) { for (int idx = 1; idx <= max_var; idx++) { for (int sign = -1; sign <= 1; sign += 2) { const int lit = sign*idx; Watches & ws = watches (lit); const const_watch_iterator end = ws.end (); watch_iterator i; for (i = ws.begin (); i != end; i++) MAP_LIT (i->blit, i->blit); } } } // We first flush inactive variables and map the links in the queue. This // has to be done before we map the actual links data structure 'ltab'. { int prev = 0, mapped_prev = 0, next; for (int idx = queue.first; idx; idx = next) { Link * l = ltab + idx; next = l->next; if (idx == first_fixed) continue; const int dst = map[idx]; if (!dst) continue; assert (active (idx)); if (prev) ltab[prev].next = dst; else queue.first = dst; l->prev = mapped_prev; mapped_prev = dst; prev = idx; } if (prev) ltab[prev].next = 0; else queue.first = 0; queue.unassigned = queue.last = mapped_prev; } /*----------------------------------------------------------------------*/ // In this second part we not only map stuff but also reallocate memory. /*----------------------------------------------------------------------*/ // Now we continue in reverse order of allocated bytes, e.g., see // 'Internal::enlarge' which reallocates in order of allocated bytes. MAP_ARRAY (Flags, ftab); MAP_ARRAY (signed char, marks); MAP_ARRAY (signed char, phases); // Special case for 'val' as always since for 'val' we trade branch less // code for memory and always allocated an [-maxvar,...,maxvar] array. { signed char * new_vals = new signed char [2*new_vsize]; new_vals += new_vsize; for (int src = -max_var; src <= -1; src++) new_vals[-map[-src]] = vals[src]; for (int src = 1; src <= max_var; src++) new_vals[map[src]] = vals[src]; new_vals[0] = 0; vals -= vsize; delete [] vals; vals = new_vals; } MAP_ARRAY (int, i2e); MAP2_ARRAY (int, ptab); MAP_ARRAY (long, btab); if (ntab2) MAP_ARRAY (long, ntab2); MAP_ARRAY (Link, ltab); MAP_ARRAY (Var, vtab); if (ntab) MAP2_ARRAY (long, ntab); if (wtab) MAP2_ARRAY (Watches, wtab); if (otab) MAP2_ARRAY (Occs, otab); if (big) MAP2_ARRAY (Bins, big); assert (propagated == trail.size ()); MAP_AND_FLUSH_INT_VECTOR (trail); propagated = trail.size (); if (first_fixed) { assert (trail.size () == 1); var (first_fixed).trail = 0; } else assert (trail.empty ()); if (!probes.empty ()) MAP_AND_FLUSH_INT_VECTOR (probes); // The simplest way to map the elimination schedule is to get all elements // from the heap and reinsert them. This could be slightly improved in // terms of speed if we add a 'flush (int * map)' function to 'Heap', but // is pretty complicated and would require that the 'Heap' knows that // mapped elements with 'zero' destination should be flushed. Note that // we use stable heap sorting. // if (!esched.empty ()) { vector<int> saved; while (!esched.empty ()) { const int src = esched.front (); esched.pop_front (); const int dst = map [src]; if (dst && src != first_fixed) saved.push_back (dst); } esched.clear (); const const_int_iterator end = saved.end (); const_int_iterator i; for (i = saved.begin (); i != end; i++) esched.push_back (*i); esched.shrink (); } /*----------------------------------------------------------------------*/ DEL (map, int, max_var); VRB ("compact", stats.compacts, "reducing internal variables from %d to %d", max_var, new_max_var); max_var = new_max_var; vsize = new_vsize; stats.now.fixed = first_fixed ? 1 : 0; stats.now.substituted = stats.now.eliminated = 0; inc.compact += opts.compactint; lim.compact = stats.conflicts + inc.compact; report ('c'); STOP (compact); } }; <|endoftext|>
<commit_before>/// /// @file pi_deleglise_rivat_parallel2.cpp /// @brief Parallel implementation of the Deleglise-Rivat prime /// counting algorithm. Compared to /// pi_deleglise_rivat_parallel1.cpp this version uses /// compression (FactorTable & PiTable) to reduce the memory /// usage. /// /// Copyright (C) 2015 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <primecount-internal.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <S1.hpp> #include "S2.hpp" #include <stdint.h> #include <algorithm> #include <iostream> #include <iomanip> #include <vector> using namespace std; using namespace primecount; namespace { /// Calculate the contribution of the special leaves. /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t c, int64_t s2_approx, int threads) { int64_t limit = z + 1; threads = validate_threads(threads, limit); int64_t s2_trivial = S2_trivial(x, y, z, c, threads); int64_t s2_easy = S2_easy(x, y, z, c, threads); int64_t s2_hard_approx = s2_approx - (s2_trivial + s2_easy); int64_t s2_hard = S2_hard(x, y, z, c, s2_hard_approx, threads); int64_t s2 = s2_trivial + s2_easy + s2_hard; return s2; } /// alpha is a tuning factor which should grow like (log(x))^3 /// for the Deleglise-Rivat prime counting algorithm. /// double compute_alpha(int64_t x) { double d = (double) x; double alpha = (get_alpha() >= 1) ? get_alpha() : log(d) * log(d) * log(d) / 1200; return in_between(1, alpha, iroot<6>(x)); } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat_parallel2(int64_t x, int threads) { if (x < 2) return 0; double alpha = compute_alpha(x); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = x / y; if (print_status()) { cout << endl; cout << "=== pi_deleglise_rivat_parallel2(x) ===" << endl; cout << "pi(x) = S1 + S2 + pi(y) - 1 - P2" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "alpha = " << fixed << setprecision(3) << alpha << endl; cout << "c = " << PhiTiny::max_a() << endl; cout << "threads = " << validate_threads(threads) << endl; } int64_t p2 = P2(x, y, threads); int64_t pi_y = pi_legendre(y, 1); int64_t c = min(pi_y, PhiTiny::max_a()); int64_t s1 = S1(x, y, c, threads); int64_t s2_approx = S2_approx(x, pi_y, p2, s1); int64_t s2 = S2(x, y, z, c, s2_approx, threads); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file pi_deleglise_rivat_parallel2.cpp /// @brief Parallel implementation of the Deleglise-Rivat prime /// counting algorithm. Compared to /// pi_deleglise_rivat_parallel1.cpp this version uses /// compression (FactorTable & PiTable) to reduce the memory /// usage. /// /// Copyright (C) 2015 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <primecount-internal.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <S1.hpp> #include "S2.hpp" #include <stdint.h> #include <algorithm> #include <iostream> #include <iomanip> #include <vector> using namespace std; using namespace primecount; namespace { /// Calculate the contribution of the special leaves. /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t c, int64_t s2_approx, int threads) { int64_t limit = z + 1; threads = validate_threads(threads, limit); int64_t s2_trivial = S2_trivial(x, y, z, c, threads); int64_t s2_easy = S2_easy(x, y, z, c, threads); int64_t s2_hard_approx = s2_approx - (s2_trivial + s2_easy); int64_t s2_hard = S2_hard(x, y, z, c, s2_hard_approx, threads); int64_t s2 = s2_trivial + s2_easy + s2_hard; return s2; } /// alpha is a tuning factor which should grow like (log(x))^3 /// for the Deleglise-Rivat prime counting algorithm. /// double compute_alpha(int64_t x) { double d = (double) x; double alpha = (get_alpha() >= 1) ? get_alpha() : log(d) * log(d) * log(d) / 1200; return in_between(1, alpha, iroot<6>(x)); } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat_parallel2(int64_t x, int threads) { if (x < 2) return 0; double alpha = compute_alpha(x); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = x / y; int64_t pi_y = pi_legendre(y, 1); int64_t c = min(pi_y, PhiTiny::max_a()); if (print_status()) { cout << endl; cout << "=== pi_deleglise_rivat_parallel2(x) ===" << endl; cout << "pi(x) = S1 + S2 + pi(y) - 1 - P2" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "alpha = " << fixed << setprecision(3) << alpha << endl; cout << "c = " << c << endl; cout << "threads = " << validate_threads(threads) << endl; } int64_t p2 = P2(x, y, threads); int64_t s1 = S1(x, y, c, threads); int64_t s2_approx = S2_approx(x, pi_y, p2, s1); int64_t s2 = S2(x, y, z, c, s2_approx, threads); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount <|endoftext|>
<commit_before>#ifndef SLIC3R_FIELD_HPP #define SLIC3R_FIELD_HPP #include <functional> #include <string> #include <limits> #include <boost/any.hpp> #include "ConfigBase.hpp" #include "Log.hpp" #include "wx/spinctrl.h" #include "wx/checkbox.h" #include "wx/textctrl.h" namespace Slic3r { namespace GUI { using namespace std::string_literals; class UI_Window { public: UI_Window(wxWindow* _parent, Slic3r::ConfigOptionDef _opt) : parent(_parent), opt(_opt) {}; virtual ~UI_Window() = default; /// Don't trigger on_change when this is true. bool disable_change_event {false}; /// Set the underlying control to the value (cast it and throw bad_any_cast if there are problems). virtual void set_value(boost::any value) = 0; /// Enables the underlying UI widget. void enable() { this->window->Enable(); } /// Disables the underlying UI widget. void disable() { this->window->Disable(); } /// Set the underlying widget to either enabled or disabled. void toggle(bool enable = true) { enable ? this->enable() : this->disable(); } /// Getter functions for UI_Window items. virtual bool get_bool() { Slic3r::Log::warn(this->LogChannel(), "get_bool does not exist"s); return false; } //< return false all the time if this is not implemented. virtual int get_int() { Slic3r::Log::warn(this->LogChannel(), "get_int does not exist"s); return 0; } //< return 0 all the time if this is not implemented. virtual std::string get_string() { Slic3r::Log::warn(this->LogChannel(), "get_string does not exist"s); return 0; } //< return 0 all the time if this is not implemented. /// Function to call when focus leaves. std::function<void (const std::string&)> on_kill_focus {nullptr}; protected: wxWindow* parent {nullptr}; wxWindow* window {nullptr}; //< Pointer copy of the derived classes const Slic3r::ConfigOptionDef opt; //< Reference to the UI-specific bits of this option virtual std::string LogChannel() { return "UI_Window"s; } virtual void _on_change(std::string opt_id) = 0; /// Define a default size for derived classes. wxSize _default_size() { return wxSize((opt.width >= 0 ? opt.width : 60), (opt.height != -1 ? opt.height : -1)); } }; class UI_Checkbox : public UI_Window { public: UI_Checkbox(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID checkid = wxID_ANY) : UI_Window(parent, _opt) { _check = new wxCheckBox(parent, checkid, ""); this->window = _check; // Set some defaults. if (this->opt.readonly) { this->_check->Disable(); } if (this->opt.default_value != nullptr) { this->_check->SetValue(this->opt.default_value->getBool()); } // Set up event handlers _check->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); }); _check->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus("");} e.Skip(); }); } ~UI_Checkbox() { _check->Destroy(); } /// Returns a bare pointer to the underlying checkbox, usually for test interface wxCheckBox* check() { return _check; } /// Returns the value of the enclosed checkbox. /// Implements get_bool virtual bool get_bool() override { return _check->GetValue();} /// Casts the containing value to boolean and sets the built-in checkbox appropriately. /// implements set_value virtual void set_value(boost::any value) override { this->_check->SetValue(boost::any_cast<bool>(value)); } /// Function to call when the contents of this change. std::function<void (const std::string&, bool value)> on_change {nullptr}; protected: wxCheckBox* _check {nullptr}; virtual std::string LogChannel() override { return "UI_Checkbox"s; } void _on_change(std::string opt_id) { if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) { this->on_change(opt_id, this->get_bool()); } } }; class UI_SpinCtrl : public UI_Window { public: UI_SpinCtrl(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID spinid = wxID_ANY) : UI_Window(parent, _opt) { /// Initialize and set defaults, if available. _spin = new wxSpinCtrl(parent, spinid, "", wxDefaultPosition, _default_size(), 0, (opt.min > 0 ? opt.min : 0), (opt.max > 0 ? opt.max : std::numeric_limits<int>::max()), (opt.default_value != NULL ? opt.default_value->getInt() : 0)); window = _spin; // Set up event handlers _spin->Bind(wxEVT_SPINCTRL, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); }); _spin->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus("");} e.Skip(); }); } ~UI_SpinCtrl() { _spin->Destroy();} int get_int() { return this->_spin->GetValue(); } void set_value(boost::any value) { this->_spin->SetValue(boost::any_cast<int>(value)); } /// Access method for the underlying SpinCtrl wxSpinCtrl* spinctrl() { return _spin; } /// Function to call when the contents of this change. std::function<void (const std::string&, int value)> on_change {nullptr}; protected: virtual std::string LogChannel() { return "UI_SpinCtrl"s; } void _on_change(std::string opt_id) { if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) { this->on_change(opt_id, this->get_int()); } } private: wxSpinCtrl* _spin {nullptr}; int _tmp {0}; }; class UI_TextCtrl : public UI_Window { public: UI_TextCtrl(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID id = wxID_ANY) : UI_Window(parent, _opt) { int style {0}; if (opt.multiline) { style |= wxHSCROLL; style |= wxTE_MULTILINE; } else { style |= wxTE_PROCESS_ENTER; } /// Initialize and set defaults, if available. _text = new wxTextCtrl(parent, id, (opt.default_value != NULL ? wxString(opt.default_value->getString()) : wxString()), wxDefaultPosition, _default_size(), style); window = _text; // Set up event handlers _text->Bind(wxEVT_TEXT_ENTER, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); }); _text->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus("");} e.Skip(); }); } ~UI_TextCtrl() { _text->Destroy(); } std::string get_string() { return this->_text->GetValue().ToStdString(); } void set_value(boost::any value) { this->_text->SetValue(boost::any_cast<std::string>(value)); } /// Access method for the underlying SpinCtrl wxTextCtrl* textctrl() { return _text; } /// Function to call when the contents of this change. std::function<void (const std::string&, std::string value)> on_change {nullptr}; protected: virtual std::string LogChannel() { return "UI_TextCtrl"s; } void _on_change(std::string opt_id) { if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) { this->on_change(opt_id, this->get_string()); } } private: wxTextCtrl* _text {nullptr}; int _tmp {0}; }; } } // Namespace Slic3r::GUI #endif // SLIC3R_FIELD_HPP <commit_msg>Trigger on_change when focus is lost for Spinctrls and textctrls.<commit_after>#ifndef SLIC3R_FIELD_HPP #define SLIC3R_FIELD_HPP #include <functional> #include <string> #include <limits> #include <boost/any.hpp> #include "ConfigBase.hpp" #include "Log.hpp" #include "wx/spinctrl.h" #include "wx/checkbox.h" #include "wx/textctrl.h" namespace Slic3r { namespace GUI { using namespace std::string_literals; class UI_Window { public: UI_Window(wxWindow* _parent, Slic3r::ConfigOptionDef _opt) : parent(_parent), opt(_opt) {}; virtual ~UI_Window() = default; /// Don't trigger on_change when this is true. bool disable_change_event {false}; /// Set the underlying control to the value (cast it and throw bad_any_cast if there are problems). virtual void set_value(boost::any value) = 0; /// Enables the underlying UI widget. void enable() { this->window->Enable(); } /// Disables the underlying UI widget. void disable() { this->window->Disable(); } /// Set the underlying widget to either enabled or disabled. void toggle(bool enable = true) { enable ? this->enable() : this->disable(); } /// Getter functions for UI_Window items. virtual bool get_bool() { Slic3r::Log::warn(this->LogChannel(), "get_bool does not exist"s); return false; } //< return false all the time if this is not implemented. virtual int get_int() { Slic3r::Log::warn(this->LogChannel(), "get_int does not exist"s); return 0; } //< return 0 all the time if this is not implemented. virtual std::string get_string() { Slic3r::Log::warn(this->LogChannel(), "get_string does not exist"s); return 0; } //< return 0 all the time if this is not implemented. /// Function to call when focus leaves. std::function<void (const std::string&)> on_kill_focus {nullptr}; protected: wxWindow* parent {nullptr}; wxWindow* window {nullptr}; //< Pointer copy of the derived classes const Slic3r::ConfigOptionDef opt; //< Reference to the UI-specific bits of this option virtual std::string LogChannel() { return "UI_Window"s; } virtual void _on_change(std::string opt_id) = 0; /// Define a default size for derived classes. wxSize _default_size() { return wxSize((opt.width >= 0 ? opt.width : 60), (opt.height != -1 ? opt.height : -1)); } }; class UI_Checkbox : public UI_Window { public: UI_Checkbox(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID checkid = wxID_ANY) : UI_Window(parent, _opt) { _check = new wxCheckBox(parent, checkid, ""); this->window = _check; // Set some defaults. if (this->opt.readonly) { this->_check->Disable(); } if (this->opt.default_value != nullptr) { this->_check->SetValue(this->opt.default_value->getBool()); } // Set up event handlers _check->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); }); _check->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus("");} e.Skip(); }); } ~UI_Checkbox() { _check->Destroy(); } /// Returns a bare pointer to the underlying checkbox, usually for test interface wxCheckBox* check() { return _check; } /// Returns the value of the enclosed checkbox. /// Implements get_bool virtual bool get_bool() override { return _check->GetValue();} /// Casts the containing value to boolean and sets the built-in checkbox appropriately. /// implements set_value virtual void set_value(boost::any value) override { this->_check->SetValue(boost::any_cast<bool>(value)); } /// Function to call when the contents of this change. std::function<void (const std::string&, bool value)> on_change {nullptr}; protected: wxCheckBox* _check {nullptr}; virtual std::string LogChannel() override { return "UI_Checkbox"s; } void _on_change(std::string opt_id) { if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) { this->on_change(opt_id, this->get_bool()); } } }; class UI_SpinCtrl : public UI_Window { public: UI_SpinCtrl(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID spinid = wxID_ANY) : UI_Window(parent, _opt) { /// Initialize and set defaults, if available. _spin = new wxSpinCtrl(parent, spinid, "", wxDefaultPosition, _default_size(), 0, (opt.min > 0 ? opt.min : 0), (opt.max > 0 ? opt.max : std::numeric_limits<int>::max()), (opt.default_value != NULL ? opt.default_value->getInt() : 0)); window = _spin; // Set up event handlers _spin->Bind(wxEVT_SPINCTRL, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); }); _spin->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) { this->_on_change(""); this->on_kill_focus("");} e.Skip(); }); } ~UI_SpinCtrl() { _spin->Destroy();} int get_int() { return this->_spin->GetValue(); } void set_value(boost::any value) { this->_spin->SetValue(boost::any_cast<int>(value)); } /// Access method for the underlying SpinCtrl wxSpinCtrl* spinctrl() { return _spin; } /// Function to call when the contents of this change. std::function<void (const std::string&, int value)> on_change {nullptr}; protected: virtual std::string LogChannel() { return "UI_SpinCtrl"s; } void _on_change(std::string opt_id) { if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) { this->on_change(opt_id, this->get_int()); } } private: wxSpinCtrl* _spin {nullptr}; int _tmp {0}; }; class UI_TextCtrl : public UI_Window { public: UI_TextCtrl(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID id = wxID_ANY) : UI_Window(parent, _opt) { int style {0}; if (opt.multiline) { style |= wxHSCROLL; style |= wxTE_MULTILINE; } else { style |= wxTE_PROCESS_ENTER; } /// Initialize and set defaults, if available. _text = new wxTextCtrl(parent, id, (opt.default_value != NULL ? wxString(opt.default_value->getString()) : wxString()), wxDefaultPosition, _default_size(), style); window = _text; // Set up event handlers if (!opt.multiline) { _text->Bind(wxEVT_TEXT_ENTER, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); }); } _text->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus(""); this->_on_change("");} e.Skip(); }); } ~UI_TextCtrl() { _text->Destroy(); } std::string get_string() { return this->_text->GetValue().ToStdString(); } void set_value(boost::any value) { this->_text->SetValue(boost::any_cast<std::string>(value)); } /// Access method for the underlying TextCtrl wxTextCtrl* textctrl() { return _text; } /// Function to call when the contents of this change. std::function<void (const std::string&, std::string value)> on_change {nullptr}; protected: virtual std::string LogChannel() { return "UI_TextCtrl"s; } void _on_change(std::string opt_id) { if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) { this->on_change(opt_id, this->get_string()); } } private: wxTextCtrl* _text {nullptr}; int _tmp {0}; }; } } // Namespace Slic3r::GUI #endif // SLIC3R_FIELD_HPP <|endoftext|>
<commit_before>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Disa Mhembere ([email protected]) * * This file is part of FlashMatrix. * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kmeans.h" #define KM_TEST 1 #define VERBOSE 0 #ifdef PROFILER #include <gperftools/profiler.h> #endif #include "libgraph-algs/sem_kmeans_util.h" #include "libgraph-algs/prune_stats.h" #include "libgraph-algs/clusters.h" namespace { static unsigned NUM_COLS; static size_t K; static unsigned NUM_ROWS; short OMP_MAX_THREADS; static unsigned g_num_changed = 0; static const unsigned INVALID_CLUSTER_ID = std::numeric_limits<unsigned>::max(); static dist_type_t g_dist_type; static struct timeval start, end; static init_type_t g_init_type; /** * \brief This initializes clusters by randomly choosing sample * membership in a cluster. * See: http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods * \param cluster_assignments Which cluster each sample falls into. */ static void random_partition_init(unsigned* cluster_assignments, const double* matrix, prune_clusters::ptr clusters) { BOOST_LOG_TRIVIAL(info) << "Random init start"; // #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments) for (unsigned row = 0; row < NUM_ROWS; row++) { size_t asgnd_clust = random() % K; // 0...K clusters->add_member(&matrix[row*NUM_COLS], asgnd_clust); cluster_assignments[row] = asgnd_clust; } // NOTE: M-Step called in compute func to update cluster counts & centers #if VERBOSE printf("After rand paritions cluster_asgns: "); print_arr(cluster_assignments, NUM_ROWS); #endif BOOST_LOG_TRIVIAL(info) << "Random init end\n"; } /** * \brief Forgy init takes `K` random samples from the matrix * and uses them as cluster centers. * \param matrix the flattened matrix who's rows are being clustered. * \param clusters The cluster centers (means) flattened matrix. */ static void forgy_init(const double* matrix, prune_clusters::ptr clusters) { BOOST_LOG_TRIVIAL(info) << "Forgy init start"; for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { // 0...K unsigned rand_idx = random() % (NUM_ROWS - 1); // 0...(n-1) clusters->set_mean(&matrix[rand_idx*NUM_COLS], clust_idx); } BOOST_LOG_TRIVIAL(info) << "Forgy init end"; } /** * \brief A parallel version of the kmeans++ initialization alg. * See: http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf for algorithm */ static void kmeanspp_init(const double* matrix, prune_clusters::ptr clusters, unsigned* cluster_assignments, std::vector<double>& dist_v) { // Choose c1 uniiformly at random unsigned selected_idx = random() % NUM_ROWS; // 0...(NUM_ROWS-1) clusters->set_mean(&matrix[selected_idx*NUM_COLS], 0); dist_v[selected_idx] = 0.0; #if KM_TEST BOOST_LOG_TRIVIAL(info) << "\nChoosing " << selected_idx << " as center K = 0"; #endif unsigned clust_idx = 0; // The number of clusters assigned // Choose next center c_i with weighted prob while ((clust_idx + 1) < K) { double cum_dist = 0; #pragma omp parallel for reduction(+:cum_dist) shared (dist_v) for (size_t row = 0; row < NUM_ROWS; row++) { double dist = std::numeric_limits<double>::max(); if (g_dist_type == EUCL) // Per thread instance dist = eucl_dist(&matrix[row*NUM_COLS], &((clusters->get_means())[clust_idx*NUM_COLS]), NUM_COLS); else if (g_dist_type == COS) dist = cos_dist(&matrix[row*NUM_COLS], &((clusters->get_means())[clust_idx*NUM_COLS]), NUM_COLS); else BOOST_ASSERT_MSG(false, "Unknown distance metric!"); if (dist < dist_v[row]) { // Found a closer cluster than before dist_v[row] = dist; cluster_assignments[row] = selected_idx; } cum_dist += dist_v[row]; } cum_dist = (cum_dist * ((double)random())) / (RAND_MAX - 1.0); clust_idx++; for (size_t i=0; i < NUM_ROWS; i++) { cum_dist -= dist_v[i]; if (cum_dist <= 0) { #if KM_TEST BOOST_LOG_TRIVIAL(info) << "Choosing " << i << " as center K = " << clust_idx; #endif clusters->set_mean(&(matrix[i*NUM_COLS]), clust_idx); selected_idx = i; break; } } assert (cum_dist <= 0); } #if VERBOSE BOOST_LOG_TRIVIAL(info) << "\n\nOriginal matrix: "; print_mat(matrix, NUM_ROWS, NUM_COLS); BOOST_LOG_TRIVIAL(info) << "\nCluster centers after kmeans++"; clusters->print_means(); #endif } /** * \brief Update the cluster assignments while recomputing distance matrix. * \param matrix The flattened matrix who's rows are being clustered. * \param clusters The cluster centers (means) flattened matrix. * \param cluster_assignments Which cluster each sample falls into. */ static void E_step(const double* matrix, prune_clusters::ptr cls, unsigned* cluster_assignments, unsigned* cluster_assignment_counts, prune_stats::ptr ps=nullptr, const bool prune_init=false) { std::vector<clusters::ptr> pt_cl(OMP_MAX_THREADS); // Per thread changed cluster count. OMP_MAX_THREADS std::vector<size_t> pt_num_change(OMP_MAX_THREADS); for (int i = 0; i < OMP_MAX_THREADS; i++) pt_cl[i] = clusters::create(K, NUM_COLS); #pragma omp parallel for firstprivate(matrix, pt_cl)\ shared(cluster_assignments) schedule(static) for (unsigned row = 0; row < NUM_ROWS; row++) { size_t asgnd_clust = INVALID_CLUSTER_ID; double best, dist; dist = best = std::numeric_limits<double>::max(); for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { if (g_dist_type == EUCL) dist = eucl_dist(&matrix[row*NUM_COLS], &(cls->get_means()[clust_idx*NUM_COLS]), NUM_COLS); else if (g_dist_type == COS) dist = cos_dist(&matrix[row*NUM_COLS], &(cls->get_means()[clust_idx*NUM_COLS]), NUM_COLS); else BOOST_ASSERT_MSG(false, "Unknown distance metric!"); if (dist < best) { best = dist; asgnd_clust = clust_idx; } } BOOST_VERIFY(asgnd_clust != INVALID_CLUSTER_ID); if (asgnd_clust != cluster_assignments[row]) { pt_num_change[omp_get_thread_num()]++; } cluster_assignments[row] = asgnd_clust; pt_cl[omp_get_thread_num()]->add_member(&matrix[row*NUM_COLS], asgnd_clust); // Accumulate for local copies } #if VERBOSE BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts"; BOOST_LOG_TRIVIAL(info) << "Clearing cluster centers ..."; #endif cls->clear(); // Serial aggreate of OMP_MAX_THREADS vectors // TODO: Pool these for (int thd = 0; thd < OMP_MAX_THREADS; thd++) { // Updated the changed cluster count g_num_changed += pt_num_change[thd]; // Summation for cluster centers cls->peq(pt_cl[thd]); } unsigned chk_nmemb = 0; for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { cls->finalize(clust_idx); cluster_assignment_counts[clust_idx] = cls->get_num_members(clust_idx); chk_nmemb += cluster_assignment_counts[clust_idx]; } BOOST_VERIFY(chk_nmemb == NUM_ROWS); #if KM_TEST BOOST_LOG_TRIVIAL(info) << "Global number of changes: " << g_num_changed; #endif } } namespace fg { unsigned compute_kmeans(const double* matrix, double* clusters_ptr, unsigned* cluster_assignments, unsigned* cluster_assignment_counts, const unsigned num_rows, const unsigned num_cols, const size_t k, const unsigned MAX_ITERS, const int max_threads, const std::string init, const double tolerance, const std::string dist_type) { #ifdef PROFILER ProfilerStart("/mnt/nfs/disa/FlashGraph/flash-graph/matrix/min-tri-kmeans.perf"); #endif NUM_COLS = num_cols; K = k; NUM_ROWS = num_rows; assert(max_threads > 0); OMP_MAX_THREADS = std::min(max_threads, get_num_omp_threads()); omp_set_num_threads(OMP_MAX_THREADS); BOOST_LOG_TRIVIAL(info) << "Running on " << OMP_MAX_THREADS << " threads!"; // Check k if (K > NUM_ROWS || K < 2 || K == (unsigned)-1) { BOOST_LOG_TRIVIAL(fatal) << "'k' must be between 2 and the number of rows in the matrix" << "k = " << K; exit(-1); } gettimeofday(&start , NULL); /*** Begin VarInit of data structures ***/ std::fill(&cluster_assignments[0], (&cluster_assignments[0])+NUM_ROWS, -1); std::fill(&cluster_assignment_counts[0], (&cluster_assignment_counts[0])+K, 0); prune_clusters::ptr clusters = prune_clusters::create(K, NUM_COLS); if (init == "none") clusters->set_mean(clusters_ptr); // For pruning std::vector<double> dist_v; dist_v.assign(NUM_ROWS, std::numeric_limits<double>::max()); /*** End VarInit ***/ BOOST_LOG_TRIVIAL(info) << "Dist_type is " << dist_type; if (dist_type == "eucl") { g_dist_type = EUCL; } else if (dist_type == "cos") { g_dist_type = COS; } else { BOOST_LOG_TRIVIAL(fatal) << "[ERROR]: param dist_type must be one of: 'eucl', 'cos'.It is '" << dist_type << "'"; exit(-1); } if (init == "random") { random_partition_init(cluster_assignments, matrix, clusters); g_init_type = RANDOM; } else if (init == "forgy") { forgy_init(matrix, clusters); g_init_type = FORGY; } else if (init == "kmeanspp") { kmeanspp_init(matrix, clusters, cluster_assignments, dist_v); g_init_type = PLUSPLUS; } else if (init == "none") { g_init_type = NONE; } else { BOOST_LOG_TRIVIAL(fatal) << "[ERROR]: param init must be one of: " "'random', 'forgy', 'kmeanspp'.It is '" << init << "'"; exit(-1); } #if KM_TEST prune_stats::ptr ps = prune_stats::create(NUM_ROWS, K); #endif if (g_init_type == NONE || g_init_type == FORGY || g_init_type == RANDOM) { E_step(matrix, clusters, cluster_assignments, cluster_assignment_counts, ps, true); } BOOST_LOG_TRIVIAL(info) << "Init is '" << init << "'"; BOOST_LOG_TRIVIAL(info) << "Matrix K-means starting ..."; bool converged = false; std::string str_iters = MAX_ITERS == std::numeric_limits<unsigned>::max() ? "until convergence ...": std::to_string(MAX_ITERS) + " iterations ..."; BOOST_LOG_TRIVIAL(info) << "Computing " << str_iters; unsigned iter = 1; while (iter < MAX_ITERS) { // Hold cluster assignment counter BOOST_LOG_TRIVIAL(info) << "E-step Iteration " << iter << ". Computing cluster assignments ..."; E_step(matrix, clusters, cluster_assignments, cluster_assignment_counts, ps); #if KM_TEST printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K); #endif if (g_num_changed == 0 || ((g_num_changed/(double)NUM_ROWS)) <= tolerance) { converged = true; break; } else { g_num_changed = 0; } iter++; } gettimeofday(&end, NULL); BOOST_LOG_TRIVIAL(info) << "\n\nAlgorithmic time taken = " << time_diff(start, end) << " sec\n"; #ifdef PROFILER ProfilerStop(); #endif BOOST_LOG_TRIVIAL(info) << "\n******************************************\n"; if (converged) { BOOST_LOG_TRIVIAL(info) << "K-means converged in " << iter << " iterations"; } else { BOOST_LOG_TRIVIAL(warning) << "[Warning]: K-means failed to converge in " << iter << " iterations"; } BOOST_LOG_TRIVIAL(info) << "\n******************************************\n"; return iter; } } <commit_msg>[Matrix]: kmeans fairly well optimized @ .2s iterations<commit_after>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Disa Mhembere ([email protected]) * * This file is part of FlashMatrix. * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kmeans.h" #define KM_TEST 1 #define VERBOSE 0 #ifdef PROFILER #include <gperftools/profiler.h> #endif #include "libgraph-algs/sem_kmeans_util.h" #include "libgraph-algs/prune_stats.h" #include "libgraph-algs/clusters.h" namespace { static unsigned NUM_COLS; static size_t K; static unsigned NUM_ROWS; short OMP_MAX_THREADS; static unsigned g_num_changed = 0; static const unsigned INVALID_CLUSTER_ID = std::numeric_limits<unsigned>::max(); static dist_type_t g_dist_type; static struct timeval start, end; static init_type_t g_init_type; /** * \brief This initializes clusters by randomly choosing sample * membership in a cluster. * See: http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods * \param cluster_assignments Which cluster each sample falls into. */ static void random_partition_init(unsigned* cluster_assignments, const double* matrix, prune_clusters::ptr clusters) { BOOST_LOG_TRIVIAL(info) << "Random init start"; // #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments) for (unsigned row = 0; row < NUM_ROWS; row++) { size_t asgnd_clust = random() % K; // 0...K clusters->add_member(&matrix[row*NUM_COLS], asgnd_clust); cluster_assignments[row] = asgnd_clust; } // NOTE: M-Step called in compute func to update cluster counts & centers #if VERBOSE printf("After rand paritions cluster_asgns: "); print_arr(cluster_assignments, NUM_ROWS); #endif BOOST_LOG_TRIVIAL(info) << "Random init end\n"; } /** * \brief Forgy init takes `K` random samples from the matrix * and uses them as cluster centers. * \param matrix the flattened matrix who's rows are being clustered. * \param clusters The cluster centers (means) flattened matrix. */ static void forgy_init(const double* matrix, prune_clusters::ptr clusters) { BOOST_LOG_TRIVIAL(info) << "Forgy init start"; for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { // 0...K unsigned rand_idx = random() % (NUM_ROWS - 1); // 0...(n-1) clusters->set_mean(&matrix[rand_idx*NUM_COLS], clust_idx); } BOOST_LOG_TRIVIAL(info) << "Forgy init end"; } /** * \brief A parallel version of the kmeans++ initialization alg. * See: http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf for algorithm */ static void kmeanspp_init(const double* matrix, prune_clusters::ptr clusters, unsigned* cluster_assignments, std::vector<double>& dist_v) { // Choose c1 uniiformly at random unsigned selected_idx = random() % NUM_ROWS; // 0...(NUM_ROWS-1) clusters->set_mean(&matrix[selected_idx*NUM_COLS], 0); dist_v[selected_idx] = 0.0; #if KM_TEST BOOST_LOG_TRIVIAL(info) << "\nChoosing " << selected_idx << " as center K = 0"; #endif unsigned clust_idx = 0; // The number of clusters assigned // Choose next center c_i with weighted prob while ((clust_idx + 1) < K) { double cum_dist = 0; #pragma omp parallel for reduction(+:cum_dist) shared (dist_v) for (size_t row = 0; row < NUM_ROWS; row++) { double dist = std::numeric_limits<double>::max(); if (g_dist_type == EUCL) // Per thread instance dist = eucl_dist(&matrix[row*NUM_COLS], &((clusters->get_means())[clust_idx*NUM_COLS]), NUM_COLS); else if (g_dist_type == COS) dist = cos_dist(&matrix[row*NUM_COLS], &((clusters->get_means())[clust_idx*NUM_COLS]), NUM_COLS); else BOOST_ASSERT_MSG(false, "Unknown distance metric!"); if (dist < dist_v[row]) { // Found a closer cluster than before dist_v[row] = dist; cluster_assignments[row] = selected_idx; } cum_dist += dist_v[row]; } cum_dist = (cum_dist * ((double)random())) / (RAND_MAX - 1.0); clust_idx++; for (size_t i=0; i < NUM_ROWS; i++) { cum_dist -= dist_v[i]; if (cum_dist <= 0) { #if KM_TEST BOOST_LOG_TRIVIAL(info) << "Choosing " << i << " as center K = " << clust_idx; #endif clusters->set_mean(&(matrix[i*NUM_COLS]), clust_idx); selected_idx = i; break; } } assert (cum_dist <= 0); } #if VERBOSE BOOST_LOG_TRIVIAL(info) << "\n\nOriginal matrix: "; print_mat(matrix, NUM_ROWS, NUM_COLS); BOOST_LOG_TRIVIAL(info) << "\nCluster centers after kmeans++"; clusters->print_means(); #endif } /** * \brief Update the cluster assignments while recomputing distance matrix. * \param matrix The flattened matrix who's rows are being clustered. * \param clusters The cluster centers (means) flattened matrix. * \param cluster_assignments Which cluster each sample falls into. */ static void EM_step(const double* matrix, prune_clusters::ptr cls, unsigned* cluster_assignments, unsigned* cluster_assignment_counts, prune_stats::ptr ps=nullptr, const bool prune_init=false) { std::vector<clusters::ptr> pt_cl(OMP_MAX_THREADS); // Per thread changed cluster count. OMP_MAX_THREADS std::vector<size_t> pt_num_change(OMP_MAX_THREADS); for (int i = 0; i < OMP_MAX_THREADS; i++) pt_cl[i] = clusters::create(K, NUM_COLS); #pragma omp parallel for firstprivate(matrix, pt_cl)\ shared(cluster_assignments) schedule(static) for (unsigned row = 0; row < NUM_ROWS; row++) { size_t asgnd_clust = INVALID_CLUSTER_ID; double best, dist; dist = best = std::numeric_limits<double>::max(); for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { if (g_dist_type == EUCL) dist = eucl_dist(&matrix[row*NUM_COLS], &(cls->get_means()[clust_idx*NUM_COLS]), NUM_COLS); else if (g_dist_type == COS) dist = cos_dist(&matrix[row*NUM_COLS], &(cls->get_means()[clust_idx*NUM_COLS]), NUM_COLS); else BOOST_ASSERT_MSG(false, "Unknown distance metric!"); if (dist < best) { best = dist; asgnd_clust = clust_idx; } } BOOST_VERIFY(asgnd_clust != INVALID_CLUSTER_ID); if (asgnd_clust != cluster_assignments[row]) { pt_num_change[omp_get_thread_num()]++; } cluster_assignments[row] = asgnd_clust; pt_cl[omp_get_thread_num()]->add_member(&matrix[row*NUM_COLS], asgnd_clust); // Accumulate for local copies } #if VERBOSE BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts"; BOOST_LOG_TRIVIAL(info) << "Clearing cluster centers ..."; #endif cls->clear(); // Serial aggreate of OMP_MAX_THREADS vectors // TODO: Pool these for (int thd = 0; thd < OMP_MAX_THREADS; thd++) { // Updated the changed cluster count g_num_changed += pt_num_change[thd]; // Summation for cluster centers cls->peq(pt_cl[thd]); } unsigned chk_nmemb = 0; for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { cls->finalize(clust_idx); cluster_assignment_counts[clust_idx] = cls->get_num_members(clust_idx); chk_nmemb += cluster_assignment_counts[clust_idx]; } BOOST_VERIFY(chk_nmemb == NUM_ROWS); #if KM_TEST BOOST_LOG_TRIVIAL(info) << "Global number of changes: " << g_num_changed; #endif } } namespace fg { unsigned compute_kmeans(const double* matrix, double* clusters_ptr, unsigned* cluster_assignments, unsigned* cluster_assignment_counts, const unsigned num_rows, const unsigned num_cols, const size_t k, const unsigned MAX_ITERS, const int max_threads, const std::string init, const double tolerance, const std::string dist_type) { #ifdef PROFILER ProfilerStart("/mnt/nfs/disa/FlashGraph/flash-graph/matrix/kmeans.perf"); #endif NUM_COLS = num_cols; K = k; NUM_ROWS = num_rows; assert(max_threads > 0); OMP_MAX_THREADS = std::min(max_threads, get_num_omp_threads()); omp_set_num_threads(OMP_MAX_THREADS); BOOST_LOG_TRIVIAL(info) << "Running on " << OMP_MAX_THREADS << " threads!"; // Check k if (K > NUM_ROWS || K < 2 || K == (unsigned)-1) { BOOST_LOG_TRIVIAL(fatal) << "'k' must be between 2 and the number of rows in the matrix" << "k = " << K; exit(-1); } gettimeofday(&start , NULL); /*** Begin VarInit of data structures ***/ std::fill(&cluster_assignments[0], (&cluster_assignments[0])+NUM_ROWS, -1); std::fill(&cluster_assignment_counts[0], (&cluster_assignment_counts[0])+K, 0); prune_clusters::ptr clusters = prune_clusters::create(K, NUM_COLS); if (init == "none") clusters->set_mean(clusters_ptr); // For pruning std::vector<double> dist_v; dist_v.assign(NUM_ROWS, std::numeric_limits<double>::max()); /*** End VarInit ***/ BOOST_LOG_TRIVIAL(info) << "Dist_type is " << dist_type; if (dist_type == "eucl") { g_dist_type = EUCL; } else if (dist_type == "cos") { g_dist_type = COS; } else { BOOST_LOG_TRIVIAL(fatal) << "[ERROR]: param dist_type must be one of: 'eucl', 'cos'.It is '" << dist_type << "'"; exit(-1); } if (init == "random") { random_partition_init(cluster_assignments, matrix, clusters); g_init_type = RANDOM; } else if (init == "forgy") { forgy_init(matrix, clusters); g_init_type = FORGY; } else if (init == "kmeanspp") { kmeanspp_init(matrix, clusters, cluster_assignments, dist_v); g_init_type = PLUSPLUS; } else if (init == "none") { g_init_type = NONE; } else { BOOST_LOG_TRIVIAL(fatal) << "[ERROR]: param init must be one of: " "'random', 'forgy', 'kmeanspp'.It is '" << init << "'"; exit(-1); } #if KM_TEST prune_stats::ptr ps = prune_stats::create(NUM_ROWS, K); #endif if (g_init_type == NONE || g_init_type == FORGY || g_init_type == RANDOM) { EM_step(matrix, clusters, cluster_assignments, cluster_assignment_counts, ps, true); } BOOST_LOG_TRIVIAL(info) << "Init is '" << init << "'"; BOOST_LOG_TRIVIAL(info) << "Matrix K-means starting ..."; bool converged = false; std::string str_iters = MAX_ITERS == std::numeric_limits<unsigned>::max() ? "until convergence ...": std::to_string(MAX_ITERS) + " iterations ..."; BOOST_LOG_TRIVIAL(info) << "Computing " << str_iters; unsigned iter = 1; while (iter < MAX_ITERS) { // Hold cluster assignment counter BOOST_LOG_TRIVIAL(info) << "E-step Iteration " << iter << ". Computing cluster assignments ..."; EM_step(matrix, clusters, cluster_assignments, cluster_assignment_counts, ps); #if KM_TEST printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K); #endif if (g_num_changed == 0 || ((g_num_changed/(double)NUM_ROWS)) <= tolerance) { converged = true; break; } else { g_num_changed = 0; } iter++; } gettimeofday(&end, NULL); BOOST_LOG_TRIVIAL(info) << "\n\nAlgorithmic time taken = " << time_diff(start, end) << " sec\n"; #ifdef PROFILER ProfilerStop(); #endif BOOST_LOG_TRIVIAL(info) << "\n******************************************\n"; if (converged) { BOOST_LOG_TRIVIAL(info) << "K-means converged in " << iter << " iterations"; } else { BOOST_LOG_TRIVIAL(warning) << "[Warning]: K-means failed to converge in " << iter << " iterations"; } BOOST_LOG_TRIVIAL(info) << "\n******************************************\n"; return iter; } } <|endoftext|>
<commit_before>/* Persons Model Item Represents one person in the model Copyright (C) 2012 Martin Klapetek <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "personitem.h" #include "contactitem.h" #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Resource> #include <Nepomuk2/Variant> #include <Soprano/Vocabulary/NAO> #include <KDebug> PersonItem::PersonItem(const QUrl &personUri) { setData(personUri, PersonsModel::UriRole); } PersonItem::PersonItem(const Nepomuk2::Resource &person) { setData(person.uri(), PersonsModel::UriRole); setContacts(person.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList()); kDebug() << "new person" << text() << rowCount(); } QVariant PersonItem::queryChildrenForRole(int role) const { QVariant ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if (!value.isNull()) { ret = value; break; } } return ret; } QVariantList PersonItem::queryChildrenForRoleList(int role) const { QVariantList ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if (value.type() == QVariant::List) { ret += value.toList(); } else if (!value.isNull()) { ret += value; } } return ret; } QVariant PersonItem::data(int role) const { if (role == PersonsModel::PresenceTypeRole || role == PersonsModel::PresenceDisplayRole || role == PersonsModel::PresenceDecorationRole) { QVariantList presences = queryChildrenForRoleList(PersonsModel::PresenceTypeRole); //we find which position in the list contains the most online presence //and then we use that index to return the other roles int mostOnlineIndex = -1; int mostOnlinePresence = 999; for (int i = 0; i < presences.size(); i++) { int currentPresencePriority = presenceSortPriority(presences.at(i).toString()); if (currentPresencePriority < mostOnlinePresence) { mostOnlineIndex = i; mostOnlinePresence = currentPresencePriority; //if the most online is "available", //break as there can't be anything more online if (mostOnlinePresence == 0) { break; } } } Q_ASSERT(mostOnlineIndex != -1); switch (role) { case PersonsModel::PresenceTypeRole: return presences.at(mostOnlineIndex); case PersonsModel::PresenceDisplayRole: { const QVariantList presenceDisplayNames = queryChildrenForRoleList(PersonsModel::PresenceDisplayRole); return presenceDisplayNames.at(mostOnlineIndex); } case PersonsModel::PresenceDecorationRole: { const QVariantList presenceDecoration = queryChildrenForRoleList(PersonsModel::PresenceDecorationRole); return presenceDecoration.at(mostOnlineIndex); } } } if (role == PersonsModel::UriRole) { //uri for PersonItem is set using setData(...), so we need to query it from there return QStandardItem::data(role); } QVariantList ret; for (int i = 0; i < rowCount(); i++) { QVariant value; //if we're being asked for the child contacts uris, //we need to query the children for their UriRole if (role == PersonsModel::ChildContactsUriRole) { value = child(i)->data(PersonsModel::UriRole); } else { value = child(i)->data(role); } //these roles must return single QVariant if ((role == Qt::DisplayRole || role == Qt::DecorationRole) && !value.isNull()) { return value; } if (value.type() == QVariant::List) { ret += value.toList(); } else if (!value.isNull()) { ret += value; } } if (ret.isEmpty()) { //we need to return empty qvariant here, otherwise we'd get a qvariant //with empty qvariantlist, which would get parsed as non-empty qvariant return QVariant(); } return ret; } void PersonItem::removeContacts(const QList<QUrl> &contacts) { kDebug() << "remove contacts" << contacts; for (int i = 0; i < rowCount(); ) { QStandardItem *item = child(i); if (item && contacts.contains(item->data(PersonsModel::UriRole).toUrl())) { model()->invisibleRootItem()->appendRow(takeRow(i)); } else { ++i; } } emitDataChanged(); } void PersonItem::addContacts(const QList<QUrl> &_contacts) { QList<QUrl> contacts(_contacts); //get existing child-contacts and remove them from the new ones QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole); foreach (const QVariant &uri, uris) { contacts.removeOne(uri.toUrl()); } //query the model for the contacts, if they are present, then need to be just moved QList<QStandardItem*> toplevelContacts; foreach (const QUrl &uri, contacts) { QModelIndex contactIndex = qobject_cast<PersonsModel*>(model())->indexForUri(uri); if (contactIndex.isValid()) { toplevelContacts.append(qobject_cast<PersonsModel*>(model())->takeRow(contactIndex.row())); } } //append the moved contacts to this person and remove them from 'contacts' //so they are not added twice foreach (QStandardItem *contactItem, toplevelContacts) { //FIXME: we need to remove the fake person item here ContactItem *contact = dynamic_cast<ContactItem*>(contactItem); appendRow(contact); contacts.removeOne(contact->uri()); } QList<ContactItem*> rows; foreach (const QUrl &uri, contacts) { ContactItem *item = new ContactItem(uri); item->loadData(); appendRow(item); } emitDataChanged(); } void PersonItem::setContacts(const QList<QUrl> &contacts) { kDebug() << "set contacts" << contacts; if (contacts.isEmpty()) { //nothing to do here return; } if (hasChildren()) { QList<QUrl> toRemove; QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole); foreach (const QVariant &contact, uris) { if (!contacts.contains(contact.toUrl())) toRemove += contact.toUrl(); } removeContacts(toRemove); } QList<QUrl> toAdd; foreach (const QUrl &contact, contacts) { toAdd += contact; } addContacts(toAdd); Q_ASSERT(hasChildren()); } int PersonItem::presenceSortPriority(const QString &presenceName) const { if (presenceName == QLatin1String("available")) { return 0; } if (presenceName == QLatin1String("busy") || presenceName == QLatin1String("dnd")) { return 1; } if (presenceName == QLatin1String("hidden")) { return 2; } if (presenceName == QLatin1String("away")) { return 3; } if (presenceName == QLatin1String("xa")) { return 4; } if (presenceName == QLatin1String("unknown")) { return 5; } return 6; } void PersonItem::contactDataChanged() { emitDataChanged(); } <commit_msg>Empty QVariant is perfectly valid return value<commit_after>/* Persons Model Item Represents one person in the model Copyright (C) 2012 Martin Klapetek <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "personitem.h" #include "contactitem.h" #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Resource> #include <Nepomuk2/Variant> #include <Soprano/Vocabulary/NAO> #include <KDebug> PersonItem::PersonItem(const QUrl &personUri) { setData(personUri, PersonsModel::UriRole); } PersonItem::PersonItem(const Nepomuk2::Resource &person) { setData(person.uri(), PersonsModel::UriRole); setContacts(person.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList()); kDebug() << "new person" << text() << rowCount(); } QVariant PersonItem::queryChildrenForRole(int role) const { QVariant ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if (!value.isNull()) { ret = value; break; } } return ret; } QVariantList PersonItem::queryChildrenForRoleList(int role) const { QVariantList ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if (value.type() == QVariant::List) { ret += value.toList(); } else if (!value.isNull()) { ret += value; } } return ret; } QVariant PersonItem::data(int role) const { if (role == PersonsModel::PresenceTypeRole || role == PersonsModel::PresenceDisplayRole || role == PersonsModel::PresenceDecorationRole) { QVariantList presences = queryChildrenForRoleList(PersonsModel::PresenceTypeRole); //we find which position in the list contains the most online presence //and then we use that index to return the other roles int mostOnlineIndex = -1; int mostOnlinePresence = 999; for (int i = 0; i < presences.size(); i++) { int currentPresencePriority = presenceSortPriority(presences.at(i).toString()); if (currentPresencePriority < mostOnlinePresence) { mostOnlineIndex = i; mostOnlinePresence = currentPresencePriority; //if the most online is "available", //break as there can't be anything more online if (mostOnlinePresence == 0) { break; } } } Q_ASSERT(mostOnlineIndex != -1); switch (role) { case PersonsModel::PresenceTypeRole: return presences.at(mostOnlineIndex); case PersonsModel::PresenceDisplayRole: { const QVariantList presenceDisplayNames = queryChildrenForRoleList(PersonsModel::PresenceDisplayRole); return presenceDisplayNames.at(mostOnlineIndex); } case PersonsModel::PresenceDecorationRole: { const QVariantList presenceDecoration = queryChildrenForRoleList(PersonsModel::PresenceDecorationRole); return presenceDecoration.at(mostOnlineIndex); } } } if (role == PersonsModel::UriRole) { //uri for PersonItem is set using setData(...), so we need to query it from there return QStandardItem::data(role); } QVariantList ret; for (int i = 0; i < rowCount(); i++) { QVariant value; //if we're being asked for the child contacts uris, //we need to query the children for their UriRole if (role == PersonsModel::ChildContactsUriRole) { value = child(i)->data(PersonsModel::UriRole); } else { value = child(i)->data(role); } //these roles must return single QVariant if ((role == Qt::DisplayRole || role == Qt::DecorationRole)) { return value; } if (value.type() == QVariant::List) { ret += value.toList(); } else if (!value.isNull()) { ret += value; } } if (ret.isEmpty()) { //we need to return empty qvariant here, otherwise we'd get a qvariant //with empty qvariantlist, which would get parsed as non-empty qvariant return QVariant(); } return ret; } void PersonItem::removeContacts(const QList<QUrl> &contacts) { kDebug() << "remove contacts" << contacts; for (int i = 0; i < rowCount(); ) { QStandardItem *item = child(i); if (item && contacts.contains(item->data(PersonsModel::UriRole).toUrl())) { model()->invisibleRootItem()->appendRow(takeRow(i)); } else { ++i; } } emitDataChanged(); } void PersonItem::addContacts(const QList<QUrl> &_contacts) { QList<QUrl> contacts(_contacts); //get existing child-contacts and remove them from the new ones QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole); foreach (const QVariant &uri, uris) { contacts.removeOne(uri.toUrl()); } //query the model for the contacts, if they are present, then need to be just moved QList<QStandardItem*> toplevelContacts; foreach (const QUrl &uri, contacts) { QModelIndex contactIndex = qobject_cast<PersonsModel*>(model())->indexForUri(uri); if (contactIndex.isValid()) { toplevelContacts.append(qobject_cast<PersonsModel*>(model())->takeRow(contactIndex.row())); } } //append the moved contacts to this person and remove them from 'contacts' //so they are not added twice foreach (QStandardItem *contactItem, toplevelContacts) { //FIXME: we need to remove the fake person item here ContactItem *contact = dynamic_cast<ContactItem*>(contactItem); appendRow(contact); contacts.removeOne(contact->uri()); } QList<ContactItem*> rows; foreach (const QUrl &uri, contacts) { ContactItem *item = new ContactItem(uri); item->loadData(); appendRow(item); } emitDataChanged(); } void PersonItem::setContacts(const QList<QUrl> &contacts) { kDebug() << "set contacts" << contacts; if (contacts.isEmpty()) { //nothing to do here return; } if (hasChildren()) { QList<QUrl> toRemove; QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole); foreach (const QVariant &contact, uris) { if (!contacts.contains(contact.toUrl())) toRemove += contact.toUrl(); } removeContacts(toRemove); } QList<QUrl> toAdd; foreach (const QUrl &contact, contacts) { toAdd += contact; } addContacts(toAdd); Q_ASSERT(hasChildren()); } int PersonItem::presenceSortPriority(const QString &presenceName) const { if (presenceName == QLatin1String("available")) { return 0; } if (presenceName == QLatin1String("busy") || presenceName == QLatin1String("dnd")) { return 1; } if (presenceName == QLatin1String("hidden")) { return 2; } if (presenceName == QLatin1String("away")) { return 3; } if (presenceName == QLatin1String("xa")) { return 4; } if (presenceName == QLatin1String("unknown")) { return 5; } return 6; } void PersonItem::contactDataChanged() { emitDataChanged(); } <|endoftext|>
<commit_before> /* * benchmark.cpp - Contains benchmark code for measuring performance related * numbers in this project * * This module should be compiled with all possible optimization flags, and * also with libc debugging flag turned off */ #include "../src/AtomicStack.h" #include "../src/LocalWriteEM.h" #include "../src/GlobalWriteEM.h" #include "test_suite.h" using namespace peloton; using namespace index; // Number of cores we test EM on (this does not have to match the number // of cores on the testing machine since we only test correctness but // not performance) uint64_t CoreNum; // Declear stack and its node type here using StackType = AtomicStack<uint64_t>; using NodeType = typename StackType::NodeType; // EM type declaration using LEM = LocalWriteEM<NodeType>; using GEM = GlobalWriteEM<NodeType>; /* * IntHasherRandBenchmark() - Benchmarks integer number hash function from * Murmurhash3, which is then used as a random * number generator */ void IntHasherRandBenchmark(uint64_t iter, uint64_t salt_num) { PrintTestName("IntHasherRandBenchmark"); std::vector<uint64_t> v{}; v.reserve(1); SimpleInt64Random<0, 10000000> r{}; Timer t{true}; for(uint64_t salt = 0;salt < salt_num;salt++) { for(uint64_t i = 0;i < iter;i++) { v[0] = r(i, salt); } } double duration = t.Stop(); dbg_printf("Iteration = %lu, Duration = %f\n", iter * salt_num, duration); dbg_printf(" Throughput = %f M op/sec\n", static_cast<double>(iter * salt_num) / duration / 1024.0 / 1024.0); return; } /* * RandomNumberBenchmark() - Benchmark random number genrator inside C++11 */ void RandomNumberBenchmark(int thread_num, int iter) { PrintTestName("RandomNumberBenchmark"); auto f = [thread_num, iter](uint64_t id) -> void { Random<uint64_t, 0, -1> r{}; // Avoid optimization std::vector<uint64_t> v{}; v.reserve(1); // Bring it into the cache such that we do not suffer from cache miss v[0] = 1; for(int i = 0;i < iter;i++) { uint64_t num = r(); // This should be a cached write, so super fast v[0] = num; } return; }; Timer t{true}; StartThreads(thread_num, f); double duration = t.Stop(); dbg_printf("Thread num = %d, Iteration = %d, Duration = %f\n", thread_num, iter, duration); dbg_printf(" Throughput = %f M op/sec\n", static_cast<double>(iter) / duration / 1024.0 / 1024.0); dbg_printf(" Throughput = %f M op/(sec * thread)\n", static_cast<double>(iter) / duration / 1024.0 / 1024.0 / thread_num); return; } /* * GetThreadAffinityBenchmark() - Measures how fast we could call this function */ void GetThreadAffinityBenchmark(uint64_t thread_num) { PrintTestName("GetThreadAffinityBenchmark"); constexpr int iter = 10000000; auto f = [iter](uint64_t thread_id) { // We need this to avoid the following loop being optimized out std::vector<int> v{}; v.reserve(10); for(int i = 0;i < iter;i++) { int core_id = GetThreadAffinity(); v[0] = core_id; } return; }; // Start Threads and timer Timer t{true}; StartThreads(thread_num, f); double duration = t.Stop(); dbg_printf("Time usage (iter %d, thread %lu) = %f\n", iter, thread_num, duration); dbg_printf(" Throughput = %f op/second\n", static_cast<double>(iter) / duration); dbg_printf(" Throughput = %f op/(second * thread)\n", static_cast<double>(iter) / duration / thread_num); return; } /* * GetRandomWorkload() - Get a random number with uniform deviation from the * given base */ uint64_t GetRandomWorkload(uint64_t base, uint64_t dev, uint64_t seed) { uint64_t r = base; // If workload is large enough then make it random // Otherwise just use the given workload if(base != 0 && dev != 0) { // Use default parameter (0 - UINT64_T MAX) SimpleInt64Random<> hasher{}; const uint64_t sign = hasher(seed, seed + 1) % 2; if(sign == 0) { r = base + hasher(seed, seed) % dev; } else { r = base - hasher(seed, seed) % dev; } } return r; } /* * LEMSimpleBenchmark() - Benchmark how LocalWriteEM works without workload - * just announce entry & exit and it's all */ void LEMSimpleBenchmark(uint64_t thread_num, uint64_t op_num, uint64_t workload) { PrintTestName("LEMSimpleBenchmark"); // Note that we use the number of counters equal to the number of threads // rather than number of cores, i.e. one core could have multiple counters LEM *em = new LEM{thread_num}; auto func = [em, op_num, workload](uint64_t id) { // This is the core ID this thread is logically pinned to // physically we do not make any constraint here uint64_t core_id = id % CoreNum; // This avoids scheduling problem // Without this function the performance will be very // unstable especially when # of threads does not match // number of core PinToCore(core_id); const uint64_t random_workload = \ GetRandomWorkload(workload, workload >> 2, id); std::vector<uint64_t> v{}; v.reserve(1); // And then announce entry on its own processor for(uint64_t i = 0;i < op_num;i++) { em->AnnounceEnter(core_id); for(uint64_t j = 0;j < random_workload;j++) { v[0] = j; } } return; }; // Need to start GC thread to periodically increase global epoch em->StartGCThread(); // Let timer start and then start threads Timer t{true}; StartThreads(thread_num, func); double duration = t.Stop(); delete em; dbg_printf("Tests of %lu threads, %lu operations each took %f seconds\n", thread_num, op_num, duration); dbg_printf(" Throughput = %f M op/sec\n", static_cast<double>(thread_num * op_num) / duration / (1024.0 * 1024.0)); dbg_printf(" Throughput Per Thread = %f M op/sec\n", static_cast<double>(op_num) / duration / (1024.0 * 1024.0)); return; } /* * GEMSimpleBenchmark() - Runs GlobalWriteEM repeatedly for benchmark numbers * * For global EM since it uses coarse grained reference counting, we have to * increase and decrease the counter whenever a thread enters and leaves the * epoch, which is two times the overhead a LocalWriteEM would have */ void GEMSimpleBenchmark(uint64_t thread_num, uint64_t op_num, uint64_t workload) { PrintTestName("GEMSimpleBenchmark"); // This instance must be created by the factory GEM *em = new GEM{}; auto func = [em, op_num, workload](uint64_t id) { // random is between (base [+/-] 1/4 base) const uint64_t random_workload = \ GetRandomWorkload(workload, workload >> 2, id); std::vector<uint64_t> v{}; v.reserve(1); // And then announce entry on its own processor for(uint64_t i = 0;i < op_num;i++) { void *epoch_node_p = em->JoinEpoch(); // Actual workload is protected by epoch manager for(uint64_t j = 0;j < random_workload;j++) { v[0] = j; } em->LeaveEpoch(epoch_node_p); } return; }; em->StartGCThread(); // Let timer start and then start threads Timer t{true}; StartThreads(thread_num, func); double duration = t.Stop(); delete em; dbg_printf("Tests of %lu threads, %lu operations each took %f seconds\n", thread_num, op_num, duration); dbg_printf(" Epoch created = %lu; Epoch freed = %lu\n", em->GetEpochCreated(), em->GetEpochFreed()); dbg_printf(" Throughput = %f M op/sec\n", static_cast<double>(thread_num * op_num) / duration / (1024.0 * 1024.0)); dbg_printf(" Throughput Per Thread = %f M op/sec\n", static_cast<double>(op_num) / duration / (1024.0 * 1024.0)); return; } /* * GetValueOrThrow() - Get an unsigned long typed value from args, or throw * exception if the format for key-value is not correct * * This function throws integer constant 0 on error */ void GetValueAsULOrThrow(Argv &args, const std::string &key, unsigned long *value_p) { bool ret = args.GetValueAsUL(key, value_p); if(ret == false) { dbg_printf("ERROR: Unrecognized value for key %s: \"%s\"\n", key.c_str(), args.GetValue("thread_num")->c_str()); throw 0; } return; } int main(int argc, char **argv) { // This returns the number of logical CPUs CoreNum = GetCoreNum(); dbg_printf("* # of cores (default thread_num) on the platform = %lu\n", CoreNum); if(CoreNum == 0) { dbg_printf(" ...which is not supported\n"); exit(1); } // This will be overloaded if a thread_num is provided as argument uint64_t thread_num = CoreNum; // By default no workload is done uint64_t workload = 0; Argv args{argc, argv}; GetValueAsULOrThrow(args, "thread_num", &thread_num); GetValueAsULOrThrow(args, "workload", &workload); dbg_printf("* thread_num = %lu\n", thread_num); dbg_printf("* workload = %lu\n", workload); dbg_printf("* CoreNum = %lu\n", CoreNum); if(argc == 1 || args.Exists("thread_affinity")) { GetThreadAffinityBenchmark(thread_num); } if(argc == 1 || args.Exists("int_hash")) { IntHasherRandBenchmark(100000000, 10); } if(argc == 1 || args.Exists("random_number")) { RandomNumberBenchmark(thread_num, 100000000); } if(argc == 1 || args.Exists("lem_simple")) { LEMSimpleBenchmark(thread_num, 1024 * 1024 * 30, workload); } if(argc == 1 || args.Exists("gem_simple")) { GEMSimpleBenchmark(thread_num, 1024 * 1024 * 10, workload); } return 0; } <commit_msg>Adding actual workload to avoid loop optimization<commit_after> /* * benchmark.cpp - Contains benchmark code for measuring performance related * numbers in this project * * This module should be compiled with all possible optimization flags, and * also with libc debugging flag turned off */ #include "../src/AtomicStack.h" #include "../src/LocalWriteEM.h" #include "../src/GlobalWriteEM.h" #include "test_suite.h" using namespace peloton; using namespace index; // Number of cores we test EM on (this does not have to match the number // of cores on the testing machine since we only test correctness but // not performance) uint64_t CoreNum; // Declear stack and its node type here using StackType = AtomicStack<uint64_t>; using NodeType = typename StackType::NodeType; // EM type declaration using LEM = LocalWriteEM<NodeType>; using GEM = GlobalWriteEM<NodeType>; /* * IntHasherRandBenchmark() - Benchmarks integer number hash function from * Murmurhash3, which is then used as a random * number generator */ void IntHasherRandBenchmark(uint64_t iter, uint64_t salt_num) { PrintTestName("IntHasherRandBenchmark"); std::vector<uint64_t> v{}; v.reserve(1); SimpleInt64Random<0, 10000000> r{}; Timer t{true}; for(uint64_t salt = 0;salt < salt_num;salt++) { for(uint64_t i = 0;i < iter;i++) { v[0] = r(i, salt); } } double duration = t.Stop(); dbg_printf("Iteration = %lu, Duration = %f\n", iter * salt_num, duration); dbg_printf(" Throughput = %f M op/sec\n", static_cast<double>(iter * salt_num) / duration / 1024.0 / 1024.0); return; } /* * RandomNumberBenchmark() - Benchmark random number genrator inside C++11 */ void RandomNumberBenchmark(int thread_num, int iter) { PrintTestName("RandomNumberBenchmark"); auto f = [thread_num, iter](uint64_t id) -> void { Random<uint64_t, 0, -1> r{}; // Avoid optimization std::vector<uint64_t> v{}; v.reserve(1); // Bring it into the cache such that we do not suffer from cache miss v[0] = 1; for(int i = 0;i < iter;i++) { uint64_t num = r(); // This should be a cached write, so super fast v[0] = num; } return; }; Timer t{true}; StartThreads(thread_num, f); double duration = t.Stop(); dbg_printf("Thread num = %d, Iteration = %d, Duration = %f\n", thread_num, iter, duration); dbg_printf(" Throughput = %f M op/sec\n", static_cast<double>(iter) / duration / 1024.0 / 1024.0); dbg_printf(" Throughput = %f M op/(sec * thread)\n", static_cast<double>(iter) / duration / 1024.0 / 1024.0 / thread_num); return; } /* * GetThreadAffinityBenchmark() - Measures how fast we could call this function */ void GetThreadAffinityBenchmark(uint64_t thread_num) { PrintTestName("GetThreadAffinityBenchmark"); constexpr int iter = 10000000; auto f = [iter](uint64_t thread_id) { // We need this to avoid the following loop being optimized out std::vector<int> v{}; v.reserve(10); for(int i = 0;i < iter;i++) { int core_id = GetThreadAffinity(); v[0] = core_id; } return; }; // Start Threads and timer Timer t{true}; StartThreads(thread_num, f); double duration = t.Stop(); dbg_printf("Time usage (iter %d, thread %lu) = %f\n", iter, thread_num, duration); dbg_printf(" Throughput = %f op/second\n", static_cast<double>(iter) / duration); dbg_printf(" Throughput = %f op/(second * thread)\n", static_cast<double>(iter) / duration / thread_num); return; } /* * GetRandomWorkload() - Get a random number with uniform deviation from the * given base */ uint64_t GetRandomWorkload(uint64_t base, uint64_t dev, uint64_t seed) { uint64_t r = base; // If workload is large enough then make it random // Otherwise just use the given workload if(base != 0 && dev != 0) { // Use default parameter (0 - UINT64_T MAX) SimpleInt64Random<> hasher{}; const uint64_t sign = hasher(seed, seed + 1) % 2; if(sign == 0) { r = base + hasher(seed, seed) % dev; } else { r = base - hasher(seed, seed) % dev; } } return r; } /* * LEMSimpleBenchmark() - Benchmark how LocalWriteEM works without workload - * just announce entry & exit and it's all */ void LEMSimpleBenchmark(uint64_t thread_num, uint64_t op_num, uint64_t workload) { PrintTestName("LEMSimpleBenchmark"); // Note that we use the number of counters equal to the number of threads // rather than number of cores, i.e. one core could have multiple counters LEM *em = new LEM{thread_num}; auto func = [em, op_num, workload](uint64_t id) { // This is the core ID this thread is logically pinned to // physically we do not make any constraint here uint64_t core_id = id % CoreNum; // This avoids scheduling problem // Without this function the performance will be very // unstable especially when # of threads does not match // number of core PinToCore(core_id); const uint64_t random_workload = \ GetRandomWorkload(workload, workload >> 2, id); //printf("**%lu**\n", random_workload); std::vector<uint64_t> v{}; v.reserve(random_workload); // And then announce entry on its own processor for(uint64_t i = 0;i < op_num;i++) { em->AnnounceEnter(core_id); for(uint64_t j = 0;j < random_workload;j++) { v[j] = j; } } return; }; // Need to start GC thread to periodically increase global epoch em->StartGCThread(); // Let timer start and then start threads Timer t{true}; StartThreads(thread_num, func); double duration = t.Stop(); delete em; dbg_printf("Tests of %lu threads, %lu operations each took %f seconds\n", thread_num, op_num, duration); dbg_printf(" Throughput = %f M op/sec\n", static_cast<double>(thread_num * op_num) / duration / (1024.0 * 1024.0)); dbg_printf(" Throughput Per Thread = %f M op/sec\n", static_cast<double>(op_num) / duration / (1024.0 * 1024.0)); return; } /* * GEMSimpleBenchmark() - Runs GlobalWriteEM repeatedly for benchmark numbers * * For global EM since it uses coarse grained reference counting, we have to * increase and decrease the counter whenever a thread enters and leaves the * epoch, which is two times the overhead a LocalWriteEM would have */ void GEMSimpleBenchmark(uint64_t thread_num, uint64_t op_num, uint64_t workload) { PrintTestName("GEMSimpleBenchmark"); // This instance must be created by the factory GEM *em = new GEM{}; auto func = [em, op_num, workload](uint64_t id) { // random is between (base [+/-] 1/4 base) const uint64_t random_workload = \ GetRandomWorkload(workload, workload >> 2, id); std::vector<uint64_t> v{}; v.reserve(random_workload); // And then announce entry on its own processor for(uint64_t i = 0;i < op_num;i++) { void *epoch_node_p = em->JoinEpoch(); // Actual workload is protected by epoch manager for(uint64_t j = 0;j < random_workload;j++) { v[j] = j; } em->LeaveEpoch(epoch_node_p); } return; }; em->StartGCThread(); // Let timer start and then start threads Timer t{true}; StartThreads(thread_num, func); double duration = t.Stop(); delete em; dbg_printf("Tests of %lu threads, %lu operations each took %f seconds\n", thread_num, op_num, duration); dbg_printf(" Epoch created = %lu; Epoch freed = %lu\n", em->GetEpochCreated(), em->GetEpochFreed()); dbg_printf(" Throughput = %f M op/sec\n", static_cast<double>(thread_num * op_num) / duration / (1024.0 * 1024.0)); dbg_printf(" Throughput Per Thread = %f M op/sec\n", static_cast<double>(op_num) / duration / (1024.0 * 1024.0)); return; } /* * GetValueOrThrow() - Get an unsigned long typed value from args, or throw * exception if the format for key-value is not correct * * This function throws integer constant 0 on error */ void GetValueAsULOrThrow(Argv &args, const std::string &key, unsigned long *value_p) { bool ret = args.GetValueAsUL(key, value_p); if(ret == false) { dbg_printf("ERROR: Unrecognized value for key %s: \"%s\"\n", key.c_str(), args.GetValue("thread_num")->c_str()); throw 0; } return; } int main(int argc, char **argv) { // This returns the number of logical CPUs CoreNum = GetCoreNum(); dbg_printf("* # of cores (default thread_num) on the platform = %lu\n", CoreNum); if(CoreNum == 0) { dbg_printf(" ...which is not supported\n"); exit(1); } // This will be overloaded if a thread_num is provided as argument uint64_t thread_num = CoreNum; // By default no workload is done uint64_t workload = 0; Argv args{argc, argv}; GetValueAsULOrThrow(args, "thread_num", &thread_num); GetValueAsULOrThrow(args, "workload", &workload); dbg_printf("* thread_num = %lu\n", thread_num); dbg_printf("* workload = %lu\n", workload); dbg_printf("* CoreNum = %lu\n", CoreNum); if(argc == 1 || args.Exists("thread_affinity")) { GetThreadAffinityBenchmark(thread_num); } if(argc == 1 || args.Exists("int_hash")) { IntHasherRandBenchmark(100000000, 10); } if(argc == 1 || args.Exists("random_number")) { RandomNumberBenchmark(thread_num, 100000000); } if(argc == 1 || args.Exists("lem_simple")) { LEMSimpleBenchmark(thread_num, 1024 * 1024 * 30, workload); } if(argc == 1 || args.Exists("gem_simple")) { GEMSimpleBenchmark(thread_num, 1024 * 1024 * 10, workload); } return 0; } <|endoftext|>
<commit_before> #include "ksp_plugin/interface.hpp" #include "base/not_null.hpp" #include "geometry/rotation.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ksp_plugin/frames.hpp" #include "ksp_plugin/identification.hpp" #include "ksp_plugin_test/mock_plugin.hpp" #include "ksp_plugin_test/mock_renderer.hpp" #include "ksp_plugin_test/mock_vessel.hpp" #include "physics/mock_dynamic_frame.hpp" #include "quantities/si.hpp" #include "testing_utilities/actions.hpp" namespace principia { namespace interface { using base::make_not_null_unique; using base::not_null; using geometry::Rotation; using ksp_plugin::Barycentric; using ksp_plugin::Index; using ksp_plugin::MockPlugin; using ksp_plugin::MockRenderer; using ksp_plugin::MockVessel; using ksp_plugin::Navigation; using physics::MockDynamicFrame; using quantities::si::Metre; using testing_utilities::FillUniquePtr; using ::testing::IsNull; using ::testing::Ref; using ::testing::Return; using ::testing::ReturnRef; using ::testing::StrictMock; using ::testing::_; namespace { char const vessel_guid[] = "123-456"; Index const celestial_index = 1; Index const parent_index = 2; Index const unused = 666; int const trajectory_size = 10; XYZ parent_position = {4, 5, 6}; } // namespace class InterfaceRendererTest : public ::testing::Test { protected: InterfaceRendererTest() : plugin_(make_not_null_unique<StrictMock<MockPlugin>>()), const_plugin_(plugin_.get()) {} not_null<std::unique_ptr<StrictMock<MockPlugin>>> const plugin_; StrictMock<MockPlugin> const* const const_plugin_; Instant const t0_; }; TEST_F(InterfaceRendererTest, SetPlottingFrame) { StrictMock<MockDynamicFrame<Barycentric, Navigation>>* const mock_navigation_frame = new StrictMock<MockDynamicFrame<Barycentric, Navigation>>; EXPECT_CALL(*plugin_, FillBarycentricRotatingNavigationFrame(celestial_index, parent_index, _)) .WillOnce(FillUniquePtr<2>(mock_navigation_frame)); NavigationFrameParameters parameters = { serialization::BarycentricRotatingDynamicFrame::kExtensionFieldNumber, unused, celestial_index, parent_index}; NavigationFrame* navigation_frame = principia__NewNavigationFrame(plugin_.get(), parameters); EXPECT_EQ(mock_navigation_frame, navigation_frame); MockRenderer renderer; EXPECT_CALL(*plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(*const_plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(renderer, SetPlottingFrameConstRef(Ref(*navigation_frame))); principia__SetPlottingFrame(plugin_.get(), &navigation_frame); EXPECT_THAT(navigation_frame, IsNull()); EXPECT_CALL(renderer, GetPlottingFrame()) .WillOnce(Return(mock_navigation_frame)); EXPECT_EQ(mock_navigation_frame, principia__GetPlottingFrame(plugin_.get())); } TEST_F(InterfaceRendererTest, RenderedPrediction) { StrictMock<MockDynamicFrame<Barycentric, Navigation>>* const mock_navigation_frame = new StrictMock<MockDynamicFrame<Barycentric, Navigation>>; EXPECT_CALL(*plugin_, FillBarycentricRotatingNavigationFrame(celestial_index, parent_index, _)) .WillOnce(FillUniquePtr<2>(mock_navigation_frame)); NavigationFrameParameters parameters = { serialization::BarycentricRotatingDynamicFrame::kExtensionFieldNumber, unused, celestial_index, parent_index}; NavigationFrame* navigation_frame = principia__NewNavigationFrame(plugin_.get(), parameters); EXPECT_EQ(mock_navigation_frame, navigation_frame); MockRenderer renderer; EXPECT_CALL(*plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(*plugin_, PlanetariumRotation()) .WillRepeatedly(ReturnRef(Rotation<Barycentric, AliceSun>::Identity())); EXPECT_CALL(*plugin_, CurrentTime()).WillOnce(Return(t0_)); EXPECT_CALL(renderer, SetPlottingFrameConstRef(Ref(*navigation_frame))); principia__SetPlottingFrame(plugin_.get(), &navigation_frame); EXPECT_THAT(navigation_frame, IsNull()); // Construct a test rendered trajectory. auto rendered_trajectory = make_not_null_unique<DiscreteTrajectory<World>>(); Position<World> position = World::origin + Displacement<World>({1 * Metre, 2 * Metre, 3 * Metre}); rendered_trajectory->Append( t0_, DegreesOfFreedom<World>(position, Velocity<World>())); for (int i = 1; i < trajectory_size; ++i) { position += Displacement<World>({10 * Metre, 20 * Metre, 30 * Metre}); rendered_trajectory->Append( t0_ + i * Second, DegreesOfFreedom<World>(position, Velocity<World>())); } StrictMock<MockVessel> vessel; DiscreteTrajectory<Barycentric> prediction; EXPECT_CALL(*plugin_, GetVessel(vessel_guid)) .WillRepeatedly(Return(&vessel)); EXPECT_CALL(vessel, prediction()) .WillRepeatedly(ReturnRef(prediction)); EXPECT_CALL(renderer, FillRenderedBarycentricTrajectoryInWorld( _, _, _, World::origin + Displacement<World>( {parent_position.x * Metre, parent_position.y * Metre, parent_position.z * Metre}), _, _)) .WillOnce(FillUniquePtr<5>(rendered_trajectory.release())); Iterator* iterator = principia__RenderedPrediction(plugin_.get(), vessel_guid, parent_position); EXPECT_EQ(trajectory_size, principia__IteratorSize(iterator)); // Traverse it and check that we get the right data. for (int i = 0; i < trajectory_size; ++i) { EXPECT_FALSE(principia__IteratorAtEnd(iterator)); XYZ const xyz = principia__IteratorGetXYZ(iterator); EXPECT_EQ(1 + 10 * i, xyz.x); EXPECT_EQ(2 + 20 * i, xyz.y); EXPECT_EQ(3 + 30 * i, xyz.z); principia__IteratorIncrement(iterator); } EXPECT_TRUE(principia__IteratorAtEnd(iterator)); // Delete it. EXPECT_THAT(iterator, Not(IsNull())); principia__IteratorDelete(&iterator); EXPECT_THAT(iterator, IsNull()); } TEST_F(InterfaceRendererTest, Iterator) { StrictMock<MockDynamicFrame<Barycentric, Navigation>>* const mock_navigation_frame = new StrictMock<MockDynamicFrame<Barycentric, Navigation>>; EXPECT_CALL(*plugin_, FillBarycentricRotatingNavigationFrame(celestial_index, parent_index, _)) .WillOnce(FillUniquePtr<2>(mock_navigation_frame)); NavigationFrameParameters parameters = { serialization::BarycentricRotatingDynamicFrame::kExtensionFieldNumber, unused, celestial_index, parent_index}; NavigationFrame* navigation_frame = principia__NewNavigationFrame(plugin_.get(), parameters); EXPECT_EQ(mock_navigation_frame, navigation_frame); MockRenderer renderer; EXPECT_CALL(*plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(*const_plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(*plugin_, PlanetariumRotation()) .WillRepeatedly(ReturnRef(Rotation<Barycentric, AliceSun>::Identity())); EXPECT_CALL(*plugin_, CurrentTime()).WillOnce(Return(t0_)); EXPECT_CALL(renderer, SetPlottingFrameConstRef(Ref(*navigation_frame))); principia__SetPlottingFrame(plugin_.get(), &navigation_frame); EXPECT_THAT(navigation_frame, IsNull()); // Construct a test rendered trajectory. auto rendered_trajectory = make_not_null_unique<DiscreteTrajectory<World>>(); Position<World> position = World::origin + Displacement<World>({1 * Metre, 2 * Metre, 3 * Metre}); rendered_trajectory->Append( t0_, DegreesOfFreedom<World>(position, Velocity<World>())); for (int i = 1; i < trajectory_size; ++i) { position += Displacement<World>({10 * Metre, 20 * Metre, 30 * Metre}); rendered_trajectory->Append( t0_ + i * Second, DegreesOfFreedom<World>(position, Velocity<World>())); } // Construct a LineAndIterator. StrictMock<MockVessel> vessel; DiscreteTrajectory<Barycentric> psychohistory; EXPECT_CALL(*plugin_, GetVessel(vessel_guid)) .WillRepeatedly(Return(&vessel)); EXPECT_CALL(vessel, psychohistory()) .WillRepeatedly(ReturnRef(psychohistory)); EXPECT_CALL(renderer, FillRenderedBarycentricTrajectoryInWorld( _, _, _, World::origin + Displacement<World>( {parent_position.x * Metre, parent_position.y * Metre, parent_position.z * Metre}), _, _)) .WillOnce(FillUniquePtr<5>(rendered_trajectory.release())); Iterator* iterator = principia__RenderedVesselTrajectory(plugin_.get(), vessel_guid, parent_position); EXPECT_EQ(trajectory_size, principia__IteratorSize(iterator)); // Traverse it and check that we get the right data. for (int i = 0; i < trajectory_size; ++i) { EXPECT_FALSE(principia__IteratorAtEnd(iterator)); XYZ const xyz = principia__IteratorGetXYZ(iterator); EXPECT_EQ(1 + 10 * i, xyz.x); EXPECT_EQ(2 + 20 * i, xyz.y); EXPECT_EQ(3 + 30 * i, xyz.z); principia__IteratorIncrement(iterator); } EXPECT_TRUE(principia__IteratorAtEnd(iterator)); // Delete it. EXPECT_THAT(iterator, Not(IsNull())); principia__IteratorDelete(&iterator); EXPECT_THAT(iterator, IsNull()); } TEST_F(InterfaceRendererTest, Frenet) { StrictMock<MockDynamicFrame<Barycentric, Navigation>>* const mock_navigation_frame = new StrictMock<MockDynamicFrame<Barycentric, Navigation>>; EXPECT_CALL(*plugin_, FillBarycentricRotatingNavigationFrame(celestial_index, parent_index, _)) .WillOnce(FillUniquePtr<2>(mock_navigation_frame)); NavigationFrameParameters parameters = { serialization::BarycentricRotatingDynamicFrame::kExtensionFieldNumber, unused, celestial_index, parent_index}; NavigationFrame* navigation_frame = principia__NewNavigationFrame(plugin_.get(), parameters); EXPECT_EQ(mock_navigation_frame, navigation_frame); MockRenderer renderer; EXPECT_CALL(*plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(renderer, SetPlottingFrameConstRef(Ref(*navigation_frame))); principia__SetPlottingFrame(plugin_.get(), &navigation_frame); EXPECT_THAT(navigation_frame, IsNull()); { auto const tangent = Vector<double, World>({4, 5, 6}); EXPECT_CALL(*plugin_, VesselTangent(vessel_guid)).WillOnce(Return(tangent)); XYZ t = principia__VesselTangent(plugin_.get(), vessel_guid); EXPECT_EQ(t.x, tangent.coordinates().x); EXPECT_EQ(t.y, tangent.coordinates().y); EXPECT_EQ(t.z, tangent.coordinates().z); } { auto const normal = Vector<double, World>({-13, 7, 5}); EXPECT_CALL(*plugin_, VesselNormal(vessel_guid)).WillOnce(Return(normal)); XYZ n = principia__VesselNormal(plugin_.get(), vessel_guid); EXPECT_EQ(n.x, normal.coordinates().x); EXPECT_EQ(n.y, normal.coordinates().y); EXPECT_EQ(n.z, normal.coordinates().z); } { auto const binormal = Vector<double, World>({43, 67, 163}); EXPECT_CALL(*plugin_, VesselBinormal(vessel_guid)) .WillOnce(Return(binormal)); XYZ b = principia__VesselBinormal(plugin_.get(), vessel_guid); EXPECT_EQ(b.x, binormal.coordinates().x); EXPECT_EQ(b.y, binormal.coordinates().y); EXPECT_EQ(b.z, binormal.coordinates().z); } { auto const velocity = Velocity<World>( {4 * Metre / Second, 5 * Metre / Second, 6 * Metre / Second}); EXPECT_CALL(*plugin_, VesselVelocity(vessel_guid)) .WillOnce(Return(velocity)); XYZ v = principia__VesselVelocity(plugin_.get(), vessel_guid); EXPECT_EQ(v.x, velocity.coordinates().x / (Metre / Second)); EXPECT_EQ(v.y, velocity.coordinates().y / (Metre / Second)); EXPECT_EQ(v.z, velocity.coordinates().z / (Metre / Second)); } } } // namespace interface } // namespace principia <commit_msg>ReturnRef(rvalue)<commit_after> #include "ksp_plugin/interface.hpp" #include "base/not_null.hpp" #include "geometry/rotation.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ksp_plugin/frames.hpp" #include "ksp_plugin/identification.hpp" #include "ksp_plugin_test/mock_plugin.hpp" #include "ksp_plugin_test/mock_renderer.hpp" #include "ksp_plugin_test/mock_vessel.hpp" #include "physics/mock_dynamic_frame.hpp" #include "quantities/si.hpp" #include "testing_utilities/actions.hpp" namespace principia { namespace interface { using base::make_not_null_unique; using base::not_null; using geometry::Rotation; using ksp_plugin::Barycentric; using ksp_plugin::Index; using ksp_plugin::MockPlugin; using ksp_plugin::MockRenderer; using ksp_plugin::MockVessel; using ksp_plugin::Navigation; using physics::MockDynamicFrame; using quantities::si::Metre; using testing_utilities::FillUniquePtr; using ::testing::IsNull; using ::testing::Ref; using ::testing::Return; using ::testing::ReturnRef; using ::testing::StrictMock; using ::testing::_; namespace { char const vessel_guid[] = "123-456"; Index const celestial_index = 1; Index const parent_index = 2; Index const unused = 666; int const trajectory_size = 10; XYZ parent_position = {4, 5, 6}; } // namespace class InterfaceRendererTest : public ::testing::Test { protected: InterfaceRendererTest() : plugin_(make_not_null_unique<StrictMock<MockPlugin>>()), const_plugin_(plugin_.get()) {} not_null<std::unique_ptr<StrictMock<MockPlugin>>> const plugin_; StrictMock<MockPlugin> const* const const_plugin_; Instant const t0_; }; TEST_F(InterfaceRendererTest, SetPlottingFrame) { StrictMock<MockDynamicFrame<Barycentric, Navigation>>* const mock_navigation_frame = new StrictMock<MockDynamicFrame<Barycentric, Navigation>>; EXPECT_CALL(*plugin_, FillBarycentricRotatingNavigationFrame(celestial_index, parent_index, _)) .WillOnce(FillUniquePtr<2>(mock_navigation_frame)); NavigationFrameParameters parameters = { serialization::BarycentricRotatingDynamicFrame::kExtensionFieldNumber, unused, celestial_index, parent_index}; NavigationFrame* navigation_frame = principia__NewNavigationFrame(plugin_.get(), parameters); EXPECT_EQ(mock_navigation_frame, navigation_frame); MockRenderer renderer; EXPECT_CALL(*plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(*const_plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(renderer, SetPlottingFrameConstRef(Ref(*navigation_frame))); principia__SetPlottingFrame(plugin_.get(), &navigation_frame); EXPECT_THAT(navigation_frame, IsNull()); EXPECT_CALL(renderer, GetPlottingFrame()) .WillOnce(Return(mock_navigation_frame)); EXPECT_EQ(mock_navigation_frame, principia__GetPlottingFrame(plugin_.get())); } TEST_F(InterfaceRendererTest, RenderedPrediction) { StrictMock<MockDynamicFrame<Barycentric, Navigation>>* const mock_navigation_frame = new StrictMock<MockDynamicFrame<Barycentric, Navigation>>; EXPECT_CALL(*plugin_, FillBarycentricRotatingNavigationFrame(celestial_index, parent_index, _)) .WillOnce(FillUniquePtr<2>(mock_navigation_frame)); NavigationFrameParameters parameters = { serialization::BarycentricRotatingDynamicFrame::kExtensionFieldNumber, unused, celestial_index, parent_index}; NavigationFrame* navigation_frame = principia__NewNavigationFrame(plugin_.get(), parameters); EXPECT_EQ(mock_navigation_frame, navigation_frame); MockRenderer renderer; auto const identity = Rotation<Barycentric, AliceSun>::Identity(); EXPECT_CALL(*plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(*plugin_, PlanetariumRotation()) .WillRepeatedly(ReturnRef(identity)); EXPECT_CALL(*plugin_, CurrentTime()).WillOnce(Return(t0_)); EXPECT_CALL(renderer, SetPlottingFrameConstRef(Ref(*navigation_frame))); principia__SetPlottingFrame(plugin_.get(), &navigation_frame); EXPECT_THAT(navigation_frame, IsNull()); // Construct a test rendered trajectory. auto rendered_trajectory = make_not_null_unique<DiscreteTrajectory<World>>(); Position<World> position = World::origin + Displacement<World>({1 * Metre, 2 * Metre, 3 * Metre}); rendered_trajectory->Append( t0_, DegreesOfFreedom<World>(position, Velocity<World>())); for (int i = 1; i < trajectory_size; ++i) { position += Displacement<World>({10 * Metre, 20 * Metre, 30 * Metre}); rendered_trajectory->Append( t0_ + i * Second, DegreesOfFreedom<World>(position, Velocity<World>())); } StrictMock<MockVessel> vessel; DiscreteTrajectory<Barycentric> prediction; EXPECT_CALL(*plugin_, GetVessel(vessel_guid)) .WillRepeatedly(Return(&vessel)); EXPECT_CALL(vessel, prediction()) .WillRepeatedly(ReturnRef(prediction)); EXPECT_CALL(renderer, FillRenderedBarycentricTrajectoryInWorld( _, _, _, World::origin + Displacement<World>( {parent_position.x * Metre, parent_position.y * Metre, parent_position.z * Metre}), _, _)) .WillOnce(FillUniquePtr<5>(rendered_trajectory.release())); Iterator* iterator = principia__RenderedPrediction(plugin_.get(), vessel_guid, parent_position); EXPECT_EQ(trajectory_size, principia__IteratorSize(iterator)); // Traverse it and check that we get the right data. for (int i = 0; i < trajectory_size; ++i) { EXPECT_FALSE(principia__IteratorAtEnd(iterator)); XYZ const xyz = principia__IteratorGetXYZ(iterator); EXPECT_EQ(1 + 10 * i, xyz.x); EXPECT_EQ(2 + 20 * i, xyz.y); EXPECT_EQ(3 + 30 * i, xyz.z); principia__IteratorIncrement(iterator); } EXPECT_TRUE(principia__IteratorAtEnd(iterator)); // Delete it. EXPECT_THAT(iterator, Not(IsNull())); principia__IteratorDelete(&iterator); EXPECT_THAT(iterator, IsNull()); } TEST_F(InterfaceRendererTest, Iterator) { StrictMock<MockDynamicFrame<Barycentric, Navigation>>* const mock_navigation_frame = new StrictMock<MockDynamicFrame<Barycentric, Navigation>>; EXPECT_CALL(*plugin_, FillBarycentricRotatingNavigationFrame(celestial_index, parent_index, _)) .WillOnce(FillUniquePtr<2>(mock_navigation_frame)); NavigationFrameParameters parameters = { serialization::BarycentricRotatingDynamicFrame::kExtensionFieldNumber, unused, celestial_index, parent_index}; NavigationFrame* navigation_frame = principia__NewNavigationFrame(plugin_.get(), parameters); EXPECT_EQ(mock_navigation_frame, navigation_frame); MockRenderer renderer; EXPECT_CALL(*plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(*const_plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(*plugin_, PlanetariumRotation()) .WillRepeatedly(ReturnRef(Rotation<Barycentric, AliceSun>::Identity())); EXPECT_CALL(*plugin_, CurrentTime()).WillOnce(Return(t0_)); EXPECT_CALL(renderer, SetPlottingFrameConstRef(Ref(*navigation_frame))); principia__SetPlottingFrame(plugin_.get(), &navigation_frame); EXPECT_THAT(navigation_frame, IsNull()); // Construct a test rendered trajectory. auto rendered_trajectory = make_not_null_unique<DiscreteTrajectory<World>>(); Position<World> position = World::origin + Displacement<World>({1 * Metre, 2 * Metre, 3 * Metre}); rendered_trajectory->Append( t0_, DegreesOfFreedom<World>(position, Velocity<World>())); for (int i = 1; i < trajectory_size; ++i) { position += Displacement<World>({10 * Metre, 20 * Metre, 30 * Metre}); rendered_trajectory->Append( t0_ + i * Second, DegreesOfFreedom<World>(position, Velocity<World>())); } // Construct a LineAndIterator. StrictMock<MockVessel> vessel; DiscreteTrajectory<Barycentric> psychohistory; EXPECT_CALL(*plugin_, GetVessel(vessel_guid)) .WillRepeatedly(Return(&vessel)); EXPECT_CALL(vessel, psychohistory()) .WillRepeatedly(ReturnRef(psychohistory)); EXPECT_CALL(renderer, FillRenderedBarycentricTrajectoryInWorld( _, _, _, World::origin + Displacement<World>( {parent_position.x * Metre, parent_position.y * Metre, parent_position.z * Metre}), _, _)) .WillOnce(FillUniquePtr<5>(rendered_trajectory.release())); Iterator* iterator = principia__RenderedVesselTrajectory(plugin_.get(), vessel_guid, parent_position); EXPECT_EQ(trajectory_size, principia__IteratorSize(iterator)); // Traverse it and check that we get the right data. for (int i = 0; i < trajectory_size; ++i) { EXPECT_FALSE(principia__IteratorAtEnd(iterator)); XYZ const xyz = principia__IteratorGetXYZ(iterator); EXPECT_EQ(1 + 10 * i, xyz.x); EXPECT_EQ(2 + 20 * i, xyz.y); EXPECT_EQ(3 + 30 * i, xyz.z); principia__IteratorIncrement(iterator); } EXPECT_TRUE(principia__IteratorAtEnd(iterator)); // Delete it. EXPECT_THAT(iterator, Not(IsNull())); principia__IteratorDelete(&iterator); EXPECT_THAT(iterator, IsNull()); } TEST_F(InterfaceRendererTest, Frenet) { StrictMock<MockDynamicFrame<Barycentric, Navigation>>* const mock_navigation_frame = new StrictMock<MockDynamicFrame<Barycentric, Navigation>>; EXPECT_CALL(*plugin_, FillBarycentricRotatingNavigationFrame(celestial_index, parent_index, _)) .WillOnce(FillUniquePtr<2>(mock_navigation_frame)); NavigationFrameParameters parameters = { serialization::BarycentricRotatingDynamicFrame::kExtensionFieldNumber, unused, celestial_index, parent_index}; NavigationFrame* navigation_frame = principia__NewNavigationFrame(plugin_.get(), parameters); EXPECT_EQ(mock_navigation_frame, navigation_frame); MockRenderer renderer; EXPECT_CALL(*plugin_, renderer()).WillRepeatedly(ReturnRef(renderer)); EXPECT_CALL(renderer, SetPlottingFrameConstRef(Ref(*navigation_frame))); principia__SetPlottingFrame(plugin_.get(), &navigation_frame); EXPECT_THAT(navigation_frame, IsNull()); { auto const tangent = Vector<double, World>({4, 5, 6}); EXPECT_CALL(*plugin_, VesselTangent(vessel_guid)).WillOnce(Return(tangent)); XYZ t = principia__VesselTangent(plugin_.get(), vessel_guid); EXPECT_EQ(t.x, tangent.coordinates().x); EXPECT_EQ(t.y, tangent.coordinates().y); EXPECT_EQ(t.z, tangent.coordinates().z); } { auto const normal = Vector<double, World>({-13, 7, 5}); EXPECT_CALL(*plugin_, VesselNormal(vessel_guid)).WillOnce(Return(normal)); XYZ n = principia__VesselNormal(plugin_.get(), vessel_guid); EXPECT_EQ(n.x, normal.coordinates().x); EXPECT_EQ(n.y, normal.coordinates().y); EXPECT_EQ(n.z, normal.coordinates().z); } { auto const binormal = Vector<double, World>({43, 67, 163}); EXPECT_CALL(*plugin_, VesselBinormal(vessel_guid)) .WillOnce(Return(binormal)); XYZ b = principia__VesselBinormal(plugin_.get(), vessel_guid); EXPECT_EQ(b.x, binormal.coordinates().x); EXPECT_EQ(b.y, binormal.coordinates().y); EXPECT_EQ(b.z, binormal.coordinates().z); } { auto const velocity = Velocity<World>( {4 * Metre / Second, 5 * Metre / Second, 6 * Metre / Second}); EXPECT_CALL(*plugin_, VesselVelocity(vessel_guid)) .WillOnce(Return(velocity)); XYZ v = principia__VesselVelocity(plugin_.get(), vessel_guid); EXPECT_EQ(v.x, velocity.coordinates().x / (Metre / Second)); EXPECT_EQ(v.y, velocity.coordinates().y / (Metre / Second)); EXPECT_EQ(v.z, velocity.coordinates().z / (Metre / Second)); } } } // namespace interface } // namespace principia <|endoftext|>
<commit_before>#include <vector> #include <iostream> #include <cstddef> #include <cstdlib> #include <cassert> #include <cstring> #include <cmath> #include <stdexcept> #include <string> #include <vector> #include <map> #include <algorithm> #include <memory> #include <cassert> #include <functional> #include <locale> #include <codecvt> #include "Platform.h" #include "ILoader.h" #include "ILexer.h" #include "Scintilla.h" #include "StringCopy.h" #include "Position.h" #include "UniqueString.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "ContractionState.h" #include "CellBuffer.h" #include "KeyMap.h" #include "Indicator.h" #include "XPM.h" #include "LineMarker.h" #include "Style.h" #include "ViewStyle.h" #include "CharClassify.h" #include "Decoration.h" #include "CaseFolder.h" #include "Document.h" #include "UniConversion.h" #include "Selection.h" #include "PositionCache.h" #include "EditModel.h" #include "MarginView.h" #include "EditView.h" #include "Editor.h" #include "AutoComplete.h" #include "CallTip.h" #include "ScintillaBase.h" #include "scite_impl.h" #include "scintilla_editor.h" #include "term_context.h" #include "term_window.h" #include "color_theme.h" #include "term_cell.h" const GUI::gui_char appName[] = GUI_TEXT("scintilla_editor"); class MyMutex : public Mutex{ public: virtual void Lock() {} virtual void Unlock() {} virtual ~MyMutex() {} }; Mutex * Mutex::Create() { return new MyMutex(); } namespace GUI { ElapsedTime::ElapsedTime(){ (void)bigBit; (void)littleBit; } double ElapsedTime::Duration(bool reset) { (void)reset; return 0; } void Menu::Destroy() {} void Menu::CreatePopUp() {} void Menu::Show(Point, Window &){} void Window::Destroy() {} bool Window::HasFocus() { return false; } Rectangle Window::GetPosition() { return Rectangle {}; } void Window::SetPosition(Rectangle) {}; Rectangle Window::GetClientPosition() {return Rectangle {};} void Window::Show(bool) {} void Window::InvalidateAll() {} void Window::SetTitle(const gui_char *) {} gui_string StringFromUTF8(const char *s) { return gui_string {s}; } gui_string StringFromUTF8(const std::string &s) { return s; } std::string UTF8FromString(const gui_string &s) { return s; } gui_string StringFromInteger(long i) { char number[32]; sprintf(number, "%0ld", i); gui_char gnumber[32]; size_t n=0; while (number[n]) { gnumber[n] = static_cast<gui_char>(number[n]); n++; } gnumber[n] = 0; return gui_string(gnumber); } gui_string StringFromLongLong(long long i) { try { std::ostringstream strstrm; strstrm << i; return StringFromUTF8(strstrm.str()); } catch (std::exception &) { // Exceptions not enabled on stream but still causes diagnostic in Coverity. // Simply swallow the failure and return the default value. } return gui_string(); } gui_string HexStringFromInteger(long i) { char number[32]; sprintf(number, "%0lx", i); gui_char gnumber[32]; size_t n = 0; while (number[n]) { gnumber[n] = static_cast<gui_char>(number[n]); n++; } gnumber[n] = 0; return gui_string(gnumber); } sptr_t ScintillaWindow::Send(unsigned int msg, uptr_t wParam, sptr_t lParam) { ScintillaEditor * pEditor = (ScintillaEditor*)GetID(); if (!pEditor) return 0; return pEditor->WndProc(msg, wParam, lParam); } bool IsDBCSLeadByte(int codePage, char ch) { // Byte ranges found in Wikipedia articles with relevant search strings in each case unsigned char uch = static_cast<unsigned char>(ch); switch (codePage) { case 932: // Shift_jis return ((uch >= 0x81) && (uch <= 0x9F)) || ((uch >= 0xE0) && (uch <= 0xEF)); case 936: // GBK return (uch >= 0x81) && (uch <= 0xFE); case 950: // Big5 return (uch >= 0x81) && (uch <= 0xFE); // Korean EUC-KR may be code page 949. } return false; } }; SciTE::SciTE() : m_pEditor{nullptr} , m_pTermWindow{nullptr} , m_PropsHomeDir{} { } FilePath SciTE::GetDefaultDirectory() { FilePath p{m_PropsHomeDir}; return p.AbsolutePath().NormalizePath(); } FilePath SciTE::GetSciteDefaultHome() { FilePath p{m_PropsHomeDir}; return p.AbsolutePath().NormalizePath(); } FilePath SciTE::GetSciteUserHome() { FilePath p{m_PropsHomeDir}; return p.AbsolutePath().NormalizePath(); } static struct color_base_s { const char * key; uint32_t color_index; } g_color_props[] = { {"colour.base02", 0}, {"colour.red", 1}, {"colour.green", 2}, {"colour.yellow", 3}, {"colour.blue", 4}, {"colour.magenta", 5}, {"colour.cyan", 6}, {"colour.base2", 7}, {"colour.base03", 8}, {"colour.orange", 9}, {"colour.base01", 10}, {"colour.base00", 11}, {"colour.base0", 12}, {"colour.violet", 13}, {"colour.base1", 14}, {"colour.base3", 15}, {"caret.fore", TermCell::DefaultCursorColorIndex}, }; static const char * g_props[] = { "colour.code.comment.box","fore:$(colour.base01),italics", "colour.code.comment.line","fore:$(colour.base01),italics", "colour.code.comment.doc","fore:$(colour.base01),italics", "colour.code.comment.nested","fore:$(colour.base01),italics", "colour.text.comment","fore:$(colour.base01),italics", "colour.other.comment","fore:$(colour.base01),italics", "colour.embedded.comment","fore:$(colour.base01),italics", "colour.embedded.js","fore:$(colour.base01)", "colour.notused","fore:$(colour.base01)", "colour.number","fore:$(colour.base0)", "colour.keyword","fore:$(colour.blue)", "colour.string","fore:$(colour.cyan)", "colour.char","fore:$(colour.base0)", "colour.operator","fore:$(colour.blue)", "colour.preproc","fore:$(colour.base0)", "colour.error","fore:$(colour.red)", }; void SciTE::Initialize(ScintillaEditor * pEditor, TermWindow * pTermWindow, const std::string & propsHomeDir) { m_pEditor = pEditor; m_pTermWindow = pTermWindow; m_PropsHomeDir = propsHomeDir; wEditor.SetID(pEditor); wOutput.SetID(new ScintillaEditor); buffers.Allocate(1); buffers.Add(); SetFileName("../src/app.cpp", true); char buf[255] = {0}; #define TC2SC(tc) (tc >> 24) & 0xFF, (tc >> 16) & 0xFF, (tc >> 8) & 0xFF sprintf(buf, "back:#%02x%02x%02x,fore:#%02x%02x%02x", TC2SC(pTermWindow->GetColorByIndex(TermCell::DefaultBackColorIndex)), TC2SC(pTermWindow->GetColorByIndex(TermCell::DefaultForeColorIndex))); props.Set("style.*.32", buf); for(size_t i=0;i < sizeof(g_color_props) / sizeof(color_base_s);i++) { sprintf(buf, "#%02x%02x%02x", TC2SC(pTermWindow->GetColorByIndex(g_color_props[i].color_index))); props.Set(g_color_props[i].key, buf); } for(size_t i=0;i < sizeof(g_props) / sizeof(const char *);i+=2) { props.Set(g_props[i], g_props[i+1]); } #undef TC2SC ReloadProperties(); } <commit_msg>update color map<commit_after>#include <vector> #include <iostream> #include <cstddef> #include <cstdlib> #include <cassert> #include <cstring> #include <cmath> #include <stdexcept> #include <string> #include <vector> #include <map> #include <algorithm> #include <memory> #include <cassert> #include <functional> #include <locale> #include <codecvt> #include "Platform.h" #include "ILoader.h" #include "ILexer.h" #include "Scintilla.h" #include "StringCopy.h" #include "Position.h" #include "UniqueString.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "ContractionState.h" #include "CellBuffer.h" #include "KeyMap.h" #include "Indicator.h" #include "XPM.h" #include "LineMarker.h" #include "Style.h" #include "ViewStyle.h" #include "CharClassify.h" #include "Decoration.h" #include "CaseFolder.h" #include "Document.h" #include "UniConversion.h" #include "Selection.h" #include "PositionCache.h" #include "EditModel.h" #include "MarginView.h" #include "EditView.h" #include "Editor.h" #include "AutoComplete.h" #include "CallTip.h" #include "ScintillaBase.h" #include "scite_impl.h" #include "scintilla_editor.h" #include "term_context.h" #include "term_window.h" #include "color_theme.h" #include "term_cell.h" const GUI::gui_char appName[] = GUI_TEXT("scintilla_editor"); class MyMutex : public Mutex{ public: virtual void Lock() {} virtual void Unlock() {} virtual ~MyMutex() {} }; Mutex * Mutex::Create() { return new MyMutex(); } namespace GUI { ElapsedTime::ElapsedTime(){ (void)bigBit; (void)littleBit; } double ElapsedTime::Duration(bool reset) { (void)reset; return 0; } void Menu::Destroy() {} void Menu::CreatePopUp() {} void Menu::Show(Point, Window &){} void Window::Destroy() {} bool Window::HasFocus() { return false; } Rectangle Window::GetPosition() { return Rectangle {}; } void Window::SetPosition(Rectangle) {}; Rectangle Window::GetClientPosition() {return Rectangle {};} void Window::Show(bool) {} void Window::InvalidateAll() {} void Window::SetTitle(const gui_char *) {} gui_string StringFromUTF8(const char *s) { return gui_string {s}; } gui_string StringFromUTF8(const std::string &s) { return s; } std::string UTF8FromString(const gui_string &s) { return s; } gui_string StringFromInteger(long i) { char number[32]; sprintf(number, "%0ld", i); gui_char gnumber[32]; size_t n=0; while (number[n]) { gnumber[n] = static_cast<gui_char>(number[n]); n++; } gnumber[n] = 0; return gui_string(gnumber); } gui_string StringFromLongLong(long long i) { try { std::ostringstream strstrm; strstrm << i; return StringFromUTF8(strstrm.str()); } catch (std::exception &) { // Exceptions not enabled on stream but still causes diagnostic in Coverity. // Simply swallow the failure and return the default value. } return gui_string(); } gui_string HexStringFromInteger(long i) { char number[32]; sprintf(number, "%0lx", i); gui_char gnumber[32]; size_t n = 0; while (number[n]) { gnumber[n] = static_cast<gui_char>(number[n]); n++; } gnumber[n] = 0; return gui_string(gnumber); } sptr_t ScintillaWindow::Send(unsigned int msg, uptr_t wParam, sptr_t lParam) { ScintillaEditor * pEditor = (ScintillaEditor*)GetID(); if (!pEditor) return 0; return pEditor->WndProc(msg, wParam, lParam); } bool IsDBCSLeadByte(int codePage, char ch) { // Byte ranges found in Wikipedia articles with relevant search strings in each case unsigned char uch = static_cast<unsigned char>(ch); switch (codePage) { case 932: // Shift_jis return ((uch >= 0x81) && (uch <= 0x9F)) || ((uch >= 0xE0) && (uch <= 0xEF)); case 936: // GBK return (uch >= 0x81) && (uch <= 0xFE); case 950: // Big5 return (uch >= 0x81) && (uch <= 0xFE); // Korean EUC-KR may be code page 949. } return false; } }; SciTE::SciTE() : m_pEditor{nullptr} , m_pTermWindow{nullptr} , m_PropsHomeDir{} { } FilePath SciTE::GetDefaultDirectory() { FilePath p{m_PropsHomeDir}; return p.AbsolutePath().NormalizePath(); } FilePath SciTE::GetSciteDefaultHome() { FilePath p{m_PropsHomeDir}; return p.AbsolutePath().NormalizePath(); } FilePath SciTE::GetSciteUserHome() { FilePath p{m_PropsHomeDir}; return p.AbsolutePath().NormalizePath(); } static struct color_base_s { const char * key; uint32_t color_index; } g_color_props[] = { {"colour.base02", 0}, {"colour.red", 1}, {"colour.green", 2}, {"colour.yellow", 3}, {"colour.blue", 4}, {"colour.magenta", 5}, {"colour.cyan", 6}, {"colour.base2", 7}, {"colour.base03", 8}, {"colour.orange", 9}, {"colour.base01", 10}, {"colour.base00", 11}, {"colour.base0", 12}, {"colour.violet", 13}, {"colour.base1", 14}, {"colour.base3", 15}, {"caret.fore", TermCell::DefaultCursorColorIndex}, }; static const char * g_props[] = { "colour.code.comment.box","fore:$(colour.base01),italics", "colour.code.comment.line","fore:$(colour.base01),italics", "colour.code.comment.doc","fore:$(colour.base01),italics", "colour.code.comment.nested","fore:$(colour.base01),italics", "colour.text.comment","fore:$(colour.base01),italics", "colour.other.comment","fore:$(colour.base01),italics", "colour.embedded.comment","fore:$(colour.base01),italics", "colour.embedded.js","fore:$(colour.base01)", "colour.notused","fore:$(colour.base01)", "colour.number","fore:$(colour.cyan)", "colour.keyword","fore:$(colour.green)", "colour.string","fore:$(colour.cyan)", "colour.char","fore:$(colour.cyan)", "colour.operator","fore:$(colour.base01)", "colour.preproc","fore:$(colour.orange)", "colour.error","fore:$(colour.red)", "style.cpp.16","fore:$(colour.blue)", }; void SciTE::Initialize(ScintillaEditor * pEditor, TermWindow * pTermWindow, const std::string & propsHomeDir) { m_pEditor = pEditor; m_pTermWindow = pTermWindow; m_PropsHomeDir = propsHomeDir; wEditor.SetID(pEditor); wOutput.SetID(new ScintillaEditor); buffers.Allocate(1); buffers.Add(); SetFileName("../src/app.cpp", true); char buf[255] = {0}; #define TC2SC(tc) (tc >> 24) & 0xFF, (tc >> 16) & 0xFF, (tc >> 8) & 0xFF sprintf(buf, "back:#%02x%02x%02x,fore:#%02x%02x%02x", TC2SC(pTermWindow->GetColorByIndex(TermCell::DefaultBackColorIndex)), TC2SC(pTermWindow->GetColorByIndex(TermCell::DefaultForeColorIndex))); props.Set("style.*.32", buf); for(size_t i=0;i < sizeof(g_color_props) / sizeof(color_base_s);i++) { sprintf(buf, "#%02x%02x%02x", TC2SC(pTermWindow->GetColorByIndex(g_color_props[i].color_index))); props.Set(g_color_props[i].key, buf); } for(size_t i=0;i < sizeof(g_props) / sizeof(const char *);i+=2) { props.Set(g_props[i], g_props[i+1]); } #undef TC2SC ReloadProperties(); } <|endoftext|>
<commit_before>// A so-called "active mesh" is one whose primary representation is a half-edge structure. It converts to a basic_mesh whenever one is needed, This allows fast application of algorithms as there is no need to convert an indexed list into a half-edge structure every time we use any algorithms. Also, as a bonus the faces on these meshes can be of any number of vertices, instead of being forced to use triangles. // NOTE: Thjo class adds overhead on top of the PolyMesh structure backing it. This comes from validity checks that prevent the app from crashing on bad values. In order to make more cool algorithms function as fast as possible, it is recommended that you extend this class and send me the patches. :) // TODO: As a utility, this mesh provides snapshotting and retrieval of previous generation. // TODO: Split faces // TODO: Add face merging (single-mesh and two meshes) #pragma once #include "Component.hpp" #include "MathFuncs.hpp" #include "BasicMesh.hpp" #include "MeshUtils.hpp" namespace noob { class active_mesh { public: struct face { std::vector<noob::vec3> verts; std::vector<noob::vec2> get_2d() const; noob::vec3 get_normal() const; }; typedef noob::component<noob::active_mesh::face>::handle face_handle; // Basic functionality face_handle add_face(const noob::active_mesh::face&); face_handle add_face(const std::vector<std::array<float, 3>>&); bool exists(const noob::vec3&) const; bool exists(const face&) const; bool exists(face_handle) const; noob::active_mesh::face get_face_by_handle(face_handle) const; noob::active_mesh::face get_face_by_vertex(const noob::vec3&) const; noob::active_mesh::face get_face_by_index(uint32_t) const; // std::vector<uint32_t> get_indices(const noob::vec3&) const; noob::basic_mesh get_basic_mesh() const; // Generation-realted utilities (meshes change and we sometimes/often need to retrieve older copies) size_t get_current_generation() const; noob::active_mesh retrieve_by_generation(size_t) const; bool is_generation_current(size_t) const; // Destructive utiiities. Those take full advantage of the speed benefits of half-edged meshes void make_hole(noob::active_mesh::face_handle); void fill_holes(); void cut_mesh(const noob::vec3& point_on_plane, const noob::vec3 plane_normal); void cut_faces(std::vector<noob::active_mesh::face_handle>&, const noob::vec3& point_on_plane, const noob::vec3& plane_normal); void connect_faces(noob::active_mesh::face_handle first_handle, noob::active_mesh::face_handle second_handle); static void connect_meshes(const noob::active_mesh& first, noob::active_mesh::face_handle first_handle, const noob::active_mesh& second, noob::active_mesh::face_handle second_handle); void extrude(noob::active_mesh::face_handle, const noob::vec3& normal, float length); protected: // TODO: Optimize. // std::map<std::array<float, 3>, std::vector<uint32_t>> verts_to_indices; typedef noob::component<noob::active_mesh::face> faces_holder; faces_holder faces; }; } <commit_msg>COntinue fleshing out active mesh API<commit_after>// A so-called "active mesh" is one whose primary representation is a half-edge structure. It converts to a basic_mesh whenever one is needed, This allows fast application of algorithms as there is no need to convert an indexed list into a half-edge structure every time we use any algorithms. Also, as a bonus the faces on these meshes can be of any number of vertices, instead of being forced to use triangles. // NOTE: Thjo class adds overhead on top of the PolyMesh structure backing it. This comes from validity checks that prevent the app from crashing on bad values. In order to make more cool algorithms function as fast as possible, it is recommended that you extend this class and send me the patches. :) // TODO: As a utility, this mesh provides snapshotting and retrieval of previous generation. // TODO: Split faces // TODO: Add face merging (single-mesh and two meshes) #pragma once #include "Component.hpp" #include "MathFuncs.hpp" #include "BasicMesh.hpp" #include "MeshUtils.hpp" typedef OpenMesh::PolyMesh_ArrayKernelT<> PolyMesh; namespace noob { struct indexed_polymesh { // Convenience std::vector<std::vector<std::array<float, 3>>> get_face_list() const; // Struct data memebers std::vector<std::array<float, 3>> vertices; std::vector<std::vector<uint32_t>> faces; }; class active_mesh { public: struct face { std::vector<noob::vec3> verts; std::vector<noob::vec2> get_2d() const; noob::vec3 get_normal() const; }; typedef noob::component<noob::active_mesh::face>::handle face_handle; // Basic functionality face_handle add_face(const noob::active_mesh::face&); face_handle add_face(const std::vector<std::array<float, 3>>&); bool exists(const noob::vec3&) const; bool exists(const face&) const; bool exists(face_handle) const; noob::active_mesh::face get_face_vals(face_handle) const; noob::active_mesh::face get_face_vals(const noob::vec3&) const; noob::active_mesh::face get_face_vals(uint32_t) const; // std::vector<uint32_t> get_indices(const noob::vec3&) const; noob::basic_mesh to_basic_mesh() const; noob::indexed_polymesh to_indexed_polymesh() const; std::vector<noob::active_mesh::face_handle> get_adjacent_faces(noob::active_mesh::face_handle) const; // Generation-related utilities (meshes change and we sometimes/often need to retrieve older copies) size_t get_current_generation() const; noob::active_mesh retrieve_by_generation(uint32_t) const; bool is_generation_current(uint32_t) const; // TODO: Find out if "topological split" makes proper sense in this context std::vector<noob::active_mesh> topological_split(const std::vector<noob::active_mesh::face_handle>&) const; // Destructive utiiities. Those take full advantage of the speed benefits of half-edged meshes void make_hole(noob::active_mesh::face_handle); void fill_holes(); void cut_mesh(const noob::vec3& point_on_plane, const noob::vec3 plane_normal); void cut_faces(std::vector<noob::active_mesh::face_handle>&, const noob::vec3& point_on_plane, const noob::vec3& plane_normal); void extrude(noob::active_mesh::face_handle, const noob::vec3& normal, float magnitude); void connect_faces(noob::active_mesh::face_handle first_handle, noob::active_mesh::face_handle second_handle); void move_vertex(const noob::vec3& vertex, const noob::vec3& normal, float magnitude); void move_vertex(uint32_t index, const noob::vec3& normal, float magnitude); // This function is static because it acts on two objects. The static modifier makes it explicit. // TODO: Possibly move into mesh_utils static void join_meshes(const noob::active_mesh& first, noob::active_mesh::face_handle first_handle, const noob::active_mesh& second, noob::active_mesh::face_handle second_handle); protected: PolyMesh half_edges; struct inner_index_mesh { std::vector<std::tuple<std::array<float, 3>, PolyMesh::Vertex*>> vertices; std::vector<uint32_t> faces; }; void update_index(); noob::active_mesh::inner_index_mesh index; // TODO: Optimize. // std::map<std::array<float, 3>, std::vector<uint32_t>> verts_to_indices; uint32_t current_generation; typedef noob::component<noob::active_mesh::face> faces_holder; faces_holder faces; }; } <|endoftext|>
<commit_before>// // GLFeature.cpp // G3MiOSSDK // // Created by Jose Miguel SN on 18/03/13. // // #include "GLFeature.hpp" BillboardGLFeature::BillboardGLFeature(int textureWidth, int textureHeight, int viewportWidth, int viewportHeight): GLFeature(NO_GROUP){ _texExtent = new GPUUniformValueVec2Float(textureWidth, textureHeight); _values.addUniformValue(TEXTURE_EXTENT, _texExtent); _viewportExtent = new GPUUniformValueVec2Float(viewportWidth, viewportHeight); _values.addUniformValue(VIEWPORT_EXTENT, _viewportExtent); } BillboardGLFeature::~BillboardGLFeature(){ // _texExtent->_release(); // _viewportExtent->_release(); } GeometryGLFeature::GeometryGLFeature(IFloatBuffer* buffer, int arrayElementSize, int index, bool normalized, int stride, bool depthTestEnabled, bool cullFace, int culledFace, bool polygonOffsetFill, float polygonOffsetFactor, float polygonOffsetUnits, float lineWidth, bool needsPointSize, float pointSize): GLFeature(NO_GROUP), _depthTestEnabled(depthTestEnabled), _cullFace(cullFace), _culledFace(culledFace), _polygonOffsetFill(polygonOffsetFill), _polygonOffsetFactor(polygonOffsetFactor), _polygonOffsetUnits(polygonOffsetUnits), _lineWidth(lineWidth) { _position = new GPUAttributeValueVec4Float(buffer, arrayElementSize, index, stride, normalized); _values.addAttributeValue(POSITION, _position); // _globalState = new GLGlobalState(); // if (depthTestEnabled){ // _globalState->enableDepthTest(); // } else{ // _globalState->disableDepthTest(); // } // // if (cullFace){ // _globalState->enableCullFace(culledFace); // } else{ // _globalState->disableCullFace(); // } // // if (polygonOffsetFill){ // _globalState->enablePolygonOffsetFill(polygonOffsetFactor, polygonOffsetFill); // } else{ // _globalState->disPolygonOffsetFill(); // } // // _globalState->setLineWidth(lineWidth); if (needsPointSize){ _values.addUniformValue(POINT_SIZE, new GPUUniformValueFloat(pointSize)); } } void GeometryGLFeature::applyOnGlobalGLState(GLGlobalState* state) const{ if (_depthTestEnabled){ state->enableDepthTest(); } else{ state->disableDepthTest(); } if (_cullFace){ state->enableCullFace(_culledFace); } else{ state->disableCullFace(); } if (_polygonOffsetFill){ state->enablePolygonOffsetFill(_polygonOffsetFactor, _polygonOffsetFill); } else{ state->disPolygonOffsetFill(); } state->setLineWidth(_lineWidth); } GeometryGLFeature::~GeometryGLFeature(){ // _position->_release(); } TextureGLFeature::TextureGLFeature(const IGLTextureId* texID, IFloatBuffer* texCoords, int arrayElementSize, int index, bool normalized, int stride, bool blend, int sFactor, int dFactor, bool coordsTransformed, const Vector2D& translate, const Vector2D& scale): GLColorGroupFeature(4, blend, sFactor, dFactor), _texID(texID) { // _globalState->bindTexture(texID); GPUAttributeValueVec4Float* value = new GPUAttributeValueVec4Float(texCoords, arrayElementSize, index, stride, normalized); _values.addAttributeValue(TEXTURE_COORDS, value); if (coordsTransformed){ _values.addUniformValue(TRANSLATION_TEXTURE_COORDS, new GPUUniformValueVec2Float((float)translate._x, (float)translate._y)); _values.addUniformValue(SCALE_TEXTURE_COORDS, new GPUUniformValueVec2Float((float)scale._x, (float)scale._y)); } } void TextureGLFeature::applyOnGlobalGLState(GLGlobalState* state) const{ blendingOnGlobalGLState(state); state->bindTexture(_texID); } ColorGLFeature::ColorGLFeature(IFloatBuffer* colors, int arrayElementSize, int index, bool normalized, int stride, bool blend, int sFactor, int dFactor): GLColorGroupFeature(3, blend, sFactor, dFactor) { GPUAttributeValueVec4Float* value = new GPUAttributeValueVec4Float(colors, arrayElementSize, index, stride, normalized); _values.addAttributeValue(COLOR, value); } FlatColorGLFeature::FlatColorGLFeature(const Color& color, bool blend, int sFactor, int dFactor): GLColorGroupFeature(2, blend, sFactor, dFactor) { _values.addUniformValue(FLAT_COLOR, new GPUUniformValueVec4Float(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha())); } <commit_msg>no leaks<commit_after>// // GLFeature.cpp // G3MiOSSDK // // Created by Jose Miguel SN on 18/03/13. // // #include "GLFeature.hpp" BillboardGLFeature::BillboardGLFeature(int textureWidth, int textureHeight, int viewportWidth, int viewportHeight): GLFeature(NO_GROUP){ _texExtent = new GPUUniformValueVec2Float(textureWidth, textureHeight); _values.addUniformValue(TEXTURE_EXTENT, _texExtent); _viewportExtent = new GPUUniformValueVec2Float(viewportWidth, viewportHeight); _values.addUniformValue(VIEWPORT_EXTENT, _viewportExtent); } BillboardGLFeature::~BillboardGLFeature(){ _texExtent->_release(); _viewportExtent->_release(); } GeometryGLFeature::GeometryGLFeature(IFloatBuffer* buffer, int arrayElementSize, int index, bool normalized, int stride, bool depthTestEnabled, bool cullFace, int culledFace, bool polygonOffsetFill, float polygonOffsetFactor, float polygonOffsetUnits, float lineWidth, bool needsPointSize, float pointSize): GLFeature(NO_GROUP), _depthTestEnabled(depthTestEnabled), _cullFace(cullFace), _culledFace(culledFace), _polygonOffsetFill(polygonOffsetFill), _polygonOffsetFactor(polygonOffsetFactor), _polygonOffsetUnits(polygonOffsetUnits), _lineWidth(lineWidth) { _position = new GPUAttributeValueVec4Float(buffer, arrayElementSize, index, stride, normalized); _values.addAttributeValue(POSITION, _position); // _globalState = new GLGlobalState(); // if (depthTestEnabled){ // _globalState->enableDepthTest(); // } else{ // _globalState->disableDepthTest(); // } // // if (cullFace){ // _globalState->enableCullFace(culledFace); // } else{ // _globalState->disableCullFace(); // } // // if (polygonOffsetFill){ // _globalState->enablePolygonOffsetFill(polygonOffsetFactor, polygonOffsetFill); // } else{ // _globalState->disPolygonOffsetFill(); // } // // _globalState->setLineWidth(lineWidth); if (needsPointSize){ _values.addNewUniformValue(POINT_SIZE, new GPUUniformValueFloat(pointSize)); } } void GeometryGLFeature::applyOnGlobalGLState(GLGlobalState* state) const{ if (_depthTestEnabled){ state->enableDepthTest(); } else{ state->disableDepthTest(); } if (_cullFace){ state->enableCullFace(_culledFace); } else{ state->disableCullFace(); } if (_polygonOffsetFill){ state->enablePolygonOffsetFill(_polygonOffsetFactor, _polygonOffsetFill); } else{ state->disPolygonOffsetFill(); } state->setLineWidth(_lineWidth); } GeometryGLFeature::~GeometryGLFeature(){ _position->_release(); } TextureGLFeature::TextureGLFeature(const IGLTextureId* texID, IFloatBuffer* texCoords, int arrayElementSize, int index, bool normalized, int stride, bool blend, int sFactor, int dFactor, bool coordsTransformed, const Vector2D& translate, const Vector2D& scale): GLColorGroupFeature(4, blend, sFactor, dFactor), _texID(texID) { // _globalState->bindTexture(texID); GPUAttributeValueVec4Float* value = new GPUAttributeValueVec4Float(texCoords, arrayElementSize, index, stride, normalized); _values.addNewAttributeValue(TEXTURE_COORDS, value); if (coordsTransformed){ _values.addNewUniformValue(TRANSLATION_TEXTURE_COORDS, new GPUUniformValueVec2Float((float)translate._x, (float)translate._y)); _values.addNewUniformValue(SCALE_TEXTURE_COORDS, new GPUUniformValueVec2Float((float)scale._x, (float)scale._y)); } } void TextureGLFeature::applyOnGlobalGLState(GLGlobalState* state) const{ blendingOnGlobalGLState(state); state->bindTexture(_texID); } ColorGLFeature::ColorGLFeature(IFloatBuffer* colors, int arrayElementSize, int index, bool normalized, int stride, bool blend, int sFactor, int dFactor): GLColorGroupFeature(3, blend, sFactor, dFactor) { GPUAttributeValueVec4Float* value = new GPUAttributeValueVec4Float(colors, arrayElementSize, index, stride, normalized); _values.addNewAttributeValue(COLOR, value); } FlatColorGLFeature::FlatColorGLFeature(const Color& color, bool blend, int sFactor, int dFactor): GLColorGroupFeature(2, blend, sFactor, dFactor) { _values.addNewUniformValue(FLAT_COLOR, new GPUUniformValueVec4Float(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha())); } <|endoftext|>
<commit_before>#include "InjectOpenGLIntrinsics.h" #include "IRMutator.h" #include "IROperator.h" namespace Halide { namespace Internal { using std::string; using std::vector; class InjectOpenGLIntrinsics : public IRMutator { public: InjectOpenGLIntrinsics() : inside_kernel_loop(false) { } Scope<int> scope; bool inside_kernel_loop; private: using IRMutator::visit; void visit(const Provide *provide) { if (!inside_kernel_loop) { IRMutator::visit(provide); return; } internal_assert(provide->values.size() == 1) << "GLSL currently only supports single-valued stores.\n"; user_assert(provide->args.size() == 3) << "GLSL stores requires three coordinates.\n"; // Create glsl_texture_store(name, name.buffer, x, y, c, value) // intrinsic. vector<Expr> args(6); args[0] = provide->name; args[1] = Variable::make(Handle(), provide->name + ".buffer"); for (size_t i = 0; i < provide->args.size(); i++) { args[i + 2] = provide->args[i]; } args[5] = mutate(provide->values[0]); stmt = Evaluate::make( Call::make(args[5].type(), Call::glsl_texture_store, args, Call::Intrinsic)); } void visit(const Call *call) { if (!inside_kernel_loop || call->call_type == Call::Intrinsic) { IRMutator::visit(call); return; } string name = call->name; if (call->call_type == Call::Halide && call->func.outputs() > 1) { name = name + '.' + int_to_string(call->value_index); } user_assert(call->args.size() == 3) << "GLSL loads requires three coordinates.\n"; // Create glsl_texture_load(name, name.buffer, x, y, c) intrinsic. vector<Expr> args(5); args[0] = call->name; args[1] = Variable::make(Handle(), call->name + ".buffer"); for (size_t i = 0; i < call->args.size(); i++) { string d = int_to_string(i); string min_name = name + ".min." + d; string min_name_constrained = min_name + ".constrained"; if (scope.contains(min_name_constrained)) { min_name = min_name_constrained; } string extent_name = name + ".extent." + d; string extent_name_constrained = extent_name + ".constrained"; if (scope.contains(extent_name_constrained)) { extent_name = extent_name_constrained; } Expr min = Variable::make(Int(32), min_name); Expr extent = Variable::make(Int(32), extent_name); // Normalize the two spatial coordinates x,y args[i + 2] = (i < 2) ? (Cast::make(Float(32), call->args[i] - min) + 0.5f) / extent : call->args[i] - min; } expr = Call::make(call->type, Call::glsl_texture_load, args, Call::Intrinsic, Function(), 0, call->image, call->param); } void visit(const LetStmt *let) { // Discover constrained versions of things. bool constrained_version_exists = ends_with(let->name, ".constrained"); if (constrained_version_exists) { scope.push(let->name, 0); } IRMutator::visit(let); if (constrained_version_exists) { scope.pop(let->name); } } void visit(const For *loop) { bool old_kernel_loop = inside_kernel_loop; if (loop->for_type == For::Parallel && (ends_with(loop->name, ".blockidx") || ends_with(loop->name, ".blockidy"))) { inside_kernel_loop = true; } IRMutator::visit(loop); inside_kernel_loop = old_kernel_loop; } }; Stmt inject_opengl_intrinsics(Stmt s) { return InjectOpenGLIntrinsics().mutate(s); } } } <commit_msg>Follow new GPU loop conventions for OpenGL<commit_after>#include "InjectOpenGLIntrinsics.h" #include "IRMutator.h" #include "IROperator.h" #include "CodeGen_GPU_Dev.h" #include "Substitute.h" namespace Halide { namespace Internal { using std::string; using std::vector; class InjectOpenGLIntrinsics : public IRMutator { public: InjectOpenGLIntrinsics() : inside_kernel_loop(false) { } Scope<int> scope; bool inside_kernel_loop; private: using IRMutator::visit; void visit(const Provide *provide) { if (!inside_kernel_loop) { IRMutator::visit(provide); return; } internal_assert(provide->values.size() == 1) << "GLSL currently only supports single-valued stores.\n"; user_assert(provide->args.size() == 3) << "GLSL stores requires three coordinates.\n"; // Create glsl_texture_store(name, name.buffer, x, y, c, value) // intrinsic. vector<Expr> args(6); args[0] = provide->name; args[1] = Variable::make(Handle(), provide->name + ".buffer"); for (size_t i = 0; i < provide->args.size(); i++) { args[i + 2] = provide->args[i]; } args[5] = mutate(provide->values[0]); stmt = Evaluate::make( Call::make(args[5].type(), Call::glsl_texture_store, args, Call::Intrinsic)); } void visit(const Call *call) { if (!inside_kernel_loop || call->call_type == Call::Intrinsic) { IRMutator::visit(call); return; } string name = call->name; if (call->call_type == Call::Halide && call->func.outputs() > 1) { name = name + '.' + int_to_string(call->value_index); } user_assert(call->args.size() == 3) << "GLSL loads requires three coordinates.\n"; // Create glsl_texture_load(name, name.buffer, x, y, c) intrinsic. vector<Expr> args(5); args[0] = call->name; args[1] = Variable::make(Handle(), call->name + ".buffer"); for (size_t i = 0; i < call->args.size(); i++) { string d = int_to_string(i); string min_name = name + ".min." + d; string min_name_constrained = min_name + ".constrained"; if (scope.contains(min_name_constrained)) { min_name = min_name_constrained; } string extent_name = name + ".extent." + d; string extent_name_constrained = extent_name + ".constrained"; if (scope.contains(extent_name_constrained)) { extent_name = extent_name_constrained; } Expr min = Variable::make(Int(32), min_name); Expr extent = Variable::make(Int(32), extent_name); // Normalize the two spatial coordinates x,y args[i + 2] = (i < 2) ? (Cast::make(Float(32), call->args[i] - min) + 0.5f) / extent : call->args[i] - min; } expr = Call::make(call->type, Call::glsl_texture_load, args, Call::Intrinsic, Function(), 0, call->image, call->param); } void visit(const LetStmt *let) { // Discover constrained versions of things. bool constrained_version_exists = ends_with(let->name, ".constrained"); if (constrained_version_exists) { scope.push(let->name, 0); } IRMutator::visit(let); if (constrained_version_exists) { scope.pop(let->name); } } void visit(const For *loop) { bool old_kernel_loop = inside_kernel_loop; if (loop->for_type == For::Parallel && CodeGen_GPU_Dev::is_gpu_block_var(loop->name)) { inside_kernel_loop = true; } IRMutator::visit(loop); inside_kernel_loop = old_kernel_loop; } }; // Rewrite all GPU loops to have a min of zero class ZeroGPULoopMins : public IRMutator { using IRMutator::visit; void visit(const For *op) { IRMutator::visit(op); if (CodeGen_GPU_Dev::is_gpu_var(op->name) && !is_zero(op->min)) { op = stmt.as<For>(); internal_assert(op); Expr adjusted = Variable::make(Int(32), op->name) + op->min; Stmt body = substitute(op->name, adjusted, op->body); stmt = For::make(op->name, 0, op->extent, op->for_type, body); } } }; Stmt inject_opengl_intrinsics(Stmt s) { ZeroGPULoopMins z; s = z.mutate(s); InjectOpenGLIntrinsics gl; return gl.mutate(s); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sdiocmpt.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 03:13:28 $ * * 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 * ************************************************************************/ #pragma hdrstop #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #include "sdiocmpt.hxx" //BFS02 ////////////////////////////////////////////////////////////////////////////// old_SdrDownCompat::old_SdrDownCompat(SvStream& rNewStream, UINT16 nNewMode) : rStream(rNewStream), nSubRecSiz(0), nSubRecPos(0), nMode(nNewMode), bOpen(FALSE) { OpenSubRecord(); } old_SdrDownCompat::~old_SdrDownCompat() { if(bOpen) CloseSubRecord(); } void old_SdrDownCompat::Read() { rStream >> nSubRecSiz; } void old_SdrDownCompat::Write() { rStream << nSubRecSiz; } void old_SdrDownCompat::OpenSubRecord() { if(rStream.GetError()) return; nSubRecPos = rStream.Tell(); if(nMode == STREAM_READ) { Read(); } else if(nMode == STREAM_WRITE) { Write(); } bOpen = TRUE; } void old_SdrDownCompat::CloseSubRecord() { if(rStream.GetError()) return; UINT32 nAktPos(rStream.Tell()); if(nMode == STREAM_READ) { UINT32 nReadAnz(nAktPos - nSubRecPos); if(nReadAnz != nSubRecSiz) { rStream.Seek(nSubRecPos + nSubRecSiz); } } else if(nMode == STREAM_WRITE) { nSubRecSiz = nAktPos - nSubRecPos; rStream.Seek(nSubRecPos); Write(); rStream.Seek(nAktPos); } bOpen = FALSE; } /************************************************************************* |* |* Konstruktor, schreibt bzw. liest Versionsnummer |* \************************************************************************/ SdIOCompat::SdIOCompat(SvStream& rNewStream, USHORT nNewMode, UINT16 nVer) : old_SdrDownCompat(rNewStream, nNewMode), nVersion(nVer) { if (nNewMode == STREAM_WRITE) { DBG_ASSERT(nVer != SDIOCOMPAT_VERSIONDONTKNOW, "kann unbekannte Version nicht schreiben"); rNewStream << nVersion; } else if (nNewMode == STREAM_READ) { DBG_ASSERT(nVer == SDIOCOMPAT_VERSIONDONTKNOW, "Lesen mit Angabe der Version ist Quatsch!"); rNewStream >> nVersion; } } SdIOCompat::~SdIOCompat() { } // eof <commit_msg>INTEGRATION: CWS pchfix02 (1.3.280); FILE MERGED 2006/09/01 17:36:43 kaib 1.3.280.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sdiocmpt.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:15:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #include "sdiocmpt.hxx" //BFS02 ////////////////////////////////////////////////////////////////////////////// old_SdrDownCompat::old_SdrDownCompat(SvStream& rNewStream, UINT16 nNewMode) : rStream(rNewStream), nSubRecSiz(0), nSubRecPos(0), nMode(nNewMode), bOpen(FALSE) { OpenSubRecord(); } old_SdrDownCompat::~old_SdrDownCompat() { if(bOpen) CloseSubRecord(); } void old_SdrDownCompat::Read() { rStream >> nSubRecSiz; } void old_SdrDownCompat::Write() { rStream << nSubRecSiz; } void old_SdrDownCompat::OpenSubRecord() { if(rStream.GetError()) return; nSubRecPos = rStream.Tell(); if(nMode == STREAM_READ) { Read(); } else if(nMode == STREAM_WRITE) { Write(); } bOpen = TRUE; } void old_SdrDownCompat::CloseSubRecord() { if(rStream.GetError()) return; UINT32 nAktPos(rStream.Tell()); if(nMode == STREAM_READ) { UINT32 nReadAnz(nAktPos - nSubRecPos); if(nReadAnz != nSubRecSiz) { rStream.Seek(nSubRecPos + nSubRecSiz); } } else if(nMode == STREAM_WRITE) { nSubRecSiz = nAktPos - nSubRecPos; rStream.Seek(nSubRecPos); Write(); rStream.Seek(nAktPos); } bOpen = FALSE; } /************************************************************************* |* |* Konstruktor, schreibt bzw. liest Versionsnummer |* \************************************************************************/ SdIOCompat::SdIOCompat(SvStream& rNewStream, USHORT nNewMode, UINT16 nVer) : old_SdrDownCompat(rNewStream, nNewMode), nVersion(nVer) { if (nNewMode == STREAM_WRITE) { DBG_ASSERT(nVer != SDIOCOMPAT_VERSIONDONTKNOW, "kann unbekannte Version nicht schreiben"); rNewStream << nVersion; } else if (nNewMode == STREAM_READ) { DBG_ASSERT(nVer == SDIOCOMPAT_VERSIONDONTKNOW, "Lesen mit Angabe der Version ist Quatsch!"); rNewStream >> nVersion; } } SdIOCompat::~SdIOCompat() { } // eof <|endoftext|>
<commit_before>#include "ffbperiodiceffect.h" #include <QDebug> FFBPeriodicEffect::FFBPeriodicEffect() : FFBEffect(FFBEffectTypes::PERIODIC) {} struct ff_effect* FFBPeriodicEffect::createFFStruct() { struct ff_effect* eff = FFBEffect::createFFStruct(m_params); if (eff == nullptr) return nullptr; eff->type = FF_PERIODIC; eff->u.periodic.envelope.attack_length = m_params->attackLength; eff->u.periodic.envelope.attack_level = m_params->attackLevel; eff->u.periodic.envelope.fade_length = m_params->fadeLength; eff->u.periodic.envelope.fade_level = m_params->fadeLevel; eff->u.periodic.magnitude = m_params->magnitude; eff->u.periodic.offset = m_params->offset; eff->u.periodic.period = m_params->period; eff->u.periodic.phase = m_params->phase; switch (m_params->waveform) { case PeriodicWaveforms::SINE: eff->u.periodic.waveform= FF_SINE; break; case PeriodicWaveforms::SQUARE: eff->u.periodic.waveform = FF_SQUARE; break; case PeriodicWaveforms::SAW_DOWN: eff->u.periodic.waveform = FF_SAW_DOWN; break; case PeriodicWaveforms::SAW_UP: eff->u.periodic.waveform = FF_SAW_UP; break; case PeriodicWaveforms::TRIANGLE: eff->u.periodic.waveform = FF_TRIANGLE; break; case PeriodicWaveforms::NONE: delete eff; return nullptr; } return eff; } bool FFBPeriodicEffect::setParameters(const std::shared_ptr<FFBEffectParameters> params) { try { return setParameters(std::dynamic_pointer_cast<FFBPeriodicEffectParameters>(params)); } catch (const std::bad_cast& ex) { reportError("Invalid effect parameters object " + QString(ex.what())); return false; } } bool FFBPeriodicEffect::setParameters(const std::shared_ptr<FFBPeriodicEffectParameters> params) { if (!checkGenericParameters(params)) return false; if (!checkBoundsInclusive(params->attackLength, 0, 0xFFFF)) { reportError("Attack length out of bounds."); return false; } if (!checkBoundsInclusive(params->attackLevel, 0, 0xFFFF)) { reportError("Attack level out of bounds."); return false; } if (!checkBoundsInclusive(params->fadeLength, 0, 0xFFFF)) { reportError("Fade length out of bounds."); return false; } if (!checkBoundsInclusive(params->fadeLevel, 0, 0xFFFF)) { reportError("Fade level out of bounds."); return false; } if (!checkBoundsInclusive(params->magnitude, -0x7FFF, 0x7FFF)) { reportError("Magnitude out of bounds."); return false; } if (!checkBoundsInclusive(params->offset, -0x7FFF, 0x7FFF)) { reportError("Offset out of bounds."); return false; } if (!checkBoundsInclusive(params->period, 0, 0xFFFF)) { reportError("Period out of bounds."); return false; } if (!checkBoundsInclusive(params->phase, 0, 0xFFFF)) { reportError("Phase out of bounds."); return false; } if (params->waveform == PeriodicWaveforms::NONE) { reportError("Invalid waveform type."); return false; } m_params = params; return true; } bool FFBPeriodicEffect::operator==(const FFBEffect& other) const { if (this->type() != other.type()) return false; else return this->m_params->waveform == dynamic_cast<const FFBPeriodicEffect&>(other).m_params->waveform; } bool FFBPeriodicEffect::operator!=(const FFBEffect& other) const { return !(*this == other); } FFBPeriodicEffect::~FFBPeriodicEffect() { } <commit_msg>Safely cast FFBEffect& to FFBPeriodicEffect& in operator==<commit_after>#include "ffbperiodiceffect.h" #include <QDebug> FFBPeriodicEffect::FFBPeriodicEffect() : FFBEffect(FFBEffectTypes::PERIODIC) {} struct ff_effect* FFBPeriodicEffect::createFFStruct() { struct ff_effect* eff = FFBEffect::createFFStruct(m_params); if (eff == nullptr) return nullptr; eff->type = FF_PERIODIC; eff->u.periodic.envelope.attack_length = m_params->attackLength; eff->u.periodic.envelope.attack_level = m_params->attackLevel; eff->u.periodic.envelope.fade_length = m_params->fadeLength; eff->u.periodic.envelope.fade_level = m_params->fadeLevel; eff->u.periodic.magnitude = m_params->magnitude; eff->u.periodic.offset = m_params->offset; eff->u.periodic.period = m_params->period; eff->u.periodic.phase = m_params->phase; switch (m_params->waveform) { case PeriodicWaveforms::SINE: eff->u.periodic.waveform= FF_SINE; break; case PeriodicWaveforms::SQUARE: eff->u.periodic.waveform = FF_SQUARE; break; case PeriodicWaveforms::SAW_DOWN: eff->u.periodic.waveform = FF_SAW_DOWN; break; case PeriodicWaveforms::SAW_UP: eff->u.periodic.waveform = FF_SAW_UP; break; case PeriodicWaveforms::TRIANGLE: eff->u.periodic.waveform = FF_TRIANGLE; break; case PeriodicWaveforms::NONE: delete eff; return nullptr; } return eff; } bool FFBPeriodicEffect::setParameters(const std::shared_ptr<FFBEffectParameters> params) { try { return setParameters(std::dynamic_pointer_cast<FFBPeriodicEffectParameters>(params)); } catch (const std::bad_cast& ex) { reportError("Invalid effect parameters object " + QString(ex.what())); return false; } } bool FFBPeriodicEffect::setParameters(const std::shared_ptr<FFBPeriodicEffectParameters> params) { if (!checkGenericParameters(params)) return false; if (!checkBoundsInclusive(params->attackLength, 0, 0xFFFF)) { reportError("Attack length out of bounds."); return false; } if (!checkBoundsInclusive(params->attackLevel, 0, 0xFFFF)) { reportError("Attack level out of bounds."); return false; } if (!checkBoundsInclusive(params->fadeLength, 0, 0xFFFF)) { reportError("Fade length out of bounds."); return false; } if (!checkBoundsInclusive(params->fadeLevel, 0, 0xFFFF)) { reportError("Fade level out of bounds."); return false; } if (!checkBoundsInclusive(params->magnitude, -0x7FFF, 0x7FFF)) { reportError("Magnitude out of bounds."); return false; } if (!checkBoundsInclusive(params->offset, -0x7FFF, 0x7FFF)) { reportError("Offset out of bounds."); return false; } if (!checkBoundsInclusive(params->period, 0, 0xFFFF)) { reportError("Period out of bounds."); return false; } if (!checkBoundsInclusive(params->phase, 0, 0xFFFF)) { reportError("Phase out of bounds."); return false; } if (params->waveform == PeriodicWaveforms::NONE) { reportError("Invalid waveform type."); return false; } m_params = params; return true; } bool FFBPeriodicEffect::operator==(const FFBEffect& other) const { if (this->type() != other.type()) return false; else { try { const FFBPeriodicEffect& eff = dynamic_cast<const FFBPeriodicEffect&>(other); return this->m_params->waveform == eff.m_params->waveform; } catch(std::bad_cast&) { return false; } } } bool FFBPeriodicEffect::operator!=(const FFBEffect& other) const { return !(*this == other); } FFBPeriodicEffect::~FFBPeriodicEffect() { } <|endoftext|>
<commit_before>#include "../services.hpp" #include "xbt.h" #include "simgrid/s4u.hpp" #include <iostream> using namespace ::apache::thrift::server; using namespace ::RsgService; using namespace ::simgrid; std::unordered_map<int, simgrid::s4u::MutexPtr> rsg::RsgMutexHandler::pMutexes; unsigned long long rsg::RsgMutexHandler::pMutexsMapId = 0; int64_t rsg::RsgMutexHandler::mutexInit() { s4u::MutexPtr mutex = s4u::Mutex::createMutex(); unsigned long long newId = rsg::RsgMutexHandler::pMutexsMapId++; rsg::RsgMutexHandler::pMutexes.insert({newId, mutex}); return newId; } void rsg::RsgMutexHandler::lock(const int64_t rmtAddr) { s4u::MutexPtr mutex = rsg::RsgMutexHandler::pMutexes.at(rmtAddr); mutex->lock(); } void rsg::RsgMutexHandler::unlock(const int64_t rmtAddr) { s4u::MutexPtr mutex = rsg::RsgMutexHandler::pMutexes.at(rmtAddr); mutex->unlock(); } bool rsg::RsgMutexHandler::try_lock(const int64_t rmtAddr) { s4u::MutexPtr mutex = rsg::RsgMutexHandler::pMutexes.at(rmtAddr); return mutex->try_lock(); } void rsg::RsgMutexHandler::destroy(const int64_t rmtAddr) { rsg::RsgMutexHandler::pMutexes.erase(rmtAddr); } <commit_msg>unlock can be used on unlocked mutex without crashe. The behaviour is stay undefined.<commit_after>#include "../services.hpp" #include "xbt.h" #include "simgrid/s4u.hpp" #include <iostream> using namespace ::apache::thrift::server; using namespace ::RsgService; using namespace ::simgrid; std::unordered_map<int, simgrid::s4u::MutexPtr> rsg::RsgMutexHandler::pMutexes; unsigned long long rsg::RsgMutexHandler::pMutexsMapId = 0; int64_t rsg::RsgMutexHandler::mutexInit() { s4u::MutexPtr mutex = s4u::Mutex::createMutex(); unsigned long long newId = rsg::RsgMutexHandler::pMutexsMapId++; rsg::RsgMutexHandler::pMutexes.insert({newId, mutex}); return newId; } void rsg::RsgMutexHandler::lock(const int64_t rmtAddr) { s4u::MutexPtr mutex = rsg::RsgMutexHandler::pMutexes.at(rmtAddr); mutex->lock(); } void rsg::RsgMutexHandler::unlock(const int64_t rmtAddr) { s4u::MutexPtr mutex = rsg::RsgMutexHandler::pMutexes.at(rmtAddr); if(!mutex->try_lock()) { mutex->unlock(); } if(mutex->try_lock()) { mutex->unlock(); } } bool rsg::RsgMutexHandler::try_lock(const int64_t rmtAddr) { s4u::MutexPtr mutex = rsg::RsgMutexHandler::pMutexes.at(rmtAddr); return mutex->try_lock(); } void rsg::RsgMutexHandler::destroy(const int64_t rmtAddr) { rsg::RsgMutexHandler::pMutexes.erase(rmtAddr); } <|endoftext|>
<commit_before>/*========================================================================= Program: DICOM for VTK Copyright (c) 2012-2014 David Gobbi All rights reserved. See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDICOMMRGenerator.h" #include "vtkDICOMMetaData.h" #include "vtkDICOMSequence.h" #include "vtkDICOMItem.h" #include "vtkDICOMTagPath.h" #include "vtkObjectFactory.h" #include "vtkDataSetAttributes.h" #include "vtkInformation.h" vtkStandardNewMacro(vtkDICOMMRGenerator); //---------------------------------------------------------------------------- vtkDICOMMRGenerator::vtkDICOMMRGenerator() { } //---------------------------------------------------------------------------- vtkDICOMMRGenerator::~vtkDICOMMRGenerator() { } //---------------------------------------------------------------------------- void vtkDICOMMRGenerator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------------- bool vtkDICOMMRGenerator::GenerateMRSeriesModule(vtkDICOMMetaData *source) { vtkDICOMMetaData *meta = this->MetaData; meta->SetAttributeValue(DC::Modality, "MR"); // optional and conditional: direct copy of values with no checks static const DC::EnumType optional[] = { DC::ReferencedPerformedProcedureStepSequence, // 1C DC::ItemDelimitationItem }; return this->CopyOptionalAttributes(optional, source); } //---------------------------------------------------------------------------- bool vtkDICOMMRGenerator::GenerateMRImageModule(vtkDICOMMetaData *source) { // ImageType is specialized from GeneralImageModule, // by adding a third value that is specific to MRI: // MPR, T2 MAP, PHASE MAP, PHASE SUBTRACT, PROJECTION IMAGE, // DIFFUSION MAP, VELOCITY MAP, MODULUS SUBTRACT, T1 MAP, // DENSITY MAP, IMAGE ADDITION, OTHER const char *it = 0; if (source) { it = source->GetAttributeValue(DC::ImageType).GetCharData(); } if (it == 0 || it[0] == '\0') { it = "DERIVED\\SECONDARY\\OTHER"; } vtkDICOMMetaData *meta = this->MetaData; meta->SetAttributeValue(DC::ImageType, it); // These specialized from ImagePixelModule: // SamplesPerPixel must be 1 // PhotometricInterpretation must be MONOCHROME1 or MONOCHROME2 // BitsAllocated must be 16 // ScanningSequence and SequenceVariant are mandatory: const char *ss = 0; const char *sv = 0; if (source) { ss = source->GetAttributeValue(DC::ScanningSequence).GetCharData(); sv = source->GetAttributeValue(DC::SequenceVariant).GetCharData(); } if (ss == 0 || ss[0] == '\0') { // default to "research mode" ss = "RM"; } if (sv == 0 || sv[0] == '\0') { sv = "NONE"; } meta->SetAttributeValue(DC::ScanningSequence, ss); meta->SetAttributeValue(DC::SequenceVariant, sv); // SpacingBetweenSlices is optional, but everyone uses it meta->SetAttributeValue(DC::SpacingBetweenSlices, this->Spacing[2]); if (source) { // set this to the time dimension if (source->HasAttribute(DC::CardiacNumberOfImages)) { meta->SetAttributeValue(DC::CardiacNumberOfImages, this->Dimensions[3]); } // keep this if data was not reformatted if (this->SourceInstanceArray != 0 && source == this->SourceMetaData) { const char *ped = source->GetAttributeValue( DC::InPlanePhaseEncodingDirection).GetCharData(); if (ped != 0 && ped[0] != '\0') { meta->SetAttributeValue(DC::InPlanePhaseEncodingDirection, ped); } } } // temporal information if (this->Dimensions[3] > 1) { int n = meta->GetNumberOfInstances(); int nslices = (this->Dimensions[2] > 0 ? this->Dimensions[2] : 1); for (int i = 0; i < n; i++) { int t = (i % (n / nslices)) / (n / (nslices*this->Dimensions[3])); meta->SetAttributeValue(i, DC::TemporalPositionIdentifier, t + 1); } meta->SetAttributeValue( DC::NumberOfTemporalPositions, this->Dimensions[3]); meta->SetAttributeValue( DC::TemporalResolution, this->Spacing[3]); } // required items: use simple read/write validation DC::EnumType required[] = { DC::ScanOptions, DC::MRAcquisitionType, DC::EchoTime, DC::EchoTrainLength, DC::ItemDelimitationItem }; // optional and conditional: direct copy of values with no checks static const DC::EnumType optional[] = { DC::RepetitionTime, // 2C, not req'd if EP and not SK DC::InversionTime, // 2C, req'd if ScanningSequence is IR DC::TriggerTime, // 2C, req'd for cardiac gating DC::SequenceName, DC::AngioFlag, DC::NumberOfAverages, DC::ImagingFrequency, DC::ImagedNucleus, DC::EchoNumbers, // can be per-instance DC::MagneticFieldStrength, // DC::SpacingBetweenSlices, // see above DC::NumberOfPhaseEncodingSteps, DC::PercentSampling, DC::PercentPhaseFieldOfView, DC::PixelBandwidth, DC::NominalInterval, DC::BeatRejectionFlag, DC::LowRRValue, DC::HighRRValue, DC::IntervalsAcquired, DC::IntervalsRejected, DC::PVCRejection, DC::SkipBeats, DC::HeartRate, // DC::CardiacNumberOfImages, // see above DC::TriggerWindow, DC::ReconstructionDiameter, DC::ReceiveCoilName, DC::TransmitCoilName, DC::AcquisitionMatrix, // DC::InPlanePhaseEncodingDirection, // see above DC::FlipAngle, DC::SAR, DC::VariableFlipAngleFlag, DC::dBdt, // DC::TemporalPositionIdentifier, // per-instance // DC::NumberOfTemporalPositions, // DC::TemporalResolution, DC::AnatomicRegionSequence, DC::PrimaryAnatomicStructureSequence, DC::ItemDelimitationItem }; return (this->CopyRequiredAttributes(required, source) && this->CopyOptionalAttributes(optional, source)); } //---------------------------------------------------------------------------- bool vtkDICOMMRGenerator::GenerateMRInstance(vtkInformation *info) { this->SetPixelRestrictions( RepresentationSigned | RepresentationUnsigned, BitsStored12 | BitsStored16, 1); const char *SOPClass = "1.2.840.10008.5.1.4.1.1.4"; this->InitializeMetaData(info); vtkDICOMMetaData *source = this->SourceMetaData; if (!this->GenerateSOPCommonModule(source, SOPClass) || !this->GeneratePatientModule(source) || !this->GenerateClinicalTrialSubjectModule(source) || !this->GenerateGeneralStudyModule(source) || !this->GeneratePatientStudyModule(source) || !this->GenerateClinicalTrialStudyModule(source) || !this->GenerateGeneralSeriesModule(source) || !this->GenerateFrameOfReferenceModule(source) || !this->GenerateClinicalTrialSeriesModule(source) || !this->GenerateGeneralEquipmentModule(source) || !this->GenerateGeneralImageModule(source) || !this->GenerateImagePlaneModule(source) || !this->GenerateImagePixelModule(source) || !this->GenerateContrastBolusModule(source) || !this->GenerateDeviceModule(source) || !this->GenerateSpecimenModule(source) || !this->GenerateMRSeriesModule(source) || !this->GenerateMRImageModule(source) || !this->GenerateOverlayPlaneModule(source) || !this->GenerateVOILUTModule(source)) { return false; } return true; } //---------------------------------------------------------------------------- bool vtkDICOMMRGenerator::GenerateInstance(vtkInformation *info) { if (this->MultiFrame) { vtkErrorMacro("Enhanced Multi-Frame MR is not yet supported."); return false; } return this->GenerateMRInstance(info); } <commit_msg>Adapter also needed for one attribute in vtkDICOMMRGenerator.<commit_after>/*========================================================================= Program: DICOM for VTK Copyright (c) 2012-2014 David Gobbi All rights reserved. See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDICOMMRGenerator.h" #include "vtkDICOMMetaData.h" #include "vtkDICOMSequence.h" #include "vtkDICOMItem.h" #include "vtkDICOMTagPath.h" #include "vtkDICOMMetaDataAdapter.h" #include "vtkObjectFactory.h" #include "vtkDataSetAttributes.h" #include "vtkInformation.h" vtkStandardNewMacro(vtkDICOMMRGenerator); //---------------------------------------------------------------------------- vtkDICOMMRGenerator::vtkDICOMMRGenerator() { } //---------------------------------------------------------------------------- vtkDICOMMRGenerator::~vtkDICOMMRGenerator() { } //---------------------------------------------------------------------------- void vtkDICOMMRGenerator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------------- bool vtkDICOMMRGenerator::GenerateMRSeriesModule(vtkDICOMMetaData *source) { vtkDICOMMetaData *meta = this->MetaData; meta->SetAttributeValue(DC::Modality, "MR"); // optional and conditional: direct copy of values with no checks static const DC::EnumType optional[] = { DC::ReferencedPerformedProcedureStepSequence, // 1C DC::ItemDelimitationItem }; return this->CopyOptionalAttributes(optional, source); } //---------------------------------------------------------------------------- bool vtkDICOMMRGenerator::GenerateMRImageModule(vtkDICOMMetaData *source) { // ImageType is specialized from GeneralImageModule, // by adding a third value that is specific to MRI: // MPR, T2 MAP, PHASE MAP, PHASE SUBTRACT, PROJECTION IMAGE, // DIFFUSION MAP, VELOCITY MAP, MODULUS SUBTRACT, T1 MAP, // DENSITY MAP, IMAGE ADDITION, OTHER const char *it = 0; if (source) { it = source->GetAttributeValue(DC::ImageType).GetCharData(); } if (it == 0 || it[0] == '\0') { it = "DERIVED\\SECONDARY\\OTHER"; } vtkDICOMMetaData *meta = this->MetaData; meta->SetAttributeValue(DC::ImageType, it); // These specialized from ImagePixelModule: // SamplesPerPixel must be 1 // PhotometricInterpretation must be MONOCHROME1 or MONOCHROME2 // BitsAllocated must be 16 // ScanningSequence and SequenceVariant are mandatory: const char *ss = 0; const char *sv = 0; if (source) { ss = source->GetAttributeValue(DC::ScanningSequence).GetCharData(); sv = source->GetAttributeValue(DC::SequenceVariant).GetCharData(); } if (ss == 0 || ss[0] == '\0') { // default to "research mode" ss = "RM"; } if (sv == 0 || sv[0] == '\0') { sv = "NONE"; } meta->SetAttributeValue(DC::ScanningSequence, ss); meta->SetAttributeValue(DC::SequenceVariant, sv); // SpacingBetweenSlices is optional, but everyone uses it meta->SetAttributeValue(DC::SpacingBetweenSlices, this->Spacing[2]); if (source) { // set this to the time dimension if (source->HasAttribute(DC::CardiacNumberOfImages)) { meta->SetAttributeValue(DC::CardiacNumberOfImages, this->Dimensions[3]); } // keep this if data was not reformatted if (this->SourceInstanceArray != 0 && source == this->SourceMetaData) { vtkDICOMMetaDataAdapter sourceAdapter(source); const char *ped = sourceAdapter->GetAttributeValue( DC::InPlanePhaseEncodingDirection).GetCharData(); if (ped != 0 && ped[0] != '\0') { meta->SetAttributeValue(DC::InPlanePhaseEncodingDirection, ped); } } } // temporal information if (this->Dimensions[3] > 1) { int n = meta->GetNumberOfInstances(); int nslices = (this->Dimensions[2] > 0 ? this->Dimensions[2] : 1); for (int i = 0; i < n; i++) { int t = (i % (n / nslices)) / (n / (nslices*this->Dimensions[3])); meta->SetAttributeValue(i, DC::TemporalPositionIdentifier, t + 1); } meta->SetAttributeValue( DC::NumberOfTemporalPositions, this->Dimensions[3]); meta->SetAttributeValue( DC::TemporalResolution, this->Spacing[3]); } // required items: use simple read/write validation DC::EnumType required[] = { DC::ScanOptions, DC::MRAcquisitionType, DC::EchoTime, DC::EchoTrainLength, DC::ItemDelimitationItem }; // optional and conditional: direct copy of values with no checks static const DC::EnumType optional[] = { DC::RepetitionTime, // 2C, not req'd if EP and not SK DC::InversionTime, // 2C, req'd if ScanningSequence is IR DC::TriggerTime, // 2C, req'd for cardiac gating DC::SequenceName, DC::AngioFlag, DC::NumberOfAverages, DC::ImagingFrequency, DC::ImagedNucleus, DC::EchoNumbers, // can be per-instance DC::MagneticFieldStrength, // DC::SpacingBetweenSlices, // see above DC::NumberOfPhaseEncodingSteps, DC::PercentSampling, DC::PercentPhaseFieldOfView, DC::PixelBandwidth, DC::NominalInterval, DC::BeatRejectionFlag, DC::LowRRValue, DC::HighRRValue, DC::IntervalsAcquired, DC::IntervalsRejected, DC::PVCRejection, DC::SkipBeats, DC::HeartRate, // DC::CardiacNumberOfImages, // see above DC::TriggerWindow, DC::ReconstructionDiameter, DC::ReceiveCoilName, DC::TransmitCoilName, DC::AcquisitionMatrix, // DC::InPlanePhaseEncodingDirection, // see above DC::FlipAngle, DC::SAR, DC::VariableFlipAngleFlag, DC::dBdt, // DC::TemporalPositionIdentifier, // per-instance // DC::NumberOfTemporalPositions, // DC::TemporalResolution, DC::AnatomicRegionSequence, DC::PrimaryAnatomicStructureSequence, DC::ItemDelimitationItem }; return (this->CopyRequiredAttributes(required, source) && this->CopyOptionalAttributes(optional, source)); } //---------------------------------------------------------------------------- bool vtkDICOMMRGenerator::GenerateMRInstance(vtkInformation *info) { this->SetPixelRestrictions( RepresentationSigned | RepresentationUnsigned, BitsStored12 | BitsStored16, 1); const char *SOPClass = "1.2.840.10008.5.1.4.1.1.4"; this->InitializeMetaData(info); vtkDICOMMetaData *source = this->SourceMetaData; if (!this->GenerateSOPCommonModule(source, SOPClass) || !this->GeneratePatientModule(source) || !this->GenerateClinicalTrialSubjectModule(source) || !this->GenerateGeneralStudyModule(source) || !this->GeneratePatientStudyModule(source) || !this->GenerateClinicalTrialStudyModule(source) || !this->GenerateGeneralSeriesModule(source) || !this->GenerateFrameOfReferenceModule(source) || !this->GenerateClinicalTrialSeriesModule(source) || !this->GenerateGeneralEquipmentModule(source) || !this->GenerateGeneralImageModule(source) || !this->GenerateImagePlaneModule(source) || !this->GenerateImagePixelModule(source) || !this->GenerateContrastBolusModule(source) || !this->GenerateDeviceModule(source) || !this->GenerateSpecimenModule(source) || !this->GenerateMRSeriesModule(source) || !this->GenerateMRImageModule(source) || !this->GenerateOverlayPlaneModule(source) || !this->GenerateVOILUTModule(source)) { return false; } return true; } //---------------------------------------------------------------------------- bool vtkDICOMMRGenerator::GenerateInstance(vtkInformation *info) { if (this->MultiFrame) { vtkErrorMacro("Enhanced Multi-Frame MR is not yet supported."); return false; } return this->GenerateMRInstance(info); } <|endoftext|>
<commit_before>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_LV2_ATOM_HPP_INCLUDED #define METHCLA_LV2_ATOM_HPP_INCLUDED #include "lv2/lv2plug.in/ns/ext/atom/atom.h" #include "lv2/lv2plug.in/ns/ext/atom/util.h" namespace LV2 { // class ObjectIterator // : public boost::iterator_facade< // ObjectIterator // , Property const // , boost::input_iterator_tag // > // { // public: // ObjectIterator() // : m_node(0) {} // explicit ObjectIterator(node_base* p) // : m_node(p) {} // private: // friend class boost::iterator_core_access; // void increment() { m_node = m_node->next(); } // bool equal(const_node_iterator const& other) const // { // return this->m_node == other.m_node; // } // node_base const& dereference() const { return *m_node; } // node_base const* m_node; // }; class Property { public: Property(const LV2_Atom_Property_Body* prop) : m_impl(prop) { } private: const LV2_Atom_Property* m_impl; }; class Object { public: Object(const LV2_Atom_Object* obj) : m_impl(obj) { } class const_iterator { public: explicit const_iterator(const LV2_Atom_Object_Body* obj) : m_iter(it) { } operator bool () const { return !lv2_atom_} }; const_iterator begin() const { return ObjectIterator(m_impl); } private: const LV2_Atom_Object_Body* m_impl; }; }; #endif // METHCLA_LV2_ATOM_HPP_INCLUDED<commit_msg>Add C++ LV2 atom forge wrapper<commit_after>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_LV2_ATOM_HPP_INCLUDED #define METHCLA_LV2_ATOM_HPP_INCLUDED #include <cassert> #include <string> #include "lv2/lv2plug.in/ns/ext/atom/atom.h" #include "lv2/lv2plug.in/ns/ext/atom/forge.h" #include "lv2/lv2plug.in/ns/ext/atom/util.h" namespace LV2 { class Property { public: Property(LV2_URID key, LV2_URID context=0) : m_key(key) , m_context(context) { } LV2_URID key() const { return m_key; } LV2_URID context() const { return m_context; } private: LV2_URID m_key, m_context; }; class Forge : public LV2_Atom_Forge { public: Forge(const LV2_Atom_Forge& forge) : LV2_Atom_Forge(forge) { } Forge(LV2_URID_Map* uridMap) { lv2_atom_forge_init(this, uridMap); } void set_buffer(uint8_t* data, uint32_t size) { lv2_atom_forge_set_buffer(this, data, size); } void atom(uint32_t size, uint32_t type) { lv2_atom_forge_atom(this, size, type); } void write(const void* data, uint32_t size) { lv2_atom_forge_write(this, const_cast<void*>(data), size); } Forge& operator<<(int32_t x) { lv2_atom_forge_int(this, x); return *this; } Forge& operator<<(int64_t x) { lv2_atom_forge_long(this, x); return *this; } Forge& operator<<(float x) { lv2_atom_forge_float(this, x); return *this; } Forge& operator<<(double x) { lv2_atom_forge_double(this, x); return *this; } Forge& operator<<(bool x) { lv2_atom_forge_bool(this, x); return *this; } Forge& operator<<(LV2_URID x) { lv2_atom_forge_urid(this, x); return *this; } Forge& operator<<(const char* x) { lv2_atom_forge_string(this, x, strlen(x)); return *this; } Forge& operator<<(const std::string& x) { lv2_atom_forge_string(this, x.c_str(), x.size()); return *this; } Forge& operator<<(const class Property& x) { lv2_atom_forge_property_head(this, x.key(), x.context()); return *this; } }; class Frame : public LV2_Atom_Forge_Frame { public: Frame(Forge& forge) : m_forge(forge) { } virtual ~Frame() { lv2_atom_forge_pop(&m_forge, this); } operator Forge& () { return m_forge; } protected: Forge& m_forge; }; class TupleFrame : public Frame { public: TupleFrame(Forge& forge) : Frame(forge) { lv2_atom_forge_tuple(&m_forge, this); } }; class ObjectFrame : public Frame { public: ObjectFrame(Forge& forge, LV2_URID id, LV2_URID otype) : Frame(forge) { lv2_atom_forge_blank(&m_forge, this, id, otype); } }; // // class ObjectIterator // : public boost::iterator_facade< // ObjectIterator // , Property const // , boost::input_iterator_tag // > // { // public: // ObjectIterator() // : m_node(0) {} // explicit ObjectIterator(node_base* p) // : m_node(p) {} // private: // friend class boost::iterator_core_access; // void increment() { m_node = m_node->next(); } // bool equal(const_node_iterator const& other) const // { // return this->m_node == other.m_node; // } // node_base const& dereference() const { return *m_node; } // node_base const* m_node; // }; //class Property //{ //public: //Property(const LV2_Atom_Property_Body* prop) //: m_impl(prop) //{ } //private: //const LV2_Atom_Property* m_impl; //}; //class Object //{ //public: //Object(const LV2_Atom_Object* obj) //: m_impl(obj) //{ } //class const_iterator //{ //public: //explicit const_iterator(const LV2_Atom_Object_Body* obj) //: m_iter(it) //{ } //operator bool () const { return !lv2_atom_} //}; //const_iterator begin() const { return ObjectIterator(m_impl); } //private: //const LV2_Atom_Object_Body* m_impl; //}; }; #endif // METHCLA_LV2_ATOM_HPP_INCLUDED <|endoftext|>
<commit_before>#include <iostream> #include <array> #include <chrono> #include <vector> #include <memory> #include <random> #include "linalg/util.h" #include "samplers/ld_sampler.h" #include "samplers/adaptive_sampler.h" AdaptiveSampler::AdaptiveSampler(int x_start, int x_end, int y_start, int y_end, int min_sp, int max_sp) : Sampler{x_start, x_end, y_start, y_end}, min_spp(round_up_pow2(min_sp)), max_spp(round_up_pow2(max_sp)), supersample_px(false), rng(std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()).count()) { if (min_sp % 2 != 0){ std::cout << "Warning: AdaptiveSampler requires power of 2 samples per pixel." << " Rounded min_spp up to " << min_spp << std::endl; } if (max_sp % 2 != 0){ std::cout << "Warning: AdaptiveSampler requires power of 2 samples per pixel." << " Rounded max_spp up to " << max_spp << std::endl; } } void AdaptiveSampler::get_samples(std::vector<Sample> &samples){ samples.clear(); if (!has_samples()){ return; } int spp = supersample_px ? max_spp : min_spp; samples.resize(spp); std::vector<std::array<float, 2>> pos(spp), lens(spp); LDSampler::sample2d(pos, distrib(rng), distrib(rng)); LDSampler::sample2d(lens, distrib(rng), distrib(rng)); std::shuffle(pos.begin(), pos.end(), rng); std::shuffle(lens.begin(), lens.end(), rng); std::transform(pos.begin(), pos.end(), lens.begin(), samples.begin(), [](const auto &p, const auto &l){ return Sample{p, l}; }); for (auto &s : samples){ s.img[0] += x; s.img[1] += y; } } int AdaptiveSampler::get_max_spp() const { return max_spp; } bool AdaptiveSampler::report_results(const std::vector<Sample> &samples, const std::vector<RayDifferential> &rays, const std::vector<Colorf> &colors) { if (supersample_px || !needs_supersampling(samples, rays, colors)){ supersample_px = false; ++x; if (x == x_end){ x = x_start; ++y; } return true; } //Throw away these samples, we need to super sample this pixel supersample_px = true; return false; } std::vector<std::unique_ptr<Sampler>> AdaptiveSampler::get_subsamplers(int w, int h) const { int x_dim = x_end - x_start; int y_dim = y_end - y_start; std::vector<std::unique_ptr<Sampler>> samplers; if (w > x_dim || h > y_dim){ std::cout << "WARNING: sampler cannot be partitioned to blocks bigger than itself\n"; samplers.emplace_back(std::make_unique<AdaptiveSampler>(*this)); return samplers; } //Compute the number of tiles to use in each dimension, we halve the number along x //and double the number along y until we hit an odd number of x tiles (cols) or //until the tiles divide the space about evenly int n_cols = x_dim / w; int n_rows = y_dim / h; x_dim /= n_cols; y_dim /= n_rows; //Check & warn if the space hasn't been split up evenly if (x_dim * n_cols != width() || y_dim * n_rows != height()){ std::cout << "WARNING: sampler could not be partitioned equally into" << " samplers of the desired dimensions " << w << " x " << h << std::endl; } for (int j = 0; j < n_rows; ++j){ for (int i = 0; i < n_cols; ++i){ samplers.emplace_back(std::make_unique<AdaptiveSampler>(i * x_dim + x_start, (i + 1) * x_dim + x_start, j * y_dim + y_start, (j + 1) * y_dim + y_start, min_spp, max_spp)); } } return samplers; } bool AdaptiveSampler::needs_supersampling(const std::vector<Sample>&, const std::vector<RayDifferential>&, const std::vector<Colorf> &colors) { const static float max_contrast = 0.5f; float lum_avg = 0; for (const auto &c : colors){ lum_avg += c.luminance(); } lum_avg /= colors.size(); for (const auto &c : colors){ if (std::abs(c.luminance() - lum_avg) / lum_avg > max_contrast){ return true; } } return false; } <commit_msg>Check that we aren't trying to supersample the last pixel<commit_after>#include <iostream> #include <array> #include <chrono> #include <vector> #include <memory> #include <random> #include "linalg/util.h" #include "samplers/ld_sampler.h" #include "samplers/adaptive_sampler.h" AdaptiveSampler::AdaptiveSampler(int x_start, int x_end, int y_start, int y_end, int min_sp, int max_sp) : Sampler{x_start, x_end, y_start, y_end}, min_spp(round_up_pow2(min_sp)), max_spp(round_up_pow2(max_sp)), supersample_px(false), rng(std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()).count()) { if (min_sp % 2 != 0){ std::cout << "Warning: AdaptiveSampler requires power of 2 samples per pixel." << " Rounded min_spp up to " << min_spp << std::endl; } if (max_sp % 2 != 0){ std::cout << "Warning: AdaptiveSampler requires power of 2 samples per pixel." << " Rounded max_spp up to " << max_spp << std::endl; } } void AdaptiveSampler::get_samples(std::vector<Sample> &samples){ samples.clear(); if (!supersample_px && !has_samples()){ return; } int spp = supersample_px ? max_spp : min_spp; samples.resize(spp); std::vector<std::array<float, 2>> pos(spp), lens(spp); LDSampler::sample2d(pos, distrib(rng), distrib(rng)); LDSampler::sample2d(lens, distrib(rng), distrib(rng)); std::shuffle(pos.begin(), pos.end(), rng); std::shuffle(lens.begin(), lens.end(), rng); std::transform(pos.begin(), pos.end(), lens.begin(), samples.begin(), [](const auto &p, const auto &l){ return Sample{p, l}; }); for (auto &s : samples){ s.img[0] += x; s.img[1] += y; } } int AdaptiveSampler::get_max_spp() const { return max_spp; } bool AdaptiveSampler::report_results(const std::vector<Sample> &samples, const std::vector<RayDifferential> &rays, const std::vector<Colorf> &colors) { if (supersample_px || !needs_supersampling(samples, rays, colors)){ supersample_px = false; ++x; if (x == x_end){ x = x_start; ++y; } return true; } //Throw away these samples, we need to super sample this pixel supersample_px = true; return false; } std::vector<std::unique_ptr<Sampler>> AdaptiveSampler::get_subsamplers(int w, int h) const { int x_dim = x_end - x_start; int y_dim = y_end - y_start; std::vector<std::unique_ptr<Sampler>> samplers; if (w > x_dim || h > y_dim){ std::cout << "WARNING: sampler cannot be partitioned to blocks bigger than itself\n"; samplers.emplace_back(std::make_unique<AdaptiveSampler>(*this)); return samplers; } //Compute the number of tiles to use in each dimension, we halve the number along x //and double the number along y until we hit an odd number of x tiles (cols) or //until the tiles divide the space about evenly int n_cols = x_dim / w; int n_rows = y_dim / h; x_dim /= n_cols; y_dim /= n_rows; //Check & warn if the space hasn't been split up evenly if (x_dim * n_cols != width() || y_dim * n_rows != height()){ std::cout << "WARNING: sampler could not be partitioned equally into" << " samplers of the desired dimensions " << w << " x " << h << std::endl; } for (int j = 0; j < n_rows; ++j){ for (int i = 0; i < n_cols; ++i){ samplers.emplace_back(std::make_unique<AdaptiveSampler>(i * x_dim + x_start, (i + 1) * x_dim + x_start, j * y_dim + y_start, (j + 1) * y_dim + y_start, min_spp, max_spp)); } } return samplers; } bool AdaptiveSampler::needs_supersampling(const std::vector<Sample>&, const std::vector<RayDifferential>&, const std::vector<Colorf> &colors) { const static float max_contrast = 0.5f; float lum_avg = 0; for (const auto &c : colors){ lum_avg += c.luminance(); } lum_avg /= colors.size(); for (const auto &c : colors){ if (std::abs(c.luminance() - lum_avg) / lum_avg > max_contrast){ return true; } } return false; } <|endoftext|>
<commit_before>#include "FileToH.h" /* Library FileToH - Write a bin file to a H header Copyright (C) 2013 Eduardo Moura Sales Martins This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA email: [email protected] AV: Walmor M. de Souza 392 Casa Gravatai RS Brazil 94065100 */ edk::FileToH::FileToH(){} bool edk::FileToH::writeToFile(edk::char8* fileName,edk::uint32 lineSize){ if(!lineSize) lineSize=10u; //test the vector and the size if(fileName){ bool ret=false; //open the file edk::File file; edk::char8* nameVec = edk::FileToH::readFileName(fileName); if(nameVec){ edk::char8* nameH = edk::String::strCat(nameVec,(edk::char8*)".h"); if(nameH){ if(file.openBinFile(fileName)){ edk::uint32 size = file.getFileSize(); if(size){ //create the vector edk::char8* fileVec = new edk::char8[size]; if(fileVec){ //read the file file.readBin(fileVec,size); //close the file file.closeFile(); if(file.createAndOpenTextFile(nameH)){ edk::char8* className = nameVec; { edk::char8* temp = className; while(*temp){ if((*temp == '.' || *temp == '/' )&& temp[1u]){ className = ++temp; } else temp++; } } edk::char8* fileNameFiltered = fileName; { edk::uint32 nameSize = edk::String::strSize(fileNameFiltered); for(edk::uint32 i=nameSize;i>0u;i--){ if(i) if(fileName[i-1u] == '/'){ fileNameFiltered = &fileName[i]; break; } } } //write the header file.writeText("#ifndef "); file.writeText(className); file.writeText("_H"); file.writeText("\n#define "); file.writeText(className); file.writeText("_H"); file.writeText("\n"); //write the size file.writeText("\nstatic unsigned int "); file.writeText(className); file.writeText("Size = "); file.writeText(size); file.writeText("u;"); //write fileName file.writeText("\nstatic char "); file.writeText(className); file.writeText("Name"); file.writeText("["); file.writeText((edk::uint32)(edk::String::strSize(fileNameFiltered) + 1u)); file.writeText("]"); file.writeText(" = \""); file.writeText(fileNameFiltered); file.writeText("\";"); //write the char; file.writeText("\nstatic unsigned char "); file.writeText(className); file.writeText("["); file.writeText(size); file.writeText("] = {\n"); //write the bytes file.writeText((edk::uint8)fileVec[0]); edk::uint8 count = 1u; bool enter=false; for(edk::uint32 i=1u;i<size;i++){ file.writeText(","); file.writeText((edk::uint8)fileVec[i]); if(count>lineSize){ file.writeText(" \\\n"); count=0u; enter=true; } else{ enter=false; } count++; } if(!enter)file.writeText("\n"); file.writeText("};"); file.writeText("\n"); //write the endIf file.writeText("\n#endif"); //flush the file file.flush(); //return true ret = true; } delete[] fileVec; } } file.closeFile(); } delete[] nameH; } delete[] nameVec; } return ret; } return false; } bool edk::FileToH::writeToFile(const edk::char8* fileName,edk::uint32 lineSize){ return edk::FileToH::writeToFile((edk::char8*) fileName,lineSize); } bool edk::FileToH::writeToEDKFile(edk::char8* fileName,edk::uint32 lineSize){ if(!lineSize) lineSize=10u; //test the vector and the size if(fileName){ bool ret=false; //open the file edk::File file; edk::char8* nameVec = edk::FileToH::readFileName(fileName); if(nameVec){ edk::char8* nameH = edk::String::strCat(nameVec,(edk::char8*)".h"); if(nameH){ if(file.openBinFile(fileName)){ edk::uint32 size = file.getFileSize(); if(size){ //create the vector edk::char8* fileVec = new edk::char8[size]; if(fileVec){ //read the file file.readBin(fileVec,size); //close the file file.closeFile(); if(file.createAndOpenTextFile(nameH)){ edk::char8* className = nameVec; { edk::char8* temp = className; while(*temp){ if((*temp == '.' || *temp == '/' )&& temp[1u]){ className = ++temp; } else temp++; } } edk::char8* fileNameFiltered = fileName; { edk::uint32 nameSize = edk::String::strSize(fileNameFiltered); for(edk::uint32 i=nameSize;i>0u;i--){ if(i) if(fileName[i-1u] == '/'){ fileNameFiltered = &fileName[i]; break; } } } //write the header file.writeText("#ifndef "); file.writeText(className); file.writeText("_H"); file.writeText("\n#define "); file.writeText(className); file.writeText("_H"); file.writeText("\n"); file.writeText("\n"); //include edk::types file.writeText("#include \"edk/TypeVars.h\"\n"); //write the size file.writeText("\nstatic edk::uint32 "); file.writeText(className); file.writeText("Size = "); file.writeText(size); file.writeText("u;"); //write fileName file.writeText("\nstatic edk::char8 "); file.writeText(className); file.writeText("Name"); file.writeText("["); file.writeText((edk::uint32)(edk::String::strSize(fileNameFiltered) + 1u)); file.writeText("]"); file.writeText(" = \""); file.writeText(fileNameFiltered); file.writeText("\";"); //write the char; file.writeText("\nstatic edk::uchar8 "); file.writeText(className); file.writeText("["); file.writeText(size); file.writeText("] = {\n"); //write the bytes file.writeText((edk::uint8)fileVec[0]); edk::uint8 count = 1u; bool enter=false; for(edk::uint32 i=1u;i<size;i++){ file.writeText(","); file.writeText((edk::uint8)fileVec[i]); if(count>lineSize){ file.writeText(" \\\n"); count=0u; enter=true; } else{ enter=false; } count++; } if(!enter)file.writeText("\n"); file.writeText("};"); file.writeText("\n"); //write the endIf file.writeText("\n#endif"); //flush the file file.flush(); //return true ret = true; } delete[] fileVec; } } file.closeFile(); } delete[] nameH; } delete[] nameVec; } return ret; } return false; } bool edk::FileToH::writeToEDKFile(const edk::char8* fileName,edk::uint32 lineSize){ return edk::FileToH::writeToEDKFile((edk::char8*) fileName,lineSize); } //read the name without the extension edk::char8* edk::FileToH::readFileName(edk::char8* fileName){ if(fileName){ edk::uint32 size = edk::String::strSize(fileName); if(size){ size--; //find the pointer while(size){ switch(fileName[size]){ case '.': //found it if(size){ edk::char8* ret = new edk::char8[size+1u]; if(ret){ ret[size] = '\0'; memcpy(ret,fileName,size); return ret; } } break; case '\0': break; } size--; } } } return NULL; } <commit_msg>edk/FileToH: - Change the fileToH to write the values in hexadecimal.<commit_after>#include "FileToH.h" /* Library FileToH - Write a bin file to a H header Copyright (C) 2013 Eduardo Moura Sales Martins This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA email: [email protected] AV: Walmor M. de Souza 392 Casa Gravatai RS Brazil 94065100 */ edk::FileToH::FileToH(){} bool edk::FileToH::writeToFile(edk::char8* fileName,edk::uint32 lineSize){ if(!lineSize) lineSize=10u; //test the vector and the size if(fileName){ bool ret=false; //open the file edk::File file; edk::char8* nameVec = edk::FileToH::readFileName(fileName); if(nameVec){ edk::char8* nameH = edk::String::strCat(nameVec,(edk::char8*)".h"); if(nameH){ if(file.openBinFile(fileName)){ edk::uint32 size = file.getFileSize(); if(size){ //create the vector edk::char8* fileVec = new edk::char8[size]; edk::char8 hex[5u]; hex[0u] = '0'; hex[1u] = 'x'; hex[4u] = '\0'; if(fileVec){ //read the file file.readBin(fileVec,size); //close the file file.closeFile(); if(file.createAndOpenTextFile(nameH)){ edk::char8* className = nameVec; { edk::char8* temp = className; while(*temp){ if((*temp == '.' || *temp == '/' )&& temp[1u]){ className = ++temp; } else temp++; } } edk::char8* fileNameFiltered = fileName; { edk::uint32 nameSize = edk::String::strSize(fileNameFiltered); for(edk::uint32 i=nameSize;i>0u;i--){ if(i) if(fileName[i-1u] == '/'){ fileNameFiltered = &fileName[i]; break; } } } //write the header file.writeText("#ifndef "); file.writeText(className); file.writeText("_H"); file.writeText("\n#define "); file.writeText(className); file.writeText("_H"); file.writeText("\n"); //write the size file.writeText("\nstatic unsigned int "); file.writeText(className); file.writeText("Size = "); file.writeText(size); file.writeText("u;"); //write fileName file.writeText("\nstatic char "); file.writeText(className); file.writeText("Name"); file.writeText("["); file.writeText((edk::uint32)(edk::String::strSize(fileNameFiltered) + 1u)); file.writeText("]"); file.writeText(" = \""); file.writeText(fileNameFiltered); file.writeText("\";"); //write the char; file.writeText("\nstatic unsigned char "); file.writeText(className); file.writeText("["); file.writeText(size); file.writeText("] = {\n"); //write the bytes sprintf(hex,"0x%02x",(edk::uint8)fileVec[0u]); file.writeText(hex); //file.writeText((edk::uint8)fileVec[0]); edk::uint8 count = 1u; bool enter=false; for(edk::uint32 i=1u;i<size;i++){ file.writeText(","); sprintf(hex,"0x%02x",(edk::uint8)fileVec[i]); file.writeText(hex); //file.writeText((edk::uint8)fileVec[i]); if(count>lineSize){ file.writeText(" \\\n"); count=0u; enter=true; } else{ enter=false; } count++; } if(!enter)file.writeText("\n"); file.writeText("};"); file.writeText("\n"); //write the endIf file.writeText("\n#endif"); //flush the file file.flush(); //return true ret = true; } delete[] fileVec; } } file.closeFile(); } delete[] nameH; } delete[] nameVec; } return ret; } return false; } bool edk::FileToH::writeToFile(const edk::char8* fileName,edk::uint32 lineSize){ return edk::FileToH::writeToFile((edk::char8*) fileName,lineSize); } bool edk::FileToH::writeToEDKFile(edk::char8* fileName,edk::uint32 lineSize){ if(!lineSize) lineSize=10u; //test the vector and the size if(fileName){ bool ret=false; //open the file edk::File file; edk::char8* nameVec = edk::FileToH::readFileName(fileName); if(nameVec){ edk::char8* nameH = edk::String::strCat(nameVec,(edk::char8*)".h"); if(nameH){ if(file.openBinFile(fileName)){ edk::uint32 size = file.getFileSize(); if(size){ //create the vector edk::char8* fileVec = new edk::char8[size]; edk::char8 hex[5u]; hex[0u] = '0'; hex[1u] = 'x'; hex[4u] = '\0'; if(fileVec){ //read the file file.readBin(fileVec,size); //close the file file.closeFile(); if(file.createAndOpenTextFile(nameH)){ edk::char8* className = nameVec; { edk::char8* temp = className; while(*temp){ if((*temp == '.' || *temp == '/' )&& temp[1u]){ className = ++temp; } else temp++; } } edk::char8* fileNameFiltered = fileName; { edk::uint32 nameSize = edk::String::strSize(fileNameFiltered); for(edk::uint32 i=nameSize;i>0u;i--){ if(i) if(fileName[i-1u] == '/'){ fileNameFiltered = &fileName[i]; break; } } } //write the header file.writeText("#ifndef "); file.writeText(className); file.writeText("_H"); file.writeText("\n#define "); file.writeText(className); file.writeText("_H"); file.writeText("\n"); file.writeText("\n"); //include edk::types file.writeText("#include \"edk/TypeVars.h\"\n"); //write the size file.writeText("\nstatic edk::uint32 "); file.writeText(className); file.writeText("Size = "); file.writeText(size); file.writeText("u;"); //write fileName file.writeText("\nstatic edk::char8 "); file.writeText(className); file.writeText("Name"); file.writeText("["); file.writeText((edk::uint32)(edk::String::strSize(fileNameFiltered) + 1u)); file.writeText("]"); file.writeText(" = \""); file.writeText(fileNameFiltered); file.writeText("\";"); //write the char; file.writeText("\nstatic edk::uchar8 "); file.writeText(className); file.writeText("["); file.writeText(size); file.writeText("] = {\n"); //write the bytes sprintf(hex,"0x%02x",(edk::uint8)fileVec[0u]); file.writeText(hex); //file.writeText((edk::uint8)fileVec[0]); edk::uint8 count = 1u; bool enter=false; for(edk::uint32 i=1u;i<size;i++){ file.writeText(","); sprintf(hex,"0x%02x",(edk::uint8)fileVec[i]); file.writeText(hex); //file.writeText((edk::uint8)fileVec[i]); if(count>lineSize){ file.writeText(" \\\n"); count=0u; enter=true; } else{ enter=false; } count++; } if(!enter)file.writeText("\n"); file.writeText("};"); file.writeText("\n"); //write the endIf file.writeText("\n#endif"); //flush the file file.flush(); //return true ret = true; } delete[] fileVec; } } file.closeFile(); } delete[] nameH; } delete[] nameVec; } return ret; } return false; } bool edk::FileToH::writeToEDKFile(const edk::char8* fileName,edk::uint32 lineSize){ return edk::FileToH::writeToEDKFile((edk::char8*) fileName,lineSize); } //read the name without the extension edk::char8* edk::FileToH::readFileName(edk::char8* fileName){ if(fileName){ edk::uint32 size = edk::String::strSize(fileName); if(size){ size--; //find the pointer while(size){ switch(fileName[size]){ case '.': //found it if(size){ edk::char8* ret = new edk::char8[size+1u]; if(ret){ ret[size] = '\0'; memcpy(ret,fileName,size); return ret; } } break; case '\0': break; } size--; } } } return NULL; } <|endoftext|>
<commit_before>#include "Jitter_CodeGen_Arm.h" using namespace Jitter; void CCodeGen_Arm::LoadMemoryFpSingleInRegister(CTempRegisterContext& tempRegContext, CArmAssembler::SINGLE_REGISTER reg, CSymbol* symbol) { switch(symbol->m_type) { case SYM_FP_REL_SINGLE: LoadRelativeFpSingleInRegister(tempRegContext, reg, symbol); break; case SYM_FP_TMP_SINGLE: LoadTemporaryFpSingleInRegister(tempRegContext, reg, symbol); break; default: assert(false); break; } } void CCodeGen_Arm::StoreRegisterInMemoryFpSingle(CTempRegisterContext& tempRegContext, CSymbol* symbol, CArmAssembler::SINGLE_REGISTER reg) { switch(symbol->m_type) { case SYM_FP_REL_SINGLE: StoreRelativeFpSingleInRegister(tempRegContext, symbol, reg); break; case SYM_FP_TMP_SINGLE: StoreTemporaryFpSingleInRegister(tempRegContext, symbol, reg); break; default: assert(false); break; } } void CCodeGen_Arm::LoadRelativeFpSingleInRegister(CTempRegisterContext& tempRegContext, CArmAssembler::SINGLE_REGISTER reg, CSymbol* symbol) { assert(symbol->m_type == SYM_FP_REL_SINGLE); if((symbol->m_valueLow / 4) < 0x100) { m_assembler.Vldr(reg, g_baseRegister, CArmAssembler::MakeImmediateLdrAddress(symbol->m_valueLow)); } else { auto offsetRegister = tempRegContext.Allocate(); LoadConstantInRegister(offsetRegister, symbol->m_valueLow); m_assembler.Add(offsetRegister, offsetRegister, g_baseRegister); m_assembler.Vldr(reg, offsetRegister, CArmAssembler::MakeImmediateLdrAddress(0)); tempRegContext.Release(offsetRegister); } } void CCodeGen_Arm::StoreRelativeFpSingleInRegister(CTempRegisterContext& tempRegContext, CSymbol* symbol, CArmAssembler::SINGLE_REGISTER reg) { assert(symbol->m_type == SYM_FP_REL_SINGLE); if((symbol->m_valueLow / 4) < 0x100) { m_assembler.Vstr(reg, g_baseRegister, CArmAssembler::MakeImmediateLdrAddress(symbol->m_valueLow)); } else { auto offsetRegister = tempRegContext.Allocate(); LoadConstantInRegister(offsetRegister, symbol->m_valueLow); m_assembler.Add(offsetRegister, offsetRegister, g_baseRegister); m_assembler.Vstr(reg, offsetRegister, CArmAssembler::MakeImmediateLdrAddress(0)); tempRegContext.Release(offsetRegister); } } void CCodeGen_Arm::LoadTemporaryFpSingleInRegister(CTempRegisterContext& tempRegContext, CArmAssembler::SINGLE_REGISTER reg, CSymbol* symbol) { assert(symbol->m_type == SYM_FP_TMP_SINGLE); auto offset = symbol->m_stackLocation + m_stackLevel; if((offset / 4) < 0x100) { m_assembler.Vldr(reg, CArmAssembler::rSP, CArmAssembler::MakeImmediateLdrAddress(symbol->m_stackLocation + m_stackLevel)); } else { auto offsetRegister = tempRegContext.Allocate(); LoadConstantInRegister(offsetRegister, offset); m_assembler.Add(offsetRegister, offsetRegister, CArmAssembler::rSP); m_assembler.Vldr(reg, offsetRegister, CArmAssembler::MakeImmediateLdrAddress(0)); tempRegContext.Release(offsetRegister); } } void CCodeGen_Arm::StoreTemporaryFpSingleInRegister(CTempRegisterContext& tempRegContext, CSymbol* symbol, CArmAssembler::SINGLE_REGISTER reg) { assert(symbol->m_type == SYM_FP_TMP_SINGLE); auto offset = symbol->m_stackLocation + m_stackLevel; if((offset / 4) < 0x100) { m_assembler.Vstr(reg, CArmAssembler::rSP, CArmAssembler::MakeImmediateLdrAddress(symbol->m_stackLocation + m_stackLevel)); } else { auto offsetRegister = tempRegContext.Allocate(); LoadConstantInRegister(offsetRegister, offset); m_assembler.Add(offsetRegister, offsetRegister,CArmAssembler::rSP); m_assembler.Vstr(reg, offsetRegister, CArmAssembler::MakeImmediateLdrAddress(0)); tempRegContext.Release(offsetRegister); } } template <typename FPUOP> void CCodeGen_Arm::Emit_Fpu_MemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); CTempRegisterContext tempRegisterContext; LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); ((m_assembler).*(FPUOP::OpReg()))(CArmAssembler::s1, CArmAssembler::s0); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, CArmAssembler::s1); } template <typename FPUOP> void CCodeGen_Arm::Emit_Fpu_MemMemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); auto src2 = statement.src2->GetSymbol().get(); CTempRegisterContext tempRegisterContext; LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s1, src2); ((m_assembler).*(FPUOP::OpReg()))(CArmAssembler::s2, CArmAssembler::s0, CArmAssembler::s1); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, CArmAssembler::s2); } template <typename FPUMDOP> void CCodeGen_Arm::Emit_FpuMd_MemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); CTempRegisterContext tempRegisterContext; LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); ((m_assembler).*(FPUMDOP::OpReg()))(CArmAssembler::q1, CArmAssembler::q0); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, CArmAssembler::s4); } template <typename FPUMDOP> void CCodeGen_Arm::Emit_FpuMd_MemMemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); auto src2 = statement.src2->GetSymbol().get(); CTempRegisterContext tempRegisterContext; LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s4, src2); ((m_assembler).*(FPUMDOP::OpReg()))(CArmAssembler::q2, CArmAssembler::q0, CArmAssembler::q1); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, CArmAssembler::s8); } void CCodeGen_Arm::Emit_Fp_Cmp_AnyMemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); auto src2 = statement.src2->GetSymbol().get(); CTempRegisterContext tempRegisterContext; auto tmpReg = tempRegisterContext.Allocate(); auto dstReg = PrepareSymbolRegisterDef(dst, tmpReg); LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s1, src2); m_assembler.Vcmp_F32(CArmAssembler::s0, CArmAssembler::s1); m_assembler.Vmrs(CArmAssembler::rPC); //Move to general purpose status register //Make sure we clear the result if unordered m_assembler.MovCc(CArmAssembler::CONDITION_VS, dstReg, CArmAssembler::MakeImmediateAluOperand(0, 0)); switch(statement.jmpCondition) { case Jitter::CONDITION_AB: m_assembler.MovCc(CArmAssembler::CONDITION_GT, dstReg, CArmAssembler::MakeImmediateAluOperand(1, 0)); m_assembler.MovCc(CArmAssembler::CONDITION_LE, dstReg, CArmAssembler::MakeImmediateAluOperand(0, 0)); break; case Jitter::CONDITION_BE: m_assembler.MovCc(CArmAssembler::CONDITION_LS, dstReg, CArmAssembler::MakeImmediateAluOperand(1, 0)); m_assembler.MovCc(CArmAssembler::CONDITION_GT, dstReg, CArmAssembler::MakeImmediateAluOperand(0, 0)); break; case Jitter::CONDITION_BL: m_assembler.MovCc(CArmAssembler::CONDITION_MI, dstReg, CArmAssembler::MakeImmediateAluOperand(1, 0)); m_assembler.MovCc(CArmAssembler::CONDITION_GE, dstReg, CArmAssembler::MakeImmediateAluOperand(0, 0)); break; case Jitter::CONDITION_EQ: m_assembler.MovCc(CArmAssembler::CONDITION_EQ, dstReg, CArmAssembler::MakeImmediateAluOperand(1, 0)); m_assembler.MovCc(CArmAssembler::CONDITION_NE, dstReg, CArmAssembler::MakeImmediateAluOperand(0, 0)); break; default: assert(0); break; } CommitSymbolRegister(dst, dstReg); tempRegisterContext.Release(tmpReg); } void CCodeGen_Arm::Emit_Fp_Mov_MemSRelI32(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); assert(src1->m_type == SYM_FP_REL_INT32); CTempRegisterContext tempRegisterContext; auto dstReg = CArmAssembler::s0; auto src1Reg = CArmAssembler::s1; m_assembler.Vldr(src1Reg, g_baseRegister, CArmAssembler::MakeImmediateLdrAddress(src1->m_valueLow)); m_assembler.Vcvt_F32_S32(dstReg, src1Reg); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, dstReg); } void CCodeGen_Arm::Emit_Fp_ToIntTrunc_MemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); CTempRegisterContext tempRegisterContext; auto dstReg = CArmAssembler::s0; auto src1Reg = CArmAssembler::s1; LoadMemoryFpSingleInRegister(tempRegisterContext, src1Reg, src1); m_assembler.Vcvt_S32_F32(dstReg, src1Reg); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, dstReg); } void CCodeGen_Arm::Emit_Fp_LdCst_TmpCst(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); assert(dst->m_type == SYM_FP_TMP_SINGLE); assert(src1->m_type == SYM_CONSTANT); LoadConstantInRegister(CArmAssembler::r0, src1->m_valueLow); m_assembler.Str(CArmAssembler::r0, CArmAssembler::rSP, CArmAssembler::MakeImmediateLdrAddress(dst->m_stackLocation + m_stackLevel)); } CCodeGen_Arm::CONSTMATCHER CCodeGen_Arm::g_fpuConstMatchers[] = { { OP_FP_ADD, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fpu_MemMemMem<FPUOP_ADD> }, { OP_FP_SUB, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fpu_MemMemMem<FPUOP_SUB> }, { OP_FP_MUL, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fpu_MemMemMem<FPUOP_MUL> }, { OP_FP_DIV, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fpu_MemMemMem<FPUOP_DIV> }, { OP_FP_CMP, MATCH_ANY, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fp_Cmp_AnyMemMem }, { OP_FP_MIN, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_FpuMd_MemMemMem<FPUMDOP_MIN> }, { OP_FP_MAX, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_FpuMd_MemMemMem<FPUMDOP_MAX> }, { OP_FP_RCPL, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_FpuMd_MemMem<FPUMDOP_RCPL> }, { OP_FP_SQRT, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_Fpu_MemMem<FPUOP_SQRT> }, { OP_FP_RSQRT, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_FpuMd_MemMem<FPUMDOP_RSQRT> }, { OP_FP_ABS, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_Fpu_MemMem<FPUOP_ABS> }, { OP_FP_NEG, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_Fpu_MemMem<FPUOP_NEG> }, { OP_MOV, MATCH_MEMORY_FP_SINGLE, MATCH_RELATIVE_FP_INT32, MATCH_NIL, &CCodeGen_Arm::Emit_Fp_Mov_MemSRelI32 }, { OP_FP_TOINT_TRUNC, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_Fp_ToIntTrunc_MemMem }, { OP_FP_LDCST, MATCH_TEMPORARY_FP_SINGLE, MATCH_CONSTANT, MATCH_NIL, &CCodeGen_Arm::Emit_Fp_LdCst_TmpCst }, { OP_MOV, MATCH_NIL, MATCH_NIL, MATCH_NIL, NULL }, }; <commit_msg>Slightly improved FP comparison on ARM.<commit_after>#include "Jitter_CodeGen_Arm.h" using namespace Jitter; void CCodeGen_Arm::LoadMemoryFpSingleInRegister(CTempRegisterContext& tempRegContext, CArmAssembler::SINGLE_REGISTER reg, CSymbol* symbol) { switch(symbol->m_type) { case SYM_FP_REL_SINGLE: LoadRelativeFpSingleInRegister(tempRegContext, reg, symbol); break; case SYM_FP_TMP_SINGLE: LoadTemporaryFpSingleInRegister(tempRegContext, reg, symbol); break; default: assert(false); break; } } void CCodeGen_Arm::StoreRegisterInMemoryFpSingle(CTempRegisterContext& tempRegContext, CSymbol* symbol, CArmAssembler::SINGLE_REGISTER reg) { switch(symbol->m_type) { case SYM_FP_REL_SINGLE: StoreRelativeFpSingleInRegister(tempRegContext, symbol, reg); break; case SYM_FP_TMP_SINGLE: StoreTemporaryFpSingleInRegister(tempRegContext, symbol, reg); break; default: assert(false); break; } } void CCodeGen_Arm::LoadRelativeFpSingleInRegister(CTempRegisterContext& tempRegContext, CArmAssembler::SINGLE_REGISTER reg, CSymbol* symbol) { assert(symbol->m_type == SYM_FP_REL_SINGLE); if((symbol->m_valueLow / 4) < 0x100) { m_assembler.Vldr(reg, g_baseRegister, CArmAssembler::MakeImmediateLdrAddress(symbol->m_valueLow)); } else { auto offsetRegister = tempRegContext.Allocate(); LoadConstantInRegister(offsetRegister, symbol->m_valueLow); m_assembler.Add(offsetRegister, offsetRegister, g_baseRegister); m_assembler.Vldr(reg, offsetRegister, CArmAssembler::MakeImmediateLdrAddress(0)); tempRegContext.Release(offsetRegister); } } void CCodeGen_Arm::StoreRelativeFpSingleInRegister(CTempRegisterContext& tempRegContext, CSymbol* symbol, CArmAssembler::SINGLE_REGISTER reg) { assert(symbol->m_type == SYM_FP_REL_SINGLE); if((symbol->m_valueLow / 4) < 0x100) { m_assembler.Vstr(reg, g_baseRegister, CArmAssembler::MakeImmediateLdrAddress(symbol->m_valueLow)); } else { auto offsetRegister = tempRegContext.Allocate(); LoadConstantInRegister(offsetRegister, symbol->m_valueLow); m_assembler.Add(offsetRegister, offsetRegister, g_baseRegister); m_assembler.Vstr(reg, offsetRegister, CArmAssembler::MakeImmediateLdrAddress(0)); tempRegContext.Release(offsetRegister); } } void CCodeGen_Arm::LoadTemporaryFpSingleInRegister(CTempRegisterContext& tempRegContext, CArmAssembler::SINGLE_REGISTER reg, CSymbol* symbol) { assert(symbol->m_type == SYM_FP_TMP_SINGLE); auto offset = symbol->m_stackLocation + m_stackLevel; if((offset / 4) < 0x100) { m_assembler.Vldr(reg, CArmAssembler::rSP, CArmAssembler::MakeImmediateLdrAddress(symbol->m_stackLocation + m_stackLevel)); } else { auto offsetRegister = tempRegContext.Allocate(); LoadConstantInRegister(offsetRegister, offset); m_assembler.Add(offsetRegister, offsetRegister, CArmAssembler::rSP); m_assembler.Vldr(reg, offsetRegister, CArmAssembler::MakeImmediateLdrAddress(0)); tempRegContext.Release(offsetRegister); } } void CCodeGen_Arm::StoreTemporaryFpSingleInRegister(CTempRegisterContext& tempRegContext, CSymbol* symbol, CArmAssembler::SINGLE_REGISTER reg) { assert(symbol->m_type == SYM_FP_TMP_SINGLE); auto offset = symbol->m_stackLocation + m_stackLevel; if((offset / 4) < 0x100) { m_assembler.Vstr(reg, CArmAssembler::rSP, CArmAssembler::MakeImmediateLdrAddress(symbol->m_stackLocation + m_stackLevel)); } else { auto offsetRegister = tempRegContext.Allocate(); LoadConstantInRegister(offsetRegister, offset); m_assembler.Add(offsetRegister, offsetRegister,CArmAssembler::rSP); m_assembler.Vstr(reg, offsetRegister, CArmAssembler::MakeImmediateLdrAddress(0)); tempRegContext.Release(offsetRegister); } } template <typename FPUOP> void CCodeGen_Arm::Emit_Fpu_MemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); CTempRegisterContext tempRegisterContext; LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); ((m_assembler).*(FPUOP::OpReg()))(CArmAssembler::s1, CArmAssembler::s0); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, CArmAssembler::s1); } template <typename FPUOP> void CCodeGen_Arm::Emit_Fpu_MemMemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); auto src2 = statement.src2->GetSymbol().get(); CTempRegisterContext tempRegisterContext; LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s1, src2); ((m_assembler).*(FPUOP::OpReg()))(CArmAssembler::s2, CArmAssembler::s0, CArmAssembler::s1); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, CArmAssembler::s2); } template <typename FPUMDOP> void CCodeGen_Arm::Emit_FpuMd_MemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); CTempRegisterContext tempRegisterContext; LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); ((m_assembler).*(FPUMDOP::OpReg()))(CArmAssembler::q1, CArmAssembler::q0); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, CArmAssembler::s4); } template <typename FPUMDOP> void CCodeGen_Arm::Emit_FpuMd_MemMemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); auto src2 = statement.src2->GetSymbol().get(); CTempRegisterContext tempRegisterContext; LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s4, src2); ((m_assembler).*(FPUMDOP::OpReg()))(CArmAssembler::q2, CArmAssembler::q0, CArmAssembler::q1); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, CArmAssembler::s8); } void CCodeGen_Arm::Emit_Fp_Cmp_AnyMemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); auto src2 = statement.src2->GetSymbol().get(); CTempRegisterContext tempRegisterContext; auto tmpReg = tempRegisterContext.Allocate(); auto dstReg = PrepareSymbolRegisterDef(dst, tmpReg); m_assembler.Mov(dstReg, CArmAssembler::MakeImmediateAluOperand(0, 0)); LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s0, src1); LoadMemoryFpSingleInRegister(tempRegisterContext, CArmAssembler::s1, src2); m_assembler.Vcmp_F32(CArmAssembler::s0, CArmAssembler::s1); m_assembler.Vmrs(CArmAssembler::rPC); //Move to general purpose status register switch(statement.jmpCondition) { case Jitter::CONDITION_AB: m_assembler.MovCc(CArmAssembler::CONDITION_GT, dstReg, CArmAssembler::MakeImmediateAluOperand(1, 0)); break; case Jitter::CONDITION_BE: m_assembler.MovCc(CArmAssembler::CONDITION_LS, dstReg, CArmAssembler::MakeImmediateAluOperand(1, 0)); break; case Jitter::CONDITION_BL: m_assembler.MovCc(CArmAssembler::CONDITION_MI, dstReg, CArmAssembler::MakeImmediateAluOperand(1, 0)); break; case Jitter::CONDITION_EQ: m_assembler.MovCc(CArmAssembler::CONDITION_EQ, dstReg, CArmAssembler::MakeImmediateAluOperand(1, 0)); break; default: assert(0); break; } CommitSymbolRegister(dst, dstReg); tempRegisterContext.Release(tmpReg); } void CCodeGen_Arm::Emit_Fp_Mov_MemSRelI32(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); assert(src1->m_type == SYM_FP_REL_INT32); CTempRegisterContext tempRegisterContext; auto dstReg = CArmAssembler::s0; auto src1Reg = CArmAssembler::s1; m_assembler.Vldr(src1Reg, g_baseRegister, CArmAssembler::MakeImmediateLdrAddress(src1->m_valueLow)); m_assembler.Vcvt_F32_S32(dstReg, src1Reg); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, dstReg); } void CCodeGen_Arm::Emit_Fp_ToIntTrunc_MemMem(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); CTempRegisterContext tempRegisterContext; auto dstReg = CArmAssembler::s0; auto src1Reg = CArmAssembler::s1; LoadMemoryFpSingleInRegister(tempRegisterContext, src1Reg, src1); m_assembler.Vcvt_S32_F32(dstReg, src1Reg); StoreRegisterInMemoryFpSingle(tempRegisterContext, dst, dstReg); } void CCodeGen_Arm::Emit_Fp_LdCst_TmpCst(const STATEMENT& statement) { auto dst = statement.dst->GetSymbol().get(); auto src1 = statement.src1->GetSymbol().get(); assert(dst->m_type == SYM_FP_TMP_SINGLE); assert(src1->m_type == SYM_CONSTANT); LoadConstantInRegister(CArmAssembler::r0, src1->m_valueLow); m_assembler.Str(CArmAssembler::r0, CArmAssembler::rSP, CArmAssembler::MakeImmediateLdrAddress(dst->m_stackLocation + m_stackLevel)); } CCodeGen_Arm::CONSTMATCHER CCodeGen_Arm::g_fpuConstMatchers[] = { { OP_FP_ADD, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fpu_MemMemMem<FPUOP_ADD> }, { OP_FP_SUB, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fpu_MemMemMem<FPUOP_SUB> }, { OP_FP_MUL, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fpu_MemMemMem<FPUOP_MUL> }, { OP_FP_DIV, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fpu_MemMemMem<FPUOP_DIV> }, { OP_FP_CMP, MATCH_ANY, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_Fp_Cmp_AnyMemMem }, { OP_FP_MIN, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_FpuMd_MemMemMem<FPUMDOP_MIN> }, { OP_FP_MAX, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, &CCodeGen_Arm::Emit_FpuMd_MemMemMem<FPUMDOP_MAX> }, { OP_FP_RCPL, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_FpuMd_MemMem<FPUMDOP_RCPL> }, { OP_FP_SQRT, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_Fpu_MemMem<FPUOP_SQRT> }, { OP_FP_RSQRT, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_FpuMd_MemMem<FPUMDOP_RSQRT> }, { OP_FP_ABS, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_Fpu_MemMem<FPUOP_ABS> }, { OP_FP_NEG, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_Fpu_MemMem<FPUOP_NEG> }, { OP_MOV, MATCH_MEMORY_FP_SINGLE, MATCH_RELATIVE_FP_INT32, MATCH_NIL, &CCodeGen_Arm::Emit_Fp_Mov_MemSRelI32 }, { OP_FP_TOINT_TRUNC, MATCH_MEMORY_FP_SINGLE, MATCH_MEMORY_FP_SINGLE, MATCH_NIL, &CCodeGen_Arm::Emit_Fp_ToIntTrunc_MemMem }, { OP_FP_LDCST, MATCH_TEMPORARY_FP_SINGLE, MATCH_CONSTANT, MATCH_NIL, &CCodeGen_Arm::Emit_Fp_LdCst_TmpCst }, { OP_MOV, MATCH_NIL, MATCH_NIL, MATCH_NIL, NULL }, }; <|endoftext|>
<commit_before>/// @brief computes scales for CORDIC-rotations in case of circular coordiantes namespace core { namespace cordic { template<size_t n, typename fp> double lut<n, fp>::circular_scale(size_t n) { double scale(1.0); BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1)) { scale *= std::sqrt(1.0 + std::powl(2.0, -2.0 * i)); } return scale; } template<size_t n, typename fp> lut<n, fp> lut<n, fp>::circular_scales() { base_class scales; BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1)) { scales[i] = std::sqrt(1.0 + std::powl(2.0, -2.0 * i)); } return this_class(scales); } }} <commit_msg>circular_scales.inl: from powl to pow -> remove implicit cast from long double to double<commit_after>/// @brief computes scales for CORDIC-rotations in case of circular coordiantes namespace core { namespace cordic { template<size_t n, typename fp> double lut<n, fp>::circular_scale(size_t n) { double scale(1.0); BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1)) { scale *= std::sqrt(1.0 + std::pow(2.0, -2.0 * i)); } return scale; } template<size_t n, typename fp> lut<n, fp> lut<n, fp>::circular_scales() { base_class scales; BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1)) { scales[i] = std::sqrt(1.0 + std::pow(2.0, -2.0 * i)); } return this_class(scales); } }} <|endoftext|>
<commit_before>#ifndef ALEPH_GEOMETRY_TANGENT_SPACE_HH__ #define ALEPH_GEOMETRY_TANGENT_SPACE_HH__ #include <aleph/config/Eigen.hh> #include <aleph/geometry/BruteForce.hh> #include <aleph/geometry/FLANN.hh> #include <aleph/geometry/distances/Euclidean.hh> #include <aleph/math/AlgebraicSphere.hh> #include <aleph/math/KahanSummation.hh> #ifdef ALEPH_WITH_EIGEN #include <Eigen/Core> #include <Eigen/Cholesky> #include <Eigen/SVD> #endif #include <cassert> #include <set> #include <vector> namespace aleph { namespace geometry { namespace detail { /** Model of a smooth decreasing weight function according to the original paper *Algebraic Point Set Surfaces* by Guennebaud & Gross. */ template <class T> T phi( T x ) { return x < 1 ? std::pow( 1 - x*x, T(4) ) : T(); } } // namespace detail #ifdef ALEPH_WITH_EIGEN // Previous versions of Eigen have a bug that occurs when mixing dynamic // and fixed-sized vectors: // // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=654 // // Until a workaround has been identified, tangent space estimation will // not be enabled for older versions. #if EIGEN_VERSION_AT_LEAST(3,3,0) class TangentSpace { public: using T = double; using Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>; using Vector = Eigen::Matrix<T, 1, Eigen::Dynamic>; using Sphere = math::AlgebraicSphere<T>; #if EIGEN_VERSION_AT_LEAST(3,3,0) using Index = Eigen::Index; #else using Index = typename Matrix::Index; #endif struct LocalTangentSpace { Matrix tangents; Vector normal; Vector position; T localFeatureSize; std::vector<std::size_t> indices; }; template <class Container> std::vector<T> operator()( const Container& container, unsigned k ) { std::vector<double> curvature; curvature.reserve( container.size() ); auto lts = localTangentSpaces( container, k ); auto spheres = fitSpheres( container, lts ); std::transform( spheres.begin(), spheres.end(), std::back_inserter( curvature ), [] ( const Sphere& sphere ) { return sphere.meanCurvature(); } ); return curvature; } private: /** Given a container and a number for determining the local neighbourhood of points, this function estimates (!) the tangent space structure around every point, resulting in a set of normal vectors and tangent vectors. @param container Container @param k Local neighbourhood size */ template <class Container> std::vector<LocalTangentSpace> localTangentSpaces( const Container& container, unsigned k ) { using ElementType = typename Container::ElementType; using Distance = distances::Euclidean<ElementType>; #ifdef ALEPH_WITH_FLANN using NearestNeighbours = FLANN<Container, Distance>; #else using NearestNeighbours = BruteForce<Container, Distance>; #endif NearestNeighbours nearestNeighbours( container ); using IndexType = typename NearestNeighbours::IndexType; std::vector< std::vector<IndexType> > indices; std::vector< std::vector<ElementType> > distances; nearestNeighbours.neighbourSearch( k, indices, distances ); std::vector<LocalTangentSpace> localTangentSpaces; auto n = container.size(); auto d = container.dimension(); for( std::size_t i = 0; i < n; i++ ) { // This coordinate matrix will contain the differences to the // centroid coordinate. The matrix will be transformed via an // SVD. Matrix M = Matrix::Zero( Index(k), Index(d) ); // Centroid calculation ------------------------------------------ Vector centroid = Vector::Zero(1, Index(d) ); for( std::size_t j = 0; j < indices[i].size(); j++ ) { auto&& neighbourIndex = indices[i][j]; auto v = getPosition( container, neighbourIndex ); centroid += v; M.row( Index(j) ) = v; } centroid /= static_cast<T>( indices.size() ); // Coordinate matrix setup --------------------------------------- M = M.rowwise() - centroid; Eigen::JacobiSVD<Matrix> svd( M, Eigen::ComputeThinV ); LocalTangentSpace lts; lts.tangents = Matrix::Zero( Index(d), Index(d - 1) ); // The singular vectors of all but the *smallest* singular value // form the tangential directions of the tangent space. auto&& V = svd.matrixV(); for( Index j = 0; j < Index( d - 1 ); j++ ) lts.tangents.col(j) = V.col(j); lts.normal = Matrix::Zero( Index(1), Index(d) ); lts.normal = V.col( Index(d-1) ).normalized(); lts.position = getPosition( container, i ); lts.indices = indices[i]; // Take the *maximum distance* in which we can find all of the // neighbours as a *rough* approximation to the local feature // size. lts.localFeatureSize = distances[i].empty() == false ? *std::max_element( distances[i].begin(), distances[i].end() ) : T(); localTangentSpaces.push_back( lts ); // TODO: // // 1. Calculate raw approximation (reconstruction) error by // assessing how well the space fits the original data // // 2. Make normal orientation consistent. I am unsure as to // whether this will improve the results or not. } propagateOrientation( localTangentSpaces ); return localTangentSpaces; } template <class Container> std::vector<Sphere> fitSpheres( const Container& container, const std::vector<LocalTangentSpace>& localTangentSpaces ) { using namespace detail; std::vector<Sphere> spheres; spheres.reserve( container.size() ); for( auto&& lts : localTangentSpaces ) { auto d = Index( container.dimension() ); Matrix A = Matrix::Zero( d+2, d+2 ); Vector b = Vector::Zero( 1, d+2 ); auto&& indices = lts.indices; // Pre-processing -------------------------------------------------- // // Choose a value for the beta parameter, based on the weighted // neighbourhood sizes of *all* points. This requires iterating // over all points prior to calculating anything else. T beta = T(); { std::vector<T> W; std::vector<T> H; W.reserve( container.size() ); H.reserve( container.size() ); for( auto&& index : indices ) { auto&& neighbour = getPosition( container, index ); W.emplace_back( phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize ) ); H.emplace_back( lts.localFeatureSize ); } // Sum of weights *before* applying the local feature size // multiplier; we need to save this result because it will // be required below. auto ws = math::accumulate_kahan_sorted( W.begin(), W.end(), T() ); // Apply weights to local feature size estimates; afterwards we // can finally obtain the scaling factor from this weighted sum for( std::size_t i = 0; i < W.size(); i++ ) W[i] = W[i] * H[i]; // TODO: make initial guess for beta (10e6) configurable? auto h = math::accumulate_kahan_sorted( W.begin(), W.end(), T() ) / ws; beta = 10e6 * h * h; } Index k = Index( indices.size() ); Matrix W = Matrix::Zero( (d+1)*k, (d+1)*k ); Matrix D = Matrix::Zero( (d+1)*k, (d+2) ); Matrix c = Matrix::Zero( (d+1)*k, 1 ); { Index i = Index(); for( auto&& index : indices ) { auto neighbour = getPosition( container, index ); auto w = phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize ); W( i*(d+1),i*(d+1) ) = w; for( Index(j) = 0; j < d; j++ ) { assert( W( i*(d+1)+j+1, i*(d+1)+j+1 ) == 0 ); W( i*(d+1)+j+1, i*(d+1)+j+1 ) = beta * w; } ++i; } } { Index i = Index(); for( auto&& index : indices ) { auto neighbour = getPosition( container, index ); D( i*(d+1), 0 ) = 1.0; for( Index(j) = 0; j < d; j++ ) D( i*(d+1), j+1 ) = neighbour(j); D( i*(d+1), d+1) = neighbour * neighbour.transpose(); for( Index(j) = 0; j < d; j++ ) { D( i*(d+1)+j+1, j+1 ) = 1; D( i*(d+1)+j+1, d+1 ) = 2 * neighbour(j); c( i*(d+1)+j+1, 0 ) = localTangentSpaces.at(index).normal(j); } ++i; } } for( auto&& index : indices ) { auto neighbour = getPosition( container, index ); auto squaredNeigbourNorm = neighbour.squaredNorm(); auto w = phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize ); A( 0, 0) += w; A( d+1, 0) += w * squaredNeigbourNorm; A( d+1, d+1) += w * squaredNeigbourNorm * squaredNeigbourNorm; for( Index(i) = 1; i < d+1; i++ ) { A( i, i) += w * ( neighbour(i-1)*neighbour(i-1) + 1 ) * beta; A( i, 0) += w * ( neighbour(i-1) ); A(d+1, i) += w * ( neighbour(i-1)*squaredNeigbourNorm + 2 * beta * neighbour(i-1) ); A(d+1, d+1) += w * ( 4*neighbour(i-1)*neighbour(i-1) ) * beta; // re-establish symmetry A( 0, i) = A(i,0); A( i, d+1) = A(d+1, i); b(i ) += beta * w * localTangentSpaces.at(index).normal(i-1); b(d+1) += 2.0 * beta * w * localTangentSpaces.at(index).normal(i-1) * neighbour(i-1); for( Index(j) = i+1; j < d+1; j++ ) { A(j, i) += w * neighbour(i-1) * neighbour(j-1); A(i, j) = A(j,i); } } // re-establish symmetry A(0, d+1) = A(d+1, 0); } // Solve the linear system --------------------------------------- // // The solution of the system Ax = b is used to obtain the // coefficients of the algebraic sphere. using Solver = Eigen::LDLT<Matrix>; Solver solver(A); Vector u = solver.solve( b.transpose() ); spheres.emplace_back( Sphere( u.data(), u.data() + u.size() ) ); } return spheres; } void propagateOrientation( std::vector<LocalTangentSpace>& localTangentSpaces ) { using Edge = std::pair<std::size_t, std::size_t>; std::set<Edge> edges; for( std::size_t i = 0; i < localTangentSpaces.size(); i++ ) { for( auto&& index : localTangentSpaces.at(i).indices ) { if( i < index ) edges.insert( std::make_pair(i,index) ); else edges.insert( std::make_pair(index,i) ); } } for( auto&& edge : edges ) { auto i = edge.first; auto&& ni = localTangentSpaces.at(i).normal; auto j = edge.second; auto&& nj = localTangentSpaces.at(j).normal; if( ni * nj.transpose() < 0 ) nj = -nj; } } /** Auxiliary function for extracting and converting a position from a given container, storing it as a (mathematical) vector. */ template <class Container> Vector getPosition( const Container& container, std::size_t i ) { auto d = container.dimension(); auto p = container[i]; Vector v = Vector::Zero(1, Index(d) ); // copy (and transform!) the vector; there's an implicit type // conversion going on here for( std::size_t l = 0; l < d; l++ ) v( Index(l) ) = p[l]; return v; } }; #endif #endif } // namespace geometry } // namespace aleph #endif <commit_msg>Implemented basic sphere fitting *without* normals<commit_after>#ifndef ALEPH_GEOMETRY_TANGENT_SPACE_HH__ #define ALEPH_GEOMETRY_TANGENT_SPACE_HH__ #include <aleph/config/Eigen.hh> #include <aleph/geometry/BruteForce.hh> #include <aleph/geometry/FLANN.hh> #include <aleph/geometry/distances/Euclidean.hh> #include <aleph/math/AlgebraicSphere.hh> #include <aleph/math/KahanSummation.hh> #ifdef ALEPH_WITH_EIGEN #include <Eigen/Core> #include <Eigen/Cholesky> #include <Eigen/Eigenvalues> #include <Eigen/SVD> #endif #include <cassert> #include <set> #include <vector> namespace aleph { namespace geometry { namespace detail { /** Model of a smooth decreasing weight function according to the original paper *Algebraic Point Set Surfaces* by Guennebaud & Gross. */ template <class T> T phi( T x ) { return x < 1 ? std::pow( 1 - x*x, T(4) ) : T(); } } // namespace detail #ifdef ALEPH_WITH_EIGEN // Previous versions of Eigen have a bug that occurs when mixing dynamic // and fixed-sized vectors: // // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=654 // // Until a workaround has been identified, tangent space estimation will // not be enabled for older versions. #if EIGEN_VERSION_AT_LEAST(3,3,0) class TangentSpace { public: using T = double; using Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>; using Vector = Eigen::Matrix<T, 1, Eigen::Dynamic>; using Sphere = math::AlgebraicSphere<T>; #if EIGEN_VERSION_AT_LEAST(3,3,0) using Index = Eigen::Index; #else using Index = typename Matrix::Index; #endif struct LocalTangentSpace { Matrix tangents; Vector normal; Vector position; T localFeatureSize; std::vector<std::size_t> indices; }; template <class Container> std::vector<T> operator()( const Container& container, unsigned k ) { std::vector<double> curvature; curvature.reserve( container.size() ); auto lts = localTangentSpaces( container, k ); auto spheres = fitSpheres( container, lts ); std::transform( spheres.begin(), spheres.end(), std::back_inserter( curvature ), [] ( const Sphere& sphere ) { return sphere.meanCurvature(); } ); return curvature; } private: /** Given a container and a number for determining the local neighbourhood of points, this function estimates (!) the tangent space structure around every point, resulting in a set of normal vectors and tangent vectors. @param container Container @param k Local neighbourhood size */ template <class Container> std::vector<LocalTangentSpace> localTangentSpaces( const Container& container, unsigned k ) { using ElementType = typename Container::ElementType; using Distance = distances::Euclidean<ElementType>; #ifdef ALEPH_WITH_FLANN using NearestNeighbours = FLANN<Container, Distance>; #else using NearestNeighbours = BruteForce<Container, Distance>; #endif NearestNeighbours nearestNeighbours( container ); using IndexType = typename NearestNeighbours::IndexType; std::vector< std::vector<IndexType> > indices; std::vector< std::vector<ElementType> > distances; nearestNeighbours.neighbourSearch( k, indices, distances ); std::vector<LocalTangentSpace> localTangentSpaces; auto n = container.size(); auto d = container.dimension(); for( std::size_t i = 0; i < n; i++ ) { // This coordinate matrix will contain the differences to the // centroid coordinate. The matrix will be transformed via an // SVD. Matrix M = Matrix::Zero( Index(k), Index(d) ); // Centroid calculation ------------------------------------------ Vector centroid = Vector::Zero(1, Index(d) ); for( std::size_t j = 0; j < indices[i].size(); j++ ) { auto&& neighbourIndex = indices[i][j]; auto v = getPosition( container, neighbourIndex ); centroid += v; M.row( Index(j) ) = v; } centroid /= static_cast<T>( indices.size() ); // Coordinate matrix setup --------------------------------------- M = M.rowwise() - centroid; Eigen::JacobiSVD<Matrix> svd( M, Eigen::ComputeThinV ); LocalTangentSpace lts; lts.tangents = Matrix::Zero( Index(d), Index(d - 1) ); // The singular vectors of all but the *smallest* singular value // form the tangential directions of the tangent space. auto&& V = svd.matrixV(); for( Index j = 0; j < Index( d - 1 ); j++ ) lts.tangents.col(j) = V.col(j); lts.normal = V.col( Index(d-1) ).normalized(); lts.position = getPosition( container, i ); lts.indices = indices[i]; // Take the *maximum distance* in which we can find all of the // neighbours as a *rough* approximation to the local feature // size. lts.localFeatureSize = distances[i].empty() == false ? *std::max_element( distances[i].begin(), distances[i].end() ) : T(); localTangentSpaces.push_back( lts ); // TODO: // // 1. Calculate raw approximation (reconstruction) error by // assessing how well the space fits the original data // // 2. Make normal orientation consistent. I am unsure as to // whether this will improve the results or not. } propagateOrientation( localTangentSpaces ); return localTangentSpaces; } template <class Container> std::vector<Sphere> fitSpheres( const Container& container, const std::vector<LocalTangentSpace>& localTangentSpaces ) { using namespace detail; std::vector<Sphere> spheres; spheres.reserve( container.size() ); for( auto&& lts : localTangentSpaces ) { auto d = Index( container.dimension() ); Matrix A = Matrix::Zero( d+2, d+2 ); Vector b = Vector::Zero( 1, d+2 ); auto&& indices = lts.indices; // Pre-processing -------------------------------------------------- // // Choose a value for the beta parameter, based on the weighted // neighbourhood sizes of *all* points. This requires iterating // over all points prior to calculating anything else. T beta = T(); { std::vector<T> W; std::vector<T> H; W.reserve( container.size() ); H.reserve( container.size() ); for( auto&& index : indices ) { auto&& neighbour = getPosition( container, index ); W.emplace_back( phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize ) ); H.emplace_back( lts.localFeatureSize ); } // Sum of weights *before* applying the local feature size // multiplier; we need to save this result because it will // be required below. auto ws = math::accumulate_kahan_sorted( W.begin(), W.end(), T() ); // Apply weights to local feature size estimates; afterwards we // can finally obtain the scaling factor from this weighted sum for( std::size_t i = 0; i < W.size(); i++ ) W[i] = W[i] * H[i]; // TODO: make initial guess for beta (10e6) configurable? auto h = math::accumulate_kahan_sorted( W.begin(), W.end(), T() ) / ws; beta = 10e6 * h * h; } Index k = Index( indices.size() ); Matrix W = Matrix::Zero( (d+1)*k, (d+1)*k ); Matrix D = Matrix::Zero( (d+1)*k, (d+2) ); Matrix c = Matrix::Zero( (d+1)*k, 1 ); { Index i = Index(); for( auto&& index : indices ) { auto neighbour = getPosition( container, index ); auto w = phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize ); W( i*(d+1),i*(d+1) ) = w; for( Index(j) = 0; j < d; j++ ) { assert( W( i*(d+1)+j+1, i*(d+1)+j+1 ) == 0 ); W( i*(d+1)+j+1, i*(d+1)+j+1 ) = beta * w; } ++i; } } { Index i = Index(); for( auto&& index : indices ) { auto neighbour = getPosition( container, index ); D( i*(d+1), 0 ) = 1.0; for( Index(j) = 0; j < d; j++ ) D( i*(d+1), j+1 ) = neighbour(j); D( i*(d+1), d+1) = neighbour * neighbour.transpose(); for( Index(j) = 0; j < d; j++ ) { D( i*(d+1)+j+1, j+1 ) = 1; D( i*(d+1)+j+1, d+1 ) = 2 * neighbour(j); c( i*(d+1)+j+1, 0 ) = localTangentSpaces.at(index).normal(j); } ++i; } } for( auto&& index : indices ) { auto neighbour = getPosition( container, index ); auto squaredNeigbourNorm = neighbour.squaredNorm(); auto w = phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize ); A( 0, 0) += w; A( d+1, 0) += w * squaredNeigbourNorm; A( d+1, d+1) += w * squaredNeigbourNorm * squaredNeigbourNorm; for( Index(i) = 1; i < d+1; i++ ) { A( i, i) += w * ( neighbour(i-1)*neighbour(i-1) + 1 ) * beta; A( i, 0) += w * ( neighbour(i-1) ); A(d+1, i) += w * ( neighbour(i-1)*squaredNeigbourNorm + 2 * beta * neighbour(i-1) ); A(d+1, d+1) += w * ( 4*neighbour(i-1)*neighbour(i-1) ) * beta; // re-establish symmetry A( 0, i) = A(i,0); A( i, d+1) = A(d+1, i); b(i ) += beta * w * localTangentSpaces.at(index).normal(i-1); b(d+1) += 2.0 * beta * w * localTangentSpaces.at(index).normal(i-1) * neighbour(i-1); for( Index(j) = i+1; j < d+1; j++ ) { A(j, i) += w * neighbour(i-1) * neighbour(j-1); A(i, j) = A(j,i); } } // re-establish symmetry A(0, d+1) = A(d+1, 0); } // Solve the linear system --------------------------------------- // // The solution of the system Ax = b is used to obtain the // coefficients of the algebraic sphere. using Solver = Eigen::LDLT<Matrix>; Solver solver(A); Vector u = solver.solve( b.transpose() ); spheres.emplace_back( Sphere( u.data(), u.data() + u.size() ) ); } return spheres; } template <class Container> std::vector<Sphere> fitSpheresWithoutNormals( const Container& container, const std::vector<LocalTangentSpace>& localTangentSpaces ) { using namespace detail; std::vector<Sphere> spheres; spheres.reserve( container.size() ); for( auto&& lts : localTangentSpaces ) { auto&& indices = lts.indices; auto d = Index( container.dimension() ); auto k = Index( indices.size() ); Matrix W = Matrix::Zero(k,k ); Matrix D = Matrix::Zero(k,d+2); Matrix C = Matrix::Identity(d+2,d+2); C(0 , 0) = 0; C(0 ,d+1) = -2; C(d+1, 0) = -2; { Index i = Index(); for( auto&& index : indices ) { auto neighbour = getPosition( container, index ); W(i, i) = phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize ); D(i, 0) = 1; D(i,d+1) = neighbour * neighbour.transpose(); for( Index j = 0; j < d; j++ ) D(i,j+1) = neighbour(j); ++i; } } // Solve the linear system --------------------------------------- // // The solution of the system Ax = b is used to obtain the // coefficients of the algebraic sphere. using Solver = Eigen::GeneralizedSelfAdjointEigenSolver<Matrix>; Solver solver; solver.compute( D.transpose() * W *D, C ); auto eigenvalues = solver.eigenvalues(); Vector u = Vector::Zero( 1, d+2 ); for( Index i = 0; i < d+2; i++ ) { if( eigenvalues(i) > 0 ) { u = solver.eigenvectors().col(i); break; } } spheres.emplace_back( Sphere( u.data(), u.data() + u.size() ) ); } return spheres; } void propagateOrientation( std::vector<LocalTangentSpace>& localTangentSpaces ) { using Edge = std::pair<std::size_t, std::size_t>; std::set<Edge> edges; for( std::size_t i = 0; i < localTangentSpaces.size(); i++ ) { for( auto&& index : localTangentSpaces.at(i).indices ) { if( i < index ) edges.insert( std::make_pair(i,index) ); else edges.insert( std::make_pair(index,i) ); } } for( auto&& edge : edges ) { auto i = edge.first; auto&& ni = localTangentSpaces.at(i).normal; auto j = edge.second; auto&& nj = localTangentSpaces.at(j).normal; if( ni * nj.transpose() < 0 ) nj = -nj; } } /** Auxiliary function for extracting and converting a position from a given container, storing it as a (mathematical) vector. */ template <class Container> Vector getPosition( const Container& container, std::size_t i ) { auto d = container.dimension(); auto p = container[i]; Vector v = Vector::Zero(1, Index(d) ); // copy (and transform!) the vector; there's an implicit type // conversion going on here for( std::size_t l = 0; l < d; l++ ) v( Index(l) ) = p[l]; return v; } }; #endif #endif } // namespace geometry } // namespace aleph #endif <|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 [email protected]. * */ #include "src/utils/regex.h" #include <pcre.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string> #include <list> #include <fstream> #include <iostream> #include "src/utils/geo_lookup.h" #if PCRE_HAVE_JIT #define pcre_study_opt PCRE_STUDY_JIT_COMPILE #else #define pcre_study_opt 0 #endif namespace modsecurity { namespace Utils { Regex::Regex(const std::string& pattern_) : pattern(pattern_), m_ovector {0} { const char *errptr = NULL; int erroffset; if (pattern.empty() == true) { pattern.assign(".*"); } m_pc = pcre_compile(pattern.c_str(), PCRE_DOTALL|PCRE_MULTILINE, &errptr, &erroffset, NULL); m_pce = pcre_study(m_pc, pcre_study_opt, &errptr); } Regex::~Regex() { if (m_pc != NULL) { pcre_free(m_pc); m_pc = NULL; } if (m_pce != NULL) { #if PCRE_HAVE_JIT pcre_free_study(m_pce); #else pcre_free(m_pce); #endif m_pce = NULL; } } std::list<SMatch> Regex::searchAll(const std::string& s) { int ovector[OVECCOUNT]; std::list<SMatch> retList; int i; const char *subject = s.c_str(); int rc; rc = pcre_exec(m_pc, m_pce, subject, s.size(), 0, 0, ovector, OVECCOUNT); for (i = 0; i < rc; i++) { SMatch match; const char *substring_start = subject + ovector[2*i]; int substring_length = ovector[2*i+1] - ovector[2*i]; match.match = std::string(subject, ovector[2*i], substring_length); retList.push_front(match); } return retList; } int regex_search(const std::string& s, SMatch *match, const Regex& regex) { int ovector[OVECCOUNT]; int ret = pcre_exec(regex.m_pc, regex.m_pce, s.c_str(), s.size(), 0, 0, ovector, OVECCOUNT) > 0; if (ret > 0) { match->match = std::string(s, ovector[ret-1], ovector[ret] - ovector[ret-1]); match->size_ = ret; } return ret; } int regex_search(const std::string& s, const Regex& regex) { int ovector[OVECCOUNT]; return pcre_exec(regex.m_pc, regex.m_pce, s.c_str(), s.size(), 0, 0, ovector, OVECCOUNT) > 0; } } // namespace Utils } // namespace modsecurity <commit_msg>Fix substring constructor in regex search all<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 [email protected]. * */ #include "src/utils/regex.h" #include <pcre.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string> #include <list> #include <fstream> #include <iostream> #include "src/utils/geo_lookup.h" #if PCRE_HAVE_JIT #define pcre_study_opt PCRE_STUDY_JIT_COMPILE #else #define pcre_study_opt 0 #endif namespace modsecurity { namespace Utils { Regex::Regex(const std::string& pattern_) : pattern(pattern_), m_ovector {0} { const char *errptr = NULL; int erroffset; if (pattern.empty() == true) { pattern.assign(".*"); } m_pc = pcre_compile(pattern.c_str(), PCRE_DOTALL|PCRE_MULTILINE, &errptr, &erroffset, NULL); m_pce = pcre_study(m_pc, pcre_study_opt, &errptr); } Regex::~Regex() { if (m_pc != NULL) { pcre_free(m_pc); m_pc = NULL; } if (m_pce != NULL) { #if PCRE_HAVE_JIT pcre_free_study(m_pce); #else pcre_free(m_pce); #endif m_pce = NULL; } } std::list<SMatch> Regex::searchAll(const std::string& s) { int ovector[OVECCOUNT]; std::list<SMatch> retList; int i; const char *subject = s.c_str(); int rc; const std::string tmpString = std::string(s.c_str(), s.size()); rc = pcre_exec(m_pc, m_pce, subject, s.size(), 0, 0, ovector, OVECCOUNT); for (i = 0; i < rc; i++) { SMatch match; size_t start = ovector[2*i]; size_t end = ovector[2*i+1]; size_t len = end - start; if (end >= s.size()) { continue; } match.match = std::string(tmpString, start, len); retList.push_front(match); } return retList; } int regex_search(const std::string& s, SMatch *match, const Regex& regex) { int ovector[OVECCOUNT]; int ret = pcre_exec(regex.m_pc, regex.m_pce, s.c_str(), s.size(), 0, 0, ovector, OVECCOUNT) > 0; if (ret > 0) { match->match = std::string(s, ovector[ret-1], ovector[ret] - ovector[ret-1]); match->size_ = ret; } return ret; } int regex_search(const std::string& s, const Regex& regex) { int ovector[OVECCOUNT]; return pcre_exec(regex.m_pc, regex.m_pce, s.c_str(), s.size(), 0, 0, ovector, OVECCOUNT) > 0; } } // namespace Utils } // namespace modsecurity <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef HEADER_GUARD_CLASS_CONTENTS_H #define HEADER_GUARD_CLASS_CONTENTS_H #include <memory> #include <string> #include <type_traits> #include <vector> #include <cstddef> #include "change.hh" #include "mode.hh" namespace vick { /*! * \file contents.hh * * \brief Defines the class contents, which contains all the * information about the buffer. */ /*! * \brief Define `move_t` so that code can be more descriptive and * can change it from one place. */ using move_t = std::size_t; /*! * \brief Define `move_ts` to be a signed version of `move_t` * * \see move_t */ using move_ts = typename std::make_signed<move_t>::type; /*! * \brief Define `move_tu` to be an unsigned version of `move_t` * * \see move_t */ using move_tu = typename std::make_unsigned<move_t>::type; /*! * \class contents contents.hh "contents.hh" * * \brief Defines all the information about the buffer. */ class contents { public: std::map<char, std::function<boost::optional<std::shared_ptr< change> >(contents &, boost::optional<int>)> > normal_map /*!< \brief The contents buffer (file) specfic * normal mode character mappings. */, insert_map /*!< \brief The contents buffer (file) specfic * insert mode character mappings. */; /*! * \brief The type of file the buffer is. * * Default mode is fundamental; */ mode* buffer_mode; /*! * \brief The literal contents of the buffer */ std::vector<std::string> cont; /*! * \brief The list of changes to the buffer. This is public so * that treed-undo (a la Emacs) can be implemented the same as * linear is. */ std::vector<std::shared_ptr<change> > changes; /*! * \brief The current change the buffer is in */ size_t changes_i = 0; move_t y = 0 /*!< \brief The y (vertical) position in the buffer. */, x = 0 /*!< \brief The x (horizontal) position in the buffer. */, desired_x = 0 /*!< \brief This will be set to the x value we * want when you move to a different line but * the line you move to is too short * * \see waiting_for_desired */, y_offset = 0 /*!< \brief The number of lines that are not * displayed (off the top) */, max_y /*!< \brief The vertical height the buffer has been * allocated on the screen - [0, max_y) */, max_x /*!< \brief The horizontal width the buffer has been * allocated on the screen - [0, max_x) */; bool waiting_for_desired = false /*!< \brief Controls if the x * value will try to adjust to * desired_x * * \see desired_x */, refresh = true /*!< \brief Controls if the screen should * refresh everytime something happens */, delete_mode = false /*!< \brief Controls if the private mode * pointer variable will be deleted in the * destructor */, is_inserting = false /*!< \brief Will be true if the user is * currently inserting text into the * buffer. This will cause the * print_contents method to not have * undefined behavior if x is too * large. */, windows_file_endings = false /*!< \brief If true, then when * saving, appends the byte 13 to * each line. We use this to * maintain plugin consistency * across platforms. (The buffer * is in no way affected by this * variable) */; explicit contents( std::vector<std::string> cont = std::vector<std::string>(), mode* buffer_mode = &fundamental_mode); explicit contents(mode* buffer_mode); contents(move_t y, move_t x, mode* buffer_mode = &fundamental_mode); /*! * \brief Constructs this contents object as a copy of the other * contents object. * * This forces the private mode member to make a deep copy. */ contents(const contents&); contents(contents&&) = default; /*! * \brief If delete_mode is true, then it will delete the private * mode pointer member. * * \see delete_mode */ ~contents(); /*! * \brief Constructs this contents object as a copy of the other * contents object. * * This forces the private mode member to make a deep copy. */ contents& operator=(const contents&); contents& operator=(contents&&); /*! * \brief Calls the private mode member's `operator()` with * `*this` and the character given to this function. */ bool operator()(char); /*! * \brief Updates the values of ``max_y`` and ``max_x`` * * \see max_y * \see max_x */ void refreshmaxyx(); /*! * \brief Calls ``cont.push_back(str)`` * * \see cont * * \param str The string to be put at the end of the vector of * strings, `cont` */ void push_back(const std::string& str); }; } #endif <commit_msg>Add a mutex to contents for printing<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef HEADER_GUARD_CLASS_CONTENTS_H #define HEADER_GUARD_CLASS_CONTENTS_H #include <memory> #include <mutex> #include <string> #include <type_traits> #include <vector> #include <cstddef> #include "change.hh" #include "mode.hh" namespace vick { /*! * \file contents.hh * * \brief Defines the class contents, which contains all the * information about the buffer. */ /*! * \brief Define `move_t` so that code can be more descriptive and * can change it from one place. */ using move_t = std::size_t; /*! * \brief Define `move_ts` to be a signed version of `move_t` * * \see move_t */ using move_ts = typename std::make_signed<move_t>::type; /*! * \brief Define `move_tu` to be an unsigned version of `move_t` * * \see move_t */ using move_tu = typename std::make_unsigned<move_t>::type; /*! * \class contents contents.hh "contents.hh" * * \brief Defines all the information about the buffer. */ class contents { public: std::map<char, std::function<boost::optional<std::shared_ptr< change> >(contents &, boost::optional<int>)> > normal_map /*!< \brief The contents buffer (file) specfic * normal mode character mappings. */, insert_map /*!< \brief The contents buffer (file) specfic * insert mode character mappings. */; /*! * \brief The type of file the buffer is. * * Default mode is fundamental; */ mode* buffer_mode; /*! * \brief The literal contents of the buffer */ std::vector<std::string> cont; /*! * \brief The list of changes to the buffer. This is public so * that treed-undo (a la Emacs) can be implemented the same as * linear is. */ std::vector<std::shared_ptr<change> > changes; /*! * \brief For use to lock access to `cont` when it is being * updated in one thread and displayed in another. */ std::mutex print_mutex; /*! * \brief The current change the buffer is in */ size_t changes_i = 0; move_t y = 0 /*!< \brief The y (vertical) position in the buffer. */, x = 0 /*!< \brief The x (horizontal) position in the buffer. */, desired_x = 0 /*!< \brief This will be set to the x value we * want when you move to a different line but * the line you move to is too short * * \see waiting_for_desired */, y_offset = 0 /*!< \brief The number of lines that are not * displayed (off the top) */, max_y /*!< \brief The vertical height the buffer has been * allocated on the screen - [0, max_y) */, max_x /*!< \brief The horizontal width the buffer has been * allocated on the screen - [0, max_x) */; bool waiting_for_desired = false /*!< \brief Controls if the x * value will try to adjust to * desired_x * * \see desired_x */, refresh = true /*!< \brief Controls if the screen should * refresh everytime something happens */, delete_mode = false /*!< \brief Controls if the private mode * pointer variable will be deleted in the * destructor */, is_inserting = false /*!< \brief Will be true if the user is * currently inserting text into the * buffer. This will cause the * print_contents method to not have * undefined behavior if x is too * large. */, windows_file_endings = false /*!< \brief If true, then when * saving, appends the byte 13 to * each line. We use this to * maintain plugin consistency * across platforms. (The buffer * is in no way affected by this * variable) */; explicit contents( std::vector<std::string> cont = std::vector<std::string>(), mode* buffer_mode = &fundamental_mode); explicit contents(mode* buffer_mode); contents(move_t y, move_t x, mode* buffer_mode = &fundamental_mode); /*! * \brief Constructs this contents object as a copy of the other * contents object. * * This forces the private mode member to make a deep copy. */ contents(const contents&); contents(contents&&) = default; /*! * \brief If delete_mode is true, then it will delete the private * mode pointer member. * * \see delete_mode */ ~contents(); /*! * \brief Constructs this contents object as a copy of the other * contents object. * * This forces the private mode member to make a deep copy. */ contents& operator=(const contents&); contents& operator=(contents&&); /*! * \brief Calls the private mode member's `operator()` with * `*this` and the character given to this function. */ bool operator()(char); /*! * \brief Updates the values of ``max_y`` and ``max_x`` * * \see max_y * \see max_x */ void refreshmaxyx(); /*! * \brief Calls ``cont.push_back(str)`` * * \see cont * * \param str The string to be put at the end of the vector of * strings, `cont` */ void push_back(const std::string& str); }; } #endif <|endoftext|>
<commit_before>#include <iostream> #include <random> #include <chrono> #include <ctime> #include <map> #include <string> #include <json/json.hpp> class Civilization { friend std::ostream& operator<<(std::ostream&, const Civilization&); typedef std::normal_distribution<double> normal; typedef std::gamma_distribution<double> gamma; typedef std::string string; typedef nlohmann::json json; public: Civilization(time_t seed=time(NULL)) { std::cout << "Using seed " << seed << std::endl; engine_.seed(seed); GenBasics(); } void GenBasics() { normal intelligence_gen(100, 30); normal friendliness_gen(100, 80); normal emotionality_gen(100, 80); normal tribalism_gen(100,25); gamma age_gen(5, 8200); intelligence_ = Clamp(intelligence_gen(engine_), 0); friendliness_ = friendliness_gen(engine_); emotionality_ = emotionality_gen(engine_); tribalism_ = tribalism_gen(engine_); age_ = age_gen(engine_) + 300; } double Clamp(double number, double min, double max=kLargeNumber) { if (number > max) { return max; } else if (number < min) { return min; } else { return number; } } private: std::default_random_engine engine_; constexpr const static double kLargeNumber = 999999999999999; double intelligence_; double friendliness_; double emotionality_; double tribalism_; double age_; json specifics; }; std::ostream& operator<<(std::ostream &strm, const Civilization &civ) { return strm << "Civilization" << "\nintelligence: " << civ.intelligence_ << "\nfriendliness: " << civ.friendliness_ << "\nemotionality: " << civ.emotionality_ << "\ntribalism: " << civ.tribalism_ << "\nage: " << civ.age_ << "\n"; } int main() { for (size_t i = 0; i < 10; ++i) { std::cout << Civilization() << std::endl; } } <commit_msg>Fixed random seed<commit_after>#include <iostream> #include <random> #include <chrono> #include <map> #include <string> #include <json/json.hpp> class Civilization { // I think this is the first time I've ever used friend without feeling bad friend std::ostream& operator<<(std::ostream&, const Civilization&); typedef std::normal_distribution<double> normal; typedef std::gamma_distribution<double> gamma; typedef std::uniform_real_distribution<double> uniform; typedef std::string string; typedef nlohmann::json json; public: Civilization(time_t seed=std::chrono::system_clock::now().time_since_epoch().count()) : unitrand_(0.0, 1.0) { std::cout << "Using seed " << seed << std::endl; engine_.seed(seed); // burn card engine_.discard(1); GenCiv(); } void GenCiv() { GenBasics(); GenCriticalThinking(); GenSpeech(); GenGovernment(); GenRelations(); GenAppearance(); } void GenBasics() { // god this is actually unbelievably fun normal intelligence_gen(100, 30); normal friendliness_gen(100, 80); normal emotionality_gen(100, 80); normal tribalism_gen(100,25); gamma age_gen(2, 8200); // no negative intelligence (despite some people I know) intelligence_ = Clamp(intelligence_gen(engine_), 0); friendliness_ = friendliness_gen(engine_); emotionality_ = emotionality_gen(engine_); tribalism_ = tribalism_gen(engine_); age_ = age_gen(engine_) + 2000; } void GenCriticalThinking() { if (intelligence_ > 70 || rand() < .05) { specifics_["critical_thinking"] = 1; } std::cout << engine_() << "\n" << engine_() << std::endl; } void GenSpeech() { } void GenGovernment() { } void GenRelations() { } void GenAppearance() { } double Clamp(double number, double min, double max=kLargeNumber) { if (number > max) { return max; } else if (number < min) { return min; } else { return number; } } double Rand() { return unitrand_(engine_); } private: std::mt19937 engine_; uniform unitrand_; constexpr const static double kLargeNumber = 999999999999999; double intelligence_; double friendliness_; double emotionality_; double tribalism_; double age_; json specifics_; }; std::ostream& operator<<(std::ostream &strm, const Civilization &civ) { return strm << "Civilization" << "\nintelligence: " << civ.intelligence_ << "\nfriendliness: " << civ.friendliness_ << "\nemotionality: " << civ.emotionality_ << "\ntribalism: " << civ.tribalism_ << "\nage: " << civ.age_ << "\n"; } int main() { for (size_t i = 0; i < 10; ++i) { std::cout << Civilization() << std::endl; } } <|endoftext|>
<commit_before>/* database-write.cpp * * Copyright (C) 2012-2014 Matthias Klumpp <[email protected]> * * Licensed under the GNU Lesser General Public License Version 3 * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #include "database-write.hpp" #include <iostream> #include <string> #include <algorithm> #include <vector> #include <glib/gstdio.h> #include "database-common.hpp" using namespace std; using namespace AppStream; DatabaseWrite::DatabaseWrite () : m_rwXapianDB(0) { } DatabaseWrite::~DatabaseWrite () { if (m_rwXapianDB) { delete m_rwXapianDB; } } bool DatabaseWrite::initialize (const gchar *dbPath) { m_dbPath = string(dbPath); try { m_rwXapianDB = new Xapian::WritableDatabase (m_dbPath, Xapian::DB_CREATE_OR_OPEN); } catch (const Xapian::Error &error) { g_warning ("Exception: %s", error.get_msg ().c_str ()); return false; } return true; } bool DatabaseWrite::rebuild (GArray *apps) { string old_path = m_dbPath + "_old"; string rebuild_path = m_dbPath + "_rb"; // Create the rebuild directory if (!appstream_utils_touch_dir (rebuild_path.c_str ())) return false; // check if old unrequired version of db still exists on filesystem if (g_file_test (old_path.c_str (), G_FILE_TEST_EXISTS)) { g_warning ("Existing xapian old db was not previously cleaned: '%s'.", old_path.c_str ()); appstream_utils_delete_dir_recursive (old_path.c_str ()); } // check if old unrequired version of db still exists on filesystem if (g_file_test (rebuild_path.c_str (), G_FILE_TEST_EXISTS)) { cout << "Removing old rebuild-dir from previous database rebuild." << endl; appstream_utils_delete_dir_recursive (rebuild_path.c_str ()); } Xapian::WritableDatabase db (rebuild_path, Xapian::DB_CREATE_OR_OVERWRITE); Xapian::TermGenerator term_generator; term_generator.set_database(db); try { /* this tests if we have spelling suggestions (there must be * a better way?!?) - this is needed as inmemory does not have * spelling corrections, but it allows setting the flag and will * raise a exception much later */ db.add_spelling("test"); db.remove_spelling("test"); /* this enables the flag for it (we only reach this line if * the db supports spelling suggestions) */ term_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING); } catch (const Xapian::UnimplementedError &error) { // Ignore } for (guint i=0; i < apps->len; i++) { AppstreamAppInfo *app = g_array_index (apps, AppstreamAppInfo*, i); Xapian::Document doc; g_debug ("Adding application: %s", appstream_app_info_to_string (app)); doc.set_data (appstream_app_info_get_name (app)); // Package name string pkgname = appstream_app_info_get_pkgname (app); doc.add_value (XapianValues::PKGNAME, pkgname); doc.add_term("AP" + pkgname); if (pkgname.find ("-") != string::npos) { // we need this to work around xapian oddness string tmp = pkgname; replace (tmp.begin(), tmp.end(), '-', '_'); doc.add_term (tmp); } // add packagename as meta-data too term_generator.index_text_without_positions (pkgname, WEIGHT_PKGNAME); // Untranslated application name string appNameGeneric = appstream_app_info_get_name_original (app); doc.add_value (XapianValues::APPNAME_UNTRANSLATED, appNameGeneric); term_generator.index_text_without_positions (appNameGeneric, WEIGHT_DESKTOP_GENERICNAME); // Application name string appName = appstream_app_info_get_name (app); doc.add_value (XapianValues::APPNAME, appName); // Desktop file doc.add_value (XapianValues::DESKTOP_FILE, appstream_app_info_get_desktop_file (app)); // URL doc.add_value (XapianValues::URL_HOMEPAGE, appstream_app_info_get_homepage (app)); // Application icon doc.add_value (XapianValues::ICON, appstream_app_info_get_icon (app)); doc.add_value (XapianValues::ICON_URL, appstream_app_info_get_icon_url (app)); // Summary string appSummary = appstream_app_info_get_summary (app); doc.add_value (XapianValues::SUMMARY, appSummary); term_generator.index_text_without_positions (appSummary, WEIGHT_DESKTOP_SUMMARY); // Long description doc.add_value (XapianValues::DESCRIPTION, appstream_app_info_get_description (app)); // Categories int length = 0; gchar **categories = appstream_app_info_get_categories (app, &length); string categories_string = ""; for (uint i=0; i < length; i++) { if (categories[i] == NULL) continue; string cat = categories[i]; string tmp = cat; transform (tmp.begin (), tmp.end (), tmp.begin (), ::tolower); doc.add_term ("AC" + tmp); categories_string += cat + ";"; } doc.add_value (XapianValues::CATEGORIES, categories_string); // Add our keywords (with high priority) length = 0; gchar **keywords = appstream_app_info_get_keywords (app, &length); for (uint i=0; i < length; i++) { if (keywords[i] == NULL) continue; string kword = keywords[i]; term_generator.index_text_without_positions (kword, WEIGHT_DESKTOP_KEYWORD); } // Add screenshot information (XML data) doc.add_value (XapianValues::SCREENSHOT_DATA, appstream_app_info_dump_screenshot_data_xml (app)); // TODO: Look at the SC Xapian database - there are still some values and terms missing! // Postprocess term_generator.set_document (doc); string docData = doc.get_data (); doc.add_term ("AA" + docData); term_generator.index_text_without_positions (docData, WEIGHT_DESKTOP_NAME); db.add_document (doc); } db.set_metadata("db-schema-version", APPSTREAM_DB_SCHEMA_VERSION); db.commit (); if (g_rename (m_dbPath.c_str (), old_path.c_str ()) < 0) { g_critical ("Error while moving old database out of the way."); return false; } if (g_rename (rebuild_path.c_str (), m_dbPath.c_str ()) < 0) { g_critical ("Error while moving rebuilt database."); return false; } appstream_utils_delete_dir_recursive (old_path.c_str ()); return true; } bool DatabaseWrite::addApplication (AppstreamAppInfo *app) { // TODO return false; } <commit_msg>Improve Xapian search capabilities<commit_after>/* database-write.cpp * * Copyright (C) 2012-2014 Matthias Klumpp <[email protected]> * * Licensed under the GNU Lesser General Public License Version 3 * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #include "database-write.hpp" #include <iostream> #include <string> #include <algorithm> #include <vector> #include <sstream> #include <iterator> #include <glib/gstdio.h> #include "database-common.hpp" using namespace std; using namespace AppStream; DatabaseWrite::DatabaseWrite () : m_rwXapianDB(0) { } DatabaseWrite::~DatabaseWrite () { if (m_rwXapianDB) { delete m_rwXapianDB; } } bool DatabaseWrite::initialize (const gchar *dbPath) { m_dbPath = string(dbPath); try { m_rwXapianDB = new Xapian::WritableDatabase (m_dbPath, Xapian::DB_CREATE_OR_OPEN); } catch (const Xapian::Error &error) { g_warning ("Exception: %s", error.get_msg ().c_str ()); return false; } return true; } bool DatabaseWrite::rebuild (GArray *apps) { string old_path = m_dbPath + "_old"; string rebuild_path = m_dbPath + "_rb"; // Create the rebuild directory if (!appstream_utils_touch_dir (rebuild_path.c_str ())) return false; // check if old unrequired version of db still exists on filesystem if (g_file_test (old_path.c_str (), G_FILE_TEST_EXISTS)) { g_warning ("Existing xapian old db was not previously cleaned: '%s'.", old_path.c_str ()); appstream_utils_delete_dir_recursive (old_path.c_str ()); } // check if old unrequired version of db still exists on filesystem if (g_file_test (rebuild_path.c_str (), G_FILE_TEST_EXISTS)) { cout << "Removing old rebuild-dir from previous database rebuild." << endl; appstream_utils_delete_dir_recursive (rebuild_path.c_str ()); } Xapian::WritableDatabase db (rebuild_path, Xapian::DB_CREATE_OR_OVERWRITE); Xapian::TermGenerator term_generator; term_generator.set_database(db); try { /* this tests if we have spelling suggestions (there must be * a better way?!?) - this is needed as inmemory does not have * spelling corrections, but it allows setting the flag and will * raise a exception much later */ db.add_spelling("test"); db.remove_spelling("test"); /* this enables the flag for it (we only reach this line if * the db supports spelling suggestions) */ term_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING); } catch (const Xapian::UnimplementedError &error) { // Ignore } for (guint i=0; i < apps->len; i++) { AppstreamAppInfo *app = g_array_index (apps, AppstreamAppInfo*, i); Xapian::Document doc; term_generator.set_document (doc); g_debug ("Adding application: %s", appstream_app_info_to_string (app)); doc.set_data (appstream_app_info_get_name (app)); // Package name string pkgname = appstream_app_info_get_pkgname (app); doc.add_value (XapianValues::PKGNAME, pkgname); doc.add_term("AP" + pkgname); if (pkgname.find ("-") != string::npos) { // we need this to work around xapian oddness string tmp = pkgname; replace (tmp.begin(), tmp.end(), '-', '_'); doc.add_term (tmp); } // add packagename as meta-data too term_generator.index_text_without_positions (pkgname, WEIGHT_PKGNAME); // Untranslated application name string appNameGeneric = appstream_app_info_get_name_original (app); doc.add_value (XapianValues::APPNAME_UNTRANSLATED, appNameGeneric); term_generator.index_text_without_positions (appNameGeneric, WEIGHT_DESKTOP_GENERICNAME); // Application name string appName = appstream_app_info_get_name (app); doc.add_value (XapianValues::APPNAME, appName); // Desktop file doc.add_value (XapianValues::DESKTOP_FILE, appstream_app_info_get_desktop_file (app)); // URL doc.add_value (XapianValues::URL_HOMEPAGE, appstream_app_info_get_homepage (app)); // Application icon doc.add_value (XapianValues::ICON, appstream_app_info_get_icon (app)); doc.add_value (XapianValues::ICON_URL, appstream_app_info_get_icon_url (app)); // Summary string appSummary = appstream_app_info_get_summary (app); doc.add_value (XapianValues::SUMMARY, appSummary); term_generator.index_text_without_positions (appSummary, WEIGHT_DESKTOP_SUMMARY); // Long description string description = appstream_app_info_get_description (app); doc.add_value (XapianValues::DESCRIPTION, description); term_generator.index_text_without_positions (description, WEIGHT_DESKTOP_SUMMARY); // Categories int length = 0; gchar **categories = appstream_app_info_get_categories (app, &length); string categories_string = ""; for (uint i=0; i < length; i++) { if (categories[i] == NULL) continue; string cat = categories[i]; string tmp = cat; transform (tmp.begin (), tmp.end (), tmp.begin (), ::tolower); doc.add_term ("AC" + tmp); categories_string += cat + ";"; } doc.add_value (XapianValues::CATEGORIES, categories_string); // Add our keywords (with high priority) length = 0; gchar **keywords = appstream_app_info_get_keywords (app, &length); for (uint i=0; i < length; i++) { if (keywords[i] == NULL) continue; string kword = keywords[i]; term_generator.index_text_without_positions (kword, WEIGHT_DESKTOP_KEYWORD); } // Add screenshot information (XML data) doc.add_value (XapianValues::SCREENSHOT_DATA, appstream_app_info_dump_screenshot_data_xml (app)); // TODO: Look at the SC Xapian database - there are still some values and terms missing! // Postprocess string docData = doc.get_data (); doc.add_term ("AA" + docData); term_generator.index_text_without_positions (docData, WEIGHT_DESKTOP_NAME); db.add_document (doc); } db.set_metadata("db-schema-version", APPSTREAM_DB_SCHEMA_VERSION); db.commit (); if (g_rename (m_dbPath.c_str (), old_path.c_str ()) < 0) { g_critical ("Error while moving old database out of the way."); return false; } if (g_rename (rebuild_path.c_str (), m_dbPath.c_str ()) < 0) { g_critical ("Error while moving rebuilt database."); return false; } appstream_utils_delete_dir_recursive (old_path.c_str ()); return true; } bool DatabaseWrite::addApplication (AppstreamAppInfo *app) { // TODO return false; } <|endoftext|>
<commit_before>#include "ToolBase.h" #include "NGSD.h" #include "Exceptions.h" #include "Helper.h" class ConcreteTool : public ToolBase { Q_OBJECT public: ConcreteTool(int& argc, char *argv[]) : ToolBase(argc, argv) { } virtual void setup() { setDescription("Imports Ensembl/CCDS transcript information into NGSD."); addInfile("in", "Ensemble transcript file (download and unzip ftp://ftp.ensembl.org/pub/grch37/update/gff3/homo_sapiens/Homo_sapiens.GRCh37.87.gff3.gz).", false); //optional addFlag("all", "If set, all transcripts are imported (the default is to skip transcripts not labeled as with the 'GENCODE basic' tag)."); addFlag("test", "Uses the test database instead of on the production database."); addFlag("force", "If set, overwrites old data."); changeLog(2017, 7, 6, "Added first version"); } QMap<QByteArray, QByteArray> parseAttributes(QByteArray attributes) { QMap<QByteArray, QByteArray> output; QByteArrayList parts = attributes.split(';'); foreach(QByteArray part, parts) { int split_index = part.indexOf('='); output[part.left(split_index)] = part.mid(split_index+1); } return output; } struct TranscriptData { QByteArray name; QByteArray name_ccds; QByteArray chr; int start_coding = -1; int end_coding = -1; QByteArray strand; BedFile exons; int ngsd_gene_id; }; int addTranscript(SqlQuery& query, int gene_id, QByteArray name, QByteArray source, const TranscriptData& t_data) { //QTextStream(stdout) << "Adding transcript name=" << name << " source=" << source << " gene=" << t_data.ngsd_gene_id << " start_coding=" << t_data.start_coding << " end_coding=" << t_data.end_coding << endl; query.bindValue(0, gene_id); query.bindValue(1, name); query.bindValue(2, source); query.bindValue(3, t_data.chr); if (t_data.start_coding!=-1 && t_data.end_coding!=-1) { query.bindValue(4, t_data.start_coding); query.bindValue(5, t_data.end_coding); } else { query.bindValue(4, QVariant()); query.bindValue(5, QVariant()); } query.bindValue(6, t_data.strand); query.exec(); return query.lastInsertId().toInt(); } void addExons(SqlQuery& query, int transcript_id, const BedFile& exons) { //QTextStream(stdout) << " " << exons.count() << endl; for (int i=0; i<exons.count(); ++i) { //out << " Adding exon start=" << exons[i].start() << " end=" <<exons[i].end() << endl; query.bindValue(0, transcript_id); query.bindValue(1, exons[i].start()); query.bindValue(2, exons[i].end()); query.exec(); } } virtual void main() { //init NGSD db(getFlag("test")); QTextStream out(stdout); bool all = getFlag("all"); //check tables exist db.tableExists("gene"); db.tableExists("gene_alias"); db.tableExists("gene_transcript"); db.tableExists("gene_exon"); //clear tables if not empty if (!db.tableEmpty("gene_transcript") || !db.tableEmpty("gene_exon")) { if (getFlag("force")) { db.clearTable("gene_exon"); db.clearTable("gene_transcript"); } else { THROW(DatabaseException, "Tables already contain data! Use '-force' to overwrite old data!"); } } //prepare queries SqlQuery q_trans = db.getQuery(); q_trans.prepare("INSERT INTO gene_transcript (gene_id, name, source, chromosome, start_coding, end_coding, strand) VALUES (:0, :1, :2, :3, :4, :5, :6);"); SqlQuery q_exon = db.getQuery(); q_exon.prepare("INSERT INTO gene_exon (transcript_id, start, end) VALUES (:0, :1, :2);"); //parse input - format description at https://www.gencodegenes.org/data_format.html and http://www.ensembl.org/info/website/upload/gff3.html QMap<QByteArray, int> gene_ensemble2ngsd; QMap<QByteArray, TranscriptData> transcripts; QSet<QByteArray> ccds_transcripts_added; auto fp = Helper::openFileForReading(getInfile("in")); while(!fp->atEnd()) { QByteArray line = fp->readLine().trimmed(); if (line.isEmpty()) continue; //section end => commit data if (line=="###") { //import data auto it = transcripts.begin(); while(it!=transcripts.end()) { //add Ensembl transcript TranscriptData& t_data = it.value(); int trans_id = addTranscript(q_trans, t_data.ngsd_gene_id, t_data.name , "ensembl", t_data); //add exons t_data.exons.merge(); addExons(q_exon, trans_id, t_data.exons); //add CCDS transcript as well (only once) if (t_data.name_ccds!="" && !ccds_transcripts_added.contains(t_data.name_ccds)) { int trans_id_ccds = addTranscript(q_trans, t_data.ngsd_gene_id, t_data.name_ccds , "ccds", t_data); //add exons (only coding part) BedFile coding_part; coding_part.append(BedLine(t_data.exons[0].chr() ,t_data.start_coding, t_data.end_coding)); t_data.exons.intersect(coding_part); addExons(q_exon, trans_id_ccds, t_data.exons); ccds_transcripts_added.insert(t_data.name_ccds); } ++it; } //clear cache gene_ensemble2ngsd.clear(); transcripts.clear(); continue; } //skip header lines if (line.startsWith("#")) continue; QByteArrayList parts = line.split('\t'); QByteArray type = parts[2]; QMap<QByteArray, QByteArray> data = parseAttributes(parts[8]); //gene line if (data.contains("gene_id")) { QByteArray gene = data["Name"]; //transform gene names to approved gene IDs int ngsd_gene_id = db.geneToApprovedID(gene); if (ngsd_gene_id==-1) { out << "ERROR " << data["gene_id"] << "/" << gene << ": no approved gene names found." << endl; continue; } gene_ensemble2ngsd[data["ID"]] = ngsd_gene_id; } //transcript line else if (data.contains("transcript_id")) { if (all || data.value("tag")=="basic") { TranscriptData tmp; tmp.name = data["transcript_id"]; tmp.name_ccds = data.value("ccdsid", ""); tmp.chr = parts[0]; tmp.strand = parts[6]; tmp.ngsd_gene_id = gene_ensemble2ngsd[data["Parent"]]; transcripts[data["ID"]] = tmp; } } //exon lines else if (type=="CDS" || type=="exon" || type=="three_prime_UTR" || type=="five_prime_UTR" ) { QByteArray parent_id = data["Parent"]; //skip exons of unhandled transcripts (not GENCODE basic) if (!transcripts.contains(parent_id)) continue; TranscriptData& t_data = transcripts[parent_id]; //check chromosome matches QByteArray chr = parts[0]; if (chr!=t_data.chr) { THROW(FileParseException, "Chromosome mismach between transcript and exon!"); } //update coding start/end int start = Helper::toInt(parts[3], "start position"); int end = Helper::toInt(parts[4], "end position"); if (type=="CDS") { t_data.start_coding = (t_data.start_coding==-1) ? start : std::min(start, t_data.start_coding); t_data.end_coding = (t_data.end_coding==-1) ? end : std::max(end, t_data.end_coding); } //add coding exon t_data.exons.append(BedLine(chr, start, end)); } } } }; #include "main.moc" int main(int argc, char *argv[]) { ConcreteTool tool(argc, argv); return tool.execute(); } <commit_msg>NGSDImportEnsembl: fixed some parsing errors<commit_after>#include "ToolBase.h" #include "NGSD.h" #include "Exceptions.h" #include "Helper.h" class ConcreteTool : public ToolBase { Q_OBJECT public: ConcreteTool(int& argc, char *argv[]) : ToolBase(argc, argv) { } virtual void setup() { setDescription("Imports Ensembl/CCDS transcript information into NGSD."); addInfile("in", "Ensemble transcript file (download and unzip ftp://ftp.ensembl.org/pub/grch37/update/gff3/homo_sapiens/Homo_sapiens.GRCh37.87.gff3.gz).", false); //optional addFlag("all", "If set, all transcripts are imported (the default is to skip transcripts not labeled as with the 'GENCODE basic' tag)."); addFlag("test", "Uses the test database instead of on the production database."); addFlag("force", "If set, overwrites old data."); changeLog(2017, 7, 6, "Added first version"); } QMap<QByteArray, QByteArray> parseAttributes(QByteArray attributes) { QMap<QByteArray, QByteArray> output; QByteArrayList parts = attributes.split(';'); foreach(QByteArray part, parts) { int split_index = part.indexOf('='); output[part.left(split_index)] = part.mid(split_index+1); } return output; } struct TranscriptData { QByteArray name; QByteArray name_ccds; QByteArray chr; int start_coding = -1; int end_coding = -1; QByteArray strand; BedFile exons; int ngsd_gene_id; }; int addTranscript(SqlQuery& query, int gene_id, QByteArray name, QByteArray source, const TranscriptData& t_data) { //QTextStream(stdout) << "Adding transcript name=" << name << " source=" << source << " gene=" << t_data.ngsd_gene_id << " start_coding=" << t_data.start_coding << " end_coding=" << t_data.end_coding << endl; query.bindValue(0, gene_id); query.bindValue(1, name); query.bindValue(2, source); query.bindValue(3, t_data.chr); if (t_data.start_coding!=-1 && t_data.end_coding!=-1) { query.bindValue(4, t_data.start_coding); query.bindValue(5, t_data.end_coding); } else { query.bindValue(4, QVariant()); query.bindValue(5, QVariant()); } query.bindValue(6, t_data.strand); query.exec(); return query.lastInsertId().toInt(); } void addExons(SqlQuery& query, int transcript_id, const BedFile& exons) { //QTextStream(stdout) << " " << exons.count() << endl; for (int i=0; i<exons.count(); ++i) { //out << " Adding exon start=" << exons[i].start() << " end=" <<exons[i].end() << endl; query.bindValue(0, transcript_id); query.bindValue(1, exons[i].start()); query.bindValue(2, exons[i].end()); query.exec(); } } virtual void main() { //init NGSD db(getFlag("test")); QTextStream out(stdout); bool all = getFlag("all"); //check tables exist db.tableExists("gene"); db.tableExists("gene_alias"); db.tableExists("gene_transcript"); db.tableExists("gene_exon"); //clear tables if not empty if (!db.tableEmpty("gene_transcript") || !db.tableEmpty("gene_exon")) { if (getFlag("force")) { db.clearTable("gene_exon"); db.clearTable("gene_transcript"); } else { THROW(DatabaseException, "Tables already contain data! Use '-force' to overwrite old data!"); } } //prepare queries SqlQuery q_trans = db.getQuery(); q_trans.prepare("INSERT INTO gene_transcript (gene_id, name, source, chromosome, start_coding, end_coding, strand) VALUES (:0, :1, :2, :3, :4, :5, :6);"); SqlQuery q_exon = db.getQuery(); q_exon.prepare("INSERT INTO gene_exon (transcript_id, start, end) VALUES (:0, :1, :2);"); //parse input - format description at https://www.gencodegenes.org/data_format.html and http://www.ensembl.org/info/website/upload/gff3.html QMap<QByteArray, int> gene_ensemble2ngsd; QMap<QByteArray, TranscriptData> transcripts; QSet<QByteArray> ccds_transcripts_added; auto fp = Helper::openFileForReading(getInfile("in")); while(!fp->atEnd()) { QByteArray line = fp->readLine().trimmed(); if (line.isEmpty()) continue; //section end => commit data if (line=="###") { //import data auto it = transcripts.begin(); while(it!=transcripts.end()) { //add Ensembl transcript TranscriptData& t_data = it.value(); int trans_id = addTranscript(q_trans, t_data.ngsd_gene_id, t_data.name , "ensembl", t_data); //add exons t_data.exons.merge(); addExons(q_exon, trans_id, t_data.exons); //add CCDS transcript as well (only once) if (t_data.name_ccds!="" && !ccds_transcripts_added.contains(t_data.name_ccds)) { int trans_id_ccds = addTranscript(q_trans, t_data.ngsd_gene_id, t_data.name_ccds , "ccds", t_data); //add exons (only coding part) BedFile coding_part; coding_part.append(BedLine(t_data.exons[0].chr() ,t_data.start_coding, t_data.end_coding)); t_data.exons.intersect(coding_part); addExons(q_exon, trans_id_ccds, t_data.exons); ccds_transcripts_added.insert(t_data.name_ccds); } ++it; } //clear cache gene_ensemble2ngsd.clear(); transcripts.clear(); continue; } //skip header lines if (line.startsWith("#")) continue; QByteArrayList parts = line.split('\t'); QByteArray type = parts[2]; QMap<QByteArray, QByteArray> data = parseAttributes(parts[8]); //gene line if (data.contains("gene_id")) { QByteArray gene = data["Name"]; //transform gene names to approved gene IDs int ngsd_gene_id = db.geneToApprovedID(gene); if (ngsd_gene_id==-1) { out << "Notice: Gene " << data["gene_id"] << "/" << gene << " without HGNC-approved name is skipped." << endl; continue; } if (!Chromosome(parts[0]).isNonSpecial()) { out << "Notice: Gene " << data["gene_id"] << "/" << gene << " on special chromosome " << parts[0] << " is skipped." << endl; continue; } gene_ensemble2ngsd[data["ID"]] = ngsd_gene_id; } //transcript line else if (data.contains("transcript_id")) { if (all || data.value("tag")=="basic") { QByteArray parent_id = data["Parent"]; //skip transcripts of unhandled genes (e.g. no HGNC gene name) if (!gene_ensemble2ngsd.contains(parent_id)) continue; TranscriptData tmp; tmp.name = data["transcript_id"]; tmp.name_ccds = data.value("ccdsid", ""); tmp.chr = parts[0]; tmp.strand = parts[6]; tmp.ngsd_gene_id = gene_ensemble2ngsd[parent_id]; transcripts[data["ID"]] = tmp; } } //exon lines else if (type=="CDS" || type=="exon" || type=="three_prime_UTR" || type=="five_prime_UTR" ) { QByteArray parent_id = data["Parent"]; //skip exons of unhandled transcripts (not GENCODE basic) if (!transcripts.contains(parent_id)) continue; TranscriptData& t_data = transcripts[parent_id]; //check chromosome matches QByteArray chr = parts[0]; if (chr!=t_data.chr) { THROW(FileParseException, "Chromosome mismach between transcript and exon!"); } //update coding start/end int start = Helper::toInt(parts[3], "start position"); int end = Helper::toInt(parts[4], "end position"); if (type=="CDS") { t_data.start_coding = (t_data.start_coding==-1) ? start : std::min(start, t_data.start_coding); t_data.end_coding = (t_data.end_coding==-1) ? end : std::max(end, t_data.end_coding); } //add coding exon t_data.exons.append(BedLine(chr, start, end)); } } } }; #include "main.moc" int main(int argc, char *argv[]) { ConcreteTool tool(argc, argv); return tool.execute(); } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2017) #ifndef DUNE_GDT_SPACES_RT_DEFAULT_HH #define DUNE_GDT_SPACES_RT_DEFAULT_HH #include <memory> #include <vector> #include <dune/geometry/referenceelements.hh> #include <dune/geometry/type.hh> #include <dune/grid/common/rangegenerators.hh> #include <dune/localfunctions/raviartthomas.hh> #include <dune/localfunctions/common/virtualinterface.hh> #include <dune/localfunctions/common/virtualwrappers.hh> #include <dune/xt/common/exceptions.hh> #include <dune/xt/common/numeric_cast.hh> #include <dune/gdt/spaces/basefunctionset/interface.hh> #include <dune/gdt/spaces/mapper/default.hh> #include <dune/gdt/spaces/rt/interface.hh> namespace Dune { namespace GDT { // forwards, required for the traits template <class E, class R = double> class RaviartThomasBasefunctionSet; template <class GL, int p, class R = double> class RtSpace; namespace internal { template <class E, class R> class RaviartThomasBasefunctionSetTraits { using LocalFunctionTraits = XT::Functions::LocalfunctionSetInterface<E, typename E::Geometry::ctype, E::dimension, R, E::dimension>; public: using derived_type = RaviartThomasBasefunctionSet<E, R>; using EntityType = E; using BackendType = RaviartThomasSimplexLocalFiniteElement<E::dimension, typename E::Geometry::ctype, R>; }; template <class GL, int p, class R> class RtSpaceTraits { static_assert(XT::Grid::is_layer<GL>::value, ""); static_assert(p == 0, "Not implemented yet!"); public: using derived_type = RtSpace<GL, p, R>; static const constexpr int polOrder = p; static const constexpr size_t dimDomain = GL::dimension; static const constexpr size_t dimRange = dimDomain; static const constexpr size_t dimRangeCols = 1; static const constexpr bool continuous = false; using GridLayerType = GL; using BaseFunctionSetType = RaviartThomasBasefunctionSet<XT::Grid::extract_entity_t<GL>, R>; using MapperType = FixedOrderMultipleCodimMultipleGeomTypeMapper<GL, RaviartThomasSimplexLocalFiniteElement<dimDomain, typename GL::ctype, R>>; using RangeFieldType = R; using BackendType = double; static const constexpr XT::Grid::Backends layer_backend = XT::Grid::Backends::view; using CommunicatorType = double; }; // class RtSpaceTraits } // namespace internal template <class E, class R> class RaviartThomasBasefunctionSet : public BaseFunctionSetInterface<internal::RaviartThomasBasefunctionSetTraits<E, R>, typename E::Geometry::ctype, E::dimension, R, E::dimension, 1> { public: using Traits = internal::RaviartThomasBasefunctionSetTraits<E, R>; private: using BaseType = BaseFunctionSetInterface<Traits, typename E::Geometry::ctype, E::dimension, R, E::dimension, 1>; using ThisType = RaviartThomasBasefunctionSet<E, R>; public: using typename BaseType::BackendType; using typename BaseType::EntityType; using typename BaseType::DomainType; using typename BaseType::RangeType; using typename BaseType::JacobianRangeType; using typename BaseType::D; using BaseType::d; RaviartThomasBasefunctionSet(const EntityType& en, const BackendType& finite_element, const std::vector<bool>& switches) : BaseType(en) , finite_element_(finite_element) , switches_(switches) { if (switches_.size() != finite_element_.size()) DUNE_THROW(XT::Common::Exceptions::shapes_do_not_match, "finite_element.size() = " << finite_element_.size() << "\n switches.size() = " << switches_.size()); } RaviartThomasBasefunctionSet(const ThisType&) = default; RaviartThomasBasefunctionSet(ThisType&&) = default; ThisType& operator=(const ThisType&) = delete; ThisType& operator=(ThisType&&) = delete; const BackendType& backend() const { return finite_element_; } size_t size() const override final { return finite_element_.localBasis().size(); } size_t order(const XT::Common::Parameter& = {}) const override final { return finite_element_.localBasis().order(); } using BaseType::evaluate; void evaluate(const DomainType& xx, std::vector<RangeType>& ret, const XT::Common::Parameter& /*mu*/ = {}) const override final { assert(this->is_a_valid_point(xx)); // evaluate shape functions finite_element_.localBasis().evaluateFunction(xx, ret); // flip shape functions to ensure continuity of normal component for (size_t ii = 0; ii < finite_element_.localBasis().size(); ++ii) if (switches_[ii]) ret[ii] *= -1; // apply piola transformation const auto J_T = this->entity().geometry().jacobianTransposed(xx); const auto det_J_T = std::abs(J_T.determinant()); RangeType tmp_value; for (size_t ii = 0; ii < finite_element_.localBasis().size(); ++ii) { J_T.mtv(ret[ii], tmp_value); tmp_value /= det_J_T; ret[ii] = tmp_value; } } // ... evaluate(...) using BaseType::jacobian; void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret, const XT::Common::Parameter& /*mu*/ = {}) const override final { assert(this->is_a_valid_point(xx)); // evaluate jacobian of shape functions finite_element_.localBasis().evaluateJacobian(xx, ret); // flip shape functions to ensure continuity of normal component for (size_t ii = 0; ii < finite_element_.localBasis().size(); ++ii) if (switches_[ii]) ret[ii] *= -1; // apply piola transformation const auto J_T = this->entity().geometry().jacobianTransposed(xx); const auto det_J_T = std::abs(J_T.determinant()); const auto J_inv_T = this->entity().geometry().jacobianInverseTransposed(xx); auto tmp_jacobian_row = ret[0][0]; for (size_t ii = 0; ii < finite_element_.localBasis().size(); ++ii) { for (size_t jj = 0; jj < d; ++jj) { J_inv_T.mtv(ret[ii][jj], tmp_jacobian_row); J_T.mtv(tmp_jacobian_row, ret[ii][jj]); ret[ii][jj] /= det_J_T; } } } // ... jacobian(...) private: const BackendType& finite_element_; const std::vector<bool>& switches_; }; // class RaviartThomasBasefunctionSet template <class GL, int p, class R> class RtSpace : public RtSpaceInterface<internal::RtSpaceTraits<GL, p, R>, GL::dimension, GL::dimension> { public: using Traits = internal::RtSpaceTraits<GL, p, R>; private: using BaseType = RtSpaceInterface<Traits, GL::dimension, GL::dimension>; using ThisType = RtSpace<GL, p, R>; using D = typename GL::ctype; static const constexpr size_t d = BaseType::dimDomain; using FiniteElementType = RaviartThomasSimplexLocalFiniteElement<d, D, R>; public: using typename BaseType::GridLayerType; using typename BaseType::EntityType; using typename BaseType::MapperType; using typename BaseType::BaseFunctionSetType; RtSpace(GridLayerType grd_lr) : grid_layer_(grd_lr) , communicator_(0) , backend_(0) , finite_elements_(new std::map<GeometryType, std::shared_ptr<FiniteElementType>>()) , local_DoF_indices_(new std::map<GeometryType, std::vector<size_t>>()) , switches_(new std::vector<std::vector<bool>>(grid_layer_.indexSet().size(0))) , mapper_(nullptr) { const auto& index_set = grid_layer_.indexSet(); // create finite elements for (auto&& geometry_type : index_set.types(0)) { auto finite_element = std::make_shared<FiniteElementType>(geometry_type, p); finite_elements_->insert(std::make_pair(geometry_type, finite_element)); // this is only valid for p0 elements local_DoF_indices_->insert(std::make_pair(geometry_type, std::vector<size_t>(finite_element->size()))); } // compute local-key-to-intersection relationship for (const auto& geometry_type_and_finite_element_ptr : *finite_elements_) { const auto& geometry_type = geometry_type_and_finite_element_ptr.first; const auto& finite_element = *geometry_type_and_finite_element_ptr.second; const auto& coeffs = finite_element.localCoefficients(); auto& local_key_to_intersection_map = (*local_DoF_indices_)[geometry_type]; for (size_t ii = 0; ii < coeffs.size(); ++ii) { const auto& local_key = coeffs.localKey(ii); if (local_key.index() != 0) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen for p0!"); if (local_key.codim() != 1) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen for p0 on simplices!"); local_key_to_intersection_map[ii] = local_key.subEntity(); } } // compute switches to ensure continuity of the normal component for (auto&& entity : elements(grid_layer_)) { const auto geometry_type = entity.geometry().type(); const auto& finite_element = *finite_elements_->at(geometry_type); const auto& coeffs = finite_element.localCoefficients(); const auto entity_index = index_set.index(entity); (*switches_)[entity_index] = std::vector<bool>(coeffs.size(), false); auto& local_switches = (*switches_)[entity_index]; for (auto&& intersection : intersections(grid_layer_, entity)) { if (intersection.neighbor() && entity_index < index_set.index(intersection.outside())) { const auto intersection_index = XT::Common::numeric_cast<unsigned int>(intersection.indexInInside()); for (size_t ii = 0; ii < coeffs.size(); ++ii) { const auto& local_key = coeffs.localKey(ii); const auto DoF_subentity_index = local_key.subEntity(); if (local_key.codim() == 1 && DoF_subentity_index == intersection_index) local_switches[DoF_subentity_index] = true; } } } } // create mapper mapper_ = std::make_shared<MapperType>(grid_layer_, finite_elements_); } // RtSpace(...) RtSpace(const ThisType&) = default; RtSpace(ThisType&&) = default; ThisType& operator=(const ThisType&) = delete; ThisType& operator=(ThisType&&) = delete; const GridLayerType& grid_layer() const { return grid_layer_; } const double& backend() const { return backend_; } const MapperType& mapper() const { return *mapper_; } BaseFunctionSetType base_function_set(const EntityType& entity) const { const auto finite_element_search_result = finite_elements_->find(entity.geometry().type()); if (finite_element_search_result == finite_elements_->end()) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen after the checks in the ctor, the grid layer did not report all geometry types!" "\n entity.geometry().type() = " << entity.geometry().type()); const auto& finite_element = *finite_element_search_result->second; return BaseFunctionSetType(entity, finite_element, (*switches_)[grid_layer_.indexSet().index(entity)]); } double& communicator() const { DUNE_THROW(NotImplemented, ""); return communicator_; } // this makes sense only for for p0 (and only on simplices?) std::vector<size_t> local_DoF_indices(const EntityType& entity) const { const auto search_result = local_DoF_indices_->find(entity.geometry().type()); if (search_result == local_DoF_indices_->end()) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen after the checks in the ctor, the grid layer did not report all geometry types!" "\n entity.geometry().type() = " << entity.geometry().type()); return search_result->second; } // ... local_DoF_indices(...) private: const GridLayerType grid_layer_; mutable double communicator_; const double backend_; std::shared_ptr<std::map<GeometryType, std::shared_ptr<FiniteElementType>>> finite_elements_; std::shared_ptr<std::map<GeometryType, std::vector<size_t>>> local_DoF_indices_; std::shared_ptr<std::vector<std::vector<bool>>> switches_; std::shared_ptr<MapperType> mapper_; }; // class RtSpace } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_RT_DEFAULT_HH <commit_msg>[spaces.rt] rescale shape functions, space is only valid for simplices<commit_after>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2017) #ifndef DUNE_GDT_SPACES_RT_DEFAULT_HH #define DUNE_GDT_SPACES_RT_DEFAULT_HH #include <memory> #include <vector> #include <dune/common/typetraits.hh> #include <dune/geometry/referenceelements.hh> #include <dune/geometry/type.hh> #include <dune/grid/common/capabilities.hh> #include <dune/grid/common/rangegenerators.hh> #include <dune/localfunctions/raviartthomas.hh> #include <dune/xt/common/exceptions.hh> #include <dune/xt/common/numeric_cast.hh> #include <dune/gdt/spaces/basefunctionset/interface.hh> #include <dune/gdt/spaces/mapper/default.hh> #include <dune/gdt/spaces/rt/interface.hh> namespace Dune { namespace GDT { // forwards, required for the traits template <class E, class R = double> class RaviartThomasBasefunctionSet; template <class GL, int p, class R = double> class RtSpace; namespace internal { template <class E, class R> class RaviartThomasBasefunctionSetTraits { using LocalFunctionTraits = XT::Functions::LocalfunctionSetInterface<E, typename E::Geometry::ctype, E::dimension, R, E::dimension>; public: using derived_type = RaviartThomasBasefunctionSet<E, R>; using EntityType = E; using BackendType = RaviartThomasSimplexLocalFiniteElement<E::dimension, typename E::Geometry::ctype, R>; }; template <class GL, int p, class R> class RtSpaceTraits { static_assert(XT::Grid::is_layer<GL>::value, ""); static_assert(p == 0, "Not implemented yet!"); using G = XT::Grid::extract_grid_t<GL>; static_assert(Capabilities::hasSingleGeometryType<G>::v && Capabilities::hasSingleGeometryType<G>::topologyId == Impl::SimplexTopology<GL::dimension>::type::id, "Not Implemented yet!"); public: using derived_type = RtSpace<GL, p, R>; static const constexpr int polOrder = p; static const constexpr size_t dimDomain = GL::dimension; static const constexpr size_t dimRange = dimDomain; static const constexpr size_t dimRangeCols = 1; static const constexpr bool continuous = false; using GridLayerType = GL; using BaseFunctionSetType = RaviartThomasBasefunctionSet<XT::Grid::extract_entity_t<GL>, R>; using MapperType = FixedOrderMultipleCodimMultipleGeomTypeMapper<GL, RaviartThomasSimplexLocalFiniteElement<dimDomain, typename GL::ctype, R>>; using RangeFieldType = R; using BackendType = double; static const constexpr XT::Grid::Backends layer_backend = XT::Grid::Backends::view; using CommunicatorType = double; }; // class RtSpaceTraits } // namespace internal template <class E, class R> class RaviartThomasBasefunctionSet : public BaseFunctionSetInterface<internal::RaviartThomasBasefunctionSetTraits<E, R>, typename E::Geometry::ctype, E::dimension, R, E::dimension, 1> { public: using Traits = internal::RaviartThomasBasefunctionSetTraits<E, R>; private: using BaseType = BaseFunctionSetInterface<Traits, typename E::Geometry::ctype, E::dimension, R, E::dimension, 1>; using ThisType = RaviartThomasBasefunctionSet<E, R>; public: using typename BaseType::BackendType; using typename BaseType::EntityType; using typename BaseType::DomainType; using typename BaseType::RangeType; using typename BaseType::JacobianRangeType; using BaseType::d; RaviartThomasBasefunctionSet(const EntityType& en, const BackendType& finite_element, const std::vector<R>& switches) : BaseType(en) , finite_element_(finite_element) , switches_(switches) { if (switches_.size() != finite_element_.size()) DUNE_THROW(XT::Common::Exceptions::shapes_do_not_match, "finite_element.size() = " << finite_element_.size() << "\n switches.size() = " << switches_.size()); } RaviartThomasBasefunctionSet(const ThisType&) = default; RaviartThomasBasefunctionSet(ThisType&&) = default; ThisType& operator=(const ThisType&) = delete; ThisType& operator=(ThisType&&) = delete; const BackendType& backend() const { return finite_element_; } size_t size() const override final { return finite_element_.localBasis().size(); } size_t order(const XT::Common::Parameter& /*mu*/ = {}) const override final { return finite_element_.localBasis().order(); } using BaseType::evaluate; void evaluate(const DomainType& xx, std::vector<RangeType>& ret, const XT::Common::Parameter& /*mu*/ = {}) const override final { assert(this->is_a_valid_point(xx)); // evaluate shape functions finite_element_.localBasis().evaluateFunction(xx, ret); // flip and scale shape functions to ensure // - continuity of normal component and // - to ensure basis*integrationElementNormal = 1 for (size_t ii = 0; ii < finite_element_.localBasis().size(); ++ii) ret[ii] *= switches_[ii]; // apply piola transformation const auto J_T = this->entity().geometry().jacobianTransposed(xx); const auto det_J_T = std::abs(J_T.determinant()); RangeType tmp_value; for (size_t ii = 0; ii < finite_element_.localBasis().size(); ++ii) { J_T.mtv(ret[ii], tmp_value); tmp_value /= det_J_T; ret[ii] = tmp_value; } } // ... evaluate(...) using BaseType::jacobian; void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret, const XT::Common::Parameter& /*mu*/ = {}) const override final { assert(this->is_a_valid_point(xx)); // evaluate jacobian of shape functions finite_element_.localBasis().evaluateJacobian(xx, ret); // flip and scale shape functions to ensure // - continuity of normal component and // - to ensure basis*integrationElementNormal = 1 for (size_t ii = 0; ii < finite_element_.localBasis().size(); ++ii) ret[ii] *= switches_[ii]; // apply piola transformation const auto J_T = this->entity().geometry().jacobianTransposed(xx); const auto det_J_T = std::abs(J_T.determinant()); const auto J_inv_T = this->entity().geometry().jacobianInverseTransposed(xx); auto tmp_jacobian_row = ret[0][0]; for (size_t ii = 0; ii < finite_element_.localBasis().size(); ++ii) { for (size_t jj = 0; jj < d; ++jj) { J_inv_T.mtv(ret[ii][jj], tmp_jacobian_row); J_T.mtv(tmp_jacobian_row, ret[ii][jj]); ret[ii][jj] /= det_J_T; } } } // ... jacobian(...) private: const BackendType& finite_element_; const std::vector<R>& switches_; }; // class RaviartThomasBasefunctionSet template <class GL, int p, class R> class RtSpace : public RtSpaceInterface<internal::RtSpaceTraits<GL, p, R>, GL::dimension, GL::dimension> { public: using Traits = internal::RtSpaceTraits<GL, p, R>; private: using BaseType = RtSpaceInterface<Traits, GL::dimension, GL::dimension>; using ThisType = RtSpace<GL, p, R>; using D = typename GL::ctype; static const constexpr size_t d = BaseType::dimDomain; using FiniteElementType = RaviartThomasSimplexLocalFiniteElement<d, D, R>; public: using typename BaseType::GridLayerType; using typename BaseType::EntityType; using typename BaseType::MapperType; using typename BaseType::BaseFunctionSetType; RtSpace(GridLayerType grd_lr) : grid_layer_(grd_lr) , communicator_(0) , backend_(0) , finite_elements_(new std::map<GeometryType, std::shared_ptr<FiniteElementType>>()) , geometry_to_local_DoF_indices_map_(new std::map<GeometryType, std::vector<size_t>>()) , switches_(new std::vector<std::vector<R>>(grid_layer_.indexSet().size(0))) , mapper_(nullptr) { const auto& index_set = grid_layer_.indexSet(); // create finite elements for (auto&& geometry_type : index_set.types(0)) { auto finite_element = std::make_shared<FiniteElementType>(geometry_type, p); finite_elements_->insert(std::make_pair(geometry_type, finite_element)); // this is only valid for p0 elements geometry_to_local_DoF_indices_map_->insert( std::make_pair(geometry_type, std::vector<size_t>(finite_element->size()))); } // compute local-key-to-intersection relationship for (const auto& geometry_type_and_finite_element_ptr : *finite_elements_) { const auto& geometry_type = geometry_type_and_finite_element_ptr.first; const auto& finite_element = *geometry_type_and_finite_element_ptr.second; const auto& coeffs = finite_element.localCoefficients(); auto& local_key_to_intersection_map = geometry_to_local_DoF_indices_map_->at(geometry_type); for (size_t ii = 0; ii < coeffs.size(); ++ii) { const auto& local_key = coeffs.localKey(ii); if (local_key.index() != 0) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen for p0!"); if (local_key.codim() != 1) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen for p0!"); local_key_to_intersection_map[ii] = local_key.subEntity(); } } // compute scaling to ensure basis*integrationElementNormal = 1 std::map<GeometryType, std::vector<R>> geometry_to_scaling_factors_map; for (const auto& geometry_type_and_finite_element_ptr : *finite_elements_) { const auto& geometry_type = geometry_type_and_finite_element_ptr.first; const auto& finite_element = *geometry_type_and_finite_element_ptr.second; const auto& shape_functions = finite_element.localBasis(); std::vector<typename BaseFunctionSetType::RangeType> shape_functions_evaluations(shape_functions.size()); const auto& reference_element = ReferenceElements<D, d>::general(geometry_type); const auto num_intersections = reference_element.size(1); geometry_to_scaling_factors_map.insert(std::make_pair(geometry_type, std::vector<R>(num_intersections, R(1.)))); auto& scaling_factors = geometry_to_scaling_factors_map.at(geometry_type); const auto& DoF_indices = geometry_to_local_DoF_indices_map_->at(geometry_type); for (auto&& intersection_index : XT::Common::value_range(num_intersections)) { const auto& normal = reference_element.integrationOuterNormal(intersection_index); const auto& intersection_center = reference_element.position(intersection_index, 1); const auto DoF_index = DoF_indices[intersection_index]; shape_functions.evaluateFunction(intersection_center, shape_functions_evaluations); scaling_factors[intersection_index] /= shape_functions_evaluations[DoF_index] * normal; } } // compute switches (as signs of the scaling factor) to ensure continuity of the normal component for (auto&& entity : elements(grid_layer_)) { const auto geometry_type = entity.geometry().type(); const auto& finite_element = *finite_elements_->at(geometry_type); const auto& coeffs = finite_element.localCoefficients(); const auto entity_index = index_set.index(entity); (*switches_)[entity_index] = geometry_to_scaling_factors_map.at(geometry_type); auto& local_switches = switches_->at(entity_index); for (auto&& intersection : intersections(grid_layer_, entity)) { if (intersection.neighbor() && entity_index < index_set.index(intersection.outside())) { const auto intersection_index = XT::Common::numeric_cast<unsigned int>(intersection.indexInInside()); for (size_t ii = 0; ii < coeffs.size(); ++ii) { const auto& local_key = coeffs.localKey(ii); const auto DoF_subentity_index = local_key.subEntity(); if (local_key.codim() == 1 && DoF_subentity_index == intersection_index) local_switches[DoF_subentity_index] *= -1.; } } } } // create mapper mapper_ = std::make_shared<MapperType>(grid_layer_, finite_elements_); } // RtSpace(...) RtSpace(const ThisType&) = default; RtSpace(ThisType&&) = default; ThisType& operator=(const ThisType&) = delete; ThisType& operator=(ThisType&&) = delete; const GridLayerType& grid_layer() const { return grid_layer_; } const double& backend() const { return backend_; } const MapperType& mapper() const { return *mapper_; } BaseFunctionSetType base_function_set(const EntityType& entity) const { const auto finite_element_search_result = finite_elements_->find(entity.geometry().type()); if (finite_element_search_result == finite_elements_->end()) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen after the checks in the ctor, the grid layer did not report all geometry types!" "\n entity.geometry().type() = " << entity.geometry().type()); const auto& finite_element = *finite_element_search_result->second; return BaseFunctionSetType(entity, finite_element, (*switches_)[grid_layer_.indexSet().index(entity)]); } double& communicator() const { DUNE_THROW(NotImplemented, ""); return communicator_; } // this makes sense only for for p0 (and only on simplices?) std::vector<size_t> local_DoF_indices(const EntityType& entity) const { const auto search_result = geometry_to_local_DoF_indices_map_->find(entity.geometry().type()); if (search_result == geometry_to_local_DoF_indices_map_->end()) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen after the checks in the ctor, the grid layer did not report all geometry types!" "\n entity.geometry().type() = " << entity.geometry().type()); return search_result->second; } // ... local_DoF_indices(...) private: const GridLayerType grid_layer_; mutable double communicator_; const double backend_; std::shared_ptr<std::map<GeometryType, std::shared_ptr<FiniteElementType>>> finite_elements_; std::shared_ptr<std::map<GeometryType, std::vector<size_t>>> geometry_to_local_DoF_indices_map_; std::shared_ptr<std::vector<std::vector<R>>> switches_; std::shared_ptr<MapperType> mapper_; }; // class RtSpace } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_RT_DEFAULT_HH <|endoftext|>
<commit_before>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/Sprite.hpp> #include <Nazara/Graphics/AbstractViewer.hpp> #include <memory> #include <Nazara/Graphics/Debug.hpp> NzSprite::NzSprite() : m_boundingVolume(NzBoundingVolumef::Null()), m_color(NzColor::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f), m_boundingVolumeUpdated(true), m_verticesUpdated(false) { } NzSprite::NzSprite(NzTexture* texture) : m_boundingVolume(NzBoundingVolumef::Null()), m_color(NzColor::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_verticesUpdated(false) { if (texture) { m_material = new NzMaterial; m_material->SetPersistent(false); m_material->SetDiffuseMap(texture); if (texture->IsValid()) m_size.Set(texture->GetWidth(), texture->GetHeight()); else m_size.Set(64.f, 64.f); m_boundingVolumeUpdated = false; } else { m_size.Set(64.f, 64.f); m_boundingVolumeUpdated = true; } } NzSprite::NzSprite(const NzSprite& sprite) : NzSceneNode(sprite), m_boundingVolume(sprite.m_boundingVolume), m_material(sprite.m_material), m_textureCoords(sprite.m_textureCoords), m_size(sprite.m_size), m_vertices(sprite.m_vertices), m_boundingVolumeUpdated(sprite.m_boundingVolumeUpdated), m_verticesUpdated(sprite.m_verticesUpdated) { SetParent(sprite); } NzSprite::NzSprite(NzSprite&& sprite) : NzSceneNode(sprite), m_boundingVolume(sprite.m_boundingVolume), m_material(std::move(sprite.m_material)), m_textureCoords(sprite.m_textureCoords), m_size(sprite.m_size), m_vertices(sprite.m_vertices), m_boundingVolumeUpdated(sprite.m_boundingVolumeUpdated), m_verticesUpdated(sprite.m_verticesUpdated) { } NzSprite::~NzSprite() = default; void NzSprite::AddToRenderQueue(NzAbstractRenderQueue* renderQueue) const { if (!m_verticesUpdated) UpdateVertices(); renderQueue->AddSprites(m_material, m_vertices, 1); } const NzBoundingVolumef& NzSprite::GetBoundingVolume() const { if (!m_boundingVolumeUpdated) UpdateBoundingVolume(); return m_boundingVolume; } const NzColor& NzSprite::GetColor() const { return m_color; } NzMaterial* NzSprite::GetMaterial() const { return m_material; } nzSceneNodeType NzSprite::GetSceneNodeType() const { return nzSceneNodeType_Sprite; } const NzVector2f& NzSprite::GetSize() const { return m_size; } const NzRectf& NzSprite::GetTextureCoords() const { return m_textureCoords; } bool NzSprite::IsDrawable() const { return m_material != nullptr; } void NzSprite::SetColor(const NzColor& color) { m_color = color; m_verticesUpdated = false; } void NzSprite::SetMaterial(NzMaterial* material, bool resizeSprite) { m_material = material; NzTexture* diffuseMap = m_material->GetDiffuseMap(); if (resizeSprite && diffuseMap && diffuseMap->IsValid()) SetSize(NzVector2f(diffuseMap->GetSize())); } void NzSprite::SetSize(const NzVector2f& size) { m_size = size; // On invalide la bounding box m_boundingVolume.MakeNull(); m_boundingVolumeUpdated = false; m_verticesUpdated = false; } void NzSprite::SetSize(float sizeX, float sizeY) { SetSize(NzVector2f(sizeX, sizeY)); } void NzSprite::SetTexture(NzTexture* texture, bool resizeSprite) { std::unique_ptr<NzMaterial> material(new NzMaterial); material->SetPersistent(false); material->Enable(nzRendererParameter_FaceCulling, false); material->EnableLighting(false); material->SetDiffuseMap(texture); SetMaterial(material.get(), resizeSprite); material.release(); } void NzSprite::SetTextureCoords(const NzRectf& coords) { m_textureCoords = coords; m_verticesUpdated = false; } void NzSprite::SetTextureRect(const NzRectui& rect) { #if NAZARA_GRAPHICS_SAFE if (!m_material) { NazaraError("Sprite has no material"); return; } if (!m_material->HasDiffuseMap()) { NazaraError("Sprite material has no diffuse map"); return; } #endif NzTexture* diffuseMap = m_material->GetDiffuseMap(); float invWidth = 1.f/diffuseMap->GetWidth(); float invHeight = 1.f/diffuseMap->GetHeight(); SetTextureCoords(NzRectf(invWidth*rect.x, invHeight*rect.y, invWidth*rect.width, invHeight*rect.height)); } void NzSprite::InvalidateNode() { NzSceneNode::InvalidateNode(); m_boundingVolumeUpdated = false; m_verticesUpdated = false; } void NzSprite::Register() { // Le changement de scène peut affecter les sommets m_verticesUpdated = false; } void NzSprite::Unregister() { } void NzSprite::UpdateBoundingVolume() const { if (m_boundingVolume.IsNull()) { NzVector3f down = m_scene->GetDown(); NzVector3f right = m_scene->GetRight(); m_boundingVolume.Set(NzVector3f(0.f), m_size.x*right + m_size.y*down); } if (!m_transformMatrixUpdated) UpdateTransformMatrix(); m_boundingVolume.Update(m_transformMatrix); m_boundingVolumeUpdated = true; } void NzSprite::UpdateVertices() const { if (!m_transformMatrixUpdated) UpdateTransformMatrix(); NzVector3f down = m_scene->GetDown(); NzVector3f right = m_scene->GetRight(); m_vertices[0].color = m_color; m_vertices[0].position = m_transformMatrix.Transform(NzVector3f(0.f)); m_vertices[0].uv.Set(m_textureCoords.GetCorner(nzRectCorner_LeftTop)); m_vertices[1].color = m_color; m_vertices[1].position = m_transformMatrix.Transform(m_size.x*right); m_vertices[1].uv.Set(m_textureCoords.GetCorner(nzRectCorner_RightTop)); m_vertices[2].color = m_color; m_vertices[2].position = m_transformMatrix.Transform(m_size.y*down); m_vertices[2].uv.Set(m_textureCoords.GetCorner(nzRectCorner_LeftBottom)); m_vertices[3].color = m_color; m_vertices[3].position = m_transformMatrix.Transform(m_size.x*right + m_size.y*down); m_vertices[3].uv.Set(m_textureCoords.GetCorner(nzRectCorner_RightBottom)); m_verticesUpdated = true; } <commit_msg>Fixed compilation error (from 683866baee26a12cf63b20914fff338cc872a4c8 [formerly a885b69881c30dcad29f87c3ffee41808761b6c9])<commit_after>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/Sprite.hpp> #include <Nazara/Graphics/AbstractViewer.hpp> #include <memory> #include <Nazara/Graphics/Debug.hpp> NzSprite::NzSprite() : m_boundingVolume(NzBoundingVolumef::Null()), m_color(NzColor::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f), m_boundingVolumeUpdated(true), m_verticesUpdated(false) { } NzSprite::NzSprite(NzTexture* texture) : m_boundingVolume(NzBoundingVolumef::Null()), m_color(NzColor::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_verticesUpdated(false) { if (texture) { m_material = new NzMaterial; m_material->SetPersistent(false); m_material->SetDiffuseMap(texture); if (texture->IsValid()) m_size.Set(texture->GetWidth(), texture->GetHeight()); else m_size.Set(64.f, 64.f); m_boundingVolumeUpdated = false; } else { m_size.Set(64.f, 64.f); m_boundingVolumeUpdated = true; } } NzSprite::NzSprite(const NzSprite& sprite) : NzSceneNode(sprite), m_boundingVolume(sprite.m_boundingVolume), m_material(sprite.m_material), m_textureCoords(sprite.m_textureCoords), m_size(sprite.m_size), m_vertices(sprite.m_vertices), m_boundingVolumeUpdated(sprite.m_boundingVolumeUpdated), m_verticesUpdated(sprite.m_verticesUpdated) { SetParent(sprite); } NzSprite::NzSprite(NzSprite&& sprite) : NzSceneNode(sprite), m_boundingVolume(sprite.m_boundingVolume), m_material(std::move(sprite.m_material)), m_textureCoords(sprite.m_textureCoords), m_size(sprite.m_size), m_vertices(sprite.m_vertices), m_boundingVolumeUpdated(sprite.m_boundingVolumeUpdated), m_verticesUpdated(sprite.m_verticesUpdated) { } NzSprite::~NzSprite() = default; void NzSprite::AddToRenderQueue(NzAbstractRenderQueue* renderQueue) const { if (!m_verticesUpdated) UpdateVertices(); renderQueue->AddSprites(m_material, m_vertices, 1); } const NzBoundingVolumef& NzSprite::GetBoundingVolume() const { if (!m_boundingVolumeUpdated) UpdateBoundingVolume(); return m_boundingVolume; } const NzColor& NzSprite::GetColor() const { return m_color; } NzMaterial* NzSprite::GetMaterial() const { return m_material; } nzSceneNodeType NzSprite::GetSceneNodeType() const { return nzSceneNodeType_Sprite; } const NzVector2f& NzSprite::GetSize() const { return m_size; } const NzRectf& NzSprite::GetTextureCoords() const { return m_textureCoords; } bool NzSprite::IsDrawable() const { return m_material != nullptr; } void NzSprite::SetColor(const NzColor& color) { m_color = color; m_verticesUpdated = false; } void NzSprite::SetMaterial(NzMaterial* material, bool resizeSprite) { m_material = material; NzTexture* diffuseMap = m_material->GetDiffuseMap(); if (resizeSprite && diffuseMap && diffuseMap->IsValid()) SetSize(NzVector2f(NzVector2ui(diffuseMap->GetSize()))); } void NzSprite::SetSize(const NzVector2f& size) { m_size = size; // On invalide la bounding box m_boundingVolume.MakeNull(); m_boundingVolumeUpdated = false; m_verticesUpdated = false; } void NzSprite::SetSize(float sizeX, float sizeY) { SetSize(NzVector2f(sizeX, sizeY)); } void NzSprite::SetTexture(NzTexture* texture, bool resizeSprite) { std::unique_ptr<NzMaterial> material(new NzMaterial); material->SetPersistent(false); material->Enable(nzRendererParameter_FaceCulling, false); material->EnableLighting(false); material->SetDiffuseMap(texture); SetMaterial(material.get(), resizeSprite); material.release(); } void NzSprite::SetTextureCoords(const NzRectf& coords) { m_textureCoords = coords; m_verticesUpdated = false; } void NzSprite::SetTextureRect(const NzRectui& rect) { #if NAZARA_GRAPHICS_SAFE if (!m_material) { NazaraError("Sprite has no material"); return; } if (!m_material->HasDiffuseMap()) { NazaraError("Sprite material has no diffuse map"); return; } #endif NzTexture* diffuseMap = m_material->GetDiffuseMap(); float invWidth = 1.f/diffuseMap->GetWidth(); float invHeight = 1.f/diffuseMap->GetHeight(); SetTextureCoords(NzRectf(invWidth*rect.x, invHeight*rect.y, invWidth*rect.width, invHeight*rect.height)); } void NzSprite::InvalidateNode() { NzSceneNode::InvalidateNode(); m_boundingVolumeUpdated = false; m_verticesUpdated = false; } void NzSprite::Register() { // Le changement de scène peut affecter les sommets m_verticesUpdated = false; } void NzSprite::Unregister() { } void NzSprite::UpdateBoundingVolume() const { if (m_boundingVolume.IsNull()) { NzVector3f down = m_scene->GetDown(); NzVector3f right = m_scene->GetRight(); m_boundingVolume.Set(NzVector3f(0.f), m_size.x*right + m_size.y*down); } if (!m_transformMatrixUpdated) UpdateTransformMatrix(); m_boundingVolume.Update(m_transformMatrix); m_boundingVolumeUpdated = true; } void NzSprite::UpdateVertices() const { if (!m_transformMatrixUpdated) UpdateTransformMatrix(); NzVector3f down = m_scene->GetDown(); NzVector3f right = m_scene->GetRight(); m_vertices[0].color = m_color; m_vertices[0].position = m_transformMatrix.Transform(NzVector3f(0.f)); m_vertices[0].uv.Set(m_textureCoords.GetCorner(nzRectCorner_LeftTop)); m_vertices[1].color = m_color; m_vertices[1].position = m_transformMatrix.Transform(m_size.x*right); m_vertices[1].uv.Set(m_textureCoords.GetCorner(nzRectCorner_RightTop)); m_vertices[2].color = m_color; m_vertices[2].position = m_transformMatrix.Transform(m_size.y*down); m_vertices[2].uv.Set(m_textureCoords.GetCorner(nzRectCorner_LeftBottom)); m_vertices[3].color = m_color; m_vertices[3].position = m_transformMatrix.Transform(m_size.x*right + m_size.y*down); m_vertices[3].uv.Set(m_textureCoords.GetCorner(nzRectCorner_RightBottom)); m_verticesUpdated = true; } <|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 "app/gtk_dnd_util.h" #include "base/logging.h" #include "base/pickle.h" #include "base/utf_string_conversions.h" #include "googleurl/src/gurl.h" static const int kBitsPerByte = 8; using WebKit::WebDragOperationsMask; using WebKit::WebDragOperation; using WebKit::WebDragOperationNone; using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationLink; using WebKit::WebDragOperationMove; namespace { void AddTargetToList(GtkTargetList* targets, int target_code) { switch (target_code) { case gtk_dnd_util::TEXT_PLAIN: gtk_target_list_add_text_targets(targets, gtk_dnd_util::TEXT_PLAIN); break; case gtk_dnd_util::TEXT_URI_LIST: gtk_target_list_add_uri_targets(targets, gtk_dnd_util::TEXT_URI_LIST); break; case gtk_dnd_util::TEXT_HTML: gtk_target_list_add( targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN), 0, gtk_dnd_util::TEXT_HTML); break; case gtk_dnd_util::NETSCAPE_URL: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL), 0, gtk_dnd_util::NETSCAPE_URL); break; case gtk_dnd_util::CHROME_TAB: case gtk_dnd_util::CHROME_BOOKMARK_ITEM: case gtk_dnd_util::CHROME_NAMED_URL: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(target_code), GTK_TARGET_SAME_APP, target_code); break; case gtk_dnd_util::DIRECT_SAVE_FILE: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::DIRECT_SAVE_FILE), 0, gtk_dnd_util::DIRECT_SAVE_FILE); break; default: NOTREACHED() << " Unexpected target code: " << target_code; } } } // namespace namespace gtk_dnd_util { GdkAtom GetAtomForTarget(int target) { switch (target) { case CHROME_TAB: static GdkAtom tab_atom = gdk_atom_intern( const_cast<char*>("application/x-chrome-tab"), false); return tab_atom; case TEXT_HTML: static GdkAtom html_atom = gdk_atom_intern( const_cast<char*>("text/html"), false); return html_atom; case CHROME_BOOKMARK_ITEM: static GdkAtom bookmark_atom = gdk_atom_intern( const_cast<char*>("application/x-chrome-bookmark-item"), false); return bookmark_atom; case TEXT_PLAIN: static GdkAtom text_atom = gdk_atom_intern( const_cast<char*>("text/plain;charset=utf-8"), false); return text_atom; case TEXT_URI_LIST: static GdkAtom uris_atom = gdk_atom_intern( const_cast<char*>("text/uri-list"), false); return uris_atom; case CHROME_NAMED_URL: static GdkAtom named_url = gdk_atom_intern( const_cast<char*>("application/x-chrome-named-url"), false); return named_url; case NETSCAPE_URL: static GdkAtom netscape_url = gdk_atom_intern( const_cast<char*>("_NETSCAPE_URL"), false); return netscape_url; case TEXT_PLAIN_NO_CHARSET: static GdkAtom text_no_charset_atom = gdk_atom_intern( const_cast<char*>("text/plain"), false); return text_no_charset_atom; case DIRECT_SAVE_FILE: static GdkAtom xds_atom = gdk_atom_intern( const_cast<char*>("XdndDirectSave0"), false); return xds_atom; default: NOTREACHED(); } return NULL; } GtkTargetList* GetTargetListFromCodeMask(int code_mask) { GtkTargetList* targets = gtk_target_list_new(NULL, 0); for (size_t i = 1; i < INVALID_TARGET; i = i << 1) { if (i == CHROME_WEBDROP_FILE_CONTENTS) continue; if (i & code_mask) AddTargetToList(targets, i); } return targets; } void SetSourceTargetListFromCodeMask(GtkWidget* source, int code_mask) { GtkTargetList* targets = GetTargetListFromCodeMask(code_mask); gtk_drag_source_set_target_list(source, targets); gtk_target_list_unref(targets); } void SetDestTargetList(GtkWidget* dest, const int* target_codes) { GtkTargetList* targets = gtk_target_list_new(NULL, 0); for (size_t i = 0; target_codes[i] != -1; ++i) { AddTargetToList(targets, target_codes[i]); } gtk_drag_dest_set_target_list(dest, targets); gtk_target_list_unref(targets); } void WriteURLWithName(GtkSelectionData* selection_data, const GURL& url, const string16& title, int type) { switch (type) { case TEXT_PLAIN: { gtk_selection_data_set_text(selection_data, url.spec().c_str(), url.spec().length()); break; } case TEXT_URI_LIST: { gchar* uri_array[2]; uri_array[0] = strdup(url.spec().c_str()); uri_array[1] = NULL; gtk_selection_data_set_uris(selection_data, uri_array); free(uri_array[0]); break; } case CHROME_NAMED_URL: { Pickle pickle; pickle.WriteString(UTF16ToUTF8(title)); pickle.WriteString(url.spec()); gtk_selection_data_set( selection_data, GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL), kBitsPerByte, reinterpret_cast<const guchar*>(pickle.data()), pickle.size()); break; } case NETSCAPE_URL: { // _NETSCAPE_URL format is URL + \n + title. std::string utf8_text = url.spec() + "\n" + UTF16ToUTF8(title); gtk_selection_data_set(selection_data, selection_data->target, kBitsPerByte, reinterpret_cast<const guchar*>(utf8_text.c_str()), utf8_text.length()); break; } default: { NOTREACHED(); break; } } } bool ExtractNamedURL(GtkSelectionData* selection_data, GURL* url, string16* title) { Pickle data(reinterpret_cast<char*>(selection_data->data), selection_data->length); void* iter = NULL; std::string title_utf8, url_utf8; if (!data.ReadString(&iter, &title_utf8) || !data.ReadString(&iter, &url_utf8)) { return false; } GURL gurl(url_utf8); if (!gurl.is_valid()) return false; *url = gurl; *title = UTF8ToUTF16(title_utf8); return true; } bool ExtractURIList(GtkSelectionData* selection_data, std::vector<GURL>* urls) { gchar** uris = gtk_selection_data_get_uris(selection_data); if (!uris) return false; for (size_t i = 0; uris[i] != NULL; ++i) { GURL url(uris[i]); if (url.is_valid()) urls->push_back(url); } g_strfreev(uris); return true; } GdkDragAction WebDragOpToGdkDragAction(WebDragOperationsMask op) { GdkDragAction action = static_cast<GdkDragAction>(0); if (op & WebDragOperationCopy) action = static_cast<GdkDragAction>(action | GDK_ACTION_COPY); if (op & WebDragOperationLink) action = static_cast<GdkDragAction>(action | GDK_ACTION_LINK); if (op & WebDragOperationMove) action = static_cast<GdkDragAction>(action | GDK_ACTION_MOVE); return action; } WebDragOperationsMask GdkDragActionToWebDragOp(GdkDragAction action) { WebDragOperationsMask op = WebDragOperationNone; if (action & GDK_ACTION_COPY) op = static_cast<WebDragOperationsMask>(op | WebDragOperationCopy); if (action & GDK_ACTION_LINK) op = static_cast<WebDragOperationsMask>(op | WebDragOperationLink); if (action & GDK_ACTION_MOVE) op = static_cast<WebDragOperationsMask>(op | WebDragOperationMove); return op; } } // namespace gtk_dnd_util <commit_msg>We DnD shouldn't provide text/html if it claims to provide text/text/plain;charset=utf-8.<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 "app/gtk_dnd_util.h" #include "base/logging.h" #include "base/pickle.h" #include "base/utf_string_conversions.h" #include "googleurl/src/gurl.h" static const int kBitsPerByte = 8; using WebKit::WebDragOperationsMask; using WebKit::WebDragOperation; using WebKit::WebDragOperationNone; using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationLink; using WebKit::WebDragOperationMove; namespace { void AddTargetToList(GtkTargetList* targets, int target_code) { switch (target_code) { case gtk_dnd_util::TEXT_PLAIN: gtk_target_list_add_text_targets(targets, gtk_dnd_util::TEXT_PLAIN); break; case gtk_dnd_util::TEXT_URI_LIST: gtk_target_list_add_uri_targets(targets, gtk_dnd_util::TEXT_URI_LIST); break; case gtk_dnd_util::TEXT_HTML: gtk_target_list_add( targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML), 0, gtk_dnd_util::TEXT_HTML); break; case gtk_dnd_util::NETSCAPE_URL: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL), 0, gtk_dnd_util::NETSCAPE_URL); break; case gtk_dnd_util::CHROME_TAB: case gtk_dnd_util::CHROME_BOOKMARK_ITEM: case gtk_dnd_util::CHROME_NAMED_URL: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(target_code), GTK_TARGET_SAME_APP, target_code); break; case gtk_dnd_util::DIRECT_SAVE_FILE: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::DIRECT_SAVE_FILE), 0, gtk_dnd_util::DIRECT_SAVE_FILE); break; default: NOTREACHED() << " Unexpected target code: " << target_code; } } } // namespace namespace gtk_dnd_util { GdkAtom GetAtomForTarget(int target) { switch (target) { case CHROME_TAB: static GdkAtom tab_atom = gdk_atom_intern( const_cast<char*>("application/x-chrome-tab"), false); return tab_atom; case TEXT_HTML: static GdkAtom html_atom = gdk_atom_intern( const_cast<char*>("text/html"), false); return html_atom; case CHROME_BOOKMARK_ITEM: static GdkAtom bookmark_atom = gdk_atom_intern( const_cast<char*>("application/x-chrome-bookmark-item"), false); return bookmark_atom; case TEXT_PLAIN: static GdkAtom text_atom = gdk_atom_intern( const_cast<char*>("text/plain;charset=utf-8"), false); return text_atom; case TEXT_URI_LIST: static GdkAtom uris_atom = gdk_atom_intern( const_cast<char*>("text/uri-list"), false); return uris_atom; case CHROME_NAMED_URL: static GdkAtom named_url = gdk_atom_intern( const_cast<char*>("application/x-chrome-named-url"), false); return named_url; case NETSCAPE_URL: static GdkAtom netscape_url = gdk_atom_intern( const_cast<char*>("_NETSCAPE_URL"), false); return netscape_url; case TEXT_PLAIN_NO_CHARSET: static GdkAtom text_no_charset_atom = gdk_atom_intern( const_cast<char*>("text/plain"), false); return text_no_charset_atom; case DIRECT_SAVE_FILE: static GdkAtom xds_atom = gdk_atom_intern( const_cast<char*>("XdndDirectSave0"), false); return xds_atom; default: NOTREACHED(); } return NULL; } GtkTargetList* GetTargetListFromCodeMask(int code_mask) { GtkTargetList* targets = gtk_target_list_new(NULL, 0); for (size_t i = 1; i < INVALID_TARGET; i = i << 1) { if (i == CHROME_WEBDROP_FILE_CONTENTS) continue; if (i & code_mask) AddTargetToList(targets, i); } return targets; } void SetSourceTargetListFromCodeMask(GtkWidget* source, int code_mask) { GtkTargetList* targets = GetTargetListFromCodeMask(code_mask); gtk_drag_source_set_target_list(source, targets); gtk_target_list_unref(targets); } void SetDestTargetList(GtkWidget* dest, const int* target_codes) { GtkTargetList* targets = gtk_target_list_new(NULL, 0); for (size_t i = 0; target_codes[i] != -1; ++i) { AddTargetToList(targets, target_codes[i]); } gtk_drag_dest_set_target_list(dest, targets); gtk_target_list_unref(targets); } void WriteURLWithName(GtkSelectionData* selection_data, const GURL& url, const string16& title, int type) { switch (type) { case TEXT_PLAIN: { gtk_selection_data_set_text(selection_data, url.spec().c_str(), url.spec().length()); break; } case TEXT_URI_LIST: { gchar* uri_array[2]; uri_array[0] = strdup(url.spec().c_str()); uri_array[1] = NULL; gtk_selection_data_set_uris(selection_data, uri_array); free(uri_array[0]); break; } case CHROME_NAMED_URL: { Pickle pickle; pickle.WriteString(UTF16ToUTF8(title)); pickle.WriteString(url.spec()); gtk_selection_data_set( selection_data, GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL), kBitsPerByte, reinterpret_cast<const guchar*>(pickle.data()), pickle.size()); break; } case NETSCAPE_URL: { // _NETSCAPE_URL format is URL + \n + title. std::string utf8_text = url.spec() + "\n" + UTF16ToUTF8(title); gtk_selection_data_set(selection_data, selection_data->target, kBitsPerByte, reinterpret_cast<const guchar*>(utf8_text.c_str()), utf8_text.length()); break; } default: { NOTREACHED(); break; } } } bool ExtractNamedURL(GtkSelectionData* selection_data, GURL* url, string16* title) { Pickle data(reinterpret_cast<char*>(selection_data->data), selection_data->length); void* iter = NULL; std::string title_utf8, url_utf8; if (!data.ReadString(&iter, &title_utf8) || !data.ReadString(&iter, &url_utf8)) { return false; } GURL gurl(url_utf8); if (!gurl.is_valid()) return false; *url = gurl; *title = UTF8ToUTF16(title_utf8); return true; } bool ExtractURIList(GtkSelectionData* selection_data, std::vector<GURL>* urls) { gchar** uris = gtk_selection_data_get_uris(selection_data); if (!uris) return false; for (size_t i = 0; uris[i] != NULL; ++i) { GURL url(uris[i]); if (url.is_valid()) urls->push_back(url); } g_strfreev(uris); return true; } GdkDragAction WebDragOpToGdkDragAction(WebDragOperationsMask op) { GdkDragAction action = static_cast<GdkDragAction>(0); if (op & WebDragOperationCopy) action = static_cast<GdkDragAction>(action | GDK_ACTION_COPY); if (op & WebDragOperationLink) action = static_cast<GdkDragAction>(action | GDK_ACTION_LINK); if (op & WebDragOperationMove) action = static_cast<GdkDragAction>(action | GDK_ACTION_MOVE); return action; } WebDragOperationsMask GdkDragActionToWebDragOp(GdkDragAction action) { WebDragOperationsMask op = WebDragOperationNone; if (action & GDK_ACTION_COPY) op = static_cast<WebDragOperationsMask>(op | WebDragOperationCopy); if (action & GDK_ACTION_LINK) op = static_cast<WebDragOperationsMask>(op | WebDragOperationLink); if (action & GDK_ACTION_MOVE) op = static_cast<WebDragOperationsMask>(op | WebDragOperationMove); return op; } } // namespace gtk_dnd_util <|endoftext|>
<commit_before>/// /// @file primecount.cpp /// @brief primecount C++ API /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <calculator.hpp> #include <ptypes.hpp> #include <pmath.hpp> #include <algorithm> #include <ctime> #include <iostream> #include <iomanip> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif using namespace std; namespace { int threads_ = primecount::MAX_THREADS; bool print_status_ = false; } namespace primecount { int64_t pi(int64_t x) { return pi(x, threads_); } int64_t pi(int64_t x, int threads) { return pi_deleglise_rivat(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, threads_); } int128_t pi(int128_t x, int threads) { return pi_deleglise_rivat(x, threads); } #endif /// Alias for the fastest prime counting function in primecount. /// @param x integer or arithmetic expression like "10^12". /// @pre x <= primecount::max(). /// std::string pi(const std::string& x) { return pi(x, threads_); } /// Alias for the fastest prime counting function in primecount. /// @param x integer or arithmetic expression like "10^12". /// @pre x <= primecount::max(). /// std::string pi(const std::string& x, int threads) { maxint_t n = to_maxint(x); maxint_t pin = pi(n, threads); ostringstream oss; oss << pin; return oss.str(); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x) { return pi_deleglise_rivat(x, threads_); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x, int threads) { if (threads <= 1) return pi_deleglise_rivat3(x); return pi_deleglise_rivat_parallel3(x, threads); } #ifdef HAVE_INT128_T /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x) { return pi_deleglise_rivat(x, threads_); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat((int64_t) x, threads); if (threads <= 1) return pi_deleglise_rivat4(x); else return pi_deleglise_rivat_parallel4(x, threads); } #endif /// Calculate the number of primes below x using Legendre's formula. /// Run time: O(x) operations, O(x^(1/2)) space. /// int64_t pi_legendre(int64_t x) { return pi_legendre(x, threads_); } /// Calculate the number of primes below x using Lehmer's formula. /// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space. /// int64_t pi_lehmer(int64_t x) { return pi_lehmer(x, threads_); } /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x) { return pi_lmo(x, threads_); } /// Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x, int threads) { if (threads <= 1) return pi_lmo5(x); return pi_lmo_parallel3(x, threads); } /// Calculate the number of primes below x using Meissel's formula. /// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space. /// int64_t pi_meissel(int64_t x) { return pi_meissel(x, threads_); } /// Calculate the number of primes below x using an optimized /// segmented sieve of Eratosthenes implementation. /// Run time: O(x log log x) operations, O(x^(1/2)) space. /// int64_t pi_primesieve(int64_t x) { return pi_primesieve(x, threads_); } /// Calculate the nth prime using a combination of an efficient prime /// counting function implementation and the sieve of Eratosthenes. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space. /// int64_t nth_prime(int64_t n) { return nth_prime(n, threads_); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a) { return phi(x, a, threads_); } /// Returns the largest integer that can be used with /// pi(std::string x). The return type is a string as max may be a /// 128-bit integer which is not supported by all compilers. /// std::string max() { #ifdef HAVE_INT128_T return string("1") + string(27, '0'); #else ostringstream oss; oss << numeric_limits<int64_t>::max(); return oss.str(); #endif } /// Get the wall time in seconds. double get_wtime() { #ifdef _OPENMP return omp_get_wtime(); #else return static_cast<double>(std::clock()) / CLOCKS_PER_SEC; #endif } int validate_threads(int threads) { #ifdef _OPENMP if (threads == MAX_THREADS) threads = omp_get_max_threads(); return in_between(1, threads, omp_get_max_threads()); #else threads = 1; return threads; #endif } int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { threads = validate_threads(threads); threads = (int) std::min((int64_t) threads, sieve_limit / thread_threshold); threads = std::max(1, threads); return threads; } void set_num_threads(int threads) { threads_ = validate_threads(threads); } int get_num_threads() { return validate_threads(threads_); } maxint_t to_maxint(const std::string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } void print_percent(maxint_t s2_current, maxint_t s2_approx, double rsd) { double percent = get_percent((double) s2_current, (double) s2_approx); double base = 0.95 + percent / 2000; double min = pow(base, 100.0); double max = pow(base, 0.0); percent = 100 - in_between(0, 100 * (pow(base, percent) - min) / (max - min), 100); int load_balance = (int) in_between(0, 100 - rsd + 0.5, 100); ostringstream oss; oss << "\r" << string(40,' ') << "\r"; oss << "Status: " << (int) percent << "%, "; oss << "Load balance: " << load_balance << "%"; cout << oss.str() << flush; } void print_result(const std::string& str, maxint_t res, double time) { cout << "\r" << string(40,' ') << "\r"; cout << "Status: 100%" << endl; cout << str << " = " << res << endl; print_seconds(get_wtime() - time); } void print_seconds(double seconds) { cout << "Seconds: " << fixed << setprecision(3) << seconds << endl; } void print_megabytes(std::size_t bytes) { double megabytes = bytes / (double) (1 << 20); cout << "memory usage = " << fixed << setprecision(3) << megabytes << " megabytes" << endl; } void set_print_status(bool print_status) { print_status_ = print_status; } bool print_status() { return print_status_; } } // namespace primecount <commit_msg>Fix division by 0<commit_after>/// /// @file primecount.cpp /// @brief primecount C++ API /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <calculator.hpp> #include <ptypes.hpp> #include <pmath.hpp> #include <algorithm> #include <ctime> #include <iostream> #include <iomanip> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif using namespace std; namespace { int threads_ = primecount::MAX_THREADS; bool print_status_ = false; } namespace primecount { int64_t pi(int64_t x) { return pi(x, threads_); } int64_t pi(int64_t x, int threads) { return pi_deleglise_rivat(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, threads_); } int128_t pi(int128_t x, int threads) { return pi_deleglise_rivat(x, threads); } #endif /// Alias for the fastest prime counting function in primecount. /// @param x integer or arithmetic expression like "10^12". /// @pre x <= primecount::max(). /// std::string pi(const std::string& x) { return pi(x, threads_); } /// Alias for the fastest prime counting function in primecount. /// @param x integer or arithmetic expression like "10^12". /// @pre x <= primecount::max(). /// std::string pi(const std::string& x, int threads) { maxint_t n = to_maxint(x); maxint_t pin = pi(n, threads); ostringstream oss; oss << pin; return oss.str(); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x) { return pi_deleglise_rivat(x, threads_); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x, int threads) { if (threads <= 1) return pi_deleglise_rivat3(x); return pi_deleglise_rivat_parallel3(x, threads); } #ifdef HAVE_INT128_T /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x) { return pi_deleglise_rivat(x, threads_); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat((int64_t) x, threads); if (threads <= 1) return pi_deleglise_rivat4(x); else return pi_deleglise_rivat_parallel4(x, threads); } #endif /// Calculate the number of primes below x using Legendre's formula. /// Run time: O(x) operations, O(x^(1/2)) space. /// int64_t pi_legendre(int64_t x) { return pi_legendre(x, threads_); } /// Calculate the number of primes below x using Lehmer's formula. /// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space. /// int64_t pi_lehmer(int64_t x) { return pi_lehmer(x, threads_); } /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x) { return pi_lmo(x, threads_); } /// Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x, int threads) { if (threads <= 1) return pi_lmo5(x); return pi_lmo_parallel3(x, threads); } /// Calculate the number of primes below x using Meissel's formula. /// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space. /// int64_t pi_meissel(int64_t x) { return pi_meissel(x, threads_); } /// Calculate the number of primes below x using an optimized /// segmented sieve of Eratosthenes implementation. /// Run time: O(x log log x) operations, O(x^(1/2)) space. /// int64_t pi_primesieve(int64_t x) { return pi_primesieve(x, threads_); } /// Calculate the nth prime using a combination of an efficient prime /// counting function implementation and the sieve of Eratosthenes. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space. /// int64_t nth_prime(int64_t n) { return nth_prime(n, threads_); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a) { return phi(x, a, threads_); } /// Returns the largest integer that can be used with /// pi(std::string x). The return type is a string as max may be a /// 128-bit integer which is not supported by all compilers. /// std::string max() { #ifdef HAVE_INT128_T return string("1") + string(27, '0'); #else ostringstream oss; oss << numeric_limits<int64_t>::max(); return oss.str(); #endif } /// Get the wall time in seconds. double get_wtime() { #ifdef _OPENMP return omp_get_wtime(); #else return static_cast<double>(std::clock()) / CLOCKS_PER_SEC; #endif } int validate_threads(int threads) { #ifdef _OPENMP if (threads == MAX_THREADS) threads = omp_get_max_threads(); return in_between(1, threads, omp_get_max_threads()); #else threads = 1; return threads; #endif } int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { threads = validate_threads(threads); threads = (int) std::min((int64_t) threads, sieve_limit / thread_threshold); threads = std::max(1, threads); return threads; } void set_num_threads(int threads) { threads_ = validate_threads(threads); } int get_num_threads() { return validate_threads(threads_); } maxint_t to_maxint(const std::string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } void print_percent(maxint_t s2_current, maxint_t s2_approx, double rsd) { double percent = get_percent((double) s2_current, (double) s2_approx); double base = 0.95 + percent / 2100; double min = pow(base, 100.0); double max = pow(base, 0.0); percent = 100 - in_between(0, 100 * (pow(base, percent) - min) / (max - min), 100); int load_balance = (int) in_between(0, 100 - rsd + 0.5, 100); ostringstream oss; oss << "\r" << string(40,' ') << "\r"; oss << "Status: " << (int) percent << "%, "; oss << "Load balance: " << load_balance << "%"; cout << oss.str() << flush; } void print_result(const std::string& str, maxint_t res, double time) { cout << "\r" << string(40,' ') << "\r"; cout << "Status: 100%" << endl; cout << str << " = " << res << endl; print_seconds(get_wtime() - time); } void print_seconds(double seconds) { cout << "Seconds: " << fixed << setprecision(3) << seconds << endl; } void print_megabytes(std::size_t bytes) { double megabytes = bytes / (double) (1 << 20); cout << "memory usage = " << fixed << setprecision(3) << megabytes << " megabytes" << endl; } void set_print_status(bool print_status) { print_status_ = print_status; } bool print_status() { return print_status_; } } // namespace primecount <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include <utility> #include <memory> #include <uv.h> #include "resource.hpp" #include "util.hpp" namespace uvw { /** * @brief CloseEvent event. * * It will be emitted by the handles according with their functionalities. */ struct CloseEvent {}; /** * @brief Handle base class. * * Base type for all `uvw` handle types. */ template<typename T, typename U> class Handle: public BaseHandle, public Resource<T, U> { static void closeCallback(uv_handle_t *handle) { Handle<T, U> &ref = *(static_cast<T*>(handle->data)); auto ptr = ref.shared_from_this(); (void)ptr; ref.reset(); ref.publish(CloseEvent{}); } protected: static void allocCallback(uv_handle_t *, std::size_t suggested, uv_buf_t *buf) { *buf = uv_buf_init(new char[suggested], suggested); } template<typename F, typename... Args> bool initialize(F &&f, Args&&... args) { if(!this->self()) { auto err = std::forward<F>(f)(this->parent(), this->get(), std::forward<Args>(args)...); if(err) { this->publish(ErrorEvent{err}); } else { this->leak(); } } return this->self(); } template<typename F, typename... Args> auto invoke(F &&f, Args&&... args) { auto err = std::forward<F>(f)(std::forward<Args>(args)...); if(err) { Emitter<T>::publish(ErrorEvent{err}); } return err; } public: using Resource<T, U>::Resource; /** * @brief Checks if the handle is active. * * What _active_ means depends on the type of handle: * * * An AsyncHandle handle is always active and cannot be deactivated, * except by closing it with uv_close(). * * A PipeHandle, TcpHandle, UDPHandle, etc. handle - basically any handle * that deals with I/O - is active when it is doing something that involves * I/O, like reading, writing, connecting, accepting new connections, etc. * * A CheckHandle, IdleHandle, TimerHandle, etc. handle is active when it * has been started with a call to `start()`. * * Rule of thumb: if a handle of type `FooHandle` has a `start()` member * method, then it’s active from the moment that method is called. Likewise, * `stop()` deactivates the handle again. * * @return True if the handle is active, false otherwise. */ bool active() const noexcept override { return !(uv_is_active(this->template get<uv_handle_t>()) == 0); } /** * @brief Checks if a handle is closing or closed. * * This function should only be used between the initialization of the * handle and the arrival of the close callback. * * @return True if the handle is closing or closed, false otherwise. */ bool closing() const noexcept override { return !(uv_is_closing(this->template get<uv_handle_t>()) == 0); } /** * @brief Request handle to be closed. * * This **must** be called on each handle before memory is released.<br/> * In-progress requests are cancelled and this can result in an ErrorEvent * emitted. * * The handle will emit a CloseEvent when finished. */ void close() noexcept override { if(!closing()) { uv_close(this->template get<uv_handle_t>(), &Handle<T, U>::closeCallback); } } /** * @brief Reference the given handle. * * References are idempotent, that is, if a handle is already referenced * calling this function again will have no effect. */ void reference() noexcept override { uv_ref(this->template get<uv_handle_t>()); } /** * @brief Unreference the given handle. * * References are idempotent, that is, if a handle is not referenced calling * this function again will have no effect. */ void unreference() noexcept override { uv_unref(this->template get<uv_handle_t>()); } /** * @brief Checks if the given handle referenced. * @return True if the handle referenced, false otherwise. */ bool referenced() const noexcept override { return !(uv_has_ref(this->template get<uv_handle_t>()) == 0); } /** * @brief Returns the size of the underlying handle type. * @return The size of the underlying handle type. */ std::size_t size() const noexcept { return uv_handle_size(this->template get<uv_handle_t>()->type); } /** * @brief Gets the size of the send buffer used for the socket. * * Gets the size of the send buffer that the operating system uses for the * socket.<br/> * This function works for TcpHandle, PipeHandle and UDPHandle handles on * Unix and for TcpHandle and UDPHandle handles on Windows.<br/> * Note that Linux will return double the size of the original set value. * * @return The size of the send buffer, 0 in case of errors. */ int sendBufferSize() { int value = 0; auto err = uv_send_buffer_size(this->template get<uv_handle_t>(), &value); return err ? 0 : value; } /** * @brief Sets the size of the send buffer used for the socket. * * Sets the size of the send buffer that the operating system uses for the * socket.<br/> * This function works for TcpHandle, PipeHandle and UDPHandle handles on * Unix and for TcpHandle and UDPHandle handles on Windows.<br/> * Note that Linux will set double the size. * * @return True in case of success, false otherwise. */ bool sendBufferSize(int value) { return (0 == uv_send_buffer_size(this->template get<uv_handle_t>(), &value)); } /** * @brief Gets the size of the receive buffer used for the socket. * * Gets the size of the receive buffer that the operating system uses for * the socket.<br/> * This function works for TcpHandle, PipeHandle and UDPHandle handles on * Unix and for TcpHandle and UDPHandle handles on Windows.<br/> * Note that Linux will return double the size of the original set value. * * @return The size of the receive buffer, 0 in case of errors. */ int recvBufferSize() { int value = 0; auto err = uv_recv_buffer_size(this->template get<uv_handle_t>(), &value); return err ? 0 : value; } /** * @brief Sets the size of the receive buffer used for the socket. * * Sets the size of the receive buffer that the operating system uses for * the socket.<br/> * This function works for TcpHandle, PipeHandle and UDPHandle handles on * Unix and for TcpHandle and UDPHandle handles on Windows.<br/> * Note that Linux will set double the size. * * @return True in case of success, false otherwise. */ bool recvBufferSize(int value) { return (0 == uv_recv_buffer_size(this->template get<uv_handle_t>(), &value)); } /** * @brief Gets the platform dependent file descriptor equivalent. * * Supported handles: * * * TcpHandle * * PipeHandle * * TTYHandle * * UDPHandle * * PollHandle * * It will emit an ErrorEvent event if invoked on any other handle.<br/> * If a handle doesn’t have an attached file descriptor yet or the handle * itself has been closed, an ErrorEvent event will be emitted. * * See the official * [documentation](http://docs.libuv.org/en/v1.x/handle.html#c.uv_fileno) * for further details. * * @return The file descriptor attached to the hande or a negative value in * case of errors. */ OSFileDescriptor fileno() const { uv_os_fd_t fd; uv_fileno(this->template get<uv_handle_t>(), &fd); return fd; } }; } <commit_msg>ongoing review<commit_after>#pragma once #include <cstddef> #include <utility> #include <memory> #include <uv.h> #include "resource.hpp" #include "util.hpp" namespace uvw { /** * @brief CloseEvent event. * * It will be emitted by the handles according with their functionalities. */ struct CloseEvent {}; /** * @brief Handle base class. * * Base type for all `uvw` handle types. */ template<typename T, typename U> class Handle: public BaseHandle, public Resource<T, U> { static void closeCallback(uv_handle_t *handle) { Handle<T, U> &ref = *(static_cast<T*>(handle->data)); auto ptr = ref.shared_from_this(); (void)ptr; ref.reset(); ref.publish(CloseEvent{}); } protected: static void allocCallback(uv_handle_t *, std::size_t suggested, uv_buf_t *buf) { auto size = static_cast<unsigned int>(suggested); *buf = uv_buf_init(new char[size], size); } template<typename F, typename... Args> bool initialize(F &&f, Args&&... args) { if(!this->self()) { auto err = std::forward<F>(f)(this->parent(), this->get(), std::forward<Args>(args)...); if(err) { this->publish(ErrorEvent{err}); } else { this->leak(); } } return this->self(); } template<typename F, typename... Args> auto invoke(F &&f, Args&&... args) { auto err = std::forward<F>(f)(std::forward<Args>(args)...); if(err) { Emitter<T>::publish(ErrorEvent{err}); } return err; } public: using Resource<T, U>::Resource; /** * @brief Checks if the handle is active. * * What _active_ means depends on the type of handle: * * * An AsyncHandle handle is always active and cannot be deactivated, * except by closing it with uv_close(). * * A PipeHandle, TcpHandle, UDPHandle, etc. handle - basically any handle * that deals with I/O - is active when it is doing something that involves * I/O, like reading, writing, connecting, accepting new connections, etc. * * A CheckHandle, IdleHandle, TimerHandle, etc. handle is active when it * has been started with a call to `start()`. * * Rule of thumb: if a handle of type `FooHandle` has a `start()` member * method, then it’s active from the moment that method is called. Likewise, * `stop()` deactivates the handle again. * * @return True if the handle is active, false otherwise. */ bool active() const noexcept override { return !(uv_is_active(this->template get<uv_handle_t>()) == 0); } /** * @brief Checks if a handle is closing or closed. * * This function should only be used between the initialization of the * handle and the arrival of the close callback. * * @return True if the handle is closing or closed, false otherwise. */ bool closing() const noexcept override { return !(uv_is_closing(this->template get<uv_handle_t>()) == 0); } /** * @brief Request handle to be closed. * * This **must** be called on each handle before memory is released.<br/> * In-progress requests are cancelled and this can result in an ErrorEvent * emitted. * * The handle will emit a CloseEvent when finished. */ void close() noexcept override { if(!closing()) { uv_close(this->template get<uv_handle_t>(), &Handle<T, U>::closeCallback); } } /** * @brief Reference the given handle. * * References are idempotent, that is, if a handle is already referenced * calling this function again will have no effect. */ void reference() noexcept override { uv_ref(this->template get<uv_handle_t>()); } /** * @brief Unreference the given handle. * * References are idempotent, that is, if a handle is not referenced calling * this function again will have no effect. */ void unreference() noexcept override { uv_unref(this->template get<uv_handle_t>()); } /** * @brief Checks if the given handle referenced. * @return True if the handle referenced, false otherwise. */ bool referenced() const noexcept override { return !(uv_has_ref(this->template get<uv_handle_t>()) == 0); } /** * @brief Returns the size of the underlying handle type. * @return The size of the underlying handle type. */ std::size_t size() const noexcept { return uv_handle_size(this->template get<uv_handle_t>()->type); } /** * @brief Gets the size of the send buffer used for the socket. * * Gets the size of the send buffer that the operating system uses for the * socket.<br/> * This function works for TcpHandle, PipeHandle and UDPHandle handles on * Unix and for TcpHandle and UDPHandle handles on Windows.<br/> * Note that Linux will return double the size of the original set value. * * @return The size of the send buffer, 0 in case of errors. */ int sendBufferSize() { int value = 0; auto err = uv_send_buffer_size(this->template get<uv_handle_t>(), &value); return err ? 0 : value; } /** * @brief Sets the size of the send buffer used for the socket. * * Sets the size of the send buffer that the operating system uses for the * socket.<br/> * This function works for TcpHandle, PipeHandle and UDPHandle handles on * Unix and for TcpHandle and UDPHandle handles on Windows.<br/> * Note that Linux will set double the size. * * @return True in case of success, false otherwise. */ bool sendBufferSize(int value) { return (0 == uv_send_buffer_size(this->template get<uv_handle_t>(), &value)); } /** * @brief Gets the size of the receive buffer used for the socket. * * Gets the size of the receive buffer that the operating system uses for * the socket.<br/> * This function works for TcpHandle, PipeHandle and UDPHandle handles on * Unix and for TcpHandle and UDPHandle handles on Windows.<br/> * Note that Linux will return double the size of the original set value. * * @return The size of the receive buffer, 0 in case of errors. */ int recvBufferSize() { int value = 0; auto err = uv_recv_buffer_size(this->template get<uv_handle_t>(), &value); return err ? 0 : value; } /** * @brief Sets the size of the receive buffer used for the socket. * * Sets the size of the receive buffer that the operating system uses for * the socket.<br/> * This function works for TcpHandle, PipeHandle and UDPHandle handles on * Unix and for TcpHandle and UDPHandle handles on Windows.<br/> * Note that Linux will set double the size. * * @return True in case of success, false otherwise. */ bool recvBufferSize(int value) { return (0 == uv_recv_buffer_size(this->template get<uv_handle_t>(), &value)); } /** * @brief Gets the platform dependent file descriptor equivalent. * * Supported handles: * * * TcpHandle * * PipeHandle * * TTYHandle * * UDPHandle * * PollHandle * * It will emit an ErrorEvent event if invoked on any other handle.<br/> * If a handle doesn’t have an attached file descriptor yet or the handle * itself has been closed, an ErrorEvent event will be emitted. * * See the official * [documentation](http://docs.libuv.org/en/v1.x/handle.html#c.uv_fileno) * for further details. * * @return The file descriptor attached to the hande or a negative value in * case of errors. */ OSFileDescriptor fileno() const { uv_os_fd_t fd; uv_fileno(this->template get<uv_handle_t>(), &fd); return fd; } }; } <|endoftext|>
<commit_before>#include "prioritydb.h" #include <functional> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <vector> #include <sqlite3.h> typedef std::map<std::string, std::string> Record; static int callback(void* response_ptr, int num_values, char** values, char** names) { auto response = (std::vector<Record>*) response_ptr; auto record = Record(); for (int i = 0; i < num_values; ++i) { if (values[i]) { record[names[i]] = values[i]; } } response->push_back(record); return 0; } class PriorityDB::Impl { public: Impl(const unsigned long long& max_size) : max_size_{max_size} {} int Open(const std::string& path); void Insert(const unsigned long long& priority, const std::string& hash, const unsigned long long& size, const bool& on_disk); void Delete(const std::string& hash); void Update(const std::string& hash, const bool& on_disk); std::string GetHighestHash(bool& on_disk); std::string GetLowestMemoryHash(); std::string GetLowestDiskHash(); bool Full(); private: std::string table_path_; std::string table_name_; unsigned long long max_size_; std::unique_ptr<sqlite3, std::function<int(sqlite3*)>> open_db_(); bool check_table_(); void create_table_(); std::vector<Record> execute_(const std::string& sql); }; int PriorityDB::Impl::Open(const std::string& path) { table_path_ = path; table_name_ = "prism_data"; if (!check_table_()) { create_table_(); } check_table_(); return 0; } void PriorityDB::Impl::Insert(const unsigned long long& priority, const std::string& hash, const unsigned long long& size, const bool& on_disk) { std::stringstream stream; stream << "INSERT INTO " << table_name_ << "(priority, hash, size, on_disk)" << "VALUES" << "(" << priority << "," << "'" << hash << "'," << size << "," << on_disk << ");"; execute_(stream.str()); } void PriorityDB::Impl::Delete(const std::string& hash) { std::stringstream stream; stream << "DELETE FROM " << table_name_ << " WHERE hash='" << hash << "';"; execute_(stream.str()); } void PriorityDB::Impl::Update(const std::string& hash, const bool& on_disk) { std::stringstream stream; stream << "UPDATE " << table_name_ << " SET on_disk=" << on_disk << " WHERE hash='" << hash << "';"; execute_(stream.str()); } std::string PriorityDB::Impl::GetHighestHash(bool& on_disk) { std::stringstream stream; stream << "SELECT hash, on_disk FROM " << table_name_ << " ORDER BY priority DESC LIMIT 1;"; auto response = execute_(stream.str()); std::string hash; if (!response.empty()) { auto record = response[0]; if (!record.empty()) { hash = record["hash"]; on_disk = std::stoi(record["on_disk"]); } } return hash; } std::string PriorityDB::Impl::GetLowestMemoryHash() { std::stringstream stream; stream << "SELECT hash FROM " << table_name_ << " WHERE on_disk=" << false << " ORDER BY priority ASC LIMIT 1;"; auto response = execute_(stream.str()); std::string hash; if (!response.empty()) { auto record = response[0]; if (!record.empty()) { hash = record["hash"]; } } return hash; } std::string PriorityDB::Impl::GetLowestDiskHash() { std::stringstream stream; stream << "SELECT hash FROM " << table_name_ << " WHERE on_disk=" << true << " ORDER BY priority ASC LIMIT 1;"; auto response = execute_(stream.str()); std::string hash; if (!response.empty()) { auto record = response[0]; if (!record.empty()) { hash = record["hash"]; } } return hash; } bool PriorityDB::Impl::Full() { std::stringstream stream; stream << "SELECT SUM(size) FROM " << table_name_ << " WHERE on_disk=" << true << ";"; auto response = execute_(stream.str()); unsigned long long total = 0; if (!response.empty()) { auto record = response[0]; if (!record.empty()) { total = std::stoi(record["SUM(size)"]); } } return total > max_size_; } std::unique_ptr<sqlite3, std::function<int(sqlite3*)>> PriorityDB::Impl::open_db_() { sqlite3* sqlite_db; sqlite3_open(table_path_.data(), &sqlite_db); return std::unique_ptr<sqlite3, std::function<int(sqlite3*)>>(sqlite_db, sqlite3_close); } bool PriorityDB::Impl::check_table_() { std::stringstream stream; stream << "SELECT name FROM sqlite_master WHERE type='table' AND name='" << table_name_ << "';"; auto response = execute_(stream.str()); return !response.empty(); } void PriorityDB::Impl::create_table_() { std::stringstream stream; stream << "CREATE TABLE " << table_name_ << "(" << "id INTEGER PRIMARY KEY AUTOINCREMENT," << "priority UNSIGNED BIGINT NOT NULL," << "hash TEXT NOT NULL," << "size UNSIGNED BIGINT NOT NULL," << "on_disk BOOL NOT NULL" << ");"; execute_(stream.str()); } std::vector<Record>PriorityDB::Impl::execute_(const std::string& sql) { std::vector<Record> response; auto db = open_db_(); char* error; int rc = sqlite3_exec(db.get(), sql.data(), callback, &response, &error); if (rc != SQLITE_OK) { std::cout << "Error: " << error << std::endl; sqlite3_free(error); } return response; } // Bridge PriorityDB::PriorityDB(const unsigned long long& max_size) : pimpl_{ new Impl{max_size} } {} PriorityDB::~PriorityDB() {} int PriorityDB::Open(const std::string& path) { return pimpl_->Open(path); } void PriorityDB::Insert(const unsigned long long& priority, const std::string& hash, const unsigned long long& size, const bool& on_disk) { pimpl_->Insert(priority, hash, size, on_disk); } void PriorityDB::Delete(const std::string& hash) { pimpl_->Delete(hash); } void PriorityDB::Update(const std::string& hash, const bool& on_disk) { pimpl_->Update(hash, on_disk); } std::string PriorityDB::GetHighestHash(bool& on_disk) { return pimpl_->GetHighestHash(on_disk); } std::string PriorityDB::GetLowestMemoryHash() { return pimpl_->GetLowestMemoryHash(); } std::string PriorityDB::GetLowestDiskHash() { return pimpl_->GetLowestDiskHash(); } bool PriorityDB::Full() { return pimpl_->Full(); } <commit_msg>Move typedef into private namespace<commit_after>#include "prioritydb.h" #include <functional> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <vector> #include <sqlite3.h> static int callback(void* response_ptr, int num_values, char** values, char** names) { auto response = (std::vector<Record>*) response_ptr; auto record = Record(); for (int i = 0; i < num_values; ++i) { if (values[i]) { record[names[i]] = values[i]; } } response->push_back(record); return 0; } class PriorityDB::Impl { public: Impl(const unsigned long long& max_size) : max_size_{max_size} {} int Open(const std::string& path); void Insert(const unsigned long long& priority, const std::string& hash, const unsigned long long& size, const bool& on_disk); void Delete(const std::string& hash); void Update(const std::string& hash, const bool& on_disk); std::string GetHighestHash(bool& on_disk); std::string GetLowestMemoryHash(); std::string GetLowestDiskHash(); bool Full(); private: std::string table_path_; std::string table_name_; unsigned long long max_size_; typedef std::map<std::string, std::string> Record; std::unique_ptr<sqlite3, std::function<int(sqlite3*)>> open_db_(); bool check_table_(); void create_table_(); std::vector<Record> execute_(const std::string& sql); }; int PriorityDB::Impl::Open(const std::string& path) { table_path_ = path; table_name_ = "prism_data"; if (!check_table_()) { create_table_(); } check_table_(); return 0; } void PriorityDB::Impl::Insert(const unsigned long long& priority, const std::string& hash, const unsigned long long& size, const bool& on_disk) { std::stringstream stream; stream << "INSERT INTO " << table_name_ << "(priority, hash, size, on_disk)" << "VALUES" << "(" << priority << "," << "'" << hash << "'," << size << "," << on_disk << ");"; execute_(stream.str()); } void PriorityDB::Impl::Delete(const std::string& hash) { std::stringstream stream; stream << "DELETE FROM " << table_name_ << " WHERE hash='" << hash << "';"; execute_(stream.str()); } void PriorityDB::Impl::Update(const std::string& hash, const bool& on_disk) { std::stringstream stream; stream << "UPDATE " << table_name_ << " SET on_disk=" << on_disk << " WHERE hash='" << hash << "';"; execute_(stream.str()); } std::string PriorityDB::Impl::GetHighestHash(bool& on_disk) { std::stringstream stream; stream << "SELECT hash, on_disk FROM " << table_name_ << " ORDER BY priority DESC LIMIT 1;"; auto response = execute_(stream.str()); std::string hash; if (!response.empty()) { auto record = response[0]; if (!record.empty()) { hash = record["hash"]; on_disk = std::stoi(record["on_disk"]); } } return hash; } std::string PriorityDB::Impl::GetLowestMemoryHash() { std::stringstream stream; stream << "SELECT hash FROM " << table_name_ << " WHERE on_disk=" << false << " ORDER BY priority ASC LIMIT 1;"; auto response = execute_(stream.str()); std::string hash; if (!response.empty()) { auto record = response[0]; if (!record.empty()) { hash = record["hash"]; } } return hash; } std::string PriorityDB::Impl::GetLowestDiskHash() { std::stringstream stream; stream << "SELECT hash FROM " << table_name_ << " WHERE on_disk=" << true << " ORDER BY priority ASC LIMIT 1;"; auto response = execute_(stream.str()); std::string hash; if (!response.empty()) { auto record = response[0]; if (!record.empty()) { hash = record["hash"]; } } return hash; } bool PriorityDB::Impl::Full() { std::stringstream stream; stream << "SELECT SUM(size) FROM " << table_name_ << " WHERE on_disk=" << true << ";"; auto response = execute_(stream.str()); unsigned long long total = 0; if (!response.empty()) { auto record = response[0]; if (!record.empty()) { total = std::stoi(record["SUM(size)"]); } } return total > max_size_; } std::unique_ptr<sqlite3, std::function<int(sqlite3*)>> PriorityDB::Impl::open_db_() { sqlite3* sqlite_db; sqlite3_open(table_path_.data(), &sqlite_db); return std::unique_ptr<sqlite3, std::function<int(sqlite3*)>>(sqlite_db, sqlite3_close); } bool PriorityDB::Impl::check_table_() { std::stringstream stream; stream << "SELECT name FROM sqlite_master WHERE type='table' AND name='" << table_name_ << "';"; auto response = execute_(stream.str()); return !response.empty(); } void PriorityDB::Impl::create_table_() { std::stringstream stream; stream << "CREATE TABLE " << table_name_ << "(" << "id INTEGER PRIMARY KEY AUTOINCREMENT," << "priority UNSIGNED BIGINT NOT NULL," << "hash TEXT NOT NULL," << "size UNSIGNED BIGINT NOT NULL," << "on_disk BOOL NOT NULL" << ");"; execute_(stream.str()); } std::vector<PriorityDB::Impl::Record>PriorityDB::Impl::execute_(const std::string& sql) { std::vector<Record> response; auto db = open_db_(); char* error; int rc = sqlite3_exec(db.get(), sql.data(), callback, &response, &error); if (rc != SQLITE_OK) { std::cout << "Error: " << error << std::endl; sqlite3_free(error); } return response; } // Bridge PriorityDB::PriorityDB(const unsigned long long& max_size) : pimpl_{ new Impl{max_size} } {} PriorityDB::~PriorityDB() {} int PriorityDB::Open(const std::string& path) { return pimpl_->Open(path); } void PriorityDB::Insert(const unsigned long long& priority, const std::string& hash, const unsigned long long& size, const bool& on_disk) { pimpl_->Insert(priority, hash, size, on_disk); } void PriorityDB::Delete(const std::string& hash) { pimpl_->Delete(hash); } void PriorityDB::Update(const std::string& hash, const bool& on_disk) { pimpl_->Update(hash, on_disk); } std::string PriorityDB::GetHighestHash(bool& on_disk) { return pimpl_->GetHighestHash(on_disk); } std::string PriorityDB::GetLowestMemoryHash() { return pimpl_->GetLowestMemoryHash(); } std::string PriorityDB::GetLowestDiskHash() { return pimpl_->GetLowestDiskHash(); } bool PriorityDB::Full() { return pimpl_->Full(); } <|endoftext|>
<commit_before>/** * Package: eVias Core unitary tests * * Copyright (c) 2010 - 2011 Grégory Saive * * For more informations about the licensing of this product, please refer * to the LICENCE file in the root application directory. * */ #include "../core/string_utils.hpp" #include "../application/console.hpp" #include "library_test_suite.hpp" // unitary test classes include #include <vector> #include <string> int main (int argc, char* args[]) { using namespace std; using evias::core::test::eviasTestSuite; using evias::core::test::testResult; using evias::application::consoleParser; using evias::core::in_vector; string project = "eVias C++ library unitary test suite"; string usage = " \ ./suite_execution.exe [--skip config,json,sqlobjects,views,dbobjects,network,regex,functional] \ [--only config,json,sqlobjects,views,dbobjects,network,regex,functional] \ [--verbosity quiet|normal|verbose] \ "; consoleParser* suiteCallArgs = new consoleParser(project, usage, argc, args); suiteCallArgs->canEmptyCall(true) ->addAllowedArg("--skip") ->addAllowedArg("--only") ->addAllowedArg("--verbosity") ->parseAll(); map<string,string> callArgs = suiteCallArgs->readData(); // suite execution call configuration // basically we test everything. bool testConfigFiles = true; bool testJson = true; bool testSqlObjects = true; bool testViews = true; bool testDbObjects = true; bool testNetwork = true; bool testRegExp = true; bool testFunctional = true; bool hasVerb = (callArgs.find("--verbosity") != callArgs.end()); bool hasOnly = (callArgs.find("--only") != callArgs.end()); bool hasSkip = (callArgs.find("--skip") != callArgs.end()); // callArg[KEY] access facility string usingOption = "default"; if (hasOnly && callArgs["--only"].size() > 0) { usingOption = "--only"; } else if (hasSkip && callArgs["--skip"].size() > 0) { usingOption = "--skip"; } // get verbosity configuration (or not).. int verbosity = evias::core::test::VERBOSE; if (hasVerb && callArgs["--verbosity"].size() > 0) { string sv = callArgs["--verbosity"]; if (sv == "1" || sv == "quiet") verbosity = evias::core::test::QUIET; else if (sv == "2" || sv == "normal") verbosity = evias::core::test::NORMAL; } // process call arguments if (usingOption == "--only" || usingOption == "--skip") { // we have a workable option (size > 0) vector<string> optionKeys; string optionData = callArgs[usingOption]; evias::core::trim(optionData, " "); if (optionData.find(",") != string::npos) optionKeys = evias::core::split(optionData.append(","), ','); // multi key ',' separated else optionKeys.push_back(optionData); // single key // if we are in "skip mode" => we test everything except present key(s) // if we are in "only mode" => we test nothing but present key(s) bool initTest = true; // everything if (usingOption == "--only") { initTest = false; } testConfigFiles = testJson = testSqlObjects = testViews = testDbObjects = testNetwork = testRegExp = (initTest); // present in option key(s) means having to change the data if (in_vector("config", optionKeys)) testConfigFiles = ! initTest; if (in_vector("json", optionKeys)) testJson = ! initTest; if (in_vector("sqlobjects", optionKeys)) testSqlObjects = ! initTest; if (in_vector("views", optionKeys)) testViews = ! initTest; if (in_vector("dbobjects", optionKeys)) testDbObjects = ! initTest; if (in_vector("network", optionKeys)) testNetwork = ! initTest; if (in_vector("regex", optionKeys)) testRegExp = ! initTest; if (in_vector("functional", optionKeys)) testFunctional = ! initTest; } // configure the test suite eviasTestSuite* librarySuite = new eviasTestSuite(); // configure suite librarySuite->setVerbosity((evias::core::test::unitTestVerbosity)verbosity); librarySuite->setTestConfig(testConfigFiles) ->setTestJSON(testJson) ->setTestSQL(testSqlObjects) ->setTestViews(testViews) ->setTestDatabase(testDbObjects) ->setTestNetwork(testNetwork) ->setTestRegExp(testRegExp) ->setTestFunctional(testFunctional); // execute suite librarySuite->bootstrap(argc, args); int returnCode = librarySuite->execute(); librarySuite->shutdown(); delete librarySuite; return returnCode; } <commit_msg>bugfix: add testFunctional initialization<commit_after>/** * Package: eVias Core unitary tests * * Copyright (c) 2010 - 2011 Grégory Saive * * For more informations about the licensing of this product, please refer * to the LICENCE file in the root application directory. * */ #include "../core/string_utils.hpp" #include "../application/console.hpp" #include "library_test_suite.hpp" // unitary test classes include #include <vector> #include <string> int main (int argc, char* args[]) { using namespace std; using evias::core::test::eviasTestSuite; using evias::core::test::testResult; using evias::application::consoleParser; using evias::core::in_vector; string project = "eVias C++ library unitary test suite"; string usage = " \ ./suite_execution.exe [--skip config,json,sqlobjects,views,dbobjects,network,regex,functional] \ [--only config,json,sqlobjects,views,dbobjects,network,regex,functional] \ [--verbosity quiet|normal|verbose] \ "; consoleParser* suiteCallArgs = new consoleParser(project, usage, argc, args); suiteCallArgs->canEmptyCall(true) ->addAllowedArg("--skip") ->addAllowedArg("--only") ->addAllowedArg("--verbosity") ->parseAll(); map<string,string> callArgs = suiteCallArgs->readData(); // suite execution call configuration // basically we test everything. bool testConfigFiles = true; bool testJson = true; bool testSqlObjects = true; bool testViews = true; bool testDbObjects = true; bool testNetwork = true; bool testRegExp = true; bool testFunctional = true; bool hasVerb = (callArgs.find("--verbosity") != callArgs.end()); bool hasOnly = (callArgs.find("--only") != callArgs.end()); bool hasSkip = (callArgs.find("--skip") != callArgs.end()); // callArg[KEY] access facility string usingOption = "default"; if (hasOnly && callArgs["--only"].size() > 0) { usingOption = "--only"; } else if (hasSkip && callArgs["--skip"].size() > 0) { usingOption = "--skip"; } // get verbosity configuration (or not).. int verbosity = evias::core::test::VERBOSE; if (hasVerb && callArgs["--verbosity"].size() > 0) { string sv = callArgs["--verbosity"]; if (sv == "1" || sv == "quiet") verbosity = evias::core::test::QUIET; else if (sv == "2" || sv == "normal") verbosity = evias::core::test::NORMAL; } // process call arguments if (usingOption == "--only" || usingOption == "--skip") { // we have a workable option (size > 0) vector<string> optionKeys; string optionData = callArgs[usingOption]; evias::core::trim(optionData, " "); if (optionData.find(",") != string::npos) optionKeys = evias::core::split(optionData.append(","), ','); // multi key ',' separated else optionKeys.push_back(optionData); // single key // if we are in "skip mode" => we test everything except present key(s) // if we are in "only mode" => we test nothing but present key(s) bool initTest = true; // everything if (usingOption == "--only") { initTest = false; } testConfigFiles = testJson = testSqlObjects = testViews = testDbObjects = testNetwork = testRegExp = testFunctional = (initTest); // present in option key(s) means having to change the data if (in_vector("config", optionKeys)) testConfigFiles = ! initTest; if (in_vector("json", optionKeys)) testJson = ! initTest; if (in_vector("sqlobjects", optionKeys)) testSqlObjects = ! initTest; if (in_vector("views", optionKeys)) testViews = ! initTest; if (in_vector("dbobjects", optionKeys)) testDbObjects = ! initTest; if (in_vector("network", optionKeys)) testNetwork = ! initTest; if (in_vector("regex", optionKeys)) testRegExp = ! initTest; if (in_vector("functional", optionKeys)) testFunctional = ! initTest; } // configure the test suite eviasTestSuite* librarySuite = new eviasTestSuite(); // configure suite librarySuite->setVerbosity((evias::core::test::unitTestVerbosity)verbosity); librarySuite->setTestConfig(testConfigFiles) ->setTestJSON(testJson) ->setTestSQL(testSqlObjects) ->setTestViews(testViews) ->setTestDatabase(testDbObjects) ->setTestNetwork(testNetwork) ->setTestRegExp(testRegExp) ->setTestFunctional(testFunctional); // execute suite librarySuite->bootstrap(argc, args); int returnCode = librarySuite->execute(); librarySuite->shutdown(); delete librarySuite; return returnCode; } <|endoftext|>
<commit_before>/** * @file dmesg.cc * @brief Dmesg Class file */ #include "dmesg.h" #include <android/log.h> namespace com { namespace eolwral { namespace osmonitor { namespace core { dmesg::dmesg() { this->_bootTime = 0; } dmesg::~dmesg() { // clean up _curDemsgList this->clearDataSet((std::vector<google::protobuf::Message*>&) this->_curDmesgList); } void dmesg::getBootTime() { // get uptime long uptime = 0; FILE *uptimeFile = fopen(SYS_BOOT_TIME, "r"); if(uptimeFile) { if ( fscanf(uptimeFile, "%lu.%*lu", &uptime) != 1 ) uptime = 0; fclose(uptimeFile); } time_t currentTime = time(0); _bootTime = currentTime - uptime; } void dmesg::refresh() { // clean up this->clearDataSet((std::vector<google::protobuf::Message*>&) this->_curDmesgList); // refresh boot time if (this->_bootTime == 0) this->getBootTime(); char* buffer = 0; char procLine[BufferSize]; char* procLineEnd = 0; unsigned int procLineLen = 0; unsigned int offsetStart = 0; unsigned int bufferSize = 0; bufferSize = klogctl(KLOG_SIZE_BUFFER, 0, 0); if (bufferSize <= 0) bufferSize = KLOG_BUF_LEN; buffer = (char *) malloc(bufferSize + 1); if (buffer == 0) return; int readSize = klogctl(KLOG_READ_ALL, buffer, bufferSize); if(readSize < 0) { free(buffer); return; } // set C style end buffer[readSize] = 0; while((procLineEnd = strstr( buffer + offsetStart, "\n" )) != 0) { procLineLen = procLineEnd - (buffer + offsetStart); // every line must less than BufferSize if(procLineLen >= BufferSize) procLineLen = BufferSize-1; // copy message into line buffer strncpy(procLine, buffer + offsetStart, procLineLen); procLine[procLineLen] = '\0'; // move to next block offsetStart = offsetStart + procLineLen + 1; // prepare a Dmesginfo object dmesgInfo* curDmesgInfo = new dmesgInfo(); char message[BufferSize]; char level = '\x0'; unsigned long seconds = 0; int itemCounts= 0; memset(message, 0, BufferSize); // detect log message format and parse it if(procLine[3] == '[') { itemCounts = sscanf(procLine, "<%c>[%lu.%*06lu] %[^\n]", &level, &seconds, message); curDmesgInfo->set_seconds(_bootTime+seconds); } else { curDmesgInfo->set_seconds(0); itemCounts = sscanf(procLine, "<%c>%[^\n]", &level, message); } switch(level) { case '0': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_EMERGENCY); break; case '1': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_ALERT); break; case '2': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_CRITICAL); break; case '3': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_ERROR); break; case '4': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_WARNING); break; case '5': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_NOTICE); break; case '6': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_INFORMATION); break; case '7': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_DEBUG); break; default: curDmesgInfo->set_level(dmesgInfo_dmesgLevel_INFORMATION); break; } curDmesgInfo->set_message(message); // push log into list if (itemCounts == 3) this->_curDmesgList.push_back(curDmesgInfo); else delete curDmesgInfo; // EOF ? if(offsetStart >= readSize) break; } // release memory if (buffer != 0) free(buffer); } const std::vector<google::protobuf::Message*>& dmesg::getData() { return ((const std::vector<google::protobuf::Message*>&) this->_curDmesgList); } } } } } <commit_msg>fix defect - CID 84869: Argument cannot be negative (NEGATIVE_RETURNS)<commit_after>/** * @file dmesg.cc * @brief Dmesg Class file */ #include "dmesg.h" #include <android/log.h> namespace com { namespace eolwral { namespace osmonitor { namespace core { dmesg::dmesg() { this->_bootTime = 0; } dmesg::~dmesg() { // clean up _curDemsgList this->clearDataSet((std::vector<google::protobuf::Message*>&) this->_curDmesgList); } void dmesg::getBootTime() { // get uptime long uptime = 0; FILE *uptimeFile = fopen(SYS_BOOT_TIME, "r"); if(uptimeFile) { if ( fscanf(uptimeFile, "%lu.%*lu", &uptime) != 1 ) uptime = 0; fclose(uptimeFile); } time_t currentTime = time(0); _bootTime = currentTime - uptime; } void dmesg::refresh() { // clean up this->clearDataSet((std::vector<google::protobuf::Message*>&) this->_curDmesgList); // refresh boot time if (this->_bootTime == 0) this->getBootTime(); char* buffer = 0; int bufferSize = 0; char procLine[BufferSize]; char* procLineEnd = 0; unsigned int procLineLen = 0; unsigned int offsetStart = 0; bufferSize = klogctl(KLOG_SIZE_BUFFER, 0, 0); if (bufferSize <= 0) bufferSize = KLOG_BUF_LEN; buffer = (char *) malloc(bufferSize + 1); if (buffer == 0) return; int readSize = klogctl(KLOG_READ_ALL, buffer, bufferSize); if(readSize < 0) { free(buffer); return; } // set C style end buffer[readSize] = 0; while((procLineEnd = strstr( buffer + offsetStart, "\n" )) != 0) { procLineLen = procLineEnd - (buffer + offsetStart); // every line must less than BufferSize if(procLineLen >= BufferSize) procLineLen = BufferSize-1; // copy message into line buffer strncpy(procLine, buffer + offsetStart, procLineLen); procLine[procLineLen] = '\0'; // move to next block offsetStart = offsetStart + procLineLen + 1; // prepare a Dmesginfo object dmesgInfo* curDmesgInfo = new dmesgInfo(); char message[BufferSize]; char level = '\x0'; unsigned long seconds = 0; int itemCounts= 0; memset(message, 0, BufferSize); // detect log message format and parse it if(procLine[3] == '[') { itemCounts = sscanf(procLine, "<%c>[%lu.%*06lu] %[^\n]", &level, &seconds, message); curDmesgInfo->set_seconds(_bootTime+seconds); } else { curDmesgInfo->set_seconds(0); itemCounts = sscanf(procLine, "<%c>%[^\n]", &level, message); } switch(level) { case '0': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_EMERGENCY); break; case '1': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_ALERT); break; case '2': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_CRITICAL); break; case '3': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_ERROR); break; case '4': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_WARNING); break; case '5': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_NOTICE); break; case '6': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_INFORMATION); break; case '7': curDmesgInfo->set_level(dmesgInfo_dmesgLevel_DEBUG); break; default: curDmesgInfo->set_level(dmesgInfo_dmesgLevel_INFORMATION); break; } curDmesgInfo->set_message(message); // push log into list if (itemCounts == 3) this->_curDmesgList.push_back(curDmesgInfo); else delete curDmesgInfo; // EOF ? if(offsetStart >= readSize) break; } // release memory if (buffer != 0) free(buffer); } const std::vector<google::protobuf::Message*>& dmesg::getData() { return ((const std::vector<google::protobuf::Message*>&) this->_curDmesgList); } } } } } <|endoftext|>
<commit_before>#include "zc_connection.h" #include <zerocopy/read_until.h> #include <boost/bind.hpp> #include <boost/algorithm/string/predicate.hpp> #include "../common/rfc822.h" const std::string ZcConnection::endOfData = "\r\n.\r\n"; void ZcConnection::start() { writeGreeting(); } ZcConnection::~ZcConnection () { // std::cout << "Connection destroyed\n"; } void ZcConnection::writeGreeting() { std::ostream os(&outBuf); os << "220 smtp11.mail.yandex.net async_server SMTP\r\n" << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleGreetingWrite, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleGreetingWrite( const boost::system::error_code& e, std::size_t /*bytes*/) { if (! e) readCommand(); else std::cout << "ZcConnection::handleGreetingWrite: " << e.message () << "\n"; } void ZcConnection::readCommand() { zerocopy::async_read_until(socket(), inBuf, "\r\n", strand_.wrap ( boost::bind(&ZcConnection::handleCommand, shared_from_this(), boost::asio::placeholders::error))); } std::string ZcConnection::getCommand() { std::istream s(&inBuf); std::string buf; std::getline(s, buf); if (!buf.empty() && buf.back() == '\r') { buf.pop_back(); } return buf; } void ZcConnection::handleCommand(const boost::system::error_code& e) { if (e) { std::cout << "ZcConnection::handleCommand: " << e.message () << "\n"; return; } const std::string cmd = getCommand(); if( boost::algorithm::iequals (cmd, "DATA") ) { writeDataGreeting(); } else if( boost::algorithm::iequals (cmd, "QUIT") ) { writeGoodbye(); } else if( boost::algorithm::istarts_with (cmd, "HELO") ) { commandReply(); } else if( boost::algorithm::istarts_with (cmd, "MAIL ") ) { commandReply(); } else if( boost::algorithm::istarts_with (cmd, "RCPT ") ) { commandReply(); } else { std::cout << "bad command: " << cmd << "\n"; writeGoodbye(); } } void ZcConnection::commandReply( const std::string & msg ) { std::ostream os(&outBuf); os << msg << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleCommandReplyWrite, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleCommandReplyWrite(const boost::system::error_code& e, std::size_t bytes) { if (! e) readCommand(); else std::cout << "ZcConnection::handleCommandReplyWrite (bytes=" << bytes << ": " << e.message () << "\n"; } void ZcConnection::writeDataGreeting() { std::ostream os(&outBuf); os << "354 Enter mail, end with \".\" on a line by itself (" << sent_ << ")\r\n" << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleDataGreetingWrite, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleDataGreetingWrite(const boost::system::error_code& e, std::size_t /*bytes*/) { if (!e) readData(); else std::cout << "ZcConnection::handleDataGreetingWrite: " << e.message () << "\n"; } void ZcConnection::readData() { zerocopy::async_read_until(socket(), inBuf, endOfData, strand_.wrap ( boost::bind(&ZcConnection::handleData, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleData(const boost::system::error_code& ec, std::size_t bytes) { if (ec) { std::cout << "ZcConnection::handleData: " << ec.message () << "\n"; return; } sent_ = bytes; #if 1 try { std::istream s(&inBuf); s.unsetf (std::ios::skipws); if( rfc822::parse(s) ) { dataReply(); } else { dataReply("451 rfc2822 violation\r\n"); } } catch ( const std::exception & e ) { dataReply(std::string("451 ") + e.what() + "\r\n"); } //Cleanup buffer since the parser read until terminal "." // inBuf.consume(std::string(endOfData).length()); inBuf.consume (inBuf.size ()); #else inBuf.consume (inBuf.size ()); dataReply(); #endif } void ZcConnection::dataReply( const std::string & msg ) { std::ostream os(&outBuf); os << msg << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleDataReply, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleDataReply(const boost::system::error_code& e, std::size_t /*bytes*/) { if (!e) { readCommand(); } else std::cout << "ZcConnection::handleDataReply: " << e.message () << "\n"; } void ZcConnection::writeGoodbye() { std::ostream os(&outBuf); os << "221 smtp11.mail.yandex.net async_server SMTP\r\n" << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleWriteGoodbye, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleWriteGoodbye(const boost::system::error_code&, std::size_t /*bytes*/) { shutdown(); } void ZcConnection::shutdown() { boost::system::error_code ignored_ec; socket().shutdown(tcp::socket::shutdown_both, ignored_ec); } <commit_msg>async_server is compatible with zerocopy completely<commit_after>#include "zc_connection.h" #include <zerocopy/read_until.h> #include <boost/bind.hpp> #include <boost/algorithm/string/predicate.hpp> #include "../common/rfc822.h" const std::string ZcConnection::endOfData = "\r\n.\r\n"; void ZcConnection::start() { writeGreeting(); } ZcConnection::~ZcConnection () { // std::cout << "Connection destroyed\n"; } void ZcConnection::writeGreeting() { std::ostream os(&outBuf); os << "220 smtp11.mail.yandex.net async_server SMTP\r\n" << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleGreetingWrite, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleGreetingWrite( const boost::system::error_code& e, std::size_t /*bytes*/) { if (! e) readCommand(); else std::cout << "ZcConnection::handleGreetingWrite: " << e.message () << "\n"; } void ZcConnection::readCommand() { zerocopy::async_read_until(socket(), inBuf, "\r\n", strand_.wrap ( boost::bind(&ZcConnection::handleCommand, shared_from_this(), boost::asio::placeholders::error))); } std::string ZcConnection::getCommand() { std::istream s(&inBuf); std::string buf; std::getline(s, buf); if (!buf.empty() && buf.back() == '\r') { buf.pop_back(); } return buf; } void ZcConnection::handleCommand(const boost::system::error_code& e) { if (e) { std::cout << "ZcConnection::handleCommand: " << e.message () << "\n"; return; } const std::string cmd = getCommand(); if( boost::algorithm::iequals (cmd, "DATA") ) { writeDataGreeting(); } else if( boost::algorithm::iequals (cmd, "QUIT") ) { writeGoodbye(); } else if( boost::algorithm::istarts_with (cmd, "HELO") ) { commandReply(); } else if( boost::algorithm::istarts_with (cmd, "MAIL ") ) { commandReply(); } else if( boost::algorithm::istarts_with (cmd, "RCPT ") ) { commandReply(); } else { std::cout << "bad command: " << cmd << "\n"; writeGoodbye(); } } void ZcConnection::commandReply( const std::string & msg ) { std::ostream os(&outBuf); os << msg << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleCommandReplyWrite, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleCommandReplyWrite(const boost::system::error_code& e, std::size_t bytes) { if (! e) readCommand(); else std::cout << "ZcConnection::handleCommandReplyWrite (bytes=" << bytes << ": " << e.message () << "\n"; } void ZcConnection::writeDataGreeting() { std::ostream os(&outBuf); os << "354 Enter mail, end with \".\" on a line by itself (" << sent_ << ")\r\n" << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleDataGreetingWrite, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleDataGreetingWrite(const boost::system::error_code& e, std::size_t /*bytes*/) { if (!e) readData(); else std::cout << "ZcConnection::handleDataGreetingWrite: " << e.message () << "\n"; } void ZcConnection::readData() { zerocopy::async_read_until(socket(), inBuf, endOfData, strand_.wrap ( boost::bind(&ZcConnection::handleData, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleData(const boost::system::error_code& ec, std::size_t bytes) { if (ec) { std::cout << "ZcConnection::handleData: " << ec.message () << "\n"; return; } sent_ = bytes; #if 1 try { if( rfc822::parse(inBuf.begin(), inBuf.end()) ) { inBuf.detach(inBuf.end()); dataReply(); } else { dataReply("451 rfc2822 violation\r\n"); } } catch ( const std::exception & e ) { dataReply(std::string("451 ") + e.what() + "\r\n"); } //Cleanup buffer since the parser read until terminal "." // inBuf.consume(std::string(endOfData).length()); inBuf.consume (inBuf.size ()); #else inBuf.consume (inBuf.size ()); dataReply(); #endif } void ZcConnection::dataReply( const std::string & msg ) { std::ostream os(&outBuf); os << msg << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleDataReply, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleDataReply(const boost::system::error_code& e, std::size_t /*bytes*/) { if (!e) { readCommand(); } else std::cout << "ZcConnection::handleDataReply: " << e.message () << "\n"; } void ZcConnection::writeGoodbye() { std::ostream os(&outBuf); os << "221 smtp11.mail.yandex.net async_server SMTP\r\n" << std::flush; boost::asio::async_write(socket(), outBuf, strand_.wrap ( boost::bind(&ZcConnection::handleWriteGoodbye, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ZcConnection::handleWriteGoodbye(const boost::system::error_code&, std::size_t /*bytes*/) { shutdown(); } void ZcConnection::shutdown() { boost::system::error_code ignored_ec; socket().shutdown(tcp::socket::shutdown_both, ignored_ec); } <|endoftext|>
<commit_before>// // Created by Miguel Rentes on 11/01/2017. // #include "introduction.h" int main(void) { unsigned int n, q; cin >> n >> q; string line; unsigned int* array[n]; // array with n pointers to the other arrays vector<string> array_indexes; vector<string> queries; // vector to hold the queries if ( cin.peek() == '\n' ) cin.ignore(); for (int i = 0; i < n; i++) { std::getline(cin, line); istringstream iss(line); copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(array_indexes)); } for (int i = 0; i < q; i++) { std::getline(cin, line); istringstream iss(line); copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(queries)); } cout << "indexes: " << endl; for (std::vector<string>::const_iterator i = array_indexes.begin(); i != array_indexes.end(); ++i) { cout << *i << endl; } cout << "queries: " << endl; for (std::vector<string>::const_iterator i = queries.begin(); i != queries.end(); ++i) { cout << *i << endl; } return EXIT_SUCCESS; } <commit_msg>Starts solution for Variable Sized Arrays challenge.<commit_after>// // Created by Miguel Rentes on 11/01/2017. // #include "introduction.h" int main(void) { unsigned int n, q; cin >> n >> q; string line; unsigned int* array[n]; // array with n pointers to the other arrays vector<string> array_indexes; vector<string> queries; // vector to hold the queries if (cin.peek() == '\n') cin.ignore(); for (int i = 0; i < n; i++) { std::getline(cin, line); istringstream iss(line); copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(array_indexes)); } for (int i = 0; i < q; i++) { std::getline(cin, line); istringstream iss(line); copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(queries)); } cout << "indexes: " << endl; for (std::vector<string>::const_iterator i = array_indexes.begin(); i != array_indexes.end(); ++i) { cout << *i << endl; } cout << "queries: " << endl; for (std::vector<string>::const_iterator i = queries.begin(); i != queries.end(); ++i) { cout << *i << endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* (C) 2016 Marc Stevens. This file is part of fplll. fplll is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ #include "enumerate_ext.h" #include <fplll/defs.h> #if FPLLL_MAX_PARALLEL_ENUM_DIM != 0 #include "../enum-parallel/enumlib.h" #endif #ifdef FPLLL_EXTENUM_FUNC extern extenum_fc_enumerate FPLLL_EXTENUM_FUNC; #endif FPLLL_BEGIN_NAMESPACE // set & get external enumerator (nullptr => disabled) #ifdef FPLLL_EXTENUM_FUNC std::function<extenum_fc_enumerate> fplll_extenum = FPLLL_EXTENUM_FUNC; #else #if FPLLL_MAX_PARALLEL_ENUM_DIM != 0 std::function<extenum_fc_enumerate> fplll_extenum = enumlib::enumlib_enumerate; #else std::function<extenum_fc_enumerate> fplll_extenum = nullptr; #endif #endif void set_external_enumerator(std::function<extenum_fc_enumerate> extenum) { fplll_extenum = extenum; } std::function<extenum_fc_enumerate> get_external_enumerator() { return fplll_extenum; } template <typename ZT, typename FT> bool ExternalEnumeration<ZT, FT>::enumerate(int first, int last, FT &fmaxdist, long fmaxdistexpo, const vector<enumf> &pruning, bool dual) { using namespace std::placeholders; if (fplll_extenum == nullptr) return false; if (last == -1) last = _gso.d; _first = first; _dual = dual; _pruning = pruning; _d = last - _first; _fx.resize(_d); FPLLL_CHECK(_pruning.empty() || int(_pruning.size()) == _d, "ExternalEnumeration: non-empty pruning vector dimension does not match"); FT fr, fmu, fmaxdistnorm; long rexpo; _normexp = -1; for (int i = 0; i < _d; ++i) { fr = _gso.get_r_exp(i + first, i + first, rexpo); _normexp = max(_normexp, rexpo + fr.exponent()); } fmaxdistnorm.mul_2si(fmaxdist, dual ? _normexp - fmaxdistexpo : fmaxdistexpo - _normexp); _maxdist = fmaxdistnorm.get_d(GMP_RNDU); _evaluator.set_normexp(_normexp); // clang-format off _nodes = fplll_extenum(_d, _maxdist, std::bind(&ExternalEnumeration<ZT,FT>::callback_set_config, this, _1, _2, _3, _4, _5), std::bind(&ExternalEnumeration<ZT,FT>::callback_process_sol, this, _1, _2), std::bind(&ExternalEnumeration<ZT,FT>::callback_process_subsol, this, _1, _2, _3), _dual, _evaluator.findsubsols ); // clang-format on return _nodes[0] != ~uint64_t(0); } template <typename ZT, typename FT> void ExternalEnumeration<ZT, FT>::callback_set_config(enumf *mu, size_t mudim, bool mutranspose, enumf *rdiag, enumf *pruning) { FT fr, fmu; long rexpo; // Copy over the squared norms for the Gram-Schmidt vectors. // Note that these norms are normalised. for (int i = 0; i < _d; ++i) { fr = _gso.get_r_exp(i + _first, i + _first, rexpo); fr.mul_2si(fr, rexpo - _normexp); rdiag[i] = fr.get_d(); } // Now we copy the mu values from the gso matrix. if (mutranspose) { size_t offs = 0; for (int i = 0; i < _d; ++i, offs += mudim) { for (int j = i + 1; j < _d; ++j) { _gso.get_mu(fmu, j + _first, i + _first); /* mu[i][j]= */ mu[offs + j] = fmu.get_d(); } } } else { size_t offs = 0; for (int j = 0; j < _d; ++j, offs += mudim) { for (int i = 0; i < _d; ++i) { _gso.get_mu(fmu, j + _first, i + _first); /* mu[j][i] = */ mu[offs + i] = fmu.get_d(); } } } // if there's no pruning enabled then we just fill pruning with 1s if (_pruning.empty()) { for (int i = 0; i < _d; ++i) pruning[i] = 1.0; } else { // Otherwise we just copy over the pruning parameters for (int i = 0; i < _d; ++i) pruning[i] = _pruning[i]; } } template <typename ZT, typename FT> enumf ExternalEnumeration<ZT, FT>::callback_process_sol(enumf dist, enumf *sol) { for (int i = 0; i < _d; ++i) _fx[i] = sol[i]; _evaluator.eval_sol(_fx, dist, _maxdist); return _maxdist; } template <typename ZT, typename FT> void ExternalEnumeration<ZT, FT>::callback_process_subsol(enumf dist, enumf *subsol, int offset) { for (int i = 0; i < offset; ++i) _fx[i] = 0.0; for (int i = offset; i < _d; ++i) _fx[i] = subsol[i]; _evaluator.eval_sub_sol(offset, _fx, dist); } template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<double>>; #ifdef FPLLL_WITH_LONG_DOUBLE template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<long double>>; #endif #ifdef FPLLL_WITH_QD template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<dd_real>>; template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<qd_real>>; #endif #ifdef FPLLL_WITH_DPE template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<dpe_t>>; #endif template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<mpfr_t>>; template class ExternalEnumeration<Z_NR<long>, FP_NR<double>>; #ifdef FPLLL_WITH_LONG_DOUBLE template class ExternalEnumeration<Z_NR<long>, FP_NR<long double>>; #endif #ifdef FPLLL_WITH_QD template class ExternalEnumeration<Z_NR<long>, FP_NR<dd_real>>; template class ExternalEnumeration<Z_NR<long>, FP_NR<qd_real>>; #endif #ifdef FPLLL_WITH_DPE template class ExternalEnumeration<Z_NR<long>, FP_NR<dpe_t>>; #endif template class ExternalEnumeration<Z_NR<long>, FP_NR<mpfr_t>>; FPLLL_END_NAMESPACE <commit_msg>fix enum ext callback<commit_after>/* (C) 2016 Marc Stevens. This file is part of fplll. fplll is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ #include "enumerate_ext.h" #include <fplll/defs.h> #if FPLLL_MAX_PARALLEL_ENUM_DIM != 0 #include "../enum-parallel/enumlib.h" #endif #ifdef FPLLL_EXTENUM_FUNC extern extenum_fc_enumerate FPLLL_EXTENUM_FUNC; #endif FPLLL_BEGIN_NAMESPACE // set & get external enumerator (nullptr => disabled) #ifdef FPLLL_EXTENUM_FUNC std::function<extenum_fc_enumerate> fplll_extenum = FPLLL_EXTENUM_FUNC; #else #if FPLLL_MAX_PARALLEL_ENUM_DIM != 0 std::function<extenum_fc_enumerate> fplll_extenum = enumlib::enumlib_enumerate; #else std::function<extenum_fc_enumerate> fplll_extenum = nullptr; #endif #endif void set_external_enumerator(std::function<extenum_fc_enumerate> extenum) { fplll_extenum = extenum; } std::function<extenum_fc_enumerate> get_external_enumerator() { return fplll_extenum; } template <typename ZT, typename FT> bool ExternalEnumeration<ZT, FT>::enumerate(int first, int last, FT &fmaxdist, long fmaxdistexpo, const vector<enumf> &pruning, bool dual) { using namespace std::placeholders; if (fplll_extenum == nullptr) return false; if (last == -1) last = _gso.d; _first = first; _dual = dual; _pruning = pruning; _d = last - _first; _fx.resize(_d); FPLLL_CHECK(_pruning.empty() || int(_pruning.size()) == _d, "ExternalEnumeration: non-empty pruning vector dimension does not match"); FT fr, fmu, fmaxdistnorm; long rexpo; _normexp = -1; for (int i = 0; i < _d; ++i) { fr = _gso.get_r_exp(i + first, i + first, rexpo); _normexp = max(_normexp, rexpo + fr.exponent()); } fmaxdistnorm.mul_2si(fmaxdist, dual ? _normexp - fmaxdistexpo : fmaxdistexpo - _normexp); _maxdist = fmaxdistnorm.get_d(GMP_RNDU); _evaluator.set_normexp(_normexp); // clang-format off _nodes = fplll_extenum(_d, _maxdist, std::bind(&ExternalEnumeration<ZT,FT>::callback_set_config, this, _1, _2, _3, _4, _5), std::bind(&ExternalEnumeration<ZT,FT>::callback_process_sol, this, _1, _2), std::bind(&ExternalEnumeration<ZT,FT>::callback_process_subsol, this, _1, _2, _3), _dual, _evaluator.findsubsols ); // clang-format on return _nodes[0] != ~uint64_t(0); } template <typename ZT, typename FT> void ExternalEnumeration<ZT, FT>::callback_set_config(enumf *mu, size_t mudim, bool mutranspose, enumf *rdiag, enumf *pruning) { FT fr, fmu; long rexpo; // Copy over the squared norms for the Gram-Schmidt vectors. // Note that these norms are normalised. for (int i = 0; i < _d; ++i) { fr = _gso.get_r_exp(i + _first, i + _first, rexpo); fr.mul_2si(fr, rexpo - _normexp); rdiag[i] = fr.get_d(); } // Now we copy the mu values from the gso matrix. if (mutranspose) { size_t offs = 0; for (int i = 0; i < _d; ++i, offs += mudim) { for (int j = i + 1; j < _d; ++j) { _gso.get_mu(fmu, j + _first, i + _first); // j > i /* mu[i][j]= */ mu[offs + j] = fmu.get_d(); } } } else { size_t offs = 0; for (int j = 0; j < _d; ++j, offs += mudim) { for (int i = 0; i < j; ++i) { _gso.get_mu(fmu, j + _first, i + _first); // j > i /* mu[j][i] = */ mu[offs + i] = fmu.get_d(); } } } // if there's no pruning enabled then we just fill pruning with 1s if (_pruning.empty()) { for (int i = 0; i < _d; ++i) pruning[i] = 1.0; } else { // Otherwise we just copy over the pruning parameters for (int i = 0; i < _d; ++i) pruning[i] = _pruning[i]; } } template <typename ZT, typename FT> enumf ExternalEnumeration<ZT, FT>::callback_process_sol(enumf dist, enumf *sol) { for (int i = 0; i < _d; ++i) _fx[i] = sol[i]; _evaluator.eval_sol(_fx, dist, _maxdist); return _maxdist; } template <typename ZT, typename FT> void ExternalEnumeration<ZT, FT>::callback_process_subsol(enumf dist, enumf *subsol, int offset) { for (int i = 0; i < offset; ++i) _fx[i] = 0.0; for (int i = offset; i < _d; ++i) _fx[i] = subsol[i]; _evaluator.eval_sub_sol(offset, _fx, dist); } template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<double>>; #ifdef FPLLL_WITH_LONG_DOUBLE template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<long double>>; #endif #ifdef FPLLL_WITH_QD template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<dd_real>>; template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<qd_real>>; #endif #ifdef FPLLL_WITH_DPE template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<dpe_t>>; #endif template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<mpfr_t>>; template class ExternalEnumeration<Z_NR<long>, FP_NR<double>>; #ifdef FPLLL_WITH_LONG_DOUBLE template class ExternalEnumeration<Z_NR<long>, FP_NR<long double>>; #endif #ifdef FPLLL_WITH_QD template class ExternalEnumeration<Z_NR<long>, FP_NR<dd_real>>; template class ExternalEnumeration<Z_NR<long>, FP_NR<qd_real>>; #endif #ifdef FPLLL_WITH_DPE template class ExternalEnumeration<Z_NR<long>, FP_NR<dpe_t>>; #endif template class ExternalEnumeration<Z_NR<long>, FP_NR<mpfr_t>>; FPLLL_END_NAMESPACE <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "session_context.h" #include <algorithm> #include "curl/curl.h" #include "cvmfs_config.h" #include "gateway_util.h" #include "json_document.h" #include "swissknife_lease_curl.h" #include "util/string.h" namespace upload { size_t SendCB(void* ptr, size_t size, size_t nmemb, void* userp) { CurlSendPayload* payload = static_cast<CurlSendPayload*>(userp); size_t max_chunk_size = size * nmemb; if (max_chunk_size < 1) { return 0; } size_t current_chunk_size = 0; while (current_chunk_size < max_chunk_size) { if (payload->index < payload->json_message->size()) { // Can add a chunk from the JSON message const size_t read_size = std::min(max_chunk_size - current_chunk_size, payload->json_message->size() - payload->index); current_chunk_size += read_size; std::memcpy(ptr, payload->json_message->data() + payload->index, read_size); payload->index += read_size; } else { // Can add a chunk from the payload const size_t max_read_size = max_chunk_size - current_chunk_size; const unsigned nbytes = payload->pack_serializer->ProduceNext( max_read_size, static_cast<unsigned char*>(ptr) + current_chunk_size); current_chunk_size += nbytes; if (!nbytes) { break; } } } return current_chunk_size; } size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) { std::string* my_buffer = static_cast<std::string*>(userp); if (size * nmemb < 1) { return 0; } *my_buffer = static_cast<char*>(buffer); return my_buffer->size(); } SessionContextBase::SessionContextBase() : upload_results_(1000, 1000), api_url_(), session_token_(), key_id_(), secret_(), queue_was_flushed_(1, 1), max_pack_size_(ObjectPack::kDefaultLimit), active_handles_(), current_pack_(NULL), current_pack_mtx_(), objects_dispatched_(0), bytes_committed_(0), bytes_dispatched_(0) {} SessionContextBase::~SessionContextBase() {} bool SessionContextBase::Initialize(const std::string& api_url, const std::string& session_token, const std::string& key_id, const std::string& secret, uint64_t max_pack_size) { bool ret = true; // Initialize session context lock pthread_mutexattr_t attr; if (pthread_mutexattr_init(&attr) || pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) || pthread_mutex_init(&current_pack_mtx_, &attr) || pthread_mutexattr_destroy(&attr)) { LogCvmfs(kLogUploadGateway, kLogStderr, "Could not initialize SessionContext lock."); return false; } // Set upstream URL and session token api_url_ = api_url; session_token_ = session_token; key_id_ = key_id; secret_ = secret; max_pack_size_ = max_pack_size; atomic_init64(&objects_dispatched_); bytes_committed_ = 0u; bytes_dispatched_ = 0u; // Ensure that the upload job and result queues are empty upload_results_.Drop(); queue_was_flushed_.Drop(); queue_was_flushed_.Enqueue(true); // Ensure that there are not open object packs if (current_pack_) { LogCvmfs( kLogUploadGateway, kLogStderr, "Could not initialize SessionContext - Existing open object packs."); ret = false; } ret = InitializeDerived() && ret; return ret; } bool SessionContextBase::Finalize(bool commit, const std::string& old_root_hash, const std::string& new_root_hash) { assert(active_handles_.empty()); { MutexLockGuard lock(current_pack_mtx_); if (current_pack_ && current_pack_->GetNoObjects() > 0) { Dispatch(); current_pack_ = NULL; } } bool results = true; int64_t jobs_finished = 0; while (!upload_results_.IsEmpty() || (jobs_finished < NumJobsSubmitted())) { Future<bool>* future = upload_results_.Dequeue(); results = future->Get() && results; delete future; jobs_finished++; } if (commit) { if (old_root_hash.empty() || new_root_hash.empty()) { return false; } results &= Commit(old_root_hash, new_root_hash); } results &= FinalizeDerived() && (bytes_committed_ == bytes_dispatched_); pthread_mutex_destroy(&current_pack_mtx_); return results; } void SessionContextBase::WaitForUpload() { if (!upload_results_.IsEmpty()) { queue_was_flushed_.Dequeue(); } } ObjectPack::BucketHandle SessionContextBase::NewBucket() { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { current_pack_ = new ObjectPack(max_pack_size_); } ObjectPack::BucketHandle hd = current_pack_->NewBucket(); active_handles_.push_back(hd); return hd; } bool SessionContextBase::CommitBucket(const ObjectPack::BucketContentType type, const shash::Any& id, const ObjectPack::BucketHandle handle, const std::string& name, const bool force_dispatch) { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { LogCvmfs(kLogUploadGateway, kLogStderr, "Error: Called SessionBaseContext::CommitBucket without an open " "ObjectPack."); return false; } uint64_t size0 = current_pack_->size(); bool committed = current_pack_->CommitBucket(type, id, handle, name); if (committed) { // Current pack is still not full active_handles_.erase( std::remove(active_handles_.begin(), active_handles_.end(), handle), active_handles_.end()); uint64_t size1 = current_pack_->size(); bytes_committed_ += size1 - size0; if (force_dispatch) { Dispatch(); current_pack_ = NULL; } } else { // Current pack is full and can be dispatched uint64_t new_size = 0; if (handle->capacity > max_pack_size_) { new_size = handle->capacity + 1; } else { new_size = max_pack_size_; } ObjectPack* new_pack = new ObjectPack(new_size); for (size_t i = 0u; i < active_handles_.size(); ++i) { current_pack_->TransferBucket(active_handles_[i], new_pack); } if (current_pack_->GetNoObjects() > 0) { Dispatch(); } current_pack_ = new_pack; CommitBucket(type, id, handle, name, false); } return true; } int64_t SessionContextBase::NumJobsSubmitted() const { return atomic_read64(&objects_dispatched_); } void SessionContextBase::Dispatch() { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { return; } atomic_inc64(&objects_dispatched_); bytes_dispatched_ += current_pack_->size(); upload_results_.Enqueue(DispatchObjectPack(current_pack_)); } SessionContext::SessionContext() : SessionContextBase(), upload_jobs_(1000, 900), worker_terminate_(), worker_() {} bool SessionContext::InitializeDerived() { // Start worker thread atomic_init32(&worker_terminate_); atomic_write32(&worker_terminate_, 0); upload_jobs_.Drop(); int retval = pthread_create(&worker_, NULL, UploadLoop, reinterpret_cast<void*>(this)); return !retval; } bool SessionContext::FinalizeDerived() { atomic_write32(&worker_terminate_, 1); pthread_join(worker_, NULL); return true; } bool SessionContext::Commit(const std::string& old_root_hash, const std::string& new_root_hash) { std::string request; JsonStringInput request_input; request_input.push_back( std::make_pair("old_root_hash", old_root_hash.c_str())); request_input.push_back( std::make_pair("new_root_hash", new_root_hash.c_str())); ToJsonString(request_input, &request); CurlBuffer buffer; return MakeEndRequest("POST", key_id_, secret_, session_token_, api_url_, request, &buffer); } Future<bool>* SessionContext::DispatchObjectPack(ObjectPack* pack) { UploadJob* job = new UploadJob; job->pack = pack; job->result = new Future<bool>(); upload_jobs_.Enqueue(job); return job->result; } bool SessionContext::DoUpload(const SessionContext::UploadJob* job) { // Set up the object pack serializer ObjectPackProducer serializer(job->pack); shash::Any payload_digest(shash::kSha1); serializer.GetDigest(&payload_digest); const std::string json_msg = "{\"session_token\" : \"" + session_token_ + "\", \"payload_digest\" : \"" + Base64(payload_digest.ToString(false)) + "\", \"header_size\" : \"" + StringifyInt(serializer.GetHeaderSize()) + "\", \"api_version\" : \"" + StringifyInt(gateway::APIVersion()) + "\"}"; // Compute HMAC shash::Any hmac(shash::kSha1); shash::HmacString(secret_, json_msg, &hmac); CurlSendPayload payload; payload.json_message = &json_msg; payload.pack_serializer = &serializer; payload.index = 0; const size_t payload_size = json_msg.size() + serializer.GetHeaderSize() + job->pack->size(); // Prepare the Curl POST request CURL* h_curl = curl_easy_init(); if (!h_curl) { return false; } // Set HTTP headers (Authorization and Message-Size) std::string header_str = std::string("Authorization: ") + key_id_ + " " + Base64(hmac.ToString(false)); struct curl_slist* auth_header = NULL; auth_header = curl_slist_append(auth_header, header_str.c_str()); header_str = std::string("Message-Size: ") + StringifyInt(json_msg.size()); auth_header = curl_slist_append(auth_header, header_str.c_str()); curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header); std::string reply; curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(h_curl, CURLOPT_USERAGENT, "cvmfs/" VERSION); curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L); curl_easy_setopt(h_curl, CURLOPT_URL, (api_url_ + "/payloads").c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, NULL); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(payload_size)); curl_easy_setopt(h_curl, CURLOPT_READDATA, &payload); curl_easy_setopt(h_curl, CURLOPT_READFUNCTION, SendCB); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, &reply); // Perform the Curl POST request CURLcode ret = curl_easy_perform(h_curl); if (ret) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext: curl_easy_perform failed: %d", ret); } const bool ok = (reply == "{\"status\":\"ok\"}"); LogCvmfs(kLogUploadGateway, kLogStdout, "SessionContext::DoUpload - reply: %s", reply.c_str()); curl_easy_cleanup(h_curl); h_curl = NULL; return ok && !ret; } void* SessionContext::UploadLoop(void* data) { SessionContext* ctx = reinterpret_cast<SessionContext*>(data); int64_t jobs_processed = 0; while (!ctx->ShouldTerminate()) { while (jobs_processed < ctx->NumJobsSubmitted()) { UploadJob* job = ctx->upload_jobs_.Dequeue(); if (!ctx->DoUpload(job)) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext: could not submit payload. Aborting."); abort(); } job->result->Set(true); delete job->pack; delete job; jobs_processed++; } if (ctx->queue_was_flushed_.IsEmpty()) { ctx->queue_was_flushed_.Enqueue(true); } } return NULL; } bool SessionContext::ShouldTerminate() { return atomic_read32(&worker_terminate_); } } // namespace upload <commit_msg>SessionContext - only log on error<commit_after>/** * This file is part of the CernVM File System. */ #include "session_context.h" #include <algorithm> #include "curl/curl.h" #include "cvmfs_config.h" #include "gateway_util.h" #include "json_document.h" #include "swissknife_lease_curl.h" #include "util/string.h" namespace upload { size_t SendCB(void* ptr, size_t size, size_t nmemb, void* userp) { CurlSendPayload* payload = static_cast<CurlSendPayload*>(userp); size_t max_chunk_size = size * nmemb; if (max_chunk_size < 1) { return 0; } size_t current_chunk_size = 0; while (current_chunk_size < max_chunk_size) { if (payload->index < payload->json_message->size()) { // Can add a chunk from the JSON message const size_t read_size = std::min(max_chunk_size - current_chunk_size, payload->json_message->size() - payload->index); current_chunk_size += read_size; std::memcpy(ptr, payload->json_message->data() + payload->index, read_size); payload->index += read_size; } else { // Can add a chunk from the payload const size_t max_read_size = max_chunk_size - current_chunk_size; const unsigned nbytes = payload->pack_serializer->ProduceNext( max_read_size, static_cast<unsigned char*>(ptr) + current_chunk_size); current_chunk_size += nbytes; if (!nbytes) { break; } } } return current_chunk_size; } size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) { std::string* my_buffer = static_cast<std::string*>(userp); if (size * nmemb < 1) { return 0; } *my_buffer = static_cast<char*>(buffer); return my_buffer->size(); } SessionContextBase::SessionContextBase() : upload_results_(1000, 1000), api_url_(), session_token_(), key_id_(), secret_(), queue_was_flushed_(1, 1), max_pack_size_(ObjectPack::kDefaultLimit), active_handles_(), current_pack_(NULL), current_pack_mtx_(), objects_dispatched_(0), bytes_committed_(0), bytes_dispatched_(0) {} SessionContextBase::~SessionContextBase() {} bool SessionContextBase::Initialize(const std::string& api_url, const std::string& session_token, const std::string& key_id, const std::string& secret, uint64_t max_pack_size) { bool ret = true; // Initialize session context lock pthread_mutexattr_t attr; if (pthread_mutexattr_init(&attr) || pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) || pthread_mutex_init(&current_pack_mtx_, &attr) || pthread_mutexattr_destroy(&attr)) { LogCvmfs(kLogUploadGateway, kLogStderr, "Could not initialize SessionContext lock."); return false; } // Set upstream URL and session token api_url_ = api_url; session_token_ = session_token; key_id_ = key_id; secret_ = secret; max_pack_size_ = max_pack_size; atomic_init64(&objects_dispatched_); bytes_committed_ = 0u; bytes_dispatched_ = 0u; // Ensure that the upload job and result queues are empty upload_results_.Drop(); queue_was_flushed_.Drop(); queue_was_flushed_.Enqueue(true); // Ensure that there are not open object packs if (current_pack_) { LogCvmfs( kLogUploadGateway, kLogStderr, "Could not initialize SessionContext - Existing open object packs."); ret = false; } ret = InitializeDerived() && ret; return ret; } bool SessionContextBase::Finalize(bool commit, const std::string& old_root_hash, const std::string& new_root_hash) { assert(active_handles_.empty()); { MutexLockGuard lock(current_pack_mtx_); if (current_pack_ && current_pack_->GetNoObjects() > 0) { Dispatch(); current_pack_ = NULL; } } bool results = true; int64_t jobs_finished = 0; while (!upload_results_.IsEmpty() || (jobs_finished < NumJobsSubmitted())) { Future<bool>* future = upload_results_.Dequeue(); results = future->Get() && results; delete future; jobs_finished++; } if (commit) { if (old_root_hash.empty() || new_root_hash.empty()) { return false; } results &= Commit(old_root_hash, new_root_hash); } results &= FinalizeDerived() && (bytes_committed_ == bytes_dispatched_); pthread_mutex_destroy(&current_pack_mtx_); return results; } void SessionContextBase::WaitForUpload() { if (!upload_results_.IsEmpty()) { queue_was_flushed_.Dequeue(); } } ObjectPack::BucketHandle SessionContextBase::NewBucket() { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { current_pack_ = new ObjectPack(max_pack_size_); } ObjectPack::BucketHandle hd = current_pack_->NewBucket(); active_handles_.push_back(hd); return hd; } bool SessionContextBase::CommitBucket(const ObjectPack::BucketContentType type, const shash::Any& id, const ObjectPack::BucketHandle handle, const std::string& name, const bool force_dispatch) { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { LogCvmfs(kLogUploadGateway, kLogStderr, "Error: Called SessionBaseContext::CommitBucket without an open " "ObjectPack."); return false; } uint64_t size0 = current_pack_->size(); bool committed = current_pack_->CommitBucket(type, id, handle, name); if (committed) { // Current pack is still not full active_handles_.erase( std::remove(active_handles_.begin(), active_handles_.end(), handle), active_handles_.end()); uint64_t size1 = current_pack_->size(); bytes_committed_ += size1 - size0; if (force_dispatch) { Dispatch(); current_pack_ = NULL; } } else { // Current pack is full and can be dispatched uint64_t new_size = 0; if (handle->capacity > max_pack_size_) { new_size = handle->capacity + 1; } else { new_size = max_pack_size_; } ObjectPack* new_pack = new ObjectPack(new_size); for (size_t i = 0u; i < active_handles_.size(); ++i) { current_pack_->TransferBucket(active_handles_[i], new_pack); } if (current_pack_->GetNoObjects() > 0) { Dispatch(); } current_pack_ = new_pack; CommitBucket(type, id, handle, name, false); } return true; } int64_t SessionContextBase::NumJobsSubmitted() const { return atomic_read64(&objects_dispatched_); } void SessionContextBase::Dispatch() { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { return; } atomic_inc64(&objects_dispatched_); bytes_dispatched_ += current_pack_->size(); upload_results_.Enqueue(DispatchObjectPack(current_pack_)); } SessionContext::SessionContext() : SessionContextBase(), upload_jobs_(1000, 900), worker_terminate_(), worker_() {} bool SessionContext::InitializeDerived() { // Start worker thread atomic_init32(&worker_terminate_); atomic_write32(&worker_terminate_, 0); upload_jobs_.Drop(); int retval = pthread_create(&worker_, NULL, UploadLoop, reinterpret_cast<void*>(this)); return !retval; } bool SessionContext::FinalizeDerived() { atomic_write32(&worker_terminate_, 1); pthread_join(worker_, NULL); return true; } bool SessionContext::Commit(const std::string& old_root_hash, const std::string& new_root_hash) { std::string request; JsonStringInput request_input; request_input.push_back( std::make_pair("old_root_hash", old_root_hash.c_str())); request_input.push_back( std::make_pair("new_root_hash", new_root_hash.c_str())); ToJsonString(request_input, &request); CurlBuffer buffer; return MakeEndRequest("POST", key_id_, secret_, session_token_, api_url_, request, &buffer); } Future<bool>* SessionContext::DispatchObjectPack(ObjectPack* pack) { UploadJob* job = new UploadJob; job->pack = pack; job->result = new Future<bool>(); upload_jobs_.Enqueue(job); return job->result; } bool SessionContext::DoUpload(const SessionContext::UploadJob* job) { // Set up the object pack serializer ObjectPackProducer serializer(job->pack); shash::Any payload_digest(shash::kSha1); serializer.GetDigest(&payload_digest); const std::string json_msg = "{\"session_token\" : \"" + session_token_ + "\", \"payload_digest\" : \"" + Base64(payload_digest.ToString(false)) + "\", \"header_size\" : \"" + StringifyInt(serializer.GetHeaderSize()) + "\", \"api_version\" : \"" + StringifyInt(gateway::APIVersion()) + "\"}"; // Compute HMAC shash::Any hmac(shash::kSha1); shash::HmacString(secret_, json_msg, &hmac); CurlSendPayload payload; payload.json_message = &json_msg; payload.pack_serializer = &serializer; payload.index = 0; const size_t payload_size = json_msg.size() + serializer.GetHeaderSize() + job->pack->size(); // Prepare the Curl POST request CURL* h_curl = curl_easy_init(); if (!h_curl) { return false; } // Set HTTP headers (Authorization and Message-Size) std::string header_str = std::string("Authorization: ") + key_id_ + " " + Base64(hmac.ToString(false)); struct curl_slist* auth_header = NULL; auth_header = curl_slist_append(auth_header, header_str.c_str()); header_str = std::string("Message-Size: ") + StringifyInt(json_msg.size()); auth_header = curl_slist_append(auth_header, header_str.c_str()); curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header); std::string reply; curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(h_curl, CURLOPT_USERAGENT, "cvmfs/" VERSION); curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L); curl_easy_setopt(h_curl, CURLOPT_URL, (api_url_ + "/payloads").c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, NULL); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(payload_size)); curl_easy_setopt(h_curl, CURLOPT_READDATA, &payload); curl_easy_setopt(h_curl, CURLOPT_READFUNCTION, SendCB); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, &reply); // Perform the Curl POST request CURLcode ret = curl_easy_perform(h_curl); if (ret) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext - curl_easy_perform failed: %d", ret); } const bool ok = (reply == "{\"status\":\"ok\"}"); if (!ok) { LogCvmfs(kLogUploadGateway, kLogStdout, "SessionContext - curl_easy_perform reply: %s", reply.c_str()); } curl_easy_cleanup(h_curl); h_curl = NULL; return ok && !ret; } void* SessionContext::UploadLoop(void* data) { SessionContext* ctx = reinterpret_cast<SessionContext*>(data); int64_t jobs_processed = 0; while (!ctx->ShouldTerminate()) { while (jobs_processed < ctx->NumJobsSubmitted()) { UploadJob* job = ctx->upload_jobs_.Dequeue(); if (!ctx->DoUpload(job)) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext: could not submit payload. Aborting."); abort(); } job->result->Set(true); delete job->pack; delete job; jobs_processed++; } if (ctx->queue_was_flushed_.IsEmpty()) { ctx->queue_was_flushed_.Enqueue(true); } } return NULL; } bool SessionContext::ShouldTerminate() { return atomic_read32(&worker_terminate_); } } // namespace upload <|endoftext|>
<commit_before>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_TESTS_HPP_INCLUDED #define METHCLA_TESTS_HPP_INCLUDED #include <string> namespace Methcla { namespace Tests { std::string inputFile(const std::string& name); std::string outputFile(const std::string& name); } } #endif // METHCLA_TESTS_HPP_INCLUDED<commit_msg>Add function for approximate floating point equality<commit_after>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_TESTS_HPP_INCLUDED #define METHCLA_TESTS_HPP_INCLUDED #include <cmath> #include <limits> #include <string> namespace Methcla { namespace Tests { std::string inputFile(const std::string& name); std::string outputFile(const std::string& name); template <typename T> bool nearlyEqual(T a, T b, T epsilon=std::numeric_limits<T>::epsilon()) { const T absA = std::fabs(a); const T absB = std::fabs(b); const T diff = std::fabs(a - b); if (a == b) { // Shortcut, handles infinities return true; } else if (a == 0 || b == 0 || diff < std::numeric_limits<T>::denorm_min()) { // a or b is zero or both are extremely close to it // relative error is less meaningful here return diff < (epsilon * std::numeric_limits<T>::denorm_min()); } else { // use relative error return diff / (absA + absB) < epsilon; } } } } #endif // METHCLA_TESTS_HPP_INCLUDED<|endoftext|>
<commit_before>/* * Copyright (c) 2012 Holger Schletz <[email protected]> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 <QFileInfo> #include "application.h" #include "thunderbird.h" Thunderbird::Thunderbird() : Mozilla("Thunderbird", "14.0") { } void Thunderbird::build(NSIS *installer, Version version) { isError = false; QStringList files; QString src(loadResource(":NSIS/Thunderbird/main.nsh")); src.replace("${Version}", version); QString prefs; prefs += setOption("Use automatic update", boolean, "app.update.enabled"); // true prefs += setOption("Allow message cache", (setOptionCallback) &Thunderbird::setDisableCache); prefs += setOption("Browser cache size", integer, "browser.cache.disk.capacity"); //1048576 prefs += setOption("Proxy configuration script", (setOptionCallback) &Thunderbird::setProxyScript); prefs += setOption("Show start page", boolean, "mailnews.start_page.enabled"); //true prefs += setOption("Display names from address book only", boolean, "mail.showCondensedAddresses"); //true prefs += setOption("Request MDN", boolean, "mail.receipt.request_return_receipt_on"); //? prefs += setOption("Reply MDN", boolean, "mail.mdn.report.enabled"); // true prefs += setOption("Compose HTML messages", boolean, "mail.identity.default.compose_html"); //true prefs += setOption("Enable file sharing", boolean, "mail.cloud_files.enabled"); // true prefs += setOption("Offer file sharing", boolean, "mail.compose.big_attachments.notify"); // true if (prefs.isEmpty()) { src += loadResource(":NSIS/Thunderbird/deleteprefs.nsh"); } else { src += loadResource(":NSIS/Thunderbird/writeprefs.nsh"); writePrefsFile(prefs); } if (!getConfig("Enable Test Pilot", true).toBool()) { src += loadResource(":NSIS/Thunderbird/uninstalltestpilot.nsh"); } QString accountConfig(getConfig("Account configuration file").toString()); if (!accountConfig.isEmpty()) { src += loadResource(":NSIS/Thunderbird/accountconfig.nsh") .replace("${AccountConfig}", QFileInfo(accountConfig).fileName()); files << accountConfig; } if (!isError) { download(version); } if (!isError) { files << tempFiles; installer->build( objectName(), getOutputFile(), NSIS::None, 80, QStringList("thunderbird.exe"), files, src ); } cleanup(); } QString Thunderbird::setProxyScript(QString cmdTemplate, QVariant value) { return cmdTemplate.arg("network.proxy.type").arg(2) + cmdTemplate.arg("network.proxy.autoconfig_url").arg(quoteString(value.toString())); } QString Thunderbird::setDisableCache(QString cmdTemplate, QVariant value) { QString arg(value.toBool() ? "true" : "false"); return cmdTemplate.arg("mail.server.default.autosync_offline_stores").arg(arg) + cmdTemplate.arg("mail.server.default.offline_download").arg(arg) + cmdTemplate.arg("mailnews.database.global.indexer.enabled").arg(arg) + cmdTemplate.arg("mail.ui.show.migration.on.upgrade").arg(arg); } <commit_msg>Removed temporary comments.<commit_after>/* * Copyright (c) 2012 Holger Schletz <[email protected]> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 <QFileInfo> #include "application.h" #include "thunderbird.h" Thunderbird::Thunderbird() : Mozilla("Thunderbird", "14.0") { } void Thunderbird::build(NSIS *installer, Version version) { isError = false; QStringList files; QString src(loadResource(":NSIS/Thunderbird/main.nsh")); src.replace("${Version}", version); QString prefs; prefs += setOption("Use automatic update", boolean, "app.update.enabled"); prefs += setOption("Allow message cache", (setOptionCallback) &Thunderbird::setDisableCache); prefs += setOption("Browser cache size", integer, "browser.cache.disk.capacity"); prefs += setOption("Proxy configuration script", (setOptionCallback) &Thunderbird::setProxyScript); prefs += setOption("Show start page", boolean, "mailnews.start_page.enabled"); prefs += setOption("Display names from address book only", boolean, "mail.showCondensedAddresses"); prefs += setOption("Request MDN", boolean, "mail.receipt.request_return_receipt_on"); prefs += setOption("Reply MDN", boolean, "mail.mdn.report.enabled"); prefs += setOption("Compose HTML messages", boolean, "mail.identity.default.compose_html"); prefs += setOption("Enable file sharing", boolean, "mail.cloud_files.enabled"); prefs += setOption("Offer file sharing", boolean, "mail.compose.big_attachments.notify"); if (prefs.isEmpty()) { src += loadResource(":NSIS/Thunderbird/deleteprefs.nsh"); } else { src += loadResource(":NSIS/Thunderbird/writeprefs.nsh"); writePrefsFile(prefs); } if (!getConfig("Enable Test Pilot", true).toBool()) { src += loadResource(":NSIS/Thunderbird/uninstalltestpilot.nsh"); } QString accountConfig(getConfig("Account configuration file").toString()); if (!accountConfig.isEmpty()) { src += loadResource(":NSIS/Thunderbird/accountconfig.nsh") .replace("${AccountConfig}", QFileInfo(accountConfig).fileName()); files << accountConfig; } if (!isError) { download(version); } if (!isError) { files << tempFiles; installer->build( objectName(), getOutputFile(), NSIS::None, 80, QStringList("thunderbird.exe"), files, src ); } cleanup(); } QString Thunderbird::setProxyScript(QString cmdTemplate, QVariant value) { return cmdTemplate.arg("network.proxy.type").arg(2) + cmdTemplate.arg("network.proxy.autoconfig_url").arg(quoteString(value.toString())); } QString Thunderbird::setDisableCache(QString cmdTemplate, QVariant value) { QString arg(value.toBool() ? "true" : "false"); return cmdTemplate.arg("mail.server.default.autosync_offline_stores").arg(arg) + cmdTemplate.arg("mail.server.default.offline_download").arg(arg) + cmdTemplate.arg("mailnews.database.global.indexer.enabled").arg(arg) + cmdTemplate.arg("mail.ui.show.migration.on.upgrade").arg(arg); } <|endoftext|>
<commit_before>#define _CRT_SECURE_NO_WARNINGS 1 #include "stdafx.h" #include "unzip.h" #include "MachineInstaller.h" #include "resource.h" bool findPackageFromEmbeddedZip(wchar_t* buf, DWORD cbSize) { bool ret = false; CResource zipResource; if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { return false; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { return false; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); ZRESULT zr; int index = 0; do { ZIPENTRY zentry; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } if (wcsstr(zentry.name, L"nupkg")) { ZeroMemory(buf, cbSize); int idx = wcscspn(zentry.name, L"nupkg"); memcpy(buf, zentry.name, sizeof(wchar_t) * idx); ret = true; break; } index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); return ret; } bool createAdminOnlySecurityAttributes(LPSECURITY_ATTRIBUTES pAttributes) { return false; } int MachineInstaller::PerformMachineInstallSetup() { wchar_t packageName[512]; if (!findPackageFromEmbeddedZip(packageName, sizeof(packageName))) { MessageBox(NULL, L"Corrupt installer", L"Cannot find package name for installer, is it created correctly?", MB_OK); return ERROR_INVALID_PARAMETER; } wchar_t machineInstallFolder[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, machineInstallFolder); wcscat(machineInstallFolder, L"\\SquirrelMachineInstalls"); SECURITY_ATTRIBUTES secattrs; createAdminOnlySecurityAttributes(&secattrs); if (!CreateDirectory(machineInstallFolder, NULL/*&secattrs*/) && GetLastError() != ERROR_ALREADY_EXISTS) { return GetLastError(); } wcscat(machineInstallFolder, L"\\"); wcscat(machineInstallFolder, packageName); wcscat(machineInstallFolder, L".exe"); wchar_t ourFile[MAX_PATH]; HMODULE hMod = GetModuleHandle(NULL); GetModuleFileName(hMod, ourFile, _countof(ourFile)); if (!CopyFile(ourFile, machineInstallFolder, false)) { return GetLastError(); } HKEY runKey; DWORD dontcare; if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, &dontcare) != ERROR_SUCCESS) { return GetLastError(); } wcscat_s(machineInstallFolder, L" --checkInstall"); if (RegSetValueEx(runKey, packageName, 0, REG_SZ, (BYTE*)machineInstallFolder, (wcsnlen(machineInstallFolder, sizeof(machineInstallFolder)) + 1) * sizeof(wchar_t)) != ERROR_SUCCESS) { return GetLastError(); } RegCloseKey(runKey); return 0; } bool MachineInstaller::ShouldSilentInstall() { // Figure out the package name from our own EXE name wchar_t ourFile[MAX_PATH]; HMODULE hMod = GetModuleHandle(NULL); GetModuleFileName(hMod, ourFile, _countof(ourFile)); CString fullPath = CString(ourFile); CString pkgName = CString(ourFile + fullPath.ReverseFind(L'\\')); pkgName.Replace(L".exe", L""); wchar_t installFolder[MAX_PATH]; // C:\Users\Username\AppData\Local\$pkgName SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder); wcscat(installFolder, L"\\"); wcscat(installFolder, pkgName); if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) return false; // C:\ProgramData\$pkgName\$username wchar_t username[512]; DWORD unamesize = _countof(username); SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder); GetUserName(username, &unamesize); wcscat(installFolder, L"\\"); wcscat(installFolder, pkgName); wcscat(installFolder, L"\\"); wcscat(installFolder, username); if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) return false; // Neither exist, create them return true; } <commit_msg>Correctly ACL machine-wide folder /cc @ericlaw<commit_after>#define _CRT_SECURE_NO_WARNINGS 1 #include "stdafx.h" #include "unzip.h" #include "MachineInstaller.h" #include "resource.h" #include <sddl.h> bool findPackageFromEmbeddedZip(wchar_t* buf, DWORD cbSize) { bool ret = false; CResource zipResource; if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { return false; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { return false; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); ZRESULT zr; int index = 0; do { ZIPENTRY zentry; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } if (wcsstr(zentry.name, L"nupkg")) { ZeroMemory(buf, cbSize); int idx = wcscspn(zentry.name, L"nupkg"); memcpy(buf, zentry.name, sizeof(wchar_t) * idx); ret = true; break; } index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); return ret; } int MachineInstaller::PerformMachineInstallSetup() { wchar_t packageName[512]; if (!findPackageFromEmbeddedZip(packageName, sizeof(packageName))) { MessageBox(NULL, L"Corrupt installer", L"Cannot find package name for installer, is it created correctly?", MB_OK); return ERROR_INVALID_PARAMETER; } wchar_t machineInstallFolder[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, machineInstallFolder); wcscat(machineInstallFolder, L"\\SquirrelMachineInstalls"); // NB: This is the DACL for Program Files PSECURITY_DESCRIPTOR descriptor; ConvertStringSecurityDescriptorToSecurityDescriptor( L"D:PAI(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;CIIO;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;;0x1301bf;;;SY)(A;OICIIO;GA;;;SY)(A;;0x1301bf;;;BA)(A;OICIIO;GA;;;BA)(A;;0x1200a9;;;BU)(A;OICIIO;GXGR;;;BU)(A;OICIIO;GA;;;CO)(A;;0x1200a9;;;AC)(A;OICIIO;GXGR;;;AC)", SDDL_REVISION_1, &descriptor, NULL); SECURITY_ATTRIBUTES attrs; attrs.nLength = sizeof(SECURITY_ATTRIBUTES); attrs.bInheritHandle = false; attrs.lpSecurityDescriptor = descriptor; if (!CreateDirectory(machineInstallFolder, &attrs) && GetLastError() != ERROR_ALREADY_EXISTS) { LocalFree(descriptor); return GetLastError(); } LocalFree(descriptor); wcscat(machineInstallFolder, L"\\"); wcscat(machineInstallFolder, packageName); wcscat(machineInstallFolder, L".exe"); wchar_t ourFile[MAX_PATH]; HMODULE hMod = GetModuleHandle(NULL); GetModuleFileName(hMod, ourFile, _countof(ourFile)); if (!CopyFile(ourFile, machineInstallFolder, false)) { return GetLastError(); } HKEY runKey; DWORD dontcare; if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, &dontcare) != ERROR_SUCCESS) { return GetLastError(); } wcscat_s(machineInstallFolder, L" --checkInstall"); if (RegSetValueEx(runKey, packageName, 0, REG_SZ, (BYTE*)machineInstallFolder, (wcsnlen(machineInstallFolder, sizeof(machineInstallFolder)) + 1) * sizeof(wchar_t)) != ERROR_SUCCESS) { return GetLastError(); } RegCloseKey(runKey); return 0; } bool MachineInstaller::ShouldSilentInstall() { // Figure out the package name from our own EXE name wchar_t ourFile[MAX_PATH]; HMODULE hMod = GetModuleHandle(NULL); GetModuleFileName(hMod, ourFile, _countof(ourFile)); CString fullPath = CString(ourFile); CString pkgName = CString(ourFile + fullPath.ReverseFind(L'\\')); pkgName.Replace(L".exe", L""); wchar_t installFolder[MAX_PATH]; // C:\Users\Username\AppData\Local\$pkgName SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder); wcscat(installFolder, L"\\"); wcscat(installFolder, pkgName); if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) return false; // C:\ProgramData\$pkgName\$username wchar_t username[512]; DWORD unamesize = _countof(username); SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder); GetUserName(username, &unamesize); wcscat(installFolder, L"\\"); wcscat(installFolder, pkgName); wcscat(installFolder, L"\\"); wcscat(installFolder, username); if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) return false; // Neither exist, create them return true; } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "session_context.h" #include <algorithm> #include "curl/curl.h" #include "cvmfs_config.h" #include "gateway_util.h" #include "json_document.h" #include "swissknife_lease_curl.h" #include "util/string.h" namespace upload { size_t SendCB(void* ptr, size_t size, size_t nmemb, void* userp) { CurlSendPayload* payload = static_cast<CurlSendPayload*>(userp); size_t max_chunk_size = size * nmemb; if (max_chunk_size < 1) { return 0; } size_t current_chunk_size = 0; while (current_chunk_size < max_chunk_size) { if (payload->index < payload->json_message->size()) { // Can add a chunk from the JSON message const size_t read_size = std::min(max_chunk_size - current_chunk_size, payload->json_message->size() - payload->index); current_chunk_size += read_size; std::memcpy(ptr, payload->json_message->data() + payload->index, read_size); payload->index += read_size; } else { // Can add a chunk from the payload const size_t max_read_size = max_chunk_size - current_chunk_size; const unsigned nbytes = payload->pack_serializer->ProduceNext( max_read_size, static_cast<unsigned char*>(ptr) + current_chunk_size); current_chunk_size += nbytes; if (!nbytes) { break; } } } return current_chunk_size; } size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) { std::string* my_buffer = static_cast<std::string*>(userp); if (size * nmemb < 1) { return 0; } *my_buffer = static_cast<char*>(buffer); return my_buffer->size(); } SessionContextBase::SessionContextBase() : upload_results_(1000000, 1000000), api_url_(), session_token_(), key_id_(), secret_(), queue_was_flushed_(1, 1), max_pack_size_(ObjectPack::kDefaultLimit), active_handles_(), current_pack_(NULL), current_pack_mtx_(), objects_dispatched_(0), bytes_committed_(0), bytes_dispatched_(0) {} SessionContextBase::~SessionContextBase() {} bool SessionContextBase::Initialize(const std::string& api_url, const std::string& session_token, const std::string& key_id, const std::string& secret, uint64_t max_pack_size) { bool ret = true; // Initialize session context lock pthread_mutexattr_t attr; if (pthread_mutexattr_init(&attr) || pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) || pthread_mutex_init(&current_pack_mtx_, &attr) || pthread_mutexattr_destroy(&attr)) { LogCvmfs(kLogUploadGateway, kLogStderr, "Could not initialize SessionContext lock."); return false; } // Set upstream URL and session token api_url_ = api_url; session_token_ = session_token; key_id_ = key_id; secret_ = secret; max_pack_size_ = max_pack_size; atomic_init64(&objects_dispatched_); bytes_committed_ = 0u; bytes_dispatched_ = 0u; // Ensure that the upload job and result queues are empty upload_results_.Drop(); queue_was_flushed_.Drop(); queue_was_flushed_.Enqueue(true); // Ensure that there are not open object packs if (current_pack_) { LogCvmfs( kLogUploadGateway, kLogStderr, "Could not initialize SessionContext - Existing open object packs."); ret = false; } ret = InitializeDerived() && ret; return ret; } bool SessionContextBase::Finalize(bool commit, const std::string& old_root_hash, const std::string& new_root_hash) { assert(active_handles_.empty()); { MutexLockGuard lock(current_pack_mtx_); if (current_pack_ && current_pack_->GetNoObjects() > 0) { Dispatch(); current_pack_ = NULL; } } bool results = true; int64_t jobs_finished = 0; while (!upload_results_.IsEmpty() || (jobs_finished < NumJobsSubmitted())) { Future<bool>* future = upload_results_.Dequeue(); results = future->Get() && results; delete future; jobs_finished++; } if (commit) { if (old_root_hash.empty() || new_root_hash.empty()) { return false; } bool commit_result = Commit(old_root_hash, new_root_hash); if (!commit_result) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext: could not commit session. Aborting."); abort(); } } results &= FinalizeDerived() && (bytes_committed_ == bytes_dispatched_); pthread_mutex_destroy(&current_pack_mtx_); return results; } void SessionContextBase::WaitForUpload() { if (!upload_results_.IsEmpty()) { queue_was_flushed_.Dequeue(); } } ObjectPack::BucketHandle SessionContextBase::NewBucket() { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { current_pack_ = new ObjectPack(max_pack_size_); } ObjectPack::BucketHandle hd = current_pack_->NewBucket(); active_handles_.push_back(hd); return hd; } bool SessionContextBase::CommitBucket(const ObjectPack::BucketContentType type, const shash::Any& id, const ObjectPack::BucketHandle handle, const std::string& name, const bool force_dispatch) { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { LogCvmfs(kLogUploadGateway, kLogStderr, "Error: Called SessionBaseContext::CommitBucket without an open " "ObjectPack."); return false; } uint64_t size0 = current_pack_->size(); bool committed = current_pack_->CommitBucket(type, id, handle, name); if (committed) { // Current pack is still not full active_handles_.erase( std::remove(active_handles_.begin(), active_handles_.end(), handle), active_handles_.end()); uint64_t size1 = current_pack_->size(); bytes_committed_ += size1 - size0; if (force_dispatch) { Dispatch(); current_pack_ = NULL; } } else { // Current pack is full and can be dispatched uint64_t new_size = 0; if (handle->capacity > max_pack_size_) { new_size = handle->capacity + 1; } else { new_size = max_pack_size_; } ObjectPack* new_pack = new ObjectPack(new_size); for (size_t i = 0u; i < active_handles_.size(); ++i) { current_pack_->TransferBucket(active_handles_[i], new_pack); } if (current_pack_->GetNoObjects() > 0) { Dispatch(); } current_pack_ = new_pack; CommitBucket(type, id, handle, name, false); } return true; } int64_t SessionContextBase::NumJobsSubmitted() const { return atomic_read64(&objects_dispatched_); } void SessionContextBase::Dispatch() { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { return; } atomic_inc64(&objects_dispatched_); bytes_dispatched_ += current_pack_->size(); upload_results_.Enqueue(DispatchObjectPack(current_pack_)); } SessionContext::SessionContext() : SessionContextBase(), upload_jobs_(1000000, 1000000), worker_terminate_(), worker_() {} bool SessionContext::InitializeDerived() { // Start worker thread atomic_init32(&worker_terminate_); atomic_write32(&worker_terminate_, 0); upload_jobs_.Drop(); int retval = pthread_create(&worker_, NULL, UploadLoop, reinterpret_cast<void*>(this)); return !retval; } bool SessionContext::FinalizeDerived() { atomic_write32(&worker_terminate_, 1); pthread_join(worker_, NULL); return true; } bool SessionContext::Commit(const std::string& old_root_hash, const std::string& new_root_hash) { std::string request; JsonStringInput request_input; request_input.push_back( std::make_pair("old_root_hash", old_root_hash.c_str())); request_input.push_back( std::make_pair("new_root_hash", new_root_hash.c_str())); ToJsonString(request_input, &request); CurlBuffer buffer; return MakeEndRequest("POST", key_id_, secret_, session_token_, api_url_, request, &buffer); } Future<bool>* SessionContext::DispatchObjectPack(ObjectPack* pack) { UploadJob* job = new UploadJob; job->pack = pack; job->result = new Future<bool>(); upload_jobs_.Enqueue(job); return job->result; } bool SessionContext::DoUpload(const SessionContext::UploadJob* job) { // Set up the object pack serializer ObjectPackProducer serializer(job->pack); shash::Any payload_digest(shash::kSha1); serializer.GetDigest(&payload_digest); const std::string json_msg = "{\"session_token\" : \"" + session_token_ + "\", \"payload_digest\" : \"" + payload_digest.ToString(false) + "\", \"header_size\" : \"" + StringifyInt(serializer.GetHeaderSize()) + "\", \"api_version\" : \"" + StringifyInt(gateway::APIVersion()) + "\"}"; // Compute HMAC shash::Any hmac(shash::kSha1); shash::HmacString(secret_, json_msg, &hmac); CurlSendPayload payload; payload.json_message = &json_msg; payload.pack_serializer = &serializer; payload.index = 0; const size_t payload_size = json_msg.size() + serializer.GetHeaderSize() + job->pack->size(); // Prepare the Curl POST request CURL* h_curl = curl_easy_init(); if (!h_curl) { return false; } // Set HTTP headers (Authorization and Message-Size) std::string header_str = std::string("Authorization: ") + key_id_ + " " + Base64(hmac.ToString(false)); struct curl_slist* auth_header = NULL; auth_header = curl_slist_append(auth_header, header_str.c_str()); header_str = std::string("Message-Size: ") + StringifyInt(json_msg.size()); auth_header = curl_slist_append(auth_header, header_str.c_str()); curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header); std::string reply; curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(h_curl, CURLOPT_USERAGENT, "cvmfs/" VERSION); curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(h_curl, CURLOPT_URL, (api_url_ + "/payloads").c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, NULL); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(payload_size)); curl_easy_setopt(h_curl, CURLOPT_READDATA, &payload); curl_easy_setopt(h_curl, CURLOPT_READFUNCTION, SendCB); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, &reply); // Perform the Curl POST request CURLcode ret = curl_easy_perform(h_curl); if (ret) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext - curl_easy_perform failed: %d", ret); } const bool ok = (reply == "{\"status\":\"ok\"}"); if (!ok) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext - curl_easy_perform reply: %s", reply.c_str()); } curl_easy_cleanup(h_curl); h_curl = NULL; return ok && !ret; } void* SessionContext::UploadLoop(void* data) { SessionContext* ctx = reinterpret_cast<SessionContext*>(data); int64_t jobs_processed = 0; while (!ctx->ShouldTerminate()) { while (jobs_processed < ctx->NumJobsSubmitted()) { UploadJob* job = ctx->upload_jobs_.Dequeue(); if (!ctx->DoUpload(job)) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext: could not submit payload. Aborting."); abort(); } job->result->Set(true); delete job->pack; delete job; jobs_processed++; } if (ctx->queue_was_flushed_.IsEmpty()) { ctx->queue_was_flushed_.Enqueue(true); } } return NULL; } bool SessionContext::ShouldTerminate() { return atomic_read32(&worker_terminate_); } } // namespace upload <commit_msg>Kill a magic number, save a kitten.<commit_after>/** * This file is part of the CernVM File System. */ #include "session_context.h" #include <algorithm> #include "curl/curl.h" #include "cvmfs_config.h" #include "gateway_util.h" #include "json_document.h" #include "swissknife_lease_curl.h" #include "util/string.h" namespace { const size_t kMaxResultQueueSize = 1000000; } namespace upload { size_t SendCB(void* ptr, size_t size, size_t nmemb, void* userp) { CurlSendPayload* payload = static_cast<CurlSendPayload*>(userp); size_t max_chunk_size = size * nmemb; if (max_chunk_size < 1) { return 0; } size_t current_chunk_size = 0; while (current_chunk_size < max_chunk_size) { if (payload->index < payload->json_message->size()) { // Can add a chunk from the JSON message const size_t read_size = std::min(max_chunk_size - current_chunk_size, payload->json_message->size() - payload->index); current_chunk_size += read_size; std::memcpy(ptr, payload->json_message->data() + payload->index, read_size); payload->index += read_size; } else { // Can add a chunk from the payload const size_t max_read_size = max_chunk_size - current_chunk_size; const unsigned nbytes = payload->pack_serializer->ProduceNext( max_read_size, static_cast<unsigned char*>(ptr) + current_chunk_size); current_chunk_size += nbytes; if (!nbytes) { break; } } } return current_chunk_size; } size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) { std::string* my_buffer = static_cast<std::string*>(userp); if (size * nmemb < 1) { return 0; } *my_buffer = static_cast<char*>(buffer); return my_buffer->size(); } SessionContextBase::SessionContextBase() : upload_results_(kMaxResultQueueSize, kMaxResultQueueSize), api_url_(), session_token_(), key_id_(), secret_(), queue_was_flushed_(1, 1), max_pack_size_(ObjectPack::kDefaultLimit), active_handles_(), current_pack_(NULL), current_pack_mtx_(), objects_dispatched_(0), bytes_committed_(0), bytes_dispatched_(0) {} SessionContextBase::~SessionContextBase() {} bool SessionContextBase::Initialize(const std::string& api_url, const std::string& session_token, const std::string& key_id, const std::string& secret, uint64_t max_pack_size) { bool ret = true; // Initialize session context lock pthread_mutexattr_t attr; if (pthread_mutexattr_init(&attr) || pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) || pthread_mutex_init(&current_pack_mtx_, &attr) || pthread_mutexattr_destroy(&attr)) { LogCvmfs(kLogUploadGateway, kLogStderr, "Could not initialize SessionContext lock."); return false; } // Set upstream URL and session token api_url_ = api_url; session_token_ = session_token; key_id_ = key_id; secret_ = secret; max_pack_size_ = max_pack_size; atomic_init64(&objects_dispatched_); bytes_committed_ = 0u; bytes_dispatched_ = 0u; // Ensure that the upload job and result queues are empty upload_results_.Drop(); queue_was_flushed_.Drop(); queue_was_flushed_.Enqueue(true); // Ensure that there are not open object packs if (current_pack_) { LogCvmfs( kLogUploadGateway, kLogStderr, "Could not initialize SessionContext - Existing open object packs."); ret = false; } ret = InitializeDerived() && ret; return ret; } bool SessionContextBase::Finalize(bool commit, const std::string& old_root_hash, const std::string& new_root_hash) { assert(active_handles_.empty()); { MutexLockGuard lock(current_pack_mtx_); if (current_pack_ && current_pack_->GetNoObjects() > 0) { Dispatch(); current_pack_ = NULL; } } bool results = true; int64_t jobs_finished = 0; while (!upload_results_.IsEmpty() || (jobs_finished < NumJobsSubmitted())) { Future<bool>* future = upload_results_.Dequeue(); results = future->Get() && results; delete future; jobs_finished++; } if (commit) { if (old_root_hash.empty() || new_root_hash.empty()) { return false; } bool commit_result = Commit(old_root_hash, new_root_hash); if (!commit_result) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext: could not commit session. Aborting."); abort(); } } results &= FinalizeDerived() && (bytes_committed_ == bytes_dispatched_); pthread_mutex_destroy(&current_pack_mtx_); return results; } void SessionContextBase::WaitForUpload() { if (!upload_results_.IsEmpty()) { queue_was_flushed_.Dequeue(); } } ObjectPack::BucketHandle SessionContextBase::NewBucket() { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { current_pack_ = new ObjectPack(max_pack_size_); } ObjectPack::BucketHandle hd = current_pack_->NewBucket(); active_handles_.push_back(hd); return hd; } bool SessionContextBase::CommitBucket(const ObjectPack::BucketContentType type, const shash::Any& id, const ObjectPack::BucketHandle handle, const std::string& name, const bool force_dispatch) { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { LogCvmfs(kLogUploadGateway, kLogStderr, "Error: Called SessionBaseContext::CommitBucket without an open " "ObjectPack."); return false; } uint64_t size0 = current_pack_->size(); bool committed = current_pack_->CommitBucket(type, id, handle, name); if (committed) { // Current pack is still not full active_handles_.erase( std::remove(active_handles_.begin(), active_handles_.end(), handle), active_handles_.end()); uint64_t size1 = current_pack_->size(); bytes_committed_ += size1 - size0; if (force_dispatch) { Dispatch(); current_pack_ = NULL; } } else { // Current pack is full and can be dispatched uint64_t new_size = 0; if (handle->capacity > max_pack_size_) { new_size = handle->capacity + 1; } else { new_size = max_pack_size_; } ObjectPack* new_pack = new ObjectPack(new_size); for (size_t i = 0u; i < active_handles_.size(); ++i) { current_pack_->TransferBucket(active_handles_[i], new_pack); } if (current_pack_->GetNoObjects() > 0) { Dispatch(); } current_pack_ = new_pack; CommitBucket(type, id, handle, name, false); } return true; } int64_t SessionContextBase::NumJobsSubmitted() const { return atomic_read64(&objects_dispatched_); } void SessionContextBase::Dispatch() { MutexLockGuard lock(current_pack_mtx_); if (!current_pack_) { return; } atomic_inc64(&objects_dispatched_); bytes_dispatched_ += current_pack_->size(); upload_results_.Enqueue(DispatchObjectPack(current_pack_)); } SessionContext::SessionContext() : SessionContextBase(), upload_jobs_(1000000, 1000000), worker_terminate_(), worker_() {} bool SessionContext::InitializeDerived() { // Start worker thread atomic_init32(&worker_terminate_); atomic_write32(&worker_terminate_, 0); upload_jobs_.Drop(); int retval = pthread_create(&worker_, NULL, UploadLoop, reinterpret_cast<void*>(this)); return !retval; } bool SessionContext::FinalizeDerived() { atomic_write32(&worker_terminate_, 1); pthread_join(worker_, NULL); return true; } bool SessionContext::Commit(const std::string& old_root_hash, const std::string& new_root_hash) { std::string request; JsonStringInput request_input; request_input.push_back( std::make_pair("old_root_hash", old_root_hash.c_str())); request_input.push_back( std::make_pair("new_root_hash", new_root_hash.c_str())); ToJsonString(request_input, &request); CurlBuffer buffer; return MakeEndRequest("POST", key_id_, secret_, session_token_, api_url_, request, &buffer); } Future<bool>* SessionContext::DispatchObjectPack(ObjectPack* pack) { UploadJob* job = new UploadJob; job->pack = pack; job->result = new Future<bool>(); upload_jobs_.Enqueue(job); return job->result; } bool SessionContext::DoUpload(const SessionContext::UploadJob* job) { // Set up the object pack serializer ObjectPackProducer serializer(job->pack); shash::Any payload_digest(shash::kSha1); serializer.GetDigest(&payload_digest); const std::string json_msg = "{\"session_token\" : \"" + session_token_ + "\", \"payload_digest\" : \"" + payload_digest.ToString(false) + "\", \"header_size\" : \"" + StringifyInt(serializer.GetHeaderSize()) + "\", \"api_version\" : \"" + StringifyInt(gateway::APIVersion()) + "\"}"; // Compute HMAC shash::Any hmac(shash::kSha1); shash::HmacString(secret_, json_msg, &hmac); CurlSendPayload payload; payload.json_message = &json_msg; payload.pack_serializer = &serializer; payload.index = 0; const size_t payload_size = json_msg.size() + serializer.GetHeaderSize() + job->pack->size(); // Prepare the Curl POST request CURL* h_curl = curl_easy_init(); if (!h_curl) { return false; } // Set HTTP headers (Authorization and Message-Size) std::string header_str = std::string("Authorization: ") + key_id_ + " " + Base64(hmac.ToString(false)); struct curl_slist* auth_header = NULL; auth_header = curl_slist_append(auth_header, header_str.c_str()); header_str = std::string("Message-Size: ") + StringifyInt(json_msg.size()); auth_header = curl_slist_append(auth_header, header_str.c_str()); curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header); std::string reply; curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(h_curl, CURLOPT_USERAGENT, "cvmfs/" VERSION); curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(h_curl, CURLOPT_URL, (api_url_ + "/payloads").c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, NULL); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(payload_size)); curl_easy_setopt(h_curl, CURLOPT_READDATA, &payload); curl_easy_setopt(h_curl, CURLOPT_READFUNCTION, SendCB); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, &reply); // Perform the Curl POST request CURLcode ret = curl_easy_perform(h_curl); if (ret) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext - curl_easy_perform failed: %d", ret); } const bool ok = (reply == "{\"status\":\"ok\"}"); if (!ok) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext - curl_easy_perform reply: %s", reply.c_str()); } curl_easy_cleanup(h_curl); h_curl = NULL; return ok && !ret; } void* SessionContext::UploadLoop(void* data) { SessionContext* ctx = reinterpret_cast<SessionContext*>(data); int64_t jobs_processed = 0; while (!ctx->ShouldTerminate()) { while (jobs_processed < ctx->NumJobsSubmitted()) { UploadJob* job = ctx->upload_jobs_.Dequeue(); if (!ctx->DoUpload(job)) { LogCvmfs(kLogUploadGateway, kLogStderr, "SessionContext: could not submit payload. Aborting."); abort(); } job->result->Set(true); delete job->pack; delete job; jobs_processed++; } if (ctx->queue_was_flushed_.IsEmpty()) { ctx->queue_was_flushed_.Enqueue(true); } } return NULL; } bool SessionContext::ShouldTerminate() { return atomic_read32(&worker_terminate_); } } // namespace upload <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Nathan Osman * * 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 <QCoreApplication> #include <QDir> #if defined(Q_OS_UNIX) # include <sys/stat.h> #elif defined(Q_OS_WIN) # include <aclapi.h> # include <fileapi.h> #endif #include "QHttpEngine/qlocalfile.h" #include "qlocalfile_p.h" QLocalFilePrivate::QLocalFilePrivate(QLocalFile *localFile) : QObject(localFile), q(localFile) { // Store the file in the user's home directory and set the filename to the // name of the application with a "." prepended q->setFileName(QDir::home().absoluteFilePath("." + QCoreApplication::applicationName())); } bool QLocalFilePrivate::setPermission() { #if defined(Q_OS_UNIX) return chmod(q->fileName().toUtf8().constData(), S_IRUSR | S_IWUSR) == 0; #elif defined(Q_OS_WIN) // Windows uses ACLs to control file access - each file contains an ACL // which consists of one or more ACEs (access control entries) - so the // ACL for the file must contain only a single ACE, granting access to the // file owner (the current user) EXPLICIT_ACCESS_W ea; ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS_W)); ea.grfAccessPermissions = STANDARD_RIGHTS_REQUIRED; ea.grfAccessMode = GRANT_ACCESS; ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT; ea.Trustee.TrusteeForm = TRUSTEE_IS_NAME; ea.Trustee.ptstrName = L"CREATOR OWNER"; // Create a new ACL with a single access control entry PACL pACL; if(SetEntriesInAclW(1, &ea, NULL, &pACL) != ERROR_SUCCESS) { return false; } // Apply the ACL to the file if(SetNamedSecurityInfoW((LPWSTR)q->fileName().utf16(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, NULL, NULL, pACL, NULL) != ERROR_SUCCESS) { LocalFree(pACL); return false; } LocalFree(pACL); return true; #else // Unsupported platform, so setPermission() must fail return false; #endif } bool QLocalFilePrivate::setHidden() { #if defined(Q_OS_UNIX) // On Unix, anything beginning with a "." is hidden return true; #elif defined(Q_OS_WIN) return SetFileAttributesW((LPCWSTR)q->fileName().utf16(), FILE_ATTRIBUTE_HIDDEN) != 0; #else // Unsupported platform, so setHidden() must fail return false; #endif } QLocalFile::QLocalFile(QObject *parent) : QFile(parent), d(new QLocalFilePrivate(this)) { } bool QLocalFile::open() { return QFile::open(QIODevice::WriteOnly) && d->setPermission() && d->setHidden(); } <commit_msg>Fixed access control issue on Windows.<commit_after>/* * Copyright (c) 2015 Nathan Osman * * 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 <QCoreApplication> #include <QDir> #if defined(Q_OS_UNIX) # include <sys/stat.h> #elif defined(Q_OS_WIN) # include <aclapi.h> # include <fileapi.h> #endif #include "QHttpEngine/qlocalfile.h" #include "qlocalfile_p.h" QLocalFilePrivate::QLocalFilePrivate(QLocalFile *localFile) : QObject(localFile), q(localFile) { // Store the file in the user's home directory and set the filename to the // name of the application with a "." prepended q->setFileName(QDir::home().absoluteFilePath("." + QCoreApplication::applicationName())); } bool QLocalFilePrivate::setPermission() { #if defined(Q_OS_UNIX) return chmod(q->fileName().toUtf8().constData(), S_IRUSR | S_IWUSR) == 0; #elif defined(Q_OS_WIN) // Windows uses ACLs to control file access - each file contains an ACL // which consists of one or more ACEs (access control entries) - so the // ACL for the file must contain only a single ACE, granting access to the // file owner (the current user) EXPLICIT_ACCESS_W ea; ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS_W)); ea.grfAccessPermissions = GENERIC_ALL; ea.grfAccessMode = GRANT_ACCESS; ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT; ea.Trustee.TrusteeForm = TRUSTEE_IS_NAME; ea.Trustee.ptstrName = L"CREATOR OWNER"; // Create a new ACL with a single access control entry PACL pACL; if(SetEntriesInAclW(1, &ea, NULL, &pACL) != ERROR_SUCCESS) { return false; } // Apply the ACL to the file if(SetNamedSecurityInfoW((LPWSTR)q->fileName().utf16(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, NULL, NULL, pACL, NULL) != ERROR_SUCCESS) { LocalFree(pACL); return false; } LocalFree(pACL); return true; #else // Unsupported platform, so setPermission() must fail return false; #endif } bool QLocalFilePrivate::setHidden() { #if defined(Q_OS_UNIX) // On Unix, anything beginning with a "." is hidden return true; #elif defined(Q_OS_WIN) return SetFileAttributesW((LPCWSTR)q->fileName().utf16(), FILE_ATTRIBUTE_HIDDEN) != 0; #else // Unsupported platform, so setHidden() must fail return false; #endif } QLocalFile::QLocalFile(QObject *parent) : QFile(parent), d(new QLocalFilePrivate(this)) { } bool QLocalFile::open() { return QFile::open(QIODevice::WriteOnly) && d->setPermission() && d->setHidden(); } <|endoftext|>
<commit_before>#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { if(uri.scheme() != QString("bitcoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("bitcoin://")) { uri.replace(0, 10, "bitcoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "BottleCaps.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "BottleCaps.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=BottleCaps\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("BottleCaps-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " BottleCaps-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("BottleCaps-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil <commit_msg>Fix URI<commit_after>#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { if(uri.scheme() != QString("bottlecaps")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bottlecaps:// to bottlecaps: // // Cannot handle this later, because bottlecaps:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("bottlecaps:// ")) { uri.replace(0, 11, "bottlecaps:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "BottleCaps.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "BottleCaps.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=BottleCaps\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("BottleCaps-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " BottleCaps-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("BottleCaps-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil <|endoftext|>
<commit_before>/* Copyright 2002-2013 CEA LIST This file is part of LIMA. LIMA 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. LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/> */ /** @brief logger for xml-formatted linguistic data in graph. * * @file MAxmlLogger.cpp * @author Benoit Mathieu <[email protected]> * Copyright (c) 2003 by CEA */ #include "FullTokenXmlLogger.h" #include "common/time/traceUtils.h" #include "common/Data/strwstrtools.h" #include "common/MediaticData/mediaticData.h" #include "common/XMLConfigurationFiles/xmlConfigurationFileExceptions.h" #include "common/AbstractFactoryPattern/SimpleFactory.h" #include "linguisticProcessing/core/LinguisticProcessors/LinguisticMetaData.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/Token.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/AgglutinatedToken.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/MorphoSyntacticData.h" #include <iostream> #include <fstream> using namespace std; using namespace boost; using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure; using namespace Lima::Common::MediaticData; using namespace Lima::Common::XMLConfigurationFiles; namespace Lima { namespace LinguisticProcessing { namespace LinguisticAnalysisStructure { SimpleFactory<MediaProcessUnit,FullTokenXmlLogger> fullTokenXmlLoggerFactory(FULLTOKENXMLLOGGER_CLASSID); FullTokenXmlLogger::FullTokenXmlLogger(): AbstractLinguisticLogger(".output.xml") {} FullTokenXmlLogger::~FullTokenXmlLogger() {} void FullTokenXmlLogger::init( Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, Manager* manager) { AbstractLinguisticLogger::init(unitConfiguration,manager); try { m_graphId=unitConfiguration.getParamsValueAtKey("graph"); } catch (NoSuchParam& ) { m_graphId=string("AnalysisGraph"); } m_language=manager->getInitializationParameters().media; m_propertyCodeManager= &(static_cast<const Common::MediaticData::LanguageData&>(Common::MediaticData::MediaticData::single().mediaData(m_language)).getPropertyCodeManager()); } // Each token of the specified path is // searched into the specified dictionary. LimaStatusCode FullTokenXmlLogger::process( AnalysisContent& analysis) const { TimeUtils::updateCurrentTime(); LinguisticMetaData* metadata=static_cast<LinguisticMetaData*>(analysis.getData("LinguisticMetaData")); if (metadata == 0) { DICTIONARYLOGINIT; LERROR << "no LinguisticMetaData ! abort"; return MISSING_DATA; } AnalysisGraph* tokenList=static_cast<AnalysisGraph*>(analysis.getData(m_graphId)); std::ofstream fout; if (!openLogFile(fout,metadata->getMetaData("FileName"))) { MORPHOLOGINIT; LERROR << "Error: cannot open log file"; return CANNOT_OPEN_FILE_ERROR; } dump(fout, *tokenList); fout.close(); TimeUtils::logElapsedTime("FullTokenXmlLogger"); return SUCCESS_ID; } //********************************************************************** // define a visitor to go through the graph and output the fulltokens class DumpXMLVisitor : public default_bfs_visitor { std::ostream& m_ostream; std::map<LinguisticGraphVertex,uint64_t> m_depthSource; std::map<LinguisticGraphVertex,uint64_t> m_depth; const Common::PropertyCode::PropertyCodeManager& m_propertyCodeManager; const FsaStringsPool& m_stringsPool; public: DumpXMLVisitor(std::ostream& os, const Common::PropertyCode::PropertyCodeManager& pcm, const FsaStringsPool& stringsPool): m_ostream(os),m_depthSource(),m_depth(),m_propertyCodeManager(pcm),m_stringsPool(stringsPool) {} void discover_vertex(LinguisticGraphVertex v, const LinguisticGraph& g); void examine_edge(LinguisticGraphEdge v, const LinguisticGraph& g); }; void DumpXMLVisitor::examine_edge(LinguisticGraphEdge e, const LinguisticGraph& g) { LinguisticGraphVertex vsource=source(e,g); LinguisticGraphVertex vtarget=target(e,g); // hack : skip edge between first and last vertex if (vsource == 0 && vtarget == 1) { return; } std::map<LinguisticGraphVertex,uint64_t>::iterator d=m_depthSource.find(vsource); if (d == m_depthSource.end()) { m_depthSource[vsource]=0; m_depth[vtarget]=0; } else { m_depthSource[vtarget]=(*d).second; (*d).second++; m_depth[vtarget]=(*d).second; } } void DumpXMLVisitor::discover_vertex(LinguisticGraphVertex v, const LinguisticGraph& g) { m_ostream << "<vertex id=\"" << v << "\">" << std::endl; Token* t = get(vertex_token,g,v); if (t != 0) { m_ostream << " <token>" << std::endl; t->outputXml(m_ostream,m_propertyCodeManager,m_stringsPool); m_ostream << " </token>" << std::endl; } MorphoSyntacticData* data = get(vertex_data,g,v); if (data != 0 ) { data->outputXml(m_ostream,m_propertyCodeManager,m_stringsPool); } m_ostream << "</vertex>" << std::endl; } //********************************************************************** // dumps memory structure on XML file void FullTokenXmlLogger::dump(std::ostream& xmlStream, AnalysisGraph& tTokenList) const { //LASLOGINIT; xmlStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl; xmlStream << "<!--generated by MM project on "; // const uint64_t dateLen = strlen("Tue Oct 22 13:42:36 2002"); time_t aclock; time(&aclock); /* Get time in seconds */ std::string str(ctime(&aclock)); xmlStream << str; xmlStream << "-->" << std::endl; xmlStream << "<?xml-stylesheet type=\"text/xsl\" href=\"DataStructure.xslt\"?>" << std::endl; xmlStream << "<data_structure xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; xmlStream << " xsi:noNamespaceSchemaLocation=\"DataStructure.xsd\">" << std::endl; // dump the graph const FsaStringsPool& sp=Common::MediaticData::MediaticData::single().stringsPool(m_language); DumpXMLVisitor vis(xmlStream,*m_propertyCodeManager,sp); breadth_first_search(*(tTokenList.getGraph()), tTokenList.firstVertex(), visitor(vis)); xmlStream << "</data_structure>" << std::endl; } } // LinguisticAnalysisStructure } // LinguisticProcessing } // Lima <commit_msg>add missing import<commit_after>/* Copyright 2002-2013 CEA LIST This file is part of LIMA. LIMA 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. LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/> */ /** @brief logger for xml-formatted linguistic data in graph. * * @file MAxmlLogger.cpp * @author Benoit Mathieu <[email protected]> * Copyright (c) 2003 by CEA */ #include "FullTokenXmlLogger.h" #include "common/time/traceUtils.h" #include "common/Data/strwstrtools.h" #include "common/MediaticData/mediaticData.h" #include "common/XMLConfigurationFiles/xmlConfigurationFileExceptions.h" #include "common/AbstractFactoryPattern/SimpleFactory.h" #include "linguisticProcessing/core/LinguisticProcessors/LinguisticMetaData.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/Token.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/AgglutinatedToken.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/MorphoSyntacticData.h" #include <iostream> #include <fstream> #include <ctime> using namespace std; using namespace boost; using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure; using namespace Lima::Common::MediaticData; using namespace Lima::Common::XMLConfigurationFiles; namespace Lima { namespace LinguisticProcessing { namespace LinguisticAnalysisStructure { SimpleFactory<MediaProcessUnit,FullTokenXmlLogger> fullTokenXmlLoggerFactory(FULLTOKENXMLLOGGER_CLASSID); FullTokenXmlLogger::FullTokenXmlLogger(): AbstractLinguisticLogger(".output.xml") {} FullTokenXmlLogger::~FullTokenXmlLogger() {} void FullTokenXmlLogger::init( Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, Manager* manager) { AbstractLinguisticLogger::init(unitConfiguration,manager); try { m_graphId=unitConfiguration.getParamsValueAtKey("graph"); } catch (NoSuchParam& ) { m_graphId=string("AnalysisGraph"); } m_language=manager->getInitializationParameters().media; m_propertyCodeManager= &(static_cast<const Common::MediaticData::LanguageData&>(Common::MediaticData::MediaticData::single().mediaData(m_language)).getPropertyCodeManager()); } // Each token of the specified path is // searched into the specified dictionary. LimaStatusCode FullTokenXmlLogger::process( AnalysisContent& analysis) const { TimeUtils::updateCurrentTime(); LinguisticMetaData* metadata=static_cast<LinguisticMetaData*>(analysis.getData("LinguisticMetaData")); if (metadata == 0) { DICTIONARYLOGINIT; LERROR << "no LinguisticMetaData ! abort"; return MISSING_DATA; } AnalysisGraph* tokenList=static_cast<AnalysisGraph*>(analysis.getData(m_graphId)); std::ofstream fout; if (!openLogFile(fout,metadata->getMetaData("FileName"))) { MORPHOLOGINIT; LERROR << "Error: cannot open log file"; return CANNOT_OPEN_FILE_ERROR; } dump(fout, *tokenList); fout.close(); TimeUtils::logElapsedTime("FullTokenXmlLogger"); return SUCCESS_ID; } //********************************************************************** // define a visitor to go through the graph and output the fulltokens class DumpXMLVisitor : public default_bfs_visitor { std::ostream& m_ostream; std::map<LinguisticGraphVertex,uint64_t> m_depthSource; std::map<LinguisticGraphVertex,uint64_t> m_depth; const Common::PropertyCode::PropertyCodeManager& m_propertyCodeManager; const FsaStringsPool& m_stringsPool; public: DumpXMLVisitor(std::ostream& os, const Common::PropertyCode::PropertyCodeManager& pcm, const FsaStringsPool& stringsPool): m_ostream(os),m_depthSource(),m_depth(),m_propertyCodeManager(pcm),m_stringsPool(stringsPool) {} void discover_vertex(LinguisticGraphVertex v, const LinguisticGraph& g); void examine_edge(LinguisticGraphEdge v, const LinguisticGraph& g); }; void DumpXMLVisitor::examine_edge(LinguisticGraphEdge e, const LinguisticGraph& g) { LinguisticGraphVertex vsource=source(e,g); LinguisticGraphVertex vtarget=target(e,g); // hack : skip edge between first and last vertex if (vsource == 0 && vtarget == 1) { return; } std::map<LinguisticGraphVertex,uint64_t>::iterator d=m_depthSource.find(vsource); if (d == m_depthSource.end()) { m_depthSource[vsource]=0; m_depth[vtarget]=0; } else { m_depthSource[vtarget]=(*d).second; (*d).second++; m_depth[vtarget]=(*d).second; } } void DumpXMLVisitor::discover_vertex(LinguisticGraphVertex v, const LinguisticGraph& g) { m_ostream << "<vertex id=\"" << v << "\">" << std::endl; Token* t = get(vertex_token,g,v); if (t != 0) { m_ostream << " <token>" << std::endl; t->outputXml(m_ostream,m_propertyCodeManager,m_stringsPool); m_ostream << " </token>" << std::endl; } MorphoSyntacticData* data = get(vertex_data,g,v); if (data != 0 ) { data->outputXml(m_ostream,m_propertyCodeManager,m_stringsPool); } m_ostream << "</vertex>" << std::endl; } //********************************************************************** // dumps memory structure on XML file void FullTokenXmlLogger::dump(std::ostream& xmlStream, AnalysisGraph& tTokenList) const { //LASLOGINIT; xmlStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl; xmlStream << "<!--generated by MM project on "; // const uint64_t dateLen = strlen("Tue Oct 22 13:42:36 2002"); time_t aclock; time(&aclock); /* Get time in seconds */ std::string str(ctime(&aclock)); xmlStream << str; xmlStream << "-->" << std::endl; xmlStream << "<?xml-stylesheet type=\"text/xsl\" href=\"DataStructure.xslt\"?>" << std::endl; xmlStream << "<data_structure xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; xmlStream << " xsi:noNamespaceSchemaLocation=\"DataStructure.xsd\">" << std::endl; // dump the graph const FsaStringsPool& sp=Common::MediaticData::MediaticData::single().stringsPool(m_language); DumpXMLVisitor vis(xmlStream,*m_propertyCodeManager,sp); breadth_first_search(*(tTokenList.getGraph()), tTokenList.firstVertex(), visitor(vis)); xmlStream << "</data_structure>" << std::endl; } } // LinguisticAnalysisStructure } // LinguisticProcessing } // Lima <|endoftext|>
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../core/Setup.h" #include <algorithm> #include <fstream> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # include <ShlObj.h> # include <Shlwapi.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__APPLE__) # include <TargetConditionals.h> # include <objc/message.h> # include <objc/NSObjCRuntime.h> # include <CoreFoundation/CoreFoundation.h> #elif defined(__ANDROID__) # include "../core/android/EngineAndroid.hpp" #elif defined(__linux__) # include <pwd.h> #endif #include "FileSystem.hpp" #include "Archive.hpp" #include "../core/Engine.hpp" #include "../utils/Log.hpp" #if defined(__APPLE__) # include "CfPointer.hpp" #endif namespace ouzel { namespace storage { FileSystem::FileSystem(Engine& initEngine): engine(initEngine) { #if defined(_WIN32) std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const int bufferSize = WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, nullptr, 0, nullptr, nullptr); if (bufferSize == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8"); std::vector<char> appFilename(bufferSize); if (WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, appFilename.data(), bufferSize, nullptr, nullptr) == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8"); appPath = Path(appFilename.data()).getDirectory(); engine.log(Log::Level::Info) << "Application directory: " << std::string(appPath); #elif defined(__APPLE__) CFBundleRef bundle = CFBundleGetMainBundle(); if (!bundle) throw std::runtime_error("Failed to get main bundle"); CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle); if (!relativePath) throw std::runtime_error("Failed to get resource directory"); CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get()); CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle); const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get()); std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize)); const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize); if (!result) throw std::runtime_error("Failed to get resource directory"); appPath = resourceDirectory.data(); engine.log(Log::Level::Info) << "Application directory: " << appPath; #elif defined(__ANDROID__) // not available for Android #elif defined(__linux__) char executableDirectory[PATH_MAX]; ssize_t length; if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1) throw std::system_error(errno, std::system_category(), "Failed to get current directory"); executableDirectory[length] = '\0'; appPath = Path(executableDirectory).getDirectory(); engine.log(Log::Level::Info) << "Application directory: " << appPath; #endif } Path FileSystem::getStorageDirectory(const bool user) const { #if defined(_WIN32) WCHAR appDataPath[MAX_PATH]; HRESULT hr; if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath))) throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory"); const int appDataBufferSize = WideCharToMultiByte(CP_UTF8, 0, appDataPath, -1, nullptr, 0, nullptr, nullptr); if (appDataBufferSize == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8"); std::vector<char> appDataBuffer(appDataBufferSize); if (WideCharToMultiByte(CP_UTF8, 0, appDataPath, -1, appDataBuffer.data(), appDataBufferSize, nullptr, nullptr) == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8"); std::string path = appDataBuffer.data(); path += Path::directorySeparator + OUZEL_DEVELOPER_NAME; if (!directoryExists(path)) { const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); if (bufferSize == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char"); std::vector<WCHAR> buffer(bufferSize); if (MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, buffer.data(), bufferSize) == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char"); // relative paths longer than MAX_PATH are not supported if (buffer.size() > MAX_PATH) buffer.insert(buffer.begin(), {L'\\', L'\\', L'?', L'\\'}); const DWORD attributes = GetFileAttributesW(buffer.data()); if (attributes == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryW(buffer.data(), nullptr)) throw std::system_error(GetLastError(), std::system_category(), "Failed to create directory " + path); } else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0) throw std::runtime_error(path + " is not a directory"); } path += Path::directorySeparator + OUZEL_APPLICATION_NAME; if (!directoryExists(path)) { const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); if (bufferSize == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char"); std::vector<WCHAR> buffer(bufferSize); if (MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, buffer.data(), bufferSize) == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char"); // relative paths longer than MAX_PATH are not supported if (buffer.size() > MAX_PATH) buffer.insert(buffer.begin(), {L'\\', L'\\', L'?', L'\\'}); const DWORD attributes = GetFileAttributesW(buffer.data()); if (attributes == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryW(buffer.data(), nullptr)) throw std::system_error(GetLastError(), std::system_category(), "Failed to create directory " + path); } else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0) throw std::runtime_error(path + " is not a directory"); } return path; #elif TARGET_OS_IOS || TARGET_OS_TV id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSDocumentDirectory = 9; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!documentDirectory) throw std::runtime_error("Failed to get document directory"); id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path")); return reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String")); #elif TARGET_OS_MAC id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSApplicationSupportDirectory = 14; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!applicationSupportDirectory) throw std::runtime_error("Failed to get application support directory"); CFBundleRef bundle = CFBundleGetMainBundle(); CFStringRef identifier = CFBundleGetIdentifier(bundle); if (!identifier) identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME); id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier); reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil); id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path")); return reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String")); #elif defined(__ANDROID__) static_cast<void>(user); EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); return engineAndroid.getFilesDirectory(); #elif defined(__linux__) std::string path; const char* homeDirectory = getenv("XDG_DATA_HOME"); if (homeDirectory) path = homeDirectory; else { struct passwd pwent; struct passwd* pwentp; std::vector<char> buffer(1024); int e; while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE) buffer.resize(buffer.size() * 2); if (e != 0) throw std::runtime_error("Failed to get home directory"); else path = pwent.pw_dir; path += Path::directorySeparator + ".local"; if (!directoryExists(path)) if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) throw std::system_error(errno, std::system_category(), "Failed to create directory " + path); path += Path::directorySeparator + "share"; if (!directoryExists(path)) if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) throw std::system_error(errno, std::system_category(), "Failed to create directory " + path); } path += Path::directorySeparator + OUZEL_DEVELOPER_NAME; if (!directoryExists(path)) if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) throw std::system_error(errno, std::system_category(), "Failed to create directory " + path); path += Path::directorySeparator + OUZEL_APPLICATION_NAME; if (!directoryExists(path)) if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) throw std::system_error(errno, std::system_category(), "Failed to create directory " + path); return path; #else return ""; #endif } std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources) { if (searchResources) for (auto& archive : archives) if (archive.second.fileExists(filename)) return archive.second.readFile(filename); #if defined(__ANDROID__) if (!Path(filename).isAbsolute()) { EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.c_str(), AASSET_MODE_STREAMING); if (!asset) throw std::runtime_error("Failed to open file " + filename); std::vector<std::uint8_t> data; std::uint8_t buffer[1024]; for (;;) { const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer)); if (bytesRead < 0) throw std::runtime_error("Failed to read from file"); else if (bytesRead == 0) break; data.insert(data.end(), buffer, buffer + bytesRead); } AAsset_close(asset); return data; } #endif const auto path = getPath(filename, searchResources); // file does not exist if (path.isEmpty()) throw std::runtime_error("Failed to find file " + std::string(filename)); std::ifstream f(path, std::ios::binary); return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()}; } bool FileSystem::resourceFileExists(const Path& filename) const { if (filename.isAbsolute()) return fileExists(filename); else { Path result = appPath / filename; if (fileExists(result)) return true; else for (const auto& path : resourcePaths) { if (path.isAbsolute()) // if resource path is absolute result = path / filename; else result = appPath / path / filename; if (fileExists(result)) return true; } return false; } } bool FileSystem::directoryExists(const Path& dirname) const { #if defined(__ANDROID__) EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.c_str()); const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr; AAssetDir_close(assetDir); if (exists) return true; #endif return dirname.isDirectory(); } bool FileSystem::fileExists(const Path& filename) const { #if defined(__ANDROID__) EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.c_str(), AASSET_MODE_STREAMING); if (asset) { AAsset_close(asset); return true; } #endif return filename.isRegular(); } } // namespace storage } // namespace ouzel <commit_msg>Fix macOS and Linux builds<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../core/Setup.h" #include <algorithm> #include <fstream> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # include <ShlObj.h> # include <Shlwapi.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__APPLE__) # include <TargetConditionals.h> # include <objc/message.h> # include <objc/NSObjCRuntime.h> # include <CoreFoundation/CoreFoundation.h> #elif defined(__ANDROID__) # include "../core/android/EngineAndroid.hpp" #elif defined(__linux__) # include <pwd.h> #endif #include "FileSystem.hpp" #include "Archive.hpp" #include "../core/Engine.hpp" #include "../utils/Log.hpp" #if defined(__APPLE__) # include "CfPointer.hpp" #endif namespace ouzel { namespace storage { FileSystem::FileSystem(Engine& initEngine): engine(initEngine) { #if defined(_WIN32) std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const int bufferSize = WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, nullptr, 0, nullptr, nullptr); if (bufferSize == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8"); std::vector<char> appFilename(bufferSize); if (WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, appFilename.data(), bufferSize, nullptr, nullptr) == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8"); appPath = Path(appFilename.data()).getDirectory(); engine.log(Log::Level::Info) << "Application directory: " << std::string(appPath); #elif defined(__APPLE__) CFBundleRef bundle = CFBundleGetMainBundle(); if (!bundle) throw std::runtime_error("Failed to get main bundle"); CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle); if (!relativePath) throw std::runtime_error("Failed to get resource directory"); CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get()); CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle); const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get()); std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize)); const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize); if (!result) throw std::runtime_error("Failed to get resource directory"); appPath = resourceDirectory.data(); engine.log(Log::Level::Info) << "Application directory: " << std::string(appPath); #elif defined(__ANDROID__) // not available for Android #elif defined(__linux__) char executableDirectory[PATH_MAX]; ssize_t length; if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1) throw std::system_error(errno, std::system_category(), "Failed to get current directory"); executableDirectory[length] = '\0'; appPath = Path(executableDirectory).getDirectory(); engine.log(Log::Level::Info) << "Application directory: " << std::string(appPath); #endif } Path FileSystem::getStorageDirectory(const bool user) const { #if defined(_WIN32) WCHAR appDataPath[MAX_PATH]; HRESULT hr; if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath))) throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory"); const int appDataBufferSize = WideCharToMultiByte(CP_UTF8, 0, appDataPath, -1, nullptr, 0, nullptr, nullptr); if (appDataBufferSize == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8"); std::vector<char> appDataBuffer(appDataBufferSize); if (WideCharToMultiByte(CP_UTF8, 0, appDataPath, -1, appDataBuffer.data(), appDataBufferSize, nullptr, nullptr) == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8"); std::string path = appDataBuffer.data(); path += Path::directorySeparator + OUZEL_DEVELOPER_NAME; if (!directoryExists(path)) { const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); if (bufferSize == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char"); std::vector<WCHAR> buffer(bufferSize); if (MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, buffer.data(), bufferSize) == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char"); // relative paths longer than MAX_PATH are not supported if (buffer.size() > MAX_PATH) buffer.insert(buffer.begin(), {L'\\', L'\\', L'?', L'\\'}); const DWORD attributes = GetFileAttributesW(buffer.data()); if (attributes == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryW(buffer.data(), nullptr)) throw std::system_error(GetLastError(), std::system_category(), "Failed to create directory " + path); } else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0) throw std::runtime_error(path + " is not a directory"); } path += Path::directorySeparator + OUZEL_APPLICATION_NAME; if (!directoryExists(path)) { const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); if (bufferSize == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char"); std::vector<WCHAR> buffer(bufferSize); if (MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, buffer.data(), bufferSize) == 0) throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char"); // relative paths longer than MAX_PATH are not supported if (buffer.size() > MAX_PATH) buffer.insert(buffer.begin(), {L'\\', L'\\', L'?', L'\\'}); const DWORD attributes = GetFileAttributesW(buffer.data()); if (attributes == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryW(buffer.data(), nullptr)) throw std::system_error(GetLastError(), std::system_category(), "Failed to create directory " + path); } else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0) throw std::runtime_error(path + " is not a directory"); } return path; #elif TARGET_OS_IOS || TARGET_OS_TV id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSDocumentDirectory = 9; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!documentDirectory) throw std::runtime_error("Failed to get document directory"); id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path")); return reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String")); #elif TARGET_OS_MAC id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSApplicationSupportDirectory = 14; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!applicationSupportDirectory) throw std::runtime_error("Failed to get application support directory"); CFBundleRef bundle = CFBundleGetMainBundle(); CFStringRef identifier = CFBundleGetIdentifier(bundle); if (!identifier) identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME); id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier); reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil); id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path")); return reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String")); #elif defined(__ANDROID__) static_cast<void>(user); EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); return engineAndroid.getFilesDirectory(); #elif defined(__linux__) std::string path; const char* homeDirectory = getenv("XDG_DATA_HOME"); if (homeDirectory) path = homeDirectory; else { struct passwd pwent; struct passwd* pwentp; std::vector<char> buffer(1024); int e; while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE) buffer.resize(buffer.size() * 2); if (e != 0) throw std::runtime_error("Failed to get home directory"); else path = pwent.pw_dir; path += Path::directorySeparator + ".local"; if (!directoryExists(path)) if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) throw std::system_error(errno, std::system_category(), "Failed to create directory " + path); path += Path::directorySeparator + "share"; if (!directoryExists(path)) if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) throw std::system_error(errno, std::system_category(), "Failed to create directory " + path); } path += Path::directorySeparator + OUZEL_DEVELOPER_NAME; if (!directoryExists(path)) if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) throw std::system_error(errno, std::system_category(), "Failed to create directory " + path); path += Path::directorySeparator + OUZEL_APPLICATION_NAME; if (!directoryExists(path)) if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) throw std::system_error(errno, std::system_category(), "Failed to create directory " + path); return path; #else return ""; #endif } std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources) { if (searchResources) for (auto& archive : archives) if (archive.second.fileExists(filename)) return archive.second.readFile(filename); #if defined(__ANDROID__) if (!Path(filename).isAbsolute()) { EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.c_str(), AASSET_MODE_STREAMING); if (!asset) throw std::runtime_error("Failed to open file " + filename); std::vector<std::uint8_t> data; std::uint8_t buffer[1024]; for (;;) { const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer)); if (bytesRead < 0) throw std::runtime_error("Failed to read from file"); else if (bytesRead == 0) break; data.insert(data.end(), buffer, buffer + bytesRead); } AAsset_close(asset); return data; } #endif const auto path = getPath(filename, searchResources); // file does not exist if (path.isEmpty()) throw std::runtime_error("Failed to find file " + std::string(filename)); std::ifstream f(path, std::ios::binary); return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()}; } bool FileSystem::resourceFileExists(const Path& filename) const { if (filename.isAbsolute()) return fileExists(filename); else { Path result = appPath / filename; if (fileExists(result)) return true; else for (const auto& path : resourcePaths) { if (path.isAbsolute()) // if resource path is absolute result = path / filename; else result = appPath / path / filename; if (fileExists(result)) return true; } return false; } } bool FileSystem::directoryExists(const Path& dirname) const { #if defined(__ANDROID__) EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.c_str()); const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr; AAssetDir_close(assetDir); if (exists) return true; #endif return dirname.isDirectory(); } bool FileSystem::fileExists(const Path& filename) const { #if defined(__ANDROID__) EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.c_str(), AASSET_MODE_STREAMING); if (asset) { AAsset_close(asset); return true; } #endif return filename.isRegular(); } } // namespace storage } // namespace ouzel <|endoftext|>
<commit_before>// -*- C++ -*- // ex1_histogram.cc // an exercise for the sandia 2014 clinic team. // here we do a histogram calculation over unsigned ints #include <cmath> #include <cstdio> #include <cstdlib> #include <vector> #include <array> #include <string> #include <chrono> #include <algorithm> // header file for openmp #include <omp.h> // header files for tbb #include <tbb/blocked_range.h> #include <tbb/parallel_reduce.h> #include <tbb/parallel_for.h> #include <tbb/task_scheduler_init.h> #include <tbb/atomic.h> // header files for cuda implementation #include "ex1_histogram_cuda.cuh" // header files for kokkos #include <Kokkos_Core.hpp> using std::string; using std::vector; using std::array; using std::chrono::high_resolution_clock; using std::chrono::duration; using std::chrono::duration_cast; using tbb::atomic; class TbbOutputter { public: vector<unsigned int> * input_; atomic<unsigned long> * result_; unsigned long numBuckets_; unsigned long size_; TbbOutputter(vector<unsigned int> * input, atomic<unsigned long> * results, unsigned long numBuckets, unsigned long size) : input_(input), result_(results), numBuckets_(numBuckets), size_(size) { } TbbOutputter(const TbbOutputter & other, tbb::split) : input_(other.input_), result_(other.result_), numBuckets_(other.numBuckets_), size_(other.size_){ //printf("split copy constructor called\n"); } void operator()(const tbb::blocked_range<size_t> & range) { //printf("TbbOutputter asked to process range from %7zu to %7zu\n", //range.begin(), range.end()); unsigned long bucketSize = size_/numBuckets_; for(unsigned long i=range.begin(); i!= range.end(); ++i ) { (result_ + (((*input_)[i])/bucketSize))->fetch_and_increment(); } } void join(const TbbOutputter & other) { } private: TbbOutputter(); }; struct KokkosFunctor { const unsigned int _bucketSize; KokkosFunctor(const double bucketSize) : _bucketSize(bucketSize) { } KOKKOS_INLINE_FUNCTION void operator()(const unsigned int elementIndex) const { } private: KokkosFunctor(); }; int main(int argc, char* argv[]) { // a couple of inputs. change the numberOfIntervals to control the amount // of work done const unsigned int numberOfElements = 1e2; // The number of buckets in our histogram const unsigned int numberOfBuckets = 1e2; // these are c++ timers...for timing high_resolution_clock::time_point tic; high_resolution_clock::time_point toc; printf("Creating the input vector \n"); vector<unsigned int> input(numberOfElements); for(unsigned int i = 0; i < numberOfElements; ++i) { input[i] = i; } //std::random_shuffle(input.begin(), input.end()); // =============================================================== // ********************** < do slow serial> ********************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vector<unsigned int> slowSerialHistogram(numberOfBuckets); tic = high_resolution_clock::now(); const unsigned int bucketSize = input.size()/numberOfBuckets; for (unsigned int index = 0; index < numberOfElements; ++index) { const unsigned int value = input[index]; const unsigned int bucketNumber = value / bucketSize; slowSerialHistogram[bucketNumber] += 1; } toc = high_resolution_clock::now(); const double slowSerialElapsedTime = duration_cast<duration<double> >(toc - tic).count(); for(unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex){ if(slowSerialHistogram[bucketIndex]!= bucketSize) fprintf(stderr, "wrong"); } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do slow serial> ********************** // =============================================================== // =============================================================== // ********************** < do fast serial> ********************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vector<unsigned int> fastSerialHistogram(numberOfBuckets, 0); tic = high_resolution_clock::now(); // TODO: can you make the serial one go faster? i can get about a // 15-20% speedup, but that's about it. not very interesting toc = high_resolution_clock::now(); const double fastSerialElapsedTime = duration_cast<duration<double> >(toc - tic).count(); for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (fastSerialHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, fastSerialHistogram[bucketIndex], bucketSize); exit(1); } } // output speedup printf("fast: time %8.2e speedup %8.2e\n", fastSerialElapsedTime, slowSerialElapsedTime / fastSerialElapsedTime); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do fast serial> ********************** // =============================================================== // we will repeat the computation for each of the numbers of threads vector<unsigned int> numberOfThreadsArray; numberOfThreadsArray.push_back(1); numberOfThreadsArray.push_back(2); numberOfThreadsArray.push_back(4); numberOfThreadsArray.push_back(8); numberOfThreadsArray.push_back(16); numberOfThreadsArray.push_back(24); const size_t grainSize = std::max(unsigned(1e4), numberOfElements / 48); // =============================================================== // ********************** < do tbb> ****************************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv printf("performing calculations with tbb\n"); // for each number of threads for (const unsigned int numberOfThreads : numberOfThreadsArray) { // initialize tbb's threading system for this number of threads tbb::task_scheduler_init init(numberOfThreads); atomic<unsigned long> * results = new atomic<unsigned long>[numberOfBuckets]; //bzero(results, sizeof(atomic<unsigned long>) * numberOfElements); TbbOutputter tbbOutputter(&input, results, numberOfBuckets, numberOfElements); // start timing tic = high_resolution_clock::now(); // dispatch threads parallel_reduce(tbb::blocked_range<size_t>(0, numberOfElements, grainSize), tbbOutputter); // stop timing toc = high_resolution_clock::now(); const double threadedElapsedTime = duration_cast<duration<double> >(toc - tic).count(); // check the answer atomic<unsigned long> * tbbHistogram = tbbOutputter.result_; for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (tbbHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, unsigned(tbbHistogram[bucketIndex]), bucketSize); exit(1); } } // output speedup printf("%3u : time %8.2e speedup %8.2e (%%%5.1f of ideal)\n", numberOfThreads, threadedElapsedTime, fastSerialElapsedTime / threadedElapsedTime, 100. * fastSerialElapsedTime / threadedElapsedTime / numberOfThreads); } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do tbb> ****************************** // =============================================================== // =============================================================== // ********************** < do openmp> *************************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv printf("performing calculations with openmp\n"); // for each number of threads for (const unsigned int numberOfThreads : numberOfThreadsArray) { // set the number of threads for openmp omp_set_num_threads(numberOfThreads); vector<unsigned int> ompHistogram(numberOfBuckets, 0); // start timing tic = high_resolution_clock::now(); // TODO: do openmp // stop timing toc = high_resolution_clock::now(); const double threadedElapsedTime = duration_cast<duration<double> >(toc - tic).count(); // check the answer for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (ompHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, ompHistogram[bucketIndex], bucketSize); exit(1); } } // output speedup printf("%3u : time %8.2e speedup %8.2e (%%%5.1f of ideal)\n", numberOfThreads, threadedElapsedTime, fastSerialElapsedTime / threadedElapsedTime, 100. * fastSerialElapsedTime / threadedElapsedTime / numberOfThreads); } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do openmp> *************************** // =============================================================== // =============================================================== // ********************** < do cuda> ***************************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv printf("performing calculations with cuda\n"); // we will repeat the computation for each of the numbers of threads vector<unsigned int> threadsPerBlockArray; threadsPerBlockArray.push_back(32); threadsPerBlockArray.push_back(64); threadsPerBlockArray.push_back(128); threadsPerBlockArray.push_back(256); threadsPerBlockArray.push_back(512); printf("performing calculations with cuda\n"); // for each number of threads per block for (const unsigned int numberOfThreadsPerBlock : threadsPerBlockArray) { vector<unsigned int> cudaHistogram(numberOfBuckets, 0); // start timing tic = high_resolution_clock::now(); // TODO: do cuda stuff // do scalar integration with cuda for this number of threads per block cudaDoHistogramPopulation(numberOfThreadsPerBlock, &cudaHistogram[0]); // stop timing toc = high_resolution_clock::now(); const double cudaElapsedTime = duration_cast<duration<double> >(toc - tic).count(); // check the answer for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (cudaHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, cudaHistogram[bucketIndex], bucketSize); exit(1); } } // output speedup printf("%3u : time %8.2e speedup %8.2e\n", numberOfThreadsPerBlock, cudaElapsedTime, fastSerialElapsedTime / cudaElapsedTime); } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do cuda> ***************************** // =============================================================== // =============================================================== // ********************** < do kokkos> ***************************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv printf("performing calculations with kokkos running on %s\n", typeid(Kokkos::DefaultExecutionSpace).name()); Kokkos::initialize(); // start timing tic = high_resolution_clock::now(); // TODO: do kokkos stuff // stop timing toc = high_resolution_clock::now(); const double kokkosElapsedTime = duration_cast<duration<double> >(toc - tic).count(); // check the answer vector<unsigned int> kokkosHistogram(numberOfBuckets, 0); for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (kokkosHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, kokkosHistogram[bucketIndex], bucketSize); exit(1); } } // output speedup printf("kokkos : time %8.2e speedup %8.2e\n", kokkosElapsedTime, fastSerialElapsedTime / kokkosElapsedTime); Kokkos::finalize(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do kokkos> *************************** // =============================================================== return 0; } <commit_msg>fast serial<commit_after>// -*- C++ -*- // ex1_histogram.cc // an exercise for the sandia 2014 clinic team. // here we do a histogram calculation over unsigned ints #include <cmath> #include <cstdio> #include <cstdlib> #include <vector> #include <array> #include <string> #include <chrono> #include <algorithm> // header file for openmp #include <omp.h> // header files for tbb #include <tbb/blocked_range.h> #include <tbb/parallel_reduce.h> #include <tbb/parallel_for.h> #include <tbb/task_scheduler_init.h> #include <tbb/atomic.h> // header files for cuda implementation #include "ex1_histogram_cuda.cuh" // header files for kokkos #include <Kokkos_Core.hpp> using std::string; using std::vector; using std::array; using std::chrono::high_resolution_clock; using std::chrono::duration; using std::chrono::duration_cast; using tbb::atomic; class TbbOutputter { public: vector<unsigned int> * input_; atomic<unsigned long> * result_; unsigned long numBuckets_; unsigned long size_; TbbOutputter(vector<unsigned int> * input, atomic<unsigned long> * results, unsigned long numBuckets, unsigned long size) : input_(input), result_(results), numBuckets_(numBuckets), size_(size) { } TbbOutputter(const TbbOutputter & other, tbb::split) : input_(other.input_), result_(other.result_), numBuckets_(other.numBuckets_), size_(other.size_){ //printf("split copy constructor called\n"); } void operator()(const tbb::blocked_range<size_t> & range) { //printf("TbbOutputter asked to process range from %7zu to %7zu\n", //range.begin(), range.end()); unsigned long bucketSize = size_/numBuckets_; for(unsigned long i=range.begin(); i!= range.end(); ++i ) { (result_ + (((*input_)[i])/bucketSize))->fetch_and_increment(); } } void join(const TbbOutputter & other) { } private: TbbOutputter(); }; struct KokkosFunctor { const unsigned int _bucketSize; KokkosFunctor(const double bucketSize) : _bucketSize(bucketSize) { } KOKKOS_INLINE_FUNCTION void operator()(const unsigned int elementIndex) const { } private: KokkosFunctor(); }; int main(int argc, char* argv[]) { // a couple of inputs. change the numberOfIntervals to control the amount // of work done const unsigned int numberOfElements = 1e2; // The number of buckets in our histogram const unsigned int numberOfBuckets = 1e2; // these are c++ timers...for timing high_resolution_clock::time_point tic; high_resolution_clock::time_point toc; printf("Creating the input vector \n"); vector<unsigned int> input(numberOfElements); for(unsigned int i = 0; i < numberOfElements; ++i) { input[i] = i; } //std::random_shuffle(input.begin(), input.end()); // =============================================================== // ********************** < do slow serial> ********************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vector<unsigned int> slowSerialHistogram(numberOfBuckets); tic = high_resolution_clock::now(); const unsigned int bucketSize = input.size()/numberOfBuckets; for (unsigned int index = 0; index < numberOfElements; ++index) { const unsigned int value = input[index]; const unsigned int bucketNumber = value / bucketSize; slowSerialHistogram[bucketNumber] += 1; } toc = high_resolution_clock::now(); const double slowSerialElapsedTime = duration_cast<duration<double> >(toc - tic).count(); for(unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex){ if(slowSerialHistogram[bucketIndex]!= bucketSize) fprintf(stderr, "wrong"); } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do slow serial> ********************** // =============================================================== // =============================================================== // ********************** < do fast serial> ********************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vector<unsigned int> fastSerialHistogram(numberOfBuckets, 0); tic = high_resolution_clock::now(); // TODO: can you make the serial one go faster? i can get about a // 15-20% speedup, but that's about it. not very interesting // TODO: do this better for (unsigned int index = 0; index < numberOfElements; ++index) { const unsigned int value = input[index]; const unsigned int bucketNumber = value / bucketSize; slowSerialHistogram[bucketNumber] += 1; } toc = high_resolution_clock::now(); const double fastSerialElapsedTime = duration_cast<duration<double> >(toc - tic).count(); for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (fastSerialHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, fastSerialHistogram[bucketIndex], bucketSize); exit(1); } } // output speedup printf("fast: time %8.2e speedup %8.2e\n", fastSerialElapsedTime, slowSerialElapsedTime / fastSerialElapsedTime); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do fast serial> ********************** // =============================================================== // we will repeat the computation for each of the numbers of threads vector<unsigned int> numberOfThreadsArray; numberOfThreadsArray.push_back(1); numberOfThreadsArray.push_back(2); numberOfThreadsArray.push_back(4); numberOfThreadsArray.push_back(8); numberOfThreadsArray.push_back(16); numberOfThreadsArray.push_back(24); const size_t grainSize = std::max(unsigned(1e4), numberOfElements / 48); // =============================================================== // ********************** < do tbb> ****************************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv printf("performing calculations with tbb\n"); // for each number of threads for (const unsigned int numberOfThreads : numberOfThreadsArray) { // initialize tbb's threading system for this number of threads tbb::task_scheduler_init init(numberOfThreads); atomic<unsigned long> * results = new atomic<unsigned long>[numberOfBuckets]; //bzero(results, sizeof(atomic<unsigned long>) * numberOfElements); TbbOutputter tbbOutputter(&input, results, numberOfBuckets, numberOfElements); // start timing tic = high_resolution_clock::now(); // dispatch threads parallel_reduce(tbb::blocked_range<size_t>(0, numberOfElements, grainSize), tbbOutputter); // stop timing toc = high_resolution_clock::now(); const double threadedElapsedTime = duration_cast<duration<double> >(toc - tic).count(); // check the answer atomic<unsigned long> * tbbHistogram = tbbOutputter.result_; for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (tbbHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, unsigned(tbbHistogram[bucketIndex]), bucketSize); exit(1); } } // output speedup printf("%3u : time %8.2e speedup %8.2e (%%%5.1f of ideal)\n", numberOfThreads, threadedElapsedTime, fastSerialElapsedTime / threadedElapsedTime, 100. * fastSerialElapsedTime / threadedElapsedTime / numberOfThreads); } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do tbb> ****************************** // =============================================================== // =============================================================== // ********************** < do openmp> *************************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv printf("performing calculations with openmp\n"); // for each number of threads for (const unsigned int numberOfThreads : numberOfThreadsArray) { // set the number of threads for openmp omp_set_num_threads(numberOfThreads); vector<unsigned int> ompHistogram(numberOfBuckets, 0); // start timing tic = high_resolution_clock::now(); // TODO: do openmp // stop timing toc = high_resolution_clock::now(); const double threadedElapsedTime = duration_cast<duration<double> >(toc - tic).count(); // check the answer for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (ompHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, ompHistogram[bucketIndex], bucketSize); exit(1); } } // output speedup printf("%3u : time %8.2e speedup %8.2e (%%%5.1f of ideal)\n", numberOfThreads, threadedElapsedTime, fastSerialElapsedTime / threadedElapsedTime, 100. * fastSerialElapsedTime / threadedElapsedTime / numberOfThreads); } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do openmp> *************************** // =============================================================== // =============================================================== // ********************** < do cuda> ***************************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv printf("performing calculations with cuda\n"); // we will repeat the computation for each of the numbers of threads vector<unsigned int> threadsPerBlockArray; threadsPerBlockArray.push_back(32); threadsPerBlockArray.push_back(64); threadsPerBlockArray.push_back(128); threadsPerBlockArray.push_back(256); threadsPerBlockArray.push_back(512); printf("performing calculations with cuda\n"); // for each number of threads per block for (const unsigned int numberOfThreadsPerBlock : threadsPerBlockArray) { vector<unsigned int> cudaHistogram(numberOfBuckets, 0); // start timing tic = high_resolution_clock::now(); // TODO: do cuda stuff // do scalar integration with cuda for this number of threads per block cudaDoHistogramPopulation(numberOfThreadsPerBlock, &cudaHistogram[0]); // stop timing toc = high_resolution_clock::now(); const double cudaElapsedTime = duration_cast<duration<double> >(toc - tic).count(); // check the answer for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (cudaHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, cudaHistogram[bucketIndex], bucketSize); exit(1); } } // output speedup printf("%3u : time %8.2e speedup %8.2e\n", numberOfThreadsPerBlock, cudaElapsedTime, fastSerialElapsedTime / cudaElapsedTime); } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do cuda> ***************************** // =============================================================== // =============================================================== // ********************** < do kokkos> ***************************** // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv printf("performing calculations with kokkos running on %s\n", typeid(Kokkos::DefaultExecutionSpace).name()); Kokkos::initialize(); // start timing tic = high_resolution_clock::now(); // TODO: do kokkos stuff // stop timing toc = high_resolution_clock::now(); const double kokkosElapsedTime = duration_cast<duration<double> >(toc - tic).count(); // check the answer vector<unsigned int> kokkosHistogram(numberOfBuckets, 0); for (unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex) { if (kokkosHistogram[bucketIndex] != bucketSize) { fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n", bucketIndex, kokkosHistogram[bucketIndex], bucketSize); exit(1); } } // output speedup printf("kokkos : time %8.2e speedup %8.2e\n", kokkosElapsedTime, fastSerialElapsedTime / kokkosElapsedTime); Kokkos::finalize(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ********************** </do kokkos> *************************** // =============================================================== return 0; } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. #include <librealsense2/rs.hpp> // Include RealSense Cross Platform API #include "example.hpp" // Include short list of convenience functions for rendering // Capture Example demonstrates how to // capture depth and color video streams and render them to the screen int main(int argc, char * argv[]) try { // Create a simple OpenGL window for rendering: window app(1280, 720, "RealSense Capture Example"); // Declare two textures on the GPU, one for color and one for depth texture depth_image, color_image; // Declare depth colorizer for pretty visualization of depth data rs2::colorizer color_map; // Declare RealSense pipeline, encapsulating the actual device and sensors rs2::pipeline pipe; // Start streaming with default recommended configuration pipe.start(); while(app) // Application still alive? { rs2::frameset data = pipe.wait_for_frames(); // Wait for next set of frames from the camera rs2::frame depth = color_map(data.get_depth_frame()); // Find and colorize the depth data rs2::frame color = data.get_color_frame(); // Find the color data // Render depth on to the first half of the screen and color on to the second depth_image.render(depth, { 0, 0, app.width() / 2, app.height() }); color_image.render(color, { app.width() / 2, 0, app.width() / 2, app.height() }); } return EXIT_SUCCESS; } catch (const rs2::error & e) { std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl; return EXIT_FAILURE; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } <commit_msg>Example for bypass device (DO NOT MERGE)<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. #include <librealsense2/rs.hpp> // Include RealSense Cross Platform API #include <librealsense2/hpp/rs_internal.hpp> // Include RealSense Cross Platform API #include "example.hpp" // Include short list of convenience functions for rendering // Capture Example demonstrates how to // capture depth and color video streams and render them to the screen int main(int argc, char * argv[]) try { using namespace rs2; //log_to_console(RS2_LOG_SEVERITY_DEBUG); const int W = 640; const int H = 480; const int BPP = 2; bypass_device dev; dev.add_sensor("DS5u"); dev.add_video_stream(0, RS2_STREAM_DEPTH, 0, 0, W, H, BPP, RS2_FORMAT_Z16); dev.add_video_stream(0, RS2_STREAM_INFRARED, 1, 1, W, H, BPP, RS2_FORMAT_Y8); recorder rec("1.bag", dev); frame_queue q; auto s = rec.query_sensors().front(); auto profiles = s.get_stream_profiles(); auto depth = profiles[0]; auto ir = profiles[1]; s.open(profiles); syncer sync; s.start(sync); std::vector<uint8_t> pixels(W * H * BPP, 0); std::thread t([&]() { for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 7, depth); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 5, ir); std::this_thread::sleep_for(std::chrono::milliseconds(30)); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 8, depth); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 6, ir); std::this_thread::sleep_for(std::chrono::milliseconds(30)); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 9, depth); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 7, ir); std::this_thread::sleep_for(std::chrono::milliseconds(30)); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 10, depth); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 8, ir); std::this_thread::sleep_for(std::chrono::milliseconds(30)); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 11, depth); for (auto& p : pixels) p = rand() % 256; dev.on_video_frame(0, pixels.data(), [](void*) {}, W*BPP, BPP, 0, RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK, 9, ir); std::this_thread::sleep_for(std::chrono::milliseconds(30)); }); try { while (true) { auto fs = sync.wait_for_frames(5000); std::cout << "Matched: " << std::endl; for (auto&& f : fs) { std::cout << "\t" << f.get_profile().stream_type() << " #" << f.get_frame_number() << std::endl; } } } catch (...) { } t.join(); return EXIT_SUCCESS; } catch (const rs2::error & e) { std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl; return EXIT_FAILURE; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } <|endoftext|>
<commit_before><commit_msg>drt: bump ACCESS_PATTERN_END_ITERATION_NUM to 10 for difficult AOI gate<commit_after><|endoftext|>
<commit_before><commit_msg>basic server mock<commit_after>#include <rest/server.h> int main() { std::unique_ptr<REST::Server> server (new REST::Server("0.0.0.0", 8080)); server->run(); } <|endoftext|>
<commit_before>/*************************************************************************/ /* array.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "array.h" #include "core/hashfuncs.h" #include "core/object.h" #include "core/variant.h" #include "core/vector.h" class ArrayPrivate { public: SafeRefCount refcount; Vector<Variant> array; }; void Array::_ref(const Array &p_from) const { ArrayPrivate *_fp = p_from._p; ERR_FAIL_COND(!_fp); // should NOT happen. if (_fp == _p) return; // whatever it is, nothing to do here move along bool success = _fp->refcount.ref(); ERR_FAIL_COND(!success); // should really not happen either _unref(); _p = p_from._p; } void Array::_unref() const { if (!_p) return; if (_p->refcount.unref()) { memdelete(_p); } _p = NULL; } Variant &Array::operator[](int p_idx) { return _p->array.write[p_idx]; } const Variant &Array::operator[](int p_idx) const { return _p->array[p_idx]; } int Array::size() const { return _p->array.size(); } bool Array::empty() const { return _p->array.empty(); } void Array::clear() { _p->array.clear(); } bool Array::operator==(const Array &p_array) const { return _p == p_array._p; } uint32_t Array::hash() const { uint32_t h = hash_djb2_one_32(0); for (int i = 0; i < _p->array.size(); i++) { h = hash_djb2_one_32(_p->array[i].hash(), h); } return h; } void Array::operator=(const Array &p_array) { _ref(p_array); } void Array::push_back(const Variant &p_value) { _p->array.push_back(p_value); } Error Array::resize(int p_new_size) { return _p->array.resize(p_new_size); } void Array::insert(int p_pos, const Variant &p_value) { _p->array.insert(p_pos, p_value); } void Array::erase(const Variant &p_value) { _p->array.erase(p_value); } Variant Array::front() const { ERR_FAIL_COND_V(_p->array.size() == 0, Variant()); return operator[](0); } Variant Array::back() const { ERR_FAIL_COND_V(_p->array.size() == 0, Variant()); return operator[](_p->array.size() - 1); } int Array::find(const Variant &p_value, int p_from) const { return _p->array.find(p_value, p_from); } int Array::rfind(const Variant &p_value, int p_from) const { if (_p->array.size() == 0) return -1; if (p_from < 0) { // Relative offset from the end p_from = _p->array.size() + p_from; } if (p_from < 0 || p_from >= _p->array.size()) { // Limit to array boundaries p_from = _p->array.size() - 1; } for (int i = p_from; i >= 0; i--) { if (_p->array[i] == p_value) { return i; }; }; return -1; } int Array::find_last(const Variant &p_value) const { return rfind(p_value); } int Array::count(const Variant &p_value) const { if (_p->array.size() == 0) return 0; int amount = 0; for (int i = 0; i < _p->array.size(); i++) { if (_p->array[i] == p_value) { amount++; }; }; return amount; } bool Array::has(const Variant &p_value) const { return _p->array.find(p_value, 0) != -1; } void Array::remove(int p_pos) { _p->array.remove(p_pos); } void Array::set(int p_idx, const Variant &p_value) { operator[](p_idx) = p_value; } const Variant &Array::get(int p_idx) const { return operator[](p_idx); } Array Array::duplicate(bool p_deep) const { Array new_arr; int element_count = size(); new_arr.resize(element_count); for (int i = 0; i < element_count; i++) { new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i); } return new_arr; } struct _ArrayVariantSort { _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const { bool valid = false; Variant res; Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid); if (!valid) res = false; return res; } }; Array &Array::sort() { _p->array.sort_custom<_ArrayVariantSort>(); return *this; } struct _ArrayVariantSortCustom { Object *obj; StringName func; _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const { const Variant *args[2] = { &p_l, &p_r }; Variant::CallError err; bool res = obj->call(func, args, 2, err); if (err.error != Variant::CallError::CALL_OK) res = false; return res; } }; Array &Array::sort_custom(Object *p_obj, const StringName &p_function) { ERR_FAIL_NULL_V(p_obj, *this); SortArray<Variant, _ArrayVariantSortCustom, true> avs; avs.compare.obj = p_obj; avs.compare.func = p_function; avs.sort(_p->array.ptrw(), _p->array.size()); return *this; } void Array::shuffle() { const int n = _p->array.size(); if (n < 2) return; Variant *data = _p->array.ptrw(); for (int i = n - 1; i >= 1; i--) { const int j = Math::rand() % (i + 1); const Variant tmp = data[j]; data[j] = data[i]; data[i] = tmp; } } template <typename Less> _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) { int lo = 0; int hi = p_array.size(); if (p_before) { while (lo < hi) { const int mid = (lo + hi) / 2; if (p_less(p_array.get(mid), p_value)) { lo = mid + 1; } else { hi = mid; } } } else { while (lo < hi) { const int mid = (lo + hi) / 2; if (p_less(p_value, p_array.get(mid))) { hi = mid; } else { lo = mid + 1; } } } return lo; } int Array::bsearch(const Variant &p_value, bool p_before) { return bisect(_p->array, p_value, p_before, _ArrayVariantSort()); } int Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) { ERR_FAIL_NULL_V(p_obj, 0); _ArrayVariantSortCustom less; less.obj = p_obj; less.func = p_function; return bisect(_p->array, p_value, p_before, less); } Array &Array::invert() { _p->array.invert(); return *this; } void Array::push_front(const Variant &p_value) { _p->array.insert(0, p_value); } Variant Array::pop_back() { if (!_p->array.empty()) { int n = _p->array.size() - 1; Variant ret = _p->array.get(n); _p->array.resize(n); return ret; } return Variant(); } Variant Array::pop_front() { if (!_p->array.empty()) { Variant ret = _p->array.get(0); _p->array.remove(0); return ret; } return Variant(); } Variant Array::min() const { Variant minval; for (int i = 0; i < size(); i++) { if (i == 0) { minval = get(i); } else { bool valid; Variant ret; Variant test = get(i); Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid); if (!valid) { return Variant(); //not a valid comparison } if (bool(ret)) { //is less minval = test; } } } return minval; } Variant Array::max() const { Variant maxval; for (int i = 0; i < size(); i++) { if (i == 0) { maxval = get(i); } else { bool valid; Variant ret; Variant test = get(i); Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid); if (!valid) { return Variant(); //not a valid comparison } if (bool(ret)) { //is less maxval = test; } } } return maxval; } Array::Array(const Array &p_from) { _p = NULL; _ref(p_from); } Array::Array() { _p = memnew(ArrayPrivate); _p->refcount.init(); } Array::~Array() { _unref(); } <commit_msg>Added a check in sort_custom thats test wether the given method exists.<commit_after>/*************************************************************************/ /* array.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "array.h" #include "core/hashfuncs.h" #include "core/object.h" #include "core/variant.h" #include "core/vector.h" class ArrayPrivate { public: SafeRefCount refcount; Vector<Variant> array; }; void Array::_ref(const Array &p_from) const { ArrayPrivate *_fp = p_from._p; ERR_FAIL_COND(!_fp); // should NOT happen. if (_fp == _p) return; // whatever it is, nothing to do here move along bool success = _fp->refcount.ref(); ERR_FAIL_COND(!success); // should really not happen either _unref(); _p = p_from._p; } void Array::_unref() const { if (!_p) return; if (_p->refcount.unref()) { memdelete(_p); } _p = NULL; } Variant &Array::operator[](int p_idx) { return _p->array.write[p_idx]; } const Variant &Array::operator[](int p_idx) const { return _p->array[p_idx]; } int Array::size() const { return _p->array.size(); } bool Array::empty() const { return _p->array.empty(); } void Array::clear() { _p->array.clear(); } bool Array::operator==(const Array &p_array) const { return _p == p_array._p; } uint32_t Array::hash() const { uint32_t h = hash_djb2_one_32(0); for (int i = 0; i < _p->array.size(); i++) { h = hash_djb2_one_32(_p->array[i].hash(), h); } return h; } void Array::operator=(const Array &p_array) { _ref(p_array); } void Array::push_back(const Variant &p_value) { _p->array.push_back(p_value); } Error Array::resize(int p_new_size) { return _p->array.resize(p_new_size); } void Array::insert(int p_pos, const Variant &p_value) { _p->array.insert(p_pos, p_value); } void Array::erase(const Variant &p_value) { _p->array.erase(p_value); } Variant Array::front() const { ERR_FAIL_COND_V(_p->array.size() == 0, Variant()); return operator[](0); } Variant Array::back() const { ERR_FAIL_COND_V(_p->array.size() == 0, Variant()); return operator[](_p->array.size() - 1); } int Array::find(const Variant &p_value, int p_from) const { return _p->array.find(p_value, p_from); } int Array::rfind(const Variant &p_value, int p_from) const { if (_p->array.size() == 0) return -1; if (p_from < 0) { // Relative offset from the end p_from = _p->array.size() + p_from; } if (p_from < 0 || p_from >= _p->array.size()) { // Limit to array boundaries p_from = _p->array.size() - 1; } for (int i = p_from; i >= 0; i--) { if (_p->array[i] == p_value) { return i; }; }; return -1; } int Array::find_last(const Variant &p_value) const { return rfind(p_value); } int Array::count(const Variant &p_value) const { if (_p->array.size() == 0) return 0; int amount = 0; for (int i = 0; i < _p->array.size(); i++) { if (_p->array[i] == p_value) { amount++; }; }; return amount; } bool Array::has(const Variant &p_value) const { return _p->array.find(p_value, 0) != -1; } void Array::remove(int p_pos) { _p->array.remove(p_pos); } void Array::set(int p_idx, const Variant &p_value) { operator[](p_idx) = p_value; } const Variant &Array::get(int p_idx) const { return operator[](p_idx); } Array Array::duplicate(bool p_deep) const { Array new_arr; int element_count = size(); new_arr.resize(element_count); for (int i = 0; i < element_count; i++) { new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i); } return new_arr; } struct _ArrayVariantSort { _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const { bool valid = false; Variant res; Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid); if (!valid) res = false; return res; } }; Array &Array::sort() { _p->array.sort_custom<_ArrayVariantSort>(); return *this; } struct _ArrayVariantSortCustom { Object *obj; StringName func; _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const { const Variant *args[2] = { &p_l, &p_r }; Variant::CallError err; bool res = obj->call(func, args, 2, err); if (err.error != Variant::CallError::CALL_OK) res = false; return res; } }; Array &Array::sort_custom(Object *p_obj, const StringName &p_function) { ERR_FAIL_NULL_V(p_obj, *this); ERR_FAIL_COND_V(!p_obj->has_method(p_function), *this); SortArray<Variant, _ArrayVariantSortCustom, true> avs; avs.compare.obj = p_obj; avs.compare.func = p_function; avs.sort(_p->array.ptrw(), _p->array.size()); return *this; } void Array::shuffle() { const int n = _p->array.size(); if (n < 2) return; Variant *data = _p->array.ptrw(); for (int i = n - 1; i >= 1; i--) { const int j = Math::rand() % (i + 1); const Variant tmp = data[j]; data[j] = data[i]; data[i] = tmp; } } template <typename Less> _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) { int lo = 0; int hi = p_array.size(); if (p_before) { while (lo < hi) { const int mid = (lo + hi) / 2; if (p_less(p_array.get(mid), p_value)) { lo = mid + 1; } else { hi = mid; } } } else { while (lo < hi) { const int mid = (lo + hi) / 2; if (p_less(p_value, p_array.get(mid))) { hi = mid; } else { lo = mid + 1; } } } return lo; } int Array::bsearch(const Variant &p_value, bool p_before) { return bisect(_p->array, p_value, p_before, _ArrayVariantSort()); } int Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) { ERR_FAIL_NULL_V(p_obj, 0); _ArrayVariantSortCustom less; less.obj = p_obj; less.func = p_function; return bisect(_p->array, p_value, p_before, less); } Array &Array::invert() { _p->array.invert(); return *this; } void Array::push_front(const Variant &p_value) { _p->array.insert(0, p_value); } Variant Array::pop_back() { if (!_p->array.empty()) { int n = _p->array.size() - 1; Variant ret = _p->array.get(n); _p->array.resize(n); return ret; } return Variant(); } Variant Array::pop_front() { if (!_p->array.empty()) { Variant ret = _p->array.get(0); _p->array.remove(0); return ret; } return Variant(); } Variant Array::min() const { Variant minval; for (int i = 0; i < size(); i++) { if (i == 0) { minval = get(i); } else { bool valid; Variant ret; Variant test = get(i); Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid); if (!valid) { return Variant(); //not a valid comparison } if (bool(ret)) { //is less minval = test; } } } return minval; } Variant Array::max() const { Variant maxval; for (int i = 0; i < size(); i++) { if (i == 0) { maxval = get(i); } else { bool valid; Variant ret; Variant test = get(i); Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid); if (!valid) { return Variant(); //not a valid comparison } if (bool(ret)) { //is less maxval = test; } } } return maxval; } Array::Array(const Array &p_from) { _p = NULL; _ref(p_from); } Array::Array() { _p = memnew(ArrayPrivate); _p->refcount.init(); } Array::~Array() { _unref(); } <|endoftext|>
<commit_before>// Copyright (c) 2014 Arista Networks, Inc. All rights reserved. // Arista Networks, Inc. Confidential and Proprietary. #include <eos/agent.h> #include <eos/ip.h> #include <eos/ip_route.h> #include <eos/mpls.h> #include <eos/nexthop_group.h> #include <eos/sdk.h> #include <stdio.h> class my_agent : public eos::agent_handler { public: eos::agent_mgr * agentMgr_; eos::ip_route_mgr * ipMgr_; eos::nexthop_group_mgr * nhgMgr_; explicit my_agent(eos::sdk & sdk) : eos::agent_handler(sdk.get_agent_mgr()), agentMgr_(sdk.get_agent_mgr()), ipMgr_(sdk.get_ip_route_mgr()), nhgMgr_(sdk.get_nexthop_group_mgr()) { printf("Constructing my agent...\n"); } void create_nexthop_group(std::string name) { printf("Creating nexthop group\n"); eos::nexthop_group_t nhg = eos::nexthop_group_t(name, eos::NEXTHOP_GROUP_MPLS); // Send 2/3rds of traffic to nexthop 10.0.0.33 with the [30, 31] // label stack: eos::nexthop_group_entry_t mplsNh1(eos::ip_addr_t("10.0.0.33")); eos::nexthop_group_mpls_action_t mplsActionA( eos::MPLS_ACTION_PUSH, {eos::mpls_label_t(30), eos::mpls_label_t(31)}); mplsNh1.mpls_action_is(mplsActionA); nhg.nexthop_set(1, mplsNh1); nhg.nexthop_set(2, mplsNh1); // Send 1/3rd of traffic to nexthop 10.0.0.44 with the [40, 41] // label stack: eos::nexthop_group_entry_t mplsNh2(eos::ip_addr_t("10.0.0.44")); eos::nexthop_group_mpls_action_t mplsActionB( eos::MPLS_ACTION_PUSH, {eos::mpls_label_t(40), eos::mpls_label_t(41)}); mplsNh2.mpls_action_is(mplsActionB); nhg.nexthop_set(3, mplsNh2); // And commit it to Sysdb! nhgMgr_->nexthop_group_set(nhg); } void on_initialized() { printf("Initializing my agent...\n"); create_nexthop_group("MplsNhg1"); eos::ip_route_key_t routeKey( eos::ip_prefix_t(eos::ip_addr_t("172.1.1.4"), 32)); eos::ip_route_t route(routeKey); eos::ip_route_via_t via(routeKey); via.nexthop_group_is("MplsNhg1"); ipMgr_->ip_route_set(route); ipMgr_->ip_route_via_set(via); printf("Done!\n"); agentMgr_->exit(); // (we'll just exit after this demo) } }; int main(int argc, char ** argv) { eos::sdk sdk; my_agent agent(sdk); sdk.main_loop(argc, argv); } <commit_msg>@2099824 Persist the configuration so we can inspect it with 'show run'<commit_after>// Copyright (c) 2014 Arista Networks, Inc. All rights reserved. // Arista Networks, Inc. Confidential and Proprietary. #include <eos/agent.h> #include <eos/ip.h> #include <eos/ip_route.h> #include <eos/mpls.h> #include <eos/nexthop_group.h> #include <eos/sdk.h> #include <stdio.h> class my_agent : public eos::agent_handler { public: eos::agent_mgr * agentMgr_; eos::ip_route_mgr * ipMgr_; eos::nexthop_group_mgr * nhgMgr_; explicit my_agent(eos::sdk & sdk) : eos::agent_handler(sdk.get_agent_mgr()), agentMgr_(sdk.get_agent_mgr()), ipMgr_(sdk.get_ip_route_mgr()), nhgMgr_(sdk.get_nexthop_group_mgr()) { printf("Constructing my agent...\n"); } void create_nexthop_group(std::string name) { printf("Creating nexthop group\n"); eos::nexthop_group_t nhg = eos::nexthop_group_t(name, eos::NEXTHOP_GROUP_MPLS); eos::nexthop_group_mpls_action_t mplsActionA( eos::MPLS_ACTION_PUSH, {eos::mpls_label_t(30), eos::mpls_label_t(31)}); eos::nexthop_group_mpls_action_t mplsActionB( eos::MPLS_ACTION_PUSH, {eos::mpls_label_t(40), eos::mpls_label_t(41)}); // Send 2/3rds of traffic to nexthop 10.0.0.33 with the [30, 31] // label stack: eos::nexthop_group_entry_t nhe1(eos::ip_addr_t("10.0.0.33")); nhe1.mpls_action_is(mplsActionA); nhg.nexthop_set(1, nhe1); nhg.nexthop_set(2, nhe1); // Send 1/3rd of traffic to nexthop 10.0.0.44 with the [40, 41] // label stack: eos::nexthop_group_entry_t nhe2(eos::ip_addr_t("10.0.0.44")); nhe2.mpls_action_is(mplsActionB); nhg.nexthop_set(3, nhe2); // Make this persist in the system configuration (not the default) nhg.persistent_is(true); // And commit it to Sysdb! nhgMgr_->nexthop_group_set(nhg); } void on_initialized() { printf("Initializing my agent...\n"); create_nexthop_group("MplsNhg1"); eos::ip_route_key_t routeKey( eos::ip_prefix_t(eos::ip_addr_t("172.1.1.4"), 32)); eos::ip_route_t route(routeKey); eos::ip_route_via_t via(routeKey); via.nexthop_group_is("MplsNhg1"); ipMgr_->ip_route_set(route); ipMgr_->ip_route_via_set(via); printf("Done!\n"); agentMgr_->exit(); // (we'll just exit after this demo) } }; int main(int argc, char ** argv) { eos::sdk sdk; my_agent agent(sdk); sdk.main_loop(argc, argv); } <|endoftext|>
<commit_before>// Orbbec (c) 2015 #include <SenseKit.h> #include <cstdio> #include <iostream> #ifdef _WIN32 #include <windows.h> #else //_WIN32 -> OS X, LINUX #include <signal.h> #include <stdlib.h> #include <unistd.h> #endif //_WIN32 bool shouldContinue = true; void signal_stop_processing(){ printf("quitting...\n\n"); shouldContinue = false; } #ifdef _WIN32 BOOL CtrlHandler(DWORD fdwCtrlType) { switch (fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: signal_stop_processing(); return(TRUE); default: return FALSE; } } #else //_WIN32 -> OSX, LINUX void signal_handler(int s){ signal_stop_processing(); } #endif //_WIN32 int main(int argc, char** argv) { #ifdef _WIN32 SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); #else //_WIN32 -> OS X, LINUX struct sigaction sigIntHandler; sigIntHandler.sa_handler = my_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif //_WIN32 sensekit_initialize(); sensekit_sensor_t* sensor; sensekit_status_t status = SENSEKIT_STATUS_SUCCESS; //client connects to daemon host, registers interest in certain sensor URI status = sensekit_open_sensor("1d27/0601@20/30", &sensor); sensekit_depthstream_t* depthStream; //client -> daemon resolves stream type to plugin, notifies plugin client added //client service starts pulling (or daemon starts pushing) when data is available //client service stores latest frame until requested (via open or event) status = sensekit_depth_open(sensor, &depthStream); do { //Needed for now until backend plugins have their own thread and we figure out a thread/dispatch model sensekit_temp_update(); sensekit_depthframe_t* depthFrame; // sensekit_depth_frame_open(depthStream, 30, depthFrame); std::cout << "index: " << depthFrame->frameIndex << " value: " << depthFrame->sampleValue << std::endl; sensekit_depth_frame_close(depthFrame); } while (shouldContinue); status = sensekit_depth_close(&depthStream); status = sensekit_close_sensor(&sensor); sensekit_terminate(); } <commit_msg>fix POSIX compilation of SimpleViewer<commit_after>// Orbbec (c) 2015 #include <SenseKit.h> #include <cstdio> #include <iostream> #ifdef _WIN32 #include <windows.h> #else //_WIN32 -> OS X, LINUX #include <signal.h> #include <stdlib.h> #include <unistd.h> #endif //_WIN32 static bool shouldContinue = true; void signal_stop_processing(){ printf("quitting...\n\n"); shouldContinue = false; } #ifdef _WIN32 BOOL CtrlHandler(DWORD fdwCtrlType) { switch (fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: signal_stop_processing(); return(TRUE); default: return FALSE; } } #else //_WIN32 -> OSX, LINUX static void signal_handler(int s){ signal_stop_processing(); } #endif //_WIN32 int main(int argc, char** argv) { #ifdef _WIN32 SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); #else //_WIN32 -> OS X, LINUX struct sigaction sigIntHandler; sigIntHandler.sa_handler = &signal_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif //_WIN32 sensekit_initialize(); sensekit_sensor_t* sensor; sensekit_status_t status = SENSEKIT_STATUS_SUCCESS; //client connects to daemon host, registers interest in certain sensor URI status = sensekit_open_sensor("1d27/0601@20/30", &sensor); sensekit_depthstream_t* depthStream; //client -> daemon resolves stream type to plugin, notifies plugin client added //client service starts pulling (or daemon starts pushing) when data is available //client service stores latest frame until requested (via open or event) status = sensekit_depth_open(sensor, &depthStream); do { //Needed for now until backend plugins have their own thread and we figure out a thread/dispatch model sensekit_temp_update(); sensekit_depthframe_t* depthFrame; // sensekit_depth_frame_open(depthStream, 30, depthFrame); std::cout << "index: " << depthFrame->frameIndex << " value: " << depthFrame->sampleValue << std::endl; sensekit_depth_frame_close(depthFrame); } while (shouldContinue); status = sensekit_depth_close(&depthStream); status = sensekit_close_sensor(&sensor); sensekit_terminate(); } <|endoftext|>
<commit_before>#include "inc/cxx/json.hpp" #include "test/catch.hpp" #include <type_traits> using namespace std::string_literals; TEST_CASE("can default construct cxx::json") { static_assert(std::is_nothrow_default_constructible_v<cxx::json>); cxx::json const json; REQUIRE(cxx::holds_alternative<cxx::document>(json)); REQUIRE(std::size(json) == 0); } TEST_CASE("can copy construct cxx::json") { static_assert(std::is_copy_constructible_v<cxx::json>); cxx::json const orig; cxx::json const copy(orig); REQUIRE(cxx::holds_alternative<cxx::document>(orig)); REQUIRE(cxx::holds_alternative<cxx::document>(copy)); REQUIRE(orig == copy); } TEST_CASE("can move construct cxx::json") { static_assert(std::is_nothrow_move_constructible_v<cxx::json>); cxx::json orig; cxx::json const copy(std::move(orig)); REQUIRE(cxx::holds_alternative<cxx::document>(copy)); } TEST_CASE("can directly initialize cxx::json from std::int64_t") { static_assert(std::is_nothrow_constructible_v<cxx::json, std::int64_t>); std::int64_t const x = 42; cxx::json const json(x); REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == x); REQUIRE(std::size(json) == 1); } TEST_CASE("can copy initialize cxx::json from std::int64_t") { cxx::json const json = 42l; REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == 42l); } TEST_CASE("can create cxx::json from double") { static_assert(std::is_nothrow_constructible_v<cxx::json, double>); double const x = 3.14; cxx::json const json(x); REQUIRE(cxx::holds_alternative<double>(json)); REQUIRE(json == x); REQUIRE(std::size(json) == 1); } TEST_CASE("can create cxx::json from bool") { static_assert(std::is_nothrow_constructible_v<cxx::json, bool>); cxx::json const json(true); REQUIRE(cxx::holds_alternative<bool>(json)); REQUIRE(json == true); REQUIRE(std::size(json) == 1); } TEST_CASE("can create cxx::json from cxx::null") { static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::null_t>); cxx::json const json(cxx::null); REQUIRE(cxx::holds_alternative<cxx::null_t>(json)); REQUIRE(json == cxx::null); REQUIRE(std::size(json) == 0); } TEST_CASE("can create cxx::json from std::string") { static_assert(std::is_constructible_v<cxx::json, std::string const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, std::string&&>); std::string const lorem = "lorem"; cxx::json const json(lorem); REQUIRE(cxx::holds_alternative<std::string>(json)); REQUIRE(json == lorem); REQUIRE(std::size(lorem) == 5); cxx::json const ipsum(std::string("ipsum")); REQUIRE(cxx::holds_alternative<std::string>(ipsum)); REQUIRE(ipsum == std::string("ipsum")); REQUIRE(std::size(ipsum) == 5); } TEST_CASE("can create cxx::json from cxx::array") { static_assert(std::is_constructible_v<cxx::json, cxx::array const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::array&&>); cxx::array const array = {true, cxx::null, 42l, 3.14}; cxx::json const json(array); REQUIRE(cxx::holds_alternative<cxx::array>(json)); REQUIRE(json == array); REQUIRE(std::size(json) == 4); cxx::json const arr(cxx::array({cxx::null, 42l})); REQUIRE(arr == cxx::array({cxx::null, 42l})); REQUIRE(std::size(arr) == 2); } TEST_CASE("can create cxx::json from cxx::document") { static_assert(std::is_constructible_v<cxx::json, cxx::document const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::document&&>); cxx::document const document = { // clang-format off {"lorem"s, 42l}, {"ipsum"s, cxx::null}, {"dolor"s, true}, {"sit"s, 3.14} // clang-format on }; cxx::json const json(document); REQUIRE(cxx::holds_alternative<cxx::document>(json)); REQUIRE(json == document); REQUIRE(std::size(json) == 4); cxx::json const doc(cxx::document({{"lorem"s, cxx::null}, {"ipsum"s, 3.14}})); REQUIRE(cxx::holds_alternative<cxx::document>(doc)); REQUIRE(doc == cxx::document({{"lorem"s, cxx::null}, {"ipsum"s, 3.14}})); REQUIRE(std::size(doc) == 2); } TEST_CASE("can create cxx::json from std::initializer_list<json>") { static_assert(std::is_constructible_v<cxx::json, std::initializer_list<cxx::json>>); cxx::json const json = {42, true, cxx::null, 3.14}; REQUIRE(cxx::holds_alternative<cxx::array>(json)); REQUIRE(json == cxx::array({42, true, cxx::null, 3.14})); } TEST_CASE("can create cxx::json from std::initializer_list<std::pair<key, json>>") { using namespace cxx::literals; static_assert( std::is_constructible_v<cxx::json, std::initializer_list<std::pair<cxx::key const, cxx::json>>>); cxx::json const json = { // clang-format off {"lorem"_key, 42}, {"ipsum"_key, true}, {"dolor"_key, cxx::null}, {"sit"_key, 3.14} // clang-format on }; REQUIRE(cxx::holds_alternative<cxx::document>(json)); REQUIRE(json == // clang-format off cxx::document( { {"lorem", 42}, {"ipsum", true}, {"dolor", cxx::null}, {"sit", 3.14} } ) // clang-format on ); } <commit_msg>direct and copy init from int<commit_after>#include "inc/cxx/json.hpp" #include "test/catch.hpp" #include <type_traits> using namespace std::string_literals; TEST_CASE("can default construct cxx::json") { static_assert(std::is_nothrow_default_constructible_v<cxx::json>); cxx::json const json; REQUIRE(cxx::holds_alternative<cxx::document>(json)); REQUIRE(std::size(json) == 0); } TEST_CASE("can copy construct cxx::json") { static_assert(std::is_copy_constructible_v<cxx::json>); cxx::json const orig; cxx::json const copy(orig); REQUIRE(cxx::holds_alternative<cxx::document>(orig)); REQUIRE(cxx::holds_alternative<cxx::document>(copy)); REQUIRE(orig == copy); } TEST_CASE("can move construct cxx::json") { static_assert(std::is_nothrow_move_constructible_v<cxx::json>); cxx::json orig; cxx::json const copy(std::move(orig)); REQUIRE(cxx::holds_alternative<cxx::document>(copy)); } TEST_CASE("can directly initialize cxx::json from std::int64_t") { static_assert(std::is_nothrow_constructible_v<cxx::json, std::int64_t>); std::int64_t const x = 42; cxx::json const json(x); REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == x); REQUIRE(std::size(json) == 1); } TEST_CASE("can copy initialize cxx::json from std::int64_t") { cxx::json const json = 42l; REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == 42l); } TEST_CASE("can create cxx::json from double") { static_assert(std::is_nothrow_constructible_v<cxx::json, double>); double const x = 3.14; cxx::json const json(x); REQUIRE(cxx::holds_alternative<double>(json)); REQUIRE(json == x); REQUIRE(std::size(json) == 1); } TEST_CASE("can create cxx::json from bool") { static_assert(std::is_nothrow_constructible_v<cxx::json, bool>); cxx::json const json(true); REQUIRE(cxx::holds_alternative<bool>(json)); REQUIRE(json == true); REQUIRE(std::size(json) == 1); } TEST_CASE("can create cxx::json from cxx::null") { static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::null_t>); cxx::json const json(cxx::null); REQUIRE(cxx::holds_alternative<cxx::null_t>(json)); REQUIRE(json == cxx::null); REQUIRE(std::size(json) == 0); } TEST_CASE("can create cxx::json from std::string") { static_assert(std::is_constructible_v<cxx::json, std::string const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, std::string&&>); std::string const lorem = "lorem"; cxx::json const json(lorem); REQUIRE(cxx::holds_alternative<std::string>(json)); REQUIRE(json == lorem); REQUIRE(std::size(lorem) == 5); cxx::json const ipsum(std::string("ipsum")); REQUIRE(cxx::holds_alternative<std::string>(ipsum)); REQUIRE(ipsum == std::string("ipsum")); REQUIRE(std::size(ipsum) == 5); } TEST_CASE("can create cxx::json from cxx::array") { static_assert(std::is_constructible_v<cxx::json, cxx::array const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::array&&>); cxx::array const array = {true, cxx::null, 42l, 3.14}; cxx::json const json(array); REQUIRE(cxx::holds_alternative<cxx::array>(json)); REQUIRE(json == array); REQUIRE(std::size(json) == 4); cxx::json const arr(cxx::array({cxx::null, 42l})); REQUIRE(arr == cxx::array({cxx::null, 42l})); REQUIRE(std::size(arr) == 2); } TEST_CASE("can create cxx::json from cxx::document") { static_assert(std::is_constructible_v<cxx::json, cxx::document const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::document&&>); cxx::document const document = { // clang-format off {"lorem"s, 42l}, {"ipsum"s, cxx::null}, {"dolor"s, true}, {"sit"s, 3.14} // clang-format on }; cxx::json const json(document); REQUIRE(cxx::holds_alternative<cxx::document>(json)); REQUIRE(json == document); REQUIRE(std::size(json) == 4); cxx::json const doc(cxx::document({{"lorem"s, cxx::null}, {"ipsum"s, 3.14}})); REQUIRE(cxx::holds_alternative<cxx::document>(doc)); REQUIRE(doc == cxx::document({{"lorem"s, cxx::null}, {"ipsum"s, 3.14}})); REQUIRE(std::size(doc) == 2); } TEST_CASE("can create cxx::json from std::initializer_list<json>") { static_assert(std::is_constructible_v<cxx::json, std::initializer_list<cxx::json>>); cxx::json const json = {42, true, cxx::null, 3.14}; REQUIRE(cxx::holds_alternative<cxx::array>(json)); REQUIRE(json == cxx::array({42, true, cxx::null, 3.14})); } TEST_CASE("can create cxx::json from std::initializer_list<std::pair<key, json>>") { using namespace cxx::literals; static_assert( std::is_constructible_v<cxx::json, std::initializer_list<std::pair<cxx::key const, cxx::json>>>); cxx::json const json = { // clang-format off {"lorem"_key, 42}, {"ipsum"_key, true}, {"dolor"_key, cxx::null}, {"sit"_key, 3.14} // clang-format on }; REQUIRE(cxx::holds_alternative<cxx::document>(json)); REQUIRE(json == // clang-format off cxx::document( { {"lorem", 42}, {"ipsum", true}, {"dolor", cxx::null}, {"sit", 3.14} } ) // clang-format on ); } TEST_CASE("can directly initialize cxx::json from int") { static_assert(std::is_nothrow_constructible_v<cxx::json, int>); int const x = 42; cxx::json const json(x); REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == x); } TEST_CASE("can copy initialize cxx::json from int") { cxx::json const json = 42; REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == 42); } <|endoftext|>
<commit_before>#include <cmath> #include <Eigen/Dense> #include <gtest/gtest.h> TEST( AdaptiveFilter, LMS ) { const unsigned kInputCount = 10; const unsigned kSampleCount = 100; const float kMaxAmplitude = 1.0f; const float kMaxFrequency = 10.0f; const float kStep = 0.1f * 1.0f / kMaxFrequency; ReferenceFilter referenceFilter( kInputCount ); Eigen::VectorXf input( kInputCount ); Eigen::VectorXf A = kMaxAmplitude / 2.0f * ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ); Eigen::VectorXf W = kMaxFrequency / 2.0f * ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ); for ( int i = 0; i < kSampleCount; ++ i ) { float t = kStep * i; input = A.array() * ( W.array() * t ).unaryExpr( std::ptr_fun( std::sinf ) ); } } <commit_msg>esn : tests : AdpativeFilter : defined ReferneceFilter<commit_after>#include <cmath> #include <Eigen/Dense> #include <gtest/gtest.h> class ReferenceFilter { public: ReferenceFilter( unsigned size ) : mW( Eigen::VectorXf::Random( size ) ) {} float operator()( Eigen::VectorXf inputs ) { return mW.dot( inputs ); } Eigen::VectorXf mW; }; TEST( AdaptiveFilter, LMS ) { const unsigned kInputCount = 10; const unsigned kSampleCount = 100; const float kMaxAmplitude = 1.0f; const float kMaxFrequency = 10.0f; const float kStep = 0.1f * 1.0f / kMaxFrequency; ReferenceFilter referenceFilter( kInputCount ); Eigen::VectorXf input( kInputCount ); Eigen::VectorXf A = kMaxAmplitude / 2.0f * ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ); Eigen::VectorXf W = kMaxFrequency / 2.0f * ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ); for ( int i = 0; i < kSampleCount; ++ i ) { float t = kStep * i; input = A.array() * ( W.array() * t ).unaryExpr( std::ptr_fun( std::sinf ) ); } } <|endoftext|>
<commit_before>// Bell inequalities (CHSH) violation // Source: ./examples/bell_inequalities.cpp #include <qpp.h> using namespace qpp; using std::cout; using std::endl; //TODO: finish the example, incomplete now int main() { ket psi = kron(st.z0, st.z0); // Measure the singlet Bell state (|01>-|10>) // /sqrt(2) idx N = 1; // number of measurements each party does // gates cmat Q = gt.Z; cmat R = gt.X; cmat S = (-gt.Z - gt.X) / std::sqrt(2); cmat T = (gt.Z - gt.X) / std::sqrt(2); //Q = S = gt.Z; //R = T = gt.X; idx statistics[4][4] = {0}; // total statistics int E[4] = {0}; // experimental estimate idx gate_idx = 0; // gate index (0, 1, 2 or 3) for (auto&& gateA: {Q, R}) // measure Alice's side { auto evalsA = hevals(gateA); // eigenvalues, so we know the order auto basisA = hevects(gateA); // eigenvectors, ordered by eigenvalues for (auto&& gateB: {S, T}) // measure Bob's side { // eigenvalues, so we know the order auto evalsB = hevals(gateB); auto basisB = hevects(gateB); for (idx i = 0; i < N; ++i) { auto measurementA = measure(psi, basisA, {0}); auto mA = std::get<0>(measurementA); // result on A // the eigenvalues corresponding to the measurement results short evalA = static_cast<short>(std::round(evalsA[mA])); // resulting state on B auto rhoB = std::get<2>(measurementA)[mA]; auto measurementB = measure(rhoB, basisB); auto mB = std::get<0>(measurementB); // measurement result B short evalB = static_cast<short>(std::round(evalsB[mB])); // count the coincidences if (evalA == 1 && evalB == 1) // +1 +1 { statistics[gate_idx][0]++; E[gate_idx]++; } else if (evalA == 1 && evalB == -1) // +1 -1 { statistics[gate_idx][1]++; E[gate_idx]--; } else if (evalA == -1 && evalB == 1) // -1 +1 { statistics[gate_idx][2]++; E[gate_idx]--; } else if (evalA == -1 && evalB == -1) // -1 -1 { statistics[gate_idx][3]++; E[gate_idx]++; } } ++gate_idx; } } std::cout << "Coincidences N = " << N << std::endl; std::cout << "(N++ N+- N-+ N-- E)" << std::endl; std::cout << "QS: " << disp(statistics[0], 4, " "); std::cout << " " << E[0] << std::endl; std::cout << "QT: " << disp(statistics[1], 4, " "); std::cout << " " << E[1] << std::endl; std::cout << "RS: " << disp(statistics[2], 4, " "); std::cout << " " << E[2] << std::endl; std::cout << "RT: " << disp(statistics[3], 4, " "); std::cout << " " << E[3] << std::endl; double val = (E[0] - E[1] + E[2] + E[3]) / static_cast<double>(N); std::cout << "<QS> + <RS> + <RT> - <QT> = " << val << std::endl; std::cout << "Theoretical value 2 * sqrt(2) = " << 2 * std::sqrt(2); }<commit_msg>commit<commit_after>// Bell inequalities (CHSH) violation // Source: ./examples/bell_inequalities.cpp #include <qpp.h> using namespace qpp; using std::cout; using std::endl; //TODO: finish the example, incomplete now int main() { ket psi = kron(st.z0, st.z0); // Measure the singlet Bell state (|01>-|10>) // /sqrt(2) idx N = 1; // number of measurements each party does // gates cmat Q = gt.Z; cmat R = gt.X; cmat S = (-gt.Z - gt.X) / std::sqrt(2); cmat T = (gt.Z - gt.X) / std::sqrt(2); //Q = S = gt.Z; //R = T = gt.X; idx statistics[4][4] = {0}; // total statistics int E[4] = {0}; // experimental estimate idx gate_idx = 0; // gate index (0, 1, 2 or 3) for (auto&& gateA: {Q, R}) // measure Alice's side { auto evalsA = hevals(gateA); // eigenvalues, so we know the order auto basisA = hevects(gateA); // eigenvectors, ordered by eigenvalues for (auto&& gateB: {S, T}) // measure Bob's side { // eigenvalues, so we know the order auto evalsB = hevals(gateB); auto basisB = hevects(gateB); for (idx i = 0; i < N; ++i) { auto measurementA = measure(psi, basisA, {0}); auto mA = std::get<0>(measurementA); // result on A // the eigenvalues corresponding to the measurement results short evalA = static_cast<short>(std::round(evalsA[mA])); // resulting state on B auto rhoB = std::get<2>(measurementA)[mA]; auto measurementB = measure(rhoB, basisB); auto mB = std::get<0>(measurementB); // measurement result B short evalB = static_cast<short>(std::round(evalsB[mB])); // count the coincidences if (evalA == 1 && evalB == 1) // +1 +1 { statistics[gate_idx][0]++; E[gate_idx]++; } else if (evalA == 1 && evalB == -1) // +1 -1 { statistics[gate_idx][1]++; E[gate_idx]--; } else if (evalA == -1 && evalB == 1) // -1 +1 { statistics[gate_idx][2]++; E[gate_idx]--; } else if (evalA == -1 && evalB == -1) // -1 -1 { statistics[gate_idx][3]++; E[gate_idx]++; } } ++gate_idx; } } std::cout << "Coincidences N = " << N << std::endl; std::cout << "(N++ N+- N-+ N-- E)" << std::endl; std::cout << "QS: " << disp(statistics[0], 4, " "); std::cout << " " << E[0] << std::endl; std::cout << "QT: " << disp(statistics[1], 4, " "); std::cout << " " << E[1] << std::endl; std::cout << "RS: " << disp(statistics[2], 4, " "); std::cout << " " << E[2] << std::endl; std::cout << "RT: " << disp(statistics[3], 4, " "); std::cout << " " << E[3] << std::endl; double val = (E[0] - E[1] + E[2] + E[3]) / static_cast<double>(N); std::cout << "<QS> + <RS> + <RT> - <QT> = " << val << std::endl; std::cout << "Theoretical value 2 * sqrt(2) = " << 2 * std::sqrt(2); }<|endoftext|>
<commit_before>// Copyright 2016-2019 Jean-Francois Poilpret // // 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. /* * Blocking EEPROM Read and Writes. * This program shows usage of FastArduino EEPROM API. * It interfaces with user through the UART console and allows: * - writing values to EEPROM * - reading values to EEPROM * * Wiring: TODO * - on ATmega328P based boards (including Arduino UNO): * - on Arduino MEGA: * - on ATtinyX4 based boards: * - D1: TX output connected to Serial-USB allowing traces display on a PC terminal */ #include <fastarduino/flash.h> #if defined(ARDUINO_UNO) || defined(BREADBOARD_ATMEGA328P) || defined(ARDUINO_NANO) #define HARDWARE_UART 1 #include <fastarduino/uart.h> static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; static constexpr const board::USART UART = board::USART::USART0; // Define vectors we need in the example REGISTER_UATX_ISR(0) #elif defined (ARDUINO_LEONARDO) #define HARDWARE_UART 1 #include <fastarduino/uart.h> static constexpr const board::USART UART = board::USART::USART1; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; // Define vectors we need in the example REGISTER_UATX_ISR(1) #elif defined (ARDUINO_MEGA) #define HARDWARE_UART 1 #include <fastarduino/uart.h> static constexpr const board::USART UART = board::USART::USART0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; // Define vectors we need in the example REGISTER_UATX_ISR(0) #elif defined (BREADBOARD_ATTINYX4) #define HARDWARE_UART 0 #include <fastarduino/soft_uart.h> static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; constexpr const board::DigitalPin TX = board::DigitalPin::D1_PA1; #else #error "Current target is not yet supported!" #endif // Buffers for UART static char output_buffer[OUTPUT_BUFFER_SIZE]; struct Dummy { uint16_t a; uint8_t b; bool c; int16_t d; char e; }; using OUTPUT = streams::ostream; OUTPUT& operator<< (OUTPUT& out, const Dummy& item) { out << streams::dec << F("{\n\ta: ") << item.a << F("\n\tb: ") << item.b << F("\n\tc: ") << item.c << F("\n\td: ") << item.d << F("\n\te: ") << item.e << F("\n}") << streams::endl; return out; } const Dummy sample1 PROGMEM = {54321, 123, true, -22222, 'z'}; const Dummy sample2 PROGMEM = {12345, 231, false, -11111, 'A'}; int main() { board::init(); // Enable interrupts at startup time sei(); #if HARDWARE_UART serial::hard::UATX<UART> uart{output_buffer}; #else serial::soft::UATX<TX> uart{output_buffer}; #endif uart.begin(115200); streams::ostream out = uart.out(); Dummy value; out << F("sample1 = ") << flash::read_flash(&sample1, value); out << F("sample2 = ") << flash::read_flash(&sample2, value); return 0; } <commit_msg>Fix typo in API doc.<commit_after>// Copyright 2016-2019 Jean-Francois Poilpret // // 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. /* * Blocking Flash Read. * This program shows usage of FastArduino Flash API. * It interfaces with user through the UART console and allows: * - reading values from Flash * * Wiring: TODO * - on ATmega328P based boards (including Arduino UNO): * - on Arduino MEGA: * - on ATtinyX4 based boards: * - D1: TX output connected to Serial-USB allowing traces display on a PC terminal */ #include <fastarduino/flash.h> #if defined(ARDUINO_UNO) || defined(BREADBOARD_ATMEGA328P) || defined(ARDUINO_NANO) #define HARDWARE_UART 1 #include <fastarduino/uart.h> static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; static constexpr const board::USART UART = board::USART::USART0; // Define vectors we need in the example REGISTER_UATX_ISR(0) #elif defined (ARDUINO_LEONARDO) #define HARDWARE_UART 1 #include <fastarduino/uart.h> static constexpr const board::USART UART = board::USART::USART1; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; // Define vectors we need in the example REGISTER_UATX_ISR(1) #elif defined (ARDUINO_MEGA) #define HARDWARE_UART 1 #include <fastarduino/uart.h> static constexpr const board::USART UART = board::USART::USART0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; // Define vectors we need in the example REGISTER_UATX_ISR(0) #elif defined (BREADBOARD_ATTINYX4) #define HARDWARE_UART 0 #include <fastarduino/soft_uart.h> static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; constexpr const board::DigitalPin TX = board::DigitalPin::D1_PA1; #else #error "Current target is not yet supported!" #endif // Buffers for UART static char output_buffer[OUTPUT_BUFFER_SIZE]; struct Dummy { uint16_t a; uint8_t b; bool c; int16_t d; char e; }; using OUTPUT = streams::ostream; OUTPUT& operator<< (OUTPUT& out, const Dummy& item) { out << streams::dec << F("{\n\ta: ") << item.a << F("\n\tb: ") << item.b << F("\n\tc: ") << item.c << F("\n\td: ") << item.d << F("\n\te: ") << item.e << F("\n}") << streams::endl; return out; } const Dummy sample1 PROGMEM = {54321, 123, true, -22222, 'z'}; const Dummy sample2 PROGMEM = {12345, 231, false, -11111, 'A'}; int main() { board::init(); // Enable interrupts at startup time sei(); #if HARDWARE_UART serial::hard::UATX<UART> uart{output_buffer}; #else serial::soft::UATX<TX> uart{output_buffer}; #endif uart.begin(115200); streams::ostream out = uart.out(); Dummy value; out << F("sample1 = ") << flash::read_flash(&sample1, value); out << F("sample2 = ") << flash::read_flash(&sample2, value); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2010-2012 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FontDatabase.h" #include "FontManager.h" namespace { const char* fontList[] = { // LiberationSans LIBERATON_TTF "/LiberationSans-BoldItalic.ttf", LIBERATON_TTF "/LiberationSans-Italic.ttf", LIBERATON_TTF "/LiberationSans-Regular.ttf", LIBERATON_TTF "/LiberationSans-Bold.ttf", // LiberationSerif LIBERATON_TTF "/LiberationSerif-BoldItalic.ttf", LIBERATON_TTF "/LiberationSerif-Italic.ttf", LIBERATON_TTF "/LiberationSerif-Regular.ttf", LIBERATON_TTF "/LiberationSerif-Bold.ttf", // LiberationMono LIBERATON_TTF "/LiberationMono-BoldItalic.ttf", LIBERATON_TTF "/LiberationMono-Italic.ttf", LIBERATON_TTF "/LiberationMono-Regular.ttf", LIBERATON_TTF "/LiberationMono-Bold.ttf", #ifdef HAVE_IPA_PGOTHIC // IPAPGothic HAVE_IPA_PGOTHIC, #endif #ifdef HAVE_IPA_PMINCHO // IPAPMincho HAVE_IPA_PMINCHO, #endif #ifdef HAVE_IPA_GOTHIC // IPAGothic HAVE_IPA_GOTHIC, #endif #ifdef HAVE_IPA_MINCHO // IPAMincho HAVE_IPA_MINCHO, #endif #ifdef HAVE_AEGEAN // Aegean HAVE_AEGEAN, #endif #ifdef HAVE_AHEM // Ahem HAVE_AHEM, #endif }; // Test fonts for CSS 2.1 test suite const char* testFontList[] = { // Ahem! TEST_FONTS "/AhemExtra/AHEM_Ahem!.TTF", // MissingNormal TEST_FONTS "/AhemExtra/AHEM_MissingNormal.TTF", // SmallCaps TEST_FONTS "/AhemExtra/AHEM_SmallCaps.TTF", // MissingItalicOblique TEST_FONTS "/AhemExtra/AHEM_MissingItalicOblique.TTF", // White Space TEST_FONTS "/AhemExtra/AHEM_WhiteSpace.TTF", // cursive TEST_FONTS "/AhemExtra/AHEM_cursive.TTF", // default TEST_FONTS "/AhemExtra/AHEM_default.TTF", // fantasy TEST_FONTS "/AhemExtra/AHEM_fantasy.TTF", // inherit TEST_FONTS "/AhemExtra/AHEM_inherit.TTF", // initial TEST_FONTS "/AhemExtra/AHEM_initial.TTF", // monospace TEST_FONTS "/AhemExtra/AHEM_monospace.TTF", // serif TEST_FONTS "/AhemExtra/AHEM_serif.TTF", // sans-serif TEST_FONTS "/AhemExtra/AHEM_sans-serif.TTF", // CSSTest ASCII TEST_FONTS "/CSSTest/csstest-ascii.ttf", // CSSTest Basic TEST_FONTS "/CSSTest/csstest-basic-bold.ttf", TEST_FONTS "/CSSTest/csstest-basic-bolditalic.ttf", TEST_FONTS "/CSSTest/csstest-basic-italic.ttf", TEST_FONTS "/CSSTest/csstest-basic-regular.ttf", // CSSTest Fallback TEST_FONTS "/CSSTest/csstest-fallback.ttf", // small-caps 1in CSSTest FamilyName Funky TEST_FONTS "/CSSTest/csstest-familyname-funkyA.ttf", // x-large CSSTest FamilyName Funky TEST_FONTS "/CSSTest/csstest-familyname-funkyB.ttf", // 12px CSSTest FamilyName Funky TEST_FONTS "/CSSTest/csstest-familyname-funkyC.ttf", // CSSTest FamilyName TEST_FONTS "/CSSTest/csstest-familyname.ttf", TEST_FONTS "/CSSTest/csstest-familyname-bold.ttf", // CSSTest Verify TEST_FONTS "/CSSTest/csstest-verify.ttf", }; } void FontDatabase::loadBaseFonts(FontManager* manager) { for (auto i = fontList; i < &fontList[sizeof fontList / sizeof fontList[0]]; ++i) manager->loadFont(*i); } void FontDatabase::loadTestFonts(FontManager* manager) { for (auto i = testFontList; i < &testFontList[sizeof testFontList / sizeof testFontList[0]]; ++i) manager->loadFont(*i); } <commit_msg>(testFontList) : Add CSSTest Weights fonts.<commit_after>/* * Copyright 2010-2012 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FontDatabase.h" #include "FontManager.h" namespace { const char* fontList[] = { // LiberationSans LIBERATON_TTF "/LiberationSans-BoldItalic.ttf", LIBERATON_TTF "/LiberationSans-Italic.ttf", LIBERATON_TTF "/LiberationSans-Regular.ttf", LIBERATON_TTF "/LiberationSans-Bold.ttf", // LiberationSerif LIBERATON_TTF "/LiberationSerif-BoldItalic.ttf", LIBERATON_TTF "/LiberationSerif-Italic.ttf", LIBERATON_TTF "/LiberationSerif-Regular.ttf", LIBERATON_TTF "/LiberationSerif-Bold.ttf", // LiberationMono LIBERATON_TTF "/LiberationMono-BoldItalic.ttf", LIBERATON_TTF "/LiberationMono-Italic.ttf", LIBERATON_TTF "/LiberationMono-Regular.ttf", LIBERATON_TTF "/LiberationMono-Bold.ttf", #ifdef HAVE_IPA_PGOTHIC // IPAPGothic HAVE_IPA_PGOTHIC, #endif #ifdef HAVE_IPA_PMINCHO // IPAPMincho HAVE_IPA_PMINCHO, #endif #ifdef HAVE_IPA_GOTHIC // IPAGothic HAVE_IPA_GOTHIC, #endif #ifdef HAVE_IPA_MINCHO // IPAMincho HAVE_IPA_MINCHO, #endif #ifdef HAVE_AEGEAN // Aegean HAVE_AEGEAN, #endif #ifdef HAVE_AHEM // Ahem HAVE_AHEM, #endif }; // Test fonts for CSS 2.1 test suite const char* testFontList[] = { // Ahem! TEST_FONTS "/AhemExtra/AHEM_Ahem!.TTF", // MissingNormal TEST_FONTS "/AhemExtra/AHEM_MissingNormal.TTF", // SmallCaps TEST_FONTS "/AhemExtra/AHEM_SmallCaps.TTF", // MissingItalicOblique TEST_FONTS "/AhemExtra/AHEM_MissingItalicOblique.TTF", // White Space TEST_FONTS "/AhemExtra/AHEM_WhiteSpace.TTF", // cursive TEST_FONTS "/AhemExtra/AHEM_cursive.TTF", // default TEST_FONTS "/AhemExtra/AHEM_default.TTF", // fantasy TEST_FONTS "/AhemExtra/AHEM_fantasy.TTF", // inherit TEST_FONTS "/AhemExtra/AHEM_inherit.TTF", // initial TEST_FONTS "/AhemExtra/AHEM_initial.TTF", // monospace TEST_FONTS "/AhemExtra/AHEM_monospace.TTF", // serif TEST_FONTS "/AhemExtra/AHEM_serif.TTF", // sans-serif TEST_FONTS "/AhemExtra/AHEM_sans-serif.TTF", // CSSTest ASCII TEST_FONTS "/CSSTest/csstest-ascii.ttf", // CSSTest Basic TEST_FONTS "/CSSTest/csstest-basic-bold.ttf", TEST_FONTS "/CSSTest/csstest-basic-bolditalic.ttf", TEST_FONTS "/CSSTest/csstest-basic-italic.ttf", TEST_FONTS "/CSSTest/csstest-basic-regular.ttf", // CSSTest Fallback TEST_FONTS "/CSSTest/csstest-fallback.ttf", // small-caps 1in CSSTest FamilyName Funky TEST_FONTS "/CSSTest/csstest-familyname-funkyA.ttf", // x-large CSSTest FamilyName Funky TEST_FONTS "/CSSTest/csstest-familyname-funkyB.ttf", // 12px CSSTest FamilyName Funky TEST_FONTS "/CSSTest/csstest-familyname-funkyC.ttf", // CSSTest FamilyName TEST_FONTS "/CSSTest/csstest-familyname.ttf", TEST_FONTS "/CSSTest/csstest-familyname-bold.ttf", // CSSTest Verify TEST_FONTS "/CSSTest/csstest-verify.ttf", // CSSTest Weights TEST_FONTS "/CSSTest/csstest-weights-100.ttf", TEST_FONTS "/CSSTest/csstest-weights-1479-w1.ttf", TEST_FONTS "/CSSTest/csstest-weights-1479-w4.ttf", TEST_FONTS "/CSSTest/csstest-weights-1479-w7.ttf", TEST_FONTS "/CSSTest/csstest-weights-1479-w9.ttf", TEST_FONTS "/CSSTest/csstest-weights-15-w1.ttf", TEST_FONTS "/CSSTest/csstest-weights-15-w5.ttf", TEST_FONTS "/CSSTest/csstest-weights-200.ttf", TEST_FONTS "/CSSTest/csstest-weights-24-w2.ttf", TEST_FONTS "/CSSTest/csstest-weights-24-w4.ttf", TEST_FONTS "/CSSTest/csstest-weights-2569-w2.ttf", TEST_FONTS "/CSSTest/csstest-weights-2569-w5.ttf", TEST_FONTS "/CSSTest/csstest-weights-2569-w6.ttf", TEST_FONTS "/CSSTest/csstest-weights-2569-w9.ttf", TEST_FONTS "/CSSTest/csstest-weights-258-w2.ttf", TEST_FONTS "/CSSTest/csstest-weights-258-w5.ttf", TEST_FONTS "/CSSTest/csstest-weights-258-w8.ttf", TEST_FONTS "/CSSTest/csstest-weights-300.ttf", TEST_FONTS "/CSSTest/csstest-weights-3589-w3.ttf", TEST_FONTS "/CSSTest/csstest-weights-3589-w5.ttf", TEST_FONTS "/CSSTest/csstest-weights-3589-w8.ttf", TEST_FONTS "/CSSTest/csstest-weights-3589-w9.ttf", TEST_FONTS "/CSSTest/csstest-weights-400.ttf", TEST_FONTS "/CSSTest/csstest-weights-47-w4.ttf", TEST_FONTS "/CSSTest/csstest-weights-47-w7.ttf", TEST_FONTS "/CSSTest/csstest-weights-500.ttf", TEST_FONTS "/CSSTest/csstest-weights-600.ttf", TEST_FONTS "/CSSTest/csstest-weights-700.ttf", TEST_FONTS "/CSSTest/csstest-weights-800.ttf", TEST_FONTS "/CSSTest/csstest-weights-900.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w1.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w2.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w3.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w4.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w5.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w6.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w7.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w8.ttf", TEST_FONTS "/CSSTest/csstest-weights-full-w9.ttf", TEST_FONTS "/CSSTest/csstest-weights.ttf", }; } void FontDatabase::loadBaseFonts(FontManager* manager) { for (auto i = fontList; i < &fontList[sizeof fontList / sizeof fontList[0]]; ++i) manager->loadFont(*i); } void FontDatabase::loadTestFonts(FontManager* manager) { for (auto i = testFontList; i < &testFontList[sizeof testFontList / sizeof testFontList[0]]; ++i) manager->loadFont(*i); } <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/sksl/SkSLCPPUniformCTypes.h" #include "include/private/SkMutex.h" #include "src/sksl/SkSLStringStream.h" #include "src/sksl/codegen/SkSLHCodeGenerator.h" #include <map> #include <vector> #if defined(SKSL_STANDALONE) || GR_TEST_UTILS namespace SkSL { ///////////////////////// // Template evaluation // ///////////////////////// static String eval_template(const String& format, std::initializer_list<String> tokens, std::initializer_list<String> replacements) { SkASSERT(tokens.size() == replacements.size()); String str = format; // Replace every token with its replacement. auto tokenIter = tokens.begin(); auto replacementIter = replacements.begin(); for (; tokenIter != tokens.end(); ++tokenIter, ++replacementIter) { size_t position = 0; for (;;) { // Replace one instance of the current token with the requested replacement. position = str.find(*tokenIter, position); if (position == String::npos) { break; } str.replace(position, tokenIter->size(), *replacementIter); position += replacementIter->size(); } } return str; } static bool determine_inline_from_template(const String& uniformTemplate) { // True if there is at most one instance of the ${var} template matcher in fUniformTemplate. int firstMatch = uniformTemplate.find("${var}"); if (firstMatch < 0) { // Template doesn't use the value variable at all, so it can "inlined" return true; } // Check for another occurrence of ${var}, after firstMatch + 6 int secondMatch = uniformTemplate.find("${var}", firstMatch + strlen("${var}")); // If there's no second match, then the value can be inlined in the c++ code return secondMatch < 0; } /////////////////////////////////////// // UniformCTypeMapper implementation // /////////////////////////////////////// String UniformCTypeMapper::dirtyExpression(const String& newVar, const String& oldVar) const { return eval_template(fDirtyExpressionTemplate, {"${newVar}", "${oldVar}"}, {newVar, oldVar}); } String UniformCTypeMapper::saveState(const String& newVar, const String& oldVar) const { return eval_template(fSaveStateTemplate, {"${newVar}", "${oldVar}"}, {newVar, oldVar}); } String UniformCTypeMapper::setUniform(const String& pdman, const String& uniform, const String& var) const { String count; String finalVar; const String* activeTemplate; if (fArrayCount != -1) { count = to_string(fArrayCount); finalVar = var + "[0]"; activeTemplate = &fUniformArrayTemplate; } else { count = "1"; finalVar = std::move(var); activeTemplate = &fUniformSingleTemplate; } return eval_template(*activeTemplate, {"${pdman}", "${uniform}", "${var}", "${count}"}, {pdman, uniform, finalVar, count}); } UniformCTypeMapper::UniformCTypeMapper( Layout::CType ctype, const std::vector<String>& skslTypes, const String& setUniformSingleFormat, const String& setUniformArrayFormat, const String& defaultValue, const String& dirtyExpressionFormat, const String& saveStateFormat) : fCType(ctype) , fSKSLTypes(skslTypes) , fUniformSingleTemplate(setUniformSingleFormat) , fUniformArrayTemplate(setUniformArrayFormat) , fInlineValue(determine_inline_from_template(setUniformSingleFormat) && determine_inline_from_template(setUniformArrayFormat)) , fDefaultValue(defaultValue) , fDirtyExpressionTemplate(dirtyExpressionFormat) , fSaveStateTemplate(saveStateFormat) {} const UniformCTypeMapper* UniformCTypeMapper::arrayMapper(int count) const { static SkMutex& mutex = *(new SkMutex); SkAutoMutexExclusive guard(mutex); using Key = std::pair<const UniformCTypeMapper*, int>; static std::map<Key, UniformCTypeMapper> registered; Key key(this, count); auto result = registered.find(key); if (result == registered.end()) { auto [iter, didInsert] = registered.insert({key, *this}); SkASSERT(didInsert); UniformCTypeMapper* inserted = &iter->second; inserted->fArrayCount = count; return inserted; } return &result->second; } static UniformCTypeMapper register_array(Layout::CType ctype, const std::vector<String>& skslTypes, const char* singleSet, const char* arraySet, const char* defaultValue, const char* dirtyExpression) { return UniformCTypeMapper(ctype, skslTypes, singleSet, arraySet, defaultValue, dirtyExpression, "${oldVar} = ${newVar}"); } static UniformCTypeMapper register_array(Layout::CType ctype, const std::vector<String>& skslTypes, const char* singleSet, const char* arraySet, const char* defaultValue) { return register_array(ctype, skslTypes, singleSet, arraySet, defaultValue, "${oldVar} != ${newVar}"); } static UniformCTypeMapper register_type(Layout::CType ctype, const std::vector<String>& skslTypes, const char* uniformFormat, const char* defaultValue, const char* dirtyExpression) { return register_array(ctype, skslTypes, uniformFormat, uniformFormat, defaultValue, dirtyExpression); } static UniformCTypeMapper register_type(Layout::CType ctype, const std::vector<String>& skslTypes, const char* uniformFormat, const char* defaultValue) { return register_array(ctype, skslTypes, uniformFormat, uniformFormat, defaultValue); } ////////////////////////////// // Currently defined ctypes // ////////////////////////////// static const std::vector<UniformCTypeMapper>& get_mappers() { static const std::vector<UniformCTypeMapper> registeredMappers = { register_type(Layout::CType::kSkRect, { "half4", "float4", "double4" }, "${pdman}.set4fv(${uniform}, ${count}, reinterpret_cast<const float*>(&${var}))", // to gpu "SkRect::MakeEmpty()", // default value "${oldVar}.isEmpty() || ${oldVar} != ${newVar}"), // dirty check register_type(Layout::CType::kSkIRect, { "int4", "short4", "byte4" }, "${pdman}.set4iv(${uniform}, ${count}, reinterpret_cast<const int*>(&${var}))", // to gpu "SkIRect::MakeEmpty()", // default value "${oldVar}.isEmpty() || ${oldVar} != ${newVar}"), // dirty check register_type(Layout::CType::kSkPMColor4f, { "half4", "float4", "double4" }, "${pdman}.set4fv(${uniform}, ${count}, ${var}.vec())", // to gpu "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}"), // default value register_type(Layout::CType::kSkV4, { "half4", "float4", "double4" }, "${pdman}.set4fv(${uniform}, ${count}, ${var}.ptr())", // to gpu "SkV4{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}", // default value "${oldVar} != (${newVar})"), // dirty check register_array(Layout::CType::kSkPoint, { "half2", "float2", "double2" } , "${pdman}.set2f(${uniform}, ${var}.fX, ${var}.fY)", // single "${pdman}.set2fv(${uniform}, ${count}, &${var}.fX)", // array "SkPoint::Make(SK_FloatNaN, SK_FloatNaN)"), // default value register_array(Layout::CType::kSkIPoint, { "int2", "short2", "byte2" }, "${pdman}.set2i(${uniform}, ${var}.fX, ${var}.fY)", // single "${pdman}.set2iv(${uniform}, ${count}, ${var}.fX, ${var}.fY)", // array "SkIPoint::Make(SK_NaN32, SK_NaN32)"), // default value register_type(Layout::CType::kSkMatrix, { "half3x3", "float3x3", "double3x3" }, "static_assert(${count} == 1); ${pdman}.setSkMatrix(${uniform}, ${var})", // to gpu "SkMatrix::Scale(SK_FloatNaN, SK_FloatNaN)", // default value "!${oldVar}.cheapEqualTo(${newVar})"), // dirty check register_type(Layout::CType::kSkM44, { "half4x4", "float4x4", "double4x4" }, "static_assert(${count} == 1); ${pdman}.setSkM44(${uniform}, ${var})", // to gpu "SkM44(SkM44::kNaN_Constructor)", // default value "${oldVar} != (${newVar})"), // dirty check register_array(Layout::CType::kFloat, { "half", "float", "double" }, "${pdman}.set1f(${uniform}, ${var})", // single "${pdman}.set1fv(${uniform}, ${count}, &${var})", // array "SK_FloatNaN"), // default value register_array(Layout::CType::kInt32, { "int", "short", "byte" }, "${pdman}.set1i(${uniform}, ${var})", // single "${pdman}.set1iv(${uniform}, ${count}, &${var})", // array "SK_NaN32"), // default value }; return registeredMappers; } ///// // Greedy search through registered handlers for one that has a matching // ctype and supports the sksl type of the variable. const UniformCTypeMapper* UniformCTypeMapper::Get(const Context& context, const Type& type, const Layout& layout) { if (type.isArray()) { const UniformCTypeMapper* base = Get(context, type.componentType(), layout); return base ? base->arrayMapper(type.columns()) : nullptr; } const std::vector<UniformCTypeMapper>& registeredMappers = get_mappers(); Layout::CType ctype = layout.fCType; // If there's no custom ctype declared in the layout, use the default type mapping if (ctype == Layout::CType::kDefault) { ctype = HCodeGenerator::ParameterCType(context, type, layout); } const String& skslType = type.name(); for (size_t i = 0; i < registeredMappers.size(); i++) { if (registeredMappers[i].ctype() == ctype) { // Check for sksl support, since some c types (e.g. SkMatrix) can be used in multiple // uniform types and send data to the gpu differently in those conditions const std::vector<String> supportedSKSL = registeredMappers[i].supportedTypeNames(); for (size_t j = 0; j < supportedSKSL.size(); j++) { if (supportedSKSL[j] == skslType) { // Found a match, so return it or an explicitly untracked version if tracking is // disabled in the layout return &registeredMappers[i]; } } } } // Didn't find a match return nullptr; } } // namespace SkSL #endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS <commit_msg>Cleanup pass over UniformCTypeMapper::Get.<commit_after>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/sksl/SkSLCPPUniformCTypes.h" #include "include/private/SkMutex.h" #include "src/sksl/SkSLStringStream.h" #include "src/sksl/codegen/SkSLHCodeGenerator.h" #include <map> #include <vector> #if defined(SKSL_STANDALONE) || GR_TEST_UTILS namespace SkSL { ///////////////////////// // Template evaluation // ///////////////////////// static String eval_template(const String& format, std::initializer_list<String> tokens, std::initializer_list<String> replacements) { SkASSERT(tokens.size() == replacements.size()); String str = format; // Replace every token with its replacement. auto tokenIter = tokens.begin(); auto replacementIter = replacements.begin(); for (; tokenIter != tokens.end(); ++tokenIter, ++replacementIter) { size_t position = 0; for (;;) { // Replace one instance of the current token with the requested replacement. position = str.find(*tokenIter, position); if (position == String::npos) { break; } str.replace(position, tokenIter->size(), *replacementIter); position += replacementIter->size(); } } return str; } static bool determine_inline_from_template(const String& uniformTemplate) { // True if there is at most one instance of the ${var} template matcher in fUniformTemplate. int firstMatch = uniformTemplate.find("${var}"); if (firstMatch < 0) { // Template doesn't use the value variable at all, so it can "inlined" return true; } // Check for another occurrence of ${var}, after firstMatch + 6 int secondMatch = uniformTemplate.find("${var}", firstMatch + strlen("${var}")); // If there's no second match, then the value can be inlined in the c++ code return secondMatch < 0; } /////////////////////////////////////// // UniformCTypeMapper implementation // /////////////////////////////////////// String UniformCTypeMapper::dirtyExpression(const String& newVar, const String& oldVar) const { return eval_template(fDirtyExpressionTemplate, {"${newVar}", "${oldVar}"}, {newVar, oldVar}); } String UniformCTypeMapper::saveState(const String& newVar, const String& oldVar) const { return eval_template(fSaveStateTemplate, {"${newVar}", "${oldVar}"}, {newVar, oldVar}); } String UniformCTypeMapper::setUniform(const String& pdman, const String& uniform, const String& var) const { String count; String finalVar; const String* activeTemplate; if (fArrayCount != -1) { count = to_string(fArrayCount); finalVar = var + "[0]"; activeTemplate = &fUniformArrayTemplate; } else { count = "1"; finalVar = std::move(var); activeTemplate = &fUniformSingleTemplate; } return eval_template(*activeTemplate, {"${pdman}", "${uniform}", "${var}", "${count}"}, {pdman, uniform, finalVar, count}); } UniformCTypeMapper::UniformCTypeMapper( Layout::CType ctype, const std::vector<String>& skslTypes, const String& setUniformSingleFormat, const String& setUniformArrayFormat, const String& defaultValue, const String& dirtyExpressionFormat, const String& saveStateFormat) : fCType(ctype) , fSKSLTypes(skslTypes) , fUniformSingleTemplate(setUniformSingleFormat) , fUniformArrayTemplate(setUniformArrayFormat) , fInlineValue(determine_inline_from_template(setUniformSingleFormat) && determine_inline_from_template(setUniformArrayFormat)) , fDefaultValue(defaultValue) , fDirtyExpressionTemplate(dirtyExpressionFormat) , fSaveStateTemplate(saveStateFormat) {} const UniformCTypeMapper* UniformCTypeMapper::arrayMapper(int count) const { static SkMutex& mutex = *(new SkMutex); SkAutoMutexExclusive guard(mutex); using Key = std::pair<const UniformCTypeMapper*, int>; static std::map<Key, UniformCTypeMapper> registered; Key key(this, count); auto result = registered.find(key); if (result == registered.end()) { auto [iter, didInsert] = registered.insert({key, *this}); SkASSERT(didInsert); UniformCTypeMapper* inserted = &iter->second; inserted->fArrayCount = count; return inserted; } return &result->second; } static UniformCTypeMapper register_array(Layout::CType ctype, const std::vector<String>& skslTypes, const char* singleSet, const char* arraySet, const char* defaultValue, const char* dirtyExpression) { return UniformCTypeMapper(ctype, skslTypes, singleSet, arraySet, defaultValue, dirtyExpression, "${oldVar} = ${newVar}"); } static UniformCTypeMapper register_array(Layout::CType ctype, const std::vector<String>& skslTypes, const char* singleSet, const char* arraySet, const char* defaultValue) { return register_array(ctype, skslTypes, singleSet, arraySet, defaultValue, "${oldVar} != ${newVar}"); } static UniformCTypeMapper register_type(Layout::CType ctype, const std::vector<String>& skslTypes, const char* uniformFormat, const char* defaultValue, const char* dirtyExpression) { return register_array(ctype, skslTypes, uniformFormat, uniformFormat, defaultValue, dirtyExpression); } static UniformCTypeMapper register_type(Layout::CType ctype, const std::vector<String>& skslTypes, const char* uniformFormat, const char* defaultValue) { return register_array(ctype, skslTypes, uniformFormat, uniformFormat, defaultValue); } ////////////////////////////// // Currently defined ctypes // ////////////////////////////// static const std::vector<UniformCTypeMapper>& get_mappers() { static const auto& kRegisteredMappers = *new std::vector<UniformCTypeMapper>{ register_type(Layout::CType::kSkRect, { "half4", "float4", "double4" }, "${pdman}.set4fv(${uniform}, ${count}, reinterpret_cast<const float*>(&${var}))", // to gpu "SkRect::MakeEmpty()", // default value "${oldVar}.isEmpty() || ${oldVar} != ${newVar}"), // dirty check register_type(Layout::CType::kSkIRect, { "int4", "short4", "byte4" }, "${pdman}.set4iv(${uniform}, ${count}, reinterpret_cast<const int*>(&${var}))", // to gpu "SkIRect::MakeEmpty()", // default value "${oldVar}.isEmpty() || ${oldVar} != ${newVar}"), // dirty check register_type(Layout::CType::kSkPMColor4f, { "half4", "float4", "double4" }, "${pdman}.set4fv(${uniform}, ${count}, ${var}.vec())", // to gpu "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}"), // default value register_type(Layout::CType::kSkV4, { "half4", "float4", "double4" }, "${pdman}.set4fv(${uniform}, ${count}, ${var}.ptr())", // to gpu "SkV4{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}", // default value "${oldVar} != (${newVar})"), // dirty check register_array(Layout::CType::kSkPoint, { "half2", "float2", "double2" } , "${pdman}.set2f(${uniform}, ${var}.fX, ${var}.fY)", // single "${pdman}.set2fv(${uniform}, ${count}, &${var}.fX)", // array "SkPoint::Make(SK_FloatNaN, SK_FloatNaN)"), // default value register_array(Layout::CType::kSkIPoint, { "int2", "short2", "byte2" }, "${pdman}.set2i(${uniform}, ${var}.fX, ${var}.fY)", // single "${pdman}.set2iv(${uniform}, ${count}, ${var}.fX, ${var}.fY)", // array "SkIPoint::Make(SK_NaN32, SK_NaN32)"), // default value register_type(Layout::CType::kSkMatrix, { "half3x3", "float3x3", "double3x3" }, "static_assert(${count} == 1); ${pdman}.setSkMatrix(${uniform}, ${var})", // to gpu "SkMatrix::Scale(SK_FloatNaN, SK_FloatNaN)", // default value "!${oldVar}.cheapEqualTo(${newVar})"), // dirty check register_type(Layout::CType::kSkM44, { "half4x4", "float4x4", "double4x4" }, "static_assert(${count} == 1); ${pdman}.setSkM44(${uniform}, ${var})", // to gpu "SkM44(SkM44::kNaN_Constructor)", // default value "${oldVar} != (${newVar})"), // dirty check register_array(Layout::CType::kFloat, { "half", "float", "double" }, "${pdman}.set1f(${uniform}, ${var})", // single "${pdman}.set1fv(${uniform}, ${count}, &${var})", // array "SK_FloatNaN"), // default value register_array(Layout::CType::kInt32, { "int", "short", "byte" }, "${pdman}.set1i(${uniform}, ${var})", // single "${pdman}.set1iv(${uniform}, ${count}, &${var})", // array "SK_NaN32"), // default value }; return kRegisteredMappers; } ///// // Greedy search through registered handlers for one that has a matching // ctype and supports the sksl type of the variable. const UniformCTypeMapper* UniformCTypeMapper::Get(const Context& context, const Type& type, const Layout& layout) { if (type.isArray()) { const UniformCTypeMapper* base = Get(context, type.componentType(), layout); return base ? base->arrayMapper(type.columns()) : nullptr; } const std::vector<UniformCTypeMapper>& registeredMappers = get_mappers(); Layout::CType ctype = layout.fCType; // If there's no custom ctype declared in the layout, use the default type mapping if (ctype == Layout::CType::kDefault) { ctype = HCodeGenerator::ParameterCType(context, type, layout); } for (const UniformCTypeMapper& mapper : registeredMappers) { if (mapper.ctype() == ctype) { // Check for SkSL support, since some C types (e.g. SkMatrix) can be used in multiple // uniform types and send data to the GPU differently depending on the uniform type. for (const String& mapperSupportedType : mapper.supportedTypeNames()) { if (mapperSupportedType == type.name()) { // Return the match that we found. return &mapper; } } } } // Didn't find a match. return nullptr; } } // namespace SkSL #endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS <|endoftext|>
<commit_before>/* * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved. * * 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 "replication.h" #ifdef XAPIAND_CLUSTERING #include "database.h" // for Database #include "database_wal.h" // for DatabaseWAL #include "fs.hh" // for delete_files, build_path_index #include "io.hh" // for io::* #include "length.h" // for serialise_string, unserialise_string #include "manager.h" // for XapiandManager::manager #include "server/binary_client.h" // for BinaryClient // #undef L_DEBUG // #define L_DEBUG L_GREY // #undef L_CALL // #define L_CALL L_STACKED_DIM_GREY // #undef L_REPLICATION // #define L_REPLICATION L_RED // #undef L_CONN // #define L_CONN L_GREEN // #undef L_BINARY_WIRE // #define L_BINARY_WIRE L_ORANGE // #undef L_BINARY // #define L_BINARY L_TEAL // #undef L_BINARY_PROTO // #define L_BINARY_PROTO L_TEAL /* ____ _ _ _ _ * | _ \ ___ _ __ | (_) ___ __ _| |_(_) ___ _ __ * | |_) / _ \ '_ \| | |/ __/ _` | __| |/ _ \| '_ \ * | _ < __/ |_) | | | (_| (_| | |_| | (_) | | | | * |_| \_\___| .__/|_|_|\___\__,_|\__|_|\___/|_| |_| * |_| */ using dispatch_func = void (Replication::*)(const std::string&); Replication::Replication(BinaryClient& client_) : LockableDatabase(), client(client_) { L_OBJ("CREATED REPLICATION OBJ!"); } Replication::~Replication() { if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } if (!switch_database_path.empty()) { delete_files(switch_database_path.c_str()); } L_OBJ("DELETED REPLICATION OBJ!"); } bool Replication::init_replication(const Endpoint &src_endpoint, const Endpoint &dst_endpoint) { L_CALL("Replication::init_replication(%s, %s)", repr(src_endpoint.to_string()), repr(dst_endpoint.to_string())); src_endpoints = Endpoints{src_endpoint}; endpoints = Endpoints{dst_endpoint}; client.temp_directory_template = endpoints[0].path + "/.tmp.XXXXXX"; L_REPLICATION("init_replication: %s --> %s", repr(src_endpoints.to_string()), repr(endpoints.to_string())); return true; } void Replication::send_message(ReplicationReplyType type, const std::string& message) { L_CALL("Replication::send_message(%s, <message>)", ReplicationReplyTypeNames(type)); L_BINARY_PROTO("<< send_message (%s): %s", ReplicationReplyTypeNames(type), repr(message)); client.send_message(toUType(type), message); } void Replication::send_file(ReplicationReplyType type, int fd) { L_CALL("Replication::send_file(%s, <fd>)", ReplicationReplyTypeNames(type)); L_BINARY_PROTO("<< send_file (%s): %d", ReplicationReplyTypeNames(type), fd); client.send_file(toUType(type), fd); } void Replication::replication_server(ReplicationMessageType type, const std::string& message) { L_CALL("Replication::replication_server(%s, <message>)", ReplicationMessageTypeNames(type)); static const dispatch_func dispatch[] = { &Replication::msg_get_changesets, }; if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) { std::string errmsg("Unexpected message type "); errmsg += std::to_string(toUType(type)); THROW(InvalidArgumentError, errmsg); } (this->*(dispatch[static_cast<int>(type)]))(message); } void Replication::msg_get_changesets(const std::string& message) { L_CALL("Replication::msg_get_changesets(<message>)"); L_REPLICATION("Replication::msg_get_changesets"); const char *p = message.c_str(); const char *p_end = p + message.size(); auto remote_uuid = unserialise_string(&p, p_end); auto from_revision = unserialise_length(&p, p_end); auto endpoint_path = unserialise_string(&p, p_end); endpoints = Endpoints{Endpoint{endpoint_path}}; flags = DB_WRITABLE; lock_database lk_db(this); auto uuid = db()->get_uuid(); auto revision = db()->get_revision(); lk_db.unlock(); if (from_revision && uuid != remote_uuid) { from_revision = 0; } DatabaseWAL wal(endpoints[0].path); if (from_revision && wal.locate_revision(from_revision).first == DatabaseWAL::max_rev) { from_revision = 0; } if (from_revision < revision) { if (from_revision == 0) { int whole_db_copies_left = 5; while (true) { // Send the current revision number in the header. send_message(ReplicationReplyType::REPLY_DB_HEADER, serialise_string(uuid) + serialise_length(revision)); static std::array<const std::string, 7> filenames = { "termlist.glass", "synonym.glass", "spelling.glass", "docdata.glass", "position.glass", "postlist.glass", "iamglass" }; for (const auto& filename : filenames) { auto path = endpoints[0].path + "/" + filename; int fd = io::open(path.c_str()); if (fd != -1) { send_message(ReplicationReplyType::REPLY_DB_FILENAME, filename); send_file(ReplicationReplyType::REPLY_DB_FILEDATA, fd); } } lk_db.lock(); auto final_revision = db()->get_revision(); lk_db.unlock(); send_message(ReplicationReplyType::REPLY_DB_FOOTER, serialise_length(final_revision)); if (revision == final_revision) { from_revision = revision; break; } if (whole_db_copies_left == 0) { send_message(ReplicationReplyType::REPLY_FAIL, "Database changing too fast"); return; } else if (--whole_db_copies_left == 0) { lk_db.lock(); uuid = db()->get_uuid(); revision = db()->get_revision(); } else { lk_db.lock(); uuid = db()->get_uuid(); revision = db()->get_revision(); lk_db.unlock(); } } lk_db.unlock(); } int wal_iterations = 5; do { // Send WAL operations. auto wal_it = wal.find(from_revision); for (; wal_it != wal.end(); ++wal_it) { send_message(ReplicationReplyType::REPLY_CHANGESET, wal_it->second); } from_revision = wal_it->first + 1; lk_db.lock(); revision = db()->get_revision(); lk_db.unlock(); } while (from_revision < revision && --wal_iterations != 0); } send_message(ReplicationReplyType::REPLY_END_OF_CHANGES, ""); } void Replication::replication_client(ReplicationReplyType type, const std::string& message) { L_CALL("Replication::replication_client(%s, <message>)", ReplicationReplyTypeNames(type)); static const dispatch_func dispatch[] = { &Replication::reply_welcome, &Replication::reply_end_of_changes, &Replication::reply_fail, &Replication::reply_db_header, &Replication::reply_db_filename, &Replication::reply_db_filedata, &Replication::reply_db_footer, &Replication::reply_changeset, }; if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) { std::string errmsg("Unexpected message type "); errmsg += std::to_string(toUType(type)); THROW(InvalidArgumentError, errmsg); } (this->*(dispatch[static_cast<int>(type)]))(message); } void Replication::reply_welcome(const std::string&) { std::string message; try { flags = DB_WRITABLE; lock_database lk_db(this); message.append(serialise_string(db()->get_uuid())); message.append(serialise_length(db()->get_revision())); message.append(serialise_string(endpoints[0].path)); } catch (const DatabaseNotFoundError&) { message.append(serialise_string("")); message.append(serialise_length(0)); message.append(serialise_string(endpoints[0].path)); } send_message(static_cast<ReplicationReplyType>(SWITCH_TO_REPL), message); } void Replication::reply_end_of_changes(const std::string&) { L_CALL("Replication::reply_end_of_changes(<message>)"); L_REPLICATION("Replication::reply_end_of_changes%s%s", slave_database ? " (checking in slave database)" : "", !switch_database_path.empty() ? " (switching database)" : ""); if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } if (!switch_database_path.empty()) { XapiandManager::manager->database_pool.switch_db(switch_database_path, endpoints[0].path); } L_REPLICATION("Replication completed!"); if (client.cluster_database) { client.cluster_database = false; XapiandManager::manager->cluster_database_ready(); } client.destroy(); client.detach(); } void Replication::reply_fail(const std::string&) { L_CALL("Replication::reply_fail(<message>)"); L_REPLICATION("Replication::reply_fail"); if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } L_ERR("Replication failure!"); client.destroy(); client.detach(); } void Replication::reply_db_header(const std::string& message) { L_CALL("Replication::reply_db_header(<message>)"); L_REPLICATION("Replication::reply_db_header"); const char *p = message.data(); const char *p_end = p + message.size(); current_uuid = unserialise_string(&p, p_end); current_revision = unserialise_length(&p, p_end); if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } if (!switch_database_path.empty()) { delete_files(switch_database_path.c_str()); switch_database_path.clear(); } char path[PATH_MAX]; strncpy(path, client.temp_directory_template.c_str(), PATH_MAX); build_path_index(client.temp_directory_template); if (io::mkdtemp(path) == nullptr) { L_ERR("Directory %s not created: %s (%d): %s", path, io::strerrno(errno), errno, strerror(errno)); client.destroy(); client.detach(); return; } switch_database_path = path; L_REPLICATION("Replication::reply_db_header %s", repr(switch_database_path)); } void Replication::reply_db_filename(const std::string& filename) { L_CALL("Replication::reply_db_filename(<filename>)"); L_REPLICATION("Replication::reply_db_filename"); assert(!switch_database_path.empty()); file_path = switch_database_path + "/" + filename; } void Replication::reply_db_filedata(const std::string& tmp_file) { L_CALL("Replication::reply_db_filedata(<tmp_file>)"); L_REPLICATION("Replication::reply_db_filedata %s -> %s", repr(tmp_file), repr(file_path)); assert(!switch_database_path.empty()); if (::rename(tmp_file.c_str(), file_path.c_str()) == -1) { L_ERR("Cannot rename temporary file %s to %s: %s (%d): %s", tmp_file, file_path, io::strerrno(errno), errno, strerror(errno)); client.destroy(); client.detach(); return; } } void Replication::reply_db_footer(const std::string& message) { L_CALL("Replication::reply_db_footer(<message>)"); const char *p = message.data(); const char *p_end = p + message.size(); size_t revision = unserialise_length(&p, p_end); assert(!switch_database_path.empty()); if (revision != current_revision) { delete_files(switch_database_path.c_str()); switch_database_path.clear(); } L_REPLICATION("Replication::reply_db_footer%s", revision != current_revision ? " (ignored files)" : ""); } void Replication::reply_changeset(const std::string& line) { L_CALL("Replication::reply_changeset(<line>)"); L_REPLICATION("Replication::reply_changeset%s", slave_database ? "" : " (checking out slave database)"); if (!slave_database) { if (!switch_database_path.empty()) { XapiandManager::manager->database_pool.checkout(slave_database, Endpoints{Endpoint{switch_database_path}}, DB_WRITABLE); } else { XapiandManager::manager->database_pool.checkout(slave_database, endpoints, DB_WRITABLE); } slave_database->begin_transaction(false); slave_wal = std::make_unique<DatabaseWAL>(switch_database_path); } slave_wal->execute_line(*slave_database, line, true, false, false); } #endif /* XAPIAND_CLUSTERING */ <commit_msg>Replication: Check endpoint_path is not empty<commit_after>/* * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved. * * 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 "replication.h" #ifdef XAPIAND_CLUSTERING #include "database.h" // for Database #include "database_wal.h" // for DatabaseWAL #include "fs.hh" // for delete_files, build_path_index #include "io.hh" // for io::* #include "length.h" // for serialise_string, unserialise_string #include "manager.h" // for XapiandManager::manager #include "server/binary_client.h" // for BinaryClient // #undef L_DEBUG // #define L_DEBUG L_GREY // #undef L_CALL // #define L_CALL L_STACKED_DIM_GREY // #undef L_REPLICATION // #define L_REPLICATION L_RED // #undef L_CONN // #define L_CONN L_GREEN // #undef L_BINARY_WIRE // #define L_BINARY_WIRE L_ORANGE // #undef L_BINARY // #define L_BINARY L_TEAL // #undef L_BINARY_PROTO // #define L_BINARY_PROTO L_TEAL /* ____ _ _ _ _ * | _ \ ___ _ __ | (_) ___ __ _| |_(_) ___ _ __ * | |_) / _ \ '_ \| | |/ __/ _` | __| |/ _ \| '_ \ * | _ < __/ |_) | | | (_| (_| | |_| | (_) | | | | * |_| \_\___| .__/|_|_|\___\__,_|\__|_|\___/|_| |_| * |_| */ using dispatch_func = void (Replication::*)(const std::string&); Replication::Replication(BinaryClient& client_) : LockableDatabase(), client(client_) { L_OBJ("CREATED REPLICATION OBJ!"); } Replication::~Replication() { if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } if (!switch_database_path.empty()) { delete_files(switch_database_path.c_str()); } L_OBJ("DELETED REPLICATION OBJ!"); } bool Replication::init_replication(const Endpoint &src_endpoint, const Endpoint &dst_endpoint) { L_CALL("Replication::init_replication(%s, %s)", repr(src_endpoint.to_string()), repr(dst_endpoint.to_string())); src_endpoints = Endpoints{src_endpoint}; endpoints = Endpoints{dst_endpoint}; client.temp_directory_template = endpoints[0].path + "/.tmp.XXXXXX"; L_REPLICATION("init_replication: %s --> %s", repr(src_endpoints.to_string()), repr(endpoints.to_string())); return true; } void Replication::send_message(ReplicationReplyType type, const std::string& message) { L_CALL("Replication::send_message(%s, <message>)", ReplicationReplyTypeNames(type)); L_BINARY_PROTO("<< send_message (%s): %s", ReplicationReplyTypeNames(type), repr(message)); client.send_message(toUType(type), message); } void Replication::send_file(ReplicationReplyType type, int fd) { L_CALL("Replication::send_file(%s, <fd>)", ReplicationReplyTypeNames(type)); L_BINARY_PROTO("<< send_file (%s): %d", ReplicationReplyTypeNames(type), fd); client.send_file(toUType(type), fd); } void Replication::replication_server(ReplicationMessageType type, const std::string& message) { L_CALL("Replication::replication_server(%s, <message>)", ReplicationMessageTypeNames(type)); static const dispatch_func dispatch[] = { &Replication::msg_get_changesets, }; if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) { std::string errmsg("Unexpected message type "); errmsg += std::to_string(toUType(type)); THROW(InvalidArgumentError, errmsg); } (this->*(dispatch[static_cast<int>(type)]))(message); } void Replication::msg_get_changesets(const std::string& message) { L_CALL("Replication::msg_get_changesets(<message>)"); L_REPLICATION("Replication::msg_get_changesets"); const char *p = message.c_str(); const char *p_end = p + message.size(); auto remote_uuid = unserialise_string(&p, p_end); auto from_revision = unserialise_length(&p, p_end); auto endpoint_path = unserialise_string(&p, p_end); if (endpoint_path.empty()) { send_message(ReplicationReplyType::REPLY_FAIL, "Database must have a valid path"); } endpoints = Endpoints{Endpoint{endpoint_path}}; flags = DB_WRITABLE; lock_database lk_db(this); auto uuid = db()->get_uuid(); auto revision = db()->get_revision(); lk_db.unlock(); if (from_revision && uuid != remote_uuid) { from_revision = 0; } DatabaseWAL wal(endpoints[0].path); if (from_revision && wal.locate_revision(from_revision).first == DatabaseWAL::max_rev) { from_revision = 0; } if (from_revision < revision) { if (from_revision == 0) { int whole_db_copies_left = 5; while (true) { // Send the current revision number in the header. send_message(ReplicationReplyType::REPLY_DB_HEADER, serialise_string(uuid) + serialise_length(revision)); static std::array<const std::string, 7> filenames = { "termlist.glass", "synonym.glass", "spelling.glass", "docdata.glass", "position.glass", "postlist.glass", "iamglass" }; for (const auto& filename : filenames) { auto path = endpoints[0].path + "/" + filename; int fd = io::open(path.c_str()); if (fd != -1) { send_message(ReplicationReplyType::REPLY_DB_FILENAME, filename); send_file(ReplicationReplyType::REPLY_DB_FILEDATA, fd); } } lk_db.lock(); auto final_revision = db()->get_revision(); lk_db.unlock(); send_message(ReplicationReplyType::REPLY_DB_FOOTER, serialise_length(final_revision)); if (revision == final_revision) { from_revision = revision; break; } if (whole_db_copies_left == 0) { send_message(ReplicationReplyType::REPLY_FAIL, "Database changing too fast"); return; } else if (--whole_db_copies_left == 0) { lk_db.lock(); uuid = db()->get_uuid(); revision = db()->get_revision(); } else { lk_db.lock(); uuid = db()->get_uuid(); revision = db()->get_revision(); lk_db.unlock(); } } lk_db.unlock(); } int wal_iterations = 5; do { // Send WAL operations. auto wal_it = wal.find(from_revision); for (; wal_it != wal.end(); ++wal_it) { send_message(ReplicationReplyType::REPLY_CHANGESET, wal_it->second); } from_revision = wal_it->first + 1; lk_db.lock(); revision = db()->get_revision(); lk_db.unlock(); } while (from_revision < revision && --wal_iterations != 0); } send_message(ReplicationReplyType::REPLY_END_OF_CHANGES, ""); } void Replication::replication_client(ReplicationReplyType type, const std::string& message) { L_CALL("Replication::replication_client(%s, <message>)", ReplicationReplyTypeNames(type)); static const dispatch_func dispatch[] = { &Replication::reply_welcome, &Replication::reply_end_of_changes, &Replication::reply_fail, &Replication::reply_db_header, &Replication::reply_db_filename, &Replication::reply_db_filedata, &Replication::reply_db_footer, &Replication::reply_changeset, }; if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) { std::string errmsg("Unexpected message type "); errmsg += std::to_string(toUType(type)); THROW(InvalidArgumentError, errmsg); } (this->*(dispatch[static_cast<int>(type)]))(message); } void Replication::reply_welcome(const std::string&) { std::string message; try { flags = DB_WRITABLE; lock_database lk_db(this); message.append(serialise_string(db()->get_uuid())); message.append(serialise_length(db()->get_revision())); message.append(serialise_string(endpoints[0].path)); } catch (const DatabaseNotFoundError&) { message.append(serialise_string("")); message.append(serialise_length(0)); message.append(serialise_string(endpoints[0].path)); } send_message(static_cast<ReplicationReplyType>(SWITCH_TO_REPL), message); } void Replication::reply_end_of_changes(const std::string&) { L_CALL("Replication::reply_end_of_changes(<message>)"); L_REPLICATION("Replication::reply_end_of_changes%s%s", slave_database ? " (checking in slave database)" : "", !switch_database_path.empty() ? " (switching database)" : ""); if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } if (!switch_database_path.empty()) { XapiandManager::manager->database_pool.switch_db(switch_database_path, endpoints[0].path); } L_REPLICATION("Replication completed!"); if (client.cluster_database) { client.cluster_database = false; XapiandManager::manager->cluster_database_ready(); } client.destroy(); client.detach(); } void Replication::reply_fail(const std::string&) { L_CALL("Replication::reply_fail(<message>)"); L_REPLICATION("Replication::reply_fail"); if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } L_ERR("Replication failure!"); client.destroy(); client.detach(); } void Replication::reply_db_header(const std::string& message) { L_CALL("Replication::reply_db_header(<message>)"); L_REPLICATION("Replication::reply_db_header"); const char *p = message.data(); const char *p_end = p + message.size(); current_uuid = unserialise_string(&p, p_end); current_revision = unserialise_length(&p, p_end); if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } if (!switch_database_path.empty()) { delete_files(switch_database_path.c_str()); switch_database_path.clear(); } char path[PATH_MAX]; strncpy(path, client.temp_directory_template.c_str(), PATH_MAX); build_path_index(client.temp_directory_template); if (io::mkdtemp(path) == nullptr) { L_ERR("Directory %s not created: %s (%d): %s", path, io::strerrno(errno), errno, strerror(errno)); client.destroy(); client.detach(); return; } switch_database_path = path; L_REPLICATION("Replication::reply_db_header %s", repr(switch_database_path)); } void Replication::reply_db_filename(const std::string& filename) { L_CALL("Replication::reply_db_filename(<filename>)"); L_REPLICATION("Replication::reply_db_filename"); assert(!switch_database_path.empty()); file_path = switch_database_path + "/" + filename; } void Replication::reply_db_filedata(const std::string& tmp_file) { L_CALL("Replication::reply_db_filedata(<tmp_file>)"); L_REPLICATION("Replication::reply_db_filedata %s -> %s", repr(tmp_file), repr(file_path)); assert(!switch_database_path.empty()); if (::rename(tmp_file.c_str(), file_path.c_str()) == -1) { L_ERR("Cannot rename temporary file %s to %s: %s (%d): %s", tmp_file, file_path, io::strerrno(errno), errno, strerror(errno)); client.destroy(); client.detach(); return; } } void Replication::reply_db_footer(const std::string& message) { L_CALL("Replication::reply_db_footer(<message>)"); const char *p = message.data(); const char *p_end = p + message.size(); size_t revision = unserialise_length(&p, p_end); assert(!switch_database_path.empty()); if (revision != current_revision) { delete_files(switch_database_path.c_str()); switch_database_path.clear(); } L_REPLICATION("Replication::reply_db_footer%s", revision != current_revision ? " (ignored files)" : ""); } void Replication::reply_changeset(const std::string& line) { L_CALL("Replication::reply_changeset(<line>)"); L_REPLICATION("Replication::reply_changeset%s", slave_database ? "" : " (checking out slave database)"); if (!slave_database) { if (!switch_database_path.empty()) { XapiandManager::manager->database_pool.checkout(slave_database, Endpoints{Endpoint{switch_database_path}}, DB_WRITABLE); } else { XapiandManager::manager->database_pool.checkout(slave_database, endpoints, DB_WRITABLE); } slave_database->begin_transaction(false); slave_wal = std::make_unique<DatabaseWAL>(switch_database_path); } slave_wal->execute_line(*slave_database, line, true, false, false); } #endif /* XAPIAND_CLUSTERING */ <|endoftext|>
<commit_before>#include "reposition.h" #include "print.h" // The reposition_window function repositions the specified window as if it had been created with CW_USEDEFAULT position. // Step 1. "Create a temporary invisible window with CW_USEDEFAULT as its position and the same height and width as your dialog box." // Step 2. "See where the window manager puts that temporary window and move your dialog box to match that position." // Source: Raymond Chen's blog entry of 22 Nov 2013 7:00 AM, // "How do I get the effect of CW_USEDEFAULT positioning on a window I've already created?" // http://blogs.msdn.com/b/oldnewthing/archive/2013/11/22/10470631.aspx #define WC_REPOSWND TEXT ("p") LRESULT CALLBACK RepositionWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg != WM_NCCREATE) return ::DefWindowProc (hwnd, msg, wParam, lParam); // Step 2. RECT window_rect; ::GetWindowRect (hwnd, & window_rect); int x = window_rect.left; int y = window_rect.top; CREATESTRUCT * cs = (CREATESTRUCT *) lParam; HWND other_hwnd = (HWND) cs->lpCreateParams; ::SetWindowPos (other_hwnd, HWND_TOP, x, y, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOSIZE); return FALSE; // Abort window creation. } void reposition_window (HWND hwnd) { // Step 1. RECT window_rect; ::GetWindowRect (hwnd, & window_rect); int cx = window_rect.right - window_rect.left; int cy = window_rect.bottom - window_rect.top; HINSTANCE hInstance = (HINSTANCE) ::GetWindowLongPtr (hwnd, GWLP_HINSTANCE); WNDCLASS wndclass = { 0, & RepositionWndProc, 0, 0, hInstance, NULL, NULL, NULL, NULL, WC_REPOSWND }; ::RegisterClass (& wndclass); ::CreateWindowEx (0, WC_REPOSWND, TEXT (""), 0, CW_USEDEFAULT, CW_USEDEFAULT, cx, cy, NULL, NULL, hInstance, (LPVOID) hwnd); ::UnregisterClass (WC_REPOSWND, hInstance); } <commit_msg>reposition.cpp: use RegisterClassEx (avoid importing RegisterClass).<commit_after>#include "reposition.h" #include "print.h" // The reposition_window function repositions the specified window as if it had been created with CW_USEDEFAULT position. // Step 1. "Create a temporary invisible window with CW_USEDEFAULT as its position and the same height and width as your dialog box." // Step 2. "See where the window manager puts that temporary window and move your dialog box to match that position." // Source: Raymond Chen's blog entry of 22 Nov 2013 7:00 AM, // "How do I get the effect of CW_USEDEFAULT positioning on a window I've already created?" // http://blogs.msdn.com/b/oldnewthing/archive/2013/11/22/10470631.aspx #define WC_REPOSWND TEXT ("p") LRESULT CALLBACK RepositionWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg != WM_NCCREATE) return ::DefWindowProc (hwnd, msg, wParam, lParam); // Step 2. RECT window_rect; ::GetWindowRect (hwnd, & window_rect); int x = window_rect.left; int y = window_rect.top; CREATESTRUCT * cs = (CREATESTRUCT *) lParam; HWND other_hwnd = (HWND) cs->lpCreateParams; ::SetWindowPos (other_hwnd, HWND_TOP, x, y, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOSIZE); return FALSE; // Abort window creation. } void reposition_window (HWND hwnd) { // Step 1. RECT window_rect; ::GetWindowRect (hwnd, & window_rect); int cx = window_rect.right - window_rect.left; int cy = window_rect.bottom - window_rect.top; HINSTANCE hInstance = (HINSTANCE) ::GetWindowLongPtr (hwnd, GWLP_HINSTANCE); WNDCLASSEX wndclass = { sizeof (WNDCLASSEX), 0, & RepositionWndProc, 0, 0, hInstance, NULL, NULL, NULL, NULL, WC_REPOSWND, NULL }; ::RegisterClassEx (& wndclass); ::CreateWindowEx (0, WC_REPOSWND, TEXT (""), 0, CW_USEDEFAULT, CW_USEDEFAULT, cx, cy, NULL, NULL, hInstance, (LPVOID) hwnd); ::UnregisterClass (WC_REPOSWND, hInstance); } <|endoftext|>
<commit_before>/* Copyright (c) DataStax, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "decoder.hpp" #include "logger.hpp" #include "value.hpp" #define CHECK_REMAINING(SIZE, DETAIL) \ do { \ if (remaining_ < static_cast<size_t>(SIZE)) { \ notify_error(DETAIL, SIZE); \ return false; \ } \ } while (0) using namespace datastax::internal::core; void Decoder::maybe_log_remaining() const { if (remaining_ > 0) { LOG_TRACE("Data remaining in %s response: %u", type_, static_cast<unsigned int>(remaining_)); } } bool Decoder::decode_inet(Address* output) { CHECK_REMAINING(sizeof(uint8_t), "length of inet"); uint8_t address_length = 0; input_ = internal::decode_byte(input_, address_length); remaining_ -= sizeof(uint8_t); if (address_length > CASS_INET_V6_LENGTH) { LOG_ERROR("Invalid inet address length of %d bytes", address_length); return false; } CHECK_REMAINING(address_length, "inet"); uint8_t address[CASS_INET_V6_LENGTH]; memcpy(address, input_, address_length); input_ += address_length; remaining_ -= address_length; CHECK_REMAINING(sizeof(int32_t), "port"); int32_t port = 0; input_ = internal::decode_int32(input_, port); remaining_ -= sizeof(int32_t); *output = Address(address, address_length, port); return output->is_valid_and_resolved(); } bool Decoder::decode_inet(CassInet* output) { CHECK_REMAINING(sizeof(uint8_t), "length of inet"); input_ = internal::decode_byte(input_, output->address_length); remaining_ -= sizeof(uint8_t); if (output->address_length > CASS_INET_V6_LENGTH) { LOG_ERROR("Invalid inet address length of %d bytes", output->address_length); return false; } CHECK_REMAINING(output->address_length, "inet"); memcpy(output->address, input_, output->address_length); input_ += output->address_length; remaining_ -= output->address_length; return true; } bool Decoder::as_inet(const int address_length, CassInet* output) const { output->address_length = static_cast<uint8_t>(address_length); if (output->address_length > CASS_INET_V6_LENGTH) { LOG_ERROR("Invalid inet address length of %d bytes", output->address_length); return false; } CHECK_REMAINING(output->address_length, "inet"); memcpy(output->address, input_, output->address_length); return true; } bool Decoder::decode_write_type(CassWriteType& output) { StringRef write_type; output = CASS_WRITE_TYPE_UNKNOWN; if (!decode_string(&write_type)) return false; if (write_type == "SIMPLE") { output = CASS_WRITE_TYPE_SIMPLE; } else if (write_type == "BATCH") { output = CASS_WRITE_TYPE_BATCH; } else if (write_type == "UNLOGGED_BATCH") { output = CASS_WRITE_TYPE_UNLOGGED_BATCH; } else if (write_type == "COUNTER") { output = CASS_WRITE_TYPE_COUNTER; } else if (write_type == "BATCH_LOG") { output = CASS_WRITE_TYPE_BATCH_LOG; } else if (write_type == "CAS") { output = CASS_WRITE_TYPE_CAS; } else if (write_type == "VIEW") { output = CASS_WRITE_TYPE_VIEW; } else if (write_type == "CDC") { output = CASS_WRITE_TYPE_CDC; } else { LOG_WARN("Invalid write type %.*s", (int)write_type.size(), write_type.data()); return false; } return true; } bool Decoder::decode_warnings(WarningVec& output) { if (remaining_ < sizeof(uint16_t)) { notify_error("count of warnings", sizeof(uint16_t)); return false; } uint16_t count = 0; input_ = internal::decode_uint16(input_, count); remaining_ -= sizeof(uint16_t); for (uint16_t i = 0; i < count; ++i) { StringRef warning; if (!decode_string(&warning)) return false; LOG_WARN("Server-side warning: %.*s", (int)warning.size(), warning.data()); output.push_back(warning); } return true; } Value Decoder::decode_value(const DataType::ConstPtr& data_type) { int32_t size = 0; if (!decode_int32(size)) return Value(); if (size >= 0) { Decoder decoder(input_, size, protocol_version_); input_ += size; remaining_ -= size; int32_t count = 0; if (data_type->is_collection() && !decoder.decode_int32(count)) { return Value(); } return Value(data_type, count, decoder); } return Value(data_type); } void Decoder::notify_error(const char* detail, size_t bytes) const { if (strlen(type_) == 0) { LOG_ERROR("Expected at least %u byte%s to decode %s value", static_cast<unsigned int>(bytes), (bytes > 1 ? "s" : ""), detail); } else { LOG_ERROR("Expected at least %u byte%s to decode %s %s response", static_cast<unsigned int>(bytes), (bytes > 1 ? "s" : ""), detail, type_); } } <commit_msg>- fix UDT Value hitting the correct ctor (#509)<commit_after>/* Copyright (c) DataStax, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "decoder.hpp" #include "logger.hpp" #include "value.hpp" #define CHECK_REMAINING(SIZE, DETAIL) \ do { \ if (remaining_ < static_cast<size_t>(SIZE)) { \ notify_error(DETAIL, SIZE); \ return false; \ } \ } while (0) using namespace datastax::internal::core; void Decoder::maybe_log_remaining() const { if (remaining_ > 0) { LOG_TRACE("Data remaining in %s response: %u", type_, static_cast<unsigned int>(remaining_)); } } bool Decoder::decode_inet(Address* output) { CHECK_REMAINING(sizeof(uint8_t), "length of inet"); uint8_t address_length = 0; input_ = internal::decode_byte(input_, address_length); remaining_ -= sizeof(uint8_t); if (address_length > CASS_INET_V6_LENGTH) { LOG_ERROR("Invalid inet address length of %d bytes", address_length); return false; } CHECK_REMAINING(address_length, "inet"); uint8_t address[CASS_INET_V6_LENGTH]; memcpy(address, input_, address_length); input_ += address_length; remaining_ -= address_length; CHECK_REMAINING(sizeof(int32_t), "port"); int32_t port = 0; input_ = internal::decode_int32(input_, port); remaining_ -= sizeof(int32_t); *output = Address(address, address_length, port); return output->is_valid_and_resolved(); } bool Decoder::decode_inet(CassInet* output) { CHECK_REMAINING(sizeof(uint8_t), "length of inet"); input_ = internal::decode_byte(input_, output->address_length); remaining_ -= sizeof(uint8_t); if (output->address_length > CASS_INET_V6_LENGTH) { LOG_ERROR("Invalid inet address length of %d bytes", output->address_length); return false; } CHECK_REMAINING(output->address_length, "inet"); memcpy(output->address, input_, output->address_length); input_ += output->address_length; remaining_ -= output->address_length; return true; } bool Decoder::as_inet(const int address_length, CassInet* output) const { output->address_length = static_cast<uint8_t>(address_length); if (output->address_length > CASS_INET_V6_LENGTH) { LOG_ERROR("Invalid inet address length of %d bytes", output->address_length); return false; } CHECK_REMAINING(output->address_length, "inet"); memcpy(output->address, input_, output->address_length); return true; } bool Decoder::decode_write_type(CassWriteType& output) { StringRef write_type; output = CASS_WRITE_TYPE_UNKNOWN; if (!decode_string(&write_type)) return false; if (write_type == "SIMPLE") { output = CASS_WRITE_TYPE_SIMPLE; } else if (write_type == "BATCH") { output = CASS_WRITE_TYPE_BATCH; } else if (write_type == "UNLOGGED_BATCH") { output = CASS_WRITE_TYPE_UNLOGGED_BATCH; } else if (write_type == "COUNTER") { output = CASS_WRITE_TYPE_COUNTER; } else if (write_type == "BATCH_LOG") { output = CASS_WRITE_TYPE_BATCH_LOG; } else if (write_type == "CAS") { output = CASS_WRITE_TYPE_CAS; } else if (write_type == "VIEW") { output = CASS_WRITE_TYPE_VIEW; } else if (write_type == "CDC") { output = CASS_WRITE_TYPE_CDC; } else { LOG_WARN("Invalid write type %.*s", (int)write_type.size(), write_type.data()); return false; } return true; } bool Decoder::decode_warnings(WarningVec& output) { if (remaining_ < sizeof(uint16_t)) { notify_error("count of warnings", sizeof(uint16_t)); return false; } uint16_t count = 0; input_ = internal::decode_uint16(input_, count); remaining_ -= sizeof(uint16_t); for (uint16_t i = 0; i < count; ++i) { StringRef warning; if (!decode_string(&warning)) return false; LOG_WARN("Server-side warning: %.*s", (int)warning.size(), warning.data()); output.push_back(warning); } return true; } Value Decoder::decode_value(const DataType::ConstPtr& data_type) { int32_t size = 0; if (!decode_int32(size)) return Value(); if (size >= 0) { Decoder decoder(input_, size, protocol_version_); input_ += size; remaining_ -= size; int32_t count = 0; if (!data_type->is_collection()) { return Value(data_type, decoder); } else if (decoder.decode_int32(count)) { return Value(data_type, count, decoder); } return Value(); } return Value(data_type); } void Decoder::notify_error(const char* detail, size_t bytes) const { if (strlen(type_) == 0) { LOG_ERROR("Expected at least %u byte%s to decode %s value", static_cast<unsigned int>(bytes), (bytes > 1 ? "s" : ""), detail); } else { LOG_ERROR("Expected at least %u byte%s to decode %s %s response", static_cast<unsigned int>(bytes), (bytes > 1 ? "s" : ""), detail, type_); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLProperty.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include <math.h> #include "vtkOpenGLRenderer.h" #include "vtkOpenGLProperty.h" #include <math.h> #include "vtkOpenGLRenderer.h" #include "vtkOpenGLProperty.h" #ifndef VTK_IMPLEMENT_MESA_CXX #if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA)) #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #endif #include "vtkObjectFactory.h" #include "vtkToolkits.h" // for VTK_USE_GL2PS #ifdef VTK_USE_GL2PS #include "gl2ps.h" #include "vtkGL2PSExporter.h" #endif // VTK_USE_GL2PS #ifndef VTK_IMPLEMENT_MESA_CXX vtkCxxRevisionMacro(vtkOpenGLProperty, "1.29"); vtkStandardNewMacro(vtkOpenGLProperty); #endif // Implement base class method. void vtkOpenGLProperty::Render(vtkActor *vtkNotUsed(anActor), vtkRenderer *vtkNotUsed(ren)) { int i; GLenum method; float Info[4]; GLenum Face; double color[4]; // unbind any textures for starters glDisable(GL_TEXTURE_2D); // disable alpha testing (this may have been enabled // by another actor in OpenGLTexture) glDisable (GL_ALPHA_TEST); glDisable(GL_COLOR_MATERIAL); Face = GL_FRONT_AND_BACK; // turn on/off backface culling if ( ! this->BackfaceCulling && ! this->FrontfaceCulling) { glDisable (GL_CULL_FACE); } else if ( this->BackfaceCulling) { glCullFace (GL_BACK); glEnable (GL_CULL_FACE); } else //if both front & back culling on, will fall into backface culling { //if you really want both front and back, use the Actor's visibility flag glCullFace (GL_FRONT); glEnable (GL_CULL_FACE); } Info[3] = this->Opacity; for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Ambient*this->AmbientColor[i]); } glMaterialfv( Face, GL_AMBIENT, Info ); for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Diffuse*this->DiffuseColor[i]); } glMaterialfv( Face, GL_DIFFUSE, Info ); for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Specular*this->SpecularColor[i]); } glMaterialfv( Face, GL_SPECULAR, Info ); Info[0] = static_cast<float>(this->SpecularPower); glMaterialfv( Face, GL_SHININESS, Info ); // set interpolation switch (this->Interpolation) { case VTK_FLAT: method = GL_FLAT; break; case VTK_GOURAUD: case VTK_PHONG: method = GL_SMOOTH; break; default: method = GL_SMOOTH; break; } glShadeModel(method); // The material properties set above are used if shading is // enabled. This color set here is used if shading is // disabled. Shading is disabled in the // vtkOpenGLPolyDataMapper::Draw() method if points or lines // are encountered without normals. this->GetColor( color ); color[3] = this->Opacity; glColor4dv( color ); // Set the PointSize glPointSize (this->PointSize); // Set the LineWidth glLineWidth (this->LineWidth); // Set pointsize and linewidth for GL2PS output. #ifdef VTK_USE_GL2PS gl2psPointSize(this->PointSize* vtkGL2PSExporter::GetGlobalPointSizeFactor()); gl2psLineWidth(this->LineWidth* vtkGL2PSExporter::GetGlobalLineWidthFactor()); #endif // VTK_USE_GL2PS // Set the LineStipple if (this->LineStipplePattern != 0xFFFF) { glEnable (GL_LINE_STIPPLE); #ifdef VTK_USE_GL2PS gl2psEnable(GL2PS_LINE_STIPPLE); #endif // VTK_USE_GL2PS glLineStipple (this->LineStippleRepeatFactor, this->LineStipplePattern); } else { glDisable (GL_LINE_STIPPLE); #ifdef VTK_USE_GL2PS gl2psDisable(GL2PS_LINE_STIPPLE); #endif // VTK_USE_GL2PS } } // Implement base class method. void vtkOpenGLProperty::BackfaceRender(vtkActor *vtkNotUsed(anActor), vtkRenderer *vtkNotUsed(ren)) { int i; float Info[4]; GLenum Face; Face = GL_BACK; Info[3] = this->Opacity; for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Ambient*this->AmbientColor[i]); } glMaterialfv( Face, GL_AMBIENT, Info ); for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Diffuse*this->DiffuseColor[i]); } glMaterialfv( Face, GL_DIFFUSE, Info ); for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Specular*this->SpecularColor[i]); } glMaterialfv( Face, GL_SPECULAR, Info ); Info[0] = static_cast<float>(this->SpecularPower); glMaterialfv( Face, GL_SHININESS, Info ); } //---------------------------------------------------------------------------- void vtkOpenGLProperty::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } <commit_msg>STYLE: Remove duplicate include file, thanks to Aurélien Regat-Barrel from vtkusers ML.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLProperty.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include <math.h> #include "vtkOpenGLRenderer.h" #include "vtkOpenGLProperty.h" #ifndef VTK_IMPLEMENT_MESA_CXX #if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA)) #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #endif #include "vtkObjectFactory.h" #include "vtkToolkits.h" // for VTK_USE_GL2PS #ifdef VTK_USE_GL2PS #include "gl2ps.h" #include "vtkGL2PSExporter.h" #endif // VTK_USE_GL2PS #ifndef VTK_IMPLEMENT_MESA_CXX vtkCxxRevisionMacro(vtkOpenGLProperty, "1.30"); vtkStandardNewMacro(vtkOpenGLProperty); #endif // Implement base class method. void vtkOpenGLProperty::Render(vtkActor *vtkNotUsed(anActor), vtkRenderer *vtkNotUsed(ren)) { int i; GLenum method; float Info[4]; GLenum Face; double color[4]; // unbind any textures for starters glDisable(GL_TEXTURE_2D); // disable alpha testing (this may have been enabled // by another actor in OpenGLTexture) glDisable (GL_ALPHA_TEST); glDisable(GL_COLOR_MATERIAL); Face = GL_FRONT_AND_BACK; // turn on/off backface culling if ( ! this->BackfaceCulling && ! this->FrontfaceCulling) { glDisable (GL_CULL_FACE); } else if ( this->BackfaceCulling) { glCullFace (GL_BACK); glEnable (GL_CULL_FACE); } else //if both front & back culling on, will fall into backface culling { //if you really want both front and back, use the Actor's visibility flag glCullFace (GL_FRONT); glEnable (GL_CULL_FACE); } Info[3] = this->Opacity; for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Ambient*this->AmbientColor[i]); } glMaterialfv( Face, GL_AMBIENT, Info ); for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Diffuse*this->DiffuseColor[i]); } glMaterialfv( Face, GL_DIFFUSE, Info ); for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Specular*this->SpecularColor[i]); } glMaterialfv( Face, GL_SPECULAR, Info ); Info[0] = static_cast<float>(this->SpecularPower); glMaterialfv( Face, GL_SHININESS, Info ); // set interpolation switch (this->Interpolation) { case VTK_FLAT: method = GL_FLAT; break; case VTK_GOURAUD: case VTK_PHONG: method = GL_SMOOTH; break; default: method = GL_SMOOTH; break; } glShadeModel(method); // The material properties set above are used if shading is // enabled. This color set here is used if shading is // disabled. Shading is disabled in the // vtkOpenGLPolyDataMapper::Draw() method if points or lines // are encountered without normals. this->GetColor( color ); color[3] = this->Opacity; glColor4dv( color ); // Set the PointSize glPointSize (this->PointSize); // Set the LineWidth glLineWidth (this->LineWidth); // Set pointsize and linewidth for GL2PS output. #ifdef VTK_USE_GL2PS gl2psPointSize(this->PointSize* vtkGL2PSExporter::GetGlobalPointSizeFactor()); gl2psLineWidth(this->LineWidth* vtkGL2PSExporter::GetGlobalLineWidthFactor()); #endif // VTK_USE_GL2PS // Set the LineStipple if (this->LineStipplePattern != 0xFFFF) { glEnable (GL_LINE_STIPPLE); #ifdef VTK_USE_GL2PS gl2psEnable(GL2PS_LINE_STIPPLE); #endif // VTK_USE_GL2PS glLineStipple (this->LineStippleRepeatFactor, this->LineStipplePattern); } else { glDisable (GL_LINE_STIPPLE); #ifdef VTK_USE_GL2PS gl2psDisable(GL2PS_LINE_STIPPLE); #endif // VTK_USE_GL2PS } } // Implement base class method. void vtkOpenGLProperty::BackfaceRender(vtkActor *vtkNotUsed(anActor), vtkRenderer *vtkNotUsed(ren)) { int i; float Info[4]; GLenum Face; Face = GL_BACK; Info[3] = this->Opacity; for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Ambient*this->AmbientColor[i]); } glMaterialfv( Face, GL_AMBIENT, Info ); for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Diffuse*this->DiffuseColor[i]); } glMaterialfv( Face, GL_DIFFUSE, Info ); for (i=0; i < 3; i++) { Info[i] = static_cast<float>(this->Specular*this->SpecularColor[i]); } glMaterialfv( Face, GL_SPECULAR, Info ); Info[0] = static_cast<float>(this->SpecularPower); glMaterialfv( Face, GL_SHININESS, Info ); } //---------------------------------------------------------------------------- void vtkOpenGLProperty::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } <|endoftext|>
<commit_before>//----------------------------------*-C++-*----------------------------------// /** * @file MGSolverGMRES.i.hh * @author robertsj * @date Jun 19, 2012 * @brief MGSolverGMRES inline member definitions. */ //---------------------------------------------------------------------------// #ifndef detran_MGSOLVERGMRES_I_HH_ #define detran_MGSOLVERGMRES_I_HH_ #include "utilities/MathUtilities.hh" #include <algorithm> #include <cstdio> #include <iostream> #include <cstring> namespace detran { //---------------------------------------------------------------------------// template <class D> inline void MGSolverGMRES<D>::solve(const double keff) { using std::cout; using std::endl; double norm_resid = 0.0; int iteration = 0; //-------------------------------------------------------------------------// // GAUSS-SEIDEL BLOCK //-------------------------------------------------------------------------// for (int g = 0; g < d_krylov_group_cutoff; g++) { d_wg_solver->solve(g); } //-------------------------------------------------------------------------// // KRYLOV BLOCK //-------------------------------------------------------------------------// if (d_number_active_groups) { //-----------------------------------------------------------------------// // BUILD RIGHT HAND SIDE //-----------------------------------------------------------------------// State::vec_moments_type B(d_number_active_groups, State::moments_type(d_moments_size_group, 0.0)); build_rhs(B); //-----------------------------------------------------------------------// // SOLVE MULTIGROUP TRANSPORT EQUATION //-----------------------------------------------------------------------// d_x->copy(d_b); d_solver->solve(*d_b, *d_x); //-----------------------------------------------------------------------// // POST-PROCESS //-----------------------------------------------------------------------// // Copy the flux solution into state. for (int g = d_krylov_group_cutoff; g < d_number_groups; g++) { int offset = (g - d_krylov_group_cutoff) * d_moments_size_group; memcpy(&d_state->phi(g)[0], &((*d_x)[offset]), d_moments_size_group*sizeof(double)); } // Set the incident boundary flux if applicable if (d_boundary->has_reflective()) { for (int g = d_krylov_group_cutoff; g < d_number_groups; g++) { int offset = (g - d_krylov_group_cutoff) * d_boundary_size_group + d_moments_size_group * d_number_active_groups; d_boundary->psi(g, &(*d_x)[offset], BoundaryBase<D>::IN, BoundaryBase<D>::SET, true); } } // Iterate to pick up outgoing boundary fluxes. Only do this if // there is at least one vacuum boundary. Otherwise, the // boundary fluxes are never going to be needed. if (d_update_boundary_flux) { //d_boundary->clear_bc(); for (int g = d_krylov_group_cutoff; g < d_number_groups; g++) { d_boundary->set(g); State::moments_type phi_g = d_state->phi(g); d_sweeper->setup_group(g); d_sweepsource->reset(); d_sweepsource->build_fixed_with_scatter(g); d_sweepsource->build_within_group_scatter(g, phi_g); solve_wg_reflection(g, phi_g); } } } // end krylov block // Diagnostic output if (d_print_level > 0) { printf(" MGSolverGMRES Final: Number Iters: %3i Error: %12.9f Sweeps: %6i \n", iteration, norm_resid, d_sweeper->number_sweeps()); } if (norm_resid > d_tolerance) { detran_utilities::warning(detran_utilities::SOLVER_CONVERGENCE, " MGSolverGMRES did not converge."); } } // end solve //---------------------------------------------------------------------------// template <class D> inline void MGSolverGMRES<D>::build_rhs(State::vec_moments_type &B) { // Perform a group sweep group_sweep(B); // Fill the source vector for (int g = 0; g < d_number_active_groups; g++) { int offset = g * d_moments_size_group; for (int i = 0; i < d_moments_size_group; i++) (*d_b)[i + offset] = B[g][i]; } } //---------------------------------------------------------------------------// template <class D> inline void MGSolverGMRES<D>:: group_sweep(State::vec_moments_type &phi) { for (int g = d_krylov_group_cutoff; g < d_number_groups; g++) { int g_index = g - d_krylov_group_cutoff; // Setup the sweeper. d_sweeper->setup_group(g); // Clear the group boundary and set with any fixed conditions. d_boundary->clear(g); d_boundary->set(g); // Build the fixed source. For fixed source problems, this // includes external sources and any in-scatter from groups // solved by Gauss-Seidel. For eigenproblems, fission is // also included. d_sweepsource->reset(); d_sweepsource->build_fixed_with_downscatter(g, d_krylov_group_cutoff); // If no reflective, one sweep and out. Otherwise, iterate. if (!d_boundary->has_reflective()) d_sweeper->sweep(phi[g_index]); else solve_wg_reflection(g, phi[g_index]); } } //---------------------------------------------------------------------------// template <class D> inline void MGSolverGMRES<D>:: solve_wg_reflection(size_t g, State::moments_type &phi_g) { // Create dummy moment container for convergence. State::moments_type phi_g_old(phi_g.size(), 0.0); // Set sweeper to update boundaries on the fly. d_sweeper->set_update_boundary(true); // Iterate on the reflective conditions int iteration; double error = 0; for (iteration = 0; iteration < 2000; iteration++) { // Update boundary. This updates boundaries due to reflection. d_boundary->update(g); // Swap old and new. std::swap(phi_g, phi_g_old); // Sweep d_sweeper->sweep(phi_g); // Compute residual and check convergence error = detran_utilities::norm_residual(phi_g_old, phi_g, "Linf"); if (error < d_tolerance) break; } d_reflective_solve_iterations += iteration; // Switch sweeper back to not updating boundaries d_sweeper->set_update_boundary(false); } } // end namespace detran #endif /* detran_MGSOLVERGMRES_I_HH_ */ //---------------------------------------------------------------------------// // end of MGSolverGMRES.i.hh //---------------------------------------------------------------------------// <commit_msg>Added line to set the fission source scaling factor to the MG Krylov solver routine. It was not updated keff previously.<commit_after>//----------------------------------*-C++-*----------------------------------// /** * @file MGSolverGMRES.i.hh * @author robertsj * @date Jun 19, 2012 * @brief MGSolverGMRES inline member definitions. */ //---------------------------------------------------------------------------// #ifndef detran_MGSOLVERGMRES_I_HH_ #define detran_MGSOLVERGMRES_I_HH_ #include "utilities/MathUtilities.hh" #include <algorithm> #include <cstdio> #include <iostream> #include <cstring> namespace detran { //---------------------------------------------------------------------------// template <class D> inline void MGSolverGMRES<D>::solve(const double keff) { using std::cout; using std::endl; double norm_resid = 0.0; int iteration = 0; // Set the scaling factor for multiplying problems if (d_multiply) d_fissionsource->setup_outer(1.0/keff); //-------------------------------------------------------------------------// // GAUSS-SEIDEL BLOCK //-------------------------------------------------------------------------// for (int g = 0; g < d_krylov_group_cutoff; g++) { d_wg_solver->solve(g); } //-------------------------------------------------------------------------// // KRYLOV BLOCK //-------------------------------------------------------------------------// if (d_number_active_groups) { //-----------------------------------------------------------------------// // BUILD RIGHT HAND SIDE //-----------------------------------------------------------------------// State::vec_moments_type B(d_number_active_groups, State::moments_type(d_moments_size_group, 0.0)); build_rhs(B); //-----------------------------------------------------------------------// // SOLVE MULTIGROUP TRANSPORT EQUATION //-----------------------------------------------------------------------// d_x->copy(d_b); d_solver->solve(*d_b, *d_x); //-----------------------------------------------------------------------// // POST-PROCESS //-----------------------------------------------------------------------// // Copy the flux solution into state. for (int g = d_krylov_group_cutoff; g < d_number_groups; g++) { int offset = (g - d_krylov_group_cutoff) * d_moments_size_group; memcpy(&d_state->phi(g)[0], &((*d_x)[offset]), d_moments_size_group*sizeof(double)); } // Set the incident boundary flux if applicable if (d_boundary->has_reflective()) { for (int g = d_krylov_group_cutoff; g < d_number_groups; g++) { int offset = (g - d_krylov_group_cutoff) * d_boundary_size_group + d_moments_size_group * d_number_active_groups; d_boundary->psi(g, &(*d_x)[offset], BoundaryBase<D>::IN, BoundaryBase<D>::SET, true); } } // Iterate to pick up outgoing boundary fluxes. Only do this if // there is at least one vacuum boundary. Otherwise, the // boundary fluxes are never going to be needed. if (d_update_boundary_flux) { //d_boundary->clear_bc(); for (int g = d_krylov_group_cutoff; g < d_number_groups; g++) { d_boundary->set(g); State::moments_type phi_g = d_state->phi(g); d_sweeper->setup_group(g); d_sweepsource->reset(); d_sweepsource->build_fixed_with_scatter(g); d_sweepsource->build_within_group_scatter(g, phi_g); solve_wg_reflection(g, phi_g); } } } // end krylov block // Diagnostic output if (d_print_level > 0) { printf(" MGSolverGMRES Final: Number Iters: %3i Error: %12.9f Sweeps: %6i \n", iteration, norm_resid, d_sweeper->number_sweeps()); } if (norm_resid > d_tolerance) { detran_utilities::warning(detran_utilities::SOLVER_CONVERGENCE, " MGSolverGMRES did not converge."); } } // end solve //---------------------------------------------------------------------------// template <class D> inline void MGSolverGMRES<D>::build_rhs(State::vec_moments_type &B) { // Perform a group sweep group_sweep(B); // Fill the source vector for (int g = 0; g < d_number_active_groups; g++) { int offset = g * d_moments_size_group; for (int i = 0; i < d_moments_size_group; i++) (*d_b)[i + offset] = B[g][i]; } } //---------------------------------------------------------------------------// template <class D> inline void MGSolverGMRES<D>:: group_sweep(State::vec_moments_type &phi) { for (int g = d_krylov_group_cutoff; g < d_number_groups; g++) { int g_index = g - d_krylov_group_cutoff; // Setup the sweeper. d_sweeper->setup_group(g); // Clear the group boundary and set with any fixed conditions. d_boundary->clear(g); d_boundary->set(g); // Build the fixed source. For fixed source problems, this // includes external sources and any in-scatter from groups // solved by Gauss-Seidel. For eigenproblems, fission is // also included. d_sweepsource->reset(); d_sweepsource->build_fixed_with_downscatter(g, d_krylov_group_cutoff); // If no reflective, one sweep and out. Otherwise, iterate. if (!d_boundary->has_reflective()) d_sweeper->sweep(phi[g_index]); else solve_wg_reflection(g, phi[g_index]); } } //---------------------------------------------------------------------------// template <class D> inline void MGSolverGMRES<D>:: solve_wg_reflection(size_t g, State::moments_type &phi_g) { // Create dummy moment container for convergence. State::moments_type phi_g_old(phi_g.size(), 0.0); // Set sweeper to update boundaries on the fly. d_sweeper->set_update_boundary(true); // Iterate on the reflective conditions int iteration; double error = 0; for (iteration = 0; iteration < 2000; iteration++) { // Update boundary. This updates boundaries due to reflection. d_boundary->update(g); // Swap old and new. std::swap(phi_g, phi_g_old); // Sweep d_sweeper->sweep(phi_g); // Compute residual and check convergence error = detran_utilities::norm_residual(phi_g_old, phi_g, "Linf"); if (error < d_tolerance) break; } d_reflective_solve_iterations += iteration; // Switch sweeper back to not updating boundaries d_sweeper->set_update_boundary(false); } } // end namespace detran #endif /* detran_MGSOLVERGMRES_I_HH_ */ //---------------------------------------------------------------------------// // end of MGSolverGMRES.i.hh //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>/*********************************************************************************************************************** * * * SPLASH build system v0.2 * * * * Copyright (c) 2016 Andrew D. Zonenberg * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashcore.h" using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction /** @brief Default constructor (for non-targets) TODO: how do we use this? Disallow? */ BuildGraphNode::BuildGraphNode() : m_ref(false) , m_job(NULL) , m_finalizationStarted(false) , m_finalized(false) { //Set initial hash to something bogus just so we can be unique in the graph before finalizing char tmp[128]; snprintf(tmp, sizeof(tmp), "%p", this); m_hash = sha256(tmp); } /** @brief Constructor for nodes which are source files */ BuildGraphNode::BuildGraphNode( BuildGraph* graph, BuildFlag::FlagUsage usage, string path, string hash) : m_ref(false) , m_graph(graph) , m_toolchain("") , m_toolchainHash("") , m_hash(hash) , m_arch("generic") , m_config("generic") , m_name(GetBasenameOfFile(path)) , m_script("") , m_path(path) , m_invalidInput(false) , m_usage(usage) , m_job(NULL) , m_finalizationStarted(false) , m_finalized(false) { } /** @brief Constructor for nodes which are object files or equivalent */ BuildGraphNode::BuildGraphNode( BuildGraph* graph, BuildFlag::FlagUsage usage, string toolchain, string arch, string name, string path, set<BuildFlag> flags) : m_ref(false) , m_graph(graph) , m_toolchain(toolchain) , m_arch(arch) , m_config("generic") , m_name(name) , m_script("") , m_path(path) , m_flags(flags) , m_invalidInput(false) , m_usage(usage) , m_job(NULL) , m_finalizationStarted(false) , m_finalized(false) { //Look up the hash of our toolchain m_toolchainHash = g_nodeManager->GetToolchainHash(m_arch, m_toolchain); //Set initial hash to something bogus just so we can be unique in the graph before finalizing char tmp[128]; snprintf(tmp, sizeof(tmp), "%p", this); m_hash = sha256(tmp); } /** @brief Constructor for nodes which are targets or tests */ BuildGraphNode::BuildGraphNode( BuildGraph* graph, BuildFlag::FlagUsage usage, string toolchain, string arch, string config, string name, string scriptpath, string path, YAML::Node& node) : m_ref(false) , m_graph(graph) , m_toolchain(toolchain) , m_arch(arch) , m_config(config) , m_name(name) , m_script(scriptpath) , m_path(path) , m_usage(usage) , m_job(NULL) , m_finalizationStarted(false) , m_finalized(false) { //Ignore the toolchain and arches sections, they're already taken care of //Read the flags section if(node["flags"]) { auto nflags = node["flags"]; for(auto it : nflags) { //If the flag is "global" pull in the upstream flags string flag = it.as<std::string>(); if(flag == "global") graph->GetFlags(toolchain, config, path, m_flags); else m_flags.emplace(BuildFlag(flag)); } } //No flags specified, import base flags else graph->GetFlags(toolchain, config, path, m_flags); //anything else is handled in base class (source files etc) //Look up the hash of our toolchain m_toolchainHash = g_nodeManager->GetToolchainHash(m_arch, m_toolchain); //Set initial hash to something bogus just so we can be unique in the graph before finalizing char tmp[128]; snprintf(tmp, sizeof(tmp), "%p", this); m_hash = sha256(tmp); } BuildGraphNode::~BuildGraphNode() { //If we have a job, we no longer need if if(m_job != NULL) { m_job->Unref(); m_job = NULL; } } /** @brief Begin finalizing the node This involves kicking off scan jobs, etc but does not block. */ void BuildGraphNode::StartFinalization() { lock_guard<recursive_mutex> lock(m_mutex); //If we already got scanned, nothing to do if(m_finalizationStarted) return; m_finalizationStarted = true; //See if we are in the working copy. //If we're not pointed to by the WC then we're an old version and should NOT be updated //(since we're probably about to get GC'd) if(m_hash != m_graph->GetWorkingCopy()->GetFileHash(GetFilePath())) return; //Go tell the derived class to prep scan jobs DoStartFinalization(); } /** @brief Finalize this node This involves running all dependency scans, etc. as well as computing the node's hash. Blocks until scans have finished. */ void BuildGraphNode::Finalize() { lock_guard<recursive_mutex> lock(m_mutex); //See if we are in the working copy. //If we're not pointed to by the WC then we're an old version and should NOT be updated //(since we're probably about to get GC'd) if(m_hash != m_graph->GetWorkingCopy()->GetFileHash(GetFilePath())) return; //If nobody started the scan jobs etc, do that now if(!m_finalizationStarted) StartFinalization(); //Block until finalization is done string old_hash = m_hash; if(!m_finalized) { DoFinalize(); m_graph->FinalizeCallback(this, old_hash); } m_finalized = true; //Update the records for us in the working copy m_graph->GetWorkingCopy()->UpdateFile(GetFilePath(), m_hash, false, false); } /** @brief Default implementation. Not declared pure virtual since many nodes won't need any heavy lifting (blocking is OK). All nodes that push scan jobs out to the cluster should take care of that here, though. */ void BuildGraphNode::DoStartFinalization() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GC reference marking /** @brief Mark the node as referenced */ void BuildGraphNode::SetRef() { lock_guard<recursive_mutex> lock(m_mutex); if(m_ref) return; m_ref = true; //Mark our dependencies as referenced (if they're not already) //Sources are a subset of dependencies, no need to process that auto wc = m_graph->GetWorkingCopy(); for(auto x : m_dependencies) { auto h = wc->GetFileHash(x); if(m_graph->HasNodeWithHash(h)) m_graph->GetNodeWithHash(h)->SetRef(); else { LogError( "Node %s (with hash %s) is a dependency of us\n" "(%s), but not in graph\n", x.c_str(), h.c_str(), GetFilePath().c_str()); } } } /// @brief Mark the node as unreferenced (do not propagate) void BuildGraphNode::SetUnref() { lock_guard<recursive_mutex> lock(m_mutex); m_ref = false; } /// @brief Checks if the node is referenced (do not propagate) bool BuildGraphNode::IsReferenced() { lock_guard<recursive_mutex> lock(m_mutex); return m_ref; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Accessors string BuildGraphNode::GetIndent(int level) { string ret; for(int i=0; i<level; i++) ret += " "; return ret; } void BuildGraphNode::PrintInfo(int indentLevel) { lock_guard<recursive_mutex> lock(m_mutex); string padded_path = GetIndent(indentLevel) + m_path; LogDebug("%-85s [%s]\n", padded_path.c_str(), m_hash.c_str()); for(auto d : m_dependencies) m_graph->GetNodeWithPath(d)->PrintInfo(indentLevel + 1); } /** @brief Figures out what flags are applicable to a particular point in the build process */ void BuildGraphNode::GetFlagsForUseAt( BuildFlag::FlagUsage when, set<BuildFlag>& flags) { lock_guard<recursive_mutex> lock(m_mutex); for(auto f : m_flags) { if(f.IsUsedAt(when)) flags.emplace(f); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Building /** @brief Actually start building this node */ Job* BuildGraphNode::Build(Job::Priority prio) { lock_guard<recursive_mutex> lock(m_mutex); //If we're already building, return a new reference to the existing job if(m_job != NULL) { m_job->Ref(); return m_job; } //Create a new job for us //Ref it again (implicit creation ref for us, second ref for the caller) m_job = new BuildJob(prio, m_usage, this, m_toolchainHash); m_job->Ref(); //Build each of our dependencies, if needed set<Job*> deps; auto wc = m_graph->GetWorkingCopy(); for(auto d : m_dependencies) { //Look up the graph node auto h = wc->GetFileHash(d); if(h == "") { LogError("Dependency \"%s\" is not in working copy\n", d.c_str()); return NULL; } auto n = m_graph->GetNodeWithHash(h); if(n == this) { LogError("BuildGraphNode %s depends on itself!\n", d.c_str()); continue; } //If the node has already been built, no action required auto state = n->GetOutputState(); if(state == NodeInfo::READY) continue; //If the build failed, die now if(state == NodeInfo::FAILED) { LogError("Dependency \"%s\" failed to build, we cannot be built\n", d.c_str()); g_cache->AddFailedFile(GetFilePath(), m_hash, "ERROR: Unable to build due to failed inputs\n"); return NULL; } //If not, build it deps.emplace(n->Build()); } //Add dependencies to our job for(auto j : deps) m_job->AddDependency(j); //Submit the job to the scheduler g_scheduler->SubmitJob(m_job); //and done return m_job; } <commit_msg>splashcore: Don't create BuildGraphNode::m_job until we know dependencies are building, otherwise Bad Things happen (not returning null next time someone tries to build us)<commit_after>/*********************************************************************************************************************** * * * SPLASH build system v0.2 * * * * Copyright (c) 2016 Andrew D. Zonenberg * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashcore.h" using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction /** @brief Default constructor (for non-targets) TODO: how do we use this? Disallow? */ BuildGraphNode::BuildGraphNode() : m_ref(false) , m_job(NULL) , m_finalizationStarted(false) , m_finalized(false) { //Set initial hash to something bogus just so we can be unique in the graph before finalizing char tmp[128]; snprintf(tmp, sizeof(tmp), "%p", this); m_hash = sha256(tmp); } /** @brief Constructor for nodes which are source files */ BuildGraphNode::BuildGraphNode( BuildGraph* graph, BuildFlag::FlagUsage usage, string path, string hash) : m_ref(false) , m_graph(graph) , m_toolchain("") , m_toolchainHash("") , m_hash(hash) , m_arch("generic") , m_config("generic") , m_name(GetBasenameOfFile(path)) , m_script("") , m_path(path) , m_invalidInput(false) , m_usage(usage) , m_job(NULL) , m_finalizationStarted(false) , m_finalized(false) { } /** @brief Constructor for nodes which are object files or equivalent */ BuildGraphNode::BuildGraphNode( BuildGraph* graph, BuildFlag::FlagUsage usage, string toolchain, string arch, string name, string path, set<BuildFlag> flags) : m_ref(false) , m_graph(graph) , m_toolchain(toolchain) , m_arch(arch) , m_config("generic") , m_name(name) , m_script("") , m_path(path) , m_flags(flags) , m_invalidInput(false) , m_usage(usage) , m_job(NULL) , m_finalizationStarted(false) , m_finalized(false) { //Look up the hash of our toolchain m_toolchainHash = g_nodeManager->GetToolchainHash(m_arch, m_toolchain); //Set initial hash to something bogus just so we can be unique in the graph before finalizing char tmp[128]; snprintf(tmp, sizeof(tmp), "%p", this); m_hash = sha256(tmp); } /** @brief Constructor for nodes which are targets or tests */ BuildGraphNode::BuildGraphNode( BuildGraph* graph, BuildFlag::FlagUsage usage, string toolchain, string arch, string config, string name, string scriptpath, string path, YAML::Node& node) : m_ref(false) , m_graph(graph) , m_toolchain(toolchain) , m_arch(arch) , m_config(config) , m_name(name) , m_script(scriptpath) , m_path(path) , m_usage(usage) , m_job(NULL) , m_finalizationStarted(false) , m_finalized(false) { //Ignore the toolchain and arches sections, they're already taken care of //Read the flags section if(node["flags"]) { auto nflags = node["flags"]; for(auto it : nflags) { //If the flag is "global" pull in the upstream flags string flag = it.as<std::string>(); if(flag == "global") graph->GetFlags(toolchain, config, path, m_flags); else m_flags.emplace(BuildFlag(flag)); } } //No flags specified, import base flags else graph->GetFlags(toolchain, config, path, m_flags); //anything else is handled in base class (source files etc) //Look up the hash of our toolchain m_toolchainHash = g_nodeManager->GetToolchainHash(m_arch, m_toolchain); //Set initial hash to something bogus just so we can be unique in the graph before finalizing char tmp[128]; snprintf(tmp, sizeof(tmp), "%p", this); m_hash = sha256(tmp); } BuildGraphNode::~BuildGraphNode() { //If we have a job, we no longer need if if(m_job != NULL) { m_job->Unref(); m_job = NULL; } } /** @brief Begin finalizing the node This involves kicking off scan jobs, etc but does not block. */ void BuildGraphNode::StartFinalization() { lock_guard<recursive_mutex> lock(m_mutex); //If we already got scanned, nothing to do if(m_finalizationStarted) return; m_finalizationStarted = true; //See if we are in the working copy. //If we're not pointed to by the WC then we're an old version and should NOT be updated //(since we're probably about to get GC'd) if(m_hash != m_graph->GetWorkingCopy()->GetFileHash(GetFilePath())) return; //Go tell the derived class to prep scan jobs DoStartFinalization(); } /** @brief Finalize this node This involves running all dependency scans, etc. as well as computing the node's hash. Blocks until scans have finished. */ void BuildGraphNode::Finalize() { lock_guard<recursive_mutex> lock(m_mutex); //See if we are in the working copy. //If we're not pointed to by the WC then we're an old version and should NOT be updated //(since we're probably about to get GC'd) if(m_hash != m_graph->GetWorkingCopy()->GetFileHash(GetFilePath())) return; //If nobody started the scan jobs etc, do that now if(!m_finalizationStarted) StartFinalization(); //Block until finalization is done string old_hash = m_hash; if(!m_finalized) { DoFinalize(); m_graph->FinalizeCallback(this, old_hash); } m_finalized = true; //Update the records for us in the working copy m_graph->GetWorkingCopy()->UpdateFile(GetFilePath(), m_hash, false, false); } /** @brief Default implementation. Not declared pure virtual since many nodes won't need any heavy lifting (blocking is OK). All nodes that push scan jobs out to the cluster should take care of that here, though. */ void BuildGraphNode::DoStartFinalization() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GC reference marking /** @brief Mark the node as referenced */ void BuildGraphNode::SetRef() { lock_guard<recursive_mutex> lock(m_mutex); if(m_ref) return; m_ref = true; //Mark our dependencies as referenced (if they're not already) //Sources are a subset of dependencies, no need to process that auto wc = m_graph->GetWorkingCopy(); for(auto x : m_dependencies) { auto h = wc->GetFileHash(x); if(m_graph->HasNodeWithHash(h)) m_graph->GetNodeWithHash(h)->SetRef(); else { LogError( "Node %s (with hash %s) is a dependency of us\n" "(%s), but not in graph\n", x.c_str(), h.c_str(), GetFilePath().c_str()); } } } /// @brief Mark the node as unreferenced (do not propagate) void BuildGraphNode::SetUnref() { lock_guard<recursive_mutex> lock(m_mutex); m_ref = false; } /// @brief Checks if the node is referenced (do not propagate) bool BuildGraphNode::IsReferenced() { lock_guard<recursive_mutex> lock(m_mutex); return m_ref; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Accessors string BuildGraphNode::GetIndent(int level) { string ret; for(int i=0; i<level; i++) ret += " "; return ret; } void BuildGraphNode::PrintInfo(int indentLevel) { lock_guard<recursive_mutex> lock(m_mutex); string padded_path = GetIndent(indentLevel) + m_path; LogDebug("%-85s [%s]\n", padded_path.c_str(), m_hash.c_str()); for(auto d : m_dependencies) m_graph->GetNodeWithPath(d)->PrintInfo(indentLevel + 1); } /** @brief Figures out what flags are applicable to a particular point in the build process */ void BuildGraphNode::GetFlagsForUseAt( BuildFlag::FlagUsage when, set<BuildFlag>& flags) { lock_guard<recursive_mutex> lock(m_mutex); for(auto f : m_flags) { if(f.IsUsedAt(when)) flags.emplace(f); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Building /** @brief Actually start building this node */ Job* BuildGraphNode::Build(Job::Priority prio) { lock_guard<recursive_mutex> lock(m_mutex); //If we're already building, return a new reference to the existing job if(m_job != NULL) { m_job->Ref(); return m_job; } //Build each of our dependencies, if needed set<Job*> deps; auto wc = m_graph->GetWorkingCopy(); for(auto d : m_dependencies) { //Look up the graph node auto h = wc->GetFileHash(d); if(h == "") { LogError("Dependency \"%s\" is not in working copy\n", d.c_str()); return NULL; } auto n = m_graph->GetNodeWithHash(h); if(n == this) { LogError("BuildGraphNode %s depends on itself!\n", d.c_str()); continue; } //If the node has already been built, no action required auto state = n->GetOutputState(); if(state == NodeInfo::READY) continue; //If the build failed, die now if(state == NodeInfo::FAILED) { LogError("Dependency \"%s\" failed to build, we cannot be built\n", d.c_str()); g_cache->AddFailedFile(GetFilePath(), m_hash, "ERROR: Unable to build due to failed inputs\n"); return NULL; } //If not, build it deps.emplace(n->Build()); } //Create a new job for us //Ref it again (implicit creation ref for us, second ref for the caller) m_job = new BuildJob(prio, m_usage, this, m_toolchainHash); m_job->Ref(); //Add dependencies to our job for(auto j : deps) m_job->AddDependency(j); //Submit the job to the scheduler g_scheduler->SubmitJob(m_job); //and done return m_job; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <HFO.hpp> #include <cstdlib> using namespace std; using namespace hfo; // Before running this program, first Start HFO server: // $> ./bin/HFO --offense-agents 1 // Server Connection Options. See printouts from bin/HFO. feature_set_t features = LOW_LEVEL_FEATURE_SET; string config_dir = "bin/teams/base/config/formations-dt"; int port = 6000; string server_addr = "localhost"; string team_name = "base_left"; bool goalie = true; int main() { // Create the HFO environment HFOEnvironment hfo; // Connect to the server and request low-level feature set. See // manual for more information on feature sets. hfo.connectToServer(features, config_dir, port, server_addr, team_name, goalie); // Play 5 episodes for (int episode=0; episode<5; episode++) { status_t status = IN_GAME; while (status == IN_GAME) { // Get the vector of state features for the current state const std::vector<float>& feature_vec = hfo.getState(); // Perform the dash hfo.act(DASH, 20.0, 0.0); // Advance the environment and recieve current game status status = hfo.step(); } // Check what the outcome of the episode was cout << "Episode " << episode << " ended with status: " << StatusToString(status) << std::endl;; } hfo.act(QUIT); }; <commit_msg>disabled goalie on example agent.<commit_after>#include <iostream> #include <vector> #include <HFO.hpp> #include <cstdlib> using namespace std; using namespace hfo; // Before running this program, first Start HFO server: // $> ./bin/HFO --offense-agents 1 // Server Connection Options. See printouts from bin/HFO. feature_set_t features = LOW_LEVEL_FEATURE_SET; string config_dir = "bin/teams/base/config/formations-dt"; int port = 6000; string server_addr = "localhost"; string team_name = "base_left"; bool goalie = false; int main() { // Create the HFO environment HFOEnvironment hfo; // Connect to the server and request low-level feature set. See // manual for more information on feature sets. hfo.connectToServer(features, config_dir, port, server_addr, team_name, goalie); // Play 5 episodes for (int episode=0; episode<5; episode++) { status_t status = IN_GAME; while (status == IN_GAME) { // Get the vector of state features for the current state const std::vector<float>& feature_vec = hfo.getState(); // Perform the dash hfo.act(DASH, 20.0, 0.0); // Advance the environment and recieve current game status status = hfo.step(); } // Check what the outcome of the episode was cout << "Episode " << episode << " ended with status: " << StatusToString(status) << std::endl;; } hfo.act(QUIT); }; <|endoftext|>
<commit_before>// // gclass.cpp // etc // // Created by Oleksii Tiurenkov on 9/30/15. // Copyright (c) 2015 Oleksii Tiurenkov. All rights reserved. // #include "gclass.h" #include <fstream> #include <iostream> #include <algorithm> #include "GLOBAL_CONST.h" using namespace std; std::string random_string( size_t length ) { auto randchar = []() -> char { const char charset[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); return charset[ rand() % max_index ]; }; std::string str(length,0); std::generate_n( str.begin(), length, randchar ); return str; } Gclass* Gclass::loadFromFile(std::string dir, std::string filename) { Gclass* result = nullptr; //open file ifstream infile(dir+filename, ios_base::binary|ios_base::in|ios::ate); //if file opened if (infile.is_open()) { //get file size size_t buffersize =infile.tellg(); //create buffer char* bufferArray = new char[buffersize]; //return to file start infile.seekg(ios::beg); //read all from file infile.read(bufferArray, buffersize); //close file infile.close(); result = new Gclass; size_t bufferlength = buffersize/sizeof(shima_t); shima_t* shimaBuffer = reinterpret_cast<shima_t*>(bufferArray); result->internalArray.assign(shimaBuffer, shimaBuffer + bufferlength); //save file name result->filename = filename; delete [] bufferArray; } return result; } bool Gclass::save(std::string dir) { bool result = false; ofstream outfile(dir + filename, ios_base::binary|ios_base::out|ios::trunc); if (outfile.is_open()) { shima_t* shimaBuffer = new shima_t[internalArray.size()]; std::copy(internalArray.begin(),internalArray.end(),shimaBuffer); outfile.write(reinterpret_cast<char*>(shimaBuffer), internalArray.size() * sizeof(shima_t)); outfile.close(); result = true; } else { cerr << "Error:" << strerror(errno) << endl; cout << "Error opening file"; } return result; } void Gclass::saveJSON(std::string dir) { ostringstream realfileName; realfileName << dir << score << "-" << filename << ".json"; ofstream outfile(realfileName.str(), ios_base::out|ios::trunc); if (outfile.is_open()) { Fleet* fleet = fleetCreate(); outfile << fleet->json(score); delete fleet; outfile.close(); } else { cerr << "Error:" << strerror(errno) << endl; cout << "Error opening file"; } } void Gclass::mutation() { for (int i = 0; i < internalArray.size(); i++) { if (RADIATION > (rand()%MAX_SCALE)) { internalArray[i]^= 1 << rand()%(sizeof(shima_t)*8); } } //insert random gene if (RADIATION > (rand()%MAX_SCALE)) { size_t position = internalArray.size() != 0 ?rand()%internalArray.size() : 0; shima_t shima = rand(); internalArray.insert(internalArray.begin() + position,shima); } //Swap two or delete if ((internalArray.size() > 1) && (RADIATION > (rand()%MAX_SCALE))) { size_t position1 = rand()%internalArray.size(); size_t position2 = rand()%internalArray.size(); if(position1 == position2) { internalArray.erase(internalArray.begin()+position1); } else { std::iter_swap(internalArray.begin() + position1, internalArray.begin() + position2); } } } Fleet* Gclass::fleetCreate() const { return new Fleet(internalArray); } Gclass* Gclass::empty() { Gclass* result = new Gclass; result->internalArray.push_back(0); result->filename = random_string(16); return result; } bool Gclass::betterThan(const Gclass *other) const { return score > other->score; } size_t randomMedium(size_t length) { long result = length/2 + (RADIATION > (rand()%MAX_SCALE)?rand()%3 -1 :0 ); result = result > 0? result:0; result = length < result? length: result; return result; } Gclass* Gclass::crossover(Gclass *gene) { size_t myGenes = randomMedium(internalArray.size()); size_t theirsGenes = randomMedium(gene->internalArray.size()); Gclass* result = new Gclass; if (rand()%2) { for(auto it = internalArray.begin(); it != internalArray.begin()+myGenes && it != internalArray.end(); it++) result->internalArray.push_back(*it); for(auto it = gene->internalArray.end() - theirsGenes; it != gene->internalArray.end(); it++) result->internalArray.push_back(*it); } else { for(auto it = gene->internalArray.begin(); it != gene->internalArray.begin()+theirsGenes && it != gene->internalArray.end(); it++) result->internalArray.push_back(*it); for(auto it = internalArray.end() - myGenes; it != internalArray.end(); it++) result->internalArray.push_back(*it); } result->filename = random_string(16); result->mutation(); return result; } void Gclass::deleteGene(std::string dir) { remove((dir + filename).c_str()); } void Gclass::compare(Gclass* other) { auto myFleet = fleetCreate(); auto otherFleet = other->fleetCreate(); switch (myFleet->result(otherFleet)) { case WIN: score+=3; break; case DRAW: score+=1; other->score+=1; break; case FAIL: other->score+=3; break; default: break; } delete myFleet; delete otherFleet; } void Gclass::print() { auto fleet = fleetCreate(); fleet->print(); delete fleet; } void Gclass::clearScore() { score = 0; } <commit_msg>Fixed cstring<commit_after>// // gclass.cpp // etc // // Created by Oleksii Tiurenkov on 9/30/15. // Copyright (c) 2015 Oleksii Tiurenkov. All rights reserved. // #include "gclass.h" #include <fstream> #include <iostream> #include <algorithm> #include <cstring> #include "GLOBAL_CONST.h" using namespace std; std::string random_string( size_t length ) { auto randchar = []() -> char { const char charset[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); return charset[ rand() % max_index ]; }; std::string str(length,0); std::generate_n( str.begin(), length, randchar ); return str; } Gclass* Gclass::loadFromFile(std::string dir, std::string filename) { Gclass* result = nullptr; //open file ifstream infile(dir+filename, ios_base::binary|ios_base::in|ios::ate); //if file opened if (infile.is_open()) { //get file size size_t buffersize =infile.tellg(); //create buffer char* bufferArray = new char[buffersize]; //return to file start infile.seekg(ios::beg); //read all from file infile.read(bufferArray, buffersize); //close file infile.close(); result = new Gclass; size_t bufferlength = buffersize/sizeof(shima_t); shima_t* shimaBuffer = reinterpret_cast<shima_t*>(bufferArray); result->internalArray.assign(shimaBuffer, shimaBuffer + bufferlength); //save file name result->filename = filename; delete [] bufferArray; } return result; } bool Gclass::save(std::string dir) { bool result = false; ofstream outfile(dir + filename, ios_base::binary|ios_base::out|ios::trunc); if (outfile.is_open()) { shima_t* shimaBuffer = new shima_t[internalArray.size()]; std::copy(internalArray.begin(),internalArray.end(),shimaBuffer); outfile.write(reinterpret_cast<char*>(shimaBuffer), internalArray.size() * sizeof(shima_t)); outfile.close(); result = true; } else { cerr << "Error:" << strerror(errno) << endl; cout << "Error opening file"; } return result; } void Gclass::saveJSON(std::string dir) { ostringstream realfileName; realfileName << dir << score << "-" << filename << ".json"; ofstream outfile(realfileName.str(), ios_base::out|ios::trunc); if (outfile.is_open()) { Fleet* fleet = fleetCreate(); outfile << fleet->json(score); delete fleet; outfile.close(); } else { cerr << "Error:" << strerror(errno) << endl; cout << "Error opening file"; } } void Gclass::mutation() { for (int i = 0; i < internalArray.size(); i++) { if (RADIATION > (rand()%MAX_SCALE)) { internalArray[i]^= 1 << rand()%(sizeof(shima_t)*8); } } //insert random gene if (RADIATION > (rand()%MAX_SCALE)) { size_t position = internalArray.size() != 0 ?rand()%internalArray.size() : 0; shima_t shima = rand(); internalArray.insert(internalArray.begin() + position,shima); } //Swap two or delete if ((internalArray.size() > 1) && (RADIATION > (rand()%MAX_SCALE))) { size_t position1 = rand()%internalArray.size(); size_t position2 = rand()%internalArray.size(); if(position1 == position2) { internalArray.erase(internalArray.begin()+position1); } else { std::iter_swap(internalArray.begin() + position1, internalArray.begin() + position2); } } } Fleet* Gclass::fleetCreate() const { return new Fleet(internalArray); } Gclass* Gclass::empty() { Gclass* result = new Gclass; result->internalArray.push_back(0); result->filename = random_string(16); return result; } bool Gclass::betterThan(const Gclass *other) const { return score > other->score; } size_t randomMedium(size_t length) { long result = length/2 + (RADIATION > (rand()%MAX_SCALE)?rand()%3 -1 :0 ); result = result > 0? result:0; result = length < result? length: result; return result; } Gclass* Gclass::crossover(Gclass *gene) { size_t myGenes = randomMedium(internalArray.size()); size_t theirsGenes = randomMedium(gene->internalArray.size()); Gclass* result = new Gclass; if (rand()%2) { for(auto it = internalArray.begin(); it != internalArray.begin()+myGenes && it != internalArray.end(); it++) result->internalArray.push_back(*it); for(auto it = gene->internalArray.end() - theirsGenes; it != gene->internalArray.end(); it++) result->internalArray.push_back(*it); } else { for(auto it = gene->internalArray.begin(); it != gene->internalArray.begin()+theirsGenes && it != gene->internalArray.end(); it++) result->internalArray.push_back(*it); for(auto it = internalArray.end() - myGenes; it != internalArray.end(); it++) result->internalArray.push_back(*it); } result->filename = random_string(16); result->mutation(); return result; } void Gclass::deleteGene(std::string dir) { remove((dir + filename).c_str()); } void Gclass::compare(Gclass* other) { auto myFleet = fleetCreate(); auto otherFleet = other->fleetCreate(); switch (myFleet->result(otherFleet)) { case WIN: score+=3; break; case DRAW: score+=1; other->score+=1; break; case FAIL: other->score+=3; break; default: break; } delete myFleet; delete otherFleet; } void Gclass::print() { auto fleet = fleetCreate(); fleet->print(); delete fleet; } void Gclass::clearScore() { score = 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/graphics/Pipeline.hpp> #include <swift2d/application/Application.hpp> #include <swift2d/components/DrawableComponent.hpp> #include <swift2d/components/CameraComponent.hpp> #include <swift2d/graphics/Window.hpp> #include <swift2d/settings/SettingsWrapper.hpp> #include <swift2d/utils/Logger.hpp> #include <swift2d/physics.hpp> #include <thread> #include <oglplus/bound/texture.hpp> #include <oglplus/bound/framebuffer.hpp> namespace swift { //////////////////////////////////////////////////////////////////////////////// Pipeline::Pipeline() : compositor_(nullptr) , max_load_amount_(-1) , current_load_amount_(0) , needs_reload_(true) , frame_time_(0) , total_time_(0) { SettingsWrapper::get().Settings->DynamicLighting.on_change().connect([this](int) { needs_reload_ = true; return true; }); SettingsWrapper::get().Settings->SubSampling.on_change().connect([this](bool) { needs_reload_ = true; return true; }); SettingsWrapper::get().Settings->LightSubSampling.on_change().connect([this](bool) { needs_reload_ = true; return true; }); SettingsWrapper::get().Settings->LensFlares.on_change().connect([this](bool) { needs_reload_ = true; return true; }); SettingsWrapper::get().Settings->HeatEffect.on_change().connect([this](bool) { needs_reload_ = true; return true; }); //SettingsWrapper::get().Settings->Fullscreen.on_change().connect([this](bool) { // needs_reload_ = true; // return true; //}); timer_.start(); } //////////////////////////////////////////////////////////////////////////////// Pipeline::~Pipeline() { if (compositor_) delete compositor_; Physics::get().clear_gravity_map(window_->get_context()); for (auto sub_sampler: sub_samplers_) { if (sub_sampler) { delete sub_sampler; } } } //////////////////////////////////////////////////////////////////////////////// void Pipeline::set_output_window(WindowPtr const& window) { window_ = window; window_->on_size_change.connect([this](math::vec2i){ needs_reload_ = true; return true; }); } //////////////////////////////////////////////////////////////////////////////// void Pipeline::update() { if (max_load_amount_ == -1) { Application::get().LoadingProgress = 1.f; } else { Application::get().LoadingProgress = 1.f - 1.0f * current_load_amount_ / max_load_amount_; } } //////////////////////////////////////////////////////////////////////////////// void Pipeline::draw(ConstSerializedScenePtr const& scene) { if (!window_->Minimized()) { SWIFT_PUSH_GL_RANGE("Frame"); // create & update window window_->set_active(true); window_->update_context(); // update window size if (needs_reload_) { window_->get_context().pipeline = this; if (window_->get_context().sub_sampling) { window_->get_context().g_buffer_size = window_->get_context().window_size / 2; } else { window_->get_context().g_buffer_size = window_->get_context().window_size; } Physics::get().create_gravity_map(window_->get_context()); if (compositor_) { delete compositor_; compositor_ = nullptr; } compositor_ = new Compositor(window_->get_context()); for (auto sub_sampler : sub_samplers_) { if (sub_sampler) { delete sub_sampler; } } sub_samplers_.clear(); needs_reload_ = false; } frame_time_ = timer_.reset(); total_time_ += frame_time_; auto& ctx(window_->get_context()); // setup projection matrix math::mat3 view_matrix(scene->camera->WorldTransform.get()); math::scale(view_matrix, scene->camera->Size.get()); ctx.projection_matrix = math::inversed(view_matrix); ctx.projection_parallax = scene->camera->Parallax(); ctx.upload_budget = 1; ctx.upload_remaining = 0; // compute gravity SWIFT_PUSH_GL_RANGE("Update gravity map"); Physics::get().update_gravity_map(scene, ctx); SWIFT_POP_GL_RANGE(); // draw opaque objects SWIFT_PUSH_GL_RANGE("Draw objects"); compositor_->draw_objects(scene, ctx); SWIFT_POP_GL_RANGE(); // draw lights SWIFT_PUSH_GL_RANGE("Draw lights"); compositor_->draw_lights(scene, ctx); SWIFT_POP_GL_RANGE(); // perform post processing SWIFT_PUSH_GL_RANGE("Post process"); compositor_->post_process(scene, ctx); SWIFT_POP_GL_RANGE(); // draw user interface SWIFT_PUSH_GL_RANGE("Draw GUI"); compositor_->draw_gui(scene, ctx); SWIFT_POP_GL_RANGE(); // update loading state if (ctx.upload_remaining > max_load_amount_) { max_load_amount_ = ctx.upload_remaining; } current_load_amount_ = ctx.upload_remaining; if (current_load_amount_ == 0) { max_load_amount_ = -1; } SWIFT_POP_GL_RANGE(); // finish frame window_->display(); } } //////////////////////////////////////////////////////////////////////////////// double Pipeline::get_total_time() const { return total_time_; } //////////////////////////////////////////////////////////////////////////////// double Pipeline::get_frame_time() const { return frame_time_; } //////////////////////////////////////////////////////////////////////////////// SubSampler* Pipeline::get_sub_sampler(int level) { int index = level - 2; if (sub_samplers_.size() > index && sub_samplers_[index] != nullptr) { return sub_samplers_[index]; } if (sub_samplers_.size() <= index) { sub_samplers_.resize(index+1); } sub_samplers_[index] = new SubSampler(window_->get_context(), level); return sub_samplers_[index]; } //////////////////////////////////////////////////////////////////////////////// } <commit_msg>fix non minimized windows<commit_after>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/graphics/Pipeline.hpp> #include <swift2d/application/Application.hpp> #include <swift2d/components/DrawableComponent.hpp> #include <swift2d/components/CameraComponent.hpp> #include <swift2d/graphics/Window.hpp> #include <swift2d/settings/SettingsWrapper.hpp> #include <swift2d/utils/Logger.hpp> #include <swift2d/physics.hpp> #include <thread> #include <oglplus/bound/texture.hpp> #include <oglplus/bound/framebuffer.hpp> namespace swift { //////////////////////////////////////////////////////////////////////////////// Pipeline::Pipeline() : compositor_(nullptr) , max_load_amount_(-1) , current_load_amount_(0) , needs_reload_(true) , frame_time_(0) , total_time_(0) { SettingsWrapper::get().Settings->DynamicLighting.on_change().connect([this](int) { needs_reload_ = true; return true; }); SettingsWrapper::get().Settings->SubSampling.on_change().connect([this](bool) { needs_reload_ = true; return true; }); SettingsWrapper::get().Settings->LightSubSampling.on_change().connect([this](bool) { needs_reload_ = true; return true; }); SettingsWrapper::get().Settings->LensFlares.on_change().connect([this](bool) { needs_reload_ = true; return true; }); SettingsWrapper::get().Settings->HeatEffect.on_change().connect([this](bool) { needs_reload_ = true; return true; }); //SettingsWrapper::get().Settings->Fullscreen.on_change().connect([this](bool) { // needs_reload_ = true; // return true; //}); timer_.start(); } //////////////////////////////////////////////////////////////////////////////// Pipeline::~Pipeline() { if (compositor_) delete compositor_; Physics::get().clear_gravity_map(window_->get_context()); for (auto sub_sampler: sub_samplers_) { if (sub_sampler) { delete sub_sampler; } } } //////////////////////////////////////////////////////////////////////////////// void Pipeline::set_output_window(WindowPtr const& window) { window_ = window; window_->on_size_change.connect([this](math::vec2i){ needs_reload_ = true; return true; }); } //////////////////////////////////////////////////////////////////////////////// void Pipeline::update() { if (max_load_amount_ == -1) { Application::get().LoadingProgress = 1.f; } else { Application::get().LoadingProgress = 1.f - 1.0f * current_load_amount_ / max_load_amount_; } } //////////////////////////////////////////////////////////////////////////////// void Pipeline::draw(ConstSerializedScenePtr const& scene) { // create & update window window_->set_active(true); window_->update_context(); if (!window_->Minimized()) { SWIFT_PUSH_GL_RANGE("Frame"); // update window size if (needs_reload_) { window_->get_context().pipeline = this; if (window_->get_context().sub_sampling) { window_->get_context().g_buffer_size = window_->get_context().window_size / 2; } else { window_->get_context().g_buffer_size = window_->get_context().window_size; } Physics::get().create_gravity_map(window_->get_context()); if (compositor_) { delete compositor_; compositor_ = nullptr; } compositor_ = new Compositor(window_->get_context()); for (auto sub_sampler : sub_samplers_) { if (sub_sampler) { delete sub_sampler; } } sub_samplers_.clear(); needs_reload_ = false; } frame_time_ = timer_.reset(); total_time_ += frame_time_; auto& ctx(window_->get_context()); // setup projection matrix math::mat3 view_matrix(scene->camera->WorldTransform.get()); math::scale(view_matrix, scene->camera->Size.get()); ctx.projection_matrix = math::inversed(view_matrix); ctx.projection_parallax = scene->camera->Parallax(); ctx.upload_budget = 1; ctx.upload_remaining = 0; // compute gravity SWIFT_PUSH_GL_RANGE("Update gravity map"); Physics::get().update_gravity_map(scene, ctx); SWIFT_POP_GL_RANGE(); // draw opaque objects SWIFT_PUSH_GL_RANGE("Draw objects"); compositor_->draw_objects(scene, ctx); SWIFT_POP_GL_RANGE(); // draw lights SWIFT_PUSH_GL_RANGE("Draw lights"); compositor_->draw_lights(scene, ctx); SWIFT_POP_GL_RANGE(); // perform post processing SWIFT_PUSH_GL_RANGE("Post process"); compositor_->post_process(scene, ctx); SWIFT_POP_GL_RANGE(); // draw user interface SWIFT_PUSH_GL_RANGE("Draw GUI"); compositor_->draw_gui(scene, ctx); SWIFT_POP_GL_RANGE(); // update loading state if (ctx.upload_remaining > max_load_amount_) { max_load_amount_ = ctx.upload_remaining; } current_load_amount_ = ctx.upload_remaining; if (current_load_amount_ == 0) { max_load_amount_ = -1; } SWIFT_POP_GL_RANGE(); // finish frame window_->display(); } } //////////////////////////////////////////////////////////////////////////////// double Pipeline::get_total_time() const { return total_time_; } //////////////////////////////////////////////////////////////////////////////// double Pipeline::get_frame_time() const { return frame_time_; } //////////////////////////////////////////////////////////////////////////////// SubSampler* Pipeline::get_sub_sampler(int level) { int index = level - 2; if (sub_samplers_.size() > index && sub_samplers_[index] != nullptr) { return sub_samplers_[index]; } if (sub_samplers_.size() <= index) { sub_samplers_.resize(index+1); } sub_samplers_[index] = new SubSampler(window_->get_context(), level); return sub_samplers_[index]; } //////////////////////////////////////////////////////////////////////////////// } <|endoftext|>