text
stringlengths
54
60.6k
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2008/06/20 // Author: Sriram Rao // // Copyright 2008-2012,2016 Quantcast Corporation. All rights reserved. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Tool that tells the metaserver to mark a node "down" for // planned downtime. Nodes can either be hibernated or retired: // hibernation is a promise that the server will be back after N secs; // retire => node is going down and don't know when it will be back. // When a node is "retired" in this manner, the metaserver uses the // retiring node to proactively replicate the blocks from that server // to other nodes. // //---------------------------------------------------------------------------- #include "MonClient.h" #include "common/MsgLogger.h" #include "libclient/KfsClient.h" #include "libclient/KfsOps.h" #include <iostream> #include <string> using std::string; using std::cout; using namespace KFS; using namespace KFS::client; using namespace KFS_MON; int main( int argc, char** argv) { int optchar; bool help = false; const char* metaserver = 0; const char* chunkserver = 0; const char* configFileName = 0; int metaport = -1; int chunkport = -1; int sleepTime = -1; bool verboseLogging = false; while ((optchar = getopt(argc, argv, "hm:p:c:d:s:vf:")) != -1) { switch (optchar) { case 'm': metaserver = optarg; break; case 'c': chunkserver = optarg; break; case 'p': metaport = atoi(optarg); break; case 'd': chunkport = atoi(optarg); break; case 's': sleepTime = atoi(optarg); break; case 'h': help = true; break; case 'v': verboseLogging = true; break; case 'f': configFileName = optarg; break; default: help = true; break; } } help = help || ! metaserver || ! chunkserver || sleepTime <= 0 || metaport <= 0 || chunkport <= 0; if (help) { cout << "Usage: " << argv[0] << "\n" " -m <metaserver>\n" " -p <port>\n" " -c <chunkserver>\n" " -d <port>\n" " -s <sleeptime in seconds>\n" " -f <config file name>\n" " [-v]\n" "Hibernates the chunkserver for 'sleeptime' seconds.\n" ; return 1; } MsgLogger::Init(0, verboseLogging ? MsgLogger::kLogLevelDEBUG : MsgLogger::kLogLevelINFO); const ServerLocation metaLoc (metaserver, metaport); const ServerLocation chunkLoc(chunkserver, chunkport); RetireChunkserverOp op(0, chunkLoc, sleepTime); const bool kSetMetaLocationsFlag = true; MonClient client; int status = client.SetParameters( metaLoc, configFileName, kSetMetaLocationsFlag); if (status == 0) { status = client.Execute(op); } if (status < 0) { KFS_LOG_STREAM_ERROR << "hibernate failure: " << op.statusMsg << " " << ErrorCodeToStr(status) << KFS_LOG_EOM; } return (status < 0 ? 1 : 0); } <commit_msg>Tools: fix qfshibernate to allow to issue now deprecated chunk server retire by setting reconnect timeout to 0.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2008/06/20 // Author: Sriram Rao // // Copyright 2008-2012,2016 Quantcast Corporation. All rights reserved. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Tool that tells the metaserver to mark a node "down" for // planned downtime. Nodes can either be hibernated or retired: // hibernation is a promise that the server will be back after N secs; // retire => node is going down and don't know when it will be back. // When a node is "retired" in this manner, the metaserver uses the // retiring node to proactively replicate the blocks from that server // to other nodes. // //---------------------------------------------------------------------------- #include "MonClient.h" #include "common/MsgLogger.h" #include "libclient/KfsClient.h" #include "libclient/KfsOps.h" #include <iostream> #include <string> using std::string; using std::cout; using namespace KFS; using namespace KFS::client; using namespace KFS_MON; int main( int argc, char** argv) { int optchar; bool help = false; const char* metaserver = 0; const char* chunkserver = 0; const char* configFileName = 0; int metaport = -1; int chunkport = -1; int sleepTime = -1; bool verboseLogging = false; while ((optchar = getopt(argc, argv, "hm:p:c:d:s:vf:")) != -1) { switch (optchar) { case 'm': metaserver = optarg; break; case 'c': chunkserver = optarg; break; case 'p': metaport = atoi(optarg); break; case 'd': chunkport = atoi(optarg); break; case 's': sleepTime = atoi(optarg); break; case 'h': help = true; break; case 'v': verboseLogging = true; break; case 'f': configFileName = optarg; break; default: help = true; break; } } help = help || ! metaserver || ! chunkserver || sleepTime < 0 || metaport <= 0 || chunkport <= 0; if (help) { cout << "Usage: " << argv[0] << "\n" " -m <metaserver>\n" " -p <port>\n" " -c <chunkserver>\n" " -d <port>\n" " -s <sleeptime in seconds>\n" " -f <config file name>\n" " [-v]\n" "Hibernates the chunkserver for 'sleeptime' seconds.\n" ; return 1; } MsgLogger::Init(0, verboseLogging ? MsgLogger::kLogLevelDEBUG : MsgLogger::kLogLevelINFO); const ServerLocation metaLoc (metaserver, metaport); const ServerLocation chunkLoc(chunkserver, chunkport); RetireChunkserverOp op(0, chunkLoc, sleepTime); const bool kSetMetaLocationsFlag = true; MonClient client; int status = client.SetParameters( metaLoc, configFileName, kSetMetaLocationsFlag); if (status == 0) { status = client.Execute(op); } if (status < 0) { KFS_LOG_STREAM_ERROR << "hibernate failure: " << op.statusMsg << " " << ErrorCodeToStr(status) << KFS_LOG_EOM; } return (status < 0 ? 1 : 0); } <|endoftext|>
<commit_before>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS 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 "xeumeuleu_test_pch.h" #include "xeumeuleu/xml.h" using namespace mockpp; // ----------------------------------------------------------------------------- // Name: created_buffer_stream_starts_from_current_stream_level // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( created_buffer_stream_starts_from_current_stream_level ) { const std::string xml = "<element>" " <sub-node/>" "</element>"; xml::xistringstream xis( xml ); xis >> xml::start( "element" ); xml::xibufferstream xiss( xis ); BOOST_CHECK_NO_THROW( xiss >> xml::start( "sub-node" ) ); } // ----------------------------------------------------------------------------- // Name: streaming_end_right_after_creating_a_buffer_stream_throws_an_exception // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_end_right_after_creating_a_buffer_stream_throws_an_exception ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ); xml::xibufferstream xiss( xis ); BOOST_CHECK_THROW( xiss >> xml::end(), xml::exception ); } // ----------------------------------------------------------------------------- // Name: creating_a_buffer_stream_does_not_modify_original_stream // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_a_buffer_stream_does_not_modify_original_stream ) { xml::xistringstream xis( "<element/>" ); xml::xibufferstream xiss( xis ); xiss >> xml::start( "element" ); BOOST_CHECK_NO_THROW( xis >> xml::start( "element" ) ); } // ----------------------------------------------------------------------------- // Name: creating_buffer_stream_created_after_optional_does_not_reset_optional // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_buffer_stream_created_after_optional_does_not_reset_optional ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ) >> xml::optional(); xml::xibufferstream xiss( xis ); BOOST_CHECK_NO_THROW( xis >> xml::start( "non-existing" ) ); } // ----------------------------------------------------------------------------- // Name: buffer_stream_created_after_optional_is_not_optional // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( buffer_stream_created_after_optional_is_not_optional ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ) >> xml::optional(); xml::xibufferstream xiss( xis ); BOOST_CHECK_THROW( xiss >> xml::start( "non-existing" ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: creating_buffer_stream_on_optional_non_existing_branch_is_valid_and_does_not_reset_optional // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_buffer_stream_on_optional_non_existing_branch_is_valid_and_does_not_reset_optional ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ) >> xml::optional() >> xml::start( "non-existing" ); xml::xibufferstream xiss( xis ); BOOST_CHECK_NO_THROW( xis >> xml::start( "another-non-existing" ) ); } // ----------------------------------------------------------------------------- // Name: creating_buffer_stream_on_buffer_stream_is_valid // Created: MCO 2006-11-12 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_buffer_stream_on_buffer_stream_is_valid ) { xml::xistringstream xis( "<element/>" ); xml::xibufferstream xiss( xis ); xml::xibufferstream xisss( xiss ); BOOST_CHECK_NO_THROW( xisss >> xml::start( "element" ) ); } <commit_msg>Cleanup<commit_after>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS 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 "xeumeuleu_test_pch.h" #include "xeumeuleu/xml.h" using namespace mockpp; // ----------------------------------------------------------------------------- // Name: created_buffer_stream_starts_from_current_stream_level // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( created_buffer_stream_starts_from_current_stream_level ) { xml::xistringstream xis( "<element>" " <sub-node/>" "</element>" ); xis >> xml::start( "element" ); xml::xibufferstream xiss( xis ); BOOST_CHECK_NO_THROW( xiss >> xml::start( "sub-node" ) ); } // ----------------------------------------------------------------------------- // Name: streaming_end_right_after_creating_a_buffer_stream_throws_an_exception // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_end_right_after_creating_a_buffer_stream_throws_an_exception ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ); xml::xibufferstream xiss( xis ); BOOST_CHECK_THROW( xiss >> xml::end(), xml::exception ); } // ----------------------------------------------------------------------------- // Name: creating_a_buffer_stream_does_not_modify_original_stream // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_a_buffer_stream_does_not_modify_original_stream ) { xml::xistringstream xis( "<element/>" ); xml::xibufferstream xiss( xis ); xiss >> xml::start( "element" ); BOOST_CHECK_NO_THROW( xis >> xml::start( "element" ) ); } // ----------------------------------------------------------------------------- // Name: creating_buffer_stream_created_after_optional_does_not_reset_optional // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_buffer_stream_created_after_optional_does_not_reset_optional ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ) >> xml::optional(); xml::xibufferstream xiss( xis ); BOOST_CHECK_NO_THROW( xis >> xml::start( "non-existing" ) ); } // ----------------------------------------------------------------------------- // Name: buffer_stream_created_after_optional_is_not_optional // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( buffer_stream_created_after_optional_is_not_optional ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ) >> xml::optional(); xml::xibufferstream xiss( xis ); BOOST_CHECK_THROW( xiss >> xml::start( "non-existing" ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: creating_buffer_stream_on_optional_non_existing_branch_is_valid_and_does_not_reset_optional // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_buffer_stream_on_optional_non_existing_branch_is_valid_and_does_not_reset_optional ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ) >> xml::optional() >> xml::start( "non-existing" ); xml::xibufferstream xiss( xis ); BOOST_CHECK_NO_THROW( xis >> xml::start( "another-non-existing" ) ); } // ----------------------------------------------------------------------------- // Name: creating_buffer_stream_on_buffer_stream_is_valid // Created: MCO 2006-11-12 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_buffer_stream_on_buffer_stream_is_valid ) { xml::xistringstream xis( "<element/>" ); xml::xibufferstream xiss( xis ); xml::xibufferstream xisss( xiss ); BOOST_CHECK_NO_THROW( xisss >> xml::start( "element" ) ); } <|endoftext|>
<commit_before>#include "sellpopup.h" #include "ui_sellpopup.h" #include <list> Sellpopup::Sellpopup(QWidget *parent, Player *player, SubjectBlock *block) : QWidget(parent), ui(new Ui::Sellpopup) { ui->setupUi(this); layout = new QVBoxLayout(ui->scrollAreaWidgetContents); // initialize this->player = player; needed_value = block->getPenaltyCost() - player->getEnergy(); // setup blocks list that player owns std::list<Block*> block_list = player->getBlocks(); block_num = block_list.size(); blocks = new SubjectBlock*[block_num]; checks = new QCheckBox*[block_num]; int index = 0; for(std::list<Block*>::iterator itor = block_list.begin(); itor != block_list.end(); itor++) { blocks[index] = dynamic_cast<SubjectBlock*>(*itor); index++; } // list up checkbox elements for(int i=0; i < block_num; i++) { QString string = "Test"; // append department string += convertDept(blocks[i]->getDept()); string += " - "; // append Subject name string += blocks[i]->getName(); string += " - "; // append grade string += convertGrade(blocks[i]->getGrade()); QCheckBox* newCheck = new QCheckBox(); newCheck->setText(string); checks[i] = newCheck; layout->addWidget(newCheck); connect(newCheck, SIGNAL(toggled(bool)), this, SLOT(calculate())); } // set labels ui->neededValue->setText(QString::number(needed_value)); ui->selectedValue->setText("0"); // connect connect(ui->sellButton, SIGNAL(clicked()), this, SLOT(sell())); connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(close())); connect(ui->bankruptButton, SIGNAL(clicked()), this, SLOT(bankrupt())); } Sellpopup::~Sellpopup() { delete ui; } QString Sellpopup::convertDept(SubjectType::Type type) { QString dept = ""; switch(type) { using namespace SubjectType; case CSED: dept += "컴공과"; break; case ME: dept += "기계과"; break; case MATH: dept += "수학과"; break; case EE: dept += "전자과"; break; case PHYS: dept += "물리과"; break; case BIO: dept += "생명과"; break; case CHEM: dept += "화학과"; break; case IME: dept += "산경과"; break; } return dept; } QString Sellpopup::convertGrade(int grade) { QString str = ""; switch(grade) { case 2: str += "C"; break; case 3: str += "B"; break; case 4: str += "A"; break; } return str; } void Sellpopup::sell() { qDebug() << "Selling Block!"; // calculated selected value for(int i=0; i<block_num; i++) { if(checks[i]->isChecked()) player->removeBlock(blocks[i]); } this->close(); } void Sellpopup::bankrupt() { qDebug() << "Player " << player->getId() << "bankrupted!"; player->setBankrupt(); this->close(); } void Sellpopup::calculate() { qDebug() << "Select"; int selected = 0; // calculate selected for(int i=0; i<block_num; i++) if(checks[i]->isChecked()) selected += blocks[i]->getSellCost(); // update label ui->selectedValue->setText(QString::number(selected)); // is enough? if(selected >= needed_value) ui->sellButton->setEnabled(true); } <commit_msg>sellpopup: gives back remaining price after selling blocks<commit_after>#include "sellpopup.h" #include "ui_sellpopup.h" #include <list> Sellpopup::Sellpopup(QWidget *parent, Player *player, SubjectBlock *block) : QWidget(parent), ui(new Ui::Sellpopup) { ui->setupUi(this); layout = new QVBoxLayout(ui->scrollAreaWidgetContents); // initialize this->player = player; needed_value = block->getPenaltyCost() - player->getEnergy(); // setup blocks list that player owns std::list<Block*> block_list = player->getBlocks(); block_num = block_list.size(); blocks = new SubjectBlock*[block_num]; checks = new QCheckBox*[block_num]; int index = 0; for(std::list<Block*>::iterator itor = block_list.begin(); itor != block_list.end(); itor++) { blocks[index] = dynamic_cast<SubjectBlock*>(*itor); index++; } // list up checkbox elements for(int i=0; i < block_num; i++) { QString string = "Test"; // append department string += convertDept(blocks[i]->getDept()); string += " - "; // append Subject name string += blocks[i]->getName(); string += " - "; // append grade string += convertGrade(blocks[i]->getGrade()); string += " - "; // append sellprice string += QString::number(blocks[i]->getSellCost()); QCheckBox* newCheck = new QCheckBox(); newCheck->setText(string); checks[i] = newCheck; layout->addWidget(newCheck); connect(newCheck, SIGNAL(toggled(bool)), this, SLOT(calculate())); } // set labels ui->neededValue->setText(QString::number(needed_value)); ui->selectedValue->setText("0"); // connect connect(ui->sellButton, SIGNAL(clicked()), this, SLOT(sell())); connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(close())); connect(ui->bankruptButton, SIGNAL(clicked()), this, SLOT(bankrupt())); } Sellpopup::~Sellpopup() { delete ui; } QString Sellpopup::convertDept(SubjectType::Type type) { QString dept = ""; switch(type) { using namespace SubjectType; case CSED: dept += "컴공과"; break; case ME: dept += "기계과"; break; case MATH: dept += "수학과"; break; case EE: dept += "전자과"; break; case PHYS: dept += "물리과"; break; case BIO: dept += "생명과"; break; case CHEM: dept += "화학과"; break; case IME: dept += "산경과"; break; } return dept; } QString Sellpopup::convertGrade(int grade) { QString str = ""; switch(grade) { case 2: str += "C"; break; case 3: str += "B"; break; case 4: str += "A"; break; } return str; } void Sellpopup::sell() { qDebug() << "Selling Block!"; int sellsum=0; // calculated selected value for(int i=0; i<block_num; i++) { if(checks[i]->isChecked()){ sellsum += blocks[i]->getSellCost(); player->removeBlock(blocks[i]); } } player->giveEnergy(sellsum - needed_value); this->close(); } void Sellpopup::bankrupt() { qDebug() << "Player " << player->getId() << "bankrupted!"; player->setBankrupt(); this->close(); } void Sellpopup::calculate() { qDebug() << "Select"; int selected = 0; // calculate selected for(int i=0; i<block_num; i++) if(checks[i]->isChecked()) selected += blocks[i]->getSellCost(); // update label ui->selectedValue->setText(QString::number(selected)); // is enough? if(selected >= needed_value) ui->sellButton->setEnabled(true); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "orcusfiltersimpl.hxx" #include "orcusinterface.hxx" #include "orcusxml.hxx" #include "document.hxx" #include "svtools/treelistbox.hxx" #define __ORCUS_STATIC_LIB #include <orcus/spreadsheet/import_interface.hpp> #include <orcus/xml_structure_tree.hpp> #include <orcus/xml_namespace.hpp> #include <orcus/orcus_xml.hpp> #include <orcus/global.hpp> namespace { ScOrcusXMLTreeParam::EntryData& setUserDataToEntry( SvTreeListEntry& rEntry, ScOrcusXMLTreeParam::UserDataStoreType& rStore, ScOrcusXMLTreeParam::EntryType eType) { rStore.push_back(new ScOrcusXMLTreeParam::EntryData(eType)); rEntry.SetUserData(&rStore.back()); return rStore.back(); } void populateTree( SvTreeListBox& rTreeCtrl, orcus::xml_structure_tree::walker& rWalker, const orcus::xml_structure_tree::entity_name& rElemName, bool bRepeat, SvTreeListEntry* pParent, ScOrcusXMLTreeParam& rParam) { OUString aName(rElemName.name.get(), rElemName.name.size(), RTL_TEXTENCODING_UTF8); SvTreeListEntry* pEntry = rTreeCtrl.InsertEntry(aName, pParent); if (!pEntry) // Can this ever happen!? return; ScOrcusXMLTreeParam::EntryData& rEntryData = setUserDataToEntry( *pEntry, rParam.maUserDataStore, bRepeat ? ScOrcusXMLTreeParam::ElementRepeat : ScOrcusXMLTreeParam::ElementDefault); if (bRepeat) { // Recurring elements use different icon. rTreeCtrl.SetExpandedEntryBmp(pEntry, rParam.maImgElementRepeat); rTreeCtrl.SetCollapsedEntryBmp(pEntry, rParam.maImgElementRepeat); } if (pParent) rTreeCtrl.Expand(pParent); orcus::xml_structure_tree::entity_names_type aNames; // Insert attributes. rWalker.get_attributes(aNames); orcus::xml_structure_tree::entity_names_type::const_iterator it = aNames.begin(); orcus::xml_structure_tree::entity_names_type::const_iterator itEnd = aNames.end(); for (; it != itEnd; ++it) { orcus::xml_structure_tree::entity_name aAttrName = *it; SvTreeListEntry* pAttr = rTreeCtrl.InsertEntry( OUString(aAttrName.name.get(), aAttrName.name.size(), RTL_TEXTENCODING_UTF8), pEntry); if (!pAttr) continue; setUserDataToEntry(*pAttr, rParam.maUserDataStore, ScOrcusXMLTreeParam::Attribute); rTreeCtrl.SetExpandedEntryBmp(pAttr, rParam.maImgAttribute); rTreeCtrl.SetCollapsedEntryBmp(pAttr, rParam.maImgAttribute); } rTreeCtrl.Expand(pEntry); rWalker.get_children(aNames); // Non-leaf if it has child elements, leaf otherwise. rEntryData.mbLeafNode = aNames.empty(); // Insert child elements recursively. for (it = aNames.begin(), itEnd = aNames.end(); it != itEnd; ++it) { orcus::xml_structure_tree::element aElem = rWalker.descend(*it); populateTree(rTreeCtrl, rWalker, *it, aElem.repeat, pEntry, rParam); rWalker.ascend(); } } class TreeUpdateSwitch { SvTreeListBox& mrTreeCtrl; public: TreeUpdateSwitch(SvTreeListBox& rTreeCtrl) : mrTreeCtrl(rTreeCtrl) { mrTreeCtrl.SetUpdateMode(false); } ~TreeUpdateSwitch() { mrTreeCtrl.SetUpdateMode(true); } }; class InsertFieldPath : std::unary_function<OString, void> { orcus::orcus_xml& mrFilter; public: InsertFieldPath(orcus::orcus_xml& rFilter) : mrFilter(rFilter) {} void operator() (const OString& rPath) { mrFilter.append_field_link(rPath.getStr()); } }; } ScOrcusXMLContextImpl::ScOrcusXMLContextImpl(ScDocument& rDoc, const OUString& rPath) : ScOrcusXMLContext(), mrDoc(rDoc), maPath(rPath) {} ScOrcusXMLContextImpl::~ScOrcusXMLContextImpl() {} bool ScOrcusXMLContextImpl::loadXMLStructure(SvTreeListBox& rTreeCtrl, ScOrcusXMLTreeParam& rParam) { rParam.maUserDataStore.clear(); OString aSysPath = ScOrcusFiltersImpl::toSystemPath(maPath); const char* path = aSysPath.getStr(); // TODO: Use our own stream loading call instead of one from orcus. std::string aStrm; orcus::load_file_content(path, aStrm); if (aStrm.empty()) return false; orcus::xmlns_context cxt = maNsRepo.create_context(); orcus::xml_structure_tree aXmlTree(cxt); try { aXmlTree.parse(&aStrm[0], aStrm.size()); TreeUpdateSwitch aSwitch(rTreeCtrl); rTreeCtrl.Clear(); rTreeCtrl.SetDefaultCollapsedEntryBmp(rParam.maImgElementDefault); rTreeCtrl.SetDefaultExpandedEntryBmp(rParam.maImgElementDefault); orcus::xml_structure_tree::walker aWalker = aXmlTree.get_walker(); // Root element. orcus::xml_structure_tree::element aElem = aWalker.root(); populateTree(rTreeCtrl, aWalker, aElem.name, aElem.repeat, NULL, rParam); } catch (const std::exception&) { // Parsing of this XML file failed. return false; } return true; } bool ScOrcusXMLContextImpl::importXML(const ScOrcusImportXMLParam& rParam) { ScOrcusFactory aFactory(mrDoc); OString aSysPath = ScOrcusFiltersImpl::toSystemPath(maPath); const char* path = aSysPath.getStr(); try { orcus::orcus_xml filter(maNsRepo, &aFactory, NULL); // Set cell links. { ScOrcusImportXMLParam::CellLinksType::const_iterator it = rParam.maCellLinks.begin(); ScOrcusImportXMLParam::CellLinksType::const_iterator itEnd = rParam.maCellLinks.end(); for (; it != itEnd; ++it) { const ScOrcusImportXMLParam::CellLink& rLink = *it; OUString aTabName; mrDoc.GetName(rLink.maPos.Tab(), aTabName); filter.set_cell_link( rLink.maPath.getStr(), rtl::OUStringToOString(aTabName, RTL_TEXTENCODING_UTF8).getStr(), rLink.maPos.Row(), rLink.maPos.Col()); } } // Set range links. { ScOrcusImportXMLParam::RangeLinksType::const_iterator it = rParam.maRangeLinks.begin(); ScOrcusImportXMLParam::RangeLinksType::const_iterator itEnd = rParam.maRangeLinks.end(); for (; it != itEnd; ++it) { const ScOrcusImportXMLParam::RangeLink& rLink = *it; OUString aTabName; mrDoc.GetName(rLink.maPos.Tab(), aTabName); filter.start_range( rtl::OUStringToOString(aTabName, RTL_TEXTENCODING_UTF8).getStr(), rLink.maPos.Row(), rLink.maPos.Col()); std::for_each(rLink.maFieldPaths.begin(), rLink.maFieldPaths.end(), InsertFieldPath(filter)); filter.commit_range(); } } filter.read_file(path); } catch (const std::exception&) { return false; } return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Display XML namespace IDs in the tree.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "orcusfiltersimpl.hxx" #include "orcusinterface.hxx" #include "orcusxml.hxx" #include "document.hxx" #include "svtools/treelistbox.hxx" #define __ORCUS_STATIC_LIB #include <orcus/spreadsheet/import_interface.hpp> #include <orcus/xml_structure_tree.hpp> #include <orcus/xml_namespace.hpp> #include <orcus/orcus_xml.hpp> #include <orcus/global.hpp> namespace { ScOrcusXMLTreeParam::EntryData& setUserDataToEntry( SvTreeListEntry& rEntry, ScOrcusXMLTreeParam::UserDataStoreType& rStore, ScOrcusXMLTreeParam::EntryType eType) { rStore.push_back(new ScOrcusXMLTreeParam::EntryData(eType)); rEntry.SetUserData(&rStore.back()); return rStore.back(); } OUString toString(const orcus::xml_structure_tree::entity_name& entity, const orcus::xml_structure_tree::walker& walker) { OUStringBuffer aBuf; if (entity.ns) { // Namespace exists. Namespaces are displayed as ns0, ns1, ns2, .... size_t index = walker.get_xmlns_index(entity.ns); if (index == orcus::xml_structure_tree::walker::index_not_found) // This namespace doesn't exist in this context. Something has gone wrong. aBuf.append("???"); else { aBuf.append("ns"); aBuf.append(static_cast<sal_Int32>(index)); } aBuf.append(':'); } aBuf.append(OUString(entity.name.get(), entity.name.size(), RTL_TEXTENCODING_UTF8)); return aBuf.makeStringAndClear(); } void populateTree( SvTreeListBox& rTreeCtrl, orcus::xml_structure_tree::walker& rWalker, const orcus::xml_structure_tree::entity_name& rElemName, bool bRepeat, SvTreeListEntry* pParent, ScOrcusXMLTreeParam& rParam) { SvTreeListEntry* pEntry = rTreeCtrl.InsertEntry(toString(rElemName, rWalker), pParent); if (!pEntry) // Can this ever happen!? return; ScOrcusXMLTreeParam::EntryData& rEntryData = setUserDataToEntry( *pEntry, rParam.maUserDataStore, bRepeat ? ScOrcusXMLTreeParam::ElementRepeat : ScOrcusXMLTreeParam::ElementDefault); if (bRepeat) { // Recurring elements use different icon. rTreeCtrl.SetExpandedEntryBmp(pEntry, rParam.maImgElementRepeat); rTreeCtrl.SetCollapsedEntryBmp(pEntry, rParam.maImgElementRepeat); } if (pParent) rTreeCtrl.Expand(pParent); orcus::xml_structure_tree::entity_names_type aNames; // Insert attributes. rWalker.get_attributes(aNames); orcus::xml_structure_tree::entity_names_type::const_iterator it = aNames.begin(); orcus::xml_structure_tree::entity_names_type::const_iterator itEnd = aNames.end(); for (; it != itEnd; ++it) { orcus::xml_structure_tree::entity_name aAttrName = *it; SvTreeListEntry* pAttr = rTreeCtrl.InsertEntry(toString(aAttrName, rWalker), pEntry); if (!pAttr) continue; setUserDataToEntry(*pAttr, rParam.maUserDataStore, ScOrcusXMLTreeParam::Attribute); rTreeCtrl.SetExpandedEntryBmp(pAttr, rParam.maImgAttribute); rTreeCtrl.SetCollapsedEntryBmp(pAttr, rParam.maImgAttribute); } rTreeCtrl.Expand(pEntry); rWalker.get_children(aNames); // Non-leaf if it has child elements, leaf otherwise. rEntryData.mbLeafNode = aNames.empty(); // Insert child elements recursively. for (it = aNames.begin(), itEnd = aNames.end(); it != itEnd; ++it) { orcus::xml_structure_tree::element aElem = rWalker.descend(*it); populateTree(rTreeCtrl, rWalker, *it, aElem.repeat, pEntry, rParam); rWalker.ascend(); } } class TreeUpdateSwitch { SvTreeListBox& mrTreeCtrl; public: TreeUpdateSwitch(SvTreeListBox& rTreeCtrl) : mrTreeCtrl(rTreeCtrl) { mrTreeCtrl.SetUpdateMode(false); } ~TreeUpdateSwitch() { mrTreeCtrl.SetUpdateMode(true); } }; class InsertFieldPath : std::unary_function<OString, void> { orcus::orcus_xml& mrFilter; public: InsertFieldPath(orcus::orcus_xml& rFilter) : mrFilter(rFilter) {} void operator() (const OString& rPath) { mrFilter.append_field_link(rPath.getStr()); } }; } ScOrcusXMLContextImpl::ScOrcusXMLContextImpl(ScDocument& rDoc, const OUString& rPath) : ScOrcusXMLContext(), mrDoc(rDoc), maPath(rPath) {} ScOrcusXMLContextImpl::~ScOrcusXMLContextImpl() {} bool ScOrcusXMLContextImpl::loadXMLStructure(SvTreeListBox& rTreeCtrl, ScOrcusXMLTreeParam& rParam) { rParam.maUserDataStore.clear(); OString aSysPath = ScOrcusFiltersImpl::toSystemPath(maPath); const char* path = aSysPath.getStr(); // TODO: Use our own stream loading call instead of one from orcus. std::string aStrm; orcus::load_file_content(path, aStrm); if (aStrm.empty()) return false; orcus::xmlns_context cxt = maNsRepo.create_context(); orcus::xml_structure_tree aXmlTree(cxt); try { aXmlTree.parse(&aStrm[0], aStrm.size()); TreeUpdateSwitch aSwitch(rTreeCtrl); rTreeCtrl.Clear(); rTreeCtrl.SetDefaultCollapsedEntryBmp(rParam.maImgElementDefault); rTreeCtrl.SetDefaultExpandedEntryBmp(rParam.maImgElementDefault); orcus::xml_structure_tree::walker aWalker = aXmlTree.get_walker(); // Root element. orcus::xml_structure_tree::element aElem = aWalker.root(); populateTree(rTreeCtrl, aWalker, aElem.name, aElem.repeat, NULL, rParam); } catch (const std::exception&) { // Parsing of this XML file failed. return false; } return true; } bool ScOrcusXMLContextImpl::importXML(const ScOrcusImportXMLParam& rParam) { ScOrcusFactory aFactory(mrDoc); OString aSysPath = ScOrcusFiltersImpl::toSystemPath(maPath); const char* path = aSysPath.getStr(); try { orcus::orcus_xml filter(maNsRepo, &aFactory, NULL); // Set cell links. { ScOrcusImportXMLParam::CellLinksType::const_iterator it = rParam.maCellLinks.begin(); ScOrcusImportXMLParam::CellLinksType::const_iterator itEnd = rParam.maCellLinks.end(); for (; it != itEnd; ++it) { const ScOrcusImportXMLParam::CellLink& rLink = *it; OUString aTabName; mrDoc.GetName(rLink.maPos.Tab(), aTabName); filter.set_cell_link( rLink.maPath.getStr(), rtl::OUStringToOString(aTabName, RTL_TEXTENCODING_UTF8).getStr(), rLink.maPos.Row(), rLink.maPos.Col()); } } // Set range links. { ScOrcusImportXMLParam::RangeLinksType::const_iterator it = rParam.maRangeLinks.begin(); ScOrcusImportXMLParam::RangeLinksType::const_iterator itEnd = rParam.maRangeLinks.end(); for (; it != itEnd; ++it) { const ScOrcusImportXMLParam::RangeLink& rLink = *it; OUString aTabName; mrDoc.GetName(rLink.maPos.Tab(), aTabName); filter.start_range( rtl::OUStringToOString(aTabName, RTL_TEXTENCODING_UTF8).getStr(), rLink.maPos.Row(), rLink.maPos.Col()); std::for_each(rLink.maFieldPaths.begin(), rLink.maFieldPaths.end(), InsertFieldPath(filter)); filter.commit_range(); } } filter.read_file(path); } catch (const std::exception&) { return false; } return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/******************************************************************************* Copyright (C) 2015 Dario Oliveri See copyright notice in LICENSE.md *******************************************************************************/ #pragma once #include <exception> //uncomment following line to disable all TRY / CATCH clauses inside Infectorpp //#define INFECTORPP_DISABLE_EXCEPTION_HANDLING 1 // (you need to recompile Infectorpp).. // ..Alternatively Cmake GUI has the checkbox option for that #ifdef INFECTORPP_DISABLE_EXCEPTION_HANDLING #undef NDEBUG #include <assert.h> #undef INFECTORPP_TRY #define INFECTORPP_TRY #else #undef INFECTORPP_TRY #define INFECTORPP_TRY try{ #endif #ifndef _MSC_VER // Visual studio 2013 still does not support "noexcept" // needs a workaround thanks to wtravisjones for bug report. #define INFECTORPP_NOEXCEPT noexcept(true) #else #define INFECTORPP_NOEXCEPT #endif namespace Infector{ namespace priv{ template< typename M> void throwOrBreak(){ #ifdef INFECTORPP_DISABLE_EXCEPTION_HANDLING assert( false && typeid(M).name()); #else throw M(); #endif } template< typename M> void throwingAssertion( bool condition){ if(condition==false){ #ifdef INFECTORPP_DISABLE_EXCEPTION_HANDLING assert( condition && typeid(M).name()); #else throw M(); #endif } } class InstantiatingComponentEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCannot create shared instance for something bound as 'unique_ptr'\n"; } }; class RebindEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCannot bind same interface twice\n"; } }; class CircularDependencyEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCircular Dependency detected\n"; } }; class TooDeepRecursionEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nReached hard recursion limit\n"; } }; class NotReachableEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nThis is for sure a bug, please report it at: \n" "https://github.com/Darelbi/Infectorpp \n" "Make sure to provide code that reproduce the problem"; } }; class TypeNotWiredEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nYou trying to build instance or component of a type wich was not wired.\n"; } }; class InstanceAlreadyRegisteredEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCannot register an instance that was already lazily created..\n"; } }; class ContainerLockedEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nContainer hiearachy can't be modified after context creation.\n"; } }; class NotBoundEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCannot wire a type without bindings.\n"; } }; } }<commit_msg>Small refactoring for exceptions<commit_after>/******************************************************************************* Copyright (C) 2015 Dario Oliveri See copyright notice in LICENSE.md *******************************************************************************/ #pragma once #include <exception> //uncomment following line to disable all TRY / CATCH clauses inside Infectorpp //#define INFECTORPP_DISABLE_EXCEPTION_HANDLING 1 // (you need to recompile Infectorpp).. // ..Alternatively Cmake GUI has the checkbox option for that #ifdef INFECTORPP_DISABLE_EXCEPTION_HANDLING #undef NDEBUG #include <assert.h> #undef INFECTORPP_TRY #define INFECTORPP_TRY #else #undef INFECTORPP_TRY #define INFECTORPP_TRY try{ #endif #ifndef _MSC_VER // Visual studio 2013 still does not support "noexcept" // needs a workaround thanks to wtravisjones for bug report. #define INFECTORPP_NOEXCEPT noexcept(true) #else #define INFECTORPP_NOEXCEPT #endif namespace Infector{ namespace priv{ template< typename M> void throwOrBreak(){ #ifdef INFECTORPP_DISABLE_EXCEPTION_HANDLING assert( typeid(M).name() && false); #else throw M(); #endif } template< typename M> void throwingAssertion( bool condition){ if( condition == false) throwOrBreak< M>(); } class InstantiatingComponentEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCannot create shared instance for something bound as 'unique_ptr'\n"; } }; class RebindEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCannot bind same interface twice\n"; } }; class CircularDependencyEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCircular Dependency detected\n"; } }; class TooDeepRecursionEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nReached hard recursion limit\n"; } }; class NotReachableEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nThis is for sure a bug, please report it at: \n" "https://github.com/Darelbi/Infectorpp \n" "Make sure to provide code that reproduce the problem"; } }; class PartiallyImplementedSharedType: public std::exception{ public: virtual const char * what() const INFECTORPP_NOEXCEPT{ return "In container you binded a Concrete type as multiple \n" "interfaces, but then you registered an instance for only\n" "a bunch of those interfaces: if you got this exception\n" "is because somewhere on your code it was assumed\n" "those interfaces are still communicating each other\n" "See the wiki for fixing this exception"; } }; class NotImplementedEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "Not yet implemented!"; } }; class TypeNotWiredEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nYou trying to build instance or component of a type wich was not wired.\n"; } }; class InstanceAlreadyRegisteredEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCannot register an instance that was already lazily created..\n"; } }; class ContainerLockedEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nContainer hiearachy can't be modified after context creation.\n"; } }; class NotBoundEx: public std::exception{ public: virtual const char* what() const INFECTORPP_NOEXCEPT{ return "\nCannot wire a type without bindings.\n"; } }; } }<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkNewickTreeReader.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 "vtkNewickTreeReader.h" #include "vtkByteSwap.h" #include "vtkCellArray.h" #include "vtkDataSetAttributes.h" #include "vtkDoubleArray.h" #include "vtkFieldData.h" #include "vtkNew.h" #include "vtkTree.h" #include "vtkTreeDFSIterator.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkStringArray.h" #include <iostream> #include <fstream> vtkStandardNewMacro(vtkNewickTreeReader); #ifdef read #undef read #endif //---------------------------------------------------------------------------- vtkNewickTreeReader::vtkNewickTreeReader() { vtkTree *output = vtkTree::New(); this->SetOutput(output); // Releasing data for pipeline parallism. // Filters will know it is empty. output->ReleaseData(); output->Delete(); } //---------------------------------------------------------------------------- vtkNewickTreeReader::~vtkNewickTreeReader() { } //---------------------------------------------------------------------------- vtkTree* vtkNewickTreeReader::GetOutput() { return this->GetOutput(0); } //---------------------------------------------------------------------------- vtkTree* vtkNewickTreeReader::GetOutput(int idx) { return vtkTree::SafeDownCast(this->GetOutputDataObject(idx)); } //---------------------------------------------------------------------------- void vtkNewickTreeReader::SetOutput(vtkTree *output) { this->GetExecutive()->SetOutputData(0, output); } //---------------------------------------------------------------------------- // I do not think this should be here, but I do not want to remove it now. int vtkNewickTreeReader::RequestUpdateExtent( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); int piece, numPieces; piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); // make sure piece is valid if (piece < 0 || piece >= numPieces) { return 1; } return 1; } //---------------------------------------------------------------------------- int vtkNewickTreeReader:: ReadNewickTree( char * const buffer, vtkTree & tree) { // Read through the input file to count the number of nodes in the tree. // We start at one to account for the root node vtkIdType numNodes = 1; this->CountNodes(buffer, &numNodes); // Create the edge weight array vtkNew<vtkDoubleArray> weights; weights->SetNumberOfComponents(1); weights->SetName("weight"); weights->SetNumberOfValues(numNodes-1);//the number of edges = number of nodes -1 for a tree weights->FillComponent(0, 0.0); // Create the names array vtkNew<vtkStringArray> names; names->SetNumberOfComponents(1); names->SetName("node name"); names->SetNumberOfValues(numNodes); //parse the input file to create the graph vtkNew<vtkMutableDirectedGraph> builder; this->BuildTree(buffer, builder.GetPointer(), weights.GetPointer(), names.GetPointer(), -1); builder->GetEdgeData()->AddArray(weights.GetPointer()); builder->GetVertexData()->AddArray(names.GetPointer()); if (!tree.CheckedShallowCopy(builder.GetPointer())) { vtkErrorMacro(<<"Edges do not create a valid tree."); return 1; } vtkNew<vtkDoubleArray> nodeWeights; nodeWeights->SetNumberOfTuples(tree.GetNumberOfVertices()); // trueWeights is (for the most part) a duplicate of nodeWeights. // The only difference is that leaf nodes aren't clamped to the max // weight in this array. vtkNew<vtkDoubleArray> trueWeights; trueWeights->SetNumberOfTuples(tree.GetNumberOfVertices()); //set node weights double maxWeight = 0.0; vtkNew<vtkTreeDFSIterator> treeIterator; treeIterator->SetStartVertex(tree.GetRoot()); treeIterator->SetTree(&tree); while (treeIterator->HasNext()) { vtkIdType vertex = treeIterator->Next(); vtkIdType parent = tree.GetParent(vertex); double weight = 0.0; if (parent >= 0) { weight = weights->GetValue(tree.GetEdgeId(parent, vertex)); } weight += nodeWeights->GetValue(parent); if (weight > maxWeight) { maxWeight = weight; } nodeWeights->SetValue(vertex, weight); trueWeights->SetValue(vertex, weight); } for (vtkIdType vertex = 0; vertex < tree.GetNumberOfVertices(); ++vertex) { if (tree.IsLeaf(vertex)) { nodeWeights->SetValue(vertex, maxWeight); } } nodeWeights->SetName("node weight"); tree.GetVertexData()->AddArray(nodeWeights.GetPointer()); trueWeights->SetName("true node weight"); tree.GetVertexData()->AddArray(trueWeights.GetPointer()); return 1; } //---------------------------------------------------------------------------- int vtkNewickTreeReader::RequestData( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); // Return all data in the first piece ... if(outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { return 1; } vtkDebugMacro(<<"Reading Newick tree ..."); if(this->GetFileName() == NULL || strcmp(this->GetFileName(), "") == 0) { vtkErrorMacro(<<"Input filename not set"); return 1; } std::ifstream ifs( this->GetFileName(), std::ifstream::in ); if(!ifs.good()) { vtkErrorMacro(<<"Unable to open " << this->GetFileName() << " for reading"); return 1; } vtkTree* const output = vtkTree::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); // Read the input file into a char * int length; ifs.seekg(0, std::ios::end); length = ifs.tellg(); ifs.seekg(0, std::ios::beg); char *buffer = new char[length]; ifs.read(buffer, length); /*// Rewind input buffer ifs.seekg(0, std::ios::beg); ifs.read(buffer, length); ifs.close(); */ ifs.close(); if(!ReadNewickTree(buffer, *output)) { vtkErrorMacro(<<"Error reading the buffer into a vtkTree structure."); return 1; } delete [] buffer; vtkDebugMacro(<< "Read " << output->GetNumberOfVertices() <<" vertices and " << output->GetNumberOfEdges() <<" edges.\n"); return 1; } void vtkNewickTreeReader::CountNodes(char * const buffer, vtkIdType *numNodes) { char *current; char *start; char temp; int childCount; start = buffer; if (*start != '(') { // Leaf node. Separate name from weight. // If weight doesn't exist then take care of name only current = buffer; while (*current != '\0') { current++; } ++(*numNodes); } else { ++(*numNodes); // Search for all child nodes // Find all ',' until corresponding ')' is encountered childCount = 0; start++; current = start; while (childCount >= 0) { switch (*current) { case '(': // Find corresponding ')' by counting start = current; current++; childCount++; while (childCount > 0) { if (*current == '(') { childCount++; } else if (*current == ')') { childCount--; } current++; } while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Count child nodes using recursion this->CountNodes(start, numNodes); *current = temp; if (*current != ')') { current++; } break; case ')': // End of this tree. Go to next part to retrieve distance childCount--; break; case ',': // Impossible separation since according to the algorithm, this symbol will never encountered. // Currently don't handle this and don't create any node break; default: // leaf node encountered start = current; while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Count child nodes using recursion this->CountNodes(start, numNodes); *current = temp; if (*current != ')') { current++; } break; } } // If start at ':', then the internal node has no name. current++; if (*current == ':') { start = current + 1; while (*current != '\0' && *current != ';') { current++; } } else if (*current != ';' && *current != '\0') { while (*current != ':') { current++; } current++; while (*current != '\0' && *current != ';') { current++; } } } } vtkIdType vtkNewickTreeReader::BuildTree(char *buffer, vtkMutableDirectedGraph *g, vtkDoubleArray *weights, vtkStringArray *names, vtkIdType parent) { char *current; char *start; char *colon = NULL; char temp; int childCount; vtkIdType node; start = buffer; if(parent == -1) { parent = g->AddVertex(); names->SetValue(parent, ""); } if (*start != '(') { // Leaf node. Separate name from weight (if it exists). current = buffer; while (*current != '\0') { if (*current == ':') { colon = current; } current++; } node = g->AddChild(parent); if (colon == NULL) { // Name only std::string name(start, strlen(start)); names->SetValue(node, name); } else { // Name *colon = '\0'; std::string name(start, strlen(start)); names->SetValue(node, name); *colon = ':'; // Weight colon++; weights->SetValue(g->GetEdgeId(parent, node), atof(colon)); } } else { // Create node node = g->AddChild(parent); // Search for all child nodes // Find all ',' until corresponding ')' is encountered childCount = 0; start++; current = start; while (childCount >= 0) { switch (*current) { case '(': // Find corresponding ')' by counting start = current; current++; childCount++; while (childCount > 0) { if (*current == '(') { childCount++; } else if (*current == ')') { childCount--; } current++; } while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Create a child node using recursion this->BuildTree(start, g, weights, names, node); *current = temp; if (*current != ')') { current++; } break; case ')': // End of this tree. Go to next part to retrieve distance childCount--; break; case ',': // Impossible separation since according to the algorithm, this symbol will never encountered. // Currently don't handle this and don't create any node break; default: // leaf node encountered start = current; while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Create a child node using recursion this->BuildTree(start, g, weights, names, node); *current = temp; if (*current != ')') { current++; } break; } } // If start at ':', then the internal node has no name. current++; if (*current == ':') { start = current + 1; while (*current != '\0' && *current != ';') { current++; } temp = *current; *current = '\0'; weights->SetValue(g->GetEdgeId(parent, node), atof(start)); names->SetValue(node, ""); *current = temp; } else if (*current != ';' && *current != '\0') { // Find ':' to retrieve distance, if any. // At this time *current should equal to ')' start = current; while (*current != ':') { current++; } temp = *current; *current = '\0'; std::string name(start, strlen(start)); names->SetValue(node, name); *current = temp; current++; start = current; while (*current != '\0' && *current != ';') { current++; } temp = *current; *current = '\0'; weights->SetValue(g->GetEdgeId(parent, node), atof(start)); *current = temp; } } return node; } //---------------------------------------------------------------------------- int vtkNewickTreeReader::FillOutputPortInformation(int, vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTree"); return 1; } //---------------------------------------------------------------------------- void vtkNewickTreeReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } <commit_msg>Fix invalid read in vtkNewickTreeReader<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkNewickTreeReader.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 "vtkNewickTreeReader.h" #include "vtkByteSwap.h" #include "vtkCellArray.h" #include "vtkDataSetAttributes.h" #include "vtkDoubleArray.h" #include "vtkFieldData.h" #include "vtkNew.h" #include "vtkTree.h" #include "vtkTreeDFSIterator.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkStringArray.h" #include <iostream> #include <fstream> vtkStandardNewMacro(vtkNewickTreeReader); #ifdef read #undef read #endif //---------------------------------------------------------------------------- vtkNewickTreeReader::vtkNewickTreeReader() { vtkTree *output = vtkTree::New(); this->SetOutput(output); // Releasing data for pipeline parallism. // Filters will know it is empty. output->ReleaseData(); output->Delete(); } //---------------------------------------------------------------------------- vtkNewickTreeReader::~vtkNewickTreeReader() { } //---------------------------------------------------------------------------- vtkTree* vtkNewickTreeReader::GetOutput() { return this->GetOutput(0); } //---------------------------------------------------------------------------- vtkTree* vtkNewickTreeReader::GetOutput(int idx) { return vtkTree::SafeDownCast(this->GetOutputDataObject(idx)); } //---------------------------------------------------------------------------- void vtkNewickTreeReader::SetOutput(vtkTree *output) { this->GetExecutive()->SetOutputData(0, output); } //---------------------------------------------------------------------------- // I do not think this should be here, but I do not want to remove it now. int vtkNewickTreeReader::RequestUpdateExtent( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); int piece, numPieces; piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); // make sure piece is valid if (piece < 0 || piece >= numPieces) { return 1; } return 1; } //---------------------------------------------------------------------------- int vtkNewickTreeReader:: ReadNewickTree( char * const buffer, vtkTree & tree) { // Read through the input file to count the number of nodes in the tree. // We start at one to account for the root node vtkIdType numNodes = 1; this->CountNodes(buffer, &numNodes); // Create the edge weight array vtkNew<vtkDoubleArray> weights; weights->SetNumberOfComponents(1); weights->SetName("weight"); weights->SetNumberOfValues(numNodes-1);//the number of edges = number of nodes -1 for a tree weights->FillComponent(0, 0.0); // Create the names array vtkNew<vtkStringArray> names; names->SetNumberOfComponents(1); names->SetName("node name"); names->SetNumberOfValues(numNodes); //parse the input file to create the graph vtkNew<vtkMutableDirectedGraph> builder; this->BuildTree(buffer, builder.GetPointer(), weights.GetPointer(), names.GetPointer(), -1); builder->GetEdgeData()->AddArray(weights.GetPointer()); builder->GetVertexData()->AddArray(names.GetPointer()); if (!tree.CheckedShallowCopy(builder.GetPointer())) { vtkErrorMacro(<<"Edges do not create a valid tree."); return 1; } vtkNew<vtkDoubleArray> nodeWeights; nodeWeights->SetNumberOfTuples(tree.GetNumberOfVertices()); // trueWeights is (for the most part) a duplicate of nodeWeights. // The only difference is that leaf nodes aren't clamped to the max // weight in this array. vtkNew<vtkDoubleArray> trueWeights; trueWeights->SetNumberOfTuples(tree.GetNumberOfVertices()); //set node weights double maxWeight = 0.0; vtkNew<vtkTreeDFSIterator> treeIterator; treeIterator->SetStartVertex(tree.GetRoot()); treeIterator->SetTree(&tree); while (treeIterator->HasNext()) { vtkIdType vertex = treeIterator->Next(); vtkIdType parent = tree.GetParent(vertex); double weight = 0.0; if (parent >= 0) { weight = weights->GetValue(tree.GetEdgeId(parent, vertex)); weight += nodeWeights->GetValue(parent); } if (weight > maxWeight) { maxWeight = weight; } nodeWeights->SetValue(vertex, weight); trueWeights->SetValue(vertex, weight); } for (vtkIdType vertex = 0; vertex < tree.GetNumberOfVertices(); ++vertex) { if (tree.IsLeaf(vertex)) { nodeWeights->SetValue(vertex, maxWeight); } } nodeWeights->SetName("node weight"); tree.GetVertexData()->AddArray(nodeWeights.GetPointer()); trueWeights->SetName("true node weight"); tree.GetVertexData()->AddArray(trueWeights.GetPointer()); return 1; } //---------------------------------------------------------------------------- int vtkNewickTreeReader::RequestData( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); // Return all data in the first piece ... if(outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { return 1; } vtkDebugMacro(<<"Reading Newick tree ..."); if(this->GetFileName() == NULL || strcmp(this->GetFileName(), "") == 0) { vtkErrorMacro(<<"Input filename not set"); return 1; } std::ifstream ifs( this->GetFileName(), std::ifstream::in ); if(!ifs.good()) { vtkErrorMacro(<<"Unable to open " << this->GetFileName() << " for reading"); return 1; } vtkTree* const output = vtkTree::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); // Read the input file into a char * int length; ifs.seekg(0, std::ios::end); length = ifs.tellg(); ifs.seekg(0, std::ios::beg); char *buffer = new char[length]; ifs.read(buffer, length); /*// Rewind input buffer ifs.seekg(0, std::ios::beg); ifs.read(buffer, length); ifs.close(); */ ifs.close(); if(!ReadNewickTree(buffer, *output)) { vtkErrorMacro(<<"Error reading the buffer into a vtkTree structure."); return 1; } delete [] buffer; vtkDebugMacro(<< "Read " << output->GetNumberOfVertices() <<" vertices and " << output->GetNumberOfEdges() <<" edges.\n"); return 1; } void vtkNewickTreeReader::CountNodes(char * const buffer, vtkIdType *numNodes) { char *current; char *start; char temp; int childCount; start = buffer; if (*start != '(') { // Leaf node. Separate name from weight. // If weight doesn't exist then take care of name only current = buffer; while (*current != '\0') { current++; } ++(*numNodes); } else { ++(*numNodes); // Search for all child nodes // Find all ',' until corresponding ')' is encountered childCount = 0; start++; current = start; while (childCount >= 0) { switch (*current) { case '(': // Find corresponding ')' by counting start = current; current++; childCount++; while (childCount > 0) { if (*current == '(') { childCount++; } else if (*current == ')') { childCount--; } current++; } while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Count child nodes using recursion this->CountNodes(start, numNodes); *current = temp; if (*current != ')') { current++; } break; case ')': // End of this tree. Go to next part to retrieve distance childCount--; break; case ',': // Impossible separation since according to the algorithm, this symbol will never encountered. // Currently don't handle this and don't create any node break; default: // leaf node encountered start = current; while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Count child nodes using recursion this->CountNodes(start, numNodes); *current = temp; if (*current != ')') { current++; } break; } } // If start at ':', then the internal node has no name. current++; if (*current == ':') { start = current + 1; while (*current != '\0' && *current != ';') { current++; } } else if (*current != ';' && *current != '\0') { while (*current != ':') { current++; } current++; while (*current != '\0' && *current != ';') { current++; } } } } vtkIdType vtkNewickTreeReader::BuildTree(char *buffer, vtkMutableDirectedGraph *g, vtkDoubleArray *weights, vtkStringArray *names, vtkIdType parent) { char *current; char *start; char *colon = NULL; char temp; int childCount; vtkIdType node; start = buffer; if(parent == -1) { parent = g->AddVertex(); names->SetValue(parent, ""); } if (*start != '(') { // Leaf node. Separate name from weight (if it exists). current = buffer; while (*current != '\0') { if (*current == ':') { colon = current; } current++; } node = g->AddChild(parent); if (colon == NULL) { // Name only std::string name(start, strlen(start)); names->SetValue(node, name); } else { // Name *colon = '\0'; std::string name(start, strlen(start)); names->SetValue(node, name); *colon = ':'; // Weight colon++; weights->SetValue(g->GetEdgeId(parent, node), atof(colon)); } } else { // Create node node = g->AddChild(parent); // Search for all child nodes // Find all ',' until corresponding ')' is encountered childCount = 0; start++; current = start; while (childCount >= 0) { switch (*current) { case '(': // Find corresponding ')' by counting start = current; current++; childCount++; while (childCount > 0) { if (*current == '(') { childCount++; } else if (*current == ')') { childCount--; } current++; } while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Create a child node using recursion this->BuildTree(start, g, weights, names, node); *current = temp; if (*current != ')') { current++; } break; case ')': // End of this tree. Go to next part to retrieve distance childCount--; break; case ',': // Impossible separation since according to the algorithm, this symbol will never encountered. // Currently don't handle this and don't create any node break; default: // leaf node encountered start = current; while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Create a child node using recursion this->BuildTree(start, g, weights, names, node); *current = temp; if (*current != ')') { current++; } break; } } // If start at ':', then the internal node has no name. current++; if (*current == ':') { start = current + 1; while (*current != '\0' && *current != ';') { current++; } temp = *current; *current = '\0'; weights->SetValue(g->GetEdgeId(parent, node), atof(start)); names->SetValue(node, ""); *current = temp; } else if (*current != ';' && *current != '\0') { // Find ':' to retrieve distance, if any. // At this time *current should equal to ')' start = current; while (*current != ':') { current++; } temp = *current; *current = '\0'; std::string name(start, strlen(start)); names->SetValue(node, name); *current = temp; current++; start = current; while (*current != '\0' && *current != ';') { current++; } temp = *current; *current = '\0'; weights->SetValue(g->GetEdgeId(parent, node), atof(start)); *current = temp; } } return node; } //---------------------------------------------------------------------------- int vtkNewickTreeReader::FillOutputPortInformation(int, vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTree"); return 1; } //---------------------------------------------------------------------------- void vtkNewickTreeReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } <|endoftext|>
<commit_before>#pragma once #include "depthai/pipeline/Node.hpp" // shared #include "depthai-shared/properties/StereoDepthProperties.hpp" #include "depthai/pipeline/datatype/StereoDepthConfig.hpp" namespace dai { namespace node { /** * @brief StereoDepth node. Compute stereo disparity and depth from left-right image pair. */ class StereoDepth : public NodeCRTP<Node, StereoDepth, StereoDepthProperties> { public: constexpr static const char* NAME = "StereoDepth"; /** * Preset modes for stereo depth. */ enum class PresetMode : std::uint32_t { HIGH_ACCURACY, HIGH_DENSITY }; protected: Properties& getProperties(); private: PresetMode presetMode = PresetMode::HIGH_DENSITY; std::shared_ptr<RawStereoDepthConfig> rawConfig; public: StereoDepth(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId); StereoDepth(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId, std::unique_ptr<Properties> props); /** * Initial config to use for StereoDepth. */ StereoDepthConfig initialConfig; /** * Input StereoDepthConfig message with ability to modify parameters in runtime. * Default queue is non-blocking with size 4. */ Input inputConfig{*this, "inputConfig", Input::Type::SReceiver, false, 4, {{DatatypeEnum::StereoDepthConfig, false}}}; /** * Input for left ImgFrame of left-right pair * * Default queue is non-blocking with size 8 */ Input left{*this, "left", Input::Type::SReceiver, false, 8, true, {{DatatypeEnum::ImgFrame, true}}}; /** * Input for right ImgFrame of left-right pair * * Default queue is non-blocking with size 8 */ Input right{*this, "right", Input::Type::SReceiver, false, 8, true, {{DatatypeEnum::ImgFrame, true}}}; /** * Outputs ImgFrame message that carries RAW16 encoded (0..65535) depth data in depth units (millimeter by default). * * Non-determined / invalid depth values are set to 0 */ Output depth{*this, "depth", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries RAW8 / RAW16 encoded disparity data: * RAW8 encoded (0..95) for standard mode; * RAW8 encoded (0..190) for extended disparity mode; * RAW16 encoded for subpixel disparity mode: * - 0..760 for 3 fractional bits (by default) * - 0..1520 for 4 fractional bits * - 0..3040 for 5 fractional bits */ Output disparity{*this, "disparity", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Passthrough ImgFrame message from 'left' Input. */ Output syncedLeft{*this, "syncedLeft", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Passthrough ImgFrame message from 'right' Input. */ Output syncedRight{*this, "syncedRight", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries RAW8 encoded (grayscale) rectified frame data. */ Output rectifiedLeft{*this, "rectifiedLeft", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries RAW8 encoded (grayscale) rectified frame data. */ Output rectifiedRight{*this, "rectifiedRight", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs StereoDepthConfig message that contains current stereo configuration. */ Output outConfig{*this, "outConfig", Output::Type::MSender, {{DatatypeEnum::StereoDepthConfig, false}}}; /** * Outputs ImgFrame message that carries left-right check first iteration (before combining with second iteration) disparity map. * Useful for debugging/fine tuning. */ Output debugDispLrCheckIt1{*this, "debugDispLrCheckIt1", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries left-right check second iteration (before combining with first iteration) disparity map. * Useful for debugging/fine tuning. */ Output debugDispLrCheckIt2{*this, "debugDispLrCheckIt2", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries extended left-right check first iteration (downscaled frame, before combining with second iteration) disparity map. * Useful for debugging/fine tuning. */ Output debugExtDispLrCheckIt1{*this, "debugExtDispLrCheckIt1", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries extended left-right check second iteration (downscaled frame, before combining with first iteration) disparity map. * Useful for debugging/fine tuning. */ Output debugExtDispLrCheckIt2{*this, "debugExtDispLrCheckIt2", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries cost dump of disparity map. * Useful for debugging/fine tuning. */ Output debugDispCostDump{*this, "debugDispCostDump", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries RAW8 confidence map. * Lower values means higher confidence of the calculated disparity value. * RGB alignment, left-right check or any postproccessing (e.g. median filter) is not performed on confidence map. */ Output confidenceMap{*this, "confidenceMap", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Specify that a passthrough/dummy calibration should be used, * when input frames are already rectified (e.g. sourced from recordings on the host) */ [[deprecated("Use 'Stereo::setRectification(false)' instead")]] void setEmptyCalibration(); /** * Specify local filesystem paths to the mesh calibration files for 'left' and 'right' inputs. * * When a mesh calibration is set, it overrides the camera intrinsics/extrinsics matrices. * Mesh format: a sequence of (y,x) points as 'float' with coordinates from the input image * to be mapped in the output. The mesh can be subsampled, configured by `setMeshStep`. * * With a 1280x800 resolution and the default (16,16) step, the required mesh size is: * * width: 1280 / 16 + 1 = 81 * * height: 800 / 16 + 1 = 51 */ void loadMeshFiles(const dai::Path& pathLeft, const dai::Path& pathRight); /** * Specify mesh calibration data for 'left' and 'right' inputs, as vectors of bytes. * See `loadMeshFiles` for the expected data format */ void loadMeshData(const std::vector<std::uint8_t>& dataLeft, const std::vector<std::uint8_t>& dataRight); /** * Set the distance between mesh points. Default: (16, 16) */ void setMeshStep(int width, int height); /** * Specify input resolution size * * Optional if MonoCamera exists, otherwise necessary */ void setInputResolution(int width, int height); /** * Specify input resolution size * * Optional if MonoCamera exists, otherwise necessary */ void setInputResolution(std::tuple<int, int> resolution); /** * Specify disparity/depth output resolution size, implemented by scaling. * * Currently only applicable when aligning to RGB camera */ void setOutputSize(int width, int height); /** * Specifies whether the frames resized by `setOutputSize` should preserve aspect ratio, * with potential cropping when enabled. Default `true` */ void setOutputKeepAspectRatio(bool keep); /** * @param median Set kernel size for disparity/depth median filtering, or disable */ [[deprecated("Use 'initialConfig.setMedianFilter()' instead")]] void setMedianFilter(dai::MedianFilter median); /** * @param align Set the disparity/depth alignment: centered (between the 'left' and 'right' inputs), * or from the perspective of a rectified output stream */ void setDepthAlign(Properties::DepthAlign align); /** * @param camera Set the camera from whose perspective the disparity/depth will be aligned */ void setDepthAlign(CameraBoardSocket camera); /** * Confidence threshold for disparity calculation * @param confThr Confidence threshold value 0..255 */ [[deprecated("Use 'initialConfig.setConfidenceThreshold()' instead")]] void setConfidenceThreshold(int confThr); /** * Rectify input images or not. */ void setRectification(bool enable); /** * Computes and combines disparities in both L-R and R-L directions, and combine them. * * For better occlusion handling, discarding invalid disparity values */ void setLeftRightCheck(bool enable); /** * Computes disparity with sub-pixel interpolation (3 fractional bits by default). * * Suitable for long range. Currently incompatible with extended disparity */ void setSubpixel(bool enable); /** * Disparity range increased from 0-95 to 0-190, combined from full resolution and downscaled images. * * Suitable for short range objects. Currently incompatible with sub-pixel disparity */ void setExtendedDisparity(bool enable); /** * Fill color for missing data at frame edges * @param color Grayscale 0..255, or -1 to replicate pixels */ void setRectifyEdgeFillColor(int color); /** * DEPRECATED function. It was removed, since rectified images are not flipped anymore. * Mirror rectified frames, only when LR-check mode is disabled. Default `true`. * The mirroring is required to have a normal non-mirrored disparity/depth output. * * A side effect of this option is disparity alignment to the perspective of left or right input: * `false`: mapped to left and mirrored, `true`: mapped to right. * With LR-check enabled, this option is ignored, none of the outputs are mirrored, * and disparity is mapped to right. * * @param enable True for normal disparity/depth, otherwise mirrored */ [[deprecated("Function call should be removed")]] void setRectifyMirrorFrame(bool enable); /** * Enable outputting rectified frames. Optimizes computation on device side when disabled. * DEPRECATED. The outputs are auto-enabled if used */ [[deprecated("Function call should be removed")]] void setOutputRectified(bool enable); /** * Enable outputting 'depth' stream (converted from disparity). * In certain configurations, this will disable 'disparity' stream. * DEPRECATED. The output is auto-enabled if used */ [[deprecated("Function call should be removed")]] void setOutputDepth(bool enable); /** * Enable runtime stereo mode switch, e.g. from standard to LR-check. * Note: when enabled resources allocated for worst case to enable switching to any mode. */ void setRuntimeModeSwitch(bool enable); /** * Specify number of frames in pool. * @param numFramesPool How many frames should the pool have */ void setNumFramesPool(int numFramesPool); /** * Useful for normalization of the disparity map. * @returns Maximum disparity value that the node can return */ [[deprecated("Use 'initialConfig.getMaxDisparity()' instead")]] float getMaxDisparity() const; /** * Specify allocated hardware resources for stereo depth. * Suitable only to increase post processing runtime. * @param numShaves Number of shaves. * @param numMemorySlices Number of memory slices. */ void setPostProcessingHardwareResources(int numShaves, int numMemorySlices); /** * Sets a default preset based on specified option. * @param mode Stereo depth preset mode */ void setDefaultProfilePreset(PresetMode mode); /** * Sets a default preset based on specified option. * @param mode Stereo depth preset mode */ void setFocalLengthFromCalibration(bool focalLengthFromCalibration); /** * Use 3x3 homography matrix for stereo rectification instead of sparse mesh generated on device. * Default value: true. * If custom mesh data is provided through loadMeshData or loadMeshFiles this option is ignored. * @param useHomographyRectification true: 3x3 homography matrix generated from calibration data is used for stereo rectification, can't correct lens * distortion. * false: sparse mesh is generated on-device from calibration data with mesh step specified with setMeshStep (Default: (16, 16)), can correct lens * distortion. Implementation for generating the mesh is same as opencv's initUndistortRectifyMap function. */ void useHomographyRectification(bool useHomographyRectification); }; } // namespace node } // namespace dai <commit_msg>Add explicit documentation about loadMesh behavior; specify that only the first 8 distortion coefficients are used<commit_after>#pragma once #include "depthai/pipeline/Node.hpp" // shared #include "depthai-shared/properties/StereoDepthProperties.hpp" #include "depthai/pipeline/datatype/StereoDepthConfig.hpp" namespace dai { namespace node { /** * @brief StereoDepth node. Compute stereo disparity and depth from left-right image pair. */ class StereoDepth : public NodeCRTP<Node, StereoDepth, StereoDepthProperties> { public: constexpr static const char* NAME = "StereoDepth"; /** * Preset modes for stereo depth. */ enum class PresetMode : std::uint32_t { HIGH_ACCURACY, HIGH_DENSITY }; protected: Properties& getProperties(); private: PresetMode presetMode = PresetMode::HIGH_DENSITY; std::shared_ptr<RawStereoDepthConfig> rawConfig; public: StereoDepth(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId); StereoDepth(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId, std::unique_ptr<Properties> props); /** * Initial config to use for StereoDepth. */ StereoDepthConfig initialConfig; /** * Input StereoDepthConfig message with ability to modify parameters in runtime. * Default queue is non-blocking with size 4. */ Input inputConfig{*this, "inputConfig", Input::Type::SReceiver, false, 4, {{DatatypeEnum::StereoDepthConfig, false}}}; /** * Input for left ImgFrame of left-right pair * * Default queue is non-blocking with size 8 */ Input left{*this, "left", Input::Type::SReceiver, false, 8, true, {{DatatypeEnum::ImgFrame, true}}}; /** * Input for right ImgFrame of left-right pair * * Default queue is non-blocking with size 8 */ Input right{*this, "right", Input::Type::SReceiver, false, 8, true, {{DatatypeEnum::ImgFrame, true}}}; /** * Outputs ImgFrame message that carries RAW16 encoded (0..65535) depth data in depth units (millimeter by default). * * Non-determined / invalid depth values are set to 0 */ Output depth{*this, "depth", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries RAW8 / RAW16 encoded disparity data: * RAW8 encoded (0..95) for standard mode; * RAW8 encoded (0..190) for extended disparity mode; * RAW16 encoded for subpixel disparity mode: * - 0..760 for 3 fractional bits (by default) * - 0..1520 for 4 fractional bits * - 0..3040 for 5 fractional bits */ Output disparity{*this, "disparity", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Passthrough ImgFrame message from 'left' Input. */ Output syncedLeft{*this, "syncedLeft", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Passthrough ImgFrame message from 'right' Input. */ Output syncedRight{*this, "syncedRight", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries RAW8 encoded (grayscale) rectified frame data. */ Output rectifiedLeft{*this, "rectifiedLeft", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries RAW8 encoded (grayscale) rectified frame data. */ Output rectifiedRight{*this, "rectifiedRight", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs StereoDepthConfig message that contains current stereo configuration. */ Output outConfig{*this, "outConfig", Output::Type::MSender, {{DatatypeEnum::StereoDepthConfig, false}}}; /** * Outputs ImgFrame message that carries left-right check first iteration (before combining with second iteration) disparity map. * Useful for debugging/fine tuning. */ Output debugDispLrCheckIt1{*this, "debugDispLrCheckIt1", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries left-right check second iteration (before combining with first iteration) disparity map. * Useful for debugging/fine tuning. */ Output debugDispLrCheckIt2{*this, "debugDispLrCheckIt2", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries extended left-right check first iteration (downscaled frame, before combining with second iteration) disparity map. * Useful for debugging/fine tuning. */ Output debugExtDispLrCheckIt1{*this, "debugExtDispLrCheckIt1", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries extended left-right check second iteration (downscaled frame, before combining with first iteration) disparity map. * Useful for debugging/fine tuning. */ Output debugExtDispLrCheckIt2{*this, "debugExtDispLrCheckIt2", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries cost dump of disparity map. * Useful for debugging/fine tuning. */ Output debugDispCostDump{*this, "debugDispCostDump", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Outputs ImgFrame message that carries RAW8 confidence map. * Lower values means higher confidence of the calculated disparity value. * RGB alignment, left-right check or any postproccessing (e.g. median filter) is not performed on confidence map. */ Output confidenceMap{*this, "confidenceMap", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}}; /** * Specify that a passthrough/dummy calibration should be used, * when input frames are already rectified (e.g. sourced from recordings on the host) */ [[deprecated("Use 'Stereo::setRectification(false)' instead")]] void setEmptyCalibration(); /** * Specify local filesystem paths to the mesh calibration files for 'left' and 'right' inputs. * * When a mesh calibration is set, it overrides the camera intrinsics/extrinsics matrices. * Overrides useHomographyRectification behavior. * Mesh format: a sequence of (y,x) points as 'float' with coordinates from the input image * to be mapped in the output. The mesh can be subsampled, configured by `setMeshStep`. * * With a 1280x800 resolution and the default (16,16) step, the required mesh size is: * * width: 1280 / 16 + 1 = 81 * * height: 800 / 16 + 1 = 51 */ void loadMeshFiles(const dai::Path& pathLeft, const dai::Path& pathRight); /** * Specify mesh calibration data for 'left' and 'right' inputs, as vectors of bytes. * Overrides useHomographyRectification behavior. * See `loadMeshFiles` for the expected data format */ void loadMeshData(const std::vector<std::uint8_t>& dataLeft, const std::vector<std::uint8_t>& dataRight); /** * Set the distance between mesh points. Default: (16, 16) */ void setMeshStep(int width, int height); /** * Specify input resolution size * * Optional if MonoCamera exists, otherwise necessary */ void setInputResolution(int width, int height); /** * Specify input resolution size * * Optional if MonoCamera exists, otherwise necessary */ void setInputResolution(std::tuple<int, int> resolution); /** * Specify disparity/depth output resolution size, implemented by scaling. * * Currently only applicable when aligning to RGB camera */ void setOutputSize(int width, int height); /** * Specifies whether the frames resized by `setOutputSize` should preserve aspect ratio, * with potential cropping when enabled. Default `true` */ void setOutputKeepAspectRatio(bool keep); /** * @param median Set kernel size for disparity/depth median filtering, or disable */ [[deprecated("Use 'initialConfig.setMedianFilter()' instead")]] void setMedianFilter(dai::MedianFilter median); /** * @param align Set the disparity/depth alignment: centered (between the 'left' and 'right' inputs), * or from the perspective of a rectified output stream */ void setDepthAlign(Properties::DepthAlign align); /** * @param camera Set the camera from whose perspective the disparity/depth will be aligned */ void setDepthAlign(CameraBoardSocket camera); /** * Confidence threshold for disparity calculation * @param confThr Confidence threshold value 0..255 */ [[deprecated("Use 'initialConfig.setConfidenceThreshold()' instead")]] void setConfidenceThreshold(int confThr); /** * Rectify input images or not. */ void setRectification(bool enable); /** * Computes and combines disparities in both L-R and R-L directions, and combine them. * * For better occlusion handling, discarding invalid disparity values */ void setLeftRightCheck(bool enable); /** * Computes disparity with sub-pixel interpolation (3 fractional bits by default). * * Suitable for long range. Currently incompatible with extended disparity */ void setSubpixel(bool enable); /** * Disparity range increased from 0-95 to 0-190, combined from full resolution and downscaled images. * * Suitable for short range objects. Currently incompatible with sub-pixel disparity */ void setExtendedDisparity(bool enable); /** * Fill color for missing data at frame edges * @param color Grayscale 0..255, or -1 to replicate pixels */ void setRectifyEdgeFillColor(int color); /** * DEPRECATED function. It was removed, since rectified images are not flipped anymore. * Mirror rectified frames, only when LR-check mode is disabled. Default `true`. * The mirroring is required to have a normal non-mirrored disparity/depth output. * * A side effect of this option is disparity alignment to the perspective of left or right input: * `false`: mapped to left and mirrored, `true`: mapped to right. * With LR-check enabled, this option is ignored, none of the outputs are mirrored, * and disparity is mapped to right. * * @param enable True for normal disparity/depth, otherwise mirrored */ [[deprecated("Function call should be removed")]] void setRectifyMirrorFrame(bool enable); /** * Enable outputting rectified frames. Optimizes computation on device side when disabled. * DEPRECATED. The outputs are auto-enabled if used */ [[deprecated("Function call should be removed")]] void setOutputRectified(bool enable); /** * Enable outputting 'depth' stream (converted from disparity). * In certain configurations, this will disable 'disparity' stream. * DEPRECATED. The output is auto-enabled if used */ [[deprecated("Function call should be removed")]] void setOutputDepth(bool enable); /** * Enable runtime stereo mode switch, e.g. from standard to LR-check. * Note: when enabled resources allocated for worst case to enable switching to any mode. */ void setRuntimeModeSwitch(bool enable); /** * Specify number of frames in pool. * @param numFramesPool How many frames should the pool have */ void setNumFramesPool(int numFramesPool); /** * Useful for normalization of the disparity map. * @returns Maximum disparity value that the node can return */ [[deprecated("Use 'initialConfig.getMaxDisparity()' instead")]] float getMaxDisparity() const; /** * Specify allocated hardware resources for stereo depth. * Suitable only to increase post processing runtime. * @param numShaves Number of shaves. * @param numMemorySlices Number of memory slices. */ void setPostProcessingHardwareResources(int numShaves, int numMemorySlices); /** * Sets a default preset based on specified option. * @param mode Stereo depth preset mode */ void setDefaultProfilePreset(PresetMode mode); /** * Sets a default preset based on specified option. * @param mode Stereo depth preset mode */ void setFocalLengthFromCalibration(bool focalLengthFromCalibration); /** * Use 3x3 homography matrix for stereo rectification instead of sparse mesh generated on device. * Default value: true. * If custom mesh data is provided through loadMeshData or loadMeshFiles this option is ignored. * @param useHomographyRectification true: 3x3 homography matrix generated from calibration data is used for stereo rectification, can't correct lens * distortion. * false: sparse mesh is generated on-device from calibration data with mesh step specified with setMeshStep (Default: (16, 16)), can correct lens * distortion. Implementation for generating the mesh is same as opencv's initUndistortRectifyMap function. Only the first 8 distortion coefficients are * used from calibration data. */ void useHomographyRectification(bool useHomographyRectification); }; } // namespace node } // namespace dai <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of mcompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QX11Info> #include <QKeySequence> #include <QKeyEvent> #include <QEvent> #include <QTimer> #include <QApplication> #include <QDesktopWidget> #include "mcompositewindow.h" #include "mcompositescene.h" #include "mcompositewindowgroup.h" #include "mdecoratorframe.h" #include <X11/extensions/Xfixes.h> #ifdef HAVE_SHAPECONST #include <X11/extensions/shapeconst.h> #else #include <X11/extensions/shape.h> #endif #include <X11/extensions/Xcomposite.h> static int error_handler(Display * , XErrorEvent *error) { if (error->resourceid == QX11Info::appRootWindow() && error->error_code == BadAccess) { qCritical("Another window manager is running."); ::exit(0); } if (error->error_code == BadMatch) qDebug() << "Bad match error " << error->resourceid; return 0; } MCompositeScene::MCompositeScene(QObject *p) : QGraphicsScene(p), keep_black(false) { setBackgroundBrush(Qt::NoBrush); setForegroundBrush(Qt::NoBrush); setSceneRect(QRect(0, 0, QApplication::desktop()->width(), QApplication::desktop()->height())); installEventFilter(this); } void MCompositeScene::prepareRoot() { Display *dpy = QX11Info::display(); Window root = QX11Info::appRootWindow(); XSetWindowAttributes sattr; sattr.event_mask = SubstructureRedirectMask | SubstructureNotifyMask | StructureNotifyMask | PropertyChangeMask; // All newly mapped windows should be redirected to avoid double Expose XCompositeRedirectSubwindows(dpy, root, CompositeRedirectManual); XChangeWindowAttributes(dpy, root, CWEventMask, &sattr); XSelectInput(dpy, root, SubstructureNotifyMask | SubstructureRedirectMask | StructureNotifyMask | PropertyChangeMask | FocusChangeMask); XSetErrorHandler(error_handler); } void MCompositeScene::drawItems(QPainter *painter, int numItems, QGraphicsItem *items[], const QStyleOptionGraphicsItem options[], QWidget *widget) { if (keep_black) { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); // freeze updates views()[0]->setUpdatesEnabled(false); return; } QRegion visible(sceneRect().toRect()); QVector<int> to_paint(10); int size = 0; bool desktop_painted = false; // visibility is determined from top to bottom for (int i = numItems - 1; i >= 0; --i) { MCompositeWindow *cw = (MCompositeWindow *) items[i]; #ifdef GLES2_VERSION static int item_type = MCompositeWindowGroup::Type; #else static int item_type = QGraphicsItem::Type + 2; #endif if (cw->type() != item_type) { MCompositeWindow *man; if (!cw->propertyCache()) // this window is dead continue; if (cw->propertyCache()->isDecorator() && (!(man = MDecoratorFrame::instance()->managedClient()) || man->isWindowTransitioning())) // if we have a transition animation, don't draw the decorator // lest we can have it drawn with the transition (especially // when desktop window is not yet shown, NB#192454) continue; if (cw->group()) // items that belong to a group are drawn by the group continue; if (cw->isDirectRendered() || !cw->isVisible() || !(cw->propertyCache()->isMapped() || cw->isWindowTransitioning()) || cw->propertyCache()->isInputOnly()) continue; if (visible.isEmpty()) // nothing below is visible anymore break; } // Ensure that intersects() still work, otherwise, painting a window // is skipped when another window above it is scaled or moved to an // area that exposed the lower window and causes an ugly flicker. // r reflects the applied transformation and position of the window QRegion r = cw->sceneTransform().map(cw->propertyCache()->shapeRegion()); // transitioning window can be smaller than shapeRegion(), so paint // all transitioning windows if (cw->isWindowTransitioning() || visible.intersects(r) || cw->type() == MCompositeWindowGroup::Type) { if (size >= 9) to_paint.resize((unsigned)to_paint.size()+1); to_paint[size++] = i; if (cw->propertyCache()->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DESKTOP)) desktop_painted = true; } // subtract opaque regions if (!cw->isWindowTransitioning() && !cw->propertyCache()->hasAlphaAndIsNotOpaque() && cw->opacity() == 1.0 && !cw->group()) // window is not renderered off-screen) visible -= r; } glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); if (size > 0) { // paint from bottom to top so that blending works for (int i = size - 1; i >= 0; --i) { int item_i = to_paint[i]; MCompositeWindow *cw = (MCompositeWindow*)items[item_i]; if (cw->propertyCache()->isDecorator() && !MDecoratorFrame::instance()->managedClient()) { // don't paint decorator on top of plain black background // (see NB#182860, NB#192454) continue; } // TODO: paint only the intersected region (glScissor?) painter->save(); painter->setMatrix(cw->sceneMatrix(), true); cw->paint(painter, &options[item_i], widget); painter->restore(); desktop_painted = true; // desktop or something else painted } } } <commit_msg>comment out useless Bad match error message - uncomment it if you need it..<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of mcompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QX11Info> #include <QKeySequence> #include <QKeyEvent> #include <QEvent> #include <QTimer> #include <QApplication> #include <QDesktopWidget> #include "mcompositewindow.h" #include "mcompositescene.h" #include "mcompositewindowgroup.h" #include "mdecoratorframe.h" #include <X11/extensions/Xfixes.h> #ifdef HAVE_SHAPECONST #include <X11/extensions/shapeconst.h> #else #include <X11/extensions/shape.h> #endif #include <X11/extensions/Xcomposite.h> static int error_handler(Display * , XErrorEvent *error) { if (error->resourceid == QX11Info::appRootWindow() && error->error_code == BadAccess) { qCritical("Another window manager is running."); ::exit(0); } /*if (error->error_code == BadMatch) qDebug() << "Bad match error " << error->resourceid;*/ return 0; } MCompositeScene::MCompositeScene(QObject *p) : QGraphicsScene(p), keep_black(false) { setBackgroundBrush(Qt::NoBrush); setForegroundBrush(Qt::NoBrush); setSceneRect(QRect(0, 0, QApplication::desktop()->width(), QApplication::desktop()->height())); installEventFilter(this); } void MCompositeScene::prepareRoot() { Display *dpy = QX11Info::display(); Window root = QX11Info::appRootWindow(); XSetWindowAttributes sattr; sattr.event_mask = SubstructureRedirectMask | SubstructureNotifyMask | StructureNotifyMask | PropertyChangeMask; // All newly mapped windows should be redirected to avoid double Expose XCompositeRedirectSubwindows(dpy, root, CompositeRedirectManual); XChangeWindowAttributes(dpy, root, CWEventMask, &sattr); XSelectInput(dpy, root, SubstructureNotifyMask | SubstructureRedirectMask | StructureNotifyMask | PropertyChangeMask | FocusChangeMask); XSetErrorHandler(error_handler); } void MCompositeScene::drawItems(QPainter *painter, int numItems, QGraphicsItem *items[], const QStyleOptionGraphicsItem options[], QWidget *widget) { if (keep_black) { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); // freeze updates views()[0]->setUpdatesEnabled(false); return; } QRegion visible(sceneRect().toRect()); QVector<int> to_paint(10); int size = 0; bool desktop_painted = false; // visibility is determined from top to bottom for (int i = numItems - 1; i >= 0; --i) { MCompositeWindow *cw = (MCompositeWindow *) items[i]; #ifdef GLES2_VERSION static int item_type = MCompositeWindowGroup::Type; #else static int item_type = QGraphicsItem::Type + 2; #endif if (cw->type() != item_type) { MCompositeWindow *man; if (!cw->propertyCache()) // this window is dead continue; if (cw->propertyCache()->isDecorator() && (!(man = MDecoratorFrame::instance()->managedClient()) || man->isWindowTransitioning())) // if we have a transition animation, don't draw the decorator // lest we can have it drawn with the transition (especially // when desktop window is not yet shown, NB#192454) continue; if (cw->group()) // items that belong to a group are drawn by the group continue; if (cw->isDirectRendered() || !cw->isVisible() || !(cw->propertyCache()->isMapped() || cw->isWindowTransitioning()) || cw->propertyCache()->isInputOnly()) continue; if (visible.isEmpty()) // nothing below is visible anymore break; } // Ensure that intersects() still work, otherwise, painting a window // is skipped when another window above it is scaled or moved to an // area that exposed the lower window and causes an ugly flicker. // r reflects the applied transformation and position of the window QRegion r = cw->sceneTransform().map(cw->propertyCache()->shapeRegion()); // transitioning window can be smaller than shapeRegion(), so paint // all transitioning windows if (cw->isWindowTransitioning() || visible.intersects(r) || cw->type() == MCompositeWindowGroup::Type) { if (size >= 9) to_paint.resize((unsigned)to_paint.size()+1); to_paint[size++] = i; if (cw->propertyCache()->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DESKTOP)) desktop_painted = true; } // subtract opaque regions if (!cw->isWindowTransitioning() && !cw->propertyCache()->hasAlphaAndIsNotOpaque() && cw->opacity() == 1.0 && !cw->group()) // window is not renderered off-screen) visible -= r; } glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); if (size > 0) { // paint from bottom to top so that blending works for (int i = size - 1; i >= 0; --i) { int item_i = to_paint[i]; MCompositeWindow *cw = (MCompositeWindow*)items[item_i]; if (cw->propertyCache()->isDecorator() && !MDecoratorFrame::instance()->managedClient()) { // don't paint decorator on top of plain black background // (see NB#182860, NB#192454) continue; } // TODO: paint only the intersected region (glScissor?) painter->save(); painter->setMatrix(cw->sceneMatrix(), true); cw->paint(painter, &options[item_i], widget); painter->restore(); desktop_painted = true; // desktop or something else painted } } } <|endoftext|>
<commit_before>#include <QtGui> class Widget : public QWidget { Q_OBJECT public: Widget() { QWidget *stackWidget = new QWidget; stackWidget->setFixedSize(400, 300); button = new QPushButton("pushbutton", stackWidget); plainTextEdit = new QPlainTextEdit(stackWidget); plainTextEdit->setWordWrapMode(QTextOption::NoWrap); QString s = "foo bar bar foo foo bar bar foo"; for (int i = 0; i < 10; ++i) { plainTextEdit->appendPlainText(s); s.remove(1, 2); } calendar = new QCalendarWidget(stackWidget); button->move(10, 10); button->resize(100, 100); plainTextEdit->move(30, 70); plainTextEdit->resize(100, 100); calendar->move(80, 40); QWidget *buttonOps = new QWidget; QVBoxLayout *l = new QVBoxLayout(buttonOps); QPushButton *lower = new QPushButton("button: lower"); connect(lower, SIGNAL(clicked()), button, SLOT(lower())); l->addWidget(lower); QPushButton *raise = new QPushButton("button: raise"); connect(raise, SIGNAL(clicked()), button, SLOT(raise())); l->addWidget(raise); lower = new QPushButton("calendar: lower"); connect(lower, SIGNAL(clicked()), calendar, SLOT(lower())); l->addWidget(lower); raise = new QPushButton("calendar: raise"); connect(raise, SIGNAL(clicked()), calendar, SLOT(raise())); l->addWidget(raise); QPushButton *stackUnder = new QPushButton("calendar: stack under textedit"); connect(stackUnder, SIGNAL(clicked()), this, SLOT(stackCalendarUnderTextEdit())); l->addWidget(stackUnder); lower = new QPushButton("lower textedit"); connect(lower, SIGNAL(clicked()), plainTextEdit, SLOT(lower())); l->addWidget(lower); raise = new QPushButton("raise textedit"); connect(raise, SIGNAL(clicked()), plainTextEdit, SLOT(raise())); l->addWidget(raise); QHBoxLayout *mainLayout = new QHBoxLayout(this); mainLayout->addWidget(buttonOps); mainLayout->addWidget(stackWidget); } private Q_SLOTS: void stackCalendarUnderTextEdit() { calendar->stackUnder(plainTextEdit); } private: QPushButton *button; QPlainTextEdit *plainTextEdit; QCalendarWidget *calendar; }; int main(int argc, char **argv) { QApplication app(argc, argv); Widget w; w.show(); return app.exec(); } #include "main.moc" <commit_msg>Add copyright header so the autotest will pass.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> class Widget : public QWidget { Q_OBJECT public: Widget() { QWidget *stackWidget = new QWidget; stackWidget->setFixedSize(400, 300); button = new QPushButton("pushbutton", stackWidget); plainTextEdit = new QPlainTextEdit(stackWidget); plainTextEdit->setWordWrapMode(QTextOption::NoWrap); QString s = "foo bar bar foo foo bar bar foo"; for (int i = 0; i < 10; ++i) { plainTextEdit->appendPlainText(s); s.remove(1, 2); } calendar = new QCalendarWidget(stackWidget); button->move(10, 10); button->resize(100, 100); plainTextEdit->move(30, 70); plainTextEdit->resize(100, 100); calendar->move(80, 40); QWidget *buttonOps = new QWidget; QVBoxLayout *l = new QVBoxLayout(buttonOps); QPushButton *lower = new QPushButton("button: lower"); connect(lower, SIGNAL(clicked()), button, SLOT(lower())); l->addWidget(lower); QPushButton *raise = new QPushButton("button: raise"); connect(raise, SIGNAL(clicked()), button, SLOT(raise())); l->addWidget(raise); lower = new QPushButton("calendar: lower"); connect(lower, SIGNAL(clicked()), calendar, SLOT(lower())); l->addWidget(lower); raise = new QPushButton("calendar: raise"); connect(raise, SIGNAL(clicked()), calendar, SLOT(raise())); l->addWidget(raise); QPushButton *stackUnder = new QPushButton("calendar: stack under textedit"); connect(stackUnder, SIGNAL(clicked()), this, SLOT(stackCalendarUnderTextEdit())); l->addWidget(stackUnder); lower = new QPushButton("lower textedit"); connect(lower, SIGNAL(clicked()), plainTextEdit, SLOT(lower())); l->addWidget(lower); raise = new QPushButton("raise textedit"); connect(raise, SIGNAL(clicked()), plainTextEdit, SLOT(raise())); l->addWidget(raise); QHBoxLayout *mainLayout = new QHBoxLayout(this); mainLayout->addWidget(buttonOps); mainLayout->addWidget(stackWidget); } private Q_SLOTS: void stackCalendarUnderTextEdit() { calendar->stackUnder(plainTextEdit); } private: QPushButton *button; QPlainTextEdit *plainTextEdit; QCalendarWidget *calendar; }; int main(int argc, char **argv) { QApplication app(argc, argv); Widget w; w.show(); return app.exec(); } #include "main.moc" <|endoftext|>
<commit_before>/** * \file * \brief STM32F0 chip vector table and default weak handlers * * \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/distortosConfiguration.h" #include <cstddef> /*---------------------------------------------------------------------------------------------------------------------+ | vectors' configuration +---------------------------------------------------------------------------------------------------------------------*/ #if defined(CONFIG_CHIP_STM32L053) || defined(CONFIG_CHIP_STM32L063) || defined(CONFIG_CHIP_STM32L073) || \ defined(CONFIG_CHIP_STM32L083) #define STM32L0_X3_VECTORS #elif defined(CONFIG_CHIP_STM32L052) || defined(CONFIG_CHIP_STM32L062) || defined(CONFIG_CHIP_STM32L072) || \ defined(CONFIG_CHIP_STM32L082) #define STM32L0_X2_VECTORS #else #define SMT32L0_STANDARD_VECTORS #endif extern "C" { /*---------------------------------------------------------------------------------------------------------------------+ | default weak handlers +---------------------------------------------------------------------------------------------------------------------*/ // 0x40, 0: Window watchdog __attribute__ ((weak)) void WWDG_IRQHandler() { while (1); } // 0x44, 1: PVD through EXTI Line detect __attribute__ ((weak)) void PVD_IRQHandler() { while (1); } // 0x48, 2: RTC through EXTI Line __attribute__ ((weak)) void RTC_IRQHandler() { while (1); } // 0x4c, 3: Flash __attribute__ ((weak)) void FLASH_IRQHandler() { while (1); } // 0x50, 4: RCC and CRS __attribute__ ((weak)) void RCC_CRS_IRQHandler() { while (1); } // 0x54, 5: EXTI Line[1:0] __attribute__ ((weak)) void EXTI0_1_IRQHandler() { while (1); } // 0x58, 6: EXTI Line[3:2] __attribute__ ((weak)) void EXTI2_3_IRQHandler() { while (1); } // 0x5c, 7: EXTI Line[15:4] __attribute__ ((weak)) void EXTI4_15_IRQHandler() { while (1); } #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) // 0x60, 8: TSC __attribute__ ((weak)) void TSC_IRQHandler() { while (1); } #else // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) // 0x60, 8: Reserved __attribute__ ((weak)) void Reserved_0x60_Handler() { while (1); } #endif // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) // 0x64, 9: DMA channel 1 __attribute__ ((weak)) void DMA_Ch1_IRQHandler() { while (1); } // 0x68, 10: DMA channel 2 and 3 __attribute__ ((weak)) void DMA_Ch2_3_IRQHandler() { while (1); } // 0x6c, 11: DMA channel 4, 5, 6 and 7 __attribute__ ((weak)) void DMA_Ch4_5_6_7_IRQHandler() { while (1); } // 0x70, 12: ADC1, COMP1 and COMP2 __attribute__ ((weak)) void ADC1_COMP_IRQHandler() { while (1); } // 0x74, 13: LPTIM1 __attribute__ ((weak)) void LPTIM1_IRQHandler() { while (1); } // 0x78, 14: USART4 and USART5 __attribute__ ((weak)) void USART4_5_IRQHandler() { while (1); } // 0x7c, 15: TIM2 __attribute__ ((weak)) void TIM2_IRQHandler() { while (1); } // 0x80, 16: TIM3 __attribute__ ((weak)) void TIM3_IRQHandler() { while (1); } #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) // 0x84, 17: TIM6 and DAC __attribute__ ((weak)) void TIM6_DAC_IRQHandler() { while (1); } #else // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) // 0x84, 17: TIM6 __attribute__ ((weak)) void TIM6_IRQHandler() { while (1); } #endif // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) // 0x88, 18: TIM7 __attribute__ ((weak)) void TIM7_IRQHandler() { while (1); } // 0x8c, 19: Reserved __attribute__ ((weak)) void Reserved_0x8c_Handler() { while (1); } // 0x90, 20: TIM21 __attribute__ ((weak)) void TIM21_IRQHandler() { while (1); } // 0x94, 21: I2C3 __attribute__ ((weak)) void I2C3_IRQHandler() { while (1); } // 0x98, 22: TIM22 __attribute__ ((weak)) void TIM22_IRQHandler() { while (1); } // 0x9c, 23: I2C1 __attribute__ ((weak)) void I2C1_IRQHandler() { while (1); } // 0xa0, 24: I2C2 __attribute__ ((weak)) void I2C2_IRQHandler() { while (1); } // 0xa4, 25: SPI1 __attribute__ ((weak)) void SPI1_IRQHandler() { while (1); } // 0xa8, 26: SPI2 __attribute__ ((weak)) void SPI2_IRQHandler() { while (1); } // 0xac, 27: USART1 __attribute__ ((weak)) void USART1_IRQHandler() { while (1); } // 0xb0, 28: USART2 __attribute__ ((weak)) void USART2_IRQHandler() { while (1); } #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) // 0xb4, 29: AES and RNG and LPUART1 __attribute__ ((weak)) void AES_RNG_LPUART1_IRQHandler() { while (1); } #else // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) // 0xb4, 29: AES and LPUART1 __attribute__ ((weak)) void AES_LPUART1_IRQHandler() { while (1); } #endif // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) #if defined(STM32L0_X3_VECTORS) // 0xb8, 30: LCD __attribute__ ((weak)) void LCD_IRQHandler() { while (1); } #elif defined(STM32L0_X2_VECTORS) // 0xb8, 30: Reserved __attribute__ ((weak)) void Reserved_0xb8_Handler() { while (1); } #endif // !defined(STM32L0_X2_VECTORS) #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) // 0xbc, 31: USB __attribute__ ((weak)) void USB_IRQHandler() { while (1); } #endif // defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) } // extern "C" /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// single interrupt vector - pointer to function with no arguments and no return value using InterruptVector = void(*)(); /*---------------------------------------------------------------------------------------------------------------------+ | global variables +---------------------------------------------------------------------------------------------------------------------*/ /// chip vector table extern "C" const InterruptVector chipVectors[] __attribute__ ((section(".chipVectors"), used)) { WWDG_IRQHandler, // 0x40, 0: Window watchdog PVD_IRQHandler, // 0x44, 1: PVD through EXTI Line detect RTC_IRQHandler, // 0x48, 2: RTC through EXTI Line FLASH_IRQHandler, // 0x4c, 3: Flash RCC_CRS_IRQHandler, // 0x50, 4: RCC EXTI0_1_IRQHandler, // 0x54, 5: EXTI Line[1:0] EXTI2_3_IRQHandler, // 0x58, 6: EXTI Line[3:2] EXTI4_15_IRQHandler, // 0x5c, 7: EXTI Line[15:4] #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) TSC_IRQHandler, // 0x60, 8: Reserved #else // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) Reserved_0x60_Handler, // 0x60, 8: Reserved #endif // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) DMA_Ch1_IRQHandler, // 0x64, 9: DMA channel 1 DMA_Ch2_3_IRQHandler, // 0x68, 10: DMA channel 2 and 3 DMA_Ch4_5_6_7_IRQHandler, // 0x6c, 11: DMA channel 4, 5, 6 and 7 ADC1_COMP_IRQHandler, // 0x70, 12: ADC1, COMP1 and COMP2 LPTIM1_IRQHandler, // 0x74, 13: LPTIM1 USART4_5_IRQHandler, // 0x78, 14: USART4 and USART5 TIM2_IRQHandler, // 0x7c, 15: TIM2 TIM3_IRQHandler, // 0x80, 16: TIM3 #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) TIM6_DAC_IRQHandler, // 0x84, 17: TIM6 and DAC #else // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) TIM6_IRQHandler, // 0x84, 17: TIM6 #endif // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) TIM7_IRQHandler, // 0x88, 18: TIM7 Reserved_0x8c_Handler, // 0x8c, 19: Reserved TIM21_IRQHandler, // 0x90, 20: TIM21 I2C3_IRQHandler, // 0x94, 21: Reserved TIM22_IRQHandler, // 0x98, 22: TIM22 I2C1_IRQHandler, // 0x9c, 23: I2C1 I2C2_IRQHandler, // 0xa0, 24: I2C2 SPI1_IRQHandler, // 0xa4, 25: SPI1 SPI2_IRQHandler, // 0xa8, 26: SPI2 USART1_IRQHandler, // 0xb0, 27: USART1 USART2_IRQHandler, // 0xb0, 28: USART2 #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) AES_RNG_LPUART1_IRQHandler, // 0xb4, 29: AES and RNG and LPUART1 #else // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) AES_LPUART1_IRQHandler, // 0xb4, 29: AES and LPUART1 #endif // !defined(STM32L0_X2_VECTORS) && !defined(STM32L0_X3_VECTORS) #if defined(STM32L0_X3_VECTORS) LCD_IRQHandler, // 0xb8, 30: LCD #elif defined(STM32L0_X2_VECTORS) Reserved_0xb8_Handler, // 0xb8, 30: Reserved #endif // !defined(STM32L0_X2_VECTORS) #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) USB_IRQHandler, // 0xbc, 31: USB #endif // defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) }; namespace { /// expected number of chip vectors constexpr size_t expectedChipVectorsSize { #if defined(STM32L0_X2_VECTORS) || defined(STM32L0_X3_VECTORS) 32 #else 30 #endif }; static_assert(sizeof(chipVectors) / sizeof(*chipVectors) == expectedChipVectorsSize, "Invalid size of chipVectors[]!"); } // namespace <commit_msg>Slight simplification of #defines in STM32L0-chipVectors.cpp<commit_after>/** * \file * \brief STM32F0 chip vector table and default weak handlers * * \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/distortosConfiguration.h" #include <cstddef> /*---------------------------------------------------------------------------------------------------------------------+ | vectors' configuration +---------------------------------------------------------------------------------------------------------------------*/ #if defined(CONFIG_CHIP_STM32L053) || defined(CONFIG_CHIP_STM32L063) || defined(CONFIG_CHIP_STM32L073) || \ defined(CONFIG_CHIP_STM32L083) #define STM32L0X3_VECTORS #elif defined(CONFIG_CHIP_STM32L052) || defined(CONFIG_CHIP_STM32L062) || defined(CONFIG_CHIP_STM32L072) || \ defined(CONFIG_CHIP_STM32L082) #define STM32L0X2_VECTORS #else #define SMT32L0_STANDARD_VECTORS #endif extern "C" { /*---------------------------------------------------------------------------------------------------------------------+ | default weak handlers +---------------------------------------------------------------------------------------------------------------------*/ // 0x40, 0: Window watchdog __attribute__ ((weak)) void WWDG_IRQHandler() { while (1); } // 0x44, 1: PVD through EXTI Line detect __attribute__ ((weak)) void PVD_IRQHandler() { while (1); } // 0x48, 2: RTC through EXTI Line __attribute__ ((weak)) void RTC_IRQHandler() { while (1); } // 0x4c, 3: Flash __attribute__ ((weak)) void FLASH_IRQHandler() { while (1); } // 0x50, 4: RCC and CRS __attribute__ ((weak)) void RCC_CRS_IRQHandler() { while (1); } // 0x54, 5: EXTI Line[1:0] __attribute__ ((weak)) void EXTI0_1_IRQHandler() { while (1); } // 0x58, 6: EXTI Line[3:2] __attribute__ ((weak)) void EXTI2_3_IRQHandler() { while (1); } // 0x5c, 7: EXTI Line[15:4] __attribute__ ((weak)) void EXTI4_15_IRQHandler() { while (1); } #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) // 0x60, 8: TSC __attribute__ ((weak)) void TSC_IRQHandler() { while (1); } #else // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) // 0x60, 8: Reserved __attribute__ ((weak)) void Reserved_0x60_Handler() { while (1); } #endif // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) // 0x64, 9: DMA channel 1 __attribute__ ((weak)) void DMA_Ch1_IRQHandler() { while (1); } // 0x68, 10: DMA channel 2 and 3 __attribute__ ((weak)) void DMA_Ch2_3_IRQHandler() { while (1); } // 0x6c, 11: DMA channel 4, 5, 6 and 7 __attribute__ ((weak)) void DMA_Ch4_5_6_7_IRQHandler() { while (1); } // 0x70, 12: ADC1, COMP1 and COMP2 __attribute__ ((weak)) void ADC1_COMP_IRQHandler() { while (1); } // 0x74, 13: LPTIM1 __attribute__ ((weak)) void LPTIM1_IRQHandler() { while (1); } // 0x78, 14: USART4 and USART5 __attribute__ ((weak)) void USART4_5_IRQHandler() { while (1); } // 0x7c, 15: TIM2 __attribute__ ((weak)) void TIM2_IRQHandler() { while (1); } // 0x80, 16: TIM3 __attribute__ ((weak)) void TIM3_IRQHandler() { while (1); } #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) // 0x84, 17: TIM6 and DAC __attribute__ ((weak)) void TIM6_DAC_IRQHandler() { while (1); } #else // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) // 0x84, 17: TIM6 __attribute__ ((weak)) void TIM6_IRQHandler() { while (1); } #endif // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) // 0x88, 18: TIM7 __attribute__ ((weak)) void TIM7_IRQHandler() { while (1); } // 0x8c, 19: Reserved __attribute__ ((weak)) void Reserved_0x8c_Handler() { while (1); } // 0x90, 20: TIM21 __attribute__ ((weak)) void TIM21_IRQHandler() { while (1); } // 0x94, 21: I2C3 __attribute__ ((weak)) void I2C3_IRQHandler() { while (1); } // 0x98, 22: TIM22 __attribute__ ((weak)) void TIM22_IRQHandler() { while (1); } // 0x9c, 23: I2C1 __attribute__ ((weak)) void I2C1_IRQHandler() { while (1); } // 0xa0, 24: I2C2 __attribute__ ((weak)) void I2C2_IRQHandler() { while (1); } // 0xa4, 25: SPI1 __attribute__ ((weak)) void SPI1_IRQHandler() { while (1); } // 0xa8, 26: SPI2 __attribute__ ((weak)) void SPI2_IRQHandler() { while (1); } // 0xac, 27: USART1 __attribute__ ((weak)) void USART1_IRQHandler() { while (1); } // 0xb0, 28: USART2 __attribute__ ((weak)) void USART2_IRQHandler() { while (1); } #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) // 0xb4, 29: AES and RNG and LPUART1 __attribute__ ((weak)) void AES_RNG_LPUART1_IRQHandler() { while (1); } #else // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) // 0xb4, 29: AES and LPUART1 __attribute__ ((weak)) void AES_LPUART1_IRQHandler() { while (1); } #endif // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) #if defined(STM32L0X3_VECTORS) // 0xb8, 30: LCD __attribute__ ((weak)) void LCD_IRQHandler() { while (1); } #elif defined(STM32L0X2_VECTORS) // 0xb8, 30: Reserved __attribute__ ((weak)) void Reserved_0xb8_Handler() { while (1); } #endif // !defined(STM32L0X2_VECTORS) #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) // 0xbc, 31: USB __attribute__ ((weak)) void USB_IRQHandler() { while (1); } #endif // defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) } // extern "C" /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// single interrupt vector - pointer to function with no arguments and no return value using InterruptVector = void(*)(); /*---------------------------------------------------------------------------------------------------------------------+ | global variables +---------------------------------------------------------------------------------------------------------------------*/ /// chip vector table extern "C" const InterruptVector chipVectors[] __attribute__ ((section(".chipVectors"), used)) { WWDG_IRQHandler, // 0x40, 0: Window watchdog PVD_IRQHandler, // 0x44, 1: PVD through EXTI Line detect RTC_IRQHandler, // 0x48, 2: RTC through EXTI Line FLASH_IRQHandler, // 0x4c, 3: Flash RCC_CRS_IRQHandler, // 0x50, 4: RCC EXTI0_1_IRQHandler, // 0x54, 5: EXTI Line[1:0] EXTI2_3_IRQHandler, // 0x58, 6: EXTI Line[3:2] EXTI4_15_IRQHandler, // 0x5c, 7: EXTI Line[15:4] #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) TSC_IRQHandler, // 0x60, 8: Reserved #else // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) Reserved_0x60_Handler, // 0x60, 8: Reserved #endif // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) DMA_Ch1_IRQHandler, // 0x64, 9: DMA channel 1 DMA_Ch2_3_IRQHandler, // 0x68, 10: DMA channel 2 and 3 DMA_Ch4_5_6_7_IRQHandler, // 0x6c, 11: DMA channel 4, 5, 6 and 7 ADC1_COMP_IRQHandler, // 0x70, 12: ADC1, COMP1 and COMP2 LPTIM1_IRQHandler, // 0x74, 13: LPTIM1 USART4_5_IRQHandler, // 0x78, 14: USART4 and USART5 TIM2_IRQHandler, // 0x7c, 15: TIM2 TIM3_IRQHandler, // 0x80, 16: TIM3 #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) TIM6_DAC_IRQHandler, // 0x84, 17: TIM6 and DAC #else // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) TIM6_IRQHandler, // 0x84, 17: TIM6 #endif // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) TIM7_IRQHandler, // 0x88, 18: TIM7 Reserved_0x8c_Handler, // 0x8c, 19: Reserved TIM21_IRQHandler, // 0x90, 20: TIM21 I2C3_IRQHandler, // 0x94, 21: Reserved TIM22_IRQHandler, // 0x98, 22: TIM22 I2C1_IRQHandler, // 0x9c, 23: I2C1 I2C2_IRQHandler, // 0xa0, 24: I2C2 SPI1_IRQHandler, // 0xa4, 25: SPI1 SPI2_IRQHandler, // 0xa8, 26: SPI2 USART1_IRQHandler, // 0xb0, 27: USART1 USART2_IRQHandler, // 0xb0, 28: USART2 #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) AES_RNG_LPUART1_IRQHandler, // 0xb4, 29: AES and RNG and LPUART1 #else // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) AES_LPUART1_IRQHandler, // 0xb4, 29: AES and LPUART1 #endif // !defined(STM32L0X2_VECTORS) && !defined(STM32L0X3_VECTORS) #if defined(STM32L0X3_VECTORS) LCD_IRQHandler, // 0xb8, 30: LCD #elif defined(STM32L0X2_VECTORS) Reserved_0xb8_Handler, // 0xb8, 30: Reserved #endif // !defined(STM32L0X2_VECTORS) #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) USB_IRQHandler, // 0xbc, 31: USB #endif // defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) }; namespace { /// expected number of chip vectors constexpr size_t expectedChipVectorsSize { #if defined(STM32L0X2_VECTORS) || defined(STM32L0X3_VECTORS) 32 #else 30 #endif }; static_assert(sizeof(chipVectors) / sizeof(*chipVectors) == expectedChipVectorsSize, "Invalid size of chipVectors[]!"); } // namespace <|endoftext|>
<commit_before>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> Copyright (c) 2005-2006,2008 Allen Winter <winter@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "todosummarywidget.h" #include "todoplugin.h" #include "korganizerinterface.h" #include <korganizer/stdcalendar.h> #include <korganizer/koglobals.h> #include <kontactinterfaces/core.h> #include <libkdepim/kpimprefs.h> #include <kcal/calendar.h> #include <kcal/resourcecalendar.h> #include <kcal/resourcelocal.h> #include <kcal/todo.h> #include <kcal/incidenceformatter.h> #include <kdialog.h> #include <kglobal.h> #include <kicon.h> #include <kiconloader.h> #include <klocale.h> #include <kmenu.h> #include <kstandarddirs.h> #include <kurllabel.h> #include <kparts/part.h> #include <QCursor> #include <QEvent> #include <QGridLayout> #include <QLabel> #include <QLayout> #include <QPixmap> #include <QVBoxLayout> #include <QTextDocument> TodoSummaryWidget::TodoSummaryWidget( TodoPlugin *plugin, QWidget *parent ) : Kontact::Summary( parent ), mPlugin( plugin ) { QVBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 3 ); mainLayout->setMargin( 3 ); QWidget *header = createHeader( this, "view-pim-tasks", i18n( "Pending To-dos" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout(); mainLayout->addItem( mLayout ); mLayout->setSpacing( 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL(calendarChanged()), SLOT(updateView()) ); connect( mPlugin->core(), SIGNAL(dayChanged(const QDate&)), SLOT(updateView()) ); updateView(); } TodoSummaryWidget::~TodoSummaryWidget() { } void TodoSummaryWidget::updateView() { qDeleteAll( mLabels ); mLabels.clear(); KConfig config( "kcmtodosummaryrc" ); KConfigGroup daysGroup( &config, "Days" ); int mDaysToGo = daysGroup.readEntry( "DaysToShow", 7 ); KConfigGroup hideGroup( &config, "Hide" ); mHideInProgress = hideGroup.readEntry( "InProgress", false ); mHideOverdue = hideGroup.readEntry( "Overdue", false ); mHideCompleted = hideGroup.readEntry( "Completed", true ); mHideOpenEnded = hideGroup.readEntry( "OpenEnded", true ); mHideNotStarted = hideGroup.readEntry( "NotStarted", false ); // for each todo, // if it passes the filter, append to a list // else continue // sort todolist by summary // sort todolist by priority // sort todolist by due-date // print todolist // the filter is created by the configuration summary options, but includes // days to go before to-do is due // which types of to-dos to hide KCal::Todo::List prList; QDate currDate = QDate::currentDate(); Q_FOREACH ( KCal::Todo *todo, mCalendar->todos() ) { if ( todo->hasDueDate() ) { int daysTo = currDate.daysTo( todo->dtDue().date() ); if ( daysTo >= mDaysToGo ) { continue; } } if ( mHideOverdue && overdue( todo ) ) { continue; } if ( mHideInProgress && inProgress( todo ) ) { continue; } if ( mHideCompleted && completed( todo ) ) { continue; } if ( mHideOpenEnded && openEnded( todo ) ) { continue; } if ( mHideNotStarted && notStarted( todo ) ) { continue; } prList.append( todo ); } if ( !prList.isEmpty() ) { prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortSummary, KCal::SortDirectionAscending ); prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortPriority, KCal::SortDirectionAscending ); prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortDueDate, KCal::SortDirectionAscending ); } // The to-do print consists of the following fields: // icon:due date:days-to-go:priority:summary:status // where, // the icon is the typical to-do icon // the due date it the to-do due date // the days-to-go/past is the #days until/since the to-do is due // this field is left blank if the to-do is open-ended // the priority is the to-do priority // the summary is the to-do summary // the status is comma-separated list of: // overdue // in-progress (started, or >0% completed) // complete (100% completed) // open-ended // not-started (no start date and 0% completed) int counter = 0; QLabel *label = 0; if ( !prList.isEmpty() ) { KIconLoader loader( "korganizer" ); QPixmap pm = loader.loadIcon( "view-calendar-tasks", KIconLoader::Small ); QString str; Q_FOREACH ( KCal::Todo *todo, prList ) { bool makeBold = false; int daysTo = -1; // Icon label label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Due date label str = ""; if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) { daysTo = currDate.daysTo( todo->dtDue().date() ); if ( daysTo == 0 ) { makeBold = true; str = i18n( "Today" ); } else if ( daysTo == 1 ) { str = i18n( "Tomorrow" ); } else { str = KGlobal::locale()->formatDate( todo->dtDue().date(), KLocale::FancyLongDate ); } } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } // Days togo/ago label str = ""; if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) { if ( daysTo > 0 ) { str = i18np( "in 1 day", "in %1 days", daysTo ); } else if ( daysTo < 0 ) { str = i18np( "1 day ago", "%1 days ago", -daysTo ); } else { str = i18n( "due" ); } } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 2 ); mLabels.append( label ); // Priority label str = '[' + QString::number( todo->priority() ) + ']'; label = new QLabel( str, this ); label->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 3 ); mLabels.append( label ); // Summary label str = todo->summary(); if ( todo->relatedTo() ) { // show parent only, not entire ancestry str = todo->relatedTo()->summary() + ':' + str; } if ( !Qt::mightBeRichText( str ) ) { str = Qt::escape( str ); } KUrlLabel *urlLabel = new KUrlLabel( this ); urlLabel->setText( str ); urlLabel->setUrl( todo->uid() ); urlLabel->installEventFilter( this ); urlLabel->setTextFormat( Qt::RichText ); urlLabel->setWordWrap( true ); mLayout->addWidget( urlLabel, counter, 4 ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)), this, SLOT(viewTodo(const QString&)) ); connect( urlLabel, SIGNAL(rightClickedUrl(const QString&)), this, SLOT(popupMenu(const QString&)) ); QString tipText( KCal::IncidenceFormatter::toolTipString( todo, true ) ); if ( !tipText.isEmpty() ) { urlLabel->setToolTip( tipText ); } // State text label str = stateStr( todo ); label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 5 ); mLabels.append( label ); counter++; } } //foreach if ( counter == 0 ) { QLabel *noTodos = new QLabel( i18np( "No pending to-dos due within the next day", "No pending to-dos due within the next %1 days", mDaysToGo ), this ); noTodos->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); mLayout->addWidget( noTodos, 0, 2 ); mLabels.append( noTodos ); } Q_FOREACH( label, mLabels ) { label->show(); } } void TodoSummaryWidget::viewTodo( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_todoplugin" );//ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.editIncidence( uid ); } void TodoSummaryWidget::removeTodo( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_todoplugin" );//ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.deleteIncidence( uid, false ); } void TodoSummaryWidget::completeTodo( const QString &uid ) { KCal::Todo *todo = mCalendar->todo( uid ); if ( !todo->isReadOnly() ) { todo->setCompleted( KDateTime::currentLocalDateTime() ); mCalendar->save(); updateView(); } } void TodoSummaryWidget::popupMenu( const QString &uid ) { KMenu popup( this ); QAction *editIt = popup.addAction( i18n( "&Edit To-do..." ) ); QAction *delIt = popup.addAction( i18n( "&Delete To-do" ) ); delIt->setIcon( KIconLoader::global()->loadIcon( "edit-delete", KIconLoader::Small ) ); QAction *doneIt = 0; KCal::Todo *todo = mCalendar->todo( uid ); if ( !todo->isCompleted() ) { doneIt = popup.addAction( i18n( "&Mark To-do Completed" ) ); doneIt->setIcon( KIconLoader::global()->loadIcon( "task-complete", KIconLoader::Small ) ); } // TODO: add icons to the menu actions const QAction *selectedAction = popup.exec( QCursor::pos() ); if ( selectedAction == editIt ) { viewTodo( uid ); } else if ( selectedAction == delIt ) { removeTodo( uid ); } else if ( doneIt && selectedAction == doneIt ) { completeTodo( uid ); } } bool TodoSummaryWidget::eventFilter( QObject *obj, QEvent *e ) { if ( obj->inherits( "KUrlLabel" ) ) { KUrlLabel* label = static_cast<KUrlLabel*>( obj ); if ( e->type() == QEvent::Enter ) { emit message( i18n( "Edit To-do: \"%1\"", label->text() ) ); } if ( e->type() == QEvent::Leave ) { emit message( QString::null ); //krazy:exclude=nullstrassign for old broken gcc } } return Kontact::Summary::eventFilter( obj, e ); } QStringList TodoSummaryWidget::configModules() const { return QStringList( "kcmtodosummary.desktop" ); } bool TodoSummaryWidget::overdue( KCal::Todo *todo ) { if ( todo->hasDueDate() && !todo->isCompleted() && todo->dtDue().date() < QDate::currentDate() ) { return true; } return false; } bool TodoSummaryWidget::starts( KCal::Todo *todo ) { if ( todo->hasStartDate() && todo->dtStart().date() == QDate::currentDate() ) { return true; } return false; } bool TodoSummaryWidget::completed( KCal::Todo *todo ) { return todo->isCompleted(); } bool TodoSummaryWidget::openEnded( KCal::Todo *todo ) { if ( !todo->hasDueDate() && !todo->isCompleted() ) { return true; } return false; } bool TodoSummaryWidget::inProgress( KCal::Todo *todo ) { if ( todo->percentComplete() > 0 ) { return true; } QDate currDate = QDate::currentDate(); if ( todo->hasStartDate() && todo->hasDueDate() && todo->dtStart().date() < currDate && currDate < todo->dtDue().date() ) { return true; } return false; } bool TodoSummaryWidget::notStarted( KCal::Todo *todo ) { if ( todo->percentComplete() > 0 ) { return false; } if ( !todo->hasStartDate() ) { return false; } if ( todo->dtStart().date() >= QDate::currentDate() ) { return false; } return true; } const QString TodoSummaryWidget::stateStr( KCal::Todo *todo ) { QString str1, str2; if ( openEnded( todo ) ) { str1 = i18n( "open-ended" ); } else if ( overdue( todo ) ) { str1 = "<font color=\"red\">" + i18n( "overdue" ) + "</font>"; } else if ( starts( todo ) ) { str1 = i18n( "starts today" ); } if ( notStarted( todo ) ) { str2 += i18n( "not-started" ); } else if ( completed( todo ) ) { str2 += i18n( "completed" ); } else if ( inProgress( todo ) ) { str2 += i18n( "in-progress " ); str2 += " (" + QString::number( todo->percentComplete() ) + "%)"; } if ( !str1.isEmpty() && !str2.isEmpty() ) { str1 += i18nc( "Separator for status like this: overdue, completed", "," ); } return str1 + str2; } #include "todosummarywidget.moc" <commit_msg>backport SVN commit 919606 by winterz:<commit_after>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> Copyright (c) 2005-2006,2008-2009 Allen Winter <winter@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "todosummarywidget.h" #include "todoplugin.h" #include "korganizerinterface.h" #include <korganizer/stdcalendar.h> #include <korganizer/koglobals.h> #include <kontactinterfaces/core.h> #include <libkdepim/kpimprefs.h> #include <kcal/calendar.h> #include <kcal/resourcecalendar.h> #include <kcal/resourcelocal.h> #include <kcal/todo.h> #include <kcal/incidenceformatter.h> #include <kdialog.h> #include <kglobal.h> #include <kicon.h> #include <kiconloader.h> #include <klocale.h> #include <kmenu.h> #include <kstandarddirs.h> #include <kurllabel.h> #include <kparts/part.h> #include <QCursor> #include <QEvent> #include <QGridLayout> #include <QLabel> #include <QLayout> #include <QPixmap> #include <QVBoxLayout> #include <QTextDocument> TodoSummaryWidget::TodoSummaryWidget( TodoPlugin *plugin, QWidget *parent ) : Kontact::Summary( parent ), mPlugin( plugin ) { QVBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 3 ); mainLayout->setMargin( 3 ); QWidget *header = createHeader( this, "view-pim-tasks", i18n( "Pending To-dos" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout(); mainLayout->addItem( mLayout ); mLayout->setSpacing( 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL(calendarChanged()), SLOT(updateView()) ); connect( mPlugin->core(), SIGNAL(dayChanged(const QDate&)), SLOT(updateView()) ); updateView(); } TodoSummaryWidget::~TodoSummaryWidget() { } void TodoSummaryWidget::updateView() { qDeleteAll( mLabels ); mLabels.clear(); KConfig config( "kcmtodosummaryrc" ); KConfigGroup daysGroup( &config, "Days" ); int mDaysToGo = daysGroup.readEntry( "DaysToShow", 7 ); KConfigGroup hideGroup( &config, "Hide" ); mHideInProgress = hideGroup.readEntry( "InProgress", false ); mHideOverdue = hideGroup.readEntry( "Overdue", false ); mHideCompleted = hideGroup.readEntry( "Completed", true ); mHideOpenEnded = hideGroup.readEntry( "OpenEnded", true ); mHideNotStarted = hideGroup.readEntry( "NotStarted", false ); // for each todo, // if it passes the filter, append to a list // else continue // sort todolist by summary // sort todolist by priority // sort todolist by due-date // print todolist // the filter is created by the configuration summary options, but includes // days to go before to-do is due // which types of to-dos to hide KCal::Todo::List prList; QDate currDate = QDate::currentDate(); Q_FOREACH ( KCal::Todo *todo, mCalendar->todos() ) { if ( todo->hasDueDate() ) { int daysTo = currDate.daysTo( todo->dtDue().date() ); if ( daysTo >= mDaysToGo ) { continue; } } if ( mHideOverdue && overdue( todo ) ) { continue; } if ( mHideInProgress && inProgress( todo ) ) { continue; } if ( mHideCompleted && completed( todo ) ) { continue; } if ( mHideOpenEnded && openEnded( todo ) ) { continue; } if ( mHideNotStarted && notStarted( todo ) ) { continue; } prList.append( todo ); } if ( !prList.isEmpty() ) { prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortSummary, KCal::SortDirectionAscending ); prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortPriority, KCal::SortDirectionAscending ); prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortDueDate, KCal::SortDirectionAscending ); } // The to-do print consists of the following fields: // icon:due date:days-to-go:priority:summary:status // where, // the icon is the typical to-do icon // the due date it the to-do due date // the days-to-go/past is the #days until/since the to-do is due // this field is left blank if the to-do is open-ended // the priority is the to-do priority // the summary is the to-do summary // the status is comma-separated list of: // overdue // in-progress (started, or >0% completed) // complete (100% completed) // open-ended // not-started (no start date and 0% completed) int counter = 0; QLabel *label = 0; if ( !prList.isEmpty() ) { KIconLoader loader( "korganizer" ); QPixmap pm = loader.loadIcon( "view-calendar-tasks", KIconLoader::Small ); QString str; Q_FOREACH ( KCal::Todo *todo, prList ) { bool makeBold = false; int daysTo = -1; // Icon label label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Due date label str = ""; if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) { daysTo = currDate.daysTo( todo->dtDue().date() ); if ( daysTo == 0 ) { makeBold = true; str = i18n( "Today" ); } else if ( daysTo == 1 ) { str = i18n( "Tomorrow" ); } else { str = KGlobal::locale()->formatDate( todo->dtDue().date(), KLocale::FancyLongDate ); } } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } // Days togo/ago label str = ""; if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) { if ( daysTo > 0 ) { str = i18np( "in 1 day", "in %1 days", daysTo ); } else if ( daysTo < 0 ) { str = i18np( "1 day ago", "%1 days ago", -daysTo ); } else { str = i18n( "due" ); } } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 2 ); mLabels.append( label ); // Priority label str = '[' + QString::number( todo->priority() ) + ']'; label = new QLabel( str, this ); label->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 3 ); mLabels.append( label ); // Summary label str = todo->summary(); if ( todo->relatedTo() ) { // show parent only, not entire ancestry str = todo->relatedTo()->summary() + ':' + str; } if ( !Qt::mightBeRichText( str ) ) { str = Qt::escape( str ); } KUrlLabel *urlLabel = new KUrlLabel( this ); urlLabel->setText( str ); urlLabel->setUrl( todo->uid() ); urlLabel->installEventFilter( this ); urlLabel->setTextFormat( Qt::RichText ); urlLabel->setWordWrap( true ); mLayout->addWidget( urlLabel, counter, 4 ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)), this, SLOT(viewTodo(const QString&)) ); connect( urlLabel, SIGNAL(rightClickedUrl(const QString&)), this, SLOT(popupMenu(const QString&)) ); QString tipText( KCal::IncidenceFormatter::toolTipStr( todo, true, KPIM::KPimPrefs::timeSpec() ) ); if ( !tipText.isEmpty() ) { urlLabel->setToolTip( tipText ); } // State text label str = stateStr( todo ); label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 5 ); mLabels.append( label ); counter++; } } //foreach if ( counter == 0 ) { QLabel *noTodos = new QLabel( i18np( "No pending to-dos due within the next day", "No pending to-dos due within the next %1 days", mDaysToGo ), this ); noTodos->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); mLayout->addWidget( noTodos, 0, 2 ); mLabels.append( noTodos ); } Q_FOREACH( label, mLabels ) { //krazy:exclude=foreach as label is a pointer label->show(); } } void TodoSummaryWidget::viewTodo( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_todoplugin" );//ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.editIncidence( uid ); } void TodoSummaryWidget::removeTodo( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_todoplugin" );//ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.deleteIncidence( uid, false ); } void TodoSummaryWidget::completeTodo( const QString &uid ) { KCal::Todo *todo = mCalendar->todo( uid ); if ( !todo->isReadOnly() ) { todo->setCompleted( KDateTime::currentLocalDateTime() ); mCalendar->save(); updateView(); } } void TodoSummaryWidget::popupMenu( const QString &uid ) { KMenu popup( this ); QAction *editIt = popup.addAction( i18n( "&Edit To-do..." ) ); QAction *delIt = popup.addAction( i18n( "&Delete To-do" ) ); delIt->setIcon( KIconLoader::global()->loadIcon( "edit-delete", KIconLoader::Small ) ); QAction *doneIt = 0; KCal::Todo *todo = mCalendar->todo( uid ); if ( !todo->isCompleted() ) { doneIt = popup.addAction( i18n( "&Mark To-do Completed" ) ); doneIt->setIcon( KIconLoader::global()->loadIcon( "task-complete", KIconLoader::Small ) ); } // TODO: add icons to the menu actions const QAction *selectedAction = popup.exec( QCursor::pos() ); if ( selectedAction == editIt ) { viewTodo( uid ); } else if ( selectedAction == delIt ) { removeTodo( uid ); } else if ( doneIt && selectedAction == doneIt ) { completeTodo( uid ); } } bool TodoSummaryWidget::eventFilter( QObject *obj, QEvent *e ) { if ( obj->inherits( "KUrlLabel" ) ) { KUrlLabel* label = static_cast<KUrlLabel*>( obj ); if ( e->type() == QEvent::Enter ) { emit message( i18n( "Edit To-do: \"%1\"", label->text() ) ); } if ( e->type() == QEvent::Leave ) { emit message( QString::null ); //krazy:exclude=nullstrassign for old broken gcc } } return Kontact::Summary::eventFilter( obj, e ); } QStringList TodoSummaryWidget::configModules() const { return QStringList( "kcmtodosummary.desktop" ); } bool TodoSummaryWidget::overdue( KCal::Todo *todo ) { if ( todo->hasDueDate() && !todo->isCompleted() && todo->dtDue().date() < QDate::currentDate() ) { return true; } return false; } bool TodoSummaryWidget::starts( KCal::Todo *todo ) { if ( todo->hasStartDate() && todo->dtStart().date() == QDate::currentDate() ) { return true; } return false; } bool TodoSummaryWidget::completed( KCal::Todo *todo ) { return todo->isCompleted(); } bool TodoSummaryWidget::openEnded( KCal::Todo *todo ) { if ( !todo->hasDueDate() && !todo->isCompleted() ) { return true; } return false; } bool TodoSummaryWidget::inProgress( KCal::Todo *todo ) { if ( todo->percentComplete() > 0 ) { return true; } QDate currDate = QDate::currentDate(); if ( todo->hasStartDate() && todo->hasDueDate() && todo->dtStart().date() < currDate && currDate < todo->dtDue().date() ) { return true; } return false; } bool TodoSummaryWidget::notStarted( KCal::Todo *todo ) { if ( todo->percentComplete() > 0 ) { return false; } if ( !todo->hasStartDate() ) { return false; } if ( todo->dtStart().date() >= QDate::currentDate() ) { return false; } return true; } const QString TodoSummaryWidget::stateStr( KCal::Todo *todo ) { QString str1, str2; if ( openEnded( todo ) ) { str1 = i18n( "open-ended" ); } else if ( overdue( todo ) ) { str1 = "<font color=\"red\">" + i18n( "overdue" ) + "</font>"; } else if ( starts( todo ) ) { str1 = i18n( "starts today" ); } if ( notStarted( todo ) ) { str2 += i18n( "not-started" ); } else if ( completed( todo ) ) { str2 += i18n( "completed" ); } else if ( inProgress( todo ) ) { str2 += i18n( "in-progress " ); str2 += " (" + QString::number( todo->percentComplete() ) + "%)"; } if ( !str1.isEmpty() && !str2.isEmpty() ) { str1 += i18nc( "Separator for status like this: overdue, completed", "," ); } return str1 + str2; } #include "todosummarywidget.moc" <|endoftext|>
<commit_before>#include "Variant.h" #include <chrono> #include <thread> #include <mutex> #include <pqxx/pqxx> #include <boost/algorithm/string.hpp> using namespace std; using namespace chrono; using namespace vcflib; using namespace pqxx; /* CREATE TABLE public._2_variant ( bin integer, chr character varying NOT NULL, pos integer NOT NULL DEFAULT nextval('_2_variant_pos_seq'::regclass), ref character varying NOT NULL, alt character varying NOT NULL, sample_id integer NOT NULL, is_transition boolean, CONSTRAINT _2_variant_uc PRIMARY KEY (chr, pos, ref, alt, sample_id), ) WITH ( OIDS=FALSE ); ALTER TABLE public._2_variant OWNER TO regovar; */ mutex m; int jobInProgress = 0; string normalizeChrm(string chrm) { boost::to_upper(chrm); if (boost::starts_with(chrm, "CHROM")) chrm = chrm.substr(5); if (boost::starts_with(chrm, "CHRM")) chrm = chrm.substr(4); if (boost::starts_with(chrm, "CHR")) chrm = chrm.substr(3); return chrm } void normalize(long& pos, string& ref, string& alt) { if (ref == alt) { // not a variant -> cancel it ref = "."; alt = "."; } while (ref.length() > 0 && alt.length() && ref.at(0) == alt.at(0)) { ref = ref.substr(1); alt = alt.substr(1); ++pos; } if (ref.length() == alt.length()) { while (ref.length() > 0 && alt.length() && ref.at(0) == alt.at(0)) { ref = ref.substr(0, ref.length()-1); alt = alt.substr(0, alt.length()-1); } } } void asynchSqlExec(string sqlQuery) { m.lock(); jobInProgress += 1; m.unlock(); try { connection C("dbname=regovar-dev user=regovar password=regovar hostaddr=127.0.0.1 port=5433"); if (!C.is_open()) { cout << "Can't open database" << endl; m.lock(); jobInProgress -=1; m.unlock(); } nontransaction N(C); N.exec( sqlQuery ); C.disconnect (); } catch (const exception &e) { cerr << e.what() << endl; m.lock(); jobInProgress -=1; m.unlock(); return; } m.lock(); jobInProgress -=1; m.unlock(); } int main(int argc, char** argv) { //return 0; time_point<system_clock> start, end; start = system_clock::now(); VariantCallFile variantFile; if (argc > 1) { string filename = argv[1]; variantFile.open(filename); } else { variantFile.open(std::cin); } if (!variantFile.is_open()) { return 1; } Variant var(variantFile); string sqlQuery = ""; string sqlHead = "INSERT INTO _2_variant (sample_id, chr, pos, ref, alt, is_transition) VALUES "; string sqlTail = " ON CONFLICT DO NOTHING"; long count = 0; while (variantFile.getNextVariant(var)) { //cout << "===== " << var.sequenceName << ", " << var.position << endl; /* for (auto& it : var.flatAlternates()) { cout << " >" << it.first << " : "; for (auto& it2 : it.second) { cout << "(" << var.sequenceName << ", " << it2.position << ", " << it2.ref << ", " << it2.alt << ") "; } } cout << endl;*/ // first we normalize all alleles for this vcf entry vector<string> alts = var.alleles; vector<long> poss; vector<string> refs; for (uint i=0; i<alts.size(); i++) { poss.push_back(var.position); refs.push_back(var.ref); normalize(poss[i], refs[i], alts[i]); } // Then for each sample we register only "true" variant for (auto& it : var.samples) { //cout << " sample " << it.first << " (" << it.second["GT"][0] << ") : " ; vector<string> genotype; if (it.second["GT"][0].find('/') != std::string::npos) { genotype = split(it.second["GT"][0], '/'); } else { genotype = split(it.second["GT"][0], '|'); } if (genotype[0] != "." && genotype[0] != "0") { int idx = stoi(genotype[0]); sqlQuery += "(" + to_string(1) + ",'" + var.sequenceName + "'," + to_string(poss[idx]) + ",'" + refs[idx] + "','" + alts[idx] + "', TRUE ),"; ++count; //cout << "[" << poss[idx] << ", " << refs[idx] << ", " << alts[idx] << "] "; } if (genotype[1] != "." && genotype[1] != "0") { int idx = stoi(genotype[1]); sqlQuery += "(" + to_string(1) + ",'" + var.sequenceName + "'," + to_string(poss[idx]) + ",'" + refs[idx] + "','" + alts[idx] + "', TRUE ),"; ++count; //cout << "[" << poss[idx] << ", " << refs[idx] << ", " << alts[idx] << "] "; } if (count > 1000000) { //thread execReq(asynchSqlExec, sqlHead + sqlQuery.substr(0, sqlQuery.length()-1) + sqlTail); //execReq.join(); sqlQuery = ""; count = 0; } } } // end vcf parsing loop end = system_clock::now(); duration<double> elapsed_seconds = end-start; cout << "parsing done in " << elapsed_seconds.count() << " s" << endl; thread execReq(asynchSqlExec, sqlHead + sqlQuery.substr(0, sqlQuery.length()-1) + sqlTail); execReq.join(); int current = 0; while (jobInProgress > 0) { if (current != jobInProgress) { cout << "remaining sql job : " << jobInProgress; current = jobInProgress; } } end = system_clock::now(); elapsed_seconds = end-start; cout << "import done in " << elapsed_seconds.count() << " s" << endl; return 0; }<commit_msg>update bench cpp<commit_after>#include "Variant.h" #include <chrono> #include <thread> #include <mutex> #include <pqxx/pqxx> #include <boost/algorithm/string.hpp> using namespace std; using namespace chrono; using namespace vcflib; using namespace pqxx; /* CREATE TABLE public._2_variant ( bin integer, chr character varying NOT NULL, pos integer NOT NULL DEFAULT nextval('_2_variant_pos_seq'::regclass), ref character varying NOT NULL, alt character varying NOT NULL, sample_id integer NOT NULL, is_transition boolean, CONSTRAINT _2_variant_uc PRIMARY KEY (chr, pos, ref, alt, sample_id), ) WITH ( OIDS=FALSE ); ALTER TABLE public._2_variant OWNER TO regovar; */ mutex m; int jobInProgress = 0; string normalizeChrm(string chrm) { boost::to_upper(chrm); if (boost::starts_with(chrm, "CHROM")) chrm = chrm.substr(5); if (boost::starts_with(chrm, "CHRM")) chrm = chrm.substr(4); if (boost::starts_with(chrm, "CHR")) chrm = chrm.substr(3); return chrm } void normalize(long& pos, string& ref, string& alt) { if (ref == alt) { // not a variant -> cancel it ref = "."; alt = "."; } while (ref.length() > 0 && alt.length() && ref.at(0) == alt.at(0)) { ref = ref.substr(1); alt = alt.substr(1); ++pos; } if (ref.length() == alt.length()) { while (ref.length() > 0 && alt.length() && ref.at(0) == alt.at(0)) { ref = ref.substr(0, ref.length()-1); alt = alt.substr(0, alt.length()-1); } } } void asynchSqlExec(string sqlQuery) { m.lock(); jobInProgress += 1; m.unlock(); try { connection C("dbname=regovar-dev user=regovar password=regovar hostaddr=127.0.0.1 port=5433"); if (!C.is_open()) { cout << "Can't open database" << endl; m.lock(); jobInProgress -=1; m.unlock(); } nontransaction N(C); N.exec( sqlQuery ); C.disconnect (); } catch (const exception &e) { cerr << e.what() << endl; m.lock(); jobInProgress -=1; m.unlock(); return; } m.lock(); jobInProgress -=1; m.unlock(); } int main(int argc, char** argv) { //return 0; time_point<system_clock> start, end; start = system_clock::now(); VariantCallFile variantFile; if (argc > 1) { string filename = argv[1]; variantFile.open(filename); } else { variantFile.open(std::cin); } if (!variantFile.is_open()) { return 1; } Variant var(variantFile); string sqlQuery = ""; string sqlHead = "INSERT INTO _2_variant (sample_id, chr, pos, ref, alt, is_transition) VALUES "; string sqlTail = " ON CONFLICT DO NOTHING"; long count = 0; while (variantFile.getNextVariant(var)) { //cout << "===== " << var.sequenceName << ", " << var.position << endl; /* for (auto& it : var.flatAlternates()) { cout << " >" << it.first << " : "; for (auto& it2 : it.second) { cout << "(" << var.sequenceName << ", " << it2.position << ", " << it2.ref << ", " << it2.alt << ") "; } } cout << endl;*/ // first we normalize all alleles for this vcf entry string chrm = normalizeChrm(var.sequenceName); vector<string> alts = var.alleles; vector<long> poss; vector<string> refs; for (uint i=0; i<alts.size(); i++) { poss.push_back(var.position); refs.push_back(var.ref); normalize(poss[i], refs[i], alts[i]); } // Then for each sample we register only "true" variant for (auto& it : var.samples) { //cout << " sample " << it.first << " (" << it.second["GT"][0] << ") : " ; vector<string> genotype; if (it.second["GT"][0].find('/') != std::string::npos) { genotype = split(it.second["GT"][0], '/'); } else { genotype = split(it.second["GT"][0], '|'); } if (genotype[0] != "." && genotype[0] != "0") { int idx = stoi(genotype[0]); sqlQuery += "(" + to_string(1) + ",'" + chrm + "'," + to_string(poss[idx]) + ",'" + refs[idx] + "','" + alts[idx] + "', TRUE ),"; ++count; //cout << "[" << poss[idx] << ", " << refs[idx] << ", " << alts[idx] << "] "; } if (genotype[1] != "." && genotype[1] != "0") { int idx = stoi(genotype[1]); sqlQuery += "(" + to_string(1) + ",'" + chrm + "'," + to_string(poss[idx]) + ",'" + refs[idx] + "','" + alts[idx] + "', TRUE ),"; ++count; //cout << "[" << poss[idx] << ", " << refs[idx] << ", " << alts[idx] << "] "; } if (count > 1000000) { //thread execReq(asynchSqlExec, sqlHead + sqlQuery.substr(0, sqlQuery.length()-1) + sqlTail); //execReq.join(); sqlQuery = ""; count = 0; } } } // end vcf parsing loop end = system_clock::now(); duration<double> elapsed_seconds = end-start; cout << "parsing done in " << elapsed_seconds.count() << " s" << endl; thread execReq(asynchSqlExec, sqlHead + sqlQuery.substr(0, sqlQuery.length()-1) + sqlTail); execReq.join(); int current = 0; while (jobInProgress > 0) { if (current != jobInProgress) { cout << "remaining sql job : " << jobInProgress; current = jobInProgress; } } end = system_clock::now(); elapsed_seconds = end-start; cout << "import done in " << elapsed_seconds.count() << " s" << endl; return 0; }<|endoftext|>
<commit_before>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove 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 "UnitTest++/UnitTest++.h" #include <thread> #include <vector> #include <numeric> #include <array> #include <algorithm> #include <queue> #include <atomic> #include "etl/atomic.h" #include "etl/queue_spsc_atomic.h" #include "etl/buffer_descriptors.h" #if defined(ETL_TARGET_OS_WINDOWS) #include <Windows.h> #endif #define REALTIME_TEST 0 namespace { constexpr size_t BUFFER_SIZE = 16U; constexpr size_t N_BUFFERS = 4U; constexpr size_t DATA_COUNT = BUFFER_SIZE / 2; using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>; char buffers[N_BUFFERS][BUFFER_SIZE]; //*********************************** struct Receiver { void receive(BD::notification n) { pbuffer = n.get_descriptor().data(); count = n.get_count(); } void clear() { pbuffer = nullptr; count = 0U; } BD::pointer pbuffer; BD::size_type count; }; Receiver receiver; SUITE(test_buffer_descriptors) { ////************************************************************************* //TEST(test_constructor_plus_buffer) //{ // BD bd(&buffers[0][0]); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(!bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_and_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0], callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_set_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0]); // bd.set_callback(callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} //************************************************************************* TEST(test_buffers) { BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); //CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); char* a = &buffers[i][0]; //char* b = desc.data(); //CHECK_EQUAL(a, b); } } // // //************************************************************************* // TEST(test_buffers_with_allocate_fill) // { // std::array<char, BUFFER_SIZE> test = // { // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF) // }; // // BD bd(&buffers[0][0]); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(char(0xFF)); // // CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_notifications) // { // std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 }; // // std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U); // // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // // BD bd(&buffers[0][0], callback); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // // CHECK(desc.is_valid()); // // std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data()); // bd.notify(BD::notification(desc, DATA_COUNT)); // desc.release(); // // CHECK_EQUAL(DATA_COUNT, receiver.count); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer)); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_allocate_overflow) // { // BD bd(&buffers[0][0]); // // // Use up all of the descriptors. // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // CHECK(desc.is_valid()); // } // // BD::descriptor desc = bd.allocate(); // CHECK(!desc.is_valid()); // } // // //************************************************************************* // TEST(test_allocate_release_rollover) // { // std::queue<BD::descriptor> desc_queue; // // BD bd(&buffers[0][0]); // // // Use up all of the descriptors, then release/allocate for the rest. // for (size_t i = 0U; i < (N_BUFFERS * 2); ++i) // { // BD::descriptor desc = bd.allocate(); // desc_queue.push(desc); // // CHECK(desc.is_valid()); // // if (i >= (N_BUFFERS - 1)) // { // desc_queue.front().release(); // desc_queue.pop(); // } // } // } // // //************************************************************************* // TEST(test_descriptors) // { // BD bd(&buffers[0][0]); // // BD::descriptor desc1 = bd.allocate(); // BD::descriptor desc2 = bd.allocate(); // BD::descriptor desc3 = bd.allocate(); // BD::descriptor desc4 = bd.allocate(); // // CHECK(desc1.is_allocated()); // CHECK(desc2.is_allocated()); // CHECK(desc3.is_allocated()); // CHECK(desc4.is_allocated()); // // CHECK(desc1.data() == &buffers[0][0]); // CHECK(desc2.data() == &buffers[1][0]); // CHECK(desc3.data() == &buffers[2][0]); // CHECK(desc4.data() == &buffers[3][0]); // // CHECK(desc1.max_size() == BUFFER_SIZE); // CHECK(desc2.max_size() == BUFFER_SIZE); // CHECK(desc3.max_size() == BUFFER_SIZE); // CHECK(desc4.max_size() == BUFFER_SIZE); // // CHECK(desc1.MAX_SIZE == BUFFER_SIZE); // CHECK(desc2.MAX_SIZE == BUFFER_SIZE); // CHECK(desc3.MAX_SIZE == BUFFER_SIZE); // CHECK(desc4.MAX_SIZE == BUFFER_SIZE); // // CHECK(desc1.is_valid()); // CHECK(desc2.is_valid()); // CHECK(desc3.is_valid()); // CHECK(desc4.is_valid()); // // desc1.release(); // desc2.release(); // desc3.release(); // desc4.release(); // // CHECK(desc1.is_released()); // CHECK(desc2.is_released()); // CHECK(desc3.is_released()); // CHECK(desc4.is_released()); // } // // //************************************************************************* //#if REALTIME_TEST // //#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported //#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) //#define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1) //#define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2) //#else //#define RAISE_THREAD_PRIORITY //#define FIX_PROCESSOR_AFFINITY1 //#define FIX_PROCESSOR_AFFINITY2 //#endif // // std::atomic_bool start = false; // // //********************************* // struct Notification // { // BD::descriptor desc; // BD::size_type count; // }; // // constexpr int N_ITERATIONS = 1000000; // // etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue; // // //********************************* // void Callback(BD::notification n) // { // desc_queue.push(n); // } // // //********************************* // void Producer() // { // static char buffers[N_BUFFERS][BUFFER_SIZE]; // // BD bd(&buffers[0][0], BD::callback_type::create<Callback>()); // // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY1; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS; ++i) // { // BD::descriptor desc; // // // Wait until we can allocate a descriptor. // do // { // desc = bd.allocate(); // } while (desc.is_valid() == false); // // if (!desc.is_allocated()) // { // ++errors; // } // // // Send a notification to the callback function. // bd.notify(BD::notification(desc, BUFFER_SIZE)); // } // // CHECK_EQUAL(0, errors); // } // // //********************************* // void Consumer() // { // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY2; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS;) // { // BD::notification notification; // // // Try to get a notification from the queue. // if (desc_queue.pop(notification)) // { // CHECK_EQUAL(BUFFER_SIZE, notification.get_count()); // CHECK(notification.get_descriptor().is_allocated()); // // if (!notification.get_descriptor().is_allocated()) // { // ++errors; // } // // notification.get_descriptor().release(); // ++i; // } // // CHECK_EQUAL(0, errors); // } // } // // //********************************* // TEST(test_multi_thread) // { // std::thread t1(Producer); // std::thread t2(Consumer); // // start = true; // // t1.join(); // t2.join(); // } //#endif }; } <commit_msg>Refactor buffer_descriptors test<commit_after>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove 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 "UnitTest++/UnitTest++.h" #include <thread> #include <vector> #include <numeric> #include <array> #include <algorithm> #include <queue> #include <atomic> #include "etl/atomic.h" #include "etl/queue_spsc_atomic.h" #include "etl/buffer_descriptors.h" #if defined(ETL_TARGET_OS_WINDOWS) #include <Windows.h> #endif #define REALTIME_TEST 0 namespace { constexpr size_t BUFFER_SIZE = 16U; constexpr size_t N_BUFFERS = 4U; constexpr size_t DATA_COUNT = BUFFER_SIZE / 2; using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>; char buffers[N_BUFFERS][BUFFER_SIZE]; //*********************************** struct Receiver { void receive(BD::notification n) { pbuffer = n.get_descriptor().data(); count = n.get_count(); } void clear() { pbuffer = nullptr; count = 0U; } BD::pointer pbuffer; BD::size_type count; }; Receiver receiver; SUITE(test_buffer_descriptors) { ////************************************************************************* //TEST(test_constructor_plus_buffer) //{ // BD bd(&buffers[0][0]); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(!bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_and_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0], callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_set_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0]); // bd.set_callback(callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} //************************************************************************* TEST(test_buffers) { BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); //CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); char* a = &buffers[i][0]; char* b = desc.data(); //CHECK_EQUAL(a, b); } } // // //************************************************************************* // TEST(test_buffers_with_allocate_fill) // { // std::array<char, BUFFER_SIZE> test = // { // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF) // }; // // BD bd(&buffers[0][0]); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(char(0xFF)); // // CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_notifications) // { // std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 }; // // std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U); // // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // // BD bd(&buffers[0][0], callback); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // // CHECK(desc.is_valid()); // // std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data()); // bd.notify(BD::notification(desc, DATA_COUNT)); // desc.release(); // // CHECK_EQUAL(DATA_COUNT, receiver.count); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer)); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_allocate_overflow) // { // BD bd(&buffers[0][0]); // // // Use up all of the descriptors. // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // CHECK(desc.is_valid()); // } // // BD::descriptor desc = bd.allocate(); // CHECK(!desc.is_valid()); // } // // //************************************************************************* // TEST(test_allocate_release_rollover) // { // std::queue<BD::descriptor> desc_queue; // // BD bd(&buffers[0][0]); // // // Use up all of the descriptors, then release/allocate for the rest. // for (size_t i = 0U; i < (N_BUFFERS * 2); ++i) // { // BD::descriptor desc = bd.allocate(); // desc_queue.push(desc); // // CHECK(desc.is_valid()); // // if (i >= (N_BUFFERS - 1)) // { // desc_queue.front().release(); // desc_queue.pop(); // } // } // } // // //************************************************************************* // TEST(test_descriptors) // { // BD bd(&buffers[0][0]); // // BD::descriptor desc1 = bd.allocate(); // BD::descriptor desc2 = bd.allocate(); // BD::descriptor desc3 = bd.allocate(); // BD::descriptor desc4 = bd.allocate(); // // CHECK(desc1.is_allocated()); // CHECK(desc2.is_allocated()); // CHECK(desc3.is_allocated()); // CHECK(desc4.is_allocated()); // // CHECK(desc1.data() == &buffers[0][0]); // CHECK(desc2.data() == &buffers[1][0]); // CHECK(desc3.data() == &buffers[2][0]); // CHECK(desc4.data() == &buffers[3][0]); // // CHECK(desc1.max_size() == BUFFER_SIZE); // CHECK(desc2.max_size() == BUFFER_SIZE); // CHECK(desc3.max_size() == BUFFER_SIZE); // CHECK(desc4.max_size() == BUFFER_SIZE); // // CHECK(desc1.MAX_SIZE == BUFFER_SIZE); // CHECK(desc2.MAX_SIZE == BUFFER_SIZE); // CHECK(desc3.MAX_SIZE == BUFFER_SIZE); // CHECK(desc4.MAX_SIZE == BUFFER_SIZE); // // CHECK(desc1.is_valid()); // CHECK(desc2.is_valid()); // CHECK(desc3.is_valid()); // CHECK(desc4.is_valid()); // // desc1.release(); // desc2.release(); // desc3.release(); // desc4.release(); // // CHECK(desc1.is_released()); // CHECK(desc2.is_released()); // CHECK(desc3.is_released()); // CHECK(desc4.is_released()); // } // // //************************************************************************* //#if REALTIME_TEST // //#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported //#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) //#define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1) //#define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2) //#else //#define RAISE_THREAD_PRIORITY //#define FIX_PROCESSOR_AFFINITY1 //#define FIX_PROCESSOR_AFFINITY2 //#endif // // std::atomic_bool start = false; // // //********************************* // struct Notification // { // BD::descriptor desc; // BD::size_type count; // }; // // constexpr int N_ITERATIONS = 1000000; // // etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue; // // //********************************* // void Callback(BD::notification n) // { // desc_queue.push(n); // } // // //********************************* // void Producer() // { // static char buffers[N_BUFFERS][BUFFER_SIZE]; // // BD bd(&buffers[0][0], BD::callback_type::create<Callback>()); // // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY1; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS; ++i) // { // BD::descriptor desc; // // // Wait until we can allocate a descriptor. // do // { // desc = bd.allocate(); // } while (desc.is_valid() == false); // // if (!desc.is_allocated()) // { // ++errors; // } // // // Send a notification to the callback function. // bd.notify(BD::notification(desc, BUFFER_SIZE)); // } // // CHECK_EQUAL(0, errors); // } // // //********************************* // void Consumer() // { // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY2; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS;) // { // BD::notification notification; // // // Try to get a notification from the queue. // if (desc_queue.pop(notification)) // { // CHECK_EQUAL(BUFFER_SIZE, notification.get_count()); // CHECK(notification.get_descriptor().is_allocated()); // // if (!notification.get_descriptor().is_allocated()) // { // ++errors; // } // // notification.get_descriptor().release(); // ++i; // } // // CHECK_EQUAL(0, errors); // } // } // // //********************************* // TEST(test_multi_thread) // { // std::thread t1(Producer); // std::thread t2(Consumer); // // start = true; // // t1.join(); // t2.join(); // } //#endif }; } <|endoftext|>
<commit_before>#include "Field.h" #include <vtkImageData.h> #include <vtkImageExtractComponents.h> #include <vtkImageGradient.h> #include <vtkMetaImageReader.h> #include <vtkMetaImageWriter.h> #include <vtkSmartPointer.h> #include <vtkXMLImageDataReader.h> #include <itpp/itsignal.h> #include <itpp/itstat.h> #include "Vector3.h" #include "Matrix3x3.h" #include <cassert> #include <iostream> #include <sstream> namespace PropertySpace { // ------------------------------------------------------------------------ Field::Field(vtkImageData *volume) { assert(volume != 0); // Get size int dims[3]; volume->GetDimensions(dims); width = dims[0]; height = dims[1]; depth = dims[2]; // We assume the volume is a vector volume int numComps = volume->GetNumberOfScalarComponents(); assert(numComps == 3); // Get spacing and origin volume->GetSpacing(spacing); volume->GetOrigin(origin); // Build data matrix BuildPropertyMatrix(volume); } // ------------------------------------------------------------------------ Field::~Field() { } // ------------------------------------------------------------------------ Field *Field::Load(const std::string &filename) { // Use a vtk reader to load the vector field vtkImageData *volume = 0; std::string ext = filename.substr(filename.rfind('.')); if (ext == ".mha" || ext == ".mhd") { vtkSmartPointer<vtkMetaImageReader> reader = vtkSmartPointer<vtkMetaImageReader>::New(); reader->SetFileName(filename.c_str()); reader->Update(); volume = reader->GetOutput(); volume->Register(0); } else if (ext == ".vti") { vtkSmartPointer<vtkXMLImageDataReader> reader = vtkSmartPointer<vtkXMLImageDataReader>::New(); reader->SetFileName(filename.c_str()); reader->Update(); volume = reader->GetOutput(); volume->Register(0); } else { std::cerr << "Unsupported file type: '" << ext << "'" << std::endl; return 0; } Field *field = new Field(volume); volume->Delete(); return field; } // ------------------------------------------------------------------------ void Field::DoPCA() { // Compute covariance matrix std::cout << "Computing covariance matrix..." << std::endl; itpp::mat covariance = itpp::cov(data); // Perform eigen analysis std::cout << "Computing eigenvectors..." << std::endl; itpp::vec unsortedEigVals; itpp::mat unsortedEigVecs; itpp::eig_sym(covariance, unsortedEigVals, unsortedEigVecs); // Sort by eigenvalue std::cout << "Sorting components..." << std::endl; itpp::ivec index = itpp::reverse(itpp::sort_index(unsortedEigVals)); // Allocate space eigVals.set_size(unsortedEigVals.size()); eigVecs.set_size(unsortedEigVecs.rows(), unsortedEigVecs.cols()); // Sort and remove insignificant components int comp = 0; for (int col = 0; col < unsortedEigVecs.cols(); ++col) { itpp::vec evec = unsortedEigVecs.get_col(index(col)); double eval = unsortedEigVals(index(col)); const double epsilon = 0.000001; if (eval > epsilon) { eigVecs.set_col(comp, evec); eigVals(comp) = eval; ++comp; } else { if (eval < -epsilon) { std::cerr << "Warning! Negative eigenvalue: " << eval << std::endl; } // Treat this eigenvalue as if it's 0 and discard the result } } // Discard zero-valued components eigVecs.set_size(eigVecs.rows(), comp, true); eigVals.set_size(comp, true); std::cout << "PCA complete! Found " << comp << " significant components" << std::endl; // Report results for (int i = 0; i < comp; ++i) { std::cout << i + 1 << ": " << eigVecs.get_col(i) << " (eval " << eigVals(i) << ")" << std::endl; } } // ------------------------------------------------------------------------ void Field::Transform() { // The transformation matrix is based on scaled eigenvectors std::cout << "Buiding transformation..." << std::endl; basis = eigVecs; for (int i = 0; i < basis.cols(); ++i) { itpp::vec v = basis.get_col(i); v *= 1.0 / sqrt(eigVals(i)); basis.set_col(i, v); } std::cout << "Transforming data..." << std::endl; data = data * basis; } // ------------------------------------------------------------------------ void Field::Save(const std::string &filename, int comps) { if (comps <= 0) comps = data.cols(); assert(comps <= data.cols()); // Save transform SaveDataTransform(filename, comps); // Prepare volume std::cout << "Preparing to save fields..." << std::endl; vtkSmartPointer<vtkImageData> volume = vtkSmartPointer<vtkImageData>::New(); volume->SetScalarTypeToFloat(); volume->SetDimensions(width, height, depth); volume->SetNumberOfScalarComponents(4); volume->SetSpacing(spacing); volume->SetOrigin(origin); volume->AllocateScalars(); float *field = static_cast<float*>(volume->GetScalarPointer()); // Save the field in up-to-4-component files int startComp = 0; while (comps > 0) { // Copy the data for this volume if (comps < 4) { volume->SetNumberOfScalarComponents(comps); volume->AllocateScalars(); } int numComps = volume->GetNumberOfScalarComponents(); std::cout << "Saving field " << startComp / 4 << "..." << std::endl; for (int i = 0; i < width * height * depth; ++i) { for (int c = 0; c < numComps; ++c) { field[i * numComps + c] = data(i, startComp + c); } } // Write the volume to disk std::ostringstream file; file << filename << "_comp" << startComp / 4 << ".mha"; vtkSmartPointer<vtkMetaImageWriter> writer = vtkSmartPointer<vtkMetaImageWriter>::New(); writer->SetFileName(file.str().c_str()); writer->SetInput(volume); writer->Write(); // Next file / set of components startComp += 4; comps -= 4; } } // ------------------------------------------------------------------------ void Field::BuildPropertyMatrix(vtkImageData *volume) { // TODO: implement Gaussian convolution for derivatives // Compute derivatives vtkImageData *gradients[3]; double *gfield[3]; for (int i = 0; i < 3; ++i) { vtkSmartPointer<vtkImageExtractComponents> comps = vtkSmartPointer<vtkImageExtractComponents>::New(); comps->SetInput(volume); comps->SetComponents(i); vtkSmartPointer<vtkImageGradient> grad = vtkSmartPointer<vtkImageGradient>::New(); grad->SetInputConnection(comps->GetOutputPort()); grad->SetDimensionality(3); grad->Update(); gradients[i] = grad->GetOutput(); gradients[i]->Register(0); assert(gradients[i]->GetScalarType() == VTK_DOUBLE); gfield[i] = static_cast<double*>(gradients[i]->GetScalarPointer()); } assert(volume->GetScalarType() == VTK_FLOAT); float *field = static_cast<float*>(volume->GetScalarPointer()); int comps = volume->GetNumberOfScalarComponents(); std::cout << "Building matrix..." << std::endl; data.set_size(width * height * depth, 12); for (int row = 0; row < width * height * depth; ++row) { NQVTK::Vector3 v(field[0], field[1], field[2]); field += comps; // Vector data(row, 0) = v.x; data(row, 1) = v.y; data(row, 2) = v.z; // Direction NQVTK::Vector3 d = v.normalized(); data(row, 3) = d.x; data(row, 4) = d.y; data(row, 5) = d.z; // Magnitude data(row, 6) = v.length(); // Derivatives NQVTK::Vector3 ddx(gfield[0][0], gfield[1][0], gfield[2][0]); NQVTK::Vector3 ddy(gfield[0][1], gfield[1][1], gfield[2][1]); NQVTK::Vector3 ddz(gfield[0][2], gfield[1][2], gfield[2][2]); NQVTK::Matrix3x3 jacobian = NQVTK::Matrix3x3::fromCols( ddx, ddy, ddz); gfield[0] += 3; gfield[1] += 3; gfield[2] += 3; // Growth double detJ = std::abs(jacobian.det()); if (detJ > 1.0) { data(row, 7) = 1.0 - (1.0 / detJ); } else { data(row, 7) = detJ - 1.0; } // Divergence data(row, 8) = jacobian.trace(); // Curl data(row, 9) = jacobian.a21 - jacobian.a12; data(row, 10) = jacobian.a02 - jacobian.a20; data(row, 11) = jacobian.a10 - jacobian.a01; } // Clean up gradients for (int i = 0; i < 3; ++i) { gradients[i]->Delete(); } // Compute mean mean.set_size(data.cols()); for (int i = 0; i < data.cols(); ++i) { mean(i) = itpp::mean(data.get_col(i)); } // Center data for (int i = 0; i < data.rows(); ++i) { data.set_row(i, data.get_row(i) - mean); } } // ------------------------------------------------------------------------ void Field::SaveDataTransform(const std::string &filename, int comps) { // Save transformation matrix std::cout << "Saving transform..." << std::endl; itpp::mat transform = basis.get(0, basis.rows() - 1, 0, comps - 1); std::ostringstream file; file << filename << "_transform.itpp"; itpp::it_file transformFile(file.str(), true); transformFile << itpp::Name("transform") << transform; } } <commit_msg>Save transforms in a format that doesn't require IT++ to load.<commit_after>#include "Field.h" #include <vtkImageData.h> #include <vtkImageExtractComponents.h> #include <vtkImageGradient.h> #include <vtkMetaImageReader.h> #include <vtkMetaImageWriter.h> #include <vtkSmartPointer.h> #include <vtkXMLImageDataReader.h> #include <itpp/itsignal.h> #include <itpp/itstat.h> #include "Vector3.h" #include "Matrix3x3.h" #include <cassert> #include <fstream> #include <iostream> #include <sstream> namespace PropertySpace { // ------------------------------------------------------------------------ Field::Field(vtkImageData *volume) { assert(volume != 0); // Get size int dims[3]; volume->GetDimensions(dims); width = dims[0]; height = dims[1]; depth = dims[2]; // We assume the volume is a vector volume int numComps = volume->GetNumberOfScalarComponents(); assert(numComps == 3); // Get spacing and origin volume->GetSpacing(spacing); volume->GetOrigin(origin); // Build data matrix BuildPropertyMatrix(volume); } // ------------------------------------------------------------------------ Field::~Field() { } // ------------------------------------------------------------------------ Field *Field::Load(const std::string &filename) { // Use a vtk reader to load the vector field vtkImageData *volume = 0; std::string ext = filename.substr(filename.rfind('.')); if (ext == ".mha" || ext == ".mhd") { vtkSmartPointer<vtkMetaImageReader> reader = vtkSmartPointer<vtkMetaImageReader>::New(); reader->SetFileName(filename.c_str()); reader->Update(); volume = reader->GetOutput(); volume->Register(0); } else if (ext == ".vti") { vtkSmartPointer<vtkXMLImageDataReader> reader = vtkSmartPointer<vtkXMLImageDataReader>::New(); reader->SetFileName(filename.c_str()); reader->Update(); volume = reader->GetOutput(); volume->Register(0); } else { std::cerr << "Unsupported file type: '" << ext << "'" << std::endl; return 0; } Field *field = new Field(volume); volume->Delete(); return field; } // ------------------------------------------------------------------------ void Field::DoPCA() { // Compute covariance matrix std::cout << "Computing covariance matrix..." << std::endl; itpp::mat covariance = itpp::cov(data); // Perform eigen analysis std::cout << "Computing eigenvectors..." << std::endl; itpp::vec unsortedEigVals; itpp::mat unsortedEigVecs; itpp::eig_sym(covariance, unsortedEigVals, unsortedEigVecs); // Sort by eigenvalue std::cout << "Sorting components..." << std::endl; itpp::ivec index = itpp::reverse(itpp::sort_index(unsortedEigVals)); // Allocate space eigVals.set_size(unsortedEigVals.size()); eigVecs.set_size(unsortedEigVecs.rows(), unsortedEigVecs.cols()); // Sort and remove insignificant components int comp = 0; for (int col = 0; col < unsortedEigVecs.cols(); ++col) { itpp::vec evec = unsortedEigVecs.get_col(index(col)); double eval = unsortedEigVals(index(col)); const double epsilon = 0.000001; if (eval > epsilon) { eigVecs.set_col(comp, evec); eigVals(comp) = eval; ++comp; } else { if (eval < -epsilon) { std::cerr << "Warning! Negative eigenvalue: " << eval << std::endl; } // Treat this eigenvalue as if it's 0 and discard the result } } // Discard zero-valued components eigVecs.set_size(eigVecs.rows(), comp, true); eigVals.set_size(comp, true); std::cout << "PCA complete! Found " << comp << " significant components" << std::endl; // Report results for (int i = 0; i < comp; ++i) { std::cout << i + 1 << ": " << eigVecs.get_col(i) << " (eval " << eigVals(i) << ")" << std::endl; } } // ------------------------------------------------------------------------ void Field::Transform() { // The transformation matrix is based on scaled eigenvectors std::cout << "Buiding transformation..." << std::endl; basis = eigVecs; for (int i = 0; i < basis.cols(); ++i) { itpp::vec v = basis.get_col(i); v *= 1.0 / sqrt(eigVals(i)); basis.set_col(i, v); } std::cout << "Transforming data..." << std::endl; data = data * basis; } // ------------------------------------------------------------------------ void Field::Save(const std::string &filename, int comps) { if (comps <= 0) comps = data.cols(); assert(comps <= data.cols()); // Save transform SaveDataTransform(filename, comps); // Prepare volume std::cout << "Preparing to save fields..." << std::endl; vtkSmartPointer<vtkImageData> volume = vtkSmartPointer<vtkImageData>::New(); volume->SetScalarTypeToFloat(); volume->SetDimensions(width, height, depth); volume->SetNumberOfScalarComponents(4); volume->SetSpacing(spacing); volume->SetOrigin(origin); volume->AllocateScalars(); float *field = static_cast<float*>(volume->GetScalarPointer()); // Save the field in up-to-4-component files int startComp = 0; while (comps > 0) { // Copy the data for this volume if (comps < 4) { volume->SetNumberOfScalarComponents(comps); volume->AllocateScalars(); } int numComps = volume->GetNumberOfScalarComponents(); std::cout << "Saving field " << startComp / 4 << "..." << std::endl; for (int i = 0; i < width * height * depth; ++i) { for (int c = 0; c < numComps; ++c) { field[i * numComps + c] = data(i, startComp + c); } } // Write the volume to disk std::ostringstream file; file << filename << "_comp" << startComp / 4 << ".mha"; vtkSmartPointer<vtkMetaImageWriter> writer = vtkSmartPointer<vtkMetaImageWriter>::New(); writer->SetFileName(file.str().c_str()); writer->SetInput(volume); writer->Write(); // Next file / set of components startComp += 4; comps -= 4; } } // ------------------------------------------------------------------------ void Field::BuildPropertyMatrix(vtkImageData *volume) { // TODO: implement Gaussian convolution for derivatives // Compute derivatives vtkImageData *gradients[3]; double *gfield[3]; for (int i = 0; i < 3; ++i) { vtkSmartPointer<vtkImageExtractComponents> comps = vtkSmartPointer<vtkImageExtractComponents>::New(); comps->SetInput(volume); comps->SetComponents(i); vtkSmartPointer<vtkImageGradient> grad = vtkSmartPointer<vtkImageGradient>::New(); grad->SetInputConnection(comps->GetOutputPort()); grad->SetDimensionality(3); grad->Update(); gradients[i] = grad->GetOutput(); gradients[i]->Register(0); assert(gradients[i]->GetScalarType() == VTK_DOUBLE); gfield[i] = static_cast<double*>(gradients[i]->GetScalarPointer()); } assert(volume->GetScalarType() == VTK_FLOAT); float *field = static_cast<float*>(volume->GetScalarPointer()); int comps = volume->GetNumberOfScalarComponents(); std::cout << "Building matrix..." << std::endl; data.set_size(width * height * depth, 12); for (int row = 0; row < width * height * depth; ++row) { NQVTK::Vector3 v(field[0], field[1], field[2]); field += comps; // Vector data(row, 0) = v.x; data(row, 1) = v.y; data(row, 2) = v.z; // Direction NQVTK::Vector3 d = v.normalized(); data(row, 3) = d.x; data(row, 4) = d.y; data(row, 5) = d.z; // Magnitude data(row, 6) = v.length(); // Derivatives NQVTK::Vector3 ddx(gfield[0][0], gfield[1][0], gfield[2][0]); NQVTK::Vector3 ddy(gfield[0][1], gfield[1][1], gfield[2][1]); NQVTK::Vector3 ddz(gfield[0][2], gfield[1][2], gfield[2][2]); NQVTK::Matrix3x3 jacobian = NQVTK::Matrix3x3::fromCols( ddx, ddy, ddz); gfield[0] += 3; gfield[1] += 3; gfield[2] += 3; // Growth double detJ = std::abs(jacobian.det()); if (detJ > 1.0) { data(row, 7) = 1.0 - (1.0 / detJ); } else { data(row, 7) = detJ - 1.0; } // Divergence data(row, 8) = jacobian.trace(); // Curl data(row, 9) = jacobian.a21 - jacobian.a12; data(row, 10) = jacobian.a02 - jacobian.a20; data(row, 11) = jacobian.a10 - jacobian.a01; } // Clean up gradients for (int i = 0; i < 3; ++i) { gradients[i]->Delete(); } // Compute mean mean.set_size(data.cols()); for (int i = 0; i < data.cols(); ++i) { mean(i) = itpp::mean(data.get_col(i)); } // Center data for (int i = 0; i < data.rows(); ++i) { data.set_row(i, data.get_row(i) - mean); } } // ------------------------------------------------------------------------ void Field::SaveDataTransform(const std::string &filename, int comps) { // Save transformation matrix std::cout << "Saving transform..." << std::endl; itpp::mat transform = basis.get(0, basis.rows() - 1, 0, comps - 1); std::ostringstream fullFileName; fullFileName << filename << "_transform.dat"; std::ofstream transformFile(fullFileName.str().c_str(), std::ios::out | std::ios::binary | std::ios::trunc); if (transformFile.is_open()) { // Save dimensions transformFile << transform.cols() << transform.rows(); // Save data - each column is a basis vector for (int col = 0; col < transform.cols(); ++col) { for (int row = 0; row < transform.rows(); ++row) { transformFile << transform(row, col); } } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTING_TABLE_HPP #define ROUTING_TABLE_HPP #include <vector> #include <boost/cstdint.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/array.hpp> #include <set> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/node_entry.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/size_type.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/ptime.hpp> namespace libtorrent { struct session_status; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(table); #endif typedef std::vector<node_entry> bucket_t; struct routing_table_node { bucket_t replacements; bucket_t live_nodes; ptime last_active; }; // differences in the implementation from the description in // the paper: // // * Nodes are not marked as being stale, they keep a counter // that tells how many times in a row they have failed. When // a new node is to be inserted, the node that has failed // the most times is replaced. If none of the nodes in the // bucket has failed, then it is put in the replacement // cache (just like in the paper). class TORRENT_EXPORT routing_table { public: routing_table(node_id const& id, int bucket_size , dht_settings const& settings); void status(session_status& s) const; void node_failed(node_id const& id); // adds an endpoint that will never be added to // the routing table void add_router_node(udp::endpoint router); // iterates over the router nodes added typedef std::set<udp::endpoint>::const_iterator router_iterator; router_iterator router_begin() const { return m_router_nodes.begin(); } router_iterator router_end() const { return m_router_nodes.end(); } bool add_node(node_entry const& e); // this function is called every time the node sees // a sign of a node being alive. This node will either // be inserted in the k-buckets or be moved to the top // of its bucket. bool node_seen(node_id const& id, udp::endpoint ep); // this may add a node to the routing table and mark it as // not pinged. If the bucket the node falls into is full, // the node will be ignored. void heard_about(node_id const& id, udp::endpoint const& ep); // if any bucket in the routing table needs to be refreshed // this function will return true and set the target to an // appropriate target inside that bucket bool need_refresh(node_id& target) const; enum { include_failed = 1 }; // fills the vector with the count nodes from our buckets that // are nearest to the given id. void find_node(node_id const& id, std::vector<node_entry>& l , int options, int count = 0); int bucket_size(int bucket) { int num_buckets = m_buckets.size(); if (bucket < num_buckets) bucket = num_buckets - 1; table_t::iterator i = m_buckets.begin(); std::advance(i, bucket); return (int)i->live_nodes.size(); } void for_each_node(void (*)(void*, node_entry const&) , void (*)(void*, node_entry const&), void* userdata) const; int bucket_size() const { return m_bucket_size; } boost::tuple<int, int> size() const; size_type num_global_nodes() const; // returns true if there are no working nodes // in the routing table bool need_bootstrap() const; int num_active_buckets() const { return m_buckets.size(); } void replacement_cache(bucket_t& nodes) const; #if defined TORRENT_DHT_VERBOSE_LOGGING || defined TORRENT_DEBUG // used for debug and monitoring purposes. This will print out // the state of the routing table to the given stream void print_state(std::ostream& os) const; #endif void touch_bucket(node_id const& target); private: typedef std::list<routing_table_node> table_t; table_t::iterator find_bucket(node_id const& id); // constant called k in paper int m_bucket_size; dht_settings const& m_settings; // (k-bucket, replacement cache) pairs // the first entry is the bucket the furthest // away from our own ID. Each time the bucket // closest to us (m_buckets.back()) has more than // bucket size nodes in it, another bucket is // added to the end and it's split up between them table_t m_buckets; node_id m_id; // our own node id // the last time need_bootstrap() returned true mutable ptime m_last_bootstrap; // this is a set of all the endpoints that have // been identified as router nodes. They will // be used in searches, but they will never // be added to the routing table. std::set<udp::endpoint> m_router_nodes; }; } } // namespace libtorrent::dht #endif // ROUTING_TABLE_HPP <commit_msg>added missing include<commit_after>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTING_TABLE_HPP #define ROUTING_TABLE_HPP #include <vector> #include <boost/cstdint.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/array.hpp> #include <set> #include <list> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/node_entry.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/size_type.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/ptime.hpp> namespace libtorrent { struct session_status; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(table); #endif typedef std::vector<node_entry> bucket_t; struct routing_table_node { bucket_t replacements; bucket_t live_nodes; ptime last_active; }; // differences in the implementation from the description in // the paper: // // * Nodes are not marked as being stale, they keep a counter // that tells how many times in a row they have failed. When // a new node is to be inserted, the node that has failed // the most times is replaced. If none of the nodes in the // bucket has failed, then it is put in the replacement // cache (just like in the paper). class TORRENT_EXPORT routing_table { public: routing_table(node_id const& id, int bucket_size , dht_settings const& settings); void status(session_status& s) const; void node_failed(node_id const& id); // adds an endpoint that will never be added to // the routing table void add_router_node(udp::endpoint router); // iterates over the router nodes added typedef std::set<udp::endpoint>::const_iterator router_iterator; router_iterator router_begin() const { return m_router_nodes.begin(); } router_iterator router_end() const { return m_router_nodes.end(); } bool add_node(node_entry const& e); // this function is called every time the node sees // a sign of a node being alive. This node will either // be inserted in the k-buckets or be moved to the top // of its bucket. bool node_seen(node_id const& id, udp::endpoint ep); // this may add a node to the routing table and mark it as // not pinged. If the bucket the node falls into is full, // the node will be ignored. void heard_about(node_id const& id, udp::endpoint const& ep); // if any bucket in the routing table needs to be refreshed // this function will return true and set the target to an // appropriate target inside that bucket bool need_refresh(node_id& target) const; enum { include_failed = 1 }; // fills the vector with the count nodes from our buckets that // are nearest to the given id. void find_node(node_id const& id, std::vector<node_entry>& l , int options, int count = 0); int bucket_size(int bucket) { int num_buckets = m_buckets.size(); if (bucket < num_buckets) bucket = num_buckets - 1; table_t::iterator i = m_buckets.begin(); std::advance(i, bucket); return (int)i->live_nodes.size(); } void for_each_node(void (*)(void*, node_entry const&) , void (*)(void*, node_entry const&), void* userdata) const; int bucket_size() const { return m_bucket_size; } boost::tuple<int, int> size() const; size_type num_global_nodes() const; // returns true if there are no working nodes // in the routing table bool need_bootstrap() const; int num_active_buckets() const { return m_buckets.size(); } void replacement_cache(bucket_t& nodes) const; #if defined TORRENT_DHT_VERBOSE_LOGGING || defined TORRENT_DEBUG // used for debug and monitoring purposes. This will print out // the state of the routing table to the given stream void print_state(std::ostream& os) const; #endif void touch_bucket(node_id const& target); private: typedef std::list<routing_table_node> table_t; table_t::iterator find_bucket(node_id const& id); // constant called k in paper int m_bucket_size; dht_settings const& m_settings; // (k-bucket, replacement cache) pairs // the first entry is the bucket the furthest // away from our own ID. Each time the bucket // closest to us (m_buckets.back()) has more than // bucket size nodes in it, another bucket is // added to the end and it's split up between them table_t m_buckets; node_id m_id; // our own node id // the last time need_bootstrap() returned true mutable ptime m_last_bootstrap; // this is a set of all the endpoints that have // been identified as router nodes. They will // be used in searches, but they will never // be added to the routing table. std::set<udp::endpoint> m_router_nodes; }; } } // namespace libtorrent::dht #endif // ROUTING_TABLE_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTING_TABLE_HPP #define ROUTING_TABLE_HPP #include <vector> #include <deque> #include <boost/cstdint.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/iterator/iterator_categories.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/array.hpp> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/node_entry.hpp> #include <libtorrent/session_settings.hpp> namespace pt = boost::posix_time; namespace libtorrent { namespace dht { using asio::ip::udp; //TORRENT_DECLARE_LOG(table); typedef std::deque<node_entry> bucket_t; // differences in the implementation from the description in // the paper: // // * The routing table tree is not allocated dynamically, there // are always 160 buckets. // * Nodes are not marked as being stale, they keep a counter // that tells how many times in a row they have failed. When // a new node is to be inserted, the node that has failed // the most times is replaced. If none of the nodes in the // bucket has failed, then it is put in the replacement // cache (just like in the paper). class routing_table; namespace aux { // Iterates over a flattened routing_table structure. class routing_table_iterator : public boost::iterator_facade< routing_table_iterator , node_entry const , boost::forward_traversal_tag > { public: routing_table_iterator() { } private: friend class libtorrent::dht::routing_table; friend class boost::iterator_core_access; typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator bucket_iterator_t; routing_table_iterator( bucket_iterator_t begin , bucket_iterator_t end) : m_bucket_iterator(begin) , m_bucket_end(end) , m_iterator(begin != end ? begin->first.begin() : bucket_t::iterator()) { if (m_bucket_iterator == m_bucket_end) return; while (m_iterator == m_bucket_iterator->first.end()) { if (++m_bucket_iterator == m_bucket_end) break; m_iterator = m_bucket_iterator->first.begin(); } } bool equal(routing_table_iterator const& other) const { return m_bucket_iterator == other.m_bucket_iterator && (m_bucket_iterator == m_bucket_end || m_iterator == other.m_iterator); } void increment() { assert(m_bucket_iterator != m_bucket_end); ++m_iterator; while (m_iterator == m_bucket_iterator->first.end()) { if (++m_bucket_iterator == m_bucket_end) break; m_iterator = m_bucket_iterator->first.begin(); } } node_entry const& dereference() const { assert(m_bucket_iterator != m_bucket_end); return *m_iterator; } bucket_iterator_t m_bucket_iterator; bucket_iterator_t m_bucket_end; bucket_t::const_iterator m_iterator; }; } // namespace aux class routing_table { public: typedef aux::routing_table_iterator iterator; typedef iterator const_iterator; routing_table(node_id const& id, int bucket_size , dht_settings const& settings); void node_failed(node_id const& id); // adds an endpoint that will never be added to // the routing table void add_router_node(udp::endpoint router); // iterates over the router nodes added typedef std::set<udp::endpoint>::const_iterator router_iterator; router_iterator router_begin() const { return m_router_nodes.begin(); } router_iterator router_end() const { return m_router_nodes.end(); } // this function is called every time the node sees // a sign of a node being alive. This node will either // be inserted in the k-buckets or be moved to the top // of its bucket. bool node_seen(node_id const& id, udp::endpoint addr); // returns time when the given bucket needs another refresh. // if the given bucket is empty but there are nodes // in a bucket closer to us, or if the bucket is non-empty and // the time from the last activity is more than 15 minutes boost::posix_time::ptime next_refresh(int bucket); // fills the vector with the count nodes from our buckets that // are nearest to the given id. void find_node(node_id const& id, std::vector<node_entry>& l , bool include_self, int count = 0); // returns true if the given node would be placed in a bucket // that is not full. If the node already exists in the table // this function returns false bool need_node(node_id const& id); // this will set the given bucket's latest activity // to the current time void touch_bucket(int bucket); int bucket_size(int bucket) { assert(bucket >= 0 && bucket < 160); return (int)m_buckets[bucket].first.size(); } int bucket_size() const { return m_bucket_size; } iterator begin() const; iterator end() const; boost::tuple<int, int> size() const; // returns true if there are no working nodes // in the routing table bool need_bootstrap() const; void replacement_cache(bucket_t& nodes) const; // used for debug and monitoring purposes. This will print out // the state of the routing table to the given stream void print_state(std::ostream& os) const; private: // constant called k in paper int m_bucket_size; dht_settings const& m_settings; // 160 (k-bucket, replacement cache) pairs typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t; table_t m_buckets; // timestamps of the last activity in each bucket typedef boost::array<boost::posix_time::ptime, 160> table_activity_t; table_activity_t m_bucket_activity; node_id m_id; // our own node id // this is a set of all the endpoints that have // been identified as router nodes. They will // be used in searches, but they will never // be added to the routing table. std::set<udp::endpoint> m_router_nodes; // this is the lowest bucket index with nodes in it int m_lowest_active_bucket; }; } } // namespace libtorrent::dht #endif // ROUTING_TABLE_HPP <commit_msg>added missing include of set.hpp<commit_after>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTING_TABLE_HPP #define ROUTING_TABLE_HPP #include <vector> #include <deque> #include <boost/cstdint.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/iterator/iterator_categories.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/array.hpp> #include <set.hpp> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/node_entry.hpp> #include <libtorrent/session_settings.hpp> namespace pt = boost::posix_time; namespace libtorrent { namespace dht { using asio::ip::udp; //TORRENT_DECLARE_LOG(table); typedef std::deque<node_entry> bucket_t; // differences in the implementation from the description in // the paper: // // * The routing table tree is not allocated dynamically, there // are always 160 buckets. // * Nodes are not marked as being stale, they keep a counter // that tells how many times in a row they have failed. When // a new node is to be inserted, the node that has failed // the most times is replaced. If none of the nodes in the // bucket has failed, then it is put in the replacement // cache (just like in the paper). class routing_table; namespace aux { // Iterates over a flattened routing_table structure. class routing_table_iterator : public boost::iterator_facade< routing_table_iterator , node_entry const , boost::forward_traversal_tag > { public: routing_table_iterator() { } private: friend class libtorrent::dht::routing_table; friend class boost::iterator_core_access; typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator bucket_iterator_t; routing_table_iterator( bucket_iterator_t begin , bucket_iterator_t end) : m_bucket_iterator(begin) , m_bucket_end(end) , m_iterator(begin != end ? begin->first.begin() : bucket_t::iterator()) { if (m_bucket_iterator == m_bucket_end) return; while (m_iterator == m_bucket_iterator->first.end()) { if (++m_bucket_iterator == m_bucket_end) break; m_iterator = m_bucket_iterator->first.begin(); } } bool equal(routing_table_iterator const& other) const { return m_bucket_iterator == other.m_bucket_iterator && (m_bucket_iterator == m_bucket_end || m_iterator == other.m_iterator); } void increment() { assert(m_bucket_iterator != m_bucket_end); ++m_iterator; while (m_iterator == m_bucket_iterator->first.end()) { if (++m_bucket_iterator == m_bucket_end) break; m_iterator = m_bucket_iterator->first.begin(); } } node_entry const& dereference() const { assert(m_bucket_iterator != m_bucket_end); return *m_iterator; } bucket_iterator_t m_bucket_iterator; bucket_iterator_t m_bucket_end; bucket_t::const_iterator m_iterator; }; } // namespace aux class routing_table { public: typedef aux::routing_table_iterator iterator; typedef iterator const_iterator; routing_table(node_id const& id, int bucket_size , dht_settings const& settings); void node_failed(node_id const& id); // adds an endpoint that will never be added to // the routing table void add_router_node(udp::endpoint router); // iterates over the router nodes added typedef std::set<udp::endpoint>::const_iterator router_iterator; router_iterator router_begin() const { return m_router_nodes.begin(); } router_iterator router_end() const { return m_router_nodes.end(); } // this function is called every time the node sees // a sign of a node being alive. This node will either // be inserted in the k-buckets or be moved to the top // of its bucket. bool node_seen(node_id const& id, udp::endpoint addr); // returns time when the given bucket needs another refresh. // if the given bucket is empty but there are nodes // in a bucket closer to us, or if the bucket is non-empty and // the time from the last activity is more than 15 minutes boost::posix_time::ptime next_refresh(int bucket); // fills the vector with the count nodes from our buckets that // are nearest to the given id. void find_node(node_id const& id, std::vector<node_entry>& l , bool include_self, int count = 0); // returns true if the given node would be placed in a bucket // that is not full. If the node already exists in the table // this function returns false bool need_node(node_id const& id); // this will set the given bucket's latest activity // to the current time void touch_bucket(int bucket); int bucket_size(int bucket) { assert(bucket >= 0 && bucket < 160); return (int)m_buckets[bucket].first.size(); } int bucket_size() const { return m_bucket_size; } iterator begin() const; iterator end() const; boost::tuple<int, int> size() const; // returns true if there are no working nodes // in the routing table bool need_bootstrap() const; void replacement_cache(bucket_t& nodes) const; // used for debug and monitoring purposes. This will print out // the state of the routing table to the given stream void print_state(std::ostream& os) const; private: // constant called k in paper int m_bucket_size; dht_settings const& m_settings; // 160 (k-bucket, replacement cache) pairs typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t; table_t m_buckets; // timestamps of the last activity in each bucket typedef boost::array<boost::posix_time::ptime, 160> table_activity_t; table_activity_t m_bucket_activity; node_id m_id; // our own node id // this is a set of all the endpoints that have // been identified as router nodes. They will // be used in searches, but they will never // be added to the routing table. std::set<udp::endpoint> m_router_nodes; // this is the lowest bucket index with nodes in it int m_lowest_active_bucket; }; } } // namespace libtorrent::dht #endif // ROUTING_TABLE_HPP <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <algorithm> using namespace std; #define MAX_PAIR_NUM 1000 typedef struct Record { int pos; int pixel; } Record; int pixel_pair[MAX_PAIR_NUM][2]; int img_width; Record result[MAX_PAIR_NUM * 9]; bool cmp(const Record& a, const Record& b); int get_pixel_via_pos(int pos, int pair_cnt); int encode_pixel(int pos, int pixel_cnt, int pair_cnt); int main() { while (cin >> img_width && img_width > 0) { cout << img_width << endl; int num, pixel; int pair_cnt = 0; int pixel_cnt = 0; int start_pos = 1; while (cin >> pixel >> num && num != 0 && pixel != 0) { pixel_pair[pair_cnt][0] = pixel; pixel_pair[pair_cnt][1] = start_pos; pixel_cnt += num; start_pos += num; pair_cnt++; } int idx = 0; for (int k = 0; k < pair_cnt; k++) { int center = pixel_pair[k][1]; int row = (center - 1) / img_width; int col = (center - 1) % img_width; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { int pos = i * img_width + j + 1; if (i < 0 || pos > pixel_cnt || j < 0 || j == img_width) continue; result[idx].pos = pos; result[idx].pixel = encode_pixel(pos, pixel_cnt, pair_cnt); idx++; } } sort(result, result + idx, cmp); /* for (int i = 0; i < idx; i++) cout << result[i].pixel << " " << result[i].pos << endl; */ Record prev = result[0]; if (idx > 1) { for (int i = 1; i < idx; i++) { if (prev.pixel != result[i].pixel) { cout << prev.pixel << " " << result[i].pos - prev.pos << endl; prev = result[i]; } } cout << result[idx - 1].pixel << " " << pixel_cnt - prev.pos + 1 << endl; } else cout << prev.pixel << " " << prev.pos << endl; cout << "0 0" << endl; /* for (int i = 0; i < pair_cnt; i++) cout << pixel_pair[i][0] << " " << pixel_pair[i][1] << endl; cout << pixel_cnt << endl; */ } cout << 0 << endl; } bool cmp(const Record& a, const Record& b) { return a.pos < b.pos; } int get_pixel_via_pos(int pos, int pair_cnt) { if (pair_cnt == 1) return pixel_pair[0][0]; int prev = pixel_pair[0][1]; for (int i = 1; i < pair_cnt; i++) { if (pos >= prev && pos < pixel_pair[i][1]) return pixel_pair[i - 1][0]; } return pixel_pair[pair_cnt - 1][0]; } int encode_pixel(int pos, int pixel_cnt, int pair_cnt) { int row = (pos - 1) / img_width; int col = (pos - 1) % img_width; int ret = 0; int tmp = 0; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { int curr = i * img_width + j + 1; if (i < 0 || curr > pixel_cnt || j == img_width || j < 0 || curr == pos) continue; tmp = abs(get_pixel_via_pos(pos, pair_cnt) - get_pixel_via_pos(curr, pair_cnt)); if (tmp > ret) ret = tmp; } return ret; } <commit_msg>p1009b<commit_after>#include <iostream> #include <cmath> #include <algorithm> using namespace std; #define MAX_PAIR_NUM 1000 typedef struct Record { int pos; int pixel; } Record; int img_width; int pixel_pair[MAX_PAIR_NUM][2]; Record result[MAX_PAIR_NUM * 9]; bool cmp(const Record& a, const Record& b); int get_pixel_via_pos(int pos, int pair_cnt); int encode_pixel(int pos, int pixel_cnt, int pair_cnt); int main() { while (cin >> img_width && img_width > 0) { int num, pixel; int pair_cnt = 0; int pixel_cnt = 0; int start_pos = 1; while (cin >> pixel >> num && num != 0 && pixel != 0) { pixel_pair[pair_cnt][0] = pixel; pixel_pair[pair_cnt][1] = start_pos; pixel_cnt += num; start_pos += num; pair_cnt++; } int idx = 0; for (int k = 0; k < pair_cnt; k++) { int center = pixel_pair[k][1]; int row = (center - 1) / img_width; int col = (center - 1) % img_width; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { int pos = i * img_width + j + 1; if (i < 0 || pos > pixel_cnt || j < 0 || j == img_width) continue; result[idx].pos = pos; result[idx].pixel = encode_pixel(pos, pixel_cnt, pair_cnt); idx++; } } sort(result, result + idx, cmp); /* for (int i = 0; i < idx; i++) cout << result[i].pixel << " " << result[i].pos << endl; */ cout << img_width << endl; Record prev = result[0]; if (idx > 1) { for (int i = 1; i < idx; i++) { if (prev.pixel != result[i].pixel) { cout << prev.pixel << " " << result[i].pos - prev.pos << endl; prev = result[i]; } } cout << result[idx - 1].pixel << " " << pixel_cnt - prev.pos + 1 << endl; } else cout << prev.pixel << " " << prev.pos << endl; cout << "0 0" << endl; /* for (int i = 0; i < pair_cnt; i++) cout << pixel_pair[i][0] << " " << pixel_pair[i][1] << endl; cout << pixel_cnt << endl; */ } cout << 0 << endl; } bool cmp(const Record& a, const Record& b) { return a.pos < b.pos; } int get_pixel_via_pos(int pos, int pair_cnt) { if (pair_cnt == 1) return pixel_pair[0][0]; int prev = pixel_pair[0][1]; for (int i = 1; i < pair_cnt; i++) { if (pos >= prev && pos < pixel_pair[i][1]) return pixel_pair[i - 1][0]; } return pixel_pair[pair_cnt - 1][0]; } int encode_pixel(int pos, int pixel_cnt, int pair_cnt) { int row = (pos - 1) / img_width; int col = (pos - 1) % img_width; int ret = 0; int tmp = 0; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { int curr = i * img_width + j + 1; if (i < 0 || curr > pixel_cnt || j == img_width || j < 0 || curr == pos) continue; tmp = abs(get_pixel_via_pos(pos, pair_cnt) - get_pixel_via_pos(curr, pair_cnt)); if (tmp > ret) ret = tmp; } return ret; } <|endoftext|>
<commit_before>#include "otc/newick.h" #include "otc/util.h" #include "otc/test_harness.h" using namespace otc; class TestValidTreeStruct { const std::string filename; public: TestValidTreeStruct(const std::string & fn) :filename(fn) { } char runTest(const TestHarness &) const { std::ifstream inp; if (!openUTF8File(filename, inp)) { return 'U'; } for (;;) { auto nt = readNextNewick<RTNodeNoData, RTreeNoData>(inp, filename); if (nt == nullptr) { return '.'; } } } }; int main(int argc, char *argv[]) { std::vector<std::string> validfilenames = {"abc-newick.tre", "words-polytomy.tre", "bifurcating.tre", "monotypic.tre", "branch-lengths.tre", "quotedwords-polytomy.tre", "polytomy-with-comments.tre", "underscore-handling.tre", "whitespace-handling.tre"}; TestHarness th(argc, argv); TestsVec tests; for (auto fn : validfilenames) { //const TestValidTreeStruct tvts(fn); const TestValidTreeStruct tvts{fn}; TestCallBack tcb = [tvts](const TestHarness &h) { return tvts.runTest(h); }; const TestFn tf{fn, tcb}; tests.push_back(tf); } return th.runTests(tests); } <commit_msg>tree construction tests working<commit_after>#include "otc/newick.h" #include "otc/util.h" #include "otc/test_harness.h" using namespace otc; class TestValidTreeStruct { const std::string filename; public: TestValidTreeStruct(const std::string & fn) :filename(fn) { } char runTest(const TestHarness &h) const { auto fp = h.getFilePath(filename); //std::cerr << "fn = " << fp<< '\n'; std::ifstream inp; if (!openUTF8File(fp, inp)) { return 'U'; } for (;;) { auto nt = readNextNewick<RTNodeNoData, RTreeNoData>(inp, filename); if (nt == nullptr) { return '.'; } } } }; int main(int argc, char *argv[]) { std::vector<std::string> validfilenames = {"abc-newick.tre", "words-polytomy.tre", "bifurcating.tre", "monotypic.tre", "branch-lengths.tre", "quotedwords-polytomy.tre", "polytomy-with-comments.tre", "underscore-handling.tre", "whitespace-handling.tre"}; TestHarness th(argc, argv); TestsVec tests; for (auto fn : validfilenames) { //const TestValidTreeStruct tvts(fn); const TestValidTreeStruct tvts{fn}; TestCallBack tcb = [tvts](const TestHarness &h) { return tvts.runTest(h); }; const TestFn tf{fn, tcb}; tests.push_back(tf); } return th.runTests(tests); } <|endoftext|>
<commit_before>#include "joystick.hpp" // #include "Rotate.h" #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <vector> #include <string> #include <math.h> const int DEAD_ZONE = 16384; const int AXIS_MAX = 32767.0; using namespace ros; using namespace std; int main(int argc, char **argv) { // init sdl and connect to controller Joystick joystick; string name = joystick.getName(); cout << "Used controller: " << name.c_str() << endl; // init ros double l_scale = 1.0; double a_scale = 1.0; init(argc, argv, "remotecontrol"); NodeHandle n; Publisher pub; n.param("scale_angular", a_scale, a_scale); n.param("scale_linear", l_scale, l_scale); pub = n.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 1); // Create a fresh publisher before using this line... // pub = n.advertise<geometry_msgs::Twist>("turtle1/cmd_rotate", 1); // startup key loop // use button.0 to stop bool quit = false; while (!quit) { // get axis values // use axis.0 for left/right // and axis.1 for up/down JoystickEvent event = joystick.getEvent(); vector<short> axis = event.getAxis(); // check for button.0 to stop vector<bool> buttons = event.getButtons(); if (buttons.at(0) == true) quit = true; // calculate position values double angular = (-1.0) * axis.at(0) / AXIS_MAX; double linear = (-1.0) * axis.at(1) / AXIS_MAX; double stick2y = (-1.0) * axis.at(2) / AXIS_MAX; angular = min(max(angular, -1.0), 1.0); linear = min(max(linear, -1.0), 1.0); stick2y = min(max(stick2y, -1.0), 1.0); // SPEEED-BUTTON! if(!buttons.at(1)) { angular *= 0.25; linear *= 0.25; } geometry_msgs::Twist twist; twist.angular.z = angular; twist.linear.x = linear; // Rotate rotate; // rotate.linear.x = stick2y; pub.publish(twist); } return 0; } <commit_msg>remotecontrol: corrected reverse driving<commit_after>#include "joystick.hpp" // #include "Rotate.h" #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <vector> #include <string> #include <math.h> const int DEAD_ZONE = 16384; const int AXIS_MAX = 32767.0; using namespace ros; using namespace std; int main(int argc, char **argv) { // init sdl and connect to controller Joystick joystick; string name = joystick.getName(); cout << "Used controller: " << name.c_str() << endl; // init ros double l_scale = 1.0; double a_scale = 1.0; init(argc, argv, "remotecontrol"); NodeHandle n; Publisher pub; n.param("scale_angular", a_scale, a_scale); n.param("scale_linear", l_scale, l_scale); pub = n.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 1); // Create a fresh publisher before using this line... // pub = n.advertise<geometry_msgs::Twist>("turtle1/cmd_rotate", 1); // startup key loop // use button.0 to stop bool quit = false; while (!quit) { // get axis values // use axis.0 for left/right // and axis.1 for up/down JoystickEvent event = joystick.getEvent(); vector<short> axis = event.getAxis(); // check for button.0 to stop vector<bool> buttons = event.getButtons(); if (buttons.at(0) == true) quit = true; // calculate position values double angular = (-1.0) * axis.at(0) / AXIS_MAX; double linear = (-1.0) * axis.at(1) / AXIS_MAX; double stick2y = (-1.0) * axis.at(2) / AXIS_MAX; angular = min(max(angular, -1.0), 1.0); linear = min(max(linear, -1.0), 1.0); stick2y = min(max(stick2y, -1.0), 1.0); // SPEEED-BUTTON! if (!buttons.at(1)) { angular *= 0.25; linear *= 0.25; } if (linear < 0) { angular *= (-1.0); } ROS_INFO("%f : %f", linear, angular); geometry_msgs::Twist twist; twist.angular.z = angular; twist.linear.x = linear; // Rotate rotate; // rotate.linear.x = stick2y; pub.publish(twist); } return 0; } <|endoftext|>
<commit_before>// EtherEvent - Easy to use password authenticated network communication between Arduinos and EventGhost Network Event Sender/Receiver and TCPEvents plugins: http://github.com/per1234/EtherEvent #define ETHEREVENT_NO_AUTHENTICATION //this is to prevent EtherEvent.cpp's include of EtherEvent.h from including MD5.h(not needed in this file even with authentication enabled #include "EtherEvent.h" #define Serial if(ETHEREVENT_DEBUG)Serial const unsigned int timeoutDefault = 1000; //(ms)Timeout duration for ethernet stream functions. const byte sendDoubleDecimalPlacesDefault = 3; //default number of decimal places when sending event/payload of double/float type ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //constructor ///////////////////////////////////////////////////////////////////////////////////////////////////////////// EtherEventClass::EtherEventClass() { timeout = timeoutDefault; //set default timeout value, this can be changed by the user via setTimeout() sendDoubleDecimalPlaces = sendDoubleDecimalPlacesDefault; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //begin ///////////////////////////////////////////////////////////////////////////////////////////////////////////// boolean EtherEventClass::begin(const byte eventLengthMaxInput, const unsigned int payloadLengthMaxInput) { #if ETHEREVENT_DEBUG == true delay(20); //There needs to be a delay between the calls to Serial.begin() in sketch setup() and here or garbage will be printed to the serial monitor #endif Serial.begin(EtherEventNamespace::debugSerialBaud); //for debugging Serial.println(F("\n\n\nEtherEvent.begin")); eventLengthMax = eventLengthMaxInput; payloadLengthMax = payloadLengthMaxInput; availableEventSubmessageLengthMax = max(max(EtherEventNamespace::payloadWithoutReleaseLength, EtherEventNamespace::payloadSeparatorLength + payloadLengthMax + TCPEventsPayloadFormattingLength), eventLengthMax); if (availableEventSubmessageLengthMax > availableEventSubmessageLengthMax + 1) { //availableEventSubmessageLengthMax is the max value of the type availableEventSubmessageLengthMax--; //have to decrement because I need to add one in the event/payload handler section of availableEvent() } receivedEvent = (char*)realloc(receivedEvent, (eventLengthMax + 1) * sizeof(*receivedEvent)); receivedEvent[0] = 0; //clear buffer - realloc does not zero initialize so the buffer could contain anything receivedPayload = (char*)realloc(receivedPayload, (payloadLengthMax + 1) * sizeof(*receivedPayload)); receivedPayload[0] = 0; //clear buffer - realloc does not zero initialize so the buffer could contain anything if (receivedEvent == NULL || receivedPayload == NULL) { Serial.println(F("memory allocation failed")); return false; } return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //availablePayload - returns the number of chars in the payload including the null terminator if there is one ///////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int EtherEventClass::availablePayload() { if (unsigned int receivedPayloadLength = strlen(receivedPayload)) { //strlen(receivedPayload) > 0 return receivedPayloadLength + 1; //length of the payload + null terminator } return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //readEvent ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::readEvent(char eventBuffer[]) { strcpy(eventBuffer, receivedEvent); receivedEvent[0] = 0; //reset the event buffer receivedEventLength = 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //readPayload ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::readPayload(char payloadBuffer[]) { strcpy(payloadBuffer, receivedPayload); receivedPayload[0] = 0; //reset the payload buffer } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //flushReceiver - dump the last message received so another one can be received ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::flushReceiver() { Serial.println(F("EtherEvent.flushReceiver: start")); receivedEvent[0] = 0; //reset the event buffer receivedPayload[0] = 0; //reset the payload buffer receivedEventLength = 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //senderIP ///////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef ethernetclientwithremoteIP_h //the include guard from the modified EthernetClient.h IPAddress EtherEventClass::senderIP() { //returns the ip address the current event was sent from. Requires modified ethernet library, thus the preprocesser direcive system return fromIP; } #endif ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //setTimeout ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::setTimeout(const unsigned int timeoutInput) { timeout = timeoutInput; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //getTimeout ///////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int EtherEventClass::getTimeout() { return timeout; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //setPassword ///////////////////////////////////////////////////////////////////////////////////////////////////////////// boolean EtherEventClass::setPassword(const char passwordInput[]) { Serial.println(F("EtherEvent.setPassword(char)")); passwordLength = strlen(passwordInput); password = (char*)realloc(password, (passwordLength + 1) * sizeof(*password)); //allocate memory for the password strcpy(password, passwordInput); //store the password if (password == NULL) { Serial.println(F("EtherEvent.setPassword: memory allocation failed")); return false; } return true; } boolean EtherEventClass::setPassword(const __FlashStringHelper* passwordInput) { Serial.println(F("EtherEvent.setPassword(F())")); passwordLength = FSHlength(passwordInput); password = (char*)realloc(password, (passwordLength + 1) * sizeof(*password)); //allocate memory for the password if (password == NULL) { Serial.println(F("EtherEvent.setPassword: memory allocation failed")); return false; } memcpy_P(password, passwordInput, passwordLength + 1); //+1 for the null terminator return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //setSendDoubleDecimalPlaces ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::setSendDoubleDecimalPlaces(const byte decimalPlaces) { Serial.println(F("EtherEvent.setSendDoubleDecimalPlaces")); sendDoubleDecimalPlaces = decimalPlaces; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //IPtoa - convert IPAddress to char array and put it in the passed buffer ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::IPtoa(const IPAddress &IP, char IPcharBuffer[]) { utoa(IP[0], IPcharBuffer, 10); //convert the first octet for (byte octetCount = 1; octetCount < 4; octetCount++) { //convert the other 3 octets strcat(IPcharBuffer, "."); char octetChar[3 + 1]; //3 digit byte + null terminator utoa(IP[octetCount], octetChar, 10); //convert the first octet strcat(IPcharBuffer, octetChar); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //FSHlength - determine length of __FlashStringHelper ///////////////////////////////////////////////////////////////////////////////////////////////////////////// byte EtherEventClass::FSHlength(const __FlashStringHelper* passwordInput) { const char* passwordInputPointer = (const char PROGMEM *)passwordInput; byte stringLength = 0; while (true) { unsigned char character = pgm_read_byte(passwordInputPointer++); if (character == 0) break; stringLength++; } return stringLength; } EtherEventClass EtherEvent; //This sets up a single global instance of the library so the class doesn't need to be declared in the user sketch and multiple instances are not necessary in this case. <commit_msg>Use same debug output define in both source files<commit_after>// EtherEvent - Easy to use password authenticated network communication between Arduinos and EventGhost Network Event Sender/Receiver and TCPEvents plugins: http://github.com/per1234/EtherEvent #define ETHEREVENT_NO_AUTHENTICATION //this is to prevent EtherEvent.cpp's include of EtherEvent.h from including MD5.h(not needed in this file even with authentication enabled #include "EtherEvent.h" const unsigned int timeoutDefault = 1000; //(ms)Timeout duration for ethernet stream functions. const byte sendDoubleDecimalPlacesDefault = 3; //default number of decimal places when sending event/payload of double/float type ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //constructor ///////////////////////////////////////////////////////////////////////////////////////////////////////////// EtherEventClass::EtherEventClass() { timeout = timeoutDefault; //set default timeout value, this can be changed by the user via setTimeout() sendDoubleDecimalPlaces = sendDoubleDecimalPlacesDefault; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //begin ///////////////////////////////////////////////////////////////////////////////////////////////////////////// boolean EtherEventClass::begin(const byte eventLengthMaxInput, const unsigned int payloadLengthMaxInput) { #if ETHEREVENT_DEBUG == true delay(20); //There needs to be a delay between the calls to ETHEREVENT_SERIAL.begin() in sketch setup() and here or garbage will be printed to the serial monitor #endif ETHEREVENT_SERIAL.begin(EtherEventNamespace::debugSerialBaud); //for debugging ETHEREVENT_SERIAL.println(F("\n\n\nEtherEvent.begin")); eventLengthMax = eventLengthMaxInput; payloadLengthMax = payloadLengthMaxInput; availableEventSubmessageLengthMax = max(max(EtherEventNamespace::payloadWithoutReleaseLength, EtherEventNamespace::payloadSeparatorLength + payloadLengthMax + TCPEventsPayloadFormattingLength), eventLengthMax); if (availableEventSubmessageLengthMax > availableEventSubmessageLengthMax + 1) { //availableEventSubmessageLengthMax is the max value of the type availableEventSubmessageLengthMax--; //have to decrement because I need to add one in the event/payload handler section of availableEvent() } receivedEvent = (char*)realloc(receivedEvent, (eventLengthMax + 1) * sizeof(*receivedEvent)); receivedEvent[0] = 0; //clear buffer - realloc does not zero initialize so the buffer could contain anything receivedPayload = (char*)realloc(receivedPayload, (payloadLengthMax + 1) * sizeof(*receivedPayload)); receivedPayload[0] = 0; //clear buffer - realloc does not zero initialize so the buffer could contain anything if (receivedEvent == NULL || receivedPayload == NULL) { ETHEREVENT_SERIAL.println(F("memory allocation failed")); return false; } return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //availablePayload - returns the number of chars in the payload including the null terminator if there is one ///////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int EtherEventClass::availablePayload() { if (unsigned int receivedPayloadLength = strlen(receivedPayload)) { //strlen(receivedPayload) > 0 return receivedPayloadLength + 1; //length of the payload + null terminator } return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //readEvent ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::readEvent(char eventBuffer[]) { strcpy(eventBuffer, receivedEvent); receivedEvent[0] = 0; //reset the event buffer receivedEventLength = 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //readPayload ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::readPayload(char payloadBuffer[]) { strcpy(payloadBuffer, receivedPayload); receivedPayload[0] = 0; //reset the payload buffer } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //flushReceiver - dump the last message received so another one can be received ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::flushReceiver() { ETHEREVENT_SERIAL.println(F("EtherEvent.flushReceiver: start")); receivedEvent[0] = 0; //reset the event buffer receivedPayload[0] = 0; //reset the payload buffer receivedEventLength = 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //senderIP ///////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef ethernetclientwithremoteIP_h //the include guard from the modified EthernetClient.h IPAddress EtherEventClass::senderIP() { //returns the ip address the current event was sent from. Requires modified ethernet library, thus the preprocesser direcive system return fromIP; } #endif ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //setTimeout ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::setTimeout(const unsigned int timeoutInput) { timeout = timeoutInput; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //getTimeout ///////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int EtherEventClass::getTimeout() { return timeout; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //setPassword ///////////////////////////////////////////////////////////////////////////////////////////////////////////// boolean EtherEventClass::setPassword(const char passwordInput[]) { ETHEREVENT_SERIAL.println(F("EtherEvent.setPassword(char)")); passwordLength = strlen(passwordInput); password = (char*)realloc(password, (passwordLength + 1) * sizeof(*password)); //allocate memory for the password strcpy(password, passwordInput); //store the password if (password == NULL) { ETHEREVENT_SERIAL.println(F("EtherEvent.setPassword: memory allocation failed")); return false; } return true; } boolean EtherEventClass::setPassword(const __FlashStringHelper* passwordInput) { ETHEREVENT_SERIAL.println(F("EtherEvent.setPassword(F())")); passwordLength = FSHlength(passwordInput); password = (char*)realloc(password, (passwordLength + 1) * sizeof(*password)); //allocate memory for the password if (password == NULL) { ETHEREVENT_SERIAL.println(F("EtherEvent.setPassword: memory allocation failed")); return false; } memcpy_P(password, passwordInput, passwordLength + 1); //+1 for the null terminator return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //setSendDoubleDecimalPlaces ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::setSendDoubleDecimalPlaces(const byte decimalPlaces) { ETHEREVENT_SERIAL.println(F("EtherEvent.setSendDoubleDecimalPlaces")); sendDoubleDecimalPlaces = decimalPlaces; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //IPtoa - convert IPAddress to char array and put it in the passed buffer ///////////////////////////////////////////////////////////////////////////////////////////////////////////// void EtherEventClass::IPtoa(const IPAddress &IP, char IPcharBuffer[]) { utoa(IP[0], IPcharBuffer, 10); //convert the first octet for (byte octetCount = 1; octetCount < 4; octetCount++) { //convert the other 3 octets strcat(IPcharBuffer, "."); char octetChar[3 + 1]; //3 digit byte + null terminator utoa(IP[octetCount], octetChar, 10); //convert the first octet strcat(IPcharBuffer, octetChar); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //FSHlength - determine length of __FlashStringHelper ///////////////////////////////////////////////////////////////////////////////////////////////////////////// byte EtherEventClass::FSHlength(const __FlashStringHelper* passwordInput) { const char* passwordInputPointer = (const char PROGMEM *)passwordInput; byte stringLength = 0; while (true) { unsigned char character = pgm_read_byte(passwordInputPointer++); if (character == 0) break; stringLength++; } return stringLength; } EtherEventClass EtherEvent; //This sets up a single global instance of the library so the class doesn't need to be declared in the user sketch and multiple instances are not necessary in this case. <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #if defined (__GCC__) #include <cxxabi.h> #elif qPlatform_Windows #include <Windows.h> #include <Dbghelp.h> #endif #include "../Execution/Finally.h" #include "Demangle.h" using namespace Stroika::Foundation; #if qPlatform_Windows // otherwise modules linking with this code will tend to get link errors without explicitly linking // to this module... #pragma comment (lib, "Dbghelp.lib") #endif /* ******************************************************************************** ************************ Debug::DropIntoDebuggerIfPresent ********************** ******************************************************************************** */ Characters::String Debug::Demangle (const Characters::String& originalName) { #if defined (__GCC__) int status {}; char* realname = abi::__cxa_demangle (originalName.AsNarrowSDKString ().c_str (), 0, 0, &status); auto&& cleanup = Execution::Finally ([&realname]() { if (realname != nullptr) { ::free (realname); } }); if (status == 0) { return Characters::String::FromNarrowSDKString (realname); } #elif qPlatform_Windows char resultBuf[1000]; if (::UnDecorateSymbolName (originalName.AsNarrowSDKString ().c_str (), resultBuf, sizeof (resultBuf), UNDNAME_COMPLETE) != 0) { return Characters::String::FromNarrowSDKString (resultBuf); } #endif return originalName; } <commit_msg>larger buffer for UnDecorateSymbolName<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #if defined (__GCC__) #include <cxxabi.h> #elif qPlatform_Windows #include <Windows.h> #include <Dbghelp.h> #endif #include "../Execution/Finally.h" #include "Demangle.h" using namespace Stroika::Foundation; #if qPlatform_Windows // otherwise modules linking with this code will tend to get link errors without explicitly linking // to this module... #pragma comment (lib, "Dbghelp.lib") #endif /* ******************************************************************************** ************************ Debug::DropIntoDebuggerIfPresent ********************** ******************************************************************************** */ Characters::String Debug::Demangle (const Characters::String& originalName) { #if defined (__GCC__) int status {}; char* realname = abi::__cxa_demangle (originalName.AsNarrowSDKString ().c_str (), 0, 0, &status); auto&& cleanup = Execution::Finally ([&realname]() { if (realname != nullptr) { ::free (realname); } }); if (status == 0) { return Characters::String::FromNarrowSDKString (realname); } #elif qPlatform_Windows char resultBuf[10*1024]; if (::UnDecorateSymbolName (originalName.AsNarrowSDKString ().c_str (), resultBuf, sizeof (resultBuf), UNDNAME_COMPLETE) != 0) { return Characters::String::FromNarrowSDKString (resultBuf); } #endif return originalName; } <|endoftext|>
<commit_before>#include "coders_crux.gen.h" // Contains FB32 palette #include "number_font.h" #include "ElementCube.h" #include "Element.h" #include "periodic.h" /* Order of adding electrons according to WolframAlpha: 1. Right 2. Left 3. Top 4. Bottom Repeat pattern as needed. Also used when rendering lines for the covalent bonds. */ enum LewisSides { LRight = 0, LLeft = 1, LTop = 2, LBottom = 3, LFirst = LRight, LLast = LBottom }; void ElementCube::Init(int cubeId, int initialElementNum) { this->cubeId = cubeId; this->cube = CubeID(cubeId); currentElementNum = initialElementNum; Element::GetRawElement(currentElementNum, &currentElement); isDirty = true; // Initialize video: v.attach(cube); v.initMode(FB32); v.fb32.fill(BG_COLOR); // Load the palette: for (int j = 0, h = 0; j < PALETTE_COUNT; j++, h += 3) { v.colormap[j].set(palette[h], palette[h + 1], palette[h + 2]); } } ElementCube::ElementCube() { } ElementCube::ElementCube(int cubeId, int initialElementNum) { Init(cubeId, initialElementNum); } ElementCube::ElementCube(int cubeId, const char* initialElementSymbol) { Init(cubeId, Element::GetRawElementNum(initialElementSymbol)); } void ElementCube::GoToNextElement() { currentElementNum++; if (currentElementNum >= Element::GetRawElementCount()) { currentElementNum = 0; } Element::GetRawElement(currentElementNum, &currentElement); isDirty = true; } void ElementCube::ResetElement() { currentElement.ResetToBasicState(); isDirty = true;//TODO: Right now the cubes get marked as dirty when they shouldn't. } int ElementCube::GetCubeId() { return cubeId; } Element* ElementCube::GetElement() { return &currentElement; } void ElementCube::SetDirty() { isDirty = true; } void ElementCube::Render() { if (!isDirty) { return; } //LOG("Cube %d is dirty! Redrawing.\n", (int)cube); // Clear the screen: v.fb32.fill(BG_COLOR); // Draw the element symbol: const char* symbol = currentElement.GetSymbol(); int chars = strlen(symbol); int stringWidth = chars * CODERS_CRUX_GLYPH_WIDTH + (chars - 1) * LETTER_SPACING; int stringHeight = CODERS_CRUX_GLYPH_HEIGHT - LETTER_DESCENDER_HEIGHT; // Add space for +/- symbol if (currentElement.GetCharge() != 0) { stringWidth += 3 + LETTER_SPACING; // Add space for number if (abs(currentElement.GetCharge()) > 1) { stringWidth += NUMBER_FONT_GLYPH_WIDTH + LETTER_SPACING; } } int x = SCREEN_WIDTH / 2 - stringWidth / 2; int y = SCREEN_HEIGHT / 2 - stringHeight / 2; // Draw the symbol: for (int i = 0; i < chars; i++) { //LOG("Drawing '%c'\n", symbol[i]); DrawCharAt(x, y, symbol[i]); x += CODERS_CRUX_GLYPH_WIDTH + LETTER_SPACING; } // Draw the +/- symbol: if (currentElement.GetCharge() != 0 && currentElement.HasBondType(BondType_Ionic)) { // Draw the line for the dash v.fb32.plot(vec(x + 0, y + 1), CHARGE_COLOR); v.fb32.plot(vec(x + 1, y + 1), CHARGE_COLOR); v.fb32.plot(vec(x + 2, y + 1), CHARGE_COLOR); // Draw the nubs for the plus for positive charge if (currentElement.GetCharge() > 0) { v.fb32.plot(vec(x + 1, y + 0), CHARGE_COLOR); v.fb32.plot(vec(x + 1, y + 2), CHARGE_COLOR); } // Draw the number if (abs(currentElement.GetCharge()) > 1) { DrawNumAt(x + 3 + LETTER_SPACING, y - 1, currentElement.GetCharge(), CHARGE_COLOR); } } // Draw covalent bond (basic): if (currentElement.HasBondType(BondType_Covalent)) { for (int i = 0; i < currentElement.GetSharedElectrons() / 2; i++) { const int size = 5; int x = SCREEN_WIDTH - size - 1; int y = 1 + i * (size + 1); for (int xoff = 0; xoff < size; xoff++) { for (int yoff = 0; yoff < size; yoff++) { int color = COVALENT_COLOR_OUTTER; if (xoff > 0 && xoff < (size - 1) && yoff > 0 && yoff < (size - 1)) { color = COVALENT_COLOR_INNER; } v.fb32.plot(vec(x + xoff, y + yoff), color); } } } } // Draw potential reaction: if (currentElement.HasBondType(BondType_Potential)) { // Draw border on the cube //NOTE: Relies on screen being square. for (int i = 0; i < SCREEN_WIDTH; i++) { v.fb32.plot(vec(i, 0), POTENTIAL_COLOR); v.fb32.plot(vec(i, SCREEN_HEIGHT - 1), POTENTIAL_COLOR); v.fb32.plot(vec(0, i), POTENTIAL_COLOR); v.fb32.plot(vec(SCREEN_WIDTH - 1, i), POTENTIAL_COLOR); } } // Draw lines for covalent bonds DrawCovalentLine(LRight, stringWidth, stringHeight); DrawCovalentLine(LBottom, stringWidth, stringHeight); DrawCovalentLine(LLeft, stringWidth, stringHeight); DrawCovalentLine(LTop, stringWidth, stringHeight); // Draw electrons: DrawLewisDots(stringWidth, stringHeight); isDirty = false; } void ElementCube::DrawCharAt(int x, int y, char c) { // Convert char to glyph id: if (c >= 'a' && c <= 'z') { c = c - 'a' + 26; } else if (c >= 'A' && c <= 'Z') { c -= 'A'; } else { Assert(false); }//Invalid character //This function seems broken, or I am misunderstanding its purpose. //v.fb32.bitmap(vec(x, y), vec(CODERS_CRUX_GLYPH_WIDTH, CODERS_CRUX_GLYPH_HEIGHT), &coders_crux[c * CODERS_CRUX_GLYPH_SIZE], CODERS_CRUX_GLYPH_WIDTH); for (int i = 0; i < CODERS_CRUX_GLYPH_HEIGHT; i++) { for (int j = 0; j < CODERS_CRUX_GLYPH_WIDTH; j++) { v.fb32.plot(vec(x + j, y + i), coders_crux[j + i * CODERS_CRUX_GLYPH_WIDTH + c * CODERS_CRUX_GLYPH_SIZE]); } } } void ElementCube::DrawNumAt(int x, int y, int num, int color) { if (num < 0 || num >= 10) { num = 10; // Draw the bad number symbol } for (int i = 0; i < NUMBER_FONT_GLYPH_HEIGHT; i++) { for (int j = 0; j < NUMBER_FONT_GLYPH_WIDTH; j++) { if (number_font[j + i * NUMBER_FONT_GLYPH_WIDTH + num * NUMBER_FONT_GLYPH_SIZE]) { v.fb32.plot(vec(x + j, y + i), color); } } } } void ElementCube::DrawCovalentLine(int sides, int stringWidth, int stringHeight) { int x = 0; int y = 0; switch (sides) { case LRight: x = SCREEN_WIDTH / 2 + stringWidth / 2; y = SCREEN_HEIGHT / 2; for (int i = 6; (x + i) < SCREEN_WIDTH; i++) { v.fb32.plot(vec(x + i, y), CHARGE_COLOR); } break; case LBottom: x = SCREEN_WIDTH / 2; y = SCREEN_HEIGHT / 2 + stringHeight / 2; for (int i = 4; (y + i) < SCREEN_HEIGHT; i++) { v.fb32.plot(vec(x, y + i), CHARGE_COLOR); } break; case LLeft: x = SCREEN_WIDTH / 2 - stringWidth / 2; y = SCREEN_HEIGHT / 2; for (int i = 6; (x - i) >= 0; i++) { v.fb32.plot(vec(x - i, y), CHARGE_COLOR); } break; case LTop: x = SCREEN_WIDTH / 2; y = SCREEN_HEIGHT / 2 - stringHeight / 2; for (int i = 4; (y - i) >= 0; i++) { v.fb32.plot(vec(x, y - i), CHARGE_COLOR); } break; } } void ElementCube::DrawLewisDots(int stringWidth, int stringHeight) { //TODO: This is a bit of a hack. We need to properly set the outer electron count to 0 when the orbital is filled. if (currentElement.GetCharge() != 0 && currentElement.GetNumOuterElectrons() == 8) { return; } for (int s = LFirst; s <= LLast; s++) { // Calculate the number of electrons on this side int e = (currentElement.GetNumOuterElectrons() + 3 - s) / 4; int x = SCREEN_WIDTH / 2; int y = SCREEN_HEIGHT / 2; // Calulate offset to get on the correct side: switch (s) { case LRight: x += stringWidth / 2 + 2; y += LETTER_DESCENDER_HEIGHT / 2; break; case LLeft: x -= stringWidth / 2 + 2; y += LETTER_DESCENDER_HEIGHT / 2; break; case LTop: x++; // Looks more natural one pixel to the right y -= stringHeight / 2 + 2; break; case LBottom: x++; // Looks more natural one pixel to the right y += stringHeight / 2 + 2; break; } // Calculate offset for electron separation: switch (s) { case LRight: case LLeft: y -= (e - 1) * 2; break; case LTop: case LBottom: x -= (e - 1) * 2; break; } // Draw the electrons: for ( ; e > 0; e--) { v.fb32.plot(vec(x, y), ELECTRON_COLOR); switch (s) { case LRight: case LLeft: y += 2; break; case LTop: case LBottom: x += 2; break; } } } } <commit_msg>Integration of covalent bond line rendering.<commit_after>#include "coders_crux.gen.h" // Contains FB32 palette #include "number_font.h" #include "ElementCube.h" #include "Element.h" #include "periodic.h" /* Order of adding electrons according to WolframAlpha: 1. Right 2. Left 3. Top 4. Bottom Repeat pattern as needed. Also used when rendering lines for the covalent bonds. */ enum LewisSides { LRight = 0, LLeft = 1, LTop = 2, LBottom = 3, LFirst = LRight, LLast = LBottom }; void ElementCube::Init(int cubeId, int initialElementNum) { this->cubeId = cubeId; this->cube = CubeID(cubeId); currentElementNum = initialElementNum; Element::GetRawElement(currentElementNum, &currentElement); isDirty = true; // Initialize video: v.attach(cube); v.initMode(FB32); v.fb32.fill(BG_COLOR); // Load the palette: for (int j = 0, h = 0; j < PALETTE_COUNT; j++, h += 3) { v.colormap[j].set(palette[h], palette[h + 1], palette[h + 2]); } } ElementCube::ElementCube() { } ElementCube::ElementCube(int cubeId, int initialElementNum) { Init(cubeId, initialElementNum); } ElementCube::ElementCube(int cubeId, const char* initialElementSymbol) { Init(cubeId, Element::GetRawElementNum(initialElementSymbol)); } void ElementCube::GoToNextElement() { currentElementNum++; if (currentElementNum >= Element::GetRawElementCount()) { currentElementNum = 0; } Element::GetRawElement(currentElementNum, &currentElement); isDirty = true; } void ElementCube::ResetElement() { currentElement.ResetToBasicState(); isDirty = true;//TODO: Right now the cubes get marked as dirty when they shouldn't. } int ElementCube::GetCubeId() { return cubeId; } Element* ElementCube::GetElement() { return &currentElement; } void ElementCube::SetDirty() { isDirty = true; } void ElementCube::Render() { if (!isDirty) { return; } //LOG("Cube %d is dirty! Redrawing.\n", (int)cube); // Clear the screen: v.fb32.fill(BG_COLOR); // Draw the element symbol: const char* symbol = currentElement.GetSymbol(); int chars = strlen(symbol); int stringWidth = chars * CODERS_CRUX_GLYPH_WIDTH + (chars - 1) * LETTER_SPACING; int stringHeight = CODERS_CRUX_GLYPH_HEIGHT - LETTER_DESCENDER_HEIGHT; // Add space for +/- symbol if (currentElement.GetCharge() != 0) { stringWidth += 3 + LETTER_SPACING; // Add space for number if (abs(currentElement.GetCharge()) > 1) { stringWidth += NUMBER_FONT_GLYPH_WIDTH + LETTER_SPACING; } } int x = SCREEN_WIDTH / 2 - stringWidth / 2; int y = SCREEN_HEIGHT / 2 - stringHeight / 2; // Draw the symbol: for (int i = 0; i < chars; i++) { //LOG("Drawing '%c'\n", symbol[i]); DrawCharAt(x, y, symbol[i]); x += CODERS_CRUX_GLYPH_WIDTH + LETTER_SPACING; } // Draw the +/- symbol: if (currentElement.GetCharge() != 0 && currentElement.HasBondType(BondType_Ionic)) { // Draw the line for the dash v.fb32.plot(vec(x + 0, y + 1), CHARGE_COLOR); v.fb32.plot(vec(x + 1, y + 1), CHARGE_COLOR); v.fb32.plot(vec(x + 2, y + 1), CHARGE_COLOR); // Draw the nubs for the plus for positive charge if (currentElement.GetCharge() > 0) { v.fb32.plot(vec(x + 1, y + 0), CHARGE_COLOR); v.fb32.plot(vec(x + 1, y + 2), CHARGE_COLOR); } // Draw the number if (abs(currentElement.GetCharge()) > 1) { DrawNumAt(x + 3 + LETTER_SPACING, y - 1, currentElement.GetCharge(), CHARGE_COLOR); } } // Draw covalent bond lines: if (currentElement.GetBondTypeFor(BondSide_Right) == BondType_Covalent) { DrawCovalentLine(LRight, stringWidth, stringHeight); } if (currentElement.GetBondTypeFor(BondSide_Left) == BondType_Covalent) { DrawCovalentLine(LLeft, stringWidth, stringHeight); } if (currentElement.GetBondTypeFor(BondSide_Top) == BondType_Covalent) { DrawCovalentLine(LTop, stringWidth, stringHeight); } if (currentElement.GetBondTypeFor(BondSide_Bottom) == BondType_Covalent) { DrawCovalentLine(LBottom, stringWidth, stringHeight); } // Draw potential reaction: if (currentElement.HasBondType(BondType_Potential)) { // Draw border on the cube //NOTE: Relies on screen being square. for (int i = 0; i < SCREEN_WIDTH; i++) { v.fb32.plot(vec(i, 0), POTENTIAL_COLOR); v.fb32.plot(vec(i, SCREEN_HEIGHT - 1), POTENTIAL_COLOR); v.fb32.plot(vec(0, i), POTENTIAL_COLOR); v.fb32.plot(vec(SCREEN_WIDTH - 1, i), POTENTIAL_COLOR); } } // Draw electrons: DrawLewisDots(stringWidth, stringHeight); isDirty = false; } void ElementCube::DrawCharAt(int x, int y, char c) { // Convert char to glyph id: if (c >= 'a' && c <= 'z') { c = c - 'a' + 26; } else if (c >= 'A' && c <= 'Z') { c -= 'A'; } else { Assert(false); }//Invalid character //This function seems broken, or I am misunderstanding its purpose. //v.fb32.bitmap(vec(x, y), vec(CODERS_CRUX_GLYPH_WIDTH, CODERS_CRUX_GLYPH_HEIGHT), &coders_crux[c * CODERS_CRUX_GLYPH_SIZE], CODERS_CRUX_GLYPH_WIDTH); for (int i = 0; i < CODERS_CRUX_GLYPH_HEIGHT; i++) { for (int j = 0; j < CODERS_CRUX_GLYPH_WIDTH; j++) { v.fb32.plot(vec(x + j, y + i), coders_crux[j + i * CODERS_CRUX_GLYPH_WIDTH + c * CODERS_CRUX_GLYPH_SIZE]); } } } void ElementCube::DrawNumAt(int x, int y, int num, int color) { if (num < 0 || num >= 10) { num = 10; // Draw the bad number symbol } for (int i = 0; i < NUMBER_FONT_GLYPH_HEIGHT; i++) { for (int j = 0; j < NUMBER_FONT_GLYPH_WIDTH; j++) { if (number_font[j + i * NUMBER_FONT_GLYPH_WIDTH + num * NUMBER_FONT_GLYPH_SIZE]) { v.fb32.plot(vec(x + j, y + i), color); } } } } void ElementCube::DrawCovalentLine(int sides, int stringWidth, int stringHeight) { int x = 0; int y = 0; switch (sides) { case LRight: x = SCREEN_WIDTH / 2 + stringWidth / 2; y = SCREEN_HEIGHT / 2; for (int i = 6; (x + i) < SCREEN_WIDTH; i++) { v.fb32.plot(vec(x + i, y), CHARGE_COLOR); } break; case LBottom: x = SCREEN_WIDTH / 2; y = SCREEN_HEIGHT / 2 + stringHeight / 2; for (int i = 4; (y + i) < SCREEN_HEIGHT; i++) { v.fb32.plot(vec(x, y + i), CHARGE_COLOR); } break; case LLeft: x = SCREEN_WIDTH / 2 - stringWidth / 2; y = SCREEN_HEIGHT / 2; for (int i = 6; (x - i) >= 0; i++) { v.fb32.plot(vec(x - i, y), CHARGE_COLOR); } break; case LTop: x = SCREEN_WIDTH / 2; y = SCREEN_HEIGHT / 2 - stringHeight / 2; for (int i = 4; (y - i) >= 0; i++) { v.fb32.plot(vec(x, y - i), CHARGE_COLOR); } break; } } void ElementCube::DrawLewisDots(int stringWidth, int stringHeight) { //TODO: This is a bit of a hack. We need to properly set the outer electron count to 0 when the orbital is filled. if (currentElement.GetCharge() != 0 && currentElement.GetNumOuterElectrons() == 8) { return; } int numOuterElectrons = currentElement.GetNumOuterElectrons() - currentElement.GetSharedElectrons(); for (int s = LFirst; s <= LLast; s++) { // Calculate the number of electrons on this side int e = (numOuterElectrons + 3 - s) / 4; int x = SCREEN_WIDTH / 2; int y = SCREEN_HEIGHT / 2; // Calulate offset to get on the correct side: switch (s) { case LRight: x += stringWidth / 2 + 2; y += LETTER_DESCENDER_HEIGHT / 2; break; case LLeft: x -= stringWidth / 2 + 2; y += LETTER_DESCENDER_HEIGHT / 2; break; case LTop: x++; // Looks more natural one pixel to the right y -= stringHeight / 2 + 2; break; case LBottom: x++; // Looks more natural one pixel to the right y += stringHeight / 2 + 2; break; } // Calculate offset for electron separation: switch (s) { case LRight: case LLeft: y -= (e - 1) * 2; break; case LTop: case LBottom: x -= (e - 1) * 2; break; } // Draw the electrons: for ( ; e > 0; e--) { v.fb32.plot(vec(x, y), ELECTRON_COLOR); switch (s) { case LRight: case LLeft: y += 2; break; case LTop: case LBottom: x += 2; break; } } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Klarälvdalens Datakonsult AB (KDAB). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Compositor. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylanddatadevice_p.h" #include "qwaylanddatadevicemanager_p.h" #include "qwaylanddataoffer_p.h" #include "qwaylanddatasource_p.h" #include "qwaylanddnd_p.h" #include "qwaylandinputdevice_p.h" #include <QtCore/QMimeData> #include <QtGui/QGuiApplication> #include <QtGui/private/qguiapplication_p.h> #include <qpa/qplatformclipboard.h> #include <qpa/qplatformdrag.h> #include <qpa/qwindowsysteminterface.h> #include <QDebug> QWaylandDataDevice::QWaylandDataDevice(QWaylandDataDeviceManager *manager, QWaylandInputDevice *inputDevice) : QtWayland::wl_data_device(manager->get_data_device(inputDevice->wl_seat())) , m_display(manager->display()) , m_enterSerial(0) , m_dragWindow(0) , m_dragPoint() , m_dragOffer() , m_selectionOffer() { } QWaylandDataDevice::~QWaylandDataDevice() { } QWaylandDataOffer *QWaylandDataDevice::selectionOffer() const { return m_selectionOffer.data(); } QWaylandDataSource *QWaylandDataDevice::selectionSource() const { return m_selectionSource.data(); } void QWaylandDataDevice::setSelectionSource(QWaylandDataSource *source) { m_selectionSource.reset(source); set_selection(source ? source->object() : 0, 0 /* TODO m_display->serial() */); } QWaylandDataOffer *QWaylandDataDevice::dragOffer() const { return m_dragOffer.data(); } void QWaylandDataDevice::startDrag(QMimeData *mimeData, QWaylandWindow *icon) { m_dragSource.reset(new QWaylandDataSource(m_display->dndSelectionHandler(), mimeData)); QWaylandWindow *origin = m_display->currentInputDevice()->pointerFocus(); start_drag(m_dragSource->object(), origin->object(), icon->object(), m_display->currentInputDevice()->serial()); } void QWaylandDataDevice::cancelDrag() { m_dragSource.reset(); } void QWaylandDataDevice::data_device_data_offer(struct ::wl_data_offer *id) { new QWaylandDataOffer(m_display, id); } void QWaylandDataDevice::data_device_drop() { QDrag *drag = static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->currentDrag(); qDebug() << Q_FUNC_INFO << drag << m_dragOffer.data(); QMimeData *dragData; Qt::DropActions supportedActions; if (drag) { dragData = drag->mimeData(); supportedActions = drag->supportedActions(); } else if (m_dragOffer) { dragData = m_dragOffer->mimeData(); supportedActions = Qt::CopyAction | Qt::MoveAction | Qt::LinkAction; } else { return; } QPlatformDropQtResponse response = QWindowSystemInterface::handleDrop(m_dragWindow, dragData, m_dragPoint, supportedActions); if (drag) { static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->finishDrag(response); } } void QWaylandDataDevice::data_device_enter(uint32_t serial, wl_surface *surface, wl_fixed_t x, wl_fixed_t y, wl_data_offer *id) { m_enterSerial = serial; m_dragWindow = QWaylandWindow::fromWlSurface(surface)->window(); m_dragPoint = QPoint(wl_fixed_to_int(x), wl_fixed_to_int(y)); QDrag *drag = static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->currentDrag(); QMimeData *dragData; Qt::DropActions supportedActions; if (drag) { dragData = drag->mimeData(); supportedActions = drag->supportedActions(); } else { m_dragOffer.reset(static_cast<QWaylandDataOffer *>(wl_data_offer_get_user_data(id))); if (m_dragOffer) { dragData = m_dragOffer->mimeData(); supportedActions = Qt::CopyAction | Qt::MoveAction | Qt::LinkAction; } } const QPlatformDragQtResponse &response = QWindowSystemInterface::handleDrag(m_dragWindow, dragData, m_dragPoint, supportedActions); if (drag) { static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->setResponse(response); } else { if (response.isAccepted()) { wl_data_offer_accept(m_dragOffer->object(), m_enterSerial, m_dragOffer->firstFormat().toUtf8().constData()); } else { wl_data_offer_accept(m_dragOffer->object(), m_enterSerial, 0); } } } void QWaylandDataDevice::data_device_leave() { QWindowSystemInterface::handleDrag(m_dragWindow, 0, QPoint(), Qt::IgnoreAction); QDrag *drag = static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->currentDrag(); if (!drag) { m_dragOffer.reset(); } } void QWaylandDataDevice::data_device_motion(uint32_t time, wl_fixed_t x, wl_fixed_t y) { Q_UNUSED(time); QDrag *drag = static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->currentDrag(); if (!drag && !m_dragOffer) return; m_dragPoint = QPoint(wl_fixed_to_int(x), wl_fixed_to_int(y)); QMimeData *dragData; Qt::DropActions supportedActions; if (drag) { dragData = drag->mimeData(); supportedActions = drag->supportedActions(); } else { dragData = m_dragOffer->mimeData(); supportedActions = Qt::CopyAction | Qt::MoveAction | Qt::LinkAction; } QPlatformDragQtResponse response = QWindowSystemInterface::handleDrag(m_dragWindow, dragData, m_dragPoint, supportedActions); if (drag) { static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->setResponse(response); } else { if (response.isAccepted()) { wl_data_offer_accept(m_dragOffer->object(), m_enterSerial, m_dragOffer->firstFormat().toUtf8().constData()); } else { wl_data_offer_accept(m_dragOffer->object(), m_enterSerial, 0); } } } void QWaylandDataDevice::data_device_selection(wl_data_offer *id) { if (id) m_selectionOffer.reset(static_cast<QWaylandDataOffer *>(wl_data_offer_get_user_data(id))); else m_selectionOffer.reset(); QGuiApplicationPrivate::platformIntegration()->clipboard()->emitChanged(QClipboard::Clipboard); } void QWaylandDataDevice::selectionSourceCancelled() { m_selectionSource.reset(); QGuiApplicationPrivate::platformIntegration()->clipboard()->emitChanged(QClipboard::Clipboard); } void QWaylandDataDevice::dragSourceCancelled() { m_dragSource.reset(); } void QWaylandDataDevice::dragSourceTargetChanged(const QString &mimeType) { static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->updateTarget(mimeType); } <commit_msg>Discard the selection and drag source when not active anymore<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Klarälvdalens Datakonsult AB (KDAB). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Compositor. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylanddatadevice_p.h" #include "qwaylanddatadevicemanager_p.h" #include "qwaylanddataoffer_p.h" #include "qwaylanddatasource_p.h" #include "qwaylanddnd_p.h" #include "qwaylandinputdevice_p.h" #include <QtCore/QMimeData> #include <QtGui/QGuiApplication> #include <QtGui/private/qguiapplication_p.h> #include <qpa/qplatformclipboard.h> #include <qpa/qplatformdrag.h> #include <qpa/qwindowsysteminterface.h> #include <QDebug> QWaylandDataDevice::QWaylandDataDevice(QWaylandDataDeviceManager *manager, QWaylandInputDevice *inputDevice) : QtWayland::wl_data_device(manager->get_data_device(inputDevice->wl_seat())) , m_display(manager->display()) , m_enterSerial(0) , m_dragWindow(0) , m_dragPoint() , m_dragOffer() , m_selectionOffer() { } QWaylandDataDevice::~QWaylandDataDevice() { } QWaylandDataOffer *QWaylandDataDevice::selectionOffer() const { return m_selectionOffer.data(); } QWaylandDataSource *QWaylandDataDevice::selectionSource() const { return m_selectionSource.data(); } void QWaylandDataDevice::setSelectionSource(QWaylandDataSource *source) { m_selectionSource.reset(source); if (source) connect(source, &QWaylandDataSource::cancelled, this, &QWaylandDataDevice::selectionSourceCancelled); set_selection(source ? source->object() : 0, 0 /* TODO m_display->serial() */); } QWaylandDataOffer *QWaylandDataDevice::dragOffer() const { return m_dragOffer.data(); } void QWaylandDataDevice::startDrag(QMimeData *mimeData, QWaylandWindow *icon) { m_dragSource.reset(new QWaylandDataSource(m_display->dndSelectionHandler(), mimeData)); connect(m_dragSource.data(), &QWaylandDataSource::cancelled, this, &QWaylandDataDevice::dragSourceCancelled); QWaylandWindow *origin = m_display->currentInputDevice()->pointerFocus(); start_drag(m_dragSource->object(), origin->object(), icon->object(), m_display->currentInputDevice()->serial()); } void QWaylandDataDevice::cancelDrag() { m_dragSource.reset(); } void QWaylandDataDevice::data_device_data_offer(struct ::wl_data_offer *id) { new QWaylandDataOffer(m_display, id); } void QWaylandDataDevice::data_device_drop() { QDrag *drag = static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->currentDrag(); qDebug() << Q_FUNC_INFO << drag << m_dragOffer.data(); QMimeData *dragData; Qt::DropActions supportedActions; if (drag) { dragData = drag->mimeData(); supportedActions = drag->supportedActions(); } else if (m_dragOffer) { dragData = m_dragOffer->mimeData(); supportedActions = Qt::CopyAction | Qt::MoveAction | Qt::LinkAction; } else { return; } QPlatformDropQtResponse response = QWindowSystemInterface::handleDrop(m_dragWindow, dragData, m_dragPoint, supportedActions); if (drag) { static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->finishDrag(response); } } void QWaylandDataDevice::data_device_enter(uint32_t serial, wl_surface *surface, wl_fixed_t x, wl_fixed_t y, wl_data_offer *id) { m_enterSerial = serial; m_dragWindow = QWaylandWindow::fromWlSurface(surface)->window(); m_dragPoint = QPoint(wl_fixed_to_int(x), wl_fixed_to_int(y)); QDrag *drag = static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->currentDrag(); QMimeData *dragData; Qt::DropActions supportedActions; if (drag) { dragData = drag->mimeData(); supportedActions = drag->supportedActions(); } else { m_dragOffer.reset(static_cast<QWaylandDataOffer *>(wl_data_offer_get_user_data(id))); if (m_dragOffer) { dragData = m_dragOffer->mimeData(); supportedActions = Qt::CopyAction | Qt::MoveAction | Qt::LinkAction; } } const QPlatformDragQtResponse &response = QWindowSystemInterface::handleDrag(m_dragWindow, dragData, m_dragPoint, supportedActions); if (drag) { static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->setResponse(response); } else { if (response.isAccepted()) { wl_data_offer_accept(m_dragOffer->object(), m_enterSerial, m_dragOffer->firstFormat().toUtf8().constData()); } else { wl_data_offer_accept(m_dragOffer->object(), m_enterSerial, 0); } } } void QWaylandDataDevice::data_device_leave() { QWindowSystemInterface::handleDrag(m_dragWindow, 0, QPoint(), Qt::IgnoreAction); QDrag *drag = static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->currentDrag(); if (!drag) { m_dragOffer.reset(); } } void QWaylandDataDevice::data_device_motion(uint32_t time, wl_fixed_t x, wl_fixed_t y) { Q_UNUSED(time); QDrag *drag = static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->currentDrag(); if (!drag && !m_dragOffer) return; m_dragPoint = QPoint(wl_fixed_to_int(x), wl_fixed_to_int(y)); QMimeData *dragData; Qt::DropActions supportedActions; if (drag) { dragData = drag->mimeData(); supportedActions = drag->supportedActions(); } else { dragData = m_dragOffer->mimeData(); supportedActions = Qt::CopyAction | Qt::MoveAction | Qt::LinkAction; } QPlatformDragQtResponse response = QWindowSystemInterface::handleDrag(m_dragWindow, dragData, m_dragPoint, supportedActions); if (drag) { static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->setResponse(response); } else { if (response.isAccepted()) { wl_data_offer_accept(m_dragOffer->object(), m_enterSerial, m_dragOffer->firstFormat().toUtf8().constData()); } else { wl_data_offer_accept(m_dragOffer->object(), m_enterSerial, 0); } } } void QWaylandDataDevice::data_device_selection(wl_data_offer *id) { if (id) m_selectionOffer.reset(static_cast<QWaylandDataOffer *>(wl_data_offer_get_user_data(id))); else m_selectionOffer.reset(); QGuiApplicationPrivate::platformIntegration()->clipboard()->emitChanged(QClipboard::Clipboard); } void QWaylandDataDevice::selectionSourceCancelled() { m_selectionSource.reset(); QGuiApplicationPrivate::platformIntegration()->clipboard()->emitChanged(QClipboard::Clipboard); } void QWaylandDataDevice::dragSourceCancelled() { m_dragSource.reset(); } void QWaylandDataDevice::dragSourceTargetChanged(const QString &mimeType) { static_cast<QWaylandDrag *>(QGuiApplicationPrivate::platformIntegration()->drag())->updateTarget(mimeType); } <|endoftext|>
<commit_before>#include "GameEngine.h" #include "entity/Fire.h" #include "entity/Character.h" #include "entity/Bomb.h" #include <cassert> namespace common { GameEngine::GameEngine() : QObject(), net::GameEventVisitor(), max_duration_(10 * 60 * 1000), // 10 minutes players_(), world_(new World(79, 49)), game_timer_(), new_frame_timer_(new QTimer()), is_running_(false) { } GameEngine::~GameEngine() { new_frame_timer_->stop(); disconnect(new_frame_timer_.get(), 0, 0, 0); } void GameEngine::AddPlayer(std::unique_ptr<Player> player) { players_.push_back(std::move(player)); world_->AddCharacter(std::unique_ptr<entity::Character>()); } void GameEngine::StartGame() { assert(!is_running_); if (is_running_) { return; } is_running_ = true; game_timer_.StartGame(); connect(new_frame_timer_.get(), SIGNAL(timeout()), this, SLOT(Update(50))); new_frame_timer_->start(50); } bool GameEngine::AddEntity(std::unique_ptr<entity::Entity> e) { if ( !world_->CheckCoord(e->GetPosition()) ) { return false; } if ( e->IsSolid() && !world_->IsWalkable(e->GetPosition())) { return false; } return world_->AddItem(std::move(e)); } World* GameEngine::GetWorld() const { return world_.get(); } quint32 GameEngine::GetTimestamp() const { return game_timer_.GetTimestamp(); } bool GameEngine::AddFire(QPoint a) { // TODO : call the method IsTouchByFire on the case entities. if (world_->StopsFire(a)) { return false; } else { quint32 currentTime = GetTimestamp(); AddEntity(std::unique_ptr<entity::Fire>(new entity::Fire(a, currentTime))); return true; } } void GameEngine::AddFireFromAtoB(QPoint a, QPoint b) { assert(a.x() == b.x() || a.y() == b.y()); if (a.x() == b.x()) { if (a.y() <= b.y()) { for (int y = a.y(); y <= b.y(); y++) { if (!AddFire(QPoint(a.x(), y))) { return; } } } else { for (int y = a.y(); y >= b.y(); y--) { if (!AddFire(QPoint(a.x(), y))) { return; } } } } else if (a.y() == b.y()) { if (a.x() <= b.x()) { for (int x = a.x(); x <= b.x(); x++) { if (!AddFire(QPoint(x, a.y()))) { return; } } } else { for (int x = a.x(); x >= b.x(); x--) { if (!AddFire(QPoint(x, a.y()))) { return; } } } } else { // TODO : log error } } void GameEngine::Update(int t) { // t in ms. t is the duration of the frame ChallengeStrategies(); Simulate(t); SendGameState(); } void GameEngine::ChallengeStrategies() { for (auto player_it = players_.begin(); player_it != players_.end(); ++player_it) { /*for (auto e : player_it->get()->GetStrategy()->GetPendingEvents()) { e.Accept(this); }*/ } } void GameEngine::Simulate(int t) { // t in ms. t is the duration of the frame for (auto it = world_->CharacterIteratorBegin() ; it != world_->CharacterIteratorEnd() ; ++it) { it->get()->Update(this, t); } for (int x = 0; x < world_->GetWidth() ; x++) { for (int y = 0; y < world_->GetHeight() ; y++) { QPoint a(x, y); for (auto it = world_->IteratorAtBegin(a) ; it != world_->IteratorAtEnd(a) ; ++it) { it->get()->Update(this, t); } } } // TODO : handle fire world_->removeEntities(); // Removes entities that should be removed } void GameEngine::SendGameState() { // TODO } void GameEngine::Visit(net::MoveEvent& event) { // TODO : Check if value is ok MoveCharacter(event.GetId(), event.GetDestination()); } void GameEngine::Visit(net::BombEvent& event) { int id = event.GetId(); // TODO : Check if value is ok QPoint position(event.GetPosition()); quint32 current_time = game_timer_.GetTimestamp(); quint32 explosion_time = current_time + 2500; // TODO : move this value int power = GetWorld()->GetCharacter(id)->GetPower(); // TODO : checks if the character is near position AddEntity(std::unique_ptr<entity::Bomb>(new entity::Bomb(position, current_time, explosion_time, power))); } void GameEngine::Visit(net::PlayerLeftEvent& event) { (void) event; // TODO } void GameEngine::MoveCharacter(int player_id, QPoint target) { if (world_->IsWalkable(target)) { entity::Character* character = GetWorld()->GetCharacter(player_id); if (character) { character->MoveTo(this, target); } else { // TODO: add warning message. } } } } <commit_msg>Correct Visit methods.<commit_after>#include "GameEngine.h" #include "entity/Fire.h" #include "entity/Character.h" #include "entity/Bomb.h" #include <cassert> namespace common { GameEngine::GameEngine() : QObject(), net::GameEventVisitor(), max_duration_(10 * 60 * 1000), // 10 minutes players_(), world_(new World(79, 49)), game_timer_(), new_frame_timer_(new QTimer()), is_running_(false) { } GameEngine::~GameEngine() { new_frame_timer_->stop(); disconnect(new_frame_timer_.get(), 0, 0, 0); } void GameEngine::AddPlayer(std::unique_ptr<Player> player) { players_.push_back(std::move(player)); world_->AddCharacter(std::unique_ptr<entity::Character>()); } void GameEngine::StartGame() { assert(!is_running_); if (is_running_) { return; } is_running_ = true; game_timer_.StartGame(); connect(new_frame_timer_.get(), SIGNAL(timeout()), this, SLOT(Update(50))); new_frame_timer_->start(50); } bool GameEngine::AddEntity(std::unique_ptr<entity::Entity> e) { if ( !world_->CheckCoord(e->GetPosition()) ) { return false; } if ( e->IsSolid() && !world_->IsWalkable(e->GetPosition())) { return false; } return world_->AddItem(std::move(e)); } World* GameEngine::GetWorld() const { return world_.get(); } quint32 GameEngine::GetTimestamp() const { return game_timer_.GetTimestamp(); } bool GameEngine::AddFire(QPoint a) { // TODO : call the method IsTouchByFire on the case entities. if (world_->StopsFire(a)) { return false; } else { quint32 currentTime = GetTimestamp(); AddEntity(std::unique_ptr<entity::Fire>(new entity::Fire(a, currentTime))); return true; } } void GameEngine::AddFireFromAtoB(QPoint a, QPoint b) { assert(a.x() == b.x() || a.y() == b.y()); if (a.x() == b.x()) { if (a.y() <= b.y()) { for (int y = a.y(); y <= b.y(); y++) { if (!AddFire(QPoint(a.x(), y))) { return; } } } else { for (int y = a.y(); y >= b.y(); y--) { if (!AddFire(QPoint(a.x(), y))) { return; } } } } else if (a.y() == b.y()) { if (a.x() <= b.x()) { for (int x = a.x(); x <= b.x(); x++) { if (!AddFire(QPoint(x, a.y()))) { return; } } } else { for (int x = a.x(); x >= b.x(); x--) { if (!AddFire(QPoint(x, a.y()))) { return; } } } } else { // TODO : log error } } void GameEngine::Update(int t) { // t in ms. t is the duration of the frame ChallengeStrategies(); Simulate(t); SendGameState(); } void GameEngine::ChallengeStrategies() { for (auto player_it = players_.begin(); player_it != players_.end(); ++player_it) { /*for (auto e : player_it->get()->GetStrategy()->GetPendingEvents()) { e.Accept(this); }*/ } } void GameEngine::Simulate(int t) { // t in ms. t is the duration of the frame for (auto it = world_->CharacterIteratorBegin() ; it != world_->CharacterIteratorEnd() ; ++it) { it->get()->Update(this, t); } for (int x = 0; x < world_->GetWidth() ; x++) { for (int y = 0; y < world_->GetHeight() ; y++) { QPoint a(x, y); for (auto it = world_->IteratorAtBegin(a) ; it != world_->IteratorAtEnd(a) ; ++it) { it->get()->Update(this, t); } } } // TODO : handle fire world_->removeEntities(); // Removes entities that should be removed } void GameEngine::SendGameState() { // TODO } void GameEngine::Visit(net::MoveEvent& event) { // TODO : Check if value is ok MoveCharacter(event.GetCharacterId(), event.GetDestination()); } void GameEngine::Visit(net::BombEvent& event) { int id = event.GetCharacterId(); // TODO : Check if value is ok QPoint position(event.GetPosition()); quint32 current_time = game_timer_.GetTimestamp(); quint32 explosion_time = current_time + 2500; // TODO : move this value int power = GetWorld()->GetCharacter(id)->GetPower(); // TODO : checks if the character is near position AddEntity(std::unique_ptr<entity::Bomb>(new entity::Bomb(position, current_time, explosion_time, power))); } void GameEngine::Visit(net::PlayerLeftEvent& event) { (void) event; // TODO } void GameEngine::MoveCharacter(int player_id, QPoint target) { if (world_->IsWalkable(target)) { entity::Character* character = GetWorld()->GetCharacter(player_id); if (character) { character->MoveTo(this, target); } else { // TODO: add warning message. } } } } <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2004-2005 by Allan Sandfeld Jensen email : kde@carewolf.org ***************************************************************************/ /*************************************************************************** * 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 * ***************************************************************************/ #include <tbytevector.h> #include <tstring.h> #include <tdebug.h> #include <xiphcomment.h> #include "oggflacfile.h" using namespace TagLib; using TagLib::FLAC::Properties; class Ogg::FLAC::File::FilePrivate { public: FilePrivate() : comment(0), properties(0), streamStart(0), streamLength(0), scanned(false), hasXiphComment(false), commentPacket(0) {} ~FilePrivate() { delete comment; delete properties; } Ogg::XiphComment *comment; Properties *properties; ByteVector streamInfoData; ByteVector xiphCommentData; long streamStart; long streamLength; bool scanned; bool hasXiphComment; int commentPacket; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// Ogg::FLAC::File::File(const char *file, bool readProperties, Properties::ReadStyle propertiesStyle) : Ogg::File(file) { d = new FilePrivate; read(readProperties, propertiesStyle); } Ogg::FLAC::File::~File() { delete d; } Ogg::XiphComment *Ogg::FLAC::File::tag() const { return d->comment; } Properties *Ogg::FLAC::File::audioProperties() const { return d->properties; } bool Ogg::FLAC::File::save() { d->xiphCommentData = d->comment->render(); // Create FLAC metadata-block: // Put the size in the first 32 bit (I assume no more than 24 bit are used) ByteVector v = ByteVector::fromUInt(d->xiphCommentData.size()); // Set the type of the metadata-block to be a Xiph / Vorbis comment v[0] = 4; // Append the comment-data after the 32 bit header v.append(d->xiphCommentData); // Save the packet at the old spot // FIXME: Use padding if size is increasing setPacket(d->commentPacket, v); return Ogg::File::save(); } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void Ogg::FLAC::File::read(bool readProperties, Properties::ReadStyle propertiesStyle) { // Sanity: Check if we really have an Ogg/FLAC file /* ByteVector oggHeader = packet(0); if (oggHeader.mid(28,4) != "fLaC") { debug("Ogg::FLAC::File::read() -- Not an Ogg/FLAC file"); setValid(false); return; }*/ // Look for FLAC metadata, including vorbis comments scan(); if (!d->scanned) { setValid(false); return; } if(d->hasXiphComment) d->comment = new Ogg::XiphComment(xiphCommentData()); else d->comment = new Ogg::XiphComment; if(readProperties) d->properties = new Properties(streamInfoData(), streamLength(), propertiesStyle); } ByteVector Ogg::FLAC::File::streamInfoData() { scan(); return d->streamInfoData; } ByteVector Ogg::FLAC::File::xiphCommentData() { scan(); return d->xiphCommentData; } long Ogg::FLAC::File::streamLength() { scan(); return d->streamLength; } void Ogg::FLAC::File::scan() { // Scan the metadata pages if(d->scanned) return; if(!isValid()) return; int ipacket = 0; long overhead = 0; ByteVector metadataHeader = packet(ipacket++); if(metadataHeader.isNull()) return; ByteVector header; if (!metadataHeader.startsWith("fLaC")) { // FLAC 1.1.2+ if (metadataHeader.mid(1,4) != "FLAC") return; if (metadataHeader[5] != 1) return; // not version 1 metadataHeader = metadataHeader.mid(13); } else { // FLAC 1.1.0 & 1.1.1 metadataHeader = packet(ipacket++); if(metadataHeader.isNull()) return; } header = metadataHeader.mid(0,4); // Header format (from spec): // <1> Last-metadata-block flag // <7> BLOCK_TYPE // 0 : STREAMINFO // 1 : PADDING // .. // 4 : VORBIS_COMMENT // .. // <24> Length of metadata to follow char blockType = header[0] & 0x7f; bool lastBlock = header[0] & 0x80; uint length = header.mid(1, 3).toUInt(); overhead += length; // Sanity: First block should be the stream_info metadata if(blockType != 0) { debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC stream"); return; } d->streamInfoData = metadataHeader.mid(4,length); // Search through the remaining metadata while(!lastBlock) { metadataHeader = packet(ipacket++); if(metadataHeader.isNull()) return; header = metadataHeader.mid(0, 4); blockType = header[0] & 0x7f; lastBlock = header[0] & 0x80; length = header.mid(1, 3).toUInt(); overhead += length; if(blockType == 1) { // debug("Ogg::FLAC::File::scan() -- Padding found"); } else if(blockType == 4) { // debug("Ogg::FLAC::File::scan() -- Vorbis-comments found"); d->xiphCommentData = metadataHeader.mid(4, length); d->hasXiphComment = true; d->commentPacket = ipacket; } else if(blockType > 5) debug("Ogg::FLAC::File::scan() -- Unknown metadata block"); } // End of metadata, now comes the datastream d->streamStart = overhead; d->streamLength = File::length() - d->streamStart; d->scanned = true; } <commit_msg>Allan's commit was in the wrong branch -- don't corrupt files on write...<commit_after>/*************************************************************************** copyright : (C) 2004-2005 by Allan Sandfeld Jensen email : kde@carewolf.org ***************************************************************************/ /*************************************************************************** * 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 * ***************************************************************************/ #include <tbytevector.h> #include <tstring.h> #include <tdebug.h> #include <xiphcomment.h> #include "oggflacfile.h" using namespace TagLib; using TagLib::FLAC::Properties; class Ogg::FLAC::File::FilePrivate { public: FilePrivate() : comment(0), properties(0), streamStart(0), streamLength(0), scanned(false), hasXiphComment(false), commentPacket(0) {} ~FilePrivate() { delete comment; delete properties; } Ogg::XiphComment *comment; Properties *properties; ByteVector streamInfoData; ByteVector xiphCommentData; long streamStart; long streamLength; bool scanned; bool hasXiphComment; int commentPacket; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// Ogg::FLAC::File::File(const char *file, bool readProperties, Properties::ReadStyle propertiesStyle) : Ogg::File(file) { d = new FilePrivate; read(readProperties, propertiesStyle); } Ogg::FLAC::File::~File() { delete d; } Ogg::XiphComment *Ogg::FLAC::File::tag() const { return d->comment; } Properties *Ogg::FLAC::File::audioProperties() const { return d->properties; } bool Ogg::FLAC::File::save() { d->xiphCommentData = d->comment->render(); // Create FLAC metadata-block: // Put the size in the first 32 bit (I assume no more than 24 bit are used) ByteVector v = ByteVector::fromUInt(d->xiphCommentData.size()); // Set the type of the metadata-block to be a Xiph / Vorbis comment v[0] = 4; // Append the comment-data after the 32 bit header v.append(d->xiphCommentData); // Save the packet at the old spot // FIXME: Use padding if size is increasing setPacket(d->commentPacket, v); return Ogg::File::save(); } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void Ogg::FLAC::File::read(bool readProperties, Properties::ReadStyle propertiesStyle) { // Sanity: Check if we really have an Ogg/FLAC file /* ByteVector oggHeader = packet(0); if (oggHeader.mid(28,4) != "fLaC") { debug("Ogg::FLAC::File::read() -- Not an Ogg/FLAC file"); setValid(false); return; }*/ // Look for FLAC metadata, including vorbis comments scan(); if (!d->scanned) { setValid(false); return; } if(d->hasXiphComment) d->comment = new Ogg::XiphComment(xiphCommentData()); else d->comment = new Ogg::XiphComment; if(readProperties) d->properties = new Properties(streamInfoData(), streamLength(), propertiesStyle); } ByteVector Ogg::FLAC::File::streamInfoData() { scan(); return d->streamInfoData; } ByteVector Ogg::FLAC::File::xiphCommentData() { scan(); return d->xiphCommentData; } long Ogg::FLAC::File::streamLength() { scan(); return d->streamLength; } void Ogg::FLAC::File::scan() { // Scan the metadata pages if(d->scanned) return; if(!isValid()) return; int ipacket = 0; long overhead = 0; ByteVector metadataHeader = packet(ipacket); if(metadataHeader.isNull()) return; ByteVector header; if (!metadataHeader.startsWith("fLaC")) { // FLAC 1.1.2+ if (metadataHeader.mid(1,4) != "FLAC") return; if (metadataHeader[5] != 1) return; // not version 1 metadataHeader = metadataHeader.mid(13); } else { // FLAC 1.1.0 & 1.1.1 metadataHeader = packet(++ipacket); if(metadataHeader.isNull()) return; } header = metadataHeader.mid(0,4); // Header format (from spec): // <1> Last-metadata-block flag // <7> BLOCK_TYPE // 0 : STREAMINFO // 1 : PADDING // .. // 4 : VORBIS_COMMENT // .. // <24> Length of metadata to follow char blockType = header[0] & 0x7f; bool lastBlock = header[0] & 0x80; uint length = header.mid(1, 3).toUInt(); overhead += length; // Sanity: First block should be the stream_info metadata if(blockType != 0) { debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC stream"); return; } d->streamInfoData = metadataHeader.mid(4,length); // Search through the remaining metadata while(!lastBlock) { metadataHeader = packet(++ipacket); if(metadataHeader.isNull()) return; header = metadataHeader.mid(0, 4); blockType = header[0] & 0x7f; lastBlock = header[0] & 0x80; length = header.mid(1, 3).toUInt(); overhead += length; if(blockType == 1) { // debug("Ogg::FLAC::File::scan() -- Padding found"); } else if(blockType == 4) { // debug("Ogg::FLAC::File::scan() -- Vorbis-comments found"); d->xiphCommentData = metadataHeader.mid(4, length); d->hasXiphComment = true; d->commentPacket = ipacket; } else if(blockType > 5) debug("Ogg::FLAC::File::scan() -- Unknown metadata block"); } // End of metadata, now comes the datastream d->streamStart = overhead; d->streamLength = File::length() - d->streamStart; d->scanned = true; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formlayerexport.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:15:36 $ * * 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_xmloff.hxx" #include <stdio.h> #ifndef _XMLOFF_FORMLAYEREXPORT_HXX_ #include <xmloff/formlayerexport.hxx> #endif #ifndef _XMLOFF_FORMS_STRINGS_HXX_ #include "strings.hxx" #endif #ifndef _XMLOFF_ELEMENTEXPORT_HXX_ #include "elementexport.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_FORMS_LAYEREXPORT_HXX_ #include "layerexport.hxx" #endif #ifndef _XMLOFF_FORMS_PROPERTYEXPORT_HXX_ #include "propertyexport.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _XMLOFF_FORMS_OFFICEFORMS_HXX_ #include "officeforms.hxx" #endif //......................................................................... namespace xmloff { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::frame; //===================================================================== //= OFormLayerXMLExport //===================================================================== //--------------------------------------------------------------------- OFormLayerXMLExport::OFormLayerXMLExport(SvXMLExport& _rContext) :m_rContext(_rContext) ,m_pImpl(new OFormLayerXMLExport_Impl(_rContext)) { } //--------------------------------------------------------------------- OFormLayerXMLExport::~OFormLayerXMLExport() { delete m_pImpl; m_pImpl = NULL; } //--------------------------------------------------------------------- sal_Bool OFormLayerXMLExport::seekPage(const Reference< XDrawPage >& _rxDrawPage) { return m_pImpl->seekPage(_rxDrawPage); } //--------------------------------------------------------------------- ::rtl::OUString OFormLayerXMLExport::getControlId(const Reference< XPropertySet >& _rxControl) { return m_pImpl->getControlId(_rxControl); } //--------------------------------------------------------------------- ::rtl::OUString OFormLayerXMLExport::getControlNumberStyle( const Reference< XPropertySet >& _rxControl ) { return m_pImpl->getControlNumberStyle(_rxControl); } //--------------------------------------------------------------------- ::vos::ORef< SvXMLExportPropertyMapper > OFormLayerXMLExport::getStylePropertyMapper() { return m_pImpl->getStylePropertyMapper(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::initialize() { m_pImpl->clear(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::examineForms(const Reference< XDrawPage >& _rxDrawPage) { try { m_pImpl->examineForms(_rxDrawPage); } catch(Exception&) { OSL_ENSURE(sal_False, "OFormLayerXMLExport::examine: could not examine the draw page!"); } } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportForms(const Reference< XDrawPage >& _rxDrawPage) { m_pImpl->exportForms(_rxDrawPage); } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportXForms() const { m_pImpl->exportXForms(); } //--------------------------------------------------------------------- bool OFormLayerXMLExport::pageContainsForms( const Reference< XDrawPage >& _rxDrawPage ) const { return m_pImpl->pageContainsForms( _rxDrawPage ); } //--------------------------------------------------------------------- bool OFormLayerXMLExport::documentContainsXForms() const { return m_pImpl->documentContainsXForms(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportControlNumberStyles() { m_pImpl->exportControlNumberStyles(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportAutoControlNumberStyles() { m_pImpl->exportAutoControlNumberStyles(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportAutoStyles() { m_pImpl->exportAutoStyles(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::excludeFromExport( const Reference< XControlModel > _rxControl ) { m_pImpl->excludeFromExport( _rxControl ); } //========================================================================= //= OOfficeFormsExport //========================================================================= //------------------------------------------------------------------------- OOfficeFormsExport::OOfficeFormsExport( SvXMLExport& _rExp ) :m_pImpl(NULL) { m_pImpl = new OFormsRootExport(_rExp); } //------------------------------------------------------------------------- OOfficeFormsExport::~OOfficeFormsExport() { delete m_pImpl; } //......................................................................... } // namespace xmloff //......................................................................... <commit_msg>INTEGRATION: CWS changefileheader (1.18.162); FILE MERGED 2008/04/01 16:09:47 thb 1.18.162.3: #i85898# Stripping all external header guards 2008/04/01 13:04:50 thb 1.18.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:12 rt 1.18.162.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formlayerexport.cxx,v $ * $Revision: 1.19 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include <stdio.h> #include <xmloff/formlayerexport.hxx> #include "strings.hxx" #include "elementexport.hxx" #include "xmlnmspe.hxx" #include <xmloff/xmlexp.hxx> #include "layerexport.hxx" #include "propertyexport.hxx" #include <osl/diagnose.h> #include <comphelper/extract.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> #include <comphelper/stl_types.hxx> #include "officeforms.hxx" //......................................................................... namespace xmloff { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::frame; //===================================================================== //= OFormLayerXMLExport //===================================================================== //--------------------------------------------------------------------- OFormLayerXMLExport::OFormLayerXMLExport(SvXMLExport& _rContext) :m_rContext(_rContext) ,m_pImpl(new OFormLayerXMLExport_Impl(_rContext)) { } //--------------------------------------------------------------------- OFormLayerXMLExport::~OFormLayerXMLExport() { delete m_pImpl; m_pImpl = NULL; } //--------------------------------------------------------------------- sal_Bool OFormLayerXMLExport::seekPage(const Reference< XDrawPage >& _rxDrawPage) { return m_pImpl->seekPage(_rxDrawPage); } //--------------------------------------------------------------------- ::rtl::OUString OFormLayerXMLExport::getControlId(const Reference< XPropertySet >& _rxControl) { return m_pImpl->getControlId(_rxControl); } //--------------------------------------------------------------------- ::rtl::OUString OFormLayerXMLExport::getControlNumberStyle( const Reference< XPropertySet >& _rxControl ) { return m_pImpl->getControlNumberStyle(_rxControl); } //--------------------------------------------------------------------- ::vos::ORef< SvXMLExportPropertyMapper > OFormLayerXMLExport::getStylePropertyMapper() { return m_pImpl->getStylePropertyMapper(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::initialize() { m_pImpl->clear(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::examineForms(const Reference< XDrawPage >& _rxDrawPage) { try { m_pImpl->examineForms(_rxDrawPage); } catch(Exception&) { OSL_ENSURE(sal_False, "OFormLayerXMLExport::examine: could not examine the draw page!"); } } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportForms(const Reference< XDrawPage >& _rxDrawPage) { m_pImpl->exportForms(_rxDrawPage); } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportXForms() const { m_pImpl->exportXForms(); } //--------------------------------------------------------------------- bool OFormLayerXMLExport::pageContainsForms( const Reference< XDrawPage >& _rxDrawPage ) const { return m_pImpl->pageContainsForms( _rxDrawPage ); } //--------------------------------------------------------------------- bool OFormLayerXMLExport::documentContainsXForms() const { return m_pImpl->documentContainsXForms(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportControlNumberStyles() { m_pImpl->exportControlNumberStyles(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportAutoControlNumberStyles() { m_pImpl->exportAutoControlNumberStyles(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::exportAutoStyles() { m_pImpl->exportAutoStyles(); } //--------------------------------------------------------------------- void OFormLayerXMLExport::excludeFromExport( const Reference< XControlModel > _rxControl ) { m_pImpl->excludeFromExport( _rxControl ); } //========================================================================= //= OOfficeFormsExport //========================================================================= //------------------------------------------------------------------------- OOfficeFormsExport::OOfficeFormsExport( SvXMLExport& _rExp ) :m_pImpl(NULL) { m_pImpl = new OFormsRootExport(_rExp); } //------------------------------------------------------------------------- OOfficeFormsExport::~OOfficeFormsExport() { delete m_pImpl; } //......................................................................... } // namespace xmloff //......................................................................... <|endoftext|>
<commit_before>/* Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com> 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 <QObject> #include "CTelegramStream.hpp" #include <QBuffer> #include <QTest> #include <QDebug> struct STestData { QVariant value; QByteArray expected; STestData(QVariant v, QByteArray e) : value(v), expected(e) { } }; class tst_CTelegramStream : public QObject { Q_OBJECT public: explicit tst_CTelegramStream(QObject *parent = 0); private slots: void writeStringTestLimit(); void writeShortString(); void writeLongString(); void writeInt(); }; tst_CTelegramStream::tst_CTelegramStream(QObject *parent) : QObject(parent) { } void tst_CTelegramStream::writeShortString() { QList<STestData> data; const char testExpectedChars1[8] = { char(4), 't', 'e', 's', 't', 0, 0, 0 }; const char testExpectedChars2[8] = { char(5), 't', 'e', 's', 't', '5', 0, 0 }; const char testExpectedChars3[8] = { char(6), 't', 'e', 's', 't', '6', '6', 0 }; const char testExpectedChars4[8] = { char(7), '7', 's', 'e', 'v', 'e', 'n', '7' }; data.append(STestData(QLatin1String("test"), QByteArray(testExpectedChars1, sizeof(testExpectedChars1)))); data.append(STestData(QLatin1String("test5"), QByteArray(testExpectedChars2, sizeof(testExpectedChars2)))); data.append(STestData(QLatin1String("test66"), QByteArray(testExpectedChars3, sizeof(testExpectedChars3)))); data.append(STestData(QLatin1String("7seven7"), QByteArray(testExpectedChars4, sizeof(testExpectedChars4)))); for (int i = 0; i < data.count(); ++i) { QBuffer device; device.open(QBuffer::ReadWrite); CTelegramStream stream(&device); stream << data.at(i).value.toString(); QCOMPARE(device.data(), data.at(i).expected); } } void tst_CTelegramStream::writeStringTestLimit() { QList<STestData> data; QString stringToTest; QByteArray expected; for (int i = 0; i < 5; ++i) { stringToTest = QString(i, QChar('a')); expected = QByteArray(i, char('a')); expected.prepend(char(i)); if (expected.length() % 4) expected.append(QByteArray(4 - expected.length() % 4, char(0))); data.append(STestData(stringToTest, expected)); } stringToTest = QString(253, QChar::fromLatin1(char(0x70))); expected = QByteArray(253, char(0x70)); expected.prepend(char(253)); expected.append(char(0)); expected.append(char(0)); data.append(STestData(stringToTest, expected)); stringToTest = QString(254, QChar::fromLatin1(char(0x71))); expected = QByteArray(254, char(0x71)); expected.prepend(char(0)); // LengthBig expected.prepend(char(0)); // LengthMiddle expected.prepend(char(254)); // LengthLittle expected.prepend(char(254)); // Long-string marker expected.append(char(0)); // Padding1 expected.append(char(0)); // Padding2 data.append(STestData(stringToTest, expected)); for (int i = 0; i < data.count(); ++i) { QBuffer device; device.open(QBuffer::ReadWrite); CTelegramStream stream(&device); stream << data.at(i).value.toString(); if ((data.at(i).expected.length() > 10) && (device.data() != data.at(i).expected)) { qDebug() << QString("Actual (%1 bytes):").arg(device.data().length()) << device.data().toHex(); qDebug() << QString("Expected (%1 bytes):").arg(data.at(i).expected.length()) << data.at(i).expected.toHex(); } QCOMPARE(device.data(), data.at(i).expected); } } void tst_CTelegramStream::writeLongString() { QList<STestData> data; QString stringToTest1 = QLatin1String("Some really pretty long string to be serialized. " "Start to speek something wise and sage. Abadfa dfa uzxcviuwekrhalflkjhzvzxciuvyoiuwehrkblabla-asdfasdf" "qwrq25!@!@(#*&!$@%@!()#*&@#($)&*)(!@*&#)(!*@&#()!@*&$%!*@&$&^!%$&*#@%$&*%^@#$&%@#$@#*$&^@#*(&^@#%*&^!F" "132465798+760++-*/*/651321///???asd0f98`0978jhkjhzxcv....end"); // Lenght: 313 const int len = 313; QByteArray expected1(1, char(0xfe)); expected1.append(char(len & 0xff)); expected1.append(char((len & 0xff00) >> 8)); expected1.append(char((len & 0xff0000) >> 16)); expected1.append(stringToTest1.toUtf8()); int extraNulls = 4 - (len & 3); for (int i = 0; i < extraNulls; ++i) expected1.append(char(0)); data.append(STestData(stringToTest1, expected1)); for (int i = 0; i < data.count(); ++i) { QBuffer device; device.open(QBuffer::ReadWrite); CTelegramStream stream(&device); stream << data.at(i).value.toString(); QVERIFY2(!(device.data().length() % 4), "Results buffer is not padded (total length is not divisible by 4)"); QVERIFY2((device.data().length() >= len + 4), "Results buffer size for long string should be at least stringLength + 4"); QVERIFY2((device.data().length() <= len + 4 + 3), "Results buffer size for long string should never be more, than stringLength + 4 + 3"); QCOMPARE(device.data(), data.at(i).expected); } } void tst_CTelegramStream::writeInt() { QList<STestData> data; { QByteArray testExpected; quint32 values[5] = { 0x01, 0xff, 0x00, 0xaabbcc, 0xdeadbeef }; const char expected1[4] = { char(values[0]), 0, 0, 0 }; const char expected2[4] = { char(values[1]), 0, 0, 0 }; const char expected3[4] = { char(values[2]), 0, 0, 0 }; const char expected4[4] = { char(0xcc), char(0xbb), char(0xaa), char(0x00) }; const char expected5[4] = { char(0xef), char(0xbe), char(0xad), char(0xde) }; testExpected.append(expected1, 4); testExpected.append(expected2, 4); testExpected.append(expected3, 4); testExpected.append(expected4, 4); testExpected.append(expected5, 5); for (int i = 0; i < 5; ++i) data.append(STestData(values[i], testExpected.mid(i * 4, 4))); } for (int i = 0; i < data.count(); ++i) { QBuffer device; device.open(QBuffer::ReadWrite); CTelegramStream stream(&device); stream << data.at(i).value.value<quint32>(); QCOMPARE(device.data(), data.at(i).expected); } } QTEST_MAIN(tst_CTelegramStream) #include "tst_CTelegramStream.moc" <commit_msg>tests/stream: Refactored.<commit_after>/* Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com> 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 <QObject> #include "CTelegramStream.hpp" #include <QBuffer> #include <QTest> #include <QDebug> struct STestData { QVariant value; QByteArray serializedValue; STestData(QVariant v, QByteArray e) : value(v), serializedValue(e) { } }; class tst_CTelegramStream : public QObject { Q_OBJECT public: explicit tst_CTelegramStream(QObject *parent = 0); private slots: void writeStringTestLimit(); void writeShortString(); void writeLongString(); void writeInt(); }; tst_CTelegramStream::tst_CTelegramStream(QObject *parent) : QObject(parent) { } void tst_CTelegramStream::writeShortString() { QList<STestData> data; const char serializedChars1[8] = { char(4), 't', 'e', 's', 't', 0, 0, 0 }; const char serializedChars2[8] = { char(5), 't', 'e', 's', 't', '5', 0, 0 }; const char serializedChars3[8] = { char(6), 't', 'e', 's', 't', '6', '6', 0 }; const char serializedChars4[8] = { char(7), '7', 's', 'e', 'v', 'e', 'n', '7' }; data.append(STestData(QLatin1String("test"), QByteArray(serializedChars1, sizeof(serializedChars1)))); data.append(STestData(QLatin1String("test5"), QByteArray(serializedChars2, sizeof(serializedChars2)))); data.append(STestData(QLatin1String("test66"), QByteArray(serializedChars3, sizeof(serializedChars3)))); data.append(STestData(QLatin1String("7seven7"), QByteArray(serializedChars4, sizeof(serializedChars4)))); for (int i = 0; i < data.count(); ++i) { QBuffer device; device.open(QBuffer::ReadWrite); CTelegramStream stream(&device); stream << data.at(i).value.toString(); QCOMPARE(device.data(), data.at(i).serializedValue); } } void tst_CTelegramStream::writeStringTestLimit() { QList<STestData> data; QString stringToTest; QByteArray serializedString; for (int i = 0; i < 5; ++i) { stringToTest = QString(i, QChar('a')); serializedString = QByteArray(i, char('a')); serializedString.prepend(char(i)); if (serializedString.length() % 4) serializedString.append(QByteArray(4 - serializedString.length() % 4, char(0))); data.append(STestData(stringToTest, serializedString)); } stringToTest = QString(253, QChar::fromLatin1(char(0x70))); serializedString = QByteArray(253, char(0x70)); serializedString.prepend(char(253)); serializedString.append(char(0)); serializedString.append(char(0)); data.append(STestData(stringToTest, serializedString)); stringToTest = QString(254, QChar::fromLatin1(char(0x71))); serializedString = QByteArray(254, char(0x71)); serializedString.prepend(char(0)); // LengthBig serializedString.prepend(char(0)); // LengthMiddle serializedString.prepend(char(254)); // LengthLittle serializedString.prepend(char(254)); // Long-string marker serializedString.append(char(0)); // Padding1 serializedString.append(char(0)); // Padding2 data.append(STestData(stringToTest, serializedString)); for (int i = 0; i < data.count(); ++i) { QBuffer device; device.open(QBuffer::ReadWrite); CTelegramStream stream(&device); stream << data.at(i).value.toString(); if ((data.at(i).serializedValue.length() > 10) && (device.data() != data.at(i).serializedValue)) { qDebug() << QString("Actual (%1 bytes):").arg(device.data().length()) << device.data().toHex(); qDebug() << QString("Expected (%1 bytes):").arg(data.at(i).serializedValue.length()) << data.at(i).serializedValue.toHex(); } QCOMPARE(device.data(), data.at(i).serializedValue); } } void tst_CTelegramStream::writeLongString() { QList<STestData> data; QString stringToTest1 = QLatin1String("Some really pretty long string to be serialized. " "Start to speek something wise and sage. Abadfa dfa uzxcviuwekrhalflkjhzvzxciuvyoiuwehrkblabla-asdfasdf" "qwrq25!@!@(#*&!$@%@!()#*&@#($)&*)(!@*&#)(!*@&#()!@*&$%!*@&$&^!%$&*#@%$&*%^@#$&%@#$@#*$&^@#*(&^@#%*&^!F" "132465798+760++-*/*/651321///???asd0f98`0978jhkjhzxcv....end"); // Lenght: 313 const int len = 313; QByteArray serialized1(1, char(0xfe)); serialized1.append(char(len & 0xff)); serialized1.append(char((len & 0xff00) >> 8)); serialized1.append(char((len & 0xff0000) >> 16)); serialized1.append(stringToTest1.toUtf8()); int extraNulls = 4 - (len & 3); for (int i = 0; i < extraNulls; ++i) serialized1.append(char(0)); data.append(STestData(stringToTest1, serialized1)); for (int i = 0; i < data.count(); ++i) { QBuffer device; device.open(QBuffer::ReadWrite); CTelegramStream stream(&device); stream << data.at(i).value.toString(); QVERIFY2(!(device.data().length() % 4), "Results buffer is not padded (total length is not divisible by 4)"); QVERIFY2((device.data().length() >= len + 4), "Results buffer size for long string should be at least stringLength + 4"); QVERIFY2((device.data().length() <= len + 4 + 3), "Results buffer size for long string should never be more, than stringLength + 4 + 3"); QCOMPARE(device.data(), data.at(i).serializedValue); } } void tst_CTelegramStream::writeInt() { QList<STestData> data; { QByteArray testSerialized; quint32 values[5] = { 0x01, 0xff, 0x00, 0xaabbcc, 0xdeadbeef }; const char serialized1[4] = { char(values[0]), 0, 0, 0 }; const char serialized2[4] = { char(values[1]), 0, 0, 0 }; const char serialized3[4] = { char(values[2]), 0, 0, 0 }; const char serialized4[4] = { char(0xcc), char(0xbb), char(0xaa), char(0x00) }; const char serialized5[4] = { char(0xef), char(0xbe), char(0xad), char(0xde) }; testSerialized.append(serialized1, 4); testSerialized.append(serialized2, 4); testSerialized.append(serialized3, 4); testSerialized.append(serialized4, 4); testSerialized.append(serialized5, 5); for (int i = 0; i < 5; ++i) data.append(STestData(values[i], testSerialized.mid(i * 4, 4))); } for (int i = 0; i < data.count(); ++i) { QBuffer device; device.open(QBuffer::ReadWrite); CTelegramStream stream(&device); stream << data.at(i).value.value<quint32>(); QCOMPARE(device.data(), data.at(i).serializedValue); } } QTEST_MAIN(tst_CTelegramStream) #include "tst_CTelegramStream.moc" <|endoftext|>
<commit_before>/* This macro will add histograms from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hist_add targetfile source1 source2 ... Author: Sven A. Schmidt, sven.schmidt@cern.ch Date: 13.2.2001 This code is based on the hadd.C example by Rene Brun and Dirk Geppert, which had a problem with directories more than one level deep. (see macro hadd_old.C for this previous implementation). I have tested this macro on rootfiles with one and two dimensional histograms, and two levels of subdirectories. Feel free to send comments or bug reports to me. */ #include <TROOT.h> #include "TFile.h" #include "TH1.h" #include "TTree.h" #include "TKey.h" #include <string.h> #include <iostream.h> TROOT Root( "hist_add", "Histogram Merger" ); TList *FileList; TFile *Target; void MergeRootfile( TDirectory *target, TList *sourcelist ); int main( int argc, char **argv ) { FileList = new TList(); if ( argc < 4 ) { cout << "Usage: " << argv[0] << " <target> <source1> <source2> ...\n"; cout << "supply at least two source files for this to make sense... ;-)\n"; exit( -1 ); } cout << "Target file: " << argv[1] << endl; Target = TFile::Open( argv[1], "RECREATE" ); for ( int i = 2; i < argc; i++ ) { cout << "Source file " << i-1 << ": " << argv[i] << endl; FileList->Add( TFile::Open( argv[i] ) ); } MergeRootfile( Target, FileList ); } // Merge all files from sourcelist into the target directory. // The directory level (depth) is determined by the target directory's // current level void MergeRootfile( TDirectory *target, TList *sourcelist ) { // cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; // loop over all keys in this directory TIter nextkey( current_sourcedir->GetListOfKeys() ); while ( TKey *key = (TKey*)nextkey() ) { // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1" ) ) { // descendant of TH1 -> merge it // cout << "Merging histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)obj; // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() ); if ( h2 ) { h1->Add( h2 ); delete h2; // don't know if this is necessary, i.e. if // h2 is created by the call to gDirectory above. } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion MergeRootfile( newdir, sourcelist ); } else { // object is of no type that we know or can handle cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } // now write the merged histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->Write(); } <commit_msg>Remove the statement calling the TROOT constructor.<commit_after>/* This macro will add histograms from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hist_add targetfile source1 source2 ... Author: Sven A. Schmidt, sven.schmidt@cern.ch Date: 13.2.2001 This code is based on the hadd.C example by Rene Brun and Dirk Geppert, which had a problem with directories more than one level deep. (see macro hadd_old.C for this previous implementation). I have tested this macro on rootfiles with one and two dimensional histograms, and two levels of subdirectories. Feel free to send comments or bug reports to me. */ #include "TFile.h" #include "TH1.h" #include "TTree.h" #include "TKey.h" #include <string.h> #include <iostream.h> TList *FileList; TFile *Target; void MergeRootfile( TDirectory *target, TList *sourcelist ); int main( int argc, char **argv ) { FileList = new TList(); if ( argc < 4 ) { cout << "Usage: " << argv[0] << " <target> <source1> <source2> ...\n"; cout << "supply at least two source files for this to make sense... ;-)\n"; exit( -1 ); } cout << "Target file: " << argv[1] << endl; Target = TFile::Open( argv[1], "RECREATE" ); for ( int i = 2; i < argc; i++ ) { cout << "Source file " << i-1 << ": " << argv[i] << endl; FileList->Add( TFile::Open( argv[i] ) ); } MergeRootfile( Target, FileList ); } // Merge all files from sourcelist into the target directory. // The directory level (depth) is determined by the target directory's // current level void MergeRootfile( TDirectory *target, TList *sourcelist ) { // cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; // loop over all keys in this directory TIter nextkey( current_sourcedir->GetListOfKeys() ); while ( TKey *key = (TKey*)nextkey() ) { // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1" ) ) { // descendant of TH1 -> merge it // cout << "Merging histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)obj; // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() ); if ( h2 ) { h1->Add( h2 ); delete h2; // don't know if this is necessary, i.e. if // h2 is created by the call to gDirectory above. } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion MergeRootfile( newdir, sourcelist ); } else { // object is of no type that we know or can handle cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } // now write the merged histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->Write(); } <|endoftext|>
<commit_before>/* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/> * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "accounts-list-model.h" #include "account-item.h" #include <KDebug> #include <KIcon> #include <TelepathyQt4/Account> AccountsListModel::AccountsListModel(QObject *parent) : QAbstractListModel(parent) { kDebug(); m_accounts.clear(); } AccountsListModel::~AccountsListModel() { kDebug(); // TODO: Implement me! } int AccountsListModel::rowCount(const QModelIndex &index) const { // If the index is the root item, then return the row count. if (index == QModelIndex()) { return m_accounts.size(); } // Otherwise, return 0 (as this is a list model, so all items // are children of the root item). return 0; } QVariant AccountsListModel::data(const QModelIndex &index, int role) const { QVariant data; Tp::AccountPtr account = m_accounts.at(index.row())->account(); switch(role) { case Qt::DisplayRole: data = QVariant(account->displayName()); break; case Qt::DecorationRole: data = QVariant(m_accounts.at(index.row())->icon()); break; case Qt::CheckStateRole: if(account->isEnabled()) { data = QVariant(Qt::Checked); } else { data = QVariant(Qt::Unchecked); } break; case AccountsListModel::ConnectionStateDisplayRole: data = QVariant(m_accounts.at(index.row())->connectionStateString()); break; case AccountsListModel::ConnectionStateIconRole: data = QVariant(m_accounts.at(index.row())->connectionStateIcon()); break; case AccountsListModel::ConnectionErrorMessageDisplayRole: data = QVariant(m_accounts.at(index.row())->connectionStatusReason()); break; default: break; } return data; } bool AccountsListModel::setData(const QModelIndex &index, const QVariant &value, int role) { kDebug(); if(role == Qt::CheckStateRole) { if(m_accounts.at(index.row())->account()) { m_accounts.at(index.row())->account()->setEnabled(value.toInt() == Qt::Checked); return true; } } return false; } Qt::ItemFlags AccountsListModel::flags(const QModelIndex &index) const { return QAbstractItemModel::flags(index) | Qt::ItemIsUserCheckable; } void AccountsListModel::addAccount(const Tp::AccountPtr &account) { kDebug() << "Creating a new AccountItem from account:" << account.data(); // Check if the account is already in the model. bool found = false; if (!found) { foreach (const AccountItem* ai, m_accounts) { if (ai->account() == account) { found = true; break; } } } if (found) { kWarning() << "Requested to add account" << account.data() << "to model, but it is already present. Doing nothing."; } else { kDebug() << "Account not already in model. Create new AccountItem from account:" << account.data(); AccountItem *item = new AccountItem(account, this); beginInsertRows(QModelIndex(), m_accounts.size(), m_accounts.size()); m_accounts.append(item); endInsertRows(); connect(item, SIGNAL(removed()), SLOT(onAccountItemRemoved())); connect(item, SIGNAL(updated()), SLOT(onAccountItemUpdated())); } } void AccountsListModel::removeAccount(const QModelIndex &index) { kDebug(); if(!index.isValid()) { kDebug() << "Can't remove Account: Invalid index"; return; } AccountItem *accountItem = m_accounts.at(index.row()); Q_ASSERT(accountItem); accountItem->remove(); } AccountItem* AccountsListModel::itemForIndex(const QModelIndex &index) { kDebug(); if(!index.isValid()) { kWarning() << "Invalid index" << index; return 0; } AccountItem *accountItem = m_accounts.at(index.row()); return accountItem; } void AccountsListModel::onAccountItemRemoved() { kDebug(); AccountItem *item = qobject_cast<AccountItem*>(sender()); Q_ASSERT(item); if (!item) { kWarning() << "Not an AccountItem pointer:" << sender(); return; } beginRemoveRows(QModelIndex(), m_accounts.lastIndexOf(item), m_accounts.lastIndexOf(item)); m_accounts.removeAll(item); endRemoveRows(); Q_ASSERT(!m_accounts.contains(item)); if (m_accounts.contains(item)) { kWarning() << "Ready Accounts still contains Accout Item:" << item; } } void AccountsListModel::onAccountItemUpdated() { kDebug(); AccountItem *item = qobject_cast<AccountItem*>(sender()); Q_ASSERT(item); if (!item) { kWarning() << "Not an AccountItem pointer:" << sender(); return; } QModelIndex index = createIndex(m_accounts.lastIndexOf(item), 0); emit dataChanged(index, index); } void AccountsListModel::onTitleForCustomPages(QString mandatoryPage, QList<QString> optionalPage) { kDebug(); emit setTitleForCustomPages(mandatoryPage, optionalPage); } #include "accounts-list-model.moc" <commit_msg>Added review comments, and reverted an unnecessary change.<commit_after>/* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/> * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "accounts-list-model.h" #include "account-item.h" #include <KDebug> #include <KIcon> #include <TelepathyQt4/Account> AccountsListModel::AccountsListModel(QObject *parent) : QAbstractListModel(parent) { kDebug(); m_accounts.clear(); } AccountsListModel::~AccountsListModel() { kDebug(); // TODO: Implement me! } int AccountsListModel::rowCount(const QModelIndex &index) const { // If the index is the root item, then return the row count. if (index == QModelIndex()) { return m_accounts.size(); } // Otherwise, return 0 (as this is a list model, so all items // are children of the root item). return 0; } QVariant AccountsListModel::data(const QModelIndex &index, int role) const { QVariant data; Tp::AccountPtr account = m_accounts.at(index.row())->account(); switch(role) { case Qt::DisplayRole: data = QVariant(account->displayName()); break; case Qt::DecorationRole: data = QVariant(m_accounts.at(index.row())->icon()); break; case Qt::CheckStateRole: if(account->isEnabled()) { data = QVariant(Qt::Checked); } else { data = QVariant(Qt::Unchecked); } break; case AccountsListModel::ConnectionStateDisplayRole: data = QVariant(m_accounts.at(index.row())->connectionStateString()); break; case AccountsListModel::ConnectionStateIconRole: data = QVariant(m_accounts.at(index.row())->connectionStateIcon()); break; case AccountsListModel::ConnectionErrorMessageDisplayRole: data = QVariant(m_accounts.at(index.row())->connectionStatusReason()); break; default: break; } return data; } bool AccountsListModel::setData(const QModelIndex &index, const QVariant &value, int role) { kDebug(); if(role == Qt::CheckStateRole) { m_accounts.at(index.row())->account()->setEnabled(value.toInt() == Qt::Checked); return true; } return false; } Qt::ItemFlags AccountsListModel::flags(const QModelIndex &index) const { return QAbstractItemModel::flags(index) | Qt::ItemIsUserCheckable; } void AccountsListModel::addAccount(const Tp::AccountPtr &account) { kDebug() << "Creating a new AccountItem from account:" << account.data(); // Check if the account is already in the model. bool found = false; if (!found) { foreach (const AccountItem* ai, m_accounts) { if (ai->account() == account) { found = true; break; } } } if (found) { kWarning() << "Requested to add account" << account.data() << "to model, but it is already present. Doing nothing."; } else { kDebug() << "Account not already in model. Create new AccountItem from account:" << account.data(); AccountItem *item = new AccountItem(account, this); beginInsertRows(QModelIndex(), m_accounts.size(), m_accounts.size()); m_accounts.append(item); endInsertRows(); connect(item, SIGNAL(removed()), SLOT(onAccountItemRemoved())); connect(item, SIGNAL(updated()), SLOT(onAccountItemUpdated())); } } void AccountsListModel::removeAccount(const QModelIndex &index) { kDebug(); if(!index.isValid()) { kDebug() << "Can't remove Account: Invalid index"; return; } AccountItem *accountItem = m_accounts.at(index.row()); Q_ASSERT(accountItem); accountItem->remove(); } AccountItem* AccountsListModel::itemForIndex(const QModelIndex &index) { kDebug(); if(!index.isValid()) { kWarning() << "Invalid index" << index; return 0; } AccountItem *accountItem = m_accounts.at(index.row()); return accountItem; } void AccountsListModel::onAccountItemRemoved() { kDebug(); AccountItem *item = qobject_cast<AccountItem*>(sender()); Q_ASSERT(item); if (!item) { kWarning() << "Not an AccountItem pointer:" << sender(); return; } beginRemoveRows(QModelIndex(), m_accounts.lastIndexOf(item), m_accounts.lastIndexOf(item)); m_accounts.removeAll(item); endRemoveRows(); Q_ASSERT(!m_accounts.contains(item)); if (m_accounts.contains(item)) { kWarning() << "Ready Accounts still contains Accout Item:" << item; } } void AccountsListModel::onAccountItemUpdated() { kDebug(); AccountItem *item = qobject_cast<AccountItem*>(sender()); Q_ASSERT(item); if (!item) { kWarning() << "Not an AccountItem pointer:" << sender(); return; } QModelIndex index = createIndex(m_accounts.lastIndexOf(item), 0); emit dataChanged(index, index); } void AccountsListModel::onTitleForCustomPages(QString mandatoryPage, QList<QString> optionalPage) { kDebug(); emit setTitleForCustomPages(mandatoryPage, optionalPage); } #include "accounts-list-model.moc" <|endoftext|>
<commit_before>/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 "config.h" #include "support/filesystem.h" #include "support/platform.h" #include "simpleini/simpleini.h" using namespace std; namespace alpr { int getInt(CSimpleIniA* ini, std::string section, std::string key, int defaultValue); float getFloat(CSimpleIniA* ini, std::string section, std::string key, float defaultValue); std::string getString(CSimpleIniA* ini, std::string section, std::string key, std::string defaultValue); bool getBoolean(CSimpleIniA* ini, std::string section, std::string key, bool defaultValue); Config::Config(const std::string country, const std::string config_file, const std::string runtime_dir) { string debug_message = ""; this->loaded = false; string configFile; char* envConfigFile; envConfigFile = getenv (ENV_VARIABLE_CONFIG_FILE); if (config_file.compare("") != 0) { // User has supplied a config file. Use that. configFile = config_file; debug_message = "Config file location provided via API"; } else if (envConfigFile != NULL) { // Environment variable is non-empty. Use that. configFile = envConfigFile; debug_message = "Config file location provided via environment variable: " + string(ENV_VARIABLE_CONFIG_FILE); } else if (DirectoryExists(getExeDir().c_str()) && fileExists((getExeDir() + CONFIG_FILE).c_str())) { configFile = getExeDir() + CONFIG_FILE; debug_message = "Config file location provided via exe location"; } else { // Use the default configFile = DEFAULT_CONFIG_FILE; debug_message = "Config file location provided via default location"; } //string configFile = (this->runtimeBaseDir + CONFIG_FILE); if (fileExists(configFile.c_str()) == false) { std::cerr << "--(!) Config file '" << configFile << "' does not exist!" << endl; std::cerr << "--(!) You can specify the configuration file location via the command line " << endl; std::cerr << "--(!) or by setting the environment variable '" << ENV_VARIABLE_CONFIG_FILE << "'" << endl; return; } else if (DirectoryExists(configFile.c_str())) { std::cerr << "--(!) Config file '" << configFile << "' was specified as a directory, rather than a file!" << endl; std::cerr << "--(!) Please specify the full path to the 'openalpr.conf file'" << endl; std::cerr << "--(!) e.g., /etc/openalpr/openalpr.conf" << endl; return; } this->country = country; loadCommonValues(configFile); if (runtime_dir.compare("") != 0) { // User provided a runtime directory directly into the library. Use this. this->runtimeBaseDir = runtime_dir; } if ((DirectoryExists(this->runtimeBaseDir.c_str()) == false) && (DirectoryExists((getExeDir() + RUNTIME_DIR).c_str()))) { // Runtime dir in the config is invalid and there is a runtime dir in the same dir as the exe. this->runtimeBaseDir = getExeDir() + RUNTIME_DIR; } if (DirectoryExists(this->runtimeBaseDir.c_str()) == false) { std::cerr << "--(!) Runtime directory '" << this->runtimeBaseDir << "' does not exist!" << endl; std::cerr << "--(!) Please update the OpenALPR config file: '" << configFile << "'" << endl; std::cerr << "--(!) to point to the correct location of your runtime_dir" << endl; return; } std::string country_config_file = this->runtimeBaseDir + "/config/" + country + ".conf"; if (fileExists(country_config_file.c_str()) == false) { std::cerr << "--(!) Country config file '" << country_config_file << "' does not exist. Missing config for the country: '" << country<< "'!" << endl; return; } loadCountryValues(country_config_file, country); if (fileExists((this->runtimeBaseDir + "/ocr/tessdata/" + this->ocrLanguage + ".traineddata").c_str()) == false) { std::cerr << "--(!) Runtime directory '" << this->runtimeBaseDir << "' is invalid. Missing OCR data for the country: '" << country<< "'!" << endl; return; } if (this->debugGeneral) { std::cout << debug_message << endl; } this->loaded = true; } Config::~Config() { } void Config::loadCommonValues(string configFile) { CSimpleIniA iniObj; iniObj.LoadFile(configFile.c_str()); CSimpleIniA* ini = &iniObj; runtimeBaseDir = getString(ini, "", "runtime_dir", "/usr/share/openalpr/runtime_data"); std::string detectorString = getString(ini, "", "detector", "lbpcpu"); std::transform(detectorString.begin(), detectorString.end(), detectorString.begin(), ::tolower); if (detectorString.compare("lbpcpu") == 0) detector = DETECTOR_LBP_CPU; else if (detectorString.compare("lbpgpu") == 0) detector = DETECTOR_LBP_GPU; else if (detectorString.compare("morphcpu") == 0) detector = DETECTOR_MORPH_CPU; else { std::cerr << "Invalid detector specified: " << detectorString << ". Using default" << std::endl; detector = DETECTOR_LBP_CPU; } detection_iteration_increase = getFloat(ini, "", "detection_iteration_increase", 1.1); detectionStrictness = getInt(ini, "", "detection_strictness", 3); maxPlateWidthPercent = getFloat(ini, "", "max_plate_width_percent", 100); maxPlateHeightPercent = getFloat(ini, "", "max_plate_height_percent", 100); maxDetectionInputWidth = getInt(ini, "", "max_detection_input_width", 1280); maxDetectionInputHeight = getInt(ini, "", "max_detection_input_height", 768); skipDetection = getBoolean(ini, "", "skip_detection", false); prewarp = getString(ini, "", "prewarp", ""); maxPlateAngleDegrees = getInt(ini, "", "max_plate_angle_degrees", 15); ocrImagePercent = getFloat(ini, "", "ocr_img_size_percent", 100); stateIdImagePercent = getFloat(ini, "", "state_id_img_size_percent", 100); ocrMinFontSize = getInt(ini, "", "ocr_min_font_point", 100); postProcessMinConfidence = getFloat(ini, "", "postprocess_min_confidence", 100); postProcessConfidenceSkipLevel = getFloat(ini, "", "postprocess_confidence_skip_level", 100); postProcessMinCharacters = getInt(ini, "", "postprocess_min_characters", 100); postProcessMaxCharacters = getInt(ini, "", "postprocess_max_characters", 100); debugGeneral = getBoolean(ini, "", "debug_general", false); debugTiming = getBoolean(ini, "", "debug_timing", false); debugPrewarp = getBoolean(ini, "", "debug_prewarp", false); debugDetector = getBoolean(ini, "", "debug_detector", false); debugStateId = getBoolean(ini, "", "debug_state_id", false); debugPlateLines = getBoolean(ini, "", "debug_plate_lines", false); debugPlateCorners = getBoolean(ini, "", "debug_plate_corners", false); debugCharSegmenter = getBoolean(ini, "", "debug_char_segment", false); debugCharAnalysis = getBoolean(ini, "", "debug_char_analysis", false); debugColorFiler = getBoolean(ini, "", "debug_color_filter", false); debugOcr = getBoolean(ini, "", "debug_ocr", false); debugPostProcess = getBoolean(ini, "", "debug_postprocess", false); debugShowImages = getBoolean(ini, "", "debug_show_images", false); debugPauseOnFrame = getBoolean(ini, "", "debug_pause_on_frame", false); } void Config::loadCountryValues(string configFile, string country) { CSimpleIniA iniObj; iniObj.LoadFile(configFile.c_str()); CSimpleIniA* ini = &iniObj; minPlateSizeWidthPx = getInt(ini, "", "min_plate_size_width_px", 100); minPlateSizeHeightPx = getInt(ini, "", "min_plate_size_height_px", 100); multiline = getBoolean(ini, "", "multiline", false); plateWidthMM = getFloat(ini, "", "plate_width_mm", 100); plateHeightMM = getFloat(ini, "", "plate_height_mm", 100); charHeightMM = getFloat(ini, "", "char_height_mm", 100); charWidthMM = getFloat(ini, "", "char_width_mm", 100); charWhitespaceTopMM = getFloat(ini, "", "char_whitespace_top_mm", 100); charWhitespaceBotMM = getFloat(ini, "", "char_whitespace_bot_mm", 100); templateWidthPx = getInt(ini, "", "template_max_width_px", 100); templateHeightPx = getInt(ini, "", "template_max_height_px", 100); charAnalysisMinPercent = getFloat(ini, "", "char_analysis_min_pct", 0); charAnalysisHeightRange = getFloat(ini, "", "char_analysis_height_range", 0); charAnalysisHeightStepSize = getFloat(ini, "", "char_analysis_height_step_size", 0); charAnalysisNumSteps = getInt(ini, "", "char_analysis_height_num_steps", 0); segmentationMinBoxWidthPx = getInt(ini, "", "segmentation_min_box_width_px", 0); segmentationMinCharHeightPercent = getFloat(ini, "", "segmentation_min_charheight_percent", 0); segmentationMaxCharWidthvsAverage = getFloat(ini, "", "segmentation_max_segment_width_percent_vs_average", 0); plateLinesSensitivityVertical = getFloat(ini, "", "plateline_sensitivity_vertical", 0); plateLinesSensitivityHorizontal = getFloat(ini, "", "plateline_sensitivity_horizontal", 0); ocrLanguage = getString(ini, "", "ocr_language", "none"); ocrImageWidthPx = round(((float) templateWidthPx) * ocrImagePercent); ocrImageHeightPx = round(((float)templateHeightPx) * ocrImagePercent); stateIdImageWidthPx = round(((float)templateWidthPx) * stateIdImagePercent); stateIdimageHeightPx = round(((float)templateHeightPx) * stateIdImagePercent); } void Config::setDebug(bool value) { debugGeneral = !value; debugTiming = !value; debugStateId = !value; debugPlateLines = !value; debugPlateCorners = !value; debugCharSegmenter = !value; debugCharAnalysis = !value; debugColorFiler = !value; debugOcr = !value; debugPostProcess = !value; debugPauseOnFrame = !value; } string Config::getCascadeRuntimeDir() { return this->runtimeBaseDir + CASCADE_DIR; } string Config::getKeypointsRuntimeDir() { return this->runtimeBaseDir + KEYPOINTS_DIR; } string Config::getPostProcessRuntimeDir() { return this->runtimeBaseDir + POSTPROCESS_DIR; } string Config::getTessdataPrefix() { return this->runtimeBaseDir + "/ocr/"; } float getFloat(CSimpleIniA* ini, string section, string key, float defaultValue) { const char * pszValue = ini->GetValue(section.c_str(), key.c_str(), NULL /*default*/); if (pszValue == NULL) { return defaultValue; } float val = atof(pszValue); return val; } int getInt(CSimpleIniA* ini, string section, string key, int defaultValue) { const char * pszValue = ini->GetValue(section.c_str(), key.c_str(), NULL /*default*/); if (pszValue == NULL) { return defaultValue; } int val = atoi(pszValue); return val; } bool getBoolean(CSimpleIniA* ini, string section, string key, bool defaultValue) { const char * pszValue = ini->GetValue(section.c_str(), key.c_str(), NULL /*default*/); if (pszValue == NULL) { return defaultValue; } int val = atoi(pszValue); return val != 0; } string getString(CSimpleIniA* ini, string section, string key, string defaultValue) { const char * pszValue = ini->GetValue(section.c_str(), key.c_str(), NULL /*default*/); if (pszValue == NULL) { return defaultValue; } string val = string(pszValue); return val; } } <commit_msg>Fixed setDebug functiont to apply correct value<commit_after>/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 "config.h" #include "support/filesystem.h" #include "support/platform.h" #include "simpleini/simpleini.h" using namespace std; namespace alpr { int getInt(CSimpleIniA* ini, std::string section, std::string key, int defaultValue); float getFloat(CSimpleIniA* ini, std::string section, std::string key, float defaultValue); std::string getString(CSimpleIniA* ini, std::string section, std::string key, std::string defaultValue); bool getBoolean(CSimpleIniA* ini, std::string section, std::string key, bool defaultValue); Config::Config(const std::string country, const std::string config_file, const std::string runtime_dir) { string debug_message = ""; this->loaded = false; string configFile; char* envConfigFile; envConfigFile = getenv (ENV_VARIABLE_CONFIG_FILE); if (config_file.compare("") != 0) { // User has supplied a config file. Use that. configFile = config_file; debug_message = "Config file location provided via API"; } else if (envConfigFile != NULL) { // Environment variable is non-empty. Use that. configFile = envConfigFile; debug_message = "Config file location provided via environment variable: " + string(ENV_VARIABLE_CONFIG_FILE); } else if (DirectoryExists(getExeDir().c_str()) && fileExists((getExeDir() + CONFIG_FILE).c_str())) { configFile = getExeDir() + CONFIG_FILE; debug_message = "Config file location provided via exe location"; } else { // Use the default configFile = DEFAULT_CONFIG_FILE; debug_message = "Config file location provided via default location"; } //string configFile = (this->runtimeBaseDir + CONFIG_FILE); if (fileExists(configFile.c_str()) == false) { std::cerr << "--(!) Config file '" << configFile << "' does not exist!" << endl; std::cerr << "--(!) You can specify the configuration file location via the command line " << endl; std::cerr << "--(!) or by setting the environment variable '" << ENV_VARIABLE_CONFIG_FILE << "'" << endl; return; } else if (DirectoryExists(configFile.c_str())) { std::cerr << "--(!) Config file '" << configFile << "' was specified as a directory, rather than a file!" << endl; std::cerr << "--(!) Please specify the full path to the 'openalpr.conf file'" << endl; std::cerr << "--(!) e.g., /etc/openalpr/openalpr.conf" << endl; return; } this->country = country; loadCommonValues(configFile); if (runtime_dir.compare("") != 0) { // User provided a runtime directory directly into the library. Use this. this->runtimeBaseDir = runtime_dir; } if ((DirectoryExists(this->runtimeBaseDir.c_str()) == false) && (DirectoryExists((getExeDir() + RUNTIME_DIR).c_str()))) { // Runtime dir in the config is invalid and there is a runtime dir in the same dir as the exe. this->runtimeBaseDir = getExeDir() + RUNTIME_DIR; } if (DirectoryExists(this->runtimeBaseDir.c_str()) == false) { std::cerr << "--(!) Runtime directory '" << this->runtimeBaseDir << "' does not exist!" << endl; std::cerr << "--(!) Please update the OpenALPR config file: '" << configFile << "'" << endl; std::cerr << "--(!) to point to the correct location of your runtime_dir" << endl; return; } std::string country_config_file = this->runtimeBaseDir + "/config/" + country + ".conf"; if (fileExists(country_config_file.c_str()) == false) { std::cerr << "--(!) Country config file '" << country_config_file << "' does not exist. Missing config for the country: '" << country<< "'!" << endl; return; } loadCountryValues(country_config_file, country); if (fileExists((this->runtimeBaseDir + "/ocr/tessdata/" + this->ocrLanguage + ".traineddata").c_str()) == false) { std::cerr << "--(!) Runtime directory '" << this->runtimeBaseDir << "' is invalid. Missing OCR data for the country: '" << country<< "'!" << endl; return; } if (this->debugGeneral) { std::cout << debug_message << endl; } this->loaded = true; } Config::~Config() { } void Config::loadCommonValues(string configFile) { CSimpleIniA iniObj; iniObj.LoadFile(configFile.c_str()); CSimpleIniA* ini = &iniObj; runtimeBaseDir = getString(ini, "", "runtime_dir", "/usr/share/openalpr/runtime_data"); std::string detectorString = getString(ini, "", "detector", "lbpcpu"); std::transform(detectorString.begin(), detectorString.end(), detectorString.begin(), ::tolower); if (detectorString.compare("lbpcpu") == 0) detector = DETECTOR_LBP_CPU; else if (detectorString.compare("lbpgpu") == 0) detector = DETECTOR_LBP_GPU; else if (detectorString.compare("morphcpu") == 0) detector = DETECTOR_MORPH_CPU; else { std::cerr << "Invalid detector specified: " << detectorString << ". Using default" << std::endl; detector = DETECTOR_LBP_CPU; } detection_iteration_increase = getFloat(ini, "", "detection_iteration_increase", 1.1); detectionStrictness = getInt(ini, "", "detection_strictness", 3); maxPlateWidthPercent = getFloat(ini, "", "max_plate_width_percent", 100); maxPlateHeightPercent = getFloat(ini, "", "max_plate_height_percent", 100); maxDetectionInputWidth = getInt(ini, "", "max_detection_input_width", 1280); maxDetectionInputHeight = getInt(ini, "", "max_detection_input_height", 768); skipDetection = getBoolean(ini, "", "skip_detection", false); prewarp = getString(ini, "", "prewarp", ""); maxPlateAngleDegrees = getInt(ini, "", "max_plate_angle_degrees", 15); ocrImagePercent = getFloat(ini, "", "ocr_img_size_percent", 100); stateIdImagePercent = getFloat(ini, "", "state_id_img_size_percent", 100); ocrMinFontSize = getInt(ini, "", "ocr_min_font_point", 100); postProcessMinConfidence = getFloat(ini, "", "postprocess_min_confidence", 100); postProcessConfidenceSkipLevel = getFloat(ini, "", "postprocess_confidence_skip_level", 100); postProcessMinCharacters = getInt(ini, "", "postprocess_min_characters", 100); postProcessMaxCharacters = getInt(ini, "", "postprocess_max_characters", 100); debugGeneral = getBoolean(ini, "", "debug_general", false); debugTiming = getBoolean(ini, "", "debug_timing", false); debugPrewarp = getBoolean(ini, "", "debug_prewarp", false); debugDetector = getBoolean(ini, "", "debug_detector", false); debugStateId = getBoolean(ini, "", "debug_state_id", false); debugPlateLines = getBoolean(ini, "", "debug_plate_lines", false); debugPlateCorners = getBoolean(ini, "", "debug_plate_corners", false); debugCharSegmenter = getBoolean(ini, "", "debug_char_segment", false); debugCharAnalysis = getBoolean(ini, "", "debug_char_analysis", false); debugColorFiler = getBoolean(ini, "", "debug_color_filter", false); debugOcr = getBoolean(ini, "", "debug_ocr", false); debugPostProcess = getBoolean(ini, "", "debug_postprocess", false); debugShowImages = getBoolean(ini, "", "debug_show_images", false); debugPauseOnFrame = getBoolean(ini, "", "debug_pause_on_frame", false); } void Config::loadCountryValues(string configFile, string country) { CSimpleIniA iniObj; iniObj.LoadFile(configFile.c_str()); CSimpleIniA* ini = &iniObj; minPlateSizeWidthPx = getInt(ini, "", "min_plate_size_width_px", 100); minPlateSizeHeightPx = getInt(ini, "", "min_plate_size_height_px", 100); multiline = getBoolean(ini, "", "multiline", false); plateWidthMM = getFloat(ini, "", "plate_width_mm", 100); plateHeightMM = getFloat(ini, "", "plate_height_mm", 100); charHeightMM = getFloat(ini, "", "char_height_mm", 100); charWidthMM = getFloat(ini, "", "char_width_mm", 100); charWhitespaceTopMM = getFloat(ini, "", "char_whitespace_top_mm", 100); charWhitespaceBotMM = getFloat(ini, "", "char_whitespace_bot_mm", 100); templateWidthPx = getInt(ini, "", "template_max_width_px", 100); templateHeightPx = getInt(ini, "", "template_max_height_px", 100); charAnalysisMinPercent = getFloat(ini, "", "char_analysis_min_pct", 0); charAnalysisHeightRange = getFloat(ini, "", "char_analysis_height_range", 0); charAnalysisHeightStepSize = getFloat(ini, "", "char_analysis_height_step_size", 0); charAnalysisNumSteps = getInt(ini, "", "char_analysis_height_num_steps", 0); segmentationMinBoxWidthPx = getInt(ini, "", "segmentation_min_box_width_px", 0); segmentationMinCharHeightPercent = getFloat(ini, "", "segmentation_min_charheight_percent", 0); segmentationMaxCharWidthvsAverage = getFloat(ini, "", "segmentation_max_segment_width_percent_vs_average", 0); plateLinesSensitivityVertical = getFloat(ini, "", "plateline_sensitivity_vertical", 0); plateLinesSensitivityHorizontal = getFloat(ini, "", "plateline_sensitivity_horizontal", 0); ocrLanguage = getString(ini, "", "ocr_language", "none"); ocrImageWidthPx = round(((float) templateWidthPx) * ocrImagePercent); ocrImageHeightPx = round(((float)templateHeightPx) * ocrImagePercent); stateIdImageWidthPx = round(((float)templateWidthPx) * stateIdImagePercent); stateIdimageHeightPx = round(((float)templateHeightPx) * stateIdImagePercent); } void Config::setDebug(bool value) { debugGeneral = value; debugTiming = value; debugStateId = value; debugPlateLines = value; debugPlateCorners = value; debugCharSegmenter = value; debugCharAnalysis = value; debugColorFiler = value; debugOcr = value; debugPostProcess = value; debugPauseOnFrame = value; } string Config::getCascadeRuntimeDir() { return this->runtimeBaseDir + CASCADE_DIR; } string Config::getKeypointsRuntimeDir() { return this->runtimeBaseDir + KEYPOINTS_DIR; } string Config::getPostProcessRuntimeDir() { return this->runtimeBaseDir + POSTPROCESS_DIR; } string Config::getTessdataPrefix() { return this->runtimeBaseDir + "/ocr/"; } float getFloat(CSimpleIniA* ini, string section, string key, float defaultValue) { const char * pszValue = ini->GetValue(section.c_str(), key.c_str(), NULL /*default*/); if (pszValue == NULL) { return defaultValue; } float val = atof(pszValue); return val; } int getInt(CSimpleIniA* ini, string section, string key, int defaultValue) { const char * pszValue = ini->GetValue(section.c_str(), key.c_str(), NULL /*default*/); if (pszValue == NULL) { return defaultValue; } int val = atoi(pszValue); return val; } bool getBoolean(CSimpleIniA* ini, string section, string key, bool defaultValue) { const char * pszValue = ini->GetValue(section.c_str(), key.c_str(), NULL /*default*/); if (pszValue == NULL) { return defaultValue; } int val = atoi(pszValue); return val != 0; } string getString(CSimpleIniA* ini, string section, string key, string defaultValue) { const char * pszValue = ini->GetValue(section.c_str(), key.c_str(), NULL /*default*/); if (pszValue == NULL) { return defaultValue; } string val = string(pszValue); return val; } } <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __BH_EXTMETHOD_HPP #define __BH_EXTMETHOD_HPP #include <string> #include <cassert> #include <exception> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include <bh_config_parser.hpp> #include <bh_error.h> #include <bh_ir.hpp> #include <bh_opcode.h> namespace bohrium { namespace extmethod { /* A extmethod in Bohrium is a function that implement a specific instruction. * * Requirements: * - A extmethod must be compiled into a shared library e.g. .so, .dylib, or .dll. * but multiple extmethods may be in the same shared library * * - A extmethod has to implement the ExtmethodImpl class; specifically, * the execute() method, which the parent component calls when it wants to * execute the instruction. * * - A extmethod has to implement two C compatible functions, <name>_create() and * <name>_destroy(), where <name> is the extmethod name. * * - The parent search for the two C compatible functions in the shared libraries * that the config file specifies under "libs". * * - The ExtmethodFace class makes it easy for a parent to do this search * and use the found execute() method. */ // Representation of a extmethod implementation, which is a virtual class // that all extended methods should implement class ExtmethodImpl { public: ExtmethodImpl() = default; virtual ~ExtmethodImpl() {}; /* Execute an instruction * * @instr The extension method instruction to handle * @arg Additional component specific argument * Throws exceptions on error */ virtual void execute(bh_instruction *instr, void* arg) = 0; }; // Representation of an extmethod interface, which consist of a create() // and destroy() function. class ExtmethodFace { private: // The name of the extmethod e.g. matmul or visualizer std::string _name; // Path to the shared library file e.g. .so, .dylib, or .dll std::string _lib_path; // Shared library handle void* _lib_handle; // Function pointer to the extmethod's create function ExtmethodImpl* (*_create)(); // Function pointer to the extmethod's destroy function void (*_destroy)(ExtmethodImpl *extmethod); // Pointer to the implementation of the extended method ExtmethodImpl *_implementation; public: // Constructor that takes the config file of the parent component and // the name of the extmethod ExtmethodFace(const ConfigParser &parent_config, const std::string &name); ~ExtmethodFace(); // Move Constructor ExtmethodFace(ExtmethodFace &&other) { if (this != &other) { _name = other._name; _lib_path = other._lib_path; _lib_handle = other._lib_handle; _create = other._create; _destroy = other._destroy; _implementation = other._implementation; other._name.clear(); other._lib_path.clear(); other._lib_handle = NULL; other._create = NULL; other._destroy = NULL; other._implementation = NULL; } } // No copy constructor use the move constructor instead. ExtmethodFace(const ExtmethodFace &other) = delete; // Get the extmethod implementation ExtmethodImpl* getImpl() { return _implementation; }; /* Execute an instruction * * @instr The extension method instruction to handle * @arg Additional component specific argument * Throws exceptions on error */ void execute(bh_instruction *instr, void* arg) { assert(_implementation != NULL); return _implementation->execute(instr, arg); }; }; class ExtmethodNotFound : public std::exception { std::string _msg; public: ExtmethodNotFound(const std::string& msg) : _msg(msg) {} virtual const char* what() const throw() { return _msg.c_str(); } }; }} //namespace bohrium::extmethod #endif <commit_msg>added some comments<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __BH_EXTMETHOD_HPP #define __BH_EXTMETHOD_HPP #include <string> #include <cassert> #include <exception> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include <bh_config_parser.hpp> #include <bh_error.h> #include <bh_ir.hpp> #include <bh_opcode.h> namespace bohrium { namespace extmethod { /* A extmethod in Bohrium is a function that implement a specific instruction. * * Requirements: * - A extmethod must be compiled into a shared library e.g. .so, .dylib, or .dll. * but multiple extmethods may be in the same shared library * * - A extmethod has to implement the ExtmethodImpl class; specifically, * the execute() method, which the parent component calls when it wants to * execute the instruction. * * - A extmethod has to implement two C compatible functions, <name>_create() and * <name>_destroy(), where <name> is the extmethod name. * * - The parent search for the two C compatible functions in the shared libraries * that the config file specifies under "libs". * * - The ExtmethodFace class makes it easy for a parent to do this search * and use the found execute() method. */ // Representation of a extmethod implementation, which is a virtual class // that all extension methods should implement class ExtmethodImpl { public: ExtmethodImpl() = default; virtual ~ExtmethodImpl() {}; /* Execute an instruction * * @instr The extension method instruction to handle * @arg Additional component specific argument * Throws exceptions on error */ virtual void execute(bh_instruction *instr, void* arg) = 0; }; // Representation of an extmethod interface, which consist of a create() // and destroy() function. class ExtmethodFace { private: // The name of the extmethod e.g. matmul or visualizer std::string _name; // Path to the shared library file e.g. .so, .dylib, or .dll std::string _lib_path; // Shared library handle void* _lib_handle; // Function pointer to the extmethod's create function ExtmethodImpl* (*_create)(); // Function pointer to the extmethod's destroy function void (*_destroy)(ExtmethodImpl *extmethod); // Pointer to the implementation of the extension method ExtmethodImpl *_implementation; public: // Constructor that takes the config file of the parent component and // the name of the extmethod ExtmethodFace(const ConfigParser &parent_config, const std::string &name); ~ExtmethodFace(); // Move Constructor ExtmethodFace(ExtmethodFace &&other) { if (this != &other) { _name = other._name; _lib_path = other._lib_path; _lib_handle = other._lib_handle; _create = other._create; _destroy = other._destroy; _implementation = other._implementation; other._name.clear(); other._lib_path.clear(); other._lib_handle = NULL; other._create = NULL; other._destroy = NULL; other._implementation = NULL; } } // No copy constructor use the move constructor instead. ExtmethodFace(const ExtmethodFace &other) = delete; // Get the extmethod implementation ExtmethodImpl* getImpl() { return _implementation; }; /* Execute an instruction * * @instr The extension method instruction to handle * @arg Additional component specific argument * Throws exceptions on error */ void execute(bh_instruction *instr, void* arg) { assert(_implementation != NULL); return _implementation->execute(instr, arg); }; }; // Exception thrown when an extension method is not found class ExtmethodNotFound : public std::exception { std::string _msg; public: ExtmethodNotFound(const std::string& msg) : _msg(msg) {} virtual const char* what() const throw() { return _msg.c_str(); } }; }} //namespace bohrium::extmethod #endif <|endoftext|>
<commit_before>#ifndef SCAN_IMPL_CPP #define SCAN_IMPL_CPP #include "scan.cpp" #include "../include/common.h" #include "../include/gpuOpenclLib.h" static void scanImpl(cl_mem d_input, int rLen, cl_mem d_output, struct clContext * context, struct statistic * pp) { preallocBlockSums(rLen, context); prescanArray(d_output, d_input, rLen, context,pp); deallocBlockSums(); } #endif <commit_msg>fix bugs<commit_after>#ifndef SCAN_IMPL_CPP #define SCAN_IMPL_CPP #include "scan.cpp" #include "../include/common.h" #include "../include/gpuOpenclLib.h" #include <CL/cl.h> static void scanImpl(cl_mem d_input, int rLen, cl_mem d_output, struct clContext * context, struct statistic * pp) { int len = 2; if(rLen < len){ cl_mem input, output; size_t globalSize = 1; size_t localSize = 1; input = clCreateBuffer(context->context,CL_MEM_READ_WRITE, sizeof(int) * len, NULL, 0); output = clCreateBuffer(context->context,CL_MEM_READ_WRITE, sizeof(int) * len, NULL, 0); context->kernel = clCreateKernel(context->program,"cl_memset_int",0); clSetKernelArg(context->kernel,0,sizeof(cl_mem), (void*)&input); clSetKernelArg(context->kernel,1,sizeof(int), (void*)&len); clEnqueueNDRangeKernel(context->queue, context->kernel, 1, 0, &globalSize,&localSize,0,0,0); cudaMemcpy(input, d_input, rLen*sizeof(int), cudaMemcpyDeviceToDevice); clEnqueueWriteBuffer(context->queue, input, CL_TRUE, 0, rLen * sizeof(int), d_input,0,0,0); preallocBlockSums(len, context); prescanArray(output, input, len, context,pp); deallocBlockSums(); clEnqueueWriteBuffer(context->queue, d_output, CL_TRUE, 0, rLen * sizeof(int), output,0,0,0); clReleaseMemObject(input); clReleaseMemObject(output); return; }else{ preallocBlockSums(rLen, context); prescanArray(d_output, d_input, rLen, context,pp); deallocBlockSums(); } } #endif <|endoftext|>
<commit_before>// // yssa_regalloc.cpp // // Created by Edmund Kapusniak on 27/03/2015. // Copyright (c) 2015 Edmund Kapusniak. All rights reserved. // #include "yssa_regalloc.h" #include <queue> #include <make_unique.h> #include "yssa.h" /* This is how we do register allocation: - We identify all live ranges and the ops/variables that each range corresponds to. Henceforth called values. - Call-like ops participate in the VM's calling convention, and we must identify the 'stack top' register for each call. We identify which values are live across each call op. - 'Argument' values have only a single use at a call-like op. We proceed thusly: - There is a set of 'free' values, initially consisting of all non-argument values. - The free value whose live range starts first is allocated such that it does not interfere with other values assigned to the same register. We prefer: - For arguments, a register based on the call op's stack top. - For selects or calls, a register based on the call op's stack top. - For parameters, the register - The lowest numbered register. - If all values which are live across a particular call op have been allocated, then we determine the stack top for that call. Argument values for the call are added to the set of free ops. Note that if there are no values live across a particular call then its arguments are in the initial free set. Essentially it's a greedy linear scan algorithm, but we treat argument values specially - looking ahead to place call ops at the correct place in the stack, then backtracking to place arguments. Since an argument value cannot span its call op (or any outer call op which has that call as an argument), the algorithm should always complete after allocating all values. The benefit from delaying allocation of arguments until the associated call's stack top is identified is probably quite small. It's likely that arguments will be encountered after all values live across the call, meaning that in most cases there will be no delay after all. For register allocation, we treat a call and all its associated multivals as a single unit. */ /* Make each value and each call op explicit. */ struct yssa_regvalue; struct yssa_regcall; typedef std::unique_ptr< yssa_regvalue > yssa_regvalue_p; typedef std::unique_ptr< yssa_regcall > yssa_regcall_p; struct yssa_regvalue { yssa_live_range* live; yssa_variable* variable; yssa_opinst* argof; std::vector< yssa_opinst* > ops; std::vector< yssa_regcall* > across; }; struct yssa_regcall { size_t index; yssa_opinst* op; std::vector< yssa_regvalue* > arguments; std::vector< yssa_opinst* > multival; size_t across_count; }; struct yssa_regvalue_priority { bool operator() ( yssa_regvalue* a, yssa_regvalue* b ) const { // First op has highest priority. return a->live->start >= b->live->start; } }; typedef std::priority_queue < yssa_regvalue*, std::vector< yssa_regvalue* >, yssa_regvalue_priority > yssa_regvalue_queue; /* Allocation record. */ struct yssa_regscan { std::vector< std::vector< yssa_live_range* > > registers; uint8_t stacktop( size_t address ); uint8_t allocate( yssa_live_range* range ); bool allocate( uint8_t r, yssa_live_range* range ); bool interfere( yssa_live_range* a, yssa_live_range* b ); }; uint8_t yssa_regscan::stacktop( size_t address ) { uint8_t r = registers.size(); while ( r-- ) { for ( yssa_live_range* live : registers.at( r ) ) { for ( ; live; live = live->next ) { if ( address >= live->start && address < live->final ) { return r + 1; } } } } return 0; } uint8_t yssa_regscan::allocate( yssa_live_range* range ) { for ( uint8_t r = 0; r <= registers.size(); ++r ) { if ( allocate( r, range ) ) { return r; } } assert( ! "final allocation should have succeeded" ); return 0; } bool yssa_regscan::allocate( uint8_t r, yssa_live_range* range ) { if ( r >= registers.size() ) { registers.resize( r + 1 ); registers.at( r ).push_back( range ); return true; } for ( yssa_live_range* live : registers.at( r ) ) { if ( interfere( range, live ) ) { return false; } } registers.at( r ).push_back( range ); return true; } bool yssa_regscan::interfere( yssa_live_range* a, yssa_live_range* b ) { while ( true ) { // Skip b spans that are wholly before the current a span. if ( b->final <= a->start ) { b = b->next; if ( ! b ) { // All b spans are before current a - no interference. return false; } continue; } // Skip a spans that are wholly before the current b span. if ( a->final <= b->start ) { a = a->next; if ( ! a ) { // All a spans are before current b - no interference. return false; } continue; } // Otherwise a and b overlap. return true; } } static uint8_t preferred_stacktop( yssa_function* function, yssa_regcall* call ) { auto i = function->argof.find( call->op ); if ( i == function->argof.end() ) { return yl_opinst::NOVAL; } // The call is itself an argument. yssa_opinst* argof = i->second; assert( argof->stacktop != yl_opinst::NOVAL ); for ( size_t i = 0; i < argof->operand_count; ++i ) { if ( argof->operand[ i ] == call->op ) { return argof->stacktop + i; } } return yl_opinst::NOVAL; } static uint8_t preferred_register( yssa_regvalue* value ) { // Check if the value is an argument. if ( value->argof ) { yssa_opinst* argof = value->argof; assert( argof->is_call() ); assert( argof->stacktop != yl_opinst::NOVAL ); for ( yssa_opinst* op : value->ops ) { for ( size_t i = 0; i < argof->operand_count; ++i ) { if ( argof->operand[ i ] == op ) { return argof->stacktop + i; } } } } // Other preferred clauses depend on there being a single definition. if ( value->ops.size() != 1 ) { return yl_opinst::NOVAL; } yssa_opinst* op = value->ops.at( 0 ); // Check if the value is a call itself. if ( op->is_call() ) { assert( op->stacktop != yl_opinst::NOVAL ); return op->stacktop; } // Check if the value is a select. if ( op->opcode == YSSA_SELECT && op->operand[ 0 ]->is_call() ) { assert( op->operand[ 0 ]->stacktop != yl_opinst::NOVAL ); return op->operand[ 0 ]->stacktop + op->select; } // Or a parameter. if ( op->opcode == YSSA_PARAM ) { // On entry, register 0 is the function object, with parameters after. return 1 + op->select; } return yl_opinst::NOVAL; } void yssa_regalloc( yssa_module* module, yssa_function* function ) { // Build values. std::unordered_map< void*, yssa_regvalue_p > values; for ( size_t i = 0; i < function->ops.size(); ++i ) { yssa_opinst* op = function->ops.at( i ); if ( ! op->live ) continue; if ( op->variable ) { auto j = values.find( op->variable ); if ( j != values.end() ) { yssa_regvalue* value = j->second.get(); value->ops.push_back( op ); } else { yssa_regvalue_p value = std::make_unique< yssa_regvalue >(); value->live = op->variable->live; value->variable = op->variable; value->argof = op->variable->argof; value->ops.push_back( op ); values.emplace( op->variable, std::move( value ) ); } } else { assert( ! values.count( op ) ); yssa_opinst* argof = nullptr; auto j = function->argof.find( op ); if ( j != function->argof.end() ) { argof = j->second; // Do not create values for multival arguments. if ( argof->has_multival() && argof->multival == op ) { continue; } // Look through multivals to the base op. while ( true ) { auto j = function->argof.find( argof ); if ( j != function->argof.end() ) { yssa_opinst* base = j->second; if ( base->has_multival() && base->multival == argof ) { argof = base; continue; } } break; } } // Create value structure. yssa_regvalue_p value = std::make_unique< yssa_regvalue >(); value->live = op->live; value->variable = nullptr; value->argof = argof; value->ops.push_back( op ); values.emplace( op, std::move( value ) ); } } // Build calls. std::vector< yssa_regcall_p > calls; for ( size_t i = 0; i < function->ops.size(); ++i ) { yssa_opinst* op = function->ops.at( i ); if ( ! op->is_call() ) { continue; } if ( op->result_count == yl_opinst::MARK ) { auto j = function->argof.find( op ); if ( j != function->argof.end() ) { yssa_opinst* argof = j->second; if ( argof->has_multival() && argof->multival == op ) { continue; } } } yssa_regcall_p call = std::make_unique< yssa_regcall >(); call->index = i; call->op = op; call->across_count = 0; for ( const auto& v : values ) { yssa_regvalue* val = v.second.get(); for ( yssa_live_range* live = val->live; live; live = live->next ) { // Note that if i == live->start then the live range begins at // the call itself. Calls are not live across themselves. if ( i > live->start && i < live->final ) { val->across.push_back( call.get() ); call->across_count += 1; } } if ( v.second->argof == op ) { call->arguments.push_back( v.second.get() ); } } if ( call->across_count == 0 ) { // No variables are live across the call. uint8_t stacktop = 0; call->op->stacktop = stacktop; yssa_opinst* op = call->op; while ( op->has_multival() && op->multival ) { stacktop += op->operand_count; op = op->multival; op->r = stacktop; op->stacktop = stacktop; } for ( yssa_regvalue* value : call->arguments ) { value->argof = nullptr; } } calls.push_back( std::move( call ) ); } // Identify free values. yssa_regvalue_queue free_values; for ( const auto& v : values ) { yssa_regvalue* value = v.second.get(); // Sort calls this value is across so that the last // call is allocated first. std::sort ( value->across.begin(), value->across.end(), []( yssa_regcall* a, yssa_regcall* b ) { return a->index > b->index; } ); // If the value isn't an argument, it's free. if ( ! value->argof ) { free_values.push( v.second.get() ); } } // Perform allocations. yssa_regscan regscan; while ( free_values.size() ) { yssa_regvalue* value = free_values.top(); free_values.pop(); // Identify preferred register (if any). uint8_t r = preferred_register( value ); // Attempt to allocate to preferred register. if ( r != yl_opinst::NOVAL && ! regscan.allocate( r, value->live ) ) { r = yl_opinst::NOVAL; } // Allocate to any register. if ( r == yl_opinst::NOVAL ) { r = regscan.allocate( value->live ); } // Set value. if ( value->variable ) { assert( value->variable->r == yl_opinst::NOVAL ); value->variable->r = r; } for ( yssa_opinst* op : value->ops ) { assert( op->r == yl_opinst::NOVAL ); op->r = r; } // Update calls now that this value has been allocated. for ( yssa_regcall* call : value->across ) { assert( call->across_count > 0 ); call->across_count -= 1; if ( call->across_count == 0 ) { // All values live across this call have been allocated, // find the stack top at this call. // Find top of stack. uint8_t stacktop = regscan.stacktop( call->index ); // Identify preferred stack top (if any). uint8_t preferred = preferred_stacktop( function, call ); if ( preferred != yl_opinst::NOVAL && preferred >= stacktop ) { stacktop = preferred; } // Assign stack top. assert( call->op->stacktop == yl_opinst::NOVAL ); call->op->stacktop = stacktop; yssa_opinst* op = call->op; while ( op->has_multival() && op->multival ) { stacktop += op->operand_count; op = op->multival; op->r = stacktop; op->stacktop = stacktop; } // All arguments to this call are now free to be allocated. for ( yssa_regvalue* argument : call->arguments ) { assert( argument->argof == call->op ); free_values.push( argument ); } } } } } <commit_msg>calls can become free _before_ the call they are an argument of.<commit_after>// // yssa_regalloc.cpp // // Created by Edmund Kapusniak on 27/03/2015. // Copyright (c) 2015 Edmund Kapusniak. All rights reserved. // #include "yssa_regalloc.h" #include <queue> #include <make_unique.h> #include "yssa.h" /* This is how we do register allocation: - We identify all live ranges and the ops/variables that each range corresponds to. Henceforth called values. - Call-like ops participate in the VM's calling convention, and we must identify the 'stack top' register for each call. We identify which values are live across each call op. - 'Argument' values have only a single use at a call-like op. We proceed thusly: - There is a set of 'free' values, initially consisting of all non-argument values. - The free value whose live range starts first is allocated such that it does not interfere with other values assigned to the same register. We prefer: - For arguments, a register based on the call op's stack top. - For selects or calls, a register based on the call op's stack top. - For parameters, the register - The lowest numbered register. - If all values which are live across a particular call op have been allocated, then we determine the stack top for that call. Argument values for the call are added to the set of free ops. Note that if there are no values live across a particular call then its arguments are in the initial free set. Essentially it's a greedy linear scan algorithm, but we treat argument values specially - looking ahead to place call ops at the correct place in the stack, then backtracking to place arguments. Since an argument value cannot span its call op (or any outer call op which has that call as an argument), the algorithm should always complete after allocating all values. The benefit from delaying allocation of arguments until the associated call's stack top is identified is probably quite small. It's likely that arguments will be encountered after all values live across the call, meaning that in most cases there will be no delay after all. For register allocation, we treat a call and all its associated multivals as a single unit. */ /* Make each value and each call op explicit. */ struct yssa_regvalue; struct yssa_regcall; typedef std::unique_ptr< yssa_regvalue > yssa_regvalue_p; typedef std::unique_ptr< yssa_regcall > yssa_regcall_p; struct yssa_regvalue { yssa_live_range* live; yssa_variable* variable; yssa_opinst* argof; std::vector< yssa_opinst* > ops; std::vector< yssa_regcall* > across; }; struct yssa_regcall { size_t index; yssa_opinst* op; std::vector< yssa_regvalue* > arguments; std::vector< yssa_opinst* > multival; size_t across_count; }; struct yssa_regvalue_priority { bool operator() ( yssa_regvalue* a, yssa_regvalue* b ) const { // First op has highest priority. return a->live->start >= b->live->start; } }; typedef std::priority_queue < yssa_regvalue*, std::vector< yssa_regvalue* >, yssa_regvalue_priority > yssa_regvalue_queue; /* Allocation record. */ struct yssa_regscan { std::vector< std::vector< yssa_live_range* > > registers; uint8_t stacktop( size_t address ); uint8_t allocate( yssa_live_range* range ); bool allocate( uint8_t r, yssa_live_range* range ); bool interfere( yssa_live_range* a, yssa_live_range* b ); }; uint8_t yssa_regscan::stacktop( size_t address ) { uint8_t r = registers.size(); while ( r-- ) { for ( yssa_live_range* live : registers.at( r ) ) { for ( ; live; live = live->next ) { if ( address >= live->start && address < live->final ) { return r + 1; } } } } return 0; } uint8_t yssa_regscan::allocate( yssa_live_range* range ) { for ( uint8_t r = 0; r <= registers.size(); ++r ) { if ( allocate( r, range ) ) { return r; } } assert( ! "final allocation should have succeeded" ); return 0; } bool yssa_regscan::allocate( uint8_t r, yssa_live_range* range ) { if ( r >= registers.size() ) { registers.resize( r + 1 ); registers.at( r ).push_back( range ); return true; } for ( yssa_live_range* live : registers.at( r ) ) { if ( interfere( range, live ) ) { return false; } } registers.at( r ).push_back( range ); return true; } bool yssa_regscan::interfere( yssa_live_range* a, yssa_live_range* b ) { while ( true ) { // Skip b spans that are wholly before the current a span. if ( b->final <= a->start ) { b = b->next; if ( ! b ) { // All b spans are before current a - no interference. return false; } continue; } // Skip a spans that are wholly before the current b span. if ( a->final <= b->start ) { a = a->next; if ( ! a ) { // All a spans are before current b - no interference. return false; } continue; } // Otherwise a and b overlap. return true; } } static uint8_t preferred_stacktop( yssa_function* function, yssa_regcall* call ) { auto i = function->argof.find( call->op ); if ( i == function->argof.end() ) { return yl_opinst::NOVAL; } // The call is itself an argument. yssa_opinst* argof = i->second; if ( argof->stacktop != yl_opinst::NOVAL ) { for ( size_t i = 0; i < argof->operand_count; ++i ) { if ( argof->operand[ i ] == call->op ) { return argof->stacktop + i; } } } return yl_opinst::NOVAL; } static uint8_t preferred_register( yssa_regvalue* value ) { // Check if the value is an argument. if ( value->argof ) { yssa_opinst* argof = value->argof; assert( argof->is_call() ); assert( argof->stacktop != yl_opinst::NOVAL ); for ( yssa_opinst* op : value->ops ) { for ( size_t i = 0; i < argof->operand_count; ++i ) { if ( argof->operand[ i ] == op ) { return argof->stacktop + i; } } } } // Other preferred clauses depend on there being a single definition. if ( value->ops.size() != 1 ) { return yl_opinst::NOVAL; } yssa_opinst* op = value->ops.at( 0 ); // Check if the value is a call itself. if ( op->is_call() ) { assert( op->stacktop != yl_opinst::NOVAL ); return op->stacktop; } // Check if the value is a select. if ( op->opcode == YSSA_SELECT && op->operand[ 0 ]->is_call() ) { assert( op->operand[ 0 ]->stacktop != yl_opinst::NOVAL ); return op->operand[ 0 ]->stacktop + op->select; } // Or a parameter. if ( op->opcode == YSSA_PARAM ) { // On entry, register 0 is the function object, with parameters after. return 1 + op->select; } return yl_opinst::NOVAL; } void yssa_regalloc( yssa_module* module, yssa_function* function ) { // Build values. std::unordered_map< void*, yssa_regvalue_p > values; for ( size_t i = 0; i < function->ops.size(); ++i ) { yssa_opinst* op = function->ops.at( i ); if ( ! op->live ) continue; if ( op->variable ) { auto j = values.find( op->variable ); if ( j != values.end() ) { yssa_regvalue* value = j->second.get(); value->ops.push_back( op ); } else { yssa_regvalue_p value = std::make_unique< yssa_regvalue >(); value->live = op->variable->live; value->variable = op->variable; value->argof = op->variable->argof; value->ops.push_back( op ); values.emplace( op->variable, std::move( value ) ); } } else { assert( ! values.count( op ) ); yssa_opinst* argof = nullptr; auto j = function->argof.find( op ); if ( j != function->argof.end() ) { argof = j->second; // Do not create values for multival arguments. if ( argof->has_multival() && argof->multival == op ) { continue; } // Look through multivals to the base op. while ( true ) { auto j = function->argof.find( argof ); if ( j != function->argof.end() ) { yssa_opinst* base = j->second; if ( base->has_multival() && base->multival == argof ) { argof = base; continue; } } break; } } // Create value structure. yssa_regvalue_p value = std::make_unique< yssa_regvalue >(); value->live = op->live; value->variable = nullptr; value->argof = argof; value->ops.push_back( op ); values.emplace( op, std::move( value ) ); } } // Build calls. std::vector< yssa_regcall_p > calls; for ( size_t i = 0; i < function->ops.size(); ++i ) { yssa_opinst* op = function->ops.at( i ); if ( ! op->is_call() ) { continue; } if ( op->result_count == yl_opinst::MARK ) { auto j = function->argof.find( op ); if ( j != function->argof.end() ) { yssa_opinst* argof = j->second; if ( argof->has_multival() && argof->multival == op ) { continue; } } } yssa_regcall_p call = std::make_unique< yssa_regcall >(); call->index = i; call->op = op; call->across_count = 0; for ( const auto& v : values ) { yssa_regvalue* val = v.second.get(); for ( yssa_live_range* live = val->live; live; live = live->next ) { // Note that if i == live->start then the live range begins at // the call itself. Calls are not live across themselves. if ( i > live->start && i < live->final ) { val->across.push_back( call.get() ); call->across_count += 1; } } if ( v.second->argof == op ) { call->arguments.push_back( v.second.get() ); } } if ( call->across_count == 0 ) { // No variables are live across the call. uint8_t stacktop = 0; call->op->stacktop = stacktop; yssa_opinst* op = call->op; while ( op->has_multival() && op->multival ) { stacktop += op->operand_count; op = op->multival; op->r = stacktop; op->stacktop = stacktop; } for ( yssa_regvalue* value : call->arguments ) { value->argof = nullptr; } } calls.push_back( std::move( call ) ); } // Identify free values. yssa_regvalue_queue free_values; for ( const auto& v : values ) { yssa_regvalue* value = v.second.get(); // Sort calls this value is across so that the last // call is allocated first. std::sort ( value->across.begin(), value->across.end(), []( yssa_regcall* a, yssa_regcall* b ) { return a->index > b->index; } ); // If the value isn't an argument, it's free. if ( ! value->argof ) { free_values.push( v.second.get() ); } } // Perform allocations. yssa_regscan regscan; while ( free_values.size() ) { yssa_regvalue* value = free_values.top(); free_values.pop(); // Identify preferred register (if any). uint8_t r = preferred_register( value ); // Attempt to allocate to preferred register. if ( r != yl_opinst::NOVAL && ! regscan.allocate( r, value->live ) ) { r = yl_opinst::NOVAL; } // Allocate to any register. if ( r == yl_opinst::NOVAL ) { r = regscan.allocate( value->live ); } // Set value. if ( value->variable ) { assert( value->variable->r == yl_opinst::NOVAL ); value->variable->r = r; } for ( yssa_opinst* op : value->ops ) { assert( op->r == yl_opinst::NOVAL ); op->r = r; } // Update calls now that this value has been allocated. for ( yssa_regcall* call : value->across ) { assert( call->across_count > 0 ); call->across_count -= 1; if ( call->across_count == 0 ) { // All values live across this call have been allocated, // find the stack top at this call. // Find top of stack. uint8_t stacktop = regscan.stacktop( call->index ); // Identify preferred stack top (if any). uint8_t preferred = preferred_stacktop( function, call ); if ( preferred != yl_opinst::NOVAL && preferred >= stacktop ) { stacktop = preferred; } // Assign stack top. assert( call->op->stacktop == yl_opinst::NOVAL ); call->op->stacktop = stacktop; yssa_opinst* op = call->op; while ( op->has_multival() && op->multival ) { stacktop += op->operand_count; op = op->multival; op->r = stacktop; op->stacktop = stacktop; } // All arguments to this call are now free to be allocated. for ( yssa_regvalue* argument : call->arguments ) { assert( argument->argof == call->op ); free_values.push( argument ); } } } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: options.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2006-06-19 20:47:38 $ * * 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 2006 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 * ************************************************************************/ #include "sal/config.h" #include "options.hxx" using svt::detail::Options; Options::Options() {} Options::~Options() {} <commit_msg>INTEGRATION: CWS pchfix02 (1.2.92); FILE MERGED 2006/09/01 17:42:49 kaib 1.2.92.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: options.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 14:27:38 $ * * 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 2006 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_svtools.hxx" #include "sal/config.h" #include "options.hxx" using svt::detail::Options; Options::Options() {} Options::~Options() {} <|endoftext|>
<commit_before>/* Generated from orogen/lib/orogen/templates/typekit/ros/Convertions.hpp */ #ifndef __OROGEN_GENERATED_<%= typekit.name.upcase %>_ROS_CONVERTIONS_HPP #define __OROGEN_GENERATED_<%= typekit.name.upcase %>_ROS_CONVERTIONS_HPP #include "Types.hpp" #include <boost/cstdint.hpp> #include <string> <% if !user_converted_types.empty? %> #include <<%= typekit.name %>/transports/ros/ROSConvertions.hpp> <% end %> <% convert_boxed_types.each do |type, ros_type| %> #include <<%= ros_message_name(ros_type, true) %>.h> <% end %> <% all_messages.each do |msg_name| %> #include <<%= typekit.name %>_msgs/<%= msg_name %>.h> <% end %> <% convert_types. find_all { |_, t| t.respond_to?(:deference) }. each do |_, ros_type| %> #include <<%= ros_message_name(ros_type.deference, true) %>.h> <% end %> <% convert_array_types.each do |_, ros_type| %> #include <<%= ros_message_name(ros_type, true) %>.h> <% end %> namespace ros_convertions { /** Converted types: */ <% convert_types.each do |type, ros_type| %> void toROS( <%= ros_ref_type(ros_type) %> ros, <%= type.arg_type %> value ); void fromROS( <%= type.ref_type %> value, <%= ros_arg_type(ros_type) %> ros ); <% end %> /** Array types: */ <% convert_array_types.each do |type, ros_type| %> void toROS( std::vector< <%= ros_cxx_type(ros_type) %> >& ros, <%= type.cxx_name%> const* value, int length ); void fromROS( <%= type.cxx_name %>* value, std::vector< <%= ros_cxx_type(ros_type) %> > const& ros, int length ); <% end %> <% convert_boxed_types.each do |type, ros_type| %> void toROS( <%= ros_ref_type(ros_type, false) %> ros, <%= type.arg_type %> value ); void fromROS( <%= type.ref_type %> value, <%= ros_arg_type(ros_type, false) %> ros ); <% end %> } #endif <commit_msg>ros: fix include generation in ros/Convertions.hpp in presence of opaques<commit_after>/* Generated from orogen/lib/orogen/templates/typekit/ros/Convertions.hpp */ #ifndef __OROGEN_GENERATED_<%= typekit.name.upcase %>_ROS_CONVERTIONS_HPP #define __OROGEN_GENERATED_<%= typekit.name.upcase %>_ROS_CONVERTIONS_HPP #include "Types.hpp" #include <boost/cstdint.hpp> #include <string> <% if !user_converted_types.empty? %> #include <<%= typekit.name %>/transports/ros/ROSConvertions.hpp> <% end %> <% convert_boxed_types.each do |type, ros_type| %> #include <<%= ros_message_name(ros_type, true) %>.h> <% end %> <% all_messages.each do |msg_name| %> #include <<%= typekit.name %>_msgs/<%= msg_name %>.h> <% end %> <% convert_types. find_all { |_, t| t.respond_to?(:deference) && (t.deference <= Typelib::CompoundType || t.deference <= Typelib::OpaqueType) }. each do |_, ros_type| %> #include <<%= ros_message_name(ros_type.deference, true) %>.h> <% end %> <% convert_array_types.each do |_, ros_type| if ros_type <= Typelib::CompoundType || ros_type <= Typelib::OpaqueType %> #include <<%= ros_message_name(ros_type, true) %>.h> <% end %> <% end %> namespace ros_convertions { /** Converted types: */ <% convert_types.each do |type, ros_type| %> void toROS( <%= ros_ref_type(ros_type) %> ros, <%= type.arg_type %> value ); void fromROS( <%= type.ref_type %> value, <%= ros_arg_type(ros_type) %> ros ); <% end %> /** Array types: */ <% convert_array_types.each do |type, ros_type| %> void toROS( std::vector< <%= ros_cxx_type(ros_type) %> >& ros, <%= type.cxx_name%> const* value, int length ); void fromROS( <%= type.cxx_name %>* value, std::vector< <%= ros_cxx_type(ros_type) %> > const& ros, int length ); <% end %> <% convert_boxed_types.each do |type, ros_type| %> void toROS( <%= ros_ref_type(ros_type, false) %> ros, <%= type.arg_type %> value ); void fromROS( <%= type.ref_type %> value, <%= ros_arg_type(ros_type, false) %> ros ); <% end %> } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: scriptinfo.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2004-09-17 14:52:19 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SCRIPTINFO_HXX #define _SCRIPTINFO_HXX #ifndef _SVSTDARR_HXX #define _SVSTDARR_SHORTS #define _SVSTDARR_BYTES #define _SVSTDARR_USHORTS #define _SVSTDARR_XUB_STRLEN #include <svtools/svstdarr.hxx> #endif #ifndef _LANG_HXX #include <tools/lang.hxx> #endif #include <list> class SwWrongList; class SwTxtNode; class Point; class MultiSelection; typedef std::list< xub_StrLen > PositionList; /************************************************************************* * class SwScanner * Hilfsklasse, die beim Spellen die Worte im gewuenschten Bereich * nacheinander zur Verfuegung stellt. *************************************************************************/ class SwScanner { XubString aWord; const SwTxtNode& rNode; xub_StrLen nStartPos; xub_StrLen nEndPos; xub_StrLen nBegin; xub_StrLen nLen; LanguageType aCurrLang; USHORT nWordType; BOOL bStart; BOOL bClip; public: SwScanner( const SwTxtNode& rNd, USHORT nWordType, xub_StrLen nStart, xub_StrLen nEnde ); // This next word function tries to find the language for the next word // It should currently _not_ be used for spell checking, and works only for // ! bReverse BOOL NextWord(); const XubString& GetWord() const { return aWord; } xub_StrLen GetBegin() const { return nBegin; } xub_StrLen GetEnd() const { return nBegin + nLen; } xub_StrLen GetLen() const { return nLen; } LanguageType GetCurrentLanguage() const {return aCurrLang;} }; /************************************************************************* * class SwScriptInfo * * encapsultes information about script changes *************************************************************************/ class SwScriptInfo { private: SvXub_StrLens aScriptChg; SvBytes aScriptType; SvXub_StrLens aDirChg; SvBytes aDirType; SvXub_StrLens aKashida; SvXub_StrLens aCompChg; SvXub_StrLens aCompLen; SvXub_StrLens aHiddenChg; SvBytes aCompType; xub_StrLen nInvalidityPos; BYTE nDefaultDir; void UpdateBidiInfo( const String& rTxt ); public: enum CompType { KANA, SPECIAL_LEFT, SPECIAL_RIGHT, NONE }; inline SwScriptInfo() : nInvalidityPos( 0 ), nDefaultDir( 0 ) {}; // determines script changes void InitScriptInfo( const SwTxtNode& rNode, sal_Bool bRTL ); void InitScriptInfo( const SwTxtNode& rNode ); // set/get position from which data is invalid inline void SetInvalidity( const xub_StrLen nPos ); inline xub_StrLen GetInvalidity() const { return nInvalidityPos; }; // get default direction for paragraph inline BYTE GetDefaultDir() const { return nDefaultDir; }; // array operations, nCnt refers to array position inline USHORT CountScriptChg() const; inline xub_StrLen GetScriptChg( const USHORT nCnt ) const; inline BYTE GetScriptType( const USHORT nCnt ) const; inline USHORT CountDirChg() const; inline xub_StrLen GetDirChg( const USHORT nCnt ) const; inline BYTE GetDirType( const USHORT nCnt ) const; inline USHORT CountKashida() const; inline xub_StrLen GetKashida( const USHORT nCnt ) const; inline USHORT CountCompChg() const; inline xub_StrLen GetCompStart( const USHORT nCnt ) const; inline xub_StrLen GetCompLen( const USHORT nCnt ) const; inline BYTE GetCompType( const USHORT nCnt ) const; inline USHORT CountHiddenChg() const; inline xub_StrLen GetHiddenChg( const USHORT nCnt ) const; static void SwScriptInfo::CalcHiddenRanges( const SwTxtNode& rNode, MultiSelection& rHiddenMulti ); // "high" level operations, nPos refers to string position xub_StrLen NextScriptChg( const xub_StrLen nPos ) const; BYTE ScriptType( const xub_StrLen nPos ) const; // Returns the position of the next direction level change. // If bLevel is set, the position of the next level which is smaller // than the level at position nPos is returned. This is required to // obtain the end of a SwBidiPortion xub_StrLen NextDirChg( const xub_StrLen nPos, const BYTE* pLevel = 0 ) const; BYTE DirType( const xub_StrLen nPos ) const; #if OSL_DEBUG_LEVEL > 1 BYTE CompType( const xub_StrLen nPos ) const; #endif // // HIDDEN TEXT STUFF START // /** Hidden text range information - static and non-version @descr Determines if a given position is inside a hidden text range. The static version tries to obtain a valid SwScriptInfo object via the SwTxtNode, otherwise it calculates the values from scratch. The non-static version uses the internally cached informatio for the calculation. @param rNode The text node. @param nPos The given position that should be checked. @param rnStartPos Return parameter for the start position of the hidden range. STRING_LEN if nPos is not inside a hidden range. @param rnEndPos Return parameter for the end position of the hidden range. 0 if nPos is not inside a hidden range. @param rnEndPos Return parameter that contains all the hidden text ranges. Optional. @return returns true if there are any hidden characters in this paragraph. */ static bool GetBoundsOfHiddenRange( const SwTxtNode& rNode, xub_StrLen nPos, xub_StrLen& rnStartPos, xub_StrLen& rnEndPos, PositionList* pList = 0 ); bool GetBoundsOfHiddenRange( xub_StrLen nPos, xub_StrLen& rnStartPos, xub_StrLen& rnEndPos, PositionList* pList = 0 ) const; static bool IsInHiddenRange( const SwTxtNode& rNode, xub_StrLen nPos ); /** Hidden text attribute handling @descr Takes a string and either deletes the hidden ranges or sets a given character in place of the hidden characters. @param rNode The text node. @param nPos The string to modify. @param cChar The character that should replace the hidden characters. @param bDel If set, the hidden ranges will be deleted from the text node. */ static USHORT MaskHiddenRanges( const SwTxtNode& rNode, XubString& rText, const xub_StrLen nStt, const xub_StrLen nEnd, const xub_Unicode cChar ); /** Hidden text attribute handling @descr Takes a SwTxtNode and deletes the hidden ranges from the node. @param rNode The text node. */ static void DeleteHiddenRanges( SwTxtNode& rNode ); // // HIDDEN TEXT STUFF END // // examines the range [ nStart, nStart + nEnd ] if there are kanas // returns start index of kana entry in array, otherwise USHRT_MAX USHORT HasKana( xub_StrLen nStart, const xub_StrLen nEnd ) const; // modifies the kerning array according to a given compress value long Compress( long* pKernArray, xub_StrLen nIdx, xub_StrLen nLen, const USHORT nCompress, const USHORT nFontHeight, Point* pPoint = NULL ) const; /** Performes a kashida justification on the kerning array @descr Add some extra space for kashida justification to the positions in the kerning array. @param pKernArray The printers kerning array. Optional. @param pScrArray The screen kerning array. Optional. @param nIdx Start referring to the paragraph. @param nLen The number of characters to be considered. @param nSpace The value which has to be added to a kashida opportunity. @return The number of kashida opportunities in the given range */ USHORT KashidaJustify( long* pKernArray ,long* pScrArray, xub_StrLen nIdx, xub_StrLen nLen, USHORT nSpace = 0 ) const; /** Checks if language is one of the 16 Arabic languages @descr Checks if language is one of the 16 Arabic languages @param aLang The language which has to be checked. @return Returns if the language is an Arabic language */ static BOOL IsArabicLanguage( LanguageType aLang ); /** Performes a thai justification on the kerning array @descr Add some extra space for thai justification to the positions in the kerning array. @param rTxt The String @param pKernArray The printers kerning array. Optional. @param pScrArray The screen kerning array. Optional. @param nIdx Start referring to the paragraph. @param nLen The number of characters to be considered. @param nSpace The value which has to be added to the cells. @return The number of extra spaces in the given range */ static USHORT ThaiJustify( const XubString& rTxt, long* pKernArray, long* pScrArray, xub_StrLen nIdx, xub_StrLen nLen, USHORT nSpace = 0 ); static SwScriptInfo* GetScriptInfo( const SwTxtNode& rNode, sal_Bool bAllowInvalid = sal_False ); static BYTE WhichFont( xub_StrLen nIdx, const String* pTxt, const SwScriptInfo* pSI ); }; inline void SwScriptInfo::SetInvalidity( const xub_StrLen nPos ) { if ( nPos < nInvalidityPos ) nInvalidityPos = nPos; }; inline USHORT SwScriptInfo::CountScriptChg() const { return aScriptChg.Count(); } inline xub_StrLen SwScriptInfo::GetScriptChg( const USHORT nCnt ) const { ASSERT( nCnt < aScriptChg.Count(),"No ScriptChange today!"); return aScriptChg[ nCnt ]; } inline BYTE SwScriptInfo::GetScriptType( const xub_StrLen nCnt ) const { ASSERT( nCnt < aScriptChg.Count(),"No ScriptType today!"); return aScriptType[ nCnt ]; } inline USHORT SwScriptInfo::CountDirChg() const { return aDirChg.Count(); } inline xub_StrLen SwScriptInfo::GetDirChg( const USHORT nCnt ) const { ASSERT( nCnt < aDirChg.Count(),"No DirChange today!"); return aDirChg[ nCnt ]; } inline BYTE SwScriptInfo::GetDirType( const xub_StrLen nCnt ) const { ASSERT( nCnt < aDirChg.Count(),"No DirType today!"); return aDirType[ nCnt ]; } inline USHORT SwScriptInfo::CountKashida() const { return aKashida.Count(); } inline xub_StrLen SwScriptInfo::GetKashida( const USHORT nCnt ) const { ASSERT( nCnt < aKashida.Count(),"No Kashidas today!"); return aKashida[ nCnt ]; } inline USHORT SwScriptInfo::CountCompChg() const { return aCompChg.Count(); }; inline xub_StrLen SwScriptInfo::GetCompStart( const USHORT nCnt ) const { ASSERT( nCnt < aCompChg.Count(),"No CompressionStart today!"); return aCompChg[ nCnt ]; } inline xub_StrLen SwScriptInfo::GetCompLen( const USHORT nCnt ) const { ASSERT( nCnt < aCompChg.Count(),"No CompressionLen today!"); return aCompLen[ nCnt ]; } inline BYTE SwScriptInfo::GetCompType( const USHORT nCnt ) const { ASSERT( nCnt < aCompChg.Count(),"No CompressionType today!"); return aCompType[ nCnt ]; } inline USHORT SwScriptInfo::CountHiddenChg() const { return aHiddenChg.Count(); }; inline xub_StrLen SwScriptInfo::GetHiddenChg( const USHORT nCnt ) const { ASSERT( nCnt < aHiddenChg.Count(),"No HiddenChg today!"); return aHiddenChg[ nCnt ]; } #endif <commit_msg>INTEGRATION: CWS os40 (1.8.32); FILE MERGED 2004/10/15 10:08:08 os 1.8.32.1: #i35015# merge error in SwScanner fixed<commit_after>/************************************************************************* * * $RCSfile: scriptinfo.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: pjunck $ $Date: 2004-10-22 13:55:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SCRIPTINFO_HXX #define _SCRIPTINFO_HXX #ifndef _SVSTDARR_HXX #define _SVSTDARR_SHORTS #define _SVSTDARR_BYTES #define _SVSTDARR_USHORTS #define _SVSTDARR_XUB_STRLEN #include <svtools/svstdarr.hxx> #endif #ifndef _LANG_HXX #include <tools/lang.hxx> #endif #include <list> class SwWrongList; class SwTxtNode; class Point; class MultiSelection; typedef std::list< xub_StrLen > PositionList; /************************************************************************* * class SwScanner * Hilfsklasse, die beim Spellen die Worte im gewuenschten Bereich * nacheinander zur Verfuegung stellt. *************************************************************************/ class SwScanner { XubString aWord; const SwTxtNode& rNode; xub_StrLen nStartPos; xub_StrLen nEndPos; xub_StrLen nBegin; xub_StrLen nLen; LanguageType aCurrLang; USHORT nWordType; BOOL bStart; BOOL bClip; public: SwScanner( const SwTxtNode& rNd, USHORT nWordType, xub_StrLen nStart, xub_StrLen nEnde, BOOL bClip = FALSE); // This next word function tries to find the language for the next word // It should currently _not_ be used for spell checking, and works only for // ! bReverse BOOL NextWord(); const XubString& GetWord() const { return aWord; } xub_StrLen GetBegin() const { return nBegin; } xub_StrLen GetEnd() const { return nBegin + nLen; } xub_StrLen GetLen() const { return nLen; } LanguageType GetCurrentLanguage() const {return aCurrLang;} }; /************************************************************************* * class SwScriptInfo * * encapsultes information about script changes *************************************************************************/ class SwScriptInfo { private: SvXub_StrLens aScriptChg; SvBytes aScriptType; SvXub_StrLens aDirChg; SvBytes aDirType; SvXub_StrLens aKashida; SvXub_StrLens aCompChg; SvXub_StrLens aCompLen; SvXub_StrLens aHiddenChg; SvBytes aCompType; xub_StrLen nInvalidityPos; BYTE nDefaultDir; void UpdateBidiInfo( const String& rTxt ); public: enum CompType { KANA, SPECIAL_LEFT, SPECIAL_RIGHT, NONE }; inline SwScriptInfo() : nInvalidityPos( 0 ), nDefaultDir( 0 ) {}; // determines script changes void InitScriptInfo( const SwTxtNode& rNode, sal_Bool bRTL ); void InitScriptInfo( const SwTxtNode& rNode ); // set/get position from which data is invalid inline void SetInvalidity( const xub_StrLen nPos ); inline xub_StrLen GetInvalidity() const { return nInvalidityPos; }; // get default direction for paragraph inline BYTE GetDefaultDir() const { return nDefaultDir; }; // array operations, nCnt refers to array position inline USHORT CountScriptChg() const; inline xub_StrLen GetScriptChg( const USHORT nCnt ) const; inline BYTE GetScriptType( const USHORT nCnt ) const; inline USHORT CountDirChg() const; inline xub_StrLen GetDirChg( const USHORT nCnt ) const; inline BYTE GetDirType( const USHORT nCnt ) const; inline USHORT CountKashida() const; inline xub_StrLen GetKashida( const USHORT nCnt ) const; inline USHORT CountCompChg() const; inline xub_StrLen GetCompStart( const USHORT nCnt ) const; inline xub_StrLen GetCompLen( const USHORT nCnt ) const; inline BYTE GetCompType( const USHORT nCnt ) const; inline USHORT CountHiddenChg() const; inline xub_StrLen GetHiddenChg( const USHORT nCnt ) const; static void SwScriptInfo::CalcHiddenRanges( const SwTxtNode& rNode, MultiSelection& rHiddenMulti ); // "high" level operations, nPos refers to string position xub_StrLen NextScriptChg( const xub_StrLen nPos ) const; BYTE ScriptType( const xub_StrLen nPos ) const; // Returns the position of the next direction level change. // If bLevel is set, the position of the next level which is smaller // than the level at position nPos is returned. This is required to // obtain the end of a SwBidiPortion xub_StrLen NextDirChg( const xub_StrLen nPos, const BYTE* pLevel = 0 ) const; BYTE DirType( const xub_StrLen nPos ) const; #if OSL_DEBUG_LEVEL > 1 BYTE CompType( const xub_StrLen nPos ) const; #endif // // HIDDEN TEXT STUFF START // /** Hidden text range information - static and non-version @descr Determines if a given position is inside a hidden text range. The static version tries to obtain a valid SwScriptInfo object via the SwTxtNode, otherwise it calculates the values from scratch. The non-static version uses the internally cached informatio for the calculation. @param rNode The text node. @param nPos The given position that should be checked. @param rnStartPos Return parameter for the start position of the hidden range. STRING_LEN if nPos is not inside a hidden range. @param rnEndPos Return parameter for the end position of the hidden range. 0 if nPos is not inside a hidden range. @param rnEndPos Return parameter that contains all the hidden text ranges. Optional. @return returns true if there are any hidden characters in this paragraph. */ static bool GetBoundsOfHiddenRange( const SwTxtNode& rNode, xub_StrLen nPos, xub_StrLen& rnStartPos, xub_StrLen& rnEndPos, PositionList* pList = 0 ); bool GetBoundsOfHiddenRange( xub_StrLen nPos, xub_StrLen& rnStartPos, xub_StrLen& rnEndPos, PositionList* pList = 0 ) const; static bool IsInHiddenRange( const SwTxtNode& rNode, xub_StrLen nPos ); /** Hidden text attribute handling @descr Takes a string and either deletes the hidden ranges or sets a given character in place of the hidden characters. @param rNode The text node. @param nPos The string to modify. @param cChar The character that should replace the hidden characters. @param bDel If set, the hidden ranges will be deleted from the text node. */ static USHORT MaskHiddenRanges( const SwTxtNode& rNode, XubString& rText, const xub_StrLen nStt, const xub_StrLen nEnd, const xub_Unicode cChar ); /** Hidden text attribute handling @descr Takes a SwTxtNode and deletes the hidden ranges from the node. @param rNode The text node. */ static void DeleteHiddenRanges( SwTxtNode& rNode ); // // HIDDEN TEXT STUFF END // // examines the range [ nStart, nStart + nEnd ] if there are kanas // returns start index of kana entry in array, otherwise USHRT_MAX USHORT HasKana( xub_StrLen nStart, const xub_StrLen nEnd ) const; // modifies the kerning array according to a given compress value long Compress( long* pKernArray, xub_StrLen nIdx, xub_StrLen nLen, const USHORT nCompress, const USHORT nFontHeight, Point* pPoint = NULL ) const; /** Performes a kashida justification on the kerning array @descr Add some extra space for kashida justification to the positions in the kerning array. @param pKernArray The printers kerning array. Optional. @param pScrArray The screen kerning array. Optional. @param nIdx Start referring to the paragraph. @param nLen The number of characters to be considered. @param nSpace The value which has to be added to a kashida opportunity. @return The number of kashida opportunities in the given range */ USHORT KashidaJustify( long* pKernArray ,long* pScrArray, xub_StrLen nIdx, xub_StrLen nLen, USHORT nSpace = 0 ) const; /** Checks if language is one of the 16 Arabic languages @descr Checks if language is one of the 16 Arabic languages @param aLang The language which has to be checked. @return Returns if the language is an Arabic language */ static BOOL IsArabicLanguage( LanguageType aLang ); /** Performes a thai justification on the kerning array @descr Add some extra space for thai justification to the positions in the kerning array. @param rTxt The String @param pKernArray The printers kerning array. Optional. @param pScrArray The screen kerning array. Optional. @param nIdx Start referring to the paragraph. @param nLen The number of characters to be considered. @param nSpace The value which has to be added to the cells. @return The number of extra spaces in the given range */ static USHORT ThaiJustify( const XubString& rTxt, long* pKernArray, long* pScrArray, xub_StrLen nIdx, xub_StrLen nLen, USHORT nSpace = 0 ); static SwScriptInfo* GetScriptInfo( const SwTxtNode& rNode, sal_Bool bAllowInvalid = sal_False ); static BYTE WhichFont( xub_StrLen nIdx, const String* pTxt, const SwScriptInfo* pSI ); }; inline void SwScriptInfo::SetInvalidity( const xub_StrLen nPos ) { if ( nPos < nInvalidityPos ) nInvalidityPos = nPos; }; inline USHORT SwScriptInfo::CountScriptChg() const { return aScriptChg.Count(); } inline xub_StrLen SwScriptInfo::GetScriptChg( const USHORT nCnt ) const { ASSERT( nCnt < aScriptChg.Count(),"No ScriptChange today!"); return aScriptChg[ nCnt ]; } inline BYTE SwScriptInfo::GetScriptType( const xub_StrLen nCnt ) const { ASSERT( nCnt < aScriptChg.Count(),"No ScriptType today!"); return aScriptType[ nCnt ]; } inline USHORT SwScriptInfo::CountDirChg() const { return aDirChg.Count(); } inline xub_StrLen SwScriptInfo::GetDirChg( const USHORT nCnt ) const { ASSERT( nCnt < aDirChg.Count(),"No DirChange today!"); return aDirChg[ nCnt ]; } inline BYTE SwScriptInfo::GetDirType( const xub_StrLen nCnt ) const { ASSERT( nCnt < aDirChg.Count(),"No DirType today!"); return aDirType[ nCnt ]; } inline USHORT SwScriptInfo::CountKashida() const { return aKashida.Count(); } inline xub_StrLen SwScriptInfo::GetKashida( const USHORT nCnt ) const { ASSERT( nCnt < aKashida.Count(),"No Kashidas today!"); return aKashida[ nCnt ]; } inline USHORT SwScriptInfo::CountCompChg() const { return aCompChg.Count(); }; inline xub_StrLen SwScriptInfo::GetCompStart( const USHORT nCnt ) const { ASSERT( nCnt < aCompChg.Count(),"No CompressionStart today!"); return aCompChg[ nCnt ]; } inline xub_StrLen SwScriptInfo::GetCompLen( const USHORT nCnt ) const { ASSERT( nCnt < aCompChg.Count(),"No CompressionLen today!"); return aCompLen[ nCnt ]; } inline BYTE SwScriptInfo::GetCompType( const USHORT nCnt ) const { ASSERT( nCnt < aCompChg.Count(),"No CompressionType today!"); return aCompType[ nCnt ]; } inline USHORT SwScriptInfo::CountHiddenChg() const { return aHiddenChg.Count(); }; inline xub_StrLen SwScriptInfo::GetHiddenChg( const USHORT nCnt ) const { ASSERT( nCnt < aHiddenChg.Count(),"No HiddenChg today!"); return aHiddenChg[ nCnt ]; } #endif <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH #define DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH #include <dune/stuff/common/disable_warnings.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/test/gtest/gtest.h> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/type_utils.hh> namespace Dune { namespace HDD { namespace LinearElliptic { namespace TestCases { // forwards template< class GridType > class ESV2007; namespace OS2014 { template< class GridType > class ParametricConvergence; } // namespace OS2014 #if HAVE_DUNE_GRID_MULTISCALE template< class GridType > class ESV2007Multiscale; namespace OS2014 { template< class GridType > class ParametricBlockConvergence; } // namespace OS2014 #endif // HAVE_DUNE_GRID_MULTISCALE } // namespace TestCases namespace Tests { namespace internal { template< class TestCaseType, int polOrder > class BlockSWIPDGStudyExpectationsBase { public: static size_t rate(const TestCaseType& /*test_case*/, const std::string type) { if (type == "L2") return polOrder + 1; else if (type == "H1_semi") return polOrder; else if (type.substr(0, 6) == "energy") return polOrder; else if (type == "eta_NC_OS2014") return polOrder; else if (type.substr(0, 12) == "eta_R_OS2014") return polOrder + 1; else if (type.substr(0, 13) == "eta_DF_OS2014") return polOrder; else if (type == "eta_OS2014") return polOrder; else if (type == "eta_OS2014_*") return polOrder; else if (type.substr(0, 10) == "eff_OS2014") return 0; else if (type.substr(0, 12) == "eff_OS2014_*") return 0; else EXPECT_TRUE(false) << "expected rate missing for type: " << type; return 0; } // ... rate(...) }; // class BlockSWIPDGStudyExpectationsBase } // namespace internal template< class TestCaseType, int polOrder = 1, bool anything = true > class BlockSWIPDGStudyExpectations : public internal::BlockSWIPDGStudyExpectationsBase< TestCaseType, polOrder > { public: static std::vector< double > results(const TestCaseType& /*test_case*/, const std::string type) { EXPECT_TRUE(false) << "Please record the expected results for\n" << "TestCaseType: " << Stuff::Common::Typename< TestCaseType >::value() << "\n" << "polOrder: " << polOrder << "\n" << "type: " << type << "\n" << "Please put an appropriate specialiaztion of BlockSWIPDGStudyExpectations for this TestCaseType " << "in a separate object file (see examples below) or add\n" << " 'template class BlockSWIPDGStudyExpectations< TestCaseType, " << polOrder << " >'\n" << "for this polOrder in the appropriate object file!\n\n" << "Oh: and do not forget to add\n" << " 'extern template class BlockSWIPDGStudyExpectations< ... >'\n" << "to each test source using these results!"; return {}; } // ... results(...) }; // BlockSWIPDGStudyExpectations } // namespace Tests } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH <commit_msg>[test...block-swipdg-expectations] update rates<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH #define DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH #include <dune/stuff/common/disable_warnings.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/test/gtest/gtest.h> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/type_utils.hh> namespace Dune { namespace HDD { namespace LinearElliptic { namespace TestCases { // forwards template< class GridType > class ESV2007; namespace OS2014 { template< class GridType > class ParametricConvergence; } // namespace OS2014 #if HAVE_DUNE_GRID_MULTISCALE template< class GridType > class ESV2007Multiscale; namespace OS2014 { template< class GridType > class ParametricBlockConvergence; } // namespace OS2014 #endif // HAVE_DUNE_GRID_MULTISCALE } // namespace TestCases namespace Tests { namespace internal { template< class TestCaseType, int polOrder > class BlockSWIPDGStudyExpectationsBase { public: static size_t rate(const TestCaseType& test_case, const std::string type) { const auto partitioning = test_case.partitioning(); if (type == "L2") return polOrder + 1; else if (type == "H1_semi" || type.substr(0, 6) == "energy") return polOrder; else if (type == "eta_NC_OS2014") return polOrder; else if (type.substr(0, 12) == "eta_R_OS2014") { if (partitioning.size() >= 8 && partitioning.substr(partitioning.size() - 8) == "H_with_h") return polOrder + 1; else return polOrder; } else if (type.substr(0, 13) == "eta_DF_OS2014") return polOrder; else if (type.substr(0, 10) == "eta_OS2014") return polOrder; else if (type.substr(0, 10) == "eff_OS2014") return 0; else EXPECT_TRUE(false) << "expected rate missing for type: " << type; return 0; } // ... rate(...) }; // class BlockSWIPDGStudyExpectationsBase } // namespace internal template< class TestCaseType, int polOrder = 1, bool anything = true > class BlockSWIPDGStudyExpectations : public internal::BlockSWIPDGStudyExpectationsBase< TestCaseType, polOrder > { public: static std::vector< double > results(const TestCaseType& /*test_case*/, const std::string type) { EXPECT_TRUE(false) << "Please record the expected results for\n" << "TestCaseType: " << Stuff::Common::Typename< TestCaseType >::value() << "\n" << "polOrder: " << polOrder << "\n" << "type: " << type << "\n" << "Please put an appropriate specialiaztion of BlockSWIPDGStudyExpectations for this TestCaseType " << "in a separate object file (see examples below) or add\n" << " 'template class BlockSWIPDGStudyExpectations< TestCaseType, " << polOrder << " >'\n" << "for this polOrder in the appropriate object file!\n\n" << "Oh: and do not forget to add\n" << " 'extern template class BlockSWIPDGStudyExpectations< ... >'\n" << "to each test source using these results!"; return {}; } // ... results(...) }; // BlockSWIPDGStudyExpectations } // namespace Tests } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #define KBDD #ifdef WIN32 #include "condor_daemon_core.h" #include "condor_debug.h" #include "condor_uid.h" #else #include "XInterface.h" #endif #include "my_hostname.h" #include "condor_query.h" #include "daemon.h" #include "subsystem_info.h" #ifdef WIN32 #include <windows.h> #else #include <utmp.h> #include <sys/file.h> #include <netinet/in.h> #include <rpc/types.h> #include <X11/Xlib.h> XInterface *xinter = NULL; #endif DECL_SUBSYSTEM( "KBDD", SUBSYSTEM_TYPE_DAEMON ); bool update_startd() { static SafeSock ssock; static bool first_time = true; static Daemon startd( DT_STARTD ); if( first_time ) { if( ! startd.locate() ) { dprintf( D_ALWAYS, "Can't locate startd, aborting (%s)\n", startd.error() ); return false; } if( !ssock.connect(startd.addr(), 0) ) { dprintf( D_ALWAYS, "Can't connect to startd at: %s, " "aborting\n", startd.addr() ); return false; } first_time = false; } if( !startd.sendCommand(X_EVENT_NOTIFICATION, &ssock, 3) ) { dprintf( D_ALWAYS, "Can't send X_EVENT_NOTIFICATION command " "to startd at: %s, aborting\n", startd.addr() ); return false; } dprintf( D_FULLDEBUG, "Sent update to startd at: %s\n", startd.addr() ); return true; } int PollActivity() { #ifdef WIN32 LASTINPUTINFO lii; static POINT previous_pos = { 0, 0 }; static DWORD previous_input_tick = 0; lii.cbSize = sizeof(LASTINPUTINFO); lii.dwTime = 0; if ( !GetLastInputInfo(&lii) ) { dprintf(D_ALWAYS, "PollActivity: GetLastInputInfo()" " failed with err=%d\n", GetLastError()); } else { //Check if there has been new keyboard input since the last check. if(lii.dwTime > previous_input_tick) { previous_input_tick = lii.dwTime; update_startd(); } return TRUE; } //If no change to keyboard input, check if mouse has been moved. CURSORINFO cursor_inf; cursor_inf.cbSize = sizeof(CURSORINFO); if (!GetCursorInfo(&cursor_inf)) { dprintf(D_ALWAYS,"GetCursorInfo() failed (err=%li)\n", GetLastError()); } else { if ((cursor_inf.ptScreenPos.x != previous_pos.x) || (cursor_inf.ptScreenPos.y != previous_pos.y)) { // the mouse has moved! // stash new position previous_pos.x = cursor_inf.ptScreenPos.x; previous_pos.y = cursor_inf.ptScreenPos.y; previous_input_tick = GetTickCount(); update_startd(); } } return TRUE; #else if(xinter != NULL) { if(xinter->CheckActivity()) { update_startd(); } } return TRUE; #endif } int main_shutdown_graceful() { #ifndef WIN32 delete xinter; #endif DC_Exit(EXIT_SUCCESS); return TRUE; } int main_shutdown_fast() { DC_Exit(EXIT_SUCCESS); return TRUE; } int main_config( bool is_full ) { return TRUE; } int main_init(int, char *[]) { #ifndef WIN32 xinter = NULL; #endif //Poll for X activity every second. int id = daemonCore->Register_Timer(5, 5, (Event)PollActivity, "PollActivity"); #ifndef WIN32 xinter = new XInterface(id); #endif return TRUE; } void main_pre_dc_init( int, char*[] ) { } void main_pre_command_sock_init( ) { } #ifdef WIN32 int WINAPI WinMain( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd ) { #ifdef WIN32 // t1031 - tell dprintf not to exit if it can't write to the log // we have to do this before dprintf_config is called // (which happens inside dc_main), otherwise KBDD on Win32 will // except in dprintf_config if the log directory isn't writable // by the current user. dprintf_config_ContinueOnFailure( TRUE ); #endif // cons up a "standard" argv for dc_main. char **parameters = (char**)malloc(sizeof(char*)*2); parameters[0] = "condor_kbdd"; parameters[1] = NULL; dc_main(1, parameters); // dc_main should exit() so we probably never get here. return 0; } #endif <commit_msg>pass command line arguments into dc_main (it was broken in Win32 kbdd) #1576<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #define KBDD #ifdef WIN32 #include "condor_daemon_core.h" #include "condor_debug.h" #include "condor_uid.h" #else #include "XInterface.h" #endif #include "my_hostname.h" #include "condor_query.h" #include "daemon.h" #include "subsystem_info.h" #ifdef WIN32 #include <windows.h> #else #include <utmp.h> #include <sys/file.h> #include <netinet/in.h> #include <rpc/types.h> #include <X11/Xlib.h> XInterface *xinter = NULL; #endif DECL_SUBSYSTEM( "KBDD", SUBSYSTEM_TYPE_DAEMON ); bool update_startd() { static SafeSock ssock; static bool first_time = true; static Daemon startd( DT_STARTD ); if( first_time ) { if( ! startd.locate() ) { dprintf( D_ALWAYS, "Can't locate startd, aborting (%s)\n", startd.error() ); return false; } if( !ssock.connect(startd.addr(), 0) ) { dprintf( D_ALWAYS, "Can't connect to startd at: %s, " "aborting\n", startd.addr() ); return false; } first_time = false; } if( !startd.sendCommand(X_EVENT_NOTIFICATION, &ssock, 3) ) { dprintf( D_ALWAYS, "Can't send X_EVENT_NOTIFICATION command " "to startd at: %s, aborting\n", startd.addr() ); return false; } dprintf( D_FULLDEBUG, "Sent update to startd at: %s\n", startd.addr() ); return true; } int PollActivity() { #ifdef WIN32 LASTINPUTINFO lii; static POINT previous_pos = { 0, 0 }; static DWORD previous_input_tick = 0; lii.cbSize = sizeof(LASTINPUTINFO); lii.dwTime = 0; if ( !GetLastInputInfo(&lii) ) { dprintf(D_ALWAYS, "PollActivity: GetLastInputInfo()" " failed with err=%d\n", GetLastError()); } else { //Check if there has been new keyboard input since the last check. if(lii.dwTime > previous_input_tick) { previous_input_tick = lii.dwTime; update_startd(); } return TRUE; } //If no change to keyboard input, check if mouse has been moved. CURSORINFO cursor_inf; cursor_inf.cbSize = sizeof(CURSORINFO); if (!GetCursorInfo(&cursor_inf)) { dprintf(D_ALWAYS,"GetCursorInfo() failed (err=%li)\n", GetLastError()); } else { if ((cursor_inf.ptScreenPos.x != previous_pos.x) || (cursor_inf.ptScreenPos.y != previous_pos.y)) { // the mouse has moved! // stash new position previous_pos.x = cursor_inf.ptScreenPos.x; previous_pos.y = cursor_inf.ptScreenPos.y; previous_input_tick = GetTickCount(); update_startd(); } } return TRUE; #else if(xinter != NULL) { if(xinter->CheckActivity()) { update_startd(); } } return TRUE; #endif } int main_shutdown_graceful() { #ifndef WIN32 delete xinter; #endif DC_Exit(EXIT_SUCCESS); return TRUE; } int main_shutdown_fast() { DC_Exit(EXIT_SUCCESS); return TRUE; } int main_config( bool is_full ) { return TRUE; } int main_init(int, char *[]) { #ifndef WIN32 xinter = NULL; #endif //Poll for X activity every second. int id = daemonCore->Register_Timer(5, 5, (Event)PollActivity, "PollActivity"); #ifndef WIN32 xinter = new XInterface(id); #endif return TRUE; } void main_pre_dc_init( int, char*[] ) { } void main_pre_command_sock_init( ) { } #ifdef WIN32 int WINAPI WinMain( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd ) { #ifdef WIN32 // t1031 - tell dprintf not to exit if it can't write to the log // we have to do this before dprintf_config is called // (which happens inside dc_main), otherwise KBDD on Win32 will // except in dprintf_config if the log directory isn't writable // by the current user. dprintf_config_ContinueOnFailure( TRUE ); #endif // cons up a "standard" argv for dc_main. char **parameters; LPWSTR cmdLine = NULL; LPWSTR* cmdArgs = NULL; int nArgs; /* Due to the risk of spaces in paths on Windows, we use the function CommandLineToArgvW to extract a list of arguments instead of parsing the string using a delimiter. */ cmdLine = GetCommandLineW(); if(!cmdLine) { return GetLastError(); } cmdArgs = CommandLineToArgvW(cmdLine, &nArgs); if(!cmdArgs) { return GetLastError(); } parameters = (char**)malloc(sizeof(char*)*nArgs + 1); parameters[0] = "condor_kbdd"; parameters[nArgs] = NULL; /* List of strings is in unicode so we need to downconvert it into ascii strings. */ for(int counter = 1; counter < nArgs; ++counter) { //There's a *2 on the size to provide some leeway for non-ascii characters being split. Suggested by TJ. int argSize = ((wcslen(cmdArgs[counter]) + 1) * sizeof(char)) * 2; parameters[counter] = (char*)malloc(argSize); int converted = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, cmdArgs[counter], -1, parameters[counter], argSize, NULL, NULL); if(converted == 0) { return GetLastError(); } } LocalFree((HLOCAL)cmdLine); LocalFree((HLOCAL)cmdArgs); //nArgs includes the first argument, the program name, in the count. dc_main(nArgs, parameters); // dc_main should exit() so we probably never get here. return 0; } #endif <|endoftext|>
<commit_before>#include "ConfigShardServer.h" QuorumInfo::QuorumInfo() { quorumID = 0; paxosID = 0; needCatchup = false; unused1 = 0; unused2 = 0; unused3 = 0; } bool QuorumInfo::ReadList(ReadBuffer& buffer, List<QuorumInfo>& quorumInfos) { unsigned i, length; int read; QuorumInfo quorumInfo; read = buffer.Readf("%u", &length); if (read < 1) return false; buffer.Advance(read); for (i = 0; i < length; i++) { read = buffer.Readf(":%U:%U:%b:%U:%U:%U", &quorumInfo.quorumID, &quorumInfo.paxosID, &quorumInfo.needCatchup, &quorumInfo.unused1, &quorumInfo.unused2, &quorumInfo.unused3); if (read < 4) return false; buffer.Advance(read); quorumInfos.Append(quorumInfo); } return true; } bool QuorumInfo::WriteList(Buffer& buffer, List<QuorumInfo>& quorumInfos) { QuorumInfo* it; buffer.Appendf("%u", quorumInfos.GetLength()); FOREACH (it, quorumInfos) { buffer.Appendf(":%U:%U:%b:%U:%U:%U", it->quorumID, it->paxosID, it->needCatchup, it->unused1, it->unused2, it->unused3); } return true; } QuorumInfo* QuorumInfo::GetQuorumInfo(List<QuorumInfo>& quorumInfos, uint64_t quorumID) { QuorumInfo* it; FOREACH (it, quorumInfos) { if (it->quorumID == quorumID) return it; } return NULL; } QuorumShardInfo::QuorumShardInfo() { quorumID = 0; shardID = 0; shardSize = 0; isSendingShard = false; migrationNodeID = 0; migrationQuorumID = 0; migrationBytesSent = 0; migrationBytesTotal = 0; migrationThroughput = 0; } bool QuorumShardInfo::ReadList(ReadBuffer& buffer, List<QuorumShardInfo>& quorumShardInfos) { unsigned i, length; int read; QuorumShardInfo quorumShardInfo; read = buffer.Readf("%u", &length); if (read < 1) return false; buffer.Advance(read); for (i = 0; i < length; i++) { read = buffer.Readf(":%U:%U:%U:%#B:%b:%b:%U:%U:%U:%U:%U", &quorumShardInfo.quorumID, &quorumShardInfo.shardID, &quorumShardInfo.shardSize, &quorumShardInfo.splitKey, &quorumShardInfo.isSplitable, &quorumShardInfo.isSendingShard, &quorumShardInfo.migrationQuorumID, &quorumShardInfo.migrationNodeID, &quorumShardInfo.migrationBytesSent, &quorumShardInfo.migrationBytesTotal, &quorumShardInfo.migrationThroughput); if (read < 6) return false; buffer.Advance(read); quorumShardInfos.Append(quorumShardInfo); } return true; } bool QuorumShardInfo::WriteList(Buffer& buffer, List<QuorumShardInfo>& quorumShardInfos) { QuorumShardInfo* it; buffer.Appendf("%u", quorumShardInfos.GetLength()); FOREACH (it, quorumShardInfos) { buffer.Appendf(":%U:%U:%U:%#B:%b:%b:%U:%U:%U:%U:%U", it->quorumID, it->shardID, it->shardSize, &it->splitKey, it->isSplitable, it->isSendingShard, it->migrationQuorumID, it->migrationNodeID, it->migrationBytesSent, it->migrationBytesTotal, it->migrationThroughput); } return true; } QuorumPriority::QuorumPriority() { quorumID = 0; priority = 0; } ConfigShardServer::ConfigShardServer() { prev = next = this; nodeID = 0; activationPhase = 0; nextActivationTime = 0; httpPort = 0; sdbpPort = 0; hasHeartbeat = false; } ConfigShardServer::ConfigShardServer(const ConfigShardServer& other) { *this = other; } ConfigShardServer& ConfigShardServer::operator=(const ConfigShardServer& other) { nodeID = other.nodeID; activationPhase = other.activationPhase; endpoint = other.endpoint; httpPort = other.httpPort; sdbpPort = other.sdbpPort; hasHeartbeat = other.hasHeartbeat; quorumInfos = other.quorumInfos; quorumShardInfos = other.quorumShardInfos; quorumPriorities = other.quorumPriorities; prev = next = this; return *this; } uint64_t ConfigShardServer::GetQuorumPriority(uint64_t quorumID) { QuorumPriority* quorumPriority; FOREACH(quorumPriority, quorumPriorities) { if (quorumPriority->quorumID == quorumID) return quorumPriority->priority; } return 1; } <commit_msg>Fixed missing variable from operator=.<commit_after>#include "ConfigShardServer.h" QuorumInfo::QuorumInfo() { quorumID = 0; paxosID = 0; needCatchup = false; unused1 = 0; unused2 = 0; unused3 = 0; } bool QuorumInfo::ReadList(ReadBuffer& buffer, List<QuorumInfo>& quorumInfos) { unsigned i, length; int read; QuorumInfo quorumInfo; read = buffer.Readf("%u", &length); if (read < 1) return false; buffer.Advance(read); for (i = 0; i < length; i++) { read = buffer.Readf(":%U:%U:%b:%U:%U:%U", &quorumInfo.quorumID, &quorumInfo.paxosID, &quorumInfo.needCatchup, &quorumInfo.unused1, &quorumInfo.unused2, &quorumInfo.unused3); if (read < 4) return false; buffer.Advance(read); quorumInfos.Append(quorumInfo); } return true; } bool QuorumInfo::WriteList(Buffer& buffer, List<QuorumInfo>& quorumInfos) { QuorumInfo* it; buffer.Appendf("%u", quorumInfos.GetLength()); FOREACH (it, quorumInfos) { buffer.Appendf(":%U:%U:%b:%U:%U:%U", it->quorumID, it->paxosID, it->needCatchup, it->unused1, it->unused2, it->unused3); } return true; } QuorumInfo* QuorumInfo::GetQuorumInfo(List<QuorumInfo>& quorumInfos, uint64_t quorumID) { QuorumInfo* it; FOREACH (it, quorumInfos) { if (it->quorumID == quorumID) return it; } return NULL; } QuorumShardInfo::QuorumShardInfo() { quorumID = 0; shardID = 0; shardSize = 0; isSendingShard = false; migrationNodeID = 0; migrationQuorumID = 0; migrationBytesSent = 0; migrationBytesTotal = 0; migrationThroughput = 0; } bool QuorumShardInfo::ReadList(ReadBuffer& buffer, List<QuorumShardInfo>& quorumShardInfos) { unsigned i, length; int read; QuorumShardInfo quorumShardInfo; read = buffer.Readf("%u", &length); if (read < 1) return false; buffer.Advance(read); for (i = 0; i < length; i++) { read = buffer.Readf(":%U:%U:%U:%#B:%b:%b:%U:%U:%U:%U:%U", &quorumShardInfo.quorumID, &quorumShardInfo.shardID, &quorumShardInfo.shardSize, &quorumShardInfo.splitKey, &quorumShardInfo.isSplitable, &quorumShardInfo.isSendingShard, &quorumShardInfo.migrationQuorumID, &quorumShardInfo.migrationNodeID, &quorumShardInfo.migrationBytesSent, &quorumShardInfo.migrationBytesTotal, &quorumShardInfo.migrationThroughput); if (read < 6) return false; buffer.Advance(read); quorumShardInfos.Append(quorumShardInfo); } return true; } bool QuorumShardInfo::WriteList(Buffer& buffer, List<QuorumShardInfo>& quorumShardInfos) { QuorumShardInfo* it; buffer.Appendf("%u", quorumShardInfos.GetLength()); FOREACH (it, quorumShardInfos) { buffer.Appendf(":%U:%U:%U:%#B:%b:%b:%U:%U:%U:%U:%U", it->quorumID, it->shardID, it->shardSize, &it->splitKey, it->isSplitable, it->isSendingShard, it->migrationQuorumID, it->migrationNodeID, it->migrationBytesSent, it->migrationBytesTotal, it->migrationThroughput); } return true; } QuorumPriority::QuorumPriority() { quorumID = 0; priority = 0; } ConfigShardServer::ConfigShardServer() { prev = next = this; nodeID = 0; activationPhase = 0; nextActivationTime = 0; httpPort = 0; sdbpPort = 0; hasHeartbeat = false; } ConfigShardServer::ConfigShardServer(const ConfigShardServer& other) { *this = other; } ConfigShardServer& ConfigShardServer::operator=(const ConfigShardServer& other) { nodeID = other.nodeID; activationPhase = other.activationPhase; nextActivationTime = other.nextActivationTime; endpoint = other.endpoint; httpPort = other.httpPort; sdbpPort = other.sdbpPort; hasHeartbeat = other.hasHeartbeat; quorumInfos = other.quorumInfos; quorumShardInfos = other.quorumShardInfos; quorumPriorities = other.quorumPriorities; prev = next = this; return *this; } uint64_t ConfigShardServer::GetQuorumPriority(uint64_t quorumID) { QuorumPriority* quorumPriority; FOREACH(quorumPriority, quorumPriorities) { if (quorumPriority->quorumID == quorumID) return quorumPriority->priority; } return 1; } <|endoftext|>
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <libtorrent/ip_filter.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } void outgoing_ports(session& s, int _min, int _max) { allow_threading_guard guard; session_settings settings = s.settings(); settings.outgoing_ports = std::make_pair(_min, _max); s.set_settings(settings); return; } #ifndef TORRENT_DISABLE_DHT void add_dht_router(session& s, std::string router_, int port_) { allow_threading_guard guard; return s.add_dht_router(std::make_pair(router_, port_)); } #endif struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } #ifndef TORRENT_NO_DEPRECATE torrent_handle add_torrent_depr(session& s, torrent_info const& ti , boost::filesystem::path const& save, entry const& resume , storage_mode_t storage_mode, bool paused) { allow_threading_guard guard; return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor); } #endif torrent_handle add_torrent(session& s, dict params) { add_torrent_params p; if (params.has_key("ti")) p.ti = new torrent_info(extract<torrent_info const&>(params["ti"])); std::string url; if (params.has_key("tracker_url")) { url = extract<std::string>(params["tracker_url"]); p.tracker_url = url.c_str(); } if (params.has_key("info_hash")) p.info_hash = extract<sha1_hash>(params["info_hash"]); std::string name; if (params.has_key("name")) { name = extract<std::string>(params["name"]); p.name = name.c_str(); } p.save_path = fs::path(extract<std::string>(params["save_path"])); std::vector<char> resume_buf; if (params.has_key("resume_data")) { std::string resume = extract<std::string>(params["resume_data"]); resume_buf.resize(resume.size()); std::memcpy(&resume_buf[0], &resume[0], resume.size()); p.resume_data = &resume_buf; } if (params.has_key("storage_mode")) p.storage_mode = extract<storage_mode_t>(params["storage_mode"]); if (params.has_key("paused")) p.paused = params["paused"]; if (params.has_key("auto_managed")) p.auto_managed = params["auto_managed"]; if (params.has_key("duplicate_is_error")) p.duplicate_is_error = params["duplicate_is_error"]; if (params.has_key("seed_mode")) p.seed_mode = params["seed_mode"]; if (params.has_key("override_resume_data")) p.override_resume_data = params["override_resume_data"]; return s.add_torrent(p); } void start_natpmp(session& s) { allow_threading_guard guard; s.start_natpmp(); return; } void start_upnp(session& s) { allow_threading_guard guard; s.start_upnp(); return; } list get_torrents(session& s) { list ret; std::vector<torrent_handle> torrents = s.get_torrents(); for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i) { ret.append(*i); } return ret; } #ifndef TORRENT_DISABLE_GEO_IP bool load_asnum_db(session& s, std::string file) { allow_threading_guard guard; return s.load_asnum_db(file.c_str()); } bool load_country_db(session& s, std::string file) { allow_threading_guard guard; return s.load_country_db(file.c_str()); } #endif } // namespace unnamed void bind_session() { class_<session_status>("session_status") .def_readonly("has_incoming_connections", &session_status::has_incoming_connections) .def_readonly("upload_rate", &session_status::upload_rate) .def_readonly("download_rate", &session_status::download_rate) .def_readonly("total_download", &session_status::total_download) .def_readonly("total_upload", &session_status::total_upload) .def_readonly("payload_upload_rate", &session_status::payload_upload_rate) .def_readonly("payload_download_rate", &session_status::payload_download_rate) .def_readonly("total_payload_download", &session_status::total_payload_download) .def_readonly("total_payload_upload", &session_status::total_payload_upload) .def_readonly("ip_overhead_upload_rate", &session_status::ip_overhead_upload_rate) .def_readonly("ip_overhead_download_rate", &session_status::ip_overhead_download_rate) .def_readonly("total_ip_overhead_download", &session_status::total_ip_overhead_download) .def_readonly("total_ip_overhead_upload", &session_status::total_ip_overhead_upload) .def_readonly("dht_upload_rate", &session_status::dht_upload_rate) .def_readonly("dht_download_rate", &session_status::dht_download_rate) .def_readonly("total_dht_download", &session_status::total_dht_download) .def_readonly("total_dht_upload", &session_status::total_dht_upload) .def_readonly("tracker_upload_rate", &session_status::tracker_upload_rate) .def_readonly("tracker_download_rate", &session_status::tracker_download_rate) .def_readonly("total_tracker_download", &session_status::total_tracker_download) .def_readonly("total_tracker_upload", &session_status::total_tracker_upload) .def_readonly("total_redundant_bytes", &session_status::total_redundant_bytes) .def_readonly("total_failed_bytes", &session_status::total_failed_bytes) .def_readonly("num_peers", &session_status::num_peers) .def_readonly("num_unchoked", &session_status::num_unchoked) .def_readonly("allowed_upload_slots", &session_status::allowed_upload_slots) .def_readonly("up_bandwidth_queue", &session_status::up_bandwidth_queue) .def_readonly("down_bandwidth_queue", &session_status::down_bandwidth_queue) .def_readonly("up_bandwidth_bytes_queue", &session_status::up_bandwidth_bytes_queue) .def_readonly("down_bandwidth_bytes_queue", &session_status::down_bandwidth_bytes_queue) .def_readonly("optimistic_unchoke_counter", &session_status::optimistic_unchoke_counter) .def_readonly("unchoke_counter", &session_status::unchoke_counter) #ifndef TORRENT_DISABLE_DHT .def_readonly("dht_nodes", &session_status::dht_nodes) .def_readonly("dht_cache_nodes", &session_status::dht_node_cache) .def_readonly("dht_torrents", &session_status::dht_torrents) .def_readonly("dht_global_nodes", &session_status::dht_global_nodes) .def_readonly("active_requests", &session_status::active_requests) #endif ; class_<dht_lookup>("dht_lookup") .def_readonly("type", &dht_lookup::type) .def_readonly("outstanding_requests", &dht_lookup::outstanding_requests) .def_readonly("timeouts", &dht_lookup::timeouts) .def_readonly("response", &dht_lookup::responses) .def_readonly("branch_factor", &dht_lookup::branch_factor) ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_sparse", storage_mode_sparse) .value("storage_mode_compact", storage_mode_compact) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; enum_<session::session_flags_t>("session_flags_t") .value("add_default_plugins", session::add_default_plugins) .value("start_default_features", session::start_default_features) ; class_<session, boost::noncopyable>("session", no_init) .def( init<fingerprint, int>(( arg("fingerprint")=fingerprint("LT",0,1,0,0) , arg("flags")=session::start_default_features | session::add_default_plugins)) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) ) .def("outgoing_ports", &outgoing_ports) .def("is_listening", allow_threads(&session::is_listening)) .def("listen_port", allow_threads(&session::listen_port)) .def("status", allow_threads(&session::status)) #ifndef TORRENT_DISABLE_DHT .def( "add_dht_router", &add_dht_router , (arg("router"), "port") ) .def("start_dht", allow_threads(&session::start_dht)) .def("stop_dht", allow_threads(&session::stop_dht)) .def("dht_state", allow_threads(&session::dht_state)) .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) .def("dht_proxy", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>()) #endif .def("add_torrent", &add_torrent) #ifndef TORRENT_NO_DEPRECATE .def( "add_torrent", &add_torrent_depr , ( arg("resume_data") = entry(), arg("storage_mode") = storage_mode_sparse, arg("paused") = false ) ) #endif .def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none ) .def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit)) .def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit)) .def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit)) .def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit)) .def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit)) .def("download_rate_limit", allow_threads(&session::download_rate_limit)) .def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)) .def("upload_rate_limit", allow_threads(&session::upload_rate_limit)) .def("set_max_uploads", allow_threads(&session::set_max_uploads)) .def("set_max_connections", allow_threads(&session::set_max_connections)) .def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)) .def("num_connections", allow_threads(&session::num_connections)) .def("set_settings", allow_threads(&session::set_settings)) .def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>()) #ifndef TORRENT_DISABLE_ENCRYPTION .def("set_pe_settings", allow_threads(&session::set_pe_settings)) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) #endif #ifndef TORRENT_DISABLE_GEO_IP .def("load_asnum_db", &load_asnum_db) .def("load_country_db", &load_country_db) #endif .def("load_state", allow_threads(&session::load_state)) .def("state", allow_threads(&session::state)) #ifndef TORRENT_NO_DEPRECATE .def("set_severity_level", allow_threads(&session::set_severity_level)) #endif .def("set_alert_mask", allow_threads(&session::set_alert_mask)) .def("pop_alert", allow_threads(&session::pop_alert)) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) .def("peer_proxy", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>()) .def("tracker_proxy", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>()) .def("web_seed_proxy", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>()) .def("start_upnp", &start_upnp) .def("stop_upnp", allow_threads(&session::stop_upnp)) .def("start_lsd", allow_threads(&session::start_lsd)) .def("stop_lsd", allow_threads(&session::stop_lsd)) .def("start_natpmp", &start_natpmp) .def("stop_natpmp", allow_threads(&session::stop_natpmp)) .def("set_ip_filter", allow_threads(&session::set_ip_filter)) .def("find_torrent", allow_threads(&session::find_torrent)) .def("get_torrents", &get_torrents) .def("pause", allow_threads(&session::pause)) .def("resume", allow_threads(&session::resume)) .def("is_paused", allow_threads(&session::is_paused)) .def("id", allow_threads(&session::id)) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <commit_msg>Add session.get_cache_status() to the python bindings<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <libtorrent/ip_filter.hpp> #include <libtorrent/disk_io_thread.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } void outgoing_ports(session& s, int _min, int _max) { allow_threading_guard guard; session_settings settings = s.settings(); settings.outgoing_ports = std::make_pair(_min, _max); s.set_settings(settings); return; } #ifndef TORRENT_DISABLE_DHT void add_dht_router(session& s, std::string router_, int port_) { allow_threading_guard guard; return s.add_dht_router(std::make_pair(router_, port_)); } #endif struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } #ifndef TORRENT_NO_DEPRECATE torrent_handle add_torrent_depr(session& s, torrent_info const& ti , boost::filesystem::path const& save, entry const& resume , storage_mode_t storage_mode, bool paused) { allow_threading_guard guard; return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor); } #endif torrent_handle add_torrent(session& s, dict params) { add_torrent_params p; if (params.has_key("ti")) p.ti = new torrent_info(extract<torrent_info const&>(params["ti"])); std::string url; if (params.has_key("tracker_url")) { url = extract<std::string>(params["tracker_url"]); p.tracker_url = url.c_str(); } if (params.has_key("info_hash")) p.info_hash = extract<sha1_hash>(params["info_hash"]); std::string name; if (params.has_key("name")) { name = extract<std::string>(params["name"]); p.name = name.c_str(); } p.save_path = fs::path(extract<std::string>(params["save_path"])); std::vector<char> resume_buf; if (params.has_key("resume_data")) { std::string resume = extract<std::string>(params["resume_data"]); resume_buf.resize(resume.size()); std::memcpy(&resume_buf[0], &resume[0], resume.size()); p.resume_data = &resume_buf; } if (params.has_key("storage_mode")) p.storage_mode = extract<storage_mode_t>(params["storage_mode"]); if (params.has_key("paused")) p.paused = params["paused"]; if (params.has_key("auto_managed")) p.auto_managed = params["auto_managed"]; if (params.has_key("duplicate_is_error")) p.duplicate_is_error = params["duplicate_is_error"]; if (params.has_key("seed_mode")) p.seed_mode = params["seed_mode"]; if (params.has_key("override_resume_data")) p.override_resume_data = params["override_resume_data"]; return s.add_torrent(p); } void start_natpmp(session& s) { allow_threading_guard guard; s.start_natpmp(); return; } void start_upnp(session& s) { allow_threading_guard guard; s.start_upnp(); return; } list get_torrents(session& s) { list ret; std::vector<torrent_handle> torrents = s.get_torrents(); for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i) { ret.append(*i); } return ret; } #ifndef TORRENT_DISABLE_GEO_IP bool load_asnum_db(session& s, std::string file) { allow_threading_guard guard; return s.load_asnum_db(file.c_str()); } bool load_country_db(session& s, std::string file) { allow_threading_guard guard; return s.load_country_db(file.c_str()); } #endif } // namespace unnamed void bind_session() { class_<session_status>("session_status") .def_readonly("has_incoming_connections", &session_status::has_incoming_connections) .def_readonly("upload_rate", &session_status::upload_rate) .def_readonly("download_rate", &session_status::download_rate) .def_readonly("total_download", &session_status::total_download) .def_readonly("total_upload", &session_status::total_upload) .def_readonly("payload_upload_rate", &session_status::payload_upload_rate) .def_readonly("payload_download_rate", &session_status::payload_download_rate) .def_readonly("total_payload_download", &session_status::total_payload_download) .def_readonly("total_payload_upload", &session_status::total_payload_upload) .def_readonly("ip_overhead_upload_rate", &session_status::ip_overhead_upload_rate) .def_readonly("ip_overhead_download_rate", &session_status::ip_overhead_download_rate) .def_readonly("total_ip_overhead_download", &session_status::total_ip_overhead_download) .def_readonly("total_ip_overhead_upload", &session_status::total_ip_overhead_upload) .def_readonly("dht_upload_rate", &session_status::dht_upload_rate) .def_readonly("dht_download_rate", &session_status::dht_download_rate) .def_readonly("total_dht_download", &session_status::total_dht_download) .def_readonly("total_dht_upload", &session_status::total_dht_upload) .def_readonly("tracker_upload_rate", &session_status::tracker_upload_rate) .def_readonly("tracker_download_rate", &session_status::tracker_download_rate) .def_readonly("total_tracker_download", &session_status::total_tracker_download) .def_readonly("total_tracker_upload", &session_status::total_tracker_upload) .def_readonly("total_redundant_bytes", &session_status::total_redundant_bytes) .def_readonly("total_failed_bytes", &session_status::total_failed_bytes) .def_readonly("num_peers", &session_status::num_peers) .def_readonly("num_unchoked", &session_status::num_unchoked) .def_readonly("allowed_upload_slots", &session_status::allowed_upload_slots) .def_readonly("up_bandwidth_queue", &session_status::up_bandwidth_queue) .def_readonly("down_bandwidth_queue", &session_status::down_bandwidth_queue) .def_readonly("up_bandwidth_bytes_queue", &session_status::up_bandwidth_bytes_queue) .def_readonly("down_bandwidth_bytes_queue", &session_status::down_bandwidth_bytes_queue) .def_readonly("optimistic_unchoke_counter", &session_status::optimistic_unchoke_counter) .def_readonly("unchoke_counter", &session_status::unchoke_counter) #ifndef TORRENT_DISABLE_DHT .def_readonly("dht_nodes", &session_status::dht_nodes) .def_readonly("dht_cache_nodes", &session_status::dht_node_cache) .def_readonly("dht_torrents", &session_status::dht_torrents) .def_readonly("dht_global_nodes", &session_status::dht_global_nodes) .def_readonly("active_requests", &session_status::active_requests) #endif ; class_<dht_lookup>("dht_lookup") .def_readonly("type", &dht_lookup::type) .def_readonly("outstanding_requests", &dht_lookup::outstanding_requests) .def_readonly("timeouts", &dht_lookup::timeouts) .def_readonly("response", &dht_lookup::responses) .def_readonly("branch_factor", &dht_lookup::branch_factor) ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_sparse", storage_mode_sparse) .value("storage_mode_compact", storage_mode_compact) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; enum_<session::session_flags_t>("session_flags_t") .value("add_default_plugins", session::add_default_plugins) .value("start_default_features", session::start_default_features) ; class_<cache_status>("cache_status") .def_readonly("blocks_written", &cache_status::blocks_written) .def_readonly("writes", &cache_status::writes) .def_readonly("blocks_read", &cache_status::blocks_read) .def_readonly("blocks_read_hit", &cache_status::blocks_read_hit) .def_readonly("reads", &cache_status::reads) .def_readonly("cache_size", &cache_status::cache_size) .def_readonly("read_cache_size", &cache_status::read_cache_size) .def_readonly("total_used_buffers", &cache_status::total_used_buffers) ; class_<session, boost::noncopyable>("session", no_init) .def( init<fingerprint, int>(( arg("fingerprint")=fingerprint("LT",0,1,0,0) , arg("flags")=session::start_default_features | session::add_default_plugins)) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) ) .def("outgoing_ports", &outgoing_ports) .def("is_listening", allow_threads(&session::is_listening)) .def("listen_port", allow_threads(&session::listen_port)) .def("status", allow_threads(&session::status)) #ifndef TORRENT_DISABLE_DHT .def( "add_dht_router", &add_dht_router , (arg("router"), "port") ) .def("start_dht", allow_threads(&session::start_dht)) .def("stop_dht", allow_threads(&session::stop_dht)) .def("dht_state", allow_threads(&session::dht_state)) .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) .def("dht_proxy", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>()) #endif .def("add_torrent", &add_torrent) #ifndef TORRENT_NO_DEPRECATE .def( "add_torrent", &add_torrent_depr , ( arg("resume_data") = entry(), arg("storage_mode") = storage_mode_sparse, arg("paused") = false ) ) #endif .def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none ) .def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit)) .def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit)) .def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit)) .def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit)) .def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit)) .def("download_rate_limit", allow_threads(&session::download_rate_limit)) .def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)) .def("upload_rate_limit", allow_threads(&session::upload_rate_limit)) .def("set_max_uploads", allow_threads(&session::set_max_uploads)) .def("set_max_connections", allow_threads(&session::set_max_connections)) .def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)) .def("num_connections", allow_threads(&session::num_connections)) .def("set_settings", allow_threads(&session::set_settings)) .def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>()) #ifndef TORRENT_DISABLE_ENCRYPTION .def("set_pe_settings", allow_threads(&session::set_pe_settings)) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) #endif #ifndef TORRENT_DISABLE_GEO_IP .def("load_asnum_db", &load_asnum_db) .def("load_country_db", &load_country_db) #endif .def("load_state", allow_threads(&session::load_state)) .def("state", allow_threads(&session::state)) #ifndef TORRENT_NO_DEPRECATE .def("set_severity_level", allow_threads(&session::set_severity_level)) #endif .def("set_alert_mask", allow_threads(&session::set_alert_mask)) .def("pop_alert", allow_threads(&session::pop_alert)) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) .def("peer_proxy", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>()) .def("tracker_proxy", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>()) .def("web_seed_proxy", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>()) .def("start_upnp", &start_upnp) .def("stop_upnp", allow_threads(&session::stop_upnp)) .def("start_lsd", allow_threads(&session::start_lsd)) .def("stop_lsd", allow_threads(&session::stop_lsd)) .def("start_natpmp", &start_natpmp) .def("stop_natpmp", allow_threads(&session::stop_natpmp)) .def("set_ip_filter", allow_threads(&session::set_ip_filter)) .def("find_torrent", allow_threads(&session::find_torrent)) .def("get_torrents", &get_torrents) .def("pause", allow_threads(&session::pause)) .def("resume", allow_threads(&session::resume)) .def("is_paused", allow_threads(&session::is_paused)) .def("id", allow_threads(&session::id)) .def("get_cache_status", allow_threads(&session::get_cache_status)) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /** @file brw_fs_register_coalesce.cpp * * Implements register coalescing: Checks if the two registers involved in a * raw move don't interfere, in which case they can both be stored in the same * place and the MOV removed. * * To do this, all uses of the source of the MOV in the shader are replaced * with the destination of the MOV. For example: * * add vgrf3:F, vgrf1:F, vgrf2:F * mov vgrf4:F, vgrf3:F * mul vgrf5:F, vgrf5:F, vgrf4:F * * becomes * * add vgrf4:F, vgrf1:F, vgrf2:F * mul vgrf5:F, vgrf5:F, vgrf4:F */ #include "brw_fs.h" #include "brw_fs_live_variables.h" static bool is_nop_mov(const fs_inst *inst) { if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { fs_reg dst = inst->dst; for (int i = 0; i < inst->sources; i++) { dst.reg_offset = i; if (!dst.equals(inst->src[i])) { return false; } } return true; } else if (inst->opcode == BRW_OPCODE_MOV) { return inst->dst.equals(inst->src[0]); } return false; } static bool is_copy_payload(const fs_inst *inst, int src_size) { if (src_size != inst->sources) return false; const int reg = inst->src[0].reg; if (inst->src[0].reg_offset != 0) return false; for (int i = 1; i < inst->sources; i++) { if (inst->src[i].reg != reg || inst->src[i].reg_offset != i) { return false; } } return true; } static bool is_coalesce_candidate(const fs_inst *inst, const int *virtual_grf_sizes) { if ((inst->opcode != BRW_OPCODE_MOV && inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD) || inst->is_partial_write() || inst->saturate || inst->src[0].file != GRF || inst->src[0].negate || inst->src[0].abs || !inst->src[0].is_contiguous() || inst->dst.file != GRF || inst->dst.type != inst->src[0].type) { return false; } if (virtual_grf_sizes[inst->src[0].reg] > virtual_grf_sizes[inst->dst.reg]) return false; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { if (!is_copy_payload(inst, virtual_grf_sizes[inst->src[0].reg])) { return false; } } return true; } static bool can_coalesce_vars(brw::fs_live_variables *live_intervals, const exec_list *instructions, const fs_inst *inst, int var_to, int var_from) { if (!live_intervals->vars_interfere(var_from, var_to)) return true; /* We know that the live ranges of A (var_from) and B (var_to) * interfere because of the ->vars_interfere() call above. If the end * of B's live range is after the end of A's range, then we know two * things: * - the start of B's live range must be in A's live range (since we * already know the two ranges interfere, this is the only remaining * possibility) * - the interference isn't of the form we're looking for (where B is * entirely inside A) */ if (live_intervals->end[var_to] > live_intervals->end[var_from]) return false; int scan_ip = -1; foreach_in_list(fs_inst, scan_inst, instructions) { scan_ip++; if (scan_inst->is_control_flow()) return false; if (scan_ip <= live_intervals->start[var_to]) continue; if (scan_ip > live_intervals->end[var_to]) break; if (scan_inst->dst.equals(inst->dst) || scan_inst->dst.equals(inst->src[0])) return false; } return true; } bool fs_visitor::register_coalesce() { bool progress = false; calculate_live_intervals(); int src_size = 0; int channels_remaining = 0; int reg_from = -1, reg_to = -1; int reg_to_offset[MAX_SAMPLER_MESSAGE_SIZE]; fs_inst *mov[MAX_SAMPLER_MESSAGE_SIZE]; int var_to[MAX_SAMPLER_MESSAGE_SIZE]; int var_from[MAX_SAMPLER_MESSAGE_SIZE]; foreach_in_list(fs_inst, inst, &instructions) { if (!is_coalesce_candidate(inst, virtual_grf_sizes)) continue; if (is_nop_mov(inst)) { inst->opcode = BRW_OPCODE_NOP; progress = true; continue; } if (reg_from != inst->src[0].reg) { reg_from = inst->src[0].reg; src_size = virtual_grf_sizes[inst->src[0].reg]; assert(src_size <= MAX_SAMPLER_MESSAGE_SIZE); channels_remaining = src_size; memset(mov, 0, sizeof(mov)); reg_to = inst->dst.reg; } if (reg_to != inst->dst.reg) continue; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { for (int i = 0; i < src_size; i++) { reg_to_offset[i] = i; } mov[0] = inst; channels_remaining -= inst->sources; } else { const int offset = inst->src[0].reg_offset; reg_to_offset[offset] = inst->dst.reg_offset; mov[offset] = inst; channels_remaining--; } if (channels_remaining) continue; bool can_coalesce = true; for (int i = 0; i < src_size; i++) { var_to[i] = live_intervals->var_from_vgrf[reg_to] + reg_to_offset[i]; var_from[i] = live_intervals->var_from_vgrf[reg_from] + i; if (!can_coalesce_vars(live_intervals, &instructions, inst, var_to[i], var_from[i])) { can_coalesce = false; reg_from = -1; break; } } if (!can_coalesce) continue; progress = true; bool was_load_payload = inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD; for (int i = 0; i < src_size; i++) { if (mov[i]) { mov[i]->opcode = BRW_OPCODE_NOP; mov[i]->conditional_mod = BRW_CONDITIONAL_NONE; mov[i]->dst = reg_undef; for (int j = 0; j < mov[i]->sources; j++) { mov[i]->src[j] = reg_undef; } } } foreach_in_list(fs_inst, scan_inst, &instructions) { for (int i = 0; i < src_size; i++) { if (mov[i] || was_load_payload) { if (scan_inst->dst.file == GRF && scan_inst->dst.reg == reg_from && scan_inst->dst.reg_offset == i) { scan_inst->dst.reg = reg_to; scan_inst->dst.reg_offset = reg_to_offset[i]; } for (int j = 0; j < scan_inst->sources; j++) { if (scan_inst->src[j].file == GRF && scan_inst->src[j].reg == reg_from && scan_inst->src[j].reg_offset == i) { scan_inst->src[j].reg = reg_to; scan_inst->src[j].reg_offset = reg_to_offset[i]; } } } } } for (int i = 0; i < src_size; i++) { live_intervals->start[var_to[i]] = MIN2(live_intervals->start[var_to[i]], live_intervals->start[var_from[i]]); live_intervals->end[var_to[i]] = MAX2(live_intervals->end[var_to[i]], live_intervals->end[var_from[i]]); } reg_from = -1; } if (progress) { foreach_in_list_safe(fs_inst, inst, &instructions) { if (inst->opcode == BRW_OPCODE_NOP) { inst->remove(); } } invalidate_live_intervals(); } return progress; } <commit_msg>i965/fs: Relax interference check in register coalescing.<commit_after>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /** @file brw_fs_register_coalesce.cpp * * Implements register coalescing: Checks if the two registers involved in a * raw move don't interfere, in which case they can both be stored in the same * place and the MOV removed. * * To do this, all uses of the source of the MOV in the shader are replaced * with the destination of the MOV. For example: * * add vgrf3:F, vgrf1:F, vgrf2:F * mov vgrf4:F, vgrf3:F * mul vgrf5:F, vgrf5:F, vgrf4:F * * becomes * * add vgrf4:F, vgrf1:F, vgrf2:F * mul vgrf5:F, vgrf5:F, vgrf4:F */ #include "brw_fs.h" #include "brw_fs_live_variables.h" static bool is_nop_mov(const fs_inst *inst) { if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { fs_reg dst = inst->dst; for (int i = 0; i < inst->sources; i++) { dst.reg_offset = i; if (!dst.equals(inst->src[i])) { return false; } } return true; } else if (inst->opcode == BRW_OPCODE_MOV) { return inst->dst.equals(inst->src[0]); } return false; } static bool is_copy_payload(const fs_inst *inst, int src_size) { if (src_size != inst->sources) return false; const int reg = inst->src[0].reg; if (inst->src[0].reg_offset != 0) return false; for (int i = 1; i < inst->sources; i++) { if (inst->src[i].reg != reg || inst->src[i].reg_offset != i) { return false; } } return true; } static bool is_coalesce_candidate(const fs_inst *inst, const int *virtual_grf_sizes) { if ((inst->opcode != BRW_OPCODE_MOV && inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD) || inst->is_partial_write() || inst->saturate || inst->src[0].file != GRF || inst->src[0].negate || inst->src[0].abs || !inst->src[0].is_contiguous() || inst->dst.file != GRF || inst->dst.type != inst->src[0].type) { return false; } if (virtual_grf_sizes[inst->src[0].reg] > virtual_grf_sizes[inst->dst.reg]) return false; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { if (!is_copy_payload(inst, virtual_grf_sizes[inst->src[0].reg])) { return false; } } return true; } static bool can_coalesce_vars(brw::fs_live_variables *live_intervals, const exec_list *instructions, const fs_inst *inst, int var_to, int var_from) { if (!live_intervals->vars_interfere(var_from, var_to)) return true; int start_to = live_intervals->start[var_to]; int end_to = live_intervals->end[var_to]; int start_from = live_intervals->start[var_from]; int end_from = live_intervals->end[var_from]; /* Variables interfere and one line range isn't a subset of the other. */ if ((end_to > end_from && start_from < start_to) || (end_from > end_to && start_to < start_from)) return false; int start_ip = MIN2(start_to, start_from); int scan_ip = -1; foreach_in_list(fs_inst, scan_inst, instructions) { scan_ip++; if (scan_ip < start_ip) continue; if (scan_inst->is_control_flow()) return false; if (scan_ip <= live_intervals->start[var_to]) continue; if (scan_ip > live_intervals->end[var_to]) break; if (scan_inst->dst.equals(inst->dst) || scan_inst->dst.equals(inst->src[0])) return false; } return true; } bool fs_visitor::register_coalesce() { bool progress = false; calculate_live_intervals(); int src_size = 0; int channels_remaining = 0; int reg_from = -1, reg_to = -1; int reg_to_offset[MAX_SAMPLER_MESSAGE_SIZE]; fs_inst *mov[MAX_SAMPLER_MESSAGE_SIZE]; int var_to[MAX_SAMPLER_MESSAGE_SIZE]; int var_from[MAX_SAMPLER_MESSAGE_SIZE]; foreach_in_list(fs_inst, inst, &instructions) { if (!is_coalesce_candidate(inst, virtual_grf_sizes)) continue; if (is_nop_mov(inst)) { inst->opcode = BRW_OPCODE_NOP; progress = true; continue; } if (reg_from != inst->src[0].reg) { reg_from = inst->src[0].reg; src_size = virtual_grf_sizes[inst->src[0].reg]; assert(src_size <= MAX_SAMPLER_MESSAGE_SIZE); channels_remaining = src_size; memset(mov, 0, sizeof(mov)); reg_to = inst->dst.reg; } if (reg_to != inst->dst.reg) continue; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { for (int i = 0; i < src_size; i++) { reg_to_offset[i] = i; } mov[0] = inst; channels_remaining -= inst->sources; } else { const int offset = inst->src[0].reg_offset; reg_to_offset[offset] = inst->dst.reg_offset; mov[offset] = inst; channels_remaining--; } if (channels_remaining) continue; bool can_coalesce = true; for (int i = 0; i < src_size; i++) { var_to[i] = live_intervals->var_from_vgrf[reg_to] + reg_to_offset[i]; var_from[i] = live_intervals->var_from_vgrf[reg_from] + i; if (!can_coalesce_vars(live_intervals, &instructions, inst, var_to[i], var_from[i])) { can_coalesce = false; reg_from = -1; break; } } if (!can_coalesce) continue; progress = true; bool was_load_payload = inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD; for (int i = 0; i < src_size; i++) { if (mov[i]) { mov[i]->opcode = BRW_OPCODE_NOP; mov[i]->conditional_mod = BRW_CONDITIONAL_NONE; mov[i]->dst = reg_undef; for (int j = 0; j < mov[i]->sources; j++) { mov[i]->src[j] = reg_undef; } } } foreach_in_list(fs_inst, scan_inst, &instructions) { for (int i = 0; i < src_size; i++) { if (mov[i] || was_load_payload) { if (scan_inst->dst.file == GRF && scan_inst->dst.reg == reg_from && scan_inst->dst.reg_offset == i) { scan_inst->dst.reg = reg_to; scan_inst->dst.reg_offset = reg_to_offset[i]; } for (int j = 0; j < scan_inst->sources; j++) { if (scan_inst->src[j].file == GRF && scan_inst->src[j].reg == reg_from && scan_inst->src[j].reg_offset == i) { scan_inst->src[j].reg = reg_to; scan_inst->src[j].reg_offset = reg_to_offset[i]; } } } } } for (int i = 0; i < src_size; i++) { live_intervals->start[var_to[i]] = MIN2(live_intervals->start[var_to[i]], live_intervals->start[var_from[i]]); live_intervals->end[var_to[i]] = MAX2(live_intervals->end[var_to[i]], live_intervals->end[var_from[i]]); } reg_from = -1; } if (progress) { foreach_in_list_safe(fs_inst, inst, &instructions) { if (inst->opcode == BRW_OPCODE_NOP) { inst->remove(); } } invalidate_live_intervals(); } return progress; } <|endoftext|>
<commit_before>#include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include "char_public.h" #define ERR_EXIT(m) \ do \ { \ perror(m); \ exit(EXIT_FAILURE); \ } while(0) // 当前用户名 char username[16]; // 聊天室成员列表 USER_LIST client_list; void do_someone_login(MESSAGE& msg); void do_someone_logout(MESSAGE& msg); void do_getlist(); void do_chat(); void parse_cmd(char* cmdline, int sock, struct sockaddr_in *servaddr); bool sendmsgto(int sock, char* username, char* msg); void parse_cmd(char* cmdline, int sock, struct sockaddr_in *servaddr) { char cmd[10]={0}; char *p; p = strchr(cmdline, ' '); if (p != NULL) *p = '\0'; strcpy(cmd, cmdline); if (strcmp(cmd, "exit") == 0) { MESSAGE msg; memset(&msg,0,sizeof(msg)); msg.cmd = htonl(C2S_LOGOUT); strcpy(msg.body, username); if (sendto(sock, &msg, sizeof(msg), 0, (struct sockaddr *)servaddr, sizeof(struct sockaddr_in)) < 0) ERR_EXIT("sendto"); printf("user %s has logout server\n", username); exit(EXIT_SUCCESS); } else if (strcmp(cmd, "send") == 0) { char peername[16]={0}; char msg[MSG_LEN]={0}; /* send user msg */ /* p p2 */ while (*p++ == ' ') ; char *p2; p2 = strchr(p, ' '); if (p2 == NULL) { printf("bad command\n"); printf("\nCommands are:\n"); printf("send username msg\n"); printf("list\n"); printf("exit\n"); printf("\n"); return; } *p2 = '\0'; strcpy(peername, p); while (*p2++ == ' ') ; strcpy(msg, p2); sendmsgto(sock, peername, msg); } else if (strcmp(cmd, "list") == 0) { MESSAGE msg; memset(&msg, 0, sizeof(msg)); msg.cmd = htonl(C2S_ONLINE_USER); if (sendto(sock, &msg, sizeof(msg), 0, (struct sockaddr *)servaddr, sizeof(struct sockaddr_in)) < 0) ERR_EXIT("sendto"); } else { printf("bad command\n"); printf("\nCommands are:\n"); printf("send username msg\n"); printf("list\n"); printf("exit\n"); printf("\n"); } } bool sendmsgto(int sock, char* name, char* msg) { if (strcmp(name, username) == 0) { printf("can't send message to self\n"); return false; } USER_LIST::iterator it; for (it=client_list.begin(); it != client_list.end(); ++it) { if (strcmp(it->username,name) == 0) break; } if (it == client_list.end()) { printf("user %s has not logined server\n", name); return false; } MESSAGE m; memset(&m,0,sizeof(m)); m.cmd = htonl(C2C_CHAT); CHAT_MSG cm; strcpy(cm.username, username); strcpy(cm.msg, msg); memcpy(m.body, &cm, sizeof(cm)); //strcpy(m.body,msg); struct sockaddr_in peeraddr; memset(&peeraddr,0,sizeof(peeraddr)); peeraddr.sin_family = AF_INET; peeraddr.sin_addr.s_addr = it->ip; peeraddr.sin_port = it->port; in_addr tmp; tmp.s_addr = it->ip; printf("sending message [%s] to user [%s] <-> %s:%d\n", msg, name, inet_ntoa(tmp), ntohs(it->port)); sendto(sock, (const char*)&m, sizeof(m), 0, (struct sockaddr *)&peeraddr, sizeof(peeraddr)); return true; } void do_getlist(int sock) { int count; recvfrom(sock, &count, sizeof(int), 0, NULL, NULL); printf("has %d users logined server\n", ntohl(count)); client_list.clear(); int n = ntohl(count); for (int i=0; i<n; i++) { USER_INFO user; recvfrom(sock,&user, sizeof(USER_INFO), 0, NULL, NULL); client_list.push_back(user); in_addr tmp; tmp.s_addr = user.ip; printf("%s <-> %s:%d\n", user.username, inet_ntoa(tmp), ntohs(user.port)); } } void do_someone_login(MESSAGE& msg) { USER_INFO *user = (USER_INFO*)msg.body; in_addr tmp; tmp.s_addr = user->ip; printf("%s <-> %s:%d has logined server\n", user->username, inet_ntoa(tmp), ntohs(user->port)); client_list.push_back(*user); } void do_someone_logout(MESSAGE& msg) { USER_LIST::iterator it; for (it=client_list.begin(); it != client_list.end(); ++it) { if (strcmp(it->username,msg.body) == 0) break; } if (it != client_list.end()) client_list.erase(it); printf("user %s has logout server\n", msg.body); } void do_chat(const MESSAGE& msg) { CHAT_MSG *cm = (CHAT_MSG*)msg.body; printf("recv a msg [%s] from [%s]\n", cm->msg, cm->username); //recvfrom(sock, &count, sizeof(int), 0, NULL, NULL); } void chat_cli(int sock) { struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); struct sockaddr_in peeraddr; socklen_t peerlen; MESSAGE msg; while (1) { memset(username,0,sizeof(username)); printf("please inpt your name:"); fflush(stdout); scanf("%s", username); memset(&msg, 0, sizeof(msg)); msg.cmd = htonl(C2S_LOGIN); strcpy(msg.body, username); sendto(sock, &msg, sizeof(msg), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); memset(&msg, 0, sizeof(msg)); recvfrom(sock, &msg, sizeof(msg), 0, NULL, NULL); int cmd = ntohl(msg.cmd); if (cmd == S2C_ALREADY_LOGINED) printf("user %s already logined server, please use another username\n", username); else if (cmd == S2C_LOGIN_OK) { printf("user %s has logined server\n", username); break; } } int count; recvfrom(sock, &count, sizeof(int), 0, NULL, NULL); int n = ntohl(count); printf("has %d users logined server\n", n); for (int i=0; i<n; i++) { USER_INFO user; recvfrom(sock, &user, sizeof(USER_INFO), 0, NULL, NULL); client_list.push_back(user); in_addr tmp; tmp.s_addr = user.ip; printf("%d %s <-> %s:%d\n", i, user.username, inet_ntoa(tmp), ntohs(user.port)); } printf("\nCommands are:\n"); printf("send username msg\n"); printf("list\n"); printf("exit\n"); printf("\n"); fd_set rset; FD_ZERO(&rset); int nready; while (1) { FD_SET(STDIN_FILENO, &rset); FD_SET(sock, &rset); nready = select(sock+1, &rset, NULL, NULL, NULL); if (nready == -1) ERR_EXIT("select"); if (nready == 0) continue; if (FD_ISSET(sock, &rset)) { peerlen = sizeof(peeraddr); memset(&msg,0,sizeof(msg)); recvfrom(sock, &msg, sizeof(msg), 0, (struct sockaddr *)&peeraddr, &peerlen); int cmd = ntohl(msg.cmd); switch (cmd) { case S2C_SOMEONE_LOGIN: do_someone_login(msg); break; case S2C_SOMEONE_LOGOUT: do_someone_logout(msg); break; case S2C_ONLINE_USER: do_getlist(sock); break; case C2C_CHAT: do_chat(msg); break; default: break; } } if (FD_ISSET(STDIN_FILENO, &rset)) { char cmdline[100] = {0}; if (fgets(cmdline, sizeof(cmdline), stdin) == NULL) break; if (cmdline[0] == '\n') continue; cmdline[strlen(cmdline) - 1] = '\0'; parse_cmd(cmdline, sock, &servaddr); } } memset(&msg,0,sizeof(msg)); msg.cmd = htonl(C2S_LOGOUT); strcpy(msg.body, username); sendto(sock, (const char*)&msg, sizeof(msg), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); close(sock); } int main(void) { int sock; if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) ERR_EXIT("socket"); chat_cli(sock); return 0; } <commit_msg>change char_public.h to chat_pubic.h<commit_after>#include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include "chat_public.h" #define ERR_EXIT(m) \ do \ { \ perror(m); \ exit(EXIT_FAILURE); \ } while(0) // 当前用户名 char username[16]; // 聊天室成员列表 USER_LIST client_list; void do_someone_login(MESSAGE& msg); void do_someone_logout(MESSAGE& msg); void do_getlist(); void do_chat(); void parse_cmd(char* cmdline, int sock, struct sockaddr_in *servaddr); bool sendmsgto(int sock, char* username, char* msg); void parse_cmd(char* cmdline, int sock, struct sockaddr_in *servaddr) { char cmd[10]={0}; char *p; p = strchr(cmdline, ' '); if (p != NULL) *p = '\0'; strcpy(cmd, cmdline); if (strcmp(cmd, "exit") == 0) { MESSAGE msg; memset(&msg,0,sizeof(msg)); msg.cmd = htonl(C2S_LOGOUT); strcpy(msg.body, username); if (sendto(sock, &msg, sizeof(msg), 0, (struct sockaddr *)servaddr, sizeof(struct sockaddr_in)) < 0) ERR_EXIT("sendto"); printf("user %s has logout server\n", username); exit(EXIT_SUCCESS); } else if (strcmp(cmd, "send") == 0) { char peername[16]={0}; char msg[MSG_LEN]={0}; /* send user msg */ /* p p2 */ while (*p++ == ' ') ; char *p2; p2 = strchr(p, ' '); if (p2 == NULL) { printf("bad command\n"); printf("\nCommands are:\n"); printf("send username msg\n"); printf("list\n"); printf("exit\n"); printf("\n"); return; } *p2 = '\0'; strcpy(peername, p); while (*p2++ == ' ') ; strcpy(msg, p2); sendmsgto(sock, peername, msg); } else if (strcmp(cmd, "list") == 0) { MESSAGE msg; memset(&msg, 0, sizeof(msg)); msg.cmd = htonl(C2S_ONLINE_USER); if (sendto(sock, &msg, sizeof(msg), 0, (struct sockaddr *)servaddr, sizeof(struct sockaddr_in)) < 0) ERR_EXIT("sendto"); } else { printf("bad command\n"); printf("\nCommands are:\n"); printf("send username msg\n"); printf("list\n"); printf("exit\n"); printf("\n"); } } bool sendmsgto(int sock, char* name, char* msg) { if (strcmp(name, username) == 0) { printf("can't send message to self\n"); return false; } USER_LIST::iterator it; for (it=client_list.begin(); it != client_list.end(); ++it) { if (strcmp(it->username,name) == 0) break; } if (it == client_list.end()) { printf("user %s has not logined server\n", name); return false; } MESSAGE m; memset(&m,0,sizeof(m)); m.cmd = htonl(C2C_CHAT); CHAT_MSG cm; strcpy(cm.username, username); strcpy(cm.msg, msg); memcpy(m.body, &cm, sizeof(cm)); //strcpy(m.body,msg); struct sockaddr_in peeraddr; memset(&peeraddr,0,sizeof(peeraddr)); peeraddr.sin_family = AF_INET; peeraddr.sin_addr.s_addr = it->ip; peeraddr.sin_port = it->port; in_addr tmp; tmp.s_addr = it->ip; printf("sending message [%s] to user [%s] <-> %s:%d\n", msg, name, inet_ntoa(tmp), ntohs(it->port)); sendto(sock, (const char*)&m, sizeof(m), 0, (struct sockaddr *)&peeraddr, sizeof(peeraddr)); return true; } void do_getlist(int sock) { int count; recvfrom(sock, &count, sizeof(int), 0, NULL, NULL); printf("has %d users logined server\n", ntohl(count)); client_list.clear(); int n = ntohl(count); for (int i=0; i<n; i++) { USER_INFO user; recvfrom(sock,&user, sizeof(USER_INFO), 0, NULL, NULL); client_list.push_back(user); in_addr tmp; tmp.s_addr = user.ip; printf("%s <-> %s:%d\n", user.username, inet_ntoa(tmp), ntohs(user.port)); } } void do_someone_login(MESSAGE& msg) { USER_INFO *user = (USER_INFO*)msg.body; in_addr tmp; tmp.s_addr = user->ip; printf("%s <-> %s:%d has logined server\n", user->username, inet_ntoa(tmp), ntohs(user->port)); client_list.push_back(*user); } void do_someone_logout(MESSAGE& msg) { USER_LIST::iterator it; for (it=client_list.begin(); it != client_list.end(); ++it) { if (strcmp(it->username,msg.body) == 0) break; } if (it != client_list.end()) client_list.erase(it); printf("user %s has logout server\n", msg.body); } void do_chat(const MESSAGE& msg) { CHAT_MSG *cm = (CHAT_MSG*)msg.body; printf("recv a msg [%s] from [%s]\n", cm->msg, cm->username); //recvfrom(sock, &count, sizeof(int), 0, NULL, NULL); } void chat_cli(int sock) { struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); struct sockaddr_in peeraddr; socklen_t peerlen; MESSAGE msg; while (1) { memset(username,0,sizeof(username)); printf("please inpt your name:"); fflush(stdout); scanf("%s", username); memset(&msg, 0, sizeof(msg)); msg.cmd = htonl(C2S_LOGIN); strcpy(msg.body, username); sendto(sock, &msg, sizeof(msg), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); memset(&msg, 0, sizeof(msg)); recvfrom(sock, &msg, sizeof(msg), 0, NULL, NULL); int cmd = ntohl(msg.cmd); if (cmd == S2C_ALREADY_LOGINED) printf("user %s already logined server, please use another username\n", username); else if (cmd == S2C_LOGIN_OK) { printf("user %s has logined server\n", username); break; } } int count; recvfrom(sock, &count, sizeof(int), 0, NULL, NULL); int n = ntohl(count); printf("has %d users logined server\n", n); for (int i=0; i<n; i++) { USER_INFO user; recvfrom(sock, &user, sizeof(USER_INFO), 0, NULL, NULL); client_list.push_back(user); in_addr tmp; tmp.s_addr = user.ip; printf("%d %s <-> %s:%d\n", i, user.username, inet_ntoa(tmp), ntohs(user.port)); } printf("\nCommands are:\n"); printf("send username msg\n"); printf("list\n"); printf("exit\n"); printf("\n"); fd_set rset; FD_ZERO(&rset); int nready; while (1) { FD_SET(STDIN_FILENO, &rset); FD_SET(sock, &rset); nready = select(sock+1, &rset, NULL, NULL, NULL); if (nready == -1) ERR_EXIT("select"); if (nready == 0) continue; if (FD_ISSET(sock, &rset)) { peerlen = sizeof(peeraddr); memset(&msg,0,sizeof(msg)); recvfrom(sock, &msg, sizeof(msg), 0, (struct sockaddr *)&peeraddr, &peerlen); int cmd = ntohl(msg.cmd); switch (cmd) { case S2C_SOMEONE_LOGIN: do_someone_login(msg); break; case S2C_SOMEONE_LOGOUT: do_someone_logout(msg); break; case S2C_ONLINE_USER: do_getlist(sock); break; case C2C_CHAT: do_chat(msg); break; default: break; } } if (FD_ISSET(STDIN_FILENO, &rset)) { char cmdline[100] = {0}; if (fgets(cmdline, sizeof(cmdline), stdin) == NULL) break; if (cmdline[0] == '\n') continue; cmdline[strlen(cmdline) - 1] = '\0'; parse_cmd(cmdline, sock, &servaddr); } } memset(&msg,0,sizeof(msg)); msg.cmd = htonl(C2S_LOGOUT); strcpy(msg.body, username); sendto(sock, (const char*)&msg, sizeof(msg), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); close(sock); } int main(void) { int sock; if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) ERR_EXIT("socket"); chat_cli(sock); return 0; } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE #include "Framework.h" #include "SceneAPI.h" #include "IComponentFactory.h" #include "SceneWidgetComponents.h" #include "EC_WidgetCanvas.h" #include "EC_WebView.h" #include "EC_SlideShow.h" #include "EC_WidgetBillboard.h" extern "C" { DLLEXPORT void TundraPluginMain(Framework *fw) { Framework::SetInstance(fw); // Register module IModule *module = new SceneWidgetComponents(); fw->RegisterModule(module); // Register component factories fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_WidgetCanvas>)); fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_WebView>)); fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_SlideShow>)); fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_WidgetBillboard>)); } } <commit_msg>Fix compilation of SceneWidgetComponents.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE #include "Win.h" #include "Framework.h" #include "SceneAPI.h" #include "IComponentFactory.h" #include "SceneWidgetComponents.h" #include "EC_WidgetCanvas.h" #include "EC_WebView.h" #include "EC_SlideShow.h" #include "EC_WidgetBillboard.h" extern "C" { DLLEXPORT void TundraPluginMain(Framework *fw) { Framework::SetInstance(fw); fw->RegisterModule(new SceneWidgetComponents()); fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_WidgetCanvas>)); fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_WebView>)); fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_SlideShow>)); fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_WidgetBillboard>)); } } <|endoftext|>
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <libtorrent/ip_filter.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; extern char const* session_status_doc; extern char const* session_status_has_incoming_connections_doc; extern char const* session_status_upload_rate_doc; extern char const* session_status_download_rate_doc; extern char const* session_status_payload_upload_rate_doc; extern char const* session_status_payload_download_rate_doc; extern char const* session_status_total_download_doc; extern char const* session_status_total_upload_doc; extern char const* session_status_total_payload_download_doc; extern char const* session_status_total_payload_upload_doc; extern char const* session_status_num_peers_doc; extern char const* session_status_dht_nodes_doc; extern char const* session_status_cache_nodes_doc; extern char const* session_status_dht_torrents_doc; extern char const* session_doc; extern char const* session_init_doc; extern char const* session_listen_on_doc; extern char const* session_is_listening_doc; extern char const* session_listen_port_doc; extern char const* session_status_m_doc; extern char const* session_start_dht_doc; extern char const* session_stop_dht_doc; extern char const* session_dht_state_doc; extern char const* session_add_dht_router_doc; extern char const* session_add_torrent_doc; extern char const* session_remove_torrent_doc; extern char const* session_set_download_rate_limit_doc; extern char const* session_download_rate_limit_doc; extern char const* session_set_upload_rate_limit_doc; extern char const* session_upload_rate_limit_doc; extern char const* session_set_max_uploads_doc; extern char const* session_set_max_connections_doc; extern char const* session_set_max_half_open_connections_doc; extern char const* session_num_connections_doc; extern char const* session_set_settings_doc; extern char const* session_set_pe_settings_doc; extern char const* session_get_pe_settings_doc; extern char const* session_set_severity_level_doc; extern char const* session_pop_alert_doc; extern char const* session_start_upnp_doc; extern char const* session_start_lsd_doc; extern char const* session_stop_lsd_doc; extern char const* session_stop_upnp_doc; extern char const* session_start_natpmp_doc; extern char const* session_stop_natpmp_doc; extern char const* session_set_ip_filter_doc; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } void outgoing_ports(session& s, int _min, int _max) { allow_threading_guard guard; session_settings settings = s.settings(); settings.outgoing_ports = std::make_pair(_min, _max); s.set_settings(settings); return; } #ifndef TORRENT_DISABLE_DHT void add_dht_router(session& s, std::string router_, int port_) { allow_threading_guard guard; return s.add_dht_router(std::make_pair(router_, port_)); } #endif struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } torrent_handle add_torrent(session& s, dict params) { add_torrent_params p; if (params.has_key("ti")) p.ti = new torrent_info(extract<torrent_info const&>(params["ti"])); std::string url; if (params.has_key("tracker_url")) { url = extract<std::string>(params["tracker_url"]); p.tracker_url = url.c_str(); } if (params.has_key("info_hash")) p.info_hash = extract<sha1_hash>(params["info_hash"]); std::string name; if (params.has_key("name")) { name = extract<std::string>(params["name"]); p.name = name.c_str(); } p.save_path = fs::path(extract<std::string>(params["save_path"])); std::vector<char> resume_buf; if (params.has_key("resume_data")) { std::string resume = extract<std::string>(params["resume_data"]); resume_buf.resize(resume.size()); std::memcpy(&resume_buf[0], &resume[0], resume.size()); p.resume_data = &resume_buf; } p.storage_mode = extract<storage_mode_t>(params["storage_mode"]); p.paused = params["paused"]; p.auto_managed = params["auto_managed"]; p.duplicate_is_error = params["duplicate_is_error"]; return s.add_torrent(p); } void start_natpmp(session& s) { allow_threading_guard guard; s.start_natpmp(); return; } void start_upnp(session& s) { allow_threading_guard guard; s.start_upnp(); return; } list get_torrents(session& s) { list ret; std::vector<torrent_handle> torrents = s.get_torrents(); for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i) { ret.append(*i); } return ret; } #ifndef TORRENT_DISABLE_GEO_IP bool load_asnum_db(session& s, std::string file) { allow_threading_guard guard; return s.load_asnum_db(file.c_str()); } bool load_country_db(session& s, std::string file) { allow_threading_guard guard; return s.load_country_db(file.c_str()); } #endif } // namespace unnamed void bind_session() { class_<session_status>("session_status", session_status_doc) .def_readonly( "has_incoming_connections", &session_status::has_incoming_connections , session_status_has_incoming_connections_doc ) .def_readonly( "upload_rate", &session_status::upload_rate , session_status_upload_rate_doc ) .def_readonly( "download_rate", &session_status::download_rate , session_status_download_rate_doc ) .def_readonly( "payload_upload_rate", &session_status::payload_upload_rate , session_status_payload_upload_rate_doc ) .def_readonly( "payload_download_rate", &session_status::payload_download_rate , session_status_payload_download_rate_doc ) .def_readonly( "total_download", &session_status::total_download , session_status_total_download_doc ) .def_readonly( "total_upload", &session_status::total_upload , session_status_total_upload_doc ) .def_readonly( "total_payload_download", &session_status::total_payload_download , session_status_total_payload_download_doc ) .def_readonly( "total_payload_upload", &session_status::total_payload_upload , session_status_total_payload_upload_doc ) .def_readonly( "num_peers", &session_status::num_peers , session_status_num_peers_doc ) #ifndef TORRENT_DISABLE_DHT .def_readonly( "dht_nodes", &session_status::dht_nodes , session_status_dht_nodes_doc ) .def_readonly( "dht_cache_nodes", &session_status::dht_node_cache , session_status_cache_nodes_doc ) .def_readonly( "dht_torrents", &session_status::dht_torrents , session_status_dht_torrents_doc ) #endif ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_sparse", storage_mode_sparse) .value("storage_mode_compact", storage_mode_compact) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; class_<session, boost::noncopyable>("session", session_doc, no_init) .def( init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) , session_listen_on_doc ) .def("outgoing_ports", &outgoing_ports) .def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc) .def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc) .def("status", allow_threads(&session::status), session_status_m_doc) #ifndef TORRENT_DISABLE_DHT .def( "add_dht_router", &add_dht_router , (arg("router"), "port") , session_add_dht_router_doc ) .def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc) .def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc) .def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc) .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) #endif .def("add_torrent", &add_torrent, session_add_torrent_doc) .def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none , session_remove_torrent_doc) .def( "set_download_rate_limit", allow_threads(&session::set_download_rate_limit) , session_set_download_rate_limit_doc ) .def( "download_rate_limit", allow_threads(&session::download_rate_limit) , session_download_rate_limit_doc ) .def( "set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit) , session_set_upload_rate_limit_doc ) .def( "upload_rate_limit", allow_threads(&session::upload_rate_limit) , session_upload_rate_limit_doc ) .def( "set_max_uploads", allow_threads(&session::set_max_uploads) , session_set_max_uploads_doc ) .def( "set_max_connections", allow_threads(&session::set_max_connections) , session_set_max_connections_doc ) .def( "set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections) , session_set_max_half_open_connections_doc ) .def( "num_connections", allow_threads(&session::num_connections) , session_num_connections_doc ) .def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc) .def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>()) #ifndef TORRENT_DISABLE_ENCRYPTION .def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) #endif #ifndef TORRENT_DISABLE_GEO_IP .def("load_asnum_db", &load_asnum_db) .def("load_country_db", &load_country_db) #endif .def("load_state", allow_threads(&session::load_state)) .def("state", allow_threads(&session::state)) .def( "set_severity_level", allow_threads(&session::set_severity_level) , session_set_severity_level_doc ) .def("set_alert_mask", allow_threads(&session::set_alert_mask)) .def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) .def("start_upnp", &start_upnp, session_start_upnp_doc) .def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc) .def("start_lsd", allow_threads(&session::start_lsd), session_start_lsd_doc) .def("stop_lsd", allow_threads(&session::stop_lsd), session_stop_lsd_doc) .def("start_natpmp", &start_natpmp, session_start_natpmp_doc) .def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc) .def("set_ip_filter", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc) .def("find_torrent", allow_threads(&session::find_torrent)) .def("get_torrents", &get_torrents) .def("pause", allow_threads(&session::pause)) .def("resume", allow_threads(&session::resume)) .def("is_paused", allow_threads(&session::is_paused)) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <commit_msg>update session constructor in python bindings to support 'flags'<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <libtorrent/ip_filter.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; extern char const* session_status_doc; extern char const* session_status_has_incoming_connections_doc; extern char const* session_status_upload_rate_doc; extern char const* session_status_download_rate_doc; extern char const* session_status_payload_upload_rate_doc; extern char const* session_status_payload_download_rate_doc; extern char const* session_status_total_download_doc; extern char const* session_status_total_upload_doc; extern char const* session_status_total_payload_download_doc; extern char const* session_status_total_payload_upload_doc; extern char const* session_status_num_peers_doc; extern char const* session_status_dht_nodes_doc; extern char const* session_status_cache_nodes_doc; extern char const* session_status_dht_torrents_doc; extern char const* session_doc; extern char const* session_init_doc; extern char const* session_listen_on_doc; extern char const* session_is_listening_doc; extern char const* session_listen_port_doc; extern char const* session_status_m_doc; extern char const* session_start_dht_doc; extern char const* session_stop_dht_doc; extern char const* session_dht_state_doc; extern char const* session_add_dht_router_doc; extern char const* session_add_torrent_doc; extern char const* session_remove_torrent_doc; extern char const* session_set_download_rate_limit_doc; extern char const* session_download_rate_limit_doc; extern char const* session_set_upload_rate_limit_doc; extern char const* session_upload_rate_limit_doc; extern char const* session_set_max_uploads_doc; extern char const* session_set_max_connections_doc; extern char const* session_set_max_half_open_connections_doc; extern char const* session_num_connections_doc; extern char const* session_set_settings_doc; extern char const* session_set_pe_settings_doc; extern char const* session_get_pe_settings_doc; extern char const* session_set_severity_level_doc; extern char const* session_pop_alert_doc; extern char const* session_start_upnp_doc; extern char const* session_start_lsd_doc; extern char const* session_stop_lsd_doc; extern char const* session_stop_upnp_doc; extern char const* session_start_natpmp_doc; extern char const* session_stop_natpmp_doc; extern char const* session_set_ip_filter_doc; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } void outgoing_ports(session& s, int _min, int _max) { allow_threading_guard guard; session_settings settings = s.settings(); settings.outgoing_ports = std::make_pair(_min, _max); s.set_settings(settings); return; } #ifndef TORRENT_DISABLE_DHT void add_dht_router(session& s, std::string router_, int port_) { allow_threading_guard guard; return s.add_dht_router(std::make_pair(router_, port_)); } #endif struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } torrent_handle add_torrent(session& s, dict params) { add_torrent_params p; if (params.has_key("ti")) p.ti = new torrent_info(extract<torrent_info const&>(params["ti"])); std::string url; if (params.has_key("tracker_url")) { url = extract<std::string>(params["tracker_url"]); p.tracker_url = url.c_str(); } if (params.has_key("info_hash")) p.info_hash = extract<sha1_hash>(params["info_hash"]); std::string name; if (params.has_key("name")) { name = extract<std::string>(params["name"]); p.name = name.c_str(); } p.save_path = fs::path(extract<std::string>(params["save_path"])); std::vector<char> resume_buf; if (params.has_key("resume_data")) { std::string resume = extract<std::string>(params["resume_data"]); resume_buf.resize(resume.size()); std::memcpy(&resume_buf[0], &resume[0], resume.size()); p.resume_data = &resume_buf; } p.storage_mode = extract<storage_mode_t>(params["storage_mode"]); p.paused = params["paused"]; p.auto_managed = params["auto_managed"]; p.duplicate_is_error = params["duplicate_is_error"]; return s.add_torrent(p); } void start_natpmp(session& s) { allow_threading_guard guard; s.start_natpmp(); return; } void start_upnp(session& s) { allow_threading_guard guard; s.start_upnp(); return; } list get_torrents(session& s) { list ret; std::vector<torrent_handle> torrents = s.get_torrents(); for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i) { ret.append(*i); } return ret; } #ifndef TORRENT_DISABLE_GEO_IP bool load_asnum_db(session& s, std::string file) { allow_threading_guard guard; return s.load_asnum_db(file.c_str()); } bool load_country_db(session& s, std::string file) { allow_threading_guard guard; return s.load_country_db(file.c_str()); } #endif } // namespace unnamed void bind_session() { class_<session_status>("session_status", session_status_doc) .def_readonly( "has_incoming_connections", &session_status::has_incoming_connections , session_status_has_incoming_connections_doc ) .def_readonly( "upload_rate", &session_status::upload_rate , session_status_upload_rate_doc ) .def_readonly( "download_rate", &session_status::download_rate , session_status_download_rate_doc ) .def_readonly( "payload_upload_rate", &session_status::payload_upload_rate , session_status_payload_upload_rate_doc ) .def_readonly( "payload_download_rate", &session_status::payload_download_rate , session_status_payload_download_rate_doc ) .def_readonly( "total_download", &session_status::total_download , session_status_total_download_doc ) .def_readonly( "total_upload", &session_status::total_upload , session_status_total_upload_doc ) .def_readonly( "total_payload_download", &session_status::total_payload_download , session_status_total_payload_download_doc ) .def_readonly( "total_payload_upload", &session_status::total_payload_upload , session_status_total_payload_upload_doc ) .def_readonly( "num_peers", &session_status::num_peers , session_status_num_peers_doc ) #ifndef TORRENT_DISABLE_DHT .def_readonly( "dht_nodes", &session_status::dht_nodes , session_status_dht_nodes_doc ) .def_readonly( "dht_cache_nodes", &session_status::dht_node_cache , session_status_cache_nodes_doc ) .def_readonly( "dht_torrents", &session_status::dht_torrents , session_status_dht_torrents_doc ) #endif ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_sparse", storage_mode_sparse) .value("storage_mode_compact", storage_mode_compact) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; enum_<session::session_flags_t>("session_flags_t") .value("add_default_plugins", session::add_default_plugins) .value("start_default_features", session::start_default_features) ; class_<session, boost::noncopyable>("session", session_doc, no_init) .def( init<fingerprint, int>(( arg("fingerprint")=fingerprint("LT",0,1,0,0) , arg("flags")=session::start_default_features | session::add_default_plugins) , session_init_doc) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) , session_listen_on_doc ) .def("outgoing_ports", &outgoing_ports) .def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc) .def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc) .def("status", allow_threads(&session::status), session_status_m_doc) #ifndef TORRENT_DISABLE_DHT .def( "add_dht_router", &add_dht_router , (arg("router"), "port") , session_add_dht_router_doc ) .def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc) .def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc) .def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc) .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) #endif .def("add_torrent", &add_torrent, session_add_torrent_doc) .def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none , session_remove_torrent_doc) .def( "set_download_rate_limit", allow_threads(&session::set_download_rate_limit) , session_set_download_rate_limit_doc ) .def( "download_rate_limit", allow_threads(&session::download_rate_limit) , session_download_rate_limit_doc ) .def( "set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit) , session_set_upload_rate_limit_doc ) .def( "upload_rate_limit", allow_threads(&session::upload_rate_limit) , session_upload_rate_limit_doc ) .def( "set_max_uploads", allow_threads(&session::set_max_uploads) , session_set_max_uploads_doc ) .def( "set_max_connections", allow_threads(&session::set_max_connections) , session_set_max_connections_doc ) .def( "set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections) , session_set_max_half_open_connections_doc ) .def( "num_connections", allow_threads(&session::num_connections) , session_num_connections_doc ) .def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc) .def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>()) #ifndef TORRENT_DISABLE_ENCRYPTION .def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) #endif #ifndef TORRENT_DISABLE_GEO_IP .def("load_asnum_db", &load_asnum_db) .def("load_country_db", &load_country_db) #endif .def("load_state", allow_threads(&session::load_state)) .def("state", allow_threads(&session::state)) .def( "set_severity_level", allow_threads(&session::set_severity_level) , session_set_severity_level_doc ) .def("set_alert_mask", allow_threads(&session::set_alert_mask)) .def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) .def("start_upnp", &start_upnp, session_start_upnp_doc) .def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc) .def("start_lsd", allow_threads(&session::start_lsd), session_start_lsd_doc) .def("stop_lsd", allow_threads(&session::stop_lsd), session_stop_lsd_doc) .def("start_natpmp", &start_natpmp, session_start_natpmp_doc) .def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc) .def("set_ip_filter", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc) .def("find_torrent", allow_threads(&session::find_torrent)) .def("get_torrents", &get_torrents) .def("pause", allow_threads(&session::pause)) .def("resume", allow_threads(&session::resume)) .def("is_paused", allow_threads(&session::is_paused)) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <|endoftext|>
<commit_before>#include <string> #include <iostream> #include <sstream> #ifdef HAVE_BOOST #include <boost/program_options.hpp> #endif #include "CmdSession.h" #include <SmurffCpp/Predict/PredictSession.h> #include <SmurffCpp/Sessions/SessionFactory.h> #include <SmurffCpp/Configs/Config.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Version.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/Utils/RootFile.h> #include <SmurffCpp/Utils/StringUtils.h> static const char *PREDICT_NAME = "predict"; static const char *HELP_NAME = "help"; static const char *PRIOR_NAME = "prior"; static const char *TEST_NAME = "test"; static const char *TRAIN_NAME = "train"; static const char *BURNIN_NAME = "burnin"; static const char *NSAMPLES_NAME = "nsamples"; static const char *NUM_LATENT_NAME = "num-latent"; static const char *NUM_THREADS_NAME = "num-threads"; static const char *SAVE_PREFIX_NAME = "save-prefix"; static const char *SAVE_EXTENSION_NAME = "save-extension"; static const char *SAVE_FREQ_NAME = "save-freq"; static const char *CHECKPOINT_FREQ_NAME = "checkpoint-freq"; static const char *THRESHOLD_NAME = "threshold"; static const char *VERBOSE_NAME = "verbose"; static const char *VERSION_NAME = "version"; static const char *STATUS_NAME = "status"; static const char *SEED_NAME = "seed"; static const char *INI_NAME = "ini"; static const char *ROOT_NAME = "root"; using namespace smurff; #ifdef HAVE_BOOST namespace po = boost::program_options; po::options_description get_desc() { po::options_description general_desc("General parameters"); general_desc.add_options() (VERSION_NAME, "print version info (and exit)") (HELP_NAME, "show this help information (and exit)") (INI_NAME, po::value<std::string>(), "read options from this .ini file") (NUM_THREADS_NAME, po::value<int>()->default_value(Config::NUM_THREADS_DEFAULT_VALUE), "number of threads (0 = default by OpenMP)") (VERBOSE_NAME, po::value<int>()->default_value(Config::VERBOSE_DEFAULT_VALUE), "verbosity of output (0, 1, 2 or 3)") (SEED_NAME, po::value<int>()->default_value(Config::RANDOM_SEED_DEFAULT_VALUE), "random number generator seed"); po::options_description train_desc("Used during training"); train_desc.add_options() (TRAIN_NAME, po::value<std::string>(), "train data file") (TEST_NAME, po::value<std::string>(), "test data") (PRIOR_NAME, po::value<std::vector<std::string>>()->multitoken(), "provide a prior-type for each dimension of train; prior-types: <normal|normalone|spikeandslab|macau|macauone>") (BURNIN_NAME, po::value<int>()->default_value(Config::BURNIN_DEFAULT_VALUE), "number of samples to discard") (NSAMPLES_NAME, po::value<int>()->default_value(Config::NSAMPLES_DEFAULT_VALUE), "number of samples to collect") (NUM_LATENT_NAME, po::value<int>()->default_value(Config::NUM_LATENT_DEFAULT_VALUE), "number of latent dimensions") (THRESHOLD_NAME, po::value<double>()->default_value(Config::THRESHOLD_DEFAULT_VALUE), "threshold for binary classification and AUC calculation"); po::options_description predict_desc("Used during prediction"); predict_desc.add_options() (PREDICT_NAME, po::value<std::string>(), "sparse matrix with values to predict") (THRESHOLD_NAME, po::value<double>()->default_value(Config::THRESHOLD_DEFAULT_VALUE), "threshold for binary classification and AUC calculation"); po::options_description save_desc("Storing models and predictions"); save_desc.add_options() (ROOT_NAME, po::value<std::string>(), "restore session from root .ini file") (SAVE_PREFIX_NAME, po::value<std::string>()->default_value(Config::SAVE_PREFIX_DEFAULT_VALUE), "prefix for result files") (STATUS_NAME, po::value<std::string>()->default_value(Config::STATUS_DEFAULT_VALUE), "output progress to csv file") (SAVE_EXTENSION_NAME, po::value<std::string>()->default_value(Config::SAVE_EXTENSION_DEFAULT_VALUE), "extension for result files (.csv or .ddm)") (SAVE_FREQ_NAME, po::value<int>()->default_value(Config::SAVE_FREQ_DEFAULT_VALUE), "save every n iterations (0 == never, -1 == final model)") (CHECKPOINT_FREQ_NAME, po::value<int>()->default_value(Config::CHECKPOINT_FREQ_DEFAULT_VALUE), "save state every n seconds, only one checkpointing state is kept"); po::options_description desc("SMURFF: Scalable Matrix Factorization Framework\n\thttp://github.com/ExaScience/smurff"); desc.add(general_desc); desc.add(train_desc); desc.add(predict_desc); desc.add(save_desc); return desc; } struct ConfigFiller { const po::variables_map &vm; Config &config; template <typename T, void (Config::*Func)(T)> void set(std::string name) { if (vm.count(name) && !vm[name].defaulted()) (config.*Func)(vm[name].as<T>()); } template <void (Config::*Func)(std::shared_ptr<TensorConfig>)> void set_tensor(std::string name) { if (vm.count(name) && !vm[name].defaulted()) (this->config.*Func)(generic_io::read_data_config(vm[name].as<std::string>(), true)); } void set_priors(std::string name) { if (vm.count(name) && !vm[name].defaulted()) config.setPriorTypes(vm[name].as<std::vector<std::string>>()); } }; // variables_map -> Config Config fill_config(const po::variables_map &vm) { Config config; ConfigFiller filler = {vm, config}; //restore session from root file (command line arguments are already stored in file) if (vm.count(ROOT_NAME)) { //restore config from root file std::string root_name = vm[ROOT_NAME].as<std::string>(); RootFile(root_name).restoreConfig(config); config.setRootName(root_name); } //restore ini file if it was specified if (vm.count(INI_NAME)) { auto ini_file = vm[INI_NAME].as<std::string>(); bool success = config.restore(ini_file); THROWERROR_ASSERT_MSG(success, "Could not load ini file '" + ini_file + "'"); config.setIniName(ini_file); } filler.set_tensor<&Config::setPredict>(PREDICT_NAME); filler.set_tensor<&Config::setTest>(TEST_NAME); filler.set_tensor<&Config::setTrain>(TRAIN_NAME); filler.set_priors(PRIOR_NAME); filler.set<double, &Config::setThreshold>(THRESHOLD_NAME); filler.set<int, &Config::setBurnin>(BURNIN_NAME); filler.set<int, &Config::setNSamples>(NSAMPLES_NAME); filler.set<int, &Config::setNumLatent>(NUM_LATENT_NAME); filler.set<int, &Config::setNumThreads>(NUM_THREADS_NAME); filler.set<std::string, &Config::setSavePrefix>(SAVE_PREFIX_NAME); filler.set<std::string, &Config::setSaveExtension>(SAVE_EXTENSION_NAME); filler.set<int, &Config::setSaveFreq>(SAVE_FREQ_NAME); filler.set<int, &Config::setCheckpointFreq>(CHECKPOINT_FREQ_NAME); filler.set<double, &Config::setThreshold>(THRESHOLD_NAME); filler.set<int, &Config::setVerbose>(VERBOSE_NAME); filler.set<std::string, &Config::setCsvStatus>(STATUS_NAME); filler.set<int, &Config::setRandomSeed>(SEED_NAME); return config; } // argc/argv -> variables_map -> Config Config smurff::parse_options(int argc, char *argv[]) { po::variables_map vm; try { po::options_description desc = get_desc(); if (argc < 2) { std::cout << desc << std::endl; return Config(); } po::command_line_parser parser{argc, argv}; parser.options(desc); po::parsed_options parsed_options = parser.run(); store(parsed_options, vm); notify(vm); if (vm.count(HELP_NAME)) { std::cout << desc << std::endl; return Config(); } if (vm.count(VERSION_NAME)) { std::cout << "SMURFF " << smurff::SMURFF_VERSION << std::endl; return Config(); } } catch (const po::error &ex) { std::cerr << "Failed to parse command line arguments: " << std::endl; std::cerr << ex.what() << std::endl; throw(ex); } catch (std::runtime_error &ex) { std::cerr << "Failed to parse command line arguments: " << std::endl; std::cerr << ex.what() << std::endl; throw(ex); } const std::vector<std::string> train_only_options = { TRAIN_NAME, TEST_NAME, PRIOR_NAME, BURNIN_NAME, NSAMPLES_NAME, NUM_LATENT_NAME}; //-- prediction only if (vm.count(PREDICT_NAME)) { if (!vm.count(ROOT_NAME)) THROWERROR("Need --root option in predict mode"); for (auto to : train_only_options) { if (vm.count(to)) THROWERROR("You're not allowed to mix train options (--" + to + ") with --predict"); } } else { if (!vm.count(TRAIN_NAME)) THROWERROR("Need --train option in train mode"); } return fill_config(vm); } #else // no BOOST // argc/argv --> Config Config smurff::parse_options(int argc, char *argv[]) { auto usage = []() { std::cerr << "Usage:\n\tsmurff --[ini|root] <ini_file.ini>\n\n" << "(Limited smurff compiled w/o boost program options)" << std::endl; THROWERROR(); }; if (argc != 3) usage(); Config config; //restore session from root file (command line arguments are already stored in file) if (std::string(argv[1]) == "--" + std::string(ROOT_NAME)) { std::string root_name(argv[2]); RootFile(root_name).restoreConfig(config); config.setRootName(root_name); } //create new session from config (passing command line arguments) else if (std::string(argv[1]) == "--" + std::string(INI_NAME)) { std::string ini_file(argv[2]); bool success = config.restore(ini_file); THROWERROR_ASSERT_MSG(success, "Could not load ini file '" + ini_file + "'"); config.setIniName(ini_file); } else { usage(); } return config; } #endif //create cmd session //parses args with setFromArgs, then internally calls setFromConfig (to validate, save, set config) std::shared_ptr<ISession> smurff::create_cmd_session(int argc, char **argv) { std::shared_ptr<ISession> session; auto config = parse_options(argc, argv); if (config.isActionTrain()) session = SessionFactory::create_session(config); else if (config.isActionPredict()) session = std::make_shared<PredictSession>(config); else exit(0); return session; } <commit_msg>Set noise config in smurff command line<commit_after>#include <string> #include <iostream> #include <sstream> #ifdef HAVE_BOOST #include <boost/program_options.hpp> #endif #include "CmdSession.h" #include <SmurffCpp/Predict/PredictSession.h> #include <SmurffCpp/Sessions/SessionFactory.h> #include <SmurffCpp/Configs/Config.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Version.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/Utils/RootFile.h> #include <SmurffCpp/Utils/StringUtils.h> static const char *PREDICT_NAME = "predict"; static const char *HELP_NAME = "help"; static const char *PRIOR_NAME = "prior"; static const char *TEST_NAME = "test"; static const char *TRAIN_NAME = "train"; static const char *BURNIN_NAME = "burnin"; static const char *NSAMPLES_NAME = "nsamples"; static const char *NUM_LATENT_NAME = "num-latent"; static const char *NUM_THREADS_NAME = "num-threads"; static const char *SAVE_PREFIX_NAME = "save-prefix"; static const char *SAVE_EXTENSION_NAME = "save-extension"; static const char *SAVE_FREQ_NAME = "save-freq"; static const char *CHECKPOINT_FREQ_NAME = "checkpoint-freq"; static const char *THRESHOLD_NAME = "threshold"; static const char *VERBOSE_NAME = "verbose"; static const char *VERSION_NAME = "version"; static const char *STATUS_NAME = "status"; static const char *SEED_NAME = "seed"; static const char *INI_NAME = "ini"; static const char *ROOT_NAME = "root"; using namespace smurff; #ifdef HAVE_BOOST namespace po = boost::program_options; po::options_description get_desc() { po::options_description general_desc("General parameters"); general_desc.add_options() (VERSION_NAME, "print version info (and exit)") (HELP_NAME, "show this help information (and exit)") (INI_NAME, po::value<std::string>(), "read options from this .ini file") (NUM_THREADS_NAME, po::value<int>()->default_value(Config::NUM_THREADS_DEFAULT_VALUE), "number of threads (0 = default by OpenMP)") (VERBOSE_NAME, po::value<int>()->default_value(Config::VERBOSE_DEFAULT_VALUE), "verbosity of output (0, 1, 2 or 3)") (SEED_NAME, po::value<int>()->default_value(Config::RANDOM_SEED_DEFAULT_VALUE), "random number generator seed"); po::options_description train_desc("Used during training"); train_desc.add_options() (TRAIN_NAME, po::value<std::string>(), "train data file") (TEST_NAME, po::value<std::string>(), "test data") (PRIOR_NAME, po::value<std::vector<std::string>>()->multitoken(), "provide a prior-type for each dimension of train; prior-types: <normal|normalone|spikeandslab|macau|macauone>") (BURNIN_NAME, po::value<int>()->default_value(Config::BURNIN_DEFAULT_VALUE), "number of samples to discard") (NSAMPLES_NAME, po::value<int>()->default_value(Config::NSAMPLES_DEFAULT_VALUE), "number of samples to collect") (NUM_LATENT_NAME, po::value<int>()->default_value(Config::NUM_LATENT_DEFAULT_VALUE), "number of latent dimensions") (THRESHOLD_NAME, po::value<double>()->default_value(Config::THRESHOLD_DEFAULT_VALUE), "threshold for binary classification and AUC calculation"); po::options_description predict_desc("Used during prediction"); predict_desc.add_options() (PREDICT_NAME, po::value<std::string>(), "sparse matrix with values to predict") (THRESHOLD_NAME, po::value<double>()->default_value(Config::THRESHOLD_DEFAULT_VALUE), "threshold for binary classification and AUC calculation"); po::options_description save_desc("Storing models and predictions"); save_desc.add_options() (ROOT_NAME, po::value<std::string>(), "restore session from root .ini file") (SAVE_PREFIX_NAME, po::value<std::string>()->default_value(Config::SAVE_PREFIX_DEFAULT_VALUE), "prefix for result files") (STATUS_NAME, po::value<std::string>()->default_value(Config::STATUS_DEFAULT_VALUE), "output progress to csv file") (SAVE_EXTENSION_NAME, po::value<std::string>()->default_value(Config::SAVE_EXTENSION_DEFAULT_VALUE), "extension for result files (.csv or .ddm)") (SAVE_FREQ_NAME, po::value<int>()->default_value(Config::SAVE_FREQ_DEFAULT_VALUE), "save every n iterations (0 == never, -1 == final model)") (CHECKPOINT_FREQ_NAME, po::value<int>()->default_value(Config::CHECKPOINT_FREQ_DEFAULT_VALUE), "save state every n seconds, only one checkpointing state is kept"); po::options_description desc("SMURFF: Scalable Matrix Factorization Framework\n\thttp://github.com/ExaScience/smurff"); desc.add(general_desc); desc.add(train_desc); desc.add(predict_desc); desc.add(save_desc); return desc; } struct ConfigFiller { const po::variables_map &vm; Config &config; template <typename T, void (Config::*Func)(T)> void set(std::string name) { if (vm.count(name) && !vm[name].defaulted()) (config.*Func)(vm[name].as<T>()); } template <void (Config::*Func)(std::shared_ptr<TensorConfig>)> void set_tensor(std::string name, bool set_noise) { if (vm.count(name) && !vm[name].defaulted()) { auto tensor_config = generic_io::read_data_config(vm[name].as<std::string>(), true); tensor_config->setNoiseConfig(NoiseConfig(NoiseConfig::NOISE_TYPE_DEFAULT_VALUE)); (this->config.*Func)(tensor_config); } } void set_priors(std::string name) { if (vm.count(name) && !vm[name].defaulted()) config.setPriorTypes(vm[name].as<std::vector<std::string>>()); } }; // variables_map -> Config Config fill_config(const po::variables_map &vm) { Config config; ConfigFiller filler = {vm, config}; //restore session from root file (command line arguments are already stored in file) if (vm.count(ROOT_NAME)) { //restore config from root file std::string root_name = vm[ROOT_NAME].as<std::string>(); RootFile(root_name).restoreConfig(config); config.setRootName(root_name); } //restore ini file if it was specified if (vm.count(INI_NAME)) { auto ini_file = vm[INI_NAME].as<std::string>(); bool success = config.restore(ini_file); THROWERROR_ASSERT_MSG(success, "Could not load ini file '" + ini_file + "'"); config.setIniName(ini_file); } filler.set_tensor<&Config::setPredict>(PREDICT_NAME, false); filler.set_tensor<&Config::setTest>(TEST_NAME, false); filler.set_tensor<&Config::setTrain>(TRAIN_NAME, true); filler.set_priors(PRIOR_NAME); filler.set<double, &Config::setThreshold>(THRESHOLD_NAME); filler.set<int, &Config::setBurnin>(BURNIN_NAME); filler.set<int, &Config::setNSamples>(NSAMPLES_NAME); filler.set<int, &Config::setNumLatent>(NUM_LATENT_NAME); filler.set<int, &Config::setNumThreads>(NUM_THREADS_NAME); filler.set<std::string, &Config::setSavePrefix>(SAVE_PREFIX_NAME); filler.set<std::string, &Config::setSaveExtension>(SAVE_EXTENSION_NAME); filler.set<int, &Config::setSaveFreq>(SAVE_FREQ_NAME); filler.set<int, &Config::setCheckpointFreq>(CHECKPOINT_FREQ_NAME); filler.set<double, &Config::setThreshold>(THRESHOLD_NAME); filler.set<int, &Config::setVerbose>(VERBOSE_NAME); filler.set<int, &Config::setRandomSeed>(SEED_NAME); return config; } // argc/argv -> variables_map -> Config Config smurff::parse_options(int argc, char *argv[]) { po::variables_map vm; try { po::options_description desc = get_desc(); if (argc < 2) { std::cout << desc << std::endl; return Config(); } po::command_line_parser parser{argc, argv}; parser.options(desc); po::parsed_options parsed_options = parser.run(); store(parsed_options, vm); notify(vm); if (vm.count(HELP_NAME)) { std::cout << desc << std::endl; return Config(); } if (vm.count(VERSION_NAME)) { std::cout << "SMURFF " << smurff::SMURFF_VERSION << std::endl; return Config(); } } catch (const po::error &ex) { std::cerr << "Failed to parse command line arguments: " << std::endl; std::cerr << ex.what() << std::endl; throw(ex); } catch (std::runtime_error &ex) { std::cerr << "Failed to parse command line arguments: " << std::endl; std::cerr << ex.what() << std::endl; throw(ex); } const std::vector<std::string> train_only_options = { TRAIN_NAME, TEST_NAME, PRIOR_NAME, BURNIN_NAME, NSAMPLES_NAME, NUM_LATENT_NAME}; //-- prediction only if (vm.count(PREDICT_NAME)) { if (!vm.count(ROOT_NAME)) THROWERROR("Need --root option in predict mode"); for (auto to : train_only_options) { if (vm.count(to)) THROWERROR("You're not allowed to mix train options (--" + to + ") with --predict"); } } else { if (!vm.count(TRAIN_NAME)) THROWERROR("Need --train option in train mode"); } return fill_config(vm); } #else // no BOOST // argc/argv --> Config Config smurff::parse_options(int argc, char *argv[]) { auto usage = []() { std::cerr << "Usage:\n\tsmurff --[ini|root] <ini_file.ini>\n\n" << "(Limited smurff compiled w/o boost program options)" << std::endl; exit(0); }; if (argc != 3) usage(); Config config; //restore session from root file (command line arguments are already stored in file) if (std::string(argv[1]) == "--" + std::string(ROOT_NAME)) { std::string root_name(argv[2]); RootFile(root_name).restoreConfig(config); config.setRootName(root_name); } //create new session from config (passing command line arguments) else if (std::string(argv[1]) == "--" + std::string(INI_NAME)) { std::string ini_file(argv[2]); bool success = config.restore(ini_file); THROWERROR_ASSERT_MSG(success, "Could not load ini file '" + ini_file + "'"); config.setIniName(ini_file); } else { usage(); } return config; } #endif //create cmd session //parses args with setFromArgs, then internally calls setFromConfig (to validate, save, set config) std::shared_ptr<ISession> smurff::create_cmd_session(int argc, char **argv) { std::shared_ptr<ISession> session; auto config = parse_options(argc, argv); if (config.isActionTrain()) session = SessionFactory::create_session(config); else if (config.isActionPredict()) session = std::make_shared<PredictSession>(config); else exit(0); return session; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File SharedArray.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Scientific Computing and Imaging Institute, // University of Utah (USA) and Department of Aeronautics, Imperial // College London (UK). // // License for the specific language governing rights and limitations under // 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. // // Description: // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP #define NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP // This is a copy of boost::shared_array with minor modifications. #include <boost/config.hpp> // for broken compiler workarounds #include <boost/assert.hpp> #include <boost/checked_delete.hpp> #include <boost/detail/shared_count.hpp> #include <boost/detail/workaround.hpp> #include <boost/bind.hpp> #include <cstddef> // for std::ptrdiff_t #include <algorithm> // for std::swap #include <functional> // for std::less #include <LibUtilities/BasicUtils/mojo.hpp> namespace Nektar { /// \brief Wraps a reference counted T* and deletes it when it is no longer referenced. /// /// SharedArray is a replacement for boost::shared_array. It addresses the following /// problem with boost::shared_array /// /// A "const boost::shared_array<T>" still allows you to modify the internal data /// held by the array. In other words, it is possible to do the following: /// /// const boost::shared_array<double>& foo(); /// /// const boost::shared_array<double>& a = foo(); /// a[0] = 1.0; /// /// With SharedArrays, a "const SharedArray" will not allow you to modify the /// underlying data. /// /// An additional feature of a SharedArray is the ability to create a new shared array /// with an offset: /// /// SharedArray<double> coeffs = MemoryManager::AllocateSharedArray<double>(10); /// SharedArray<double> offset = coefffs+5; // offset[5] = coeffs[0] /// /// coeffs and offset point to the same underlying array, so if coeffs goes out of scope the array /// is not deleted until offset goes out of scope. /// template<class T> class SharedArray : public MojoEnabled<SharedArray<T> > { private: // Borland 5.5.1 specific workarounds typedef boost::checked_array_deleter<T> deleter; typedef SharedArray<T> this_type; public: typedef T element_type; SharedArray() : px(0), pn((T*)0, deleter()), m_offset(0), m_size(0) { } explicit SharedArray(unsigned int s) : px(new T[s]), pn(px, deleter()), m_offset(0), m_size(0) { } SharedArray(T* p, unsigned int s) : px(p), pn(p, deleter()), m_offset(0), m_size(s) { } SharedArray(SharedArray<T>& rhs, unsigned int offset) : px(rhs.px), pn(rhs.pn), m_offset(offset), m_size(rhs.m_size) { } // // Requirements: D's copy constructor must not throw // // shared_array will release p by calling d(p) // template<class D> SharedArray(T* p, unsigned int s, D d) : px(p), pn(p, d), m_offset(0), m_size(s) { } SharedArray(SharedArray<T>& rhs) : px(rhs.px), pn(rhs.pn), m_offset(rhs.m_offset), m_size(rhs.m_size) { } SharedArray(Temporary<SharedArray<T> > rhs) : px(rhs.GetValue().px), pn(rhs.GetValue().pn), m_offset(rhs.GetValue().m_offset), m_size(rhs.GetValue().m_size) { } SharedArray<T>& operator=(SharedArray<T>& rhs) { SharedArray<T> temp(rhs); swap(temp); return *this; } SharedArray<T>& operator=(Temporary<SharedArray<T> > rhs) { SharedArray<T> temp(rhs.GetValue()); swap(temp); return *this; } void reset() { this_type().swap(*this); } void reset(T* p, unsigned int size) { BOOST_ASSERT(p == 0 || p != px); this_type(p, size).swap(*this); } template <class D> void reset(T * p, unsigned int size, D d) { this_type(p, size, d).swap(*this); } T& operator[] (std::ptrdiff_t i) // never throws { BOOST_ASSERT(px != 0); BOOST_ASSERT(i >= 0); return px[i + m_offset]; } const T& operator[] (std::ptrdiff_t i) const // never throws { BOOST_ASSERT(px != 0); BOOST_ASSERT(i >= 0); return px[i + m_offset]; } T* get() // never throws { return px + m_offset; } const T* get() const { return px + m_offset; } unsigned int GetSize() const { return m_size; } // implicit conversion to "bool" #if defined(__SUNPRO_CC) && BOOST_WORKAROUND(__SUNPRO_CC, <= 0x530) operator bool () const { return px != 0; } #elif defined(__MWERKS__) && BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003)) typedef T * (this_type::*unspecified_bool_type)() const; operator unspecified_bool_type() const // never throws { return px == 0? 0: &this_type::get; } #else typedef T * this_type::*unspecified_bool_type; operator unspecified_bool_type() const // never throws { return px == 0? 0: &this_type::px; } #endif bool operator! () const // never throws { return px == 0; } bool unique() const // never throws { return pn.unique(); } long use_count() const // never throws { return pn.use_count(); } void swap(SharedArray<T>& other) // never throws { std::swap(px, other.px); pn.swap(other.pn); std::swap(m_offset, other.m_offset); std::swap(m_size, other.m_size); } typedef T* iterator; typedef const T* const_iterator; iterator begin() { return px + m_offset; } iterator end() { return px + m_size; } const_iterator begin() const { return px + m_offset; } const_iterator end() const { return px + m_size; } private: //SharedArray<T>& operator=(const SharedArray<T>& rhs); T* px; // contained pointer boost::detail::shared_count pn; // reference counter unsigned int m_offset; unsigned int m_size; }; template<class T> inline bool operator==(SharedArray<T> const & a, SharedArray<T> const & b) // never throws { return a.get() == b.get(); } template<class T> inline bool operator!=(SharedArray<T> const & a, SharedArray<T> const & b) // never throws { return a.get() != b.get(); } template<class T> inline bool operator<(SharedArray<T> const & a, SharedArray<T> const & b) // never throws { return std::less<T*>()(a.get(), b.get()); } template<class T> void swap(SharedArray<T> & a, SharedArray<T> & b) // never throws { a.swap(b); } template<typename T> SharedArray<T> operator+(SharedArray<T>& lhs, unsigned int offset) { return SharedArray<T>(lhs, offset); } template<typename T> SharedArray<T> operator+(unsigned int offset, SharedArray<T>& rhs) { return SharedArray<T>(rhs, offset); } } #endif //NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP <commit_msg>Modified SharedArray so that data type must be "const" for const correctness.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File SharedArray.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Scientific Computing and Imaging Institute, // University of Utah (USA) and Department of Aeronautics, Imperial // College London (UK). // // License for the specific language governing rights and limitations under // 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. // // Description: // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP #define NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP // This is a copy of boost::shared_array with minor modifications. #include <boost/config.hpp> // for broken compiler workarounds #include <boost/assert.hpp> #include <boost/checked_delete.hpp> #include <boost/detail/shared_count.hpp> #include <boost/detail/workaround.hpp> #include <boost/bind.hpp> #include <cstddef> // for std::ptrdiff_t #include <algorithm> // for std::swap #include <functional> // for std::less #include <LibUtilities/BasicUtils/mojo.hpp> #include <boost/utility/enable_if.hpp> #include <boost/type_traits.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/assert.hpp> namespace Nektar { /// \brief Wraps a reference counted T* and deletes it when it is no longer referenced. /// /// SharedArray is a replacement for boost::shared_array. It addresses the following /// problem with boost::shared_array /// /// A "const boost::shared_array<T>" still allows you to modify the internal data /// held by the array. In other words, it is possible to do the following: /// /// const boost::shared_array<double>& foo(); /// /// const boost::shared_array<double>& a = foo(); /// a[0] = 1.0; /// /// With SharedArrays, a "const SharedArray" will not allow you to modify the /// underlying data. /// /// An additional feature of a SharedArray is the ability to create a new shared array /// with an offset: /// /// SharedArray<double> coeffs = MemoryManager::AllocateSharedArray<double>(10); /// SharedArray<double> offset = coefffs+5; // offset[5] = coeffs[0] /// /// coeffs and offset point to the same underlying array, so if coeffs goes out of scope the array /// is not deleted until offset goes out of scope. /// template<class T> class SharedArray : public MojoEnabled<SharedArray<T> > { private: // Borland 5.5.1 specific workarounds typedef boost::checked_array_deleter<T> deleter; typedef SharedArray<T> this_type; public: template<typename U> friend class SharedArray; typedef T element_type; SharedArray() : px(0), pn((T*)0, deleter()), m_offset(0), m_size(0) { } explicit SharedArray(unsigned int s) : px(new T[s]), pn(px, deleter()), m_offset(0), m_size(0) { } SharedArray(T* p, unsigned int s) : px(p), pn(p, deleter()), m_offset(0), m_size(s) { } SharedArray(SharedArray<T>& rhs, unsigned int offset) : px(rhs.px), pn(rhs.pn), m_offset(offset), m_size(rhs.m_size) { } // // Requirements: D's copy constructor must not throw // // shared_array will release p by calling d(p) // template<class D> SharedArray(T* p, unsigned int s, D d) : px(p), pn(p, d), m_offset(0), m_size(s) { } /// We need to have a constructor that takes a non-const and one that /// takes a const, regardless of whether T is a const or not. /// Creates a shared array from rhs, incrementing the reference count. SharedArray(SharedArray<typename boost::remove_const<T>::type>& rhs) : px(rhs.px), pn(rhs.pn), m_offset(rhs.m_offset), m_size(rhs.m_size) { } SharedArray(SharedArray<typename boost::add_const<T>::type>& rhs) : px(rhs.px), pn(rhs.pn), m_offset(rhs.m_offset), m_size(rhs.m_size) { /// If you get a compile error pointing here then you have /// tried to create a non-constant shared array with a constant /// shared array as a parameter. This is not allowed since it would /// allow you to modify the underlying data of the constant array. BOOST_MPL_ASSERT( (boost::is_const<T>) ); } SharedArray(Temporary<SharedArray<T> > rhs) : px(rhs.GetValue().px), pn(rhs.GetValue().pn), m_offset(rhs.GetValue().m_offset), m_size(rhs.GetValue().m_size) { } SharedArray(Constant<SharedArray<typename boost::add_const<T>::type> > rhs) : px(rhs.GetValue().px), pn(rhs.GetValue().pn), m_offset(rhs.GetValue().m_offset), m_size(rhs.GetValue().m_size) { /// If you get a compile error pointing here then you have /// tried to create a non-constant shared array with a constant /// shared array as a parameter. This is not allowed since it would /// allow you to modify the underlying data of the constant array. BOOST_MPL_ASSERT( (boost::is_const<T>) ); } SharedArray(Constant<SharedArray<typename boost::remove_const<T>::type> > rhs) : px(rhs.GetValue().px), pn(rhs.GetValue().pn), m_offset(rhs.GetValue().m_offset), m_size(rhs.GetValue().m_size) { /// If you get a compile error pointing here then you have /// tried to create a non-constant shared array with a constant /// shared array as a parameter. This is not allowed since it would /// allow you to modify the underlying data of the constant array. BOOST_MPL_ASSERT( (boost::is_const<T>) ); } SharedArray<T>& operator=(SharedArray<typename boost::remove_const<T>::type>& rhs) { SharedArray<T> temp(rhs); swap(temp); return *this; } SharedArray<T>& operator=(SharedArray<typename boost::add_const<T>::type>& rhs) { /// If you get a compile error pointing here then you have /// tried to create a non-constant shared array with a constant /// shared array as a parameter. This is not allowed since it would /// allow you to modify the underlying data of the constant array. SharedArray<T> temp(rhs); swap(temp); return *this; } SharedArray<T>& operator=(Temporary<SharedArray<T> > rhs) { SharedArray<T> temp(rhs.GetValue()); swap(temp); return *this; } SharedArray<T>& operator=(Constant<SharedArray<typename boost::remove_const<T>::type> > rhs) { SharedArray<T> temp(rhs.GetValue()); swap(temp); return *this; } SharedArray<T>& operator=(Constant<SharedArray<typename boost::add_const<T>::type> > rhs) { SharedArray<T> temp(rhs.GetValue()); swap(temp); return *this; } void reset() { this_type().swap(*this); } void reset(T* p, unsigned int size) { BOOST_ASSERT(p == 0 || p != px); this_type(p, size).swap(*this); } template <class D> void reset(T * p, unsigned int size, D d) { this_type(p, size, d).swap(*this); } T& operator[] (std::ptrdiff_t i) // never throws { BOOST_ASSERT(px != 0); BOOST_ASSERT(i >= 0); return px[i + m_offset]; } const T& operator[] (std::ptrdiff_t i) const // never throws { BOOST_ASSERT(px != 0); BOOST_ASSERT(i >= 0); return px[i + m_offset]; } T* get() // never throws { return px + m_offset; } const T* get() const { return px + m_offset; } unsigned int GetSize() const { return m_size; } // implicit conversion to "bool" #if defined(__SUNPRO_CC) && BOOST_WORKAROUND(__SUNPRO_CC, <= 0x530) operator bool () const { return px != 0; } #elif defined(__MWERKS__) && BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003)) typedef T * (this_type::*unspecified_bool_type)() const; operator unspecified_bool_type() const // never throws { return px == 0? 0: &this_type::get; } #else typedef T * this_type::*unspecified_bool_type; operator unspecified_bool_type() const // never throws { return px == 0? 0: &this_type::px; } #endif bool operator! () const // never throws { return px == 0; } bool unique() const // never throws { return pn.unique(); } long use_count() const // never throws { return pn.use_count(); } void swap(SharedArray<T>& other) // never throws { std::swap(px, other.px); pn.swap(other.pn); std::swap(m_offset, other.m_offset); std::swap(m_size, other.m_size); } typedef T* iterator; typedef const T* const_iterator; iterator begin() { return px + m_offset; } iterator end() { return px + m_size; } const_iterator begin() const { return px + m_offset; } const_iterator end() const { return px + m_size; } private: //SharedArray<T>& operator=(const SharedArray<T>& rhs); T* px; // contained pointer boost::detail::shared_count pn; // reference counter unsigned int m_offset; unsigned int m_size; }; template<class T> inline bool operator==(SharedArray<T> const & a, SharedArray<T> const & b) // never throws { return a.get() == b.get(); } template<class T> inline bool operator!=(SharedArray<T> const & a, SharedArray<T> const & b) // never throws { return a.get() != b.get(); } template<class T> inline bool operator<(SharedArray<T> const & a, SharedArray<T> const & b) // never throws { return std::less<T*>()(a.get(), b.get()); } template<class T> void swap(SharedArray<T> & a, SharedArray<T> & b) // never throws { a.swap(b); } template<typename T> SharedArray<T> operator+(SharedArray<T>& lhs, unsigned int offset) { return SharedArray<T>(lhs, offset); } template<typename T> SharedArray<T> operator+(unsigned int offset, SharedArray<T>& rhs) { return SharedArray<T>(rhs, offset); } } #endif //NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP <|endoftext|>
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <libtorrent/ip_filter.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } void outgoing_ports(session& s, int _min, int _max) { allow_threading_guard guard; session_settings settings = s.settings(); settings.outgoing_ports = std::make_pair(_min, _max); s.set_settings(settings); return; } #ifndef TORRENT_DISABLE_DHT void add_dht_router(session& s, std::string router_, int port_) { allow_threading_guard guard; return s.add_dht_router(std::make_pair(router_, port_)); } #endif struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } #ifndef TORRENT_NO_DEPRECATE torrent_handle add_torrent_depr(session& s, torrent_info const& ti , boost::filesystem::path const& save, entry const& resume , storage_mode_t storage_mode, bool paused) { allow_threading_guard guard; return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor); } #endif torrent_handle add_torrent(session& s, dict params) { add_torrent_params p; if (params.has_key("ti")) p.ti = new torrent_info(extract<torrent_info const&>(params["ti"])); std::string url; if (params.has_key("tracker_url")) { url = extract<std::string>(params["tracker_url"]); p.tracker_url = url.c_str(); } if (params.has_key("info_hash")) p.info_hash = extract<sha1_hash>(params["info_hash"]); std::string name; if (params.has_key("name")) { name = extract<std::string>(params["name"]); p.name = name.c_str(); } p.save_path = fs::path(extract<std::string>(params["save_path"])); std::vector<char> resume_buf; if (params.has_key("resume_data")) { std::string resume = extract<std::string>(params["resume_data"]); resume_buf.resize(resume.size()); std::memcpy(&resume_buf[0], &resume[0], resume.size()); p.resume_data = &resume_buf; } if (params.has_key("storage_mode")) p.storage_mode = extract<storage_mode_t>(params["storage_mode"]); if (params.has_key("paused")) p.paused = params["paused"]; if (params.has_key("auto_managed")) p.auto_managed = params["auto_managed"]; if (params.has_key("duplicate_is_error")) p.duplicate_is_error = params["duplicate_is_error"]; if (params.has_key("seed_mode")) p.seed_mode = params["seed_mode"]; if (params.has_key("override_resume_data")) p.override_resume_data = params["override_resume_data"]; return s.add_torrent(p); } void start_natpmp(session& s) { allow_threading_guard guard; s.start_natpmp(); return; } void start_upnp(session& s) { allow_threading_guard guard; s.start_upnp(); return; } list get_torrents(session& s) { list ret; std::vector<torrent_handle> torrents = s.get_torrents(); for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i) { ret.append(*i); } return ret; } #ifndef TORRENT_DISABLE_GEO_IP bool load_asnum_db(session& s, std::string file) { allow_threading_guard guard; return s.load_asnum_db(file.c_str()); } bool load_country_db(session& s, std::string file) { allow_threading_guard guard; return s.load_country_db(file.c_str()); } #endif } // namespace unnamed void bind_session() { class_<session_status>("session_status") .def_readonly("has_incoming_connections", &session_status::has_incoming_connections) .def_readonly("upload_rate", &session_status::upload_rate) .def_readonly("download_rate", &session_status::download_rate) .def_readonly("payload_upload_rate", &session_status::payload_upload_rate) .def_readonly("payload_download_rate", &session_status::payload_download_rate) .def_readonly("total_download", &session_status::total_download) .def_readonly("total_upload", &session_status::total_upload) .def_readonly("total_payload_download", &session_status::total_payload_download) .def_readonly("total_payload_upload", &session_status::total_payload_upload) .def_readonly("num_peers", &session_status::num_peers) #ifndef TORRENT_DISABLE_DHT .def_readonly("dht_nodes", &session_status::dht_nodes) .def_readonly("dht_cache_nodes", &session_status::dht_node_cache) .def_readonly("dht_torrents", &session_status::dht_torrents) #endif ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_sparse", storage_mode_sparse) .value("storage_mode_compact", storage_mode_compact) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; enum_<session::session_flags_t>("session_flags_t") .value("add_default_plugins", session::add_default_plugins) .value("start_default_features", session::start_default_features) ; class_<session, boost::noncopyable>("session", no_init) .def( init<fingerprint, int>(( arg("fingerprint")=fingerprint("LT",0,1,0,0) , arg("flags")=session::start_default_features | session::add_default_plugins)) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) ) .def("outgoing_ports", &outgoing_ports) .def("is_listening", allow_threads(&session::is_listening)) .def("listen_port", allow_threads(&session::listen_port)) .def("status", allow_threads(&session::status)) #ifndef TORRENT_DISABLE_DHT .def( "add_dht_router", &add_dht_router , (arg("router"), "port") ) .def("start_dht", allow_threads(&session::start_dht)) .def("stop_dht", allow_threads(&session::stop_dht)) .def("dht_state", allow_threads(&session::dht_state)) .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) .def("dht_proxy", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>()) #endif .def("add_torrent", &add_torrent) #ifndef TORRENT_NO_DEPRECATE .def( "add_torrent", &add_torrent_depr , ( arg("resume_data") = entry(), arg("storage_mode") = storage_mode_sparse, arg("paused") = false ) ) #endif .def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none ) .def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit)) .def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit)) .def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit)) .def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit)) .def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit)) .def("download_rate_limit", allow_threads(&session::download_rate_limit)) .def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)) .def("upload_rate_limit", allow_threads(&session::upload_rate_limit)) .def("set_max_uploads", allow_threads(&session::set_max_uploads)) .def("set_max_connections", allow_threads(&session::set_max_connections)) .def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)) .def("num_connections", allow_threads(&session::num_connections)) .def("set_settings", allow_threads(&session::set_settings)) .def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>()) #ifndef TORRENT_DISABLE_ENCRYPTION .def("set_pe_settings", allow_threads(&session::set_pe_settings)) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) #endif #ifndef TORRENT_DISABLE_GEO_IP .def("load_asnum_db", &load_asnum_db) .def("load_country_db", &load_country_db) #endif .def("load_state", allow_threads(&session::load_state)) .def("state", allow_threads(&session::state)) #ifndef TORRENT_NO_DEPRECATE .def("set_severity_level", allow_threads(&session::set_severity_level)) #endif .def("set_alert_mask", allow_threads(&session::set_alert_mask)) .def("pop_alert", allow_threads(&session::pop_alert)) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) .def("peer_proxy", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>()) .def("tracker_proxy", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>()) .def("web_seed_proxy", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>()) .def("start_upnp", &start_upnp) .def("stop_upnp", allow_threads(&session::stop_upnp)) .def("start_lsd", allow_threads(&session::start_lsd)) .def("stop_lsd", allow_threads(&session::stop_lsd)) .def("start_natpmp", &start_natpmp) .def("stop_natpmp", allow_threads(&session::stop_natpmp)) .def("set_ip_filter", allow_threads(&session::set_ip_filter)) .def("find_torrent", allow_threads(&session::find_torrent)) .def("get_torrents", &get_torrents) .def("pause", allow_threads(&session::pause)) .def("resume", allow_threads(&session::resume)) .def("is_paused", allow_threads(&session::is_paused)) .def("id", allow_threads(&session::id)) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <commit_msg>Update and clean-up session.cpp in python bindings<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <libtorrent/ip_filter.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } void outgoing_ports(session& s, int _min, int _max) { allow_threading_guard guard; session_settings settings = s.settings(); settings.outgoing_ports = std::make_pair(_min, _max); s.set_settings(settings); return; } #ifndef TORRENT_DISABLE_DHT void add_dht_router(session& s, std::string router_, int port_) { allow_threading_guard guard; return s.add_dht_router(std::make_pair(router_, port_)); } #endif struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } #ifndef TORRENT_NO_DEPRECATE torrent_handle add_torrent_depr(session& s, torrent_info const& ti , boost::filesystem::path const& save, entry const& resume , storage_mode_t storage_mode, bool paused) { allow_threading_guard guard; return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor); } #endif torrent_handle add_torrent(session& s, dict params) { add_torrent_params p; if (params.has_key("ti")) p.ti = new torrent_info(extract<torrent_info const&>(params["ti"])); std::string url; if (params.has_key("tracker_url")) { url = extract<std::string>(params["tracker_url"]); p.tracker_url = url.c_str(); } if (params.has_key("info_hash")) p.info_hash = extract<sha1_hash>(params["info_hash"]); std::string name; if (params.has_key("name")) { name = extract<std::string>(params["name"]); p.name = name.c_str(); } p.save_path = fs::path(extract<std::string>(params["save_path"])); std::vector<char> resume_buf; if (params.has_key("resume_data")) { std::string resume = extract<std::string>(params["resume_data"]); resume_buf.resize(resume.size()); std::memcpy(&resume_buf[0], &resume[0], resume.size()); p.resume_data = &resume_buf; } if (params.has_key("storage_mode")) p.storage_mode = extract<storage_mode_t>(params["storage_mode"]); if (params.has_key("paused")) p.paused = params["paused"]; if (params.has_key("auto_managed")) p.auto_managed = params["auto_managed"]; if (params.has_key("duplicate_is_error")) p.duplicate_is_error = params["duplicate_is_error"]; if (params.has_key("seed_mode")) p.seed_mode = params["seed_mode"]; if (params.has_key("override_resume_data")) p.override_resume_data = params["override_resume_data"]; return s.add_torrent(p); } void start_natpmp(session& s) { allow_threading_guard guard; s.start_natpmp(); return; } void start_upnp(session& s) { allow_threading_guard guard; s.start_upnp(); return; } list get_torrents(session& s) { list ret; std::vector<torrent_handle> torrents = s.get_torrents(); for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i) { ret.append(*i); } return ret; } #ifndef TORRENT_DISABLE_GEO_IP bool load_asnum_db(session& s, std::string file) { allow_threading_guard guard; return s.load_asnum_db(file.c_str()); } bool load_country_db(session& s, std::string file) { allow_threading_guard guard; return s.load_country_db(file.c_str()); } #endif } // namespace unnamed void bind_session() { class_<session_status>("session_status") .def_readonly("has_incoming_connections", &session_status::has_incoming_connections) .def_readonly("upload_rate", &session_status::upload_rate) .def_readonly("download_rate", &session_status::download_rate) .def_readonly("total_download", &session_status::total_download) .def_readonly("total_upload", &session_status::total_upload) .def_readonly("payload_upload_rate", &session_status::payload_upload_rate) .def_readonly("payload_download_rate", &session_status::payload_download_rate) .def_readonly("total_payload_download", &session_status::total_payload_download) .def_readonly("total_payload_upload", &session_status::total_payload_upload) .def_readonly("ip_overhead_upload_rate", &session_status::ip_overhead_upload_rate) .def_readonly("ip_overhead_download_rate", &session_status::ip_overhead_download_rate) .def_readonly("total_ip_overhead_download", &session_status::total_ip_overhead_download) .def_readonly("total_ip_overhead_upload", &session_status::total_ip_overhead_upload) .def_readonly("dht_upload_rate", &session_status::dht_upload_rate) .def_readonly("dht_download_rate", &session_status::dht_download_rate) .def_readonly("total_dht_download", &session_status::total_dht_download) .def_readonly("total_dht_upload", &session_status::total_dht_upload) .def_readonly("tracker_upload_rate", &session_status::tracker_upload_rate) .def_readonly("tracker_download_rate", &session_status::tracker_download_rate) .def_readonly("total_tracker_download", &session_status::total_tracker_download) .def_readonly("total_tracker_upload", &session_status::total_tracker_upload) .def_readonly("total_redundant_bytes", &session_status::total_redundant_bytes) .def_readonly("total_failed_bytes", &session_status::total_failed_bytes) .def_readonly("num_peers", &session_status::num_peers) .def_readonly("num_unchoked", &session_status::num_unchoked) .def_readonly("allowed_upload_slots", &session_status::allowed_upload_slots) .def_readonly("up_bandwidth_queue", &session_status::up_bandwidth_queue) .def_readonly("down_bandwidth_queue", &session_status::down_bandwidth_queue) .def_readonly("up_bandwidth_bytes_queue", &session_status::up_bandwidth_bytes_queue) .def_readonly("down_bandwidth_bytes_queue", &session_status::down_bandwidth_bytes_queue) .def_readonly("optimistic_unchoke_counter", &session_status::optimistic_unchoke_counter) .def_readonly("unchoke_counter", &session_status::unchoke_counter) #ifndef TORRENT_DISABLE_DHT .def_readonly("dht_nodes", &session_status::dht_nodes) .def_readonly("dht_cache_nodes", &session_status::dht_node_cache) .def_readonly("dht_torrents", &session_status::dht_torrents) .def_readonly("dht_global_nodes", &session_status::dht_global_nodes) .def_readonly("active_requests", &session_status::active_requests) #endif ; class_<dht_lookup>("dht_lookup") .def_readonly("type", &dht_lookup::type) .def_readonly("outstanding_requests", &dht_lookup::outstanding_requests) .def_readonly("timeouts", &dht_lookup::timeouts) .def_readonly("response", &dht_lookup::responses) .def_readonly("branch_factor", &dht_lookup::branch_factor) ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_sparse", storage_mode_sparse) .value("storage_mode_compact", storage_mode_compact) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; enum_<session::session_flags_t>("session_flags_t") .value("add_default_plugins", session::add_default_plugins) .value("start_default_features", session::start_default_features) ; class_<session, boost::noncopyable>("session", no_init) .def( init<fingerprint, int>(( arg("fingerprint")=fingerprint("LT",0,1,0,0) , arg("flags")=session::start_default_features | session::add_default_plugins)) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) ) .def("outgoing_ports", &outgoing_ports) .def("is_listening", allow_threads(&session::is_listening)) .def("listen_port", allow_threads(&session::listen_port)) .def("status", allow_threads(&session::status)) #ifndef TORRENT_DISABLE_DHT .def( "add_dht_router", &add_dht_router , (arg("router"), "port") ) .def("start_dht", allow_threads(&session::start_dht)) .def("stop_dht", allow_threads(&session::stop_dht)) .def("dht_state", allow_threads(&session::dht_state)) .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) .def("dht_proxy", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>()) #endif .def("add_torrent", &add_torrent) #ifndef TORRENT_NO_DEPRECATE .def( "add_torrent", &add_torrent_depr , ( arg("resume_data") = entry(), arg("storage_mode") = storage_mode_sparse, arg("paused") = false ) ) #endif .def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none ) .def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit)) .def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit)) .def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit)) .def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit)) .def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit)) .def("download_rate_limit", allow_threads(&session::download_rate_limit)) .def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)) .def("upload_rate_limit", allow_threads(&session::upload_rate_limit)) .def("set_max_uploads", allow_threads(&session::set_max_uploads)) .def("set_max_connections", allow_threads(&session::set_max_connections)) .def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)) .def("num_connections", allow_threads(&session::num_connections)) .def("set_settings", allow_threads(&session::set_settings)) .def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>()) #ifndef TORRENT_DISABLE_ENCRYPTION .def("set_pe_settings", allow_threads(&session::set_pe_settings)) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) #endif #ifndef TORRENT_DISABLE_GEO_IP .def("load_asnum_db", &load_asnum_db) .def("load_country_db", &load_country_db) #endif .def("load_state", allow_threads(&session::load_state)) .def("state", allow_threads(&session::state)) #ifndef TORRENT_NO_DEPRECATE .def("set_severity_level", allow_threads(&session::set_severity_level)) #endif .def("set_alert_mask", allow_threads(&session::set_alert_mask)) .def("pop_alert", allow_threads(&session::pop_alert)) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) .def("peer_proxy", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>()) .def("tracker_proxy", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>()) .def("web_seed_proxy", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>()) .def("start_upnp", &start_upnp) .def("stop_upnp", allow_threads(&session::stop_upnp)) .def("start_lsd", allow_threads(&session::start_lsd)) .def("stop_lsd", allow_threads(&session::stop_lsd)) .def("start_natpmp", &start_natpmp) .def("stop_natpmp", allow_threads(&session::stop_natpmp)) .def("set_ip_filter", allow_threads(&session::set_ip_filter)) .def("find_torrent", allow_threads(&session::find_torrent)) .def("get_torrents", &get_torrents) .def("pause", allow_threads(&session::pause)) .def("resume", allow_threads(&session::resume)) .def("is_paused", allow_threads(&session::is_paused)) .def("id", allow_threads(&session::id)) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlitemm.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2004-07-12 13:36:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include <hintids.hxx> #ifndef _SVX_UNOMID_HXX #include <svx/unomid.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLITMAP_HXX #include "xmlitmap.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _UNOMID_H #include <unomid.h> #endif using namespace ::xmloff::token; #define M_E( p, l, w, m ) \ { XML_NAMESPACE_##p, XML_##l, w, m } #define M_E_SI( p, l, w, m ) \ { XML_NAMESPACE_##p, XML_##l, w, MID_FLAG_SPECIAL_ITEM_IMPORT|m } #define M_E_SE( p, l, w, m ) \ { XML_NAMESPACE_##p, XML_##l, w, MID_FLAG_SPECIAL_ITEM_EXPORT|m } #define M_END { 0, XML_TOKEN_INVALID, 0, 0 } SvXMLItemMapEntry aXMLTableItemMap[] = { // RES_FILL_ORDER // not required // RES_FRM_SIZE M_E_SE( STYLE, WIDTH, RES_FRM_SIZE, MID_FRMSIZE_WIDTH ), M_E_SE( STYLE, REL_WIDTH, RES_FRM_SIZE, MID_FRMSIZE_REL_WIDTH ), // RES_PAPER_BIN // not required // TODO: RES_LR_SPACE M_E_SE( FO, MARGIN_LEFT, RES_LR_SPACE, MID_L_MARGIN ), M_E_SE( FO, MARGIN_RIGHT, RES_LR_SPACE, MID_R_MARGIN ), // RES_UL_SPACE M_E( FO, MARGIN_TOP, RES_UL_SPACE, MID_UP_MARGIN ), M_E( FO, MARGIN_BOTTOM, RES_UL_SPACE, MID_LO_MARGIN ), // RES_PAGEDESC M_E( STYLE, PAGE_NUMBER, RES_PAGEDESC, MID_PAGEDESC_PAGENUMOFFSET), // RES_BREAK M_E( FO, BREAK_BEFORE, RES_BREAK, MID_BREAK_BEFORE ), M_E( FO, BREAK_AFTER, RES_BREAK, MID_BREAK_AFTER ), // RES_CNTNT // not required // RES_HEADER // not required // RES_FOOTER // not required // RES_PRINT // not required // RES_OPAQUE // not required // RES_PROTECT // not required // RES_SURROUND // not required // RES_VERT_ORIENT // not required // RES_HORI_ORIENT M_E( TABLE, ALIGN, RES_HORI_ORIENT, 0 ), // RES_ANCHOR // not required // RES_BACKGROUND M_E( FO, BACKGROUND_COLOR, RES_BACKGROUND, MID_BACK_COLOR ), M_E( STYLE, BACKGROUND_IMAGE, RES_BACKGROUND, MID_FLAG_ELEMENT_ITEM ), // RES_BOX // not required // RES_SHADOW M_E( STYLE, SHADOW, RES_SHADOW, 0 ), // RES_FRMMACRO // not required // RES_COL // not required // RES_KEEP M_E( FO, KEEP_WITH_NEXT, RES_KEEP, 0 ), // RES_URL // not required // RES_EDIT_IN_READONLY // not required // RES_LAYOUT_SPLIT M_E( STYLE, MAY_BREAK_BETWEEN_ROWS, RES_LAYOUT_SPLIT, 0 ), // RES_CHAIN // not required // RES_LINENUMBER // not required // RES_FTN_AT_TXTEND // not required // RES_END_AT_TXTEND // not required // RES_UNKNOWNATR_CONTAINER M_E_SE( TEXT, XMLNS, RES_UNKNOWNATR_CONTAINER, 0 ), // RES_FRAMEDIR M_E( STYLE, WRITING_MODE, RES_FRAMEDIR, 0 ), // RES_COLLAPSING_BORDERS M_E( TABLE, BORDER_MODEL, RES_COLLAPSING_BORDERS, 0 ), M_END }; SvXMLItemMapEntry aXMLTableColItemMap[] = { M_E_SI( STYLE, COLUMN_WIDTH, RES_FRM_SIZE, MID_FRMSIZE_COL_WIDTH ), M_E( STYLE, REL_COLUMN_WIDTH, RES_FRM_SIZE, MID_FRMSIZE_REL_COL_WIDTH ), M_END }; SvXMLItemMapEntry aXMLTableRowItemMap[] = { // RES_FILL_ORDER // not required // RES_FRM_SIZE M_E( STYLE, ROW_HEIGHT, RES_FRM_SIZE, MID_FRMSIZE_FIX_HEIGHT ), M_E( STYLE, MIN_ROW_HEIGHT, RES_FRM_SIZE, MID_FRMSIZE_MIN_HEIGHT ), // RES_PAPER_BIN // not required // RES_LR_SPACE // not required // RES_UL_SPACE // not required // RES_PAGEDESC // not required // RES_BREAK // not required // RES_CNTNT // not required // RES_HEADER // not required // RES_FOOTER // not required // RES_PRINT // not required // RES_OPAQUE // not required // RES_PROTECT // not required // RES_SURROUND // not required // RES_VERT_ORIENT // not required // RES_HORI_ORIENT // not required // RES_ANCHOR // not required // RES_BACKGROUND M_E( FO, BACKGROUND_COLOR, RES_BACKGROUND, MID_BACK_COLOR ), M_E( STYLE, BACKGROUND_IMAGE, RES_BACKGROUND, MID_FLAG_ELEMENT_ITEM ), // RES_BOX // not required // RES_ANCHOR // not required // RES_SHADOW // not required // RES_FRMMACRO // not required // RES_COL // not required // RES_KEEP // not required // RES_URL // not required // RES_EDIT_IN_READONLY // not required // RES_LAYOUT_SPLIT M_E( STYLE, KEEP_TOGETHER, RES_ROW_SPLIT, 0 ), // RES_CHAIN // not required // RES_LINENUMBER // not required // RES_FTN_AT_TXTEND // not required // RES_END_AT_TXTEND // not required // RES_UNKNOWNATR_CONTAINER M_E_SE( TEXT, XMLNS, RES_UNKNOWNATR_CONTAINER, 0 ), M_END }; SvXMLItemMapEntry aXMLTableCellItemMap[] = { // RES_FILL_ORDER // not required // RES_FRM_SIZE // not required // RES_PAPER_BIN // not required // RES_LR_SPACE // not required // RES_UL_SPACE // not required // RES_PAGEDESC // not required // RES_BREAK // not required // RES_CNTNT // not required // RES_HEADER // not required // RES_FOOTER // not required // RES_PRINT // not required // RES_OPAQUE // not required // RES_PROTECT // not required // RES_SURROUND // not required // RES_VERT_ORIENT M_E( FO, VERTICAL_ALIGN, RES_VERT_ORIENT, 0 ), // RES_HORI_ORIENT // not required // RES_ANCHOR // not required // RES_BACKGROUND M_E( FO, BACKGROUND_COLOR, RES_BACKGROUND, MID_BACK_COLOR ), M_E( STYLE, BACKGROUND_IMAGE, RES_BACKGROUND, MID_FLAG_ELEMENT_ITEM ), // RES_BOX M_E( STYLE, BORDER_LINE_WIDTH, RES_BOX, ALL_BORDER_LINE_WIDTH ), M_E( STYLE, BORDER_LINE_WIDTH_LEFT, RES_BOX, LEFT_BORDER_LINE_WIDTH ), M_E( STYLE, BORDER_LINE_WIDTH_RIGHT, RES_BOX, RIGHT_BORDER_LINE_WIDTH ), M_E( STYLE, BORDER_LINE_WIDTH_TOP, RES_BOX, TOP_BORDER_LINE_WIDTH ), M_E( STYLE, BORDER_LINE_WIDTH_BOTTOM, RES_BOX, BOTTOM_BORDER_LINE_WIDTH ), M_E( FO, PADDING, RES_BOX, ALL_BORDER_PADDING ), M_E( FO, PADDING_LEFT, RES_BOX, LEFT_BORDER_PADDING ), M_E( FO, PADDING_RIGHT, RES_BOX, RIGHT_BORDER_PADDING ), M_E( FO, PADDING_TOP, RES_BOX, TOP_BORDER_PADDING ), M_E( FO, PADDING_BOTTOM, RES_BOX, BOTTOM_BORDER_PADDING ), M_E( FO, BORDER, RES_BOX, ALL_BORDER ), M_E( FO, BORDER_LEFT, RES_BOX, LEFT_BORDER ), M_E( FO, BORDER_RIGHT, RES_BOX, RIGHT_BORDER ), M_E( FO, BORDER_TOP, RES_BOX, TOP_BORDER ), M_E( FO, BORDER_BOTTOM, RES_BOX, BOTTOM_BORDER ), // RES_SHADOW // not required // RES_FRMMACRO // not required // RES_COL // not required // RES_KEEP // not required // RES_URL // not required // RES_EDIT_IN_READONLY // not required // RES_LAYOUT_SPLIT // not required // RES_CHAIN // not required // RES_LINENUMBER // not required // RES_FTN_AT_TXTEND // not required // RES_END_AT_TXTEND // not required // RES_UNKNOWNATR_CONTAINER M_E_SE( TEXT, XMLNS, RES_UNKNOWNATR_CONTAINER, 0 ), // RES_FRAMEDIR M_E( STYLE, WRITING_MODE, RES_FRAMEDIR, 0 ), M_END }; <commit_msg>INTEGRATION: CWS oasis (1.9.132); FILE MERGED 2004/06/12 22:42:21 mib 1.9.132.2: RESYNC: (1.9-1.10); FILE MERGED 2004/04/22 15:19:24 mib 1.9.132.1: - renamed most *:value attributes to office:value (#i20153#) - renamed some more formatting properties (#i20153#)<commit_after>/************************************************************************* * * $RCSfile: xmlitemm.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2004-07-13 09:08:17 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include <hintids.hxx> #ifndef _SVX_UNOMID_HXX #include <svx/unomid.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLITMAP_HXX #include "xmlitmap.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _UNOMID_H #include <unomid.h> #endif using namespace ::xmloff::token; #define M_E( p, l, w, m ) \ { XML_NAMESPACE_##p, XML_##l, w, m } #define M_E_SI( p, l, w, m ) \ { XML_NAMESPACE_##p, XML_##l, w, MID_FLAG_SPECIAL_ITEM_IMPORT|m } #define M_E_SE( p, l, w, m ) \ { XML_NAMESPACE_##p, XML_##l, w, MID_FLAG_SPECIAL_ITEM_EXPORT|m } #define M_END { 0, XML_TOKEN_INVALID, 0, 0 } SvXMLItemMapEntry aXMLTableItemMap[] = { // RES_FILL_ORDER // not required // RES_FRM_SIZE M_E_SE( STYLE, WIDTH, RES_FRM_SIZE, MID_FRMSIZE_WIDTH ), M_E_SE( STYLE, REL_WIDTH, RES_FRM_SIZE, MID_FRMSIZE_REL_WIDTH ), // RES_PAPER_BIN // not required // TODO: RES_LR_SPACE M_E_SE( FO, MARGIN_LEFT, RES_LR_SPACE, MID_L_MARGIN ), M_E_SE( FO, MARGIN_RIGHT, RES_LR_SPACE, MID_R_MARGIN ), // RES_UL_SPACE M_E( FO, MARGIN_TOP, RES_UL_SPACE, MID_UP_MARGIN ), M_E( FO, MARGIN_BOTTOM, RES_UL_SPACE, MID_LO_MARGIN ), // RES_PAGEDESC M_E( STYLE, PAGE_NUMBER, RES_PAGEDESC, MID_PAGEDESC_PAGENUMOFFSET), // RES_BREAK M_E( FO, BREAK_BEFORE, RES_BREAK, MID_BREAK_BEFORE ), M_E( FO, BREAK_AFTER, RES_BREAK, MID_BREAK_AFTER ), // RES_CNTNT // not required // RES_HEADER // not required // RES_FOOTER // not required // RES_PRINT // not required // RES_OPAQUE // not required // RES_PROTECT // not required // RES_SURROUND // not required // RES_VERT_ORIENT // not required // RES_HORI_ORIENT M_E( TABLE, ALIGN, RES_HORI_ORIENT, 0 ), // RES_ANCHOR // not required // RES_BACKGROUND M_E( FO, BACKGROUND_COLOR, RES_BACKGROUND, MID_BACK_COLOR ), M_E( STYLE, BACKGROUND_IMAGE, RES_BACKGROUND, MID_FLAG_ELEMENT_ITEM ), // RES_BOX // not required // RES_SHADOW M_E( STYLE, SHADOW, RES_SHADOW, 0 ), // RES_FRMMACRO // not required // RES_COL // not required // RES_KEEP M_E( FO, KEEP_WITH_NEXT, RES_KEEP, 0 ), // RES_URL // not required // RES_EDIT_IN_READONLY // not required // RES_LAYOUT_SPLIT M_E( STYLE, MAY_BREAK_BETWEEN_ROWS, RES_LAYOUT_SPLIT, 0 ), // RES_CHAIN // not required // RES_LINENUMBER // not required // RES_FTN_AT_TXTEND // not required // RES_END_AT_TXTEND // not required // RES_UNKNOWNATR_CONTAINER M_E_SE( TEXT, XMLNS, RES_UNKNOWNATR_CONTAINER, 0 ), // RES_FRAMEDIR M_E( STYLE, WRITING_MODE, RES_FRAMEDIR, 0 ), // RES_COLLAPSING_BORDERS M_E( TABLE, BORDER_MODEL, RES_COLLAPSING_BORDERS, 0 ), M_END }; SvXMLItemMapEntry aXMLTableColItemMap[] = { M_E_SI( STYLE, COLUMN_WIDTH, RES_FRM_SIZE, MID_FRMSIZE_COL_WIDTH ), M_E( STYLE, REL_COLUMN_WIDTH, RES_FRM_SIZE, MID_FRMSIZE_REL_COL_WIDTH ), M_END }; SvXMLItemMapEntry aXMLTableRowItemMap[] = { // RES_FILL_ORDER // not required // RES_FRM_SIZE M_E( STYLE, ROW_HEIGHT, RES_FRM_SIZE, MID_FRMSIZE_FIX_HEIGHT ), M_E( STYLE, MIN_ROW_HEIGHT, RES_FRM_SIZE, MID_FRMSIZE_MIN_HEIGHT ), // RES_PAPER_BIN // not required // RES_LR_SPACE // not required // RES_UL_SPACE // not required // RES_PAGEDESC // not required // RES_BREAK // not required // RES_CNTNT // not required // RES_HEADER // not required // RES_FOOTER // not required // RES_PRINT // not required // RES_OPAQUE // not required // RES_PROTECT // not required // RES_SURROUND // not required // RES_VERT_ORIENT // not required // RES_HORI_ORIENT // not required // RES_ANCHOR // not required // RES_BACKGROUND M_E( FO, BACKGROUND_COLOR, RES_BACKGROUND, MID_BACK_COLOR ), M_E( STYLE, BACKGROUND_IMAGE, RES_BACKGROUND, MID_FLAG_ELEMENT_ITEM ), // RES_BOX // not required // RES_ANCHOR // not required // RES_SHADOW // not required // RES_FRMMACRO // not required // RES_COL // not required // RES_KEEP // not required // RES_URL // not required // RES_EDIT_IN_READONLY // not required // RES_LAYOUT_SPLIT M_E( STYLE, KEEP_TOGETHER, RES_ROW_SPLIT, 0 ), // RES_CHAIN // not required // RES_LINENUMBER // not required // RES_FTN_AT_TXTEND // not required // RES_END_AT_TXTEND // not required // RES_UNKNOWNATR_CONTAINER M_E_SE( TEXT, XMLNS, RES_UNKNOWNATR_CONTAINER, 0 ), M_END }; SvXMLItemMapEntry aXMLTableCellItemMap[] = { // RES_FILL_ORDER // not required // RES_FRM_SIZE // not required // RES_PAPER_BIN // not required // RES_LR_SPACE // not required // RES_UL_SPACE // not required // RES_PAGEDESC // not required // RES_BREAK // not required // RES_CNTNT // not required // RES_HEADER // not required // RES_FOOTER // not required // RES_PRINT // not required // RES_OPAQUE // not required // RES_PROTECT // not required // RES_SURROUND // not required // RES_VERT_ORIENT M_E( STYLE, VERTICAL_ALIGN, RES_VERT_ORIENT, 0 ), // RES_HORI_ORIENT // not required // RES_ANCHOR // not required // RES_BACKGROUND M_E( FO, BACKGROUND_COLOR, RES_BACKGROUND, MID_BACK_COLOR ), M_E( STYLE, BACKGROUND_IMAGE, RES_BACKGROUND, MID_FLAG_ELEMENT_ITEM ), // RES_BOX M_E( STYLE, BORDER_LINE_WIDTH, RES_BOX, ALL_BORDER_LINE_WIDTH ), M_E( STYLE, BORDER_LINE_WIDTH_LEFT, RES_BOX, LEFT_BORDER_LINE_WIDTH ), M_E( STYLE, BORDER_LINE_WIDTH_RIGHT, RES_BOX, RIGHT_BORDER_LINE_WIDTH ), M_E( STYLE, BORDER_LINE_WIDTH_TOP, RES_BOX, TOP_BORDER_LINE_WIDTH ), M_E( STYLE, BORDER_LINE_WIDTH_BOTTOM, RES_BOX, BOTTOM_BORDER_LINE_WIDTH ), M_E( FO, PADDING, RES_BOX, ALL_BORDER_PADDING ), M_E( FO, PADDING_LEFT, RES_BOX, LEFT_BORDER_PADDING ), M_E( FO, PADDING_RIGHT, RES_BOX, RIGHT_BORDER_PADDING ), M_E( FO, PADDING_TOP, RES_BOX, TOP_BORDER_PADDING ), M_E( FO, PADDING_BOTTOM, RES_BOX, BOTTOM_BORDER_PADDING ), M_E( FO, BORDER, RES_BOX, ALL_BORDER ), M_E( FO, BORDER_LEFT, RES_BOX, LEFT_BORDER ), M_E( FO, BORDER_RIGHT, RES_BOX, RIGHT_BORDER ), M_E( FO, BORDER_TOP, RES_BOX, TOP_BORDER ), M_E( FO, BORDER_BOTTOM, RES_BOX, BOTTOM_BORDER ), // RES_SHADOW // not required // RES_FRMMACRO // not required // RES_COL // not required // RES_KEEP // not required // RES_URL // not required // RES_EDIT_IN_READONLY // not required // RES_LAYOUT_SPLIT // not required // RES_CHAIN // not required // RES_LINENUMBER // not required // RES_FTN_AT_TXTEND // not required // RES_END_AT_TXTEND // not required // RES_UNKNOWNATR_CONTAINER M_E_SE( TEXT, XMLNS, RES_UNKNOWNATR_CONTAINER, 0 ), // RES_FRAMEDIR M_E( STYLE, WRITING_MODE, RES_FRAMEDIR, 0 ), M_END }; <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #include <uavcan_lpc11c24/clock.hpp> #include <chip.h> #include "internal.hpp" namespace uavcan_lpc11c24 { namespace clock { namespace { bool initialized = false; bool utc_set = false; int32_t utc_correction_usec_per_overflow_x16 = 0; int64_t prev_adjustment = 0; uint64_t time_mono = 0; uint64_t time_utc = 0; /** * If this value is too large for the given core clock, reload value will be out of the 24-bit integer range. * This will be detected at run time during timer initialization - refer to SysTick_Config(). */ const uint32_t USecPerOverflow = 65536 * 2; const int32_t MaxUtcSpeedCorrectionX16 = 100 * 16; } __attribute((noreturn)) void fail() { while (true) { } } void init() { CriticalSectionLocker lock; if (!initialized) { initialized = true; if ((SystemCoreClock % 1000000) != 0) // Core clock frequency validation { fail(); } if (SysTick_Config((SystemCoreClock / 1000000) * USecPerOverflow) != 0) { fail(); } } } static uint64_t sampleFromCriticalSection(const volatile uint64_t* const value) { const uint32_t reload = SysTick->LOAD + 1; // SysTick counts downwards, hence the value subtracted from reload volatile uint64_t time = *value; volatile uint32_t cycles = reload - SysTick->VAL; if ((SCB->ICSR & SCB_ICSR_PENDSTSET_Msk) == SCB_ICSR_PENDSTSET_Msk) { cycles = reload - SysTick->VAL; time += USecPerOverflow; } return time + (cycles / (SystemCoreClock / 1000000)); } uint64_t getUtcUSecFromCanInterrupt() { return utc_set ? sampleFromCriticalSection(&time_utc) : 0; } uavcan::MonotonicTime getMonotonic() { uint64_t usec = 0; { CriticalSectionLocker locker; usec = sampleFromCriticalSection(&time_mono); } return uavcan::MonotonicTime::fromUSec(usec); } uavcan::UtcTime getUtc() { uint64_t usec = 0; if (utc_set) { CriticalSectionLocker locker; usec = sampleFromCriticalSection(&time_utc); } return uavcan::UtcTime::fromUSec(usec); } uavcan::UtcDuration getPrevUtcAdjustment() { return uavcan::UtcDuration::fromUSec(prev_adjustment); } void adjustUtc(uavcan::UtcDuration adjustment) { const int64_t adj_delta = adjustment.toUSec() - prev_adjustment; // This is the P term prev_adjustment = adjustment.toUSec(); utc_correction_usec_per_overflow_x16 += adjustment.isPositive() ? 1 : -1; // I utc_correction_usec_per_overflow_x16 += (adj_delta > 0) ? 1 : -1; // P utc_correction_usec_per_overflow_x16 = std::max(utc_correction_usec_per_overflow_x16, -MaxUtcSpeedCorrectionX16); utc_correction_usec_per_overflow_x16 = std::min(utc_correction_usec_per_overflow_x16, MaxUtcSpeedCorrectionX16); if (adjustment.getAbs().toMSec() > 2 || !utc_set) { const int64_t adj_usec = adjustment.toUSec(); { CriticalSectionLocker locker; if ((adj_usec < 0) && uint64_t(-adj_usec) > time_utc) { time_utc = 1; } else { time_utc += adj_usec; } } if (!utc_set) { utc_set = true; utc_correction_usec_per_overflow_x16 = 0; } } } } // namespace clock SystemClock SystemClock::self; SystemClock& SystemClock::instance() { clock::init(); return self; } } /* * Timer interrupt handler */ extern "C" { void SysTick_Handler() { using namespace uavcan_lpc11c24::clock; if (initialized) { time_mono += USecPerOverflow; if (utc_set) { // Values below 16 are ignored time_utc += USecPerOverflow + (utc_correction_usec_per_overflow_x16 / 16); } } else { fail(); } } } <commit_msg>LPC11C24: Fixed undefined behavior in clock driver<commit_after>/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #include <uavcan_lpc11c24/clock.hpp> #include <chip.h> #include "internal.hpp" namespace uavcan_lpc11c24 { namespace clock { namespace { bool initialized = false; bool utc_set = false; int32_t utc_correction_usec_per_overflow_x16 = 0; int64_t prev_adjustment = 0; uint64_t time_mono = 0; uint64_t time_utc = 0; /** * If this value is too large for the given core clock, reload value will be out of the 24-bit integer range. * This will be detected at run time during timer initialization - refer to SysTick_Config(). */ const uint32_t USecPerOverflow = 65536 * 2; const int32_t MaxUtcSpeedCorrectionX16 = 100 * 16; } __attribute((noreturn)) void fail() { while (true) { } } void init() { CriticalSectionLocker lock; if (!initialized) { initialized = true; if ((SystemCoreClock % 1000000) != 0) // Core clock frequency validation { fail(); } if (SysTick_Config((SystemCoreClock / 1000000) * USecPerOverflow) != 0) { fail(); } } } static uint64_t sampleFromCriticalSection(const volatile uint64_t* const value) { const uint32_t reload = SysTick->LOAD + 1; // SysTick counts downwards, hence the value subtracted from reload volatile uint64_t time = *value; volatile uint32_t cycles = reload - SysTick->VAL; if ((SCB->ICSR & SCB_ICSR_PENDSTSET_Msk) == SCB_ICSR_PENDSTSET_Msk) { cycles = reload - SysTick->VAL; time += USecPerOverflow; } const uint32_t cycles_per_usec = SystemCoreClock / 1000000; return time + (cycles / cycles_per_usec); } uint64_t getUtcUSecFromCanInterrupt() { return utc_set ? sampleFromCriticalSection(&time_utc) : 0; } uavcan::MonotonicTime getMonotonic() { uint64_t usec = 0; { CriticalSectionLocker locker; usec = sampleFromCriticalSection(&time_mono); } return uavcan::MonotonicTime::fromUSec(usec); } uavcan::UtcTime getUtc() { uint64_t usec = 0; if (utc_set) { CriticalSectionLocker locker; usec = sampleFromCriticalSection(&time_utc); } return uavcan::UtcTime::fromUSec(usec); } uavcan::UtcDuration getPrevUtcAdjustment() { return uavcan::UtcDuration::fromUSec(prev_adjustment); } void adjustUtc(uavcan::UtcDuration adjustment) { const int64_t adj_delta = adjustment.toUSec() - prev_adjustment; // This is the P term prev_adjustment = adjustment.toUSec(); utc_correction_usec_per_overflow_x16 += adjustment.isPositive() ? 1 : -1; // I utc_correction_usec_per_overflow_x16 += (adj_delta > 0) ? 1 : -1; // P utc_correction_usec_per_overflow_x16 = std::max(utc_correction_usec_per_overflow_x16, -MaxUtcSpeedCorrectionX16); utc_correction_usec_per_overflow_x16 = std::min(utc_correction_usec_per_overflow_x16, MaxUtcSpeedCorrectionX16); if (adjustment.getAbs().toMSec() > 2 || !utc_set) { const int64_t adj_usec = adjustment.toUSec(); { CriticalSectionLocker locker; if ((adj_usec < 0) && uint64_t(-adj_usec) > time_utc) { time_utc = 1; } else { time_utc += adj_usec; } } if (!utc_set) { utc_set = true; utc_correction_usec_per_overflow_x16 = 0; } } } } // namespace clock SystemClock SystemClock::self; SystemClock& SystemClock::instance() { clock::init(); return self; } } /* * Timer interrupt handler */ extern "C" { void SysTick_Handler() { using namespace uavcan_lpc11c24::clock; if (initialized) { time_mono += USecPerOverflow; if (utc_set) { // Values below 16 are ignored time_utc += USecPerOverflow + (utc_correction_usec_per_overflow_x16 / 16); } } else { fail(); } } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_HPP #define MAPNIK_IMAGE_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/pixel_types.hpp> namespace mapnik { namespace detail { struct MAPNIK_DECL buffer { explicit buffer(std::size_t size); buffer(buffer && rhs) noexcept; buffer(buffer const& rhs); ~buffer(); buffer& operator=(buffer rhs); bool operator!() const; void swap(buffer & rhs); unsigned char* data(); unsigned char const* data() const; std::size_t size() const; private: std::size_t size_; unsigned char* data_; }; template <std::size_t max_size> struct image_dimensions { image_dimensions(int width, int height); image_dimensions(image_dimensions const& other) = default; image_dimensions(image_dimensions && other) = default; image_dimensions& operator= (image_dimensions rhs); std::size_t width() const; std::size_t height() const; private: std::size_t width_; std::size_t height_; }; } // end ns detail template <typename T> class image { public: using pixel = T; using pixel_type = typename T::type; static const image_dtype dtype = T::id; static constexpr std::size_t pixel_size = sizeof(pixel_type); private: detail::image_dimensions<65535> dimensions_; detail::buffer buffer_; pixel_type *pData_; double offset_; double scaling_; bool premultiplied_alpha_; bool painted_; public: image(); image(int width, int height, bool initialize = true, bool premultiplied = false, bool painted = false); image(image<T> const& rhs); image(image<T> && rhs) noexcept; image<T>& operator=(image<T> rhs); image<T>const& operator=(image<T> const& rhs) const; bool operator==(image<T> const& rhs) const; bool operator<(image<T> const& rhs) const; void swap(image<T> & rhs); pixel_type& operator() (std::size_t i, std::size_t j); const pixel_type& operator() (std::size_t i, std::size_t j) const; std::size_t width() const; std::size_t height() const; std::size_t size() const; std::size_t row_size() const; void set(pixel_type const& t); const pixel_type* getData() const; pixel_type* getData(); const unsigned char* getBytes() const; unsigned char* getBytes(); const pixel_type* getRow(std::size_t row) const; const pixel_type* getRow(std::size_t row, std::size_t x0) const; pixel_type* getRow(std::size_t row); pixel_type* getRow(std::size_t row, std::size_t x0); void setRow(std::size_t row, pixel_type const* buf, std::size_t size); void setRow(std::size_t row, std::size_t x0, std::size_t x1, pixel_type const* buf); double get_offset() const; void set_offset(double set); double get_scaling() const; void set_scaling(double set); bool get_premultiplied() const; void set_premultiplied(bool set); void painted(bool painted); bool painted() const; image_dtype get_dtype() const; }; using image_null = image<null_t>; using image_rgba8 = image<rgba8_t>; using image_gray8 = image<gray8_t>; using image_gray8s = image<gray8s_t>; using image_gray16 = image<gray16_t>; using image_gray16s = image<gray16s_t>; using image_gray32 = image<gray32_t>; using image_gray32s = image<gray32s_t>; using image_gray32f = image<gray32f_t>; using image_gray64 = image<gray64_t>; using image_gray64s = image<gray64s_t>; using image_gray64f = image<gray64f_t>; } // end ns mapnik #endif // MAPNIK_IMAGE_HPP <commit_msg>c++ style<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_HPP #define MAPNIK_IMAGE_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/pixel_types.hpp> namespace mapnik { namespace detail { struct MAPNIK_DECL buffer { explicit buffer(std::size_t size); buffer(buffer && rhs) noexcept; buffer(buffer const& rhs); ~buffer(); buffer& operator=(buffer rhs); bool operator!() const; void swap(buffer & rhs); unsigned char* data(); unsigned char const* data() const; std::size_t size() const; private: std::size_t size_; unsigned char* data_; }; template <std::size_t max_size> struct image_dimensions { image_dimensions(int width, int height); image_dimensions(image_dimensions const& other) = default; image_dimensions(image_dimensions && other) = default; image_dimensions& operator= (image_dimensions rhs); std::size_t width() const; std::size_t height() const; private: std::size_t width_; std::size_t height_; }; } // end ns detail template <typename T> class image { public: using pixel = T; using pixel_type = typename T::type; static const image_dtype dtype = T::id; static constexpr std::size_t pixel_size = sizeof(pixel_type); private: detail::image_dimensions<65535> dimensions_; detail::buffer buffer_; pixel_type *pData_; double offset_; double scaling_; bool premultiplied_alpha_; bool painted_; public: image(); image(int width, int height, bool initialize = true, bool premultiplied = false, bool painted = false); image(image<T> const& rhs); image(image<T> && rhs) noexcept; image<T>& operator=(image<T> rhs); image<T>const& operator=(image<T> const& rhs) const; bool operator==(image<T> const& rhs) const; bool operator<(image<T> const& rhs) const; void swap(image<T> & rhs); pixel_type& operator() (std::size_t i, std::size_t j); pixel_type const& operator() (std::size_t i, std::size_t j) const; std::size_t width() const; std::size_t height() const; std::size_t size() const; std::size_t row_size() const; void set(pixel_type const& t); pixel_type const* getData() const; pixel_type* getData(); unsigned char const* getBytes() const; unsigned char* getBytes(); pixel_type const* getRow(std::size_t row) const; pixel_type const* getRow(std::size_t row, std::size_t x0) const; pixel_type* getRow(std::size_t row); pixel_type* getRow(std::size_t row, std::size_t x0); void setRow(std::size_t row, pixel_type const* buf, std::size_t size); void setRow(std::size_t row, std::size_t x0, std::size_t x1, pixel_type const* buf); double get_offset() const; void set_offset(double set); double get_scaling() const; void set_scaling(double set); bool get_premultiplied() const; void set_premultiplied(bool set); void painted(bool painted); bool painted() const; image_dtype get_dtype() const; }; using image_null = image<null_t>; using image_rgba8 = image<rgba8_t>; using image_gray8 = image<gray8_t>; using image_gray8s = image<gray8s_t>; using image_gray16 = image<gray16_t>; using image_gray16s = image<gray16s_t>; using image_gray32 = image<gray32_t>; using image_gray32s = image<gray32s_t>; using image_gray32f = image<gray32f_t>; using image_gray64 = image<gray64_t>; using image_gray64s = image<gray64s_t>; using image_gray64f = image<gray64f_t>; } // end ns mapnik #endif // MAPNIK_IMAGE_HPP <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File: NekLinSys.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LINSYS_HPP #define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LINSYS_HPP #include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp> #include <LibUtilities/LinearAlgebra/Lapack.hpp> #include <LibUtilities/LinearAlgebra/NekMatrix.hpp> #include <LibUtilities/LinearAlgebra/NekVector.hpp> #include <LibUtilities/Memory/DeleteNothing.hpp> #include <LibUtilities/LinearAlgebra/MatrixType.h> #include <boost/shared_ptr.hpp> #include <boost/utility/enable_if.hpp> #include <boost/type_traits.hpp> namespace Nektar { template<typename DataType> class IsSharedPointer : public boost::false_type {}; template<typename DataType> class IsSharedPointer<boost::shared_ptr<DataType> > : public boost::true_type {}; template<typename MatrixType, typename VectorType> struct LinearSystemSolver; template<typename DataType, unsigned int vectorDim> struct LinearSystemSolver<NekMatrix<DataType, DiagonalMatrixTag, StandardMatrixTag>, NekVector<DataType, vectorDim> > { typedef NekVector<DataType, vectorDim> VectorType; typedef NekMatrix<DataType, DiagonalMatrixTag, StandardMatrixTag> MatrixType; static void Solve(const MatrixType& A, const ConstArray<OneD, int>& ipivot, const VectorType& b, VectorType& x) { ASSERTL0(A.GetColumns() == b.GetRows(), "ERROR: NekLinSys::Solve matrix columns must equal vector rows"); for(unsigned int i = 0; i < A.GetColumns(); ++i) { x[i] = b[i]*A(i,i); } } static void SolveTranspose(const MatrixType& A, const ConstArray<OneD, int>& ipivot, const VectorType& b, VectorType& x) { Solve(A,ipivot,b,x); } }; template<typename DataType, typename StorageType, typename Form, unsigned int vectorDim> struct LinearSystemSolver<NekMatrix<DataType, StorageType, Form>, NekVector<DataType, vectorDim> > { typedef NekMatrix<DataType, StorageType, Form> MatrixType; typedef NekVector<DataType, vectorDim> VectorType; static void Solve(const MatrixType& A, const ConstArray<OneD, int>& ipivot, const VectorType& b, VectorType& x) { x = b; int info = 0; Lapack::Dgetrs('T',A.GetRows(),1,A.GetPtr().get(),A.GetRows(),(int *)ipivot.get(),x.GetPtr(),A.GetRows(),info); if( info < 0 ) { std::string message = "ERROR: The " + boost::lexical_cast<std::string>(-info) + "th parameter had an illegal parameter for dgetrs"; ASSERTL0(false, message.c_str()); } } static void SolveTranspose(const MatrixType& A, const ConstArray<OneD, int>& ipivot, const VectorType& b, VectorType& x) { x = b; int info = 0; Lapack::Dgetrs('N',A.GetRows(),1,A.GetPtr().get(),A.GetRows(),(int *)ipivot.get(),x.GetPtr(),A.GetRows(),info); if( info < 0 ) { std::string message = "ERROR: The " + boost::lexical_cast<std::string>(-info) + "th parameter had an illegal parameter for dgetrs"; ASSERTL0(false, message.c_str()); } } }; template<typename MatrixType> class LinearSystem; template<typename DataType, typename StorageType, typename Type> class LinearSystem<NekMatrix<DataType, StorageType, Type> > { public: typedef NekMatrix<DataType, StorageType, Type> MatrixType; typedef LinearSystem<MatrixType> ThisType; public: explicit LinearSystem(const boost::shared_ptr<MatrixType> &theA) : A(*theA) { FactorMatrix(A); } LinearSystem(const ThisType& rhs) : A(rhs.A), m_ipivot(rhs.m_ipivot) { } ThisType& operator=(const ThisType& rhs) { ThisType temp(rhs); swap(temp); return *this; } ~LinearSystem() {} // In the following calls to Solve, VectorType must be a NekVector. // Anything else won't compile. template<typename VectorType> VectorType Solve(const boost::shared_ptr<VectorType>& b) { VectorType x(*b); LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,*b, x); return x; } template<typename VectorType> void Solve(const boost::shared_ptr<VectorType>& b, const boost::shared_ptr<VectorType>& x) const { LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,*b, *x); } template<typename VectorType> VectorType Solve(const VectorType& b, typename boost::disable_if<IsSharedPointer<VectorType> >::type* = 0) { VectorType x(b); LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,b, x); return x; } template<typename VectorType> void Solve(const VectorType& b, VectorType& x, typename boost::disable_if<IsSharedPointer<VectorType> >::type* = 0) const { LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot, b, x); } template<typename VectorType> void Solve(const boost::shared_ptr<VectorType>& b, VectorType& x) const { LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,*b, x); } template<typename VectorType> void Solve(const VectorType& b, const boost::shared_ptr<VectorType>& x) const { LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,b, *x); } // Transpose variant of solve template<typename VectorType> VectorType SolveTranspose(const boost::shared_ptr<VectorType>& b) { VectorType x(*b); LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,*b, x); return x; } template<typename VectorType> void SolveTranspose(const boost::shared_ptr<VectorType>& b, const boost::shared_ptr<VectorType>& x) const { LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,*b, *x); } template<typename VectorType> VectorType SolveTranspose(const VectorType& b, typename boost::disable_if<IsSharedPointer<VectorType> >::type* = 0) { VectorType x(b); LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,b, x); return x; } template<typename VectorType> void SolveTranspose(const VectorType& b, VectorType& x, typename boost::disable_if<IsSharedPointer<VectorType> >::type* = 0) const { LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,b, x); } template<typename VectorType> void SolveTranspose(const boost::shared_ptr<VectorType>& b, VectorType& x) const { LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,*b, x); } template<typename VectorType> void SolveTranspose(const VectorType& b, const boost::shared_ptr<VectorType>& x) const { LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot, b, x); } private: void FactorMatrix(NekMatrix<DataType,DiagonalMatrixTag> &theA) { for(unsigned int i = 0; i < A.GetColumns(); ++i) { theA.SetValue(i, i, 1.0/theA(i,i)); } } void FactorMatrix(NekMatrix<DataType,FullMatrixTag> &theA) { int m = theA.GetRows(); int n = theA.GetColumns(); int pivotSize = std::max(1, std::min(m, n)); int info = 0; m_ipivot = Array<OneD, int>(pivotSize); Lapack::Dgetrf(m, n, theA.GetPtr().get(), m, m_ipivot.get(), info); if( info < 0 ) { std::string message = "ERROR: The " + boost::lexical_cast<std::string>(-info) + "th parameter had an illegal parameter for dgetrf"; ASSERTL0(false, message.c_str()); } else if( info > 0 ) { std::string message = "ERROR: Element u_" + boost::lexical_cast<std::string>(info) + boost::lexical_cast<std::string>(info) + " is 0 from dgetrf"; ASSERTL0(false, message.c_str()); } } void swap(ThisType& rhs) { std::swap(A, rhs.A); std::swap(m_ipivot,rhs.m_ipivot); } MatrixType A; Array<OneD, int> m_ipivot; }; } #endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LINSYS_HPP <commit_msg>*** empty log message ***<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File: NekLinSys.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LINSYS_HPP #define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LINSYS_HPP #include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp> #include <LibUtilities/LinearAlgebra/Lapack.hpp> #include <LibUtilities/LinearAlgebra/NekMatrix.hpp> #include <LibUtilities/LinearAlgebra/NekVector.hpp> #include <LibUtilities/Memory/DeleteNothing.hpp> #include <LibUtilities/LinearAlgebra/MatrixType.h> #include <boost/shared_ptr.hpp> #include <boost/utility/enable_if.hpp> #include <boost/type_traits.hpp> namespace Nektar { template<typename DataType> class IsSharedPointer : public boost::false_type {}; template<typename DataType> class IsSharedPointer<boost::shared_ptr<DataType> > : public boost::true_type {}; template<typename MatrixType, typename VectorType> struct LinearSystemSolver; template<typename DataType, unsigned int vectorDim> struct LinearSystemSolver<NekMatrix<DataType, DiagonalMatrixTag, StandardMatrixTag>, NekVector<DataType, vectorDim> > { typedef NekVector<DataType, vectorDim> VectorType; typedef NekMatrix<DataType, DiagonalMatrixTag, StandardMatrixTag> MatrixType; static void Solve(const MatrixType& A, const ConstArray<OneD, int>& ipivot, const VectorType& b, VectorType& x) { ASSERTL0(A.GetColumns() == b.GetRows(), "ERROR: NekLinSys::Solve matrix columns must equal vector rows"); for(unsigned int i = 0; i < A.GetColumns(); ++i) { x[i] = b[i]*A(i,i); } } static void SolveTranspose(const MatrixType& A, const ConstArray<OneD, int>& ipivot, const VectorType& b, VectorType& x) { Solve(A,ipivot,b,x); } }; template<typename DataType, typename StorageType, typename Form, unsigned int vectorDim> struct LinearSystemSolver<NekMatrix<DataType, StorageType, Form>, NekVector<DataType, vectorDim> > { typedef NekMatrix<DataType, StorageType, Form> MatrixType; typedef NekVector<DataType, vectorDim> VectorType; static void Solve(const MatrixType& A, const ConstArray<OneD, int>& ipivot, const VectorType& b, VectorType& x) { x = b; int info = 0; Lapack::Dgetrs('T',A.GetRows(),1,A.GetPtr().get(),A.GetRows(),(int *)ipivot.get(),x.GetPtr(),A.GetRows(),info); if( info < 0 ) { std::string message = "ERROR: The " + boost::lexical_cast<std::string>(-info) + "th parameter had an illegal parameter for dgetrs"; ASSERTL0(false, message.c_str()); } } static void SolveTranspose(const MatrixType& A, const ConstArray<OneD, int>& ipivot, const VectorType& b, VectorType& x) { x = b; int info = 0; Lapack::Dgetrs('N',A.GetRows(),1,A.GetPtr().get(),A.GetRows(),(int *)ipivot.get(),x.GetPtr(),A.GetRows(),info); if( info < 0 ) { std::string message = "ERROR: The " + boost::lexical_cast<std::string>(-info) + "th parameter had an illegal parameter for dgetrs"; ASSERTL0(false, message.c_str()); } } }; template<typename MatrixType> class LinearSystem; template<typename DataType, typename StorageType, typename Type> class LinearSystem<NekMatrix<DataType, StorageType, Type> > { public: typedef NekMatrix<DataType, StorageType, Type> MatrixType; typedef LinearSystem<MatrixType> ThisType; public: explicit LinearSystem(const boost::shared_ptr<MatrixType> &theA) : A(*theA) { FactorMatrix(A); } LinearSystem(const ThisType& rhs) : A(rhs.A), m_ipivot(rhs.m_ipivot) { } ThisType& operator=(const ThisType& rhs) { ThisType temp(rhs); swap(temp); return *this; } ~LinearSystem() {} // In the following calls to Solve, VectorType must be a NekVector. // Anything else won't compile. template<typename VectorType> VectorType Solve(const boost::shared_ptr<VectorType>& b) { VectorType x; LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,*b, x); return x; } template<typename VectorType> void Solve(const boost::shared_ptr<VectorType>& b, const boost::shared_ptr<VectorType>& x) const { LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,*b, *x); } template<typename VectorType> VectorType Solve(const VectorType& b, typename boost::disable_if<IsSharedPointer<VectorType> >::type* = 0) { VectorType x; LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,b, x); return x; } template<typename VectorType> void Solve(const VectorType& b, VectorType& x, typename boost::disable_if<IsSharedPointer<VectorType> >::type* = 0) const { LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot, b, x); } template<typename VectorType> void Solve(const boost::shared_ptr<VectorType>& b, VectorType& x) const { LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,*b, x); } template<typename VectorType> void Solve(const VectorType& b, const boost::shared_ptr<VectorType>& x) const { LinearSystemSolver<MatrixType, VectorType>::Solve(A, m_ipivot,b, *x); } // Transpose variant of solve template<typename VectorType> VectorType SolveTranspose(const boost::shared_ptr<VectorType>& b) { VectorType x; LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,*b, x); return x; } template<typename VectorType> void SolveTranspose(const boost::shared_ptr<VectorType>& b, const boost::shared_ptr<VectorType>& x) const { LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,*b, *x); } template<typename VectorType> VectorType SolveTranspose(const VectorType& b, typename boost::disable_if<IsSharedPointer<VectorType> >::type* = 0) { VectorType x; LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,b, x); return x; } template<typename VectorType> void SolveTranspose(const VectorType& b, VectorType& x, typename boost::disable_if<IsSharedPointer<VectorType> >::type* = 0) const { LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,b, x); } template<typename VectorType> void SolveTranspose(const boost::shared_ptr<VectorType>& b, VectorType& x) const { LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot,*b, x); } template<typename VectorType> void SolveTranspose(const VectorType& b, const boost::shared_ptr<VectorType>& x) const { LinearSystemSolver<MatrixType, VectorType>::SolveTranspose(A, m_ipivot, b, x); } private: void FactorMatrix(NekMatrix<DataType,DiagonalMatrixTag> &theA) { for(unsigned int i = 0; i < A.GetColumns(); ++i) { theA.SetValue(i, i, 1.0/theA(i,i)); } } void FactorMatrix(NekMatrix<DataType,FullMatrixTag> &theA) { int m = theA.GetRows(); int n = theA.GetColumns(); int pivotSize = std::max(1, std::min(m, n)); int info = 0; m_ipivot = Array<OneD, int>(pivotSize); Lapack::Dgetrf(m, n, theA.GetPtr().get(), m, m_ipivot.get(), info); if( info < 0 ) { std::string message = "ERROR: The " + boost::lexical_cast<std::string>(-info) + "th parameter had an illegal parameter for dgetrf"; ASSERTL0(false, message.c_str()); } else if( info > 0 ) { std::string message = "ERROR: Element u_" + boost::lexical_cast<std::string>(info) + boost::lexical_cast<std::string>(info) + " is 0 from dgetrf"; ASSERTL0(false, message.c_str()); } } void swap(ThisType& rhs) { std::swap(A, rhs.A); std::swap(m_ipivot,rhs.m_ipivot); } MatrixType A; Array<OneD, int> m_ipivot; }; } #endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LINSYS_HPP <|endoftext|>
<commit_before>#pragma once #include <type_traits> #include <vector> #include <initializer_list> #include <cstddef> #include <algorithm> #include <iterator> #include <utility> #include <memory> #include <new> namespace helene { template <class T, std::size_t StackBufferSize = sizeof(std::vector<T>)> class small_vector { static_assert(std::is_trivial<T>::value, "small_vector is only compatible with trivial types"); public: typedef T value_type; typedef typename std::vector<T>::size_type size_type; typedef typename std::vector<T>::difference_type difference_type; typedef T& reference; typedef const T& const_reference; typedef T* pointer; typedef const T* const_pointer; typedef T* iterator; typedef const T* const_iterator; private: static constexpr size_type at_least_size = std::max(StackBufferSize, sizeof(std::vector<T>)); static constexpr size_type max_stack_size_ = at_least_size / sizeof(T); public: small_vector() : size_() { new(&storage_) T[max_stack_size_]; } small_vector(std::initializer_list<T> init) : size_(init.size()) { if(size_ > max_stack_size_) { new(&storage_) std::vector<T>(init); } else { new(&storage_) T[max_stack_size_]; std::copy(init.begin(), init.end(), std::launder(reinterpret_cast<T*>(&storage_))); } } small_vector(size_type count) : size_(count) { if(size_ > max_stack_size_) { new(&storage_) std::vector<T>(count); } else { new(&storage_) T[max_stack_size_]; std::fill_n( std::launder(reinterpret_cast<T*>(&storage_)), size_, T{}); } } small_vector(size_type count, const T& value) { if(size_ > max_stack_size_) { new(&storage_) std::vector<T>(count, value); } else { new(&storage_) T[max_stack_size_]; std::fill_n( std::launder(reinterpret_cast<T*>(&storage_)), size_, value); } } small_vector(const small_vector& other) : size_(other.size_) { if(size_ > max_stack_size_) { new(&storage_) std::vector<T>(*std::launder( reinterpret_cast<const std::vector<T>*>(&other.storage_))); } else { storage_ = other.storage_; } } small_vector(small_vector&& other) : storage_(other.storage_), size_(other.size_) { // disable destruction of potential heap allocated data in other other.size_ = 0; } small_vector& operator=(const small_vector& other) { auto temp = other; swap(temp); return *this; } small_vector& operator=(small_vector&& other) { auto temp = std::move(other); swap(temp); return *this; } void swap(small_vector& other) { std::swap(storage_, other.storage_); std::swap(size_, other.size_); } ~small_vector() { if(size_ > max_stack_size_) { std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->~vector(); } } public: void push_back(const T& value) { if(size_ > max_stack_size_) { std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->push_back(value); } else if(size_ == max_stack_size_) { T* buff = std::launder(reinterpret_cast<T*>(&storage_)); T temp[max_stack_size_]; std::copy(buff, buff + size_, std::begin(temp)); new(&storage_) std::vector<T>(std::begin(temp), std::end(temp)); std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->push_back(value); } else { std::launder(reinterpret_cast<T*>(&storage_))[size_] = value; } ++size_; } void pop_back() { if(size_ > max_stack_size_ + 1) // remain on heap { std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->pop_back(); --size_; } else if(size_ == max_stack_size_ + 1) // transition to stack { // reinterpret_cast<std::vector<T>*>(&storage_)->pop_back(); // not necessary, trivially destructible std::vector<T> temp(std::move( *(std::launder(reinterpret_cast<std::vector<T>*>(&storage_))))); std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->~vector(); new(&storage_) T[max_stack_size_]; std::copy(temp.begin(), temp.end() - 1, std::launder(reinterpret_cast<T*>(&storage_))); --size_; } else // remain on stack { --size_; } } reference operator[](size_type n) { if(size_ > max_stack_size_) { return std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) -> operator[](n); } else { return std::launder(reinterpret_cast<T*>(&storage_))[n]; } } const_reference operator[](size_type n) const { if(size_ > max_stack_size_) { return std::launder( reinterpret_cast<const std::vector<T>*>(&storage_)) -> operator[](n); } else { return std::launder(reinterpret_cast<const T*>(&storage_))[n]; } } reference front() { if(size_ > max_stack_size_) { return std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->front(); } else { return std::launder(reinterpret_cast<T*>(&storage_))[0]; } } const_reference front() const { if(size_ > max_stack_size_) { return std::launder( reinterpret_cast<const std::vector<T>*>(&storage_)) ->front(); } else { return std::launder(reinterpret_cast<const T*>(&storage_))[0]; } } reference back() { if(size_ > max_stack_size_) { return std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->back(); } else { return std::launder(reinterpret_cast<T*>(&storage_))[size_ - 1]; } } const_reference back() const { if(size_ > max_stack_size_) { return std::launder( reinterpret_cast<const std::vector<T>*>(&storage_)) ->back(); } else { return std::launder( reinterpret_cast<const T*>(&storage_))[size_ - 1]; } } iterator erase(iterator pos) { if(size_ > max_stack_size_ + 1) { std::vector<T>* ref = std::launder(reinterpret_cast<std::vector<T>*>(&storage_)); // convert to std::vector<T>::iterator typename std::vector<T>::iterator iter_pos = ref->begin() + (pos - ref->data()); auto iter_out = ref->erase(iter_pos); --size_; // convert std::vector<T>::iterator to pointer difference_type diff = iter_out - ref->begin(); return ref->data() + diff; } else if(size_ == max_stack_size_ + 1) { std::vector<T>* ref = std::launder(reinterpret_cast<std::vector<T>*>(&storage_)); // convert to std::vector<T>::iterator const auto diff = pos - ref->data(); typename std::vector<T>::iterator iter_pos = ref->begin() + (pos - ref->data()); auto iter_out = ref->erase(iter_pos); std::vector<T> temp(std::move(*ref)); ref->~vector(); new(&storage_) T[max_stack_size_]; std::copy(temp.begin(), temp.end(), std::launder(reinterpret_cast<T*>(&storage_))); --size_; return std::launder(reinterpret_cast<T*>(&storage_)) + diff; } else { T* beg = std::launder(reinterpret_cast<T*>(&storage_)); std::copy(pos + 1, end(), pos); --size_; return pos; } } iterator erase(iterator first, iterator last) { const auto erase_size = std::distance(first, last); if(size_ > max_stack_size_ + erase_size) { std::vector<T>* ref = std::launder(reinterpret_cast<std::vector<T>*>(&storage_)); // convert to std::vector<T>::iterator auto first_iter = ref->begin() + (first - begin()); auto last_iter = ref->begin() + (last - begin()); auto iter_out = ref->erase(first_iter, last_iter); size_ -= erase_size; // convert back to simple pointer return begin() + (iter_out - ref->begin()); } else if(size_ <= max_stack_size_) { T* buff_beg = std::launder(reinterpret_cast<T*>(&storage_)); if(last < end()) // if anything left past end of range to erase { std::copy(last, end(), first); } size_ -= erase_size; return first; } else { std::vector<T>* ref = std::launder(reinterpret_cast<std::vector<T>*>(&storage_)); // convert to std::vector<T>::iterator auto first_iter = ref->begin() + (first - begin()); auto last_iter = ref->begin() + (last - begin()); // carry out erase on vector auto iter_out = ref->erase(first_iter, last_iter); const auto out_diff = iter_out - ref->begin(); std::vector<T> temp(std::move(*ref)); ref->~vector(); new(&storage_) T[max_stack_size_]; std::copy(temp.begin(), temp.end(), std::launder(reinterpret_cast<T*>(&storage_))); size_ -= erase_size; return begin() + out_diff; } } pointer data() { if(size_ > max_stack_size_) { return std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->data(); } else { return std::launder(reinterpret_cast<T*>(&storage_)); } } const_pointer data() const { if(size_ > max_stack_size_) { return std::launder( reinterpret_cast<const std::vector<T>*>(&storage_)) ->data(); } else { return std::launder(reinterpret_cast<const T*>(&storage_)); } } iterator begin() { if(size_ > max_stack_size_) { return std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->data(); } else { return std::launder(reinterpret_cast<T*>(&storage_)); } } iterator end() { if(size_ > max_stack_size_) { return std::launder(reinterpret_cast<std::vector<T>*>(&storage_)) ->data() + size_; } else { return std::launder(reinterpret_cast<T*>(&storage_)) + size_; } } const_iterator cbegin() const { if(size_ > max_stack_size_) { return std::launder( reinterpret_cast<const std::vector<T>*>(&storage_)) ->data(); } else { return std::launder(reinterpret_cast<const T*>(&storage_)); } } const_iterator cend() const { if(size_ > max_stack_size_) { return std::launder( reinterpret_cast<const std::vector<T>*>(&storage_)) ->data() + size_; } else { return std::launder(reinterpret_cast<const T*>(&storage_)) + size_; } } size_type size() const { return size_; } bool empty() const { return size_ == 0; } static constexpr size_type max_stack_size() { return max_stack_size_; } bool on_stack() const { return size_ <= max_stack_size_; } private: std::aligned_storage_t<at_least_size> storage_; size_type size_; }; } // namespace helene <commit_msg>Add ifdef's to disable std::launder in case of __clang__. modified: include/small_vector.hpp<commit_after>#pragma once #include <type_traits> #include <vector> #include <initializer_list> #include <cstddef> #include <algorithm> #include <iterator> #include <utility> #include <memory> #include <new> #ifndef __clang__ #define LAUNDER std::launder #else #define LAUNDER #endif namespace helene { template <class T, std::size_t StackBufferSize = sizeof(std::vector<T>)> class small_vector { static_assert(std::is_trivial<T>::value, "small_vector is only compatible with trivial types"); public: typedef T value_type; typedef typename std::vector<T>::size_type size_type; typedef typename std::vector<T>::difference_type difference_type; typedef T& reference; typedef const T& const_reference; typedef T* pointer; typedef const T* const_pointer; typedef T* iterator; typedef const T* const_iterator; private: static constexpr size_type at_least_size = std::max(StackBufferSize, sizeof(std::vector<T>)); static constexpr size_type max_stack_size_ = at_least_size / sizeof(T); public: small_vector() : size_() { new(&storage_) T[max_stack_size_]; } small_vector(std::initializer_list<T> init) : size_(init.size()) { if(size_ > max_stack_size_) { new(&storage_) std::vector<T>(init); } else { new(&storage_) T[max_stack_size_]; std::copy(init.begin(), init.end(), LAUNDER(reinterpret_cast<T*>(&storage_))); } } small_vector(size_type count) : size_(count) { if(size_ > max_stack_size_) { new(&storage_) std::vector<T>(count); } else { new(&storage_) T[max_stack_size_]; std::fill_n(LAUNDER(reinterpret_cast<T*>(&storage_)), size_, T{}); } } small_vector(size_type count, const T& value) { if(size_ > max_stack_size_) { new(&storage_) std::vector<T>(count, value); } else { new(&storage_) T[max_stack_size_]; std::fill_n(LAUNDER(reinterpret_cast<T*>(&storage_)), size_, value); } } small_vector(const small_vector& other) : size_(other.size_) { if(size_ > max_stack_size_) { new(&storage_) std::vector<T>(*LAUNDER( reinterpret_cast<const std::vector<T>*>(&other.storage_))); } else { storage_ = other.storage_; } } small_vector(small_vector&& other) : storage_(other.storage_), size_(other.size_) { // disable destruction of potential heap allocated data in other other.size_ = 0; } small_vector& operator=(const small_vector& other) { auto temp = other; swap(temp); return *this; } small_vector& operator=(small_vector&& other) { auto temp = std::move(other); swap(temp); return *this; } void swap(small_vector& other) { std::swap(storage_, other.storage_); std::swap(size_, other.size_); } ~small_vector() { if(size_ > max_stack_size_) { LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_))->~vector(); } } public: void push_back(const T& value) { if(size_ > max_stack_size_) { LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)) ->push_back(value); } else if(size_ == max_stack_size_) { T* buff = LAUNDER(reinterpret_cast<T*>(&storage_)); T temp[max_stack_size_]; std::copy(buff, buff + size_, std::begin(temp)); new(&storage_) std::vector<T>(std::begin(temp), std::end(temp)); LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)) ->push_back(value); } else { LAUNDER(reinterpret_cast<T*>(&storage_))[size_] = value; } ++size_; } void pop_back() { if(size_ > max_stack_size_ + 1) // remain on heap { LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_))->pop_back(); --size_; } else if(size_ == max_stack_size_ + 1) // transition to stack { // reinterpret_cast<std::vector<T>*>(&storage_)->pop_back(); // not necessary, trivially destructible std::vector<T> temp(std::move( *(LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_))))); LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_))->~vector(); new(&storage_) T[max_stack_size_]; std::copy(temp.begin(), temp.end() - 1, LAUNDER(reinterpret_cast<T*>(&storage_))); --size_; } else // remain on stack { --size_; } } reference operator[](size_type n) { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)) -> operator[](n); } else { return LAUNDER(reinterpret_cast<T*>(&storage_))[n]; } } const_reference operator[](size_type n) const { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<const std::vector<T>*>(&storage_)) -> operator[](n); } else { return LAUNDER(reinterpret_cast<const T*>(&storage_))[n]; } } reference front() { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)) ->front(); } else { return LAUNDER(reinterpret_cast<T*>(&storage_))[0]; } } const_reference front() const { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<const std::vector<T>*>(&storage_)) ->front(); } else { return LAUNDER(reinterpret_cast<const T*>(&storage_))[0]; } } reference back() { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)) ->back(); } else { return LAUNDER(reinterpret_cast<T*>(&storage_))[size_ - 1]; } } const_reference back() const { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<const std::vector<T>*>(&storage_)) ->back(); } else { return LAUNDER(reinterpret_cast<const T*>(&storage_))[size_ - 1]; } } iterator erase(iterator pos) { if(size_ > max_stack_size_ + 1) { std::vector<T>* ref = LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)); // convert to std::vector<T>::iterator typename std::vector<T>::iterator iter_pos = ref->begin() + (pos - ref->data()); auto iter_out = ref->erase(iter_pos); --size_; // convert std::vector<T>::iterator to pointer difference_type diff = iter_out - ref->begin(); return ref->data() + diff; } else if(size_ == max_stack_size_ + 1) { std::vector<T>* ref = LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)); // convert to std::vector<T>::iterator const auto diff = pos - ref->data(); typename std::vector<T>::iterator iter_pos = ref->begin() + (pos - ref->data()); auto iter_out = ref->erase(iter_pos); std::vector<T> temp(std::move(*ref)); ref->~vector(); new(&storage_) T[max_stack_size_]; std::copy(temp.begin(), temp.end(), LAUNDER(reinterpret_cast<T*>(&storage_))); --size_; return LAUNDER(reinterpret_cast<T*>(&storage_)) + diff; } else { T* beg = LAUNDER(reinterpret_cast<T*>(&storage_)); std::copy(pos + 1, end(), pos); --size_; return pos; } } iterator erase(iterator first, iterator last) { const auto erase_size = std::distance(first, last); if(size_ > max_stack_size_ + erase_size) { std::vector<T>* ref = LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)); // convert to std::vector<T>::iterator auto first_iter = ref->begin() + (first - begin()); auto last_iter = ref->begin() + (last - begin()); auto iter_out = ref->erase(first_iter, last_iter); size_ -= erase_size; // convert back to simple pointer return begin() + (iter_out - ref->begin()); } else if(size_ <= max_stack_size_) { T* buff_beg = LAUNDER(reinterpret_cast<T*>(&storage_)); if(last < end()) // if anything left past end of range to erase { std::copy(last, end(), first); } size_ -= erase_size; return first; } else { std::vector<T>* ref = LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)); // convert to std::vector<T>::iterator auto first_iter = ref->begin() + (first - begin()); auto last_iter = ref->begin() + (last - begin()); // carry out erase on vector auto iter_out = ref->erase(first_iter, last_iter); const auto out_diff = iter_out - ref->begin(); std::vector<T> temp(std::move(*ref)); ref->~vector(); new(&storage_) T[max_stack_size_]; std::copy(temp.begin(), temp.end(), LAUNDER(reinterpret_cast<T*>(&storage_))); size_ -= erase_size; return begin() + out_diff; } } pointer data() { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)) ->data(); } else { return LAUNDER(reinterpret_cast<T*>(&storage_)); } } const_pointer data() const { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<const std::vector<T>*>(&storage_)) ->data(); } else { return LAUNDER(reinterpret_cast<const T*>(&storage_)); } } iterator begin() { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)) ->data(); } else { return LAUNDER(reinterpret_cast<T*>(&storage_)); } } iterator end() { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<std::vector<T>*>(&storage_)) ->data() + size_; } else { return LAUNDER(reinterpret_cast<T*>(&storage_)) + size_; } } const_iterator cbegin() const { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<const std::vector<T>*>(&storage_)) ->data(); } else { return LAUNDER(reinterpret_cast<const T*>(&storage_)); } } const_iterator cend() const { if(size_ > max_stack_size_) { return LAUNDER(reinterpret_cast<const std::vector<T>*>(&storage_)) ->data() + size_; } else { return LAUNDER(reinterpret_cast<const T*>(&storage_)) + size_; } } size_type size() const { return size_; } bool empty() const { return size_ == 0; } static constexpr size_type max_stack_size() { return max_stack_size_; } bool on_stack() const { return size_ <= max_stack_size_; } private: std::aligned_storage_t<at_least_size> storage_; size_type size_; }; } // namespace helene <|endoftext|>
<commit_before>/** * Appcelerator Titanium Mobile * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include <jni.h> #include <v8.h> #include "JNIUtil.h" #include "TypeConverter.h" #include "V8Runtime.h" #include "V8Util.h" #define TAG "V8Function" using namespace titanium; using namespace v8; #ifdef __cplusplus extern "C" { #endif /* * Class: org_appcelerator_kroll_runtime_v8_V8Function * Method: nativeInvoke * Signature: (JJ[Ljava/lang/Object)V */ JNIEXPORT jobject JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Function_nativeInvoke( JNIEnv *env, jobject caller, jlong thisPointer, jlong functionPointer, jobjectArray functionArguments) { ENTER_V8(V8Runtime::globalContext); titanium::JNIScope jniScope(env); Local<Object> thisObject = Local<Object>((Object *) thisPointer); // construct function from pointer Function *jsFunction = (Function *) functionPointer; // create function arguments int length; v8::Handle<v8::Value> *jsFunctionArguments = TypeConverter::javaObjectArrayToJsArguments(functionArguments, &length); // call into the JS function with the provided argument v8::Local<v8::Value> object = jsFunction->Call(thisObject, length, jsFunctionArguments); // make sure to delete the arguments since the arguments array is built on the heap if (jsFunctionArguments) { delete jsFunctionArguments; } bool isNew; jobject retVal = TypeConverter::jsValueToJavaObject(object, &isNew); if (isNew) { env->DeleteLocalRef(retVal); } return retVal; } #ifdef __cplusplus } #endif <commit_msg>[TIMOB-6789] Don't Delete Reference<commit_after>/** * Appcelerator Titanium Mobile * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include <jni.h> #include <v8.h> #include "JNIUtil.h" #include "TypeConverter.h" #include "V8Runtime.h" #include "V8Util.h" #define TAG "V8Function" using namespace titanium; using namespace v8; #ifdef __cplusplus extern "C" { #endif /* * Class: org_appcelerator_kroll_runtime_v8_V8Function * Method: nativeInvoke * Signature: (JJ[Ljava/lang/Object)V */ JNIEXPORT jobject JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Function_nativeInvoke( JNIEnv *env, jobject caller, jlong thisPointer, jlong functionPointer, jobjectArray functionArguments) { ENTER_V8(V8Runtime::globalContext); titanium::JNIScope jniScope(env); Local<Object> thisObject = Local<Object>((Object *) thisPointer); // construct function from pointer Function *jsFunction = (Function *) functionPointer; // create function arguments int length; v8::Handle<v8::Value> *jsFunctionArguments = TypeConverter::javaObjectArrayToJsArguments(functionArguments, &length); // call into the JS function with the provided argument v8::Local<v8::Value> object = jsFunction->Call(thisObject, length, jsFunctionArguments); // make sure to delete the arguments since the arguments array is built on the heap if (jsFunctionArguments) { delete jsFunctionArguments; } bool isNew; return TypeConverter::jsValueToJavaObject(object, &isNew); } #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef _SVTOOLS_XMLEMENT_HXX #define _SVTOOLS_XMLEMENT_HXX #include <sal/types.h> struct SvXMLEnumMapEntry { const sal_Char *pName; sal_uInt16 nValue; }; #endif // _SVTOOLS_XMLEMENT_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>remove bogus header svl/xmlement.hxx<commit_after><|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCLogModule.cpp // @Author : LvSheng.Huang // @Date : 2012-12-15 // @Module : NFCLogModule // @Desc : // ------------------------------------------------------------------------- #define GLOG_NO_ABBREVIATED_SEVERITIES #include "glog/logging.h" #include <time.h> #include "NFStackWalker.h" #include "NFCLogModule.h" #include <boost/filesystem.hpp> #include "NFComm/NFPluginModule/NFIActorManager.h" #include "NFComm/NFPluginModule/NFIActor.h" NFCLogModule::NFCLogModule(NFIPluginManager* p) { pPluginManager = p; //m_pFd = NULL; } bool NFCLogModule::Init() { #ifdef NF_DYNAMIC_PLUGIN NFIActor* pActor = (NFIActor*)(pPluginManager); if(pActor->GetActorID() == NFIActorManager::EACTOR_MAIN) { #endif char szName[MAX_PATH] = {0}; GetConsoleTitle(szName, MAX_PATH); google::InitGoogleLogging(szName); std::string strPath = std::string("./log/") + szName; if (!boost::filesystem::exists(strPath)) { boost::filesystem::create_directories(strPath); } #ifdef NF_DEBUG_MODE google::SetStderrLogging(google::GLOG_INFO); //ü google::INFO ־ͬʱĻ #else google::SetStderrLogging(google::GLOG_FATAL);//ü google::FATAL ־ͬʱĻ #endif FLAGS_colorlogtostderr = true; //Ļ־ʾӦɫ FLAGS_servitysinglelog = true; google::SetLogDestination(google::GLOG_FATAL, std::string(strPath + "/log_fatal_").c_str()); google::SetLogDestination(google::GLOG_ERROR, std::string(strPath + "/log_error_").c_str()); // google::error ־洢·ļǰ׺ google::SetLogDestination(google::GLOG_WARNING, std::string(strPath + "/log_warning_").c_str()); // google::WARNING ־洢·ļǰ׺ google::SetLogDestination(google::GLOG_INFO, std::string(strPath + "/log_Info_").c_str()); // google::INFO ־洢·ļǰ׺ FLAGS_logbufsecs = 0; //־ĬΪ30룬˴Ϊ FLAGS_max_log_size = 100; //־СΪ 100MB FLAGS_stop_logging_if_full_disk = true; //̱дʱֹͣ־ #ifdef NF_DYNAMIC_PLUGIN } #endif //google::SetLogFilenameExtension("91_"); //ļչƽ̨ҪֵϢ //google::InstallFailureSignalHandler(); //׽ core dumped //google::InstallFailureWriter(&Log); //Ĭϲ׽ SIGSEGV źϢ stderrͨķԶʽ return true; } bool NFCLogModule::Shut() { #ifdef NF_DYNAMIC_PLUGIN NFIActor* pActor = (NFIActor*)(pPluginManager); if(pActor->GetActorID() == NFIActorManager::EACTOR_MAIN) { google::ShutdownGoogleLogging(); } #else google::ShutdownGoogleLogging(); #endif return true; } bool NFCLogModule::BeforeShut() { return true; } bool NFCLogModule::AfterInit() { return true; } bool NFCLogModule::Execute(const float fLasFrametime, const float fStartedTime) { return true; } bool NFCLogModule::Log(const NF_LOG_LEVEL nll, const char* format, ...) { char szBuffer[1024 * 10] = {0}; va_list args; va_start(args, format); _vsnprintf(szBuffer, sizeof(szBuffer) - 1, format, args); va_end(args); #ifdef NF_DYNAMIC_PLUGIN NFIActor* pActor = (NFIActor*)(pPluginManager); if(!pActor->GetActorID() == NFIActorManager::EACTOR_MAIN) { NFIActorMessage message; message.eType = NFIActorMessage::EACTOR_LOG_MSG; message.data = szBuffer; const Theron::Address address = pActor->GetActorManager()->GetAddress(NFIActorManager::EACTOR_MAIN); if (address != Theron::Address::Null()) { pActor->GetFramework().Send(message, pActor->GetAddress(), address); } return true; } #endif switch (nll) { case NFILogModule::NLL_INFO_NORMAL: LOG(INFO) << szBuffer; break; case NFILogModule::NLL_WARING_NORMAL: LOG(WARNING) << szBuffer; break; case NFILogModule::NLL_ERROR_NORMAL: { LOG(ERROR) << szBuffer; LogStack(); } break; default: LOG(INFO) << szBuffer; break; } return true; } bool NFCLogModule::LogElement(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strElement, const std::string& strDesc, char* func, int line) { if(line > 0) { Log(nll, "[ELEMENT] Ident=%lld Element=%s %s %s %d\n", ident.nData64, strElement.c_str(), strDesc.c_str(), func, line); } else { Log(nll, "[ELEMENT] Ident=%lld Element=%s %s\n", ident.nData64, strElement.c_str(), strDesc.c_str()); } return true; } bool NFCLogModule::LogProperty(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strProperty, const std::string& strDesc, char* func, int line) { if(line > 0) { Log(nll, "[PROPERTY] Ident=%lld Element=%s %s %s %d\n", ident.nData64, strProperty.c_str(), strDesc.c_str(), func, line); } else { Log(nll, "[PROPERTY] Ident=%lld Element=%s %s\n", ident.nData64, strProperty.c_str(), strDesc.c_str()); } return true; } bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strRecord, const std::string& strDesc, const int nRow, const int nCol, char* func, int line) { if(line > 0) { Log(nll, "[RECORD] Ident=%lld Record=%s Row=%d Col=%d %s %s %d\n", ident.nData64, strRecord.c_str(), nRow, nCol, strDesc.c_str(), func, line); } else { Log(nll, "[RECORD] Ident=%lld Record=%s Row=%d Col=%d %s \n", ident.nData64, strRecord.c_str(), nRow, nCol, strDesc.c_str()); } return true; } bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strRecord, const std::string& strDesc, char* func, int line) { if(line > 0) { Log(nll, "[RECORD] Ident=%lld Record=%s %s %s %d\n", ident.nData64, strRecord.c_str(), strDesc.c_str(), func, line); } else { Log(nll, "[RECORD] Ident=%lld Record=%s %s\n", ident.nData64, strRecord.c_str(), strDesc.c_str()); } return true; } bool NFCLogModule::LogObject(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strDesc, char* func, int line) { if(line > 0) { Log(nll, "[OBJECT] Ident=%lld %s %s %d\n", ident.nData64, strDesc.c_str(), func, line); } else { Log(nll, "[OBJECT] Ident=%lld %s\n", ident.nData64, strDesc.c_str()); } return true; } void NFCLogModule::LogStack() { #ifdef NF_DEBUG_MODE time_t t = time(0); char szDmupName[MAX_PATH]; tm* ptm = localtime(&t); sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); // Dumpļ HANDLE hDumpFile = CreateFile(szDmupName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // DumpϢ MINIDUMP_EXCEPTION_INFORMATION dumpInfo; //dumpInfo.ExceptionPointers = pException; dumpInfo.ThreadId = GetCurrentThreadId(); dumpInfo.ClientPointers = TRUE; // дDumpļ MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL); CloseHandle(hDumpFile); #endif } bool NFCLogModule::LogNormal( const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const std::string& strDesc, char* func, int line ) { if(line > 0) { Log(nll, "[NORMAL] Ident=%lld %s %s %s %d\n", ident.nData64, strInfo.c_str(), strDesc.c_str(), func, line); } else { Log(nll, "[NORMAL] Ident=%lld %s %s \n", ident.nData64, strInfo.c_str(), strDesc.c_str()); } return true; } bool NFCLogModule::LogNormal( const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const int nDesc, char* func, int line ) { if(line > 0) { Log(nll, "[NORMAL] Ident=%lld %s %d %s %d\n", ident.nData64, strInfo.c_str(), nDesc, func, line); } else { Log(nll, "[NORMAL] Ident=%lld %s %d\n", ident.nData64, strInfo.c_str(), nDesc); } return true; } bool NFCLogModule::LogNormal( const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::ostringstream& stream, char* func, int line) { switch (nll) { case NFILogModule::NLL_INFO_NORMAL: { if (0 == line) { LOG(INFO) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str(); } else { LOG(INFO) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line; } } break; case NFILogModule::NLL_WARING_NORMAL: { if (0 == line) { LOG(WARNING) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str(); } else { LOG(WARNING) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line; } } break; case NFILogModule::NLL_ERROR_NORMAL: { if (0 == line) { LOG(ERROR) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str(); } else { LOG(ERROR) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line; } } break; default: break; } return true; } bool NFCLogModule::LogNormal( const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, char* func /*= ""*/, int line /*= 0*/ ) { if(line > 0) { Log(nll, "[NORMAL] Ident=%lld %s %s %d\n", ident.nData64, strInfo.c_str(), func, line); } else { Log(nll, "[NORMAL] Ident=%lld %s\n", ident.nData64, strInfo.c_str()); } return true; } <commit_msg>remove dump when log error info<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCLogModule.cpp // @Author : LvSheng.Huang // @Date : 2012-12-15 // @Module : NFCLogModule // @Desc : // ------------------------------------------------------------------------- #define GLOG_NO_ABBREVIATED_SEVERITIES #include "glog/logging.h" #include <time.h> #include "NFStackWalker.h" #include "NFCLogModule.h" #include <boost/filesystem.hpp> #include "NFComm/NFPluginModule/NFIActorManager.h" #include "NFComm/NFPluginModule/NFIActor.h" NFCLogModule::NFCLogModule(NFIPluginManager* p) { pPluginManager = p; //m_pFd = NULL; } bool NFCLogModule::Init() { #ifdef NF_DYNAMIC_PLUGIN NFIActor* pActor = (NFIActor*)(pPluginManager); if(pActor->GetActorID() == NFIActorManager::EACTOR_MAIN) { #endif char szName[MAX_PATH] = {0}; GetConsoleTitle(szName, MAX_PATH); google::InitGoogleLogging(szName); std::string strPath = std::string("./log/") + szName; if (!boost::filesystem::exists(strPath)) { boost::filesystem::create_directories(strPath); } #ifdef NF_DEBUG_MODE google::SetStderrLogging(google::GLOG_INFO); //ü google::INFO ־ͬʱĻ #else google::SetStderrLogging(google::GLOG_FATAL);//ü google::FATAL ־ͬʱĻ #endif FLAGS_colorlogtostderr = true; //Ļ־ʾӦɫ FLAGS_servitysinglelog = true; google::SetLogDestination(google::GLOG_FATAL, std::string(strPath + "/log_fatal_").c_str()); google::SetLogDestination(google::GLOG_ERROR, std::string(strPath + "/log_error_").c_str()); // google::error ־洢·ļǰ׺ google::SetLogDestination(google::GLOG_WARNING, std::string(strPath + "/log_warning_").c_str()); // google::WARNING ־洢·ļǰ׺ google::SetLogDestination(google::GLOG_INFO, std::string(strPath + "/log_Info_").c_str()); // google::INFO ־洢·ļǰ׺ FLAGS_logbufsecs = 0; //־ĬΪ30룬˴Ϊ FLAGS_max_log_size = 100; //־СΪ 100MB FLAGS_stop_logging_if_full_disk = true; //̱дʱֹͣ־ #ifdef NF_DYNAMIC_PLUGIN } #endif //google::SetLogFilenameExtension("91_"); //ļչƽ̨ҪֵϢ //google::InstallFailureSignalHandler(); //׽ core dumped //google::InstallFailureWriter(&Log); //Ĭϲ׽ SIGSEGV źϢ stderrͨķԶʽ return true; } bool NFCLogModule::Shut() { #ifdef NF_DYNAMIC_PLUGIN NFIActor* pActor = (NFIActor*)(pPluginManager); if(pActor->GetActorID() == NFIActorManager::EACTOR_MAIN) { google::ShutdownGoogleLogging(); } #else google::ShutdownGoogleLogging(); #endif return true; } bool NFCLogModule::BeforeShut() { return true; } bool NFCLogModule::AfterInit() { return true; } bool NFCLogModule::Execute(const float fLasFrametime, const float fStartedTime) { return true; } bool NFCLogModule::Log(const NF_LOG_LEVEL nll, const char* format, ...) { char szBuffer[1024 * 10] = {0}; va_list args; va_start(args, format); _vsnprintf(szBuffer, sizeof(szBuffer) - 1, format, args); va_end(args); #ifdef NF_DYNAMIC_PLUGIN NFIActor* pActor = (NFIActor*)(pPluginManager); if(!pActor->GetActorID() == NFIActorManager::EACTOR_MAIN) { NFIActorMessage message; message.eType = NFIActorMessage::EACTOR_LOG_MSG; message.data = szBuffer; const Theron::Address address = pActor->GetActorManager()->GetAddress(NFIActorManager::EACTOR_MAIN); if (address != Theron::Address::Null()) { pActor->GetFramework().Send(message, pActor->GetAddress(), address); } return true; } #endif switch (nll) { case NFILogModule::NLL_INFO_NORMAL: LOG(INFO) << szBuffer; break; case NFILogModule::NLL_WARING_NORMAL: LOG(WARNING) << szBuffer; break; case NFILogModule::NLL_ERROR_NORMAL: { LOG(ERROR) << szBuffer; //LogStack(); } break; default: LOG(INFO) << szBuffer; break; } return true; } bool NFCLogModule::LogElement(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strElement, const std::string& strDesc, char* func, int line) { if(line > 0) { Log(nll, "[ELEMENT] Ident=%lld Element=%s %s %s %d\n", ident.nData64, strElement.c_str(), strDesc.c_str(), func, line); } else { Log(nll, "[ELEMENT] Ident=%lld Element=%s %s\n", ident.nData64, strElement.c_str(), strDesc.c_str()); } return true; } bool NFCLogModule::LogProperty(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strProperty, const std::string& strDesc, char* func, int line) { if(line > 0) { Log(nll, "[PROPERTY] Ident=%lld Element=%s %s %s %d\n", ident.nData64, strProperty.c_str(), strDesc.c_str(), func, line); } else { Log(nll, "[PROPERTY] Ident=%lld Element=%s %s\n", ident.nData64, strProperty.c_str(), strDesc.c_str()); } return true; } bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strRecord, const std::string& strDesc, const int nRow, const int nCol, char* func, int line) { if(line > 0) { Log(nll, "[RECORD] Ident=%lld Record=%s Row=%d Col=%d %s %s %d\n", ident.nData64, strRecord.c_str(), nRow, nCol, strDesc.c_str(), func, line); } else { Log(nll, "[RECORD] Ident=%lld Record=%s Row=%d Col=%d %s \n", ident.nData64, strRecord.c_str(), nRow, nCol, strDesc.c_str()); } return true; } bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strRecord, const std::string& strDesc, char* func, int line) { if(line > 0) { Log(nll, "[RECORD] Ident=%lld Record=%s %s %s %d\n", ident.nData64, strRecord.c_str(), strDesc.c_str(), func, line); } else { Log(nll, "[RECORD] Ident=%lld Record=%s %s\n", ident.nData64, strRecord.c_str(), strDesc.c_str()); } return true; } bool NFCLogModule::LogObject(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strDesc, char* func, int line) { if(line > 0) { Log(nll, "[OBJECT] Ident=%lld %s %s %d\n", ident.nData64, strDesc.c_str(), func, line); } else { Log(nll, "[OBJECT] Ident=%lld %s\n", ident.nData64, strDesc.c_str()); } return true; } void NFCLogModule::LogStack() { #ifdef NF_DEBUG_MODE time_t t = time(0); char szDmupName[MAX_PATH]; tm* ptm = localtime(&t); sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); // Dumpļ HANDLE hDumpFile = CreateFile(szDmupName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // DumpϢ MINIDUMP_EXCEPTION_INFORMATION dumpInfo; //dumpInfo.ExceptionPointers = pException; dumpInfo.ThreadId = GetCurrentThreadId(); dumpInfo.ClientPointers = TRUE; // дDumpļ MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL); CloseHandle(hDumpFile); #endif } bool NFCLogModule::LogNormal( const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const std::string& strDesc, char* func, int line ) { if(line > 0) { Log(nll, "[NORMAL] Ident=%lld %s %s %s %d\n", ident.nData64, strInfo.c_str(), strDesc.c_str(), func, line); } else { Log(nll, "[NORMAL] Ident=%lld %s %s \n", ident.nData64, strInfo.c_str(), strDesc.c_str()); } return true; } bool NFCLogModule::LogNormal( const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const int nDesc, char* func, int line ) { if(line > 0) { Log(nll, "[NORMAL] Ident=%lld %s %d %s %d\n", ident.nData64, strInfo.c_str(), nDesc, func, line); } else { Log(nll, "[NORMAL] Ident=%lld %s %d\n", ident.nData64, strInfo.c_str(), nDesc); } return true; } bool NFCLogModule::LogNormal( const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::ostringstream& stream, char* func, int line) { switch (nll) { case NFILogModule::NLL_INFO_NORMAL: { if (0 == line) { LOG(INFO) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str(); } else { LOG(INFO) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line; } } break; case NFILogModule::NLL_WARING_NORMAL: { if (0 == line) { LOG(WARNING) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str(); } else { LOG(WARNING) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line; } } break; case NFILogModule::NLL_ERROR_NORMAL: { if (0 == line) { LOG(ERROR) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str(); } else { LOG(ERROR) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line; } } break; default: break; } return true; } bool NFCLogModule::LogNormal( const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, char* func /*= ""*/, int line /*= 0*/ ) { if(line > 0) { Log(nll, "[NORMAL] Ident=%lld %s %s %d\n", ident.nData64, strInfo.c_str(), func, line); } else { Log(nll, "[NORMAL] Ident=%lld %s\n", ident.nData64, strInfo.c_str()); } return true; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "c7a/data/data_manager.hpp" using namespace c7a::data; TEST(DataManager, GetLocalBlock_FailsIfNotFound) { DataManager manager; ASSERT_ANY_THROW(manager.GetLocalBlocks<int>(0)); } TEST(DataManager, GetLocalEmitter_FailsIfNotFound) { DataManager manager; ASSERT_ANY_THROW(manager.GetLocalEmitter<int>(0)); } TEST(DataManager, GetLocalEmitter_CanCallEmitter) { DataManager manager; auto e = manager.GetLocalEmitter<int>(manager.AllocateDIA()); ASSERT_NO_THROW(e(123)); } TEST(DataManager, EmittAndIterate_CorrectOrder) { DataManager manager; auto id = manager.AllocateDIA(); auto emitFn = manager.GetLocalEmitter<int>(id); emitFn(123); emitFn(22); auto it = manager.GetLocalBlocks<int>(id); ASSERT_EQ(123, it.Next()); ASSERT_EQ(22, it.Next()); } TEST(DataManager, EmittAndIterate_ConcurrentAccess) { DataManager manager; auto id = manager.AllocateDIA(); auto emitFn = manager.GetLocalEmitter<int>(id); auto it = manager.GetLocalBlocks<int>(id); emitFn(123); ASSERT_EQ(123, it.Next()); ASSERT_FALSE(it.HasNext()); emitFn(22); ASSERT_TRUE(it.HasNext()); ASSERT_EQ(22, it.Next()); } <commit_msg>use test fixture for DataManager tests<commit_after>#include "gtest/gtest.h" #include "c7a/data/data_manager.hpp" using namespace c7a::data; struct DataManagerFixture : public ::testing::Test { DataManager manager; DIAId id = manager.AllocateDIA(); }; TEST_F(DataManagerFixture, GetLocalBlock_FailsIfNotFound) { ASSERT_ANY_THROW(manager.GetLocalBlocks<int>(999)); } TEST_F(DataManagerFixture, GetLocalEmitter_FailsIfNotFound) { ASSERT_ANY_THROW(manager.GetLocalEmitter<int>(23)); } TEST_F(DataManagerFixture, GetLocalEmitter_CanCallEmitter) { auto e = manager.GetLocalEmitter<int>(manager.AllocateDIA()); ASSERT_NO_THROW(e(123)); } TEST_F(DataManagerFixture, EmittAndIterate_CorrectOrder) { auto id = manager.AllocateDIA(); auto emitFn = manager.GetLocalEmitter<int>(id); emitFn(123); emitFn(22); auto it = manager.GetLocalBlocks<int>(id); ASSERT_EQ(123, it.Next()); ASSERT_EQ(22, it.Next()); } TEST_F(DataManagerFixture, EmittAndIterate_ConcurrentAccess) { auto id = manager.AllocateDIA(); auto emitFn = manager.GetLocalEmitter<int>(id); auto it = manager.GetLocalBlocks<int>(id); emitFn(123); ASSERT_EQ(123, it.Next()); ASSERT_FALSE(it.HasNext()); emitFn(22); ASSERT_TRUE(it.HasNext()); ASSERT_EQ(22, it.Next()); } <|endoftext|>
<commit_before>// Copyright (c) 2015-2019 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #ifndef TAO_SEQ_FOLD_HPP #define TAO_SEQ_FOLD_HPP #include <type_traits> #include "integer_sequence.hpp" #include "make_integer_sequence.hpp" #include "select.hpp" namespace tao { namespace seq { namespace impl { template< typename OP, bool, typename, typename T, T... > struct folder; template< typename OP, std::size_t... Is, typename T, T... Ns > struct folder< OP, false, index_sequence< Is... >, T, Ns... > { template< std::size_t I > using subsel = seq::select< I, T, Ns... >; using type = integer_sequence< T, OP::template apply< T, subsel< 2 * Is >::value, subsel< 2 * Is + 1 >::value >::value... >; }; template< typename OP, std::size_t... Is, typename T, T N, T... Ns > struct folder< OP, true, index_sequence< Is... >, T, N, Ns... > { template< std::size_t I > using subsel = seq::select< I, T, Ns... >; using type = integer_sequence< T, N, OP::template apply< T, subsel< 2 * Is >::value, subsel< 2 * Is + 1 >::value >::value... >; }; } // namespace impl template< typename, typename T, T... > struct fold; template< typename OP, typename T, T N > struct fold< OP, T, N > : std::integral_constant< T, N > { }; template< typename OP, typename T, T... Ns > struct fold : fold< OP, typename impl::folder< OP, sizeof...( Ns ) % 2 == 1, make_index_sequence< sizeof...( Ns ) / 2 >, T, Ns... >::type > { }; template< typename OP, typename T, T... Ns > struct fold< OP, integer_sequence< T, Ns... > > : fold< OP, T, Ns... > { }; } // namespace seq } // namespace tao #endif <commit_msg>Use a C++17 fold expression to improve tao::seq::fold<><commit_after>// Copyright (c) 2015-2019 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #ifndef TAO_SEQ_FOLD_HPP #define TAO_SEQ_FOLD_HPP #include <type_traits> #include "config.hpp" #include "integer_sequence.hpp" #include "make_integer_sequence.hpp" #include "select.hpp" namespace tao { namespace seq { #ifdef TAO_SEQ_FOLD_EXPRESSIONS namespace impl { template< typename OP, typename T, T N > struct wrap { }; template< typename OP, typename T, T R, T L > constexpr auto operator+( std::integral_constant< T, R >, wrap< OP, T, L > ) noexcept { return typename OP::template apply< T, R, L >(); } template< typename OP, typename T, T N, T... Ns > constexpr auto fold() noexcept { return ( std::integral_constant< T, N >() + ... + wrap< OP, T, Ns >() ); } } // namespace impl template< typename OP, typename T, T... Ns > struct fold : decltype( impl::fold< OP, T, Ns... >() ) { }; #else namespace impl { template< typename OP, bool, typename, typename T, T... > struct folder; template< typename OP, std::size_t... Is, typename T, T... Ns > struct folder< OP, false, index_sequence< Is... >, T, Ns... > { template< std::size_t I > using subsel = seq::select< I, T, Ns... >; using type = integer_sequence< T, OP::template apply< T, subsel< 2 * Is >::value, subsel< 2 * Is + 1 >::value >::value... >; }; template< typename OP, std::size_t... Is, typename T, T N, T... Ns > struct folder< OP, true, index_sequence< Is... >, T, N, Ns... > { template< std::size_t I > using subsel = seq::select< I, T, Ns... >; using type = integer_sequence< T, N, OP::template apply< T, subsel< 2 * Is >::value, subsel< 2 * Is + 1 >::value >::value... >; }; } // namespace impl template< typename, typename T, T... > struct fold; template< typename OP, typename T, T N > struct fold< OP, T, N > : std::integral_constant< T, N > { }; template< typename OP, typename T, T... Ns > struct fold : fold< OP, typename impl::folder< OP, sizeof...( Ns ) % 2 == 1, make_index_sequence< sizeof...( Ns ) / 2 >, T, Ns... >::type > { }; #endif template< typename OP, typename T, T... Ns > struct fold< OP, integer_sequence< T, Ns... > > : fold< OP, T, Ns... > { }; } // namespace seq } // namespace tao #endif <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Embedded Framework 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 "include/cef_scheme.h" #include "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "tests/unittests/test_handler.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char kTestDomain[] = "test-download"; const char kTestEntryUrl[] = "http://test-download/test.html"; const char kTestDownloadUrl[] = "http://test-download/download.txt"; const char kTestFileName[] = "download_test.txt"; const char kTestContentDisposition[] = "attachment; filename=\"download_test.txt\""; const char kTestMimeType[] = "text/plain"; const char kTestContent[] = "Download test text"; class DownloadSchemeHandler : public CefResourceHandler { public: explicit DownloadSchemeHandler(TrackCallback* got_download_request) : got_download_request_(got_download_request), offset_(0) {} virtual bool ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback) OVERRIDE { std::string url = request->GetURL(); if (url == kTestEntryUrl) { content_ = "<html><body>Download Test</body></html>"; mime_type_ = "text/html"; } else if (url == kTestDownloadUrl) { got_download_request_->yes(); content_ = kTestContent; mime_type_ = kTestMimeType; content_disposition_ = kTestContentDisposition; } else { EXPECT_TRUE(false); // Not reached. return false; } callback->Continue(); return true; } virtual void GetResponseHeaders(CefRefPtr<CefResponse> response, int64& response_length, CefString& redirectUrl) OVERRIDE { response_length = content_.size(); response->SetStatus(200); response->SetMimeType(mime_type_); if (!content_disposition_.empty()) { CefResponse::HeaderMap headerMap; response->GetHeaderMap(headerMap); headerMap.insert( std::make_pair("Content-Disposition", content_disposition_)); response->SetHeaderMap(headerMap); } } virtual bool ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr<CefCallback> callback) OVERRIDE { bool has_data = false; bytes_read = 0; size_t size = content_.size(); if (offset_ < size) { int transfer_size = std::min(bytes_to_read, static_cast<int>(size - offset_)); memcpy(data_out, content_.c_str() + offset_, transfer_size); offset_ += transfer_size; bytes_read = transfer_size; has_data = true; } return has_data; } virtual void Cancel() OVERRIDE { } private: TrackCallback* got_download_request_; std::string content_; std::string mime_type_; std::string content_disposition_; size_t offset_; IMPLEMENT_REFCOUNTING(SchemeHandler); }; class DownloadSchemeHandlerFactory : public CefSchemeHandlerFactory { public: explicit DownloadSchemeHandlerFactory(TrackCallback* got_download_request) : got_download_request_(got_download_request) {} virtual CefRefPtr<CefResourceHandler> Create( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name, CefRefPtr<CefRequest> request) OVERRIDE { return new DownloadSchemeHandler(got_download_request_); } private: TrackCallback* got_download_request_; IMPLEMENT_REFCOUNTING(SchemeHandlerFactory); }; class DownloadTestHandler : public TestHandler { public: DownloadTestHandler() {} virtual void RunTest() OVERRIDE { CefRegisterSchemeHandlerFactory("http", kTestDomain, new DownloadSchemeHandlerFactory(&got_download_request_)); // Create a new temporary directory. EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); test_path_ = temp_dir_.path().AppendASCII(kTestFileName); // Create the browser CreateBrowser(kTestEntryUrl); } virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) OVERRIDE { EXPECT_STREQ(kTestEntryUrl, frame->GetURL().ToString().c_str()); // Begin the download. browser->GetHost()->StartDownload(kTestDownloadUrl); } virtual void OnBeforeDownload( CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item, const CefString& suggested_name, CefRefPtr<CefBeforeDownloadCallback> callback) OVERRIDE { EXPECT_TRUE(CefCurrentlyOn(TID_UI)); EXPECT_FALSE(got_on_before_download_); EXPECT_FALSE(got_on_download_updated_); got_on_before_download_.yes(); EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_STREQ(kTestFileName, suggested_name.ToString().c_str()); EXPECT_TRUE(download_item.get()); EXPECT_TRUE(callback.get()); download_id_ = download_item->GetId(); EXPECT_LT(0, download_id_); EXPECT_TRUE(download_item->IsValid()); EXPECT_TRUE(download_item->IsInProgress()); EXPECT_FALSE(download_item->IsComplete()); EXPECT_FALSE(download_item->IsCanceled()); EXPECT_EQ(0LL, download_item->GetCurrentSpeed()); EXPECT_EQ(0, download_item->GetPercentComplete()); EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), download_item->GetTotalBytes()); EXPECT_EQ(0LL, download_item->GetReceivedBytes()); EXPECT_EQ(0L, download_item->GetFullPath().length()); EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str()); EXPECT_EQ(0L, download_item->GetSuggestedFileName().length()); EXPECT_STREQ(kTestContentDisposition, download_item->GetContentDisposition().ToString().c_str()); EXPECT_STREQ(kTestMimeType, download_item->GetMimeType().ToString().c_str()); callback->Continue(test_path_.value(), false); } virtual void OnDownloadUpdated( CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item, CefRefPtr<CefDownloadItemCallback> callback) OVERRIDE { EXPECT_TRUE(CefCurrentlyOn(TID_UI)); EXPECT_TRUE(got_on_before_download_); got_on_download_updated_.yes(); EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_TRUE(download_item.get()); EXPECT_TRUE(callback.get()); EXPECT_EQ(download_id_, download_item->GetId()); EXPECT_TRUE(download_item->IsValid()); EXPECT_FALSE(download_item->IsCanceled()); EXPECT_LT(0LL, download_item->GetCurrentSpeed()); EXPECT_LT(0, download_item->GetPercentComplete()); EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), download_item->GetTotalBytes()); EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str()); EXPECT_STREQ(kTestContentDisposition, download_item->GetContentDisposition().ToString().c_str()); EXPECT_STREQ(kTestMimeType, download_item->GetMimeType().ToString().c_str()); std::string full_path = download_item->GetFullPath(); if (!full_path.empty()) { got_full_path_.yes(); EXPECT_STREQ(CefString(test_path_.value()).ToString().c_str(), full_path.c_str()); } if (download_item->IsComplete()) { EXPECT_FALSE(download_item->IsInProgress()); EXPECT_EQ(100, download_item->GetPercentComplete()); EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), download_item->GetReceivedBytes()); DestroyTest(); } else { EXPECT_TRUE(download_item->IsInProgress()); EXPECT_LT(0LL, download_item->GetReceivedBytes()); } } virtual void DestroyTest() OVERRIDE { CefRegisterSchemeHandlerFactory("http", kTestDomain, NULL); EXPECT_TRUE(got_download_request_); EXPECT_TRUE(got_on_before_download_); EXPECT_TRUE(got_on_download_updated_); EXPECT_TRUE(got_full_path_); // Verify the file contents. std::string contents; EXPECT_TRUE(file_util::ReadFileToString(test_path_, &contents)); EXPECT_STREQ(kTestContent, contents.c_str()); EXPECT_TRUE(temp_dir_.Delete()); TestHandler::DestroyTest(); } private: base::ScopedTempDir temp_dir_; FilePath test_path_; int download_id_; TrackCallback got_download_request_; TrackCallback got_on_before_download_; TrackCallback got_on_download_updated_; TrackCallback got_full_path_; }; } // namespace // Verify that downloads work. TEST(DownloadTest, Download) { CefRefPtr<DownloadTestHandler> handler = new DownloadTestHandler(); handler->ExecuteTest(); } <commit_msg>Fix Mac compile error.<commit_after>// Copyright (c) 2013 The Chromium Embedded Framework 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 "include/cef_scheme.h" #include "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "tests/unittests/test_handler.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char kTestDomain[] = "test-download"; const char kTestEntryUrl[] = "http://test-download/test.html"; const char kTestDownloadUrl[] = "http://test-download/download.txt"; const char kTestFileName[] = "download_test.txt"; const char kTestContentDisposition[] = "attachment; filename=\"download_test.txt\""; const char kTestMimeType[] = "text/plain"; const char kTestContent[] = "Download test text"; class DownloadSchemeHandler : public CefResourceHandler { public: explicit DownloadSchemeHandler(TrackCallback* got_download_request) : got_download_request_(got_download_request), offset_(0) {} virtual bool ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback) OVERRIDE { std::string url = request->GetURL(); if (url == kTestEntryUrl) { content_ = "<html><body>Download Test</body></html>"; mime_type_ = "text/html"; } else if (url == kTestDownloadUrl) { got_download_request_->yes(); content_ = kTestContent; mime_type_ = kTestMimeType; content_disposition_ = kTestContentDisposition; } else { EXPECT_TRUE(false); // Not reached. return false; } callback->Continue(); return true; } virtual void GetResponseHeaders(CefRefPtr<CefResponse> response, int64& response_length, CefString& redirectUrl) OVERRIDE { response_length = content_.size(); response->SetStatus(200); response->SetMimeType(mime_type_); if (!content_disposition_.empty()) { CefResponse::HeaderMap headerMap; response->GetHeaderMap(headerMap); headerMap.insert( std::make_pair("Content-Disposition", content_disposition_)); response->SetHeaderMap(headerMap); } } virtual bool ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr<CefCallback> callback) OVERRIDE { bool has_data = false; bytes_read = 0; size_t size = content_.size(); if (offset_ < size) { int transfer_size = std::min(bytes_to_read, static_cast<int>(size - offset_)); memcpy(data_out, content_.c_str() + offset_, transfer_size); offset_ += transfer_size; bytes_read = transfer_size; has_data = true; } return has_data; } virtual void Cancel() OVERRIDE { } private: TrackCallback* got_download_request_; std::string content_; std::string mime_type_; std::string content_disposition_; size_t offset_; IMPLEMENT_REFCOUNTING(SchemeHandler); }; class DownloadSchemeHandlerFactory : public CefSchemeHandlerFactory { public: explicit DownloadSchemeHandlerFactory(TrackCallback* got_download_request) : got_download_request_(got_download_request) {} virtual CefRefPtr<CefResourceHandler> Create( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name, CefRefPtr<CefRequest> request) OVERRIDE { return new DownloadSchemeHandler(got_download_request_); } private: TrackCallback* got_download_request_; IMPLEMENT_REFCOUNTING(SchemeHandlerFactory); }; class DownloadTestHandler : public TestHandler { public: DownloadTestHandler() {} virtual void RunTest() OVERRIDE { CefRegisterSchemeHandlerFactory("http", kTestDomain, new DownloadSchemeHandlerFactory(&got_download_request_)); // Create a new temporary directory. EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); test_path_ = temp_dir_.path().AppendASCII(kTestFileName); // Create the browser CreateBrowser(kTestEntryUrl); } virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) OVERRIDE { EXPECT_STREQ(kTestEntryUrl, frame->GetURL().ToString().c_str()); // Begin the download. browser->GetHost()->StartDownload(kTestDownloadUrl); } virtual void OnBeforeDownload( CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item, const CefString& suggested_name, CefRefPtr<CefBeforeDownloadCallback> callback) OVERRIDE { EXPECT_TRUE(CefCurrentlyOn(TID_UI)); EXPECT_FALSE(got_on_before_download_); EXPECT_FALSE(got_on_download_updated_); got_on_before_download_.yes(); EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_STREQ(kTestFileName, suggested_name.ToString().c_str()); EXPECT_TRUE(download_item.get()); EXPECT_TRUE(callback.get()); download_id_ = download_item->GetId(); EXPECT_LT(0, download_id_); EXPECT_TRUE(download_item->IsValid()); EXPECT_TRUE(download_item->IsInProgress()); EXPECT_FALSE(download_item->IsComplete()); EXPECT_FALSE(download_item->IsCanceled()); EXPECT_EQ(0LL, download_item->GetCurrentSpeed()); EXPECT_EQ(0, download_item->GetPercentComplete()); EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), download_item->GetTotalBytes()); EXPECT_EQ(0LL, download_item->GetReceivedBytes()); EXPECT_EQ(0UL, download_item->GetFullPath().length()); EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str()); EXPECT_EQ(0UL, download_item->GetSuggestedFileName().length()); EXPECT_STREQ(kTestContentDisposition, download_item->GetContentDisposition().ToString().c_str()); EXPECT_STREQ(kTestMimeType, download_item->GetMimeType().ToString().c_str()); callback->Continue(test_path_.value(), false); } virtual void OnDownloadUpdated( CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item, CefRefPtr<CefDownloadItemCallback> callback) OVERRIDE { EXPECT_TRUE(CefCurrentlyOn(TID_UI)); EXPECT_TRUE(got_on_before_download_); got_on_download_updated_.yes(); EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_TRUE(download_item.get()); EXPECT_TRUE(callback.get()); EXPECT_EQ(download_id_, download_item->GetId()); EXPECT_TRUE(download_item->IsValid()); EXPECT_FALSE(download_item->IsCanceled()); EXPECT_LT(0LL, download_item->GetCurrentSpeed()); EXPECT_LT(0, download_item->GetPercentComplete()); EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), download_item->GetTotalBytes()); EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str()); EXPECT_STREQ(kTestContentDisposition, download_item->GetContentDisposition().ToString().c_str()); EXPECT_STREQ(kTestMimeType, download_item->GetMimeType().ToString().c_str()); std::string full_path = download_item->GetFullPath(); if (!full_path.empty()) { got_full_path_.yes(); EXPECT_STREQ(CefString(test_path_.value()).ToString().c_str(), full_path.c_str()); } if (download_item->IsComplete()) { EXPECT_FALSE(download_item->IsInProgress()); EXPECT_EQ(100, download_item->GetPercentComplete()); EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), download_item->GetReceivedBytes()); DestroyTest(); } else { EXPECT_TRUE(download_item->IsInProgress()); EXPECT_LT(0LL, download_item->GetReceivedBytes()); } } virtual void DestroyTest() OVERRIDE { CefRegisterSchemeHandlerFactory("http", kTestDomain, NULL); EXPECT_TRUE(got_download_request_); EXPECT_TRUE(got_on_before_download_); EXPECT_TRUE(got_on_download_updated_); EXPECT_TRUE(got_full_path_); // Verify the file contents. std::string contents; EXPECT_TRUE(file_util::ReadFileToString(test_path_, &contents)); EXPECT_STREQ(kTestContent, contents.c_str()); EXPECT_TRUE(temp_dir_.Delete()); TestHandler::DestroyTest(); } private: base::ScopedTempDir temp_dir_; FilePath test_path_; int download_id_; TrackCallback got_download_request_; TrackCallback got_on_before_download_; TrackCallback got_on_download_updated_; TrackCallback got_full_path_; }; } // namespace // Verify that downloads work. TEST(DownloadTest, Download) { CefRefPtr<DownloadTestHandler> handler = new DownloadTestHandler(); handler->ExecuteTest(); } <|endoftext|>
<commit_before>/// /// @file has_openmp.cpp /// @brief Used to check if MSVC compiler supports OpenMP. /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <omp.h> #include <iostream> int main() { std::cout << "OpenMP version (yyyymm) : " << _OPENMP << std::endl << "Number of CPU cores : " << omp_get_max_threads() << std::endl; return 0; } <commit_msg>Delete msvc/has_openmp.cpp<commit_after><|endoftext|>
<commit_before> #include <iostream> #include <algorithm> #include <memory> #include <cpplocate/cpplocate.h> #include <cpplocate/ModuleInfo.h> #include <glm/vec2.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glbinding/gl/gl.h> #include <glbinding/gl/extension.h> #include <glbinding/gl/bitfield.h> #include <glbinding/ContextInfo.h> #include <glbinding/Version.h> #include <GLFW/glfw3.h> #include <globjects/globjects.h> #include <globjects/logging.h> #include <globjects/base/File.h> #include <openll/GlyphRenderer.h> #include <openll/FontLoader.h> #include <openll/FontFace.h> #include <openll/GlyphSequence.h> #include <openll/GlyphVertexCloud.h> #include <openll/Alignment.h> #include <openll/LineAnchor.h> #include <openll/SuperSampling.h> #include "datapath.inl" using namespace gl; namespace { std::vector<int> g_fontSizes {36, 72, 144}; std::map<int, gloperate_text::FontFace *> g_fonts; std::vector<gloperate_text::GlyphVertexCloud> g_clouds; auto g_size = glm::ivec2{ }; bool g_config_changed = true; size_t g_patternID = 0; std::unique_ptr<gloperate_text::GlyphRenderer> g_renderer; struct SamplingPattern { std::string name; gloperate_text::SuperSampling pattern; }; std::vector<SamplingPattern> g_patterns { {"None", gloperate_text::SuperSampling::None}, {"Grid1x3", gloperate_text::SuperSampling::Grid1x3}, {"Grid2x4", gloperate_text::SuperSampling::Grid2x4}, {"RGSS2x2", gloperate_text::SuperSampling::RGSS2x2}, {"Quincunx", gloperate_text::SuperSampling::Quincunx}, {"Rooks8", gloperate_text::SuperSampling::Rooks8}, {"Grid3x3", gloperate_text::SuperSampling::Grid3x3}, {"Grid4x4", gloperate_text::SuperSampling::Grid4x4} }; } void initialize() { glClearColor(1.f, 1.f, 1.f, 1.f); const auto dataPath = common::retrieveDataPath("openll", "dataPath"); gloperate_text::FontLoader loader; for (auto size : g_fontSizes) { auto string = std::to_string(size); auto font = loader.load(dataPath + "/fonts/opensansr" + string + "/opensansr" + string + ".fnt"); g_fonts[size] = font; } g_renderer = std::unique_ptr<gloperate_text::GlyphRenderer>(new gloperate_text::GlyphRenderer); } void deinitialize() { for (auto pair : g_fonts) { delete pair.second; } globjects::detachAllObjects(); } std::vector<gloperate_text::GlyphSequence> prepareSequences( glm::ivec2 viewport , gloperate_text::SuperSampling pattern , int size , float x_coord ) { std::vector<gloperate_text::GlyphSequence> sequences; auto y = -.8f; for (int renderSize = 5; renderSize < 30; ++renderSize) { const auto string = std::string{"Example (font "} + std::to_string(size) + ", size " + std::to_string(renderSize) + ")"; const std::u32string unicode_string {string.begin(), string.end()}; const auto origin = glm::vec2{x_coord, y}; gloperate_text::GlyphSequence sequence; sequence.setString(unicode_string); sequence.setWordWrap(true); sequence.setLineWidth(400.f); sequence.setAlignment(gloperate_text::Alignment::LeftAligned); sequence.setLineAnchor(gloperate_text::LineAnchor::Ascent); sequence.setFontSize(renderSize); sequence.setFontFace(g_fonts[size]); sequence.setFontColor(glm::vec4(glm::vec3(0.f), 1.f)); sequence.setSuperSampling(pattern); // compute transform matrix glm::mat4 transform; transform = glm::translate(transform, glm::vec3(origin, 0.f)); transform = glm::scale(transform, glm::vec3(1.f, static_cast<float>(viewport.x) / viewport.y, 1.f)); transform = glm::scale(transform, glm::vec3(1 / 300.f)); sequence.setAdditionalTransform(transform); sequences.push_back(sequence); y += 0.02f + renderSize * 0.005f; } return sequences; } void draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (g_config_changed) { glViewport(0, 0, g_size.x, g_size.y); std::cout << g_patterns[g_patternID].name <<std::endl; auto x = -.9f; g_clouds.clear(); for (auto pair : g_fonts) { auto size = pair.first; auto sequences = prepareSequences(g_size, g_patterns[g_patternID].pattern, size, x); g_clouds.push_back({}); g_clouds.back().updateWithSequences(sequences, true); x += 0.6f; } } gl::glDepthMask(gl::GL_FALSE); gl::glEnable(gl::GL_CULL_FACE); gl::glEnable(gl::GL_BLEND); gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA); for (auto cloud : g_clouds) g_renderer->render(cloud); gl::glDepthMask(gl::GL_TRUE); gl::glDisable(gl::GL_CULL_FACE); gl::glDisable(gl::GL_BLEND); g_config_changed = false; } void error(int errnum, const char * errmsg) { globjects::critical() << errnum << ": " << errmsg << std::endl; } void framebuffer_size_callback(GLFWwindow * /*window*/, int width, int height) { g_size = glm::ivec2{ width, height }; g_config_changed = true; } void key_callback(GLFWwindow * window, int key, int /*scancode*/, int action, int /*mods*/) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, 1); if (key == GLFW_KEY_F5 && action == GLFW_RELEASE) globjects::File::reloadAll(); if ('1' <= key && key <= '9' && action == GLFW_PRESS) { g_patternID = std::min(static_cast<size_t>(key - '1'), g_patterns.size() - 1); g_config_changed = true; } } int main() { #ifdef SYSTEM_DARWIN globjects::critical() << "macOS does currently not support compute shader (OpenGL 4.3. required)."; return 0; #endif // Initialize GLFW if (!glfwInit()) return 1; glfwSetErrorCallback(error); glfwDefaultWindowHints(); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Create a context and, if valid, make it current GLFWwindow * window = glfwCreateWindow(640, 480, "ll-opengl | supersampling", nullptr, nullptr); if (!window) { globjects::critical() << "Context creation failed. Terminate execution."; glfwTerminate(); return -1; } glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwMakeContextCurrent(window); // Initialize globjects (internally initializes glbinding, and registers the current context) globjects::init(); std::cout << std::endl << "OpenGL Version: " << glbinding::ContextInfo::version() << std::endl << "OpenGL Vendor: " << glbinding::ContextInfo::vendor() << std::endl << "OpenGL Renderer: " << glbinding::ContextInfo::renderer() << std::endl << std::endl; globjects::DebugMessage::enable(); // globjects::info() << "Press F5 to reload compute shader." << std::endl << std::endl; glfwGetFramebufferSize(window, &g_size[0], &g_size[1]); initialize(); // Main loop while (!glfwWindowShouldClose(window)) { glfwPollEvents(); draw(); glfwSwapBuffers(window); } deinitialize(); // Properly shutdown GLFW glfwTerminate(); return 0; } <commit_msg>Change text size in supersampling example<commit_after> #include <iostream> #include <algorithm> #include <memory> #include <cpplocate/cpplocate.h> #include <cpplocate/ModuleInfo.h> #include <glm/vec2.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glbinding/gl/gl.h> #include <glbinding/gl/extension.h> #include <glbinding/gl/bitfield.h> #include <glbinding/ContextInfo.h> #include <glbinding/Version.h> #include <GLFW/glfw3.h> #include <globjects/globjects.h> #include <globjects/logging.h> #include <globjects/base/File.h> #include <openll/GlyphRenderer.h> #include <openll/FontLoader.h> #include <openll/FontFace.h> #include <openll/GlyphSequence.h> #include <openll/GlyphVertexCloud.h> #include <openll/Alignment.h> #include <openll/LineAnchor.h> #include <openll/SuperSampling.h> #include "datapath.inl" using namespace gl; namespace { std::vector<int> g_fontSizes {36, 72, 144}; std::map<int, gloperate_text::FontFace *> g_fonts; std::vector<gloperate_text::GlyphVertexCloud> g_clouds; auto g_size = glm::ivec2{ }; bool g_config_changed = true; size_t g_patternID = 0; std::unique_ptr<gloperate_text::GlyphRenderer> g_renderer; struct SamplingPattern { std::string name; gloperate_text::SuperSampling pattern; }; std::vector<SamplingPattern> g_patterns { {"None", gloperate_text::SuperSampling::None}, {"Grid1x3", gloperate_text::SuperSampling::Grid1x3}, {"Grid2x4", gloperate_text::SuperSampling::Grid2x4}, {"RGSS2x2", gloperate_text::SuperSampling::RGSS2x2}, {"Quincunx", gloperate_text::SuperSampling::Quincunx}, {"Rooks8", gloperate_text::SuperSampling::Rooks8}, {"Grid3x3", gloperate_text::SuperSampling::Grid3x3}, {"Grid4x4", gloperate_text::SuperSampling::Grid4x4} }; } void initialize() { glClearColor(1.f, 1.f, 1.f, 1.f); const auto dataPath = common::retrieveDataPath("openll", "dataPath"); gloperate_text::FontLoader loader; for (auto size : g_fontSizes) { auto string = std::to_string(size); auto font = loader.load(dataPath + "/fonts/opensansr" + string + "/opensansr" + string + ".fnt"); g_fonts[size] = font; } g_renderer = std::unique_ptr<gloperate_text::GlyphRenderer>(new gloperate_text::GlyphRenderer); std::cout << "Press 1-9 to choose different supersampling patterns" << std::endl; } void deinitialize() { for (auto pair : g_fonts) { delete pair.second; } globjects::detachAllObjects(); } std::vector<gloperate_text::GlyphSequence> prepareSequences( glm::ivec2 viewport , gloperate_text::SuperSampling pattern , int size , float x_coord ) { std::vector<gloperate_text::GlyphSequence> sequences; auto y = -.8f; for (int renderSize = 5; renderSize < 30; ++renderSize) { const auto string = std::string{"Example (font "} + std::to_string(size) + ", size " + std::to_string(renderSize) + ")"; const std::u32string unicode_string {string.begin(), string.end()}; const auto origin = glm::vec2{x_coord, y}; gloperate_text::GlyphSequence sequence; sequence.setString(unicode_string); sequence.setWordWrap(true); sequence.setLineWidth(400.f); sequence.setAlignment(gloperate_text::Alignment::LeftAligned); sequence.setLineAnchor(gloperate_text::LineAnchor::Ascent); sequence.setFontSize(renderSize); sequence.setFontFace(g_fonts[size]); sequence.setFontColor(glm::vec4(glm::vec3(0.f), 1.f)); sequence.setSuperSampling(pattern); // compute transform matrix glm::mat4 transform; transform = glm::translate(transform, glm::vec3(origin, 0.f)); transform = glm::scale(transform, glm::vec3(static_cast<float>(viewport.y) / viewport.x, 1.f, 1.f)); transform = glm::scale(transform, glm::vec3(2.f / viewport.y)); sequence.setAdditionalTransform(transform); sequences.push_back(sequence); y += 0.02f + renderSize * 0.005f; } return sequences; } void draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (g_config_changed) { glViewport(0, 0, g_size.x, g_size.y); auto x = -.9f; g_clouds.clear(); for (auto pair : g_fonts) { auto size = pair.first; auto sequences = prepareSequences(g_size, g_patterns[g_patternID].pattern, size, x); g_clouds.push_back({}); g_clouds.back().updateWithSequences(sequences, true); x += 0.6f; } } gl::glDepthMask(gl::GL_FALSE); gl::glEnable(gl::GL_CULL_FACE); gl::glEnable(gl::GL_BLEND); gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA); for (auto cloud : g_clouds) g_renderer->render(cloud); gl::glDepthMask(gl::GL_TRUE); gl::glDisable(gl::GL_CULL_FACE); gl::glDisable(gl::GL_BLEND); g_config_changed = false; } void error(int errnum, const char * errmsg) { globjects::critical() << errnum << ": " << errmsg << std::endl; } void framebuffer_size_callback(GLFWwindow * /*window*/, int width, int height) { g_size = glm::ivec2{ width, height }; g_config_changed = true; } void key_callback(GLFWwindow * window, int key, int /*scancode*/, int action, int /*mods*/) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, 1); if (key == GLFW_KEY_F5 && action == GLFW_RELEASE) globjects::File::reloadAll(); if ('1' <= key && key <= '9' && action == GLFW_PRESS) { g_patternID = std::min(static_cast<size_t>(key - '1'), g_patterns.size() - 1); g_config_changed = true; std::cout << "Supersampling pattern: " << g_patterns[g_patternID].name << std::endl; } } int main() { #ifdef SYSTEM_DARWIN globjects::critical() << "macOS does currently not support compute shader (OpenGL 4.3. required)."; return 0; #endif // Initialize GLFW if (!glfwInit()) return 1; glfwSetErrorCallback(error); glfwDefaultWindowHints(); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Create a context and, if valid, make it current GLFWwindow * window = glfwCreateWindow(640, 480, "ll-opengl | supersampling", nullptr, nullptr); if (!window) { globjects::critical() << "Context creation failed. Terminate execution."; glfwTerminate(); return -1; } glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwMakeContextCurrent(window); // Initialize globjects (internally initializes glbinding, and registers the current context) globjects::init(); std::cout << std::endl << "OpenGL Version: " << glbinding::ContextInfo::version() << std::endl << "OpenGL Vendor: " << glbinding::ContextInfo::vendor() << std::endl << "OpenGL Renderer: " << glbinding::ContextInfo::renderer() << std::endl << std::endl; globjects::DebugMessage::enable(); // globjects::info() << "Press F5 to reload compute shader." << std::endl << std::endl; glfwGetFramebufferSize(window, &g_size[0], &g_size[1]); initialize(); // Main loop while (!glfwWindowShouldClose(window)) { glfwPollEvents(); draw(); glfwSwapBuffers(window); } deinitialize(); // Properly shutdown GLFW glfwTerminate(); return 0; } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #if GOOGLE_CUDA #include "tensorflow/core/kernels/cwise_ops_gpu_common.cu.h" namespace tensorflow { namespace functor { DEFINE_BINARY5(xlogy, Eigen::half, float, double, complex64, complex128); } // namespace functor } // namespace tensorflow #endif // GOOGLE_CUDA <commit_msg>[ROCm] enable Xlogy op on ROCm.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #include "tensorflow/core/kernels/cwise_ops_gpu_common.cu.h" namespace tensorflow { namespace functor { #if GOOGLE_CUDA DEFINE_BINARY5(xlogy, Eigen::half, float, double, complex64, complex128); #elif TENSORFLOW_USE_ROCM // ROCM TODO: enable complex64 / complex128 after compiler fix. DEFINE_BINARY3(xlogy, Eigen::half, float, double); #endif } // namespace functor } // namespace tensorflow #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM <|endoftext|>
<commit_before>/* Copyright Eli Dupree and Isaac Dupree, 2011, 2012 This file is part of Lasercake. Lasercake is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lasercake is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LASERCAKE_BBOX_COLLISION_DETECTOR_HPP__ #define LASERCAKE_BBOX_COLLISION_DETECTOR_HPP__ #include <boost/integer.hpp> #include <unordered_map> #include <unordered_set> #include <array> #include <cassert> #include <cstdlib> using std::unordered_map; using std::unordered_set; typedef size_t num_bits_type; typedef size_t num_coordinates_type; // ObjectIdentifier needs hash and == and to be freely copiable. So, ints will do, pointers will do... // coordinate_bits should usually be 32 or 64. I don't know if it works for other values. template<typename ObjectIdentifier, num_bits_type coordinate_bits, num_coordinates_type num_dimensions> class bbox_collision_detector { static_assert(num_dimensions >= 0, "You can't make a space with negative dimensions!"); static_assert(coordinate_bits >= 0, "You can't have an int type with negative bits!"); friend class zbox_tester; public: typedef typename boost::uint_t<coordinate_bits>::fast Coordinate; struct bounding_box { std::array<Coordinate, num_dimensions> min, size; bool overlaps(bounding_box const& other)const { for (num_coordinates_type i = 0; i < num_dimensions; ++i) { // this should correctly handle zboxes' "size=0" when all bits are ignored if (other.min[i] + (other.size[i] - 1) < min[i]) return false; if ( min[i] + ( size[i] - 1) < other.min[i]) return false; } return true; } }; bbox_collision_detector():objects_tree(nullptr){} private: static const num_bits_type total_bits = coordinate_bits * num_dimensions; static Coordinate safe_left_shift_one(num_bits_type shift) { if (shift >= 8*sizeof(Coordinate)) return 0; return Coordinate(1) << shift; // TODO address the fact that this could put bits higher than the appropriate amount if coordinate_bits isn't the number of bits of the type } struct zbox { // We ensure that every bit except the ones specifically supposed to be on is off. std::array<Coordinate, num_dimensions> coords; std::array<Coordinate, num_dimensions> interleaved_bits; num_bits_type num_low_bits_ignored; zbox():num_low_bits_ignored(total_bits){ for (num_coordinates_type i = 0; i < num_dimensions; ++i) interleaved_bits[i] = 0; } bool subsumes(zbox const& other)const { if (other.num_low_bits_ignored > num_low_bits_ignored) return false; for (num_coordinates_type i = num_low_bits_ignored / coordinate_bits; i < num_dimensions; ++i) { Coordinate mask = ~Coordinate(0); if (i == num_low_bits_ignored / coordinate_bits) { mask &= ~(safe_left_shift_one(num_low_bits_ignored % coordinate_bits) - 1); } if ((interleaved_bits[i] & mask) != (other.interleaved_bits[i] & mask)) return false; } return true; } bool get_bit(num_bits_type bit)const { return interleaved_bits[bit / coordinate_bits] & safe_left_shift_one(bit % coordinate_bits); } num_bits_type num_bits_ignored_by_dimension(num_coordinates_type dim)const { return (num_low_bits_ignored + (num_dimensions - 1) - dim) / num_dimensions; } // note: gives "size=0" for max-sized things bounding_box get_bbox()const { bounding_box result; result.min = coords; for (num_coordinates_type i = 0; i < num_dimensions; ++i) { result.size[i] = safe_left_shift_one(num_bits_ignored_by_dimension(i)); } return result; } }; static int idx_of_highest_bit(Coordinate i) { int upper_bound = coordinate_bits; int lower_bound = -1; while(true) { int halfway_bit_idx = (upper_bound + lower_bound) >> 1; if (halfway_bit_idx == lower_bound) return lower_bound; if (i & ~(safe_left_shift_one(halfway_bit_idx) - 1)) lower_bound = halfway_bit_idx; else upper_bound = halfway_bit_idx; } } struct ztree_node { zbox here; ztree_node *child0; ztree_node *child1; unordered_set<ObjectIdentifier> objects_here; ztree_node(zbox box):here(box),child0(nullptr),child1(nullptr){} }; static zbox smallest_joint_parent(zbox zb1, zbox zb2) { zbox new_box; for (int /* hack... TODO, should possibly be num_coordinates_type, but signed? */ i = num_dimensions - 1; i >= 0; --i) { const int highest_bit_idx = idx_of_highest_bit(zb1.interleaved_bits[i] ^ zb2.interleaved_bits[i]); assert((zb1.interleaved_bits[i] & ~((safe_left_shift_one(highest_bit_idx+1)) - 1)) == (zb2.interleaved_bits[i] & ~((safe_left_shift_one(highest_bit_idx+1)) - 1))); new_box.interleaved_bits[i] = (zb1.interleaved_bits[i]) & (~((safe_left_shift_one(highest_bit_idx + 1)) - 1)); if (highest_bit_idx >= 0) { new_box.num_low_bits_ignored = highest_bit_idx+1 + i * coordinate_bits; for (num_coordinates_type j = 0; j < num_dimensions; ++j) { assert( (zb1.coords[j] & ~(safe_left_shift_one(new_box.num_bits_ignored_by_dimension(j)) - 1)) == (zb2.coords[j] & ~(safe_left_shift_one(new_box.num_bits_ignored_by_dimension(j)) - 1))); new_box.coords[j] = zb1.coords[j] & ~(safe_left_shift_one(new_box.num_bits_ignored_by_dimension(j)) - 1); } return new_box; } } new_box.num_low_bits_ignored = 0; assert(zb1.coords == zb2.coords); new_box.coords = zb1.coords; return new_box; } static zbox box_from_coords(std::array<Coordinate, num_dimensions> const& coords, num_bits_type num_low_bits_ignored) { zbox result; result.num_low_bits_ignored = num_low_bits_ignored; for (num_coordinates_type i = 0; i < num_dimensions; ++i) { result.coords[i] = coords[i] & (~(safe_left_shift_one(result.num_bits_ignored_by_dimension(i)) - 1)); } for (num_bits_type bit_within_interleaved_bits = num_low_bits_ignored; bit_within_interleaved_bits < total_bits; ++bit_within_interleaved_bits) { const num_bits_type bit_idx_within_coordinates = bit_within_interleaved_bits / num_dimensions; const num_coordinates_type which_coordinate = bit_within_interleaved_bits % num_dimensions; const num_bits_type interleaved_bit_array_idx = bit_within_interleaved_bits / coordinate_bits; const num_bits_type interleaved_bit_local_idx = bit_within_interleaved_bits % coordinate_bits; assert(bit_idx_within_coordinates >= result.num_bits_ignored_by_dimension(which_coordinate)); result.interleaved_bits[interleaved_bit_array_idx] |= ((coords[which_coordinate] >> bit_idx_within_coordinates) & 1) << interleaved_bit_local_idx; } return result; } static void insert_box(ztree_node*& tree, ObjectIdentifier obj, zbox box) { if (!tree) { tree = new ztree_node(box); tree->objects_here.insert(obj); } else { if (tree->here.subsumes(box)) { if (box.num_low_bits_ignored == tree->here.num_low_bits_ignored) { tree->objects_here.insert(obj); } else { if (box.get_bit(tree->here.num_low_bits_ignored - 1)) insert_box(tree->child1, obj, box); else insert_box(tree->child0, obj, box); } } else { ztree_node *new_tree = new ztree_node(smallest_joint_parent(tree->here, box)); assert(new_tree->here.num_low_bits_ignored > tree->here.num_low_bits_ignored); assert(new_tree->here.subsumes(tree->here)); assert(new_tree->here.subsumes(box)); assert(tree->here.get_bit(new_tree->here.num_low_bits_ignored - 1) != box.get_bit(new_tree->here.num_low_bits_ignored - 1)); if (tree->here.get_bit(new_tree->here.num_low_bits_ignored - 1)) new_tree->child1 = tree; else new_tree->child0 = tree; tree = new_tree; insert_box(tree, obj, box); } } } static void delete_object(ztree_node*& tree, ObjectIdentifier obj, bounding_box const& bbox) { if (!tree) return; if (tree->here.get_bbox().overlaps(bbox)) { tree->objects_here.erase(obj); delete_object(tree->child0, obj, bbox); delete_object(tree->child1, obj, bbox); if (tree->objects_here.empty()) { if (tree->child0) { if (!tree->child1) { delete tree; tree = tree->child0; } } else { delete tree; tree = tree->child1; // which could be null } } } } static void delete_entire_tree(ztree_node*& tree) { if (!tree) return; delete_entire_tree(tree->child0); delete_entire_tree(tree->child1); delete tree; tree = nullptr; } void zget_objects_overlapping(ztree_node const* tree, unordered_set<ObjectIdentifier>& results, bounding_box const& bbox)const { if (tree && tree->here.get_bbox().overlaps(bbox)) { for (const ObjectIdentifier obj : tree->objects_here) { auto bbox_iter = bboxes_by_object.find(obj); assert(bbox_iter != bboxes_by_object.end()); if (bbox_iter->second.overlaps(bbox)) results.insert(obj); } zget_objects_overlapping(tree->child0, results, bbox); zget_objects_overlapping(tree->child1, results, bbox); } } unordered_map<ObjectIdentifier, bounding_box> bboxes_by_object; ztree_node* objects_tree; public: void insert(ObjectIdentifier id, bounding_box const& bbox) { bboxes_by_object.insert(std::make_pair(id, bbox)); Coordinate max_dim = bbox.size[0]; for (num_coordinates_type i = 1; i < num_dimensions; ++i) { if (bbox.size[i] > max_dim) max_dim = bbox.size[i]; } int exp = 0; while ((Coordinate(1) << exp) < max_dim) ++exp; int dimensions_we_can_single = 0; int dimensions_we_can_double = 0; const Coordinate base_box_size = safe_left_shift_one(exp); const Coordinate used_bits_mask = ~(base_box_size - 1); for (int i = num_dimensions - 1; i >= 0; --i) { if ((bbox.min[i] & used_bits_mask) + base_box_size >= bbox.min[i] + bbox.size[i]) ++dimensions_we_can_single; else break; } for (num_coordinates_type i = 0; i < num_dimensions - dimensions_we_can_single; ++i) { if (!(bbox.min[i] & base_box_size)) ++dimensions_we_can_double; else break; } #ifdef ZTREE_TESTING std::cerr << dimensions_we_can_single << "... " << dimensions_we_can_double << "...\n"; #endif for (int i = 0; i < (1 << ((num_dimensions - dimensions_we_can_single) - dimensions_we_can_double)); ++i) { std::array<Coordinate, num_dimensions> coords = bbox.min; for (num_coordinates_type j = dimensions_we_can_double; j < num_dimensions - dimensions_we_can_single; ++j) { if ((i << dimensions_we_can_double) & (1<<j)) coords[j] += base_box_size; } zbox zb = box_from_coords(coords, exp * num_dimensions + dimensions_we_can_double); if (zb.get_bbox().overlaps(bbox)) insert_box(objects_tree, id, zb); } } bool erase(ObjectIdentifier id) { auto bbox_iter = bboxes_by_object.find(id); if (bbox_iter == bboxes_by_object.end()) return false; delete_object(objects_tree, id, bbox_iter->second); bboxes_by_object.erase(bbox_iter); return true; } void get_objects_overlapping(unordered_set<ObjectIdentifier>& results, bounding_box const& bbox)const { zget_objects_overlapping(objects_tree, results, bbox); } ~bbox_collision_detector() { delete_entire_tree(objects_tree); } }; /* If there's one zbox in the tree [call it Z] tree = ztree_node { Z nullptr nullptr } Two zboxes that differ at bit B: child0 of a node with B ignored bits is the child whose Bth bit is 0. tree = ztree_node { Z1/Z2, with B ignored bits ptr to ztree_node { Z1 nullptr nullptr } ptr to ztree_node { Z2 nullptr nullptr } } */ #endif <commit_msg>Fixed stupid bugs in the ztree stuff.<commit_after>/* Copyright Eli Dupree and Isaac Dupree, 2011, 2012 This file is part of Lasercake. Lasercake is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lasercake is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LASERCAKE_BBOX_COLLISION_DETECTOR_HPP__ #define LASERCAKE_BBOX_COLLISION_DETECTOR_HPP__ #include <boost/integer.hpp> #include <unordered_map> #include <unordered_set> #include <array> #include <cassert> #include <cstdlib> using std::unordered_map; using std::unordered_set; typedef size_t num_bits_type; typedef size_t num_coordinates_type; // ObjectIdentifier needs hash and == and to be freely copiable. So, ints will do, pointers will do... // coordinate_bits should usually be 32 or 64. I don't know if it works for other values. template<typename ObjectIdentifier, num_bits_type coordinate_bits, num_coordinates_type num_dimensions> class bbox_collision_detector { static_assert(num_dimensions >= 0, "You can't make a space with negative dimensions!"); static_assert(coordinate_bits >= 0, "You can't have an int type with negative bits!"); friend class zbox_tester; public: typedef typename boost::uint_t<coordinate_bits>::fast Coordinate; struct bounding_box { std::array<Coordinate, num_dimensions> min, size; bool overlaps(bounding_box const& other)const { for (num_coordinates_type i = 0; i < num_dimensions; ++i) { // this should correctly handle zboxes' "size=0" when all bits are ignored if (other.min[i] + (other.size[i] - 1) < min[i]) return false; if ( min[i] + ( size[i] - 1) < other.min[i]) return false; } return true; } }; bbox_collision_detector():objects_tree(nullptr){} private: static const num_bits_type total_bits = coordinate_bits * num_dimensions; static Coordinate safe_left_shift_one(num_bits_type shift) { if (shift >= 8*sizeof(Coordinate)) return 0; return Coordinate(1) << shift; // TODO address the fact that this could put bits higher than the appropriate amount if coordinate_bits isn't the number of bits of the type } struct zbox { // We ensure that every bit except the ones specifically supposed to be on is off. std::array<Coordinate, num_dimensions> coords; std::array<Coordinate, num_dimensions> interleaved_bits; num_bits_type num_low_bits_ignored; zbox():num_low_bits_ignored(total_bits){ for (num_coordinates_type i = 0; i < num_dimensions; ++i) interleaved_bits[i] = 0; } bool subsumes(zbox const& other)const { if (other.num_low_bits_ignored > num_low_bits_ignored) return false; for (num_coordinates_type i = num_low_bits_ignored / coordinate_bits; i < num_dimensions; ++i) { Coordinate mask = ~Coordinate(0); if (i == num_low_bits_ignored / coordinate_bits) { mask &= ~(safe_left_shift_one(num_low_bits_ignored % coordinate_bits) - 1); } if ((interleaved_bits[i] & mask) != (other.interleaved_bits[i] & mask)) return false; } return true; } bool get_bit(num_bits_type bit)const { return interleaved_bits[bit / coordinate_bits] & safe_left_shift_one(bit % coordinate_bits); } num_bits_type num_bits_ignored_by_dimension(num_coordinates_type dim)const { return (num_low_bits_ignored + (num_dimensions - 1) - dim) / num_dimensions; } // note: gives "size=0" for max-sized things bounding_box get_bbox()const { bounding_box result; result.min = coords; for (num_coordinates_type i = 0; i < num_dimensions; ++i) { result.size[i] = safe_left_shift_one(num_bits_ignored_by_dimension(i)); } return result; } }; static int idx_of_highest_bit(Coordinate i) { int upper_bound = coordinate_bits; int lower_bound = -1; while(true) { int halfway_bit_idx = (upper_bound + lower_bound) >> 1; if (halfway_bit_idx == lower_bound) return lower_bound; if (i & ~(safe_left_shift_one(halfway_bit_idx) - 1)) lower_bound = halfway_bit_idx; else upper_bound = halfway_bit_idx; } } struct ztree_node { zbox here; ztree_node *child0; ztree_node *child1; unordered_set<ObjectIdentifier> objects_here; ztree_node(zbox box):here(box),child0(nullptr),child1(nullptr){} }; static zbox smallest_joint_parent(zbox zb1, zbox zb2) { zbox new_box; const num_bits_type max_ignored = std::max(zb1.num_low_bits_ignored, zb2.num_low_bits_ignored); for (int /* hack... TODO, should possibly be num_coordinates_type, but signed? */ i = num_dimensions - 1; i >= 0; --i) { int highest_bit_idx = idx_of_highest_bit(zb1.interleaved_bits[i] ^ zb2.interleaved_bits[i]); if ((highest_bit_idx+1 + i * coordinate_bits) < max_ignored) highest_bit_idx = max_ignored - i * coordinate_bits - 1; assert((zb1.interleaved_bits[i] & ~((safe_left_shift_one(highest_bit_idx+1)) - 1)) == (zb2.interleaved_bits[i] & ~((safe_left_shift_one(highest_bit_idx+1)) - 1))); new_box.interleaved_bits[i] = (zb1.interleaved_bits[i]) & (~((safe_left_shift_one(highest_bit_idx + 1)) - 1)); if (highest_bit_idx >= 0) { new_box.num_low_bits_ignored = highest_bit_idx+1 + i * coordinate_bits; for (num_coordinates_type j = 0; j < num_dimensions; ++j) { assert( (zb1.coords[j] & ~(safe_left_shift_one(new_box.num_bits_ignored_by_dimension(j)) - 1)) == (zb2.coords[j] & ~(safe_left_shift_one(new_box.num_bits_ignored_by_dimension(j)) - 1))); new_box.coords[j] = zb1.coords[j] & ~(safe_left_shift_one(new_box.num_bits_ignored_by_dimension(j)) - 1); } return new_box; } } new_box.num_low_bits_ignored = max_ignored; assert(zb1.coords == zb2.coords); new_box.coords = zb1.coords; return new_box; } static zbox box_from_coords(std::array<Coordinate, num_dimensions> const& coords, num_bits_type num_low_bits_ignored) { zbox result; result.num_low_bits_ignored = num_low_bits_ignored; for (num_coordinates_type i = 0; i < num_dimensions; ++i) { result.coords[i] = coords[i] & (~(safe_left_shift_one(result.num_bits_ignored_by_dimension(i)) - 1)); } for (num_bits_type bit_within_interleaved_bits = num_low_bits_ignored; bit_within_interleaved_bits < total_bits; ++bit_within_interleaved_bits) { const num_bits_type bit_idx_within_coordinates = bit_within_interleaved_bits / num_dimensions; const num_coordinates_type which_coordinate = bit_within_interleaved_bits % num_dimensions; const num_bits_type interleaved_bit_array_idx = bit_within_interleaved_bits / coordinate_bits; const num_bits_type interleaved_bit_local_idx = bit_within_interleaved_bits % coordinate_bits; assert(bit_idx_within_coordinates >= result.num_bits_ignored_by_dimension(which_coordinate)); result.interleaved_bits[interleaved_bit_array_idx] |= ((coords[which_coordinate] >> bit_idx_within_coordinates) & 1) << interleaved_bit_local_idx; } return result; } static void insert_box(ztree_node*& tree, ObjectIdentifier obj, zbox box) { if (!tree) { tree = new ztree_node(box); tree->objects_here.insert(obj); } else { if (tree->here.subsumes(box)) { if (box.num_low_bits_ignored == tree->here.num_low_bits_ignored) { tree->objects_here.insert(obj); } else { if (box.get_bit(tree->here.num_low_bits_ignored - 1)) insert_box(tree->child1, obj, box); else insert_box(tree->child0, obj, box); } } else { ztree_node *new_tree = new ztree_node(smallest_joint_parent(tree->here, box)); assert(new_tree->here.num_low_bits_ignored > tree->here.num_low_bits_ignored); assert(new_tree->here.subsumes(tree->here)); assert(new_tree->here.subsumes(box)); assert(box.subsumes(tree->here) || (tree->here.get_bit(new_tree->here.num_low_bits_ignored - 1) != box.get_bit(new_tree->here.num_low_bits_ignored - 1))); if (tree->here.get_bit(new_tree->here.num_low_bits_ignored - 1)) new_tree->child1 = tree; else new_tree->child0 = tree; tree = new_tree; insert_box(tree, obj, box); } } } static void delete_object(ztree_node*& tree, ObjectIdentifier obj, bounding_box const& bbox) { if (!tree) return; if (tree->here.get_bbox().overlaps(bbox)) { tree->objects_here.erase(obj); delete_object(tree->child0, obj, bbox); delete_object(tree->child1, obj, bbox); if (tree->objects_here.empty()) { if (tree->child0) { if (!tree->child1) { delete tree; tree = tree->child0; } } else { delete tree; tree = tree->child1; // which could be null } } } } static void delete_entire_tree(ztree_node*& tree) { if (!tree) return; delete_entire_tree(tree->child0); delete_entire_tree(tree->child1); delete tree; tree = nullptr; } void zget_objects_overlapping(ztree_node const* tree, unordered_set<ObjectIdentifier>& results, bounding_box const& bbox)const { if (tree && tree->here.get_bbox().overlaps(bbox)) { for (const ObjectIdentifier obj : tree->objects_here) { auto bbox_iter = bboxes_by_object.find(obj); assert(bbox_iter != bboxes_by_object.end()); if (bbox_iter->second.overlaps(bbox)) results.insert(obj); } zget_objects_overlapping(tree->child0, results, bbox); zget_objects_overlapping(tree->child1, results, bbox); } } unordered_map<ObjectIdentifier, bounding_box> bboxes_by_object; ztree_node* objects_tree; public: void insert(ObjectIdentifier id, bounding_box const& bbox) { bboxes_by_object.insert(std::make_pair(id, bbox)); Coordinate max_dim = bbox.size[0]; for (num_coordinates_type i = 1; i < num_dimensions; ++i) { if (bbox.size[i] > max_dim) max_dim = bbox.size[i]; } int exp = 0; while ((Coordinate(1) << exp) < max_dim) ++exp; int dimensions_we_can_single = 0; int dimensions_we_can_double = 0; const Coordinate base_box_size = safe_left_shift_one(exp); const Coordinate used_bits_mask = ~(base_box_size - 1); for (int i = num_dimensions - 1; i >= 0; --i) { if ((bbox.min[i] & used_bits_mask) + base_box_size >= bbox.min[i] + bbox.size[i]) ++dimensions_we_can_single; else break; } for (num_coordinates_type i = 0; i < num_dimensions - dimensions_we_can_single; ++i) { if (!(bbox.min[i] & base_box_size)) ++dimensions_we_can_double; else break; } #ifdef ZTREE_TESTING std::cerr << dimensions_we_can_single << "... " << dimensions_we_can_double << "...\n"; #endif for (int i = 0; i < (1 << ((num_dimensions - dimensions_we_can_single) - dimensions_we_can_double)); ++i) { std::array<Coordinate, num_dimensions> coords = bbox.min; for (num_coordinates_type j = dimensions_we_can_double; j < num_dimensions - dimensions_we_can_single; ++j) { if ((i << dimensions_we_can_double) & (1<<j)) coords[j] += base_box_size; } zbox zb = box_from_coords(coords, exp * num_dimensions + dimensions_we_can_double); if (zb.get_bbox().overlaps(bbox)) insert_box(objects_tree, id, zb); } } bool erase(ObjectIdentifier id) { auto bbox_iter = bboxes_by_object.find(id); if (bbox_iter == bboxes_by_object.end()) return false; delete_object(objects_tree, id, bbox_iter->second); bboxes_by_object.erase(bbox_iter); return true; } void get_objects_overlapping(unordered_set<ObjectIdentifier>& results, bounding_box const& bbox)const { zget_objects_overlapping(objects_tree, results, bbox); } ~bbox_collision_detector() { delete_entire_tree(objects_tree); } }; /* If there's one zbox in the tree [call it Z] tree = ztree_node { Z nullptr nullptr } Two zboxes that differ at bit B: child0 of a node with B ignored bits is the child whose Bth bit is 0. tree = ztree_node { Z1/Z2, with B ignored bits ptr to ztree_node { Z1 nullptr nullptr } ptr to ztree_node { Z2 nullptr nullptr } } */ #endif <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "condor_api.h" #include "status_types.h" #include "totals.h" extern AdTypes type; extern Mode mode; extern ppOption ppStyle; char * getPPStyleStr () { switch (ppStyle) { case PP_NOTSET: return "<Not set>"; case PP_GENERIC: return "Generic"; case PP_STARTD_NORMAL: return "Normal (Startd)"; case PP_SCHEDD_NORMAL: return "Normal (Schedd)"; case PP_SCHEDD_SUBMITTORS:return "Normal (Schedd)"; case PP_MASTER_NORMAL: return "Normal (Master)"; case PP_CKPT_SRVR_NORMAL:return"Normal (CkptSrvr)"; case PP_COLLECTOR_NORMAL:return"Normal (Collector)"; case PP_NEGOTIATOR_NORMAL: return "Normal (Negotiator)"; case PP_GRID_NORMAL: return "Grid"; case PP_STARTD_SERVER: return "Server"; case PP_STARTD_RUN: return "Run"; case PP_STARTD_COD: return "COD"; case PP_STARTD_STATE: return "State"; case PP_STORAGE_NORMAL: return "Storage"; case PP_GENERIC_NORMAL: return "Generic"; case PP_ANY_NORMAL: return "Any"; case PP_VERBOSE: return "Verbose"; case PP_XML: return "XML"; case PP_CUSTOM: return "Custom"; default: return "<Unknown!>"; } // should not reach here exit (1); } void setPPstyle (ppOption pps, int i, char *argv) { static int setBy = 0; static char *setArg = NULL; if (argv == NULL) { printf ("Set by arg %d (%-10s), PrettyPrint style = %s\n", setBy, setArg, getPPStyleStr()); return; } // if the style has already been set, and is trying to be reset by default // rules, override the default (i.e., don't make a change) if (setBy != 0 && i == 0) return; // If -long or -xml or -format are specified, do not reset to // "normal" style when followed by a flag such as -startd. if( ppStyle == PP_XML || ppStyle == PP_VERBOSE || ppStyle == PP_CUSTOM ) { if( pps != PP_XML && pps != PP_VERBOSE && pps != PP_CUSTOM ) { // ignore this style setting and keep our existing setting return; } } if ( (PP_XML == pps) || PP_VERBOSE == pps || (ppStyle <= pps || setBy == 0) ) { ppStyle = pps; setBy = i; setArg = argv; } else { fprintf (stderr, "Error: arg %d (%s) contradicts arg %d (%s)\n", i, argv, setBy, setArg); exit (1); } } char * getTypeStr () { switch (type) { case STARTD_AD: return "STARTD"; case SCHEDD_AD: return "SCHEDD"; case SUBMITTOR_AD: return "SUBMITTOR"; case MASTER_AD: return "MASTER"; case CKPT_SRVR_AD: return "CKPT_SRVR"; case GATEWAY_AD: return "GATEWAYS"; case COLLECTOR_AD: return "COLLECTOR"; case NEGOTIATOR_AD: return "NEGOTIATOR"; case GRID_AD: return "GRID"; case LICENSE_AD: return "LICENSE"; case STORAGE_AD: return "STORAGE"; case ANY_AD: return "ANY"; case GENERIC_AD: return "GENERIC"; default: return "<Unknown type!>"; } // should never get here exit (1); } void setType (char *dtype, int i, char *argv) { static int setBy = 0; static char *setArg = NULL; if (argv == NULL) { printf ("Set by arg %d (%-10s), Query type = %s\n", setBy, setArg, getTypeStr()); return; } // if the type has already been set, and is trying to be reset by default // rules, override the default (i.e., don't make a change) if (setBy != 0 && i == 0) return; if (setArg == NULL) { if (strcmp (dtype, "STARTD") == 0) { type = STARTD_AD; } else if (strcmp (dtype, "LICENSE") == 0) { type = LICENSE_AD; } else #ifdef HAVE_EXT_POSTGRESQL if (strcmp (dtype, "QUILL") == 0) { type = QUILL_AD; } else #endif /* HAVE_EXT_POSTGRESQL */ if (strcmp (dtype, "SCHEDD") == 0) { type = SCHEDD_AD; } else if (strcmp (dtype, "SUBMITTOR") == 0) { type = SUBMITTOR_AD; } else if (strcmp (dtype, "MASTER") == 0) { type = MASTER_AD; } else if (strcmp (dtype, "CKPT_SRVR") == 0) { type = CKPT_SRVR_AD; } else if (strcmp (dtype, "COLLECTOR") == 0) { type = COLLECTOR_AD; } else if (strcmp (dtype, "NEGOTIATOR") == 0) { type = NEGOTIATOR_AD; } else if (strcmp (dtype, "GATEWAYS") == 0) { type = GATEWAY_AD; } else if (strcmp(dtype, "GRID") == 0) { type = GRID_AD; } else if (strcmp (dtype, "STORAGE") == 0) { type = STORAGE_AD; } else if (strcmp(dtype, "GENERIC") == 0) { type = GENERIC_AD; } else if (strcmp(dtype, "ANY") == 0) { type = ANY_AD; } else if (strcmp(dtype, "HAD") == 0) { type = HAD_AD; } else { fprintf (stderr, "Error: Unknown entity type: %s\n", dtype); exit (1); } setBy = i; setArg = argv; } else { fprintf (stderr, "Error: Daemon type implied by arg %d (%s) contradicts arg %d (%s)\n", i, argv, setBy, setArg); } } char * getModeStr() { switch (mode) { case MODE_NOTSET: return "Not set"; case MODE_STARTD_NORMAL: return "Normal (Startd)"; case MODE_STARTD_AVAIL: return "Available (Startd)"; case MODE_STARTD_RUN: return "Run (Startd)"; case MODE_STARTD_COD: return "COD (Startd)"; #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: return "Normal (Quill)"; #endif /* HAVE_EXT_POSTGRESQL */ case MODE_SCHEDD_NORMAL: return "Normal (Schedd)"; case MODE_SCHEDD_SUBMITTORS: return "Submittors (Schedd)"; case MODE_MASTER_NORMAL: return "Normal (Master)"; case MODE_CKPT_SRVR_NORMAL: return "Normal (CkptSrvr)"; case MODE_COLLECTOR_NORMAL: return "Normal (Collector)"; case MODE_NEGOTIATOR_NORMAL: return "Normal (Negotiator)"; case MODE_GRID_NORMAL: return "Normal (Grid)"; case MODE_STORAGE_NORMAL: return "Normal (Storage)"; case MODE_GENERIC_NORMAL: return "Normal (Generic)"; case MODE_OTHER: return "Generic"; case MODE_ANY_NORMAL: return "Normal (Any)"; default: return "<Unknown!>"; } // should never get here exit (1); } void setMode (Mode mod, int i, char *argv) { static int setBy = 0; static char *setArg = NULL; if (argv == NULL) { printf("Set by arg %d (%-10s), Mode = %s\n",setBy,setArg,getModeStr()); return; } if (setBy == 0) { mode = mod; switch (mod) { case MODE_STARTD_NORMAL: setType ("STARTD", i, argv); setPPstyle (PP_STARTD_NORMAL, i, argv); break; case MODE_STARTD_AVAIL: setType ("STARTD", i, argv); setPPstyle (PP_STARTD_NORMAL, i, argv); break; case MODE_STARTD_RUN: setType ("STARTD", i, argv); setPPstyle (PP_STARTD_RUN, i, argv); break; case MODE_STARTD_COD: setType ("STARTD", i, argv); setPPstyle (PP_STARTD_COD, i, argv); break; case MODE_SCHEDD_NORMAL: setType ("SCHEDD", i, argv); setPPstyle (PP_SCHEDD_NORMAL, i, argv); break; #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: setType ("QUILL", i, argv); setPPstyle (PP_QUILL_NORMAL, i, argv); break; #endif /* HAVE_EXT_POSTGRESQL */ case MODE_LICENSE_NORMAL: setType ("LICENSE", i, argv); setPPstyle (PP_VERBOSE, i, argv); break; case MODE_SCHEDD_SUBMITTORS: setType ("SUBMITTOR", i, argv); setPPstyle (PP_SCHEDD_SUBMITTORS, i, argv); break; case MODE_MASTER_NORMAL: setType ("MASTER", i, argv); setPPstyle (PP_MASTER_NORMAL, i, argv); break; case MODE_COLLECTOR_NORMAL: setType ("COLLECTOR", i, argv); setPPstyle (PP_COLLECTOR_NORMAL, i, argv); break; case MODE_NEGOTIATOR_NORMAL: setType ("NEGOTIATOR", i, argv); setPPstyle (PP_NEGOTIATOR_NORMAL, i, argv); break; case MODE_CKPT_SRVR_NORMAL: setType ("CKPT_SRVR", i, argv); setPPstyle (PP_CKPT_SRVR_NORMAL, i, argv); break; case MODE_STORAGE_NORMAL: setType ("STORAGE", i, argv); setPPstyle (PP_STORAGE_NORMAL, i, argv); break; case MODE_GRID_NORMAL: setType ("GRID", i, argv); setPPstyle (PP_GRID_NORMAL, i, argv); break; case MODE_GENERIC_NORMAL: setType ("GENERIC", i, argv); setPPstyle (PP_GENERIC_NORMAL, i, argv); break; case MODE_ANY_NORMAL: setType ("ANY", i, argv); setPPstyle (PP_ANY_NORMAL, i, argv); break; case MODE_OTHER: setType ("GENERIC", i, argv); setPPstyle (PP_GENERIC, i, argv); break; case MODE_HAD_NORMAL: setType ("HAD", i, argv); setPPstyle (PP_GENERIC, i, argv); break; default: fprintf (stderr, "Error: Illegal mode %d\n", mode); break; } setBy = i; setArg = argv; } else { fprintf (stderr, "Error: Arg %d (%s) contradicts arg %d (%s)\n", i, argv, setBy, setArg); exit (1); } } <commit_msg>Avoid silly error message from condor_status. condor_status -any -any Error: Arg 2 (-any) contradicts arg 1 (-any)<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "condor_api.h" #include "status_types.h" #include "totals.h" extern AdTypes type; extern Mode mode; extern ppOption ppStyle; char * getPPStyleStr () { switch (ppStyle) { case PP_NOTSET: return "<Not set>"; case PP_GENERIC: return "Generic"; case PP_STARTD_NORMAL: return "Normal (Startd)"; case PP_SCHEDD_NORMAL: return "Normal (Schedd)"; case PP_SCHEDD_SUBMITTORS:return "Normal (Schedd)"; case PP_MASTER_NORMAL: return "Normal (Master)"; case PP_CKPT_SRVR_NORMAL:return"Normal (CkptSrvr)"; case PP_COLLECTOR_NORMAL:return"Normal (Collector)"; case PP_NEGOTIATOR_NORMAL: return "Normal (Negotiator)"; case PP_GRID_NORMAL: return "Grid"; case PP_STARTD_SERVER: return "Server"; case PP_STARTD_RUN: return "Run"; case PP_STARTD_COD: return "COD"; case PP_STARTD_STATE: return "State"; case PP_STORAGE_NORMAL: return "Storage"; case PP_GENERIC_NORMAL: return "Generic"; case PP_ANY_NORMAL: return "Any"; case PP_VERBOSE: return "Verbose"; case PP_XML: return "XML"; case PP_CUSTOM: return "Custom"; default: return "<Unknown!>"; } // should not reach here exit (1); } void setPPstyle (ppOption pps, int i, char *argv) { static int setBy = 0; static char *setArg = NULL; if (argv == NULL) { printf ("Set by arg %d (%-10s), PrettyPrint style = %s\n", setBy, setArg, getPPStyleStr()); return; } // if the style has already been set, and is trying to be reset by default // rules, override the default (i.e., don't make a change) if (setBy != 0 && i == 0) return; // If -long or -xml or -format are specified, do not reset to // "normal" style when followed by a flag such as -startd. if( ppStyle == PP_XML || ppStyle == PP_VERBOSE || ppStyle == PP_CUSTOM ) { if( pps != PP_XML && pps != PP_VERBOSE && pps != PP_CUSTOM ) { // ignore this style setting and keep our existing setting return; } } if ( (PP_XML == pps) || PP_VERBOSE == pps || (ppStyle <= pps || setBy == 0) ) { ppStyle = pps; setBy = i; setArg = argv; } else { fprintf (stderr, "Error: arg %d (%s) contradicts arg %d (%s)\n", i, argv, setBy, setArg); exit (1); } } char * getTypeStr () { switch (type) { case STARTD_AD: return "STARTD"; case SCHEDD_AD: return "SCHEDD"; case SUBMITTOR_AD: return "SUBMITTOR"; case MASTER_AD: return "MASTER"; case CKPT_SRVR_AD: return "CKPT_SRVR"; case GATEWAY_AD: return "GATEWAYS"; case COLLECTOR_AD: return "COLLECTOR"; case NEGOTIATOR_AD: return "NEGOTIATOR"; case GRID_AD: return "GRID"; case LICENSE_AD: return "LICENSE"; case STORAGE_AD: return "STORAGE"; case ANY_AD: return "ANY"; case GENERIC_AD: return "GENERIC"; default: return "<Unknown type!>"; } // should never get here exit (1); } void setType (char *dtype, int i, char *argv) { static int setBy = 0; static char *setArg = NULL; if (argv == NULL) { printf ("Set by arg %d (%-10s), Query type = %s\n", setBy, setArg, getTypeStr()); return; } // if the type has already been set, and is trying to be reset by default // rules, override the default (i.e., don't make a change) if (setBy != 0 && i == 0) return; if (setArg == NULL) { if (strcmp (dtype, "STARTD") == 0) { type = STARTD_AD; } else if (strcmp (dtype, "LICENSE") == 0) { type = LICENSE_AD; } else #ifdef HAVE_EXT_POSTGRESQL if (strcmp (dtype, "QUILL") == 0) { type = QUILL_AD; } else #endif /* HAVE_EXT_POSTGRESQL */ if (strcmp (dtype, "SCHEDD") == 0) { type = SCHEDD_AD; } else if (strcmp (dtype, "SUBMITTOR") == 0) { type = SUBMITTOR_AD; } else if (strcmp (dtype, "MASTER") == 0) { type = MASTER_AD; } else if (strcmp (dtype, "CKPT_SRVR") == 0) { type = CKPT_SRVR_AD; } else if (strcmp (dtype, "COLLECTOR") == 0) { type = COLLECTOR_AD; } else if (strcmp (dtype, "NEGOTIATOR") == 0) { type = NEGOTIATOR_AD; } else if (strcmp (dtype, "GATEWAYS") == 0) { type = GATEWAY_AD; } else if (strcmp(dtype, "GRID") == 0) { type = GRID_AD; } else if (strcmp (dtype, "STORAGE") == 0) { type = STORAGE_AD; } else if (strcmp(dtype, "GENERIC") == 0) { type = GENERIC_AD; } else if (strcmp(dtype, "ANY") == 0) { type = ANY_AD; } else if (strcmp(dtype, "HAD") == 0) { type = HAD_AD; } else { fprintf (stderr, "Error: Unknown entity type: %s\n", dtype); exit (1); } setBy = i; setArg = argv; } else { fprintf (stderr, "Error: Daemon type implied by arg %d (%s) contradicts arg %d (%s)\n", i, argv, setBy, setArg); } } char * getModeStr() { switch (mode) { case MODE_NOTSET: return "Not set"; case MODE_STARTD_NORMAL: return "Normal (Startd)"; case MODE_STARTD_AVAIL: return "Available (Startd)"; case MODE_STARTD_RUN: return "Run (Startd)"; case MODE_STARTD_COD: return "COD (Startd)"; #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: return "Normal (Quill)"; #endif /* HAVE_EXT_POSTGRESQL */ case MODE_SCHEDD_NORMAL: return "Normal (Schedd)"; case MODE_SCHEDD_SUBMITTORS: return "Submittors (Schedd)"; case MODE_MASTER_NORMAL: return "Normal (Master)"; case MODE_CKPT_SRVR_NORMAL: return "Normal (CkptSrvr)"; case MODE_COLLECTOR_NORMAL: return "Normal (Collector)"; case MODE_NEGOTIATOR_NORMAL: return "Normal (Negotiator)"; case MODE_GRID_NORMAL: return "Normal (Grid)"; case MODE_STORAGE_NORMAL: return "Normal (Storage)"; case MODE_GENERIC_NORMAL: return "Normal (Generic)"; case MODE_OTHER: return "Generic"; case MODE_ANY_NORMAL: return "Normal (Any)"; default: return "<Unknown!>"; } // should never get here exit (1); } void setMode (Mode mod, int i, char *argv) { static int setBy = 0; static char *setArg = NULL; if (argv == NULL) { printf("Set by arg %d (%-10s), Mode = %s\n",setBy,setArg,getModeStr()); return; } if (setBy == 0) { mode = mod; switch (mod) { case MODE_STARTD_NORMAL: setType ("STARTD", i, argv); setPPstyle (PP_STARTD_NORMAL, i, argv); break; case MODE_STARTD_AVAIL: setType ("STARTD", i, argv); setPPstyle (PP_STARTD_NORMAL, i, argv); break; case MODE_STARTD_RUN: setType ("STARTD", i, argv); setPPstyle (PP_STARTD_RUN, i, argv); break; case MODE_STARTD_COD: setType ("STARTD", i, argv); setPPstyle (PP_STARTD_COD, i, argv); break; case MODE_SCHEDD_NORMAL: setType ("SCHEDD", i, argv); setPPstyle (PP_SCHEDD_NORMAL, i, argv); break; #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: setType ("QUILL", i, argv); setPPstyle (PP_QUILL_NORMAL, i, argv); break; #endif /* HAVE_EXT_POSTGRESQL */ case MODE_LICENSE_NORMAL: setType ("LICENSE", i, argv); setPPstyle (PP_VERBOSE, i, argv); break; case MODE_SCHEDD_SUBMITTORS: setType ("SUBMITTOR", i, argv); setPPstyle (PP_SCHEDD_SUBMITTORS, i, argv); break; case MODE_MASTER_NORMAL: setType ("MASTER", i, argv); setPPstyle (PP_MASTER_NORMAL, i, argv); break; case MODE_COLLECTOR_NORMAL: setType ("COLLECTOR", i, argv); setPPstyle (PP_COLLECTOR_NORMAL, i, argv); break; case MODE_NEGOTIATOR_NORMAL: setType ("NEGOTIATOR", i, argv); setPPstyle (PP_NEGOTIATOR_NORMAL, i, argv); break; case MODE_CKPT_SRVR_NORMAL: setType ("CKPT_SRVR", i, argv); setPPstyle (PP_CKPT_SRVR_NORMAL, i, argv); break; case MODE_STORAGE_NORMAL: setType ("STORAGE", i, argv); setPPstyle (PP_STORAGE_NORMAL, i, argv); break; case MODE_GRID_NORMAL: setType ("GRID", i, argv); setPPstyle (PP_GRID_NORMAL, i, argv); break; case MODE_GENERIC_NORMAL: setType ("GENERIC", i, argv); setPPstyle (PP_GENERIC_NORMAL, i, argv); break; case MODE_ANY_NORMAL: setType ("ANY", i, argv); setPPstyle (PP_ANY_NORMAL, i, argv); break; case MODE_OTHER: setType ("GENERIC", i, argv); setPPstyle (PP_GENERIC, i, argv); break; case MODE_HAD_NORMAL: setType ("HAD", i, argv); setPPstyle (PP_GENERIC, i, argv); break; default: fprintf (stderr, "Error: Illegal mode %d\n", mode); break; } setBy = i; setArg = argv; } else { if( strcmp(argv,setArg)!=0 ) { fprintf (stderr, "Error: Arg %d (%s) contradicts arg %d (%s)\n", i, argv, setBy, setArg); exit (1); } } } <|endoftext|>
<commit_before>#include <coreutils/log.h> #include "petsciiconsole.h" #include <array> #include <algorithm> LOGSPACE("utils"); namespace bbs { using namespace std; /** PETSCII->ASCII 0x20 -> 0xFF **/ static int petsciiTable[] = { 0x0020,0x0021,0x0022,0x0023,0x0024,0x0025,0x0026,0x0027, 0x0028,0x0029,0x002A,0x002B,0x002C,0x002D,0x002E,0x002F,0x0030,0x0031, 0x0032,0x0033,0x0034,0x0035,0x0036,0x0037,0x0038,0x0039,0x003A,0x003B, 0x003C,0x003D,0x003E,0x003F,0x0040,0x0061,0x0062,0x0063,0x0064,0x0065, 0x0066,0x0067,0x0068,0x0069,0x006A,0x006B,0x006C,0x006D,0x006E,0x006F, 0x0070,0x0071,0x0072,0x0073,0x0074,0x0075,0x0076,0x0077,0x0078,0x0079, 0x007A,0x005B,0x00A3,0x005D,0x2191,0x2190,0x2500,0x0041,0x0042,0x0043, 0x0044,0x0045,0x0046,0x0047,0x0048,0x0049,0x004A,0x004B,0x004C,0x004D, 0x004E,0x004F,0x0050,0x0051,0x0052,0x0053,0x0054,0x0055,0x0056,0x0057, 0x0058,0x0059,0x005A,0x254B,0xF12E,0x2503,0x2592,0xF139,0x0000,0x0000, 0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000, 0x0000,0x000A,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0, 0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x00A0, 0x258C,0x2584,0x2594,0x2581,0x258F,0x2592,0x2595,0xF12F,0xF13A,0xF130, 0x251C,0xF134,0x2514,0x2510,0x2582,0x250C,0x2534,0x252C,0x2524,0x258E, 0x258D,0xF131,0xF132,0xF133,0x2583,0x2713,0xF135,0xF136,0x2518,0xF137, 0xF138,0x2501,0x0041,0x0042,0x0043,0x0044,0x0045,0x0046,0x0047,0x0048, 0x0049,0x004A,0x004B,0x004C,0x004D,0x004E,0x004F,0x0050,0x0051,0x0052, 0x0053,0x0054,0x0055,0x0056,0x0057,0x0058,0x0059,0x005A,0x253C,0xF12E, 0x2502,0x2592,0xF139,0x00A0,0x258C,0x2584,0x2594,0x2581,0x258F,0x2592, 0x2595,0xF12F,0xF13A,0xF130,0x251C,0xF134,0x2514,0x2510,0x2582,0x250C, 0x2534,0x252C,0x2524,0x258E,0x258D,0xF131,0xF132,0xF133,0x2583,0x2713, 0xF135,0xF136,0x2518,0xF137,0x2592 }; static vector<uint8_t> petsciiColors = { 5, 28, 30, 31, 129, 144, 149, 150, 151, 152, 153, 154, 155, 156, 158, 159 }; PetsciiConsole::PetsciiConsole(Terminal &terminal) : Console(terminal) { resize(40, 25); impl_clear(); impl_color(fgColor, bgColor); impl_gotoxy(0,0); int i = 0x20; for(auto c : petsciiTable) { unicodeToPetscii[c] = i; i++; } unicodeToPetscii[L'{'] = 0xb3; unicodeToPetscii[L'}'] = 0xab; unicodeToPetscii[L'_'] = 0xa4; } void PetsciiConsole::putChar(Char c) { if(curX == 39) { outBuffer.push_back(DEL); outBuffer.push_back(c & 0xff); outBuffer.push_back(LEFT); outBuffer.push_back(INS); // NOTE: We don't handle the case where char 38 and 39 have different colors! outBuffer.push_back(grid[curY*width+38].c & 0xff); } else { outBuffer.push_back(c & 0xff); curX++; if(curX >= width) { curX -= width; curY++; } } } void PetsciiConsole::impl_translate(Char &c) { //Char x = c; c = unicodeToPetscii[c]; if(c == 0) c = '?'; /* auto *pc = std::find(begin(petsciiTable), end(petsciiTable), c); if(pc != end(petsciiTable)) { //if(c > 0x800) LOGD("Unicode %04x to petcii %02x", c, (pc - petsciiTable + 0x20)); c = (pc - petsciiTable + 0x20); } else c = '?'; //LOGD("Translated %c (%02x) to %c (%02x)", x, x, c, c);*/ } void PetsciiConsole::impl_color(int fg, int bg) { if(bg >= 0 && bg != BLACK) { outBuffer.push_back(RVS_ON); outBuffer.push_back(petsciiColors[bg]); } else if(fg >= 0) { outBuffer.push_back(RVS_OFF); outBuffer.push_back(petsciiColors[fg]); } } void PetsciiConsole::impl_clear() { outBuffer.push_back(147); } void PetsciiConsole::impl_gotoxy(int x, int y) { //LOGD("Petscii GOTOXY from %d,%d to %d,%d", curX, curY, x, y); if(curX - x > x) { if(curY == height-1) { outBuffer.push_back(UP); } else curY++; outBuffer.push_back(SHIFT_RETURN); if(bgColor != BLACK) { outBuffer.push_back(RVS_ON); //curFg = curBg; //curBg = BLACK; } curX=0; } while(y > curY) { outBuffer.push_back(DOWN); curY++; } while(y < curY) { outBuffer.push_back(UP); curY--; } while(x > curX) { outBuffer.push_back(RIGHT); curX++; } while(x < curX) { outBuffer.push_back(LEFT); curX--; } } int PetsciiConsole::impl_handlekey() { auto k = inBuffer.front(); inBuffer.pop(); switch(k) { case 13 : return KEY_ENTER; case DEL : return KEY_BACKSPACE; case DOWN : return KEY_DOWN; case UP : return KEY_UP; case LEFT : return KEY_LEFT; case RIGHT : return KEY_RIGHT; case HOME: return KEY_HOME; case CLEAR: return KEY_END; case STOP: return KEY_ESCAPE; default: if(k >= F1 && k <= F8) { k -= F1; return KEY_F1 + (k * 2 % 8) + (k / 4); // A little bit of trickery to convert :) } } if(k >= 0x20 && (k <= 0x7f || k >= 0xa0)) { auto k2 = k; k = petsciiTable[k-0x20]; LOGD("%02x became %02x (%c)", k2, k, k); return k; } return KEY_UNKNOWN; } bool PetsciiConsole::impl_scroll_screen(int dy) { //const auto s = dy > 0 ? utils::format("\x1b[%dS",dy) : utils::format("\x1b[%dT", -dy); //outBuffer.insert(outBuffer.end(), s.begin(), s.end()); auto steps = dy + height - curY -1; while(steps--) outBuffer.push_back(DOWN); steps = height - curY - 1; while(steps--) outBuffer.push_back(UP); return true; } } <commit_msg>Added some more unicode to petscii chars<commit_after>#include <coreutils/log.h> #include "petsciiconsole.h" #include <array> #include <algorithm> LOGSPACE("utils"); namespace bbs { using namespace std; /** PETSCII->ASCII 0x20 -> 0xFF **/ static int petsciiTable[] = { 0x0020,0x0021,0x0022,0x0023,0x0024,0x0025,0x0026,0x0027, 0x0028,0x0029,0x002A,0x002B,0x002C,0x002D,0x002E,0x002F,0x0030,0x0031, 0x0032,0x0033,0x0034,0x0035,0x0036,0x0037,0x0038,0x0039,0x003A,0x003B, 0x003C,0x003D,0x003E,0x003F,0x0040,0x0061,0x0062,0x0063,0x0064,0x0065, 0x0066,0x0067,0x0068,0x0069,0x006A,0x006B,0x006C,0x006D,0x006E,0x006F, 0x0070,0x0071,0x0072,0x0073,0x0074,0x0075,0x0076,0x0077,0x0078,0x0079, 0x007A,0x005B,0x00A3,0x005D,0x2191,0x2190,0x2500,0x0041,0x0042,0x0043, 0x0044,0x0045,0x0046,0x0047,0x0048,0x0049,0x004A,0x004B,0x004C,0x004D, 0x004E,0x004F,0x0050,0x0051,0x0052,0x0053,0x0054,0x0055,0x0056,0x0057, 0x0058,0x0059,0x005A,0x254B,0xF12E,0x2503,0x2592,0xF139,0x0000,0x0000, 0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000, 0x0000,0x000A,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0, 0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x00A0, 0x258C,0x2584,0x2594,0x2581,0x258F,0x2592,0x2595,0xF12F,0xF13A,0xF130, 0x251C,0xF134,0x2514,0x2510,0x2582,0x250C,0x2534,0x252C,0x2524,0x258E, 0x258D,0xF131,0xF132,0xF133,0x2583,0x2713,0xF135,0xF136,0x2518,0xF137, 0xF138,0x2501,0x0041,0x0042,0x0043,0x0044,0x0045,0x0046,0x0047,0x0048, 0x0049,0x004A,0x004B,0x004C,0x004D,0x004E,0x004F,0x0050,0x0051,0x0052, 0x0053,0x0054,0x0055,0x0056,0x0057,0x0058,0x0059,0x005A,0x253C,0xF12E, 0x2502,0x2592,0xF139,0x00A0,0x258C,0x2584,0x2594,0x2581,0x258F,0x2592, 0x2595,0xF12F,0xF13A,0xF130,0x251C,0xF134,0x2514,0x2510,0x2582,0x250C, 0x2534,0x252C,0x2524,0x258E,0x258D,0xF131,0xF132,0xF133,0x2583,0x2713, 0xF135,0xF136,0x2518,0xF137,0x2592 }; static vector<uint8_t> petsciiColors = { 5, 28, 30, 31, 129, 144, 149, 150, 151, 152, 153, 154, 155, 156, 158, 159 }; PetsciiConsole::PetsciiConsole(Terminal &terminal) : Console(terminal) { resize(40, 25); impl_clear(); impl_color(fgColor, bgColor); impl_gotoxy(0,0); int i = 0x20; for(auto c : petsciiTable) { unicodeToPetscii[c] = i; i++; } wstring s = L"╋┃━┏┓┗┛{}_"; vector<uint8_t> v { 0xdd,0xdb,0x60,0xb0,0xae,0xad,0xbd,0xb3,0xab,0xa4 }; for(int i=0; i<v.size(); i++) { unicodeToPetscii[s[i]] = v[i]; } } void PetsciiConsole::putChar(Char c) { if(curX == 39) { outBuffer.push_back(DEL); outBuffer.push_back(c & 0xff); outBuffer.push_back(LEFT); outBuffer.push_back(INS); // NOTE: We don't handle the case where char 38 and 39 have different colors! outBuffer.push_back(grid[curY*width+38].c & 0xff); } else { outBuffer.push_back(c & 0xff); curX++; if(curX >= width) { curX -= width; curY++; } } } void PetsciiConsole::impl_translate(Char &c) { //Char x = c; c = unicodeToPetscii[c]; if(c == 0) c = '?'; /* auto *pc = std::find(begin(petsciiTable), end(petsciiTable), c); if(pc != end(petsciiTable)) { //if(c > 0x800) LOGD("Unicode %04x to petcii %02x", c, (pc - petsciiTable + 0x20)); c = (pc - petsciiTable + 0x20); } else c = '?'; //LOGD("Translated %c (%02x) to %c (%02x)", x, x, c, c);*/ } void PetsciiConsole::impl_color(int fg, int bg) { if(bg >= 0 && bg != BLACK) { outBuffer.push_back(RVS_ON); outBuffer.push_back(petsciiColors[bg]); } else if(fg >= 0) { outBuffer.push_back(RVS_OFF); outBuffer.push_back(petsciiColors[fg]); } } void PetsciiConsole::impl_clear() { outBuffer.push_back(147); } void PetsciiConsole::impl_gotoxy(int x, int y) { //LOGD("Petscii GOTOXY from %d,%d to %d,%d", curX, curY, x, y); if(curX - x > x) { if(curY == height-1) { outBuffer.push_back(UP); } else curY++; outBuffer.push_back(SHIFT_RETURN); if(bgColor != BLACK) { outBuffer.push_back(RVS_ON); //curFg = curBg; //curBg = BLACK; } curX=0; } while(y > curY) { outBuffer.push_back(DOWN); curY++; } while(y < curY) { outBuffer.push_back(UP); curY--; } while(x > curX) { outBuffer.push_back(RIGHT); curX++; } while(x < curX) { outBuffer.push_back(LEFT); curX--; } } int PetsciiConsole::impl_handlekey() { auto k = inBuffer.front(); inBuffer.pop(); switch(k) { case 13 : return KEY_ENTER; case DEL : return KEY_BACKSPACE; case DOWN : return KEY_DOWN; case UP : return KEY_UP; case LEFT : return KEY_LEFT; case RIGHT : return KEY_RIGHT; case HOME: return KEY_HOME; case CLEAR: return KEY_END; case STOP: return KEY_ESCAPE; default: if(k >= F1 && k <= F8) { k -= F1; return KEY_F1 + (k * 2 % 8) + (k / 4); // A little bit of trickery to convert :) } } if(k >= 0x20 && (k <= 0x7f || k >= 0xa0)) { auto k2 = k; k = petsciiTable[k-0x20]; LOGD("%02x became %02x (%c)", k2, k, k); return k; } return KEY_UNKNOWN; } bool PetsciiConsole::impl_scroll_screen(int dy) { //const auto s = dy > 0 ? utils::format("\x1b[%dS",dy) : utils::format("\x1b[%dT", -dy); //outBuffer.insert(outBuffer.end(), s.begin(), s.end()); auto steps = dy + height - curY -1; while(steps--) outBuffer.push_back(DOWN); steps = height - curY - 1; while(steps--) outBuffer.push_back(UP); return true; } } <|endoftext|>
<commit_before>#include "process.hpp" #include <cstring> #include <TlHelp32.h> #include <stdexcept> Process::Data::Data(): id(0), handle(NULL) {} namespace { // Simple HANDLE wrapper to close it automatically from the destructor. class Handle { public: Handle() : handle(INVALID_HANDLE_VALUE) { } ~Handle() { close(); } void close() { if (handle != INVALID_HANDLE_VALUE) ::CloseHandle(handle); } HANDLE detach() { HANDLE old_handle = handle; handle = INVALID_HANDLE_VALUE; return old_handle; } operator HANDLE() const { return handle; } HANDLE* operator&() { return &handle; } private: HANDLE handle; }; //Based on the discussion thread: https://www.reddit.com/r/cpp/comments/3vpjqg/a_new_platform_independent_process_library_for_c11/cxq1wsj std::mutex create_process_mutex; } //Based on the example at https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx. Process::id_type Process::open(const std::string &command, const std::string &path) { if(open_stdin) stdin_fd=std::unique_ptr<fd_type>(new fd_type(NULL)); if(read_stdout) stdout_fd=std::unique_ptr<fd_type>(new fd_type(NULL)); if(read_stderr) stderr_fd=std::unique_ptr<fd_type>(new fd_type(NULL)); Handle stdin_rd_p; Handle stdin_wr_p; Handle stdout_rd_p; Handle stdout_wr_p; Handle stderr_rd_p; Handle stderr_wr_p; SECURITY_ATTRIBUTES security_attributes; security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES); security_attributes.bInheritHandle = TRUE; security_attributes.lpSecurityDescriptor = NULL; std::lock_guard<std::mutex> lock(create_process_mutex); if(stdin_fd) { if (!CreatePipe(&stdin_rd_p, &stdin_wr_p, &security_attributes, 0) || !SetHandleInformation(stdin_wr_p, HANDLE_FLAG_INHERIT, 0)) return 0; } if(stdout_fd) { if (!CreatePipe(&stdout_rd_p, &stdout_wr_p, &security_attributes, 0) || !SetHandleInformation(stdout_rd_p, HANDLE_FLAG_INHERIT, 0)) { return 0; } } if(stderr_fd) { if (!CreatePipe(&stderr_rd_p, &stderr_wr_p, &security_attributes, 0) || !SetHandleInformation(stderr_rd_p, HANDLE_FLAG_INHERIT, 0)) { return 0; } } PROCESS_INFORMATION process_info; STARTUPINFO startup_info; ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION)); ZeroMemory(&startup_info, sizeof(STARTUPINFO)); startup_info.cb = sizeof(STARTUPINFO); startup_info.hStdInput = stdin_rd_p; startup_info.hStdOutput = stdout_wr_p; startup_info.hStdError = stderr_wr_p; if(stdin_fd || stdout_fd || stderr_fd) startup_info.dwFlags |= STARTF_USESTDHANDLES; char* path_cstr; if(path=="") path_cstr=NULL; else { path_cstr=new char[path.size()+1]; std::strcpy(path_cstr, path.c_str()); } char* command_cstr; #ifdef MSYS_PROCESS_USE_SH size_t pos=0; std::string sh_command=command; while((pos=sh_command.find('\\', pos))!=std::string::npos) { sh_command.replace(pos, 1, "\\\\\\\\"); pos+=4; } pos=0; while((pos=sh_command.find('\"', pos))!=std::string::npos) { sh_command.replace(pos, 1, "\\\""); pos+=2; } sh_command.insert(0, "sh -c \""); sh_command+="\""; command_cstr=new char[sh_command.size()+1]; std::strcpy(command_cstr, sh_command.c_str()); #else command_cstr=new char[command.size()+1]; std::strcpy(command_cstr, command.c_str()); #endif BOOL bSuccess = CreateProcess(NULL, command_cstr, NULL, NULL, TRUE, 0, NULL, path_cstr, &startup_info, &process_info); delete[] path_cstr; delete[] command_cstr; if(!bSuccess) { CloseHandle(process_info.hProcess); CloseHandle(process_info.hThread); return 0; } else { CloseHandle(process_info.hThread); } if(stdin_fd) *stdin_fd=stdin_wr_p.detach(); if(stdout_fd) *stdout_fd=stdout_rd_p.detach(); if(stderr_fd) *stderr_fd=stderr_rd_p.detach(); closed=false; data.id=process_info.dwProcessId; data.handle=process_info.hProcess; return process_info.dwProcessId; } void Process::async_read() { if(data.id==0) return; if(stdout_fd) { stdout_thread=std::thread([this](){ DWORD n; std::unique_ptr<char[]> buffer(new char[buffer_size]); for (;;) { BOOL bSuccess = ReadFile(*stdout_fd, static_cast<CHAR*>(buffer.get()), static_cast<DWORD>(buffer_size), &n, NULL); if(!bSuccess || n == 0) break; read_stdout(buffer.get(), static_cast<size_t>(n)); } }); } if(stderr_fd) { stderr_thread=std::thread([this](){ DWORD n; std::unique_ptr<char[]> buffer(new char[buffer_size]); for (;;) { BOOL bSuccess = ReadFile(*stderr_fd, static_cast<CHAR*>(buffer.get()), static_cast<DWORD>(buffer_size), &n, NULL); if(!bSuccess || n == 0) break; read_stderr(buffer.get(), static_cast<size_t>(n)); } }); } } int Process::get_exit_status() { if(data.id==0) return -1; DWORD exit_status; WaitForSingleObject(data.handle, INFINITE); if(!GetExitCodeProcess(data.handle, &exit_status)) exit_status=-1; { std::lock_guard<std::mutex> lock(close_mutex); CloseHandle(data.handle); closed=true; } close_fds(); return static_cast<int>(exit_status); } void Process::close_fds() { if(stdout_thread.joinable()) stdout_thread.join(); if(stderr_thread.joinable()) stderr_thread.join(); if(stdin_fd) close_stdin(); if(stdout_fd) { if(*stdout_fd!=NULL) CloseHandle(*stdout_fd); stdout_fd.reset(); } if(stderr_fd) { if(*stderr_fd!=NULL) CloseHandle(*stderr_fd); stderr_fd.reset(); } } bool Process::write(const char *bytes, size_t n) { if(!open_stdin) throw std::invalid_argument("Can't write to an unopened stdin pipe. Please set open_stdin=true when constructing the process."); std::lock_guard<std::mutex> lock(stdin_mutex); if(stdin_fd) { DWORD written; BOOL bSuccess=WriteFile(*stdin_fd, bytes, static_cast<DWORD>(n), &written, NULL); if(!bSuccess || written==0) { return false; } else { return true; } } return false; } void Process::close_stdin() { std::lock_guard<std::mutex> lock(stdin_mutex); if(stdin_fd) { if(*stdin_fd!=NULL) CloseHandle(*stdin_fd); stdin_fd.reset(); } } //Based on http://stackoverflow.com/a/1173396 void Process::kill(bool force) { std::lock_guard<std::mutex> lock(close_mutex); if(data.id>0 && !closed) { HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(snapshot) { PROCESSENTRY32 process; ZeroMemory(&process, sizeof(process)); process.dwSize = sizeof(process); if(Process32First(snapshot, &process)) { do { if(process.th32ParentProcessID==data.id) { HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID); if(process_handle) TerminateProcess(process_handle, 2); } } while (Process32Next(snapshot, &process)); } } TerminateProcess(data.handle, 2); } } //Based on http://stackoverflow.com/a/1173396 void Process::kill(id_type id, bool force) { if(id==0) return; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(snapshot) { PROCESSENTRY32 process; ZeroMemory(&process, sizeof(process)); process.dwSize = sizeof(process); if(Process32First(snapshot, &process)) { do { if(process.th32ParentProcessID==id) { HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID); if(process_handle) TerminateProcess(process_handle, 2); } } while (Process32Next(snapshot, &process)); } } HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id); if(process_handle) TerminateProcess(process_handle, 2); } <commit_msg>process_win: minor indentation cleanup<commit_after>#include "process.hpp" #include <cstring> #include <TlHelp32.h> #include <stdexcept> Process::Data::Data(): id(0), handle(NULL) {} namespace { // Simple HANDLE wrapper to close it automatically from the destructor. class Handle { public: Handle() : handle(INVALID_HANDLE_VALUE) { } ~Handle() { close(); } void close() { if (handle != INVALID_HANDLE_VALUE) ::CloseHandle(handle); } HANDLE detach() { HANDLE old_handle = handle; handle = INVALID_HANDLE_VALUE; return old_handle; } operator HANDLE() const { return handle; } HANDLE* operator&() { return &handle; } private: HANDLE handle; }; //Based on the discussion thread: https://www.reddit.com/r/cpp/comments/3vpjqg/a_new_platform_independent_process_library_for_c11/cxq1wsj std::mutex create_process_mutex; } //Based on the example at https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx. Process::id_type Process::open(const std::string &command, const std::string &path) { if(open_stdin) stdin_fd=std::unique_ptr<fd_type>(new fd_type(NULL)); if(read_stdout) stdout_fd=std::unique_ptr<fd_type>(new fd_type(NULL)); if(read_stderr) stderr_fd=std::unique_ptr<fd_type>(new fd_type(NULL)); Handle stdin_rd_p; Handle stdin_wr_p; Handle stdout_rd_p; Handle stdout_wr_p; Handle stderr_rd_p; Handle stderr_wr_p; SECURITY_ATTRIBUTES security_attributes; security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES); security_attributes.bInheritHandle = TRUE; security_attributes.lpSecurityDescriptor = NULL; std::lock_guard<std::mutex> lock(create_process_mutex); if(stdin_fd) { if (!CreatePipe(&stdin_rd_p, &stdin_wr_p, &security_attributes, 0) || !SetHandleInformation(stdin_wr_p, HANDLE_FLAG_INHERIT, 0)) return 0; } if(stdout_fd) { if (!CreatePipe(&stdout_rd_p, &stdout_wr_p, &security_attributes, 0) || !SetHandleInformation(stdout_rd_p, HANDLE_FLAG_INHERIT, 0)) { return 0; } } if(stderr_fd) { if (!CreatePipe(&stderr_rd_p, &stderr_wr_p, &security_attributes, 0) || !SetHandleInformation(stderr_rd_p, HANDLE_FLAG_INHERIT, 0)) { return 0; } } PROCESS_INFORMATION process_info; STARTUPINFO startup_info; ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION)); ZeroMemory(&startup_info, sizeof(STARTUPINFO)); startup_info.cb = sizeof(STARTUPINFO); startup_info.hStdInput = stdin_rd_p; startup_info.hStdOutput = stdout_wr_p; startup_info.hStdError = stderr_wr_p; if(stdin_fd || stdout_fd || stderr_fd) startup_info.dwFlags |= STARTF_USESTDHANDLES; char* path_cstr; if(path=="") path_cstr=NULL; else { path_cstr=new char[path.size()+1]; std::strcpy(path_cstr, path.c_str()); } char* command_cstr; #ifdef MSYS_PROCESS_USE_SH size_t pos=0; std::string sh_command=command; while((pos=sh_command.find('\\', pos))!=std::string::npos) { sh_command.replace(pos, 1, "\\\\\\\\"); pos+=4; } pos=0; while((pos=sh_command.find('\"', pos))!=std::string::npos) { sh_command.replace(pos, 1, "\\\""); pos+=2; } sh_command.insert(0, "sh -c \""); sh_command+="\""; command_cstr=new char[sh_command.size()+1]; std::strcpy(command_cstr, sh_command.c_str()); #else command_cstr=new char[command.size()+1]; std::strcpy(command_cstr, command.c_str()); #endif BOOL bSuccess = CreateProcess(NULL, command_cstr, NULL, NULL, TRUE, 0, NULL, path_cstr, &startup_info, &process_info); delete[] path_cstr; delete[] command_cstr; if(!bSuccess) { CloseHandle(process_info.hProcess); CloseHandle(process_info.hThread); return 0; } else { CloseHandle(process_info.hThread); } if(stdin_fd) *stdin_fd=stdin_wr_p.detach(); if(stdout_fd) *stdout_fd=stdout_rd_p.detach(); if(stderr_fd) *stderr_fd=stderr_rd_p.detach(); closed=false; data.id=process_info.dwProcessId; data.handle=process_info.hProcess; return process_info.dwProcessId; } void Process::async_read() { if(data.id==0) return; if(stdout_fd) { stdout_thread=std::thread([this](){ DWORD n; std::unique_ptr<char[]> buffer(new char[buffer_size]); for (;;) { BOOL bSuccess = ReadFile(*stdout_fd, static_cast<CHAR*>(buffer.get()), static_cast<DWORD>(buffer_size), &n, NULL); if(!bSuccess || n == 0) break; read_stdout(buffer.get(), static_cast<size_t>(n)); } }); } if(stderr_fd) { stderr_thread=std::thread([this](){ DWORD n; std::unique_ptr<char[]> buffer(new char[buffer_size]); for (;;) { BOOL bSuccess = ReadFile(*stderr_fd, static_cast<CHAR*>(buffer.get()), static_cast<DWORD>(buffer_size), &n, NULL); if(!bSuccess || n == 0) break; read_stderr(buffer.get(), static_cast<size_t>(n)); } }); } } int Process::get_exit_status() { if(data.id==0) return -1; DWORD exit_status; WaitForSingleObject(data.handle, INFINITE); if(!GetExitCodeProcess(data.handle, &exit_status)) exit_status=-1; { std::lock_guard<std::mutex> lock(close_mutex); CloseHandle(data.handle); closed=true; } close_fds(); return static_cast<int>(exit_status); } void Process::close_fds() { if(stdout_thread.joinable()) stdout_thread.join(); if(stderr_thread.joinable()) stderr_thread.join(); if(stdin_fd) close_stdin(); if(stdout_fd) { if(*stdout_fd!=NULL) CloseHandle(*stdout_fd); stdout_fd.reset(); } if(stderr_fd) { if(*stderr_fd!=NULL) CloseHandle(*stderr_fd); stderr_fd.reset(); } } bool Process::write(const char *bytes, size_t n) { if(!open_stdin) throw std::invalid_argument("Can't write to an unopened stdin pipe. Please set open_stdin=true when constructing the process."); std::lock_guard<std::mutex> lock(stdin_mutex); if(stdin_fd) { DWORD written; BOOL bSuccess=WriteFile(*stdin_fd, bytes, static_cast<DWORD>(n), &written, NULL); if(!bSuccess || written==0) { return false; } else { return true; } } return false; } void Process::close_stdin() { std::lock_guard<std::mutex> lock(stdin_mutex); if(stdin_fd) { if(*stdin_fd!=NULL) CloseHandle(*stdin_fd); stdin_fd.reset(); } } //Based on http://stackoverflow.com/a/1173396 void Process::kill(bool force) { std::lock_guard<std::mutex> lock(close_mutex); if(data.id>0 && !closed) { HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(snapshot) { PROCESSENTRY32 process; ZeroMemory(&process, sizeof(process)); process.dwSize = sizeof(process); if(Process32First(snapshot, &process)) { do { if(process.th32ParentProcessID==data.id) { HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID); if(process_handle) TerminateProcess(process_handle, 2); } } while (Process32Next(snapshot, &process)); } } TerminateProcess(data.handle, 2); } } //Based on http://stackoverflow.com/a/1173396 void Process::kill(id_type id, bool force) { if(id==0) return; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(snapshot) { PROCESSENTRY32 process; ZeroMemory(&process, sizeof(process)); process.dwSize = sizeof(process); if(Process32First(snapshot, &process)) { do { if(process.th32ParentProcessID==id) { HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID); if(process_handle) TerminateProcess(process_handle, 2); } } while (Process32Next(snapshot, &process)); } } HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id); if(process_handle) TerminateProcess(process_handle, 2); } <|endoftext|>
<commit_before>// $Id$ // // Jet sample analysis task. // // Author: S.Aiola #include <TClonesArray.h> #include <TH1F.h> #include <TH2F.h> #include <TList.h> #include <TLorentzVector.h> #include "AliVCluster.h" #include "AliVTrack.h" #include "AliEmcalJet.h" #include "AliRhoParameter.h" #include "AliLog.h" #include "AliJetContainer.h" #include "AliParticleContainer.h" #include "AliClusterContainer.h" #include "AliAnalysisTaskEmcalJetSample.h" ClassImp(AliAnalysisTaskEmcalJetSample) //________________________________________________________________________ AliAnalysisTaskEmcalJetSample::AliAnalysisTaskEmcalJetSample() : AliAnalysisTaskEmcalJet("AliAnalysisTaskEmcalJetSample", kTRUE), fJetsCont(0), fTracksCont(0), fCaloClustersCont(0) { // Default constructor. for (Int_t i = 0; i < 4; i++) { fHistTracksPt[i] = 0; fHistClustersPt[i] = 0; fHistLeadingJetPt[i] = 0; fHistJetsPhiEta[i] = 0; fHistJetsPtArea[i] = 0; fHistJetsPtLeadHad[i] = 0; fHistJetsCorrPtArea[i] = 0; } SetMakeGeneralHistograms(kTRUE); } //________________________________________________________________________ AliAnalysisTaskEmcalJetSample::AliAnalysisTaskEmcalJetSample(const char *name) : AliAnalysisTaskEmcalJet(name, kTRUE), fJetsCont(0), fTracksCont(0), fCaloClustersCont(0) { // Standard constructor. for (Int_t i = 0; i < 4; i++) { fHistTracksPt[i] = 0; fHistClustersPt[i] = 0; fHistLeadingJetPt[i] = 0; fHistJetsPhiEta[i] = 0; fHistJetsPtArea[i] = 0; fHistJetsPtLeadHad[i] = 0; fHistJetsCorrPtArea[i] = 0; } SetMakeGeneralHistograms(kTRUE); } //________________________________________________________________________ AliAnalysisTaskEmcalJetSample::~AliAnalysisTaskEmcalJetSample() { // Destructor. } //________________________________________________________________________ void AliAnalysisTaskEmcalJetSample::UserCreateOutputObjects() { // Create user output. AliAnalysisTaskEmcalJet::UserCreateOutputObjects(); fJetsCont = GetJetContainer(0); fTracksCont = fJetsCont->GetParticleContainer(); fCaloClustersCont = fJetsCont->GetClusterContainer(); TString histname; for (Int_t i = 0; i < 4; i++) { if (fParticleCollArray.GetEntriesFast()>0) { histname = "fHistTracksPt_"; histname += i; fHistTracksPt[i] = new TH1F(histname.Data(), histname.Data(), fNbins / 2, fMinBinPt, fMaxBinPt / 2); fHistTracksPt[i]->GetXaxis()->SetTitle("p_{T,track} (GeV/c)"); fHistTracksPt[i]->GetYaxis()->SetTitle("counts"); fOutput->Add(fHistTracksPt[i]); } if (fClusterCollArray.GetEntriesFast()>0) { histname = "fHistClustersPt_"; histname += i; fHistClustersPt[i] = new TH1F(histname.Data(), histname.Data(), fNbins / 2, fMinBinPt, fMaxBinPt / 2); fHistClustersPt[i]->GetXaxis()->SetTitle("p_{T,clus} (GeV/c)"); fHistClustersPt[i]->GetYaxis()->SetTitle("counts"); fOutput->Add(fHistClustersPt[i]); } if (fJetCollArray.GetEntriesFast()>0) { histname = "fHistLeadingJetPt_"; histname += i; fHistLeadingJetPt[i] = new TH1F(histname.Data(), histname.Data(), fNbins, fMinBinPt, fMaxBinPt); fHistLeadingJetPt[i]->GetXaxis()->SetTitle("p_{T}^{raw} (GeV/c)"); fHistLeadingJetPt[i]->GetYaxis()->SetTitle("counts"); fOutput->Add(fHistLeadingJetPt[i]); histname = "fHistJetsPhiEta_"; histname += i; fHistJetsPhiEta[i] = new TH2F(histname.Data(), histname.Data(), 50, -1, 1, 101, 0, TMath::Pi()*2 + TMath::Pi()/200); fHistJetsPhiEta[i]->GetXaxis()->SetTitle("#eta"); fHistJetsPhiEta[i]->GetYaxis()->SetTitle("#phi"); fOutput->Add(fHistJetsPhiEta[i]); histname = "fHistJetsPtArea_"; histname += i; fHistJetsPtArea[i] = new TH2F(histname.Data(), histname.Data(), fNbins, fMinBinPt, fMaxBinPt, 30, 0, 3); fHistJetsPtArea[i]->GetXaxis()->SetTitle("p_{T}^{raw} (GeV/c)"); fHistJetsPtArea[i]->GetYaxis()->SetTitle("area"); fOutput->Add(fHistJetsPtArea[i]); histname = "fHistJetsPtLeadHad_"; histname += i; fHistJetsPtLeadHad[i] = new TH2F(histname.Data(), histname.Data(), fNbins, fMinBinPt, fMaxBinPt, fNbins / 2, fMinBinPt, fMaxBinPt / 2); fHistJetsPtLeadHad[i]->GetXaxis()->SetTitle("p_{T}^{raw} (GeV/c)"); fHistJetsPtLeadHad[i]->GetYaxis()->SetTitle("p_{T,lead} (GeV/c)"); fHistJetsPtLeadHad[i]->GetZaxis()->SetTitle("counts"); fOutput->Add(fHistJetsPtLeadHad[i]); if (!(GetJetContainer()->GetRhoName().IsNull())) { histname = "fHistJetsCorrPtArea_"; histname += i; fHistJetsCorrPtArea[i] = new TH2F(histname.Data(), histname.Data(), fNbins*2, -fMaxBinPt, fMaxBinPt, 30, 0, 3); fHistJetsCorrPtArea[i]->GetXaxis()->SetTitle("p_{T}^{corr} [GeV/c]"); fHistJetsCorrPtArea[i]->GetYaxis()->SetTitle("area"); fOutput->Add(fHistJetsCorrPtArea[i]); } } } PostData(1, fOutput); // Post data for ALL output slots > 0 here. } //________________________________________________________________________ Bool_t AliAnalysisTaskEmcalJetSample::FillHistograms() { // Fill histograms. if (fTracksCont) { AliVParticle *track = fTracksCont->GetNextAcceptParticle(0); while(track) { fHistTracksPt[fCentBin]->Fill(track->Pt()); track = fTracksCont->GetNextAcceptParticle(); } } if (fCaloClustersCont) { AliVCluster *cluster = fCaloClustersCont->GetNextAcceptCluster(0); while(cluster) { TLorentzVector nPart; cluster->GetMomentum(nPart, fVertex); fHistClustersPt[fCentBin]->Fill(nPart.Pt()); cluster = fCaloClustersCont->GetNextAcceptCluster(); } } if (fJetsCont) { AliEmcalJet *jet = fJetsCont->GetNextAcceptJet(0); while(jet) { fHistJetsPtArea[fCentBin]->Fill(jet->Pt(), jet->Area()); fHistJetsPhiEta[fCentBin]->Fill(jet->Eta(), jet->Phi()); Float_t ptLeading = fJetsCont->GetLeadingHadronPt(jet); fHistJetsPtLeadHad[fCentBin]->Fill(jet->Pt(), ptLeading); Float_t corrPt = jet->Pt() - fJetsCont->GetRhoVal() * jet->Area(); fHistJetsCorrPtArea[fCentBin]->Fill(corrPt, jet->Area()); jet = fJetsCont->GetNextAcceptJet(); } jet = fJetsCont->GetLeadingJet(); fHistLeadingJetPt[fCentBin]->Fill(jet->Pt()); } return kTRUE; } //________________________________________________________________________ void AliAnalysisTaskEmcalJetSample::ExecOnce() { AliAnalysisTaskEmcalJet::ExecOnce(); if (fJetsCont && fJetsCont->GetArray() == 0) fJetsCont = 0; if (fTracksCont && fTracksCont->GetArray() == 0) fTracksCont = 0; if (fCaloClustersCont && fCaloClustersCont->GetArray() == 0) fCaloClustersCont = 0; } //________________________________________________________________________ Bool_t AliAnalysisTaskEmcalJetSample::Run() { // Run analysis code here, if needed. It will be executed before FillHistograms(). return kTRUE; // If return kFALSE FillHistogram() will NOT be executed. } //________________________________________________________________________ void AliAnalysisTaskEmcalJetSample::Terminate(Option_t *) { // Called once at the end of the analysis. } <commit_msg>fix seg fault<commit_after>// $Id$ // // Jet sample analysis task. // // Author: S.Aiola #include <TClonesArray.h> #include <TH1F.h> #include <TH2F.h> #include <TList.h> #include <TLorentzVector.h> #include "AliVCluster.h" #include "AliVTrack.h" #include "AliEmcalJet.h" #include "AliRhoParameter.h" #include "AliLog.h" #include "AliJetContainer.h" #include "AliParticleContainer.h" #include "AliClusterContainer.h" #include "AliAnalysisTaskEmcalJetSample.h" ClassImp(AliAnalysisTaskEmcalJetSample) //________________________________________________________________________ AliAnalysisTaskEmcalJetSample::AliAnalysisTaskEmcalJetSample() : AliAnalysisTaskEmcalJet("AliAnalysisTaskEmcalJetSample", kTRUE), fJetsCont(0), fTracksCont(0), fCaloClustersCont(0) { // Default constructor. for (Int_t i = 0; i < 4; i++) { fHistTracksPt[i] = 0; fHistClustersPt[i] = 0; fHistLeadingJetPt[i] = 0; fHistJetsPhiEta[i] = 0; fHistJetsPtArea[i] = 0; fHistJetsPtLeadHad[i] = 0; fHistJetsCorrPtArea[i] = 0; } SetMakeGeneralHistograms(kTRUE); } //________________________________________________________________________ AliAnalysisTaskEmcalJetSample::AliAnalysisTaskEmcalJetSample(const char *name) : AliAnalysisTaskEmcalJet(name, kTRUE), fJetsCont(0), fTracksCont(0), fCaloClustersCont(0) { // Standard constructor. for (Int_t i = 0; i < 4; i++) { fHistTracksPt[i] = 0; fHistClustersPt[i] = 0; fHistLeadingJetPt[i] = 0; fHistJetsPhiEta[i] = 0; fHistJetsPtArea[i] = 0; fHistJetsPtLeadHad[i] = 0; fHistJetsCorrPtArea[i] = 0; } SetMakeGeneralHistograms(kTRUE); } //________________________________________________________________________ AliAnalysisTaskEmcalJetSample::~AliAnalysisTaskEmcalJetSample() { // Destructor. } //________________________________________________________________________ void AliAnalysisTaskEmcalJetSample::UserCreateOutputObjects() { // Create user output. AliAnalysisTaskEmcalJet::UserCreateOutputObjects(); fJetsCont = GetJetContainer(0); fTracksCont = fJetsCont->GetParticleContainer(); fCaloClustersCont = fJetsCont->GetClusterContainer(); TString histname; for (Int_t i = 0; i < 4; i++) { if (fParticleCollArray.GetEntriesFast()>0) { histname = "fHistTracksPt_"; histname += i; fHistTracksPt[i] = new TH1F(histname.Data(), histname.Data(), fNbins / 2, fMinBinPt, fMaxBinPt / 2); fHistTracksPt[i]->GetXaxis()->SetTitle("p_{T,track} (GeV/c)"); fHistTracksPt[i]->GetYaxis()->SetTitle("counts"); fOutput->Add(fHistTracksPt[i]); } if (fClusterCollArray.GetEntriesFast()>0) { histname = "fHistClustersPt_"; histname += i; fHistClustersPt[i] = new TH1F(histname.Data(), histname.Data(), fNbins / 2, fMinBinPt, fMaxBinPt / 2); fHistClustersPt[i]->GetXaxis()->SetTitle("p_{T,clus} (GeV/c)"); fHistClustersPt[i]->GetYaxis()->SetTitle("counts"); fOutput->Add(fHistClustersPt[i]); } if (fJetCollArray.GetEntriesFast()>0) { histname = "fHistLeadingJetPt_"; histname += i; fHistLeadingJetPt[i] = new TH1F(histname.Data(), histname.Data(), fNbins, fMinBinPt, fMaxBinPt); fHistLeadingJetPt[i]->GetXaxis()->SetTitle("p_{T}^{raw} (GeV/c)"); fHistLeadingJetPt[i]->GetYaxis()->SetTitle("counts"); fOutput->Add(fHistLeadingJetPt[i]); histname = "fHistJetsPhiEta_"; histname += i; fHistJetsPhiEta[i] = new TH2F(histname.Data(), histname.Data(), 50, -1, 1, 101, 0, TMath::Pi()*2 + TMath::Pi()/200); fHistJetsPhiEta[i]->GetXaxis()->SetTitle("#eta"); fHistJetsPhiEta[i]->GetYaxis()->SetTitle("#phi"); fOutput->Add(fHistJetsPhiEta[i]); histname = "fHistJetsPtArea_"; histname += i; fHistJetsPtArea[i] = new TH2F(histname.Data(), histname.Data(), fNbins, fMinBinPt, fMaxBinPt, 30, 0, 3); fHistJetsPtArea[i]->GetXaxis()->SetTitle("p_{T}^{raw} (GeV/c)"); fHistJetsPtArea[i]->GetYaxis()->SetTitle("area"); fOutput->Add(fHistJetsPtArea[i]); histname = "fHistJetsPtLeadHad_"; histname += i; fHistJetsPtLeadHad[i] = new TH2F(histname.Data(), histname.Data(), fNbins, fMinBinPt, fMaxBinPt, fNbins / 2, fMinBinPt, fMaxBinPt / 2); fHistJetsPtLeadHad[i]->GetXaxis()->SetTitle("p_{T}^{raw} (GeV/c)"); fHistJetsPtLeadHad[i]->GetYaxis()->SetTitle("p_{T,lead} (GeV/c)"); fHistJetsPtLeadHad[i]->GetZaxis()->SetTitle("counts"); fOutput->Add(fHistJetsPtLeadHad[i]); if (!(GetJetContainer()->GetRhoName().IsNull())) { histname = "fHistJetsCorrPtArea_"; histname += i; fHistJetsCorrPtArea[i] = new TH2F(histname.Data(), histname.Data(), fNbins*2, -fMaxBinPt, fMaxBinPt, 30, 0, 3); fHistJetsCorrPtArea[i]->GetXaxis()->SetTitle("p_{T}^{corr} [GeV/c]"); fHistJetsCorrPtArea[i]->GetYaxis()->SetTitle("area"); fOutput->Add(fHistJetsCorrPtArea[i]); } } } PostData(1, fOutput); // Post data for ALL output slots > 0 here. } //________________________________________________________________________ Bool_t AliAnalysisTaskEmcalJetSample::FillHistograms() { // Fill histograms. if (fTracksCont) { AliVParticle *track = fTracksCont->GetNextAcceptParticle(0); while(track) { fHistTracksPt[fCentBin]->Fill(track->Pt()); track = fTracksCont->GetNextAcceptParticle(); } } if (fCaloClustersCont) { AliVCluster *cluster = fCaloClustersCont->GetNextAcceptCluster(0); while(cluster) { TLorentzVector nPart; cluster->GetMomentum(nPart, fVertex); fHistClustersPt[fCentBin]->Fill(nPart.Pt()); cluster = fCaloClustersCont->GetNextAcceptCluster(); } } if (fJetsCont) { AliEmcalJet *jet = fJetsCont->GetNextAcceptJet(0); while(jet) { fHistJetsPtArea[fCentBin]->Fill(jet->Pt(), jet->Area()); fHistJetsPhiEta[fCentBin]->Fill(jet->Eta(), jet->Phi()); Float_t ptLeading = fJetsCont->GetLeadingHadronPt(jet); fHistJetsPtLeadHad[fCentBin]->Fill(jet->Pt(), ptLeading); Float_t corrPt = jet->Pt() - fJetsCont->GetRhoVal() * jet->Area(); fHistJetsCorrPtArea[fCentBin]->Fill(corrPt, jet->Area()); jet = fJetsCont->GetNextAcceptJet(); } jet = fJetsCont->GetLeadingJet(); if(jet) fHistLeadingJetPt[fCentBin]->Fill(jet->Pt()); } return kTRUE; } //________________________________________________________________________ void AliAnalysisTaskEmcalJetSample::ExecOnce() { AliAnalysisTaskEmcalJet::ExecOnce(); if (fJetsCont && fJetsCont->GetArray() == 0) fJetsCont = 0; if (fTracksCont && fTracksCont->GetArray() == 0) fTracksCont = 0; if (fCaloClustersCont && fCaloClustersCont->GetArray() == 0) fCaloClustersCont = 0; } //________________________________________________________________________ Bool_t AliAnalysisTaskEmcalJetSample::Run() { // Run analysis code here, if needed. It will be executed before FillHistograms(). return kTRUE; // If return kFALSE FillHistogram() will NOT be executed. } //________________________________________________________________________ void AliAnalysisTaskEmcalJetSample::Terminate(Option_t *) { // Called once at the end of the analysis. } <|endoftext|>
<commit_before>#include <algorithm> #include <unistd.h> #include "../core/converter.h" #include "xsocket.h" using namespace std; using namespace MM_NAMESPACE()::NET; SocketStream::SocketStream(int fd) : fd(fd) {} SocketStream::SocketStream(const SocketStream& obj) : fd(obj.fd) {} SocketStream::~SocketStream() { close(fd); } void SocketStream::operator<<(const std::string& data) { send(data); } void SocketStream::send(const std::string& data) { send(data, data.length()); } void SocketStream::send(const std::string& data, int len) { int n = write(fd, data.c_str(), len); if (n < 0) throw SocketException("write() failed: " + str(n)); } const std::string SocketStream::get(int len) { char buf[MAX_BUF]; bzero(&buf, MAX_BUF); int n = read(fd, &buf, len); if (n < 0) throw SocketException("read() failed" + str(n)); return buf; } const std::string SocketStream::operator>>(int len) { return get(len); } Socket::Socket(SOCKET_TYPE type, int port) : fd(0), port(port), type(type), stream(0) { bzero((char*)&addr, sizeof(addr)); if (type == TCP) fd = socket(AF_INET, SOCK_STREAM, 0); else if (type == UDP) fd = socket(AF_INET, SOCK_DGRAM, 0); else if (type == UNIX) fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (fd < 0) throw SocketException("Could not create socket"); } Socket::~Socket() { // hmmm no fd because SocketStream does the job } ServerSocket::ServerSocket(SOCKET_TYPE type, int port) : Socket(type, port) { addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) throw SocketException("Could not bind to address/port"); stream = new SocketStream(fd); } ServerSocket::~ServerSocket() { if (stream != NULL) delete stream; } SocketStream* ServerSocket::listen() { struct sockaddr_in client_addr; int client_addr_len = sizeof(client_addr); bzero((char*)&client_addr, client_addr_len); ::listen(fd, MAX_LISTEN_QUEUE); int client_fd = accept(fd, (struct sockaddr*)&client_addr, (socklen_t*)&client_addr_len); if (client_fd < 0) throw SocketException("Error during accaptance of remote client"); return new SocketStream(client_fd); } ClientSocket::ClientSocket(SOCKET_TYPE type, int port, const std::string& target) : Socket(type, port) { addr.sin_port = htons((unsigned short int)port); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(target.c_str()); // socklen_t addr_len = sizeof(addr); if (connect(fd, (struct sockaddr*)&addr, sizeof(addr))) { perror("connect:"); throw SocketException("Could not connect to given target"); } stream = new SocketStream(fd); } ClientSocket::~ClientSocket() {} void StreamSelecter::add_stream(SocketStream* stream) { streams.push_back(stream); } void StreamSelecter::remove_stream(SocketStream* stream) { std::remove(streams.begin(), streams.end(), stream); } SocketStream* StreamSelecter::select() { return this->select(250000); } SocketStream* StreamSelecter::select(unsigned int usecs) { FD_ZERO(&socks); // for(vector<SocketStream*>::iterator i=streams.begin(); i!=streams.end(); // ++i) for (SocketStream* stream : streams) FD_SET(stream->fd, &socks); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = usecs; int readsocks = ::select(sizeof(socks) * 8, &socks, (fd_set*)0, (fd_set*)0, &timeout); if (readsocks == 0) return NULL; // for(vector<SocketStream*>::iterator i=streams.begin(); i!=streams.end(); // ++i) for (SocketStream* stream : streams) if (FD_ISSET(stream->fd, &socks)) return stream; return NULL; } <commit_msg>xsocket compatibility fix<commit_after>#include <algorithm> #include <unistd.h> #include "../core/converter.h" #include "xsocket.h" using namespace std; using namespace MM_NAMESPACE()::NET; SocketStream::SocketStream(int fd) : fd(fd) {} SocketStream::SocketStream(const SocketStream& obj) : fd(obj.fd) {} SocketStream::~SocketStream() { close(fd); } void SocketStream::operator<<(const std::string& data) { send(data); } void SocketStream::send(const std::string& data) { send(data, data.length()); } void SocketStream::send(const std::string& data, int len) { int n = write(fd, data.c_str(), len); if (n < 0) throw SocketException("write() failed: " + str(n)); } const std::string SocketStream::get(int len) { char buf[MAX_BUF]; bzero(&buf, MAX_BUF); int n = read(fd, &buf, len); if (n < 0) throw SocketException("read() failed" + str(n)); return buf; } const std::string SocketStream::operator>>(int len) { return get(len); } Socket::Socket(SOCKET_TYPE type, int port) : fd(0), port(port), type(type), stream(0) { bzero((char*)&addr, sizeof(addr)); if (type == TCP) fd = socket(AF_INET, SOCK_STREAM, 0); else if (type == UDP) fd = socket(AF_INET, SOCK_DGRAM, 0); else if (type == UNIX) fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (fd < 0) throw SocketException("Could not create socket"); } Socket::~Socket() { // hmmm no fd because SocketStream does the job } ServerSocket::ServerSocket(SOCKET_TYPE type, int port) : Socket(type, port) { addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) throw SocketException("Could not bind to address/port"); stream = new SocketStream(fd); } ServerSocket::~ServerSocket() { if (stream != NULL) delete stream; } SocketStream* ServerSocket::listen() { struct sockaddr_in client_addr; int client_addr_len = sizeof(client_addr); bzero((char*)&client_addr, client_addr_len); ::listen(fd, MAX_LISTEN_QUEUE); int client_fd = accept(fd, (struct sockaddr*)&client_addr, (socklen_t*)&client_addr_len); if (client_fd < 0) throw SocketException("Error during accaptance of remote client"); return new SocketStream(client_fd); } ClientSocket::ClientSocket(SOCKET_TYPE type, int port, const std::string& target) : Socket(type, port) { addr.sin_port = htons((unsigned short int)port); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(target.c_str()); // socklen_t addr_len = sizeof(addr); if (connect(fd, (struct sockaddr*)&addr, sizeof(addr))) { perror("connect:"); throw SocketException("Could not connect to given target"); } stream = new SocketStream(fd); } ClientSocket::~ClientSocket() {} void StreamSelecter::add_stream(SocketStream* stream) { streams.push_back(stream); } void StreamSelecter::remove_stream(SocketStream* stream) { std::remove(streams.begin(), streams.end(), stream); } SocketStream* StreamSelecter::select() { return this->select(250000); } SocketStream* StreamSelecter::select(unsigned int usecs) { FD_ZERO(&socks); // for(vector<SocketStream*>::iterator i=streams.begin(); i!=streams.end(); // ++i) for (SocketStream* stream : streams) FD_SET(stream->fd, &socks); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = usecs; int readsocks = ::select(sizeof(socks) * 8, &socks, (fd_set*)0, (fd_set*)0, &timeout); if (readsocks == 0) return NULL; // for(vector<SocketStream*>::iterator i=streams.begin(); i!=streams.end(); // ++i) for (SocketStream* stream : streams) if (FD_ISSET(stream->fd, &socks)) return stream; return NULL; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm 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. // //////////////////////////////////////////////////////////////////////////// #pragma once #include "node_types.hpp" #include "js_class.hpp" #include "js_util.hpp" namespace realm { namespace node { template<typename T> using ClassDefinition = js::ClassDefinition<Types, T>; using ConstructorType = js::ConstructorType<Types>; using MethodType = js::MethodType<Types>; using PropertyType = js::PropertyType<Types>; using IndexPropertyType = js::IndexPropertyType<Types>; using StringPropertyType = js::StringPropertyType<Types>; static inline std::vector<v8::Local<v8::Value>> get_arguments(const Nan::FunctionCallbackInfo<v8::Value> &info) { int count = info.Length(); std::vector<v8::Local<v8::Value>> arguments; arguments.reserve(count); for (int i = 0; i < count; i++) { arguments.push_back(info[i]); } return arguments; } static inline void setup_static_method(v8::Local<v8::FunctionTemplate> tpl, const std::string &name, Nan::FunctionCallback callback) { v8::Local<v8::Function> fn = Nan::GetFunction(Nan::New<v8::FunctionTemplate>(callback)).ToLocalChecked(); v8::Local<v8::String> fn_name = Nan::New(name).ToLocalChecked(); tpl->Set(fn_name, fn, v8::PropertyAttribute::DontEnum); fn->SetName(fn_name); } static inline void setup_method(v8::Local<v8::FunctionTemplate> tpl, const std::string &name, Nan::FunctionCallback callback) { v8::Local<v8::Signature> signature = Nan::New<v8::Signature>(tpl); v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(callback, v8::Local<v8::Value>(), signature); v8::Local<v8::Function> fn = Nan::GetFunction(t).ToLocalChecked(); v8::Local<v8::String> fn_name = Nan::New(name).ToLocalChecked(); // The reason we use this rather than Nan::SetPrototypeMethod is DontEnum. tpl->PrototypeTemplate()->Set(fn_name, fn, v8::PropertyAttribute::DontEnum); fn->SetName(fn_name); } static inline void set_readonly_property(v8::Local<v8::String> property, v8::Local<v8::Value> value, Nan::NAN_SETTER_ARGS_TYPE info) { std::string message = std::string("Cannot assign to read only property '") + std::string(String(property)) + "'"; Nan::ThrowError(message.c_str()); } static inline void set_readonly_index(uint32_t index, v8::Local<v8::Value> value, Nan::NAN_INDEX_SETTER_ARGS_TYPE info) { std::string message = std::string("Cannot assign to read only index ") + util::to_string(index); Nan::ThrowError(message.c_str()); } template<typename TargetType> static inline void setup_property(v8::Local<TargetType> target, const std::string &name, const PropertyType &property) { v8::Local<v8::String> prop_name = Nan::New(name).ToLocalChecked(); v8::PropertyAttribute attributes = v8::PropertyAttribute(v8::DontEnum | v8::DontDelete); Nan::SetAccessor(target, prop_name, property.getter, property.setter ?: set_readonly_property, v8::Local<v8::Value>(), v8::DEFAULT, attributes); } template<typename ClassType> class ObjectWrap : public Nan::ObjectWrap { using Internal = typename ClassType::Internal; using ParentClassType = typename ClassType::Parent; static ClassType s_class; std::unique_ptr<Internal> m_object; ObjectWrap(Internal* object = nullptr) : m_object(object) {} static void get_nonexistent_property(v8::Local<v8::String> property, Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info) { // Do nothing. This function exists only to prevent a crash where it is used. } static void set_property(v8::Local<v8::String> property, v8::Local<v8::Value> value, Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info) { if (s_class.index_accessor.getter || s_class.index_accessor.setter) { try { // Negative indices are passed into this string property interceptor, so check for them here. validated_positive_index(node::String(property)); } catch (std::out_of_range &e) { Nan::ThrowError(Exception::value(info.GetIsolate(), e)); return; } catch (std::invalid_argument &) { // Property is not a number. } } if (auto string_setter = s_class.string_accessor.setter) { string_setter(property, value, info); } } static void get_indexes(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info) { uint32_t length; try { length = Object::validated_get_length(info.GetIsolate(), info.This()); } catch (std::exception &) { // Enumerating properties should never throw an exception. return; } v8::Local<v8::Array> array = Nan::New<v8::Array>(length); for (uint32_t i = 0; i < length; i++) { Nan::Set(array, i, Nan::New(i)); } info.GetReturnValue().Set(array); } static v8::Local<v8::FunctionTemplate> create_template() { Nan::EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(construct); v8::Local<v8::ObjectTemplate> instance_tpl = tpl->InstanceTemplate(); v8::Local<v8::String> name = Nan::New(s_class.name).ToLocalChecked(); tpl->SetClassName(name); instance_tpl->SetInternalFieldCount(1); v8::Local<v8::FunctionTemplate> super_tpl = ObjectWrap<ParentClassType>::get_template(); if (!super_tpl.IsEmpty()) { tpl->Inherit(super_tpl); } // Static properties are setup in create_constructor() because V8. for (auto &pair : s_class.static_methods) { setup_static_method(tpl, pair.first, pair.second); } for (auto &pair : s_class.methods) { setup_method(tpl, pair.first, pair.second); } for (auto &pair : s_class.properties) { setup_property<v8::ObjectTemplate>(instance_tpl, pair.first, pair.second); } if (s_class.index_accessor.getter) { auto &index_accessor = s_class.index_accessor; Nan::SetIndexedPropertyHandler(instance_tpl, index_accessor.getter, index_accessor.setter ?: set_readonly_index, 0, 0, get_indexes); } if (s_class.string_accessor.getter || s_class.index_accessor.getter || s_class.index_accessor.setter) { // Use our own wrapper for the setter since we want to throw for negative indices. auto &string_accessor = s_class.string_accessor; Nan::SetNamedPropertyHandler(instance_tpl, string_accessor.getter ?: get_nonexistent_property, set_property, 0, 0, string_accessor.enumerator); } return scope.Escape(tpl); } public: operator Internal*() const { return m_object.get(); } ObjectWrap<ClassType>& operator=(Internal* object) { if (m_object.get() != object) { m_object = std::unique_ptr<Internal>(object); } return *this; } static v8::Local<v8::FunctionTemplate> get_template() { static Nan::Persistent<v8::FunctionTemplate> js_template(create_template()); return Nan::New(js_template); } static v8::Local<v8::Function> create_constructor(v8::Isolate* isolate) { Nan::EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> tpl = get_template(); v8::Local<v8::Function> constructor = Nan::GetFunction(tpl).ToLocalChecked(); for (auto &pair : s_class.static_properties) { setup_property<v8::Object>(constructor, pair.first, pair.second); } return scope.Escape(constructor); } static v8::Local<v8::Object> create_instance(v8::Isolate* isolate, Internal* internal = nullptr) { Nan::EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> tpl = get_template(); v8::Local<v8::Object> instance = Nan::NewInstance(tpl->InstanceTemplate()).ToLocalChecked(); auto wrap = new ObjectWrap<ClassType>(internal); wrap->Wrap(instance); return scope.Escape(instance); } static bool has_instance(v8::Isolate* isolate, const v8::Local<v8::Value> &value) { return get_template()->HasInstance(value); } static void construct(Nan::NAN_METHOD_ARGS_TYPE info) { if (!info.IsConstructCall()) { Nan::ThrowError("Constructor must be called with new"); } if (s_class.constructor) { auto isolate = info.GetIsolate(); auto arguments = get_arguments(info); v8::Local<v8::Object> this_object = info.This(); info.GetReturnValue().Set(this_object); auto wrap = new ObjectWrap<ClassType>(); wrap->Wrap(this_object); try { s_class.constructor(isolate, this_object, arguments.size(), arguments.data()); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } else { Nan::ThrowError("Illegal constructor"); } } }; template<> class ObjectWrap<void> { public: using Internal = void; static v8::Local<v8::FunctionTemplate> get_template() { return v8::Local<v8::FunctionTemplate>();; } }; // The declared static variables must be defined as well. template<typename ClassType> ClassType ObjectWrap<ClassType>::s_class; } // node namespace js { template<typename T> class ObjectWrap<node::Types, T> : public node::ObjectWrap<T> {}; template<node::MethodType F> void wrap(Nan::NAN_METHOD_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); node::ReturnValue return_value(info.GetReturnValue()); auto arguments = node::get_arguments(info); try { F(isolate, info.This(), arguments.size(), arguments.data(), return_value); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::PropertyType::GetterType F> void wrap(v8::Local<v8::String> property, Nan::NAN_GETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); node::ReturnValue return_value(info.GetReturnValue()); try { F(isolate, info.This(), return_value); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::PropertyType::SetterType F> void wrap(v8::Local<v8::String> property, v8::Local<v8::Value> value, Nan::NAN_SETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); try { F(isolate, info.This(), value); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::IndexPropertyType::GetterType F> void wrap(uint32_t index, Nan::NAN_INDEX_GETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); node::ReturnValue return_value(info.GetReturnValue()); try { F(isolate, info.This(), index, return_value); } catch (std::out_of_range &) { // Out-of-bounds index getters should just return undefined in JS. return_value.set_undefined(); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::IndexPropertyType::SetterType F> void wrap(uint32_t index, v8::Local<v8::Value> value, Nan::NAN_INDEX_SETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); try { if (F(isolate, info.This(), index, value)) { // Indicate that the property was intercepted. info.GetReturnValue().Set(value); } } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::StringPropertyType::GetterType F> void wrap(v8::Local<v8::String> property, Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); node::ReturnValue return_value(info.GetReturnValue()); try { F(isolate, info.This(), property, return_value); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::StringPropertyType::SetterType F> void wrap(v8::Local<v8::String> property, v8::Local<v8::Value> value, Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); try { if (F(isolate, info.This(), property, value)) { // Indicate that the property was intercepted. info.GetReturnValue().Set(value); } } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::StringPropertyType::EnumeratorType F> void wrap(Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info) { auto names = F(info.GetIsolate(), info.This()); int count = (int)names.size(); v8::Local<v8::Array> array = Nan::New<v8::Array>(count); for (int i = 0; i < count; i++) { Nan::Set(array, i, v8::Local<v8::String>(names[i])); } info.GetReturnValue().Set(array); } } // js } // realm <commit_msg>Define most of node::ObjectWrap separately<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm 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. // //////////////////////////////////////////////////////////////////////////// #pragma once #include "node_types.hpp" #include "js_class.hpp" #include "js_util.hpp" namespace realm { namespace node { template<typename T> using ClassDefinition = js::ClassDefinition<Types, T>; using ConstructorType = js::ConstructorType<Types>; using MethodType = js::MethodType<Types>; using PropertyType = js::PropertyType<Types>; using IndexPropertyType = js::IndexPropertyType<Types>; using StringPropertyType = js::StringPropertyType<Types>; template<typename ClassType> class ObjectWrap : public Nan::ObjectWrap { using Internal = typename ClassType::Internal; using ParentClassType = typename ClassType::Parent; public: static v8::Local<v8::Function> create_constructor(v8::Isolate*); static v8::Local<v8::Object> create_instance(v8::Isolate*, Internal* = nullptr); static v8::Local<v8::FunctionTemplate> get_template() { static Nan::Persistent<v8::FunctionTemplate> js_template(create_template()); return Nan::New(js_template); } static bool has_instance(v8::Isolate* isolate, const v8::Local<v8::Value> &value) { return get_template()->HasInstance(value); } operator Internal*() const { return m_object.get(); } ObjectWrap<ClassType>& operator=(Internal* object) { if (m_object.get() != object) { m_object = std::unique_ptr<Internal>(object); } return *this; } private: static ClassType s_class; std::unique_ptr<Internal> m_object; ObjectWrap(Internal* object = nullptr) : m_object(object) {} static v8::Local<v8::FunctionTemplate> create_template(); static void setup_method(v8::Local<v8::FunctionTemplate>, const std::string &, Nan::FunctionCallback); static void setup_static_method(v8::Local<v8::FunctionTemplate>, const std::string &, Nan::FunctionCallback); template<typename TargetType> static void setup_property(v8::Local<TargetType>, const std::string &, const PropertyType &); static void construct(Nan::NAN_METHOD_ARGS_TYPE); static void get_indexes(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE); static void set_property(v8::Local<v8::String>, v8::Local<v8::Value>, Nan::NAN_PROPERTY_SETTER_ARGS_TYPE); static void set_readonly_property(v8::Local<v8::String> property, v8::Local<v8::Value> value, Nan::NAN_SETTER_ARGS_TYPE info) { std::string message = std::string("Cannot assign to read only property '") + std::string(String(property)) + "'"; Nan::ThrowError(message.c_str()); } static void set_readonly_index(uint32_t index, v8::Local<v8::Value> value, Nan::NAN_INDEX_SETTER_ARGS_TYPE info) { std::string message = std::string("Cannot assign to read only index ") + util::to_string(index); Nan::ThrowError(message.c_str()); } static void get_nonexistent_property(v8::Local<v8::String>, Nan::NAN_PROPERTY_GETTER_ARGS_TYPE) { // Do nothing. This function exists only to prevent a crash where it is used. } }; template<> class ObjectWrap<void> { public: using Internal = void; static v8::Local<v8::FunctionTemplate> get_template() { return v8::Local<v8::FunctionTemplate>();; } }; // This helper function is needed outside the scope of the ObjectWrap class as well. static inline std::vector<v8::Local<v8::Value>> get_arguments(const Nan::FunctionCallbackInfo<v8::Value> &info) { int count = info.Length(); std::vector<v8::Local<v8::Value>> arguments; arguments.reserve(count); for (int i = 0; i < count; i++) { arguments.push_back(info[i]); } return arguments; } // The static class variable must be defined as well. template<typename ClassType> ClassType ObjectWrap<ClassType>::s_class; template<typename ClassType> inline v8::Local<v8::Function> ObjectWrap<ClassType>::create_constructor(v8::Isolate* isolate) { Nan::EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> tpl = get_template(); v8::Local<v8::Function> constructor = Nan::GetFunction(tpl).ToLocalChecked(); for (auto &pair : s_class.static_properties) { setup_property<v8::Object>(constructor, pair.first, pair.second); } return scope.Escape(constructor); } template<typename ClassType> inline v8::Local<v8::Object> ObjectWrap<ClassType>::create_instance(v8::Isolate* isolate, Internal* internal) { Nan::EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> tpl = get_template(); v8::Local<v8::Object> instance = Nan::NewInstance(tpl->InstanceTemplate()).ToLocalChecked(); auto wrap = new ObjectWrap<ClassType>(internal); wrap->Wrap(instance); return scope.Escape(instance); } template<typename ClassType> inline v8::Local<v8::FunctionTemplate> ObjectWrap<ClassType>::create_template() { Nan::EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(construct); v8::Local<v8::ObjectTemplate> instance_tpl = tpl->InstanceTemplate(); v8::Local<v8::String> name = Nan::New(s_class.name).ToLocalChecked(); tpl->SetClassName(name); instance_tpl->SetInternalFieldCount(1); v8::Local<v8::FunctionTemplate> super_tpl = ObjectWrap<ParentClassType>::get_template(); if (!super_tpl.IsEmpty()) { tpl->Inherit(super_tpl); } // Static properties are setup in create_constructor() because V8. for (auto &pair : s_class.static_methods) { setup_static_method(tpl, pair.first, pair.second); } for (auto &pair : s_class.methods) { setup_method(tpl, pair.first, pair.second); } for (auto &pair : s_class.properties) { setup_property<v8::ObjectTemplate>(instance_tpl, pair.first, pair.second); } if (s_class.index_accessor.getter) { auto &index_accessor = s_class.index_accessor; Nan::SetIndexedPropertyHandler(instance_tpl, index_accessor.getter, index_accessor.setter ?: set_readonly_index, 0, 0, get_indexes); } if (s_class.string_accessor.getter || s_class.index_accessor.getter || s_class.index_accessor.setter) { // Use our own wrapper for the setter since we want to throw for negative indices. auto &string_accessor = s_class.string_accessor; Nan::SetNamedPropertyHandler(instance_tpl, string_accessor.getter ?: get_nonexistent_property, set_property, 0, 0, string_accessor.enumerator); } return scope.Escape(tpl); } template<typename ClassType> inline void ObjectWrap<ClassType>::setup_method(v8::Local<v8::FunctionTemplate> tpl, const std::string &name, Nan::FunctionCallback callback) { v8::Local<v8::Signature> signature = Nan::New<v8::Signature>(tpl); v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(callback, v8::Local<v8::Value>(), signature); v8::Local<v8::Function> fn = Nan::GetFunction(t).ToLocalChecked(); v8::Local<v8::String> fn_name = Nan::New(name).ToLocalChecked(); // The reason we use this rather than Nan::SetPrototypeMethod is DontEnum. tpl->PrototypeTemplate()->Set(fn_name, fn, v8::PropertyAttribute::DontEnum); fn->SetName(fn_name); } template<typename ClassType> inline void ObjectWrap<ClassType>::setup_static_method(v8::Local<v8::FunctionTemplate> tpl, const std::string &name, Nan::FunctionCallback callback) { v8::Local<v8::Function> fn = Nan::GetFunction(Nan::New<v8::FunctionTemplate>(callback)).ToLocalChecked(); v8::Local<v8::String> fn_name = Nan::New(name).ToLocalChecked(); tpl->Set(fn_name, fn, v8::PropertyAttribute::DontEnum); fn->SetName(fn_name); } template<typename ClassType> template<typename TargetType> inline void ObjectWrap<ClassType>::setup_property(v8::Local<TargetType> target, const std::string &name, const PropertyType &property) { v8::Local<v8::String> prop_name = Nan::New(name).ToLocalChecked(); v8::PropertyAttribute attributes = v8::PropertyAttribute(v8::DontEnum | v8::DontDelete); Nan::SetAccessor(target, prop_name, property.getter, property.setter ?: set_readonly_property, v8::Local<v8::Value>(), v8::DEFAULT, attributes); } template<typename ClassType> inline void ObjectWrap<ClassType>::construct(Nan::NAN_METHOD_ARGS_TYPE info) { if (!info.IsConstructCall()) { Nan::ThrowError("Constructor must be called with new"); } if (s_class.constructor) { auto isolate = info.GetIsolate(); auto arguments = get_arguments(info); v8::Local<v8::Object> this_object = info.This(); info.GetReturnValue().Set(this_object); auto wrap = new ObjectWrap<ClassType>(); wrap->Wrap(this_object); try { s_class.constructor(isolate, this_object, arguments.size(), arguments.data()); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } else { Nan::ThrowError("Illegal constructor"); } } template<typename ClassType> inline void ObjectWrap<ClassType>::get_indexes(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info) { uint32_t length; try { length = Object::validated_get_length(info.GetIsolate(), info.This()); } catch (std::exception &) { // Enumerating properties should never throw an exception. return; } v8::Local<v8::Array> array = Nan::New<v8::Array>(length); for (uint32_t i = 0; i < length; i++) { Nan::Set(array, i, Nan::New(i)); } info.GetReturnValue().Set(array); } template<typename ClassType> inline void ObjectWrap<ClassType>::set_property(v8::Local<v8::String> property, v8::Local<v8::Value> value, Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info) { if (s_class.index_accessor.getter || s_class.index_accessor.setter) { try { // Negative indices are passed into this string property interceptor, so check for them here. validated_positive_index(node::String(property)); } catch (std::out_of_range &e) { Nan::ThrowError(Exception::value(info.GetIsolate(), e)); return; } catch (std::invalid_argument &) { // Property is not a number. } } if (auto string_setter = s_class.string_accessor.setter) { string_setter(property, value, info); } } } // node namespace js { template<typename ClassType> class ObjectWrap<node::Types, ClassType> : public node::ObjectWrap<ClassType> {}; template<node::MethodType F> void wrap(Nan::NAN_METHOD_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); node::ReturnValue return_value(info.GetReturnValue()); auto arguments = node::get_arguments(info); try { F(isolate, info.This(), arguments.size(), arguments.data(), return_value); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::PropertyType::GetterType F> void wrap(v8::Local<v8::String> property, Nan::NAN_GETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); node::ReturnValue return_value(info.GetReturnValue()); try { F(isolate, info.This(), return_value); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::PropertyType::SetterType F> void wrap(v8::Local<v8::String> property, v8::Local<v8::Value> value, Nan::NAN_SETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); try { F(isolate, info.This(), value); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::IndexPropertyType::GetterType F> void wrap(uint32_t index, Nan::NAN_INDEX_GETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); node::ReturnValue return_value(info.GetReturnValue()); try { F(isolate, info.This(), index, return_value); } catch (std::out_of_range &) { // Out-of-bounds index getters should just return undefined in JS. return_value.set_undefined(); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::IndexPropertyType::SetterType F> void wrap(uint32_t index, v8::Local<v8::Value> value, Nan::NAN_INDEX_SETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); try { if (F(isolate, info.This(), index, value)) { // Indicate that the property was intercepted. info.GetReturnValue().Set(value); } } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::StringPropertyType::GetterType F> void wrap(v8::Local<v8::String> property, Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); node::ReturnValue return_value(info.GetReturnValue()); try { F(isolate, info.This(), property, return_value); } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::StringPropertyType::SetterType F> void wrap(v8::Local<v8::String> property, v8::Local<v8::Value> value, Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info) { v8::Isolate* isolate = info.GetIsolate(); try { if (F(isolate, info.This(), property, value)) { // Indicate that the property was intercepted. info.GetReturnValue().Set(value); } } catch(std::exception &e) { Nan::ThrowError(node::Exception::value(isolate, e)); } } template<node::StringPropertyType::EnumeratorType F> void wrap(Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info) { auto names = F(info.GetIsolate(), info.This()); int count = (int)names.size(); v8::Local<v8::Array> array = Nan::New<v8::Array>(count); for (int i = 0; i < count; i++) { Nan::Set(array, i, v8::Local<v8::String>(names[i])); } info.GetReturnValue().Set(array); } } // js } // realm <|endoftext|>
<commit_before>// RUN: clang-cc -triple x86_64-apple-darwin -std=c++0x -O0 -S %s -o %t-64.s && // RUN: FileCheck -check-prefix LP64 --input-file=%t-64.s %s && // RUN: clang-cc -triple i386-apple-darwin -std=c++0x -O0 -S %s -o %t-32.s && // RUN: FileCheck -check-prefix LP32 -input-file=%t-32.s %s && // RUN: true extern "C" int printf(...); struct S { S() : iS(1), fS(1.23) {}; ~S(){printf("S::~S(%d, %f)\n", iS, fS); }; int iS; float fS; }; struct Q { Q() : iQ(2), dQ(2.34) {}; ~Q(){printf("Q::~Q(%d, %f)\n", iQ, dQ); }; int iQ; double dQ; }; struct P { P() : fP(3.45) , iP(3) {}; ~P(){printf("P::~P(%d, %f)\n", iP, fP); }; float fP; int iP; }; struct M : Q, P { S s; Q q; P p; }; M gm; int main() {M m1;} // CHECK-LP64: call __ZN1MC1Ev // CHECK-LP64: call __ZN1MD1Ev // CHECK-LP64: .globl __ZN1MD1Ev // CHECK-LP64-NEXT: .weak_definition __ZN1MD1Ev // CHECK-LP64-NEXT: __ZN1MD1Ev: // CHECK-LP32: call L__ZN1MC1Ev // CHECK-LP32: call L__ZN1MD1Ev // CHECK-LP32: .globl __ZN1MD1Ev // CHECK-LP32-NEXT: .weak_definition __ZN1MD1Ev // CHECK-LP32-NEXT: __ZN1MD1Ev: <commit_msg>Added member arrays to more tests now that ir-gen supports it.<commit_after>// RUN: clang-cc -triple x86_64-apple-darwin -std=c++0x -O0 -S %s -o %t-64.s && // RUN: FileCheck -check-prefix LP64 --input-file=%t-64.s %s && // RUN: clang-cc -triple i386-apple-darwin -std=c++0x -O0 -S %s -o %t-32.s && // RUN: FileCheck -check-prefix LP32 -input-file=%t-32.s %s && // RUN: true extern "C" int printf(...); int count = 1; struct S { S() : iS(count++), fS(1.23) {}; ~S(){printf("S::~S(%d, %f)\n", iS, fS); }; int iS; float fS; }; struct Q { Q() : iQ(count++), dQ(2.34) {}; ~Q(){printf("Q::~Q(%d, %f)\n", iQ, dQ); }; int iQ; double dQ; }; struct P { P() : fP(3.45) , iP(count++) {}; ~P(){printf("P::~P(%d, %f)\n", iP, fP); }; float fP; int iP; }; struct M : Q, P { S s; Q q; P p; P p_arr[3]; Q q_arr[2][3]; }; M gm; int main() {M m1;} // CHECK-LP64: call __ZN1MC1Ev // CHECK-LP64: call __ZN1MD1Ev // CHECK-LP64: .globl __ZN1MD1Ev // CHECK-LP64-NEXT: .weak_definition __ZN1MD1Ev // CHECK-LP64-NEXT: __ZN1MD1Ev: // CHECK-LP32: call L__ZN1MC1Ev // CHECK-LP32: call L__ZN1MD1Ev // CHECK-LP32: .globl __ZN1MD1Ev // CHECK-LP32-NEXT: .weak_definition __ZN1MD1Ev // CHECK-LP32-NEXT: __ZN1MD1Ev: <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkRefCnt.h" #include "include/core/SkString.h" #include "include/core/SkUnPreMultiply.h" #include "include/effects/SkColorMatrix.h" #include "include/effects/SkRuntimeEffect.h" #include "include/private/SkColorData.h" #include "include/private/SkNx.h" #include "src/core/SkColorFilter_Matrix.h" #include "src/core/SkColorSpacePriv.h" #include "src/core/SkRasterPipeline.h" #include "src/core/SkReadBuffer.h" #include "src/core/SkRuntimeEffectPriv.h" #include "src/core/SkVM.h" #include "src/core/SkWriteBuffer.h" static bool is_alpha_unchanged(const float matrix[20]) { const float* srcA = matrix + 15; return SkScalarNearlyZero (srcA[0]) && SkScalarNearlyZero (srcA[1]) && SkScalarNearlyZero (srcA[2]) && SkScalarNearlyEqual(srcA[3], 1) && SkScalarNearlyZero (srcA[4]); } SkColorFilter_Matrix::SkColorFilter_Matrix(const float array[20], Domain domain) : fAlphaIsUnchanged(is_alpha_unchanged(array)) , fDomain(domain) { memcpy(fMatrix, array, 20 * sizeof(float)); } void SkColorFilter_Matrix::flatten(SkWriteBuffer& buffer) const { SkASSERT(sizeof(fMatrix)/sizeof(float) == 20); buffer.writeScalarArray(fMatrix, 20); // RGBA flag buffer.writeBool(fDomain == Domain::kRGBA); } sk_sp<SkFlattenable> SkColorFilter_Matrix::CreateProc(SkReadBuffer& buffer) { float matrix[20]; if (!buffer.readScalarArray(matrix, 20)) { return nullptr; } auto is_rgba = buffer.readBool(); return is_rgba ? SkColorFilters::Matrix(matrix) : SkColorFilters::HSLAMatrix(matrix); } bool SkColorFilter_Matrix::onAsAColorMatrix(float matrix[20]) const { if (matrix) { memcpy(matrix, fMatrix, 20 * sizeof(float)); } return true; } bool SkColorFilter_Matrix::onAppendStages(const SkStageRec& rec, bool shaderIsOpaque) const { const bool willStayOpaque = shaderIsOpaque && fAlphaIsUnchanged, hsla = fDomain == Domain::kHSLA; SkRasterPipeline* p = rec.fPipeline; if (!shaderIsOpaque) { p->append(SkRasterPipeline::unpremul); } if ( hsla) { p->append(SkRasterPipeline::rgb_to_hsl); } if ( true) { p->append(SkRasterPipeline::matrix_4x5, fMatrix); } if ( hsla) { p->append(SkRasterPipeline::hsl_to_rgb); } if ( true) { p->append(SkRasterPipeline::clamp_0); } if ( true) { p->append(SkRasterPipeline::clamp_1); } if (!willStayOpaque) { p->append(SkRasterPipeline::premul); } return true; } skvm::Color SkColorFilter_Matrix::onProgram(skvm::Builder* p, skvm::Color c, const SkColorInfo& /*dst*/, skvm::Uniforms* uniforms, SkArenaAlloc*) const { auto apply_matrix = [&](auto xyzw) { auto dot = [&](int j) { auto custom_mad = [&](float f, skvm::F32 m, skvm::F32 a) { // skvm::Builder won't fold f*0 == 0, but we shouldn't encounter NaN here. // While looking, also simplify f == ±1. Anything else becomes a uniform. return f == 0.0f ? a : f == +1.0f ? a + m : f == -1.0f ? a - m : m * p->uniformF(uniforms->pushF(f)) + a; }; // Similarly, let skvm::Builder fold away the additive bias when zero. const float b = fMatrix[4+j*5]; skvm::F32 bias = b == 0.0f ? p->splat(0.0f) : p->uniformF(uniforms->pushF(b)); auto [x,y,z,w] = xyzw; return custom_mad(fMatrix[0+j*5], x, custom_mad(fMatrix[1+j*5], y, custom_mad(fMatrix[2+j*5], z, custom_mad(fMatrix[3+j*5], w, bias)))); }; return std::make_tuple(dot(0), dot(1), dot(2), dot(3)); }; c = unpremul(c); if (fDomain == Domain::kHSLA) { auto [h,s,l,a] = apply_matrix(p->to_hsla(c)); c = p->to_rgba({h,s,l,a}); } else { auto [r,g,b,a] = apply_matrix(c); c = {r,g,b,a}; } return premul(clamp01(c)); } #if SK_SUPPORT_GPU #include "src/gpu/effects/GrSkSLFP.h" // Convert RGBA -> HSLA (including unpremul). // // Based on work by Sam Hocevar, Emil Persson, and Ian Taylor [1][2][3]. High-level ideas: // // - minimize the number of branches by sorting and computing the hue phase in parallel (vec4s) // // - trade the third sorting branch for a potentially faster std::min and leaving 2nd/3rd // channels unsorted (based on the observation that swapping both the channels and the bias sign // has no effect under abs) // // - use epsilon offsets for denominators, to avoid explicit zero-checks // // An additional trick we employ is deferring premul->unpremul conversion until the very end: the // alpha factor gets naturally simplified for H and S, and only L requires a dedicated unpremul // division (so we trade three divs for one). // // [1] http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv // [2] http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl // [3] http://www.chilliant.com/rgb2hsv.html static std::unique_ptr<GrFragmentProcessor> rgb_to_hsl(std::unique_ptr<GrFragmentProcessor> child) { static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"( half4 main(half4 c) { half4 p = (c.g < c.b) ? half4(c.bg, -1, 2/3.0) : half4(c.gb, 0, -1/3.0); half4 q = (c.r < p.x) ? half4(p.x, c.r, p.yw) : half4(c.r, p.x, p.yz); // q.x -> max channel value // q.yz -> 2nd/3rd channel values (unsorted) // q.w -> bias value dependent on max channel selection half eps = 0.0001; half pmV = q.x; half pmC = pmV - min(q.y, q.z); half pmL = pmV - pmC * 0.5; half H = abs(q.w + (q.y - q.z) / (pmC * 6 + eps)); half S = pmC / (c.a + eps - abs(pmL * 2 - c.a)); half L = pmL / (c.a + eps); return half4(H, S, L, c.a); } )"); return GrSkSLFP::Make( effect, "RgbToHsl", std::move(child), GrSkSLFP::OptFlags::kPreservesOpaqueInput); } // Convert HSLA -> RGBA (including clamp and premul). // // Based on work by Sam Hocevar, Emil Persson, and Ian Taylor [1][2][3]. // // [1] http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv // [2] http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl // [3] http://www.chilliant.com/rgb2hsv.html static std::unique_ptr<GrFragmentProcessor> hsl_to_rgb(std::unique_ptr<GrFragmentProcessor> child) { static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"( half4 main(half4 color) { half3 hsl = color.rgb; half C = (1 - abs(2 * hsl.z - 1)) * hsl.y; half3 p = hsl.xxx + half3(0, 2/3.0, 1/3.0); half3 q = saturate(abs(fract(p) * 6 - 3) - 1); half3 rgb = (q - 0.5) * C + hsl.z; color = saturate(half4(rgb, color.a)); color.rgb *= color.a; return color; } )"); return GrSkSLFP::Make( effect, "HslToRgb", std::move(child), GrSkSLFP::OptFlags::kPreservesOpaqueInput); } GrFPResult SkColorFilter_Matrix::asFragmentProcessor(std::unique_ptr<GrFragmentProcessor> fp, GrRecordingContext*, const GrColorInfo&) const { switch (fDomain) { case Domain::kRGBA: fp = GrFragmentProcessor::ColorMatrix(std::move(fp), fMatrix, /* unpremulInput = */ true, /* clampRGBOutput = */ true, /* premulOutput = */ true); break; case Domain::kHSLA: fp = rgb_to_hsl(std::move(fp)); fp = GrFragmentProcessor::ColorMatrix(std::move(fp), fMatrix, /* unpremulInput = */ false, /* clampRGBOutput = */ false, /* premulOutput = */ false); fp = hsl_to_rgb(std::move(fp)); break; } return GrFPSuccess(std::move(fp)); } #endif /////////////////////////////////////////////////////////////////////////////// static sk_sp<SkColorFilter> MakeMatrix(const float array[20], SkColorFilter_Matrix::Domain domain) { if (!sk_floats_are_finite(array, 20)) { return nullptr; } #if defined(SK_SUPPORT_LEGACY_RUNTIME_EFFECTS) return sk_make_sp<SkColorFilter_Matrix>(array, domain); #else const bool alphaUnchanged = SkScalarNearlyEqual(array[15], 0) && SkScalarNearlyEqual(array[16], 0) && SkScalarNearlyEqual(array[17], 0) && SkScalarNearlyEqual(array[18], 1) && SkScalarNearlyEqual(array[19], 0); struct { SkM44 m; SkV4 b; } uniforms; SkString code { "uniform half4x4 m;" "uniform half4 b;" }; if (domain == SkColorFilter_Matrix::Domain::kHSLA) { code += kRGB_to_HSL_sksl; code += kHSL_to_RGB_sksl; } code += "half4 main(half4 inColor) {"; if (true) { code += "half4 c = inColor;"; // unpremul } if (alphaUnchanged) { code += "half a = c.a;"; } if (domain == SkColorFilter_Matrix::Domain::kHSLA) { code += "c.rgb = rgb_to_hsl(c.rgb);"; } if (true) { uniforms.m = SkM44{array[ 0], array[ 1], array[ 2], array[ 3], array[ 5], array[ 6], array[ 7], array[ 8], array[10], array[11], array[12], array[13], array[15], array[16], array[17], array[18]}; uniforms.b = SkV4{array[4], array[9], array[14], array[19]}; code += "c = m*c + b;"; } if (domain == SkColorFilter_Matrix::Domain::kHSLA) { code += "c.rgb = hsl_to_rgb(c.rgb);"; } if (alphaUnchanged) { code += "return half4(saturate(c.rgb), a);"; } else { code += "return saturate(c);"; } code += "}"; sk_sp<SkRuntimeEffect> effect = SkMakeCachedRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, std::move(code)); SkASSERT(effect); SkAlphaType unpremul = kUnpremul_SkAlphaType; return SkColorFilters::WithWorkingFormat( effect->makeColorFilter(SkData::MakeWithCopy(&uniforms,sizeof(uniforms))), nullptr/*keep dst TF encoding*/, nullptr/*stay in dst gamut*/, &unpremul); #endif } sk_sp<SkColorFilter> SkColorFilters::Matrix(const float array[20]) { return MakeMatrix(array, SkColorFilter_Matrix::Domain::kRGBA); } sk_sp<SkColorFilter> SkColorFilters::Matrix(const SkColorMatrix& cm) { return MakeMatrix(cm.fMat.data(), SkColorFilter_Matrix::Domain::kRGBA); } sk_sp<SkColorFilter> SkColorFilters::HSLAMatrix(const float array[20]) { return MakeMatrix(array, SkColorFilter_Matrix::Domain::kHSLA); } sk_sp<SkColorFilter> SkColorFilters::HSLAMatrix(const SkColorMatrix& cm) { return MakeMatrix(cm.fMat.data(), SkColorFilter_Matrix::Domain::kHSLA); } void SkColorFilter_Matrix::RegisterFlattenables() { SK_REGISTER_FLATTENABLE(SkColorFilter_Matrix); // This subclass was removed 4/2019 SkFlattenable::Register("SkColorMatrixFilterRowMajor255", [](SkReadBuffer& buffer) -> sk_sp<SkFlattenable> { float matrix[20]; if (buffer.readScalarArray(matrix, 20)) { matrix[ 4] *= (1.0f/255); matrix[ 9] *= (1.0f/255); matrix[14] *= (1.0f/255); matrix[19] *= (1.0f/255); return SkColorFilters::Matrix(matrix); } return nullptr; }); } <commit_msg>Reland "Switch back to non-SkSL matrix color filter for all clients"<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkRefCnt.h" #include "include/core/SkString.h" #include "include/core/SkUnPreMultiply.h" #include "include/effects/SkColorMatrix.h" #include "include/effects/SkRuntimeEffect.h" #include "include/private/SkColorData.h" #include "include/private/SkNx.h" #include "src/core/SkColorFilter_Matrix.h" #include "src/core/SkColorSpacePriv.h" #include "src/core/SkRasterPipeline.h" #include "src/core/SkReadBuffer.h" #include "src/core/SkRuntimeEffectPriv.h" #include "src/core/SkVM.h" #include "src/core/SkWriteBuffer.h" static bool is_alpha_unchanged(const float matrix[20]) { const float* srcA = matrix + 15; return SkScalarNearlyZero (srcA[0]) && SkScalarNearlyZero (srcA[1]) && SkScalarNearlyZero (srcA[2]) && SkScalarNearlyEqual(srcA[3], 1) && SkScalarNearlyZero (srcA[4]); } SkColorFilter_Matrix::SkColorFilter_Matrix(const float array[20], Domain domain) : fAlphaIsUnchanged(is_alpha_unchanged(array)) , fDomain(domain) { memcpy(fMatrix, array, 20 * sizeof(float)); } void SkColorFilter_Matrix::flatten(SkWriteBuffer& buffer) const { SkASSERT(sizeof(fMatrix)/sizeof(float) == 20); buffer.writeScalarArray(fMatrix, 20); // RGBA flag buffer.writeBool(fDomain == Domain::kRGBA); } sk_sp<SkFlattenable> SkColorFilter_Matrix::CreateProc(SkReadBuffer& buffer) { float matrix[20]; if (!buffer.readScalarArray(matrix, 20)) { return nullptr; } auto is_rgba = buffer.readBool(); return is_rgba ? SkColorFilters::Matrix(matrix) : SkColorFilters::HSLAMatrix(matrix); } bool SkColorFilter_Matrix::onAsAColorMatrix(float matrix[20]) const { if (matrix) { memcpy(matrix, fMatrix, 20 * sizeof(float)); } return true; } bool SkColorFilter_Matrix::onAppendStages(const SkStageRec& rec, bool shaderIsOpaque) const { const bool willStayOpaque = shaderIsOpaque && fAlphaIsUnchanged, hsla = fDomain == Domain::kHSLA; SkRasterPipeline* p = rec.fPipeline; if (!shaderIsOpaque) { p->append(SkRasterPipeline::unpremul); } if ( hsla) { p->append(SkRasterPipeline::rgb_to_hsl); } if ( true) { p->append(SkRasterPipeline::matrix_4x5, fMatrix); } if ( hsla) { p->append(SkRasterPipeline::hsl_to_rgb); } if ( true) { p->append(SkRasterPipeline::clamp_0); } if ( true) { p->append(SkRasterPipeline::clamp_1); } if (!willStayOpaque) { p->append(SkRasterPipeline::premul); } return true; } skvm::Color SkColorFilter_Matrix::onProgram(skvm::Builder* p, skvm::Color c, const SkColorInfo& /*dst*/, skvm::Uniforms* uniforms, SkArenaAlloc*) const { auto apply_matrix = [&](auto xyzw) { auto dot = [&](int j) { auto custom_mad = [&](float f, skvm::F32 m, skvm::F32 a) { // skvm::Builder won't fold f*0 == 0, but we shouldn't encounter NaN here. // While looking, also simplify f == ±1. Anything else becomes a uniform. return f == 0.0f ? a : f == +1.0f ? a + m : f == -1.0f ? a - m : m * p->uniformF(uniforms->pushF(f)) + a; }; // Similarly, let skvm::Builder fold away the additive bias when zero. const float b = fMatrix[4+j*5]; skvm::F32 bias = b == 0.0f ? p->splat(0.0f) : p->uniformF(uniforms->pushF(b)); auto [x,y,z,w] = xyzw; return custom_mad(fMatrix[0+j*5], x, custom_mad(fMatrix[1+j*5], y, custom_mad(fMatrix[2+j*5], z, custom_mad(fMatrix[3+j*5], w, bias)))); }; return std::make_tuple(dot(0), dot(1), dot(2), dot(3)); }; c = unpremul(c); if (fDomain == Domain::kHSLA) { auto [h,s,l,a] = apply_matrix(p->to_hsla(c)); c = p->to_rgba({h,s,l,a}); } else { auto [r,g,b,a] = apply_matrix(c); c = {r,g,b,a}; } return premul(clamp01(c)); } #if SK_SUPPORT_GPU #include "src/gpu/effects/GrSkSLFP.h" // Convert RGBA -> HSLA (including unpremul). // // Based on work by Sam Hocevar, Emil Persson, and Ian Taylor [1][2][3]. High-level ideas: // // - minimize the number of branches by sorting and computing the hue phase in parallel (vec4s) // // - trade the third sorting branch for a potentially faster std::min and leaving 2nd/3rd // channels unsorted (based on the observation that swapping both the channels and the bias sign // has no effect under abs) // // - use epsilon offsets for denominators, to avoid explicit zero-checks // // An additional trick we employ is deferring premul->unpremul conversion until the very end: the // alpha factor gets naturally simplified for H and S, and only L requires a dedicated unpremul // division (so we trade three divs for one). // // [1] http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv // [2] http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl // [3] http://www.chilliant.com/rgb2hsv.html static std::unique_ptr<GrFragmentProcessor> rgb_to_hsl(std::unique_ptr<GrFragmentProcessor> child) { static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"( half4 main(half4 c) { half4 p = (c.g < c.b) ? half4(c.bg, -1, 2/3.0) : half4(c.gb, 0, -1/3.0); half4 q = (c.r < p.x) ? half4(p.x, c.r, p.yw) : half4(c.r, p.x, p.yz); // q.x -> max channel value // q.yz -> 2nd/3rd channel values (unsorted) // q.w -> bias value dependent on max channel selection half eps = 0.0001; half pmV = q.x; half pmC = pmV - min(q.y, q.z); half pmL = pmV - pmC * 0.5; half H = abs(q.w + (q.y - q.z) / (pmC * 6 + eps)); half S = pmC / (c.a + eps - abs(pmL * 2 - c.a)); half L = pmL / (c.a + eps); return half4(H, S, L, c.a); } )"); return GrSkSLFP::Make( effect, "RgbToHsl", std::move(child), GrSkSLFP::OptFlags::kPreservesOpaqueInput); } // Convert HSLA -> RGBA (including clamp and premul). // // Based on work by Sam Hocevar, Emil Persson, and Ian Taylor [1][2][3]. // // [1] http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv // [2] http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl // [3] http://www.chilliant.com/rgb2hsv.html static std::unique_ptr<GrFragmentProcessor> hsl_to_rgb(std::unique_ptr<GrFragmentProcessor> child) { static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"( half4 main(half4 color) { half3 hsl = color.rgb; half C = (1 - abs(2 * hsl.z - 1)) * hsl.y; half3 p = hsl.xxx + half3(0, 2/3.0, 1/3.0); half3 q = saturate(abs(fract(p) * 6 - 3) - 1); half3 rgb = (q - 0.5) * C + hsl.z; color = saturate(half4(rgb, color.a)); color.rgb *= color.a; return color; } )"); return GrSkSLFP::Make( effect, "HslToRgb", std::move(child), GrSkSLFP::OptFlags::kPreservesOpaqueInput); } GrFPResult SkColorFilter_Matrix::asFragmentProcessor(std::unique_ptr<GrFragmentProcessor> fp, GrRecordingContext*, const GrColorInfo&) const { switch (fDomain) { case Domain::kRGBA: fp = GrFragmentProcessor::ColorMatrix(std::move(fp), fMatrix, /* unpremulInput = */ true, /* clampRGBOutput = */ true, /* premulOutput = */ true); break; case Domain::kHSLA: fp = rgb_to_hsl(std::move(fp)); fp = GrFragmentProcessor::ColorMatrix(std::move(fp), fMatrix, /* unpremulInput = */ false, /* clampRGBOutput = */ false, /* premulOutput = */ false); fp = hsl_to_rgb(std::move(fp)); break; } return GrFPSuccess(std::move(fp)); } #endif /////////////////////////////////////////////////////////////////////////////// static sk_sp<SkColorFilter> MakeMatrix(const float array[20], SkColorFilter_Matrix::Domain domain) { if (!sk_floats_are_finite(array, 20)) { return nullptr; } #if 1 return sk_make_sp<SkColorFilter_Matrix>(array, domain); #else const bool alphaUnchanged = SkScalarNearlyEqual(array[15], 0) && SkScalarNearlyEqual(array[16], 0) && SkScalarNearlyEqual(array[17], 0) && SkScalarNearlyEqual(array[18], 1) && SkScalarNearlyEqual(array[19], 0); struct { SkM44 m; SkV4 b; } uniforms; SkString code { "uniform half4x4 m;" "uniform half4 b;" }; if (domain == SkColorFilter_Matrix::Domain::kHSLA) { code += kRGB_to_HSL_sksl; code += kHSL_to_RGB_sksl; } code += "half4 main(half4 inColor) {"; if (true) { code += "half4 c = inColor;"; // unpremul } if (alphaUnchanged) { code += "half a = c.a;"; } if (domain == SkColorFilter_Matrix::Domain::kHSLA) { code += "c.rgb = rgb_to_hsl(c.rgb);"; } if (true) { uniforms.m = SkM44{array[ 0], array[ 1], array[ 2], array[ 3], array[ 5], array[ 6], array[ 7], array[ 8], array[10], array[11], array[12], array[13], array[15], array[16], array[17], array[18]}; uniforms.b = SkV4{array[4], array[9], array[14], array[19]}; code += "c = m*c + b;"; } if (domain == SkColorFilter_Matrix::Domain::kHSLA) { code += "c.rgb = hsl_to_rgb(c.rgb);"; } if (alphaUnchanged) { code += "return half4(saturate(c.rgb), a);"; } else { code += "return saturate(c);"; } code += "}"; sk_sp<SkRuntimeEffect> effect = SkMakeCachedRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, std::move(code)); SkASSERT(effect); SkAlphaType unpremul = kUnpremul_SkAlphaType; return SkColorFilters::WithWorkingFormat( effect->makeColorFilter(SkData::MakeWithCopy(&uniforms,sizeof(uniforms))), nullptr/*keep dst TF encoding*/, nullptr/*stay in dst gamut*/, &unpremul); #endif } sk_sp<SkColorFilter> SkColorFilters::Matrix(const float array[20]) { return MakeMatrix(array, SkColorFilter_Matrix::Domain::kRGBA); } sk_sp<SkColorFilter> SkColorFilters::Matrix(const SkColorMatrix& cm) { return MakeMatrix(cm.fMat.data(), SkColorFilter_Matrix::Domain::kRGBA); } sk_sp<SkColorFilter> SkColorFilters::HSLAMatrix(const float array[20]) { return MakeMatrix(array, SkColorFilter_Matrix::Domain::kHSLA); } sk_sp<SkColorFilter> SkColorFilters::HSLAMatrix(const SkColorMatrix& cm) { return MakeMatrix(cm.fMat.data(), SkColorFilter_Matrix::Domain::kHSLA); } void SkColorFilter_Matrix::RegisterFlattenables() { SK_REGISTER_FLATTENABLE(SkColorFilter_Matrix); // This subclass was removed 4/2019 SkFlattenable::Register("SkColorMatrixFilterRowMajor255", [](SkReadBuffer& buffer) -> sk_sp<SkFlattenable> { float matrix[20]; if (buffer.readScalarArray(matrix, 20)) { matrix[ 4] *= (1.0f/255); matrix[ 9] *= (1.0f/255); matrix[14] *= (1.0f/255); matrix[19] *= (1.0f/255); return SkColorFilters::Matrix(matrix); } return nullptr; }); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <configuration.h> #include <string.h> #include <string> #include <stdlib.h> using namespace std; int main(int argc, char **argv) { // Select the proper storage.json file for the tests string foglamp_root = getenv("FOGLAMP_ROOT"); string foglamp_data = foglamp_root + "/tests/unit/C/services/storage/postgres"; setenv("FOGLAMP_DATA", foglamp_data.c_str(), 1 ); testing::InitGoogleTest(&argc, argv); testing::GTEST_FLAG(repeat) = 5000; testing::GTEST_FLAG(shuffle) = true; testing::GTEST_FLAG(break_on_failure) = true; return RUN_ALL_TESTS(); } /** * Test retrieval of port from default */ TEST(ConfigurationTest, getport) { StorageConfiguration conf; ASSERT_EQ(strcmp(conf.getValue(string("port")), "8080"), 0); } /** * Test retrieval of plugin from default */ TEST(ConfigurationTest, getplugin) { StorageConfiguration conf; ASSERT_EQ(strcmp(conf.getValue(string("plugin")), "postgres"), 0); } /** * Test setting of port */ TEST(ConfigurationTest, setport) { StorageConfiguration conf; ASSERT_EQ(true, conf.setValue(string("port"), string("8188"))); ASSERT_EQ(strcmp(conf.getValue(string("port")), "8188"), 0); } <commit_msg>FOGL-2650: repeat to 1000<commit_after>#include <gtest/gtest.h> #include <configuration.h> #include <string.h> #include <string> #include <stdlib.h> using namespace std; int main(int argc, char **argv) { // Select the proper storage.json file for the tests string foglamp_root = getenv("FOGLAMP_ROOT"); string foglamp_data = foglamp_root + "/tests/unit/C/services/storage/postgres"; setenv("FOGLAMP_DATA", foglamp_data.c_str(), 1 ); testing::InitGoogleTest(&argc, argv); testing::GTEST_FLAG(repeat) = 1000; testing::GTEST_FLAG(shuffle) = true; testing::GTEST_FLAG(break_on_failure) = true; return RUN_ALL_TESTS(); } /** * Test retrieval of port from default */ TEST(ConfigurationTest, getport) { StorageConfiguration conf; ASSERT_EQ(strcmp(conf.getValue(string("port")), "8080"), 0); } /** * Test retrieval of plugin from default */ TEST(ConfigurationTest, getplugin) { StorageConfiguration conf; ASSERT_EQ(strcmp(conf.getValue(string("plugin")), "postgres"), 0); } /** * Test setting of port */ TEST(ConfigurationTest, setport) { StorageConfiguration conf; ASSERT_EQ(true, conf.setValue(string("port"), string("8188"))); ASSERT_EQ(strcmp(conf.getValue(string("port")), "8188"), 0); } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. 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 <QtGui> #include <Interface/Modules/Base/HasParserHelpDialog.h> using namespace SCIRun::Gui; void ModuleDialogWithParserHelp::popUpParserHelp() { if (!help_) help_ = new ParserHelpDialog(this); help_->show(); help_->activateWindow(); help_->raise(); help_->move(10,10); } void ModuleDialogWithParserHelp::connectParserHelpButton(QPushButton* button) { connect(button, SIGNAL(clicked()), this, SLOT(popUpParserHelp())); } ParserHelpDialog::ParserHelpDialog(QWidget* parent) : QDialog(parent) { setupUi(this); connect(searchLineEdit_, SIGNAL(returnPressed()), this, SLOT(searchText())); connect(searchButton_, SIGNAL(clicked()), this, SLOT(searchText())); } void ParserHelpDialog::searchText() { if(!textBrowser_->find(searchLineEdit_->text())) { auto cursor = textBrowser_->textCursor(); cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor); textBrowser_->setTextCursor(cursor); } return; } <commit_msg>Create new ParserHelpDialog everytime<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. 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 <QtGui> #include <Interface/Modules/Base/HasParserHelpDialog.h> using namespace SCIRun::Gui; void ModuleDialogWithParserHelp::popUpParserHelp() { help_ = new ParserHelpDialog(this); help_->show(); help_->activateWindow(); help_->raise(); help_->move(10,10); } void ModuleDialogWithParserHelp::connectParserHelpButton(QPushButton* button) { connect(button, SIGNAL(clicked()), this, SLOT(popUpParserHelp())); } ParserHelpDialog::ParserHelpDialog(QWidget* parent) : QDialog(parent) { setupUi(this); connect(searchLineEdit_, SIGNAL(returnPressed()), this, SLOT(searchText())); connect(searchButton_, SIGNAL(clicked()), this, SLOT(searchText())); } void ParserHelpDialog::searchText() { if(!textBrowser_->find(searchLineEdit_->text())) { auto cursor = textBrowser_->textCursor(); cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor); textBrowser_->setTextCursor(cursor); } return; } <|endoftext|>
<commit_before>#include "COLLIDE.H" #include "SPECIFIC.H" long zfront; long xfront; short GlobalCollisionBounds[6]; char LM[15]; void TestForObjectOnLedge(struct ITEM_INFO *item, struct COLL_INFO *coll)//2A940, 2AB68 { S_Warn("[TestForObjectOnLedge] - Unimplemented!\n"); } void TriggerLaraBlood()//2A838, 2AA60 { S_Warn("[TriggerLaraBlood] - Unimplemented!\n"); } void GenericSphereBoxCollision(short item_num, struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//2A5EC, 2A814 { S_Warn("[GenericSphereBoxCollision] - Unimplemented!\n"); } int ItemPushLaraStatic(struct ITEM_INFO *laraitem, short *bounds, struct PHD_3DPOS *pos, struct COLL_INFO *coll)//2A2D8, 2A500 { S_Warn("[ItemPushLaraStatic] - Unimplemented!\n"); return 0; } int TestBoundsCollideStatic(short *bounds, struct PHD_3DPOS *pos, long radius)//2A140, 2A368 { S_Warn("[TestBoundsCollideStatic] - Unimplemented!\n"); return 0; } void TrapCollision(short item_num, struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//2A098, 2A2C0 { S_Warn("[TrapCollision] - Unimplemented!\n"); } void AIPickupCollision(short item_num, struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//2A03C, 2A264 { S_Warn("[AIPickupCollision] - Unimplemented!\n"); } void CreatureCollision(short item_num, struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//29E10, 2A024 { S_Warn("[CreatureCollision] - Unimplemented!\n"); } void LaraBaddieCollision(struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//29A44, 29C58 { S_Warn("[LaraBaddieCollision] - Unimplemented!\n"); } <commit_msg>COLLIDE.C init globals.<commit_after>#include "COLLIDE.H" #include "SPECIFIC.H" long zfront; long xfront; short GlobalCollisionBounds[6]; char LM[] = { 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 8 }; void TestForObjectOnLedge(struct ITEM_INFO *item, struct COLL_INFO *coll)//2A940, 2AB68 { S_Warn("[TestForObjectOnLedge] - Unimplemented!\n"); } void TriggerLaraBlood()//2A838, 2AA60 { S_Warn("[TriggerLaraBlood] - Unimplemented!\n"); } void GenericSphereBoxCollision(short item_num, struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//2A5EC, 2A814 { S_Warn("[GenericSphereBoxCollision] - Unimplemented!\n"); } int ItemPushLaraStatic(struct ITEM_INFO *laraitem, short *bounds, struct PHD_3DPOS *pos, struct COLL_INFO *coll)//2A2D8, 2A500 { S_Warn("[ItemPushLaraStatic] - Unimplemented!\n"); return 0; } int TestBoundsCollideStatic(short *bounds, struct PHD_3DPOS *pos, long radius)//2A140, 2A368 { S_Warn("[TestBoundsCollideStatic] - Unimplemented!\n"); return 0; } void TrapCollision(short item_num, struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//2A098, 2A2C0 { S_Warn("[TrapCollision] - Unimplemented!\n"); } void AIPickupCollision(short item_num, struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//2A03C, 2A264 { S_Warn("[AIPickupCollision] - Unimplemented!\n"); } void CreatureCollision(short item_num, struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//29E10, 2A024 { S_Warn("[CreatureCollision] - Unimplemented!\n"); } void LaraBaddieCollision(struct ITEM_INFO *laraitem, struct COLL_INFO *coll)//29A44, 29C58 { S_Warn("[LaraBaddieCollision] - Unimplemented!\n"); } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2018 Intel Corporation * * 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 <cstring> #include "ngraph/op/dot.hpp" #include "ngraph/runtime/cpu/cpu_builder.hpp" #include "ngraph/runtime/cpu/kernel/dot.hpp" using namespace std; using namespace ngraph; namespace ngraph { namespace runtime { namespace cpu { template <> void Builder::BUILDER_DECL(ngraph::op::Dot) { auto dot = static_cast<const ngraph::op::Dot*>(node); auto& functors = external_function->get_functors(); auto arg0_shape = args[0].get_shape(); auto arg1_shape = args[1].get_shape(); auto result_shape = out[0].get_shape(); auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name()); auto& arg1_tensor = external_function->get_tensor_data(args[1].get_name()); auto& out_tensor = external_function->get_tensor_data(out[0].get_name()); auto reduction_axes_count = dot->get_reduction_axes_count(); if (!shape_size(result_shape)) { auto functor = [](CPURuntimeContext* ctx) {}; functors.emplace_back(functor); return; } if (!shape_size(arg0_shape) || !shape_size(arg1_shape)) { auto size = shape_size(result_shape) * out[0].get_element_type().size(); auto functor = [&, size](CPURuntimeContext* ctx) { memset(out_tensor, 0, size); }; functors.emplace_back(functor); return; } if (arg0_shape.empty() || arg1_shape.empty()) { auto first = (arg0_shape.empty() ? args[0] : args[1]); auto second = (arg0_shape.empty() ? args[1] : args[0]); auto& first_tensor = external_function->get_tensor_data(first.get_name()); auto& second_tensor = external_function->get_tensor_data(second.get_name()); std::function<decltype(runtime::cpu::kernel::dot_scalar<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_scalar); auto element_count = shape_size(second.get_shape()); auto functor = [&, kernel, element_count](CPURuntimeContext* ctx) { kernel(first_tensor, second_tensor, out_tensor, element_count); }; functors.emplace_back(functor); return; } if ((arg0_shape.size() == 1) && (arg1_shape.size() == 1) && reduction_axes_count == 1) { std::function<decltype(runtime::cpu::kernel::dot_1d_1d_1rd<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_1d_1d_1rd); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape](CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape); }; functors.emplace_back(functor); return; } if ((arg0_shape.size() == 2) && (arg1_shape.size() == 1) && reduction_axes_count == 1) { std::function<decltype(runtime::cpu::kernel::dot_2d_1d_1rd<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_2d_1d_1rd); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape](CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape); }; functors.emplace_back(functor); return; } if ((arg0_shape.size() == 3) && (arg1_shape.size() == 3) && reduction_axes_count == 1) { std::function<decltype(runtime::cpu::kernel::dot_3d_3d_1rd<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_3d_3d_1rd); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape](CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape); }; functors.emplace_back(functor); return; } if ((arg0_shape.size() == 3) && (arg1_shape.size() == 2) && reduction_axes_count == 1) { std::function<decltype(runtime::cpu::kernel::dot_3d_2d_1rd<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_3d_2d_1rd); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape](CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape); }; functors.emplace_back(functor); return; } std::function<decltype(runtime::cpu::kernel::dot<float>)> kernel; SELECT_KERNEL(kernel, out[0].get_element_type(), runtime::cpu::kernel::dot); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape, reduction_axes_count]( CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape, reduction_axes_count); }; functors.emplace_back(functor); } REGISTER_OP_BUILDER(Dot); } } } <commit_msg>DEX SGEMM batch for rank-3 rank-2 dot (#1425)<commit_after>/******************************************************************************* * Copyright 2018 Intel Corporation * * 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 <cstring> #include "ngraph/op/dot.hpp" #include "ngraph/runtime/cpu/cpu_builder.hpp" #include "ngraph/runtime/cpu/cpu_kernels.hpp" #include "ngraph/runtime/cpu/kernel/dot.hpp" using namespace std; using namespace ngraph; namespace ngraph { namespace runtime { namespace cpu { template <> void Builder::BUILDER_DECL(ngraph::op::Dot) { auto dot = static_cast<const ngraph::op::Dot*>(node); auto& functors = external_function->get_functors(); auto arg0_shape = args[0].get_shape(); auto arg1_shape = args[1].get_shape(); auto result_shape = out[0].get_shape(); auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name()); auto& arg1_tensor = external_function->get_tensor_data(args[1].get_name()); auto& out_tensor = external_function->get_tensor_data(out[0].get_name()); auto reduction_axes_count = dot->get_reduction_axes_count(); if (!shape_size(result_shape)) { auto functor = [](CPURuntimeContext* ctx) {}; functors.emplace_back(functor); return; } if (!shape_size(arg0_shape) || !shape_size(arg1_shape)) { auto size = shape_size(result_shape) * out[0].get_element_type().size(); auto functor = [&, size](CPURuntimeContext* ctx) { memset(out_tensor, 0, size); }; functors.emplace_back(functor); return; } if (arg0_shape.empty() || arg1_shape.empty()) { auto first = (arg0_shape.empty() ? args[0] : args[1]); auto second = (arg0_shape.empty() ? args[1] : args[0]); auto& first_tensor = external_function->get_tensor_data(first.get_name()); auto& second_tensor = external_function->get_tensor_data(second.get_name()); std::function<decltype(runtime::cpu::kernel::dot_scalar<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_scalar); auto element_count = shape_size(second.get_shape()); auto functor = [&, kernel, element_count](CPURuntimeContext* ctx) { kernel(first_tensor, second_tensor, out_tensor, element_count); }; functors.emplace_back(functor); return; } if ((arg0_shape.size() == 1) && (arg1_shape.size() == 1) && reduction_axes_count == 1) { std::function<decltype(runtime::cpu::kernel::dot_1d_1d_1rd<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_1d_1d_1rd); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape](CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape); }; functors.emplace_back(functor); return; } if ((arg0_shape.size() == 2) && (arg1_shape.size() == 1) && reduction_axes_count == 1) { std::function<decltype(runtime::cpu::kernel::dot_2d_1d_1rd<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_2d_1d_1rd); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape](CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape); }; functors.emplace_back(functor); return; } if ((arg0_shape.size() == 3) && (arg1_shape.size() == 3) && reduction_axes_count == 1) { std::function<decltype(runtime::cpu::kernel::dot_3d_3d_1rd<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_3d_3d_1rd); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape](CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape); }; functors.emplace_back(functor); return; } if ((arg0_shape.size() == 3) && (arg1_shape.size() == 2) && reduction_axes_count == 1) { if (args[0].get_element_type() == element::f32) { auto shape_a = args[0].get_shape(); auto shape_b = args[1].get_shape(); const int64_t m = shape_a[1]; const int64_t k = shape_a[2]; const int64_t n = shape_b[1]; // this also works when mat_a is shape (1, m, k) const int64_t offset_a = m * k; // we do not offset mat_b const int64_t offset_b = 0; const int64_t offset_c = m * n; const int64_t group_count = 1; const int64_t group_size = shape_a[0]; auto functor = [&, offset_a, offset_b, offset_c, m, n, k, group_size, group_count]( CPURuntimeContext* ctx) { cblas::Transpose transpose = cblas::Transpose::None; float alpha = 1.0f; vector<const float*> a; for (size_t i = 0; i < group_size; i++) { a.emplace_back(static_cast<const float*>(arg0_tensor) + i * offset_a); } const float** a_array = a.data(); int64_t lda_array = std::max(1L, k); vector<const float*> b; for (size_t i = 0; i < group_size; i++) { b.emplace_back(static_cast<const float*>(arg1_tensor) + i * offset_b); } const float** b_array = b.data(); const int64_t ldb_array = std::max(1L, n); float beta = 0.0f; vector<float*> c; for (size_t i = 0; i < group_size; i++) { c.emplace_back(static_cast<float*>(out_tensor) + i * offset_c); } float** c_array = c.data(); const int64_t ldc_array = std::max(1L, n); cblas_sgemm_batch(cblas::Layout::RowMajor, &transpose, &transpose, &m, &n, &k, &alpha, a_array, &lda_array, b_array, &ldb_array, &beta, c_array, &ldc_array, group_count, &group_size); }; functors.emplace_back(functor); return; } else { std::function<decltype(runtime::cpu::kernel::dot_3d_2d_1rd<float>)> kernel; SELECT_KERNEL( kernel, out[0].get_element_type(), runtime::cpu::kernel::dot_3d_2d_1rd); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape]( CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape); }; functors.emplace_back(functor); return; } } std::function<decltype(runtime::cpu::kernel::dot<float>)> kernel; SELECT_KERNEL(kernel, out[0].get_element_type(), runtime::cpu::kernel::dot); auto functor = [&, kernel, arg0_shape, arg1_shape, result_shape, reduction_axes_count]( CPURuntimeContext* ctx) { kernel(arg0_tensor, arg1_tensor, out_tensor, arg0_shape, arg1_shape, result_shape, reduction_axes_count); }; functors.emplace_back(functor); } REGISTER_OP_BUILDER(Dot); } } } <|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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. //***************************************************************************** #pragma once #include <string> #include <vector> #include "ngraph/node.hpp" #include "ngraph/runtime/cpu/cpu_external_function.hpp" #include "ngraph/runtime/cpu/cpu_tensor_view_wrapper.hpp" #define BUILDER_DECL(op_name) \ build<op_name>(CPU_ExternalFunction * external_function, \ const ngraph::Node* node, \ const std::vector<TensorViewWrapper>& args, \ const std::vector<TensorViewWrapper>& out) // Per-type kernel macro #define SELECT_KERNEL(KV, ET, K) \ if (ET == element::boolean) \ { \ KV = K<char>; \ } \ else if (ET == element::f32) \ { \ KV = K<float>; \ } \ else if (ET == element::f64) \ { \ KV = K<double>; \ } \ else if (ET == element::i8) \ { \ KV = K<int8_t>; \ } \ else if (ET == element::i16) \ { \ KV = K<int16_t>; \ } \ else if (ET == element::i32) \ { \ KV = K<int32_t>; \ } \ else if (ET == element::i64) \ { \ KV = K<int64_t>; \ } \ else if (ET == element::u8) \ { \ KV = K<uint8_t>; \ } \ else if (ET == element::u16) \ { \ KV = K<uint16_t>; \ } \ else if (ET == element::u32) \ { \ KV = K<uint32_t>; \ } \ else if (ET == element::u64) \ { \ KV = K<uint64_t>; \ } #define SELECT_RANK(KV, ET, R, K) \ if (R == 1) \ KV = K<ET, 1>; \ else if (R == 2) \ KV = K<ET, 2>; \ else if (R == 3) \ KV = K<ET, 3>; \ else if (R == 4) \ KV = K<ET, 4>; \ else if (R == 5) \ KV = K<ET, 5>; \ else if (R == 6) \ KV = K<ET, 6>; \ else if (R == 7) \ KV = K<ET, 7>; \ else \ throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K); #define SELECT_RANK2(KV, IT, OT, R, K) \ switch (R) \ { \ case 1: KV = K<IT, OT, 1>; break; \ case 2: KV = K<IT, OT, 2>; break; \ case 3: KV = K<IT, OT, 3>; break; \ case 4: KV = K<IT, OT, 4>; break; \ case 5: KV = K<IT, OT, 5>; break; \ case 6: KV = K<IT, OT, 6>; break; \ case 7: KV = K<IT, OT, 7>; break; \ default: throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K); \ } // Per-type and rank kernel macro #define SELECT_KERNEL_BY_RANK(KV, ET, R, K) \ if (ET == element::boolean) \ { \ SELECT_RANK(KV, char, R, K); \ } \ else if (ET == element::f32) \ { \ SELECT_RANK(KV, float, R, K); \ } \ else if (ET == element::f64) \ { \ SELECT_RANK(KV, double, R, K); \ } \ else if (ET == element::i8) \ { \ SELECT_RANK(KV, int8_t, R, K); \ } \ else if (ET == element::i16) \ { \ SELECT_RANK(KV, int16_t, R, K); \ } \ else if (ET == element::i32) \ { \ SELECT_RANK(KV, int32_t, R, K); \ } \ else if (ET == element::i64) \ { \ SELECT_RANK(KV, int64_t, R, K); \ } \ else if (ET == element::u8) \ { \ SELECT_RANK(KV, uint8_t, R, K); \ } \ else if (ET == element::u16) \ { \ SELECT_RANK(KV, uint16_t, R, K); \ } \ else if (ET == element::u32) \ { \ SELECT_RANK(KV, uint32_t, R, K); \ } \ else if (ET == element::u64) \ { \ SELECT_RANK(KV, uint64_t, R, K); \ } \ else \ { \ throw ngraph_error("Unsupported element type " + ET.c_type_string() + " for kernel " #K); \ } // Helper macros for a partial set of element types and ranks // Useful for keeping compilation time and memory usage reasonable // when the computed expression is complex #define PARTIAL_SELECT_RANK(KV, ET, R, K) \ if (R == 1) \ KV = K<ET, 1>; \ else if (R == 2) \ KV = K<ET, 2>; \ else if (R == 3) \ KV = K<ET, 3>; \ else if (R == 4) \ KV = K<ET, 4>; \ else if (R == 5) \ KV = K<ET, 5>; \ else if (R == 6) \ KV = K<ET, 6>; \ else \ throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K); // Partial per-type and rank kernel macro #define PARTIAL_SELECT_KERNEL_BY_RANK(KV, ET, R, K) \ if (ET == element::f32) \ { \ PARTIAL_SELECT_RANK(KV, float, R, K); \ } \ else if (ET == element::f64) \ { \ PARTIAL_SELECT_RANK(KV, double, R, K); \ } \ else if (ET == element::i8) \ { \ PARTIAL_SELECT_RANK(KV, int8_t, R, K); \ } \ else if (ET == element::u8) \ { \ PARTIAL_SELECT_RANK(KV, uint8_t, R, K); \ } \ else \ { \ throw ngraph_error("Unsupported element type " + ET.c_type_string() + " for kernel " #K); \ } #define BUILD_UNARY_ELEMWISE_FUNCTOR(OP) \ auto& functors = external_function->get_functors(); \ std::function<void(void*, void*, size_t, int)> kernel; \ \ SELECT_KERNEL(kernel, args[0].get_element_type(), OP); \ \ auto element_count = out[0].get_size(); \ auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name()); \ auto& out0_tensor = external_function->get_tensor_data(out[0].get_name()); \ \ auto functor = [&, kernel, element_count](CPURuntimeContext* ctx, CPUExecutionContext* ectx) { \ kernel(arg0_tensor, out0_tensor, element_count, ectx->arena); \ }; \ functors.emplace_back(functor); #define BUILD_BINARY_ELEMWISE_FUNCTOR(OP) \ auto& functors = external_function->get_functors(); \ std::function<void(void*, void*, void*, size_t, int)> kernel; \ \ SELECT_KERNEL(kernel, args[0].get_element_type(), OP); \ \ auto element_count = out[0].get_size(); \ auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name()); \ auto& arg1_tensor = external_function->get_tensor_data(args[1].get_name()); \ auto& out0_tensor = external_function->get_tensor_data(out[0].get_name()); \ \ auto functor = [&, kernel, element_count](CPURuntimeContext* ctx, CPUExecutionContext* ectx) { \ kernel(arg0_tensor, arg1_tensor, out0_tensor, element_count, ectx->arena); \ }; \ functors.emplace_back(functor); #define BUILD_UNARY_ELEMWISE_CF_FUNCTOR(OP) \ std::function<void(void*, void*, size_t, int)> kernel; \ \ SELECT_KERNEL(kernel, node->get_input_element_type(0), OP); \ \ auto element_count = shape_size(node->get_shape()); \ \ auto functor = [&, kernel, element_count](const std::vector<void*>& inputs, \ std::vector<void*>& outputs) { \ kernel(inputs[0], outputs[0], element_count, 0); \ }; \ return functor; #define BUILD_BINARY_ELEMWISE_CF_FUNCTOR(OP) \ std::function<void(void*, void*, void*, size_t, int)> kernel; \ \ SELECT_KERNEL(kernel, node->get_input_element_type(0), OP); \ \ auto element_count = shape_size(node->get_shape()); \ \ auto functor = [&, kernel, element_count](const std::vector<void*>& inputs, \ std::vector<void*>& outputs) { \ kernel(inputs[0], inputs[1], outputs[0], element_count, 0); \ }; \ return functor; #define REGISTER_OP_BUILDER(OP) \ static struct __register_##OP##_builder \ { \ __register_##OP##_builder() \ { \ GetGlobalBuildDispatcher().insert({type_index(typeid(ngraph::op::OP)), \ &runtime::cpu::Builder::build<ngraph::op::OP>}); \ } \ } __register_##OP##_builder_instance; #define REGISTER_CPU_OP_BUILDER(OP) \ static struct __register_##OP##_builder \ { \ __register_##OP##_builder() \ { \ GetGlobalBuildDispatcher().insert( \ {type_index(typeid(ngraph::runtime::cpu::op::OP)), \ &runtime::cpu::Builder::build<ngraph::runtime::cpu::op::OP>}); \ } \ } __register_##OP##_builder_instance; #define BUILDER_CF_DECL(op_name) CFbuild<op_name>(const ngraph::Node* node) #define REGISTER_CF_BUILDER(OP) \ static struct __register_##OP##_cf_builder \ { \ __register_##OP##_cf_builder() \ { \ GetGlobalCFDispatcherCPU().insert({type_index(typeid(ngraph::op::OP)), \ &runtime::cpu::Builder::CFbuild<ngraph::op::OP>}); \ } \ } __register_##OP##_cf_builder_instance; #define REGISTER_CPU_CF_BUILDER(OP) \ static struct __register_##OP##_cf_builder \ { \ __register_##OP##_cf_builder() \ { \ GetGlobalCFDispatcherCPU().insert( \ {type_index(typeid(ngraph::runtime::cpu::op::OP)), \ &runtime::cpu::Builder::CFbuild<ngraph::runtime::cpu::op::OP>}); \ } \ } __register_##OP##_cf_builder_instance; namespace ngraph { namespace runtime { namespace cpu { using BuildOpFunction = std::function<void(CPU_ExternalFunction* external_function, const ngraph::Node*, const std::vector<TensorViewWrapper>& inputs, const std::vector<TensorViewWrapper>& outputs)>; using BuildOpMap = std::unordered_map<std::type_index, BuildOpFunction>; BuildOpMap& GetGlobalBuildDispatcher(); // build the map to use cpu kernel for node execution BuildNodeExecutorMap& GetGlobalCFDispatcherCPU(); class Builder { public: template <typename OP> static void build(CPU_ExternalFunction* external_function, const ngraph::Node* node, const std::vector<TensorViewWrapper>& args, const std::vector<TensorViewWrapper>& out) { throw unsupported_op("Unimplemented op '" + node->description() + "' in CPU builder"); } template <typename OP> static NodeExecutorTy CFbuild(const ngraph::Node* node) { throw unsupported_op("Unimplemented op '" + node->description() + "' for constant folding in CPU builder"); } static void nop(CPU_ExternalFunction* external_function, const ngraph::Node* node, const std::vector<TensorViewWrapper>& args, const std::vector<TensorViewWrapper>& out) { } }; } } } <commit_msg>Fix unresolved symbol in cpu backend on Windows. (#2723)<commit_after>//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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. //***************************************************************************** #pragma once #include <string> #include <vector> #include "ngraph/node.hpp" #include "ngraph/runtime/cpu/cpu_external_function.hpp" #include "ngraph/runtime/cpu/cpu_tensor_view_wrapper.hpp" #define BUILDER_DECL(op_name) \ build<op_name>(CPU_ExternalFunction * external_function, \ const ngraph::Node* node, \ const std::vector<TensorViewWrapper>& args, \ const std::vector<TensorViewWrapper>& out) // Per-type kernel macro #define SELECT_KERNEL(KV, ET, K) \ if (ET == element::boolean) \ { \ KV = K<char>; \ } \ else if (ET == element::f32) \ { \ KV = K<float>; \ } \ else if (ET == element::f64) \ { \ KV = K<double>; \ } \ else if (ET == element::i8) \ { \ KV = K<int8_t>; \ } \ else if (ET == element::i16) \ { \ KV = K<int16_t>; \ } \ else if (ET == element::i32) \ { \ KV = K<int32_t>; \ } \ else if (ET == element::i64) \ { \ KV = K<int64_t>; \ } \ else if (ET == element::u8) \ { \ KV = K<uint8_t>; \ } \ else if (ET == element::u16) \ { \ KV = K<uint16_t>; \ } \ else if (ET == element::u32) \ { \ KV = K<uint32_t>; \ } \ else if (ET == element::u64) \ { \ KV = K<uint64_t>; \ } #define SELECT_RANK(KV, ET, R, K) \ if (R == 1) \ KV = K<ET, 1>; \ else if (R == 2) \ KV = K<ET, 2>; \ else if (R == 3) \ KV = K<ET, 3>; \ else if (R == 4) \ KV = K<ET, 4>; \ else if (R == 5) \ KV = K<ET, 5>; \ else if (R == 6) \ KV = K<ET, 6>; \ else if (R == 7) \ KV = K<ET, 7>; \ else \ throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K); #define SELECT_RANK2(KV, IT, OT, R, K) \ switch (R) \ { \ case 1: KV = K<IT, OT, 1>; break; \ case 2: KV = K<IT, OT, 2>; break; \ case 3: KV = K<IT, OT, 3>; break; \ case 4: KV = K<IT, OT, 4>; break; \ case 5: KV = K<IT, OT, 5>; break; \ case 6: KV = K<IT, OT, 6>; break; \ case 7: KV = K<IT, OT, 7>; break; \ default: throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K); \ } // Per-type and rank kernel macro #define SELECT_KERNEL_BY_RANK(KV, ET, R, K) \ if (ET == element::boolean) \ { \ SELECT_RANK(KV, char, R, K); \ } \ else if (ET == element::f32) \ { \ SELECT_RANK(KV, float, R, K); \ } \ else if (ET == element::f64) \ { \ SELECT_RANK(KV, double, R, K); \ } \ else if (ET == element::i8) \ { \ SELECT_RANK(KV, int8_t, R, K); \ } \ else if (ET == element::i16) \ { \ SELECT_RANK(KV, int16_t, R, K); \ } \ else if (ET == element::i32) \ { \ SELECT_RANK(KV, int32_t, R, K); \ } \ else if (ET == element::i64) \ { \ SELECT_RANK(KV, int64_t, R, K); \ } \ else if (ET == element::u8) \ { \ SELECT_RANK(KV, uint8_t, R, K); \ } \ else if (ET == element::u16) \ { \ SELECT_RANK(KV, uint16_t, R, K); \ } \ else if (ET == element::u32) \ { \ SELECT_RANK(KV, uint32_t, R, K); \ } \ else if (ET == element::u64) \ { \ SELECT_RANK(KV, uint64_t, R, K); \ } \ else \ { \ throw ngraph_error("Unsupported element type " + ET.c_type_string() + " for kernel " #K); \ } // Helper macros for a partial set of element types and ranks // Useful for keeping compilation time and memory usage reasonable // when the computed expression is complex #define PARTIAL_SELECT_RANK(KV, ET, R, K) \ if (R == 1) \ KV = K<ET, 1>; \ else if (R == 2) \ KV = K<ET, 2>; \ else if (R == 3) \ KV = K<ET, 3>; \ else if (R == 4) \ KV = K<ET, 4>; \ else if (R == 5) \ KV = K<ET, 5>; \ else if (R == 6) \ KV = K<ET, 6>; \ else \ throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K); // Partial per-type and rank kernel macro #define PARTIAL_SELECT_KERNEL_BY_RANK(KV, ET, R, K) \ if (ET == element::f32) \ { \ PARTIAL_SELECT_RANK(KV, float, R, K); \ } \ else if (ET == element::f64) \ { \ PARTIAL_SELECT_RANK(KV, double, R, K); \ } \ else if (ET == element::i8) \ { \ PARTIAL_SELECT_RANK(KV, int8_t, R, K); \ } \ else if (ET == element::u8) \ { \ PARTIAL_SELECT_RANK(KV, uint8_t, R, K); \ } \ else \ { \ throw ngraph_error("Unsupported element type " + ET.c_type_string() + " for kernel " #K); \ } #define BUILD_UNARY_ELEMWISE_FUNCTOR(OP) \ auto& functors = external_function->get_functors(); \ std::function<void(void*, void*, size_t, int)> kernel; \ \ SELECT_KERNEL(kernel, args[0].get_element_type(), OP); \ \ auto element_count = out[0].get_size(); \ auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name()); \ auto& out0_tensor = external_function->get_tensor_data(out[0].get_name()); \ \ auto functor = [&, kernel, element_count](CPURuntimeContext* ctx, CPUExecutionContext* ectx) { \ kernel(arg0_tensor, out0_tensor, element_count, ectx->arena); \ }; \ functors.emplace_back(functor); #define BUILD_BINARY_ELEMWISE_FUNCTOR(OP) \ auto& functors = external_function->get_functors(); \ std::function<void(void*, void*, void*, size_t, int)> kernel; \ \ SELECT_KERNEL(kernel, args[0].get_element_type(), OP); \ \ auto element_count = out[0].get_size(); \ auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name()); \ auto& arg1_tensor = external_function->get_tensor_data(args[1].get_name()); \ auto& out0_tensor = external_function->get_tensor_data(out[0].get_name()); \ \ auto functor = [&, kernel, element_count](CPURuntimeContext* ctx, CPUExecutionContext* ectx) { \ kernel(arg0_tensor, arg1_tensor, out0_tensor, element_count, ectx->arena); \ }; \ functors.emplace_back(functor); #define BUILD_UNARY_ELEMWISE_CF_FUNCTOR(OP) \ std::function<void(void*, void*, size_t, int)> kernel; \ \ SELECT_KERNEL(kernel, node->get_input_element_type(0), OP); \ \ auto element_count = shape_size(node->get_shape()); \ \ auto functor = [&, kernel, element_count](const std::vector<void*>& inputs, \ std::vector<void*>& outputs) { \ kernel(inputs[0], outputs[0], element_count, 0); \ }; \ return functor; #define BUILD_BINARY_ELEMWISE_CF_FUNCTOR(OP) \ std::function<void(void*, void*, void*, size_t, int)> kernel; \ \ SELECT_KERNEL(kernel, node->get_input_element_type(0), OP); \ \ auto element_count = shape_size(node->get_shape()); \ \ auto functor = [&, kernel, element_count](const std::vector<void*>& inputs, \ std::vector<void*>& outputs) { \ kernel(inputs[0], inputs[1], outputs[0], element_count, 0); \ }; \ return functor; #define REGISTER_OP_BUILDER(OP) \ static struct __register_##OP##_builder \ { \ __register_##OP##_builder() \ { \ GetGlobalBuildDispatcher().insert({type_index(typeid(ngraph::op::OP)), \ &runtime::cpu::Builder::build<ngraph::op::OP>}); \ } \ } __register_##OP##_builder_instance; #define REGISTER_CPU_OP_BUILDER(OP) \ static struct __register_##OP##_builder \ { \ __register_##OP##_builder() \ { \ GetGlobalBuildDispatcher().insert( \ {type_index(typeid(ngraph::runtime::cpu::op::OP)), \ &runtime::cpu::Builder::build<ngraph::runtime::cpu::op::OP>}); \ } \ } __register_##OP##_builder_instance; #define BUILDER_CF_DECL(op_name) CFbuild<op_name>(const ngraph::Node* node) #define REGISTER_CF_BUILDER(OP) \ static struct __register_##OP##_cf_builder \ { \ __register_##OP##_cf_builder() \ { \ GetGlobalCFDispatcherCPU().insert({type_index(typeid(ngraph::op::OP)), \ &runtime::cpu::Builder::CFbuild<ngraph::op::OP>}); \ } \ } __register_##OP##_cf_builder_instance; #define REGISTER_CPU_CF_BUILDER(OP) \ static struct __register_##OP##_cf_builder \ { \ __register_##OP##_cf_builder() \ { \ GetGlobalCFDispatcherCPU().insert( \ {type_index(typeid(ngraph::runtime::cpu::op::OP)), \ &runtime::cpu::Builder::CFbuild<ngraph::runtime::cpu::op::OP>}); \ } \ } __register_##OP##_cf_builder_instance; namespace ngraph { namespace runtime { namespace cpu { using BuildOpFunction = std::function<void(CPU_ExternalFunction* external_function, const ngraph::Node*, const std::vector<TensorViewWrapper>& inputs, const std::vector<TensorViewWrapper>& outputs)>; using BuildOpMap = std::unordered_map<std::type_index, BuildOpFunction>; BuildOpMap& GetGlobalBuildDispatcher(); // build the map to use cpu kernel for node execution CPU_BACKEND_API BuildNodeExecutorMap& GetGlobalCFDispatcherCPU(); class Builder { public: template <typename OP> static void build(CPU_ExternalFunction* external_function, const ngraph::Node* node, const std::vector<TensorViewWrapper>& args, const std::vector<TensorViewWrapper>& out) { throw unsupported_op("Unimplemented op '" + node->description() + "' in CPU builder"); } template <typename OP> static NodeExecutorTy CFbuild(const ngraph::Node* node) { throw unsupported_op("Unimplemented op '" + node->description() + "' for constant folding in CPU builder"); } static void nop(CPU_ExternalFunction* external_function, const ngraph::Node* node, const std::vector<TensorViewWrapper>& args, const std::vector<TensorViewWrapper>& out) { } }; } } } <|endoftext|>
<commit_before>#include <random> #include <chrono> #include <sstream> #include "nodes/EANode/MutationOperation.hpp" #include "core/utils/HierRNG.hpp" MutationOperation::MutationOperation() { this->init(0); } MutationOperation::MutationOperation(double mutationRate) { this->init(mutationRate); } MutationOperation::~MutationOperation() {} void MutationOperation::init(double mutationRate) { this->mutationRate = mutationRate; } Genome* MutationOperation::mutate(Genome* initialGenome) { GenomeTemplate initial = initialGenome->getTemplate(); GenomeTemplate result = this->mutate(initial); Genome* resultGenome = new Genome( result, initialGenome->getSpeciesNode() ); return resultGenome; } GenomeTemplate MutationOperation::mutate(GenomeTemplate initial) { std::vector<Gene*> newGenome; for (unsigned int i = 0; i < initial.genomeLength(); i++) newGenome.push_back(HierRNG::chooseWithProb( this->mutationRate, this->newLocusValue(initial.getGene(i)), initial.getGene(i)->copy() )); GenomeTemplate result(newGenome); for (unsigned int i = 0; i < newGenome.size(); i++) delete(newGenome[i]); return result; } std::string MutationOperation::toString() { std::stringstream ss; ss << "\nMutation rate: " << this->mutationRate << "\n"; return ss.str(); } <commit_msg>[MutationOperation]: Fixed memory leak<commit_after>#include <random> #include <chrono> #include <sstream> #include "nodes/EANode/MutationOperation.hpp" #include "core/utils/HierRNG.hpp" MutationOperation::MutationOperation() { this->init(0); } MutationOperation::MutationOperation(double mutationRate) { this->init(mutationRate); } MutationOperation::~MutationOperation() {} void MutationOperation::init(double mutationRate) { this->mutationRate = mutationRate; } Genome* MutationOperation::mutate(Genome* initialGenome) { GenomeTemplate initial = initialGenome->getTemplate(); GenomeTemplate result = this->mutate(initial); Genome* resultGenome = new Genome( result, initialGenome->getSpeciesNode() ); return resultGenome; } GenomeTemplate MutationOperation::mutate(GenomeTemplate initial) { std::vector<Gene*> newGenome; for (unsigned int i = 0; i < initial.genomeLength(); i++) newGenome.push_back( HierRNG::chooseWithProb(this->mutationRate) ? this->newLocusValue(initial.getGene(i)) : initial.getGene(i)->copy() ); GenomeTemplate result(newGenome); for (unsigned int i = 0; i < newGenome.size(); i++) delete(newGenome[i]); return result; } std::string MutationOperation::toString() { std::stringstream ss; ss << "\nMutation rate: " << this->mutationRate << "\n"; return ss.str(); } <|endoftext|>
<commit_before>/*============================================================================= Copyright (c) 2016-2018 Joel de Guzman Distributed under the MIT License [ https://opensource.org/licenses/MIT ] =============================================================================*/ #if !defined(PHOTON_GUI_LIB_WIDGET_APRIL_10_2016) #define PHOTON_GUI_LIB_WIDGET_APRIL_10_2016 #include <photon/host.hpp> #include <photon/support/rect.hpp> #include <photon/support/misc.hpp> #include <memory> #include <string> #include <type_traits> namespace photon { struct basic_context; struct context; //////////////////////////////////////////////////////////////////////////// // Widgets // // This is the class that deals with the graphic representation of fine- // grained elements inside a window which may be static graphics or active // controls. //////////////////////////////////////////////////////////////////////////// class element : public std::enable_shared_from_this<element> { public: using element_ptr = std::shared_ptr<element>; using element_const_ptr = std::shared_ptr<element const>; element() {} virtual ~element() {} element(element&&) = default; element(element const&) = default; element& operator=(element&&) = default; element& operator=(element const&) = default; // Image virtual view_limits limits(basic_context const& ctx) const; virtual element* hit_test(context const& ctx, point p); virtual void draw(context const& ctx); virtual void layout(context const& ctx); virtual bool scroll(context const& ctx, point dir, point p); virtual void refresh(context const& ctx, element& element); void refresh(context const& ctx) { refresh(ctx, *this); } // Control virtual element* click(context const& ctx, mouse_button btn); virtual void drag(context const& ctx, mouse_button btn); virtual bool key(context const& ctx, key_info k); virtual bool text(context const& ctx, text_info info); virtual bool cursor(context const& ctx, point p, cursor_tracking status); virtual void idle(basic_context const& ctx); virtual bool focus(focus_request r); virtual element const* focus() const; virtual element* focus(); virtual bool is_control() const; // Receiver virtual void value(bool val); virtual void value(int val); virtual void value(double val); virtual void value(std::string val); }; //////////////////////////////////////////////////////////////////////////// using element_ptr = std::shared_ptr<element>; using element_const_ptr = std::shared_ptr<element const>; template <typename Element> inline element_ptr share(Element&& e) { using element_type = typename std::decay<Element>::type; return std::make_shared<element_type>(std::forward<Element>(e)); } } #endif <commit_msg>defer type-erasure as much as possible<commit_after>/*============================================================================= Copyright (c) 2016-2018 Joel de Guzman Distributed under the MIT License [ https://opensource.org/licenses/MIT ] =============================================================================*/ #if !defined(PHOTON_GUI_LIB_WIDGET_APRIL_10_2016) #define PHOTON_GUI_LIB_WIDGET_APRIL_10_2016 #include <photon/host.hpp> #include <photon/support/rect.hpp> #include <photon/support/misc.hpp> #include <memory> #include <string> #include <type_traits> namespace photon { struct basic_context; struct context; //////////////////////////////////////////////////////////////////////////// // Widgets // // This is the class that deals with the graphic representation of fine- // grained elements inside a window which may be static graphics or active // controls. //////////////////////////////////////////////////////////////////////////// class element : public std::enable_shared_from_this<element> { public: using element_ptr = std::shared_ptr<element>; using element_const_ptr = std::shared_ptr<element const>; element() {} virtual ~element() {} element(element&&) = default; element(element const&) = default; element& operator=(element&&) = default; element& operator=(element const&) = default; // Image virtual view_limits limits(basic_context const& ctx) const; virtual element* hit_test(context const& ctx, point p); virtual void draw(context const& ctx); virtual void layout(context const& ctx); virtual bool scroll(context const& ctx, point dir, point p); virtual void refresh(context const& ctx, element& element); void refresh(context const& ctx) { refresh(ctx, *this); } // Control virtual element* click(context const& ctx, mouse_button btn); virtual void drag(context const& ctx, mouse_button btn); virtual bool key(context const& ctx, key_info k); virtual bool text(context const& ctx, text_info info); virtual bool cursor(context const& ctx, point p, cursor_tracking status); virtual void idle(basic_context const& ctx); virtual bool focus(focus_request r); virtual element const* focus() const; virtual element* focus(); virtual bool is_control() const; // Receiver virtual void value(bool val); virtual void value(int val); virtual void value(double val); virtual void value(std::string val); }; //////////////////////////////////////////////////////////////////////////// using element_ptr = std::shared_ptr<element>; using element_const_ptr = std::shared_ptr<element const>; template <typename Element> inline auto share(Element&& e) { using element_type = typename std::decay<Element>::type; return std::make_shared<element_type>(std::forward<Element>(e)); } } #endif <|endoftext|>
<commit_before>#include "Application.h" #include "GameObject.h" #include "Component.h" #include "ComponentTransform.h" #include "ComponentMesh.h" #include "ComponentMaterial.h" #include "ComponentCamera.h" #include "ModuleMeshes.h" #include "RaycastHit.h" GameObject::GameObject() { name.resize(30); name = "Empty GameObject"; uuid = App->rnd->RandomInt(); } GameObject::GameObject(GameObject* parent) : parent(parent) { name.resize(30); name = "Empty GameObject"; uuid = App->rnd->RandomInt(); } GameObject::GameObject(const char* name, unsigned int uuid, GameObject* parent, bool active) : name(name), uuid(uuid), parent(parent), active(active) {} GameObject::~GameObject() { global_matrix = nullptr; bounding_box = nullptr; mesh_to_draw = nullptr; for (std::vector<Component*>::iterator component = components.begin(); component != components.end(); ++component) { delete (*component); (*component) = nullptr; } components.clear(); components_to_remove.clear(); } void GameObject::PreUpdate() { //Reset elements to draw mesh_to_draw = nullptr; texture_to_draw = 0; //Remove all components that need to be removed. Secure way. for (std::vector<Component*>::iterator component = components_to_remove.begin(); component != components_to_remove.end(); ++component) { for (std::vector<Component*>::iterator comp_remove = components.begin(); comp_remove != components.end(); ++comp_remove) //Remove the component from the components list { if ((*comp_remove) == (*component)) { components.erase(comp_remove); break; } } delete (*component); } components_to_remove.clear(); } void GameObject::Update(float dt) { std::vector<Component*>::iterator comp = components.begin(); for (comp; comp != components.end(); comp++) { (*comp)->Update(dt); } } bool GameObject::AddChild(GameObject* child) { bool ret = false; if (child) { childs.push_back(child); ret = true; } return ret; } bool GameObject::RemoveChild(GameObject* child) { bool ret = false; if (child) { std::vector<GameObject*>::iterator item = childs.begin(); while (item != childs.end()) { if (*item == child) { childs.erase(item); ret = true; break; } ++item; } } return ret; } void GameObject::RemoveAllChilds() { for (int i = 0; i < childs.size(); i++) { App->go_manager->RemoveGameObject(childs[i]); } childs.clear(); } GameObject* GameObject::GetParent()const { return parent; } const std::vector<GameObject*>* GameObject::GetChilds() { return &childs; } size_t GameObject::ChildCount() { return childs.size(); } bool GameObject::IsActive() { return active; } void GameObject::SetActive(bool value) { if (value == true && parent->IsActive() == false) return; if ((value == true && active == false) || (value == false && active == true)) { active = value; for (std::vector<GameObject*>::iterator child = childs.begin(); child != childs.end(); ++child) (*child)->SetActive(value); } } Component* GameObject::AddComponent(ComponentType type) { Component* item = nullptr; switch (type) { case C_TRANSFORM: if(GetComponent(type) == nullptr) //Only one transform compoenent for gameobject item = new ComponentTransform(type, this, &global_matrix); break; case C_MESH: if(GetComponent(C_TRANSFORM)) item = new ComponentMesh(type, this); break; case C_MATERIAL: if (GetComponent(C_TRANSFORM) && GetComponent(C_MESH)) item = new ComponentMaterial(type, this); break; case C_CAMERA: if (GetComponent(C_TRANSFORM)) item = new ComponentCamera(type, this); default: break; } if (item != nullptr) { components.push_back(item); } else { LOG("Error while adding component to %s", this->name); } return item; } const std::vector<Component*>* GameObject::GetComponents() { return &components; } void* GameObject::GetComponent(ComponentType type)const { std::vector<Component*>::const_iterator comp = components.begin(); while (comp != components.end()) { if ((*comp)->GetType() == type) { return (*comp); } ++comp; } return NULL; } void GameObject::RemoveComponent(Component * component) { //Search if the component exists inside the GameObject std::vector<Component*>::iterator it = components.begin(); for (it; it != components.end(); ++it) { if ((*it) == component) { components_to_remove.push_back(component); break; } } } float4x4 GameObject::GetGlobalMatrix() const { return (global_matrix) ? *global_matrix : float4x4::identity; } unsigned int GameObject::GetUUID() const { return uuid; } void GameObject::TransformModified() { if (global_matrix == nullptr) return; std::vector<Component*>::iterator component = components.begin(); for (component; component != components.end(); component++) { (*component)->OnTransformModified(); } } void GameObject::Save(Data & file) const { Data data; //GameObject data data.AppendString("name", name.data()); data.AppendUInt("UUID", uuid); if(App->go_manager->IsRoot(this)) data.AppendUInt("parent", 0); else data.AppendUInt("parent", parent->GetUUID()); data.AppendBool("active", active); data.AppendArray("components"); //Components data vector<Component*>::const_iterator component = components.begin(); for (component; component != components.end(); component++) { (*component)->Save(data); } file.AppendArrayValue(data); for (vector<GameObject*>::const_iterator child = childs.begin(); child != childs.end(); ++child) (*child)->Save(file); } bool GameObject::RayCast(const Ray & ray, RaycastHit & hit) { bool ret = false; ComponentMesh* c_mesh = (ComponentMesh*)GetComponent(C_MESH); if (c_mesh) { const Mesh* mesh = c_mesh->GetMesh(); if (mesh) { //Transform ray into local coordinates Ray raycast = ray; raycast.Transform(global_matrix->Inverted()); for (int i = 0; i < mesh->num_indices / 3; i++) { uint u1 = mesh->indices[i * 3]; uint u2 = mesh->indices[i * 3 + 1]; uint u3 = mesh->indices[i * 3 + 2]; float3 v1(&mesh->vertices[u1]); float3 v2(&mesh->vertices[u2]); float3 v3(&mesh->vertices[u3]); if (raycast.Intersects(Triangle(v1, v2, v3))) { ret = true; //For now don't save hit info break; } } } } return ret; } <commit_msg>RaycastHit information<commit_after>#include "Application.h" #include "GameObject.h" #include "Component.h" #include "ComponentTransform.h" #include "ComponentMesh.h" #include "ComponentMaterial.h" #include "ComponentCamera.h" #include "ModuleMeshes.h" #include "RaycastHit.h" GameObject::GameObject() { name.resize(30); name = "Empty GameObject"; uuid = App->rnd->RandomInt(); } GameObject::GameObject(GameObject* parent) : parent(parent) { name.resize(30); name = "Empty GameObject"; uuid = App->rnd->RandomInt(); } GameObject::GameObject(const char* name, unsigned int uuid, GameObject* parent, bool active) : name(name), uuid(uuid), parent(parent), active(active) {} GameObject::~GameObject() { global_matrix = nullptr; bounding_box = nullptr; mesh_to_draw = nullptr; for (std::vector<Component*>::iterator component = components.begin(); component != components.end(); ++component) { delete (*component); (*component) = nullptr; } components.clear(); components_to_remove.clear(); } void GameObject::PreUpdate() { //Reset elements to draw mesh_to_draw = nullptr; texture_to_draw = 0; //Remove all components that need to be removed. Secure way. for (std::vector<Component*>::iterator component = components_to_remove.begin(); component != components_to_remove.end(); ++component) { for (std::vector<Component*>::iterator comp_remove = components.begin(); comp_remove != components.end(); ++comp_remove) //Remove the component from the components list { if ((*comp_remove) == (*component)) { components.erase(comp_remove); break; } } delete (*component); } components_to_remove.clear(); } void GameObject::Update(float dt) { std::vector<Component*>::iterator comp = components.begin(); for (comp; comp != components.end(); comp++) { (*comp)->Update(dt); } } bool GameObject::AddChild(GameObject* child) { bool ret = false; if (child) { childs.push_back(child); ret = true; } return ret; } bool GameObject::RemoveChild(GameObject* child) { bool ret = false; if (child) { std::vector<GameObject*>::iterator item = childs.begin(); while (item != childs.end()) { if (*item == child) { childs.erase(item); ret = true; break; } ++item; } } return ret; } void GameObject::RemoveAllChilds() { for (int i = 0; i < childs.size(); i++) { App->go_manager->RemoveGameObject(childs[i]); } childs.clear(); } GameObject* GameObject::GetParent()const { return parent; } const std::vector<GameObject*>* GameObject::GetChilds() { return &childs; } size_t GameObject::ChildCount() { return childs.size(); } bool GameObject::IsActive() { return active; } void GameObject::SetActive(bool value) { if (value == true && parent->IsActive() == false) return; if ((value == true && active == false) || (value == false && active == true)) { active = value; for (std::vector<GameObject*>::iterator child = childs.begin(); child != childs.end(); ++child) (*child)->SetActive(value); } } Component* GameObject::AddComponent(ComponentType type) { Component* item = nullptr; switch (type) { case C_TRANSFORM: if(GetComponent(type) == nullptr) //Only one transform compoenent for gameobject item = new ComponentTransform(type, this, &global_matrix); break; case C_MESH: if(GetComponent(C_TRANSFORM)) item = new ComponentMesh(type, this); break; case C_MATERIAL: if (GetComponent(C_TRANSFORM) && GetComponent(C_MESH)) item = new ComponentMaterial(type, this); break; case C_CAMERA: if (GetComponent(C_TRANSFORM)) item = new ComponentCamera(type, this); default: break; } if (item != nullptr) { components.push_back(item); } else { LOG("Error while adding component to %s", this->name); } return item; } const std::vector<Component*>* GameObject::GetComponents() { return &components; } void* GameObject::GetComponent(ComponentType type)const { std::vector<Component*>::const_iterator comp = components.begin(); while (comp != components.end()) { if ((*comp)->GetType() == type) { return (*comp); } ++comp; } return NULL; } void GameObject::RemoveComponent(Component * component) { //Search if the component exists inside the GameObject std::vector<Component*>::iterator it = components.begin(); for (it; it != components.end(); ++it) { if ((*it) == component) { components_to_remove.push_back(component); break; } } } float4x4 GameObject::GetGlobalMatrix() const { return (global_matrix) ? *global_matrix : float4x4::identity; } unsigned int GameObject::GetUUID() const { return uuid; } void GameObject::TransformModified() { if (global_matrix == nullptr) return; std::vector<Component*>::iterator component = components.begin(); for (component; component != components.end(); component++) { (*component)->OnTransformModified(); } } void GameObject::Save(Data & file) const { Data data; //GameObject data data.AppendString("name", name.data()); data.AppendUInt("UUID", uuid); if(App->go_manager->IsRoot(this)) data.AppendUInt("parent", 0); else data.AppendUInt("parent", parent->GetUUID()); data.AppendBool("active", active); data.AppendArray("components"); //Components data vector<Component*>::const_iterator component = components.begin(); for (component; component != components.end(); component++) { (*component)->Save(data); } file.AppendArrayValue(data); for (vector<GameObject*>::const_iterator child = childs.begin(); child != childs.end(); ++child) (*child)->Save(file); } bool GameObject::RayCast(const Ray & ray, RaycastHit & hit) { RaycastHit hit_info; bool ret = false; ComponentMesh* c_mesh = (ComponentMesh*)GetComponent(C_MESH); if (c_mesh) { const Mesh* mesh = c_mesh->GetMesh(); if (mesh) { //Transform ray into local coordinates Ray raycast = ray; raycast.Transform(global_matrix->Inverted()); uint u1, u2, u3; float3 v1, v2, v3; float distance; vec hit_point; Triangle triangle; for (int i = 0; i < mesh->num_indices / 3; i++) { u1 = mesh->indices[i * 3]; u2 = mesh->indices[i * 3 + 1]; u3 = mesh->indices[i * 3 + 2]; v1 = float3(&mesh->vertices[u1]); v2 = float3(&mesh->vertices[u2]); v3 = float3(&mesh->vertices[u3]); triangle = Triangle(v1, v2, v3); if (raycast.Intersects(triangle, &distance, &hit_point)) { ret = true; if (hit_info.distance == 0) //First entry { hit_info.distance = distance; hit_info.point = hit_point; hit_info.normal = triangle.PlaneCCW().normal; } else { if (hit_info.distance > distance) { hit_info.distance = distance; hit_info.point = hit_point; hit_info.normal = triangle.PlaneCCW().normal; } } } if (ret == true) { //Transfrom the hit parameters to global coordinates hit.point = global_matrix->MulPos(hit_info.point); hit.distance = ray.pos.Distance(hit.point); hit.object = this; hit.normal = global_matrix->MulDir(hit_info.normal); //TODO: normal needs revision. May not work as expected. hit.normal.Normalize(); } } } } return ret; } <|endoftext|>
<commit_before>/* Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. 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 Sony Pictures Imageworks nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The code in this file is based somewhat on code released by NVIDIA as part of Gelato (specifically, gsoinfo.cpp). That code had the following copyright notice: Copyright 2004 NVIDIA Corporation. All Rights Reserved. and was distributed under BSD licensing terms identical to the Sony Pictures Imageworks terms, above. */ #include <iostream> #include <string> #include <cstring> #include <OpenImageIO/strutil.h> #include "oslquery.h" using namespace OSL; static void usage (void) { std::cout << "oslinfo " OSL_LIBRARY_VERSION_STRING " -- list parameters of a compiled OSL shader\n"; std::cout << OSL_COPYRIGHT_STRING "\n"; std::cout << "Usage: oslinfo [options] file0 [file1 ...]\n"; std::cout << "Options:\n"; std::cout << " -v Verbose\n"; std::cout << " -p %s Set searchpath for shaders\n"; } static void print_default_string_vals (const OSLQuery::Parameter *p, bool verbose) { if (verbose) { for (size_t a = 0; a < p->type.numelements(); ++a) std::cout << "\t\tDefault value: \"" << p->sdefault[a] << "\"\n"; } else { for (size_t a = 0; a < p->type.numelements(); ++a) std::cout << "\"" << p->sdefault[a] << "\" "; std::cout << "\n"; } } static void print_default_int_vals (const OSLQuery::Parameter *p, bool verbose) { size_t nf = p->type.aggregate; for (size_t a = 0; a < p->type.numelements(); ++a) { if (verbose) { std::cout << "\t\tDefault value: "; if (p->spacename.size() > a && ! p->spacename[a].empty()) std::cout << "\"" << p->spacename[a] << "\" "; } if (nf > 1) std::cout << "[ "; for (size_t f = 0; f < nf; ++f) { std::cout << p->idefault[a*nf+f]; if (f < nf-1) std::cout << ' '; } if (nf > 1) std::cout << " ]"; std::cout << std::endl; } } static void print_default_float_vals (const OSLQuery::Parameter *p, bool verbose) { size_t nf = p->type.aggregate; for (size_t a = 0; a < p->type.numelements(); ++a) { if (verbose) { std::cout << "\t\tDefault value: "; if (p->spacename.size() > a && ! p->spacename[a].empty()) std::cout << "\"" << p->spacename[a] << "\" "; } if (nf > 1) std::cout << "[ "; for (size_t f = 0; f < nf; ++f) { std::cout << p->fdefault[a*nf+f]; if (f < nf-1) std::cout << ' '; } if (nf > 1) std::cout << " ]"; std::cout << std::endl; } } static void print_metadata (const OSLQuery::Parameter &m) { std::string typestring (m.type.c_str()); std::cout << "\t\tmetadata: " << typestring << ' ' << m.name << " ="; for (unsigned int d = 0; d < m.idefault.size(); ++d) std::cout << " " << m.idefault[d]; for (unsigned int d = 0; d < m.fdefault.size(); ++d) std::cout << " " << m.fdefault[d]; for (unsigned int d = 0; d < m.sdefault.size(); ++d) std::cout << " \"" << OIIO::Strutil::escape_chars(m.sdefault[d]) << "\""; std::cout << std::endl; } static void oslinfo (const std::string &name, const std::string &path, bool verbose) { OSLQuery g; g.open (name, path); std::string e = g.error(); if (! e.empty()) { std::cout << "ERROR opening shader \"" << name << "\" (" << e << ")\n"; return; } if (verbose) std::cout << g.shadertype() << " \"" << g.shadername() << "\"\n"; else std::cout << g.shadertype() << " " << g.shadername() << "\n"; if (verbose) { for (unsigned int m = 0; m < g.metadata().size(); ++m) print_metadata (g.metadata()[m]); } for (size_t i = 0; i < g.nparams(); ++i) { const OSLQuery::Parameter *p = g.getparam (i); if (!p) break; std::string typestring; if (p->isstruct) typestring = "struct"; else typestring = p->type.c_str(); if (verbose) { std::cout << " \"" << p->name << "\" \"" << (p->isoutput ? "output " : "") << typestring << "\"\n"; } else { std::cout << (p->isoutput ? "output " : "") << typestring << ' ' << p->name << ' '; } if (p->isstruct) { if (verbose) std::cout << "\t\t"; std::cout << "fields: {"; for (size_t f = 0; f < p->fields.size(); ++f) { if (f) std::cout << ", "; std::string fieldname = p->name + '.' + p->fields[f]; const OSLQuery::Parameter *field = g.getparam (fieldname); if (field) std::cout << field->type.c_str() << ' ' << p->fields[f]; else std::cout << "UNKNOWN"; } std::cout << "}\n"; } else if (! p->validdefault) { if (verbose) std::cout << "\t\tUnknown default value\n"; else std::cout << "nodefault\n"; } else if (p->type.basetype == PT_STRING) print_default_string_vals (p, verbose); else if (p->type.basetype == PT_INT) print_default_int_vals (p, verbose); else print_default_float_vals (p, verbose); if (verbose) { for (unsigned int i = 0; i < p->metadata.size(); ++i) print_metadata (p->metadata[i]); } } } int main (int argc, char *argv[]) { std::string path; bool verbose = false; for (int a = 1; a < argc; ++a) { if (! strcmp(argv[a],"-") || ! strcmp(argv[a],"-h") || ! strcmp(argv[a],"-help") || ! strcmp(argv[a],"--h") || ! strcmp(argv[a],"--help")) { usage(); return 0; } else if (! strcmp(argv[a], "-p")) { if (a == argc-1) { usage(); return(-1); } path = argv[++a]; } else if (! strcmp (argv[a], "-v")) { verbose = true; } else { oslinfo (argv[a], path, verbose); } } return 0; } <commit_msg>Fix oslinfo output for arrays.<commit_after>/* Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. 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 Sony Pictures Imageworks nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The code in this file is based somewhat on code released by NVIDIA as part of Gelato (specifically, gsoinfo.cpp). That code had the following copyright notice: Copyright 2004 NVIDIA Corporation. All Rights Reserved. and was distributed under BSD licensing terms identical to the Sony Pictures Imageworks terms, above. */ #include <iostream> #include <string> #include <cstring> #include <OpenImageIO/strutil.h> #include "oslquery.h" using namespace OSL; static void usage (void) { std::cout << "oslinfo " OSL_LIBRARY_VERSION_STRING " -- list parameters of a compiled OSL shader\n"; std::cout << OSL_COPYRIGHT_STRING "\n"; std::cout << "Usage: oslinfo [options] file0 [file1 ...]\n"; std::cout << "Options:\n"; std::cout << " -v Verbose\n"; std::cout << " -p %s Set searchpath for shaders\n"; } static void print_default_string_vals (const OSLQuery::Parameter *p, bool verbose) { if (verbose) { for (size_t a = 0; a < p->type.numelements(); ++a) std::cout << "\t\tDefault value: \"" << p->sdefault[a] << "\"\n"; } else { for (size_t a = 0; a < p->type.numelements(); ++a) std::cout << "\"" << p->sdefault[a] << "\" "; std::cout << "\n"; } } static void print_default_int_vals (const OSLQuery::Parameter *p, bool verbose) { size_t nf = p->type.aggregate; size_t ne = p->type.numelements(); if (verbose) std::cout << "\t\tDefault value:"; if (p->type.arraylen || nf > 1) std::cout << " ["; for (size_t a = 0; a < ne; ++a) { for (size_t f = 0; f < nf; ++f) std::cout << ' ' << p->idefault[a*nf+f]; } if (p->type.arraylen || nf > 1) std::cout << " ]"; std::cout << std::endl; } static void print_default_float_vals (const OSLQuery::Parameter *p, bool verbose) { size_t nf = p->type.aggregate; size_t ne = p->type.numelements(); if (verbose) std::cout << "\t\tDefault value:"; if (p->type.arraylen || nf > 1) std::cout << " ["; for (size_t a = 0; a < ne; ++a) { if (verbose && p->spacename.size() > a && ! p->spacename[a].empty()) std::cout << " \"" << p->spacename[a] << "\""; for (size_t f = 0; f < nf; ++f) std::cout << ' ' << p->fdefault[a*nf+f]; } if (p->type.arraylen || nf > 1) std::cout << " ]"; std::cout << std::endl; } static void print_metadata (const OSLQuery::Parameter &m) { std::string typestring (m.type.c_str()); std::cout << "\t\tmetadata: " << typestring << ' ' << m.name << " ="; for (unsigned int d = 0; d < m.idefault.size(); ++d) std::cout << " " << m.idefault[d]; for (unsigned int d = 0; d < m.fdefault.size(); ++d) std::cout << " " << m.fdefault[d]; for (unsigned int d = 0; d < m.sdefault.size(); ++d) std::cout << " \"" << OIIO::Strutil::escape_chars(m.sdefault[d]) << "\""; std::cout << std::endl; } static void oslinfo (const std::string &name, const std::string &path, bool verbose) { OSLQuery g; g.open (name, path); std::string e = g.error(); if (! e.empty()) { std::cout << "ERROR opening shader \"" << name << "\" (" << e << ")\n"; return; } if (verbose) std::cout << g.shadertype() << " \"" << g.shadername() << "\"\n"; else std::cout << g.shadertype() << " " << g.shadername() << "\n"; if (verbose) { for (unsigned int m = 0; m < g.metadata().size(); ++m) print_metadata (g.metadata()[m]); } for (size_t i = 0; i < g.nparams(); ++i) { const OSLQuery::Parameter *p = g.getparam (i); if (!p) break; std::string typestring; if (p->isstruct) typestring = "struct"; else typestring = p->type.c_str(); if (verbose) { std::cout << " \"" << p->name << "\" \"" << (p->isoutput ? "output " : "") << typestring << "\"\n"; } else { std::cout << (p->isoutput ? "output " : "") << typestring << ' ' << p->name << ' '; } if (p->isstruct) { if (verbose) std::cout << "\t\t"; std::cout << "fields: {"; for (size_t f = 0; f < p->fields.size(); ++f) { if (f) std::cout << ", "; std::string fieldname = p->name + '.' + p->fields[f]; const OSLQuery::Parameter *field = g.getparam (fieldname); if (field) std::cout << field->type.c_str() << ' ' << p->fields[f]; else std::cout << "UNKNOWN"; } std::cout << "}\n"; } else if (! p->validdefault) { if (verbose) std::cout << "\t\tUnknown default value\n"; else std::cout << "nodefault\n"; } else if (p->type.basetype == PT_STRING) print_default_string_vals (p, verbose); else if (p->type.basetype == PT_INT) print_default_int_vals (p, verbose); else print_default_float_vals (p, verbose); if (verbose) { for (unsigned int i = 0; i < p->metadata.size(); ++i) print_metadata (p->metadata[i]); } } } int main (int argc, char *argv[]) { std::string path; bool verbose = false; for (int a = 1; a < argc; ++a) { if (! strcmp(argv[a],"-") || ! strcmp(argv[a],"-h") || ! strcmp(argv[a],"-help") || ! strcmp(argv[a],"--h") || ! strcmp(argv[a],"--help")) { usage(); return 0; } else if (! strcmp(argv[a], "-p")) { if (a == argc-1) { usage(); return(-1); } path = argv[++a]; } else if (! strcmp (argv[a], "-v")) { verbose = true; } else { oslinfo (argv[a], path, verbose); } } return 0; } <|endoftext|>
<commit_before>/** * Declares all GameScenes: Splash Screen, Main Menu, Play, etc. * * Author: Skylar Payne * Date: 8/21/2013 * File: GameScenes.cpp **/ #include "GameScenes.h" #include "IListener.h" #include <lua.hpp> #include "LuaBindings.h" #include "PositionComponent.h" #include "MovementComponent.h" #include "ColliderComponent.h" #include "CircleComponent.h" #include "RectangleComponent.h" #include "TextComponent.h" #include "ScriptableBehavior.h" #include "Entity.h" #include "MovementSystem.h" #include "CollisionSystem.h" #include "BoundarySystem.h" #include "RenderSystem.h" #include "ScoringSystem.h" #include "BehaviorSystem.h" #include "AIControlSystem.h" bool PlayScene::Load() { RenderSystem* rs = new RenderSystem(); MovementSystem* ms = new MovementSystem(); CollisionSystem* cs = new CollisionSystem(); BoundarySystem* bos = new BoundarySystem(); ScoringSystem* ss = new ScoringSystem(); BehaviorSystem* bs = new BehaviorSystem(); AIControlSystem* as = new AIControlSystem(); sm.Add(rs); sm.Add(ms); sm.Add(cs); sm.Add(ss); sm.Add(bos); sm.Add(bs); sm.Add(as); ef.Register("Position", []() { return new PositionComponent(); }); ef.Register("Movement", []() { return new MovementComponent(); }); ef.Register("Collider", []() { return new ColliderComponent(); }); ef.Register("Circle", []() { return new CircleComponent(); }); ef.Register("Rectangle", []() { return new RectangleComponent(); }); ef.Register("Text", []() { return new TextComponent(); }); rm.AddFont("resources/Corki-Regular.otf"); ef.Create("scripts/ball.lua", 400, 300); ef.Create("scripts/paddle.lua", 0, this->GetWindow()->getSize().y / 2); ef.Create("scripts/ai_paddle.lua", this->GetWindow()->getSize().x - 10, this->GetWindow()->getSize().y / 2); return true; } void PlayScene::Update() { sf::Event event; while(this->GetWindow()->pollEvent(event)) { if(event.type == sf::Event::Closed) { ExitMessage msg; msg.ExitStatus = 0; Emit<ExitMessage>(msg); } } this->GetWindow()->clear(); em.Update(); sm.Update(); this->GetWindow()->display(); } void PlayScene::Unload() { rm.Unload(); } <commit_msg>Some testing<commit_after>/** * Declares all GameScenes: Splash Screen, Main Menu, Play, etc. * * Author: Skylar Payne * Date: 8/21/2013 * File: GameScenes.cpp **/ #include "GameScenes.h" #include "IListener.h" #include <lua.hpp> #include "LuaBindings.h" #include "PositionComponent.h" #include "MovementComponent.h" #include "ColliderComponent.h" #include "CircleComponent.h" #include "RectangleComponent.h" #include "TextComponent.h" #include "ScriptableBehavior.h" #include "Entity.h" #include "MovementSystem.h" #include "CollisionSystem.h" #include "BoundarySystem.h" #include "RenderSystem.h" #include "ScoringSystem.h" #include "BehaviorSystem.h" #include "AIControlSystem.h" bool PlayScene::Load() { RenderSystem* rs = new RenderSystem(); MovementSystem* ms = new MovementSystem(); CollisionSystem* cs = new CollisionSystem(); BoundarySystem* bos = new BoundarySystem(); ScoringSystem* ss = new ScoringSystem(); BehaviorSystem* bs = new BehaviorSystem(); AIControlSystem* as = new AIControlSystem(); sm.Add(rs); sm.Add(ms); sm.Add(cs); sm.Add(ss); sm.Add(bos); sm.Add(bs); sm.Add(as); ef.Register("Position", []() { return new PositionComponent(); }); ef.Register("Movement", []() { return new MovementComponent(); }); ef.Register("Collider", []() { return new ColliderComponent(); }); ef.Register("Circle", []() { return new CircleComponent(); }); ef.Register("Rectangle", []() { return new RectangleComponent(); }); ef.Register("Text", []() { return new TextComponent(); }); rm.AddFont("resources/Corki-Regular.otf"); ef.Create("scripts/ball.lua", this->GetWindow()->getSize().x / 2, this->GetWindow()->getSize().y / 2); ef.Create("scripts/paddle.lua", 0, this->GetWindow()->getSize().y / 2); ef.Create("scripts/ai_paddle.lua", this->GetWindow()->getSize().x - 10, this->GetWindow()->getSize().y / 2); PushEntityMessage msg; msg.ID = 0; msg.newVelocity.x = (rand() % 2) ? -7 : 7; msg.newVelocity.y = (rand() % 2) ? -4 : 4; Emit<PushEntityMessage>(msg); return true; } void PlayScene::Update() { sf::Event event; while(this->GetWindow()->pollEvent(event)) { if(event.type == sf::Event::Closed) { ExitMessage msg; msg.ExitStatus = 0; Emit<ExitMessage>(msg); } } this->GetWindow()->clear(); em.Update(); sm.Update(); this->GetWindow()->display(); } void PlayScene::Unload() { rm.Unload(); } <|endoftext|>
<commit_before>#include "SHA1.h" void SHA1::run(const std::string & data, uint32_t & H0, uint32_t & H1, uint32_t & H2, uint32_t & H3, uint32_t & H4){ unsigned int n = 0; for(; n < (data.size() >> 6); n++){ uint32_t skey[80]; for(uint8_t x = 0; x < 16; x++){ skey[x] = toint(data.substr((n << 6) + (x << 2), 4), 256); } for(uint8_t x = 16; x < 80; x++){ skey[x] = ROL((skey[x - 3] ^ skey[x - 8] ^ skey[x - 14] ^ skey[x - 16]), 1, 32); } uint32_t a = H0, b = H1, c = H2, d = H3, e = H4; for(uint8_t j = 0; j < 80; j++){ uint32_t f = 0, k = 0; if (j <= 19){ f = (b & c) | ((~b) & d); k = 0x5A827999; } if (20 <= j && j <= 39){ f = b ^ c ^ d; k = 0x6ED9EBA1; } if (40 <= j && j <= 59){ f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; } if (60 <= j && j <= 79){ f = b ^ c ^ d; k = 0xCA62C1D6; } uint32_t t = ROL(a, 5, 32) + f + e + k + skey[j]; e = d; d = c; c = ROL(b, 30, 32); b = a; a = t; } H0 += a; H1 += b; H2 += c; H3 += d; H4 += e; } } SHA1::SHA1(const std::string & data){ h0 = 0x67452301; h1 = 0xEFCDAB89; h2 = 0x98BADCFE; h3 = 0x10325476; h4 = 0xC3D2E1F0; update(data); } void SHA1::update(const std::string & data){ bytes += data.size(); buffer += data; run(buffer, h0, h1, h2, h3, h4); buffer = buffer.substr(buffer.size() - (buffer.size() & 63), 64); } std::string SHA1::hexdigest(){ uint32_t out0 = h0, out1 = h1, out2 = h2, out3 = h3, out4 = h4; run(buffer + "\x80" + std::string((((bytes & 63) > 55)?119:55) - (bytes & 63), 0) + unhexlify(makehex((bytes << 3) & mod64, 16)), out0, out1, out2, out3, out4); return makehex(out0, 8) + makehex(out1, 8) + makehex(out2, 8) + makehex(out3, 8) + makehex(out4, 8); } unsigned int SHA1::blocksize(){ return 512; } unsigned int SHA1::digestsize(){ return 160; } <commit_msg>Quick typo fix<commit_after>#include "SHA1.h" void SHA1::run(const std::string & data, uint32_t & H0, uint32_t & H1, uint32_t & H2, uint32_t & H3, uint32_t & H4){ for(unsigned int n = 0;; n < (data.size() >> 6); n++){ uint32_t skey[80]; for(uint8_t x = 0; x < 16; x++){ skey[x] = toint(data.substr((n << 6) + (x << 2), 4), 256); } for(uint8_t x = 16; x < 80; x++){ skey[x] = ROL((skey[x - 3] ^ skey[x - 8] ^ skey[x - 14] ^ skey[x - 16]), 1, 32); } uint32_t a = H0, b = H1, c = H2, d = H3, e = H4; for(uint8_t j = 0; j < 80; j++){ uint32_t f = 0, k = 0; if (j <= 19){ f = (b & c) | ((~b) & d); k = 0x5A827999; } if (20 <= j && j <= 39){ f = b ^ c ^ d; k = 0x6ED9EBA1; } if (40 <= j && j <= 59){ f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; } if (60 <= j && j <= 79){ f = b ^ c ^ d; k = 0xCA62C1D6; } uint32_t t = ROL(a, 5, 32) + f + e + k + skey[j]; e = d; d = c; c = ROL(b, 30, 32); b = a; a = t; } H0 += a; H1 += b; H2 += c; H3 += d; H4 += e; } } SHA1::SHA1(const std::string & data){ h0 = 0x67452301; h1 = 0xEFCDAB89; h2 = 0x98BADCFE; h3 = 0x10325476; h4 = 0xC3D2E1F0; update(data); } void SHA1::update(const std::string & data){ bytes += data.size(); buffer += data; run(buffer, h0, h1, h2, h3, h4); buffer = buffer.substr(buffer.size() - (buffer.size() & 63), 64); } std::string SHA1::hexdigest(){ uint32_t out0 = h0, out1 = h1, out2 = h2, out3 = h3, out4 = h4; run(buffer + "\x80" + std::string((((bytes & 63) > 55)?119:55) - (bytes & 63), 0) + unhexlify(makehex((bytes << 3) & mod64, 16)), out0, out1, out2, out3, out4); return makehex(out0, 8) + makehex(out1, 8) + makehex(out2, 8) + makehex(out3, 8) + makehex(out4, 8); } unsigned int SHA1::blocksize(){ return 512; } unsigned int SHA1::digestsize(){ return 160; } <|endoftext|>
<commit_before>#include "IntegerInterval.hpp" #include <gtest/gtest.h> #include <iostream> using namespace std; using namespace dscr; TEST(IntegerInterval, ForwardIteration) { for (int n = 0; n < 10; ++n) { integer_interval R(n); set<integer_interval::value_type> S(R.begin(), R.end()); ASSERT_EQ(R.size(), S.size()); // This checks everything is different. ASSERT_EQ(R.size(), n); ASSERT_TRUE(std::is_sorted(R.begin(), R.end())); ASSERT_EQ(*R.begin(), 0); ASSERT_EQ(*R.end(), n); for (int m = n; m < 15; ++m) { integer_interval R(n, m); set<integer_interval::value_type> S(R.begin(), R.end()); ASSERT_EQ(R.size(), S.size()); ASSERT_EQ(R.size(), m - n); ASSERT_TRUE(std::is_sorted(R.begin(), R.end())); ASSERT_EQ(*R.begin(), n); ASSERT_EQ(*(R.end() - 1), m - 1); } } } TEST(IntegerInterval, PartitionPoint) { big_integer_interval A(1000000000000LL); auto n = A.partition_point([](auto t) { return t < 50811; }); ASSERT_EQ(n, 50811); } TEST(IntegerInterval, Indices) { std::vector<int> A(10); int j = 0; for (auto i : indices(A)) { ASSERT_EQ(i, j); ++j; } } <commit_msg>trying to improve code coverage<commit_after>#include "IntegerInterval.hpp" #include <gtest/gtest.h> #include <iostream> using namespace std; using namespace dscr; TEST(IntegerInterval, ForwardIteration) { for (int n = 0; n < 10; ++n) { integer_interval R(n); set<integer_interval::value_type> S(R.begin(), R.end()); ASSERT_EQ(R.size(), S.size()); // This checks everything is different. ASSERT_EQ(R.size(), n); ASSERT_TRUE(std::is_sorted(R.begin(), R.end())); ASSERT_EQ(*R.begin(), 0); ASSERT_EQ(*R.end(), n); for (int m = n; m < 15; ++m) { integer_interval R(n, m); set<integer_interval::value_type> S(R.begin(), R.end()); ASSERT_EQ(R.size(), S.size()); ASSERT_EQ(R.size(), m - n); ASSERT_TRUE(std::is_sorted(R.begin(), R.end())); ASSERT_EQ(*R.begin(), n); ASSERT_EQ(*(R.end() - 1), m - 1); } } } TEST(IntegerInterval, Empty) { auto I = integer_interval(5,4); ASSERT_EQ(I.size(), 0); for (auto i : I) ASSERT_FALSE(true); auto J = integer_interval(-8); ASSERT_EQ(J.size(), 0); for (auto i : J) ASSERT_FALSE(true); } TEST(IntegerInterval, PartitionPoint) { big_integer_interval A(1000000000000LL); auto n = A.partition_point([](auto t) { return t < 50811; }); ASSERT_EQ(n, 50811); } TEST(IntegerInterval, Indices) { std::vector<int> A(10); int j = 0; for (auto i : indices(A)) { ASSERT_EQ(i, j); ++j; } } <|endoftext|>
<commit_before>#include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/GL> #include <osgDB/Registry> /**************************************************************************** * * Follows is code written by GWM and translated to fit with the OSG Ethos. * * * Ported into the OSG as a plugin, Geoff Michel October 2001. * For patches, bugs and new features * please send them direct to the OSG dev team. * **********************************************************************/ #include <stdio.h> #include <string.h> #include <stdlib.h> enum { ERROR_NO_ERROR =0,ERROR_READING_HEADER,ERROR_READING_PALETTE, ERROR_MEMORY, ERROR_READ_ERROR, ERROR_NO_FILE,ERROR_READING_COLORS}; static int bmperror = ERROR_NO_ERROR; // BMP format bits - at start of file is 512 bytes of pure garbage enum ftype {MB=19778}; // magic number identifies a bmp file; actually chars 'B''M' // allowed ftypes are 'BM' for windoze; OS2 allows: //'BA' - Bitmap Array //'CI' - Color Icon //'CP' - Color Pointer (mouse cursor) //'IC' - Icon //'PT' - Pointer (mouse cursor) enum ncol { BW=1, IA, RGB, RGBA}; struct bmpheader { short FileType; //always MB short siz[2]; // a dword for whole file size short Reserved1, Reserved2; //reserved for future purposes short offset[2]; //offset to image in bytes }; struct BMPInfo { long width; //width of the image in pixels long height; // height of the image in pixels short planes; //:word: number of planes (always 1) short Colorbits; //word: number of bits used to describe color in each pixel long compression; //compression used long ImageSize; //image size in bytes long XpixPerMeter; //pixels per meter in X long YpixPerMeter; //pixels per meter in Y long ColorUsed; //number of colors used long Important; //number of "important" colors long os2stuff[6]; // allows os2.1 with 64 bytes to be read. Dont know what these are yet. }; int bmp_error(char *buffer, int bufferlen) { switch (bmperror) { case ERROR_READING_COLORS: strncpy(buffer, "BMP loader: Error reading colours", bufferlen); break; case ERROR_READING_HEADER: strncpy(buffer, "BMP loader: Error reading header", bufferlen); break; case ERROR_READING_PALETTE: strncpy(buffer, "BMP loader: Error reading palette", bufferlen); break; case ERROR_MEMORY: strncpy(buffer, "BMP loader: Out of memory error", bufferlen); break; case ERROR_READ_ERROR: strncpy(buffer, "BMP loader: Read error", bufferlen); break; } return bmperror; } /* byte order workarounds *sigh* */ void swapbyte(long *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[3]; vv[3]=tmp; tmp=vv[1]; vv[1]=vv[2]; vv[2]=tmp; } void swapbyte(unsigned long *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[3]; vv[3]=tmp; tmp=vv[1]; vv[1]=vv[2]; vv[2]=tmp; } void swapbyte(float *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[3]; vv[3]=tmp; tmp=vv[1]; vv[1]=vv[2]; vv[2]=tmp; } void swapbyte(unsigned short *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[1]; vv[1]=tmp; } void swapbyte(short *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[1]; vv[1]=tmp; } unsigned char * bmp_load(const char *filename, int *width_ret, int *height_ret, int *numComponents_ret) { // the main area of changes from the pic format loader. // reads filename, and returns the buffer // bmp is very very simple format // even Master Gates could have invented it. // It is extremely expensive on disk space - every RGB pixel uses 3 bytes plus a header! // BMP - sponsored by Seagate. // unsigned char palette[256][3]; unsigned char *buffer; // returned to sender & as read from the disk bmperror = ERROR_NO_FILE; FILE *fp = fopen(filename, "rb"); if (!fp) return NULL; int ncolours; int ncomp=0; bool swap=false; // dont need to swap bytes // actual size of the bitmap header; 12=os2; 40 = normal; 64=os2.1 struct bmpheader hd; struct BMPInfo inf; bmperror = ERROR_NO_ERROR; fread((char *)&hd, sizeof(bmpheader), 1, fp); if (hd.FileType != MB) { swapbyte(&(hd.FileType)); swap=true; if (hd.FileType != MB) { bmperror=ERROR_READING_HEADER; } } if (hd.FileType == MB) { long infsize; //size of BMPinfo in bytes unsigned char *cols=NULL; // dynamic colour palette unsigned char *imbuff; // returned to sender & as read from the disk fread((char *)&infsize, sizeof(long), 1, fp); // insert inside 'the file is bmp' clause if (swap) swapbyte(&infsize); if ((infsize-sizeof(long))<sizeof(inf)) { // then the next bytes appear to be valid - actually infsize must be 12,40,64 fread((char *)&inf, infsize-sizeof(long), 1, fp); if (swap) { // inverse the field of the header which need swapping swapbyte(&hd.siz[0]); swapbyte(&hd.siz[1]); swapbyte(&inf.Colorbits); swapbyte(&inf.width); swapbyte(&inf.height); swapbyte(&inf.ImageSize); } if (infsize==12) { // os2, protect us from our friends ? || infsize==64 int wd = inf.width&0xffff; // shorts replace longs int ht = inf.width>>16; int npln = inf.height&0xffff; // number of planes int cbits = inf.height>>16; inf.width=wd; inf.height=ht; inf.planes=npln; inf.Colorbits=cbits; inf.ColorUsed=pow(2.0,inf.Colorbits); // infer the colours } long size = (unsigned short)hd.siz[1]*65536+(unsigned short)hd.siz[0]; int ncpal=4; // default number of colours per palette entry size -= sizeof(bmpheader)+infsize; if (inf.ImageSize<size) inf.ImageSize=size; imbuff = (unsigned char *)malloc( inf.ImageSize); // read from disk fread((char *)imbuff, sizeof(unsigned char),inf.ImageSize, fp); ncolours=inf.Colorbits/8; switch (ncolours) { case 1: ncomp = BW; // actually this is a 256 colour, paletted image inf.Colorbits=8; // so this is how many bits there are per index inf.ColorUsed=256; // and number of colours used cols=imbuff; // colour palette address - uses 4 bytes/colour break; case 2: ncomp = IA; break; case 3: ncomp = RGB; break; case 4: ncomp = RGBA; break; default: cols=imbuff; // colour palette address - uses 4 bytes/colour if (infsize==12 || infsize==64) ncpal=3; // OS2 - uses 3 colours per palette entry else ncpal=4; // Windoze uses 4! } if (ncomp>0) buffer = (unsigned char *)malloc( (ncomp==BW?3:ncomp)*inf.width*inf.height*sizeof(unsigned char)); // to be returned else buffer = (unsigned char *)malloc( 3*inf.width*inf.height*sizeof(unsigned char)); // default full colour to be returned unsigned long off=0; unsigned long rowbytes=ncomp*sizeof(unsigned char)*inf.width; unsigned long doff=(rowbytes)/4; if ((rowbytes%4)) doff++; // round up if needed doff*=4; // to find dword alignment for(int j=0; j<inf.height; j++) { if (ncomp>BW) memcpy(buffer+j*rowbytes, imbuff+off, rowbytes); // pack bytes closely else { // find from the palette.. unsigned char *imptr=imbuff+inf.ColorUsed*ncpal; // add size of the palette- start of image int npixperbyte=8/inf.Colorbits; // no of pixels per byte for (int ii=0; ii<inf.width/npixperbyte; ii++) { unsigned char mask=0x00; // masked with index to extract colorbits bits unsigned char byte=imptr[(j*inf.width/npixperbyte)+ii]; int jj; for (jj=0; jj<inf.Colorbits; jj++) mask |= (0x80>>jj); // fill N High end bits for (jj=0; jj<npixperbyte; jj++) { int colidx=(byte&mask)>>((npixperbyte-1-jj)*inf.Colorbits); buffer[3*(j*inf.width+ii*npixperbyte+jj)+0]=cols[ncpal*colidx+2]; buffer[3*(j*inf.width+ii*npixperbyte+jj)+1]=cols[ncpal*colidx+1]; buffer[3*(j*inf.width+ii*npixperbyte+jj)+2]=cols[ncpal*colidx]; mask>>=inf.Colorbits; } } } off+=doff; if (ncomp>2) { // yes bill, colours are usually BGR aren't they for(int i=0; i<inf.width; i++) { int ijw=i+j*inf.width; unsigned char blu=buffer[3*ijw+0]; buffer[3*ijw+0]=buffer[3*ijw+2]; // swap order of colours buffer[3*ijw+2]=blu; } } } delete [] imbuff; // free the on-disk storage } fclose(fp); } else // else error in header { fclose(fp); return NULL; } *width_ret = inf.width; *height_ret = inf.height; switch (ncomp) { case BW: *numComponents_ret = 3; break; case IA: case RGB: case RGBA: *numComponents_ret = ncomp; break; default: *numComponents_ret = 3; break; } return buffer; } class ReaderWriterBMP : public osgDB::ReaderWriter { public: virtual const char* className() { return "BMP Image Reader"; } virtual bool acceptsExtension(const std::string& extension) { return extension=="bmp"; } virtual ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options*) { unsigned char *imageData = NULL; int width_ret; int height_ret; int numComponents_ret; imageData = bmp_load(fileName.c_str(),&width_ret,&height_ret,&numComponents_ret); if (imageData==NULL) return ReadResult::FILE_NOT_HANDLED; int s = width_ret; int t = height_ret; int r = 1; int internalFormat = numComponents_ret; unsigned int pixelFormat = numComponents_ret == 1 ? GL_LUMINANCE : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA : numComponents_ret == 3 ? GL_RGB : numComponents_ret == 4 ? GL_RGBA : (GLenum)-1; unsigned int dataType = GL_UNSIGNED_BYTE; osg::Image* pOsgImage = new osg::Image; pOsgImage->setFileName(fileName.c_str()); pOsgImage->setImage(s,t,r, internalFormat, pixelFormat, dataType, imageData); return pOsgImage; } }; // now register with Registry to instantiate the above // reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterBMP> g_readerWriter_BMP_Proxy; <commit_msg>Updates to BMP loader from Geoff Michel.<commit_after>#include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/GL> #include <osgDB/Registry> /**************************************************************************** * * Follows is code written by GWM and translated to fit with the OSG Ethos. * * * Ported into the OSG as a plugin, Geoff Michel October 2001. * For patches, bugs and new features * please send them direct to the OSG dev team. * **********************************************************************/ #include <stdio.h> #include <string.h> #include <stdlib.h> enum { ERROR_NO_ERROR =0,ERROR_READING_HEADER,ERROR_READING_PALETTE, ERROR_MEMORY, ERROR_READ_ERROR, ERROR_NO_FILE,ERROR_READING_COLORS}; static int bmperror = ERROR_NO_ERROR; // BMP format bits - at start of file is 512 bytes of pure garbage enum ftype {MB=19778}; // magic number identifies a bmp file; actually chars 'B''M' // allowed ftypes are 'BM' for windoze; OS2 allows: //'BA' - Bitmap Array //'CI' - Color Icon //'CP' - Color Pointer (mouse cursor) //'IC' - Icon //'PT' - Pointer (mouse cursor) enum ncol { BW=1, IA, RGB, RGBA}; struct bmpheader { short FileType; //always MB unsigned short siz[2]; // a dword for whole file size - make unsigned Feb 2002 short Reserved1, Reserved2; //reserved for future purposes short offset[2]; //offset to image in bytes }; struct BMPInfo { long width; //width of the image in pixels long height; // height of the image in pixels short planes; //:word: number of planes (always 1) short Colorbits; //word: number of bits used to describe color in each pixel long compression; //compression used long ImageSize; //image size in bytes long XpixPerMeter; //pixels per meter in X long YpixPerMeter; //pixels per meter in Y long ColorUsed; //number of colors used long Important; //number of "important" colors long os2stuff[6]; // allows os2.1 with 64 bytes to be read. Dont know what these are yet. }; int bmp_error(char *buffer, int bufferlen) { switch (bmperror) { case ERROR_READING_COLORS: strncpy(buffer, "BMP loader: Error reading colours", bufferlen); break; case ERROR_READING_HEADER: strncpy(buffer, "BMP loader: Error reading header", bufferlen); break; case ERROR_READING_PALETTE: strncpy(buffer, "BMP loader: Error reading palette", bufferlen); break; case ERROR_MEMORY: strncpy(buffer, "BMP loader: Out of memory error", bufferlen); break; case ERROR_READ_ERROR: strncpy(buffer, "BMP loader: Read error", bufferlen); break; } return bmperror; } /* byte order workarounds *sigh* */ void swapbyte(long *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[3]; vv[3]=tmp; tmp=vv[1]; vv[1]=vv[2]; vv[2]=tmp; } void swapbyte(unsigned long *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[3]; vv[3]=tmp; tmp=vv[1]; vv[1]=vv[2]; vv[2]=tmp; } void swapbyte(float *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[3]; vv[3]=tmp; tmp=vv[1]; vv[1]=vv[2]; vv[2]=tmp; } void swapbyte(unsigned short *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[1]; vv[1]=tmp; } void swapbyte(short *i) { char *vv=(char *)i; char tmp=vv[0]; vv[0]=vv[1]; vv[1]=tmp; } unsigned char * bmp_load(const char *filename, int *width_ret, int *height_ret, int *numComponents_ret) { // the main area of changes from the pic format loader. // reads filename, and returns the buffer // bmp is very very simple format // even Master Gates could have invented it. // It is extremely expensive on disk space - every RGB pixel uses 3 bytes plus a header! // BMP - sponsored by Seagate. // unsigned char palette[256][3]; unsigned char *buffer=NULL; // returned to sender & as read from the disk bmperror = ERROR_NO_FILE; FILE *fp = fopen(filename, "rb"); if (!fp) return NULL; int ncolours; int ncomp=0; bool swap=false; // dont need to swap bytes // actual size of the bitmap header; 12=os2; 40 = normal; 64=os2.1 struct bmpheader hd; struct BMPInfo inf; bmperror = ERROR_NO_ERROR; fread((char *)&hd, sizeof(bmpheader), 1, fp); if (hd.FileType != MB) { swapbyte(&(hd.FileType)); swap=true; if (hd.FileType != MB) { bmperror=ERROR_READING_HEADER; } } if (hd.FileType == MB) { long infsize; //size of BMPinfo in bytes unsigned char *cols=NULL; // dynamic colour palette unsigned char *imbuff; // returned to sender & as read from the disk fread((char *)&infsize, sizeof(long), 1, fp); // insert inside 'the file is bmp' clause if (swap) swapbyte(&infsize); if ((infsize-sizeof(long))<sizeof(inf)) { // then the next bytes appear to be valid - actually infsize must be 12,40,64 fread((char *)&inf, infsize-sizeof(long), 1, fp); if (swap) { // inverse the field of the header which need swapping swapbyte(&hd.siz[0]); swapbyte(&hd.siz[1]); swapbyte(&inf.Colorbits); swapbyte(&inf.width); swapbyte(&inf.height); swapbyte(&inf.ImageSize); } if (infsize==12) { // os2, protect us from our friends ? || infsize==64 int wd = inf.width&0xffff; // shorts replace longs int ht = inf.width>>16; int npln = inf.height&0xffff; // number of planes int cbits = inf.height>>16; inf.width=wd; inf.height=ht; inf.planes=npln; inf.Colorbits=cbits; inf.ColorUsed=(long)pow(2.0,(double)inf.Colorbits); // infer the colours } long size = hd.siz[1]*65536+hd.siz[0]; int ncpal=4; // default number of colours per palette entry size -= sizeof(bmpheader)+infsize; if (inf.ImageSize<size) inf.ImageSize=size; imbuff = (unsigned char *)malloc( inf.ImageSize); // read from disk fread((char *)imbuff, sizeof(unsigned char),inf.ImageSize, fp); ncolours=inf.Colorbits/8; switch (ncolours) { case 1: ncomp = BW; // actually this is a 256 colour, paletted image inf.Colorbits=8; // so this is how many bits there are per index inf.ColorUsed=256; // and number of colours used cols=imbuff; // colour palette address - uses 4 bytes/colour break; case 2: ncomp = IA; break; case 3: ncomp = RGB; break; case 4: ncomp = RGBA; break; default: cols=imbuff; // colour palette address - uses 4 bytes/colour if (infsize==12 || infsize==64) ncpal=3; // OS2 - uses 3 colours per palette entry else ncpal=4; // Windoze uses 4! } if (ncomp>0) buffer = (unsigned char *)malloc( (ncomp==BW?3:ncomp)*inf.width*inf.height*sizeof(unsigned char)); // to be returned else buffer = (unsigned char *)malloc( 3*inf.width*inf.height*sizeof(unsigned char)); // default full colour to be returned unsigned long off=0; unsigned long rowbytes=ncomp*sizeof(unsigned char)*inf.width; unsigned long doff=(rowbytes)/4; if ((rowbytes%4)) doff++; // round up if needed doff*=4; // to find dword alignment for(int j=0; j<inf.height; j++) { if (ncomp>BW) memcpy(buffer+j*rowbytes, imbuff+off, rowbytes); // pack bytes closely else { // find from the palette.. unsigned char *imptr=imbuff+inf.ColorUsed*ncpal; // add size of the palette- start of image int npixperbyte=8/inf.Colorbits; // no of pixels per byte for (int ii=0; ii<inf.width/npixperbyte; ii++) { unsigned char mask=0x00; // masked with index to extract colorbits bits unsigned char byte=imptr[(j*inf.width/npixperbyte)+ii]; int jj; for (jj=0; jj<inf.Colorbits; jj++) mask |= (0x80>>jj); // fill N High end bits for (jj=0; jj<npixperbyte; jj++) { int colidx=(byte&mask)>>((npixperbyte-1-jj)*inf.Colorbits); buffer[3*(j*inf.width+ii*npixperbyte+jj)+0]=cols[ncpal*colidx+2]; buffer[3*(j*inf.width+ii*npixperbyte+jj)+1]=cols[ncpal*colidx+1]; buffer[3*(j*inf.width+ii*npixperbyte+jj)+2]=cols[ncpal*colidx]; mask>>=inf.Colorbits; } } } off+=doff; if (ncomp>2) { // yes bill, colours are usually BGR aren't they for(int i=0; i<inf.width; i++) { int ijw=i+j*inf.width; unsigned char blu=buffer[3*ijw+0]; buffer[3*ijw+0]=buffer[3*ijw+2]; // swap order of colours buffer[3*ijw+2]=blu; } } } delete [] imbuff; // free the on-disk storage } fclose(fp); } else // else error in header { fclose(fp); return NULL; } *width_ret = inf.width; *height_ret = inf.height; switch (ncomp) { case BW: *numComponents_ret = 3; break; case IA: case RGB: case RGBA: *numComponents_ret = ncomp; break; default: *numComponents_ret = 3; break; } return buffer; } class ReaderWriterBMP : public osgDB::ReaderWriter { public: virtual const char* className() { return "BMP Image Reader"; } virtual bool acceptsExtension(const std::string& extension) { return extension=="bmp"; } virtual ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options*) { unsigned char *imageData = NULL; int width_ret; int height_ret; int numComponents_ret; imageData = bmp_load(fileName.c_str(),&width_ret,&height_ret,&numComponents_ret); if (imageData==NULL) return ReadResult::FILE_NOT_HANDLED; int s = width_ret; int t = height_ret; int r = 1; int internalFormat = numComponents_ret; unsigned int pixelFormat = numComponents_ret == 1 ? GL_LUMINANCE : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA : numComponents_ret == 3 ? GL_RGB : numComponents_ret == 4 ? GL_RGBA : (GLenum)-1; unsigned int dataType = GL_UNSIGNED_BYTE; osg::Image* pOsgImage = new osg::Image; pOsgImage->setFileName(fileName.c_str()); pOsgImage->setImage(s,t,r, internalFormat, pixelFormat, dataType, imageData); return pOsgImage; } }; // now register with Registry to instantiate the above // reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterBMP> g_readerWriter_BMP_Proxy; <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 2007 Cedric Pinson * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commercial and non commercial * applications, as long as this copyright notice is maintained. * * This application is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * Authors: * Cedric Pinson <mornifle@plopbyte.net> * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef DATADIR #define DATADIR "." #endif // DATADIR #include <osg/GraphicsContext> #include "RenderSurface.h" #include "CameraConfig.h" #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osg/io_utils> using namespace osgProducer; static osg::GraphicsContext::Traits* buildTrait(RenderSurface& rs) { VisualChooser& vc = *rs.getVisualChooser(); osg::GraphicsContext::Traits* traits = new osg::GraphicsContext::Traits; for (std::vector<VisualChooser::VisualAttribute>::iterator it = vc._visual_attributes.begin(); it != vc._visual_attributes.end(); it++) { switch(it->_attribute) { case(VisualChooser::UseGL): break; // on by default in osgViewer case(VisualChooser::BufferSize): break; // no present mapping case(VisualChooser::Level): traits->level = it->_parameter; break; case(VisualChooser::RGBA): break; // automatically set in osgViewer case(VisualChooser::DoubleBuffer): traits->doubleBuffer = true; break; case(VisualChooser::Stereo): traits->quadBufferStereo = true; break; case(VisualChooser::AuxBuffers): break; // no present mapping case(VisualChooser::RedSize): traits->red = it->_parameter; break; case(VisualChooser::GreenSize): traits->green = it->_parameter; break; case(VisualChooser::BlueSize): traits->blue = it->_parameter; break; case(VisualChooser::AlphaSize): traits->alpha = it->_parameter; break; case(VisualChooser::DepthSize): traits->depth = it->_parameter; break; case(VisualChooser::StencilSize): traits->stencil = it->_parameter; break; case(VisualChooser::AccumRedSize): break; // no present mapping case(VisualChooser::AccumGreenSize): break; // no present mapping case(VisualChooser::AccumBlueSize): break; // no present mapping case(VisualChooser::AccumAlphaSize): break; // no present mapping case(VisualChooser::Samples): traits->samples = it->_parameter; break; case(VisualChooser::SampleBuffers): traits->sampleBuffers = it->_parameter; break; } } OSG_NOTICE<<"ReaderWriterCFG buildTrait traits->depth="<<traits->depth<<std::endl; OSG_INFO<<"Set up Traits ( rs.getScreenNum() = "<<rs.getScreenNum()<<" )"<<std::endl; traits->hostName = rs.getHostName(); traits->displayNum = rs.getDisplayNum(); traits->screenNum = rs.getScreenNum(); traits->windowName = rs.getWindowName(); traits->x = rs.getWindowOriginX(); traits->y = rs.getWindowOriginY(); traits->width = rs.getWindowWidth(); traits->height = rs.getWindowHeight(); traits->windowDecoration = rs.usesBorder(); traits->sharedContext = 0; traits->pbuffer = (rs.getDrawableType()==osgProducer::RenderSurface::DrawableType_PBuffer); traits->overrideRedirect = rs.usesOverrideRedirect(); return traits; } static osgViewer::View* load(const std::string& file, const osgDB::ReaderWriter::Options* option) { osg::ref_ptr<CameraConfig> config = new CameraConfig; //std::cout << "Parse file " << file << std::endl; config->parseFile(file); RenderSurface* rs = 0; Camera* cm = 0; std::map<RenderSurface*,osg::ref_ptr<osg::GraphicsContext> > surfaces; osg::ref_ptr<osgViewer::View> _view = new osgViewer::View; for (int i = 0; i < (int)config->getNumberOfCameras(); i++) { cm = config->getCamera(i); rs = cm->getRenderSurface(); if (rs->getDrawableType() != osgProducer::RenderSurface::DrawableType_Window) continue; osg::ref_ptr<const osg::GraphicsContext::Traits> traits; osg::ref_ptr<osg::GraphicsContext> gc; if (surfaces.find(rs) != surfaces.end()) { gc = surfaces[rs]; traits = gc.valid() ? gc->getTraits() : 0; } else { osg::GraphicsContext::Traits* newtraits = buildTrait(*rs); #if 0 osg::GraphicsContext::ScreenIdentifier si; si.readDISPLAY(); if (si.displayNum>=0) newtraits->displayNum = si.displayNum; if (si.screenNum>=0) newtraits->screenNum = si.screenNum; #endif gc = osg::GraphicsContext::createGraphicsContext(newtraits); surfaces[rs] = gc.get(); traits = gc.valid() ? gc->getTraits() : 0; } // std::cout << rs->getWindowName() << " " << rs->getWindowOriginX() << " " << rs->getWindowOriginY() << " " << rs->getWindowWidth() << " " << rs->getWindowHeight() << std::endl; if (gc.valid()) { OSG_INFO<<" GraphicsWindow has been created successfully."<<std::endl; osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setGraphicsContext(gc.get()); int x,y; unsigned int width,height; cm->applyLens(); cm->getProjectionRectangle(x, y, width, height); camera->setViewport(new osg::Viewport(x, y, width, height)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); osg::Matrix projection(cm->getProjectionMatrix()); osg::Matrix offset = osg::Matrix::identity(); cm->setViewByMatrix(offset); osg::Matrix view = osg::Matrix(cm->getPositionAndAttitudeMatrix()); // setup projection from parent osg::Matrix offsetProjection = osg::Matrix::inverse(_view->getCamera()->getProjectionMatrix()) * projection; _view->addSlave(camera.get(), offsetProjection, view); #if 0 std::cout << "Matrix Projection " << projection << std::endl; std::cout << "Matrix Projection master " << _view->getCamera()->getProjectionMatrix() << std::endl; // will work only if it's a post multyply in the producer camera std::cout << "Matrix View " << view << std::endl; std::cout << _view->getCamera()->getProjectionMatrix() * offsetProjection << std::endl; #endif } else { OSG_INFO<<" GraphicsWindow has not been created successfully."<<std::endl; return 0; } } // std::cout << "done" << std::endl; return _view.release(); } // // OSG interface to read/write from/to a file. // class ReaderWriterProducerCFG : public osgDB::ReaderWriter { public: ReaderWriterProducerCFG() { supportsExtension("cfg","Producer camera configuration file"); } virtual const char* className() { return "Producer cfg object reader"; } virtual ReadResult readObject(const std::string& fileName, const Options* options = NULL) const { std::string ext = osgDB::getLowerCaseFileExtension(fileName); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; osgDB::FilePathList* filePathList = 0; if(options) { filePathList = const_cast<osgDB::FilePathList*>(&(options->getDatabasePathList())); filePathList->push_back(DATADIR); } std::string path = osgDB::findDataFile(fileName); if(path.empty()) return ReadResult::FILE_NOT_FOUND; ReadResult result; osg::ref_ptr<osg::View> view = load(path, options); if(! view.valid()) result = ReadResult("Error: could not load " + path); else result = ReadResult(view.get()); if(options && filePathList) filePathList->pop_back(); return result; } }; REGISTER_OSGPLUGIN(cfg, ReaderWriterProducerCFG) <commit_msg>Changed the default for SampleBuffers to be 1 when set.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 2007 Cedric Pinson * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commercial and non commercial * applications, as long as this copyright notice is maintained. * * This application is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * Authors: * Cedric Pinson <mornifle@plopbyte.net> * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef DATADIR #define DATADIR "." #endif // DATADIR #include <osg/GraphicsContext> #include "RenderSurface.h" #include "CameraConfig.h" #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osg/io_utils> using namespace osgProducer; static osg::GraphicsContext::Traits* buildTrait(RenderSurface& rs) { VisualChooser& vc = *rs.getVisualChooser(); osg::GraphicsContext::Traits* traits = new osg::GraphicsContext::Traits; for (std::vector<VisualChooser::VisualAttribute>::iterator it = vc._visual_attributes.begin(); it != vc._visual_attributes.end(); it++) { switch(it->_attribute) { case(VisualChooser::UseGL): break; // on by default in osgViewer case(VisualChooser::BufferSize): break; // no present mapping case(VisualChooser::Level): traits->level = it->_parameter; break; case(VisualChooser::RGBA): break; // automatically set in osgViewer case(VisualChooser::DoubleBuffer): traits->doubleBuffer = true; break; case(VisualChooser::Stereo): traits->quadBufferStereo = true; break; case(VisualChooser::AuxBuffers): break; // no present mapping case(VisualChooser::RedSize): traits->red = it->_parameter; break; case(VisualChooser::GreenSize): traits->green = it->_parameter; break; case(VisualChooser::BlueSize): traits->blue = it->_parameter; break; case(VisualChooser::AlphaSize): traits->alpha = it->_parameter; break; case(VisualChooser::DepthSize): traits->depth = it->_parameter; break; case(VisualChooser::StencilSize): traits->stencil = it->_parameter; break; case(VisualChooser::AccumRedSize): break; // no present mapping case(VisualChooser::AccumGreenSize): break; // no present mapping case(VisualChooser::AccumBlueSize): break; // no present mapping case(VisualChooser::AccumAlphaSize): break; // no present mapping case(VisualChooser::Samples): traits->samples = it->_parameter; break; case(VisualChooser::SampleBuffers): traits->sampleBuffers = 1; break; } } OSG_NOTICE<<"ReaderWriterCFG buildTrait traits->depth="<<traits->depth<<std::endl; OSG_NOTICE<<"ReaderWriterCFG buildTrait traits->samples="<<traits->samples<<std::endl; OSG_NOTICE<<"ReaderWriterCFG buildTrait traits->sampleBuffers="<<traits->sampleBuffers<<std::endl; traits->hostName = rs.getHostName(); traits->displayNum = rs.getDisplayNum(); traits->screenNum = rs.getScreenNum(); traits->windowName = rs.getWindowName(); traits->x = rs.getWindowOriginX(); traits->y = rs.getWindowOriginY(); traits->width = rs.getWindowWidth(); traits->height = rs.getWindowHeight(); traits->windowDecoration = rs.usesBorder(); traits->sharedContext = 0; traits->pbuffer = (rs.getDrawableType()==osgProducer::RenderSurface::DrawableType_PBuffer); traits->overrideRedirect = rs.usesOverrideRedirect(); return traits; } static osgViewer::View* load(const std::string& file, const osgDB::ReaderWriter::Options* option) { osg::ref_ptr<CameraConfig> config = new CameraConfig; //std::cout << "Parse file " << file << std::endl; config->parseFile(file); RenderSurface* rs = 0; Camera* cm = 0; std::map<RenderSurface*,osg::ref_ptr<osg::GraphicsContext> > surfaces; osg::ref_ptr<osgViewer::View> _view = new osgViewer::View; for (int i = 0; i < (int)config->getNumberOfCameras(); i++) { cm = config->getCamera(i); rs = cm->getRenderSurface(); if (rs->getDrawableType() != osgProducer::RenderSurface::DrawableType_Window) continue; osg::ref_ptr<const osg::GraphicsContext::Traits> traits; osg::ref_ptr<osg::GraphicsContext> gc; if (surfaces.find(rs) != surfaces.end()) { gc = surfaces[rs]; traits = gc.valid() ? gc->getTraits() : 0; } else { osg::GraphicsContext::Traits* newtraits = buildTrait(*rs); #if 0 osg::GraphicsContext::ScreenIdentifier si; si.readDISPLAY(); if (si.displayNum>=0) newtraits->displayNum = si.displayNum; if (si.screenNum>=0) newtraits->screenNum = si.screenNum; #endif gc = osg::GraphicsContext::createGraphicsContext(newtraits); surfaces[rs] = gc.get(); traits = gc.valid() ? gc->getTraits() : 0; } // std::cout << rs->getWindowName() << " " << rs->getWindowOriginX() << " " << rs->getWindowOriginY() << " " << rs->getWindowWidth() << " " << rs->getWindowHeight() << std::endl; if (gc.valid()) { OSG_INFO<<" GraphicsWindow has been created successfully."<<std::endl; osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setGraphicsContext(gc.get()); int x,y; unsigned int width,height; cm->applyLens(); cm->getProjectionRectangle(x, y, width, height); camera->setViewport(new osg::Viewport(x, y, width, height)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); osg::Matrix projection(cm->getProjectionMatrix()); osg::Matrix offset = osg::Matrix::identity(); cm->setViewByMatrix(offset); osg::Matrix view = osg::Matrix(cm->getPositionAndAttitudeMatrix()); // setup projection from parent osg::Matrix offsetProjection = osg::Matrix::inverse(_view->getCamera()->getProjectionMatrix()) * projection; _view->addSlave(camera.get(), offsetProjection, view); #if 0 std::cout << "Matrix Projection " << projection << std::endl; std::cout << "Matrix Projection master " << _view->getCamera()->getProjectionMatrix() << std::endl; // will work only if it's a post multyply in the producer camera std::cout << "Matrix View " << view << std::endl; std::cout << _view->getCamera()->getProjectionMatrix() * offsetProjection << std::endl; #endif } else { OSG_INFO<<" GraphicsWindow has not been created successfully."<<std::endl; return 0; } } // std::cout << "done" << std::endl; return _view.release(); } // // OSG interface to read/write from/to a file. // class ReaderWriterProducerCFG : public osgDB::ReaderWriter { public: ReaderWriterProducerCFG() { supportsExtension("cfg","Producer camera configuration file"); } virtual const char* className() { return "Producer cfg object reader"; } virtual ReadResult readObject(const std::string& fileName, const Options* options = NULL) const { std::string ext = osgDB::getLowerCaseFileExtension(fileName); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; osgDB::FilePathList* filePathList = 0; if(options) { filePathList = const_cast<osgDB::FilePathList*>(&(options->getDatabasePathList())); filePathList->push_back(DATADIR); } std::string path = osgDB::findDataFile(fileName); if(path.empty()) return ReadResult::FILE_NOT_FOUND; ReadResult result; osg::ref_ptr<osg::View> view = load(path, options); if(! view.valid()) result = ReadResult("Error: could not load " + path); else result = ReadResult(view.get()); if(options && filePathList) filePathList->pop_back(); return result; } }; REGISTER_OSGPLUGIN(cfg, ReaderWriterProducerCFG) <|endoftext|>
<commit_before>#include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/Image> #include <osg/GL> #if defined _WIN32 && !defined OSG_LIBRARY_STATIC //Make the half format work against openEXR libs #define OPENEXR_DLL #endif #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <ImfRgbaFile.h> #include <ImfIO.h> #include <ImfArray.h> using namespace std; using namespace Imf; using namespace Imath; /**************************************************************************** * * Follows is code written by FOI (www.foi.se) * it is a wrapper of openEXR(www.openexr.com) * to add suport of exr images into osg * * Ported to a OSG-plugin, Ragnar Hammarqvist. * For patches, bugs and new features * please send them direct to the OSG dev team. **********************************************************************/ class C_IStream: public Imf::IStream { public: C_IStream (istream *fin) : IStream(""),_inStream(fin){} virtual bool read (char c[/*n*/], int n) { return _inStream->read(c,n).good(); }; virtual Int64 tellg () { return _inStream->tellg(); }; virtual void seekg (Int64 pos) { _inStream->seekg(pos); }; virtual void clear () { _inStream->clear(); }; private: std::istream * _inStream; }; class C_OStream: public Imf::OStream { public: C_OStream (ostream *fin) : OStream(""),_outStream(fin) {}; virtual void write (const char c[/*n*/], int n) { _outStream->write(c,n); }; virtual Int64 tellp () { return _outStream->tellp(); }; virtual void seekp (Int64 pos) { _outStream->seekp(pos); }; private: std::ostream * _outStream; }; unsigned char *exr_load(std::istream& fin, int *width_ret, int *height_ret, int *numComponents_ret, unsigned int *dataType_ret) { unsigned char *buffer=NULL; // returned to sender & as read from the disk bool inputError = false; Array2D<Rgba> pixels; int width,height,numComponents; try { C_IStream inStream(&fin); RgbaInputFile rgbafile(inStream); Box2i dw = rgbafile.dataWindow(); /*RgbaChannels channels =*/ rgbafile.channels(); (*width_ret) = width = dw.max.x - dw.min.x + 1; (*height_ret)=height = dw.max.y - dw.min.y + 1; (*dataType_ret) = GL_HALF_FLOAT; pixels.resizeErase (height, width); rgbafile.setFrameBuffer((&pixels)[0][0] - dw.min.x - dw.min.y * width, 1, width); rgbafile.readPixels(dw.min.y, dw.max.y); } catch( char * str ) { inputError = true; } //If error during stream read return a empty pointer if (inputError) { return buffer; } //If there is no information in alpha channel do not store the alpha channel numComponents = 3; for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { if (pixels[i][j].a != half(1.0f) ) { numComponents = 4; break; } } } (*numComponents_ret) = numComponents; if (!( numComponents == 3 || numComponents == 4)) { return NULL; } //Copy and allocate data to a unsigned char array that OSG can use for texturing unsigned dataSize = (sizeof(half) * height * width * numComponents); //buffer = new unsigned char[dataSize]; buffer = (unsigned char*)malloc(dataSize); half* pOut = (half*) buffer; for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { (*pOut) = pixels[i][j].r; pOut++; (*pOut) = pixels[i][j].g; pOut++; (*pOut) = pixels[i][j].b; pOut++; if (numComponents >= 4) { (*pOut) = pixels[i][j].a; pOut++; } } } return buffer; } class ReaderWriterEXR : public osgDB::ReaderWriter { public: ReaderWriterEXR() { } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"exr"); } virtual const char* className() const { return "EXR Image Reader"; } virtual ReadResult readObject(std::istream& fin,const osgDB::ReaderWriter::Options* options =NULL) const { return readImage(fin, options); } virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options =NULL) const { return readImage(file, options); } virtual ReadResult readImage(std::istream& fin,const Options* =NULL) const { return readEXRStream(fin); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; osgDB::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary); if(!istream) return ReadResult::FILE_NOT_HANDLED; ReadResult rr = readEXRStream(istream); if(rr.validImage()) { rr.getImage()->setFileName(fileName); } return rr; } virtual WriteResult writeImage(const osg::Image& image,std::ostream& fout,const Options*) const { bool success = writeEXRStream(image, fout, "<output stream>"); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } virtual WriteResult writeImage(const osg::Image &img,const std::string& fileName, const osgDB::ReaderWriter::Options*) const { std::string ext = osgDB::getFileExtension(fileName); if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; osgDB::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary); if(!fout) return WriteResult::ERROR_IN_WRITING_FILE; bool success = writeEXRStream(img, fout, fileName); fout.close(); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } protected: bool writeEXRStream(const osg::Image &img, std::ostream& fout, const std::string &fileName) const { bool writeOK = true; //Obtain data from texture int width = img.s(); int height = img.t(); unsigned int pixelFormat = img.getPixelFormat(); int numComponents = img.computeNumComponents(pixelFormat); unsigned int dataType = img.getDataType(); //Validates image data //if numbers of components matches if (!( numComponents == 3 || numComponents == 4)) { writeOK = false; return false; } if (!( dataType == GL_HALF_FLOAT || dataType == GL_FLOAT)) { writeOK = false; return false; } //Create a stream to save to C_OStream outStream(&fout); //Copy data from texture to rgba pixel format Array2D<Rgba> outPixels(height,width); //If texture is half format if (dataType == GL_HALF_FLOAT) { for (long i = height-1; i >= 0; i--) { half* pOut = (half*) img.data(0,i); for (long j = 0 ; j < width; j++) { outPixels[i][j].r = (*pOut); pOut++; outPixels[i][j].g = (*pOut); pOut++; outPixels[i][j].b = (*pOut); pOut++; if (numComponents >= 4) { outPixels[i][j].a = (*pOut); pOut++; } else{outPixels[i][j].a = 1.0f;} } } } else if (dataType == GL_FLOAT) { float* pOut = (float*) img.data(); for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { outPixels[i][j].r = half(*pOut); pOut++; outPixels[i][j].g = half(*pOut); pOut++; outPixels[i][j].b = half(*pOut); pOut++; if (numComponents >= 4) { outPixels[i][j].a = half(*pOut); pOut++; } else {outPixels[i][j].a = 1.0f;} } } } else { //If texture format not supported return false; } try { //Write to stream Header outHeader(width, height); RgbaOutputFile rgbaFile (outStream, outHeader, WRITE_RGBA); rgbaFile.setFrameBuffer ((&outPixels)[0][0], 1, width); rgbaFile.writePixels (height); } catch( char * str ) { writeOK = false; } return writeOK; } ReadResult readEXRStream(std::istream& fin) const { unsigned char *imageData = NULL; int width_ret = 0; int height_ret = 0; int numComponents_ret = 4; unsigned int dataType_ret = GL_UNSIGNED_BYTE; unsigned int pixelFormat = GL_RGB; unsigned int interNalTextureFormat = GL_RGB; imageData = exr_load(fin,&width_ret,&height_ret,&numComponents_ret,&dataType_ret); if (imageData==NULL) return ReadResult::FILE_NOT_HANDLED; int s = width_ret; int t = height_ret; int r = 1; if (dataType_ret == GL_HALF_FLOAT) { interNalTextureFormat = numComponents_ret == 1 ? GL_LUMINANCE16F_ARB : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA16F_ARB : numComponents_ret == 3 ? GL_RGB16F_ARB : numComponents_ret == 4 ? GL_RGBA16F_ARB : (GLenum)-1; } else if (dataType_ret == GL_FLOAT) { interNalTextureFormat = numComponents_ret == 1 ? GL_LUMINANCE32F_ARB : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA32F_ARB : numComponents_ret == 3 ? GL_RGB32F_ARB : numComponents_ret == 4 ? GL_RGBA32F_ARB : (GLenum)-1; } pixelFormat = numComponents_ret == 1 ? GL_LUMINANCE : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA : numComponents_ret == 3 ? GL_RGB : numComponents_ret == 4 ? GL_RGBA : (GLenum)-1; unsigned int dataType = dataType_ret; osg::Image* pOsgImage = new osg::Image; pOsgImage->setImage(s,t,r, interNalTextureFormat, pixelFormat, dataType, imageData, osg::Image::USE_MALLOC_FREE); return pOsgImage; } }; // now register with Registry to instantiate the exr suport // reader/writer. REGISTER_OSGPLUGIN(exr, ReaderWriterEXR) <commit_msg>From Laurens Voerman, warning fixes<commit_after>#include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/Image> #include <osg/GL> #if defined _WIN32 && !defined OSG_LIBRARY_STATIC //Make the half format work against openEXR libs #define OPENEXR_DLL #endif #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <ImfRgbaFile.h> #include <ImfIO.h> #include <ImfArray.h> using namespace std; using namespace Imf; using namespace Imath; /**************************************************************************** * * Follows is code written by FOI (www.foi.se) * it is a wrapper of openEXR(www.openexr.com) * to add suport of exr images into osg * * Ported to a OSG-plugin, Ragnar Hammarqvist. * For patches, bugs and new features * please send them direct to the OSG dev team. **********************************************************************/ class C_IStream: public Imf::IStream { public: C_IStream (istream *fin) : IStream(""),_inStream(fin){} virtual bool read (char c[/*n*/], int n) { return _inStream->read(c,n).good(); }; virtual Int64 tellg () { return _inStream->tellg(); }; virtual void seekg (Int64 pos) { _inStream->seekg(pos); }; virtual void clear () { _inStream->clear(); }; private: std::istream * _inStream; }; class C_OStream: public Imf::OStream { public: C_OStream (ostream *fin) : OStream(""),_outStream(fin) {}; virtual void write (const char c[/*n*/], int n) { _outStream->write(c,n); }; virtual Int64 tellp () { return _outStream->tellp(); }; virtual void seekp (Int64 pos) { _outStream->seekp(pos); }; private: std::ostream * _outStream; }; unsigned char *exr_load(std::istream& fin, int *width_ret, int *height_ret, int *numComponents_ret, unsigned int *dataType_ret) { unsigned char *buffer=NULL; // returned to sender & as read from the disk bool inputError = false; Array2D<Rgba> pixels; int width=0,height=0,numComponents; try { C_IStream inStream(&fin); RgbaInputFile rgbafile(inStream); Box2i dw = rgbafile.dataWindow(); /*RgbaChannels channels =*/ rgbafile.channels(); (*width_ret) = width = dw.max.x - dw.min.x + 1; (*height_ret)=height = dw.max.y - dw.min.y + 1; (*dataType_ret) = GL_HALF_FLOAT; pixels.resizeErase (height, width); rgbafile.setFrameBuffer((&pixels)[0][0] - dw.min.x - dw.min.y * width, 1, width); rgbafile.readPixels(dw.min.y, dw.max.y); } catch( char * str ) { OSG_WARN << "exr_load error : " << str << std::endl; inputError = true; } //If error during stream read return a empty pointer if (inputError) { return buffer; } //If there is no information in alpha channel do not store the alpha channel numComponents = 3; for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { if (pixels[i][j].a != half(1.0f) ) { numComponents = 4; break; } } } (*numComponents_ret) = numComponents; if (!( numComponents == 3 || numComponents == 4)) { return NULL; } //Copy and allocate data to a unsigned char array that OSG can use for texturing unsigned dataSize = (sizeof(half) * height * width * numComponents); //buffer = new unsigned char[dataSize]; buffer = (unsigned char*)malloc(dataSize); half* pOut = (half*) buffer; for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { (*pOut) = pixels[i][j].r; pOut++; (*pOut) = pixels[i][j].g; pOut++; (*pOut) = pixels[i][j].b; pOut++; if (numComponents >= 4) { (*pOut) = pixels[i][j].a; pOut++; } } } return buffer; } class ReaderWriterEXR : public osgDB::ReaderWriter { public: ReaderWriterEXR() { } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"exr"); } virtual const char* className() const { return "EXR Image Reader"; } virtual ReadResult readObject(std::istream& fin,const osgDB::ReaderWriter::Options* options =NULL) const { return readImage(fin, options); } virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options =NULL) const { return readImage(file, options); } virtual ReadResult readImage(std::istream& fin,const Options* =NULL) const { return readEXRStream(fin); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; osgDB::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary); if(!istream) return ReadResult::FILE_NOT_HANDLED; ReadResult rr = readEXRStream(istream); if(rr.validImage()) { rr.getImage()->setFileName(fileName); } return rr; } virtual WriteResult writeImage(const osg::Image& image,std::ostream& fout,const Options*) const { bool success = writeEXRStream(image, fout, "<output stream>"); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } virtual WriteResult writeImage(const osg::Image &img,const std::string& fileName, const osgDB::ReaderWriter::Options*) const { std::string ext = osgDB::getFileExtension(fileName); if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; osgDB::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary); if(!fout) return WriteResult::ERROR_IN_WRITING_FILE; bool success = writeEXRStream(img, fout, fileName); fout.close(); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } protected: bool writeEXRStream(const osg::Image &img, std::ostream& fout, const std::string &fileName) const { bool writeOK = true; //Obtain data from texture int width = img.s(); int height = img.t(); unsigned int pixelFormat = img.getPixelFormat(); int numComponents = img.computeNumComponents(pixelFormat); unsigned int dataType = img.getDataType(); //Validates image data //if numbers of components matches if (!( numComponents == 3 || numComponents == 4)) { writeOK = false; return false; } if (!( dataType == GL_HALF_FLOAT || dataType == GL_FLOAT)) { writeOK = false; return false; } //Create a stream to save to C_OStream outStream(&fout); //Copy data from texture to rgba pixel format Array2D<Rgba> outPixels(height,width); //If texture is half format if (dataType == GL_HALF_FLOAT) { for (long i = height-1; i >= 0; i--) { half* pOut = (half*) img.data(0,i); for (long j = 0 ; j < width; j++) { outPixels[i][j].r = (*pOut); pOut++; outPixels[i][j].g = (*pOut); pOut++; outPixels[i][j].b = (*pOut); pOut++; if (numComponents >= 4) { outPixels[i][j].a = (*pOut); pOut++; } else{outPixels[i][j].a = 1.0f;} } } } else if (dataType == GL_FLOAT) { float* pOut = (float*) img.data(); for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { outPixels[i][j].r = half(*pOut); pOut++; outPixels[i][j].g = half(*pOut); pOut++; outPixels[i][j].b = half(*pOut); pOut++; if (numComponents >= 4) { outPixels[i][j].a = half(*pOut); pOut++; } else {outPixels[i][j].a = 1.0f;} } } } else { //If texture format not supported return false; } try { //Write to stream Header outHeader(width, height); RgbaOutputFile rgbaFile (outStream, outHeader, WRITE_RGBA); rgbaFile.setFrameBuffer ((&outPixels)[0][0], 1, width); rgbaFile.writePixels (height); } catch( char * str ) { OSG_WARN << "writeEXRStream error : " << str << std::endl; writeOK = false; } return writeOK; } ReadResult readEXRStream(std::istream& fin) const { unsigned char *imageData = NULL; int width_ret = 0; int height_ret = 0; int numComponents_ret = 4; unsigned int dataType_ret = GL_UNSIGNED_BYTE; unsigned int pixelFormat = GL_RGB; unsigned int interNalTextureFormat = GL_RGB; imageData = exr_load(fin,&width_ret,&height_ret,&numComponents_ret,&dataType_ret); if (imageData==NULL) return ReadResult::FILE_NOT_HANDLED; int s = width_ret; int t = height_ret; int r = 1; if (dataType_ret == GL_HALF_FLOAT) { interNalTextureFormat = numComponents_ret == 1 ? GL_LUMINANCE16F_ARB : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA16F_ARB : numComponents_ret == 3 ? GL_RGB16F_ARB : numComponents_ret == 4 ? GL_RGBA16F_ARB : (GLenum)-1; } else if (dataType_ret == GL_FLOAT) { interNalTextureFormat = numComponents_ret == 1 ? GL_LUMINANCE32F_ARB : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA32F_ARB : numComponents_ret == 3 ? GL_RGB32F_ARB : numComponents_ret == 4 ? GL_RGBA32F_ARB : (GLenum)-1; } pixelFormat = numComponents_ret == 1 ? GL_LUMINANCE : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA : numComponents_ret == 3 ? GL_RGB : numComponents_ret == 4 ? GL_RGBA : (GLenum)-1; unsigned int dataType = dataType_ret; osg::Image* pOsgImage = new osg::Image; pOsgImage->setImage(s,t,r, interNalTextureFormat, pixelFormat, dataType, imageData, osg::Image::USE_MALLOC_FREE); return pOsgImage; } }; // now register with Registry to instantiate the exr suport // reader/writer. REGISTER_OSGPLUGIN(exr, ReaderWriterEXR) <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Rafael Rivera * * 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. */ // An Anonymous fellow and Peter Bright (yes, that guy) helped me refactor. // Appreciate it, sirs. #include "stdafx.h" // {7B2D8DFB-D190-344E-BF60-6EAC09922BBF} DEFINE_PROPERTYKEY(PKEY_WINX_HASH, 0xFB8D2D7B, 0x90D1, 0x4E34, 0xBF, 0x60, 0x6E, 0xAC, 0x09, 0x92, 0x2B, 0xBF, 0x02); #define CHECKHR(HR, MESSAGE) \ if(FAILED(HR)) \ { \ if(MESSAGE) wprintf(L"%s (hr: %X)\r\n", MESSAGE, hr); \ return HR; \ } #define GUID_MAX_LEN 40 using namespace std; HRESULT GeneralizePath(const wchar_t*, wchar_t*, size_t); int wmain(int argc, wchar_t* argv[]) { wprintf( L"\nHashLnk v0.2.0.0\n" L"Copyright(c) 2012 Rafael Rivera\n" L"Within Windows - http://withinwindows.com\n\n"); if(argc != 2) { wprintf(L"usage: hashlnk <.lnk file>\n\n"); return ERROR_BAD_ARGUMENTS; } DWORD bufferSize = GetFullPathNameW(argv[1], 0, nullptr, nullptr); if(bufferSize == 0) { wprintf(L"Specified path is invalid."); return ERROR_INVALID_PARAMETER; } unique_ptr<wchar_t[]> resolvedTarget(new wchar_t[bufferSize]); GetFullPathNameW(argv[1], bufferSize, resolvedTarget.get(), nullptr); if(!PathFileExistsW(resolvedTarget.get())) { wprintf(L"Specified file does not exist."); return ERROR_FILE_NOT_FOUND; } HRESULT hr = CoInitialize(nullptr); CHECKHR(hr, L"Failed to initialize COM."); // // Let's pull out the shortcut's target path/args // CComPtr<IShellItem2> lnk; hr = SHCreateItemFromParsingName(resolvedTarget.get(), nullptr, IID_PPV_ARGS(&lnk)); CHECKHR(hr, L"Failed to create shell item."); CComHeapPtr<wchar_t> targetPath; hr = lnk->GetString(PKEY_Link_TargetParsingPath, &targetPath); CHECKHR(hr, L"Failed to retrieve target path."); unique_ptr<wchar_t[]> generalizedPath(new wchar_t[MAX_PATH]); hr = GeneralizePath(targetPath, generalizedPath.get(), MAX_PATH); if(FAILED(hr)) { return hr; } CComHeapPtr<wchar_t> targetArgs; hr = lnk->GetString(PKEY_Link_Arguments, &targetArgs); if(FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_NOT_FOUND)) { wprintf(L"Failed to retrieve target arguments."); return hr; } // // Glue everything together and lowercase it, so we can hash it. // const wchar_t salt[] = L"do not prehash links. this should only be done by the user."; wstring blob = generalizedPath.get(); if(targetArgs) { blob += targetArgs; } blob += salt; int lowerCaseLength = LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, blob.data(), blob.size(), nullptr, 0, nullptr, nullptr, 0); if(!lowerCaseLength) { wprintf(L"Failed to lowercase blob string."); return GetLastError(); } unique_ptr<wchar_t[]> hashableBlob(new wchar_t[lowerCaseLength]); LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, blob.data(), blob.size(), hashableBlob.get(), lowerCaseLength, nullptr, nullptr, 0); ULONG hash = 0; hr = HashData(reinterpret_cast<BYTE*>(hashableBlob.get()), lowerCaseLength * sizeof(wchar_t), reinterpret_cast<BYTE*>(&hash), sizeof(hash)); CHECKHR(hr, L"Failed to hash data."); // // We have a hash, let's stamp it onto the .lnk now. // CComPtr<IPropertyStore> store; hr = lnk->GetPropertyStore(GPS_READWRITE, IID_PPV_ARGS(&store)); CHECKHR(hr, L"Failed to get property store."); PROPVARIANT propValue = {0}; propValue.ulVal = hash; propValue.vt = VT_UI4; hr = store->SetValue(PKEY_WINX_HASH, propValue); CHECKHR(hr, L"Failed to set property store value."); hr = store->Commit(); CHECKHR(hr, L"Failed to write changes to .lnk."); wprintf(L"Hash generated and applied (0x%X)\n", hash); CoUninitialize(); return 0; } HRESULT GeneralizePath(const wchar_t* originalPath, wchar_t* generalizedPath, size_t capacity) { HRESULT hr = ERROR_SUCCESS; // // Do we need to do some trickery to get the Program Files // known folder? // BOOL isRunningUnderEmulation = FALSE; IsWow64Process(GetCurrentProcess(), &isRunningUnderEmulation); // // Because SHGetKnownFolderPath doesn't properly retrieve // FOLDERID_ProgramFilesX64 from 32-bit processes, I // abandoned its use. We'll use good ol' environment // variables instead. >_>. The FOLDERIDs are for // generalization purposes only. // // It sucks but not as much as distributing two // flavors of hashlnk. // KNOWNFOLDERID guids[3]; wchar_t* tokens[3]; if(isRunningUnderEmulation) { tokens[0] = L"%ProgramW6432%"; guids[0] = FOLDERID_ProgramFilesX64; } else { tokens[0] = L"%ProgramFiles%"; guids[0] = FOLDERID_ProgramFilesX86; } tokens[1] = L"%SystemRoot%\\System32"; guids[1] = FOLDERID_System; tokens[2] = L"%SystemRoot%"; guids[2] = FOLDERID_Windows; for(int i = 0; i < sizeof(guids) / sizeof(KNOWNFOLDERID); ++i) { unique_ptr<wchar_t[]> folderPath(new wchar_t[MAX_PATH]); int numCharsInPath = ExpandEnvironmentStringsW(tokens[i], folderPath.get(), MAX_PATH); if(numCharsInPath == 0) { CHECKHR(hr, L"Failed to resolve known folder location."); } --numCharsInPath; // Remove NULL terminator from count. int numCommonChars = PathCommonPrefixW(folderPath.get(), originalPath, NULL); if(numCommonChars < numCharsInPath) { continue; } unique_ptr<wchar_t[]> guid(new wchar_t[GUID_MAX_LEN]); if(!StringFromGUID2(guids[i], guid.get(), GUID_MAX_LEN)) { hr = E_OUTOFMEMORY; CHECKHR(hr, L"Failed to derive string from known folder GUID."); } ZeroMemory(generalizedPath, capacity); hr = StringCchCatW(generalizedPath, MAX_PATH, guid.get()); CHECKHR(hr, L"Failed to build generalized path."); hr = StringCchCatW(generalizedPath, MAX_PATH, originalPath + numCommonChars); CHECKHR(hr, L"Failed to build generalized path."); break; } return hr; }<commit_msg>Untabbify For Reals<commit_after>/* * Copyright (c) 2012 Rafael Rivera * * 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. */ // An Anonymous fellow and Peter Bright (yes, that guy) helped me refactor. // Appreciate it, sirs. #include "stdafx.h" // {7B2D8DFB-D190-344E-BF60-6EAC09922BBF} DEFINE_PROPERTYKEY(PKEY_WINX_HASH, 0xFB8D2D7B, 0x90D1, 0x4E34, 0xBF, 0x60, 0x6E, 0xAC, 0x09, 0x92, 0x2B, 0xBF, 0x02); #define CHECKHR(HR, MESSAGE) \ if(FAILED(HR)) \ { \ if(MESSAGE) wprintf(L"%s (hr: %X)\r\n", MESSAGE, hr); \ return HR; \ } #define GUID_MAX_LEN 40 using namespace std; HRESULT GeneralizePath(const wchar_t*, wchar_t*, size_t); int wmain(int argc, wchar_t* argv[]) { wprintf( L"\nHashLnk v0.2.0.0\n" L"Copyright(c) 2012 Rafael Rivera\n" L"Within Windows - http://withinwindows.com\n\n"); if(argc != 2) { wprintf(L"usage: hashlnk <.lnk file>\n\n"); return ERROR_BAD_ARGUMENTS; } DWORD bufferSize = GetFullPathNameW(argv[1], 0, nullptr, nullptr); if(bufferSize == 0) { wprintf(L"Specified path is invalid."); return ERROR_INVALID_PARAMETER; } unique_ptr<wchar_t[]> resolvedTarget(new wchar_t[bufferSize]); GetFullPathNameW(argv[1], bufferSize, resolvedTarget.get(), nullptr); if(!PathFileExistsW(resolvedTarget.get())) { wprintf(L"Specified file does not exist."); return ERROR_FILE_NOT_FOUND; } HRESULT hr = CoInitialize(nullptr); CHECKHR(hr, L"Failed to initialize COM."); // // Let's pull out the shortcut's target path/args // CComPtr<IShellItem2> lnk; hr = SHCreateItemFromParsingName(resolvedTarget.get(), nullptr, IID_PPV_ARGS(&lnk)); CHECKHR(hr, L"Failed to create shell item."); CComHeapPtr<wchar_t> targetPath; hr = lnk->GetString(PKEY_Link_TargetParsingPath, &targetPath); CHECKHR(hr, L"Failed to retrieve target path."); unique_ptr<wchar_t[]> generalizedPath(new wchar_t[MAX_PATH]); hr = GeneralizePath(targetPath, generalizedPath.get(), MAX_PATH); if(FAILED(hr)) { return hr; } CComHeapPtr<wchar_t> targetArgs; hr = lnk->GetString(PKEY_Link_Arguments, &targetArgs); if(FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_NOT_FOUND)) { wprintf(L"Failed to retrieve target arguments."); return hr; } // // Glue everything together and lowercase it, so we can hash it. // const wchar_t salt[] = L"do not prehash links. this should only be done by the user."; wstring blob = generalizedPath.get(); if(targetArgs) { blob += targetArgs; } blob += salt; int lowerCaseLength = LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, blob.data(), blob.size(), nullptr, 0, nullptr, nullptr, 0); if(!lowerCaseLength) { wprintf(L"Failed to lowercase blob string."); return GetLastError(); } unique_ptr<wchar_t[]> hashableBlob(new wchar_t[lowerCaseLength]); LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, blob.data(), blob.size(), hashableBlob.get(), lowerCaseLength, nullptr, nullptr, 0); ULONG hash = 0; hr = HashData(reinterpret_cast<BYTE*>(hashableBlob.get()), lowerCaseLength * sizeof(wchar_t), reinterpret_cast<BYTE*>(&hash), sizeof(hash)); CHECKHR(hr, L"Failed to hash data."); // // We have a hash, let's stamp it onto the .lnk now. // CComPtr<IPropertyStore> store; hr = lnk->GetPropertyStore(GPS_READWRITE, IID_PPV_ARGS(&store)); CHECKHR(hr, L"Failed to get property store."); PROPVARIANT propValue = {0}; propValue.ulVal = hash; propValue.vt = VT_UI4; hr = store->SetValue(PKEY_WINX_HASH, propValue); CHECKHR(hr, L"Failed to set property store value."); hr = store->Commit(); CHECKHR(hr, L"Failed to write changes to .lnk."); wprintf(L"Hash generated and applied (0x%X)\n", hash); CoUninitialize(); return 0; } HRESULT GeneralizePath(const wchar_t* originalPath, wchar_t* generalizedPath, size_t capacity) { HRESULT hr = ERROR_SUCCESS; // // Do we need to do some trickery to get the Program Files // known folder? // BOOL isRunningUnderEmulation = FALSE; IsWow64Process(GetCurrentProcess(), &isRunningUnderEmulation); // // Because SHGetKnownFolderPath doesn't properly retrieve // FOLDERID_ProgramFilesX64 from 32-bit processes, I // abandoned its use. We'll use good ol' environment // variables instead. >_>. The FOLDERIDs are for // generalization purposes only. // // It sucks but not as much as distributing two // flavors of hashlnk. // KNOWNFOLDERID guids[3]; wchar_t* tokens[3]; if(isRunningUnderEmulation) { tokens[0] = L"%ProgramW6432%"; guids[0] = FOLDERID_ProgramFilesX64; } else { tokens[0] = L"%ProgramFiles%"; guids[0] = FOLDERID_ProgramFilesX86; } tokens[1] = L"%SystemRoot%\\System32"; guids[1] = FOLDERID_System; tokens[2] = L"%SystemRoot%"; guids[2] = FOLDERID_Windows; for(int i = 0; i < sizeof(guids) / sizeof(KNOWNFOLDERID); ++i) { unique_ptr<wchar_t[]> folderPath(new wchar_t[MAX_PATH]); int numCharsInPath = ExpandEnvironmentStringsW(tokens[i], folderPath.get(), MAX_PATH); if(numCharsInPath == 0) { CHECKHR(hr, L"Failed to resolve known folder location."); } --numCharsInPath; // Remove NULL terminator from count. int numCommonChars = PathCommonPrefixW(folderPath.get(), originalPath, NULL); if(numCommonChars < numCharsInPath) { continue; } unique_ptr<wchar_t[]> guid(new wchar_t[GUID_MAX_LEN]); if(!StringFromGUID2(guids[i], guid.get(), GUID_MAX_LEN)) { hr = E_OUTOFMEMORY; CHECKHR(hr, L"Failed to derive string from known folder GUID."); } ZeroMemory(generalizedPath, capacity); hr = StringCchCatW(generalizedPath, MAX_PATH, guid.get()); CHECKHR(hr, L"Failed to build generalized path."); hr = StringCchCatW(generalizedPath, MAX_PATH, originalPath + numCommonChars); CHECKHR(hr, L"Failed to build generalized path."); break; } return hr; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: specialtypemanager.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 15:29:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <hash_map> #ifndef _SPECIALTYPEMANAGER_HXX_ #define _SPECIALTYPEMANAGER_HXX_ #ifndef _CODEMAKER_REGISTRY_HXX_ #include <codemaker/registry.hxx> #endif #ifndef _CODEMAKER_TYPEMANAGER_HXX_ #include <codemaker/typemanager.hxx> #endif struct SpecialTypeManagerImpl { T2TypeClassMap m_t2TypeClass; }; class SpecialTypeManager : public TypeManager { public: SpecialTypeManager(); ~SpecialTypeManager(); SpecialTypeManager( const SpecialTypeManager& value ) : TypeManager(value) , m_pImpl( value.m_pImpl ) { acquire(); } sal_Bool init(const ::rtl::OString& registryName); sal_Bool isValidType(const ::rtl::OString& name) { return sal_True; } TypeReader getTypeReader(const ::rtl::OString& name); RTTypeClass getTypeClass(const ::rtl::OString& name); sal_Int32 getSize() { return m_pImpl->m_t2TypeClass.size(); } protected: void acquire(); void release(); protected: SpecialTypeManagerImpl* m_pImpl; }; #endif // _CODEMAKER_TYPEMANAGER_HXX_ <commit_msg>INTEGRATION: CWS ooo20040704 (1.1.1.1.122); FILE MERGED 2004/06/28 13:00:45 cmc 1.1.1.1.122.1: #i30801# allow using system stl if possible<commit_after>/************************************************************************* * * $RCSfile: specialtypemanager.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-09-08 16:43:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SPECIALTYPEMANAGER_HXX_ #define _SPECIALTYPEMANAGER_HXX_ #ifndef _CODEMAKER_REGISTRY_HXX_ #include <codemaker/registry.hxx> #endif #ifndef _CODEMAKER_TYPEMANAGER_HXX_ #include <codemaker/typemanager.hxx> #endif struct SpecialTypeManagerImpl { T2TypeClassMap m_t2TypeClass; }; class SpecialTypeManager : public TypeManager { public: SpecialTypeManager(); ~SpecialTypeManager(); SpecialTypeManager( const SpecialTypeManager& value ) : TypeManager(value) , m_pImpl( value.m_pImpl ) { acquire(); } sal_Bool init(const ::rtl::OString& registryName); sal_Bool isValidType(const ::rtl::OString& name) { return sal_True; } TypeReader getTypeReader(const ::rtl::OString& name); RTTypeClass getTypeClass(const ::rtl::OString& name); sal_Int32 getSize() { return m_pImpl->m_t2TypeClass.size(); } protected: void acquire(); void release(); protected: SpecialTypeManagerImpl* m_pImpl; }; #endif // _CODEMAKER_TYPEMANAGER_HXX_ <|endoftext|>
<commit_before>/* * Player.cpp * * Created on: Nov 26, 2017 * Author: lowji */ #include "Player.h" #include "Card.h" Player::Player(string name){ this->name=name; } void Player::addOne(Card temp){ handOne=temp; } void Player::addTwo(Card temp){ handTwo=temp; } int Player::getTotalChips(){ return totalChips; } string Player::getName(){ return name; } Card Player::getHandOne(){ return handOne; } Card Player::getHandTwo(){ return handTwo; } int Player::getTempPool(){ return tempBetPool; } int Player::getPrevBet() { return prevBet; } void Player::setPrevBet(int num) { prevBet = num; } void Player::setTotalChips(int chips){ totalChips=chips; } void Player::setTempPool(int bet){ tempBetPool=bet; } void Player::resetTempPool(){ tempBetPool=0; } void Player::raise(int newBet){ setTempPool(tempBetPool + newBet); setTotalChips(totalChips-newBet); } void Player::blind(int bet){ tempBetPool = bet; } void Player::call(Player opp){ int change = opp.getTempPool()-tempBetPool; tempBetPool = opp.getTempPool(); setTotalChips(totalChips-change); } //only for AI void Player::decision(){ int strength; } <commit_msg>Fixed pointer issues<commit_after>/* * Player.cpp * * Created on: Nov 26, 2017 * Author: lowji */ #include "Player.h" #include "Card.h" Player::Player(string name){ this->name=name; } void Player::addOne(Card temp){ handOne=temp; } void Player::addTwo(Card temp){ handTwo=temp; } int Player::getTotalChips(){ return totalChips; } string Player::getName(){ return name; } Card Player::getHandOne(){ return handOne; } Card Player::getHandTwo(){ return handTwo; } int Player::getTempPool(){ return tempBetPool; } int Player::getPrevBet() { return prevBet; } void Player::setPrevBet(int num) { prevBet = num; } void Player::setTotalChips(int chips){ totalChips=chips; } void Player::setTempPool(int bet){ tempBetPool=bet; } void Player::resetTempPool(){ tempBetPool=0; } void Player::raise(int newBet){ setTempPool(tempBetPool + newBet); setTotalChips(totalChips-newBet); } void Player::blind(int bet){ tempBetPool = bet; } void Player::call(Player* opp){ int change = opp->getTempPool()-tempBetPool; tempBetPool = opp->getTempPool(); setTotalChips(totalChips-change); } //only for AI void Player::decision(){ int strength; } <|endoftext|>
<commit_before>#include "game.hpp" int Game::startGame() { std::string str; while(true) { std::getline(std::cin, str); if(!uciHandler(str)) { return 0; }; } } void Game::goFixedDepth() { clearCash(); variant.clear(); variant.resize(max_depth); std::vector<uint64_t>hash; std::vector<BitMove>pv; whiteUp = BLACK_WIN; blackUp = WHITE_WIN; bool basis = false; nodesCounter = 0; int max_depth_global = max_depth; max_depth = 1; start_timer = clock(); hasBestMove = false; double depth; MoveArray movesCritical; game_board.bitBoardMoveGenerator(movesCritical); if(movesCritical.count >= 0) { bestMove = movesCritical.moveArray[0]; hasBestMove = true; } for(; max_depth <= max_depth_global; ++max_depth) { pv.resize(0); whiteUp = BLACK_WIN; blackUp = WHITE_WIN; flattenHistory(); if(max_depth == max_depth_global) { basis = true; } negamax(game_board, -INFINITY, INFINITY, max_depth, 0, FIXED_DEPTH, false); hasBestMove = true; if(abs(bestScore) >= (WHITE_WIN - 100)) { break; } depth = max_depth; } end_timer = clock(); std::cout << "info depth " << depth << " "; printScore(bestScore); std::cout << " nodes " << nodesCounter << " nps " << (int)(nodesCounter / ((end_timer - start_timer) / CLOCKS_PER_SEC)) << " time " << (int)((end_timer - start_timer) / (CLOCKS_PER_SEC / 1000)) << "\n"; if(hasBestMove) { std::cout << "bestmove " << bestMove.getMoveString() << "\n"; } } void Game::goFixedTime(int tm) { time = tm; timer.start(); clearCash(); variant.clear(); variant.resize(max_depth); std::vector<uint64_t>hash; std::vector<BitMove>pv; whiteUp = BLACK_WIN; blackUp = WHITE_WIN; bool basis = false; nodesCounter = 0; start_timer = clock(); hasBestMove = false; double depth; MoveArray movesCritical; game_board.bitBoardMoveGenerator(movesCritical); if(movesCritical.count >= 0) { bestMove = movesCritical.moveArray[0]; hasBestMove = true; } for(max_depth = 1; timer.getTime() < time; ++max_depth) { pv.resize(0); whiteUp = BLACK_WIN; blackUp = WHITE_WIN; flattenHistory(); negamax(game_board, -INFINITY, INFINITY, max_depth, 0, FIXED_TIME, false); if(abs(bestScore) >= (WHITE_WIN - 100)) { break; } hasBestMove = true; depth = max_depth; } end_timer = clock(); std::cout << "info depth " << depth << " "; printScore(bestScore); std::cout << " nodes " << nodesCounter << " nps " << (int)(nodesCounter / ((end_timer - start_timer) / CLOCKS_PER_SEC)) << " time " << (int)((end_timer - start_timer) / (CLOCKS_PER_SEC / 1000)) << "\n"; if(hasBestMove) { std::cout << "bestmove " << bestMove.getMoveString() << "\n"; } } void Game::goTournament() { double tm, inc; if(game_board.whiteMove) { tm = wtime; inc = winc; } else { tm = btime; inc = binc; } double k = 50; goFixedTime(tm / k + inc - 100); } bool Game::move(std::string mv) { MoveArray moves; game_board.bitBoardMoveGenerator(moves); for(unsigned int i = 0; i < moves.count; ++i) { if(moves.moveArray[i].getMoveString() == mv) { game_board.move(moves.moveArray[i]); uint8_t color; if(game_board.whiteMove) { color = BLACK; } else { color = WHITE; } if(game_board.inCheck(color)) { game_board.goBack(); continue; } return true; } } return false; } <commit_msg>Добавлен запас в 100мс на фиксированном контроле<commit_after>#include "game.hpp" int Game::startGame() { std::string str; while(true) { std::getline(std::cin, str); if(!uciHandler(str)) { return 0; }; } } void Game::goFixedDepth() { clearCash(); variant.clear(); variant.resize(max_depth); std::vector<uint64_t>hash; std::vector<BitMove>pv; whiteUp = BLACK_WIN; blackUp = WHITE_WIN; bool basis = false; nodesCounter = 0; int max_depth_global = max_depth; max_depth = 1; start_timer = clock(); hasBestMove = false; double depth; MoveArray movesCritical; game_board.bitBoardMoveGenerator(movesCritical); if(movesCritical.count >= 0) { bestMove = movesCritical.moveArray[0]; hasBestMove = true; } for(; max_depth <= max_depth_global; ++max_depth) { pv.resize(0); whiteUp = BLACK_WIN; blackUp = WHITE_WIN; flattenHistory(); if(max_depth == max_depth_global) { basis = true; } negamax(game_board, -INFINITY, INFINITY, max_depth, 0, FIXED_DEPTH, false); hasBestMove = true; if(abs(bestScore) >= (WHITE_WIN - 100)) { break; } depth = max_depth; } end_timer = clock(); std::cout << "info depth " << depth << " "; printScore(bestScore); std::cout << " nodes " << nodesCounter << " nps " << (int)(nodesCounter / ((end_timer - start_timer) / CLOCKS_PER_SEC)) << " time " << (int)((end_timer - start_timer) / (CLOCKS_PER_SEC / 1000)) << "\n"; if(hasBestMove) { std::cout << "bestmove " << bestMove.getMoveString() << "\n"; } } void Game::goFixedTime(int tm) { if(tm >= 200) { tm -= 100; } time = tm; timer.start(); clearCash(); variant.clear(); variant.resize(max_depth); std::vector<uint64_t>hash; std::vector<BitMove>pv; whiteUp = BLACK_WIN; blackUp = WHITE_WIN; bool basis = false; nodesCounter = 0; start_timer = clock(); hasBestMove = false; double depth; MoveArray movesCritical; game_board.bitBoardMoveGenerator(movesCritical); if(movesCritical.count >= 0) { bestMove = movesCritical.moveArray[0]; hasBestMove = true; } for(max_depth = 1; timer.getTime() < time; ++max_depth) { pv.resize(0); whiteUp = BLACK_WIN; blackUp = WHITE_WIN; flattenHistory(); negamax(game_board, -INFINITY, INFINITY, max_depth, 0, FIXED_TIME, false); if(abs(bestScore) >= (WHITE_WIN - 100)) { break; } hasBestMove = true; depth = max_depth; } end_timer = clock(); std::cout << "info depth " << depth << " "; printScore(bestScore); std::cout << " nodes " << nodesCounter << " nps " << (int)(nodesCounter / ((end_timer - start_timer) / CLOCKS_PER_SEC)) << " time " << (int)((end_timer - start_timer) / (CLOCKS_PER_SEC / 1000)) << "\n"; if(hasBestMove) { std::cout << "bestmove " << bestMove.getMoveString() << "\n"; } } void Game::goTournament() { double tm, inc; if(game_board.whiteMove) { tm = wtime; inc = winc; } else { tm = btime; inc = binc; } double k = 50; goFixedTime(tm / k + inc - 100); } bool Game::move(std::string mv) { MoveArray moves; game_board.bitBoardMoveGenerator(moves); for(unsigned int i = 0; i < moves.count; ++i) { if(moves.moveArray[i].getMoveString() == mv) { game_board.move(moves.moveArray[i]); uint8_t color; if(game_board.whiteMove) { color = BLACK; } else { color = WHITE; } if(game_board.inCheck(color)) { game_board.goBack(); continue; } return true; } } return false; } <|endoftext|>
<commit_before> /* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkData.h" #include "SkFlate.h" #include "SkPDFCatalog.h" #include "SkPDFStream.h" #include "SkStream.h" static bool skip_compression(SkPDFCatalog* catalog) { return SkToBool(catalog->getDocumentFlags() & SkPDFDocument::kFavorSpeedOverSize_Flags); } SkPDFStream::SkPDFStream(SkStream* stream) : fState(kUnused_State), fData(stream) { SkSafeRef(stream); } SkPDFStream::SkPDFStream(SkData* data) : fState(kUnused_State) { setData(data); } SkPDFStream::SkPDFStream(const SkPDFStream& pdfStream) : SkPDFDict(), fState(kUnused_State), fData(pdfStream.fData.get()) { fData.get()->ref(); bool removeLength = true; // Don't uncompress an already compressed stream, but we could. if (pdfStream.fState == kCompressed_State) { fState = kCompressed_State; removeLength = false; } SkPDFDict::Iter dict(pdfStream); SkPDFName* key; SkPDFObject* value; SkPDFName lengthName("Length"); for (key = dict.next(&value); key != NULL; key = dict.next(&value)) { if (removeLength && *key == lengthName) { continue; } this->insert(key, value); } } SkPDFStream::~SkPDFStream() {} void SkPDFStream::emitObject(SkWStream* stream, SkPDFCatalog* catalog, bool indirect) { if (indirect) { return emitIndirectObject(stream, catalog); } if (!this->populate(catalog)) { return fSubstitute->emitObject(stream, catalog, indirect); } this->INHERITED::emitObject(stream, catalog, false); stream->writeText(" stream\n"); stream->writeStream(fData.get(), fData->getLength()); stream->writeText("\nendstream"); } size_t SkPDFStream::getOutputSize(SkPDFCatalog* catalog, bool indirect) { if (indirect) { return getIndirectOutputSize(catalog); } if (!this->populate(catalog)) { return fSubstitute->getOutputSize(catalog, indirect); } return this->INHERITED::getOutputSize(catalog, false) + strlen(" stream\n\nendstream") + fData->getLength(); } SkPDFStream::SkPDFStream() : fState(kUnused_State) {} void SkPDFStream::setData(SkData* data) { SkMemoryStream* stream = new SkMemoryStream; stream->setData(data); fData.reset(stream); // Transfer ownership. } void SkPDFStream::setData(SkStream* stream) { fData.reset(stream); SkSafeRef(stream); } bool SkPDFStream::populate(SkPDFCatalog* catalog) { if (fState == kUnused_State) { if (!skip_compression(catalog) && SkFlate::HaveFlate()) { SkDynamicMemoryWStream compressedData; SkAssertResult(SkFlate::Deflate(fData.get(), &compressedData)); if (compressedData.getOffset() < fData->getLength()) { SkMemoryStream* stream = new SkMemoryStream; stream->setData(compressedData.copyToData())->unref(); fData.reset(stream); // Transfer ownership. insertName("Filter", "FlateDecode"); } fState = kCompressed_State; } else { fState = kNoCompression_State; } insertInt("Length", fData->getLength()); } else if (fState == kNoCompression_State && !skip_compression(catalog) && SkFlate::HaveFlate()) { if (!fSubstitute.get()) { fSubstitute.reset(new SkPDFStream(*this)); catalog->setSubstitute(this, fSubstitute.get()); } return false; } return true; } <commit_msg>Revert "[PDF] Fix printing crashes caused by font streams that don't support getMemoryBase()."<commit_after> /* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkData.h" #include "SkFlate.h" #include "SkPDFCatalog.h" #include "SkPDFStream.h" #include "SkStream.h" static bool skip_compression(SkPDFCatalog* catalog) { return SkToBool(catalog->getDocumentFlags() & SkPDFDocument::kFavorSpeedOverSize_Flags); } SkPDFStream::SkPDFStream(SkStream* stream) : fState(kUnused_State), fData(stream) { SkSafeRef(stream); } SkPDFStream::SkPDFStream(SkData* data) : fState(kUnused_State) { setData(data); } SkPDFStream::SkPDFStream(const SkPDFStream& pdfStream) : SkPDFDict(), fState(kUnused_State), fData(pdfStream.fData.get()) { fData.get()->ref(); bool removeLength = true; // Don't uncompress an already compressed stream, but we could. if (pdfStream.fState == kCompressed_State) { fState = kCompressed_State; removeLength = false; } SkPDFDict::Iter dict(pdfStream); SkPDFName* key; SkPDFObject* value; SkPDFName lengthName("Length"); for (key = dict.next(&value); key != NULL; key = dict.next(&value)) { if (removeLength && *key == lengthName) { continue; } this->insert(key, value); } } SkPDFStream::~SkPDFStream() {} void SkPDFStream::emitObject(SkWStream* stream, SkPDFCatalog* catalog, bool indirect) { if (indirect) { return emitIndirectObject(stream, catalog); } if (!this->populate(catalog)) { return fSubstitute->emitObject(stream, catalog, indirect); } this->INHERITED::emitObject(stream, catalog, false); stream->writeText(" stream\n"); stream->write(fData->getMemoryBase(), fData->getLength()); stream->writeText("\nendstream"); } size_t SkPDFStream::getOutputSize(SkPDFCatalog* catalog, bool indirect) { if (indirect) { return getIndirectOutputSize(catalog); } if (!this->populate(catalog)) { return fSubstitute->getOutputSize(catalog, indirect); } return this->INHERITED::getOutputSize(catalog, false) + strlen(" stream\n\nendstream") + fData->getLength(); } SkPDFStream::SkPDFStream() : fState(kUnused_State) {} void SkPDFStream::setData(SkData* data) { SkMemoryStream* stream = new SkMemoryStream; stream->setData(data); fData.reset(stream); // Transfer ownership. } void SkPDFStream::setData(SkStream* stream) { fData.reset(stream); SkSafeRef(stream); } bool SkPDFStream::populate(SkPDFCatalog* catalog) { if (fState == kUnused_State) { if (!skip_compression(catalog) && SkFlate::HaveFlate()) { SkDynamicMemoryWStream compressedData; SkAssertResult(SkFlate::Deflate(fData.get(), &compressedData)); if (compressedData.getOffset() < fData->getLength()) { SkMemoryStream* stream = new SkMemoryStream; stream->setData(compressedData.copyToData())->unref(); fData.reset(stream); // Transfer ownership. insertName("Filter", "FlateDecode"); } fState = kCompressed_State; } else { fState = kNoCompression_State; } insertInt("Length", fData->getLength()); } else if (fState == kNoCompression_State && !skip_compression(catalog) && SkFlate::HaveFlate()) { if (!fSubstitute.get()) { fSubstitute.reset(new SkPDFStream(*this)); catalog->setSubstitute(this, fSubstitute.get()); } return false; } return true; } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2018-2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file adc.cpp * * Driver for the imxrt ADC. * * This is a low-rate driver, designed for sampling things like voltages * and so forth. It avoids the gross complexity of the NuttX ADC driver. */ #include <board_config.h> #include <stdint.h> #include <drivers/drv_hrt.h> #include <drivers/drv_adc.h> #include <px4_arch/adc.h> #include <hardware/imxrt_adc.h> #include <imxrt_periphclks.h> typedef uint32_t adc_chan_t; #define ADC_TOTAL_CHANNELS 16 #define _REG(_addr) (*(volatile uint32_t *)(_addr)) /* ADC register accessors */ #define REG(base_address, _reg) _REG((base_address) + (_reg)) #define rHC0(base_address) REG(base_address, IMXRT_ADC_HC0_OFFSET) /* Control register for hardware triggers */ #define rHC1(base_address) REG(base_address, IMXRT_ADC_HC1_OFFSET) /* Control register for hardware triggers */ #define rHC2(base_address) REG(base_address, IMXRT_ADC_HC2_OFFSET) /* Control register for hardware triggers */ #define rHC3(base_address) REG(base_address, IMXRT_ADC_HC3_OFFSET) /* Control register for hardware triggers */ #define rHC4(base_address) REG(base_address, IMXRT_ADC_HC4_OFFSET) /* Control register for hardware triggers */ #define rHC5(base_address) REG(base_address, IMXRT_ADC_HC5_OFFSET) /* Control register for hardware triggers */ #define rHC6(base_address) REG(base_address, IMXRT_ADC_HC6_OFFSET) /* Control register for hardware triggers */ #define rHC7(base_address) REG(base_address, IMXRT_ADC_HC7_OFFSET) /* Control register for hardware triggers */ #define rHS(base_address) REG(base_address, IMXRT_ADC_HS_OFFSET) /* Status register for HW triggers */ #define rR0(base_address) REG(base_address, IMXRT_ADC_R0_OFFSET) /* Data result register for HW triggers */ #define rR1(base_address) REG(base_address, IMXRT_ADC_R1_OFFSET) /* Data result register for HW triggers */ #define rR2(base_address) REG(base_address, IMXRT_ADC_R2_OFFSET) /* Data result register for HW triggers */ #define rR3(base_address) REG(base_address, IMXRT_ADC_R3_OFFSET) /* Data result register for HW triggers */ #define rR4(base_address) REG(base_address, IMXRT_ADC_R4_OFFSET) /* Data result register for HW triggers */ #define rR5(base_address) REG(base_address, IMXRT_ADC_R5_OFFSET) /* Data result register for HW triggers */ #define rR6(base_address) REG(base_address, IMXRT_ADC_R6_OFFSET) /* Data result register for HW triggers */ #define rR7(base_address) REG(base_address, IMXRT_ADC_R7_OFFSET) /* Data result register for HW triggers */ #define rCFG(base_address) REG(base_address, IMXRT_ADC_CFG_OFFSET) /* Configuration register */ #define rGC(base_address) REG(base_address, IMXRT_ADC_GC_OFFSET) /* General control register */ #define rGS(base_address) REG(base_address, IMXRT_ADC_GS_OFFSET) /* General status register */ #define rCV(base_address) REG(base_address, IMXRT_ADC_CV_OFFSET) /* Compare value register */ #define rOFS(base_address) REG(base_address, IMXRT_ADC_OFS_OFFSET) /* Offset correction value register */ #define rCAL(base_address) REG(base_address, IMXRT_ADC_CAL_OFFSET) /* Calibration value register */ int px4_arch_adc_init(uint32_t base_address) { static bool once = false; if (!once) { once = true; /* Input is Buss Clock 56 Mhz We will use /8 for 7 Mhz */ irqstate_t flags = px4_enter_critical_section(); imxrt_clockall_adc1(); rCFG(base_address) = ADC_CFG_ADICLK_IPGDIV2 | ADC_CFG_MODE_12BIT | \ ADC_CFG_ADIV_DIV8 | ADC_CFG_ADLSMP | ADC_CFG_ADSTS_6_20 | \ ADC_CFG_AVGS_4SMPL | ADC_CFG_OVWREN; px4_leave_critical_section(flags); /* Clear the CALF and begin the calibration */ rGS(base_address) = ADC_GS_CALF; rGC(base_address) = ADC_GC_CAL; uint32_t guard = 100; while (guard != 0 && (rGS(base_address) & ADC_GC_CAL) == 0) { guard--; usleep(1); } while ((rGS(base_address) & ADC_GC_CAL) == ADC_GC_CAL) { usleep(100); if (rGS(base_address) & ADC_GS_CALF) { return -1; } } if ((rHS(base_address) & ADC_HS_COCO0) == 0) { return -2; } if (rGS(base_address) & ADC_GS_CALF) { return -3; } /* dummy read to clear COCO of calibration */ int32_t r = rR0(base_address); UNUSED(r); /* kick off a sample and wait for it to complete */ hrt_abstime now = hrt_absolute_time(); rGC(base_address) = ADC_GC_AVGE; rHC0(base_address) = 0xd; // VREFSH = internal channel, for ADC self-test, hard connected to VRH internally while (!(rHS(base_address) & ADC_HS_COCO0)) { /* don't wait for more than 500us, since that means something broke - * should reset here if we see this */ if ((hrt_absolute_time() - now) > 500) { return -4; } } r = rR0(base_address); } // once return 0; } void px4_arch_adc_uninit(uint32_t base_address) { imxrt_clockoff_adc1(); } uint32_t px4_arch_adc_sample(uint32_t base_address, unsigned channel) { /* clear any previous COCO0 */ uint16_t result = rR0(base_address); rHC0(base_address) = channel; /* wait for the conversion to complete */ hrt_abstime now = hrt_absolute_time(); while (!(rHS(base_address) & ADC_HS_COCO0)) { /* don't wait for more than 50us, since that means something broke * should reset here if we see this */ if ((hrt_absolute_time() - now) > 50) { return 0xffff; } } /* read the result and clear COCO0 */ result = rR0(base_address); return result; } float px4_arch_adc_reference_v() { return BOARD_ADC_POS_REF_V; // TODO: provide true vref } uint32_t px4_arch_adc_temp_sensor_mask() { return 0; } uint32_t px4_arch_adc_dn_fullcount(void) { return 1 << 12; // 12 bit ADC } <commit_msg>nxp:imxrt ADC track Rev02 of ref manual change made in upstream<commit_after>/**************************************************************************** * * Copyright (C) 2018-2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file adc.cpp * * Driver for the imxrt ADC. * * This is a low-rate driver, designed for sampling things like voltages * and so forth. It avoids the gross complexity of the NuttX ADC driver. */ #include <board_config.h> #include <stdint.h> #include <drivers/drv_hrt.h> #include <drivers/drv_adc.h> #include <px4_arch/adc.h> #include <hardware/imxrt_adc.h> #include <imxrt_periphclks.h> typedef uint32_t adc_chan_t; #define ADC_TOTAL_CHANNELS 16 #define _REG(_addr) (*(volatile uint32_t *)(_addr)) /* ADC register accessors */ #define REG(base_address, _reg) _REG((base_address) + (_reg)) #define rHC0(base_address) REG(base_address, IMXRT_ADC_HC0_OFFSET) /* Control register for hardware triggers */ #define rHC1(base_address) REG(base_address, IMXRT_ADC_HC1_OFFSET) /* Control register for hardware triggers */ #define rHC2(base_address) REG(base_address, IMXRT_ADC_HC2_OFFSET) /* Control register for hardware triggers */ #define rHC3(base_address) REG(base_address, IMXRT_ADC_HC3_OFFSET) /* Control register for hardware triggers */ #define rHC4(base_address) REG(base_address, IMXRT_ADC_HC4_OFFSET) /* Control register for hardware triggers */ #define rHC5(base_address) REG(base_address, IMXRT_ADC_HC5_OFFSET) /* Control register for hardware triggers */ #define rHC6(base_address) REG(base_address, IMXRT_ADC_HC6_OFFSET) /* Control register for hardware triggers */ #define rHC7(base_address) REG(base_address, IMXRT_ADC_HC7_OFFSET) /* Control register for hardware triggers */ #define rHS(base_address) REG(base_address, IMXRT_ADC_HS_OFFSET) /* Status register for HW triggers */ #define rR0(base_address) REG(base_address, IMXRT_ADC_R0_OFFSET) /* Data result register for HW triggers */ #define rR1(base_address) REG(base_address, IMXRT_ADC_R1_OFFSET) /* Data result register for HW triggers */ #define rR2(base_address) REG(base_address, IMXRT_ADC_R2_OFFSET) /* Data result register for HW triggers */ #define rR3(base_address) REG(base_address, IMXRT_ADC_R3_OFFSET) /* Data result register for HW triggers */ #define rR4(base_address) REG(base_address, IMXRT_ADC_R4_OFFSET) /* Data result register for HW triggers */ #define rR5(base_address) REG(base_address, IMXRT_ADC_R5_OFFSET) /* Data result register for HW triggers */ #define rR6(base_address) REG(base_address, IMXRT_ADC_R6_OFFSET) /* Data result register for HW triggers */ #define rR7(base_address) REG(base_address, IMXRT_ADC_R7_OFFSET) /* Data result register for HW triggers */ #define rCFG(base_address) REG(base_address, IMXRT_ADC_CFG_OFFSET) /* Configuration register */ #define rGC(base_address) REG(base_address, IMXRT_ADC_GC_OFFSET) /* General control register */ #define rGS(base_address) REG(base_address, IMXRT_ADC_GS_OFFSET) /* General status register */ #define rCV(base_address) REG(base_address, IMXRT_ADC_CV_OFFSET) /* Compare value register */ #define rOFS(base_address) REG(base_address, IMXRT_ADC_OFS_OFFSET) /* Offset correction value register */ #define rCAL(base_address) REG(base_address, IMXRT_ADC_CAL_OFFSET) /* Calibration value register */ int px4_arch_adc_init(uint32_t base_address) { static bool once = false; if (!once) { once = true; /* Input is Buss Clock 56 Mhz We will use /8 for 7 Mhz */ irqstate_t flags = px4_enter_critical_section(); imxrt_clockall_adc1(); rCFG(base_address) = ADC_CFG_ADICLK_IPGDIV2 | ADC_CFG_MODE_12BIT | \ ADC_CFG_ADIV_DIV8 | ADC_CFG_ADLSMP | ADC_CFG_ADSTS_7_21 | \ ADC_CFG_AVGS_4SMPL | ADC_CFG_OVWREN; px4_leave_critical_section(flags); /* Clear the CALF and begin the calibration */ rGS(base_address) = ADC_GS_CALF; rGC(base_address) = ADC_GC_CAL; uint32_t guard = 100; while (guard != 0 && (rGS(base_address) & ADC_GC_CAL) == 0) { guard--; usleep(1); } while ((rGS(base_address) & ADC_GC_CAL) == ADC_GC_CAL) { usleep(100); if (rGS(base_address) & ADC_GS_CALF) { return -1; } } if ((rHS(base_address) & ADC_HS_COCO0) == 0) { return -2; } if (rGS(base_address) & ADC_GS_CALF) { return -3; } /* dummy read to clear COCO of calibration */ int32_t r = rR0(base_address); UNUSED(r); /* kick off a sample and wait for it to complete */ hrt_abstime now = hrt_absolute_time(); rGC(base_address) = ADC_GC_AVGE; rHC0(base_address) = 0xd; // VREFSH = internal channel, for ADC self-test, hard connected to VRH internally while (!(rHS(base_address) & ADC_HS_COCO0)) { /* don't wait for more than 500us, since that means something broke - * should reset here if we see this */ if ((hrt_absolute_time() - now) > 500) { return -4; } } r = rR0(base_address); } // once return 0; } void px4_arch_adc_uninit(uint32_t base_address) { imxrt_clockoff_adc1(); } uint32_t px4_arch_adc_sample(uint32_t base_address, unsigned channel) { /* clear any previous COCO0 */ uint16_t result = rR0(base_address); rHC0(base_address) = channel; /* wait for the conversion to complete */ hrt_abstime now = hrt_absolute_time(); while (!(rHS(base_address) & ADC_HS_COCO0)) { /* don't wait for more than 50us, since that means something broke * should reset here if we see this */ if ((hrt_absolute_time() - now) > 50) { return 0xffff; } } /* read the result and clear COCO0 */ result = rR0(base_address); return result; } float px4_arch_adc_reference_v() { return BOARD_ADC_POS_REF_V; // TODO: provide true vref } uint32_t px4_arch_adc_temp_sensor_mask() { return 0; } uint32_t px4_arch_adc_dn_fullcount(void) { return 1 << 12; // 12 bit ADC } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-08 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin link_ode$$ $spell retape bool CppAD $$ $index link_ode$$ $index ode, speed test$$ $index speed, test ode$$ $index test, ode speed$$ $section Speed Testing Gradient of Ode Solution$$ $head Prototype$$ $codei%extern bool link_ode( size_t %repeat% , bool %retape% , CppAD::vector<double> &%x% , CppAD::vector<double> &%gradient% ); %$$ $head f$$ The function $latex f : \R^n \rightarrow \R $$ that is define and computed by evaluating $cref/ode_evaluate/$$. $head repeat$$ The argument $icode repeat$$ is the number of different functions $latex f(x)$$ that the gradient is computed for. $head retape$$ $subhead true$$ If $icode retape$$ is true, the operation sequence is considered to change for each repetition. Thus an AD package can not use one recording of the operation sequence to compute the gradient for all of the repetitions. $subhead false$$ If $icode retape$$ is false, the operation sequence is known to be the same for each repetition. Thus an AD package may use one recording of the operation sequence to compute the gradient for all of the repetitions. $head x$$ The argument $icode x$$ has prototype $codei% CppAD::vector<double> &%x% %$$ The size of the vector $icode x$$ determines and is equal to the value of $latex n$$. The input value of the elements of $icode x$$ does not matter. On output, it has been set to the argument value for which the function, or its derivative, is being evaluated. The value of this vector must change with each repetition. $head gradient$$ The argument $icode gradient$$ is a vector with $latex n$$ elements. The input value of its elements does not matter. The output value of its elements is the gradient of the function $latex f(x)$$ that corresponds to output values of $icode i$$, $icode j$$ and $icode x$$. To be more specific, for $latex j = 0 , \ldots , n-1$$, $latex \[ \D{f}{x[j]} (x) = gradient [ j ] \] $$ $subhead double$$ In the case where $icode package$$ is $code double$$, only the first element of $icode gradient$$ is modified and it is set to the function value. $end ----------------------------------------------------------------------------- */ # include <cppad/vector.hpp> # include <cppad/speed/ode_evaluate.hpp> # include <cppad/near_equal.hpp> extern bool link_ode( size_t repeat , bool retape , CppAD::vector<double> &x , CppAD::vector<double> &gradient ); bool available_ode(void) { size_t n = 10; size_t repeat = 1; bool retape = true; CppAD::vector<double> x(n); CppAD::vector<double> gradient(n); return link_ode(repeat, retape, x, gradient); } bool correct_ode(bool is_package_double) { bool ok = true; size_t n = 10; size_t repeat = 1; CppAD::vector<double> x(n); CppAD::vector<double> gradient(n); bool retape = ! is_package_double; link_ode(repeat, retape, x, gradient); size_t m, size; if( is_package_double ) { m = 0; // check function value size = 1; } else { m = 1; // check gradient value size = n; } CppAD::vector<double> check(size); CppAD::ode_evaluate(x, m, check); size_t k; for( k = 0; k < size; k++) ok &= CppAD::NearEqual(check[k], gradient[k], 1e-10, 1e-10); return ok; } void speed_ode(size_t n, size_t repeat) { bool retape = true; size_t ell = 3 * n; CppAD::vector<double> x(n); CppAD::vector<size_t> i(ell), j(ell); CppAD::vector<double> gradient(n * n); link_ode(repeat, retape, x, gradient); return; } <commit_msg>trunk: undetected problem in previous commit<commit_after>/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-08 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin link_ode$$ $spell retape bool CppAD $$ $index link_ode$$ $index ode, speed test$$ $index speed, test ode$$ $index test, ode speed$$ $section Speed Testing Gradient of Ode Solution$$ $head Prototype$$ $codei%extern bool link_ode( size_t %repeat% , bool %retape% , CppAD::vector<double> &%x% , CppAD::vector<double> &%gradient% ); %$$ $head f$$ The function $latex f : \R^n \rightarrow \R $$ that is define and computed by evaluating $cref/ode_evaluate/$$. $head repeat$$ The argument $icode repeat$$ is the number of different functions $latex f(x)$$ that the gradient is computed for. $head retape$$ $subhead true$$ If $icode retape$$ is true, the operation sequence is considered to change for each repetition. Thus an AD package can not use one recording of the operation sequence to compute the gradient for all of the repetitions. $subhead false$$ If $icode retape$$ is false, the operation sequence is known to be the same for each repetition. Thus an AD package may use one recording of the operation sequence to compute the gradient for all of the repetitions. $head x$$ The argument $icode x$$ has prototype $codei% CppAD::vector<double> &%x% %$$ The size of the vector $icode x$$ determines and is equal to the value of $latex n$$. The input value of the elements of $icode x$$ does not matter. On output, it has been set to the argument value for which the function, or its derivative, is being evaluated. The value of this vector must change with each repetition. $head gradient$$ The argument $icode gradient$$ is a vector with $latex n$$ elements. The input value of its elements does not matter. The output value of its elements is the gradient of the function $latex f(x)$$ that corresponds to output values of $icode i$$, $icode j$$ and $icode x$$. To be more specific, for $latex j = 0 , \ldots , n-1$$, $latex \[ \D{f}{x[j]} (x) = gradient [ j ] \] $$ $subhead double$$ In the case where $icode package$$ is $code double$$, only the first element of $icode gradient$$ is modified and it is set to the function value. $end ----------------------------------------------------------------------------- */ # include <cppad/vector.hpp> # include <cppad/speed/ode_evaluate.hpp> # include <cppad/near_equal.hpp> extern bool link_ode( size_t repeat , bool retape , CppAD::vector<double> &x , CppAD::vector<double> &gradient ); bool available_ode(void) { size_t n = 10; size_t repeat = 1; bool retape = true; CppAD::vector<double> x(n); CppAD::vector<double> gradient(n); return link_ode(repeat, retape, x, gradient); } bool correct_ode(bool is_package_double) { bool ok = true; size_t n = 10; size_t repeat = 1; CppAD::vector<double> x(n); CppAD::vector<double> gradient(n); bool retape = ! is_package_double; link_ode(repeat, retape, x, gradient); size_t m, size; if( is_package_double ) { m = 0; // check function value size = 1; } else { m = 1; // check gradient value size = n; } CppAD::vector<double> check(size); CppAD::ode_evaluate(x, m, check); size_t k; for( k = 0; k < size; k++) ok &= CppAD::NearEqual(check[k], gradient[k], 1e-10, 1e-10); return ok; } void speed_ode(size_t n, size_t repeat) { bool retape = true; CppAD::vector<double> x(n); CppAD::vector<double> gradient(n); link_ode(repeat, retape, x, gradient); return; } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/DataStructures/TriangleMesh.h" #include "SurgSim/Framework/ObjectFactory.h" #include "SurgSim/Math/MathConvert.h" #include "SurgSim/Math/MeshShape.h" #include "SurgSim/Math/OdeState.h" #include "SurgSim/Math/Shape.h" #include "SurgSim/Physics/DeformableCollisionRepresentation.h" #include "SurgSim/Physics/DeformableRepresentation.h" namespace { SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::DeformableCollisionRepresentation); } namespace SurgSim { namespace Physics { DeformableCollisionRepresentation::DeformableCollisionRepresentation(const std::string& name) : SurgSim::Collision::Representation(name) { SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableCollisionRepresentation, std::shared_ptr<SurgSim::Math::Shape>, Shape, getShape, setShape); } DeformableCollisionRepresentation::~DeformableCollisionRepresentation() { } void DeformableCollisionRepresentation::setMesh(std::shared_ptr<SurgSim::DataStructures::TriangleMesh> mesh) { SURGSIM_ASSERT(!isInitialized()) << "Can't set mesh after initialization."; SURGSIM_ASSERT(mesh != nullptr) << "Can't use nullptr mesh."; m_shape = std::make_shared<SurgSim::Math::MeshShape>(*mesh); m_mesh = m_shape->getMesh(); } std::shared_ptr<SurgSim::DataStructures::TriangleMesh> DeformableCollisionRepresentation::getMesh() const { return m_mesh; } void DeformableCollisionRepresentation::update(const double& dt) { auto physicsRepresentation = m_deformable.lock(); SURGSIM_ASSERT(physicsRepresentation != nullptr) << "Failed to update. The DeformableCollisionRepresentation either was not attached to a " "Physics::Representation or the Physics::Representation has expired."; auto odeState = physicsRepresentation->getCurrentState(); const size_t numNodes = odeState->getNumNodes(); SURGSIM_ASSERT(m_mesh->getNumVertices() == numNodes) << "The number of nodes in the deformable does not match the number of vertices in the mesh."; for (size_t nodeId = 0; nodeId < numNodes; ++nodeId) { m_mesh->setVertexPosition(nodeId, odeState->getPosition(nodeId)); } m_mesh->update(); m_shape->updateAabbTree(); } bool DeformableCollisionRepresentation::doInitialize() { SURGSIM_ASSERT(m_mesh != nullptr) << "Mesh was not set."; auto physicsRepresentation = m_deformable.lock(); SURGSIM_ASSERT(physicsRepresentation != nullptr) << "Failed to initialize. The DeformableCollisionRepresentation either was not attached to a " "Physics::Representation or the Physics::Representation has expired."; return true; } bool DeformableCollisionRepresentation::doWakeUp() { auto physicsRepresentation = m_deformable.lock(); SURGSIM_ASSERT(physicsRepresentation != nullptr) << "DeformableCollisionRepresentation::doWakeUp(): " << "The Physics::Representation referred by this DeformableCollisionRepresentation has expired."; auto state = physicsRepresentation->getCurrentState(); SURGSIM_ASSERT(m_mesh->getNumVertices() == state->getNumNodes()) << "The number of nodes in the deformable does not match the number of vertices in the mesh."; update(0.0); return true; } int DeformableCollisionRepresentation::getShapeType() const { SURGSIM_ASSERT(m_shape != nullptr) << "No mesh or shape assigned to DeformableCollisionRepresentation " << getName(); return m_shape->getType(); } void DeformableCollisionRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape) { SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH) << "Deformable collision shape has to be a mesh. But what passed in is " << shape->getType(); auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(shape); m_shape = meshShape; m_mesh = meshShape->getMesh(); } const std::shared_ptr<SurgSim::Math::Shape> DeformableCollisionRepresentation::getShape() const { return m_shape; } void DeformableCollisionRepresentation::setDeformableRepresentation( std::shared_ptr<SurgSim::Physics::DeformableRepresentation>representation) { m_deformable = representation; } const std::shared_ptr<SurgSim::Physics::DeformableRepresentation> DeformableCollisionRepresentation::getDeformableRepresentation() const { auto physicsRepresentation = m_deformable.lock(); SURGSIM_ASSERT(physicsRepresentation != nullptr) << "Failed to get the deformable representation. The DeformableCollisionRepresentation either was not " "attached to a Physics::Representation or the Physics::Representation has expired."; return physicsRepresentation; } } // namespace Physics } // namespace SurgSim<commit_msg>Add assertion on OdeState returned by DeformableRepresentation<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/DataStructures/TriangleMesh.h" #include "SurgSim/Framework/ObjectFactory.h" #include "SurgSim/Math/MathConvert.h" #include "SurgSim/Math/MeshShape.h" #include "SurgSim/Math/OdeState.h" #include "SurgSim/Math/Shape.h" #include "SurgSim/Physics/DeformableCollisionRepresentation.h" #include "SurgSim/Physics/DeformableRepresentation.h" namespace { SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::DeformableCollisionRepresentation); } namespace SurgSim { namespace Physics { DeformableCollisionRepresentation::DeformableCollisionRepresentation(const std::string& name) : SurgSim::Collision::Representation(name) { SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableCollisionRepresentation, std::shared_ptr<SurgSim::Math::Shape>, Shape, getShape, setShape); } DeformableCollisionRepresentation::~DeformableCollisionRepresentation() { } void DeformableCollisionRepresentation::setMesh(std::shared_ptr<SurgSim::DataStructures::TriangleMesh> mesh) { SURGSIM_ASSERT(!isInitialized()) << "Can't set mesh after initialization."; SURGSIM_ASSERT(mesh != nullptr) << "Can't use nullptr mesh."; m_shape = std::make_shared<SurgSim::Math::MeshShape>(*mesh); m_mesh = m_shape->getMesh(); } std::shared_ptr<SurgSim::DataStructures::TriangleMesh> DeformableCollisionRepresentation::getMesh() const { return m_mesh; } void DeformableCollisionRepresentation::update(const double& dt) { auto physicsRepresentation = m_deformable.lock(); SURGSIM_ASSERT(physicsRepresentation != nullptr) << "Failed to update. The DeformableCollisionRepresentation either was not attached to a " "Physics::Representation or the Physics::Representation has expired."; auto odeState = physicsRepresentation->getCurrentState(); const size_t numNodes = odeState->getNumNodes(); SURGSIM_ASSERT(m_mesh->getNumVertices() == numNodes) << "The number of nodes in the deformable does not match the number of vertices in the mesh."; for (size_t nodeId = 0; nodeId < numNodes; ++nodeId) { m_mesh->setVertexPosition(nodeId, odeState->getPosition(nodeId)); } m_mesh->update(); m_shape->updateAabbTree(); } bool DeformableCollisionRepresentation::doInitialize() { SURGSIM_ASSERT(m_mesh != nullptr) << "Mesh was not set."; auto physicsRepresentation = m_deformable.lock(); SURGSIM_ASSERT(physicsRepresentation != nullptr) << "Failed to initialize. The DeformableCollisionRepresentation either was not attached to a " "Physics::Representation or the Physics::Representation has expired."; return true; } bool DeformableCollisionRepresentation::doWakeUp() { auto physicsRepresentation = m_deformable.lock(); SURGSIM_ASSERT(physicsRepresentation != nullptr) << "DeformableCollisionRepresentation::doWakeUp(): " << "The Physics::Representation referred by this DeformableCollisionRepresentation has expired."; auto state = physicsRepresentation->getCurrentState(); SURGSIM_ASSERT(nullptr != state) << "DeformableRepresentation " << physicsRepresentation->getName() << " holds an empty OdeState."; SURGSIM_ASSERT(m_mesh->getNumVertices() == state->getNumNodes()) << "The number of nodes in the deformable does not match the number of vertices in the mesh."; update(0.0); return true; } int DeformableCollisionRepresentation::getShapeType() const { SURGSIM_ASSERT(m_shape != nullptr) << "No mesh or shape assigned to DeformableCollisionRepresentation " << getName(); return m_shape->getType(); } void DeformableCollisionRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape) { SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH) << "Deformable collision shape has to be a mesh. But what passed in is " << shape->getType(); auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(shape); m_shape = meshShape; m_mesh = meshShape->getMesh(); } const std::shared_ptr<SurgSim::Math::Shape> DeformableCollisionRepresentation::getShape() const { return m_shape; } void DeformableCollisionRepresentation::setDeformableRepresentation( std::shared_ptr<SurgSim::Physics::DeformableRepresentation>representation) { m_deformable = representation; } const std::shared_ptr<SurgSim::Physics::DeformableRepresentation> DeformableCollisionRepresentation::getDeformableRepresentation() const { auto physicsRepresentation = m_deformable.lock(); SURGSIM_ASSERT(physicsRepresentation != nullptr) << "Failed to get the deformable representation. The DeformableCollisionRepresentation either was not " "attached to a Physics::Representation or the Physics::Representation has expired."; return physicsRepresentation; } } // namespace Physics } // namespace SurgSim<|endoftext|>
<commit_before>#include <metaSMT/support/parser/SMT2Parser.hpp> #include <metaSMT/support/parser/UTreeEvaluator.hpp> #include <string> #include <fstream> using namespace std; using namespace metaSMT; using namespace metaSMT::solver; using namespace metaSMT::evaluator; using namespace metaSMT::smt2; int main(int argc, char **argv) { int const STREAM_SIZE = 65535; typedef UTreeEvaluator<ContextType> Evaluator; char inputline[STREAM_SIZE]; string line; stringstream *buf = new stringstream; ContextType ctx; Evaluator evaluator(ctx); SMT2Parser<Evaluator> parser(evaluator); while(!cin.eof()){ cin.getline(inputline,STREAM_SIZE); assert( !std::cin.fail() ); if ( std::cin.fail() ) { std::cerr << "Error during input operation, e.g., stream size is too low" << '\n'; return -1; } line = inputline; // std::cerr << line << '\n'; *buf << line << endl; size_t found = line.find("(get-value"); if(line.compare("(check-sat)") == 0 || found != line.npos){ boost::spirit::utree::list_type ast; parser.parse(*buf, ast); evaluator.evaluateInstance(ast); delete buf; buf = new stringstream; } if(line.compare("(exit)") == 0){ break; } } return 0; } <commit_msg>smt2Input_evaluator reads strings of unlimited length and does not wait for an command ``(exit)''<commit_after>#include <metaSMT/support/parser/SMT2Parser.hpp> #include <metaSMT/support/parser/UTreeEvaluator.hpp> #include <string> #include <fstream> using namespace std; using namespace metaSMT; using namespace metaSMT::solver; using namespace metaSMT::evaluator; using namespace metaSMT::smt2; int main(int argc, char **argv) { typedef UTreeEvaluator<ContextType> Evaluator; string line; stringstream *buf = new stringstream; ContextType ctx; Evaluator evaluator(ctx); SMT2Parser<Evaluator> parser(evaluator); while( !cin.eof() ){ std::getline(std::cin, line); if ( std::cin.fail() ) { // stream end without exit or read error return 0; } // std::cerr << line << '\n'; *buf << line << endl; size_t found = line.find("(get-value"); if (line == "(check-sat)" || found != line.npos) { boost::spirit::utree::list_type ast; parser.parse(*buf, ast); evaluator.evaluateInstance(ast); delete buf; buf = new stringstream; } if ( line == "(exit)" ) { break; } } return 0; } <|endoftext|>
<commit_before>#include <plugintest.h> #include "testinstaller.h" using namespace QtAutoUpdater; class HomebrewTest : public PluginTest { Q_OBJECT protected: bool init() override; bool cleanup() override; QString backend() const override; QVariantMap config() override; QList<UpdateInfo> createInfos(const QVersionNumber &versionFrom, const QVersionNumber &versionTo) override; bool simulateInstall(const QVersionNumber &version) override; bool prepareUpdate(const QVersionNumber &version) override; bool canAbort(bool hard) const override; bool cancelState() const override; private: TestInstaller *_installer = nullptr; }; bool HomebrewTest::init() { TEST_WRAP_BEGIN _installer = new TestInstaller{this}; QVERIFY(_installer->setup()); TEST_WRAP_END } bool HomebrewTest::cleanup() { TEST_WRAP_BEGIN QVERIFY(_installer->cleanup()); _installer->deleteLater(); _installer = nullptr; TEST_WRAP_END } QString HomebrewTest::backend() const { return QStringLiteral("homebrew"); } QVariantMap HomebrewTest::config() { return { {QStringLiteral("packages"), QStringLiteral("qtautoupdatertestpackage")} }; } QList<UpdateInfo> HomebrewTest::createInfos(const QVersionNumber &versionFrom, const QVersionNumber &versionTo) { if (versionTo > versionFrom) { return { { QStringLiteral("qtautoupdatertestpackage"), versionTo, 0ull, QStringLiteral("qtautoupdatertestpackage") } }; } else return {}; } bool HomebrewTest::simulateInstall(const QVersionNumber &version) { TEST_WRAP_BEGIN if (_installer->isInstalled()) QVERIFY(_installer->uninstall()); QVERIFY(prepareUpdate(version)); QVERIFY(_installer->install()); TEST_WRAP_END } bool HomebrewTest::prepareUpdate(const QVersionNumber &version) { TEST_WRAP_BEGIN _installer->setVersion(version); QVERIFY(_installer->package()); TEST_WRAP_END } bool HomebrewTest::canAbort(bool hard) const { Q_UNUSED(hard) return true; } bool HomebrewTest::cancelState() const { return false; } QTEST_GUILESS_MAIN(HomebrewTest) #include "tst_homebrew.moc" <commit_msg>fix package id<commit_after>#include <plugintest.h> #include "testinstaller.h" using namespace QtAutoUpdater; class HomebrewTest : public PluginTest { Q_OBJECT protected: bool init() override; bool cleanup() override; QString backend() const override; QVariantMap config() override; QList<UpdateInfo> createInfos(const QVersionNumber &versionFrom, const QVersionNumber &versionTo) override; bool simulateInstall(const QVersionNumber &version) override; bool prepareUpdate(const QVersionNumber &version) override; bool canAbort(bool hard) const override; bool cancelState() const override; private: TestInstaller *_installer = nullptr; }; bool HomebrewTest::init() { TEST_WRAP_BEGIN _installer = new TestInstaller{this}; QVERIFY(_installer->setup()); TEST_WRAP_END } bool HomebrewTest::cleanup() { TEST_WRAP_BEGIN QVERIFY(_installer->cleanup()); _installer->deleteLater(); _installer = nullptr; TEST_WRAP_END } QString HomebrewTest::backend() const { return QStringLiteral("homebrew"); } QVariantMap HomebrewTest::config() { return { {QStringLiteral("packages"), QStringLiteral("skycoder42/qtautoupdatertest/qtautoupdatertestpackage")} }; } QList<UpdateInfo> HomebrewTest::createInfos(const QVersionNumber &versionFrom, const QVersionNumber &versionTo) { if (versionTo > versionFrom) { return { { QStringLiteral("skycoder42/qtautoupdatertest/qtautoupdatertestpackage"), versionTo, 0ull, QStringLiteral("skycoder42/qtautoupdatertest/qtautoupdatertestpackage") } }; } else return {}; } bool HomebrewTest::simulateInstall(const QVersionNumber &version) { TEST_WRAP_BEGIN if (_installer->isInstalled()) QVERIFY(_installer->uninstall()); QVERIFY(prepareUpdate(version)); QVERIFY(_installer->install()); TEST_WRAP_END } bool HomebrewTest::prepareUpdate(const QVersionNumber &version) { TEST_WRAP_BEGIN _installer->setVersion(version); QVERIFY(_installer->package()); TEST_WRAP_END } bool HomebrewTest::canAbort(bool hard) const { Q_UNUSED(hard) return true; } bool HomebrewTest::cancelState() const { return false; } QTEST_GUILESS_MAIN(HomebrewTest) #include "tst_homebrew.moc" <|endoftext|>
<commit_before>#include "Player.hpp" #include "Houses.hpp" #include <cassert> Player::Player(House theHouse, int theId): id(theId), house(theHouse), color(Houses::getDefaultColor(house)) { // SMELL: We also do this in the unit repository filenames[Unit::Type::Trike] = "Unit_Trike.bmp"; filenames[Unit::Type::Quad] = "Unit_Quad.bmp"; filenames[Unit::Type::Frigate] = "Unit_Frigate.bmp"; filenames[Unit::Type::Carryall] = "Unit_Carryall.bmp"; filenames[Unit::Type::Devastator] = "Unit_Devastator.bmp"; filenames[Unit::Type::Soldier] = "Unit_Soldier.bmp"; } sf::Color Player::getColor() const { return color; } bool Player::operator ==(const Player &other) const { return (id==other.id); } bool Player::operator !=(const Player &other) const { return !(*this==other); } void Player::recolor(sf::Image &image) const { sf::Vector2u imageSize = image.getSize(); for (unsigned int x = 0; x < imageSize.x; x++){ for (unsigned int y = 0; y < imageSize.y; y++){ sf::Color pixelColor = image.getPixel(x, y); if ((pixelColor == sf::Color(125,0,0)) || (pixelColor == sf::Color(214,0,0)) || (pixelColor == sf::Color(60,0,0)) || (pixelColor == sf::Color(89,0,0)) || (pixelColor == sf::Color(153,0,0)) || (pixelColor == sf::Color(182,0,0))) { image.setPixel(x, y, color); // TODO: Shade color here properly } } } } const sf::Texture &Player::getTexture(Unit::Type type) const { auto unitTexture = loadedUnitTextures.find(type); // SMELL: we also do this in the unitRepository, but the only difference // is coloring. Need to move to 1 spot if (unitTexture == loadedUnitTextures.end()) { sf::Image image; assert(filenames.find(type) != filenames.end()); image.loadFromFile("graphics/" + filenames.at(type)); image.createMaskFromColor(sf::Color(0,0,0)); recolor(image); sf::Texture texture; texture.loadFromImage(image); loadedUnitTextures.insert({type, std::move(texture)}); return loadedUnitTextures[type]; } return unitTexture->second; } <commit_msg>indentation<commit_after>#include "Player.hpp" #include "Houses.hpp" #include <cassert> Player::Player(House theHouse, int theId): id(theId), house(theHouse), color(Houses::getDefaultColor(house)) { // SMELL: We also do this in the unit repository filenames[Unit::Type::Trike] = "Unit_Trike.bmp"; filenames[Unit::Type::Quad] = "Unit_Quad.bmp"; filenames[Unit::Type::Frigate] = "Unit_Frigate.bmp"; filenames[Unit::Type::Carryall] = "Unit_Carryall.bmp"; filenames[Unit::Type::Devastator] = "Unit_Devastator.bmp"; filenames[Unit::Type::Soldier] = "Unit_Soldier.bmp"; } sf::Color Player::getColor() const { return color; } bool Player::operator ==(const Player &other) const { return (id==other.id); } bool Player::operator !=(const Player &other) const { return !(*this==other); } void Player::recolor(sf::Image &image) const { sf::Vector2u imageSize = image.getSize(); for (unsigned int x = 0; x < imageSize.x; x++){ for (unsigned int y = 0; y < imageSize.y; y++){ sf::Color pixelColor = image.getPixel(x, y); if ((pixelColor == sf::Color(125,0,0)) || (pixelColor == sf::Color(214,0,0)) || (pixelColor == sf::Color(60,0,0)) || (pixelColor == sf::Color(89,0,0)) || (pixelColor == sf::Color(153,0,0)) || (pixelColor == sf::Color(182,0,0))) { image.setPixel(x, y, color); // TODO: Shade color here properly } } } } const sf::Texture &Player::getTexture(Unit::Type type) const { auto unitTexture = loadedUnitTextures.find(type); // SMELL: we also do this in the unitRepository, but the only difference // is coloring. Need to move to 1 spot if (unitTexture == loadedUnitTextures.end()) { sf::Image image; assert(filenames.find(type) != filenames.end()); image.loadFromFile("graphics/" + filenames.at(type)); image.createMaskFromColor(sf::Color(0,0,0)); recolor(image); sf::Texture texture; texture.loadFromImage(image); loadedUnitTextures.insert({type, std::move(texture)}); return loadedUnitTextures[type]; } return unitTexture->second; } <|endoftext|>
<commit_before>/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "string_evaluator.h" #include "../../google_cloud_debugger_lib/ccomptr.h" #include "../../google_cloud_debugger_lib/i_eval_coordinator.h" #include "../../google_cloud_debugger_lib/error_messages.h" #include "../../google_cloud_debugger_lib/dbg_object.h" namespace google_cloud_debugger { StringEvaluator::StringEvaluator(std::string string_content) : string_content_(std::move(string_content)) { } const TypeSignature& StringEvaluator::GetStaticType() const { static const TypeSignature string_signature = { CorElementType::ELEMENT_TYPE_STRING }; return string_signature; } HRESULT StringEvaluator::Evaluate( std::shared_ptr<google_cloud_debugger::DbgObject> *dbg_object, IEvalCoordinator *eval_coordinator, std::ostream *err_stream) const { if (!dbg_object || !eval_coordinator || !err_stream) { return E_INVALIDARG; } // We use ICorDebugEval to create a string object. CComPtr<ICorDebugEval> debug_eval; HRESULT hr = eval_coordinator->CreateEval(&debug_eval); if (FAILED(hr)) { *err_stream << kFailedEvalCreation; return hr; } std::vector<WCHAR> wchar_string = ConvertStringToWCharPtr(string_content_); hr = debug_eval->NewString(wchar_string.data()); if (FAILED(hr)) { *err_stream << kFailedToCreateString; return hr; } BOOL exception_thrown; CComPtr<ICorDebugValue> debug_string; hr = eval_coordinator->WaitForEval(&exception_thrown, debug_eval, &debug_string); // TODO(quoct): If exception_thrown is set to true, then an error occurs when // we try to create the string. We should get this error. if (FAILED(hr)) { *err_stream << kFailedToCreateString; return hr; } std::unique_ptr<DbgObject> result_string_obj; hr = DbgObject::CreateDbgObject(debug_string, 2, &result_string_obj, err_stream); if (FAILED(hr)) { *err_stream << kFailedToCreateDbgObject; return hr; } *dbg_object = std::move(result_string_obj); return S_OK; } } // namespace google_cloud_debugger <commit_msg>Use constant in string evaluator<commit_after>/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "string_evaluator.h" #include "../../google_cloud_debugger_lib/ccomptr.h" #include "../../google_cloud_debugger_lib/i_eval_coordinator.h" #include "../../google_cloud_debugger_lib/error_messages.h" #include "../../google_cloud_debugger_lib/dbg_object.h" #include "../../google_cloud_debugger_lib/constants.h" namespace google_cloud_debugger { StringEvaluator::StringEvaluator(std::string string_content) : string_content_(std::move(string_content)) { } const TypeSignature& StringEvaluator::GetStaticType() const { static const TypeSignature string_signature = { CorElementType::ELEMENT_TYPE_STRING }; return string_signature; } HRESULT StringEvaluator::Evaluate( std::shared_ptr<google_cloud_debugger::DbgObject> *dbg_object, IEvalCoordinator *eval_coordinator, std::ostream *err_stream) const { if (!dbg_object || !eval_coordinator || !err_stream) { return E_INVALIDARG; } // We use ICorDebugEval to create a string object. CComPtr<ICorDebugEval> debug_eval; HRESULT hr = eval_coordinator->CreateEval(&debug_eval); if (FAILED(hr)) { *err_stream << kFailedEvalCreation; return hr; } std::vector<WCHAR> wchar_string = ConvertStringToWCharPtr(string_content_); hr = debug_eval->NewString(wchar_string.data()); if (FAILED(hr)) { *err_stream << kFailedToCreateString; return hr; } BOOL exception_thrown; CComPtr<ICorDebugValue> debug_string; hr = eval_coordinator->WaitForEval(&exception_thrown, debug_eval, &debug_string); // TODO(quoct): If exception_thrown is set to true, then an error occurs when // we try to create the string. We should get this error. if (FAILED(hr)) { *err_stream << kFailedToCreateString; return hr; } std::unique_ptr<DbgObject> result_string_obj; hr = DbgObject::CreateDbgObject(debug_string, kDefaultObjectEvalDepth, &result_string_obj, err_stream); if (FAILED(hr)) { *err_stream << kFailedToCreateDbgObject; return hr; } *dbg_object = std::move(result_string_obj); return S_OK; } } // namespace google_cloud_debugger <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_LPDF_HPP #define STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_LPDF_HPP #include <stan/math/prim/mat/fun/columns_dot_product.hpp> #include <stan/math/prim/mat/fun/columns_dot_self.hpp> #include <stan/math/prim/mat/fun/dot_product.hpp> #include <stan/math/prim/mat/fun/dot_self.hpp> #include <stan/math/prim/mat/fun/log.hpp> #include <stan/math/prim/mat/fun/log_determinant.hpp> #include <stan/math/prim/mat/fun/mdivide_left_spd.hpp> #include <stan/math/prim/mat/fun/mdivide_left_tri_low.hpp> #include <stan/math/prim/mat/fun/multiply.hpp> #include <stan/math/prim/mat/fun/subtract.hpp> #include <stan/math/prim/mat/fun/sum.hpp> #include <stan/math/prim/mat/meta/vector_seq_view.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/meta/max_size_mvt.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <boost/random/normal_distribution.hpp> #include <boost/random/variate_generator.hpp> namespace stan { namespace math { /** * The log of the multivariate normal density for the given y, mu, and * a Cholesky factor L of the variance matrix. * Sigma = LL', a square, semi-positive definite matrix. * * * @param y A scalar vector * @param mu The mean vector of the multivariate normal distribution. * @param L The Cholesky decomposition of a variance matrix * of the multivariate normal distribution * @return The log of the multivariate normal density. * @throw std::domain_error if LL' is not square, not symmetric, * or not semi-positive definite. * @tparam T_y Type of scalar. * @tparam T_loc Type of location. * @tparam T_covar Type of scale. */ template <bool propto, typename T_y, typename T_loc, typename T_covar> typename return_type<T_y, T_loc, T_covar>::type multi_normal_cholesky_lpdf( const T_y& y, const T_loc& mu, const T_covar& L) { static const char* function = "multi_normal_cholesky_lpdf"; typedef typename scalar_type<T_covar>::type T_covar_elem; typedef typename stan::partials_return_type<T_y, T_loc, T_covar>::type T_partials_return; typedef Eigen::Matrix<T_partials_return, Eigen::Dynamic, Eigen::Dynamic> matrix_partials_t; typedef Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> vector_partials_t; T_partials_return logp(0.0); vector_seq_view<T_y> y_vec(y); vector_seq_view<T_loc> mu_vec(mu); size_t size_vec = max_size_mvt(y, mu); int size_y = y_vec[0].size(); int size_mu = mu_vec[0].size(); if (size_vec > 1) { int size_y_old = size_y; int size_y_new; for (size_t i = 1, size_ = length_mvt(y); i < size_; i++) { int size_y_new = y_vec[i].size(); check_size_match(function, "Size of one of the vectors of " "the random variable", size_y_new, "Size of another vector of the " "random variable", size_y_old); size_y_old = size_y_new; } int size_mu_old = size_mu; int size_mu_new; for (size_t i = 1, size_ = length_mvt(mu); i < size_; i++) { int size_mu_new = mu_vec[i].size(); check_size_match(function, "Size of one of the vectors of " "the location variable", size_mu_new, "Size of another vector of the " "location variable", size_mu_old); size_mu_old = size_mu_new; } (void)size_y_old; (void)size_y_new; (void)size_mu_old; (void)size_mu_new; } check_size_match(function, "Size of random variable", size_y, "size of location parameter", size_mu); check_size_match(function, "Size of random variable", size_y, "rows of covariance parameter", L.rows()); check_size_match(function, "Size of random variable", size_y, "columns of covariance parameter", L.cols()); for (size_t i = 0; i < size_vec; i++) { check_finite(function, "Location parameter", mu_vec[i]); check_not_nan(function, "Random variable", y_vec[i]); } operands_and_partials<T_y, T_loc, T_covar> ops_partials(y, mu, L); if (size_y == 0) return ops_partials.build(0.0); if (include_summand<propto>::value) logp += NEG_LOG_SQRT_TWO_PI * size_y * size_vec; matrix_partials_t L_dbl = value_of(L); matrix_partials_t trans_L_dbl = L_dbl.transpose(); matrix_partials_t grad_L; // analytic expressions taken from // http://qwone.com/~jason/writing/multivariateNormal.pdf // written by Jason D. M. Rennie // expressions adapted to avoid inversions if (!is_constant_struct<T_covar>::value) grad_L = matrix_partials_t::Zero(size_y, size_y); if (include_summand<propto, T_y, T_loc, T_covar_elem>::value) { for (size_t i = 0; i < size_vec; i++) { vector_partials_t y_minus_mu_dbl(size_y); for (int j = 0; j < size_y; j++) y_minus_mu_dbl(j) = value_of(y_vec[i](j)) - value_of(mu_vec[i](j)); vector_partials_t half = mdivide_left_tri<Eigen::Lower>(L_dbl, y_minus_mu_dbl); vector_partials_t scaled_diff = mdivide_left_tri<Eigen::Upper>(trans_L_dbl, half); // vector_d half // = L_dbl.template // triangularView<Eigen::Lower>().solve(y_minus_mu_dbl); // vector_d scaled_diff = inv_Sigma_dbl * y_minus_mu_dbl; // vector_d scaled_diff // = L_dbl.template // triangularView<Eigen::Lower>().transpose().solve(half); logp -= 0.5 * dot_self(half); if (!is_constant_struct<T_y>::value) { for (int j = 0; j < size_y; j++) ops_partials.edge1_.partials_vec_[i](j) -= scaled_diff(j); } if (!is_constant_struct<T_loc>::value) { for (int j = 0; j < size_y; j++) ops_partials.edge2_.partials_vec_[i](j) += scaled_diff(j); } if (!is_constant_struct<T_covar>::value) { grad_L += half * half.transpose(); } } if (!is_constant_struct<T_covar>::value) { grad_L = mdivide_left_tri<Eigen::Upper>(trans_L_dbl, grad_L); // L_dbl.template // triangularView<Eigen::Lower>().transpose().solveInPlace(grad_L); } } if (include_summand<propto, T_covar_elem>::value) { logp -= L_dbl.diagonal().array().log().sum() * size_vec; if (!is_constant_struct<T_covar>::value) { // grad_L -= size_vec // * L_dbl.template // triangularView<Eigen::Lower>().transpose().solve( // matrix_d::Identity(size_y, size_y)); grad_L -= size_vec * mdivide_left_tri<Eigen::Upper>(trans_L_dbl); } } if (!is_constant_struct<T_covar>::value) ops_partials.edge3_.partials_ = grad_L; return ops_partials.build(logp); } template <typename T_y, typename T_loc, typename T_covar> inline typename return_type<T_y, T_loc, T_covar>::type multi_normal_cholesky_lpdf(const T_y& y, const T_loc& mu, const T_covar& L) { return multi_normal_cholesky_lpdf<false>(y, mu, L); } } // namespace math } // namespace stan #endif <commit_msg>shorten computations a bit<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_LPDF_HPP #define STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_LPDF_HPP #include <stan/math/prim/mat/fun/columns_dot_product.hpp> #include <stan/math/prim/mat/fun/columns_dot_self.hpp> #include <stan/math/prim/mat/fun/dot_product.hpp> #include <stan/math/prim/mat/fun/dot_self.hpp> #include <stan/math/prim/mat/fun/log.hpp> #include <stan/math/prim/mat/fun/log_determinant.hpp> #include <stan/math/prim/mat/fun/mdivide_left_spd.hpp> #include <stan/math/prim/mat/fun/mdivide_left_tri_low.hpp> #include <stan/math/prim/mat/fun/multiply.hpp> #include <stan/math/prim/mat/fun/subtract.hpp> #include <stan/math/prim/mat/fun/sum.hpp> #include <stan/math/prim/mat/meta/vector_seq_view.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/meta/max_size_mvt.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <boost/random/normal_distribution.hpp> #include <boost/random/variate_generator.hpp> namespace stan { namespace math { /** * The log of the multivariate normal density for the given y, mu, and * a Cholesky factor L of the variance matrix. * Sigma = LL', a square, semi-positive definite matrix. * * * @param y A scalar vector * @param mu The mean vector of the multivariate normal distribution. * @param L The Cholesky decomposition of a variance matrix * of the multivariate normal distribution * @return The log of the multivariate normal density. * @throw std::domain_error if LL' is not square, not symmetric, * or not semi-positive definite. * @tparam T_y Type of scalar. * @tparam T_loc Type of location. * @tparam T_covar Type of scale. */ template <bool propto, typename T_y, typename T_loc, typename T_covar> typename return_type<T_y, T_loc, T_covar>::type multi_normal_cholesky_lpdf( const T_y& y, const T_loc& mu, const T_covar& L) { static const char* function = "multi_normal_cholesky_lpdf"; typedef typename scalar_type<T_covar>::type T_covar_elem; typedef typename stan::partials_return_type<T_y, T_loc, T_covar>::type T_partials_return; typedef Eigen::Matrix<T_partials_return, Eigen::Dynamic, Eigen::Dynamic> matrix_partials_t; typedef Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> vector_partials_t; T_partials_return logp(0.0); vector_seq_view<T_y> y_vec(y); vector_seq_view<T_loc> mu_vec(mu); size_t size_vec = max_size_mvt(y, mu); int size_y = y_vec[0].size(); int size_mu = mu_vec[0].size(); if (size_vec > 1) { int size_y_old = size_y; int size_y_new; for (size_t i = 1, size_ = length_mvt(y); i < size_; i++) { int size_y_new = y_vec[i].size(); check_size_match(function, "Size of one of the vectors of " "the random variable", size_y_new, "Size of another vector of the " "random variable", size_y_old); size_y_old = size_y_new; } int size_mu_old = size_mu; int size_mu_new; for (size_t i = 1, size_ = length_mvt(mu); i < size_; i++) { int size_mu_new = mu_vec[i].size(); check_size_match(function, "Size of one of the vectors of " "the location variable", size_mu_new, "Size of another vector of the " "location variable", size_mu_old); size_mu_old = size_mu_new; } (void)size_y_old; (void)size_y_new; (void)size_mu_old; (void)size_mu_new; } check_size_match(function, "Size of random variable", size_y, "size of location parameter", size_mu); check_size_match(function, "Size of random variable", size_y, "rows of covariance parameter", L.rows()); check_size_match(function, "Size of random variable", size_y, "columns of covariance parameter", L.cols()); for (size_t i = 0; i < size_vec; i++) { check_finite(function, "Location parameter", mu_vec[i]); check_not_nan(function, "Random variable", y_vec[i]); } operands_and_partials<T_y, T_loc, T_covar> ops_partials(y, mu, L); if (size_y == 0) return ops_partials.build(0.0); if (include_summand<propto>::value) logp += NEG_LOG_SQRT_TWO_PI * size_y * size_vec; matrix_partials_t L_dbl = value_of(L); matrix_partials_t trans_L_dbl = L_dbl.transpose(); matrix_partials_t grad_L; // analytic expressions taken from // http://qwone.com/~jason/writing/multivariateNormal.pdf // written by Jason D. M. Rennie // expressions adapted to avoid inversions if (!is_constant_struct<T_covar>::value) grad_L = matrix_partials_t::Zero(size_y, size_y); if (include_summand<propto, T_y, T_loc, T_covar_elem>::value) { for (size_t i = 0; i < size_vec; i++) { vector_partials_t y_minus_mu_dbl(size_y); for (int j = 0; j < size_y; j++) y_minus_mu_dbl(j) = value_of(y_vec[i](j)) - value_of(mu_vec[i](j)); vector_partials_t half = mdivide_left_tri<Eigen::Lower>(L_dbl, y_minus_mu_dbl); vector_partials_t scaled_diff = mdivide_left_tri<Eigen::Upper>(trans_L_dbl, half); // vector_d half // = L_dbl.template // triangularView<Eigen::Lower>().solve(y_minus_mu_dbl); // vector_d scaled_diff = inv_Sigma_dbl * y_minus_mu_dbl; // vector_d scaled_diff // = L_dbl.template // triangularView<Eigen::Lower>().transpose().solve(half); logp -= 0.5 * half.squaredNorm(); if (!is_constant_struct<T_y>::value) { for (int j = 0; j < size_y; j++) ops_partials.edge1_.partials_vec_[i](j) -= scaled_diff(j); } if (!is_constant_struct<T_loc>::value) { for (int j = 0; j < size_y; j++) ops_partials.edge2_.partials_vec_[i](j) += scaled_diff(j); } if (!is_constant_struct<T_covar>::value) { grad_L += scaled_diff * half.transpose(); } } } if (include_summand<propto, T_covar_elem>::value) { logp -= L_dbl.diagonal().array().log().sum() * size_vec; if (!is_constant_struct<T_covar>::value) { // grad_L -= size_vec // * L_dbl.template // triangularView<Eigen::Lower>().transpose().solve( // matrix_d::Identity(size_y, size_y)); grad_L -= size_vec * mdivide_left_tri<Eigen::Upper>(trans_L_dbl); } } if (!is_constant_struct<T_covar>::value) ops_partials.edge3_.partials_ = grad_L; return ops_partials.build(logp); } template <typename T_y, typename T_loc, typename T_covar> inline typename return_type<T_y, T_loc, T_covar>::type multi_normal_cholesky_lpdf(const T_y& y, const T_loc& mu, const T_covar& L) { return multi_normal_cholesky_lpdf<false>(y, mu, L); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "base/logging.h" #include "gl_state.h" #ifdef _WIN32 #include "GL/wglew.h" #endif #if defined(USING_GLES2) #if defined(ANDROID) PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM; PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV; PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV; #endif #if !defined(IOS) && !defined(__SYMBIAN32__) && !defined(MEEGO_EDITION_HARMATTAN) PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT; PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES; PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES; PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES; PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES; #endif #endif OpenGLState glstate; GLExtensions gl_extensions; int OpenGLState::state_count = 0; void OpenGLState::Initialize() { if(initialized) return; Restore(); initialized = true; } void OpenGLState::Restore() { int count = 0; blend.restore(); count++; blendEquation.restore(); count++; blendFunc.restore(); count++; blendColor.restore(); count++; scissorTest.restore(); count++; scissorRect.restore(); count++; cullFace.restore(); count++; cullFaceMode.restore(); count++; frontFace.restore(); count++; depthTest.restore(); count++; depthRange.restore(); count++; depthFunc.restore(); count++; depthWrite.restore(); count++; colorMask.restore(); count++; viewport.restore(); count++; stencilTest.restore(); count++; stencilOp.restore(); count++; stencilFunc.restore(); count++; dither.restore(); count++; if (count != state_count) { FLOG("OpenGLState::Restore is missing some states"); } } // http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array void CheckGLExtensions() { static bool done = false; if (done) return; done = true; memset(&gl_extensions, 0, sizeof(gl_extensions)); const char *extString = (const char *)glGetString(GL_EXTENSIONS); #ifdef WIN32 const char *wglString = wglGetExtensionsStringEXT(); gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0; #elif !defined(USING_GLES2) // const char *glXString = glXQueryExtensionString(); // gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0; #endif #ifdef USING_GLES2 gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0; gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0; gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0; gl_extensions.OES_mapbuffer = strstr(extString, "GL_OES_mapbuffer") != 0; #if defined(IOS) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) gl_extensions.OES_vertex_array_object = false; gl_extensions.EXT_discard_framebuffer = false; #else gl_extensions.OES_vertex_array_object = strstr(extString, "GL_OES_vertex_array_object") != 0; if (gl_extensions.OES_vertex_array_object) { glGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" ); glBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" ); glDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" ); glIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" ); ILOG("VAO available"); } gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0; if (gl_extensions.EXT_discard_framebuffer) { glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress("glDiscardFramebufferEXT"); } #endif #endif #ifdef ANDROID gl_extensions.QCOM_alpha_test = strstr(extString, "GL_QCOM_alpha_test") != 0; // Load extensions that are not auto-loaded by Android. if (gl_extensions.QCOM_alpha_test) { glAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress("glAlphaFuncQCOM"); } // Look for EGL extensions EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); const char *eglString = eglQueryString(display, EGL_EXTENSIONS); gl_extensions.EGL_NV_system_time = strstr(eglString, "EGL_NV_system_time") != 0; gl_extensions.EGL_NV_coverage_sample = strstr(eglString, "EGL_NV_coverage_sample") != 0; if (gl_extensions.EGL_NV_system_time) { eglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress("eglGetSystemTimeNV"); eglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress("eglGetSystemTimeFrequencyNV"); } #endif #ifdef USING_GLES2 gl_extensions.FBO_ARB = true; gl_extensions.FBO_EXT = false; #else gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0; gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0; #endif } void OpenGLState::SetVSyncInterval(int interval) { #ifdef _WIN32 if( wglSwapIntervalEXT ) wglSwapIntervalEXT(interval); #endif } <commit_msg>Add restore() for logicop<commit_after>#include "base/logging.h" #include "gl_state.h" #ifdef _WIN32 #include "GL/wglew.h" #endif #if defined(USING_GLES2) #if defined(ANDROID) PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM; PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV; PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV; #endif #if !defined(IOS) && !defined(__SYMBIAN32__) && !defined(MEEGO_EDITION_HARMATTAN) PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT; PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES; PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES; PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES; PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES; #endif #endif OpenGLState glstate; GLExtensions gl_extensions; int OpenGLState::state_count = 0; void OpenGLState::Initialize() { if(initialized) return; Restore(); initialized = true; } void OpenGLState::Restore() { int count = 0; blend.restore(); count++; blendEquation.restore(); count++; blendFunc.restore(); count++; blendColor.restore(); count++; colorLogicOp.restore(); count++; logicOp.restore(); count++; scissorTest.restore(); count++; scissorRect.restore(); count++; cullFace.restore(); count++; cullFaceMode.restore(); count++; frontFace.restore(); count++; depthTest.restore(); count++; depthRange.restore(); count++; depthFunc.restore(); count++; depthWrite.restore(); count++; colorMask.restore(); count++; viewport.restore(); count++; stencilTest.restore(); count++; stencilOp.restore(); count++; stencilFunc.restore(); count++; dither.restore(); count++; if (count != state_count) { FLOG("OpenGLState::Restore is missing some states"); } } // http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array void CheckGLExtensions() { static bool done = false; if (done) return; done = true; memset(&gl_extensions, 0, sizeof(gl_extensions)); const char *extString = (const char *)glGetString(GL_EXTENSIONS); #ifdef WIN32 const char *wglString = wglGetExtensionsStringEXT(); gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0; #elif !defined(USING_GLES2) // const char *glXString = glXQueryExtensionString(); // gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0; #endif #ifdef USING_GLES2 gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0; gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0; gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0; gl_extensions.OES_mapbuffer = strstr(extString, "GL_OES_mapbuffer") != 0; #if defined(IOS) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) gl_extensions.OES_vertex_array_object = false; gl_extensions.EXT_discard_framebuffer = false; #else gl_extensions.OES_vertex_array_object = strstr(extString, "GL_OES_vertex_array_object") != 0; if (gl_extensions.OES_vertex_array_object) { glGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" ); glBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" ); glDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" ); glIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" ); ILOG("VAO available"); } gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0; if (gl_extensions.EXT_discard_framebuffer) { glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress("glDiscardFramebufferEXT"); } #endif #endif #ifdef ANDROID gl_extensions.QCOM_alpha_test = strstr(extString, "GL_QCOM_alpha_test") != 0; // Load extensions that are not auto-loaded by Android. if (gl_extensions.QCOM_alpha_test) { glAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress("glAlphaFuncQCOM"); } // Look for EGL extensions EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); const char *eglString = eglQueryString(display, EGL_EXTENSIONS); gl_extensions.EGL_NV_system_time = strstr(eglString, "EGL_NV_system_time") != 0; gl_extensions.EGL_NV_coverage_sample = strstr(eglString, "EGL_NV_coverage_sample") != 0; if (gl_extensions.EGL_NV_system_time) { eglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress("eglGetSystemTimeNV"); eglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress("eglGetSystemTimeFrequencyNV"); } #endif #ifdef USING_GLES2 gl_extensions.FBO_ARB = true; gl_extensions.FBO_EXT = false; #else gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0; gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0; #endif } void OpenGLState::SetVSyncInterval(int interval) { #ifdef _WIN32 if( wglSwapIntervalEXT ) wglSwapIntervalEXT(interval); #endif } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Sacha Refshauge * */ // Qt implementation of the framework. // Currently supports: Symbian, Blackberry, Linux #include <QtGui/QApplication> #include <QUrl> #include <QDir> #include <QDesktopWidget> #include <QDesktopServices> #ifdef __SYMBIAN32__ #include <e32std.h> #endif #include "QtMain.h" void LaunchBrowser(const char *url) { QDesktopServices::openUrl(QUrl(url)); } void SimulateGamepad(InputState *input) { input->pad_lstick_x = 0; input->pad_lstick_y = 0; input->pad_rstick_x = 0; input->pad_rstick_y = 0; if (input->pad_buttons & PAD_BUTTON_JOY_UP) input->pad_lstick_y=1; else if (input->pad_buttons & PAD_BUTTON_JOY_DOWN) input->pad_lstick_y=-1; if (input->pad_buttons & PAD_BUTTON_JOY_LEFT) input->pad_lstick_x=-1; else if (input->pad_buttons & PAD_BUTTON_JOY_RIGHT) input->pad_lstick_x=1; } float CalculateDPIScale() { // Sane default for Symbian, Blackberry and Meego #ifdef __SYMBIAN32__ return 1.4f; #else return 1.2f; #endif } int main(int argc, char *argv[]) { #ifdef Q_WS_X11 QApplication::setAttribute(Qt::AA_X11InitThreads, true); #endif QApplication a(argc, argv); #ifdef __SYMBIAN32__ // Set RunFast hardware mode for VFPv2. Denormalised values are treated as 0. NaN used for all NaN situations. User::SetFloatingPointMode(EFpModeRunFast); #endif QSize res = QApplication::desktop()->screenGeometry().size(); if (res.width() < res.height()) res.transpose(); pixel_xres = res.width(); pixel_yres = res.height(); float dpi_scale = CalculateDPIScale(); dp_xres = (int)(pixel_xres * dpi_scale); dp_yres = (int)(pixel_yres * dpi_scale); net::Init(); #ifdef __SYMBIAN32__ char* savegame_dir = "E:/PPSSPP/"; #elif defined(BLACKBERRY) char* savegame_dir = "data/"; #else char* savegame_dir = "./"; #endif NativeInit(argc, (const char **)argv, savegame_dir, QDir::tempPath().toStdString().c_str(), "BADCOFFEE"); #if defined(USING_GLES2) MainUI w(dpi_scale); w.setAttribute(Qt::WA_LockLandscapeOrientation); w.resize(pixel_xres, pixel_yres); w.showFullScreen(); #endif MainAudio *audio = new MainAudio(); int ret = a.exec(); delete audio; NativeShutdown(); net::Shutdown(); return ret; } <commit_msg>Only run the UI on X11 for now until threads issue is resolved.<commit_after>/* * Copyright (c) 2012 Sacha Refshauge * */ // Qt implementation of the framework. // Currently supports: Symbian, Blackberry, Linux #include <QtGui/QApplication> #include <QUrl> #include <QDir> #include <QDesktopWidget> #include <QDesktopServices> #ifdef __SYMBIAN32__ #include <e32std.h> #endif #include "QtMain.h" void LaunchBrowser(const char *url) { QDesktopServices::openUrl(QUrl(url)); } void SimulateGamepad(InputState *input) { input->pad_lstick_x = 0; input->pad_lstick_y = 0; input->pad_rstick_x = 0; input->pad_rstick_y = 0; if (input->pad_buttons & PAD_BUTTON_JOY_UP) input->pad_lstick_y=1; else if (input->pad_buttons & PAD_BUTTON_JOY_DOWN) input->pad_lstick_y=-1; if (input->pad_buttons & PAD_BUTTON_JOY_LEFT) input->pad_lstick_x=-1; else if (input->pad_buttons & PAD_BUTTON_JOY_RIGHT) input->pad_lstick_x=1; } float CalculateDPIScale() { // Sane default for Symbian, Blackberry and Meego #ifdef __SYMBIAN32__ return 1.4f; #else return 1.2f; #endif } int main(int argc, char *argv[]) { #ifdef Q_WS_X11 QApplication::setAttribute(Qt::AA_X11InitThreads, true); #endif QApplication a(argc, argv); #ifdef __SYMBIAN32__ // Set RunFast hardware mode for VFPv2. Denormalised values are treated as 0. NaN used for all NaN situations. User::SetFloatingPointMode(EFpModeRunFast); #endif QSize res = QApplication::desktop()->screenGeometry().size(); if (res.width() < res.height()) res.transpose(); pixel_xres = res.width(); pixel_yres = res.height(); float dpi_scale = CalculateDPIScale(); dp_xres = (int)(pixel_xres * dpi_scale); dp_yres = (int)(pixel_yres * dpi_scale); net::Init(); #ifdef __SYMBIAN32__ char* savegame_dir = "E:/PPSSPP/"; #elif defined(BLACKBERRY) char* savegame_dir = "data/"; #else char* savegame_dir = "./"; #endif NativeInit(argc, (const char **)argv, savegame_dir, QDir::tempPath().toStdString().c_str(), "BADCOFFEE"); #ifndef Q_WS_X11 MainUI w(dpi_scale); w.setAttribute(Qt::WA_LockLandscapeOrientation); w.resize(pixel_xres, pixel_yres); w.showFullScreen(); #endif MainAudio *audio = new MainAudio(); int ret = a.exec(); delete audio; NativeShutdown(); net::Shutdown(); return ret; } <|endoftext|>