text
stringlengths 54
60.6k
|
---|
<commit_before>/** \brief Utility for finding referenced PPN's that we should have, but that are missing.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2020 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include "FileUtil.h"
#include "MARC.h"
#include "util.h"
int Main(int argc, char *argv[]) {
if (argc != 3)
::Usage("marc_input missing_references");
const auto marc_reader(MARC::Reader::Factory(argv[1]));
std::unique_ptr<MARC::Writer> marc_writer(nullptr);
const auto missing_references_log(FileUtil::OpenOutputFileOrDie(argv[2]));
std::unordered_set<std::string> all_ppns;
while (const auto record = marc_reader->read())
all_ppns.emplace(record.getControlNumber());
marc_reader->rewind();
std::unordered_map<std::string, std::set<std::string>> missing_ppns_to_referers_map;
while (const auto record = marc_reader->read()) {
for (const auto _787_field : record.getTagRange("787")) {
if (not StringUtil::StartsWith(_787_field.getFirstSubfieldWithCode('i'), "Rezension"))
continue;
for (const auto &subfield : _787_field.getSubfields()) {
if (subfield.code_ == 'w' and StringUtil::StartsWith(subfield.value_, "(DE-627)")) {
const auto referenced_ppn(subfield.value_.substr(__builtin_strlen("(DE-627)")));
if (all_ppns.find(referenced_ppn) == all_ppns.end()) {
auto missing_ppn_and_referers(missing_ppns_to_referers_map.find(referenced_ppn));
if (missing_ppn_and_referers != missing_ppns_to_referers_map.end())
missing_ppn_and_referers->second.emplace(record.getControlNumber());
else
missing_ppns_to_referers_map.emplace(referenced_ppn, std::set<std::string>{ record.getControlNumber() });
}
break;
}
}
}
}
for (const auto &[missing_ppn, referers] : missing_ppns_to_referers_map)
(*missing_references_log) << missing_ppn << " <- " << StringUtil::Join(referers, ", ") << '\n';
LOG_INFO("Found " + std::to_string(missing_ppns_to_referers_map.size()) + " missing reference(s).");
return EXIT_FAILURE;
}
<commit_msg>Now we send notification emails.<commit_after>/** \brief Utility for finding referenced PPN's that we should have, but that are missing.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2020 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include "DbConnection.h"
#include "EmailSender.h"
#include "FileUtil.h"
#include "MARC.h"
#include "UBTools.h"
#include "util.h"
namespace {
DbConnection *OpenOrCreateDatabase() {
const std::string DATABASE_PATH(UBTools::GetTuelibPath() + "previously_reported_missing_ppns.sq3");
if (FileUtil::Exists(DATABASE_PATH))
return new DbConnection(DATABASE_PATH, DbConnection::READWRITE);
DbConnection *db_connection(new DbConnection(DATABASE_PATH, DbConnection::CREATE));
db_connection->queryOrDie("CREATE TABLE missing_references (ppn PRIMARY TEXT KEY) WITHOUT ROWID");
return db_connection;
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 3)
::Usage("marc_input email_address");
const auto marc_reader(MARC::Reader::Factory(argv[1]));
std::unique_ptr<MARC::Writer> marc_writer(nullptr);
const auto missing_references_log(FileUtil::OpenOutputFileOrDie(argv[2]));
const std::string email_address(argv[2]);
if (not EmailSender::IsValidEmailAddress(email_address))
LOG_ERROR("\"" + email_address + "\" is not a valid email address!");
DbConnection *db_connection(OpenOrCreateDatabase());
std::unordered_set<std::string> all_ppns;
while (const auto record = marc_reader->read())
all_ppns.emplace(record.getControlNumber());
marc_reader->rewind();
std::unordered_map<std::string, std::set<std::string>> missing_ppns_to_referers_map;
while (const auto record = marc_reader->read()) {
for (const auto _787_field : record.getTagRange("787")) {
if (not StringUtil::StartsWith(_787_field.getFirstSubfieldWithCode('i'), "Rezension"))
continue;
for (const auto &subfield : _787_field.getSubfields()) {
if (subfield.code_ == 'w' and StringUtil::StartsWith(subfield.value_, "(DE-627)")) {
const auto referenced_ppn(subfield.value_.substr(__builtin_strlen("(DE-627)")));
if (all_ppns.find(referenced_ppn) == all_ppns.end()) {
auto missing_ppn_and_referers(missing_ppns_to_referers_map.find(referenced_ppn));
if (missing_ppn_and_referers != missing_ppns_to_referers_map.end())
missing_ppn_and_referers->second.emplace(record.getControlNumber());
else
missing_ppns_to_referers_map.emplace(referenced_ppn, std::set<std::string>{ record.getControlNumber() });
}
break;
}
}
}
}
std::string email_attachement;
unsigned new_missing_count(0);
for (const auto &[missing_ppn, referers] : missing_ppns_to_referers_map) {
db_connection->queryOrDie("SELECT ppn FROM missing_references WHERE ppn='" + missing_ppn + "'");
const DbResultSet result_set(db_connection->getLastResultSet());
if (result_set.empty()) {
++new_missing_count;
email_attachement += missing_ppn + " <- " + StringUtil::Join(referers, ", ") + "\n";
db_connection->queryOrDie("INSERT INTO missing_references (ppn) VALUES ('" + missing_ppn + "')");
}
}
LOG_INFO("Found " + std::to_string(missing_ppns_to_referers_map.size()) + " new missing reference(s).");
if (not email_attachement.empty()) {
const auto status_code(EmailSender::SendEmail("[email protected]", email_address, "Missing PPN's",
"Attached is the new list of " + std::to_string(new_missing_count) + " missing PPN('s).",
EmailSender::DO_NOT_SET_PRIORITY, EmailSender::PLAIN_TEXT, /* reply_to = */"",
/* use_ssl = */true, /* use_authentication = */true, { email_attachement }));
if (status_code > 299)
LOG_ERROR("Failed to send an email to \"" + email_address + "\"! The server returned "
+ std::to_string(status_code) + ".");
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wakeupthread.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:28:08 $
*
* 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
*
************************************************************************/
//_______________________________________________
// include files of own module
#ifndef __FRAMEWORK_HELPER_WAKEUPTHREAD_HXX_
#include <helper/wakeupthread.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
//_______________________________________________
// namespace
namespace framework{
//_______________________________________________
// declarations
//***********************************************
WakeUpThread::WakeUpThread(const css::uno::Reference< css::util::XUpdatable >& xListener)
: ThreadHelpBase( )
, m_xListener (xListener)
{
}
//***********************************************
void SAL_CALL WakeUpThread::run()
{
::osl::Condition aSleeper;
TimeValue aTime;
aTime.Seconds = 0;
aTime.Nanosec = 25000000; // 25 msec
while(schedule())
{
aSleeper.reset();
aSleeper.wait(&aTime);
// SAFE ->
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::util::XUpdatable > xListener(m_xListener.get(), css::uno::UNO_QUERY);
aReadLock.unlock();
// <- SAFE
if (xListener.is())
xListener->update();
}
}
//***********************************************
void SAL_CALL WakeUpThread::onTerminated()
{
delete this;
}
} // namespace framework
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.202); FILE MERGED 2006/09/01 17:29:12 kaib 1.4.202.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wakeupthread.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:01:54 $
*
* 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_framework.hxx"
//_______________________________________________
// include files of own module
#ifndef __FRAMEWORK_HELPER_WAKEUPTHREAD_HXX_
#include <helper/wakeupthread.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
//_______________________________________________
// namespace
namespace framework{
//_______________________________________________
// declarations
//***********************************************
WakeUpThread::WakeUpThread(const css::uno::Reference< css::util::XUpdatable >& xListener)
: ThreadHelpBase( )
, m_xListener (xListener)
{
}
//***********************************************
void SAL_CALL WakeUpThread::run()
{
::osl::Condition aSleeper;
TimeValue aTime;
aTime.Seconds = 0;
aTime.Nanosec = 25000000; // 25 msec
while(schedule())
{
aSleeper.reset();
aSleeper.wait(&aTime);
// SAFE ->
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::util::XUpdatable > xListener(m_xListener.get(), css::uno::UNO_QUERY);
aReadLock.unlock();
// <- SAFE
if (xListener.is())
xListener->update();
}
}
//***********************************************
void SAL_CALL WakeUpThread::onTerminated()
{
delete this;
}
} // namespace framework
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <string>
#include <vector>
using namespace std;
constexpr bool debug = true;
using UChar = unsigned char;
using ULInt = unsigned long int;
template <typename Container>
void printContainer(const Container& c, const string& name) {
cout << "Printing container - " << name << " of size = " << c.size() << " : [";
for (auto i = c.begin(); i != c.end(); ++i) {
cout << *i << ",";
}
cout << "]" << endl;
}
void findChange(ULInt change, const vector<ULInt>& coins, string& solution, ULInt& nSolutions,
unordered_set<string>& solutions, vector<ULInt>::const_iterator& fromStart, unordered_set<string>& unsortedSolutions) {
if (change != 0) {
for (auto it = fromStart; it != coins.cend(); ++it) {
auto coin = *it;
auto coinStr = to_string(coin);
if (debug) {
cout << "current coin is : " << coinStr << endl;
cout << "current change is : " << change << endl;
}
if (change > coin) {
findChange(change - coin, coins, solution.append(coinStr), nSolutions, solutions, fromStart, unsortedSolutions);
solution.pop_back();
} else if (change == coin) {
solution.append(coinStr);
auto sortedSolution = solution;
sort(sortedSolution.begin(), sortedSolution.end());
auto checkInsert = solutions.insert(sortedSolution);
unsortedSolutions.insert(solution);
if (checkInsert.second == true) {
++nSolutions;
cout << "solution found! : " << solution << endl;
}
if (debug) printContainer(solutions, "solutions so far");
if (debug) printContainer(unsortedSolutions, "unsortedSolutions so far");
solution.pop_back();
} else {
if (debug) {
cout << "overshooting, try with next coin " << coinStr << endl;
}
++fromStart;
}
}
}
}
int main() {
auto change = static_cast<ULInt>(0);
cin >> change;
auto nCoins = static_cast<ULInt>(0);
cin >> nCoins;
vector<ULInt> coins;
for (auto i = 0; i < nCoins; ++i) {
auto coin = static_cast<ULInt>(0);
cin >> coin;
coins.push_back(coin);
}
sort(coins.begin(), coins.end());
reverse(coins.begin(), coins.end());
if (debug) printContainer(coins, "coins (sorted)");
ULInt nSolutions = 0;
unordered_set<string> solutions;
unordered_set<string> unsortedSolutions;
auto fromStart = coins.cbegin();
// for (auto coin : coins) {
string solution;
findChange(change, coins, solution, nSolutions, solutions, fromStart, unsortedSolutions);
// }
cout << nSolutions << endl;
return 0;
}<commit_msg>on the right path, to be continued<commit_after>#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <string>
#include <vector>
using namespace std;
constexpr bool debug = true;
using UChar = unsigned char;
using ULInt = unsigned long int;
using UInt = unsigned int;
template <typename Container>
void printContainer(const Container& c, const string& name) {
cout << "Printing container - " << name << " of size = " << c.size() << " : [";
for (auto i = c.begin(); i != c.end(); ++i) {
cout << *i << ",";
}
cout << "]" << endl;
}
// void printContainerInsideContainer(const vector<vector<UInt>>& c, const string& name) {
// cout << "Printing container - " << name << " of size = " << c.size() << " : {" << endl;
// for (auto i = c.begin(); i != c.end(); ++i) {
// cout << "[";
// for (auto j = (*i).cbegin(); j != (*i).cend(); ++j) {
// cout << *j << ",";
// }
// cout << "]," << endl;
// }
// cout << endl << "}" << endl;
// }
// void findChange(ULInt change, const vector<ULInt>& coins, string& solution, ULInt& nSolutions,
// unordered_set<string>& solutions, vector<ULInt>::const_iterator& fromStart, unordered_set<string>& unsortedSolutions) {
// if (change != 0) {
// for (auto it = fromStart; it != coins.cend(); ++it) {
// auto coin = *it;
// auto coinStr = to_string(coin);
// if (debug) {
// cout << "current coin is : " << coinStr << endl;
// cout << "current change is : " << change << endl;
// }
// if (change > coin) {
// findChange(change - coin, coins, solution.append(coinStr), nSolutions, solutions, fromStart, unsortedSolutions);
// solution.pop_back();
// } else if (change == coin) {
// solution.append(coinStr);
// auto sortedSolution = solution;
// sort(sortedSolution.begin(), sortedSolution.end());
// auto checkInsert = solutions.insert(sortedSolution);
// unsortedSolutions.insert(solution);
// if (checkInsert.second == true) {
// ++nSolutions;
// cout << "solution found! : " << solution << endl;
// }
// if (next(it) == coins.cend()) {
// ++fromStart;
// }
// solution.pop_back();
// if (debug) printContainer(solutions, "solutions so far");
// if (debug) printContainer(unsortedSolutions, "unsortedSolutions so far");
// } else {
// if (debug) {
// cout << "overshooting, try with next coin " << coinStr << endl;
// }
// // ++fromStart;
// }
// }
// }
// }
class Solution {
public:
Solution(vector<UInt> s, UInt i, UInt c);
Solution(const Solution& a);
Solution(Solution&& a);
Solution& operator=(const Solution& a);
Solution& operator=(Solution&& a);
vector<UInt>& getSequence();
UInt getIndex();
UInt getChange();
void setChange(UInt c);
friend ostream& operator<<(ostream& outstream, const Solution& a);
friend void printCompleteSolution(const Solution& a);
private:
vector<UInt> sequence;
UInt index;
UInt change;
};
Solution::Solution(vector<UInt> s, UInt i, UInt c)
: sequence(s), index(i), change(c)
{}
Solution::Solution(const Solution& a)
: sequence(a.sequence), index(a.index), change(a.change)
{}
Solution::Solution(Solution&& a)
: sequence(move(a.sequence)), index(move(a.index)), change(move(a.change))
{}
Solution& Solution::operator=(const Solution& a) {
sequence = a.sequence;
index = a.index;
change = a.change;
return *this;
}
Solution& Solution::operator=(Solution&& a) {
sequence = move(a.sequence);
index = move(a.index);
change = move(a.change);
return *this;
}
vector<UInt>& Solution::getSequence() {
return sequence;
}
UInt Solution::getIndex() {
return index;
}
UInt Solution::getChange() {
return change;
}
void Solution::setChange(UInt c) {
change = c;
}
ostream& operator<<(ostream& outstream, const Solution& a) {
if (a.sequence.size() > 0) {
outstream << "[";
for (auto i = 0; i < a.sequence.size()-1; ++i) {
outstream << a.sequence[i] << ",";
}
outstream << a.sequence[a.sequence.size()-1] << "]" << endl;
}
return outstream;
}
void printCompleteSolution(const Solution& a) {
cout << "---------------------------------" << endl;
cout << "Solution index : " << a.index << endl;
cout << "Solution change : " << a.change << endl;
cout << "Solution sequence : " << endl << a;
cout << "---------------------------------" << endl;
}
ULInt findChange(UInt change, const vector<UInt>& coins) {
auto i = 0;
auto prevIndex = 0;
vector<Solution> solutions;
vector<Solution> partialSolutions;
Solution solution(vector<UInt>(), i, change);
auto remainingChange = solution.getChange();
while (i < coins.size()) {
auto coin = coins[i];
if (remainingChange >= coin) {
vector<UInt>& seq = solution.getSequence();
seq.insert(seq.end(), remainingChange / coin, coin);
solution.setChange(remainingChange % coin);
if (i < coins.size()-1) {
partialSolutions.push_back(Solution(seq, i, remainingChange));
if (debug) {
cout << "storing partial solution" << endl;
printCompleteSolution(solution);
}
}
}
if (remainingChange == 0) {
solutions.push_back(solution);
if (debug) {
printContainer(solution.getSequence(), "solution found");
}
if (!partialSolutions.empty()) {
auto solution = partialSolutions.back();
partialSolutions.pop_back();
i = solution.getIndex();
remainingChange = solution.getChange();
}
}
if (i == coins.size()-1) {
if (debug) cout << "resetting change" << endl;
remainingChange = change;
i = prevIndex + 1;
++prevIndex;
vector<UInt>& seq = solution.getSequence();
seq.clear();
if (debug) cout << "increasing prevIndex to : " << prevIndex << endl;
} else {
++i;
}
if (debug) printContainer(solutions, "solutions so far");
if (debug) printContainer(partialSolutions, "partial solutions");
}
return solutions.size();
}
int main() {
auto change = static_cast<UInt>(0);
cin >> change;
auto nCoins = static_cast<UInt>(0);
cin >> nCoins;
vector<UInt> coins;
for (auto i = 0; i < nCoins; ++i) {
auto coin = static_cast<UInt>(0);
cin >> coin;
coins.push_back(coin);
}
sort(coins.begin(), coins.end());
reverse(coins.begin(), coins.end());
if (debug) printContainer(coins, "coins (sorted)");
cout << findChange(change, coins) << endl;
return 0;
}<|endoftext|> |
<commit_before>#ifndef STACKTRANSFORMS_HPP_
#define STACKTRANSFORMS_HPP_
#include "boost/filesystem.hpp"
#include "itkTranslationTransform.h"
#include "itkCenteredRigid2DTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkSingleValuedNonLinearOptimizer.h"
#include "itkBSplineDeformableTransform.h"
#include "itkBSplineDeformableTransformInitializer.h"
#include "itkLBFGSBOptimizer.h"
#include "Stack.hpp"
#include "Dirs.hpp"
#include "Parameters.hpp"
#include "StdOutIterationUpdate.hpp"
using namespace std;
namespace StackTransforms {
typedef itk::MatrixOffsetTransformBase< double, 2, 2 > LinearTransformType;
typedef itk::TranslationTransform< double, 2 > TranslationTransformType;
itk::Vector< double, 2 > GetLoResTranslation(const string& roi) {
itk::Vector< double, 2 > LoResTranslation;
boost::shared_ptr< YAML::Node > roiNode = config("ROIs/" + roi + ".yml");
for(unsigned int i=0; i<2; i++) {
(*roiNode)["Translation"][i] >> LoResTranslation[i];
}
return LoResTranslation;
}
template <typename StackType>
void InitializeToIdentity(StackType& stack) {
typedef itk::TranslationTransform< double, 2 > TransformType;
typename StackType::TransformVectorType newTransforms;
for(unsigned int i=0; i<stack.GetSize(); i++)
{
typename StackType::TransformType::Pointer transform( TransformType::New() );
transform->SetIdentity();
newTransforms.push_back( transform );
}
stack.SetTransforms(newTransforms);
}
template <typename StackType>
void InitializeWithTranslation(StackType& stack, const itk::Vector< double, 2 > &translation) {
typedef itk::TranslationTransform< double, 2 > TransformType;
typename StackType::TransformVectorType newTransforms;
TransformType::ParametersType parameters(2);
parameters[0] = translation[0];
parameters[1] = translation[1];
for(unsigned int i=0; i<stack.GetSize(); i++)
{
typename StackType::TransformType::Pointer transform( TransformType::New() );
transform->SetParametersByValue( parameters );
newTransforms.push_back( transform );
}
stack.SetTransforms(newTransforms);
}
template <typename StackType>
void InitializeToCommonCentre(StackType& stack) {
typedef itk::CenteredRigid2DTransform< double > TransformType;
typename StackType::TransformVectorType newTransforms;
TransformType::ParametersType parameters(5);
for(unsigned int i=0; i<stack.GetSize(); i++)
{
const typename StackType::SliceType::SizeType &originalSize( stack.GetOriginalImage(i)->GetLargestPossibleRegion().GetSize() ),
&resamplerSize( stack.GetResamplerSize() );
const typename StackType::SliceType::SpacingType &originalSpacings( stack.GetOriginalSpacings() );
const typename StackType::VolumeType::SpacingType &spacings( stack.GetSpacings() );
// rotation in radians
parameters[0] = 0;
// translation, applied after rotation.
parameters[3] = ( originalSpacings[0] * (double)originalSize[0] - spacings[0] * (double)resamplerSize[0] ) / 2.0;
parameters[4] = ( originalSpacings[1] * (double)originalSize[1] - spacings[1] * (double)resamplerSize[1] ) / 2.0;
// set them to new transform
typename StackType::TransformType::Pointer transform( TransformType::New() );
transform->SetParametersByValue( parameters );
newTransforms.push_back( transform );
}
stack.SetTransforms(newTransforms);
}
// Moves centre of rotation without changing the transform
void MoveCenter(LinearTransformType * transform, const LinearTransformType::CenterType& newCenter)
{
LinearTransformType::OffsetType offset = transform->GetOffset();
transform->SetCenter(newCenter);
transform->SetOffset(offset);
}
template <typename StackType>
void SetMovingStackCenterWithFixedStack( StackType& fixedStack, StackType& movingStack )
{
const typename StackType::TransformVectorType& movingTransforms = movingStack.GetTransforms();
// set the moving slices' centre of rotation to the centre of the fixed image
for(unsigned int i=0; i<movingStack.GetSize(); ++i)
{
LinearTransformType::Pointer transform = dynamic_cast< LinearTransformType* >( movingTransforms[i].GetPointer() );
if(transform)
{
const typename StackType::SliceType::SizeType &resamplerSize( fixedStack.GetResamplerSize() );
const typename StackType::VolumeType::SpacingType &spacings( fixedStack.GetSpacings() );
LinearTransformType::CenterType center;
center[0] = spacings[0] * (double)resamplerSize[0] / 2.0;
center[1] = spacings[1] * (double)resamplerSize[1] / 2.0;
MoveCenter(transform, center);
}
else
{
cerr << "slice " << slice_number << " isn't a MatrixOffsetTransformBase :-(\n";
cerr << "stack.GetTransform(slice_number): " << stack.GetTransform(slice_number) << endl;
std::abort();
}
}
}
template <typename StackType, typename NewTransformType>
void InitializeFromCurrentTransforms(StackType& stack)
{
typename StackType::TransformVectorType newTransforms;
for(unsigned int i=0; i<stack.GetSize(); i++)
{
typename NewTransformType::Pointer newTransform = NewTransformType::New();
newTransform->SetIdentity();
// specialize from vanilla Transform to lowest common denominator in order to call GetCenter()
LinearTransformType::Pointer oldTransform( dynamic_cast< LinearTransformType* >( stack.GetTransform(i).GetPointer() ) );
newTransform->SetCenter( oldTransform->GetCenter() );
newTransform->Compose( oldTransform );
typename StackType::TransformType::Pointer baseTransform( newTransform );
newTransforms.push_back( baseTransform );
}
// set stack's transforms to newTransforms
stack.SetTransforms(newTransforms);
}
template <typename StackType>
void InitializeBSplineDeformableFromBulk(StackType& LoResStack, StackType& HiResStack)
{
// Perform non-rigid registration
typedef double CoordinateRepType;
const unsigned int SpaceDimension = 2;
const unsigned int SplineOrder = 3;
typedef itk::BSplineDeformableTransform< CoordinateRepType, SpaceDimension, SplineOrder > TransformType;
typedef itk::BSplineDeformableTransformInitializer< TransformType, typename StackType::SliceType > InitializerType;
typename StackType::TransformVectorType newTransforms;
for(unsigned int slice_number=0; slice_number<HiResStack.GetSize(); slice_number++)
{
// instantiate transform
TransformType::Pointer transform( TransformType::New() );
// initialise transform
typename InitializerType::Pointer initializer = InitializerType::New();
initializer->SetTransform( transform );
initializer->SetImage( LoResStack.GetResampledSlice(slice_number) );
unsigned int gridSize;
boost::shared_ptr<YAML::Node> deformableParameters = config("deformable_parameters.yml");
(*deformableParameters)["bsplineTransform"]["gridSize"] >> gridSize;
TransformType::RegionType::SizeType gridSizeInsideTheImage;
gridSizeInsideTheImage.Fill(gridSize);
initializer->SetGridSizeInsideTheImage( gridSizeInsideTheImage );
initializer->InitializeTransform();
transform->SetBulkTransform( HiResStack.GetTransform(slice_number) );
// set initial parameters to zero
TransformType::ParametersType initialDeformableTransformParameters( transform->GetNumberOfParameters() );
initialDeformableTransformParameters.Fill( 0.0 );
transform->SetParametersByValue( initialDeformableTransformParameters );
// add transform to vector
typename StackType::TransformType::Pointer baseTransform( transform );
newTransforms.push_back( baseTransform );
}
HiResStack.SetTransforms(newTransforms);
}
// Translate a single slice
template <typename StackType>
void Translate(StackType& stack, const itk::Vector< double, 2 > translation, unsigned int slice_number)
{
// attempt to cast stack transform and apply translation
LinearTransformType::Pointer linearTransform
= dynamic_cast< LinearTransformType* >( stack.GetTransform(slice_number).GetPointer() );
TranslationTransformType::Pointer translationTransform
= dynamic_cast< TranslationTransformType* >( stack.GetTransform(slice_number).GetPointer() );
if(linearTransform)
{
// construct transform to represent translation
LinearTransformType::Pointer translationTransform = LinearTransformType::New();
translationTransform->SetIdentity();
translationTransform->SetTranslation(translation);
// if second argument is true, translationTransform is applied first,
// then linearTransform
linearTransform->Compose(translationTransform, true);
}
else if(translationTransform)
{
translationTransform->Translate(translation);
}
else
{
cerr << "slice " << slice_number << " isn't a MatrixOffsetTransformBase or a TranslationTransform :-(\n";
cerr << "stack.GetTransform(slice_number): " << stack.GetTransform(slice_number) << endl;
std::abort();
}
}
// Translate the entire stack
template <typename StackType>
void Translate(StackType& stack, const itk::Vector< double, 2 > translation)
{
// attempt to cast stack transforms and apply translation
for(unsigned int slice_number=0; slice_number<stack.GetSize(); ++slice_number)
{
Translate(stack, translation, slice_number);
}
}
}
#endif
<commit_msg>Oops, fixed type and error message bugs.<commit_after>#ifndef STACKTRANSFORMS_HPP_
#define STACKTRANSFORMS_HPP_
#include "boost/filesystem.hpp"
#include "itkTranslationTransform.h"
#include "itkCenteredRigid2DTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkSingleValuedNonLinearOptimizer.h"
#include "itkBSplineDeformableTransform.h"
#include "itkBSplineDeformableTransformInitializer.h"
#include "itkLBFGSBOptimizer.h"
#include "Stack.hpp"
#include "Dirs.hpp"
#include "Parameters.hpp"
#include "StdOutIterationUpdate.hpp"
using namespace std;
namespace StackTransforms {
typedef itk::MatrixOffsetTransformBase< double, 2, 2 > LinearTransformType;
typedef itk::TranslationTransform< double, 2 > TranslationTransformType;
itk::Vector< double, 2 > GetLoResTranslation(const string& roi) {
itk::Vector< double, 2 > LoResTranslation;
boost::shared_ptr< YAML::Node > roiNode = config("ROIs/" + roi + ".yml");
for(unsigned int i=0; i<2; i++) {
(*roiNode)["Translation"][i] >> LoResTranslation[i];
}
return LoResTranslation;
}
template <typename StackType>
void InitializeToIdentity(StackType& stack) {
typedef itk::TranslationTransform< double, 2 > TransformType;
typename StackType::TransformVectorType newTransforms;
for(unsigned int i=0; i<stack.GetSize(); i++)
{
TransformType::Pointer transform = TransformType::New();
transform->SetIdentity();
typename StackType::TransformType::Pointer baseTransform( transform );
newTransforms.push_back( baseTransform );
}
stack.SetTransforms(newTransforms);
}
template <typename StackType>
void InitializeWithTranslation(StackType& stack, const itk::Vector< double, 2 > &translation) {
typedef itk::TranslationTransform< double, 2 > TransformType;
typename StackType::TransformVectorType newTransforms;
TransformType::ParametersType parameters(2);
parameters[0] = translation[0];
parameters[1] = translation[1];
for(unsigned int i=0; i<stack.GetSize(); i++)
{
typename StackType::TransformType::Pointer transform( TransformType::New() );
transform->SetParametersByValue( parameters );
newTransforms.push_back( transform );
}
stack.SetTransforms(newTransforms);
}
template <typename StackType>
void InitializeToCommonCentre(StackType& stack) {
typedef itk::CenteredRigid2DTransform< double > TransformType;
typename StackType::TransformVectorType newTransforms;
TransformType::ParametersType parameters(5);
for(unsigned int i=0; i<stack.GetSize(); i++)
{
const typename StackType::SliceType::SizeType &originalSize( stack.GetOriginalImage(i)->GetLargestPossibleRegion().GetSize() ),
&resamplerSize( stack.GetResamplerSize() );
const typename StackType::SliceType::SpacingType &originalSpacings( stack.GetOriginalSpacings() );
const typename StackType::VolumeType::SpacingType &spacings( stack.GetSpacings() );
// rotation in radians
parameters[0] = 0;
// translation, applied after rotation.
parameters[3] = ( originalSpacings[0] * (double)originalSize[0] - spacings[0] * (double)resamplerSize[0] ) / 2.0;
parameters[4] = ( originalSpacings[1] * (double)originalSize[1] - spacings[1] * (double)resamplerSize[1] ) / 2.0;
// set them to new transform
typename StackType::TransformType::Pointer transform( TransformType::New() );
transform->SetParametersByValue( parameters );
newTransforms.push_back( transform );
}
stack.SetTransforms(newTransforms);
}
// Moves centre of rotation without changing the transform
void MoveCenter(LinearTransformType * transform, const LinearTransformType::CenterType& newCenter)
{
LinearTransformType::OffsetType offset = transform->GetOffset();
transform->SetCenter(newCenter);
transform->SetOffset(offset);
}
template <typename StackType>
void SetMovingStackCenterWithFixedStack( StackType& fixedStack, StackType& movingStack )
{
const typename StackType::TransformVectorType& movingTransforms = movingStack.GetTransforms();
// set the moving slices' centre of rotation to the centre of the fixed image
for(unsigned int slice_number=0; slice_number<movingStack.GetSize(); ++slice_number)
{
LinearTransformType::Pointer transform = dynamic_cast< LinearTransformType* >( movingTransforms[slice_number].GetPointer() );
if(transform)
{
const typename StackType::SliceType::SizeType &resamplerSize( fixedStack.GetResamplerSize() );
const typename StackType::VolumeType::SpacingType &spacings( fixedStack.GetSpacings() );
LinearTransformType::CenterType center;
center[0] = spacings[0] * (double)resamplerSize[0] / 2.0;
center[1] = spacings[1] * (double)resamplerSize[1] / 2.0;
MoveCenter(transform, center);
}
else
{
cerr << "transform " << slice_number << " isn't a MatrixOffsetTransformBase :-(\n";
cerr << "transform: " << transform << endl;
std::abort();
}
}
}
template <typename StackType, typename NewTransformType>
void InitializeFromCurrentTransforms(StackType& stack)
{
typename StackType::TransformVectorType newTransforms;
for(unsigned int i=0; i<stack.GetSize(); i++)
{
typename NewTransformType::Pointer newTransform = NewTransformType::New();
newTransform->SetIdentity();
// specialize from vanilla Transform to lowest common denominator in order to call GetCenter()
LinearTransformType::Pointer oldTransform( dynamic_cast< LinearTransformType* >( stack.GetTransform(i).GetPointer() ) );
newTransform->SetCenter( oldTransform->GetCenter() );
newTransform->Compose( oldTransform );
typename StackType::TransformType::Pointer baseTransform( newTransform );
newTransforms.push_back( baseTransform );
}
// set stack's transforms to newTransforms
stack.SetTransforms(newTransforms);
}
template <typename StackType>
void InitializeBSplineDeformableFromBulk(StackType& LoResStack, StackType& HiResStack)
{
// Perform non-rigid registration
typedef double CoordinateRepType;
const unsigned int SpaceDimension = 2;
const unsigned int SplineOrder = 3;
typedef itk::BSplineDeformableTransform< CoordinateRepType, SpaceDimension, SplineOrder > TransformType;
typedef itk::BSplineDeformableTransformInitializer< TransformType, typename StackType::SliceType > InitializerType;
typename StackType::TransformVectorType newTransforms;
for(unsigned int slice_number=0; slice_number<HiResStack.GetSize(); slice_number++)
{
// instantiate transform
TransformType::Pointer transform( TransformType::New() );
// initialise transform
typename InitializerType::Pointer initializer = InitializerType::New();
initializer->SetTransform( transform );
initializer->SetImage( LoResStack.GetResampledSlice(slice_number) );
unsigned int gridSize;
boost::shared_ptr<YAML::Node> deformableParameters = config("deformable_parameters.yml");
(*deformableParameters)["bsplineTransform"]["gridSize"] >> gridSize;
TransformType::RegionType::SizeType gridSizeInsideTheImage;
gridSizeInsideTheImage.Fill(gridSize);
initializer->SetGridSizeInsideTheImage( gridSizeInsideTheImage );
initializer->InitializeTransform();
transform->SetBulkTransform( HiResStack.GetTransform(slice_number) );
// set initial parameters to zero
TransformType::ParametersType initialDeformableTransformParameters( transform->GetNumberOfParameters() );
initialDeformableTransformParameters.Fill( 0.0 );
transform->SetParametersByValue( initialDeformableTransformParameters );
// add transform to vector
typename StackType::TransformType::Pointer baseTransform( transform );
newTransforms.push_back( baseTransform );
}
HiResStack.SetTransforms(newTransforms);
}
// Translate a single slice
template <typename StackType>
void Translate(StackType& stack, const itk::Vector< double, 2 > translation, unsigned int slice_number)
{
// attempt to cast stack transform and apply translation
LinearTransformType::Pointer linearTransform
= dynamic_cast< LinearTransformType* >( stack.GetTransform(slice_number).GetPointer() );
TranslationTransformType::Pointer translationTransform
= dynamic_cast< TranslationTransformType* >( stack.GetTransform(slice_number).GetPointer() );
if(linearTransform)
{
// construct transform to represent translation
LinearTransformType::Pointer translationTransform = LinearTransformType::New();
translationTransform->SetIdentity();
translationTransform->SetTranslation(translation);
// if second argument is true, translationTransform is applied first,
// then linearTransform
linearTransform->Compose(translationTransform, true);
}
else if(translationTransform)
{
translationTransform->Translate(translation);
}
else
{
cerr << "slice " << slice_number << " isn't a MatrixOffsetTransformBase or a TranslationTransform :-(\n";
cerr << "stack.GetTransform(slice_number): " << stack.GetTransform(slice_number) << endl;
std::abort();
}
}
// Translate the entire stack
template <typename StackType>
void Translate(StackType& stack, const itk::Vector< double, 2 > translation)
{
// attempt to cast stack transforms and apply translation
for(unsigned int slice_number=0; slice_number<stack.GetSize(); ++slice_number)
{
Translate(stack, translation, slice_number);
}
}
}
#endif
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIOpenGLGeometryBuffer.cpp
created: Wed, 8th Feb 2012
author: Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include <GL/glew.h>
#include "glm/glm.hpp"
#include "glm/gtc/quaternion.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RenderEffect.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ShaderParameterBindings.h"
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h"
#include "CEGUI/RendererModules/OpenGL/GL3ShaderWrapper.h"
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner, CEGUI::RefCounted<RenderMaterial> renderMaterial) :
OpenGLGeometryBufferBase(owner, renderMaterial),
d_glStateChanger(owner.getOpenGLStateChanger()),
d_bufferSize(0)
{
initialiseOpenGLBuffers();
}
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()
{
deinitialiseOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::draw() const
{
CEGUI::Rectf viewPort = d_owner->getActiveViewPort();
d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),
static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),
static_cast<GLint>(d_clipRect.getWidth()),
static_cast<GLint>(d_clipRect.getHeight()));
// apply the transformations we need to use.
if (!d_matrixValid)
updateMatrix();
CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();
// Set the ModelViewProjection matrix in the bindings
glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;
shaderParameterBindings->setParameter("modelViewPerspMatrix", modelViewProjectionMatrix);
// activate desired blending mode
d_owner->setupRenderingBlendMode(d_blendMode);
// Bind our vao
d_glStateChanger->bindVertexArray(d_verticesVAO);
const int pass_count = d_effect ? d_effect->getPassCount() : 1;
size_t pos = 0;
for (int pass = 0; pass < pass_count; ++pass)
{
// set up RenderEffect
if (d_effect)
d_effect->performPreRenderFunctions(pass);
// draw the batches
BatchList::const_iterator i = d_batches.begin();
for ( ; i != d_batches.end(); ++i)
{
const BatchInfo& currentBatch = *i;
if (currentBatch.clip)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
if(currentBatch.texture != 0)
shaderParameterBindings->setParameter("texture0", currentBatch.texture);
d_renderMaterial->prepareForRendering();
// draw the geometry
const unsigned int numVertices = currentBatch.vertexCount;
glDrawArrays(GL_TRIANGLES, pos, numVertices);
pos += numVertices;
}
}
// clean up RenderEffect
if (d_effect)
d_effect->performPostRenderFunctions();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::reset()
{
OpenGLGeometryBufferBase::reset();
updateOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::initialiseOpenGLBuffers()
{
glGenVertexArrays(1, &d_verticesVAO);
d_glStateChanger->bindVertexArray(d_verticesVAO);
// Generate and bind position vbo
glGenBuffers(1, &d_verticesVBO);
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);
// Unbind Vertex Attribute Array (VAO)
d_glStateChanger->bindVertexArray(0);
// Unbind array and element array buffers
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, 0);
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::finaliseVertexAttributes()
{
d_glStateChanger->bindVertexArray(d_verticesVAO);
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
GLsizei stride = getVertexAttributeElementCount() * sizeof(GL_FLOAT);
CEGUI::OpenGL3ShaderWrapper* gl3_shader_wrapper = static_cast<CEGUI::OpenGL3ShaderWrapper*>(d_renderMaterial->getShaderWrapper());
//Update the vertex attrib pointers of the vertex array object depending on the saved attributes
int dataOffset = 0;
const unsigned int attribute_count = d_vertexAttributes.size();
for (unsigned int i = 0; i < attribute_count; ++i)
{
switch(d_vertexAttributes.at(i))
{
case VAT_POSITION0:
{
GLint shader_pos_loc = gl3_shader_wrapper->getAttributeLocation("inPosition");
glVertexAttribPointer(shader_pos_loc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(shader_pos_loc);
dataOffset += 3;
}
break;
case VAT_COLOUR0:
{
GLint shader_colour_loc = gl3_shader_wrapper->getAttributeLocation("inColour");
glVertexAttribPointer(shader_colour_loc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(shader_colour_loc);
dataOffset += 4;
}
break;
case VAT_TEXCOORD0:
{
GLint texture_coord_loc = gl3_shader_wrapper->getAttributeLocation("inTexCoord");
glVertexAttribPointer(texture_coord_loc, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(texture_coord_loc);
dataOffset += 2;
}
break;
default:
break;
}
}
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()
{
glDeleteVertexArrays(1, &d_verticesVAO);
glDeleteBuffers(1, &d_verticesVBO);
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::updateOpenGLBuffers()
{
bool needNewBuffer = false;
unsigned int vertexCount = d_vertexData.size();
if(d_bufferSize < vertexCount)
{
needNewBuffer = true;
d_bufferSize = vertexCount;
}
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
float* vertexData;
if(d_vertexData.empty())
vertexData = 0;
else
vertexData = &d_vertexData[0];
GLsizei dataSize = d_bufferSize * sizeof(float);
if(needNewBuffer)
{
glBufferData(GL_ARRAY_BUFFER, dataSize, vertexData, GL_DYNAMIC_DRAW);
}
else
{
glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, vertexData);
}
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::appendGeometry(const std::vector<float>& vertex_data)
{
OpenGLGeometryBufferBase::appendGeometry(vertex_data);
updateOpenGLBuffers();
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>MOD: Should be static draw because we assume we don't change it every frame<commit_after>/***********************************************************************
filename: CEGUIOpenGLGeometryBuffer.cpp
created: Wed, 8th Feb 2012
author: Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include <GL/glew.h>
#include "glm/glm.hpp"
#include "glm/gtc/quaternion.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RenderEffect.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ShaderParameterBindings.h"
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h"
#include "CEGUI/RendererModules/OpenGL/GL3ShaderWrapper.h"
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner, CEGUI::RefCounted<RenderMaterial> renderMaterial) :
OpenGLGeometryBufferBase(owner, renderMaterial),
d_glStateChanger(owner.getOpenGLStateChanger()),
d_bufferSize(0)
{
initialiseOpenGLBuffers();
}
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()
{
deinitialiseOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::draw() const
{
CEGUI::Rectf viewPort = d_owner->getActiveViewPort();
d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),
static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),
static_cast<GLint>(d_clipRect.getWidth()),
static_cast<GLint>(d_clipRect.getHeight()));
// apply the transformations we need to use.
if (!d_matrixValid)
updateMatrix();
CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();
// Set the ModelViewProjection matrix in the bindings
glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;
shaderParameterBindings->setParameter("modelViewPerspMatrix", modelViewProjectionMatrix);
// activate desired blending mode
d_owner->setupRenderingBlendMode(d_blendMode);
// Bind our vao
d_glStateChanger->bindVertexArray(d_verticesVAO);
const int pass_count = d_effect ? d_effect->getPassCount() : 1;
size_t pos = 0;
for (int pass = 0; pass < pass_count; ++pass)
{
// set up RenderEffect
if (d_effect)
d_effect->performPreRenderFunctions(pass);
// draw the batches
BatchList::const_iterator i = d_batches.begin();
for ( ; i != d_batches.end(); ++i)
{
const BatchInfo& currentBatch = *i;
if (currentBatch.clip)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
if(currentBatch.texture != 0)
shaderParameterBindings->setParameter("texture0", currentBatch.texture);
d_renderMaterial->prepareForRendering();
// draw the geometry
const unsigned int numVertices = currentBatch.vertexCount;
glDrawArrays(GL_TRIANGLES, pos, numVertices);
pos += numVertices;
}
}
// clean up RenderEffect
if (d_effect)
d_effect->performPostRenderFunctions();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::reset()
{
OpenGLGeometryBufferBase::reset();
updateOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::initialiseOpenGLBuffers()
{
glGenVertexArrays(1, &d_verticesVAO);
d_glStateChanger->bindVertexArray(d_verticesVAO);
// Generate and bind position vbo
glGenBuffers(1, &d_verticesVBO);
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_STATIC_DRAW);
// Unbind Vertex Attribute Array (VAO)
d_glStateChanger->bindVertexArray(0);
// Unbind array and element array buffers
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, 0);
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::finaliseVertexAttributes()
{
d_glStateChanger->bindVertexArray(d_verticesVAO);
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
GLsizei stride = getVertexAttributeElementCount() * sizeof(GL_FLOAT);
CEGUI::OpenGL3ShaderWrapper* gl3_shader_wrapper = static_cast<CEGUI::OpenGL3ShaderWrapper*>(d_renderMaterial->getShaderWrapper());
//Update the vertex attrib pointers of the vertex array object depending on the saved attributes
int dataOffset = 0;
const unsigned int attribute_count = d_vertexAttributes.size();
for (unsigned int i = 0; i < attribute_count; ++i)
{
switch(d_vertexAttributes.at(i))
{
case VAT_POSITION0:
{
GLint shader_pos_loc = gl3_shader_wrapper->getAttributeLocation("inPosition");
glVertexAttribPointer(shader_pos_loc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(shader_pos_loc);
dataOffset += 3;
}
break;
case VAT_COLOUR0:
{
GLint shader_colour_loc = gl3_shader_wrapper->getAttributeLocation("inColour");
glVertexAttribPointer(shader_colour_loc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(shader_colour_loc);
dataOffset += 4;
}
break;
case VAT_TEXCOORD0:
{
GLint texture_coord_loc = gl3_shader_wrapper->getAttributeLocation("inTexCoord");
glVertexAttribPointer(texture_coord_loc, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(texture_coord_loc);
dataOffset += 2;
}
break;
default:
break;
}
}
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()
{
glDeleteVertexArrays(1, &d_verticesVAO);
glDeleteBuffers(1, &d_verticesVBO);
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::updateOpenGLBuffers()
{
bool needNewBuffer = false;
unsigned int vertexCount = d_vertexData.size();
if(d_bufferSize < vertexCount)
{
needNewBuffer = true;
d_bufferSize = vertexCount;
}
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
float* vertexData;
if(d_vertexData.empty())
vertexData = 0;
else
vertexData = &d_vertexData[0];
GLsizei dataSize = d_bufferSize * sizeof(float);
if(needNewBuffer)
{
glBufferData(GL_ARRAY_BUFFER, dataSize, vertexData, GL_STATIC_DRAW);
}
else
{
glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, vertexData);
}
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::appendGeometry(const std::vector<float>& vertex_data)
{
OpenGLGeometryBufferBase::appendGeometry(vertex_data);
updateOpenGLBuffers();
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include <string>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/time.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// The language menu consists of 3 parts (in this order):
//
// (1) XKB layout names and IME languages names. The size of the list is
// always >= 1.
// (2) IME properties. This list might be empty.
// (3) "Configure IME..." button.
//
// Example of the menu (Japanese):
//
// ============================== (border of the popup window)
// [ ] US (|index| in the following functions is 0)
// [*] Anthy
// [ ] PinYin
// ------------------------------ (separator)
// [*] Hiragana (index = 5, The property has 2 radio groups)
// [ ] Katakana
// [ ] HalfWidthKatakana
// [*] Roman
// [ ] Kana
// ------------------------------ (separator)
// Configure IME... (index = 11)
// ============================== (border of the popup window)
//
// Example of the menu (Simplified Chinese):
//
// ============================== (border of the popup window)
// [ ] US
// [ ] Anthy
// [*] PinYin
// ------------------------------ (separator)
// Switch to full letter mode (The property has 2 command buttons)
// Switch to half punctuation mode
// ------------------------------ (separator)
// Configure IME...
// ============================== (border of the popup window)
//
namespace {
// Constants to specify the type of items in |model_|.
enum {
COMMAND_ID_LANGUAGES = 0, // US, Anthy, PinYin, ...
COMMAND_ID_IME_PROPERTIES, // Hiragana, Katakana, ...
COMMAND_ID_CONFIGURE_IME, // The "Configure IME..." button.
};
// A group ID for IME properties starts from 0. We use the huge value for the
// XKB/IME language list to avoid conflict.
const int kRadioGroupLanguage = 1 << 16;
const int kRadioGroupNone = -1;
const size_t kMaxLanguageNameLen = 7;
const wchar_t kSpacer[] = L"MMMMMMM";
// Converts chromeos::InputLanguage object into human readable string. Returns
// a string for the drop-down menu if |for_menu| is true. Otherwise, returns a
// string for the status area.
std::string FormatInputLanguage(
const chromeos::InputLanguage& language, bool for_menu) {
std::string formatted = language.display_name;
if (formatted.empty()) {
formatted = language.id;
}
if (for_menu) {
switch (language.category) {
case chromeos::LANGUAGE_CATEGORY_XKB:
// TODO(yusukes): Use message catalog.
formatted += " (Layout)";
break;
case chromeos::LANGUAGE_CATEGORY_IME:
// TODO(yusukes): Use message catalog.
formatted += " (IME)";
break;
}
} else {
// For status area. Trim the string.
formatted = formatted.substr(0, kMaxLanguageNameLen);
// TODO(yusukes): Simple substr() does not work for non-ASCII string.
// TODO(yusukes): How can we ensure that the trimmed string does not
// overflow the area?
}
return formatted;
}
} // namespace
namespace chromeos {
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton
LanguageMenuButton::LanguageMenuButton(StatusAreaHost* host)
: MenuButton(NULL, std::wstring(), this, false),
language_list_(LanguageLibrary::Get()->GetActiveLanguages()),
model_(NULL),
// Be aware that the constructor of |language_menu_| calls GetItemCount()
// in this class. Therefore, GetItemCount() have to return 0 when
// |model_| is NULL.
ALLOW_THIS_IN_INITIALIZER_LIST(language_menu_(this)),
host_(host) {
DCHECK(language_list_.get() && !language_list_->empty());
// Update the model
RebuildModel();
// Grab the real estate.
UpdateIcon(kSpacer);
// Display the default XKB name (usually "US").
const std::string name = FormatInputLanguage(language_list_->at(0), false);
UpdateIcon(UTF8ToWide(name));
LanguageLibrary::Get()->AddObserver(this);
}
LanguageMenuButton::~LanguageMenuButton() {
LanguageLibrary::Get()->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, menus::MenuModel implementation:
int LanguageMenuButton::GetCommandIdAt(int index) const {
return 0; // dummy
}
bool LanguageMenuButton::IsLabelDynamicAt(int index) const {
// Menu content for the language button could change time by time.
return true;
}
bool LanguageMenuButton::GetAcceleratorAt(
int index, menus::Accelerator* accelerator) const {
// Views for Chromium OS does not support accelerators yet.
return false;
}
bool LanguageMenuButton::IsItemCheckedAt(int index) const {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexIsInLanguageList(index)) {
const InputLanguage& language = language_list_->at(index);
return language == LanguageLibrary::Get()->current_language();
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
return property_list.at(index).is_selection_item_checked;
}
// Separator(s) or the "Configure IME" button.
return false;
}
int LanguageMenuButton::GetGroupIdAt(int index) const {
DCHECK_GE(index, 0);
if (IndexIsInLanguageList(index)) {
return kRadioGroupLanguage;
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
return property_list.at(index).selection_item_id;
}
return kRadioGroupNone;
}
bool LanguageMenuButton::HasIcons() const {
// TODO(yusukes): Display IME icons.
return false;
}
bool LanguageMenuButton::GetIconAt(int index, SkBitmap* icon) const {
// TODO(yusukes): Display IME icons.
return false;
}
bool LanguageMenuButton::IsEnabledAt(int index) const {
// Just return true so all IMEs, XKB layouts, and IME properties could be
// clicked.
return true;
}
menus::MenuModel* LanguageMenuButton::GetSubmenuModelAt(int index) const {
// We don't use nested menus.
return NULL;
}
void LanguageMenuButton::HighlightChangedTo(int index) {
// Views for Chromium OS does not support this interface yet.
}
void LanguageMenuButton::MenuWillShow() {
// Views for Chromium OS does not support this interface yet.
}
int LanguageMenuButton::GetItemCount() const {
if (!model_.get()) {
// Model is not constructed yet. This means that LanguageMenuButton is
// being constructed. Return zero.
return 0;
}
return model_->GetItemCount();
}
menus::MenuModel::ItemType LanguageMenuButton::GetTypeAt(int index) const {
DCHECK_GE(index, 0);
if (IndexPointsToConfigureImeMenuItem(index)) {
return menus::MenuModel::TYPE_COMMAND; // "Configure IME"
}
if (IndexIsInLanguageList(index)) {
return menus::MenuModel::TYPE_RADIO;
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
if (property_list.at(index).is_selection_item) {
return menus::MenuModel::TYPE_RADIO;
}
return menus::MenuModel::TYPE_COMMAND;
}
return menus::MenuModel::TYPE_SEPARATOR;
}
string16 LanguageMenuButton::GetLabelAt(int index) const {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexPointsToConfigureImeMenuItem(index)) {
// TODO(yusukes): Use message catalog.
return WideToUTF16(L"Configure IME...");
}
std::string name;
if (IndexIsInLanguageList(index)) {
name = FormatInputLanguage(language_list_->at(index), true);
} else if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
name = property_list.at(index).label;
}
return UTF8ToUTF16(name);
}
void LanguageMenuButton::ActivatedAt(int index) {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexPointsToConfigureImeMenuItem(index)) {
host_->OpenButtonOptions(this);
return;
}
if (IndexIsInLanguageList(index)) {
// Inter-IME switching or IME-XKB switching.
const InputLanguage& language = language_list_->at(index);
LanguageLibrary::Get()->ChangeLanguage(language.category, language.id);
return;
}
if (GetPropertyIndex(index, &index)) {
// Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana).
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
const std::string key = property_list.at(index).key;
if (property_list.at(index).is_selection_item) {
// Radio button is clicked.
const int id = property_list.at(index).selection_item_id;
// First, deactivate all other properties in the same radio group.
for (int i = 0; i < static_cast<int>(property_list.size()); ++i) {
if (i != index && id == property_list.at(i).selection_item_id) {
LanguageLibrary::Get()->DeactivateImeProperty(
property_list.at(i).key);
}
}
// Then, activate the property clicked.
LanguageLibrary::Get()->ActivateImeProperty(key);
} else {
// Command button like "Switch to half punctuation mode" is clicked.
// We can always use "Deactivate" for command buttons.
LanguageLibrary::Get()->DeactivateImeProperty(key);
}
return;
}
// Separators are not clickable.
NOTREACHED();
}
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, views::ViewMenuDelegate implementation:
void LanguageMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
language_list_.reset(LanguageLibrary::Get()->GetActiveLanguages());
RebuildModel();
language_menu_.Rebuild();
language_menu_.UpdateStates();
language_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
////////////////////////////////////////////////////////////////////////////////
// LanguageLibrary::Observer implementation:
void LanguageMenuButton::LanguageChanged(LanguageLibrary* obj) {
const std::string name = FormatInputLanguage(obj->current_language(), false);
UpdateIcon(UTF8ToWide(name));
}
void LanguageMenuButton::ImePropertiesChanged(LanguageLibrary* obj) {
RebuildModel();
}
void LanguageMenuButton::UpdateIcon(const std::wstring& name) {
set_border(NULL);
SetFont(ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
SetEnabledColor(SK_ColorWHITE);
SetShowHighlighted(false);
SetText(name);
// TODO(yusukes): Show icon on the status area?
set_alignment(TextButton::ALIGN_RIGHT);
SchedulePaint();
}
void LanguageMenuButton::RebuildModel() {
model_.reset(new menus::SimpleMenuModel(NULL));
string16 dummy_label = UTF8ToUTF16("");
// Indicates if separator's needed before each section.
bool need_separator = false;
if (!language_list_->empty()) {
// We "abuse" the command_id and group_id arguments of AddRadioItem method.
// A COMMAND_ID_XXX enum value is passed as command_id, and array index of
// |language_list_| or |property_list| is passed as group_id.
for (size_t i = 0; i < language_list_->size(); ++i) {
model_->AddRadioItem(COMMAND_ID_LANGUAGES, dummy_label, i);
}
need_separator = true;
}
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
if (!property_list.empty()) {
if (need_separator)
model_->AddSeparator();
for (size_t i = 0; i < property_list.size(); ++i) {
model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i);
}
need_separator = true;
}
if (host_->ShouldOpenButtonOptions(this)) {
// Note: We use AddSeparator() for separators, and AddRadioItem() for all
// other items even if an item is not actually a radio item.
if (need_separator)
model_->AddSeparator();
model_->AddRadioItem(COMMAND_ID_CONFIGURE_IME, dummy_label, 0 /* dummy */);
}
}
bool LanguageMenuButton::IndexIsInLanguageList(int index) const {
DCHECK_GE(index, 0);
DCHECK(model_.get());
return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_LANGUAGES));
}
bool LanguageMenuButton::GetPropertyIndex(
int index, int* property_index) const {
DCHECK_GE(index, 0);
DCHECK(property_index);
DCHECK(model_.get());
if ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) {
*property_index = model_->GetGroupIdAt(index);
return true;
}
return false;
}
bool LanguageMenuButton::IndexPointsToConfigureImeMenuItem(int index) const {
DCHECK_GE(index, 0);
DCHECK(model_.get());
return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_CONFIGURE_IME));
}
// TODO(yusukes): Register and handle hotkeys for IME and XKB switching?
} // namespace chromeos
<commit_msg>Remove obsolete TODOs. No code change.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include <string>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/time.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// The language menu consists of 3 parts (in this order):
//
// (1) XKB layout names and IME languages names. The size of the list is
// always >= 1.
// (2) IME properties. This list might be empty.
// (3) "Configure IME..." button.
//
// Example of the menu (Japanese):
//
// ============================== (border of the popup window)
// [ ] US (|index| in the following functions is 0)
// [*] Anthy
// [ ] PinYin
// ------------------------------ (separator)
// [*] Hiragana (index = 5, The property has 2 radio groups)
// [ ] Katakana
// [ ] HalfWidthKatakana
// [*] Roman
// [ ] Kana
// ------------------------------ (separator)
// Configure IME... (index = 11)
// ============================== (border of the popup window)
//
// Example of the menu (Simplified Chinese):
//
// ============================== (border of the popup window)
// [ ] US
// [ ] Anthy
// [*] PinYin
// ------------------------------ (separator)
// Switch to full letter mode (The property has 2 command buttons)
// Switch to half punctuation mode
// ------------------------------ (separator)
// Configure IME...
// ============================== (border of the popup window)
//
namespace {
// Constants to specify the type of items in |model_|.
enum {
COMMAND_ID_LANGUAGES = 0, // US, Anthy, PinYin, ...
COMMAND_ID_IME_PROPERTIES, // Hiragana, Katakana, ...
COMMAND_ID_CONFIGURE_IME, // The "Configure IME..." button.
};
// A group ID for IME properties starts from 0. We use the huge value for the
// XKB/IME language list to avoid conflict.
const int kRadioGroupLanguage = 1 << 16;
const int kRadioGroupNone = -1;
const size_t kMaxLanguageNameLen = 7;
const wchar_t kSpacer[] = L"MMMMMMM";
// Converts chromeos::InputLanguage object into human readable string. Returns
// a string for the drop-down menu if |for_menu| is true. Otherwise, returns a
// string for the status area.
std::string FormatInputLanguage(
const chromeos::InputLanguage& language, bool for_menu) {
std::string formatted = language.display_name;
if (formatted.empty()) {
formatted = language.id;
}
if (for_menu) {
switch (language.category) {
case chromeos::LANGUAGE_CATEGORY_XKB:
// TODO(yusukes): Use message catalog.
formatted += " (Layout)";
break;
case chromeos::LANGUAGE_CATEGORY_IME:
// TODO(yusukes): Use message catalog.
formatted += " (IME)";
break;
}
} else {
// For status area. Trim the string.
formatted = formatted.substr(0, kMaxLanguageNameLen);
// TODO(yusukes): Simple substr() does not work for non-ASCII string.
// TODO(yusukes): How can we ensure that the trimmed string does not
// overflow the area?
}
return formatted;
}
} // namespace
namespace chromeos {
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton
LanguageMenuButton::LanguageMenuButton(StatusAreaHost* host)
: MenuButton(NULL, std::wstring(), this, false),
language_list_(LanguageLibrary::Get()->GetActiveLanguages()),
model_(NULL),
// Be aware that the constructor of |language_menu_| calls GetItemCount()
// in this class. Therefore, GetItemCount() have to return 0 when
// |model_| is NULL.
ALLOW_THIS_IN_INITIALIZER_LIST(language_menu_(this)),
host_(host) {
DCHECK(language_list_.get() && !language_list_->empty());
// Update the model
RebuildModel();
// Grab the real estate.
UpdateIcon(kSpacer);
// Display the default XKB name (usually "US").
const std::string name = FormatInputLanguage(language_list_->at(0), false);
UpdateIcon(UTF8ToWide(name));
LanguageLibrary::Get()->AddObserver(this);
}
LanguageMenuButton::~LanguageMenuButton() {
LanguageLibrary::Get()->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, menus::MenuModel implementation:
int LanguageMenuButton::GetCommandIdAt(int index) const {
return 0; // dummy
}
bool LanguageMenuButton::IsLabelDynamicAt(int index) const {
// Menu content for the language button could change time by time.
return true;
}
bool LanguageMenuButton::GetAcceleratorAt(
int index, menus::Accelerator* accelerator) const {
// Views for Chromium OS does not support accelerators yet.
return false;
}
bool LanguageMenuButton::IsItemCheckedAt(int index) const {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexIsInLanguageList(index)) {
const InputLanguage& language = language_list_->at(index);
return language == LanguageLibrary::Get()->current_language();
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
return property_list.at(index).is_selection_item_checked;
}
// Separator(s) or the "Configure IME" button.
return false;
}
int LanguageMenuButton::GetGroupIdAt(int index) const {
DCHECK_GE(index, 0);
if (IndexIsInLanguageList(index)) {
return kRadioGroupLanguage;
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
return property_list.at(index).selection_item_id;
}
return kRadioGroupNone;
}
bool LanguageMenuButton::HasIcons() const {
// We don't support IME nor keyboard icons on Chrome OS.
return false;
}
bool LanguageMenuButton::GetIconAt(int index, SkBitmap* icon) const {
return false;
}
bool LanguageMenuButton::IsEnabledAt(int index) const {
// Just return true so all IMEs, XKB layouts, and IME properties could be
// clicked.
return true;
}
menus::MenuModel* LanguageMenuButton::GetSubmenuModelAt(int index) const {
// We don't use nested menus.
return NULL;
}
void LanguageMenuButton::HighlightChangedTo(int index) {
// Views for Chromium OS does not support this interface yet.
}
void LanguageMenuButton::MenuWillShow() {
// Views for Chromium OS does not support this interface yet.
}
int LanguageMenuButton::GetItemCount() const {
if (!model_.get()) {
// Model is not constructed yet. This means that LanguageMenuButton is
// being constructed. Return zero.
return 0;
}
return model_->GetItemCount();
}
menus::MenuModel::ItemType LanguageMenuButton::GetTypeAt(int index) const {
DCHECK_GE(index, 0);
if (IndexPointsToConfigureImeMenuItem(index)) {
return menus::MenuModel::TYPE_COMMAND; // "Configure IME"
}
if (IndexIsInLanguageList(index)) {
return menus::MenuModel::TYPE_RADIO;
}
if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
if (property_list.at(index).is_selection_item) {
return menus::MenuModel::TYPE_RADIO;
}
return menus::MenuModel::TYPE_COMMAND;
}
return menus::MenuModel::TYPE_SEPARATOR;
}
string16 LanguageMenuButton::GetLabelAt(int index) const {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexPointsToConfigureImeMenuItem(index)) {
// TODO(yusukes): Use message catalog.
return WideToUTF16(L"Configure IME...");
}
std::string name;
if (IndexIsInLanguageList(index)) {
name = FormatInputLanguage(language_list_->at(index), true);
} else if (GetPropertyIndex(index, &index)) {
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
name = property_list.at(index).label;
}
return UTF8ToUTF16(name);
}
void LanguageMenuButton::ActivatedAt(int index) {
DCHECK_GE(index, 0);
DCHECK(language_list_.get());
if (IndexPointsToConfigureImeMenuItem(index)) {
host_->OpenButtonOptions(this);
return;
}
if (IndexIsInLanguageList(index)) {
// Inter-IME switching or IME-XKB switching.
const InputLanguage& language = language_list_->at(index);
LanguageLibrary::Get()->ChangeLanguage(language.category, language.id);
return;
}
if (GetPropertyIndex(index, &index)) {
// Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana).
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
const std::string key = property_list.at(index).key;
if (property_list.at(index).is_selection_item) {
// Radio button is clicked.
const int id = property_list.at(index).selection_item_id;
// First, deactivate all other properties in the same radio group.
for (int i = 0; i < static_cast<int>(property_list.size()); ++i) {
if (i != index && id == property_list.at(i).selection_item_id) {
LanguageLibrary::Get()->DeactivateImeProperty(
property_list.at(i).key);
}
}
// Then, activate the property clicked.
LanguageLibrary::Get()->ActivateImeProperty(key);
} else {
// Command button like "Switch to half punctuation mode" is clicked.
// We can always use "Deactivate" for command buttons.
LanguageLibrary::Get()->DeactivateImeProperty(key);
}
return;
}
// Separators are not clickable.
NOTREACHED();
}
////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, views::ViewMenuDelegate implementation:
void LanguageMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
language_list_.reset(LanguageLibrary::Get()->GetActiveLanguages());
RebuildModel();
language_menu_.Rebuild();
language_menu_.UpdateStates();
language_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
////////////////////////////////////////////////////////////////////////////////
// LanguageLibrary::Observer implementation:
void LanguageMenuButton::LanguageChanged(LanguageLibrary* obj) {
const std::string name = FormatInputLanguage(obj->current_language(), false);
UpdateIcon(UTF8ToWide(name));
}
void LanguageMenuButton::ImePropertiesChanged(LanguageLibrary* obj) {
RebuildModel();
}
void LanguageMenuButton::UpdateIcon(const std::wstring& name) {
set_border(NULL);
SetFont(ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
SetEnabledColor(SK_ColorWHITE);
SetShowHighlighted(false);
SetText(name);
set_alignment(TextButton::ALIGN_RIGHT);
SchedulePaint();
}
void LanguageMenuButton::RebuildModel() {
model_.reset(new menus::SimpleMenuModel(NULL));
string16 dummy_label = UTF8ToUTF16("");
// Indicates if separator's needed before each section.
bool need_separator = false;
if (!language_list_->empty()) {
// We "abuse" the command_id and group_id arguments of AddRadioItem method.
// A COMMAND_ID_XXX enum value is passed as command_id, and array index of
// |language_list_| or |property_list| is passed as group_id.
for (size_t i = 0; i < language_list_->size(); ++i) {
model_->AddRadioItem(COMMAND_ID_LANGUAGES, dummy_label, i);
}
need_separator = true;
}
const ImePropertyList& property_list
= LanguageLibrary::Get()->current_ime_properties();
if (!property_list.empty()) {
if (need_separator)
model_->AddSeparator();
for (size_t i = 0; i < property_list.size(); ++i) {
model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i);
}
need_separator = true;
}
if (host_->ShouldOpenButtonOptions(this)) {
// Note: We use AddSeparator() for separators, and AddRadioItem() for all
// other items even if an item is not actually a radio item.
if (need_separator)
model_->AddSeparator();
model_->AddRadioItem(COMMAND_ID_CONFIGURE_IME, dummy_label, 0 /* dummy */);
}
}
bool LanguageMenuButton::IndexIsInLanguageList(int index) const {
DCHECK_GE(index, 0);
DCHECK(model_.get());
return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_LANGUAGES));
}
bool LanguageMenuButton::GetPropertyIndex(
int index, int* property_index) const {
DCHECK_GE(index, 0);
DCHECK(property_index);
DCHECK(model_.get());
if ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) {
*property_index = model_->GetGroupIdAt(index);
return true;
}
return false;
}
bool LanguageMenuButton::IndexPointsToConfigureImeMenuItem(int index) const {
DCHECK_GE(index, 0);
DCHECK(model_.get());
return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
(model_->GetCommandIdAt(index) == COMMAND_ID_CONFIGURE_IME));
}
// TODO(yusukes): Register and handle hotkeys for IME and XKB switching?
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/crx_installer.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/test/ui_test_utils.h"
namespace {
class MockInstallUI : public ExtensionInstallUI {
public:
explicit MockInstallUI(Profile* profile) :
ExtensionInstallUI(profile), confirmation_requested_(false) {}
// Did the Delegate request confirmation?
bool confirmation_requested() { return confirmation_requested_; }
// Overriding some of the ExtensionInstallUI API.
void ConfirmInstall(Delegate* delegate, const Extension* extension) {
confirmation_requested_ = true;
delegate->InstallUIProceed();
}
void OnInstallSuccess(const Extension* extension) {
MessageLoopForUI::current()->Quit();
}
void OnInstallFailure(const std::string& error) {
ADD_FAILURE() << "insall failed";
MessageLoopForUI::current()->Quit();
}
private:
bool confirmation_requested_;
};
} // namespace
class ExtensionCrxInstallerTest : public ExtensionBrowserTest {
public:
// Installs a crx from |crx_relpath| (a path relative to the extension test
// data dir) with expected id |id|. Returns whether a confirmation prompt
// happened or not.
bool DidWhitelistInstallPrompt(const std::string& crx_relpath,
const std::string& id) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
MockInstallUI* mock_install_ui = new MockInstallUI(browser()->profile());
scoped_refptr<CrxInstaller> installer(
new CrxInstaller(service->install_directory(),
service,
mock_install_ui /* ownership transferred */));
installer->set_allow_silent_install(true);
CrxInstaller::SetWhitelistedInstallId(id);
FilePath crx_path = test_data_dir_.AppendASCII(crx_relpath);
installer->InstallCrx(crx_path);
ui_test_utils::RunMessageLoop();
return mock_install_ui->confirmation_requested();
}
};
IN_PROC_BROWSER_TEST_F(ExtensionCrxInstallerTest, Whitelisting) {
// A regular extension should give no prompt.
EXPECT_FALSE(DidWhitelistInstallPrompt("good.crx",
"ldnnhddmnhbkjipkidpdiheffobcpfmf"));
// An extension with NPAPI should give a prompt.
EXPECT_TRUE(DidWhitelistInstallPrompt("uitest/plugins.crx",
"hdgllgikmikobbofgnabhfimcfoopgnd"));
}
<commit_msg>Don't run test with NPAPI extension on ChromeOS<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/crx_installer.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/test/ui_test_utils.h"
namespace {
class MockInstallUI : public ExtensionInstallUI {
public:
explicit MockInstallUI(Profile* profile) :
ExtensionInstallUI(profile), confirmation_requested_(false) {}
// Did the Delegate request confirmation?
bool confirmation_requested() { return confirmation_requested_; }
// Overriding some of the ExtensionInstallUI API.
void ConfirmInstall(Delegate* delegate, const Extension* extension) {
confirmation_requested_ = true;
delegate->InstallUIProceed();
}
void OnInstallSuccess(const Extension* extension) {
MessageLoopForUI::current()->Quit();
}
void OnInstallFailure(const std::string& error) {
ADD_FAILURE() << "insall failed";
MessageLoopForUI::current()->Quit();
}
private:
bool confirmation_requested_;
};
} // namespace
class ExtensionCrxInstallerTest : public ExtensionBrowserTest {
public:
// Installs a crx from |crx_relpath| (a path relative to the extension test
// data dir) with expected id |id|. Returns whether a confirmation prompt
// happened or not.
bool DidWhitelistInstallPrompt(const std::string& crx_relpath,
const std::string& id) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
MockInstallUI* mock_install_ui = new MockInstallUI(browser()->profile());
scoped_refptr<CrxInstaller> installer(
new CrxInstaller(service->install_directory(),
service,
mock_install_ui /* ownership transferred */));
installer->set_allow_silent_install(true);
CrxInstaller::SetWhitelistedInstallId(id);
FilePath crx_path = test_data_dir_.AppendASCII(crx_relpath);
installer->InstallCrx(crx_path);
ui_test_utils::RunMessageLoop();
return mock_install_ui->confirmation_requested();
}
};
IN_PROC_BROWSER_TEST_F(ExtensionCrxInstallerTest, Whitelisting) {
// A regular extension should give no prompt.
EXPECT_FALSE(DidWhitelistInstallPrompt("good.crx",
"ldnnhddmnhbkjipkidpdiheffobcpfmf"));
#if !defined(OS_CHROMEOS)
// An extension with NPAPI should give a prompt.
EXPECT_TRUE(DidWhitelistInstallPrompt("uitest/plugins.crx",
"hdgllgikmikobbofgnabhfimcfoopgnd"));
#endif // !defined(OS_CHROMEOS
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
<commit_msg>Disable test failing since r29947. <commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
// Started failing with r29947. WebKit merge 49961:49992.
IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <consensus/validation.h>
#include <crypto/sha256.h>
#include <test/util/mining.h>
#include <test/util/setup_common.h>
#include <test/util/wallet.h>
#include <txmempool.h>
#include <validation.h>
#include <vector>
static void AssembleBlock(benchmark::Bench& bench)
{
const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
const std::vector<unsigned char> op_true{OP_TRUE};
CScriptWitness witness;
witness.stack.push_back(op_true);
uint256 witness_program;
CSHA256().Write(&op_true[0], op_true.size()).Finalize(witness_program.begin());
const CScript SCRIPT_PUB{CScript(OP_0) << std::vector<unsigned char>{witness_program.begin(), witness_program.end()}};
// Collect some loose transactions that spend the coinbases of our mined blocks
constexpr size_t NUM_BLOCKS{200};
std::array<CTransactionRef, NUM_BLOCKS - COINBASE_MATURITY + 1> txs;
for (size_t b{0}; b < NUM_BLOCKS; ++b) {
CMutableTransaction tx;
tx.vin.push_back(MineBlock(test_setup->m_node, SCRIPT_PUB));
tx.vin.back().scriptWitness = witness;
tx.vout.emplace_back(1337, SCRIPT_PUB);
if (NUM_BLOCKS - b >= COINBASE_MATURITY)
txs.at(b) = MakeTransactionRef(tx);
}
{
LOCK(::cs_main); // Required for ::AcceptToMemoryPool.
for (const auto& txr : txs) {
const MempoolAcceptResult res = ::AcceptToMemoryPool(::ChainstateActive(), *test_setup->m_node.mempool, txr, false /* bypass_limits */);
assert(res.m_result_type == MempoolAcceptResult::ResultType::VALID);
}
}
bench.run([&] {
PrepareBlock(test_setup->m_node, SCRIPT_PUB);
});
}
BENCHMARK(AssembleBlock);
<commit_msg>bench: Remove duplicate constants<commit_after>// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <consensus/validation.h>
#include <crypto/sha256.h>
#include <test/util/mining.h>
#include <test/util/script.h>
#include <test/util/setup_common.h>
#include <test/util/wallet.h>
#include <txmempool.h>
#include <validation.h>
#include <vector>
static void AssembleBlock(benchmark::Bench& bench)
{
const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
CScriptWitness witness;
witness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE);
// Collect some loose transactions that spend the coinbases of our mined blocks
constexpr size_t NUM_BLOCKS{200};
std::array<CTransactionRef, NUM_BLOCKS - COINBASE_MATURITY + 1> txs;
for (size_t b{0}; b < NUM_BLOCKS; ++b) {
CMutableTransaction tx;
tx.vin.push_back(MineBlock(test_setup->m_node, P2WSH_OP_TRUE));
tx.vin.back().scriptWitness = witness;
tx.vout.emplace_back(1337, P2WSH_OP_TRUE);
if (NUM_BLOCKS - b >= COINBASE_MATURITY)
txs.at(b) = MakeTransactionRef(tx);
}
{
LOCK(::cs_main); // Required for ::AcceptToMemoryPool.
for (const auto& txr : txs) {
const MempoolAcceptResult res = ::AcceptToMemoryPool(::ChainstateActive(), *test_setup->m_node.mempool, txr, false /* bypass_limits */);
assert(res.m_result_type == MempoolAcceptResult::ResultType::VALID);
}
}
bench.run([&] {
PrepareBlock(test_setup->m_node, P2WSH_OP_TRUE);
});
}
BENCHMARK(AssembleBlock);
<|endoftext|> |
<commit_before>#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/System.h"
#if CINDER_VERSION >= 807
#include "cinder/app/RendererGl.h"
#include "cinder/Log.h"
#endif
#include "cidart/VM.h"
#include "cidart/Script.h"
#include "cidart/Types.h"
#include "cidart/Debug.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
using namespace std;
struct BreathingRect {
vec2 pos;
vec2 size;
ColorA color;
float speed;
float breath;
float seed;
};
class DartFieldsApp : public AppNative {
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void keyDown( KeyEvent event ) override;
void update() override;
void draw() override;
void loadScript();
cidart::ScriptRef mScript;
std::vector<BreathingRect> mBreathingRects;
};
void DartFieldsApp::setup()
{
cidart::VM::setCinderDartScriptDataSource( loadResource( CIDART_RES_CINDER_DART ) );
cidart::VM::setSnapshotBinDataSource( loadResource( CIDART_RES_SNAPSHOT_BIN ) );
loadScript();
// setup rendering
gl::enableAlphaBlending();
}
void DartFieldsApp::loadScript()
{
try {
mScript = cidart::Script::create( loadAsset( "main.dart" ) );
}
catch( Exception &exc ) {
CI_LOG_E( "exception of type: " << System::demangleTypeName( typeid( exc ).name() ) << ", what: " << exc.what() );
}
}
void DartFieldsApp::mouseDown( MouseEvent event )
{
// Before calling into the script, you must enter into 'dart scope'.
// This way, you will have access to the handle it returns, and all resources will be freed at the end of the function.
cidart::DartScope enterScope;
Dart_Handle handle = mScript->invoke( "makeBreathingRect" );
BreathingRect br;
br.pos = getMousePos() - getWindowPos();
br.breath = 0;
br.size = cidart::getField<vec2>( handle, "size" );
br.color = cidart::getField<ColorA>( handle, "color" );
br.speed = cidart::getField<float>( handle, "speed" );
br.seed = cidart::getField<float>( handle, "seed" );
mBreathingRects.push_back( br );
}
void DartFieldsApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'r' ) // reload script
loadScript();
if( event.getChar() == 'c' ) // clear existing objects
mBreathingRects.clear();
}
void DartFieldsApp::update()
{
for( auto &br : mBreathingRects )
br.breath = 0.7f + sinf( br.speed + getElapsedSeconds() + br.seed * 1000 ) * 0.3f;
}
void DartFieldsApp::draw()
{
gl::clear();
for( const auto &br : mBreathingRects ) {
gl::color( br.color );
vec2 size2 = ( br.size * br.breath ) / 2;
Rectf rect( br.pos.x - size2.x, br.pos.y - size2.y, br.pos.x + size2.x, br.pos.y + size2.y );
gl::drawSolidRect( rect );
}
}
CINDER_APP_NATIVE( DartFieldsApp, RendererGl )
<commit_msg>fix glm compile error on windows<commit_after>#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/System.h"
#if CINDER_VERSION >= 807
#include "cinder/app/RendererGl.h"
#include "cinder/Log.h"
#endif
#include "cidart/VM.h"
#include "cidart/Script.h"
#include "cidart/Types.h"
#include "cidart/Debug.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
using namespace std;
struct BreathingRect {
vec2 pos;
vec2 size;
ColorA color;
float speed;
float breath;
float seed;
};
class DartFieldsApp : public AppNative {
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void keyDown( KeyEvent event ) override;
void update() override;
void draw() override;
void loadScript();
cidart::ScriptRef mScript;
std::vector<BreathingRect> mBreathingRects;
};
void DartFieldsApp::setup()
{
cidart::VM::setCinderDartScriptDataSource( loadResource( CIDART_RES_CINDER_DART ) );
cidart::VM::setSnapshotBinDataSource( loadResource( CIDART_RES_SNAPSHOT_BIN ) );
loadScript();
// setup rendering
gl::enableAlphaBlending();
}
void DartFieldsApp::loadScript()
{
try {
mScript = cidart::Script::create( loadAsset( "main.dart" ) );
}
catch( Exception &exc ) {
CI_LOG_E( "exception of type: " << System::demangleTypeName( typeid( exc ).name() ) << ", what: " << exc.what() );
}
}
void DartFieldsApp::mouseDown( MouseEvent event )
{
// Before calling into the script, you must enter into 'dart scope'.
// This way, you will have access to the handle it returns, and all resources will be freed at the end of the function.
cidart::DartScope enterScope;
Dart_Handle handle = mScript->invoke( "makeBreathingRect" );
BreathingRect br;
br.pos = getMousePos() - getWindowPos();
br.breath = 0;
br.size = cidart::getField<vec2>( handle, "size" );
br.color = cidart::getField<ColorA>( handle, "color" );
br.speed = cidart::getField<float>( handle, "speed" );
br.seed = cidart::getField<float>( handle, "seed" );
mBreathingRects.push_back( br );
}
void DartFieldsApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'r' ) // reload script
loadScript();
if( event.getChar() == 'c' ) // clear existing objects
mBreathingRects.clear();
}
void DartFieldsApp::update()
{
for( auto &br : mBreathingRects )
br.breath = 0.7f + sinf( br.speed + getElapsedSeconds() + br.seed * 1000 ) * 0.3f;
}
void DartFieldsApp::draw()
{
gl::clear();
for( const auto &br : mBreathingRects ) {
gl::color( br.color );
vec2 size2 = ( br.size * br.breath ) / 2.0f;
Rectf rect( br.pos.x - size2.x, br.pos.y - size2.y, br.pos.x + size2.x, br.pos.y + size2.y );
gl::drawSolidRect( rect );
}
}
CINDER_APP_NATIVE( DartFieldsApp, RendererGl )
<|endoftext|> |
<commit_before><commit_msg>Append kernel signature to the log area in the SAL_INFO dump of its source<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 3.
*
*
* GNU Lesser General Public License Version 3
* =============================================
* 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
*
************************************************************************/
/* Currently the "all" installer has a bit over 100 UI languages, and
* I doubt it will grow a lot over that.
*/
#define MAX_LANGUAGES 200
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0500
#undef WINVER
#define WINVER 0x0500
#include <windows.h>
#include <msiquery.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sal/macros.h>
#include <systools/win32/uwinapi.h>
static const char *
langid_to_string( LANGID langid, int *have_default_lang )
{
/* Map from LANGID to string. The languages below are now in
* alphabetical order of codes as in
* setup_native/source/win32/msi-encodinglist.txt. Only the
* language part is returned in the string.
*/
switch (PRIMARYLANGID (langid)) {
case LANG_ENGLISH:
if (have_default_lang != NULL &&
langid == MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT))
*have_default_lang = 1;
return "en";
#define CASE(name, primary) \
case LANG_##primary: return #name
CASE(af, AFRIKAANS);
CASE(am, AMHARIC);
CASE(ar, ARABIC);
CASE(as, ASSAMESE);
CASE(be, BELARUSIAN);
CASE(bg, BULGARIAN);
CASE(bn, BENGALI);
CASE(br, BRETON);
CASE(ca, CATALAN);
CASE(cs, CZECH);
CASE(cy, WELSH);
CASE(da, DANISH);
CASE(de, GERMAN);
CASE(el, GREEK);
CASE(es, SPANISH);
CASE(et, ESTONIAN);
CASE(eu, BASQUE);
CASE(fa, FARSI);
CASE(fi, FINNISH);
CASE(fo, FAEROESE);
CASE(fr, FRENCH);
CASE(ga, IRISH);
CASE(gl, GALICIAN);
CASE(gu, GUJARATI);
CASE(he, HEBREW);
CASE(hi, HINDI);
CASE(hu, HUNGARIAN);
CASE(hy, ARMENIAN);
CASE(id, INDONESIAN);
CASE(is, ICELANDIC);
CASE(it, ITALIAN);
CASE(ja, JAPANESE);
CASE(ka, GEORGIAN);
CASE(km, KHMER);
CASE(kn, KANNADA);
CASE(ko, KOREAN);
CASE(ks, KASHMIRI);
CASE(lo, LAO);
CASE(lt, LITHUANIAN);
CASE(lv, LATVIAN);
CASE(mk, MACEDONIAN);
CASE(ml, MALAYALAM);
CASE(mn, MONGOLIAN);
CASE(mr, MARATHI);
CASE(ms, MALAY);
CASE(mt, MALTESE);
CASE(ne, NEPALI);
CASE(nl, DUTCH);
CASE(ns, SOTHO);
CASE(or, ORIYA);
CASE(pa, PUNJABI);
CASE(pl, POLISH);
CASE(pt, PORTUGUESE);
CASE(rm, ROMANSH);
CASE(ro, ROMANIAN);
CASE(ru, RUSSIAN);
CASE(rw, KINYARWANDA);
CASE(sa, SANSKRIT);
CASE(sb, UPPER_SORBIAN);
CASE(sd, SINDHI);
CASE(sk, SLOVAK);
CASE(sl, SLOVENIAN);
CASE(sq, ALBANIAN);
CASE(sv, SWEDISH);
CASE(sw, SWAHILI);
CASE(ta, TAMIL);
CASE(te, TELUGU);
CASE(tg, TAJIK);
CASE(th, THAI);
CASE(ti, TIGRIGNA);
CASE(tn, TSWANA);
CASE(tr, TURKISH);
CASE(tt, TATAR);
CASE(uk, UKRAINIAN);
CASE(ur, URDU);
CASE(uz, UZBEK);
CASE(vi, VIETNAMESE);
CASE(xh, XHOSA);
CASE(zh, CHINESE);
CASE(zu, ZULU);
#undef CASE
/* Special cases */
default:
switch (langid) {
case MAKELANGID(LANG_SERBIAN, 0x05): return "bs";
#define CASE(name, primary, sub) \
case MAKELANGID(LANG_##primary, SUBLANG_##sub): return #name
CASE(hr, SERBIAN, DEFAULT);
CASE(nb, NORWEGIAN, NORWEGIAN_BOKMAL);
CASE(nn, NORWEGIAN, NORWEGIAN_NYNORSK);
CASE(sh, SERBIAN, SERBIAN_LATIN);
CASE(sr, SERBIAN, SERBIAN_CYRILLIC);
#undef CASE
default: return "";
}
}
}
/* Here we collect the UI languages present on the system;
* MAX_LANGUAGES is certainly enough for that
*/
static const char *ui_langs[MAX_LANGUAGES];
static int num_ui_langs = 0;
BOOL CALLBACK
enum_ui_lang_proc (LPTSTR language, LONG_PTR /* unused_lParam */)
{
long langid = strtol(language, NULL, 16);
if (langid > 0xFFFF)
return TRUE;
ui_langs[num_ui_langs] = langid_to_string((LANGID) langid, NULL);
num_ui_langs++;
if (num_ui_langs == SAL_N_ELEMENTS(ui_langs) )
return FALSE;
return TRUE;
}
static BOOL
present_in_ui_langs(const char *lang)
{
for (int i = 0; i < num_ui_langs; i++)
if (memcmp (ui_langs[i], lang, 2) == 0)
return TRUE;
return FALSE;
}
extern "C" UINT __stdcall SelectLanguage( MSIHANDLE handle )
{
char feature[100];
MSIHANDLE database, view, record;
DWORD length;
int nlangs = 0;
char langs[MAX_LANGUAGES][6];
database = MsiGetActiveDatabase(handle);
if (MsiDatabaseOpenViewA(database, "SELECT Feature from Feature WHERE Feature_Parent = 'gm_Langpack_Languageroot'", &view) != ERROR_SUCCESS) {
MsiCloseHandle(database);
return ERROR_SUCCESS;
}
if (MsiViewExecute(view, NULL) != ERROR_SUCCESS) {
MsiCloseHandle(view);
MsiCloseHandle(database);
return ERROR_SUCCESS;
}
while (nlangs < MAX_LANGUAGES &&
MsiViewFetch(view, &record) == ERROR_SUCCESS) {
length = sizeof(feature);
if (MsiRecordGetStringA(record, 1, feature, &length) != ERROR_SUCCESS) {
MsiCloseHandle(record);
MsiCloseHandle(view);
MsiCloseHandle(database);
return ERROR_SUCCESS;
}
/* Keep track of what languages are included in this installer, if
* it is a multilanguage one.
*/
if (strcmp(feature, "gm_Langpack_r_en_US") != 0)
strcpy(langs[nlangs++], feature + strlen("gm_Langpack_r_"));
MsiCloseHandle(record);
}
MsiCloseHandle(view);
if (nlangs > 0) {
/* Deselect those languages that don't match any of the UI languages
* available on the system.
*/
int i;
int have_system_default_lang = 0;
const char *system_default_lang = langid_to_string(GetSystemDefaultUILanguage(), &have_system_default_lang);
const char *user_locale_lang = langid_to_string(LANGIDFROMLCID(GetThreadLocale()), NULL);
EnumUILanguagesA(enum_ui_lang_proc, 0, 0);
/* If one of the alternative languages in a multi-language installer
* is the system default UI language, deselect those languages that
* aren't among the UI languages available on the system.
* (On most Windows installations, just one UI language is present,
* which obviously is the same as the default UI language. But
* we want to be generic.)
* If none of the languages in a multi-language installer is the
* system default UI language (this happens now in 2.4.0 where we
* cannot put as many UI languages into the installer as we would
* like, but only half a dozen: en-US,de,es,fr,it,pt-BR), pretend
* that English is the system default UI language,
* so that we will by default deselect everything except
* English. We don't want to by default install all half dozen
* languages for an unsuspecting user of a Finnish Windows, for
* instance. Sigh.
*/
if (system_default_lang[0]) {
for (i = 0; i < nlangs; i++) {
if (memcmp (system_default_lang, langs[i], 2) == 0) {
have_system_default_lang = 1;
}
}
}
if (!have_system_default_lang) {
system_default_lang = "en";
have_system_default_lang = 1;
}
if (have_system_default_lang) {
for (i = 0; i < nlangs; i++) {
if (memcmp(system_default_lang, langs[i], 2) != 0 &&
memcmp(user_locale_lang, langs[i], 2) != 0 &&
!present_in_ui_langs(langs[i])) {
UINT rc;
sprintf(feature, "gm_Langpack_r_%s", langs[i]);
rc = MsiSetFeatureStateA(handle, feature, INSTALLSTATE_ABSENT);
}
}
}
}
MsiCloseHandle(database);
return ERROR_SUCCESS;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#50509 MSI: UI language selection from command line (e.g. silent install)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 3.
*
*
* GNU Lesser General Public License Version 3
* =============================================
* 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
*
************************************************************************/
/* Currently the "all" installer has a bit over 100 UI languages, and
* I doubt it will grow a lot over that.
*/
#define MAX_LANGUAGES 200
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0500
#undef WINVER
#define WINVER 0x0500
#include <windows.h>
#include <msiquery.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sal/macros.h>
#include <systools/win32/uwinapi.h>
BOOL GetMsiProp( MSIHANDLE hMSI, const char* pPropName, char** ppValue )
{
DWORD sz = 0;
if ( MsiGetProperty( hMSI, pPropName, "", &sz ) == ERROR_MORE_DATA ) {
sz++;
DWORD nbytes = sz * sizeof( char );
char* buff = reinterpret_cast<char*>( malloc( nbytes ) );
ZeroMemory( buff, nbytes );
MsiGetProperty( hMSI, pPropName, buff, &sz );
*ppValue = buff;
return ( strlen(buff) > 0 );
}
return FALSE;
}
static const char *
langid_to_string( LANGID langid, int *have_default_lang )
{
/* Map from LANGID to string. The languages below are now in
* alphabetical order of codes as in
* setup_native/source/win32/msi-encodinglist.txt. Only the
* language part is returned in the string.
*/
switch (PRIMARYLANGID (langid)) {
case LANG_ENGLISH:
if (have_default_lang != NULL &&
langid == MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT))
*have_default_lang = 1;
return "en";
#define CASE(name, primary) \
case LANG_##primary: return #name
CASE(af, AFRIKAANS);
CASE(am, AMHARIC);
CASE(ar, ARABIC);
CASE(as, ASSAMESE);
CASE(be, BELARUSIAN);
CASE(bg, BULGARIAN);
CASE(bn, BENGALI);
CASE(br, BRETON);
CASE(ca, CATALAN);
CASE(cs, CZECH);
CASE(cy, WELSH);
CASE(da, DANISH);
CASE(de, GERMAN);
CASE(el, GREEK);
CASE(es, SPANISH);
CASE(et, ESTONIAN);
CASE(eu, BASQUE);
CASE(fa, FARSI);
CASE(fi, FINNISH);
CASE(fo, FAEROESE);
CASE(fr, FRENCH);
CASE(ga, IRISH);
CASE(gl, GALICIAN);
CASE(gu, GUJARATI);
CASE(he, HEBREW);
CASE(hi, HINDI);
CASE(hu, HUNGARIAN);
CASE(hy, ARMENIAN);
CASE(id, INDONESIAN);
CASE(is, ICELANDIC);
CASE(it, ITALIAN);
CASE(ja, JAPANESE);
CASE(ka, GEORGIAN);
CASE(km, KHMER);
CASE(kn, KANNADA);
CASE(ko, KOREAN);
CASE(ks, KASHMIRI);
CASE(lo, LAO);
CASE(lt, LITHUANIAN);
CASE(lv, LATVIAN);
CASE(mk, MACEDONIAN);
CASE(ml, MALAYALAM);
CASE(mn, MONGOLIAN);
CASE(mr, MARATHI);
CASE(ms, MALAY);
CASE(mt, MALTESE);
CASE(ne, NEPALI);
CASE(nl, DUTCH);
CASE(ns, SOTHO);
CASE(or, ORIYA);
CASE(pa, PUNJABI);
CASE(pl, POLISH);
CASE(pt, PORTUGUESE);
CASE(rm, ROMANSH);
CASE(ro, ROMANIAN);
CASE(ru, RUSSIAN);
CASE(rw, KINYARWANDA);
CASE(sa, SANSKRIT);
CASE(sb, UPPER_SORBIAN);
CASE(sd, SINDHI);
CASE(sk, SLOVAK);
CASE(sl, SLOVENIAN);
CASE(sq, ALBANIAN);
CASE(sv, SWEDISH);
CASE(sw, SWAHILI);
CASE(ta, TAMIL);
CASE(te, TELUGU);
CASE(tg, TAJIK);
CASE(th, THAI);
CASE(ti, TIGRIGNA);
CASE(tn, TSWANA);
CASE(tr, TURKISH);
CASE(tt, TATAR);
CASE(uk, UKRAINIAN);
CASE(ur, URDU);
CASE(uz, UZBEK);
CASE(vi, VIETNAMESE);
CASE(xh, XHOSA);
CASE(zh, CHINESE);
CASE(zu, ZULU);
#undef CASE
/* Special cases */
default:
switch (langid) {
case MAKELANGID(LANG_SERBIAN, 0x05): return "bs";
#define CASE(name, primary, sub) \
case MAKELANGID(LANG_##primary, SUBLANG_##sub): return #name
CASE(hr, SERBIAN, DEFAULT);
CASE(nb, NORWEGIAN, NORWEGIAN_BOKMAL);
CASE(nn, NORWEGIAN, NORWEGIAN_NYNORSK);
CASE(sh, SERBIAN, SERBIAN_LATIN);
CASE(sr, SERBIAN, SERBIAN_CYRILLIC);
#undef CASE
default: return "";
}
}
}
/* Here we collect the UI languages present on the system;
* MAX_LANGUAGES is certainly enough for that
*/
static const char *ui_langs[MAX_LANGUAGES];
static int num_ui_langs = 0;
BOOL CALLBACK
enum_ui_lang_proc (LPTSTR language, LONG_PTR /* unused_lParam */)
{
long langid = strtol(language, NULL, 16);
if (langid > 0xFFFF)
return TRUE;
ui_langs[num_ui_langs] = langid_to_string((LANGID) langid, NULL);
num_ui_langs++;
if (num_ui_langs == SAL_N_ELEMENTS(ui_langs) )
return FALSE;
return TRUE;
}
static BOOL
present_in_ui_langs(const char *lang)
{
for (int i = 0; i < num_ui_langs; i++)
if (memcmp (ui_langs[i], lang, ( strlen(ui_langs[i]) >= strlen(lang) ) ? strlen(lang) : strlen(ui_langs[i]) ) == 0)
return TRUE;
return FALSE;
}
extern "C" UINT __stdcall SelectLanguage( MSIHANDLE handle )
{
char feature[100];
MSIHANDLE database, view, record;
DWORD length;
int nlangs = 0;
char langs[MAX_LANGUAGES][6];
database = MsiGetActiveDatabase(handle);
if (MsiDatabaseOpenViewA(database, "SELECT Feature from Feature WHERE Feature_Parent = 'gm_Langpack_Languageroot'", &view) != ERROR_SUCCESS) {
MsiCloseHandle(database);
return ERROR_SUCCESS;
}
if (MsiViewExecute(view, NULL) != ERROR_SUCCESS) {
MsiCloseHandle(view);
MsiCloseHandle(database);
return ERROR_SUCCESS;
}
while (nlangs < MAX_LANGUAGES &&
MsiViewFetch(view, &record) == ERROR_SUCCESS) {
length = sizeof(feature);
if (MsiRecordGetStringA(record, 1, feature, &length) != ERROR_SUCCESS) {
MsiCloseHandle(record);
MsiCloseHandle(view);
MsiCloseHandle(database);
return ERROR_SUCCESS;
}
/* Keep track of what languages are included in this installer, if
* it is a multilanguage one.
*/
if (strcmp(feature, "gm_Langpack_r_en_US") != 0)
strcpy(langs[nlangs++], feature + strlen("gm_Langpack_r_"));
MsiCloseHandle(record);
}
MsiCloseHandle(view);
if (nlangs > 0) {
int i;
char* pVal = NULL;
if ( (GetMsiProp( handle, "UI_LANGS", &pVal )) && pVal ) {
/* user gave UI languages explicitely with UI_LANGS property */
int sel_ui_lang = 0;
strcpy(langs[nlangs++], "en_US");
char *str_ptr;
str_ptr = strtok(pVal, ",");
for(; str_ptr != NULL ;) {
ui_langs[num_ui_langs] = str_ptr;
num_ui_langs++;
str_ptr = strtok(NULL, ",");
}
for (i = 0; i < nlangs; i++) {
if (!present_in_ui_langs(langs[i])) {
UINT rc;
sprintf(feature, "gm_Langpack_r_%s", langs[i]);
rc = MsiSetFeatureStateA(handle, feature, INSTALLSTATE_ABSENT);
}
else {
sel_ui_lang++;
}
}
if ( sel_ui_lang == 0 ) {
/* When UI_LANG property contains only languages that are not present
* in the installer, install at least en_US localization.
*/
MsiSetFeatureStateA(handle, "gm_Langpack_r_en_US", INSTALLSTATE_LOCAL);
}
}
else {
/* Deselect those languages that don't match any of the UI languages
* available on the system.
*/
int have_system_default_lang = 0;
const char *system_default_lang = langid_to_string(GetSystemDefaultUILanguage(), &have_system_default_lang);
const char *user_locale_lang = langid_to_string(LANGIDFROMLCID(GetThreadLocale()), NULL);
EnumUILanguagesA(enum_ui_lang_proc, 0, 0);
/* If one of the alternative languages in a multi-language installer
* is the system default UI language, deselect those languages that
* aren't among the UI languages available on the system.
* (On most Windows installations, just one UI language is present,
* which obviously is the same as the default UI language. But
* we want to be generic.)
* If none of the languages in a multi-language installer is the
* system default UI language (this happens now in 2.4.0 where we
* cannot put as many UI languages into the installer as we would
* like, but only half a dozen: en-US,de,es,fr,it,pt-BR), pretend
* that English is the system default UI language,
* so that we will by default deselect everything except
* English. We don't want to by default install all half dozen
* languages for an unsuspecting user of a Finnish Windows, for
* instance. Sigh.
*/
if (system_default_lang[0]) {
for (i = 0; i < nlangs; i++) {
if (memcmp (system_default_lang, langs[i], 2) == 0) {
have_system_default_lang = 1;
}
}
}
if (!have_system_default_lang) {
system_default_lang = "en";
have_system_default_lang = 1;
}
if (have_system_default_lang) {
for (i = 0; i < nlangs; i++) {
if (memcmp(system_default_lang, langs[i], 2) != 0 &&
memcmp(user_locale_lang, langs[i], 2) != 0 &&
!present_in_ui_langs(langs[i])) {
UINT rc;
sprintf(feature, "gm_Langpack_r_%s", langs[i]);
rc = MsiSetFeatureStateA(handle, feature, INSTALLSTATE_ABSENT);
}
}
}
}
}
MsiCloseHandle(database);
return ERROR_SUCCESS;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
typedef InProcessBrowserTest SessionRestoreTest;
#if !defined(OS_WIN)
// http://crbug.com/39476
#define RestoreOnNewWindowWithNoTabbedBrowsers \
FLAKY_RestoreOnNewWindowWithNoTabbedBrowsers
#endif
// Makes sure when session restore is triggered in the same process we don't end
// up with an extra tab.
IN_PROC_BROWSER_TEST_F(SessionRestoreTest,
RestoreOnNewWindowWithNoTabbedBrowsers) {
if (browser_defaults::kRestorePopups)
return;
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
ui_test_utils::NavigateToURL(browser(), url);
// Turn on session restore.
SessionStartupPref::SetStartupPref(
browser()->profile(),
SessionStartupPref(SessionStartupPref::LAST));
// Create a new popup.
Profile* profile = browser()->profile();
Browser* popup = Browser::CreateForPopup(profile);
popup->window()->Show();
// Close the browser.
browser()->window()->Close();
// Create a new window, which should trigger session restore.
popup->NewWindow();
Browser* new_browser = ui_test_utils::WaitForNewBrowser();
ASSERT_TRUE(new_browser != NULL);
// The browser should only have one tab.
ASSERT_EQ(1, new_browser->tab_count());
// And the first url should be url.
EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());
}
<commit_msg>Disable SessionRestoreTest.RestoreOnNewWindowWithNoTabbedBrowsers on Mac and Linux since it crashes.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
typedef InProcessBrowserTest SessionRestoreTest;
#if !defined(OS_WIN)
// http://crbug.com/39476
#define RestoreOnNewWindowWithNoTabbedBrowsers \
DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers
#endif
// Makes sure when session restore is triggered in the same process we don't end
// up with an extra tab.
IN_PROC_BROWSER_TEST_F(SessionRestoreTest,
RestoreOnNewWindowWithNoTabbedBrowsers) {
if (browser_defaults::kRestorePopups)
return;
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
ui_test_utils::NavigateToURL(browser(), url);
// Turn on session restore.
SessionStartupPref::SetStartupPref(
browser()->profile(),
SessionStartupPref(SessionStartupPref::LAST));
// Create a new popup.
Profile* profile = browser()->profile();
Browser* popup = Browser::CreateForPopup(profile);
popup->window()->Show();
// Close the browser.
browser()->window()->Close();
// Create a new window, which should trigger session restore.
popup->NewWindow();
Browser* new_browser = ui_test_utils::WaitForNewBrowser();
ASSERT_TRUE(new_browser != NULL);
// The browser should only have one tab.
ASSERT_EQ(1, new_browser->tab_count());
// And the first url should be url.
EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/panels/panel_browser_titlebar_gtk.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/gtk/custom_button.h"
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/ui/panels/panel_browser_window_gtk.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/gtk/gtk_compat.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/skia_utils_gtk.h"
namespace {
// Padding around the titlebar.
const int kPanelTitlebarPaddingTop = 7;
const int kPanelTitlebarPaddingBottom = 7;
const int kPanelTitlebarPaddingLeft = 4;
const int kPanelTitlebarPaddingRight = 9;
// Spacing between buttons of panel's titlebar.
const int kPanelButtonSpacing = 9;
// Spacing between the icon and the title text.
const int kPanelIconTitleSpacing = 9;
// Color used to draw title text under default theme.
const SkColor kTitleTextDefaultColor = SkColorSetRGB(0xf9, 0xf9, 0xf9);
// Markup used to paint the title with the desired font.
const char* const kTitleMarkupPrefix = "<span face='Arial' size='11264'>";
const char* const kTitleMarkupSuffix = "</span>";
} // namespace
PanelBrowserTitlebarGtk::PanelBrowserTitlebarGtk(
PanelBrowserWindowGtk* browser_window, GtkWindow* window)
: browser_window_(browser_window),
window_(window),
container_(NULL),
titlebar_right_buttons_vbox_(NULL),
titlebar_right_buttons_hbox_(NULL),
icon_(NULL),
title_(NULL),
theme_service_(NULL) {
}
PanelBrowserTitlebarGtk::~PanelBrowserTitlebarGtk() {
}
void PanelBrowserTitlebarGtk::Init() {
container_ = gtk_event_box_new();
gtk_widget_set_name(container_, "chrome-panel-titlebar");
gtk_event_box_set_visible_window(GTK_EVENT_BOX(container_), FALSE);
// We use an alignment to control the titlebar paddings.
GtkWidget* container_alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_container_add(GTK_CONTAINER(container_), container_alignment);
gtk_alignment_set_padding(GTK_ALIGNMENT(container_alignment),
kPanelTitlebarPaddingTop,
kPanelTitlebarPaddingBottom,
kPanelTitlebarPaddingLeft,
kPanelTitlebarPaddingRight);
// Add a container box.
GtkWidget* container_hbox = gtk_hbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(container_alignment), container_hbox);
g_signal_connect(window_, "window-state-event",
G_CALLBACK(OnWindowStateChangedThunk), this);
// Add minimize/restore and close buttons. Panel buttons are always placed
// on the right part of the titlebar.
titlebar_right_buttons_vbox_ = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(container_hbox), titlebar_right_buttons_vbox_,
FALSE, FALSE, 0);
BuildButtons();
// Add hbox for holding icon and title.
GtkWidget* icon_title_hbox = gtk_hbox_new(FALSE, kPanelIconTitleSpacing);
gtk_box_pack_start(GTK_BOX(container_hbox), icon_title_hbox, TRUE, TRUE, 0);
// Add icon. We use the app logo as a placeholder image so the title doesn't
// jump around.
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
icon_ = gtk_image_new_from_pixbuf(rb.GetNativeImageNamed(
IDR_PRODUCT_LOGO_16, ui::ResourceBundle::RTL_ENABLED).ToGdkPixbuf());
g_object_set_data(G_OBJECT(icon_), "left-align-popup",
reinterpret_cast<void*>(true));
gtk_box_pack_start(GTK_BOX(icon_title_hbox), icon_, FALSE, FALSE, 0);
// Add title.
title_ = gtk_label_new(NULL);
gtk_label_set_ellipsize(GTK_LABEL(title_), PANGO_ELLIPSIZE_END);
gtk_misc_set_alignment(GTK_MISC(title_), 0.0, 0.5);
gtk_box_pack_start(GTK_BOX(icon_title_hbox), title_, TRUE, TRUE, 0);
UpdateTitleAndIcon();
theme_service_ = GtkThemeService::GetFrom(
browser_window_->panel()->profile());
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
content::Source<ThemeService>(theme_service_));
theme_service_->InitThemesFor(this);
gtk_widget_show_all(container_);
}
SkColor PanelBrowserTitlebarGtk::GetTextColor() const {
if (browser_window_->UsingDefaultTheme())
return kTitleTextDefaultColor;
return theme_service_->GetColor(browser_window_->paint_state() ==
PanelBrowserWindowGtk::PAINT_AS_ACTIVE ?
ThemeService::COLOR_TAB_TEXT :
ThemeService::COLOR_BACKGROUND_TAB_TEXT);
}
void PanelBrowserTitlebarGtk::BuildButtons() {
minimize_button_.reset(CreateButton(panel::MINIMIZE_BUTTON));
restore_button_.reset(CreateButton(panel::RESTORE_BUTTON));
close_button_.reset(CreateButton(panel::CLOSE_BUTTON));
// We control visibility of minimize and restore buttons.
gtk_widget_set_no_show_all(minimize_button_->widget(), TRUE);
gtk_widget_set_no_show_all(restore_button_->widget(), TRUE);
// Now show the correct widgets in the two hierarchies.
UpdateMinimizeRestoreButtonVisibility();
}
CustomDrawButton* PanelBrowserTitlebarGtk::CreateButton(
panel::TitlebarButtonType button_type) {
int normal_image_id;
int pressed_image_id;
int hover_image_id;
int tooltip_id;
GetButtonResources(button_type, &normal_image_id, &pressed_image_id,
&hover_image_id, &tooltip_id);
CustomDrawButton* button = new CustomDrawButton(normal_image_id,
pressed_image_id,
hover_image_id,
0);
gtk_widget_add_events(GTK_WIDGET(button->widget()), GDK_POINTER_MOTION_MASK);
g_signal_connect(button->widget(), "clicked",
G_CALLBACK(OnButtonClickedThunk), this);
std::string localized_tooltip = l10n_util::GetStringUTF8(tooltip_id);
gtk_widget_set_tooltip_text(button->widget(),
localized_tooltip.c_str());
GtkWidget* box = GetButtonHBox();
gtk_box_pack_start(GTK_BOX(box), button->widget(), FALSE, FALSE, 0);
return button;
}
void PanelBrowserTitlebarGtk::GetButtonResources(
panel::TitlebarButtonType button_type,
int* normal_image_id,
int* pressed_image_id,
int* hover_image_id,
int* tooltip_id) const {
switch (button_type) {
case panel::CLOSE_BUTTON:
*normal_image_id = IDR_PANEL_CLOSE;
*pressed_image_id = IDR_PANEL_CLOSE_C;
*hover_image_id = IDR_PANEL_CLOSE_H;
*tooltip_id = IDS_PANEL_CLOSE_TOOLTIP;
break;
case panel::MINIMIZE_BUTTON:
*normal_image_id = IDR_PANEL_MINIMIZE;
*pressed_image_id = IDR_PANEL_MINIMIZE_C;
*hover_image_id = IDR_PANEL_MINIMIZE_H;
*tooltip_id = IDS_PANEL_MINIMIZE_TOOLTIP;
break;
case panel::RESTORE_BUTTON:
*normal_image_id = IDR_PANEL_RESTORE;
*pressed_image_id = IDR_PANEL_RESTORE_C;
*hover_image_id = IDR_PANEL_RESTORE_H;
*tooltip_id = IDS_PANEL_RESTORE_TOOLTIP;
break;
}
}
GtkWidget* PanelBrowserTitlebarGtk::GetButtonHBox() {
if (!titlebar_right_buttons_hbox_) {
// We put the minimize/restore/close buttons in a vbox so they are top
// aligned (up to padding) and don't vertically stretch.
titlebar_right_buttons_hbox_ = gtk_hbox_new(FALSE, kPanelButtonSpacing);
gtk_box_pack_start(GTK_BOX(titlebar_right_buttons_vbox_),
titlebar_right_buttons_hbox_, FALSE, FALSE, 0);
}
return titlebar_right_buttons_hbox_;
}
void PanelBrowserTitlebarGtk::UpdateCustomFrame(bool use_custom_frame) {
// Nothing to do.
}
void PanelBrowserTitlebarGtk::UpdateTitleAndIcon() {
std::string title_text =
UTF16ToUTF8(browser_window_->panel()->GetWindowTitle());
// Add the markup to show the title in the desired font.
gchar* escaped_title_text = g_markup_escape_text(title_text.c_str(), -1);
gchar* title_text_with_markup = g_strconcat(kTitleMarkupPrefix,
escaped_title_text,
kTitleMarkupSuffix,
NULL);
gtk_label_set_markup(GTK_LABEL(title_), title_text_with_markup);
g_free(escaped_title_text);
g_free(title_text_with_markup);
}
void PanelBrowserTitlebarGtk::UpdateThrobber(
content::WebContents* web_contents) {
if (web_contents && web_contents->IsLoading()) {
GdkPixbuf* icon_pixbuf =
throbber_.GetNextFrame(web_contents->IsWaitingForResponse());
gtk_image_set_from_pixbuf(GTK_IMAGE(icon_), icon_pixbuf);
} else {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
SkBitmap icon = browser_window_->panel()->GetCurrentPageIcon();
if (icon.empty()) {
// Fallback to the Chromium icon if the page has no icon.
gtk_image_set_from_pixbuf(GTK_IMAGE(icon_),
rb.GetNativeImageNamed(IDR_PRODUCT_LOGO_16).ToGdkPixbuf());
} else {
GdkPixbuf* icon_pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
gtk_image_set_from_pixbuf(GTK_IMAGE(icon_), icon_pixbuf);
g_object_unref(icon_pixbuf);
}
throbber_.Reset();
}
}
void PanelBrowserTitlebarGtk::ShowContextMenu(GdkEventButton* event) {
// Panel does not show any context menu.
}
void PanelBrowserTitlebarGtk::UpdateTextColor() {
GdkColor text_color = gfx::SkColorToGdkColor(GetTextColor());
gtk_util::SetLabelColor(title_, &text_color);
}
void PanelBrowserTitlebarGtk::UpdateMinimizeRestoreButtonVisibility() {
Panel* panel = browser_window_->panel();
gtk_widget_set_visible(minimize_button_->widget(), panel->CanMinimize());
gtk_widget_set_visible(restore_button_->widget(), panel->CanRestore());
}
gboolean PanelBrowserTitlebarGtk::OnWindowStateChanged(
GtkWindow* window, GdkEventWindowState* event) {
UpdateTextColor();
return FALSE;
}
void PanelBrowserTitlebarGtk::OnButtonClicked(GtkWidget* button) {
if (close_button_->widget() == button) {
browser_window_->panel()->Close();
return;
}
GdkEvent* event = gtk_get_current_event();
DCHECK(event && event->type == GDK_BUTTON_RELEASE);
if (minimize_button_->widget() == button) {
browser_window_->panel()->OnMinimizeButtonClicked(
(event->button.state & GDK_CONTROL_MASK) ?
panel::APPLY_TO_ALL : panel::NO_MODIFIER);
} else if (restore_button_->widget() == button) {
browser_window_->panel()->OnRestoreButtonClicked(
(event->button.state & GDK_CONTROL_MASK) ?
panel::APPLY_TO_ALL : panel::NO_MODIFIER);
}
gdk_event_free(event);
}
void PanelBrowserTitlebarGtk::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
UpdateTextColor();
break;
default:
NOTREACHED();
}
}
void PanelBrowserTitlebarGtk::SendEnterNotifyToCloseButtonIfUnderMouse() {
if (!close_button())
return;
gint x;
gint y;
GtkAllocation widget_allocation = close_button()->WidgetAllocation();
gtk_widget_get_pointer(GTK_WIDGET(close_button()->widget()), &x, &y);
gfx::Rect button_rect(0, 0, widget_allocation.width,
widget_allocation.height);
if (!button_rect.Contains(x, y)) {
// Mouse is not over the close button.
return;
}
// Create and emit an enter-notify-event on close button.
GValue return_value;
return_value.g_type = G_TYPE_BOOLEAN;
g_value_set_boolean(&return_value, false);
GdkEvent* event = gdk_event_new(GDK_ENTER_NOTIFY);
event->crossing.window =
gtk_button_get_event_window(GTK_BUTTON(close_button()->widget()));
event->crossing.send_event = FALSE;
event->crossing.subwindow = gtk_widget_get_window(close_button()->widget());
event->crossing.time = gtk_util::XTimeNow();
event->crossing.x = x;
event->crossing.y = y;
event->crossing.x_root = widget_allocation.x;
event->crossing.y_root = widget_allocation.y;
event->crossing.mode = GDK_CROSSING_NORMAL;
event->crossing.detail = GDK_NOTIFY_ANCESTOR;
event->crossing.focus = true;
event->crossing.state = 0;
g_signal_emit_by_name(GTK_OBJECT(close_button()->widget()),
"enter-notify-event", event,
&return_value);
}
GtkWidget* PanelBrowserTitlebarGtk::widget() const {
return container_;
}
void PanelBrowserTitlebarGtk::set_window(GtkWindow* window) {
window_ = window;
}
AvatarMenuButtonGtk* PanelBrowserTitlebarGtk::avatar_button() const {
// Not supported in panel.
return NULL;
}
<commit_msg>Initialize variables PanelBrowserTitlebarGtk::CreateButton() to make g++ 4.6 happy.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/panels/panel_browser_titlebar_gtk.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/gtk/custom_button.h"
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/ui/panels/panel_browser_window_gtk.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/gtk/gtk_compat.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/skia_utils_gtk.h"
namespace {
// Padding around the titlebar.
const int kPanelTitlebarPaddingTop = 7;
const int kPanelTitlebarPaddingBottom = 7;
const int kPanelTitlebarPaddingLeft = 4;
const int kPanelTitlebarPaddingRight = 9;
// Spacing between buttons of panel's titlebar.
const int kPanelButtonSpacing = 9;
// Spacing between the icon and the title text.
const int kPanelIconTitleSpacing = 9;
// Color used to draw title text under default theme.
const SkColor kTitleTextDefaultColor = SkColorSetRGB(0xf9, 0xf9, 0xf9);
// Markup used to paint the title with the desired font.
const char* const kTitleMarkupPrefix = "<span face='Arial' size='11264'>";
const char* const kTitleMarkupSuffix = "</span>";
} // namespace
PanelBrowserTitlebarGtk::PanelBrowserTitlebarGtk(
PanelBrowserWindowGtk* browser_window, GtkWindow* window)
: browser_window_(browser_window),
window_(window),
container_(NULL),
titlebar_right_buttons_vbox_(NULL),
titlebar_right_buttons_hbox_(NULL),
icon_(NULL),
title_(NULL),
theme_service_(NULL) {
}
PanelBrowserTitlebarGtk::~PanelBrowserTitlebarGtk() {
}
void PanelBrowserTitlebarGtk::Init() {
container_ = gtk_event_box_new();
gtk_widget_set_name(container_, "chrome-panel-titlebar");
gtk_event_box_set_visible_window(GTK_EVENT_BOX(container_), FALSE);
// We use an alignment to control the titlebar paddings.
GtkWidget* container_alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_container_add(GTK_CONTAINER(container_), container_alignment);
gtk_alignment_set_padding(GTK_ALIGNMENT(container_alignment),
kPanelTitlebarPaddingTop,
kPanelTitlebarPaddingBottom,
kPanelTitlebarPaddingLeft,
kPanelTitlebarPaddingRight);
// Add a container box.
GtkWidget* container_hbox = gtk_hbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(container_alignment), container_hbox);
g_signal_connect(window_, "window-state-event",
G_CALLBACK(OnWindowStateChangedThunk), this);
// Add minimize/restore and close buttons. Panel buttons are always placed
// on the right part of the titlebar.
titlebar_right_buttons_vbox_ = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(container_hbox), titlebar_right_buttons_vbox_,
FALSE, FALSE, 0);
BuildButtons();
// Add hbox for holding icon and title.
GtkWidget* icon_title_hbox = gtk_hbox_new(FALSE, kPanelIconTitleSpacing);
gtk_box_pack_start(GTK_BOX(container_hbox), icon_title_hbox, TRUE, TRUE, 0);
// Add icon. We use the app logo as a placeholder image so the title doesn't
// jump around.
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
icon_ = gtk_image_new_from_pixbuf(rb.GetNativeImageNamed(
IDR_PRODUCT_LOGO_16, ui::ResourceBundle::RTL_ENABLED).ToGdkPixbuf());
g_object_set_data(G_OBJECT(icon_), "left-align-popup",
reinterpret_cast<void*>(true));
gtk_box_pack_start(GTK_BOX(icon_title_hbox), icon_, FALSE, FALSE, 0);
// Add title.
title_ = gtk_label_new(NULL);
gtk_label_set_ellipsize(GTK_LABEL(title_), PANGO_ELLIPSIZE_END);
gtk_misc_set_alignment(GTK_MISC(title_), 0.0, 0.5);
gtk_box_pack_start(GTK_BOX(icon_title_hbox), title_, TRUE, TRUE, 0);
UpdateTitleAndIcon();
theme_service_ = GtkThemeService::GetFrom(
browser_window_->panel()->profile());
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
content::Source<ThemeService>(theme_service_));
theme_service_->InitThemesFor(this);
gtk_widget_show_all(container_);
}
SkColor PanelBrowserTitlebarGtk::GetTextColor() const {
if (browser_window_->UsingDefaultTheme())
return kTitleTextDefaultColor;
return theme_service_->GetColor(browser_window_->paint_state() ==
PanelBrowserWindowGtk::PAINT_AS_ACTIVE ?
ThemeService::COLOR_TAB_TEXT :
ThemeService::COLOR_BACKGROUND_TAB_TEXT);
}
void PanelBrowserTitlebarGtk::BuildButtons() {
minimize_button_.reset(CreateButton(panel::MINIMIZE_BUTTON));
restore_button_.reset(CreateButton(panel::RESTORE_BUTTON));
close_button_.reset(CreateButton(panel::CLOSE_BUTTON));
// We control visibility of minimize and restore buttons.
gtk_widget_set_no_show_all(minimize_button_->widget(), TRUE);
gtk_widget_set_no_show_all(restore_button_->widget(), TRUE);
// Now show the correct widgets in the two hierarchies.
UpdateMinimizeRestoreButtonVisibility();
}
CustomDrawButton* PanelBrowserTitlebarGtk::CreateButton(
panel::TitlebarButtonType button_type) {
int normal_image_id = -1;
int pressed_image_id = -1;
int hover_image_id = -1;
int tooltip_id = -1;
GetButtonResources(button_type, &normal_image_id, &pressed_image_id,
&hover_image_id, &tooltip_id);
CustomDrawButton* button = new CustomDrawButton(normal_image_id,
pressed_image_id,
hover_image_id,
0);
gtk_widget_add_events(GTK_WIDGET(button->widget()), GDK_POINTER_MOTION_MASK);
g_signal_connect(button->widget(), "clicked",
G_CALLBACK(OnButtonClickedThunk), this);
std::string localized_tooltip = l10n_util::GetStringUTF8(tooltip_id);
gtk_widget_set_tooltip_text(button->widget(),
localized_tooltip.c_str());
GtkWidget* box = GetButtonHBox();
gtk_box_pack_start(GTK_BOX(box), button->widget(), FALSE, FALSE, 0);
return button;
}
void PanelBrowserTitlebarGtk::GetButtonResources(
panel::TitlebarButtonType button_type,
int* normal_image_id,
int* pressed_image_id,
int* hover_image_id,
int* tooltip_id) const {
switch (button_type) {
case panel::CLOSE_BUTTON:
*normal_image_id = IDR_PANEL_CLOSE;
*pressed_image_id = IDR_PANEL_CLOSE_C;
*hover_image_id = IDR_PANEL_CLOSE_H;
*tooltip_id = IDS_PANEL_CLOSE_TOOLTIP;
break;
case panel::MINIMIZE_BUTTON:
*normal_image_id = IDR_PANEL_MINIMIZE;
*pressed_image_id = IDR_PANEL_MINIMIZE_C;
*hover_image_id = IDR_PANEL_MINIMIZE_H;
*tooltip_id = IDS_PANEL_MINIMIZE_TOOLTIP;
break;
case panel::RESTORE_BUTTON:
*normal_image_id = IDR_PANEL_RESTORE;
*pressed_image_id = IDR_PANEL_RESTORE_C;
*hover_image_id = IDR_PANEL_RESTORE_H;
*tooltip_id = IDS_PANEL_RESTORE_TOOLTIP;
break;
}
}
GtkWidget* PanelBrowserTitlebarGtk::GetButtonHBox() {
if (!titlebar_right_buttons_hbox_) {
// We put the minimize/restore/close buttons in a vbox so they are top
// aligned (up to padding) and don't vertically stretch.
titlebar_right_buttons_hbox_ = gtk_hbox_new(FALSE, kPanelButtonSpacing);
gtk_box_pack_start(GTK_BOX(titlebar_right_buttons_vbox_),
titlebar_right_buttons_hbox_, FALSE, FALSE, 0);
}
return titlebar_right_buttons_hbox_;
}
void PanelBrowserTitlebarGtk::UpdateCustomFrame(bool use_custom_frame) {
// Nothing to do.
}
void PanelBrowserTitlebarGtk::UpdateTitleAndIcon() {
std::string title_text =
UTF16ToUTF8(browser_window_->panel()->GetWindowTitle());
// Add the markup to show the title in the desired font.
gchar* escaped_title_text = g_markup_escape_text(title_text.c_str(), -1);
gchar* title_text_with_markup = g_strconcat(kTitleMarkupPrefix,
escaped_title_text,
kTitleMarkupSuffix,
NULL);
gtk_label_set_markup(GTK_LABEL(title_), title_text_with_markup);
g_free(escaped_title_text);
g_free(title_text_with_markup);
}
void PanelBrowserTitlebarGtk::UpdateThrobber(
content::WebContents* web_contents) {
if (web_contents && web_contents->IsLoading()) {
GdkPixbuf* icon_pixbuf =
throbber_.GetNextFrame(web_contents->IsWaitingForResponse());
gtk_image_set_from_pixbuf(GTK_IMAGE(icon_), icon_pixbuf);
} else {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
SkBitmap icon = browser_window_->panel()->GetCurrentPageIcon();
if (icon.empty()) {
// Fallback to the Chromium icon if the page has no icon.
gtk_image_set_from_pixbuf(GTK_IMAGE(icon_),
rb.GetNativeImageNamed(IDR_PRODUCT_LOGO_16).ToGdkPixbuf());
} else {
GdkPixbuf* icon_pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
gtk_image_set_from_pixbuf(GTK_IMAGE(icon_), icon_pixbuf);
g_object_unref(icon_pixbuf);
}
throbber_.Reset();
}
}
void PanelBrowserTitlebarGtk::ShowContextMenu(GdkEventButton* event) {
// Panel does not show any context menu.
}
void PanelBrowserTitlebarGtk::UpdateTextColor() {
GdkColor text_color = gfx::SkColorToGdkColor(GetTextColor());
gtk_util::SetLabelColor(title_, &text_color);
}
void PanelBrowserTitlebarGtk::UpdateMinimizeRestoreButtonVisibility() {
Panel* panel = browser_window_->panel();
gtk_widget_set_visible(minimize_button_->widget(), panel->CanMinimize());
gtk_widget_set_visible(restore_button_->widget(), panel->CanRestore());
}
gboolean PanelBrowserTitlebarGtk::OnWindowStateChanged(
GtkWindow* window, GdkEventWindowState* event) {
UpdateTextColor();
return FALSE;
}
void PanelBrowserTitlebarGtk::OnButtonClicked(GtkWidget* button) {
if (close_button_->widget() == button) {
browser_window_->panel()->Close();
return;
}
GdkEvent* event = gtk_get_current_event();
DCHECK(event && event->type == GDK_BUTTON_RELEASE);
if (minimize_button_->widget() == button) {
browser_window_->panel()->OnMinimizeButtonClicked(
(event->button.state & GDK_CONTROL_MASK) ?
panel::APPLY_TO_ALL : panel::NO_MODIFIER);
} else if (restore_button_->widget() == button) {
browser_window_->panel()->OnRestoreButtonClicked(
(event->button.state & GDK_CONTROL_MASK) ?
panel::APPLY_TO_ALL : panel::NO_MODIFIER);
}
gdk_event_free(event);
}
void PanelBrowserTitlebarGtk::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
UpdateTextColor();
break;
default:
NOTREACHED();
}
}
void PanelBrowserTitlebarGtk::SendEnterNotifyToCloseButtonIfUnderMouse() {
if (!close_button())
return;
gint x;
gint y;
GtkAllocation widget_allocation = close_button()->WidgetAllocation();
gtk_widget_get_pointer(GTK_WIDGET(close_button()->widget()), &x, &y);
gfx::Rect button_rect(0, 0, widget_allocation.width,
widget_allocation.height);
if (!button_rect.Contains(x, y)) {
// Mouse is not over the close button.
return;
}
// Create and emit an enter-notify-event on close button.
GValue return_value;
return_value.g_type = G_TYPE_BOOLEAN;
g_value_set_boolean(&return_value, false);
GdkEvent* event = gdk_event_new(GDK_ENTER_NOTIFY);
event->crossing.window =
gtk_button_get_event_window(GTK_BUTTON(close_button()->widget()));
event->crossing.send_event = FALSE;
event->crossing.subwindow = gtk_widget_get_window(close_button()->widget());
event->crossing.time = gtk_util::XTimeNow();
event->crossing.x = x;
event->crossing.y = y;
event->crossing.x_root = widget_allocation.x;
event->crossing.y_root = widget_allocation.y;
event->crossing.mode = GDK_CROSSING_NORMAL;
event->crossing.detail = GDK_NOTIFY_ANCESTOR;
event->crossing.focus = true;
event->crossing.state = 0;
g_signal_emit_by_name(GTK_OBJECT(close_button()->widget()),
"enter-notify-event", event,
&return_value);
}
GtkWidget* PanelBrowserTitlebarGtk::widget() const {
return container_;
}
void PanelBrowserTitlebarGtk::set_window(GtkWindow* window) {
window_ = window;
}
AvatarMenuButtonGtk* PanelBrowserTitlebarGtk::avatar_button() const {
// Not supported in panel.
return NULL;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/extensions/extension_dialog.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/extensions/extension_dialog_observer.h"
#include "chrome/browser/ui/views/window.h" // CreateViewsWindow
#include "chrome/common/chrome_notification_types.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "googleurl/src/gurl.h"
#include "views/widget/widget.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/frame/bubble_window.h"
#endif
namespace {
views::Widget* CreateWindow(gfx::NativeWindow parent,
views::WidgetDelegate* delegate) {
#if defined(OS_CHROMEOS)
// On Chrome OS we need to override the style to suppress padding around
// the borders.
return chromeos::BubbleWindow::Create(parent,
chromeos::STYLE_FLUSH, delegate);
#else
return browser::CreateViewsWindow(parent, delegate);
#endif
}
} // namespace
ExtensionDialog::ExtensionDialog(ExtensionHost* host,
ExtensionDialogObserver* observer)
: window_(NULL),
extension_host_(host),
observer_(observer) {
AddRef(); // Balanced in DeleteDelegate();
// Listen for the containing view calling window.close();
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
Source<Profile>(host->profile()));
}
ExtensionDialog::~ExtensionDialog() {
}
// static
ExtensionDialog* ExtensionDialog::Show(
const GURL& url,
Browser* browser,
TabContents* tab_contents,
int width,
int height,
ExtensionDialogObserver* observer) {
CHECK(browser);
ExtensionHost* host = CreateExtensionHost(url, browser);
if (!host)
return NULL;
host->set_associated_tab_contents(tab_contents);
ExtensionDialog* dialog = new ExtensionDialog(host, observer);
dialog->InitWindow(browser, width, height);
// Ensure the DOM JavaScript can respond immediately to keyboard shortcuts.
host->render_view_host()->view()->Focus();
return dialog;
}
// static
ExtensionHost* ExtensionDialog::CreateExtensionHost(const GURL& url,
Browser* browser) {
ExtensionProcessManager* manager =
browser->profile()->GetExtensionProcessManager();
DCHECK(manager);
if (!manager)
return NULL;
return manager->CreateDialogHost(url, browser);
}
void ExtensionDialog::InitWindow(Browser* browser, int width, int height) {
gfx::NativeWindow parent = browser->window()->GetNativeHandle();
window_ = CreateWindow(parent, this /* views::WidgetDelegate */);
// Center the window over the browser.
gfx::Point center = browser->window()->GetBounds().CenterPoint();
int x = center.x() - width / 2;
int y = center.y() - height / 2;
window_->SetBounds(gfx::Rect(x, y, width, height));
window_->Show();
window_->Activate();
}
void ExtensionDialog::ObserverDestroyed() {
observer_ = NULL;
}
void ExtensionDialog::Close() {
if (!window_)
return;
if (observer_)
observer_->ExtensionDialogIsClosing(this);
window_->Close();
window_ = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// views::WidgetDelegate overrides.
bool ExtensionDialog::CanResize() const {
return false;
}
bool ExtensionDialog::IsModal() const {
return true;
}
bool ExtensionDialog::ShouldShowWindowTitle() const {
return false;
}
void ExtensionDialog::DeleteDelegate() {
// The window has finished closing. Allow ourself to be deleted.
Release();
}
views::Widget* ExtensionDialog::GetWidget() {
return extension_host_->view()->GetWidget();
}
const views::Widget* ExtensionDialog::GetWidget() const {
return extension_host_->view()->GetWidget();
}
views::View* ExtensionDialog::GetContentsView() {
return extension_host_->view();
}
/////////////////////////////////////////////////////////////////////////////
// NotificationObserver overrides.
void ExtensionDialog::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
// If we aren't the host of the popup, then disregard the notification.
if (Details<ExtensionHost>(host()) != details)
return;
Close();
break;
default:
NOTREACHED() << L"Received unexpected notification";
break;
}
}
<commit_msg>Aura: Fix crash when opening CrOS file picker<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/extensions/extension_dialog.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/extensions/extension_dialog_observer.h"
#include "chrome/browser/ui/views/window.h" // CreateViewsWindow
#include "chrome/common/chrome_notification_types.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "googleurl/src/gurl.h"
#include "views/widget/widget.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/frame/bubble_window.h"
#endif
namespace {
views::Widget* CreateWindow(gfx::NativeWindow parent,
views::WidgetDelegate* delegate) {
#if defined(OS_CHROMEOS) && defined(TOOLKIT_USES_GTK)
// TODO(msw): revert to BubbleWindow for all ChromeOS cases when CL
// for crbug.com/98322 is landed.
// On Chrome OS we need to override the style to suppress padding around
// the borders.
return chromeos::BubbleWindow::Create(parent,
chromeos::STYLE_FLUSH, delegate);
#else
return browser::CreateViewsWindow(parent, delegate);
#endif
}
} // namespace
ExtensionDialog::ExtensionDialog(ExtensionHost* host,
ExtensionDialogObserver* observer)
: window_(NULL),
extension_host_(host),
observer_(observer) {
AddRef(); // Balanced in DeleteDelegate();
// Listen for the containing view calling window.close();
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
Source<Profile>(host->profile()));
}
ExtensionDialog::~ExtensionDialog() {
}
// static
ExtensionDialog* ExtensionDialog::Show(
const GURL& url,
Browser* browser,
TabContents* tab_contents,
int width,
int height,
ExtensionDialogObserver* observer) {
CHECK(browser);
ExtensionHost* host = CreateExtensionHost(url, browser);
if (!host)
return NULL;
host->set_associated_tab_contents(tab_contents);
ExtensionDialog* dialog = new ExtensionDialog(host, observer);
dialog->InitWindow(browser, width, height);
// Ensure the DOM JavaScript can respond immediately to keyboard shortcuts.
host->render_view_host()->view()->Focus();
return dialog;
}
// static
ExtensionHost* ExtensionDialog::CreateExtensionHost(const GURL& url,
Browser* browser) {
ExtensionProcessManager* manager =
browser->profile()->GetExtensionProcessManager();
DCHECK(manager);
if (!manager)
return NULL;
return manager->CreateDialogHost(url, browser);
}
void ExtensionDialog::InitWindow(Browser* browser, int width, int height) {
gfx::NativeWindow parent = browser->window()->GetNativeHandle();
window_ = CreateWindow(parent, this /* views::WidgetDelegate */);
// Center the window over the browser.
gfx::Point center = browser->window()->GetBounds().CenterPoint();
int x = center.x() - width / 2;
int y = center.y() - height / 2;
window_->SetBounds(gfx::Rect(x, y, width, height));
window_->Show();
window_->Activate();
}
void ExtensionDialog::ObserverDestroyed() {
observer_ = NULL;
}
void ExtensionDialog::Close() {
if (!window_)
return;
if (observer_)
observer_->ExtensionDialogIsClosing(this);
window_->Close();
window_ = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// views::WidgetDelegate overrides.
bool ExtensionDialog::CanResize() const {
return false;
}
bool ExtensionDialog::IsModal() const {
return true;
}
bool ExtensionDialog::ShouldShowWindowTitle() const {
return false;
}
void ExtensionDialog::DeleteDelegate() {
// The window has finished closing. Allow ourself to be deleted.
Release();
}
views::Widget* ExtensionDialog::GetWidget() {
return extension_host_->view()->GetWidget();
}
const views::Widget* ExtensionDialog::GetWidget() const {
return extension_host_->view()->GetWidget();
}
views::View* ExtensionDialog::GetContentsView() {
return extension_host_->view();
}
/////////////////////////////////////////////////////////////////////////////
// NotificationObserver overrides.
void ExtensionDialog::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
// If we aren't the host of the popup, then disregard the notification.
if (Details<ExtensionHost>(host()) != details)
return;
Close();
break;
default:
NOTREACHED() << L"Received unexpected notification";
break;
}
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/browser/devtools/remote_debugging_server.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/strings/stringprintf.h"
#include "chromecast/browser/devtools/cast_dev_tools_delegate.h"
#include "chromecast/common/chromecast_config.h"
#include "chromecast/common/pref_names.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/user_agent.h"
#include "net/socket/tcp_server_socket.h"
#if defined(OS_ANDROID)
#include "content/public/browser/android/devtools_auth.h"
#include "net/socket/unix_domain_server_socket_posix.h"
#endif // defined(OS_ANDROID)
namespace chromecast {
namespace shell {
namespace {
const char kFrontEndURL[] =
"https://chrome-devtools-frontend.appspot.com/serve_rev/%s/devtools.html";
const int kDefaultRemoteDebuggingPort = 9222;
#if defined(OS_ANDROID)
class UnixDomainServerSocketFactory
: public content::DevToolsHttpHandler::ServerSocketFactory {
public:
explicit UnixDomainServerSocketFactory(const std::string& socket_name)
: content::DevToolsHttpHandler::ServerSocketFactory(socket_name, 0, 1) {}
private:
// content::DevToolsHttpHandler::ServerSocketFactory.
virtual scoped_ptr<net::ServerSocket> Create() const override {
return scoped_ptr<net::ServerSocket>(
new net::UnixDomainServerSocket(
base::Bind(&content::CanUserConnectToDevTools),
true /* use_abstract_namespace */));
}
DISALLOW_COPY_AND_ASSIGN(UnixDomainServerSocketFactory);
};
#else
class TCPServerSocketFactory
: public content::DevToolsHttpHandler::ServerSocketFactory {
public:
TCPServerSocketFactory(const std::string& address, int port, int backlog)
: content::DevToolsHttpHandler::ServerSocketFactory(
address, port, backlog) {}
private:
// content::DevToolsHttpHandler::ServerSocketFactory.
virtual scoped_ptr<net::ServerSocket> Create() const override {
return scoped_ptr<net::ServerSocket>(
new net::TCPServerSocket(NULL, net::NetLog::Source()));
}
DISALLOW_COPY_AND_ASSIGN(TCPServerSocketFactory);
};
#endif
scoped_ptr<content::DevToolsHttpHandler::ServerSocketFactory>
CreateSocketFactory(int port) {
#if defined(OS_ANDROID)
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
std::string socket_name = "cast_shell_devtools_remote";
if (command_line->HasSwitch(switches::kRemoteDebuggingSocketName)) {
socket_name = command_line->GetSwitchValueASCII(
switches::kRemoteDebuggingSocketName);
}
return scoped_ptr<content::DevToolsHttpHandler::ServerSocketFactory>(
new UnixDomainServerSocketFactory(socket_name));
#else
return scoped_ptr<content::DevToolsHttpHandler::ServerSocketFactory>(
new TCPServerSocketFactory("0.0.0.0", port, 1));
#endif
}
std::string GetFrontendUrl() {
return base::StringPrintf(kFrontEndURL, content::GetWebKitRevision().c_str());
}
} // namespace
RemoteDebuggingServer::RemoteDebuggingServer()
: devtools_http_handler_(NULL),
port_(0) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
pref_port_.Init(prefs::kRemoteDebuggingPort,
ChromecastConfig::GetInstance()->pref_service(),
base::Bind(&RemoteDebuggingServer::OnPortChanged,
base::Unretained(this)));
// Starts new dev tools, clearing port number saved in config.
// Remote debugging in production must be triggered only by config server.
pref_port_.SetValue(ShouldStartImmediately() ?
kDefaultRemoteDebuggingPort : 0);
OnPortChanged();
}
RemoteDebuggingServer::~RemoteDebuggingServer() {
pref_port_.SetValue(0);
OnPortChanged();
}
void RemoteDebuggingServer::OnPortChanged() {
int new_port = *pref_port_;
if (new_port < 0) {
new_port = 0;
}
VLOG(1) << "OnPortChanged called: old_port=" << port_
<< ", new_port=" << new_port;
if (new_port == port_) {
VLOG(1) << "Port has not been changed. Ignore silently.";
return;
}
if (devtools_http_handler_) {
LOG(INFO) << "Stop old devtools: port=" << port_;
devtools_http_handler_.reset();
}
port_ = new_port;
if (port_ > 0) {
devtools_http_handler_.reset(content::DevToolsHttpHandler::Start(
CreateSocketFactory(port_),
GetFrontendUrl(),
new CastDevToolsDelegate(),
base::FilePath()));
LOG(INFO) << "Devtools started: port=" << port_;
}
}
} // namespace shell
} // namespace chromecast
<commit_msg>Chromecast buildfix: scoped_ptr cannot be initialized with NULL.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/browser/devtools/remote_debugging_server.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/strings/stringprintf.h"
#include "chromecast/browser/devtools/cast_dev_tools_delegate.h"
#include "chromecast/common/chromecast_config.h"
#include "chromecast/common/pref_names.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/user_agent.h"
#include "net/socket/tcp_server_socket.h"
#if defined(OS_ANDROID)
#include "content/public/browser/android/devtools_auth.h"
#include "net/socket/unix_domain_server_socket_posix.h"
#endif // defined(OS_ANDROID)
namespace chromecast {
namespace shell {
namespace {
const char kFrontEndURL[] =
"https://chrome-devtools-frontend.appspot.com/serve_rev/%s/devtools.html";
const int kDefaultRemoteDebuggingPort = 9222;
#if defined(OS_ANDROID)
class UnixDomainServerSocketFactory
: public content::DevToolsHttpHandler::ServerSocketFactory {
public:
explicit UnixDomainServerSocketFactory(const std::string& socket_name)
: content::DevToolsHttpHandler::ServerSocketFactory(socket_name, 0, 1) {}
private:
// content::DevToolsHttpHandler::ServerSocketFactory.
virtual scoped_ptr<net::ServerSocket> Create() const override {
return scoped_ptr<net::ServerSocket>(
new net::UnixDomainServerSocket(
base::Bind(&content::CanUserConnectToDevTools),
true /* use_abstract_namespace */));
}
DISALLOW_COPY_AND_ASSIGN(UnixDomainServerSocketFactory);
};
#else
class TCPServerSocketFactory
: public content::DevToolsHttpHandler::ServerSocketFactory {
public:
TCPServerSocketFactory(const std::string& address, int port, int backlog)
: content::DevToolsHttpHandler::ServerSocketFactory(
address, port, backlog) {}
private:
// content::DevToolsHttpHandler::ServerSocketFactory.
virtual scoped_ptr<net::ServerSocket> Create() const override {
return scoped_ptr<net::ServerSocket>(
new net::TCPServerSocket(NULL, net::NetLog::Source()));
}
DISALLOW_COPY_AND_ASSIGN(TCPServerSocketFactory);
};
#endif
scoped_ptr<content::DevToolsHttpHandler::ServerSocketFactory>
CreateSocketFactory(int port) {
#if defined(OS_ANDROID)
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
std::string socket_name = "cast_shell_devtools_remote";
if (command_line->HasSwitch(switches::kRemoteDebuggingSocketName)) {
socket_name = command_line->GetSwitchValueASCII(
switches::kRemoteDebuggingSocketName);
}
return scoped_ptr<content::DevToolsHttpHandler::ServerSocketFactory>(
new UnixDomainServerSocketFactory(socket_name));
#else
return scoped_ptr<content::DevToolsHttpHandler::ServerSocketFactory>(
new TCPServerSocketFactory("0.0.0.0", port, 1));
#endif
}
std::string GetFrontendUrl() {
return base::StringPrintf(kFrontEndURL, content::GetWebKitRevision().c_str());
}
} // namespace
RemoteDebuggingServer::RemoteDebuggingServer() : port_(0) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
pref_port_.Init(prefs::kRemoteDebuggingPort,
ChromecastConfig::GetInstance()->pref_service(),
base::Bind(&RemoteDebuggingServer::OnPortChanged,
base::Unretained(this)));
// Starts new dev tools, clearing port number saved in config.
// Remote debugging in production must be triggered only by config server.
pref_port_.SetValue(ShouldStartImmediately() ?
kDefaultRemoteDebuggingPort : 0);
OnPortChanged();
}
RemoteDebuggingServer::~RemoteDebuggingServer() {
pref_port_.SetValue(0);
OnPortChanged();
}
void RemoteDebuggingServer::OnPortChanged() {
int new_port = *pref_port_;
if (new_port < 0) {
new_port = 0;
}
VLOG(1) << "OnPortChanged called: old_port=" << port_
<< ", new_port=" << new_port;
if (new_port == port_) {
VLOG(1) << "Port has not been changed. Ignore silently.";
return;
}
if (devtools_http_handler_) {
LOG(INFO) << "Stop old devtools: port=" << port_;
devtools_http_handler_.reset();
}
port_ = new_port;
if (port_ > 0) {
devtools_http_handler_.reset(content::DevToolsHttpHandler::Start(
CreateSocketFactory(port_),
GetFrontendUrl(),
new CastDevToolsDelegate(),
base::FilePath()));
LOG(INFO) << "Devtools started: port=" << port_;
}
}
} // namespace shell
} // namespace chromecast
<|endoftext|> |
<commit_before>#ifndef WF_SAFE_LIST_HPP
#define WF_SAFE_LIST_HPP
#include <list>
#include <memory>
#include <algorithm>
#include <functional>
#include <wayland-server.h>
#include "reverse.hpp"
/* This is a trimmed-down wrapper of std::list<T>.
*
* It supports safe iteration over all elements in the collection, where any
* element can be deleted from the list at any given time (i.e even in a
* for-each-like loop) */
namespace wf
{
/* The object type depends on the safe list type, and the safe list type
* needs access to the event loop. However, the event loop is typically
* available from core.hpp. Because we can't resolve this circular dependency,
* we provide a link to the event loop specially for the safe list */
namespace _safe_list_detail
{
/* In main.cpp, and initialized there */
extern wl_event_loop* event_loop;
void idle_cleanup_func(void *data);
}
template<class T>
class safe_list_t
{
std::list<std::unique_ptr<T>> list;
wl_event_source *idle_cleanup_source = NULL;
/* Remove all invalidated elements in the list */
std::function<void()> do_cleanup = [&] ()
{
auto it = list.begin();
while (it != list.end())
{
if (*it) {
++it;
} else {
it = list.erase(it);
}
}
idle_cleanup_source = NULL;
};
/* Return whether the list has invalidated elements */
bool is_dirty() const
{
return idle_cleanup_source;
}
public:
safe_list_t() {};
/* Copy the not-erased elements from other, but do not copy the idle source */
safe_list_t(const safe_list_t& other) { *this = other; }
safe_list_t& operator = (const safe_list_t& other)
{
this->idle_cleanup_source = NULL;
other.for_each([&] (auto& el) {
this->push_back(el);
});
}
safe_list_t(safe_list_t&& other) = default;
safe_list_t& operator = (safe_list_t&& other) = default;
~safe_list_t()
{
if (idle_cleanup_source)
wl_event_source_remove(idle_cleanup_source);
}
T& back()
{
/* No invalidated elements */
if (!is_dirty())
return *list.back();
auto it = list.rbegin();
while (it != list.rend() && (*it) == nullptr)
++it;
if (it == list.rend())
throw std::out_of_range("back() called on an empty list!");
return **it;
}
size_t size() const
{
if (!is_dirty())
return list.size();
/* Count non-null elements, because that's the real size */
size_t sz = 0;
for (auto& it : list)
sz += (it != nullptr);
return sz;
}
/* Push back by copying */
void push_back(T value)
{
list.push_back(std::make_unique<T> (std::move(value)));
}
/* Push back by moving */
void emplace_back(T&& value)
{
list.push_back(std::make_unique<T> (value));
}
enum insert_place_t
{
INSERT_BEFORE,
INSERT_AFTER,
INSERT_NONE,
};
/* Insert the given value at a position in the list, determined by the
* check function. The value is inserted at the first position that
* check indicates, or at the end of the list otherwise */
void emplace_at(T&& value, std::function<insert_place_t(T&)> check)
{
auto it = list.begin();
while (it != list.end())
{
/* Skip empty elements */
if (*it == nullptr)
{
++it;
continue;
}
auto place = check(**it);
switch (place)
{
case INSERT_AFTER:
/* We can safely increment it, because it points to an
* element in the list */
++it;
// fall through
case INSERT_BEFORE:
list.emplace(it, std::make_unique<T>(value));
return;
default:
break;
}
++it;
}
/* If no place found, insert at the end */
emplace_back(std::move(value));
}
void insert_at(T value, std::function<insert_place_t(T&)> check)
{
emplace_at(std::move(value), check);
}
/* Call func for each non-erased element of the list */
void for_each(std::function<void(T&)> func) const
{
for (auto& el : list)
{
/* The for-each loop here is safe, because no elements will be
* erased util the event loop goes idle */
if (el)
func(*el);
}
}
/* Call func for each non-erased element of the list in reversed order */
void for_each_reverse(std::function<void(T&)> func) const
{
for (auto& el : wf::reverse(list))
{
/* The loop here is safe, because no elements will be erased
* util the event loop goes idle */
if (el)
func(*el);
}
}
/* Safely remove all elements equal to value */
void remove_all(const T& value)
{
remove_if([=] (const T& el) { return el == value; });
}
/* Remove all elements satisfying a given condition.
* This function resets their pointers and scheduling a cleanup operation */
void remove_if(std::function<bool(const T&)> predicate)
{
bool actually_removed = false;
for (auto& it : list)
{
if (it && predicate(*it))
{
actually_removed = true;
/* First reset the element in the list, and then free resources */
auto copy = std::move(it);
it = nullptr;
/* Now copy goes out of scope */
}
}
/* Schedule a clean-up, but be careful to not schedule it twice */
if (!idle_cleanup_source && actually_removed)
{
idle_cleanup_source = wl_event_loop_add_idle(_safe_list_detail::event_loop,
_safe_list_detail::idle_cleanup_func, &do_cleanup);
}
}
};
}
#endif /* end of include guard: WF_SAFE_LIST_HPP */
<commit_msg>safe-list: iterate only on already-available elements in for_each<commit_after>#ifndef WF_SAFE_LIST_HPP
#define WF_SAFE_LIST_HPP
#include <list>
#include <memory>
#include <algorithm>
#include <functional>
#include <wayland-server.h>
#include "reverse.hpp"
/* This is a trimmed-down wrapper of std::list<T>.
*
* It supports safe iteration over all elements in the collection, where any
* element can be deleted from the list at any given time (i.e even in a
* for-each-like loop) */
namespace wf
{
/* The object type depends on the safe list type, and the safe list type
* needs access to the event loop. However, the event loop is typically
* available from core.hpp. Because we can't resolve this circular dependency,
* we provide a link to the event loop specially for the safe list */
namespace _safe_list_detail
{
/* In main.cpp, and initialized there */
extern wl_event_loop* event_loop;
void idle_cleanup_func(void *data);
}
template<class T>
class safe_list_t
{
std::list<std::unique_ptr<T>> list;
wl_event_source *idle_cleanup_source = NULL;
/* Remove all invalidated elements in the list */
std::function<void()> do_cleanup = [&] ()
{
auto it = list.begin();
while (it != list.end())
{
if (*it) {
++it;
} else {
it = list.erase(it);
}
}
idle_cleanup_source = NULL;
};
/* Return whether the list has invalidated elements */
bool is_dirty() const
{
return idle_cleanup_source;
}
public:
safe_list_t() {};
/* Copy the not-erased elements from other, but do not copy the idle source */
safe_list_t(const safe_list_t& other) { *this = other; }
safe_list_t& operator = (const safe_list_t& other)
{
this->idle_cleanup_source = NULL;
other.for_each([&] (auto& el) {
this->push_back(el);
});
}
safe_list_t(safe_list_t&& other) = default;
safe_list_t& operator = (safe_list_t&& other) = default;
~safe_list_t()
{
if (idle_cleanup_source)
wl_event_source_remove(idle_cleanup_source);
}
T& back()
{
/* No invalidated elements */
if (!is_dirty())
return *list.back();
auto it = list.rbegin();
while (it != list.rend() && (*it) == nullptr)
++it;
if (it == list.rend())
throw std::out_of_range("back() called on an empty list!");
return **it;
}
size_t size() const
{
if (!is_dirty())
return list.size();
/* Count non-null elements, because that's the real size */
size_t sz = 0;
for (auto& it : list)
sz += (it != nullptr);
return sz;
}
/* Push back by copying */
void push_back(T value)
{
list.push_back(std::make_unique<T> (std::move(value)));
}
/* Push back by moving */
void emplace_back(T&& value)
{
list.push_back(std::make_unique<T> (value));
}
enum insert_place_t
{
INSERT_BEFORE,
INSERT_AFTER,
INSERT_NONE,
};
/* Insert the given value at a position in the list, determined by the
* check function. The value is inserted at the first position that
* check indicates, or at the end of the list otherwise */
void emplace_at(T&& value, std::function<insert_place_t(T&)> check)
{
auto it = list.begin();
while (it != list.end())
{
/* Skip empty elements */
if (*it == nullptr)
{
++it;
continue;
}
auto place = check(**it);
switch (place)
{
case INSERT_AFTER:
/* We can safely increment it, because it points to an
* element in the list */
++it;
// fall through
case INSERT_BEFORE:
list.emplace(it, std::make_unique<T>(value));
return;
default:
break;
}
++it;
}
/* If no place found, insert at the end */
emplace_back(std::move(value));
}
void insert_at(T value, std::function<insert_place_t(T&)> check)
{
emplace_at(std::move(value), check);
}
/* Call func for each non-erased element of the list */
void for_each(std::function<void(T&)> func) const
{
/* Go through all elements currently in the list */
auto it = list.begin();
for (int size = list.size(); size > 0; size--, it++)
{
if (*it)
func(**it);
}
}
/* Call func for each non-erased element of the list in reversed order */
void for_each_reverse(std::function<void(T&)> func) const
{
auto it = list.rbegin();
for (int size = list.size(); size > 0; size--, it++)
{
if (*it)
func(**it);
}
}
/* Safely remove all elements equal to value */
void remove_all(const T& value)
{
remove_if([=] (const T& el) { return el == value; });
}
/* Remove all elements satisfying a given condition.
* This function resets their pointers and scheduling a cleanup operation */
void remove_if(std::function<bool(const T&)> predicate)
{
bool actually_removed = false;
for (auto& it : list)
{
if (it && predicate(*it))
{
actually_removed = true;
/* First reset the element in the list, and then free resources */
auto copy = std::move(it);
it = nullptr;
/* Now copy goes out of scope */
}
}
/* Schedule a clean-up, but be careful to not schedule it twice */
if (!idle_cleanup_source && actually_removed)
{
idle_cleanup_source = wl_event_loop_add_idle(_safe_list_detail::event_loop,
_safe_list_detail::idle_cleanup_func, &do_cleanup);
}
}
};
}
#endif /* end of include guard: WF_SAFE_LIST_HPP */
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <openssl/ssl.h>
#include <fcntl.h>
#include <unistd.h>
#include <fstream>
#include "gtest/gtest.h"
#include "security_manager/crypto_manager.h"
#include "security_manager/crypto_manager_impl.h"
#include "security_manager/ssl_context.h"
#include "utils/custom_string.h"
#ifdef __QNXNTO__
#define FORD_CIPHER SSL3_TXT_RSA_DES_192_CBC3_SHA
#else
// Used cipher from ford protocol requirement
#define FORD_CIPHER TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384
#endif
#define ALL_CIPHERS "ALL"
namespace {
const size_t updates_before_hour = 24;
}
namespace test {
namespace components {
namespace ssl_context_test {
namespace custom_str = utils::custom_string;
class SSLTest : public testing::Test {
protected:
static void SetUpTestCase() {
std::ifstream file("server/spt_credential.p12.enc");
std::stringstream ss;
ss << file.rdbuf();
file.close();
crypto_manager = new security_manager::CryptoManagerImpl();
const bool crypto_manager_initialization = crypto_manager->Init(
security_manager::SERVER, security_manager::TLSv1_2, ss.str(),
FORD_CIPHER, false, "", updates_before_hour);
EXPECT_TRUE(crypto_manager_initialization);
client_manager = new security_manager::CryptoManagerImpl();
const bool client_manager_initialization = client_manager->Init(
security_manager::CLIENT, security_manager::TLSv1_2, "", FORD_CIPHER,
false, "", updates_before_hour);
EXPECT_TRUE(client_manager_initialization);
}
static void TearDownTestCase() {
delete crypto_manager;
delete client_manager;
}
virtual void SetUp() {
server_ctx = crypto_manager->CreateSSLContext();
client_ctx = client_manager->CreateSSLContext();
security_manager::SSLContext::HandshakeContext ctx;
ctx.make_context("SPT", "client");
server_ctx->SetHandshakeContext(ctx);
ctx.expected_cn = "server";
client_ctx->SetHandshakeContext(ctx);
}
virtual void TearDown() {
crypto_manager->ReleaseSSLContext(server_ctx);
client_manager->ReleaseSSLContext(client_ctx);
}
static security_manager::CryptoManager* crypto_manager;
static security_manager::CryptoManager* client_manager;
security_manager::SSLContext* server_ctx;
security_manager::SSLContext* client_ctx;
};
security_manager::CryptoManager* SSLTest::crypto_manager;
security_manager::CryptoManager* SSLTest::client_manager;
// TODO(EZAMAKHOV): Split to SSL/TLS1/TLS1_1/TLS1_2 tests
TEST_F(SSLTest, BrokenHandshake) {
const uint8_t* server_buf;
const uint8_t* client_buf;
size_t server_buf_len;
size_t client_buf_len;
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
client_ctx->StartHandshake(&client_buf, &client_buf_len));
ASSERT_FALSE(client_buf == NULL);
ASSERT_GT(client_buf_len, 0u);
// Broke 3 bytes for get abnormal fail of handshake
const_cast<uint8_t*>(client_buf)[0] ^= 0xFF;
const_cast<uint8_t*>(client_buf)[client_buf_len / 2] ^= 0xFF;
const_cast<uint8_t*>(client_buf)[client_buf_len - 1] ^= 0xFF;
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_AbnormalFail,
server_ctx->DoHandshakeStep(client_buf, client_buf_len, &server_buf,
&server_buf_len));
}
TEST_F(SSLTest, Positive) {
const uint8_t* server_buf;
const uint8_t* client_buf;
size_t server_buf_len;
size_t client_buf_len;
ASSERT_EQ(client_ctx->StartHandshake(&client_buf, &client_buf_len),
security_manager::SSLContext::Handshake_Result_Success);
ASSERT_FALSE(client_buf == NULL);
ASSERT_GT(client_buf_len, 0u);
for (;;) {
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
server_ctx->DoHandshakeStep(client_buf, client_buf_len,
&server_buf, &server_buf_len));
ASSERT_FALSE(server_buf == NULL);
ASSERT_GT(server_buf_len, 0u);
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
client_ctx->DoHandshakeStep(server_buf, server_buf_len,
&client_buf, &client_buf_len));
if (server_ctx->IsInitCompleted()) {
break;
}
ASSERT_FALSE(client_buf == NULL);
ASSERT_GT(client_buf_len, 0u);
}
// Expect empty buffers after init complete
ASSERT_TRUE(client_buf == NULL);
ASSERT_EQ(client_buf_len, 0u);
// expect both side initialization complete
EXPECT_TRUE(client_ctx->IsInitCompleted());
EXPECT_TRUE(server_ctx->IsInitCompleted());
// Encrypt text on client side
const uint8_t* text = reinterpret_cast<const uint8_t*>("abra");
const uint8_t* encrypted_text = 0;
size_t text_len = 4;
size_t encrypted_text_len;
EXPECT_TRUE(client_ctx->Encrypt(text, text_len, &encrypted_text,
&encrypted_text_len));
ASSERT_NE(encrypted_text, reinterpret_cast<void*>(NULL));
ASSERT_GT(encrypted_text_len, 0u);
// Decrypt text on server side
EXPECT_TRUE(server_ctx->Decrypt(encrypted_text, encrypted_text_len, &text,
&text_len));
ASSERT_NE(text, reinterpret_cast<void*>(NULL));
ASSERT_GT(text_len, 0u);
ASSERT_EQ(strncmp(reinterpret_cast<const char*>(text), "abra", 4), 0);
}
TEST_F(SSLTest, EcncryptionFail) {
const uint8_t* server_buf;
const uint8_t* client_buf;
size_t server_buf_len;
size_t client_buf_len;
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
client_ctx->StartHandshake(&client_buf, &client_buf_len));
while (!server_ctx->IsInitCompleted()) {
ASSERT_FALSE(client_buf == NULL);
ASSERT_GT(client_buf_len, 0u);
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
server_ctx->DoHandshakeStep(client_buf, client_buf_len,
&server_buf, &server_buf_len));
ASSERT_FALSE(server_buf == NULL);
ASSERT_GT(server_buf_len, 0u);
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
client_ctx->DoHandshakeStep(server_buf, server_buf_len,
&client_buf, &client_buf_len));
}
// expect empty buffers after init complete
ASSERT_TRUE(client_buf == NULL);
ASSERT_EQ(client_buf_len, 0u);
// expect both side initialization complete
EXPECT_TRUE(client_ctx->IsInitCompleted());
EXPECT_TRUE(server_ctx->IsInitCompleted());
// Encrypt text on client side
const uint8_t* text = reinterpret_cast<const uint8_t*>("abra");
const uint8_t* encrypted_text = 0;
size_t text_len = 4;
size_t encrypted_text_len;
EXPECT_TRUE(client_ctx->Encrypt(text, text_len, &encrypted_text,
&encrypted_text_len));
ASSERT_NE(encrypted_text, reinterpret_cast<void*>(NULL));
ASSERT_GT(encrypted_text_len, 0u);
std::vector<uint8_t> broken(encrypted_text,
encrypted_text + encrypted_text_len);
// Broke message
broken[encrypted_text_len / 2] ^= 0xFF;
const uint8_t* out_text;
size_t out_text_size;
// Decrypt broken text on server side
EXPECT_FALSE(server_ctx->Decrypt(&broken[0], broken.size(), &out_text,
&out_text_size));
// Check after broken message that server encryption and decryption fail
// Encrypte message on server side
EXPECT_FALSE(server_ctx->Decrypt(encrypted_text, encrypted_text_len,
&out_text, &out_text_size));
EXPECT_FALSE(server_ctx->Encrypt(text, text_len, &encrypted_text,
&encrypted_text_len));
}
} // namespace ssl_context_test
} // namespace components
} // namespace test
<commit_msg>Add macro OVERRIDE for virtual methods<commit_after>/*
* Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <openssl/ssl.h>
#include <fcntl.h>
#include <unistd.h>
#include <fstream>
#include "gtest/gtest.h"
#include "security_manager/crypto_manager.h"
#include "security_manager/crypto_manager_impl.h"
#include "security_manager/ssl_context.h"
#include "utils/custom_string.h"
#ifdef __QNXNTO__
#define FORD_CIPHER SSL3_TXT_RSA_DES_192_CBC3_SHA
#else
// Used cipher from ford protocol requirement
#define FORD_CIPHER TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384
#endif
#define ALL_CIPHERS "ALL"
namespace {
const size_t updates_before_hour = 24;
}
namespace test {
namespace components {
namespace ssl_context_test {
namespace custom_str = utils::custom_string;
class SSLTest : public testing::Test {
protected:
static void SetUpTestCase() {
std::ifstream file("server/spt_credential.p12.enc");
std::stringstream ss;
ss << file.rdbuf();
file.close();
crypto_manager = new security_manager::CryptoManagerImpl();
const bool crypto_manager_initialization = crypto_manager->Init(
security_manager::SERVER, security_manager::TLSv1_2, ss.str(),
FORD_CIPHER, false, "", updates_before_hour);
EXPECT_TRUE(crypto_manager_initialization);
client_manager = new security_manager::CryptoManagerImpl();
const bool client_manager_initialization = client_manager->Init(
security_manager::CLIENT, security_manager::TLSv1_2, "", FORD_CIPHER,
false, "", updates_before_hour);
EXPECT_TRUE(client_manager_initialization);
}
static void TearDownTestCase() {
delete crypto_manager;
delete client_manager;
}
virtual void SetUp() OVERRIDE {
server_ctx = crypto_manager->CreateSSLContext();
client_ctx = client_manager->CreateSSLContext();
security_manager::SSLContext::HandshakeContext ctx;
ctx.make_context("SPT", "client");
server_ctx->SetHandshakeContext(ctx);
ctx.expected_cn = "server";
client_ctx->SetHandshakeContext(ctx);
}
virtual void TearDown() OVERRIDE {
crypto_manager->ReleaseSSLContext(server_ctx);
client_manager->ReleaseSSLContext(client_ctx);
}
static security_manager::CryptoManager* crypto_manager;
static security_manager::CryptoManager* client_manager;
security_manager::SSLContext* server_ctx;
security_manager::SSLContext* client_ctx;
};
security_manager::CryptoManager* SSLTest::crypto_manager;
security_manager::CryptoManager* SSLTest::client_manager;
// TODO(EZAMAKHOV): Split to SSL/TLS1/TLS1_1/TLS1_2 tests
TEST_F(SSLTest, BrokenHandshake) {
const uint8_t* server_buf;
const uint8_t* client_buf;
size_t server_buf_len;
size_t client_buf_len;
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
client_ctx->StartHandshake(&client_buf, &client_buf_len));
ASSERT_FALSE(client_buf == NULL);
ASSERT_GT(client_buf_len, 0u);
// Broke 3 bytes for get abnormal fail of handshake
const_cast<uint8_t*>(client_buf)[0] ^= 0xFF;
const_cast<uint8_t*>(client_buf)[client_buf_len / 2] ^= 0xFF;
const_cast<uint8_t*>(client_buf)[client_buf_len - 1] ^= 0xFF;
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_AbnormalFail,
server_ctx->DoHandshakeStep(client_buf, client_buf_len, &server_buf,
&server_buf_len));
}
TEST_F(SSLTest, Positive) {
const uint8_t* server_buf;
const uint8_t* client_buf;
size_t server_buf_len;
size_t client_buf_len;
ASSERT_EQ(client_ctx->StartHandshake(&client_buf, &client_buf_len),
security_manager::SSLContext::Handshake_Result_Success);
ASSERT_FALSE(client_buf == NULL);
ASSERT_GT(client_buf_len, 0u);
for (;;) {
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
server_ctx->DoHandshakeStep(client_buf, client_buf_len,
&server_buf, &server_buf_len));
ASSERT_FALSE(server_buf == NULL);
ASSERT_GT(server_buf_len, 0u);
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
client_ctx->DoHandshakeStep(server_buf, server_buf_len,
&client_buf, &client_buf_len));
if (server_ctx->IsInitCompleted()) {
break;
}
ASSERT_FALSE(client_buf == NULL);
ASSERT_GT(client_buf_len, 0u);
}
// Expect empty buffers after init complete
ASSERT_TRUE(client_buf == NULL);
ASSERT_EQ(client_buf_len, 0u);
// expect both side initialization complete
EXPECT_TRUE(client_ctx->IsInitCompleted());
EXPECT_TRUE(server_ctx->IsInitCompleted());
// Encrypt text on client side
const uint8_t* text = reinterpret_cast<const uint8_t*>("abra");
const uint8_t* encrypted_text = 0;
size_t text_len = 4;
size_t encrypted_text_len;
EXPECT_TRUE(client_ctx->Encrypt(text, text_len, &encrypted_text,
&encrypted_text_len));
ASSERT_NE(encrypted_text, reinterpret_cast<void*>(NULL));
ASSERT_GT(encrypted_text_len, 0u);
// Decrypt text on server side
EXPECT_TRUE(server_ctx->Decrypt(encrypted_text, encrypted_text_len, &text,
&text_len));
ASSERT_NE(text, reinterpret_cast<void*>(NULL));
ASSERT_GT(text_len, 0u);
ASSERT_EQ(strncmp(reinterpret_cast<const char*>(text), "abra", 4), 0);
}
TEST_F(SSLTest, EcncryptionFail) {
const uint8_t* server_buf;
const uint8_t* client_buf;
size_t server_buf_len;
size_t client_buf_len;
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
client_ctx->StartHandshake(&client_buf, &client_buf_len));
while (!server_ctx->IsInitCompleted()) {
ASSERT_FALSE(client_buf == NULL);
ASSERT_GT(client_buf_len, 0u);
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
server_ctx->DoHandshakeStep(client_buf, client_buf_len,
&server_buf, &server_buf_len));
ASSERT_FALSE(server_buf == NULL);
ASSERT_GT(server_buf_len, 0u);
ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
client_ctx->DoHandshakeStep(server_buf, server_buf_len,
&client_buf, &client_buf_len));
}
// expect empty buffers after init complete
ASSERT_TRUE(client_buf == NULL);
ASSERT_EQ(client_buf_len, 0u);
// expect both side initialization complete
EXPECT_TRUE(client_ctx->IsInitCompleted());
EXPECT_TRUE(server_ctx->IsInitCompleted());
// Encrypt text on client side
const uint8_t* text = reinterpret_cast<const uint8_t*>("abra");
const uint8_t* encrypted_text = 0;
size_t text_len = 4;
size_t encrypted_text_len;
EXPECT_TRUE(client_ctx->Encrypt(text, text_len, &encrypted_text,
&encrypted_text_len));
ASSERT_NE(encrypted_text, reinterpret_cast<void*>(NULL));
ASSERT_GT(encrypted_text_len, 0u);
std::vector<uint8_t> broken(encrypted_text,
encrypted_text + encrypted_text_len);
// Broke message
broken[encrypted_text_len / 2] ^= 0xFF;
const uint8_t* out_text;
size_t out_text_size;
// Decrypt broken text on server side
EXPECT_FALSE(server_ctx->Decrypt(&broken[0], broken.size(), &out_text,
&out_text_size));
// Check after broken message that server encryption and decryption fail
// Encrypte message on server side
EXPECT_FALSE(server_ctx->Decrypt(encrypted_text, encrypted_text_len,
&out_text, &out_text_size));
EXPECT_FALSE(server_ctx->Encrypt(text, text_len, &encrypted_text,
&encrypted_text_len));
}
} // namespace ssl_context_test
} // namespace components
} // namespace test
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/gpu/GrContext.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrContextThreadSafeProxyPriv.h"
#include "src/gpu/GrSkSLFPFactoryCache.h"
/**
* The DDL Context is the one in effect during DDL Recording. It isn't backed by a GrGPU and
* cannot allocate any GPU resources.
*/
class GrDDLContext : public GrContext {
public:
GrDDLContext(sk_sp<GrContextThreadSafeProxy> proxy)
: INHERITED(proxy->backend(), proxy->priv().options(), proxy->priv().contextID()) {
fThreadSafeProxy = std::move(proxy);
}
~GrDDLContext() final { }
void abandonContext() final {
SkASSERT(0); // abandoning in a DDL Recorder doesn't make a whole lot of sense
INHERITED::abandonContext();
}
void releaseResourcesAndAbandonContext() final {
SkASSERT(0); // abandoning in a DDL Recorder doesn't make a whole lot of sense
INHERITED::releaseResourcesAndAbandonContext();
}
void freeGpuResources() final {
SkASSERT(0); // freeing resources in a DDL Recorder doesn't make a whole lot of sense
INHERITED::freeGpuResources();
}
private:
// TODO: Here we're pretending this isn't derived from GrContext. Switch this to be derived from
// GrRecordingContext!
GrContext* asDirectContext() final { return nullptr; }
bool init(sk_sp<const GrCaps> caps, sk_sp<GrSkSLFPFactoryCache> FPFactoryCache) final {
SkASSERT(caps && FPFactoryCache);
SkASSERT(fThreadSafeProxy); // should've been set in the ctor
if (!INHERITED::init(std::move(caps), std::move(FPFactoryCache))) {
return false;
}
// DDL contexts/drawing managers always sort the oplists and attempt to reduce opsTask
// splitting.
this->setupDrawingManager(true, true);
SkASSERT(this->caps());
return true;
}
GrAtlasManager* onGetAtlasManager() final {
SkASSERT(0); // the DDL Recorders should never invoke this
return nullptr;
}
typedef GrContext INHERITED;
};
sk_sp<GrContext> GrContextPriv::MakeDDL(const sk_sp<GrContextThreadSafeProxy>& proxy) {
sk_sp<GrContext> context(new GrDDLContext(proxy));
if (!context->init(proxy->priv().refCaps(), proxy->priv().fpFactoryCache())) {
return nullptr;
}
return context;
}
<commit_msg>Fix warning in Fuchsia build<commit_after>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/gpu/GrContext.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrContextThreadSafeProxyPriv.h"
#include "src/gpu/GrSkSLFPFactoryCache.h"
/**
* The DDL Context is the one in effect during DDL Recording. It isn't backed by a GrGPU and
* cannot allocate any GPU resources.
*/
class GrDDLContext final : public GrContext {
public:
GrDDLContext(sk_sp<GrContextThreadSafeProxy> proxy)
: INHERITED(proxy->backend(), proxy->priv().options(), proxy->priv().contextID()) {
fThreadSafeProxy = std::move(proxy);
}
~GrDDLContext() final { }
void abandonContext() final {
SkASSERT(0); // abandoning in a DDL Recorder doesn't make a whole lot of sense
INHERITED::abandonContext();
}
void releaseResourcesAndAbandonContext() final {
SkASSERT(0); // abandoning in a DDL Recorder doesn't make a whole lot of sense
INHERITED::releaseResourcesAndAbandonContext();
}
void freeGpuResources() final {
SkASSERT(0); // freeing resources in a DDL Recorder doesn't make a whole lot of sense
INHERITED::freeGpuResources();
}
private:
// TODO: Here we're pretending this isn't derived from GrContext. Switch this to be derived from
// GrRecordingContext!
GrContext* asDirectContext() final { return nullptr; }
bool init(sk_sp<const GrCaps> caps, sk_sp<GrSkSLFPFactoryCache> FPFactoryCache) final {
SkASSERT(caps && FPFactoryCache);
SkASSERT(fThreadSafeProxy); // should've been set in the ctor
if (!INHERITED::init(std::move(caps), std::move(FPFactoryCache))) {
return false;
}
// DDL contexts/drawing managers always sort the oplists and attempt to reduce opsTask
// splitting.
this->setupDrawingManager(true, true);
SkASSERT(this->caps());
return true;
}
GrAtlasManager* onGetAtlasManager() final {
SkASSERT(0); // the DDL Recorders should never invoke this
return nullptr;
}
typedef GrContext INHERITED;
};
sk_sp<GrContext> GrContextPriv::MakeDDL(const sk_sp<GrContextThreadSafeProxy>& proxy) {
sk_sp<GrContext> context(new GrDDLContext(proxy));
if (!context->init(proxy->priv().refCaps(), proxy->priv().fpFactoryCache())) {
return nullptr;
}
return context;
}
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of DO-CV, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2021-present David Ok <[email protected]>
//
// 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 <DO/Shakti/Cuda/VideoIO/VideoStream.hpp>
#include "nvidia-video-codec-sdk-9.1.23/NvCodec/NvDecoder/NvDecoder.h"
#include "nvidia-video-codec-sdk-9.1.23/Utils/ColorSpace.h"
#include "nvidia-video-codec-sdk-9.1.23/Utils/FFmpegDemuxer.h"
#include "nvidia-video-codec-sdk-9.1.23/Utils/NvCodecUtils.h"
namespace DriverApi {
auto init() -> void
{
ck(cuInit(0));
}
auto get_device_count() -> int
{
auto num_gpus = 0;
ck(cuDeviceGetCount(&num_gpus));
return num_gpus;
}
CudaContext::CudaContext(int gpu_id_)
: gpu_id{gpu_id_}
{
ck(cuDeviceGet(&cuda_device, gpu_id));
std::array<char, 80> device_name;
ck(cuDeviceGetName(device_name.data(), device_name.size(), cuda_device));
std::cout << "GPU in use: " << device_name.data() << std::endl;
ck(cuCtxCreate(&cuda_context, CU_CTX_BLOCKING_SYNC, cuda_device));
}
CudaContext::CudaContext(CudaContext&& other)
{
std::swap(gpu_id, other.gpu_id);
std::swap(cuda_context, other.cuda_context);
std::swap(cuda_device, other.cuda_device);
}
CudaContext::~CudaContext()
{
if (cuda_context)
{
ck(cuCtxDestroy(cuda_context));
cuda_context = 0;
cuda_device = 0;
gpu_id = -1;
}
}
auto CudaContext::make_current() -> void
{
ck(cuCtxSetCurrent(cuda_context));
}
DeviceBgraBuffer::DeviceBgraBuffer(int width_, int height_)
: width{width_}
, height{height_}
{
ck(cuMemAlloc(&data, width * height * 4));
ck(cuMemsetD8(data, 0, width * height * 4));
}
DeviceBgraBuffer::~DeviceBgraBuffer()
{
if (data)
ck(cuMemFree(data));
}
auto
DeviceBgraBuffer::to_host(DO::Sara::ImageView<DO::Sara::Bgra8>& image) const
-> void
{
ck(cudaMemcpy(reinterpret_cast<void*>(image.data()),
reinterpret_cast<const void*>(data), width * height * 4,
cudaMemcpyDeviceToHost));
}
} // namespace DriverApi
simplelogger::Logger* logger =
simplelogger::LoggerFactory::CreateConsoleLogger();
namespace DO { namespace Shakti {
struct VideoStream::Impl
{
Impl(const std::string& video_filepath,
const DriverApi::CudaContext& context)
: demuxer{video_filepath.c_str()}
, decoder{context.cuda_context, true,
FFmpeg2NvCodecId(demuxer.GetVideoCodec())}
{
}
auto
read_decoded_frame_packet(DriverApi::DeviceBgraBuffer& bgra_frame_buffer)
-> void
{
// Launch CUDA kernels for colorspace conversion from raw video to raw
// image formats which OpenGL textures can work with
if (decoder.GetBitDepth() == 8)
{
if (decoder.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
YUV444ToColor32<BGRA32>(
(uint8_t*) raw_frame_packet[frame_index], decoder.GetWidth(),
(uint8_t*) bgra_frame_buffer.data, bgra_frame_buffer.width * 4,
decoder.GetWidth(), decoder.GetHeight());
else // default assumed NV12
Nv12ToColor32<BGRA32>(
(uint8_t*) raw_frame_packet[frame_index], decoder.GetWidth(),
(uint8_t*) bgra_frame_buffer.data, bgra_frame_buffer.width * 4,
decoder.GetWidth(), decoder.GetHeight());
}
else
{
if (decoder.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
YUV444P16ToColor32<BGRA32>(
(uint8_t*) raw_frame_packet[frame_index], 2 * decoder.GetWidth(),
(uint8_t*) bgra_frame_buffer.data, bgra_frame_buffer.width * 4,
decoder.GetWidth(), decoder.GetHeight());
else // default assumed P016
P016ToColor32<BGRA32>(
(uint8_t*) raw_frame_packet[frame_index], 2 * decoder.GetWidth(),
(uint8_t*) bgra_frame_buffer.data, bgra_frame_buffer.width * 4,
decoder.GetWidth(), decoder.GetHeight());
}
++frame_index;
if (frame_index == num_frames_decoded)
num_frames_decoded = frame_index = 0;
}
auto decode() -> bool
{
// Initialize the video stream.
do
{
if (not demuxer.Demux(&frame_data_compressed.data,
&frame_data_compressed.size))
return false;
decoder.Decode(frame_data_compressed.data, frame_data_compressed.size,
&raw_frame_packet, &num_frames_decoded);
} while (num_frames_decoded <= 0);
return true;
}
auto read(DriverApi::DeviceBgraBuffer& bgra_frame_buffer) -> bool
{
if (num_frames_decoded == 0 and !decode())
return false;
#ifdef DEBUG
LOG(INFO) << decoder.GetVideoInfo();
#endif
if (frame_index < num_frames_decoded)
read_decoded_frame_packet(bgra_frame_buffer);
return true;
}
mutable FFmpegDemuxer demuxer;
NvDecoder decoder;
std::uint8_t** raw_frame_packet{nullptr};
std::int32_t num_frames_decoded{};
std::int32_t frame_index{};
struct EncodedVideoBuffer
{
std::uint8_t* data{nullptr};
std::int32_t size{};
} frame_data_compressed;
};
auto VideoStream::ImplDeleter::operator()(const VideoStream::Impl* p) const
-> void
{
delete p;
}
VideoStream::VideoStream(const std::string& video_filepath,
const DriverApi::CudaContext& context)
: _impl{new VideoStream::Impl{video_filepath, context}}
{
}
auto VideoStream::width() const -> int
{
return _impl->demuxer.GetWidth();
}
auto VideoStream::height() const -> int
{
return _impl->demuxer.GetHeight();
}
auto VideoStream::decode() -> bool
{
return _impl->decode();
}
auto VideoStream::read(DriverApi::DeviceBgraBuffer& bgra_frame_buffer) -> bool
{
return _impl->read(bgra_frame_buffer);
}
}} // namespace DO::Shakti
static auto get_output_format_names(unsigned short output_format_mask,
char* OutputFormats) -> void
{
if (output_format_mask == 0)
{
strcpy(OutputFormats, "N/A");
return;
}
if (output_format_mask & (1U << cudaVideoSurfaceFormat_NV12))
strcat(OutputFormats, "NV12 ");
if (output_format_mask & (1U << cudaVideoSurfaceFormat_P016))
strcat(OutputFormats, "P016 ");
if (output_format_mask & (1U << cudaVideoSurfaceFormat_YUV444))
strcat(OutputFormats, "YUV444 ");
if (output_format_mask & (1U << cudaVideoSurfaceFormat_YUV444_16Bit))
strcat(OutputFormats, "YUV444P16 ");
}
auto show_decoder_capability() -> void
{
ck(cuInit(0));
int num_gpus = 0;
ck(cuDeviceGetCount(&num_gpus));
std::cout << "Decoder Capability" << std::endl << std::endl;
const char* codec_names[] = {
"JPEG", "MPEG1", "MPEG2", "MPEG4", "H264", "HEVC", "HEVC", "HEVC",
"HEVC", "HEVC", "HEVC", "VC1", "VP8", "VP9", "VP9", "VP9"};
const char* chroma_format_strings[] = {"4:0:0", "4:2:0", "4:2:2", "4:4:4"};
char output_formats[64];
cudaVideoCodec codecs[] = {
cudaVideoCodec_JPEG, cudaVideoCodec_MPEG1, cudaVideoCodec_MPEG2,
cudaVideoCodec_MPEG4, cudaVideoCodec_H264, cudaVideoCodec_HEVC,
cudaVideoCodec_HEVC, cudaVideoCodec_HEVC, cudaVideoCodec_HEVC,
cudaVideoCodec_HEVC, cudaVideoCodec_HEVC, cudaVideoCodec_VC1,
cudaVideoCodec_VP8, cudaVideoCodec_VP9, cudaVideoCodec_VP9,
cudaVideoCodec_VP9};
int bit_depth_minus_8[] = {0, 0, 0, 0, 0, 0, 2, 4, 0, 2, 4, 0, 0, 0, 2, 4};
cudaVideoChromaFormat chroma_formats[] = {
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_444, cudaVideoChromaFormat_444,
cudaVideoChromaFormat_444, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420};
for (int gpu_id = 0; gpu_id < num_gpus; ++gpu_id)
{
auto cuda_context = DriverApi::CudaContext{gpu_id};
for (auto i = 0u; i < sizeof(codecs) / sizeof(codecs[0]); ++i)
{
CUVIDDECODECAPS decode_caps = {};
decode_caps.eCodecType = codecs[i];
decode_caps.eChromaFormat = chroma_formats[i];
decode_caps.nBitDepthMinus8 = bit_depth_minus_8[i];
cuvidGetDecoderCaps(&decode_caps);
output_formats[0] = '\0';
get_output_format_names(decode_caps.nOutputFormatMask, output_formats);
// setw() width = maximum_width_of_string + 2 spaces
std::cout << "Codec " << std::left << std::setw(7) << codec_names[i]
<< "BitDepth " << std::setw(4)
<< decode_caps.nBitDepthMinus8 + 8 << "ChromaFormat "
<< std::setw(7)
<< chroma_format_strings[decode_caps.eChromaFormat]
<< "Supported " << std::setw(3)
<< (int) decode_caps.bIsSupported << "MaxWidth "
<< std::setw(7) << decode_caps.nMaxWidth << "MaxHeight "
<< std::setw(7) << decode_caps.nMaxHeight << "MaxMBCount "
<< std::setw(10) << decode_caps.nMaxMBCount << "MinWidth "
<< std::setw(5) << decode_caps.nMinWidth << "MinHeight "
<< std::setw(5) << decode_caps.nMinHeight << "SurfaceFormat "
<< std::setw(11) << output_formats << std::endl;
}
std::cout << std::endl;
}
}
<commit_msg>MAINT: fix compile error.<commit_after>// ========================================================================== //
// This file is part of DO-CV, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2021-present David Ok <[email protected]>
//
// 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 <DO/Shakti/Cuda/VideoIO/VideoStream.hpp>
#include "nvidia-video-codec-sdk-9.1.23/NvCodec/NvDecoder/NvDecoder.h"
#include "nvidia-video-codec-sdk-9.1.23/Utils/ColorSpace.h"
#include "nvidia-video-codec-sdk-9.1.23/Utils/FFmpegDemuxer.h"
#include "nvidia-video-codec-sdk-9.1.23/Utils/NvCodecUtils.h"
#include <array>
namespace DriverApi {
auto init() -> void
{
ck(cuInit(0));
}
auto get_device_count() -> int
{
auto num_gpus = 0;
ck(cuDeviceGetCount(&num_gpus));
return num_gpus;
}
CudaContext::CudaContext(int gpu_id_)
: gpu_id{gpu_id_}
{
ck(cuDeviceGet(&cuda_device, gpu_id));
std::array<char, 80> device_name;
ck(cuDeviceGetName(device_name.data(), static_cast<int>(device_name.size()),
cuda_device));
std::cout << "GPU in use: " << device_name.data() << std::endl;
ck(cuCtxCreate(&cuda_context, CU_CTX_BLOCKING_SYNC, cuda_device));
}
CudaContext::CudaContext(CudaContext&& other)
{
std::swap(gpu_id, other.gpu_id);
std::swap(cuda_context, other.cuda_context);
std::swap(cuda_device, other.cuda_device);
}
CudaContext::~CudaContext()
{
if (cuda_context)
{
ck(cuCtxDestroy(cuda_context));
cuda_context = 0;
cuda_device = 0;
gpu_id = -1;
}
}
auto CudaContext::make_current() -> void
{
ck(cuCtxSetCurrent(cuda_context));
}
DeviceBgraBuffer::DeviceBgraBuffer(int width_, int height_)
: width{width_}
, height{height_}
{
ck(cuMemAlloc(&data, width * height * 4));
ck(cuMemsetD8(data, 0, width * height * 4));
}
DeviceBgraBuffer::~DeviceBgraBuffer()
{
if (data)
ck(cuMemFree(data));
}
auto
DeviceBgraBuffer::to_host(DO::Sara::ImageView<DO::Sara::Bgra8>& image) const
-> void
{
ck(cudaMemcpy(reinterpret_cast<void*>(image.data()),
reinterpret_cast<const void*>(data), width * height * 4,
cudaMemcpyDeviceToHost));
}
} // namespace DriverApi
simplelogger::Logger* logger =
simplelogger::LoggerFactory::CreateConsoleLogger();
namespace DO { namespace Shakti {
struct VideoStream::Impl
{
Impl(const std::string& video_filepath,
const DriverApi::CudaContext& context)
: demuxer{video_filepath.c_str()}
, decoder{context.cuda_context, true,
FFmpeg2NvCodecId(demuxer.GetVideoCodec())}
{
}
auto
read_decoded_frame_packet(DriverApi::DeviceBgraBuffer& bgra_frame_buffer)
-> void
{
// Launch CUDA kernels for colorspace conversion from raw video to raw
// image formats which OpenGL textures can work with
if (decoder.GetBitDepth() == 8)
{
if (decoder.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
YUV444ToColor32<BGRA32>(
(uint8_t*) raw_frame_packet[frame_index], decoder.GetWidth(),
(uint8_t*) bgra_frame_buffer.data, bgra_frame_buffer.width * 4,
decoder.GetWidth(), decoder.GetHeight());
else // default assumed NV12
Nv12ToColor32<BGRA32>(
(uint8_t*) raw_frame_packet[frame_index], decoder.GetWidth(),
(uint8_t*) bgra_frame_buffer.data, bgra_frame_buffer.width * 4,
decoder.GetWidth(), decoder.GetHeight());
}
else
{
if (decoder.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
YUV444P16ToColor32<BGRA32>(
(uint8_t*) raw_frame_packet[frame_index], 2 * decoder.GetWidth(),
(uint8_t*) bgra_frame_buffer.data, bgra_frame_buffer.width * 4,
decoder.GetWidth(), decoder.GetHeight());
else // default assumed P016
P016ToColor32<BGRA32>(
(uint8_t*) raw_frame_packet[frame_index], 2 * decoder.GetWidth(),
(uint8_t*) bgra_frame_buffer.data, bgra_frame_buffer.width * 4,
decoder.GetWidth(), decoder.GetHeight());
}
++frame_index;
if (frame_index == num_frames_decoded)
num_frames_decoded = frame_index = 0;
}
auto decode() -> bool
{
// Initialize the video stream.
do
{
if (!demuxer.Demux(&frame_data_compressed.data,
&frame_data_compressed.size))
return false;
decoder.Decode(frame_data_compressed.data, frame_data_compressed.size,
&raw_frame_packet, &num_frames_decoded);
} while (num_frames_decoded <= 0);
return true;
}
auto read(DriverApi::DeviceBgraBuffer& bgra_frame_buffer) -> bool
{
if (num_frames_decoded == 0 && !decode())
return false;
#ifdef DEBUG
LOG(INFO) << decoder.GetVideoInfo();
#endif
if (frame_index < num_frames_decoded)
read_decoded_frame_packet(bgra_frame_buffer);
return true;
}
mutable FFmpegDemuxer demuxer;
NvDecoder decoder;
std::uint8_t** raw_frame_packet{nullptr};
std::int32_t num_frames_decoded{};
std::int32_t frame_index{};
struct EncodedVideoBuffer
{
std::uint8_t* data{nullptr};
std::int32_t size{};
} frame_data_compressed;
};
auto VideoStream::ImplDeleter::operator()(const VideoStream::Impl* p) const
-> void
{
delete p;
}
VideoStream::VideoStream(const std::string& video_filepath,
const DriverApi::CudaContext& context)
: _impl{new VideoStream::Impl{video_filepath, context}}
{
}
auto VideoStream::width() const -> int
{
return _impl->demuxer.GetWidth();
}
auto VideoStream::height() const -> int
{
return _impl->demuxer.GetHeight();
}
auto VideoStream::decode() -> bool
{
return _impl->decode();
}
auto VideoStream::read(DriverApi::DeviceBgraBuffer& bgra_frame_buffer) -> bool
{
return _impl->read(bgra_frame_buffer);
}
}} // namespace DO::Shakti
static auto get_output_format_names(unsigned short output_format_mask,
char* OutputFormats) -> void
{
if (output_format_mask == 0)
{
strcpy(OutputFormats, "N/A");
return;
}
if (output_format_mask & (1U << cudaVideoSurfaceFormat_NV12))
strcat(OutputFormats, "NV12 ");
if (output_format_mask & (1U << cudaVideoSurfaceFormat_P016))
strcat(OutputFormats, "P016 ");
if (output_format_mask & (1U << cudaVideoSurfaceFormat_YUV444))
strcat(OutputFormats, "YUV444 ");
if (output_format_mask & (1U << cudaVideoSurfaceFormat_YUV444_16Bit))
strcat(OutputFormats, "YUV444P16 ");
}
auto show_decoder_capability() -> void
{
ck(cuInit(0));
int num_gpus = 0;
ck(cuDeviceGetCount(&num_gpus));
std::cout << "Decoder Capability" << std::endl << std::endl;
const char* codec_names[] = {
"JPEG", "MPEG1", "MPEG2", "MPEG4", "H264", "HEVC", "HEVC", "HEVC",
"HEVC", "HEVC", "HEVC", "VC1", "VP8", "VP9", "VP9", "VP9"};
const char* chroma_format_strings[] = {"4:0:0", "4:2:0", "4:2:2", "4:4:4"};
char output_formats[64];
cudaVideoCodec codecs[] = {
cudaVideoCodec_JPEG, cudaVideoCodec_MPEG1, cudaVideoCodec_MPEG2,
cudaVideoCodec_MPEG4, cudaVideoCodec_H264, cudaVideoCodec_HEVC,
cudaVideoCodec_HEVC, cudaVideoCodec_HEVC, cudaVideoCodec_HEVC,
cudaVideoCodec_HEVC, cudaVideoCodec_HEVC, cudaVideoCodec_VC1,
cudaVideoCodec_VP8, cudaVideoCodec_VP9, cudaVideoCodec_VP9,
cudaVideoCodec_VP9};
int bit_depth_minus_8[] = {0, 0, 0, 0, 0, 0, 2, 4, 0, 2, 4, 0, 0, 0, 2, 4};
cudaVideoChromaFormat chroma_formats[] = {
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_444, cudaVideoChromaFormat_444,
cudaVideoChromaFormat_444, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420,
cudaVideoChromaFormat_420, cudaVideoChromaFormat_420};
for (int gpu_id = 0; gpu_id < num_gpus; ++gpu_id)
{
auto cuda_context = DriverApi::CudaContext{gpu_id};
for (auto i = 0u; i < sizeof(codecs) / sizeof(codecs[0]); ++i)
{
CUVIDDECODECAPS decode_caps = {};
decode_caps.eCodecType = codecs[i];
decode_caps.eChromaFormat = chroma_formats[i];
decode_caps.nBitDepthMinus8 = bit_depth_minus_8[i];
cuvidGetDecoderCaps(&decode_caps);
output_formats[0] = '\0';
get_output_format_names(decode_caps.nOutputFormatMask, output_formats);
// setw() width = maximum_width_of_string + 2 spaces
std::cout << "Codec " << std::left << std::setw(7) << codec_names[i]
<< "BitDepth " << std::setw(4)
<< decode_caps.nBitDepthMinus8 + 8 << "ChromaFormat "
<< std::setw(7)
<< chroma_format_strings[decode_caps.eChromaFormat]
<< "Supported " << std::setw(3)
<< (int) decode_caps.bIsSupported << "MaxWidth "
<< std::setw(7) << decode_caps.nMaxWidth << "MaxHeight "
<< std::setw(7) << decode_caps.nMaxHeight << "MaxMBCount "
<< std::setw(10) << decode_caps.nMaxMBCount << "MinWidth "
<< std::setw(5) << decode_caps.nMinWidth << "MinHeight "
<< std::setw(5) << decode_caps.nMinHeight << "SurfaceFormat "
<< std::setw(11) << output_formats << std::endl;
}
std::cout << std::endl;
}
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osg/GraphicsContext>
#include <osg/Notify>
#include <map>
using namespace osg;
static ref_ptr<GraphicsContext::CreateGraphicContextCallback> s_createGraphicsContextCallback;
void GraphicsContext::setCreateGraphicsContextCallback(CreateGraphicContextCallback* callback)
{
s_createGraphicsContextCallback = callback;
}
GraphicsContext::CreateGraphicContextCallback* GraphicsContext::getCreateGraphicsContextCallback()
{
return s_createGraphicsContextCallback.get();
}
GraphicsContext* GraphicsContext::createGraphicsContext(Traits* traits)
{
if (s_createGraphicsContextCallback.valid())
return s_createGraphicsContextCallback->createGraphicsContext(traits);
else
return 0;
}
typedef std::map<unsigned int, unsigned int> ContextIDMap;
static ContextIDMap s_contextIDMap;
static OpenThreads::Mutex s_contextIDMapMutex;
unsigned int GraphicsContext::createNewContextID()
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(s_contextIDMapMutex);
// first check to see if we can reuse contextID;
for(ContextIDMap::iterator itr = s_contextIDMap.begin();
itr != s_contextIDMap.end();
++itr)
{
if (itr->second == 0)
{
// reuse contextID;
itr->second = 1;
osg::notify(osg::NOTICE)<<"GraphicsContext::createNewContextID() reusing contextID="<<itr->first<<std::endl;
return itr->first;
}
}
unsigned int contextID = s_contextIDMap.size();
s_contextIDMap[contextID] = 1;
osg::notify(osg::INFO)<<"GraphicsContext::createNewContextID() creating contextID="<<contextID<<std::endl;
if ( (contextID+1) > osg::DisplaySettings::instance()->getMaxNumberOfGraphicsContexts() )
{
osg::notify(osg::INFO)<<"Updating the MaxNumberOfGraphicsContexts to "<<contextID+1<<std::endl;
// update the the maximum number of graphics contexts,
// to ensure that texture objects and display buffers are configured to the correct size.
osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( contextID + 1 );
}
return contextID;
}
void GraphicsContext::incrementContextIDUsageCount(unsigned int contextID)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(s_contextIDMapMutex);
osg::notify(osg::INFO)<<"GraphicsContext::incrementContextIDUsageCount("<<contextID<<") to "<<s_contextIDMap[contextID]<<std::endl;
++s_contextIDMap[contextID];
}
void GraphicsContext::decrementContextIDUsageCount(unsigned int contextID)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(s_contextIDMapMutex);
if (s_contextIDMap[contextID]!=0)
{
--s_contextIDMap[contextID];
}
else
{
osg::notify(osg::NOTICE)<<"Warning: decrementContextIDUsageCount("<<contextID<<") called on expired contextID."<<std::endl;
}
osg::notify(osg::INFO)<<"GraphicsContext::decrementContextIDUsageCount("<<contextID<<") to "<<s_contextIDMap[contextID]<<std::endl;
}
GraphicsContext::GraphicsContext():
_threadOfLastMakeCurrent(0)
{
}
GraphicsContext::~GraphicsContext()
{
close(false);
}
/** Realise the GraphicsContext.*/
bool GraphicsContext::realize()
{
if (realizeImplementation())
{
if (_graphicsThread.valid() && !_graphicsThread->isRunning())
{
_graphicsThread->startThread();
}
return true;
}
else
{
return false;
}
}
void GraphicsContext::close(bool callCloseImplementation)
{
// switch off the graphics thread...
setGraphicsThread(0);
if (callCloseImplementation) closeImplementation();
if (_state.valid())
{
decrementContextIDUsageCount(_state->getContextID());
_state = 0;
}
}
void GraphicsContext::makeCurrent()
{
ReleaseContext_Block_MakeCurrentOperation* rcbmco = 0;
if (_graphicsThread.valid() &&
_threadOfLastMakeCurrent == _graphicsThread.get() &&
_threadOfLastMakeCurrent != OpenThreads::Thread::CurrentThread())
{
// create a relase contex, block and make current operation to stop the graphics thread while we use the graphics context for ourselves
rcbmco = new ReleaseContext_Block_MakeCurrentOperation;
_graphicsThread->add(rcbmco);
}
if (!isCurrent()) _mutex.lock();
makeCurrentImplementation();
_threadOfLastMakeCurrent = OpenThreads::Thread::CurrentThread();
if (rcbmco)
{
// Let the "relase contex, block and make current operation" proceed, which will now move on to trying to aquire the graphics
// contex itself with a makeCurrent(), this will then block on the GraphicsContext mutex till releaseContext() releases it.
rcbmco->release();
}
}
void GraphicsContext::makeContextCurrent(GraphicsContext* readContext)
{
if (!isCurrent()) _mutex.lock();
makeContextCurrentImplementation(readContext);
_threadOfLastMakeCurrent = OpenThreads::Thread::CurrentThread();
}
void GraphicsContext::releaseContext()
{
_mutex.unlock();
}
void GraphicsContext::swapBuffers()
{
if (isCurrent())
{
swapBuffersImplementation();
}
else if (_graphicsThread.valid() &&
_threadOfLastMakeCurrent == _graphicsThread.get())
{
_graphicsThread->add(new SwapBuffersOperation);
}
else
{
makeCurrent();
swapBuffersImplementation();
releaseContext();
}
}
void GraphicsContext::createGraphicsThread()
{
if (!_graphicsThread)
{
setGraphicsThread(new GraphicsThread);
}
}
void GraphicsContext::setGraphicsThread(GraphicsThread* gt)
{
if (_graphicsThread==gt) return;
if (_graphicsThread.valid())
{
// need to kill the thread in some way...
_graphicsThread->cancel();
_graphicsThread->_graphicsContext = 0;
}
_graphicsThread = gt;
if (_graphicsThread.valid())
{
_graphicsThread->_graphicsContext = this;
if (!_graphicsThread->isRunning())
{
_graphicsThread->startThread();
}
}
}
<commit_msg>Changed debug message to INFO.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osg/GraphicsContext>
#include <osg/Notify>
#include <map>
using namespace osg;
static ref_ptr<GraphicsContext::CreateGraphicContextCallback> s_createGraphicsContextCallback;
void GraphicsContext::setCreateGraphicsContextCallback(CreateGraphicContextCallback* callback)
{
s_createGraphicsContextCallback = callback;
}
GraphicsContext::CreateGraphicContextCallback* GraphicsContext::getCreateGraphicsContextCallback()
{
return s_createGraphicsContextCallback.get();
}
GraphicsContext* GraphicsContext::createGraphicsContext(Traits* traits)
{
if (s_createGraphicsContextCallback.valid())
return s_createGraphicsContextCallback->createGraphicsContext(traits);
else
return 0;
}
typedef std::map<unsigned int, unsigned int> ContextIDMap;
static ContextIDMap s_contextIDMap;
static OpenThreads::Mutex s_contextIDMapMutex;
unsigned int GraphicsContext::createNewContextID()
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(s_contextIDMapMutex);
// first check to see if we can reuse contextID;
for(ContextIDMap::iterator itr = s_contextIDMap.begin();
itr != s_contextIDMap.end();
++itr)
{
if (itr->second == 0)
{
// reuse contextID;
itr->second = 1;
osg::notify(osg::INFO)<<"GraphicsContext::createNewContextID() reusing contextID="<<itr->first<<std::endl;
return itr->first;
}
}
unsigned int contextID = s_contextIDMap.size();
s_contextIDMap[contextID] = 1;
osg::notify(osg::INFO)<<"GraphicsContext::createNewContextID() creating contextID="<<contextID<<std::endl;
if ( (contextID+1) > osg::DisplaySettings::instance()->getMaxNumberOfGraphicsContexts() )
{
osg::notify(osg::INFO)<<"Updating the MaxNumberOfGraphicsContexts to "<<contextID+1<<std::endl;
// update the the maximum number of graphics contexts,
// to ensure that texture objects and display buffers are configured to the correct size.
osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( contextID + 1 );
}
return contextID;
}
void GraphicsContext::incrementContextIDUsageCount(unsigned int contextID)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(s_contextIDMapMutex);
osg::notify(osg::INFO)<<"GraphicsContext::incrementContextIDUsageCount("<<contextID<<") to "<<s_contextIDMap[contextID]<<std::endl;
++s_contextIDMap[contextID];
}
void GraphicsContext::decrementContextIDUsageCount(unsigned int contextID)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(s_contextIDMapMutex);
if (s_contextIDMap[contextID]!=0)
{
--s_contextIDMap[contextID];
}
else
{
osg::notify(osg::NOTICE)<<"Warning: decrementContextIDUsageCount("<<contextID<<") called on expired contextID."<<std::endl;
}
osg::notify(osg::INFO)<<"GraphicsContext::decrementContextIDUsageCount("<<contextID<<") to "<<s_contextIDMap[contextID]<<std::endl;
}
GraphicsContext::GraphicsContext():
_threadOfLastMakeCurrent(0)
{
}
GraphicsContext::~GraphicsContext()
{
close(false);
}
/** Realise the GraphicsContext.*/
bool GraphicsContext::realize()
{
if (realizeImplementation())
{
if (_graphicsThread.valid() && !_graphicsThread->isRunning())
{
_graphicsThread->startThread();
}
return true;
}
else
{
return false;
}
}
void GraphicsContext::close(bool callCloseImplementation)
{
// switch off the graphics thread...
setGraphicsThread(0);
if (callCloseImplementation) closeImplementation();
if (_state.valid())
{
decrementContextIDUsageCount(_state->getContextID());
_state = 0;
}
}
void GraphicsContext::makeCurrent()
{
ReleaseContext_Block_MakeCurrentOperation* rcbmco = 0;
if (_graphicsThread.valid() &&
_threadOfLastMakeCurrent == _graphicsThread.get() &&
_threadOfLastMakeCurrent != OpenThreads::Thread::CurrentThread())
{
// create a relase contex, block and make current operation to stop the graphics thread while we use the graphics context for ourselves
rcbmco = new ReleaseContext_Block_MakeCurrentOperation;
_graphicsThread->add(rcbmco);
}
if (!isCurrent()) _mutex.lock();
makeCurrentImplementation();
_threadOfLastMakeCurrent = OpenThreads::Thread::CurrentThread();
if (rcbmco)
{
// Let the "relase contex, block and make current operation" proceed, which will now move on to trying to aquire the graphics
// contex itself with a makeCurrent(), this will then block on the GraphicsContext mutex till releaseContext() releases it.
rcbmco->release();
}
}
void GraphicsContext::makeContextCurrent(GraphicsContext* readContext)
{
if (!isCurrent()) _mutex.lock();
makeContextCurrentImplementation(readContext);
_threadOfLastMakeCurrent = OpenThreads::Thread::CurrentThread();
}
void GraphicsContext::releaseContext()
{
_mutex.unlock();
}
void GraphicsContext::swapBuffers()
{
if (isCurrent())
{
swapBuffersImplementation();
}
else if (_graphicsThread.valid() &&
_threadOfLastMakeCurrent == _graphicsThread.get())
{
_graphicsThread->add(new SwapBuffersOperation);
}
else
{
makeCurrent();
swapBuffersImplementation();
releaseContext();
}
}
void GraphicsContext::createGraphicsThread()
{
if (!_graphicsThread)
{
setGraphicsThread(new GraphicsThread);
}
}
void GraphicsContext::setGraphicsThread(GraphicsThread* gt)
{
if (_graphicsThread==gt) return;
if (_graphicsThread.valid())
{
// need to kill the thread in some way...
_graphicsThread->cancel();
_graphicsThread->_graphicsContext = 0;
}
_graphicsThread = gt;
if (_graphicsThread.valid())
{
_graphicsThread->_graphicsContext = this;
if (!_graphicsThread->isRunning())
{
_graphicsThread->startThread();
}
}
}
<|endoftext|> |
<commit_before>/// HEADER
#include "optimization_dummy.h"
/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_value_message.hpp>
CSAPEX_REGISTER_CLASS(csapex::OptimizationDummy, csapex::Node)
using namespace csapex;
using namespace csapex::connection_types;
OptimizationDummy::OptimizationDummy()
{
}
void OptimizationDummy::setupParameters(Parameterizable& parameters)
{
parameters.addParameter(csapex::param::ParameterFactory::declareRange("a", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("b", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("c", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("d", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("e", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("f", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("g", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("h", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("i", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("j", -10.0, 10.0, 0.0, 0.1));
}
void OptimizationDummy::setup(NodeModifier& node_modifier)
{
in_ = node_modifier.addInput<double>("argument");
out_ = node_modifier.addOutput<double>("Fitness");
}
void OptimizationDummy::process()
{
double a = readParameter<double>("a");
double b = readParameter<double>("b");
double c = readParameter<double>("c");
double d = readParameter<double>("d");
double e = readParameter<double>("e");
double f = readParameter<double>("f");
double g = readParameter<double>("g");
double h = readParameter<double>("h");
double i = readParameter<double>("i");
double j = readParameter<double>("j");
double x = msg::getValue<double>(in_);
double fitness = -std::pow((a - 4), 2)
+ std::pow(x + 1.0 - b, 2)
+ std::pow(x + 2.0 - c, 2)
+ std::pow(x + 3.0 - d, 2)
+ std::pow(x + 4.0 - e, 2)
+ std::pow(x + 5.0 - f, 2)
+ std::pow(x + 6.0 - g, 2)
+ std::pow(x + 7.0 - h, 2)
+ std::pow(x + 8.0 - i, 2)
+ std::pow(x + 9.0 - j, 2)
;
msg::publish(out_, fitness);
}
<commit_msg>changed optimization dummy for minimization<commit_after>/// HEADER
#include "optimization_dummy.h"
/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_value_message.hpp>
CSAPEX_REGISTER_CLASS(csapex::OptimizationDummy, csapex::Node)
using namespace csapex;
using namespace csapex::connection_types;
OptimizationDummy::OptimizationDummy()
{
}
void OptimizationDummy::setupParameters(Parameterizable& parameters)
{
parameters.addParameter(csapex::param::ParameterFactory::declareRange("a", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("b", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("c", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("d", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("e", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("f", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("g", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("h", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("i", -10.0, 10.0, 0.0, 0.1));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("j", -10.0, 10.0, 0.0, 0.1));
}
void OptimizationDummy::setup(NodeModifier& node_modifier)
{
in_ = node_modifier.addInput<double>("argument");
out_ = node_modifier.addOutput<double>("Fitness");
}
void OptimizationDummy::process()
{
double a = readParameter<double>("a");
double b = readParameter<double>("b");
double c = readParameter<double>("c");
double d = readParameter<double>("d");
double e = readParameter<double>("e");
double f = readParameter<double>("f");
double g = readParameter<double>("g");
double h = readParameter<double>("h");
double i = readParameter<double>("i");
double j = readParameter<double>("j");
double x = msg::getValue<double>(in_);
double fitness = std::abs(a - 4)
+ std::pow(x - 5.0 - b, 2)
+ std::pow(x - 2.0 - c, 2)
+ std::pow(x - 3.0 - d, 2)
+ std::pow(x - 4.0 - e, 2)
+ std::pow(x - 5.0 - f, 2)
+ std::pow(x - 6.0 - g, 2)
+ std::pow(x - 7.0 - h, 2)
+ std::pow(x - 8.0 - i, 2)
+ std::pow(x - 9.0 - j, 2)
;
msg::publish(out_, fitness);
}
<|endoftext|> |
<commit_before>#include <sys/socket.h>
#include "utils.h"
#include "client_base.h"
const int WRITE_QUEUE_SIZE = -1;
int BaseClient::total_clients = 0;
BaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
: io(loop),
async(loop),
destroyed(false),
closed(false),
sock(sock_),
database_pool(database_pool_),
write_queue(WRITE_QUEUE_SIZE)
{
sig.set<BaseClient, &BaseClient::signal_cb>(this);
sig.start(SIGINT);
async.set<BaseClient, &BaseClient::async_cb>(this);
async.start();
io.set<BaseClient, &BaseClient::io_cb>(this);
io.start(sock, ev::READ);
}
BaseClient::~BaseClient()
{
destroy();
sig.stop();
LOG_OBJ(this, "DELETED!\n");
}
void BaseClient::signal_cb(ev::sig &signal, int revents)
{
LOG_EV(this, "Signaled destroy!!\n");
destroy();
delete this;
}
void BaseClient::destroy()
{
if (destroyed) {
return;
}
destroyed = true;
close();
// Stop and free watcher if client socket is closing
io.stop();
async.stop();
::close(sock);
LOG_OBJ(this, "DESTROYED!\n");
}
void BaseClient::close() {
if (closed) {
return;
}
closed = true;
LOG_OBJ(this, "CLOSED!\n");
}
void BaseClient::async_cb(ev::async &watcher, int revents)
{
if (destroyed) {
return;
}
LOG_EV(this, "ASYNC_CB (sock=%d) %x\n", sock, revents);
if (write_queue.empty()) {
if (closed) {
destroy();
}
} else {
io.set(ev::READ|ev::WRITE);
}
if (destroyed) {
delete this;
}
}
void BaseClient::io_cb(ev::io &watcher, int revents)
{
if (destroyed) {
return;
}
LOG_EV(this, "IO_CB (sock=%d) %x\n", sock, revents);
if (revents & EV_ERROR) {
LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno));
destroy();
return;
}
if (revents & EV_READ)
read_cb(watcher);
if (revents & EV_WRITE)
write_cb(watcher);
if (write_queue.empty()) {
if (closed) {
destroy();
} else {
io.set(ev::READ);
}
} else {
io.set(ev::READ|ev::WRITE);
}
if (destroyed) {
delete this;
}
}
void BaseClient::write_cb(ev::io &watcher)
{
if (!write_queue.empty()) {
Buffer* buffer = write_queue.front();
size_t buf_size = buffer->nbytes();
const char * buf = buffer->dpos();
LOG_CONN(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str());
ssize_t written = ::write(watcher.fd, buf, buf_size);
if (written < 0) {
if (errno != EAGAIN) {
LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno));
destroy();
}
} else if (written == 0) {
// nothing written?
} else {
buffer->pos += written;
if (buffer->nbytes() == 0) {
write_queue.pop(buffer);
delete buffer;
}
}
}
}
void BaseClient::read_cb(ev::io &watcher)
{
char buf[1024];
ssize_t received = ::read(watcher.fd, buf, sizeof(buf));
if (received < 0) {
if (errno != EAGAIN) {
LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno));
destroy();
}
} else if (received == 0) {
// The peer has closed its half side of the connection.
LOG_CONN(this, "Received EOF (sock=%d)!\n", sock);
destroy();
} else {
LOG_CONN(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str());
on_read(buf, received);
}
}
void BaseClient::write(const char *buf, size_t buf_size)
{
Buffer *buffer = new Buffer('\0', buf, buf_size);
write_queue.push(buffer);
async.send();
}
<commit_msg>Assert watcher.fd == sock<commit_after>#include <assert.h>
#include <sys/socket.h>
#include "utils.h"
#include "client_base.h"
const int WRITE_QUEUE_SIZE = -1;
int BaseClient::total_clients = 0;
BaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
: io(loop),
async(loop),
destroyed(false),
closed(false),
sock(sock_),
database_pool(database_pool_),
write_queue(WRITE_QUEUE_SIZE)
{
sig.set<BaseClient, &BaseClient::signal_cb>(this);
sig.start(SIGINT);
async.set<BaseClient, &BaseClient::async_cb>(this);
async.start();
io.set<BaseClient, &BaseClient::io_cb>(this);
io.start(sock, ev::READ);
}
BaseClient::~BaseClient()
{
destroy();
sig.stop();
LOG_OBJ(this, "DELETED!\n");
}
void BaseClient::signal_cb(ev::sig &signal, int revents)
{
LOG_EV(this, "Signaled destroy!!\n");
destroy();
delete this;
}
void BaseClient::destroy()
{
if (destroyed) {
return;
}
destroyed = true;
close();
// Stop and free watcher if client socket is closing
io.stop();
async.stop();
::close(sock);
LOG_OBJ(this, "DESTROYED!\n");
}
void BaseClient::close() {
if (closed) {
return;
}
closed = true;
LOG_OBJ(this, "CLOSED!\n");
}
void BaseClient::async_cb(ev::async &watcher, int revents)
{
if (destroyed) {
return;
}
LOG_EV(this, "ASYNC_CB (sock=%d) %x\n", sock, revents);
if (write_queue.empty()) {
if (closed) {
destroy();
}
} else {
io.set(ev::READ|ev::WRITE);
}
if (destroyed) {
delete this;
}
}
void BaseClient::io_cb(ev::io &watcher, int revents)
{
if (destroyed) {
return;
}
assert(sock == watcher.fd);
LOG_EV(this, "IO_CB (sock=%d) %x\n", sock, revents);
if (revents & EV_ERROR) {
LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno));
destroy();
return;
}
if (revents & EV_READ)
read_cb(watcher);
if (revents & EV_WRITE)
write_cb(watcher);
if (write_queue.empty()) {
if (closed) {
destroy();
} else {
io.set(ev::READ);
}
} else {
io.set(ev::READ|ev::WRITE);
}
if (destroyed) {
delete this;
}
}
void BaseClient::write_cb(ev::io &watcher)
{
if (!write_queue.empty()) {
Buffer* buffer = write_queue.front();
size_t buf_size = buffer->nbytes();
const char * buf = buffer->dpos();
LOG_CONN(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str());
ssize_t written = ::write(sock, buf, buf_size);
if (written < 0) {
if (errno != EAGAIN) {
LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno));
destroy();
}
} else if (written == 0) {
// nothing written?
} else {
buffer->pos += written;
if (buffer->nbytes() == 0) {
write_queue.pop(buffer);
delete buffer;
}
}
}
}
void BaseClient::read_cb(ev::io &watcher)
{
char buf[1024];
ssize_t received = ::read(sock, buf, sizeof(buf));
if (received < 0) {
if (errno != EAGAIN) {
LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno));
destroy();
}
} else if (received == 0) {
// The peer has closed its half side of the connection.
LOG_CONN(this, "Received EOF (sock=%d)!\n", sock);
destroy();
} else {
LOG_CONN(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str());
on_read(buf, received);
}
}
void BaseClient::write(const char *buf, size_t buf_size)
{
Buffer *buffer = new Buffer('\0', buf, buf_size);
write_queue.push(buffer);
async.send();
}
<|endoftext|> |
<commit_before>#include "playerwidget.h"
#include "ui_playerwidget.h"
#include "musicselector.h"
static QString _ms2mmss(qint64 ms)
{
int ss = ms / 1000;
int mm = ss / 60;
ss = ss % 60;
QString str;
str.sprintf("%02d:%02d", mm, ss);
return str;
}
LRCX_BEGIN_NS
PlayerWidget::PlayerWidget(QWidget *parent)
: QDockWidget(parent)
, m_ui(new Ui::PlayerWidget)
{
m_ui->setupUi(this);
connect(m_ui->btn_Open, SIGNAL(clicked(bool)), this, SLOT(onBtnOpen_Clicked()));
connect(m_ui->btn_PlayPause, SIGNAL(clicked(bool)), this, SLOT(onBtnPlayPause_Clicked()));
connect(m_ui->slider_Duration, SIGNAL(sliderReleased()), this, SLOT(onSliderDuration_Changed()) );
}
PlayerWidget::~PlayerWidget()
{
}
QString PlayerWidget::getTitle() const
{
return m_ui->le_Title->text().trimmed();
}
QString PlayerWidget::getArtist() const
{
return m_ui->le_Artist->text().trimmed();
}
QString PlayerWidget::getAlbum() const
{
return m_ui->le_Album->text().trimmed();
}
QString PlayerWidget::getEditor() const
{
return m_ui->le_Editor->text().trimmed();
}
qint64 PlayerWidget::getCurrentPosition() const
{
if (m_player)
return m_player->position();
return 0;
}
void PlayerWidget::onBtnOpen_Clicked()
{
std::unique_ptr<Player> player(MusicSelector::select());
if (player == nullptr)
return ;
m_ui->le_Title->setText(player->metaData(Player::Title).toString());
m_ui->le_Artist->setText(player->metaData(Player::Artist).toString());
m_ui->le_Album->setText(player->metaData(Player::AlbumTitle).toString());
if (m_ui->le_Editor->text().trimmed().isEmpty())
m_ui->le_Editor->setText(tr("LyricsX"));
m_ui->btn_PlayPause->setEnabled(true);
m_ui->slider_Duration->setEnabled(true);
if (m_player)
m_player->disconnect();
m_player = std::move(player);
connect(m_player.get(), SIGNAL(stateChanged(Player::State)), this, SLOT(onPlayerStateChanged(Player::State)));
connect(m_player.get(), SIGNAL(durationChanged(qint64)), this, SLOT(onPlayerDurationChanged(qint64)));
connect(m_player.get(), SIGNAL(positionChanged(qint64)), this, SLOT(onPlayerPositionChanged(qint64)));
}
void PlayerWidget::onBtnPlayPause_Clicked()
{
if (m_player)
{
if (m_player->state() == Player::Playing)
m_player->pause();
else
m_player->play();
}
}
void PlayerWidget::onSliderDuration_Changed()
{
if (m_player)
{
int pos = m_ui->slider_Duration->value();
if (m_player->position() != pos)
{
m_ui->slider_Duration->blockSignals(true);
m_player->setPosition(pos);
m_ui->slider_Duration->blockSignals(false);
}
}
}
void PlayerWidget::onPlayerStateChanged(Player::State state)
{
QIcon icon = QIcon::fromTheme(state == Player::Playing ?
"media-playback-pause" :
"media-playback-start"
);
m_ui->btn_PlayPause->setIcon(icon);
}
void PlayerWidget::onPlayerDurationChanged(qint64 duration)
{
m_ui->slider_Duration->setMaximum(duration);
}
void PlayerWidget::onPlayerPositionChanged(qint64 pos)
{
qint64 total = m_player->duration();
QString strText = _ms2mmss(pos) + "/" + _ms2mmss(total);
m_ui->label_Duration->setText(strText);
m_ui->slider_Duration->blockSignals(true);
m_ui->slider_Duration->setValue(pos);
m_ui->slider_Duration->blockSignals(false);
}
LRCX_END_NS
<commit_msg>update window title while selected music<commit_after>#include "playerwidget.h"
#include "ui_playerwidget.h"
#include "musicselector.h"
static QString _ms2mmss(qint64 ms)
{
int ss = ms / 1000;
int mm = ss / 60;
ss = ss % 60;
QString str;
str.sprintf("%02d:%02d", mm, ss);
return str;
}
LRCX_BEGIN_NS
PlayerWidget::PlayerWidget(QWidget *parent)
: QDockWidget(parent)
, m_ui(new Ui::PlayerWidget)
{
m_ui->setupUi(this);
connect(m_ui->btn_Open, SIGNAL(clicked(bool)), this, SLOT(onBtnOpen_Clicked()));
connect(m_ui->btn_PlayPause, SIGNAL(clicked(bool)), this, SLOT(onBtnPlayPause_Clicked()));
connect(m_ui->slider_Duration, SIGNAL(sliderReleased()), this, SLOT(onSliderDuration_Changed()) );
}
PlayerWidget::~PlayerWidget()
{
}
QString PlayerWidget::getTitle() const
{
return m_ui->le_Title->text().trimmed();
}
QString PlayerWidget::getArtist() const
{
return m_ui->le_Artist->text().trimmed();
}
QString PlayerWidget::getAlbum() const
{
return m_ui->le_Album->text().trimmed();
}
QString PlayerWidget::getEditor() const
{
return m_ui->le_Editor->text().trimmed();
}
qint64 PlayerWidget::getCurrentPosition() const
{
if (m_player)
return m_player->position();
return 0;
}
void PlayerWidget::onBtnOpen_Clicked()
{
std::unique_ptr<Player> player(MusicSelector::select());
if (player == nullptr)
return ;
m_ui->le_Title->setText(player->metaData(Player::Title).toString());
m_ui->le_Artist->setText(player->metaData(Player::Artist).toString());
m_ui->le_Album->setText(player->metaData(Player::AlbumTitle).toString());
if (m_ui->le_Editor->text().trimmed().isEmpty())
m_ui->le_Editor->setText(tr("LyricsX"));
QString strTitle = player->metaData(Player::Artist).toString();
strTitle += " - " + player->metaData(Player::Title).toString();
setWindowTitle(strTitle);
m_ui->btn_PlayPause->setEnabled(true);
m_ui->slider_Duration->setEnabled(true);
if (m_player)
m_player->disconnect();
m_player = std::move(player);
connect(m_player.get(), SIGNAL(stateChanged(Player::State)), this, SLOT(onPlayerStateChanged(Player::State)));
connect(m_player.get(), SIGNAL(durationChanged(qint64)), this, SLOT(onPlayerDurationChanged(qint64)));
connect(m_player.get(), SIGNAL(positionChanged(qint64)), this, SLOT(onPlayerPositionChanged(qint64)));
}
void PlayerWidget::onBtnPlayPause_Clicked()
{
if (m_player)
{
if (m_player->state() == Player::Playing)
m_player->pause();
else
m_player->play();
}
}
void PlayerWidget::onSliderDuration_Changed()
{
if (m_player)
{
int pos = m_ui->slider_Duration->value();
if (m_player->position() != pos)
{
m_ui->slider_Duration->blockSignals(true);
m_player->setPosition(pos);
m_ui->slider_Duration->blockSignals(false);
}
}
}
void PlayerWidget::onPlayerStateChanged(Player::State state)
{
QIcon icon = QIcon::fromTheme(state == Player::Playing ?
"media-playback-pause" :
"media-playback-start"
);
m_ui->btn_PlayPause->setIcon(icon);
}
void PlayerWidget::onPlayerDurationChanged(qint64 duration)
{
m_ui->slider_Duration->setMaximum(duration);
}
void PlayerWidget::onPlayerPositionChanged(qint64 pos)
{
qint64 total = m_player->duration();
QString strText = _ms2mmss(pos) + "/" + _ms2mmss(total);
m_ui->label_Duration->setText(strText);
m_ui->slider_Duration->blockSignals(true);
m_ui->slider_Duration->setValue(pos);
m_ui->slider_Duration->blockSignals(false);
}
LRCX_END_NS
<|endoftext|> |
<commit_before>#ifndef DEDICATED_ONLY
#include "CViewport.h"
#include "gusgame.h"
#include "sound/sfx.h"
#include "gfx.h"
#include "gusanos/allegro.h"
#include "CWorm.h"
#include "game/WormInputHandler.h"
#include "CWormHuman.h"
#include "glua.h"
#include "lua/bindings-gfx.h"
#include "blitters/blitters.h"
#include "culling.h"
#include "CMap.h"
#include "game/Game.h"
#include <list>
#include "sprite_set.h" // TEMP
#include "sprite.h" // TEMP
#include "CGameScript.h"
#include <iostream>
using namespace std;
void CViewport::gusInit()
{
dest = 0;
hud = 0;
fadeBuffer = 0;
}
void CViewport::gusReset()
{
if(luaReference) lua.destroyReference(luaReference); luaReference = LuaReference();
destroy_bitmap(dest); dest = 0;
destroy_bitmap(hud); hud = 0;
destroy_bitmap(fadeBuffer); fadeBuffer = 0;
}
struct TestCuller : public Culler<TestCuller>
{
TestCuller(ALLEGRO_BITMAP* dest_, ALLEGRO_BITMAP* src_, int scrOffX_, int scrOffY_, int destOffX_, int destOffY_, Rect const& rect)
: Culler<TestCuller>(rect), dest(dest_), src(src_),
scrOffX(scrOffX_), scrOffY(scrOffY_), destOffX(destOffX_), destOffY(destOffY_)
{
}
bool block(int x, int y)
{
return !gusGame.level().unsafeGetMaterial(x, y).worm_pass;
}
void line(int y, int x1, int x2)
{
//hline_add(dest, x1 + scrOffX, y + scrOffY, x2 + scrOffX + 1, makecol(50, 50, 50), 255);
drawSpriteLine_add(
dest,
src,
x1 + scrOffX,
y + scrOffY,
x1 + destOffX,
y + destOffY,
x2 + destOffX + 1,
255);
}
ALLEGRO_BITMAP* dest;
ALLEGRO_BITMAP* src;
int scrOffX;
int scrOffY;
int destOffX;
int destOffY;
};
static ALLEGRO_BITMAP* testLight = 0;
void CViewport::setDestination(ALLEGRO_BITMAP* where, int x, int y, int width, int height)
{
if(width > where->w
|| height > where->h) {
errors << "CViewport::setDestination: " << width << "x" << height << " too big" << endl;
return;
}
if(luaReference) lua.destroyReference(luaReference);
destroy_bitmap(dest);
destroy_bitmap(hud);
if ( x < 0 )
x = 0;
if ( y < 0 )
y = 0;
if ( x + width > where->w )
x = where->w - width;
if ( y + height > where->h )
y = where->h - height;
dest = create_sub_bitmap(where,x,y,width,height);
hud = create_sub_bitmap(where,x,y,width,height);
destroy_bitmap(fadeBuffer);
fadeBuffer = create_bitmap_ex(8, width, height);
if(!testLight) {
static int s = 500;
destroy_bitmap(testLight);
testLight = create_bitmap_ex(8, s, s);
for(int y = 0; y < s; ++y)
for(int x = 0; x < s; ++x) {
double v = 1.0*(double(s)/2 - (IVec(x, y) - IVec(s/2, s/2)).length());
if(v < 0.0)
v = 0.0;
int iv = int(v);
putpixel_solid(testLight, x, y, iv);
}
}
lua.pushFullReference(*this, LuaBindings::CViewportMetaTable);
//lua.pushLightReference(this, LuaBindings::viewportMetaTable);
luaReference = lua.createReference();
}
void CViewport::drawLight(IVec const& v)
{
IVec off(Left,Top);
IVec loff(v - IVec(testLight->w/2, testLight->h/2));
Rect r(0, 0, gusGame.level().GetWidth() - 1, gusGame.level().GetHeight() - 1);
r &= Rect(testLight) + loff;
TestCuller testCuller(fadeBuffer, testLight, -off.x, -off.y, -loff.x, -loff.y, r);
testCuller.cullOmni(v.x, v.y);
}
void CViewport::gusRender()
{
{
int destx = Left/2;
int desty = Top/2;
int destw = Width;
int desth = Height;
bool needDestReset = false;
if(!dest)
needDestReset = true;
else if(dest->sub_x != destx || dest->sub_y != desty || dest->w != destw || dest->h != desth )
needDestReset = true;
else if(dest->surf.get() != gfx.buffer->surf.get())
needDestReset = true;
if(needDestReset)
setDestination(gfx.buffer, destx, desty, destw, desth);
}
int offX = static_cast<int>(WorldX);
int offY = static_cast<int>(WorldY);
gusGame.level().gusDraw(dest, offX, offY);
if ( gusGame.level().config()->darkMode && gusGame.level().lightmap )
blit( gusGame.level().lightmap, fadeBuffer, offX,offY, 0, 0, fadeBuffer->w, fadeBuffer->h );
for ( Grid::iterator iter = game.objects.beginAll(); iter; ++iter) {
//iter->draw(dest, offX, offY);
iter->draw(this);
}
/*
static double a = 0.0;
a += 0.003;
*/
#if 0
if(gfx.m_haxWormLight) {
CWormInputHandler* player = game.localPlayers[0];
CWorm* worm = player->getWorm();
if(worm->isActive()) {
IVec v(worm->pos);
drawLight(v);
}
}
#endif
if(gusGame.level().config()->darkMode)
drawSprite_mult_8(dest, fadeBuffer, 0, 0);
// only use the player/worm specific drawings in gus mods
if(game.gameScript()->gusEngineUsed()) {
CWormInputHandler* player = pcTargetWorm ? pcTargetWorm->inputHandler() : NULL;
// Note that we only process worms in the Lua callbacks which have a player set.
// Most Lua code depends on this assumption so it would break otherwise.
EACH_CALLBACK(i, wormRender) {
for(vector<CWormInputHandler*>::iterator playerIter = game.players.begin(); playerIter != game.players.end(); ++playerIter) {
CWorm* worm = (*playerIter)->getWorm();
if( worm && worm->isActive() && worm->inputHandler() ) {
IVec renderPos( worm->getRenderPos() );
int x = renderPos.x - offX;
int y = renderPos.y - offY;
//bool ownViewport = (*playerIter == player);
LuaReference ownerRef;
if ( player )
ownerRef = player->getLuaReference();
//lua.callReference(0, *i, (lua_Number)x, (lua_Number)y, worm->luaReference, luaReference, ownViewport);
(lua.call(*i), (lua_Number)x, (lua_Number)y, worm->getLuaReference(), luaReference, ownerRef)();
}
}
}
// draw viewport specific stuff only for human worms
if(pcTargetWorm && dynamic_cast<CWormHumanInputHandler*>(pcTargetWorm->inputHandler()) != NULL) {
EACH_CALLBACK(i, viewportRender) {
//lua.callReference(0, *i, luaReference, worm->luaReference);
(lua.call(*i), luaReference, pcTargetWorm->getLuaReference())();
}
}
}
// no gus mod
else {
}
}
#endif
<commit_msg>cleanup. deleting old commented-out code<commit_after>#ifndef DEDICATED_ONLY
#include "CViewport.h"
#include "gusgame.h"
#include "sound/sfx.h"
#include "gfx.h"
#include "gusanos/allegro.h"
#include "CWorm.h"
#include "game/WormInputHandler.h"
#include "CWormHuman.h"
#include "glua.h"
#include "lua/bindings-gfx.h"
#include "blitters/blitters.h"
#include "culling.h"
#include "CMap.h"
#include "game/Game.h"
#include <list>
#include "sprite_set.h" // TEMP
#include "sprite.h" // TEMP
#include "CGameScript.h"
#include <iostream>
using namespace std;
void CViewport::gusInit()
{
dest = 0;
hud = 0;
fadeBuffer = 0;
}
void CViewport::gusReset()
{
if(luaReference) lua.destroyReference(luaReference); luaReference = LuaReference();
destroy_bitmap(dest); dest = 0;
destroy_bitmap(hud); hud = 0;
destroy_bitmap(fadeBuffer); fadeBuffer = 0;
}
struct TestCuller : public Culler<TestCuller>
{
TestCuller(ALLEGRO_BITMAP* dest_, ALLEGRO_BITMAP* src_, int scrOffX_, int scrOffY_, int destOffX_, int destOffY_, Rect const& rect)
: Culler<TestCuller>(rect), dest(dest_), src(src_),
scrOffX(scrOffX_), scrOffY(scrOffY_), destOffX(destOffX_), destOffY(destOffY_)
{
}
bool block(int x, int y)
{
return !gusGame.level().unsafeGetMaterial(x, y).worm_pass;
}
void line(int y, int x1, int x2)
{
//hline_add(dest, x1 + scrOffX, y + scrOffY, x2 + scrOffX + 1, makecol(50, 50, 50), 255);
drawSpriteLine_add(
dest,
src,
x1 + scrOffX,
y + scrOffY,
x1 + destOffX,
y + destOffY,
x2 + destOffX + 1,
255);
}
ALLEGRO_BITMAP* dest;
ALLEGRO_BITMAP* src;
int scrOffX;
int scrOffY;
int destOffX;
int destOffY;
};
static ALLEGRO_BITMAP* testLight = 0;
void CViewport::setDestination(ALLEGRO_BITMAP* where, int x, int y, int width, int height)
{
if(width > where->w
|| height > where->h) {
errors << "CViewport::setDestination: " << width << "x" << height << " too big" << endl;
return;
}
if(luaReference) lua.destroyReference(luaReference);
destroy_bitmap(dest);
destroy_bitmap(hud);
if ( x < 0 )
x = 0;
if ( y < 0 )
y = 0;
if ( x + width > where->w )
x = where->w - width;
if ( y + height > where->h )
y = where->h - height;
dest = create_sub_bitmap(where,x,y,width,height);
hud = create_sub_bitmap(where,x,y,width,height);
destroy_bitmap(fadeBuffer);
fadeBuffer = create_bitmap_ex(8, width, height);
if(!testLight) {
static int s = 500;
destroy_bitmap(testLight);
testLight = create_bitmap_ex(8, s, s);
for(int y = 0; y < s; ++y)
for(int x = 0; x < s; ++x) {
double v = 1.0*(double(s)/2 - (IVec(x, y) - IVec(s/2, s/2)).length());
if(v < 0.0)
v = 0.0;
int iv = int(v);
putpixel_solid(testLight, x, y, iv);
}
}
lua.pushFullReference(*this, LuaBindings::CViewportMetaTable);
luaReference = lua.createReference();
}
void CViewport::drawLight(IVec const& v)
{
IVec off(Left,Top);
IVec loff(v - IVec(testLight->w/2, testLight->h/2));
Rect r(0, 0, gusGame.level().GetWidth() - 1, gusGame.level().GetHeight() - 1);
r &= Rect(testLight) + loff;
TestCuller testCuller(fadeBuffer, testLight, -off.x, -off.y, -loff.x, -loff.y, r);
testCuller.cullOmni(v.x, v.y);
}
void CViewport::gusRender()
{
{
int destx = Left/2;
int desty = Top/2;
int destw = Width;
int desth = Height;
bool needDestReset = false;
if(!dest)
needDestReset = true;
else if(dest->sub_x != destx || dest->sub_y != desty || dest->w != destw || dest->h != desth )
needDestReset = true;
else if(dest->surf.get() != gfx.buffer->surf.get())
needDestReset = true;
if(needDestReset)
setDestination(gfx.buffer, destx, desty, destw, desth);
}
int offX = static_cast<int>(WorldX);
int offY = static_cast<int>(WorldY);
gusGame.level().gusDraw(dest, offX, offY);
if ( gusGame.level().config()->darkMode && gusGame.level().lightmap )
blit( gusGame.level().lightmap, fadeBuffer, offX,offY, 0, 0, fadeBuffer->w, fadeBuffer->h );
for ( Grid::iterator iter = game.objects.beginAll(); iter; ++iter)
iter->draw(this);
#if 0
if(gfx.m_haxWormLight) {
CWormInputHandler* player = game.localPlayers[0];
CWorm* worm = player->getWorm();
if(worm->isActive()) {
IVec v(worm->pos);
drawLight(v);
}
}
#endif
if(gusGame.level().config()->darkMode)
drawSprite_mult_8(dest, fadeBuffer, 0, 0);
// only use the player/worm specific drawings in gus mods
if(game.gameScript()->gusEngineUsed()) {
CWormInputHandler* player = pcTargetWorm ? pcTargetWorm->inputHandler() : NULL;
// Note that we only process worms in the Lua callbacks which have a player set.
// Most Lua code depends on this assumption so it would break otherwise.
EACH_CALLBACK(i, wormRender) {
for(vector<CWormInputHandler*>::iterator playerIter = game.players.begin(); playerIter != game.players.end(); ++playerIter) {
CWorm* worm = (*playerIter)->getWorm();
if( worm && worm->isActive() && worm->inputHandler() ) {
IVec renderPos( worm->getRenderPos() );
int x = renderPos.x - offX;
int y = renderPos.y - offY;
LuaReference ownerRef;
if ( player )
ownerRef = player->getLuaReference();
(lua.call(*i), (lua_Number)x, (lua_Number)y, worm->getLuaReference(), luaReference, ownerRef)();
}
}
}
// draw viewport specific stuff only for human worms
if(pcTargetWorm && dynamic_cast<CWormHumanInputHandler*>(pcTargetWorm->inputHandler()) != NULL) {
EACH_CALLBACK(i, viewportRender) {
(lua.call(*i), luaReference, pcTargetWorm->getLuaReference())();
}
}
}
}
#endif
<|endoftext|> |
<commit_before>/* ************************************************************************************
*
* ftVelocityMask
*
* Created by Matthias Oostrik on 03/16.14.
* Copyright 2014 http://www.MatthiasOostrik.com 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ************************************************************************************ */
#include "ftVelocityMask.h"
namespace flowTools {
void ftVelocityMask::setup(int _width, int _height){
width = _width;
height = _height;
colorMaskSwapBuffer.allocate(width, height, GL_RGBA);
colorMaskSwapBuffer.clear();
luminanceMaskFbo.allocate(width, height, GL_RGB);
luminanceMaskFbo.clear();
parameters.setName("velocity mask");
parameters.add(strength.set("strength", 1, 0, 10));
parameters.add(saturation.set("saturation", 1, 1, 5));
parameters.add(blurPasses.set("blur passes", 1, 0, 10));
parameters.add(blurRadius.set("blur radius", 6, 0, 10));
};
void ftVelocityMask::update() {
ofPushStyle();
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
colorMaskSwapBuffer.clear();
VelocityMaskShader.update(*colorMaskSwapBuffer.src, *densityTexture, *velocityTexture, strength.get());
HSLShader.update(*colorMaskSwapBuffer.dst,
colorMaskSwapBuffer.src->getTextureReference(),
0,
saturation.get(),
1);
colorMaskSwapBuffer.swap();
if (blurPasses.get() > 0 && blurRadius.get() > 0) {
gaussianBlurShader.update(*colorMaskSwapBuffer.src, blurPasses.get(), blurRadius.get());
}
luminanceShader.update(luminanceMaskFbo, colorMaskSwapBuffer.src->getTextureReference());
ofPopStyle();
}
void ftVelocityMask::setDensity(ofTexture &tex) {
densityTexture = &tex;
}
void ftVelocityMask::setVelocity(ofTexture &tex) {
velocityTexture = &tex;
}
}<commit_msg>Update ftVelocityMask.cpp<commit_after>/* ************************************************************************************
*
* ftVelocityMask
*
* Created by Matthias Oostrik on 03/16.14.
* Copyright 2014 http://www.MatthiasOostrik.com 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ************************************************************************************ */
#include "ftVelocityMask.h"
namespace flowTools {
void ftVelocityMask::setup(int _width, int _height){
width = _width;
height = _height;
colorMaskSwapBuffer.allocate(width, height, GL_RGBA);
colorMaskSwapBuffer.clear();
luminanceMaskFbo.allocate(width, height, GL_RGB);
luminanceMaskFbo.clear();
parameters.setName("velocity mask");
parameters.add(strength.set("strength", 1, 0, 10));
parameters.add(saturation.set("saturation", 1, 1, 5));
parameters.add(blurPasses.set("blur passes", 1, 0, 10));
parameters.add(blurRadius.set("blur radius", 6, 0, 10));
};
void ftVelocityMask::update() {
ofPushStyle();
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
colorMaskSwapBuffer.clear();
VelocityMaskShader.update(*colorMaskSwapBuffer.src, *densityTexture, *velocityTexture, strength.get());
HSLShader.update(*colorMaskSwapBuffer.dst,
colorMaskSwapBuffer.src->getTextureReference(),
0,
saturation.get(),
1);
colorMaskSwapBuffer.swap();
if (blurPasses.get() > 0 && blurRadius.get() > 0) {
gaussianBlurShader.update(*colorMaskSwapBuffer.src, blurPasses.get(), blurRadius.get());
}
ofEnableBlendMode(OF_BLENDMODE_DISABLED);
luminanceShader.update(luminanceMaskFbo, colorMaskSwapBuffer.src->getTextureReference());
ofPopStyle();
}
void ftVelocityMask::setDensity(ofTexture &tex) {
densityTexture = &tex;
}
void ftVelocityMask::setVelocity(ofTexture &tex) {
velocityTexture = &tex;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TitledControl.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:16:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "taskpane/TitledControl.hxx"
#include "AccessibleTreeNode.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
namespace sd { namespace toolpanel {
TitledControl::TitledControl (
TreeNode* pParent,
::std::auto_ptr<TreeNode> pControl,
const String& rTitle,
TitleBar::TitleBarType eType)
: ::Window (pParent->GetWindow(), WB_TABSTOP),
TreeNode(pParent),
msTitle(rTitle),
mbVisible(true),
mpUserData(NULL),
mpControlFactory(NULL),
mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
if (pControl.get() != NULL)
{
mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
pControl->SetParentNode (this);
}
mpControlContainer->AddControl (pControl);
FocusManager::Instance().RegisterDownLink(this, GetControl()->GetWindow());
FocusManager::Instance().RegisterUpLink(GetControl()->GetWindow(), this);
SetBackground (Wallpaper());
GetTitleBar()->GetWindow()->Show ();
GetTitleBar()->GetWindow()->AddEventListener (
LINK(this,TitledControl,WindowEventListener));
UpdateStates ();
}
TitledControl::TitledControl (
TreeNode* pParent,
::std::auto_ptr<ControlFactory> pControlFactory,
const String& rTitle,
TitleBar::TitleBarType eType)
: ::Window (pParent->GetWindow(), WB_TABSTOP),
TreeNode(pParent),
msTitle (rTitle),
mbVisible (true),
mpUserData (NULL),
mpControlFactory(pControlFactory),
mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
new TitleBar (this, rTitle, eType, true)));
// The second control is created on demand, i.e. when GetControl(true)
// is called the first time.
SetBackground (Wallpaper());
GetTitleBar()->GetWindow()->Show ();
GetTitleBar()->GetWindow()->AddEventListener (
LINK(this,TitledControl,WindowEventListener));
UpdateStates ();
}
TitledControl::~TitledControl (void)
{
GetTitleBar()->GetWindow()->RemoveEventListener (
LINK(this,TitledControl,WindowEventListener));
}
Size TitledControl::GetPreferredSize (void)
{
Size aPreferredSize;
if (GetControl(false) != NULL)
{
aPreferredSize = GetControl()->GetPreferredSize();
if ( ! IsExpanded())
aPreferredSize.Height() = 0;
}
else
aPreferredSize = Size (GetSizePixel().Width(), 0);
if (aPreferredSize.Width() == 0)
aPreferredSize.Width() = 300;
aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
aPreferredSize.Width());
return aPreferredSize;
}
sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
int nPreferredWidth = 0;
if (GetControl(false) != NULL)
nPreferredWidth = GetControl()->GetPreferredWidth(
nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
else
nPreferredWidth = GetSizePixel().Width();
if (nPreferredWidth == 0)
nPreferredWidth = 300;
return nPreferredWidth;
}
sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
int nPreferredHeight = 0;
if (IsExpanded() && GetControl(false)!=NULL)
nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);
return nPreferredHeight;
}
bool TitledControl::IsResizable (void)
{
return IsExpanded()
&& GetControl()->IsResizable();
}
::Window* TitledControl::GetWindow (void)
{
return this;
}
void TitledControl::Resize (void)
{
Size aWindowSize (GetOutputSizePixel());
int nTitleBarHeight
= GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
GetTitleBar()->GetWindow()->SetPosSizePixel (
Point (0,0),
Size (aWindowSize.Width(), nTitleBarHeight));
TreeNode* pControl = GetControl(false);
if (pControl != NULL
&& pControl->GetWindow() != NULL
&& pControl->GetWindow()->IsVisible())
{
pControl->GetWindow()->SetPosSizePixel (
Point (0,nTitleBarHeight),
Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
}
}
void TitledControl::GetFocus (void)
{
::Window::GetFocus();
if (GetTitleBar() != NULL)
GetTitleBar()->SetFocus (true);
}
void TitledControl::LoseFocus (void)
{
::Window::LoseFocus();
if (GetTitleBar() != NULL)
GetTitleBar()->SetFocus (false);
}
void TitledControl::KeyInput (const KeyEvent& rEvent)
{
KeyCode nCode = rEvent.GetKeyCode();
if (nCode == KEY_SPACE)
{
// Toggle the expansion state of the control (when toggling is
// supported.) The focus remains on this control.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
ControlContainer::ES_TOGGLE);
}
else if (nCode == KEY_RETURN)
{
// Return, also called enter, enters the control and puts the
// focus to the first child. If the control is not yet
// expanded then do that first.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
ControlContainer::ES_EXPAND);
if ( ! FocusManager::Instance().TransferFocus(this,nCode))
{
// When already expanded then put focus on first child.
TreeNode* pControl = GetControl(false);
if (pControl!=NULL && IsExpanded())
if (pControl->GetWindow() != NULL)
pControl->GetWindow()->GrabFocus();
}
}
else if (nCode == KEY_ESCAPE)
{
if ( ! FocusManager::Instance().TransferFocus(this,nCode))
// Put focus to parent.
GetParent()->GrabFocus();
}
else
Window::KeyInput (rEvent);
}
const String& TitledControl::GetTitle (void) const
{
return msTitle;
}
bool TitledControl::Expand (bool bExpanded)
{
bool bExpansionStateChanged (false);
if (IsExpandable())
{
if (GetTitleBar()->IsExpanded() != bExpanded)
bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
// Get the control. Use the bExpanded parameter as argument to
// indicate that a control is created via its factory only when it
// is to be expanded. When it is collapsed this is not necessary.
TreeNode* pControl = GetControl(bExpanded);
if (pControl != NULL
&& GetControl()->IsExpanded() != bExpanded)
{
bExpansionStateChanged |= pControl->Expand (bExpanded);
}
if (bExpansionStateChanged)
UpdateStates();
}
return bExpansionStateChanged;
}
bool TitledControl::IsExpandable (void) const
{
const TreeNode* pControl = GetConstControl(false);
if (pControl != NULL)
return pControl->IsExpandable();
else
// When a control factory is given but the control has not yet been
// created we assume that the control is expandable.
return true;
}
bool TitledControl::IsExpanded (void) const
{
const TreeNode* pControl = GetConstControl(false);
if (pControl != NULL)
return pControl->IsExpanded();
else
return false;
}
void TitledControl::SetUserData (void* pUserData)
{
mpUserData = pUserData;
}
void* TitledControl::GetUserData (void) const
{
return mpUserData;
}
bool TitledControl::IsShowing (void) const
{
return mbVisible;
}
void TitledControl::Show (bool bVisible)
{
if (mbVisible != bVisible)
{
mbVisible = bVisible;
UpdateStates ();
}
}
void TitledControl::UpdateStates (void)
{
if (mbVisible)
GetWindow()->Show();
else
GetWindow()->Hide();
TreeNode* pControl = GetControl(false);
if (pControl!=NULL && pControl->GetWindow() != NULL)
if (IsVisible() && IsExpanded())
pControl->GetWindow()->Show();
else
pControl->GetWindow()->Hide();
}
IMPL_LINK(TitledControl, WindowEventListener,
VclSimpleEvent*, pEvent)
{
if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
{
VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
switch (pWindowEvent->GetId())
{
case VCLEVENT_WINDOW_MOUSEBUTTONUP:
// Toggle expansion.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
mbExpansionModeIsToggle ? ControlContainer::ES_TOGGLE
: ControlContainer::ES_EXPAND);
break;
}
}
return 0;
}
TreeNode* TitledControl::GetControl (bool bCreate)
{
TreeNode* pNode = mpControlContainer->GetControl(1);
if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
{
// We have to create the control with the factory object.
::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
if (pControl.get() != NULL)
{
pControl->SetParentNode(this);
mpControlContainer->AddControl(pControl);
pNode = mpControlContainer->GetControl(1);
FocusManager::Instance().RegisterDownLink(this, pNode->GetWindow());
FocusManager::Instance().RegisterUpLink(pNode->GetWindow(), this);
}
}
return pNode;
}
const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
return const_cast<TitledControl*>(this)->GetControl(bCreate);
}
TitleBar* TitledControl::GetTitleBar (void)
{
return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> TitledControl::CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent)
{
return new ::accessibility::AccessibleTreeNode(
*this,
GetTitle(),
GetTitle(),
::com::sun::star::accessibility::AccessibleRole::LIST_ITEM);
}
} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.11.38); FILE MERGED 2006/11/22 12:42:16 cl 1.11.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TitledControl.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2006-12-12 18:44:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "taskpane/TitledControl.hxx"
#include "AccessibleTreeNode.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
namespace sd { namespace toolpanel {
TitledControl::TitledControl (
TreeNode* pParent,
::std::auto_ptr<TreeNode> pControl,
const String& rTitle,
TitleBar::TitleBarType eType)
: ::Window (pParent->GetWindow(), WB_TABSTOP),
TreeNode(pParent),
msTitle(rTitle),
mbVisible(true),
mpUserData(NULL),
mpControlFactory(NULL),
mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
if (pControl.get() != NULL)
{
mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
pControl->SetParentNode (this);
}
mpControlContainer->AddControl (pControl);
FocusManager::Instance().RegisterDownLink(this, GetControl()->GetWindow());
FocusManager::Instance().RegisterUpLink(GetControl()->GetWindow(), this);
SetBackground (Wallpaper());
GetTitleBar()->GetWindow()->Show ();
GetTitleBar()->GetWindow()->AddEventListener (
LINK(this,TitledControl,WindowEventListener));
UpdateStates ();
}
TitledControl::TitledControl (
TreeNode* pParent,
::std::auto_ptr<ControlFactory> pControlFactory,
const String& rTitle,
TitleBar::TitleBarType eType)
: ::Window (pParent->GetWindow(), WB_TABSTOP),
TreeNode(pParent),
msTitle (rTitle),
mbVisible (true),
mpUserData (NULL),
mpControlFactory(pControlFactory),
mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
new TitleBar (this, rTitle, eType, true)));
// The second control is created on demand, i.e. when GetControl(true)
// is called the first time.
SetBackground (Wallpaper());
GetTitleBar()->GetWindow()->Show ();
GetTitleBar()->GetWindow()->AddEventListener (
LINK(this,TitledControl,WindowEventListener));
UpdateStates ();
}
TitledControl::~TitledControl (void)
{
GetTitleBar()->GetWindow()->RemoveEventListener (
LINK(this,TitledControl,WindowEventListener));
}
Size TitledControl::GetPreferredSize (void)
{
Size aPreferredSize;
if (GetControl(false) != NULL)
{
aPreferredSize = GetControl()->GetPreferredSize();
if ( ! IsExpanded())
aPreferredSize.Height() = 0;
}
else
aPreferredSize = Size (GetSizePixel().Width(), 0);
if (aPreferredSize.Width() == 0)
aPreferredSize.Width() = 300;
aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
aPreferredSize.Width());
return aPreferredSize;
}
sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
int nPreferredWidth = 0;
if (GetControl(false) != NULL)
nPreferredWidth = GetControl()->GetPreferredWidth(
nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
else
nPreferredWidth = GetSizePixel().Width();
if (nPreferredWidth == 0)
nPreferredWidth = 300;
return nPreferredWidth;
}
sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
int nPreferredHeight = 0;
if (IsExpanded() && GetControl(false)!=NULL)
nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);
return nPreferredHeight;
}
bool TitledControl::IsResizable (void)
{
return IsExpanded()
&& GetControl()->IsResizable();
}
::Window* TitledControl::GetWindow (void)
{
return this;
}
void TitledControl::Resize (void)
{
Size aWindowSize (GetOutputSizePixel());
int nTitleBarHeight
= GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
GetTitleBar()->GetWindow()->SetPosSizePixel (
Point (0,0),
Size (aWindowSize.Width(), nTitleBarHeight));
TreeNode* pControl = GetControl(false);
if (pControl != NULL
&& pControl->GetWindow() != NULL
&& pControl->GetWindow()->IsVisible())
{
pControl->GetWindow()->SetPosSizePixel (
Point (0,nTitleBarHeight),
Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
}
}
void TitledControl::GetFocus (void)
{
::Window::GetFocus();
if (GetTitleBar() != NULL)
GetTitleBar()->SetFocus (true);
}
void TitledControl::LoseFocus (void)
{
::Window::LoseFocus();
if (GetTitleBar() != NULL)
GetTitleBar()->SetFocus (false);
}
void TitledControl::KeyInput (const KeyEvent& rEvent)
{
KeyCode nCode = rEvent.GetKeyCode();
if (nCode == KEY_SPACE)
{
// Toggle the expansion state of the control (when toggling is
// supported.) The focus remains on this control.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
ControlContainer::ES_TOGGLE);
}
else if (nCode == KEY_RETURN)
{
// Return, also called enter, enters the control and puts the
// focus to the first child. If the control is not yet
// expanded then do that first.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
ControlContainer::ES_EXPAND);
if ( ! FocusManager::Instance().TransferFocus(this,nCode))
{
// When already expanded then put focus on first child.
TreeNode* pControl = GetControl(false);
if (pControl!=NULL && IsExpanded())
if (pControl->GetWindow() != NULL)
pControl->GetWindow()->GrabFocus();
}
}
else if (nCode == KEY_ESCAPE)
{
if ( ! FocusManager::Instance().TransferFocus(this,nCode))
// Put focus to parent.
GetParent()->GrabFocus();
}
else
Window::KeyInput (rEvent);
}
const String& TitledControl::GetTitle (void) const
{
return msTitle;
}
bool TitledControl::Expand (bool bExpanded)
{
bool bExpansionStateChanged (false);
if (IsExpandable())
{
if (GetTitleBar()->IsExpanded() != bExpanded)
bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
// Get the control. Use the bExpanded parameter as argument to
// indicate that a control is created via its factory only when it
// is to be expanded. When it is collapsed this is not necessary.
TreeNode* pControl = GetControl(bExpanded);
if (pControl != NULL
&& GetControl()->IsExpanded() != bExpanded)
{
bExpansionStateChanged |= pControl->Expand (bExpanded);
}
if (bExpansionStateChanged)
UpdateStates();
}
return bExpansionStateChanged;
}
bool TitledControl::IsExpandable (void) const
{
const TreeNode* pControl = GetConstControl(false);
if (pControl != NULL)
return pControl->IsExpandable();
else
// When a control factory is given but the control has not yet been
// created we assume that the control is expandable.
return true;
}
bool TitledControl::IsExpanded (void) const
{
const TreeNode* pControl = GetConstControl(false);
if (pControl != NULL)
return pControl->IsExpanded();
else
return false;
}
void TitledControl::SetUserData (void* pUserData)
{
mpUserData = pUserData;
}
void* TitledControl::GetUserData (void) const
{
return mpUserData;
}
bool TitledControl::IsShowing (void) const
{
return mbVisible;
}
void TitledControl::Show (bool bVisible)
{
if (mbVisible != bVisible)
{
mbVisible = bVisible;
UpdateStates ();
}
}
void TitledControl::UpdateStates (void)
{
if (mbVisible)
GetWindow()->Show();
else
GetWindow()->Hide();
TreeNode* pControl = GetControl(false);
if (pControl!=NULL && pControl->GetWindow() != NULL)
if (IsVisible() && IsExpanded())
pControl->GetWindow()->Show();
else
pControl->GetWindow()->Hide();
}
IMPL_LINK(TitledControl, WindowEventListener,
VclSimpleEvent*, pEvent)
{
if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
{
VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
switch (pWindowEvent->GetId())
{
case VCLEVENT_WINDOW_MOUSEBUTTONUP:
// Toggle expansion.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
mbExpansionModeIsToggle ? ControlContainer::ES_TOGGLE
: ControlContainer::ES_EXPAND);
break;
}
}
return 0;
}
TreeNode* TitledControl::GetControl (bool bCreate)
{
TreeNode* pNode = mpControlContainer->GetControl(1);
if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
{
// We have to create the control with the factory object.
::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
if (pControl.get() != NULL)
{
pControl->SetParentNode(this);
mpControlContainer->AddControl(pControl);
pNode = mpControlContainer->GetControl(1);
FocusManager::Instance().RegisterDownLink(this, pNode->GetWindow());
FocusManager::Instance().RegisterUpLink(pNode->GetWindow(), this);
}
}
return pNode;
}
const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
return const_cast<TitledControl*>(this)->GetControl(bCreate);
}
TitleBar* TitledControl::GetTitleBar (void)
{
return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> TitledControl::CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& )
{
return new ::accessibility::AccessibleTreeNode(
*this,
GetTitle(),
GetTitle(),
::com::sun::star::accessibility::AccessibleRole::LIST_ITEM);
}
} } // end of namespace ::sd::toolpanel
<|endoftext|> |
<commit_before>#pragma once
#include "xson/object.hpp"
#include "xson/trace.hpp"
#include "xson/fast/decoder.hpp"
namespace xson {
namespace fson {
class decoder : public fast::decoder
{
public:
decoder(std::istream& is) : fast::decoder(is)
{}
using fast::decoder::decode;
void decode(double& d)
{
union{
std::uint64_t i64;
double d64;
} i2d;
decode(i2d.i64);
d = i2d.d64;
}
void decode(bool& b)
{
std::uint8_t byte;
decode(byte);
b = static_cast<bool>(byte);
}
void decode(std::chrono::system_clock::time_point& tp)
{
using namespace std::chrono;
std::int64_t i64;
decode(i64);
tp = system_clock::time_point{milliseconds{i64}};
}
void decode(object& parent)
{
std::uint8_t byte;
decode(byte);
while(byte != xson::eod && m_is)
{
xson::type type = static_cast<xson::type>(byte);
std::string name;
decode(name);
auto& child = parent[name];
std::int32_t i32;
std::int64_t i64;
double d;
std::string str;
bool b;
std::chrono::system_clock::time_point tp;
switch(type)
{
case type::object:
case type::array:
decode(child);
child.type(type);
break;
case type::int32:
decode(i32);
child.value(i32);
break;
case type::int64:
decode(i64);
child.value(i64);
break;
case type::number:
decode(d);
child.value(d);
break;
case type::string:
decode(str);
child.value(str);
break;
case type::boolean:
decode(b);
child.value(b);
break;
case type::date:
decode(tp);
child.value(tp);
break;
case type::null:
child.value(nullptr);
break;
}
decode(byte);
}
}
};
inline std::istream& operator >> (std::istream& is, object& ob)
{
decoder{is}.decode(ob);
return is;
}
} // namespace fson
} // namespace xson
<commit_msg>Clean up<commit_after>#pragma once
#include "xson/object.hpp"
#include "xson/fast/decoder.hpp"
namespace xson {
namespace fson {
class decoder : public fast::decoder
{
public:
decoder(std::istream& is) : fast::decoder(is)
{}
using fast::decoder::decode;
void decode(double& d)
{
union{
std::uint64_t i64;
double d64;
} i2d;
decode(i2d.i64);
d = i2d.d64;
}
void decode(bool& b)
{
std::uint8_t byte;
decode(byte);
b = static_cast<bool>(byte);
}
void decode(std::chrono::system_clock::time_point& tp)
{
using namespace std::chrono;
std::int64_t i64;
decode(i64);
tp = system_clock::time_point{milliseconds{i64}};
}
void decode(object& parent)
{
std::uint8_t byte;
decode(byte);
while(byte != xson::eod && m_is)
{
xson::type type = static_cast<xson::type>(byte);
std::string name;
decode(name);
auto& child = parent[name];
std::int32_t i32;
std::int64_t i64;
double d;
std::string str;
bool b;
std::chrono::system_clock::time_point tp;
switch(type)
{
case type::object:
case type::array:
decode(child);
child.type(type);
break;
case type::int32:
decode(i32);
child.value(i32);
break;
case type::int64:
decode(i64);
child.value(i64);
break;
case type::number:
decode(d);
child.value(d);
break;
case type::string:
decode(str);
child.value(str);
break;
case type::boolean:
decode(b);
child.value(b);
break;
case type::date:
decode(tp);
child.value(tp);
break;
case type::null:
child.value(nullptr);
break;
}
decode(byte);
}
}
};
inline std::istream& operator >> (std::istream& is, object& ob)
{
decoder{is}.decode(ob);
return is;
}
} // namespace fson
} // namespace xson
<|endoftext|> |
<commit_before>#include "entity/entity_network_remote_peer.h"
#include "entity/entity_network_session.h"
#include "halley/entity/entity_factory.h"
#include "halley/entity/world.h"
#include "halley/support/logger.h"
#include "halley/utils/algorithm.h"
class NetworkComponent;
using namespace Halley;
EntityNetworkRemotePeer::EntityNetworkRemotePeer(EntityNetworkSession& parent, NetworkSession::PeerId peerId)
: parent(&parent)
, peerId(peerId)
{}
NetworkSession::PeerId EntityNetworkRemotePeer::getPeerId() const
{
return peerId;
}
void EntityNetworkRemotePeer::sendEntities(Time t, gsl::span<const std::pair<EntityId, uint8_t>> entityIds, const EntityClientSharedData& clientData)
{
Expects(isAlive());
// Mark all as not alive
for (auto& e: outboundEntities) {
e.second.alive = false;
}
for (auto [entityId, ownerId]: entityIds) {
if (ownerId == peerId) {
// Don't send updates back to the owner
continue;
}
const auto entity = parent->getWorld().getEntity(entityId);
if (peerId == 0 || parent->isEntityInView(entity, clientData)) { // Always send to host
if (const auto iter = outboundEntities.find(entityId); iter == outboundEntities.end()) {
sendCreateEntity(entity);
} else {
sendUpdateEntity(t, iter->second, entity);
}
}
}
// Destroy dead entities
for (auto& e: outboundEntities) {
if (!e.second.alive) {
sendDestroyEntity(e.second);
}
}
std_ex::erase_if_value(outboundEntities, [](const OutboundEntity& e) { return !e.alive; });
if (!hasSentData) {
hasSentData = true;
onFirstDataBatchSent();
}
}
void EntityNetworkRemotePeer::receiveEntityPacket(NetworkSession::PeerId fromPeerId, EntityNetworkHeaderType type, InboundNetworkPacket packet)
{
Expects(isAlive());
EntityNetworkEntityHeader header;
packet.extractHeader(header);
const auto networkEntityId = header.entityId;
if (type == EntityNetworkHeaderType::Create) {
receiveCreateEntity(networkEntityId, packet.getBytes());
} else if (type == EntityNetworkHeaderType::Update) {
receiveUpdateEntity(networkEntityId, packet.getBytes());
} else if (type == EntityNetworkHeaderType::Destroy) {
receiveDestroyEntity(networkEntityId);
}
}
void EntityNetworkRemotePeer::destroy()
{
if (alive) {
if (parent->hasWorld()) {
auto& world = parent->getWorld();
for (const auto& [k, v] : inboundEntities) {
world.destroyEntity(v.worldId);
}
}
inboundEntities.clear();
alive = false;
}
}
bool EntityNetworkRemotePeer::isAlive() const
{
return alive;
}
uint16_t EntityNetworkRemotePeer::assignId()
{
for (uint16_t i = 0; i < std::numeric_limits<uint16_t>::max() - 1; ++i) {
const uint16_t id = i + nextId;
if (!allocatedOutboundIds.contains(id)) {
allocatedOutboundIds.insert(id);
nextId = id + 1;
return id;
}
}
throw Exception("Unable to allocate network id for entity.", HalleyExceptions::Network);
}
void EntityNetworkRemotePeer::sendCreateEntity(EntityRef entity)
{
OutboundEntity result;
result.networkId = assignId();
result.data = parent->getFactory().serializeEntity(entity, parent->getEntitySerializationOptions());
auto deltaData = parent->getFactory().entityDataToPrefabDelta(result.data, entity.getPrefab(), parent->getEntityDeltaOptions());
auto bytes = Serializer::toBytes(result.data, parent->getByteSerializationOptions());
const auto size = send(EntityNetworkHeaderType::Create, result.networkId, std::move(bytes));
outboundEntities[entity.getEntityId()] = std::move(result);
//Logger::logDev("Sending create " + entity.getName() + ": " + toString(size) + " bytes to peer " + toString(static_cast<int>(peerId)));
//Logger::logDev("Create:\n" + EntityData(deltaData).toYAML() + "\n");
}
void EntityNetworkRemotePeer::sendUpdateEntity(Time t, OutboundEntity& remote, EntityRef entity)
{
remote.alive = true; // Important: mark it back alive
remote.timeSinceSend += t;
if (remote.timeSinceSend < parent->getMinSendInterval()) {
return;
}
auto newData = parent->getFactory().serializeEntity(entity, parent->getEntitySerializationOptions());
auto deltaData = EntityDataDelta(remote.data, newData, parent->getEntityDeltaOptions());
if (deltaData.hasChange()) {
parent->onPreSendDelta(deltaData);
}
if (deltaData.hasChange()) {
remote.data = std::move(newData);
remote.timeSinceSend = 0;
auto bytes = Serializer::toBytes(deltaData, parent->getByteSerializationOptions());
const auto size = send(EntityNetworkHeaderType::Update, remote.networkId, std::move(bytes));
//Logger::logDev("Sending update " + entity.getName() + ": " + toString(size) + " bytes to peer " + toString(static_cast<int>(peerId)));
//Logger::logDev("Update:\n" + EntityData(deltaData).toYAML() + "\n");
}
}
void EntityNetworkRemotePeer::sendDestroyEntity(OutboundEntity& remote)
{
allocatedOutboundIds.erase(remote.networkId);
send(EntityNetworkHeaderType::Destroy, remote.networkId, Bytes());
//Logger::logDev("Sending destroy entity to peer " + toString(static_cast<int>(peerId)));
}
size_t EntityNetworkRemotePeer::send(EntityNetworkHeaderType type, EntityNetworkId networkId, Bytes data)
{
// TODO: compress them into one update?
const size_t size = data.size() + 3;
auto packet = OutboundNetworkPacket(std::move(data));
packet.addHeader(EntityNetworkEntityHeader(networkId));
packet.addHeader(EntityNetworkHeader(type));
parent->getSession().sendToPeer(packet, peerId);
return size;
}
void EntityNetworkRemotePeer::receiveCreateEntity(EntityNetworkId id, gsl::span<const gsl::byte> data)
{
const auto iter = inboundEntities.find(id);
if (iter != inboundEntities.end()) {
Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " already exists from peer " + toString(static_cast<int>(peerId)));
return;
}
auto delta = Deserializer::fromBytes<EntityDataDelta>(data, parent->getByteSerializationOptions());
auto [entityData, prefab, prefabUUID] = parent->getFactory().prefabDeltaToEntityData(delta);
auto [entity, parentUUID] = parent->getFactory().loadEntityDelta(delta, {});
if (parentUUID) {
if (auto parentEntity = parent->getWorld().findEntity(parentUUID.value()); parentEntity) {
entity.setParent(parentEntity.value());
}
}
//Logger::logDev("Instantiating from network:\n" + entityData.toYAML());
entity.setupNetwork(peerId);
InboundEntity remote;
remote.data = std::move(entityData);
remote.worldId = entity.getEntityId();
inboundEntities[id] = std::move(remote);
parent->onRemoteEntityCreated(entity, peerId);
}
void EntityNetworkRemotePeer::receiveUpdateEntity(EntityNetworkId id, gsl::span<const gsl::byte> data)
{
const auto iter = inboundEntities.find(id);
if (iter == inboundEntities.end()) {
Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not found from peer " + toString(static_cast<int>(peerId)));
return;
}
auto& remote = iter->second;
auto entity = parent->getWorld().getEntity(remote.worldId);
if (!entity.isValid()) {
Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not alive in the world from peer " + toString(static_cast<int>(peerId)));
return;
}
auto delta = Deserializer::fromBytes<EntityDataDelta>(data, parent->getByteSerializationOptions());
parent->getFactory().updateEntity(entity, delta, static_cast<int>(EntitySerialization::Type::SaveData));
remote.data.applyDelta(delta);
}
void EntityNetworkRemotePeer::receiveDestroyEntity(EntityNetworkId id)
{
const auto iter = inboundEntities.find(id);
if (iter == inboundEntities.end()) {
Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not found from peer " + toString(static_cast<int>(peerId)));
return;
}
auto& remote = iter->second;
parent->getWorld().destroyEntity(remote.worldId);
inboundEntities.erase(id);
}
void EntityNetworkRemotePeer::onFirstDataBatchSent()
{
if (parent->getSession().getType() == NetworkSessionType::Host) {
auto packet = OutboundNetworkPacket(Bytes());
packet.addHeader(EntityNetworkHeader(EntityNetworkHeaderType::ReadyToStart));
parent->getSession().sendToPeer(packet, peerId);
}
}
<commit_msg>Fix creating entities over the network<commit_after>#include "entity/entity_network_remote_peer.h"
#include "entity/entity_network_session.h"
#include "halley/entity/entity_factory.h"
#include "halley/entity/world.h"
#include "halley/support/logger.h"
#include "halley/utils/algorithm.h"
class NetworkComponent;
using namespace Halley;
EntityNetworkRemotePeer::EntityNetworkRemotePeer(EntityNetworkSession& parent, NetworkSession::PeerId peerId)
: parent(&parent)
, peerId(peerId)
{}
NetworkSession::PeerId EntityNetworkRemotePeer::getPeerId() const
{
return peerId;
}
void EntityNetworkRemotePeer::sendEntities(Time t, gsl::span<const std::pair<EntityId, uint8_t>> entityIds, const EntityClientSharedData& clientData)
{
Expects(isAlive());
// Mark all as not alive
for (auto& e: outboundEntities) {
e.second.alive = false;
}
for (auto [entityId, ownerId]: entityIds) {
if (ownerId == peerId) {
// Don't send updates back to the owner
continue;
}
const auto entity = parent->getWorld().getEntity(entityId);
if (peerId == 0 || parent->isEntityInView(entity, clientData)) { // Always send to host
if (const auto iter = outboundEntities.find(entityId); iter == outboundEntities.end()) {
sendCreateEntity(entity);
} else {
sendUpdateEntity(t, iter->second, entity);
}
}
}
// Destroy dead entities
for (auto& e: outboundEntities) {
if (!e.second.alive) {
sendDestroyEntity(e.second);
}
}
std_ex::erase_if_value(outboundEntities, [](const OutboundEntity& e) { return !e.alive; });
if (!hasSentData) {
hasSentData = true;
onFirstDataBatchSent();
}
}
void EntityNetworkRemotePeer::receiveEntityPacket(NetworkSession::PeerId fromPeerId, EntityNetworkHeaderType type, InboundNetworkPacket packet)
{
Expects(isAlive());
EntityNetworkEntityHeader header;
packet.extractHeader(header);
const auto networkEntityId = header.entityId;
if (type == EntityNetworkHeaderType::Create) {
receiveCreateEntity(networkEntityId, packet.getBytes());
} else if (type == EntityNetworkHeaderType::Update) {
receiveUpdateEntity(networkEntityId, packet.getBytes());
} else if (type == EntityNetworkHeaderType::Destroy) {
receiveDestroyEntity(networkEntityId);
}
}
void EntityNetworkRemotePeer::destroy()
{
if (alive) {
if (parent->hasWorld()) {
auto& world = parent->getWorld();
for (const auto& [k, v] : inboundEntities) {
world.destroyEntity(v.worldId);
}
}
inboundEntities.clear();
alive = false;
}
}
bool EntityNetworkRemotePeer::isAlive() const
{
return alive;
}
uint16_t EntityNetworkRemotePeer::assignId()
{
for (uint16_t i = 0; i < std::numeric_limits<uint16_t>::max() - 1; ++i) {
const uint16_t id = i + nextId;
if (!allocatedOutboundIds.contains(id)) {
allocatedOutboundIds.insert(id);
nextId = id + 1;
return id;
}
}
throw Exception("Unable to allocate network id for entity.", HalleyExceptions::Network);
}
void EntityNetworkRemotePeer::sendCreateEntity(EntityRef entity)
{
OutboundEntity result;
result.networkId = assignId();
result.data = parent->getFactory().serializeEntity(entity, parent->getEntitySerializationOptions());
auto deltaData = parent->getFactory().entityDataToPrefabDelta(result.data, entity.getPrefab(), parent->getEntityDeltaOptions());
auto bytes = Serializer::toBytes(deltaData, parent->getByteSerializationOptions());
const auto size = send(EntityNetworkHeaderType::Create, result.networkId, std::move(bytes));
outboundEntities[entity.getEntityId()] = std::move(result);
//Logger::logDev("Sending create " + entity.getName() + ": " + toString(size) + " bytes to peer " + toString(static_cast<int>(peerId)));
//Logger::logDev("Create:\n" + EntityData(deltaData).toYAML() + "\n");
}
void EntityNetworkRemotePeer::sendUpdateEntity(Time t, OutboundEntity& remote, EntityRef entity)
{
remote.alive = true; // Important: mark it back alive
remote.timeSinceSend += t;
if (remote.timeSinceSend < parent->getMinSendInterval()) {
return;
}
auto newData = parent->getFactory().serializeEntity(entity, parent->getEntitySerializationOptions());
auto deltaData = EntityDataDelta(remote.data, newData, parent->getEntityDeltaOptions());
if (deltaData.hasChange()) {
parent->onPreSendDelta(deltaData);
}
if (deltaData.hasChange()) {
remote.data = std::move(newData);
remote.timeSinceSend = 0;
auto bytes = Serializer::toBytes(deltaData, parent->getByteSerializationOptions());
const auto size = send(EntityNetworkHeaderType::Update, remote.networkId, std::move(bytes));
//Logger::logDev("Sending update " + entity.getName() + ": " + toString(size) + " bytes to peer " + toString(static_cast<int>(peerId)));
//Logger::logDev("Update:\n" + EntityData(deltaData).toYAML() + "\n");
}
}
void EntityNetworkRemotePeer::sendDestroyEntity(OutboundEntity& remote)
{
allocatedOutboundIds.erase(remote.networkId);
send(EntityNetworkHeaderType::Destroy, remote.networkId, Bytes());
//Logger::logDev("Sending destroy entity to peer " + toString(static_cast<int>(peerId)));
}
size_t EntityNetworkRemotePeer::send(EntityNetworkHeaderType type, EntityNetworkId networkId, Bytes data)
{
// TODO: compress them into one update?
const size_t size = data.size() + 3;
auto packet = OutboundNetworkPacket(std::move(data));
packet.addHeader(EntityNetworkEntityHeader(networkId));
packet.addHeader(EntityNetworkHeader(type));
parent->getSession().sendToPeer(packet, peerId);
return size;
}
void EntityNetworkRemotePeer::receiveCreateEntity(EntityNetworkId id, gsl::span<const gsl::byte> data)
{
const auto iter = inboundEntities.find(id);
if (iter != inboundEntities.end()) {
Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " already exists from peer " + toString(static_cast<int>(peerId)));
return;
}
const auto delta = Deserializer::fromBytes<EntityDataDelta>(data, parent->getByteSerializationOptions());
//Logger::logDev("Instantiating from network (" + toString(data.size()) + " bytes):\n\n" + EntityData(delta).toYAML());
auto [entityData, prefab, prefabUUID] = parent->getFactory().prefabDeltaToEntityData(delta);
auto [entity, parentUUID] = parent->getFactory().loadEntityDelta(delta, {});
if (parentUUID) {
if (auto parentEntity = parent->getWorld().findEntity(parentUUID.value()); parentEntity) {
entity.setParent(parentEntity.value());
}
}
entity.setupNetwork(peerId);
InboundEntity remote;
remote.data = std::move(entityData);
remote.worldId = entity.getEntityId();
inboundEntities[id] = std::move(remote);
parent->onRemoteEntityCreated(entity, peerId);
}
void EntityNetworkRemotePeer::receiveUpdateEntity(EntityNetworkId id, gsl::span<const gsl::byte> data)
{
const auto iter = inboundEntities.find(id);
if (iter == inboundEntities.end()) {
Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not found from peer " + toString(static_cast<int>(peerId)));
return;
}
auto& remote = iter->second;
auto entity = parent->getWorld().getEntity(remote.worldId);
if (!entity.isValid()) {
Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not alive in the world from peer " + toString(static_cast<int>(peerId)));
return;
}
auto delta = Deserializer::fromBytes<EntityDataDelta>(data, parent->getByteSerializationOptions());
parent->getFactory().updateEntity(entity, delta, static_cast<int>(EntitySerialization::Type::SaveData));
remote.data.applyDelta(delta);
}
void EntityNetworkRemotePeer::receiveDestroyEntity(EntityNetworkId id)
{
const auto iter = inboundEntities.find(id);
if (iter == inboundEntities.end()) {
Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not found from peer " + toString(static_cast<int>(peerId)));
return;
}
auto& remote = iter->second;
parent->getWorld().destroyEntity(remote.worldId);
inboundEntities.erase(id);
}
void EntityNetworkRemotePeer::onFirstDataBatchSent()
{
if (parent->getSession().getType() == NetworkSessionType::Host) {
auto packet = OutboundNetworkPacket(Bytes());
packet.addHeader(EntityNetworkHeader(EntityNetworkHeaderType::ReadyToStart));
parent->getSession().sendToPeer(packet, peerId);
}
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
// PCL specific includes
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
ros::Publisher pub;
// How to avoid hard-coding a topic name?
void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& input) {
// Create a container for the data.
sensor_msgs::PointCloud2 output;
/* Do data processing here...*/
output = *input; // modify input
// Publish the data.
pub.publish(output);
}
int main (int argc, char** argv) {
// Initialize ROS
ros::init (argc, argv, "my_pcl_tutorial");
ros::NodeHandle nh;
// Create a ROS subscriber for the input point cloud
// when topic /input is incoming, cloud_cb callback is called
ros::Subscriber sub = nh.subscribe("assemble_cloud", 1, cloud_cb);
// Create a ROS publisher for the output point cloud
// A node has both of publisheres and subscribers.
pub = nh.advertise<sensor_msgs::PointCloud2>("output", 1);
// Spin
ros::spin();
}
<commit_msg>Deleted one file.<commit_after><|endoftext|> |
<commit_before>#ifndef __sitksimpletransformix_cxx_
#define __sitksimpletransformix_cxx_
#include "sitkSimpleTransformix.h"
#include "sitkSimpleTransformix.hxx"
namespace itk {
namespace simple {
SimpleTransformix
::SimpleTransformix( void )
{
// Register this class with SimpleITK
this->m_MemberFactory.reset( new detail::MemberFunctionFactory< MemberFunctionType >( this ) );
this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 2 >();
this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 3 >();
#ifdef SITK_4D_IMAGES
m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 4 >();
#endif
this->SetInputImage( Image() );
this->ComputeSpatialJacobianOff();
this->ComputeDeterminantOfSpatialJacobianOff();
this->ComputeDeformationFieldOff();
this->m_OutputDirectory = ".";
this->m_LogFileName = std::string();
this->LogToFileOff();
this->LogToConsoleOff();
m_ResultImage = Image();
}
SimpleTransformix
::~SimpleTransformix( void )
{
}
const std::string
SimpleTransformix
::GetName( void )
{
const std::string name = std::string( "SimpleTransformix" );
return name;
}
SimpleTransformix::Self&
SimpleTransformix
::SetInputImage( const Image& inputImage )
{
this->m_InputImage = inputImage;
return *this;
}
Image&
SimpleTransformix
::GetInputImage( void )
{
return this->m_InputImage;
}
SimpleTransformix::Self&
SimpleTransformix
::SetInputPointSetFileName( const std::string inputPointSetFileName )
{
this->m_InputPointSetFileName = inputPointSetFileName;
return *this;
}
std::string
SimpleTransformix
::GetInputPointSetFileName( void )
{
return this->m_InputPointSetFileName;
}
SimpleTransformix::Self&
SimpleTransformix
::RemoveInputPointSetFileName( void )
{
this->m_InputPointSetFileName = std::string();
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetComputeSpatialJacobian( const bool computeSpatialJacobian )
{
this->m_ComputeSpatialJacobian = computeSpatialJacobian;
return *this;
}
bool
SimpleTransformix
::GetComputeSpatialJacobian( void )
{
return this->m_ComputeSpatialJacobian;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeSpatialJacobianOn( void )
{
this->SetComputeSpatialJacobian( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeSpatialJacobianOff( void )
{
this->SetComputeSpatialJacobian( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetComputeDeterminantOfSpatialJacobian( const bool computeDeterminantOfSpatialJacobian )
{
this->m_ComputeSpatialJacobian = computeDeterminantOfSpatialJacobian;
return *this;
}
bool
SimpleTransformix
::GetComputeDeterminantOfSpatialJacobian( void )
{
return this->m_ComputeDeterminantOfSpatialJacobian;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeDeterminantOfSpatialJacobianOn( void )
{
this->SetComputeDeterminantOfSpatialJacobian( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeDeterminantOfSpatialJacobianOff( void )
{
this->SetComputeDeterminantOfSpatialJacobian( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetComputeDeformationField( const bool computeDeformationField )
{
this->m_ComputeDeformationField = computeDeformationField;
return *this;
}
bool
SimpleTransformix
::GetComputeDeformationField( void )
{
return this->m_ComputeDeformationField;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeDeformationFieldOn( void )
{
this->SetComputeDeformationField( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeDeformationFieldOff( void )
{
this->SetComputeDeformationField( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetOutputDirectory( const std::string outputDirectory )
{
this->m_OutputDirectory = outputDirectory;
return *this;
}
std::string
SimpleTransformix
::GetOutputDirectory( void )
{
return this->m_OutputDirectory;
}
SimpleTransformix::Self&
SimpleTransformix
::RemoveOutputDirectory( void )
{
this->m_OutputDirectory = std::string();
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetLogFileName( std::string logFileName )
{
this->m_LogFileName = logFileName;
return *this;
}
std::string
SimpleTransformix
::GetLogFileName( void )
{
return this->m_LogFileName;
}
SimpleTransformix::Self&
SimpleTransformix
::RemoveLogFileName( void )
{
this->m_LogFileName = std::string();
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetLogToFile( bool logToFile )
{
this->m_LogToFile = logToFile;
return *this;
}
bool
SimpleTransformix
::GetLogToFile( void )
{
return this->m_LogToFile;
}
SimpleTransformix::Self&
SimpleTransformix
::LogToFileOn()
{
this->SetLogToFile( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::LogToFileOff()
{
this->SetLogToFile( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetLogToConsole( bool logToConsole )
{
this->m_LogToConsole = logToConsole;
return *this;
}
bool
SimpleTransformix
::GetLogToConsole( void )
{
return this->m_LogToConsole;
}
SimpleTransformix::Self&
SimpleTransformix
::LogToConsoleOn()
{
this->SetLogToConsole( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::LogToConsoleOff()
{
this->SetLogToConsole( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetTransformParameterMap( const ParameterMapVectorType parameterMapVector )
{
this->m_TransformParameterMapVector = parameterMapVector;
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetTransformParameterMap( const ParameterMapType parameterMap )
{
ParameterMapVectorType parameterMapVector;
parameterMapVector.push_back( parameterMap );
this->SetTransformParameterMap( parameterMapVector );
return *this;
}
SimpleTransformix::ParameterMapVectorType
SimpleTransformix
::GetTransformParameterMap( void )
{
return this->m_TransformParameterMapVector;
}
SimpleTransformix::ParameterMapType
SimpleTransformix
::ReadParameterFile( const std::string filename )
{
ParameterFileParserPointer parser = ParameterFileParserType::New();
parser->SetParameterFileName( filename );
try
{
parser->ReadParameterFile();
}
catch( itk::ExceptionObject &e )
{
std::cout << e.what() << std::endl;
}
return parser->GetParameterMap();
}
SimpleTransformix::Self&
SimpleTransformix
::WriteParameterFile( const ParameterMapType parameterMap, const std::string parameterFileName )
{
ParameterObjectPointer parameterObject = ParameterObjectType::New();
parameterObject->WriteParameterFile( parameterMap, parameterFileName );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( void )
{
this->PrettyPrint( this->GetTransformParameterMap() );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( const ParameterMapType parameterMap )
{
ParameterMapVectorType parameterMapVector = ParameterMapVectorType( 1 );
parameterMapVector[ 0 ] = parameterMap;
this->PrettyPrint( parameterMapVector );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( const ParameterMapVectorType parameterMapList )
{
for( unsigned int i = 0; i < parameterMapList.size(); ++i )
{
std::cout << "ParameterMap " << i << ": " << std::endl;
ParameterMapConstIterator parameterMapIterator = parameterMapList[ i ].begin();
ParameterMapConstIterator parameterMapIteratorEnd = parameterMapList[ i ].end();
while( parameterMapIterator != parameterMapIteratorEnd )
{
std::cout << " (" << parameterMapIterator->first;
ParameterValueVectorType parameterMapValueVector = parameterMapIterator->second;
for(unsigned int j = 0; j < parameterMapValueVector.size(); ++j)
{
std::stringstream stream( parameterMapValueVector[ j ] );
float number;
stream >> number;
if( stream.fail() ) {
std::cout << " \"" << parameterMapValueVector[ j ] << "\"";
}
else
{
std::cout << " " << number;
}
}
std::cout << ")" << std::endl;
parameterMapIterator++;
}
}
return *this;
}
Image
SimpleTransformix
::Execute( void )
{
const PixelIDValueEnum InputImagePixelEnum = this->m_InputImage.GetPixelID();
const unsigned int InputImageDimension = this->m_InputImage.GetDimension();
if( this->m_MemberFactory->HasMemberFunction( InputImagePixelEnum, InputImageDimension ) )
{
try {
return this->m_MemberFactory->GetMemberFunction( InputImagePixelEnum, InputImageDimension )();
} catch( itk::ExceptionObject &e ) {
sitkExceptionMacro( << e );
}
}
sitkExceptionMacro( << "SimpleTransformix does not support the combination of image type \""
<< GetPixelIDValueAsString( InputImagePixelEnum ) << "\" ("
<< GetPixelIDValueAsElastixParameter( InputImagePixelEnum ) << ") and dimension "
<< InputImageDimension << "." );
}
Image
SimpleTransformix
::GetResultImage( void )
{
if( this->IsEmpty( this->m_ResultImage ) )
{
sitkExceptionMacro( "No result image was found. Has transformix run yet?" )
}
return this->m_ResultImage;
}
bool
SimpleTransformix
::IsEmpty( const Image& image )
{
bool isEmpty = image.GetWidth() == 0 && image.GetHeight() == 0;
return isEmpty;
}
/**
* Procedural interface
*/
Image
Transformix( const Image& inputImage, const SimpleTransformix::ParameterMapType parameterMap, const bool logToConsole, const std::string outputDirectory )
{
SimpleTransformix::ParameterMapVectorType parameterMapVector;
parameterMapVector.push_back( parameterMap );
return Transformix( inputImage, parameterMapVector, logToConsole, outputDirectory );
}
Image
Transformix( const Image& inputImage, const SimpleTransformix::ParameterMapVectorType parameterMapVector, const bool logToConsole, const std::string outputDirectory )
{
SimpleTransformix stfx;
stfx.SetInputImage( inputImage );
stfx.SetTransformParameterMap( parameterMapVector );
stfx.SetOutputDirectory( outputDirectory );
stfx.LogToFileOn();
stfx.SetLogToConsole( logToConsole );
return stfx.Execute();
}
} // end namespace simple
} // end namespace itk
#endif // __sitksimpletransformix_cxx_<commit_msg>BUG: Fix setting ComputeDeterminantOfSpatialJacobian<commit_after>#ifndef __sitksimpletransformix_cxx_
#define __sitksimpletransformix_cxx_
#include "sitkSimpleTransformix.h"
#include "sitkSimpleTransformix.hxx"
namespace itk {
namespace simple {
SimpleTransformix
::SimpleTransformix( void )
{
// Register this class with SimpleITK
this->m_MemberFactory.reset( new detail::MemberFunctionFactory< MemberFunctionType >( this ) );
this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 2 >();
this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 3 >();
#ifdef SITK_4D_IMAGES
m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 4 >();
#endif
this->SetInputImage( Image() );
this->ComputeSpatialJacobianOff();
this->ComputeDeterminantOfSpatialJacobianOff();
this->ComputeDeformationFieldOff();
this->SetOutputDirectory( "" );
this->SetLogFileName( "" );
this->LogToFileOff();
this->LogToConsoleOff();
this->m_ResultImage = Image();
}
SimpleTransformix
::~SimpleTransformix( void )
{
}
const std::string
SimpleTransformix
::GetName( void )
{
const std::string name = std::string( "SimpleTransformix" );
return name;
}
SimpleTransformix::Self&
SimpleTransformix
::SetInputImage( const Image& inputImage )
{
this->m_InputImage = inputImage;
return *this;
}
Image&
SimpleTransformix
::GetInputImage( void )
{
return this->m_InputImage;
}
SimpleTransformix::Self&
SimpleTransformix
::SetInputPointSetFileName( const std::string inputPointSetFileName )
{
this->m_InputPointSetFileName = inputPointSetFileName;
return *this;
}
std::string
SimpleTransformix
::GetInputPointSetFileName( void )
{
return this->m_InputPointSetFileName;
}
SimpleTransformix::Self&
SimpleTransformix
::RemoveInputPointSetFileName( void )
{
this->m_InputPointSetFileName = std::string();
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetComputeSpatialJacobian( const bool computeSpatialJacobian )
{
this->m_ComputeSpatialJacobian = computeSpatialJacobian;
return *this;
}
bool
SimpleTransformix
::GetComputeSpatialJacobian( void )
{
return this->m_ComputeSpatialJacobian;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeSpatialJacobianOn( void )
{
this->SetComputeSpatialJacobian( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeSpatialJacobianOff( void )
{
this->SetComputeSpatialJacobian( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetComputeDeterminantOfSpatialJacobian( const bool computeDeterminantOfSpatialJacobian )
{
this->m_ComputeDeterminantOfSpatialJacobian = computeDeterminantOfSpatialJacobian;
return *this;
}
bool
SimpleTransformix
::GetComputeDeterminantOfSpatialJacobian( void )
{
return this->m_ComputeDeterminantOfSpatialJacobian;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeDeterminantOfSpatialJacobianOn( void )
{
this->SetComputeDeterminantOfSpatialJacobian( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeDeterminantOfSpatialJacobianOff( void )
{
this->SetComputeDeterminantOfSpatialJacobian( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetComputeDeformationField( const bool computeDeformationField )
{
this->m_ComputeDeformationField = computeDeformationField;
return *this;
}
bool
SimpleTransformix
::GetComputeDeformationField( void )
{
return this->m_ComputeDeformationField;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeDeformationFieldOn( void )
{
this->SetComputeDeformationField( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::ComputeDeformationFieldOff( void )
{
this->SetComputeDeformationField( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetOutputDirectory( const std::string outputDirectory )
{
this->m_OutputDirectory = outputDirectory;
return *this;
}
std::string
SimpleTransformix
::GetOutputDirectory( void )
{
return this->m_OutputDirectory;
}
SimpleTransformix::Self&
SimpleTransformix
::RemoveOutputDirectory( void )
{
this->m_OutputDirectory = std::string();
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetLogFileName( std::string logFileName )
{
this->m_LogFileName = logFileName;
return *this;
}
std::string
SimpleTransformix
::GetLogFileName( void )
{
return this->m_LogFileName;
}
SimpleTransformix::Self&
SimpleTransformix
::RemoveLogFileName( void )
{
this->m_LogFileName = std::string();
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetLogToFile( bool logToFile )
{
this->m_LogToFile = logToFile;
return *this;
}
bool
SimpleTransformix
::GetLogToFile( void )
{
return this->m_LogToFile;
}
SimpleTransformix::Self&
SimpleTransformix
::LogToFileOn()
{
this->SetLogToFile( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::LogToFileOff()
{
this->SetLogToFile( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetLogToConsole( bool logToConsole )
{
this->m_LogToConsole = logToConsole;
return *this;
}
bool
SimpleTransformix
::GetLogToConsole( void )
{
return this->m_LogToConsole;
}
SimpleTransformix::Self&
SimpleTransformix
::LogToConsoleOn()
{
this->SetLogToConsole( true );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::LogToConsoleOff()
{
this->SetLogToConsole( false );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetTransformParameterMap( const ParameterMapVectorType parameterMapVector )
{
this->m_TransformParameterMapVector = parameterMapVector;
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::SetTransformParameterMap( const ParameterMapType parameterMap )
{
ParameterMapVectorType parameterMapVector;
parameterMapVector.push_back( parameterMap );
this->SetTransformParameterMap( parameterMapVector );
return *this;
}
SimpleTransformix::ParameterMapVectorType
SimpleTransformix
::GetTransformParameterMap( void )
{
return this->m_TransformParameterMapVector;
}
SimpleTransformix::ParameterMapType
SimpleTransformix
::ReadParameterFile( const std::string filename )
{
ParameterFileParserPointer parser = ParameterFileParserType::New();
parser->SetParameterFileName( filename );
try
{
parser->ReadParameterFile();
}
catch( itk::ExceptionObject &e )
{
std::cout << e.what() << std::endl;
}
return parser->GetParameterMap();
}
SimpleTransformix::Self&
SimpleTransformix
::WriteParameterFile( const ParameterMapType parameterMap, const std::string parameterFileName )
{
ParameterObjectPointer parameterObject = ParameterObjectType::New();
parameterObject->WriteParameterFile( parameterMap, parameterFileName );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( void )
{
this->PrettyPrint( this->GetTransformParameterMap() );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( const ParameterMapType parameterMap )
{
ParameterMapVectorType parameterMapVector = ParameterMapVectorType( 1 );
parameterMapVector[ 0 ] = parameterMap;
this->PrettyPrint( parameterMapVector );
return *this;
}
SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( const ParameterMapVectorType parameterMapList )
{
for( unsigned int i = 0; i < parameterMapList.size(); ++i )
{
std::cout << "ParameterMap " << i << ": " << std::endl;
ParameterMapConstIterator parameterMapIterator = parameterMapList[ i ].begin();
ParameterMapConstIterator parameterMapIteratorEnd = parameterMapList[ i ].end();
while( parameterMapIterator != parameterMapIteratorEnd )
{
std::cout << " (" << parameterMapIterator->first;
ParameterValueVectorType parameterMapValueVector = parameterMapIterator->second;
for(unsigned int j = 0; j < parameterMapValueVector.size(); ++j)
{
std::stringstream stream( parameterMapValueVector[ j ] );
float number;
stream >> number;
if( stream.fail() ) {
std::cout << " \"" << parameterMapValueVector[ j ] << "\"";
}
else
{
std::cout << " " << number;
}
}
std::cout << ")" << std::endl;
parameterMapIterator++;
}
}
return *this;
}
Image
SimpleTransformix
::Execute( void )
{
const PixelIDValueEnum InputImagePixelEnum = this->m_InputImage.GetPixelID();
const unsigned int InputImageDimension = this->m_InputImage.GetDimension();
if( this->m_MemberFactory->HasMemberFunction( InputImagePixelEnum, InputImageDimension ) )
{
try {
return this->m_MemberFactory->GetMemberFunction( InputImagePixelEnum, InputImageDimension )();
} catch( itk::ExceptionObject &e ) {
sitkExceptionMacro( << e );
}
}
sitkExceptionMacro( << "SimpleTransformix does not support the combination of image type \""
<< GetPixelIDValueAsString( InputImagePixelEnum ) << "\" ("
<< GetPixelIDValueAsElastixParameter( InputImagePixelEnum ) << ") and dimension "
<< InputImageDimension << "." );
}
Image
SimpleTransformix
::GetResultImage( void )
{
if( this->IsEmpty( this->m_ResultImage ) )
{
sitkExceptionMacro( "No result image was found. Has transformix run yet?" )
}
return this->m_ResultImage;
}
bool
SimpleTransformix
::IsEmpty( const Image& image )
{
bool isEmpty = image.GetWidth() == 0 && image.GetHeight() == 0;
return isEmpty;
}
/**
* Procedural interface
*/
Image
Transformix( const Image& inputImage, const SimpleTransformix::ParameterMapType parameterMap, const bool logToConsole, const std::string outputDirectory )
{
SimpleTransformix::ParameterMapVectorType parameterMapVector;
parameterMapVector.push_back( parameterMap );
return Transformix( inputImage, parameterMapVector, logToConsole, outputDirectory );
}
Image
Transformix( const Image& inputImage, const SimpleTransformix::ParameterMapVectorType parameterMapVector, const bool logToConsole, const std::string outputDirectory )
{
SimpleTransformix stfx;
stfx.SetInputImage( inputImage );
stfx.SetTransformParameterMap( parameterMapVector );
stfx.SetOutputDirectory( outputDirectory );
stfx.LogToFileOn();
stfx.SetLogToConsole( logToConsole );
return stfx.Execute();
}
} // end namespace simple
} // end namespace itk
#endif // __sitksimpletransformix_cxx_<|endoftext|> |
<commit_before>// Modified from chromium/src/webkit/glue/gl_bindings_skia_cmd_buffer.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gl/GrGLInterface.h"
#include "gl/GrGLAssembleInterface.h"
#include "gl/GrGLExtensions.h"
#include "gl/GrGLUtil.h"
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
static GrGLInterface* create_es_interface(GrGLVersion version,
GrGLExtensions* extensions) {
if (version < GR_GL_VER(2,0)) {
return NULL;
}
GrGLInterface* interface = SkNEW(GrGLInterface);
interface->fStandard = kGLES_GrGLStandard;
GrGLInterface::Functions* functions = &interface->fFunctions;
functions->fActiveTexture = glActiveTexture;
functions->fAttachShader = glAttachShader;
functions->fBindAttribLocation = glBindAttribLocation;
functions->fBindBuffer = glBindBuffer;
functions->fBindTexture = glBindTexture;
functions->fBindVertexArray = glBindVertexArrayOES;
functions->fBlendColor = glBlendColor;
functions->fBlendFunc = glBlendFunc;
functions->fBufferData = glBufferData;
functions->fBufferSubData = glBufferSubData;
functions->fClear = glClear;
functions->fClearColor = glClearColor;
functions->fClearStencil = glClearStencil;
functions->fColorMask = glColorMask;
functions->fCompileShader = glCompileShader;
functions->fCompressedTexImage2D = glCompressedTexImage2D;
functions->fCopyTexSubImage2D = glCopyTexSubImage2D;
functions->fCreateProgram = glCreateProgram;
functions->fCreateShader = glCreateShader;
functions->fCullFace = glCullFace;
functions->fDeleteBuffers = glDeleteBuffers;
functions->fDeleteProgram = glDeleteProgram;
functions->fDeleteShader = glDeleteShader;
functions->fDeleteTextures = glDeleteTextures;
functions->fDeleteVertexArrays = glDeleteVertexArraysOES;
functions->fDepthMask = glDepthMask;
functions->fDisable = glDisable;
functions->fDisableVertexAttribArray = glDisableVertexAttribArray;
functions->fDrawArrays = glDrawArrays;
functions->fDrawElements = glDrawElements;
functions->fEnable = glEnable;
functions->fEnableVertexAttribArray = glEnableVertexAttribArray;
functions->fFinish = glFinish;
functions->fFlush = glFlush;
functions->fFrontFace = glFrontFace;
functions->fGenBuffers = glGenBuffers;
functions->fGenerateMipmap = glGenerateMipmap;
functions->fGenTextures = glGenTextures;
functions->fGenVertexArrays = glGenVertexArraysOES;
functions->fGetBufferParameteriv = glGetBufferParameteriv;
functions->fGetError = glGetError;
functions->fGetIntegerv = glGetIntegerv;
functions->fGetProgramInfoLog = glGetProgramInfoLog;
functions->fGetProgramiv = glGetProgramiv;
functions->fGetShaderInfoLog = glGetShaderInfoLog;
functions->fGetShaderiv = glGetShaderiv;
functions->fGetString = glGetString;
#if GL_ES_VERSION_3_0
functions->fGetStringi = glGetStringi;
#else
functions->fGetStringi = (GrGLGetStringiProc) eglGetProcAddress("glGetStringi");
#endif
functions->fGetUniformLocation = glGetUniformLocation;
functions->fLineWidth = glLineWidth;
functions->fLinkProgram = glLinkProgram;
functions->fPixelStorei = glPixelStorei;
functions->fReadPixels = glReadPixels;
functions->fScissor = glScissor;
#if GR_GL_USE_NEW_SHADER_SOURCE_SIGNATURE
functions->fShaderSource = (GrGLShaderSourceProc) glShaderSource;
#else
functions->fShaderSource = glShaderSource;
#endif
functions->fStencilFunc = glStencilFunc;
functions->fStencilFuncSeparate = glStencilFuncSeparate;
functions->fStencilMask = glStencilMask;
functions->fStencilMaskSeparate = glStencilMaskSeparate;
functions->fStencilOp = glStencilOp;
functions->fStencilOpSeparate = glStencilOpSeparate;
functions->fTexImage2D = glTexImage2D;
functions->fTexParameteri = glTexParameteri;
functions->fTexParameteriv = glTexParameteriv;
functions->fTexSubImage2D = glTexSubImage2D;
if (version >= GR_GL_VER(3,0)) {
#if GL_ES_VERSION_3_0
functions->fTexStorage2D = glTexStorage2D;
#else
functions->fTexStorage2D = (GrGLTexStorage2DProc) eglGetProcAddress("glTexStorage2D");
#endif
} else {
#if GL_EXT_texture_storage
functions->fTexStorage2D = glTexStorage2DEXT;
#else
functions->fTexStorage2D = (GrGLTexStorage2DProc) eglGetProcAddress("glTexStorage2DEXT");
#endif
}
#if GL_EXT_discard_framebuffer
functions->fDiscardFramebuffer = glDiscardFramebufferEXT;
#endif
functions->fUniform1f = glUniform1f;
functions->fUniform1i = glUniform1i;
functions->fUniform1fv = glUniform1fv;
functions->fUniform1iv = glUniform1iv;
functions->fUniform2f = glUniform2f;
functions->fUniform2i = glUniform2i;
functions->fUniform2fv = glUniform2fv;
functions->fUniform2iv = glUniform2iv;
functions->fUniform3f = glUniform3f;
functions->fUniform3i = glUniform3i;
functions->fUniform3fv = glUniform3fv;
functions->fUniform3iv = glUniform3iv;
functions->fUniform4f = glUniform4f;
functions->fUniform4i = glUniform4i;
functions->fUniform4fv = glUniform4fv;
functions->fUniform4iv = glUniform4iv;
functions->fUniformMatrix2fv = glUniformMatrix2fv;
functions->fUniformMatrix3fv = glUniformMatrix3fv;
functions->fUniformMatrix4fv = glUniformMatrix4fv;
functions->fUseProgram = glUseProgram;
functions->fVertexAttrib4fv = glVertexAttrib4fv;
functions->fVertexAttribPointer = glVertexAttribPointer;
functions->fViewport = glViewport;
functions->fBindFramebuffer = glBindFramebuffer;
functions->fBindRenderbuffer = glBindRenderbuffer;
functions->fCheckFramebufferStatus = glCheckFramebufferStatus;
functions->fDeleteFramebuffers = glDeleteFramebuffers;
functions->fDeleteRenderbuffers = glDeleteRenderbuffers;
functions->fFramebufferRenderbuffer = glFramebufferRenderbuffer;
functions->fFramebufferTexture2D = glFramebufferTexture2D;
if (version >= GR_GL_VER(3,0)) {
#if GL_ES_VERSION_3_0
functions->fRenderbufferStorageMultisample = glRenderbufferStorageMultisample;
functions->fBlitFramebuffer = glBlitFramebuffer;
#else
functions->fRenderbufferStorageMultisample = (GrGLRenderbufferStorageMultisampleProc) eglGetProcAddress("glRenderbufferStorageMultisample");
functions->fBlitFramebuffer = (GrGLBlitFramebufferProc) eglGetProcAddress("glBlitFramebuffer");
#endif
}
if (extensions->has("GL_EXT_multisampled_render_to_texture")) {
#if GL_EXT_multisampled_render_to_texture
functions->fFramebufferTexture2DMultisample = glFramebufferTexture2DMultisampleEXT;
functions->fRenderbufferStorageMultisampleES2EXT = glRenderbufferStorageMultisampleEXT;
#else
functions->fFramebufferTexture2DMultisample = (GrGLFramebufferTexture2DMultisampleProc) eglGetProcAddress("glFramebufferTexture2DMultisampleEXT");
functions->fRenderbufferStorageMultisampleES2EXT = (GrGLRenderbufferStorageMultisampleProc) eglGetProcAddress("glRenderbufferStorageMultisampleEXT");
#endif
} else if (extensions->has("GL_IMG_multisampled_render_to_texture")) {
#if GL_IMG_multisampled_render_to_texture
functions->fFramebufferTexture2DMultisample = glFramebufferTexture2DMultisampleIMG;
functions->fRenderbufferStorageMultisampleES2EXT = glRenderbufferStorageMultisampleIMG;
#else
functions->fFramebufferTexture2DMultisample = (GrGLFramebufferTexture2DMultisampleProc) eglGetProcAddress("glFramebufferTexture2DMultisampleIMG");
functions->fRenderbufferStorageMultisampleES2EXT = (GrGLRenderbufferStorageMultisampleProc) eglGetProcAddress("glRenderbufferStorageMultisampleIMG");
#endif
}
functions->fGenFramebuffers = glGenFramebuffers;
functions->fGenRenderbuffers = glGenRenderbuffers;
functions->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv;
functions->fGetRenderbufferParameteriv = glGetRenderbufferParameteriv;
functions->fRenderbufferStorage = glRenderbufferStorage;
#if GL_OES_mapbuffer
functions->fMapBuffer = glMapBufferOES;
functions->fUnmapBuffer = glUnmapBufferOES;
#else
functions->fMapBuffer = (GrGLMapBufferProc) eglGetProcAddress("glMapBufferOES");
functions->fUnmapBuffer = (GrGLUnmapBufferProc) eglGetProcAddress("glUnmapBufferOES");
#endif
#if GL_ES_VERSION_3_0 || GL_EXT_map_buffer_range
functions->fMapBufferRange = glMapBufferRange;
functions->fFlushMappedBufferRange = glFlushMappedBufferRange;
#else
if (version >= GR_GL_VER(3,0) || extensions->has("GL_EXT_map_buffer_range")) {
functions->fMapBufferRange = (GrGLMapBufferRangeProc) eglGetProcAddress("glMapBufferRange");
functions->fFlushMappedBufferRange = (GrGLFlushMappedBufferRangeProc) eglGetProcAddress("glFlushMappedBufferRange");
}
#endif
if (extensions->has("GL_EXT_debug_marker")) {
functions->fInsertEventMarker = (GrGLInsertEventMarkerProc) eglGetProcAddress("glInsertEventMarker");
functions->fPushGroupMarker = (GrGLInsertEventMarkerProc) eglGetProcAddress("glPushGroupMarker");
functions->fPopGroupMarker = (GrGLPopGroupMarkerProc) eglGetProcAddress("glPopGroupMarker");
// The below check is here because a device has been found that has the extension string but
// returns NULL from the eglGetProcAddress for the functions
if (NULL == functions->fInsertEventMarker ||
NULL == functions->fPushGroupMarker ||
NULL == functions->fPopGroupMarker) {
extensions->remove("GL_EXT_debug_marker");
}
}
#if GL_ES_VERSION_3_0
functions->fInvalidateFramebuffer = glInvalidateFramebuffer;
functions->fInvalidateSubFramebuffer = glInvalidateSubFramebuffer;
#else
functions->fInvalidateFramebuffer = (GrGLInvalidateFramebufferProc) eglGetProcAddress("glInvalidateFramebuffer");
functions->fInvalidateSubFramebuffer = (GrGLInvalidateSubFramebufferProc) eglGetProcAddress("glInvalidateSubFramebuffer");
#endif
functions->fInvalidateBufferData = (GrGLInvalidateBufferDataProc) eglGetProcAddress("glInvalidateBufferData");
functions->fInvalidateBufferSubData = (GrGLInvalidateBufferSubDataProc) eglGetProcAddress("glInvalidateBufferSubData");
functions->fInvalidateTexImage = (GrGLInvalidateTexImageProc) eglGetProcAddress("glInvalidateTexImage");
functions->fInvalidateTexSubImage = (GrGLInvalidateTexSubImageProc) eglGetProcAddress("glInvalidateTexSubImage");
return interface;
}
static GrGLFuncPtr android_get_gl_proc(void* ctx, const char name[]) {
SkASSERT(NULL == ctx);
return eglGetProcAddress(name);
}
static const GrGLInterface* create_desktop_interface() {
return GrGLAssembleGLInterface(NULL, android_get_gl_proc);
}
const GrGLInterface* GrGLCreateNativeInterface() {
const char* verStr = reinterpret_cast<const char*>(glGetString(GR_GL_VERSION));
GrGLStandard standard = GrGLGetStandardInUseFromString(verStr);
if (kGLES_GrGLStandard == standard) {
GrGLVersion version = GrGLGetVersionFromString(verStr);
GrGLExtensions extensions;
GrGLGetStringiProc getStringi = (GrGLGetStringiProc) eglGetProcAddress("glGetStringi");
if (!extensions.init(standard, glGetString, getStringi, glGetIntegerv)) {
return NULL;
}
GrGLInterface* interface = create_es_interface(version, &extensions);
if (NULL != interface) {
interface->fExtensions.swap(&extensions);
}
return interface;
} else if (kGL_GrGLStandard == standard) {
return create_desktop_interface();
}
return NULL;
}
<commit_msg>Add EXT suffix to EXT_map_buffer_range references<commit_after>// Modified from chromium/src/webkit/glue/gl_bindings_skia_cmd_buffer.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gl/GrGLInterface.h"
#include "gl/GrGLAssembleInterface.h"
#include "gl/GrGLExtensions.h"
#include "gl/GrGLUtil.h"
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
static GrGLInterface* create_es_interface(GrGLVersion version,
GrGLExtensions* extensions) {
if (version < GR_GL_VER(2,0)) {
return NULL;
}
GrGLInterface* interface = SkNEW(GrGLInterface);
interface->fStandard = kGLES_GrGLStandard;
GrGLInterface::Functions* functions = &interface->fFunctions;
functions->fActiveTexture = glActiveTexture;
functions->fAttachShader = glAttachShader;
functions->fBindAttribLocation = glBindAttribLocation;
functions->fBindBuffer = glBindBuffer;
functions->fBindTexture = glBindTexture;
functions->fBindVertexArray = glBindVertexArrayOES;
functions->fBlendColor = glBlendColor;
functions->fBlendFunc = glBlendFunc;
functions->fBufferData = glBufferData;
functions->fBufferSubData = glBufferSubData;
functions->fClear = glClear;
functions->fClearColor = glClearColor;
functions->fClearStencil = glClearStencil;
functions->fColorMask = glColorMask;
functions->fCompileShader = glCompileShader;
functions->fCompressedTexImage2D = glCompressedTexImage2D;
functions->fCopyTexSubImage2D = glCopyTexSubImage2D;
functions->fCreateProgram = glCreateProgram;
functions->fCreateShader = glCreateShader;
functions->fCullFace = glCullFace;
functions->fDeleteBuffers = glDeleteBuffers;
functions->fDeleteProgram = glDeleteProgram;
functions->fDeleteShader = glDeleteShader;
functions->fDeleteTextures = glDeleteTextures;
functions->fDeleteVertexArrays = glDeleteVertexArraysOES;
functions->fDepthMask = glDepthMask;
functions->fDisable = glDisable;
functions->fDisableVertexAttribArray = glDisableVertexAttribArray;
functions->fDrawArrays = glDrawArrays;
functions->fDrawElements = glDrawElements;
functions->fEnable = glEnable;
functions->fEnableVertexAttribArray = glEnableVertexAttribArray;
functions->fFinish = glFinish;
functions->fFlush = glFlush;
functions->fFrontFace = glFrontFace;
functions->fGenBuffers = glGenBuffers;
functions->fGenerateMipmap = glGenerateMipmap;
functions->fGenTextures = glGenTextures;
functions->fGenVertexArrays = glGenVertexArraysOES;
functions->fGetBufferParameteriv = glGetBufferParameteriv;
functions->fGetError = glGetError;
functions->fGetIntegerv = glGetIntegerv;
functions->fGetProgramInfoLog = glGetProgramInfoLog;
functions->fGetProgramiv = glGetProgramiv;
functions->fGetShaderInfoLog = glGetShaderInfoLog;
functions->fGetShaderiv = glGetShaderiv;
functions->fGetString = glGetString;
#if GL_ES_VERSION_3_0
functions->fGetStringi = glGetStringi;
#else
functions->fGetStringi = (GrGLGetStringiProc) eglGetProcAddress("glGetStringi");
#endif
functions->fGetUniformLocation = glGetUniformLocation;
functions->fLineWidth = glLineWidth;
functions->fLinkProgram = glLinkProgram;
functions->fPixelStorei = glPixelStorei;
functions->fReadPixels = glReadPixels;
functions->fScissor = glScissor;
#if GR_GL_USE_NEW_SHADER_SOURCE_SIGNATURE
functions->fShaderSource = (GrGLShaderSourceProc) glShaderSource;
#else
functions->fShaderSource = glShaderSource;
#endif
functions->fStencilFunc = glStencilFunc;
functions->fStencilFuncSeparate = glStencilFuncSeparate;
functions->fStencilMask = glStencilMask;
functions->fStencilMaskSeparate = glStencilMaskSeparate;
functions->fStencilOp = glStencilOp;
functions->fStencilOpSeparate = glStencilOpSeparate;
functions->fTexImage2D = glTexImage2D;
functions->fTexParameteri = glTexParameteri;
functions->fTexParameteriv = glTexParameteriv;
functions->fTexSubImage2D = glTexSubImage2D;
if (version >= GR_GL_VER(3,0)) {
#if GL_ES_VERSION_3_0
functions->fTexStorage2D = glTexStorage2D;
#else
functions->fTexStorage2D = (GrGLTexStorage2DProc) eglGetProcAddress("glTexStorage2D");
#endif
} else {
#if GL_EXT_texture_storage
functions->fTexStorage2D = glTexStorage2DEXT;
#else
functions->fTexStorage2D = (GrGLTexStorage2DProc) eglGetProcAddress("glTexStorage2DEXT");
#endif
}
#if GL_EXT_discard_framebuffer
functions->fDiscardFramebuffer = glDiscardFramebufferEXT;
#endif
functions->fUniform1f = glUniform1f;
functions->fUniform1i = glUniform1i;
functions->fUniform1fv = glUniform1fv;
functions->fUniform1iv = glUniform1iv;
functions->fUniform2f = glUniform2f;
functions->fUniform2i = glUniform2i;
functions->fUniform2fv = glUniform2fv;
functions->fUniform2iv = glUniform2iv;
functions->fUniform3f = glUniform3f;
functions->fUniform3i = glUniform3i;
functions->fUniform3fv = glUniform3fv;
functions->fUniform3iv = glUniform3iv;
functions->fUniform4f = glUniform4f;
functions->fUniform4i = glUniform4i;
functions->fUniform4fv = glUniform4fv;
functions->fUniform4iv = glUniform4iv;
functions->fUniformMatrix2fv = glUniformMatrix2fv;
functions->fUniformMatrix3fv = glUniformMatrix3fv;
functions->fUniformMatrix4fv = glUniformMatrix4fv;
functions->fUseProgram = glUseProgram;
functions->fVertexAttrib4fv = glVertexAttrib4fv;
functions->fVertexAttribPointer = glVertexAttribPointer;
functions->fViewport = glViewport;
functions->fBindFramebuffer = glBindFramebuffer;
functions->fBindRenderbuffer = glBindRenderbuffer;
functions->fCheckFramebufferStatus = glCheckFramebufferStatus;
functions->fDeleteFramebuffers = glDeleteFramebuffers;
functions->fDeleteRenderbuffers = glDeleteRenderbuffers;
functions->fFramebufferRenderbuffer = glFramebufferRenderbuffer;
functions->fFramebufferTexture2D = glFramebufferTexture2D;
if (version >= GR_GL_VER(3,0)) {
#if GL_ES_VERSION_3_0
functions->fRenderbufferStorageMultisample = glRenderbufferStorageMultisample;
functions->fBlitFramebuffer = glBlitFramebuffer;
#else
functions->fRenderbufferStorageMultisample = (GrGLRenderbufferStorageMultisampleProc) eglGetProcAddress("glRenderbufferStorageMultisample");
functions->fBlitFramebuffer = (GrGLBlitFramebufferProc) eglGetProcAddress("glBlitFramebuffer");
#endif
}
if (extensions->has("GL_EXT_multisampled_render_to_texture")) {
#if GL_EXT_multisampled_render_to_texture
functions->fFramebufferTexture2DMultisample = glFramebufferTexture2DMultisampleEXT;
functions->fRenderbufferStorageMultisampleES2EXT = glRenderbufferStorageMultisampleEXT;
#else
functions->fFramebufferTexture2DMultisample = (GrGLFramebufferTexture2DMultisampleProc) eglGetProcAddress("glFramebufferTexture2DMultisampleEXT");
functions->fRenderbufferStorageMultisampleES2EXT = (GrGLRenderbufferStorageMultisampleProc) eglGetProcAddress("glRenderbufferStorageMultisampleEXT");
#endif
} else if (extensions->has("GL_IMG_multisampled_render_to_texture")) {
#if GL_IMG_multisampled_render_to_texture
functions->fFramebufferTexture2DMultisample = glFramebufferTexture2DMultisampleIMG;
functions->fRenderbufferStorageMultisampleES2EXT = glRenderbufferStorageMultisampleIMG;
#else
functions->fFramebufferTexture2DMultisample = (GrGLFramebufferTexture2DMultisampleProc) eglGetProcAddress("glFramebufferTexture2DMultisampleIMG");
functions->fRenderbufferStorageMultisampleES2EXT = (GrGLRenderbufferStorageMultisampleProc) eglGetProcAddress("glRenderbufferStorageMultisampleIMG");
#endif
}
functions->fGenFramebuffers = glGenFramebuffers;
functions->fGenRenderbuffers = glGenRenderbuffers;
functions->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv;
functions->fGetRenderbufferParameteriv = glGetRenderbufferParameteriv;
functions->fRenderbufferStorage = glRenderbufferStorage;
#if GL_OES_mapbuffer
functions->fMapBuffer = glMapBufferOES;
functions->fUnmapBuffer = glUnmapBufferOES;
#else
functions->fMapBuffer = (GrGLMapBufferProc) eglGetProcAddress("glMapBufferOES");
functions->fUnmapBuffer = (GrGLUnmapBufferProc) eglGetProcAddress("glUnmapBufferOES");
#endif
if (version >= GR_GL_VER(3,0)) {
#if GL_ES_VERSION_3_0
functions->fMapBufferRange = glMapBufferRange;
functions->fFlushMappedBufferRange = glFlushMappedBufferRange;
#else
functions->fMapBufferRange = (GrGLMapBufferRangeProc) eglGetProcAddress("glMapBufferRange");
functions->fFlushMappedBufferRange = (GrGLFlushMappedBufferRangeProc) eglGetProcAddress("glFlushMappedBufferRange");
#endif
} else if (extensions->has("GL_EXT_map_buffer_range")) {
#if GL_EXT_map_buffer_range
functions->fMapBufferRange = glMapBufferRangeEXT;
functions->fFlushMappedBufferRange = glFlushMappedBufferRangeEXT;
#else
functions->fMapBufferRange = (GrGLMapBufferRangeProc) eglGetProcAddress("glMapBufferRangeEXT");
functions->fFlushMappedBufferRange = (GrGLFlushMappedBufferRangeProc) eglGetProcAddress("glFlushMappedBufferRangeEXT");
#endif
}
if (extensions->has("GL_EXT_debug_marker")) {
functions->fInsertEventMarker = (GrGLInsertEventMarkerProc) eglGetProcAddress("glInsertEventMarker");
functions->fPushGroupMarker = (GrGLInsertEventMarkerProc) eglGetProcAddress("glPushGroupMarker");
functions->fPopGroupMarker = (GrGLPopGroupMarkerProc) eglGetProcAddress("glPopGroupMarker");
// The below check is here because a device has been found that has the extension string but
// returns NULL from the eglGetProcAddress for the functions
if (NULL == functions->fInsertEventMarker ||
NULL == functions->fPushGroupMarker ||
NULL == functions->fPopGroupMarker) {
extensions->remove("GL_EXT_debug_marker");
}
}
#if GL_ES_VERSION_3_0
functions->fInvalidateFramebuffer = glInvalidateFramebuffer;
functions->fInvalidateSubFramebuffer = glInvalidateSubFramebuffer;
#else
functions->fInvalidateFramebuffer = (GrGLInvalidateFramebufferProc) eglGetProcAddress("glInvalidateFramebuffer");
functions->fInvalidateSubFramebuffer = (GrGLInvalidateSubFramebufferProc) eglGetProcAddress("glInvalidateSubFramebuffer");
#endif
functions->fInvalidateBufferData = (GrGLInvalidateBufferDataProc) eglGetProcAddress("glInvalidateBufferData");
functions->fInvalidateBufferSubData = (GrGLInvalidateBufferSubDataProc) eglGetProcAddress("glInvalidateBufferSubData");
functions->fInvalidateTexImage = (GrGLInvalidateTexImageProc) eglGetProcAddress("glInvalidateTexImage");
functions->fInvalidateTexSubImage = (GrGLInvalidateTexSubImageProc) eglGetProcAddress("glInvalidateTexSubImage");
return interface;
}
static GrGLFuncPtr android_get_gl_proc(void* ctx, const char name[]) {
SkASSERT(NULL == ctx);
return eglGetProcAddress(name);
}
static const GrGLInterface* create_desktop_interface() {
return GrGLAssembleGLInterface(NULL, android_get_gl_proc);
}
const GrGLInterface* GrGLCreateNativeInterface() {
const char* verStr = reinterpret_cast<const char*>(glGetString(GR_GL_VERSION));
GrGLStandard standard = GrGLGetStandardInUseFromString(verStr);
if (kGLES_GrGLStandard == standard) {
GrGLVersion version = GrGLGetVersionFromString(verStr);
GrGLExtensions extensions;
GrGLGetStringiProc getStringi = (GrGLGetStringiProc) eglGetProcAddress("glGetStringi");
if (!extensions.init(standard, glGetString, getStringi, glGetIntegerv)) {
return NULL;
}
GrGLInterface* interface = create_es_interface(version, &extensions);
if (NULL != interface) {
interface->fExtensions.swap(&extensions);
}
return interface;
} else if (kGL_GrGLStandard == standard) {
return create_desktop_interface();
}
return NULL;
}
<|endoftext|> |
<commit_before>#include "iteration/outer/outer_power_iteration.hpp"
#include <memory>
#include "instrumentation/tests/instrument_mock.h"
#include "iteration/group/tests/group_solve_iteration_mock.h"
#include "iteration/subroutine/tests/subroutine_mock.hpp"
#include "eigenvalue/k_effective/tests/k_effective_updater_mock.h"
#include "convergence/tests/final_checker_mock.h"
#include "formulation/updater/tests/fission_source_updater_mock.h"
#include "test_helpers/gmock_wrapper.h"
#include "system/system.hpp"
namespace {
using namespace bart;
using ::testing::A, ::testing::AtLeast, ::testing::Expectation;
using ::testing::Ref, ::testing::Return, ::testing::Sequence, ::testing::_;
class IterationOuterPowerIterationTest : public ::testing::Test {
protected:
using GroupIterator = iteration::group::GroupSolveIterationMock;
using ConvergenceChecker = convergence::FinalCheckerMock<double>;
using ConvergenceInstrumentType = instrumentation::InstrumentMock<convergence::Status>;
using ErrorInstrumentType = instrumentation::InstrumentMock<std::pair<int, double>>;
using K_EffectiveUpdater = eigenvalue::k_effective::K_EffectiveUpdaterMock;
using OuterPowerIteration = iteration::outer::OuterPowerIteration;
using SourceUpdater = formulation::updater::FissionSourceUpdaterMock;
using StatusInstrumentType = instrumentation::InstrumentMock<std::string>;
using Subroutine = iteration::subroutine::SubroutineMock;
std::unique_ptr<OuterPowerIteration> test_iterator;
// Dependencies
std::shared_ptr<SourceUpdater> source_updater_ptr_;
std::shared_ptr<ConvergenceInstrumentType> convergence_instrument_ptr_;
std::shared_ptr<ErrorInstrumentType> error_instrument_ptr_;
std::shared_ptr<StatusInstrumentType> status_instrument_ptr_;
// Supporting objects
system::System test_system;
// Observation pointers
GroupIterator* group_iterator_obs_ptr_;
ConvergenceChecker* convergence_checker_obs_ptr_;
K_EffectiveUpdater* k_effective_updater_obs_ptr_;
Subroutine* post_iteration_subroutine_obs_ptr_;
// Test parameters
const int total_groups = 2;
const int total_angles = 3;
static constexpr int iterations_ = 4;
void SetUp() override;
};
void IterationOuterPowerIterationTest::SetUp() {
// Dependencies
source_updater_ptr_ = std::make_shared<SourceUpdater>();
auto group_iterator_ptr = std::make_unique<GroupIterator>();
group_iterator_obs_ptr_ = group_iterator_ptr.get();
auto convergenge_checker_ptr = std::make_unique<ConvergenceChecker>();
convergence_checker_obs_ptr_ = convergenge_checker_ptr.get();
auto k_effective_updater_ptr = std::make_unique<K_EffectiveUpdater>();
k_effective_updater_obs_ptr_ = k_effective_updater_ptr.get();
convergence_instrument_ptr_ = std::make_shared<ConvergenceInstrumentType>();
status_instrument_ptr_ = std::make_shared<StatusInstrumentType>();
error_instrument_ptr_ = std::make_shared<ErrorInstrumentType>();
auto post_iteration_subroutine_ptr = std::make_unique<Subroutine>();
post_iteration_subroutine_obs_ptr_ = post_iteration_subroutine_ptr.get();
// Set up system
test_system.total_angles = total_angles;
test_system.total_groups = total_groups;
// Construct test object
test_iterator = std::make_unique<OuterPowerIteration>(
std::move(group_iterator_ptr),
std::move(convergenge_checker_ptr),
std::move(k_effective_updater_ptr),
source_updater_ptr_);
test_iterator->AddPostIterationSubroutine(std::move(post_iteration_subroutine_ptr));
using ConvergenceStatusPort = iteration::outer::data_names::ConvergenceStatusPort;
instrumentation::GetPort<ConvergenceStatusPort>(*test_iterator).AddInstrument(
convergence_instrument_ptr_);
using StatusPort = iteration::outer::data_names::StatusPort;
instrumentation::GetPort<StatusPort>(*test_iterator).AddInstrument(
status_instrument_ptr_);
using IterationErrorPort = iteration::outer::data_names::IterationErrorPort;
instrumentation::GetPort<IterationErrorPort>(*test_iterator)
.AddInstrument(error_instrument_ptr_);
}
TEST_F(IterationOuterPowerIterationTest, Constructor) {
EXPECT_NE(this->test_iterator, nullptr);
EXPECT_NE(this->test_iterator->group_iterator_ptr(), nullptr);
EXPECT_NE(this->test_iterator->source_updater_ptr(), nullptr);
EXPECT_NE(this->test_iterator->convergence_checker_ptr(), nullptr);
EXPECT_NE(this->test_iterator->k_effective_updater_ptr(), nullptr);
EXPECT_NE(this->test_iterator->post_iteration_subroutine_ptr(), nullptr);
EXPECT_EQ(this->source_updater_ptr_.use_count(), 2);
}
TEST_F(IterationOuterPowerIterationTest, ConstructorErrors) {
for (int i = 0; i < 4; ++i) {
auto convergence_checker_ptr = (i == 0) ? nullptr :
std::make_unique<convergence::FinalCheckerMock<double>>();
auto k_effective_updater_ptr = (i == 1) ? nullptr :
std::make_unique<eigenvalue::k_effective::K_EffectiveUpdaterMock>();
auto source_updater_ptr = (i == 2) ? nullptr : this->source_updater_ptr_;
auto group_iterator_ptr = (i == 3) ? nullptr :
std::make_unique<iteration::group::GroupSolveIterationMock>();
EXPECT_ANY_THROW({
iteration::outer::OuterPowerIteration test_iterator(
std::move(group_iterator_ptr),
std::move(convergence_checker_ptr),
std::move(k_effective_updater_ptr),
source_updater_ptr);
});
}
}
TEST_F(IterationOuterPowerIterationTest, IterateToConvergenceTest) {
for (int group = 0; group < this->total_groups; ++group) {
for (int angle = 0; angle < this->total_angles; ++angle) {
EXPECT_CALL(*this->source_updater_ptr_, UpdateFissionSource(
Ref(this->test_system),
bart::system::EnergyGroup(group),
quadrature::QuadraturePointIndex(angle)))
.Times(this->iterations_);
}
}
// K_Effective updater return values
std::array<double, iterations_ + 1> k_effective_by_iteration;
k_effective_by_iteration.fill(0);
Sequence k_effective_calls;
std::vector<double> expected_errors;
for (int i = 0; i < this->iterations_; ++i) {
k_effective_by_iteration.at(i + 1) = i * 1.5;
EXPECT_CALL(*this->k_effective_updater_obs_ptr_,
CalculateK_Effective(Ref(this->test_system)))
.InSequence(k_effective_calls)
.WillOnce(Return(k_effective_by_iteration.at(i + 1)));
convergence::Status convergence_status;
convergence_status.is_complete = (i == (this->iterations_ - 1));
if (i > 0) {
double expected_error =
(k_effective_by_iteration.at(i + 1) - k_effective_by_iteration.at(i))
/ (k_effective_by_iteration.at(i + 1));
expected_errors.push_back(expected_error);
convergence_status.delta = expected_error;
} else {
convergence_status.delta = std::nullopt;
}
EXPECT_CALL(*this->convergence_checker_obs_ptr_,
CheckFinalConvergence(k_effective_by_iteration.at(i + 1),
k_effective_by_iteration.at(i)))
.WillOnce(Return(convergence_status));
}
EXPECT_CALL(*this->group_iterator_obs_ptr_, Iterate(Ref(this->test_system)))
.Times(this->iterations_);
EXPECT_CALL(*this->convergence_instrument_ptr_, Read(_))
.Times(this->iterations_);
EXPECT_CALL(*this->post_iteration_subroutine_obs_ptr_, Execute(Ref(this->test_system)))
.Times(this->iterations_);
EXPECT_CALL(*this->status_instrument_ptr_, Read(_))
.Times(AtLeast(this->iterations_));
EXPECT_CALL(*this->error_instrument_ptr_, Read(_))
.Times(this->iterations_ - 1);
this->test_iterator->IterateToConvergence(this->test_system);
}
} // namespace<commit_msg>Added documentation and formatting fixes to tests for OuterPowerIteration.<commit_after>#include "iteration/outer/outer_power_iteration.hpp"
#include <memory>
#include "instrumentation/tests/instrument_mock.h"
#include "iteration/group/tests/group_solve_iteration_mock.h"
#include "iteration/subroutine/tests/subroutine_mock.hpp"
#include "eigenvalue/k_effective/tests/k_effective_updater_mock.h"
#include "convergence/tests/final_checker_mock.h"
#include "formulation/updater/tests/fission_source_updater_mock.h"
#include "test_helpers/gmock_wrapper.h"
#include "system/system.hpp"
namespace {
using namespace bart;
using ::testing::A, ::testing::AtLeast, ::testing::Expectation;
using ::testing::Ref, ::testing::Return, ::testing::Sequence, ::testing::_;
/* This fixture tests the operation of the OuterPowerIteration class. This is a mediator class so the tests will verify
* proper mediation between the dependencies and exposure of data to instruments.
*
* At the completion of SetUp() the test_iterator pointee object is set up with mock dependencies accessible via
* the provided observation pointers. Mock instrumentation is accessible via shared pointers.
* */
class IterationOuterPowerIterationTest : public ::testing::Test {
protected:
using GroupIterator = iteration::group::GroupSolveIterationMock;
using ConvergenceChecker = convergence::FinalCheckerMock<double>;
using ConvergenceInstrumentType = instrumentation::InstrumentMock<convergence::Status>;
using ErrorInstrumentType = instrumentation::InstrumentMock<std::pair<int, double>>;
using K_EffectiveUpdater = eigenvalue::k_effective::K_EffectiveUpdaterMock;
using OuterPowerIteration = iteration::outer::OuterPowerIteration;
using SourceUpdater = formulation::updater::FissionSourceUpdaterMock;
using StatusInstrumentType = instrumentation::InstrumentMock<std::string>;
using Subroutine = iteration::subroutine::SubroutineMock;
std::unique_ptr<OuterPowerIteration> test_iterator;
// Dependencies
std::shared_ptr<SourceUpdater> source_updater_ptr_{ std::make_shared<SourceUpdater>() };
// Mock instruments
std::shared_ptr<ConvergenceInstrumentType> convergence_instrument_ptr_{ std::make_shared<ConvergenceInstrumentType>() };
std::shared_ptr<ErrorInstrumentType> error_instrument_ptr_{ std::make_shared<ErrorInstrumentType>() };
std::shared_ptr<StatusInstrumentType> status_instrument_ptr_{ std::make_shared<StatusInstrumentType>() };
// Supporting objects
system::System test_system;
// Observation pointers
GroupIterator* group_iterator_obs_ptr_;
ConvergenceChecker* convergence_checker_obs_ptr_;
K_EffectiveUpdater* k_effective_updater_obs_ptr_;
Subroutine* post_iteration_subroutine_obs_ptr_;
// Test parameters
static constexpr int total_groups{ 2 };
static constexpr int total_angles{ 3 };
static constexpr int iterations_{ 4 };
void SetUp() override;
};
void IterationOuterPowerIterationTest::SetUp() {
// Dependencies
auto group_iterator_ptr = std::make_unique<GroupIterator>();
group_iterator_obs_ptr_ = group_iterator_ptr.get();
auto convergenge_checker_ptr = std::make_unique<ConvergenceChecker>();
convergence_checker_obs_ptr_ = convergenge_checker_ptr.get();
auto k_effective_updater_ptr = std::make_unique<K_EffectiveUpdater>();
k_effective_updater_obs_ptr_ = k_effective_updater_ptr.get();
auto post_iteration_subroutine_ptr = std::make_unique<Subroutine>();
post_iteration_subroutine_obs_ptr_ = post_iteration_subroutine_ptr.get();
// Set up system
test_system.total_angles = total_angles;
test_system.total_groups = total_groups;
// Construct test object
test_iterator = std::make_unique<OuterPowerIteration>(
std::move(group_iterator_ptr),
std::move(convergenge_checker_ptr),
std::move(k_effective_updater_ptr),
source_updater_ptr_);
test_iterator->AddPostIterationSubroutine(std::move(post_iteration_subroutine_ptr));
using ConvergenceStatusPort = iteration::outer::data_names::ConvergenceStatusPort;
instrumentation::GetPort<ConvergenceStatusPort>(*test_iterator).AddInstrument(convergence_instrument_ptr_);
using StatusPort = iteration::outer::data_names::StatusPort;
instrumentation::GetPort<StatusPort>(*test_iterator).AddInstrument(status_instrument_ptr_);
using IterationErrorPort = iteration::outer::data_names::IterationErrorPort;
instrumentation::GetPort<IterationErrorPort>(*test_iterator).AddInstrument(error_instrument_ptr_);
}
/* Constructor (called in SetUp()) should have stored the correct pointers in the test object */
TEST_F(IterationOuterPowerIterationTest, Constructor) {
EXPECT_NE(this->test_iterator, nullptr);
EXPECT_NE(this->test_iterator->group_iterator_ptr(), nullptr);
EXPECT_NE(this->test_iterator->source_updater_ptr(), nullptr);
EXPECT_NE(this->test_iterator->convergence_checker_ptr(), nullptr);
EXPECT_NE(this->test_iterator->k_effective_updater_ptr(), nullptr);
EXPECT_NE(this->test_iterator->post_iteration_subroutine_ptr(), nullptr);
EXPECT_EQ(this->source_updater_ptr_.use_count(), 2);
}
/* Constructor should throw an error if pointers passed to dependencies are null. */
TEST_F(IterationOuterPowerIterationTest, ConstructorErrors) {
for (int i = 0; i < 4; ++i) {
auto convergence_checker_ptr = (i == 0) ? nullptr :
std::make_unique<convergence::FinalCheckerMock<double>>();
auto k_effective_updater_ptr = (i == 1) ? nullptr :
std::make_unique<eigenvalue::k_effective::K_EffectiveUpdaterMock>();
auto source_updater_ptr = (i == 2) ? nullptr : this->source_updater_ptr_;
auto group_iterator_ptr = (i == 3) ? nullptr :
std::make_unique<iteration::group::GroupSolveIterationMock>();
EXPECT_ANY_THROW({
iteration::outer::OuterPowerIteration test_iterator(
std::move(group_iterator_ptr),
std::move(convergence_checker_ptr),
std::move(k_effective_updater_ptr),
source_updater_ptr);
});
}
}
/* A call to Iterate() should properly mediate the calls to the owned classes, including the group iteration class, and
* convergence-checker. */
TEST_F(IterationOuterPowerIterationTest, IterateToConvergenceTest) {
for (int group = 0; group < this->total_groups; ++group) {
for (int angle = 0; angle < this->total_angles; ++angle) {
EXPECT_CALL(*this->source_updater_ptr_, UpdateFissionSource(Ref(this->test_system),
bart::system::EnergyGroup(group),
quadrature::QuadraturePointIndex(angle)))
.Times(this->iterations_);
}
}
// K_Effective updater return values
std::array<double, iterations_ + 1> k_effective_by_iteration;
k_effective_by_iteration.fill(0);
Sequence k_effective_calls;
std::vector<double> expected_errors;
for (int i = 0; i < this->iterations_; ++i) {
const double iteration_k_effective{i * 1.5 };
k_effective_by_iteration.at(i + 1) = iteration_k_effective;
EXPECT_CALL(*this->k_effective_updater_obs_ptr_, CalculateK_Effective(Ref(this->test_system)))
.InSequence(k_effective_calls)
.WillOnce(Return(iteration_k_effective));
convergence::Status convergence_status;
convergence_status.is_complete = (i == (this->iterations_ - 1));
if (i > 0) {
double expected_error = (iteration_k_effective - k_effective_by_iteration.at(i)) / (iteration_k_effective);
expected_errors.push_back(expected_error);
convergence_status.delta = expected_error;
} else {
convergence_status.delta = std::nullopt;
}
EXPECT_CALL(*this->convergence_checker_obs_ptr_,
CheckFinalConvergence(k_effective_by_iteration.at(i + 1), k_effective_by_iteration.at(i)))
.WillOnce(Return(convergence_status));
}
EXPECT_CALL(*this->group_iterator_obs_ptr_, Iterate(Ref(this->test_system)))
.Times(this->iterations_);
EXPECT_CALL(*this->convergence_instrument_ptr_, Read(_))
.Times(this->iterations_);
EXPECT_CALL(*this->post_iteration_subroutine_obs_ptr_, Execute(Ref(this->test_system)))
.Times(this->iterations_);
EXPECT_CALL(*this->status_instrument_ptr_, Read(_))
.Times(AtLeast(this->iterations_));
EXPECT_CALL(*this->error_instrument_ptr_, Read(_))
.Times(this->iterations_ - 1);
this->test_iterator->IterateToConvergence(this->test_system);
}
} // namespace<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "MediaFile.h"
#include <iostream>
#include <string>
#include <algorithm>
#ifdef WIN32
void ConvertPath(std::string &path)
{
std::replace(dir.begin(), dir.end(), '/', '\\');
}
#endif
//
// MediaFile
//
MediaFile::MediaFile(std::istream* _stream) : stream(_stream)
{
// do nothing
}
MediaFile::~MediaFile()
{
// do nothing
}
bool MediaFile::isOkay() const
{
return (stream != NULL && stream->good());
}
void MediaFile::readRaw(void* vbuffer, uint32_t bytes)
{
char* buffer = reinterpret_cast<char*>(vbuffer);
stream->read(buffer, bytes);
}
void MediaFile::skip(uint32_t bytes)
{
stream->ignore(bytes);
}
uint16_t MediaFile::read16LE()
{
uint16_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap16LE(&b);
}
uint16_t MediaFile::read16BE()
{
uint16_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap16BE(&b);
}
uint32_t MediaFile::read32LE()
{
uint32_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap32LE(&b);
}
uint32_t MediaFile::read32BE()
{
uint32_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap32BE(&b);
}
uint16_t MediaFile::swap16LE(uint16_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint16_t>(b[0]) + (static_cast<uint16_t>(b[1]) << 8);
return *d;
}
uint16_t MediaFile::swap16BE(uint16_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint16_t>(b[1]) + (static_cast<uint16_t>(b[0]) << 8);
return *d;
}
uint32_t MediaFile::swap32LE(uint32_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint32_t>(b[0]) + (static_cast<uint32_t>(b[1]) << 8) +
(static_cast<uint32_t>(b[2]) << 16) +
(static_cast<uint32_t>(b[3]) << 24);
return *d;
}
uint32_t MediaFile::swap32BE(uint32_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint32_t>(b[3]) + (static_cast<uint32_t>(b[2]) << 8) +
(static_cast<uint32_t>(b[1]) << 16) +
(static_cast<uint32_t>(b[0]) << 24);
return *d;
}
//
// utility methods to read various media files in any supported format
//
#include "FileManager.h"
#include "SGIImageFile.h"
#include "PNGImageFile.h"
#include "WaveAudioFile.h"
#define OPENMEDIA(_T) \
do { \
stream = FILEMGR.createDataInStream(filename, true); \
if (stream == NULL) \
stream = FILEMGR.createDataInStream(filename + \
_T::getExtension(), true); \
if (stream != NULL) { \
file = new _T(stream); \
if (!file->isOpen()) { \
file = NULL; \
delete stream; \
stream = NULL; \
} \
} \
} while (0)
unsigned char* MediaFile::readImage(
const std::string& filename,
int* width, int* height)
{
#ifdef WIN32
// cheat and make sure the file is a windows file path
ConvertPath(filename);
#endif //WIN32
// try opening file as an image
std::istream* stream;
ImageFile* file = NULL;
if (file == NULL)
OPENMEDIA(PNGImageFile);
if (file == NULL)
OPENMEDIA(SGIImageFile);
// read the image
unsigned char* image = NULL;
if (file != NULL) {
// get the image size
int dx = *width = file->getWidth();
int dy = *height = file->getHeight();
int dz = file->getNumChannels();
// make buffer for final image
image = new unsigned char[dx * dy * 4];
// make buffer to read image. if the image file has 4 channels
// then read directly into the final image buffer.
unsigned char* buffer = (dz == 4) ? image : new unsigned char[dx * dy * dz];
// read the image
if (image != NULL && buffer != NULL) {
if (!file->read(buffer)) {
// failed to read image. clean up.
if (buffer != image)
delete[] buffer;
delete[] image;
image = NULL;
buffer = NULL;
} else {
// expand image into 4 channels
int n = dx * dy;
const unsigned char* src = buffer;
unsigned char* dst = image;
if (dz == 1) {
// r=g=b=i, a=max
for (; n > 0; --n) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = 0xff;
src += 1;
dst += 4;
}
} else if (dz == 2) {
// r=g=b=i
for (; n > 0; --n) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = src[1];
src += 2;
dst += 4;
}
} else if (dz == 3) {
// a=max
for (; n > 0; --n) {
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = 0xff;
src += 3;
dst += 4;
}
}
}
}
// clean up
if (buffer != image)
delete[] buffer;
delete file;
}
// clean up
delete stream;
return image;
}
/*
float* MediaFile::readSound(
const std::string& filename,
int* _numFrames, int* rate)
{
// try opening as an audio file
std::istream* stream;
AudioFile* file = NULL;
if (file == NULL)
OPENMEDIA(WaveAudioFile);
// read the audio
float* audio = NULL;
if (file != NULL) {
// get the audio info
*rate = file->getFramesPerSecond();
int numChannels = file->getNumChannels();
int numFrames = file->getNumFrames();
int sampleWidth = file->getSampleWidth();
// make a buffer to read into
unsigned char* raw = new unsigned char[numFrames * numChannels * sampleWidth];
// read raw samples
if (file->read(raw, numFrames)) {
// prepare conversion parameters
int step = 1;
#if defined(HALF_RATE_AUDIO)
step *= 2;
numFrames /= 2;
*rate /= 2;
#endif
// make final audio buffer
audio = new float[2 * numFrames];
// convert
if (numChannels == 1) {
if (sampleWidth == 1) {
signed char* src = reinterpret_cast<signed char*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = audio[2 * i + 1] = 257.0f * static_cast<float>(*src);
src += step;
}
} else {
int16_t* src = reinterpret_cast<int16_t*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = audio[2 * i + 1] = static_cast<float>(*src);
src += step;
}
}
} else {
step *= 2;
if (sampleWidth == 1) {
signed char* src = reinterpret_cast<signed char*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = 257.0f * static_cast<float>(src[0]);
audio[2 * i + 1] = 257.0f * static_cast<float>(src[1]);
src += step;
}
} else {
int16_t* src = reinterpret_cast<int16_t*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = static_cast<float>(src[0]);
audio[2 * i + 1] = static_cast<float>(src[1]);
src += step;
}
}
}
}
// clean up
delete[] raw;
delete file;
*_numFrames = numFrames;
}
// clean up
delete stream;
return audio;
}
*/
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>fixes for the little people<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "MediaFile.h"
#include <iostream>
#include <string>
#include <algorithm>
#ifdef WIN32
void ConvertPath(const std::string &path)
{
std::replace(const_cast<std::string &>(path).begin(), const_cast<std::string &>(path).end(), '/', '\\');
}
#endif
//
// MediaFile
//
MediaFile::MediaFile(std::istream* _stream) : stream(_stream)
{
// do nothing
}
MediaFile::~MediaFile()
{
// do nothing
}
bool MediaFile::isOkay() const
{
return (stream != NULL && stream->good());
}
void MediaFile::readRaw(void* vbuffer, uint32_t bytes)
{
char* buffer = reinterpret_cast<char*>(vbuffer);
stream->read(buffer, bytes);
}
void MediaFile::skip(uint32_t bytes)
{
stream->ignore(bytes);
}
uint16_t MediaFile::read16LE()
{
uint16_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap16LE(&b);
}
uint16_t MediaFile::read16BE()
{
uint16_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap16BE(&b);
}
uint32_t MediaFile::read32LE()
{
uint32_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap32LE(&b);
}
uint32_t MediaFile::read32BE()
{
uint32_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap32BE(&b);
}
uint16_t MediaFile::swap16LE(uint16_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint16_t>(b[0]) + (static_cast<uint16_t>(b[1]) << 8);
return *d;
}
uint16_t MediaFile::swap16BE(uint16_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint16_t>(b[1]) + (static_cast<uint16_t>(b[0]) << 8);
return *d;
}
uint32_t MediaFile::swap32LE(uint32_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint32_t>(b[0]) + (static_cast<uint32_t>(b[1]) << 8) +
(static_cast<uint32_t>(b[2]) << 16) +
(static_cast<uint32_t>(b[3]) << 24);
return *d;
}
uint32_t MediaFile::swap32BE(uint32_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint32_t>(b[3]) + (static_cast<uint32_t>(b[2]) << 8) +
(static_cast<uint32_t>(b[1]) << 16) +
(static_cast<uint32_t>(b[0]) << 24);
return *d;
}
//
// utility methods to read various media files in any supported format
//
#include "FileManager.h"
#include "SGIImageFile.h"
#include "PNGImageFile.h"
#include "WaveAudioFile.h"
#define OPENMEDIA(_T) \
do { \
stream = FILEMGR.createDataInStream(filename, true); \
if (stream == NULL) \
stream = FILEMGR.createDataInStream(filename + \
_T::getExtension(), true); \
if (stream != NULL) { \
file = new _T(stream); \
if (!file->isOpen()) { \
file = NULL; \
delete stream; \
stream = NULL; \
} \
} \
} while (0)
unsigned char* MediaFile::readImage(
const std::string& filename,
int* width, int* height)
{
#ifdef WIN32
// cheat and make sure the file is a windows file path
ConvertPath(filename);
#endif //WIN32
// try opening file as an image
std::istream* stream;
ImageFile* file = NULL;
if (file == NULL)
OPENMEDIA(PNGImageFile);
if (file == NULL)
OPENMEDIA(SGIImageFile);
// read the image
unsigned char* image = NULL;
if (file != NULL) {
// get the image size
int dx = *width = file->getWidth();
int dy = *height = file->getHeight();
int dz = file->getNumChannels();
// make buffer for final image
image = new unsigned char[dx * dy * 4];
// make buffer to read image. if the image file has 4 channels
// then read directly into the final image buffer.
unsigned char* buffer = (dz == 4) ? image : new unsigned char[dx * dy * dz];
// read the image
if (image != NULL && buffer != NULL) {
if (!file->read(buffer)) {
// failed to read image. clean up.
if (buffer != image)
delete[] buffer;
delete[] image;
image = NULL;
buffer = NULL;
} else {
// expand image into 4 channels
int n = dx * dy;
const unsigned char* src = buffer;
unsigned char* dst = image;
if (dz == 1) {
// r=g=b=i, a=max
for (; n > 0; --n) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = 0xff;
src += 1;
dst += 4;
}
} else if (dz == 2) {
// r=g=b=i
for (; n > 0; --n) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = src[1];
src += 2;
dst += 4;
}
} else if (dz == 3) {
// a=max
for (; n > 0; --n) {
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = 0xff;
src += 3;
dst += 4;
}
}
}
}
// clean up
if (buffer != image)
delete[] buffer;
delete file;
}
// clean up
delete stream;
return image;
}
/*
float* MediaFile::readSound(
const std::string& filename,
int* _numFrames, int* rate)
{
// try opening as an audio file
std::istream* stream;
AudioFile* file = NULL;
if (file == NULL)
OPENMEDIA(WaveAudioFile);
// read the audio
float* audio = NULL;
if (file != NULL) {
// get the audio info
*rate = file->getFramesPerSecond();
int numChannels = file->getNumChannels();
int numFrames = file->getNumFrames();
int sampleWidth = file->getSampleWidth();
// make a buffer to read into
unsigned char* raw = new unsigned char[numFrames * numChannels * sampleWidth];
// read raw samples
if (file->read(raw, numFrames)) {
// prepare conversion parameters
int step = 1;
#if defined(HALF_RATE_AUDIO)
step *= 2;
numFrames /= 2;
*rate /= 2;
#endif
// make final audio buffer
audio = new float[2 * numFrames];
// convert
if (numChannels == 1) {
if (sampleWidth == 1) {
signed char* src = reinterpret_cast<signed char*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = audio[2 * i + 1] = 257.0f * static_cast<float>(*src);
src += step;
}
} else {
int16_t* src = reinterpret_cast<int16_t*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = audio[2 * i + 1] = static_cast<float>(*src);
src += step;
}
}
} else {
step *= 2;
if (sampleWidth == 1) {
signed char* src = reinterpret_cast<signed char*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = 257.0f * static_cast<float>(src[0]);
audio[2 * i + 1] = 257.0f * static_cast<float>(src[1]);
src += step;
}
} else {
int16_t* src = reinterpret_cast<int16_t*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = static_cast<float>(src[0]);
audio[2 * i + 1] = static_cast<float>(src[1]);
src += step;
}
}
}
}
// clean up
delete[] raw;
delete file;
*_numFrames = numFrames;
}
// clean up
delete stream;
return audio;
}
*/
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#include "itemapi.h"
#include "entitycomponents.h"
using namespace RoseCommon;
ItemAPI::ItemAPI(sol::environment&& env) : LuaAPI(std::move(env)) {
// build the C++/lua connectors here
env_.set_function("getAttr", [this](void* entity, std::string attr) {
throw_assert(entity, "The entity cannot be nullptr");
Entity e = *(Entity*)entity;
logger_->info("getAttr called for client {} and attr {}", getId(e), attr);
return 42;
});
env_.set_function("setAttr", [this](void* entity, std::string attr, int32_t value) {
throw_assert(entity, "The entity cannot be nullptr");
Entity e = *(Entity*)entity;
logger_->info("setAttr called for client {} and attr {} value {}", getId(e), attr, value);
}
}
<commit_msg>Update lua API<commit_after>#include "itemapi.h"
#include "entitycomponents.h"
using namespace RoseCommon;
ItemAPI::ItemAPI(sol::environment&& env) : LuaAPI(std::move(env)) {
// build the C++/lua connectors here
env_.set_function("getAttr", [this](void* entity, std::string attr) {
throw_assert(entity, "The entity cannot be nullptr");
Entity e = *(Entity*)entity;
logger_->info("getAttr called for client {} and attr {}", getId(e), attr);
return 42;
});
env_.set_function("addBonusAttr", [this](void* entity, std::string attr, int32_t value) {
throw_assert(entity, "The entity cannot be nullptr");
Entity e = *(Entity*)entity;
logger_->info("addBonusAttr called for client {} and attr {} value {}", getId(e), attr, value);
});
env_.set_function("removeBonusAttr", [this](void* entity, std::string attr, int32_t value) {
throw_assert(entity, "The entity cannot be nullptr");
Entity e = *(Entity*)entity;
logger_->info("removeBonusAttr called for client {} and attr {} value {}", getId(e), attr, value);
});
}
<|endoftext|> |
<commit_before>// Copyright 2011 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.
//
// Author: [email protected] <Nadav Samet>
// Jin Qing (http://blog.csdn.net/jq0123)
#include "connection_manager.hpp"
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>
#include <map>
#include <ostream>
#include <sstream>
#include <stddef.h>
#include <string>
#include <utility>
#include <vector>
#include <zmq.hpp>
#include <google/protobuf/stubs/common.h>
#include "application_options.hpp"
#include "client_connection.hpp"
#include "connection.hpp"
#include "broker_thread.hpp"
#include "internal_commands.hpp"
#include "logging.hpp"
#include "rpcz/callback.hpp"
#include "rpcz/sync_event.hpp"
#include "zmq_utils.hpp"
#include "request_handler.hpp" // TODO: extract worker_thread
namespace rpcz {
connection_manager::weak_ptr connection_manager::this_weak_ptr_;
boost::mutex connection_manager::this_weak_ptr_mutex_;
void worker_thread(connection_manager* connection_manager,
zmq::context_t & context, std::string endpoint) {
zmq::socket_t socket(context, ZMQ_DEALER);
socket.connect(endpoint.c_str());
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kReady);
bool should_quit = false;
while (!should_quit) {
message_iterator iter(socket);
CHECK_EQ(0, iter.next().size());
char command(interpret_message<char>(iter.next()));
switch (command) {
case kWorkerQuit:
should_quit = true;
break;
case krunclosure:
interpret_message<closure*>(iter.next())->run();
break;
case kHandleRequest: {
request_handler * handler =
interpret_message<request_handler*>(iter.next());
assert(handler);
handler->handle_request(iter);
}
break;
case kInvokeclient_request_callback: {
client_request_callback cb =
interpret_message<client_request_callback>(
iter.next());
connection_manager_status status = connection_manager_status(
interpret_message<uint64>(iter.next()));
cb(status, iter);
}
}
}
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kWorkerDone);
}
connection_manager::connection_manager()
: context_(NULL),
frontend_endpoint_("inproc://" + boost::lexical_cast<std::string>(this)
+ ".rpcz.connection_manager.frontend"),
is_terminating_(new sync_event) // scoped_ptr
{
DLOG(INFO) << "connection_manager() ";
application_options options;
context_ = options.get_zmq_context();
if (NULL == context_)
{
int zmq_io_threads = options.get_zmq_io_threads();
assert(zmq_io_threads > 0);
own_context_.reset(new zmq::context_t(zmq_io_threads));
context_ = own_context_.get();
}
assert(context_);
zmq::socket_t* frontend_socket = new zmq::socket_t(*context_, ZMQ_ROUTER);
int linger_ms = 0;
frontend_socket->setsockopt(ZMQ_LINGER, &linger_ms, sizeof(linger_ms));
frontend_socket->bind(frontend_endpoint_.c_str());
int nthreads = options.get_connection_manager_threads();
assert(nthreads > 0);
for (int i = 0; i < nthreads; ++i) {
worker_threads_.add_thread(
new boost::thread(&worker_thread, this, boost::ref(*context_), frontend_endpoint_));
}
sync_event event;
broker_thread_ = boost::thread(&broker_thread::run,
boost::ref(*context_), nthreads, &event,
frontend_socket);
event.wait();
}
connection_manager_ptr connection_manager::get_new()
{
lock_guard lock(this_weak_ptr_mutex_);
connection_manager_ptr p = this_weak_ptr_.lock();
if (p) return p;
p.reset(new connection_manager);
this_weak_ptr_ = p;
return p;
}
bool connection_manager::is_destroyed()
{
return 0 == this_weak_ptr_.use_count();
}
// used by get_frontend_socket()
zmq::socket_t& connection_manager::new_frontend_socket() {
assert(NULL == socket_.get());
zmq::socket_t* socket = new zmq::socket_t(*context_, ZMQ_DEALER);
int linger_ms = 0;
socket->setsockopt(ZMQ_LINGER, &linger_ms, sizeof(linger_ms));
socket->connect(frontend_endpoint_.c_str());
assert(NULL == socket_.get());
socket_.reset(socket); // set thread specific socket
return *socket;
}
connection connection_manager::connect(const std::string& endpoint) {
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kConnect, ZMQ_SNDMORE);
send_string(&socket, endpoint, 0);
zmq::message_t msg;
socket.recv(&msg);
socket.recv(&msg);
uint64 connection_id = interpret_message<uint64>(msg);
return connection(connection_id);
}
void connection_manager::bind(const std::string& endpoint,
const service_factory_map & factories) {
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kBind, ZMQ_SNDMORE);
send_string(&socket, endpoint, ZMQ_SNDMORE);
send_pointer(&socket, &factories, 0);
zmq::message_t msg;
socket.recv(&msg);
socket.recv(&msg);
}
// Unbind socket and unregister server_function.
void connection_manager::unbind(const std::string& endpoint)
{
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kUnbind, ZMQ_SNDMORE);
send_string(&socket, endpoint, 0);
zmq::message_t msg;
socket.recv(&msg);
socket.recv(&msg);
}
void connection_manager::add(closure* closure) {
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, krunclosure, ZMQ_SNDMORE);
send_pointer(&socket, closure, 0);
return;
}
void connection_manager::run() {
is_terminating_->wait();
}
void connection_manager::terminate() {
is_terminating_->signal();
}
connection_manager::~connection_manager() {
DLOG(INFO) << "~connection_manager()";
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kQuit, 0);
broker_thread_.join();
worker_threads_.join_all();
DLOG(INFO) << "All threads joined.";
}
} // namespace rpcz
<commit_msg>fix warn<commit_after>// Copyright 2011 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.
//
// Author: [email protected] <Nadav Samet>
// Jin Qing (http://blog.csdn.net/jq0123)
#include "connection_manager.hpp"
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>
#include <map>
#include <ostream>
#include <sstream>
#include <stddef.h>
#include <string>
#include <utility>
#include <vector>
#include <zmq.hpp>
#include <google/protobuf/stubs/common.h>
#include "application_options.hpp"
#include "client_connection.hpp"
#include "connection.hpp"
#include "broker_thread.hpp"
#include "internal_commands.hpp"
#include "logging.hpp"
#include "rpcz/callback.hpp"
#include "rpcz/sync_event.hpp"
#include "zmq_utils.hpp"
#include "request_handler.hpp" // TODO: extract worker_thread
namespace rpcz {
connection_manager::weak_ptr connection_manager::this_weak_ptr_;
boost::mutex connection_manager::this_weak_ptr_mutex_;
void worker_thread(connection_manager* connection_manager,
zmq::context_t & context, std::string endpoint) {
zmq::socket_t socket(context, ZMQ_DEALER);
socket.connect(endpoint.c_str());
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kReady);
bool should_quit = false;
while (!should_quit) {
message_iterator iter(socket);
CHECK_EQ(0, iter.next().size());
char command(interpret_message<char>(iter.next()));
switch (command) {
case kWorkerQuit:
should_quit = true;
break;
case krunclosure:
interpret_message<closure*>(iter.next())->run();
break;
case kHandleRequest: {
request_handler * handler =
interpret_message<request_handler*>(iter.next());
assert(handler);
handler->handle_request(iter);
}
break;
case kInvokeclient_request_callback: {
client_request_callback cb =
interpret_message<client_request_callback>(
iter.next());
connection_manager_status status = connection_manager_status(
interpret_message<uint64>(iter.next()));
cb(status, iter);
}
}
}
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kWorkerDone);
}
connection_manager::connection_manager()
: context_(NULL),
is_terminating_(new sync_event) // scoped_ptr
{
DLOG(INFO) << "connection_manager() ";
frontend_endpoint_ = "inproc://" + boost::lexical_cast<std::string>(this)
+ ".rpcz.connection_manager.frontend";
application_options options;
context_ = options.get_zmq_context();
if (NULL == context_)
{
int zmq_io_threads = options.get_zmq_io_threads();
assert(zmq_io_threads > 0);
own_context_.reset(new zmq::context_t(zmq_io_threads));
context_ = own_context_.get();
}
assert(context_);
zmq::socket_t* frontend_socket = new zmq::socket_t(*context_, ZMQ_ROUTER);
int linger_ms = 0;
frontend_socket->setsockopt(ZMQ_LINGER, &linger_ms, sizeof(linger_ms));
frontend_socket->bind(frontend_endpoint_.c_str());
int nthreads = options.get_connection_manager_threads();
assert(nthreads > 0);
for (int i = 0; i < nthreads; ++i) {
worker_threads_.add_thread(
new boost::thread(&worker_thread, this, boost::ref(*context_), frontend_endpoint_));
}
sync_event event;
broker_thread_ = boost::thread(&broker_thread::run,
boost::ref(*context_), nthreads, &event,
frontend_socket);
event.wait();
}
connection_manager_ptr connection_manager::get_new()
{
lock_guard lock(this_weak_ptr_mutex_);
connection_manager_ptr p = this_weak_ptr_.lock();
if (p) return p;
p.reset(new connection_manager);
this_weak_ptr_ = p;
return p;
}
bool connection_manager::is_destroyed()
{
return 0 == this_weak_ptr_.use_count();
}
// used by get_frontend_socket()
zmq::socket_t& connection_manager::new_frontend_socket() {
assert(NULL == socket_.get());
zmq::socket_t* socket = new zmq::socket_t(*context_, ZMQ_DEALER);
int linger_ms = 0;
socket->setsockopt(ZMQ_LINGER, &linger_ms, sizeof(linger_ms));
socket->connect(frontend_endpoint_.c_str());
assert(NULL == socket_.get());
socket_.reset(socket); // set thread specific socket
return *socket;
}
connection connection_manager::connect(const std::string& endpoint) {
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kConnect, ZMQ_SNDMORE);
send_string(&socket, endpoint, 0);
zmq::message_t msg;
socket.recv(&msg);
socket.recv(&msg);
uint64 connection_id = interpret_message<uint64>(msg);
return connection(connection_id);
}
void connection_manager::bind(const std::string& endpoint,
const service_factory_map & factories) {
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kBind, ZMQ_SNDMORE);
send_string(&socket, endpoint, ZMQ_SNDMORE);
send_pointer(&socket, &factories, 0);
zmq::message_t msg;
socket.recv(&msg);
socket.recv(&msg);
}
// Unbind socket and unregister server_function.
void connection_manager::unbind(const std::string& endpoint)
{
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kUnbind, ZMQ_SNDMORE);
send_string(&socket, endpoint, 0);
zmq::message_t msg;
socket.recv(&msg);
socket.recv(&msg);
}
void connection_manager::add(closure* closure) {
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, krunclosure, ZMQ_SNDMORE);
send_pointer(&socket, closure, 0);
return;
}
void connection_manager::run() {
is_terminating_->wait();
}
void connection_manager::terminate() {
is_terminating_->signal();
}
connection_manager::~connection_manager() {
DLOG(INFO) << "~connection_manager()";
zmq::socket_t& socket = get_frontend_socket();
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, kQuit, 0);
broker_thread_.join();
worker_threads_.join_all();
DLOG(INFO) << "All threads joined.";
}
} // namespace rpcz
<|endoftext|> |
<commit_before>#include "mitpi.h"
#define GPIO_BASE 0x20200000 //base address of the GPIO control registers.
#define PAGE_SIZE 4096 //mmap maps pages of memory, so we must give it multiples of this size
#define GPFSEL0 0x00000000 //gpio function select. There are 6 of these (32 bit registers)
//bits 2-0 of GPFSEL0: set to 000 to make Pin 0 an output. 001 is an input. Other combinations represent alternate functions
//bits 3-5 are for pin 1.
//...
//bits 27-29 are for pin 9.
//GPFSEL1 repeats, but bits 2-0 are Pin 10, 27-29 are pin 19.
//...
#define GPSET0 0x0000001C //GPIO Pin Output Set. There are 2 of these (32 bit registers)
#define GPSET1 0x00000020
//writing a '1' to bit N of GPSET0 makes that pin HIGH.
//writing a '0' has no effect.
//GPSET0[0-31] maps to pins 0-31
//GPSET1[0-21] maps to pins 32-53
#define GPCLR0 0x00000028 //GPIO Pin Output Clear. There are 2 of these (32 bits each)
#define GPCLR1 0x0000002C
//GPCLR acts the same way as GPSET, but clears the pin instead.
#define GPLEV0 0x00000034 //GPIO Pin Level. There are 2 of these (32 bits each)
#define GPPUD 0x00000094 //GPIO Pull-up/down register. Write 1 for pd, 2 for pu, and then write the PUDCLK
#define GPPUDCLK0 0x00000098 //GPIO Pull-up/down clock. Have to send a clock signal to the pull-up/down resistors to activate them.
#define GPPUDCLK1 0x000000a0 //second register for GPPUDCLK (first is for pins 0-31, 2nd for the rest)
#define TIMER_BASE 0x20003000
#define TIMER_CLO 0x00000004 //lower 32-bits of 1 MHz timer
#define TIMER_CHI 0x00000008 //upper 32-bits
#include <sys/mman.h> //for mmap
#include <sys/time.h>
#include <time.h> //for nanosleep / usleep (if have -std=gnu99)
#include <unistd.h> //for usleep
#include <stdlib.h> //for exit
#include <cassert> //for assert
#include <fcntl.h> //for file opening
#include "common/logging.h"
namespace mitpi {
volatile uint32_t *gpioBaseMem = nullptr;
volatile uint32_t *timerBaseMem = nullptr;
void assertValidPin(int pin) {
(void)pin; //unused when assertions are disabled.
assert(pin >= 0 && pin < 64);
}
void writeBitmasked(volatile uint32_t *dest, uint32_t mask, uint32_t value) {
//set bits designated by (mask) at the address (dest) to (value), without affecting the other bits
//eg if x = 0b11001100
// writeBitmasked(&x, 0b00000110, 0b11110011),
// then x now = 0b11001110
uint32_t cur = *dest;
uint32_t revised = (cur & (~mask)) | (value & mask);
*dest = revised;
*dest = revised; //best to be safe when crossing memory boundaries
}
volatile uint32_t* mapPeripheral(int memfd, int addr) {
///dev/mem behaves as a file. We need to map that file into memory:
//NULL = virtual address of mapping is chosen by kernel.
//PAGE_SIZE = map 1 page.
//PROT_READ|PROT_WRITE means give us read and write priveliges to the memory
//MAP_SHARED means updates to the mapped memory should be written back to the file & shared with other processes
//addr = offset in file to map
void *mapped = mmap(nullptr, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, memfd, addr);
//now, *mapped = memory at physical address of addr.
if (mapped == MAP_FAILED) {
LOGE("MitPi::mapPeripheral failed to map memory (did you remember to run as root?)\n");
exit(1);
} else {
LOGV("MitPi::mapPeripheral mapped: %p\n", mapped);
}
return (volatile uint32_t*)mapped;
}
bool init() {
if (gpioBaseMem) {
return 0; //already initialized
}
int memfd = open("/dev/mem", O_RDWR | O_SYNC);
if (memfd < 0) {
LOGE("Failed to open /dev/mem (did you remember to run as root?)\n");
exit(1);
}
gpioBaseMem = mapPeripheral(memfd, GPIO_BASE);
timerBaseMem = mapPeripheral(memfd, TIMER_BASE);
return 0; //init OK
}
void makeOutput(int pin) {
assertValidPin(pin);
volatile uint32_t *fselAddr = (volatile uint32_t*)(gpioBaseMem + GPFSEL0/4 + pin/10);
writeBitmasked(fselAddr, 0x7 << (3*(pin%10)), 0x1 << (3*(pin%10))); //0x7 is bitmask to select just our pin, 0x1 is mode to make pin an output
}
void makeInput(int pin) {
assertValidPin(pin);
volatile uint32_t *fselAddr = (volatile uint32_t*)(gpioBaseMem + GPFSEL0/4 + pin/10);
writeBitmasked(fselAddr, 0x7 << (3*(pin%10)), 0x0 << (3*(pin%10))); //0x7 is bitmask to select just our pin, 0x0 is mode to make pin an input
}
void setPinHigh(int pin) {
assertValidPin(pin);
//first, select the appropriate register. The first register controls pins 0-31, the second pins 32-63.
volatile uint32_t *gpSetAddr = (volatile uint32_t*)(gpioBaseMem + GPSET0/4 + (pin/32));
//now write a 1 ONLY to our pin. The act of writing a 1 to the address triggers it to be set high.
*gpSetAddr = 1 << (pin & 31);
}
void setPinLow(int pin) {
assertValidPin(pin);
//first, select the appropriate register. The first register controls pins 0-31, the second pins 32-63.
volatile uint32_t *gpClrAddr = (volatile uint32_t*)(gpioBaseMem + GPCLR0/4 + (pin/32));
//now write a 1 ONLY to our pin. The act of writing a 1 to the address triggers it to be set high.
*gpClrAddr = 1 << (pin & 31);
}
void setPinState(int pin, bool state) {
state ? setPinHigh(pin) : setPinLow(pin);
}
bool readPinState(int pin) {
assertValidPin(pin);
volatile uint32_t* gpLevAddr = (volatile uint32_t*)(gpioBaseMem + GPLEV0/4 + (pin/32));
uint32_t value = *gpLevAddr;
return (value & (1 << (pin & 31))) ? 1 : 0;
}
void setPinPull(int pin, GpioPull pull) {
assertValidPin(pin);
volatile uint32_t *pudAddr = (volatile uint32_t*)(gpioBaseMem + GPPUD/4);
volatile uint32_t *pudClkAddr = (volatile uint32_t*)(gpioBaseMem + GPPUDCLK0/4 + pin/32);
*pudAddr = pull;
usleep(10);
*pudClkAddr = 1 << (pin & 31);
usleep(10);
*pudAddr = GPIOPULL_NONE;
*pudClkAddr = 0;
}
void usleep(unsigned int us) {
//explicitly exposed to allow users of the library access to a usleep function
::usleep(us);
}
uint64_t readSysTime() {
return ((uint64_t)*(timerBaseMem + TIMER_CHI/4) << 32) + (uint64_t)(*(timerBaseMem + TIMER_CLO/4));
}
}
<commit_msg>Correctly prefix private functions with static<commit_after>#include "mitpi.h"
#define GPIO_BASE 0x20200000 //base address of the GPIO control registers.
#define PAGE_SIZE 4096 //mmap maps pages of memory, so we must give it multiples of this size
#define GPFSEL0 0x00000000 //gpio function select. There are 6 of these (32 bit registers)
//bits 2-0 of GPFSEL0: set to 000 to make Pin 0 an output. 001 is an input. Other combinations represent alternate functions
//bits 3-5 are for pin 1.
//...
//bits 27-29 are for pin 9.
//GPFSEL1 repeats, but bits 2-0 are Pin 10, 27-29 are pin 19.
//...
#define GPSET0 0x0000001C //GPIO Pin Output Set. There are 2 of these (32 bit registers)
#define GPSET1 0x00000020
//writing a '1' to bit N of GPSET0 makes that pin HIGH.
//writing a '0' has no effect.
//GPSET0[0-31] maps to pins 0-31
//GPSET1[0-21] maps to pins 32-53
#define GPCLR0 0x00000028 //GPIO Pin Output Clear. There are 2 of these (32 bits each)
#define GPCLR1 0x0000002C
//GPCLR acts the same way as GPSET, but clears the pin instead.
#define GPLEV0 0x00000034 //GPIO Pin Level. There are 2 of these (32 bits each)
#define GPPUD 0x00000094 //GPIO Pull-up/down register. Write 1 for pd, 2 for pu, and then write the PUDCLK
#define GPPUDCLK0 0x00000098 //GPIO Pull-up/down clock. Have to send a clock signal to the pull-up/down resistors to activate them.
#define GPPUDCLK1 0x000000a0 //second register for GPPUDCLK (first is for pins 0-31, 2nd for the rest)
#define TIMER_BASE 0x20003000
#define TIMER_CLO 0x00000004 //lower 32-bits of 1 MHz timer
#define TIMER_CHI 0x00000008 //upper 32-bits
#include <sys/mman.h> //for mmap
#include <sys/time.h>
#include <time.h> //for nanosleep / usleep (if have -std=gnu99)
#include <unistd.h> //for usleep
#include <stdlib.h> //for exit
#include <cassert> //for assert
#include <fcntl.h> //for file opening
#include "common/logging.h"
namespace mitpi {
static volatile uint32_t *gpioBaseMem = nullptr;
static volatile uint32_t *timerBaseMem = nullptr;
static void assertValidPin(int pin) {
(void)pin; //unused when assertions are disabled.
assert(pin >= 0 && pin < 64);
}
static void writeBitmasked(volatile uint32_t *dest, uint32_t mask, uint32_t value) {
//set bits designated by (mask) at the address (dest) to (value), without affecting the other bits
//eg if x = 0b11001100
// writeBitmasked(&x, 0b00000110, 0b11110011),
// then x now = 0b11001110
uint32_t cur = *dest;
uint32_t revised = (cur & (~mask)) | (value & mask);
*dest = revised;
*dest = revised; //best to be safe when crossing memory boundaries
}
volatile uint32_t* mapPeripheral(int memfd, int addr) {
///dev/mem behaves as a file. We need to map that file into memory:
//NULL = virtual address of mapping is chosen by kernel.
//PAGE_SIZE = map 1 page.
//PROT_READ|PROT_WRITE means give us read and write priveliges to the memory
//MAP_SHARED means updates to the mapped memory should be written back to the file & shared with other processes
//addr = offset in file to map
void *mapped = mmap(nullptr, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, memfd, addr);
//now, *mapped = memory at physical address of addr.
if (mapped == MAP_FAILED) {
LOGE("MitPi::mapPeripheral failed to map memory (did you remember to run as root?)\n");
exit(1);
} else {
LOGV("MitPi::mapPeripheral mapped: %p\n", mapped);
}
return (volatile uint32_t*)mapped;
}
bool init() {
if (gpioBaseMem) {
return 0; //already initialized
}
int memfd = open("/dev/mem", O_RDWR | O_SYNC);
if (memfd < 0) {
LOGE("Failed to open /dev/mem (did you remember to run as root?)\n");
exit(1);
}
gpioBaseMem = mapPeripheral(memfd, GPIO_BASE);
timerBaseMem = mapPeripheral(memfd, TIMER_BASE);
return 0; //init OK
}
void makeOutput(int pin) {
assertValidPin(pin);
volatile uint32_t *fselAddr = (volatile uint32_t*)(gpioBaseMem + GPFSEL0/4 + pin/10);
writeBitmasked(fselAddr, 0x7 << (3*(pin%10)), 0x1 << (3*(pin%10))); //0x7 is bitmask to select just our pin, 0x1 is mode to make pin an output
}
void makeInput(int pin) {
assertValidPin(pin);
volatile uint32_t *fselAddr = (volatile uint32_t*)(gpioBaseMem + GPFSEL0/4 + pin/10);
writeBitmasked(fselAddr, 0x7 << (3*(pin%10)), 0x0 << (3*(pin%10))); //0x7 is bitmask to select just our pin, 0x0 is mode to make pin an input
}
void setPinHigh(int pin) {
assertValidPin(pin);
//first, select the appropriate register. The first register controls pins 0-31, the second pins 32-63.
volatile uint32_t *gpSetAddr = (volatile uint32_t*)(gpioBaseMem + GPSET0/4 + (pin/32));
//now write a 1 ONLY to our pin. The act of writing a 1 to the address triggers it to be set high.
*gpSetAddr = 1 << (pin & 31);
}
void setPinLow(int pin) {
assertValidPin(pin);
//first, select the appropriate register. The first register controls pins 0-31, the second pins 32-63.
volatile uint32_t *gpClrAddr = (volatile uint32_t*)(gpioBaseMem + GPCLR0/4 + (pin/32));
//now write a 1 ONLY to our pin. The act of writing a 1 to the address triggers it to be set high.
*gpClrAddr = 1 << (pin & 31);
}
void setPinState(int pin, bool state) {
state ? setPinHigh(pin) : setPinLow(pin);
}
bool readPinState(int pin) {
assertValidPin(pin);
volatile uint32_t* gpLevAddr = (volatile uint32_t*)(gpioBaseMem + GPLEV0/4 + (pin/32));
uint32_t value = *gpLevAddr;
return (value & (1 << (pin & 31))) ? 1 : 0;
}
void setPinPull(int pin, GpioPull pull) {
assertValidPin(pin);
volatile uint32_t *pudAddr = (volatile uint32_t*)(gpioBaseMem + GPPUD/4);
volatile uint32_t *pudClkAddr = (volatile uint32_t*)(gpioBaseMem + GPPUDCLK0/4 + pin/32);
*pudAddr = pull;
usleep(10);
*pudClkAddr = 1 << (pin & 31);
usleep(10);
*pudAddr = GPIOPULL_NONE;
*pudClkAddr = 0;
}
void usleep(unsigned int us) {
//explicitly exposed to allow users of the library access to a usleep function
::usleep(us);
}
uint64_t readSysTime() {
return ((uint64_t)*(timerBaseMem + TIMER_CHI/4) << 32) + (uint64_t)(*(timerBaseMem + TIMER_CLO/4));
}
}
<|endoftext|> |
<commit_before>
#include "mpris.h"
#include "dbus.h"
#include <map>
#include <vector>
#include <functional>
#include <core/sdk/IEnvironment.h>
extern "C" {
#include <unistd.h>
}
std::string thumbnailPath;
thread_local char localBuffer[4096];
static MPRISRemote remote;
static const std::map<MPRISProperty, const std::vector<const char*>> MPRISPropertyNames =
{{MPRISProperty::Volume, {"Volume", NULL}},
{MPRISProperty::PlaybackStatus, {"PlaybackStatus", NULL}},
{MPRISProperty::LoopStatus, {"LoopStatus", NULL}},
{MPRISProperty::Shuffle, {"Shuffle", NULL}},
{MPRISProperty::Metadata, {"Metadata", NULL}}};
static std::string GetMetadataString(ITrack* track, const char* key)
{
track->GetString(key, localBuffer, sizeof(localBuffer));
return std::string(localBuffer);
}
static std::string GetThumbnailPath(ITrack* track)
{
int64_t thumbnailId = track->GetInt64(track::ThumbnailId);
return thumbnailPath + std::to_string(thumbnailId) + ".jpg";
}
static class MPRISPlugin : public IPlugin {
public:
MPRISPlugin() { }
void Release() { }
const char* Name() { return "MPRIS interface"; }
const char* Version() { return "0.1.0"; }
const char* Author() { return "brunosmmm"; }
const char* Guid() { return "457df67f-f489-415f-975e-282f470b1c10"; }
bool Configurable() { return false; }
void Configure() { }
void Reload() { }
int SdkVersion() { return musik::core::sdk::SdkVersion; }
} plugin;
extern "C" void SetEnvironment(IEnvironment* environment) {
if (environment) {
environment->GetPath(PathLibrary, localBuffer, sizeof(localBuffer));
thumbnailPath = std::string(localBuffer) + "/thumbs/";
}
}
extern "C" IPlugin* GetPlugin() {
return &plugin;
}
extern "C" IPlaybackRemote* GetPlaybackRemote() {
return &remote;
}
bool MPRISRemote::MPRISInit() {
int ret = 0;
std::string requested_name;
if (this->mpris_initialized) {
return true;
}
ret = sd_bus_default_user(&(this->bus));
if (ret < 0) {
MPRISDeinit();
return false;
}
// add DBUS entries
ret = sd_bus_add_object_vtable(this->bus, NULL, "/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2", musikcube_mp_table, this);
if (ret < 0) {
MPRISDeinit();
return false;
}
ret = sd_bus_add_object_vtable(this->bus, NULL, "/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player", musikcube_mpp_table, this);
if (ret < 0) {
MPRISDeinit();
return false;
}
requested_name = std::string("org.mpris.MediaPlayer2.musikcube.instance") + std::to_string(getpid());
ret = sd_bus_request_name(this->bus, requested_name.c_str(), 0);
if (ret < 0) {
MPRISDeinit();
return false;
}
// start loop
thread.reset(new std::thread(std::bind(&MPRISRemote::MPRISLoop, this)));
return true;
}
void MPRISRemote::MPRISDeinit() {
sd_bus_close(this->bus);
sd_bus_unref(this->bus);
bus = NULL;
stop_processing = true;
if (thread) {
thread->join();
thread.reset();
}
}
void MPRISRemote::MPRISEmitChange(MPRISProperty prop) {
if (bus) {
char** strv = (char**)(MPRISPropertyNames.at(prop).data());
std::unique_lock<decltype(sd_mutex)> lock(sd_mutex);
sd_bus_emit_properties_changed_strv(bus, "/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player",
strv);
sd_bus_flush(bus);
}
};
void MPRISRemote::MPRISEmitSeek(double curpos) {
if (bus) {
int64_t position = (int64_t)(curpos*1000*1000);
std::unique_lock<decltype(sd_mutex)> lock(sd_mutex);
sd_bus_emit_signal(bus, "/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player",
"Seeked", "x", position);
}
};
void MPRISRemote::MPRISLoop() {
while (!stop_processing) {
if (bus && sd_bus_get_current_slot(bus)) {
if (sd_bus_process(bus, NULL) > 0) {
continue;
}
if (sd_bus_wait(bus, 500*1000) < 0) {
break;
}
}
}
}
void MPRISRemote::OnTrackChanged(ITrack* track) {
if (playback) {
MPRISEmitChange(MPRISProperty::Metadata);
MPRISEmitSeek(playback->GetPosition());
}
}
void MPRISRemote::OnPlaybackStateChanged(PlaybackState state) {
if (playback) {
MPRISEmitChange(MPRISProperty::PlaybackStatus);
}
}
void MPRISRemote::OnVolumeChanged(double volume) {
if (playback) {
MPRISEmitChange(MPRISProperty::Volume);
}
}
void MPRISRemote::OnPlaybackTimeChanged(double time) {
if (playback) {
MPRISEmitChange(MPRISProperty::Metadata);
MPRISEmitSeek(time);
}
}
void MPRISRemote::OnModeChanged(RepeatMode repeatMode, bool shuffled) {
if (playback) {
MPRISEmitChange(MPRISProperty::LoopStatus);
MPRISEmitChange(MPRISProperty::Shuffle);
}
}
struct MPRISMetadataValues MPRISRemote::MPRISGetMetadata() {
struct MPRISMetadataValues metadata;
if (playback) {
auto curTrack = playback->GetPlayingTrack();
if (curTrack) {
metadata.artist = GetMetadataString(curTrack, track::Artist);
metadata.title = GetMetadataString(curTrack, track::Title);
metadata.albumArtist = GetMetadataString(curTrack, track::AlbumArtist);
metadata.genre = GetMetadataString(curTrack, track::Genre);
// TODO implement track ID properly using track index in playlist if possible
metadata.trackid = std::string("/1");
metadata.album = GetMetadataString(curTrack, track::Album);
metadata.discNumber = curTrack->GetInt32(track::DiscNum);
metadata.trackNumber = curTrack->GetInt32(track::TrackNum);
metadata.length = curTrack->GetInt64(track::Duration)*1000*1000;
metadata.albumArt = GetThumbnailPath(curTrack);
metadata.available = true;
}
}
return metadata;
}
void MPRISRemote::SetPlaybackService(IPlaybackService* playback) {
std::unique_lock<decltype(sd_mutex)> lock(sd_mutex);
this->playback = playback;
mpris_initialized = MPRISInit();
}
void MPRISRemote::MPRISNext() {
if (playback) {
playback->Next();
}
}
void MPRISRemote::MPRISPrev() {
if (playback) {
playback->Previous();
}
}
void MPRISRemote::MPRISPause() {
if (playback) {
auto state = playback->GetPlaybackState();
if (state == PlaybackState::PlaybackPlaying) {
playback->PauseOrResume();
}
}
}
void MPRISRemote::MPRISPlayPause() {
if (playback) {
playback->PauseOrResume();
}
}
void MPRISRemote::MPRISStop() {
if (playback) {
playback->Stop();
}
}
void MPRISRemote::MPRISPlay() {
if (playback) {
auto state = playback->GetPlaybackState();
if (state != PlaybackState::PlaybackPlaying) {
playback->PauseOrResume();
}
}
}
void MPRISRemote::MPRISSeek(int64_t position, bool relative) {
double _pos = ((double)position)/(1000*1000);
if (playback) {
if (!relative) {
playback->SetPosition(_pos);
}
else {
double curPos = playback->GetPosition();
playback->SetPosition(curPos+_pos);
}
}
}
const char* MPRISRemote::MPRISGetPlaybackStatus() {
if (playback) {
auto state = playback->GetPlaybackState();
switch (state) {
case PlaybackState::PlaybackPlaying:
return "Playing";
case PlaybackState::PlaybackPaused:
return "Paused";
case PlaybackState::PlaybackPrepared:
case PlaybackState::PlaybackStopped:
default:
break;
}
}
return "Stopped";
}
const char* MPRISRemote::MPRISGetLoopStatus() {
if (playback) {
auto state = playback->GetRepeatMode();
switch (state) {
case RepeatMode::RepeatTrack:
return "Track";
case RepeatMode::RepeatList:
return "Playlist";
case RepeatMode::RepeatNone:
default:
break;
}
}
return "None";
}
void MPRISRemote::MPRISSetLoopStatus(const char* state) {
if (playback) {
if (!strcmp(state, "None")) {
playback->SetRepeatMode(RepeatMode::RepeatNone);
}
else if (!strcmp(state, "Playlist")) {
playback->SetRepeatMode(RepeatMode::RepeatList);
}
else if (!strcmp(state, "Track")) {
playback->SetRepeatMode(RepeatMode::RepeatTrack);
}
}
}
uint64_t MPRISRemote::MPRISGetPosition() {
if (playback) {
return (uint64_t)(playback->GetPosition()*1000*1000);
}
return 0;
}
unsigned int MPRISRemote::MPRISGetShuffleStatus() {
if (playback) {
return playback->IsShuffled() ? 1: 0;
}
return 0;
}
void MPRISRemote::MPRISSetShuffleStatus(unsigned int state) {
if (playback)
{
unsigned int isShuffled = playback->IsShuffled() ? 1: 0;
if ((state & 0x1) ^ isShuffled) {
playback->ToggleShuffle();
}
}
}
double MPRISRemote::MPRISGetVolume() {
if (playback) {
return playback->GetVolume();
}
return 0.0;
}
void MPRISRemote::MPRISSetVolume(double vol) {
if (playback) {
playback->SetVolume(vol);
}
}
MPRISMetadataValues::MPRISMetadataValues() {
trackid = "";
length = 0;
artist = "";
title = "";
album = "";
albumArtist = "";
genre = "";
comment = "";
trackNumber = 0;
discNumber = 0;
available = false;
}
<commit_msg>Revert mpris change that seems to be causing more harm than good.<commit_after>
#include "mpris.h"
#include "dbus.h"
#include <map>
#include <vector>
#include <functional>
#include <core/sdk/IEnvironment.h>
extern "C" {
#include <unistd.h>
}
std::string thumbnailPath;
thread_local char localBuffer[4096];
static MPRISRemote remote;
static const std::map<MPRISProperty, const std::vector<const char*>> MPRISPropertyNames =
{{MPRISProperty::Volume, {"Volume", NULL}},
{MPRISProperty::PlaybackStatus, {"PlaybackStatus", NULL}},
{MPRISProperty::LoopStatus, {"LoopStatus", NULL}},
{MPRISProperty::Shuffle, {"Shuffle", NULL}},
{MPRISProperty::Metadata, {"Metadata", NULL}}};
static std::string GetMetadataString(ITrack* track, const char* key)
{
track->GetString(key, localBuffer, sizeof(localBuffer));
return std::string(localBuffer);
}
static std::string GetThumbnailPath(ITrack* track)
{
int64_t thumbnailId = track->GetInt64(track::ThumbnailId);
return thumbnailPath + std::to_string(thumbnailId) + ".jpg";
}
static class MPRISPlugin : public IPlugin {
public:
MPRISPlugin() { }
void Release() { }
const char* Name() { return "MPRIS interface"; }
const char* Version() { return "0.1.0"; }
const char* Author() { return "brunosmmm"; }
const char* Guid() { return "457df67f-f489-415f-975e-282f470b1c10"; }
bool Configurable() { return false; }
void Configure() { }
void Reload() { }
int SdkVersion() { return musik::core::sdk::SdkVersion; }
} plugin;
extern "C" void SetEnvironment(IEnvironment* environment) {
if (environment) {
environment->GetPath(PathLibrary, localBuffer, sizeof(localBuffer));
thumbnailPath = std::string(localBuffer) + "/thumbs/";
}
}
extern "C" IPlugin* GetPlugin() {
return &plugin;
}
extern "C" IPlaybackRemote* GetPlaybackRemote() {
return &remote;
}
bool MPRISRemote::MPRISInit() {
int ret = 0;
std::string requested_name;
if (this->mpris_initialized) {
return true;
}
ret = sd_bus_default_user(&(this->bus));
if (ret < 0) {
MPRISDeinit();
return false;
}
// add DBUS entries
ret = sd_bus_add_object_vtable(this->bus, NULL, "/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2", musikcube_mp_table, this);
if (ret < 0) {
MPRISDeinit();
return false;
}
ret = sd_bus_add_object_vtable(this->bus, NULL, "/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player", musikcube_mpp_table, this);
if (ret < 0) {
MPRISDeinit();
return false;
}
requested_name = std::string("org.mpris.MediaPlayer2.musikcube.instance") + std::to_string(getpid());
ret = sd_bus_request_name(this->bus, requested_name.c_str(), 0);
if (ret < 0) {
MPRISDeinit();
return false;
}
// start loop
thread.reset(new std::thread(std::bind(&MPRISRemote::MPRISLoop, this)));
return true;
}
void MPRISRemote::MPRISDeinit() {
sd_bus_close(this->bus);
sd_bus_unref(this->bus);
bus = NULL;
stop_processing = true;
if (thread) {
thread->join();
thread.reset();
}
}
void MPRISRemote::MPRISEmitChange(MPRISProperty prop) {
if (bus) {
char** strv = (char**)(MPRISPropertyNames.at(prop).data());
std::unique_lock<decltype(sd_mutex)> lock(sd_mutex);
sd_bus_emit_properties_changed_strv(bus, "/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player",
strv);
sd_bus_flush(bus);
}
};
void MPRISRemote::MPRISEmitSeek(double curpos) {
if (bus) {
int64_t position = (int64_t)(curpos*1000*1000);
std::unique_lock<decltype(sd_mutex)> lock(sd_mutex);
sd_bus_emit_signal(bus, "/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player",
"Seeked", "x", position);
}
};
void MPRISRemote::MPRISLoop() {
while (!stop_processing) {
if (bus) {
if (sd_bus_process(bus, NULL) > 0) {
continue;
}
if (sd_bus_wait(bus, 500*1000) < 0) {
break;
}
}
}
}
void MPRISRemote::OnTrackChanged(ITrack* track) {
if (playback) {
MPRISEmitChange(MPRISProperty::Metadata);
MPRISEmitSeek(playback->GetPosition());
}
}
void MPRISRemote::OnPlaybackStateChanged(PlaybackState state) {
if (playback) {
MPRISEmitChange(MPRISProperty::PlaybackStatus);
}
}
void MPRISRemote::OnVolumeChanged(double volume) {
if (playback) {
MPRISEmitChange(MPRISProperty::Volume);
}
}
void MPRISRemote::OnPlaybackTimeChanged(double time) {
if (playback) {
MPRISEmitChange(MPRISProperty::Metadata);
MPRISEmitSeek(time);
}
}
void MPRISRemote::OnModeChanged(RepeatMode repeatMode, bool shuffled) {
if (playback) {
MPRISEmitChange(MPRISProperty::LoopStatus);
MPRISEmitChange(MPRISProperty::Shuffle);
}
}
struct MPRISMetadataValues MPRISRemote::MPRISGetMetadata() {
struct MPRISMetadataValues metadata;
if (playback) {
auto curTrack = playback->GetPlayingTrack();
if (curTrack) {
metadata.artist = GetMetadataString(curTrack, track::Artist);
metadata.title = GetMetadataString(curTrack, track::Title);
metadata.albumArtist = GetMetadataString(curTrack, track::AlbumArtist);
metadata.genre = GetMetadataString(curTrack, track::Genre);
// TODO implement track ID properly using track index in playlist if possible
metadata.trackid = std::string("/1");
metadata.album = GetMetadataString(curTrack, track::Album);
metadata.discNumber = curTrack->GetInt32(track::DiscNum);
metadata.trackNumber = curTrack->GetInt32(track::TrackNum);
metadata.length = curTrack->GetInt64(track::Duration)*1000*1000;
metadata.albumArt = GetThumbnailPath(curTrack);
metadata.available = true;
}
}
return metadata;
}
void MPRISRemote::SetPlaybackService(IPlaybackService* playback) {
std::unique_lock<decltype(sd_mutex)> lock(sd_mutex);
this->playback = playback;
mpris_initialized = MPRISInit();
}
void MPRISRemote::MPRISNext() {
if (playback) {
playback->Next();
}
}
void MPRISRemote::MPRISPrev() {
if (playback) {
playback->Previous();
}
}
void MPRISRemote::MPRISPause() {
if (playback) {
auto state = playback->GetPlaybackState();
if (state == PlaybackState::PlaybackPlaying) {
playback->PauseOrResume();
}
}
}
void MPRISRemote::MPRISPlayPause() {
if (playback) {
playback->PauseOrResume();
}
}
void MPRISRemote::MPRISStop() {
if (playback) {
playback->Stop();
}
}
void MPRISRemote::MPRISPlay() {
if (playback) {
auto state = playback->GetPlaybackState();
if (state != PlaybackState::PlaybackPlaying) {
playback->PauseOrResume();
}
}
}
void MPRISRemote::MPRISSeek(int64_t position, bool relative) {
double _pos = ((double)position)/(1000*1000);
if (playback) {
if (!relative) {
playback->SetPosition(_pos);
}
else {
double curPos = playback->GetPosition();
playback->SetPosition(curPos+_pos);
}
}
}
const char* MPRISRemote::MPRISGetPlaybackStatus() {
if (playback) {
auto state = playback->GetPlaybackState();
switch (state) {
case PlaybackState::PlaybackPlaying:
return "Playing";
case PlaybackState::PlaybackPaused:
return "Paused";
case PlaybackState::PlaybackPrepared:
case PlaybackState::PlaybackStopped:
default:
break;
}
}
return "Stopped";
}
const char* MPRISRemote::MPRISGetLoopStatus() {
if (playback) {
auto state = playback->GetRepeatMode();
switch (state) {
case RepeatMode::RepeatTrack:
return "Track";
case RepeatMode::RepeatList:
return "Playlist";
case RepeatMode::RepeatNone:
default:
break;
}
}
return "None";
}
void MPRISRemote::MPRISSetLoopStatus(const char* state) {
if (playback) {
if (!strcmp(state, "None")) {
playback->SetRepeatMode(RepeatMode::RepeatNone);
}
else if (!strcmp(state, "Playlist")) {
playback->SetRepeatMode(RepeatMode::RepeatList);
}
else if (!strcmp(state, "Track")) {
playback->SetRepeatMode(RepeatMode::RepeatTrack);
}
}
}
uint64_t MPRISRemote::MPRISGetPosition() {
if (playback) {
return (uint64_t)(playback->GetPosition()*1000*1000);
}
return 0;
}
unsigned int MPRISRemote::MPRISGetShuffleStatus() {
if (playback) {
return playback->IsShuffled() ? 1: 0;
}
return 0;
}
void MPRISRemote::MPRISSetShuffleStatus(unsigned int state) {
if (playback)
{
unsigned int isShuffled = playback->IsShuffled() ? 1: 0;
if ((state & 0x1) ^ isShuffled) {
playback->ToggleShuffle();
}
}
}
double MPRISRemote::MPRISGetVolume() {
if (playback) {
return playback->GetVolume();
}
return 0.0;
}
void MPRISRemote::MPRISSetVolume(double vol) {
if (playback) {
playback->SetVolume(vol);
}
}
MPRISMetadataValues::MPRISMetadataValues() {
trackid = "";
length = 0;
artist = "";
title = "";
album = "";
albumArtist = "";
genre = "";
comment = "";
trackNumber = 0;
discNumber = 0;
available = false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (uint64_t)GetProofOfWorkReward(0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
Object obj, diff, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(0)));
obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
weight.push_back(Pair("minimum", (uint64_t)nMinWeight));
weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
obj.push_back(Pair("stakeinterest", (uint64_t)COIN_YEAR_REWARD));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
uint64_t nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
int nExpectedTime = staking ? (nTargetSpacing * nNetworkWeight / nWeight) : -1;
Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "DFSCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "DFSCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "DFSCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "DFSCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "DFSCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "DFSCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
<commit_msg>Delete rpcmining.cpp<commit_after><|endoftext|> |
<commit_before>#include "memc/Compiler.hpp"
namespace memc {
Compiler::Compiler (opt::Options* opts)
{
mem::log::Formatter* formatter = NULL;
// TODO: Should use a factory or something here
if (opts->getStr("--log-formatter") == "test-friendly")
{
formatter = new mem::log::TestFriendlyFormatter();
}
else
{
mem::log::ConsoleFormatter* cons_formatter = new mem::log::ConsoleFormatter();
if (opts->getStrEnum("--color") == "yes")
{
cons_formatter->setColorsEnabled(true);
}
else
{
cons_formatter->setColorsEnabled(false);
}
formatter = cons_formatter;
}
_logger = new mem::log::ConsoleLogger();
_logger->setFormatter(formatter);
_parser = new langmem::Parse();
_parser->setLogger(_logger);
_parser->setSymbolTable(&symbols);
_opts = opts;
addDecorator(new mem::decorator::External());
addDecorator(new mem::decorator::Overriding());
addDecorator(new mem::decorator::Require());
addDecorator(new mem::decorator::Virtual());
addMacro(new mem::ast::macro::PtrMacros());
// Setup AST visitors
addAstVisitor(new mem::ast::visitor::CoherenceChecker());
addAstVisitor(new mem::ast::visitor::UseAlias());
addAstVisitor(new mem::ast::visitor::Prechecker());
addAstVisitor(new mem::ast::visitor::FindClasses());
addAstVisitor(new mem::ast::visitor::TopTypesChecker());
addAstVisitor(new mem::ast::visitor::Decorate(_decorators));
addAstVisitor(new mem::ast::visitor::Ctor());
addAstVisitor(new mem::ast::visitor::BlockTypesChecker());
addAstVisitor(new mem::ast::visitor::CoherenceChecker());
addAstVisitor(new mem::ast::visitor::CheckValidity());
addAstVisitor(new mem::ast::visitor::FindEntryPoint());
addAstVisitor(new mem::ast::visitor::Stats());
mem::st::util::setupBool(this->symbols, this->symbols.gCoreTypes());
mem::st::util::setupBugType(this->symbols, this->symbols.gCoreTypes());
mem::st::util::setupInts(this->symbols, this->symbols.gCoreTypes());
mem::st::util::setupVoid(this->symbols, this->symbols.gCoreTypes());
}
Compiler::~Compiler ()
{
delete _logger;
delete _parser;
mem::decorator::DecoratorMap::iterator i;
for (i = _decorators.begin(); i != _decorators.end(); ++i)
{
delete i->second;
}
// Delete AST visitors
for (size_t i = 0; i < ast_visitors.size(); ++i)
{
delete ast_visitors[i];
}
// Delete ST visitors
for (size_t i = 0; i < st_visitors.size(); ++i)
{
delete st_visitors[i];
}
}
void
Compiler::addDecorator (mem::decorator::Decorator* dec)
{
DEBUG_REQUIRE (dec != NULL);
if (_decorators.find(dec->Name()) == _decorators.end())
{
_decorators[dec->Name()] = dec;
}
}
void
Compiler::addMacro (mem::ast::macro::Macro* macro)
{
DEBUG_REQUIRE (macro != NULL);
mem::st::Macro* macro_sym = macro->getSymbol();
symbols.System()->addChild(macro_sym);
delete macro;
}
void
Compiler::dumpAst ()
{
if (_opts->isSet("--dump-ast-xml"))
{
std::string dump_path = _opts->getStr("--dump-ast-xml");
std::ofstream dump_file(dump_path.c_str());
mem::ast::visitor::XmlDumper dumper;
dumper.Out(&dump_file);
dumper.setup();
dumper.visit(&ast);
dumper.tearDown();
dump_file.close();
_logger->info("AST dumped to %s (XML)", dump_path.c_str());
}
}
void
Compiler::dumpSt ()
{
if (_opts->isSet("--dump-st-xml"))
{
std::string dump_path = _opts->getStr("--dump-st-xml");
// Open dump file
// TODO We should have a default output file in case the user did not
// give one
std::ofstream st_dump_file(dump_path.c_str());
mem::st::visitor::XmlDumper dumper;
dumper._out = &st_dump_file;
dumper.setup();
dumper.visitPreorder(symbols.Root());
st_dump_file.close();
_logger->info("SymbolTable dumped to %s (XML)", dump_path.c_str());
}
}
void
Compiler::emitCode ()
{
if (_opts->hasArguments())
{
#ifdef HAVE_LLVM
std::string llvm_ir_path = "./mem.bc";
std::string bin_path = "./mem.out";
if (_opts->isSet("--emit-llvm-bc"))
{
llvm_ir_path = _opts->getStr("--emit-llvm-bc");
}
if (_opts->isSet("--output"))
{
bin_path = _opts->getStr("--output");
}
codegen::llvm_::Codegen cg;
cg.setSymbolTable(&symbols);
cg.gen(&ast);
// Dump LLVM bytecode
std::ofstream bc_file;
bc_file.open(llvm_ir_path.c_str());
bc_file << cg.getLlvmByteCode();
bc_file.close();
_logger->info("LLVM ByteCode dumped to %s", llvm_ir_path.c_str());
// Generate native code
std::string out_s = llvm_ir_path + ".s";
std::string out_as = llvm_ir_path + ".as";
tool::CommandChain cc (_tools);
cc.run(Toolbox::LLVM_COMPILER, "-o=" + out_s + " " + llvm_ir_path)
->then(Toolbox::GCC, out_s + " -o " + bin_path);
if (cc.Status() == 0)
{
_logger->debug("Binary generated as %s", bin_path.c_str());
}
else
{
_logger->fatalError("Couldn't generate binary as %s",
bin_path.c_str());
}
#endif // HAVE_LLVM
}
}
void
Compiler::parse (std::string file_path)
{
_logger->debug("[%s] parsing...", file_path.c_str());
std::string ns_name = mem::Util::getNamespaceNameFromPath(file_path);
std::vector<std::string> ns_parts = mem::Util::split(ns_name, '.');
mem::st::Namespace* file_sym = mem::st::util::createNamespace(symbols.Home(), ns_parts);
assert(file_sym != NULL);
std::vector<std::string> paths_tried;
mem::fs::File* file = fm.tryOpenFile(file_path, paths_tried);
if (file != NULL)
{
mem::ast::node::File* file_node = NULL;
gTOKENIZER.reset();
gTOKENIZER.setInputFile(file->Path());
file_node = _parser->parse (file);
file_node->setBoundSymbol(file_sym);
file_node->setId(ns_name);
file_node->setIncludePath(file->IncludePath());
file_node->setPath(file_path);
ast.addChild(file_node);
mem::ast::visitor::FindUse find_use;
_logger->debug("Searching for use statements", "");
find_use.visit_preorder(file_node);
for (size_t i = 0; i < find_use._uses.size(); ++i)
{
if (ns_name == find_use._uses[i])
{
// FIXME This thing is probably failing, should use a pointer.
mem::log::Message warn(mem::log::WARNING);
warn.formatMessage(
"File {path:%s} is trying to include itself: include ignored.",
file_path.c_str()
);
_logger->log(&warn);
}
else
{
std::string rel_file_path (find_use._uses[i]);
mem::Util::namespace_to_path(rel_file_path);
rel_file_path += ".mem";
this->_parse_queue.push(rel_file_path);
}
}
}
else
{
std::string description = "We tried :\n";
std::vector<std::string>::size_type i;
for (i=0; i<paths_tried.size(); ++i)
{
description.append("* {path:" + paths_tried[i] + "}\n");
}
mem::log::Message* msg = new mem::log::Error();
msg->formatMessage("Couldn't open file {path:%s}.", file_path.c_str());
msg->setSecondaryText(description);
_logger->log(msg);
}
}
void
Compiler::printBuildSummary ()
{
std::ostringstream sec_text;
if (_logger->FatalErrorCount() > 0)
{
sec_text << "Fatal errors: ";
sec_text << _logger->FatalErrorCount();
sec_text << "\n";
}
if (_logger->ErrorCount() > 0)
{
sec_text << "Errors: ";
sec_text << _logger->ErrorCount();
sec_text << "\n";
}
if (_logger->WarningCount() > 0)
{
sec_text << "Warnings: ";
sec_text << _logger->WarningCount();
sec_text << "\n";
}
if (isBuildSuccessful())
{
_logger->info("Build SUCCESSFUL", "");
}
else
{
mem::log::Message* err = new mem::log::FatalError();
err->setPrimaryText("Build FAILED");
err->setSecondaryText(sec_text.str());
_logger->log(err);
}
}
void
Compiler::printUsage (std::ostream& out)
{
out << "USAGE: ";
#ifdef PACKAGE_NAME
out << PACKAGE_NAME;
#else
out << "?";
#endif
out << " [OPTIONS] <input>\n\n";
out << "OPTIONS:\n";
_opts->dump(out);
/*
std::map<std::string, opt::CliOption*>::iterator i;
for (i = _opts->_cli_options.begin(); i != _opts->_cli_options.end(); ++i)
{
if (i->second != NULL)
{
out << " --";
out << i->second->_cli_name;
out << " : \n ";
out << i->second->_description;
out << "\n";
}
}
*/
}
void
Compiler::processParseQueue ()
{
while (!_parse_queue.empty())
{
parse(_parse_queue.front());
_parse_queue.pop();
}
}
void
Compiler::run ()
{
std::string formatter_id = _opts->getStr("--log-formatter");
if (formatter_id == "xml")
{
_logger->setFormatter(new mem::log::XmlFormatter());
}
_logger->begin();
fm.appendPath(".");
// Need to set this before parsing command line arguments because it can
// raise warnings
#ifdef NDEBUG
_logger->setLevel(mem::log::INFO);
#else
_logger->setLevel(mem::log::DEBUG);
#endif
if (_opts->isSet("--log-level"))
{
_logger->setLevel(_opts->getInt("--log-level"));
}
if (_opts->isSet("--version"))
{
std::cout << PACKAGE_NAME " version " PACKAGE_VERSION;
std::cout << " (" __DATE__ " " __TIME__ ")";
IF_DEBUG
{
std::cout << " [DEBUG]";
}
std::cout << "\n\n";
std::cout << " Build date: " << __DATE__ << "\n";
std::cout << " Build time: " << __TIME__ << "\n";
std::cout << " Compiler: " << COMPILER_NAME << "\n";
std::cout << " Compiler flags: " << COMPILER_FLAGS << "\n";
std::cout << " Version: " << PACKAGE_VERSION << "\n";
std::cout << " Yacc: " << YACC_EXE << "\n";
}
else if (_opts->isSet("--help"))
{
printUsage(std::cout);
}
else if (_opts->hasArguments())
{
_parse_queue.push(_opts->getArgument(0));
processParseQueue();
runAstVisitors();
//runStVisitors();
dumpAst();
dumpSt();
if (isBuildSuccessful()) emitCode();
printBuildSummary();
}
_logger->finish();
}
void
Compiler::runAstVisitors ()
{
for (size_t i=0;
i < ast_visitors.size() && _logger->FatalErrorCount() == 0 && _logger->ErrorCount()==0; ++i)
{
_logger->debug("[%s] running...", ast_visitors[i]->_name.c_str());
ast_visitors[i]->SymbolTable(&symbols);
ast_visitors[i]->Logger(_logger);
ast_visitors[i]->setup();
ast_visitors[i]->visit_preorder(&ast);
ast_visitors[i]->tearDown();
}
}
void
Compiler::runStVisitors ()
{
for (size_t i = 0; i < st_visitors.size(); ++i)
{
_logger->debug("[%s] running...", st_visitors[i]->gNameCstr());
st_visitors[i]->setup();
st_visitors[i]->visitPreorder(symbols.Root());
st_visitors[i]->tearDown();
}
}
}
<commit_msg>Add id to `build failed` log message<commit_after>#include "memc/Compiler.hpp"
namespace memc {
Compiler::Compiler (opt::Options* opts)
{
mem::log::Formatter* formatter = NULL;
// TODO: Should use a factory or something here
if (opts->getStr("--log-formatter") == "test-friendly")
{
formatter = new mem::log::TestFriendlyFormatter();
}
else
{
mem::log::ConsoleFormatter* cons_formatter = new mem::log::ConsoleFormatter();
if (opts->getStrEnum("--color") == "yes")
{
cons_formatter->setColorsEnabled(true);
}
else
{
cons_formatter->setColorsEnabled(false);
}
formatter = cons_formatter;
}
_logger = new mem::log::ConsoleLogger();
_logger->setFormatter(formatter);
_parser = new langmem::Parse();
_parser->setLogger(_logger);
_parser->setSymbolTable(&symbols);
_opts = opts;
addDecorator(new mem::decorator::External());
addDecorator(new mem::decorator::Overriding());
addDecorator(new mem::decorator::Require());
addDecorator(new mem::decorator::Virtual());
addMacro(new mem::ast::macro::PtrMacros());
// Setup AST visitors
addAstVisitor(new mem::ast::visitor::CoherenceChecker());
addAstVisitor(new mem::ast::visitor::UseAlias());
addAstVisitor(new mem::ast::visitor::Prechecker());
addAstVisitor(new mem::ast::visitor::FindClasses());
addAstVisitor(new mem::ast::visitor::TopTypesChecker());
addAstVisitor(new mem::ast::visitor::Decorate(_decorators));
addAstVisitor(new mem::ast::visitor::Ctor());
addAstVisitor(new mem::ast::visitor::BlockTypesChecker());
addAstVisitor(new mem::ast::visitor::CoherenceChecker());
addAstVisitor(new mem::ast::visitor::CheckValidity());
addAstVisitor(new mem::ast::visitor::FindEntryPoint());
addAstVisitor(new mem::ast::visitor::Stats());
mem::st::util::setupBool(this->symbols, this->symbols.gCoreTypes());
mem::st::util::setupBugType(this->symbols, this->symbols.gCoreTypes());
mem::st::util::setupInts(this->symbols, this->symbols.gCoreTypes());
mem::st::util::setupVoid(this->symbols, this->symbols.gCoreTypes());
}
Compiler::~Compiler ()
{
delete _logger;
delete _parser;
mem::decorator::DecoratorMap::iterator i;
for (i = _decorators.begin(); i != _decorators.end(); ++i)
{
delete i->second;
}
// Delete AST visitors
for (size_t i = 0; i < ast_visitors.size(); ++i)
{
delete ast_visitors[i];
}
// Delete ST visitors
for (size_t i = 0; i < st_visitors.size(); ++i)
{
delete st_visitors[i];
}
}
void
Compiler::addDecorator (mem::decorator::Decorator* dec)
{
DEBUG_REQUIRE (dec != NULL);
if (_decorators.find(dec->Name()) == _decorators.end())
{
_decorators[dec->Name()] = dec;
}
}
void
Compiler::addMacro (mem::ast::macro::Macro* macro)
{
DEBUG_REQUIRE (macro != NULL);
mem::st::Macro* macro_sym = macro->getSymbol();
symbols.System()->addChild(macro_sym);
delete macro;
}
void
Compiler::dumpAst ()
{
if (_opts->isSet("--dump-ast-xml"))
{
std::string dump_path = _opts->getStr("--dump-ast-xml");
std::ofstream dump_file(dump_path.c_str());
mem::ast::visitor::XmlDumper dumper;
dumper.Out(&dump_file);
dumper.setup();
dumper.visit(&ast);
dumper.tearDown();
dump_file.close();
_logger->info("AST dumped to %s (XML)", dump_path.c_str());
}
}
void
Compiler::dumpSt ()
{
if (_opts->isSet("--dump-st-xml"))
{
std::string dump_path = _opts->getStr("--dump-st-xml");
// Open dump file
// TODO We should have a default output file in case the user did not
// give one
std::ofstream st_dump_file(dump_path.c_str());
mem::st::visitor::XmlDumper dumper;
dumper._out = &st_dump_file;
dumper.setup();
dumper.visitPreorder(symbols.Root());
st_dump_file.close();
_logger->info("SymbolTable dumped to %s (XML)", dump_path.c_str());
}
}
void
Compiler::emitCode ()
{
if (_opts->hasArguments())
{
#ifdef HAVE_LLVM
std::string llvm_ir_path = "./mem.bc";
std::string bin_path = "./mem.out";
if (_opts->isSet("--emit-llvm-bc"))
{
llvm_ir_path = _opts->getStr("--emit-llvm-bc");
}
if (_opts->isSet("--output"))
{
bin_path = _opts->getStr("--output");
}
codegen::llvm_::Codegen cg;
cg.setSymbolTable(&symbols);
cg.gen(&ast);
// Dump LLVM bytecode
std::ofstream bc_file;
bc_file.open(llvm_ir_path.c_str());
bc_file << cg.getLlvmByteCode();
bc_file.close();
_logger->info("LLVM ByteCode dumped to %s", llvm_ir_path.c_str());
// Generate native code
std::string out_s = llvm_ir_path + ".s";
std::string out_as = llvm_ir_path + ".as";
tool::CommandChain cc (_tools);
cc.run(Toolbox::LLVM_COMPILER, "-o=" + out_s + " " + llvm_ir_path)
->then(Toolbox::GCC, out_s + " -o " + bin_path);
if (cc.Status() == 0)
{
_logger->debug("Binary generated as %s", bin_path.c_str());
}
else
{
_logger->fatalError("Couldn't generate binary as %s",
bin_path.c_str());
}
#endif // HAVE_LLVM
}
}
void
Compiler::parse (std::string file_path)
{
_logger->debug("[%s] parsing...", file_path.c_str());
std::string ns_name = mem::Util::getNamespaceNameFromPath(file_path);
std::vector<std::string> ns_parts = mem::Util::split(ns_name, '.');
mem::st::Namespace* file_sym = mem::st::util::createNamespace(symbols.Home(), ns_parts);
assert(file_sym != NULL);
std::vector<std::string> paths_tried;
mem::fs::File* file = fm.tryOpenFile(file_path, paths_tried);
if (file != NULL)
{
mem::ast::node::File* file_node = NULL;
gTOKENIZER.reset();
gTOKENIZER.setInputFile(file->Path());
file_node = _parser->parse (file);
file_node->setBoundSymbol(file_sym);
file_node->setId(ns_name);
file_node->setIncludePath(file->IncludePath());
file_node->setPath(file_path);
ast.addChild(file_node);
mem::ast::visitor::FindUse find_use;
_logger->debug("Searching for use statements", "");
find_use.visit_preorder(file_node);
for (size_t i = 0; i < find_use._uses.size(); ++i)
{
if (ns_name == find_use._uses[i])
{
// FIXME This thing is probably failing, should use a pointer.
mem::log::Message warn(mem::log::WARNING);
warn.formatMessage(
"File {path:%s} is trying to include itself: include ignored.",
file_path.c_str()
);
_logger->log(&warn);
}
else
{
std::string rel_file_path (find_use._uses[i]);
mem::Util::namespace_to_path(rel_file_path);
rel_file_path += ".mem";
this->_parse_queue.push(rel_file_path);
}
}
}
else
{
std::string description = "We tried :\n";
std::vector<std::string>::size_type i;
for (i=0; i<paths_tried.size(); ++i)
{
description.append("* {path:" + paths_tried[i] + "}\n");
}
mem::log::Message* msg = new mem::log::Error();
msg->formatMessage("Couldn't open file {path:%s}.", file_path.c_str());
msg->setSecondaryText(description);
_logger->log(msg);
}
}
void
Compiler::printBuildSummary ()
{
std::ostringstream sec_text;
if (_logger->FatalErrorCount() > 0)
{
sec_text << "Fatal errors: ";
sec_text << _logger->FatalErrorCount();
sec_text << "\n";
}
if (_logger->ErrorCount() > 0)
{
sec_text << "Errors: ";
sec_text << _logger->ErrorCount();
sec_text << "\n";
}
if (_logger->WarningCount() > 0)
{
sec_text << "Warnings: ";
sec_text << _logger->WarningCount();
sec_text << "\n";
}
if (isBuildSuccessful())
{
_logger->info("Build SUCCESSFUL", "");
}
else
{
mem::log::Message* err = new mem::log::FatalError();
err->setPrimaryText("Build FAILED");
err->setId("build-failed");
err->setSecondaryText(sec_text.str());
_logger->log(err);
}
}
void
Compiler::printUsage (std::ostream& out)
{
out << "USAGE: ";
#ifdef PACKAGE_NAME
out << PACKAGE_NAME;
#else
out << "?";
#endif
out << " [OPTIONS] <input>\n\n";
out << "OPTIONS:\n";
_opts->dump(out);
/*
std::map<std::string, opt::CliOption*>::iterator i;
for (i = _opts->_cli_options.begin(); i != _opts->_cli_options.end(); ++i)
{
if (i->second != NULL)
{
out << " --";
out << i->second->_cli_name;
out << " : \n ";
out << i->second->_description;
out << "\n";
}
}
*/
}
void
Compiler::processParseQueue ()
{
while (!_parse_queue.empty())
{
parse(_parse_queue.front());
_parse_queue.pop();
}
}
void
Compiler::run ()
{
std::string formatter_id = _opts->getStr("--log-formatter");
if (formatter_id == "xml")
{
_logger->setFormatter(new mem::log::XmlFormatter());
}
_logger->begin();
fm.appendPath(".");
// Need to set this before parsing command line arguments because it can
// raise warnings
#ifdef NDEBUG
_logger->setLevel(mem::log::INFO);
#else
_logger->setLevel(mem::log::DEBUG);
#endif
if (_opts->isSet("--log-level"))
{
_logger->setLevel(_opts->getInt("--log-level"));
}
if (_opts->isSet("--version"))
{
std::cout << PACKAGE_NAME " version " PACKAGE_VERSION;
std::cout << " (" __DATE__ " " __TIME__ ")";
IF_DEBUG
{
std::cout << " [DEBUG]";
}
std::cout << "\n\n";
std::cout << " Build date: " << __DATE__ << "\n";
std::cout << " Build time: " << __TIME__ << "\n";
std::cout << " Compiler: " << COMPILER_NAME << "\n";
std::cout << " Compiler flags: " << COMPILER_FLAGS << "\n";
std::cout << " Version: " << PACKAGE_VERSION << "\n";
std::cout << " Yacc: " << YACC_EXE << "\n";
}
else if (_opts->isSet("--help"))
{
printUsage(std::cout);
}
else if (_opts->hasArguments())
{
_parse_queue.push(_opts->getArgument(0));
processParseQueue();
runAstVisitors();
//runStVisitors();
dumpAst();
dumpSt();
if (isBuildSuccessful()) emitCode();
printBuildSummary();
}
_logger->finish();
}
void
Compiler::runAstVisitors ()
{
for (size_t i=0;
i < ast_visitors.size() && _logger->FatalErrorCount() == 0 && _logger->ErrorCount()==0; ++i)
{
_logger->debug("[%s] running...", ast_visitors[i]->_name.c_str());
ast_visitors[i]->SymbolTable(&symbols);
ast_visitors[i]->Logger(_logger);
ast_visitors[i]->setup();
ast_visitors[i]->visit_preorder(&ast);
ast_visitors[i]->tearDown();
}
}
void
Compiler::runStVisitors ()
{
for (size_t i = 0; i < st_visitors.size(); ++i)
{
_logger->debug("[%s] running...", st_visitors[i]->gNameCstr());
st_visitors[i]->setup();
st_visitors[i]->visitPreorder(symbols.Root());
st_visitors[i]->tearDown();
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of HyperDex 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.
// Google Log
#include <glog/logging.h>
// HyperDex
#include <hyperdex/physical.h>
hyperdex :: physical :: physical(ev::loop_ref lr, const po6::net::ipaddr& ip, bool listen)
: m_lr(lr)
, m_wakeup(lr)
, m_listen(ip.family(), SOCK_STREAM, IPPROTO_TCP)
, m_listen_event(lr)
, m_bindto()
, m_lock()
, m_channels()
, m_location_map()
, m_incoming()
{
// Enable other threads to wake us from the event loop.
m_wakeup.set<physical, &physical::refresh>(this);
m_wakeup.start();
if (listen)
{
// Enable other hosts to connect to us.
m_listen.bind(po6::net::location(ip, 0));
m_listen.listen(4);
m_listen_event.set<physical, &physical::accept_connection>(this);
m_listen_event.set(m_listen.get(), ev::READ);
m_listen_event.start();
}
else
{
m_listen.close();
}
// Setup a channel which connects to ourself. The purpose of this channel
// is two-fold: first, it gives a really cheap way of doing self-messaging
// without the queue at the higher layer (at the expense of a bigger
// performance hit); second, it gives us a way to get a port to which we
// may bind repeatedly when establishing connections.
//
// TODO: Make establishing this channel only serve the second purpose.
if (listen)
{
std::tr1::shared_ptr<channel> chan;
chan.reset(new channel(m_lr, this, po6::net::location(ip, 0), m_listen.getsockname()));
m_location_map[chan->loc] = m_channels.size();
m_channels.push_back(chan);
m_bindto = chan->soc.getsockname();
}
else
{
m_bindto = po6::net::location(ip, 0);
}
}
hyperdex :: physical :: ~physical()
{
}
void
hyperdex :: physical :: send(const po6::net::location& to,
const e::buffer& msg)
{
// Get a reference to the channel for "to" with mtx held.
m_lock.rdlock();
std::map<po6::net::location, size_t>::iterator position;
std::tr1::shared_ptr<channel> chan;
if ((position = m_location_map.find(to)) == m_location_map.end())
{
m_lock.unlock();
m_lock.wrlock();
chan = create_connection(to);
if (!chan)
{
m_lock.unlock();
return;
}
}
else
{
chan = m_channels[position->second];
}
chan->mtx.lock();
m_lock.unlock();
// Add msg to the outgoing buffer.
bool notify = chan->outgoing.empty() && chan->outprogress.empty();
chan->outgoing.push(msg);
// Notify the event loop thread.
if (notify)
{
m_wakeup.send();
}
chan->mtx.unlock();
}
bool
hyperdex :: physical :: recv(po6::net::location* from,
e::buffer* msg)
{
message m;
bool ret = m_incoming.pop(&m);
*from = m.loc;
*msg = m.buf;
return ret;
}
void
hyperdex :: physical :: shutdown()
{
m_incoming.shutdown();
}
// Invariant: m_lock.wrlock must be held.
std::tr1::shared_ptr<hyperdex :: physical :: channel>
hyperdex :: physical :: create_connection(const po6::net::location& to)
{
std::map<po6::net::location, size_t>::iterator position;
if ((position = m_location_map.find(to)) != m_location_map.end())
{
return m_channels[position->second];
}
try
{
std::tr1::shared_ptr<channel> chan;
chan.reset(new channel(m_lr, this, m_bindto, to));
place_channel(chan);
return chan;
}
catch (...)
{
return std::tr1::shared_ptr<channel>();
}
}
// Invariant: no locks may be held.
void
hyperdex :: physical :: remove_connection(channel* to_remove)
{
m_lock.wrlock();
po6::net::location loc = to_remove->loc;
std::map<po6::net::location, size_t>::iterator iter = m_location_map.find(loc);
if (iter == m_location_map.end())
{
LOG(FATAL) << "The physical layer's address map got out of sync with its open channels.";
}
size_t index = iter->second;
m_location_map.erase(iter);
// This lock/unlock pair is necessary to ensure the channel is no longer in
// use. As we know that we are the only one who can use m_location_map and
// m_channels, the only other possibility is that a send is in-progress
// (after the rdlock is released, but before the chan lock is released).
// Once this succeeds, we know that no one else may possibly use this
// channel.
m_channels[index]->mtx.lock();
m_channels[index]->mtx.unlock();
m_channels[index] = std::tr1::shared_ptr<channel>();
m_lock.unlock();
}
void
hyperdex :: physical :: refresh(ev::async&, int)
{
m_lock.rdlock();
for (std::map<po6::net::location, size_t>::iterator i = m_location_map.begin();
i != m_location_map.end(); ++ i)
{
if (m_channels[i->second])
{
m_channels[i->second]->mtx.lock();
int flags = ev::READ;
// If there is data to write.
if (m_channels[i->second]->outprogress.size() > 0 ||
m_channels[i->second]->outgoing.size() > 0)
{
flags |= ev::WRITE;
}
m_channels[i->second]->io.set(flags);
m_channels[i->second]->mtx.unlock();
}
}
m_lock.unlock();
}
void
hyperdex :: physical :: accept_connection(ev::io&, int)
{
std::tr1::shared_ptr<channel> chan;
try
{
chan.reset(new channel(m_lr, this, &m_listen));
}
catch (po6::error& e)
{
return;
}
m_lock.wrlock();
try
{
place_channel(chan);
}
catch (...)
{
m_lock.unlock();
throw;
}
m_lock.unlock();
}
// Invariant: m_lock.wrlock must be held.
void
hyperdex :: physical :: place_channel(std::tr1::shared_ptr<channel> chan)
{
// Find an empty slot.
for (size_t i = 0; i < m_channels.size(); ++i)
{
if (!m_channels[i])
{
m_channels[i] = chan;
m_location_map[chan->loc] = i;
return;
}
}
// Resize to create new slots.
m_location_map[chan->loc] = m_channels.size();
m_channels.push_back(chan);
}
hyperdex :: physical :: channel :: channel(ev::loop_ref lr,
physical* m,
po6::net::socket* accept_from)
: mtx()
, soc()
, loc()
, io(lr)
, inprogress()
, outprogress()
, outgoing()
, manager(m)
{
accept_from->accept(&soc);
loc = soc.getpeername();
io.set<channel, &channel::io_cb>(this);
io.set(soc.get(), ev::READ);
io.start();
}
hyperdex :: physical :: channel :: channel(ev::loop_ref lr,
physical* m,
const po6::net::location& from,
const po6::net::location& to)
: mtx()
, soc(to.address.family(), SOCK_STREAM, IPPROTO_TCP)
, loc(to)
, io(lr)
, inprogress()
, outprogress()
, outgoing()
, manager(m)
{
io.set<channel, &channel::io_cb>(this);
io.set(soc.get(), ev::READ);
io.start();
soc.reuseaddr(true);
soc.bind(from);
soc.connect(to);
}
hyperdex :: physical :: channel :: ~channel()
{
io.stop();
}
#define IO_BLOCKSIZE 65536
void
hyperdex :: physical :: channel :: io_cb(ev::io& w, int revents)
{
if (revents & ev::READ)
{
read_cb(w);
}
if (revents & ev::WRITE)
{
write_cb(w);
}
}
void
hyperdex :: physical :: channel :: read_cb(ev::io&)
{
if (!mtx.trylock())
{
return;
}
char block[IO_BLOCKSIZE];
try
{
size_t ret = soc.read(block, IO_BLOCKSIZE);
inprogress += e::buffer(block, ret);
if (ret == 0)
{
mtx.unlock();
manager->remove_connection(this);
return;
}
while (inprogress.size() >= sizeof(uint32_t))
{
e::unpacker up(inprogress);
uint32_t message_size;
up >> message_size;
if (inprogress.size() < message_size + sizeof(uint32_t))
{
break;
}
e::buffer buf;
up >> buf;
message m;
m.loc = loc;
m.buf = buf;
manager->m_incoming.push(m);
inprogress.trim_prefix(message_size + sizeof(uint32_t));
}
}
catch (po6::error& e)
{
if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
{
LOG(ERROR) << "could not read from " << loc << "; closing";
mtx.unlock();
manager->remove_connection(this);
return;
}
}
mtx.unlock();
}
void
hyperdex :: physical :: channel :: write_cb(ev::io&)
{
if (!mtx.trylock())
{
return;
}
if (outgoing.empty() && outprogress.empty())
{
io.set(ev::READ);
mtx.unlock();
// XXX this probably means we need to shut it down.
return;
}
// Pop one message to flush to network.
if (outprogress.empty())
{
uint32_t size = outgoing.front().size();
outprogress.pack() << size << outgoing.front();
outgoing.pop();
}
try
{
size_t ret = soc.write(outprogress.get(), outprogress.size());
outprogress.trim_prefix(ret);
}
catch (po6::error& e)
{
if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
{
LOG(ERROR) << "could not write to " << loc << "; closing";
mtx.unlock();
manager->remove_connection(this);
return;
}
}
mtx.unlock();
}
hyperdex :: physical :: message :: message()
: loc()
, buf()
{
}
hyperdex :: physical :: message :: ~message()
{
}
<commit_msg>Use the proper pack/unpack routines for buffer.<commit_after>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of HyperDex 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.
// Google Log
#include <glog/logging.h>
// HyperDex
#include <hyperdex/physical.h>
hyperdex :: physical :: physical(ev::loop_ref lr, const po6::net::ipaddr& ip, bool listen)
: m_lr(lr)
, m_wakeup(lr)
, m_listen(ip.family(), SOCK_STREAM, IPPROTO_TCP)
, m_listen_event(lr)
, m_bindto()
, m_lock()
, m_channels()
, m_location_map()
, m_incoming()
{
// Enable other threads to wake us from the event loop.
m_wakeup.set<physical, &physical::refresh>(this);
m_wakeup.start();
if (listen)
{
// Enable other hosts to connect to us.
m_listen.bind(po6::net::location(ip, 0));
m_listen.listen(4);
m_listen_event.set<physical, &physical::accept_connection>(this);
m_listen_event.set(m_listen.get(), ev::READ);
m_listen_event.start();
}
else
{
m_listen.close();
}
// Setup a channel which connects to ourself. The purpose of this channel
// is two-fold: first, it gives a really cheap way of doing self-messaging
// without the queue at the higher layer (at the expense of a bigger
// performance hit); second, it gives us a way to get a port to which we
// may bind repeatedly when establishing connections.
//
// TODO: Make establishing this channel only serve the second purpose.
if (listen)
{
std::tr1::shared_ptr<channel> chan;
chan.reset(new channel(m_lr, this, po6::net::location(ip, 0), m_listen.getsockname()));
m_location_map[chan->loc] = m_channels.size();
m_channels.push_back(chan);
m_bindto = chan->soc.getsockname();
}
else
{
m_bindto = po6::net::location(ip, 0);
}
}
hyperdex :: physical :: ~physical()
{
}
void
hyperdex :: physical :: send(const po6::net::location& to,
const e::buffer& msg)
{
// Get a reference to the channel for "to" with mtx held.
m_lock.rdlock();
std::map<po6::net::location, size_t>::iterator position;
std::tr1::shared_ptr<channel> chan;
if ((position = m_location_map.find(to)) == m_location_map.end())
{
m_lock.unlock();
m_lock.wrlock();
chan = create_connection(to);
if (!chan)
{
m_lock.unlock();
return;
}
}
else
{
chan = m_channels[position->second];
}
chan->mtx.lock();
m_lock.unlock();
// Add msg to the outgoing buffer.
bool notify = chan->outgoing.empty() && chan->outprogress.empty();
chan->outgoing.push(msg);
// Notify the event loop thread.
if (notify)
{
m_wakeup.send();
}
chan->mtx.unlock();
}
bool
hyperdex :: physical :: recv(po6::net::location* from,
e::buffer* msg)
{
message m;
bool ret = m_incoming.pop(&m);
*from = m.loc;
*msg = m.buf;
return ret;
}
void
hyperdex :: physical :: shutdown()
{
m_incoming.shutdown();
}
// Invariant: m_lock.wrlock must be held.
std::tr1::shared_ptr<hyperdex :: physical :: channel>
hyperdex :: physical :: create_connection(const po6::net::location& to)
{
std::map<po6::net::location, size_t>::iterator position;
if ((position = m_location_map.find(to)) != m_location_map.end())
{
return m_channels[position->second];
}
try
{
std::tr1::shared_ptr<channel> chan;
chan.reset(new channel(m_lr, this, m_bindto, to));
place_channel(chan);
return chan;
}
catch (...)
{
return std::tr1::shared_ptr<channel>();
}
}
// Invariant: no locks may be held.
void
hyperdex :: physical :: remove_connection(channel* to_remove)
{
m_lock.wrlock();
po6::net::location loc = to_remove->loc;
std::map<po6::net::location, size_t>::iterator iter = m_location_map.find(loc);
if (iter == m_location_map.end())
{
LOG(FATAL) << "The physical layer's address map got out of sync with its open channels.";
}
size_t index = iter->second;
m_location_map.erase(iter);
// This lock/unlock pair is necessary to ensure the channel is no longer in
// use. As we know that we are the only one who can use m_location_map and
// m_channels, the only other possibility is that a send is in-progress
// (after the rdlock is released, but before the chan lock is released).
// Once this succeeds, we know that no one else may possibly use this
// channel.
m_channels[index]->mtx.lock();
m_channels[index]->mtx.unlock();
m_channels[index] = std::tr1::shared_ptr<channel>();
m_lock.unlock();
}
void
hyperdex :: physical :: refresh(ev::async&, int)
{
m_lock.rdlock();
for (std::map<po6::net::location, size_t>::iterator i = m_location_map.begin();
i != m_location_map.end(); ++ i)
{
if (m_channels[i->second])
{
m_channels[i->second]->mtx.lock();
int flags = ev::READ;
// If there is data to write.
if (m_channels[i->second]->outprogress.size() > 0 ||
m_channels[i->second]->outgoing.size() > 0)
{
flags |= ev::WRITE;
}
m_channels[i->second]->io.set(flags);
m_channels[i->second]->mtx.unlock();
}
}
m_lock.unlock();
}
void
hyperdex :: physical :: accept_connection(ev::io&, int)
{
std::tr1::shared_ptr<channel> chan;
try
{
chan.reset(new channel(m_lr, this, &m_listen));
}
catch (po6::error& e)
{
return;
}
m_lock.wrlock();
try
{
place_channel(chan);
}
catch (...)
{
m_lock.unlock();
throw;
}
m_lock.unlock();
}
// Invariant: m_lock.wrlock must be held.
void
hyperdex :: physical :: place_channel(std::tr1::shared_ptr<channel> chan)
{
// Find an empty slot.
for (size_t i = 0; i < m_channels.size(); ++i)
{
if (!m_channels[i])
{
m_channels[i] = chan;
m_location_map[chan->loc] = i;
return;
}
}
// Resize to create new slots.
m_location_map[chan->loc] = m_channels.size();
m_channels.push_back(chan);
}
hyperdex :: physical :: channel :: channel(ev::loop_ref lr,
physical* m,
po6::net::socket* accept_from)
: mtx()
, soc()
, loc()
, io(lr)
, inprogress()
, outprogress()
, outgoing()
, manager(m)
{
accept_from->accept(&soc);
loc = soc.getpeername();
io.set<channel, &channel::io_cb>(this);
io.set(soc.get(), ev::READ);
io.start();
}
hyperdex :: physical :: channel :: channel(ev::loop_ref lr,
physical* m,
const po6::net::location& from,
const po6::net::location& to)
: mtx()
, soc(to.address.family(), SOCK_STREAM, IPPROTO_TCP)
, loc(to)
, io(lr)
, inprogress()
, outprogress()
, outgoing()
, manager(m)
{
io.set<channel, &channel::io_cb>(this);
io.set(soc.get(), ev::READ);
io.start();
soc.reuseaddr(true);
soc.bind(from);
soc.connect(to);
}
hyperdex :: physical :: channel :: ~channel()
{
io.stop();
}
#define IO_BLOCKSIZE 65536
void
hyperdex :: physical :: channel :: io_cb(ev::io& w, int revents)
{
if (revents & ev::READ)
{
read_cb(w);
}
if (revents & ev::WRITE)
{
write_cb(w);
}
}
void
hyperdex :: physical :: channel :: read_cb(ev::io&)
{
if (!mtx.trylock())
{
return;
}
char block[IO_BLOCKSIZE];
try
{
size_t ret = soc.read(block, IO_BLOCKSIZE);
inprogress += e::buffer(block, ret);
if (ret == 0)
{
mtx.unlock();
manager->remove_connection(this);
return;
}
while (inprogress.size() >= sizeof(uint32_t))
{
uint32_t message_size;
inprogress.unpack() >> message_size;
if (inprogress.size() < message_size + sizeof(uint32_t))
{
break;
}
message m;
inprogress.unpack() >> m.buf; // Different unpacker.
m.loc = loc;
manager->m_incoming.push(m);
inprogress.trim_prefix(message_size + sizeof(uint32_t));
}
}
catch (po6::error& e)
{
if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
{
LOG(ERROR) << "could not read from " << loc << "; closing";
mtx.unlock();
manager->remove_connection(this);
return;
}
}
mtx.unlock();
}
void
hyperdex :: physical :: channel :: write_cb(ev::io&)
{
if (!mtx.trylock())
{
return;
}
if (outgoing.empty() && outprogress.empty())
{
io.set(ev::READ);
io.start();
mtx.unlock();
return;
}
// Pop one message to flush to network.
if (outprogress.empty())
{
outprogress.pack() << outgoing.front();
outgoing.pop();
}
try
{
size_t ret = soc.write(outprogress.get(), outprogress.size());
outprogress.trim_prefix(ret);
}
catch (po6::error& e)
{
if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
{
LOG(ERROR) << "could not write to " << loc << "; closing";
mtx.unlock();
manager->remove_connection(this);
return;
}
}
mtx.unlock();
}
hyperdex :: physical :: message :: message()
: loc()
, buf()
{
}
hyperdex :: physical :: message :: ~message()
{
}
<|endoftext|> |
<commit_before>/**
Copyright (c) 2017 Ryan Porter
You may use, distribute, or modify this code under the terms of the MIT license.
*/
#include <stdio.h>
#include <vector>
#include "parseArgs.h"
#include "polyDeformerWeights.h"
#include "polySymmetryNode.h"
#include "sceneCache.h"
#include "selection.h"
#include <maya/MArgList.h>
#include <maya/MArgDatabase.h>
#include <maya/MDagPath.h>
#include <maya/MFnMesh.h>
#include <maya/MFnWeightGeometryFilter.h>
#include <maya/MFloatArray.h>
#include <maya/MGlobal.h>
#include <maya/MItGeometry.h>
#include <maya/MObject.h>
#include <maya/MObjectArray.h>
#include <maya/MPxCommand.h>
#include <maya/MSelectionList.h>
#include <maya/MString.h>
#include <maya/MStatus.h>
#include <maya/MSyntax.h>
using namespace std;
// Indicates the source deformer.
#define SOURCE_DEFORMER_FLAG "-sd"
#define SOURCE_DEFORMER_LONG_FLAG "-sourceDeformer"
// Indicates the source deformed mesh.
#define SOURCE_MESH_FLAG "-sm"
#define SOURCE_MESH_LONG_FLAG "-sourceMesh"
// Indicates the destination deformer.
#define DESTINATION_DEFORMER_FLAG "-dd"
#define DESTINATION_DEFORMER_LONG_FLAG "-destinationDeformer"
// Indicates the destination deformed shape.
#define DESTINATION_MESH_FLAG "-dm"
#define DESTINATION_MESH_LONG_FLAG "-destinationMesh"
// Indicates the direction of the mirror or flip action - 1 (left to right) or -1 (right to left)
#define DIRECTION_FLAG "-d"
#define DIRECTION_LONG_FLAG "-direction"
// Indicates that the deformer weights should be mirrored.
#define MIRROR_FLAG "-m"
#define MIRROR_LONG_FLAG "-mirror"
// Indicates that the deformer weights should be flipped.
#define FLIP_FLAG "-f"
#define FLIP_LONG_FLAG "-flip"
#define RETURN_IF_ERROR(s) if (!s) { return s; }
PolyDeformerWeightsCommand::PolyDeformerWeightsCommand() {}
PolyDeformerWeightsCommand::~PolyDeformerWeightsCommand() {}
void* PolyDeformerWeightsCommand::creator()
{
return new PolyDeformerWeightsCommand();
}
MSyntax PolyDeformerWeightsCommand::getSyntax()
{
MSyntax syntax;
syntax.addFlag(SOURCE_DEFORMER_FLAG, SOURCE_DEFORMER_LONG_FLAG, MSyntax::kSelectionItem);
syntax.addFlag(SOURCE_MESH_FLAG, SOURCE_MESH_LONG_FLAG, MSyntax::kSelectionItem);
syntax.addFlag(DESTINATION_DEFORMER_FLAG, DESTINATION_DEFORMER_LONG_FLAG, MSyntax::kSelectionItem);
syntax.addFlag(DESTINATION_MESH_FLAG, DESTINATION_MESH_LONG_FLAG, MSyntax::kSelectionItem);
syntax.addFlag(DIRECTION_FLAG, DIRECTION_LONG_FLAG, MSyntax::kLong);
syntax.addFlag(MIRROR_FLAG, MIRROR_LONG_FLAG);
syntax.addFlag(FLIP_FLAG, FLIP_LONG_FLAG);
syntax.enableEdit(false);
syntax.enableQuery(false);
return syntax;
}
MStatus PolyDeformerWeightsCommand::parseArguments(MArgDatabase &argsData)
{
MStatus status;
status = parseArgs::getNodeArgument(argsData, SOURCE_DEFORMER_FLAG, this->sourceDeformer, true);
RETURN_IF_ERROR(status);
status = parseArgs::getNodeArgument(argsData, DESTINATION_DEFORMER_FLAG, this->destinationDeformer, false);
RETURN_IF_ERROR(status);
status = parseArgs::getDagPathArgument(argsData, SOURCE_MESH_FLAG, this->sourceMesh, true);
RETURN_IF_ERROR(status);
status = parseArgs::getDagPathArgument(argsData, DESTINATION_MESH_FLAG, this->destinationMesh, false);
RETURN_IF_ERROR(status);
this->mirrorWeights = argsData.isFlagSet(MIRROR_FLAG);
this->flipWeights = argsData.isFlagSet(FLIP_FLAG);
status = argsData.getFlagArgument(DIRECTION_FLAG, 0, this->direction);
return MStatus::kSuccess;
}
MStatus PolyDeformerWeightsCommand::validateArguments()
{
MStatus status;
if (this->direction != 1 && this->direction != -1)
{
MString errorMsg("^1s/^2s flag should be 1 (left to right) or -1 (right to left)");
errorMsg.format(errorMsg, MString(DIRECTION_LONG_FLAG), MString(DIRECTION_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
if (!parseArgs::isNodeType(sourceDeformer, MFn::kWeightGeometryFilt))
{
MString errorMsg("A deformer node should be specified with the ^1s/^2s flag.");
errorMsg.format(errorMsg, MString(SOURCE_DEFORMER_LONG_FLAG), MString(SOURCE_DEFORMER_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
if (destinationDeformer.isNull())
{
destinationDeformer = sourceDeformer;
} else if (!destinationDeformer.hasFn(MFn::kWeightGeometryFilt)) {
MString errorMsg("A deformer node should be specified with the ^1s/^2s flag.");
errorMsg.format(errorMsg, MString(DESTINATION_DEFORMER_LONG_FLAG), MString(DESTINATION_DEFORMER_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
if (!parseArgs::isNodeType(this->sourceMesh, MFn::kMesh))
{
MString errorMsg("A mesh node should be specified with the ^1s/^2s flag.");
errorMsg.format(errorMsg, MString(SOURCE_MESH_LONG_FLAG), MString(SOURCE_MESH_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
if (destinationMesh.node().isNull())
{
destinationMesh.set(sourceMesh);
} else if (!destinationMesh.hasFn(MFn::kMesh)) {
MString errorMsg("A mesh node should be specified with the ^1s/^2s flag.");
errorMsg.format(errorMsg, MString(DESTINATION_MESH_LONG_FLAG), MString(DESTINATION_MESH_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
} else {
MFnMesh fnSourceMesh(this->sourceMesh);
MFnMesh fnDestinationMesh(this->destinationMesh);
if (fnSourceMesh.numVertices() != fnDestinationMesh.numVertices())
{
MString errorMsg("Source mesh and destination mesh are not point compatible. Cannot continue.");
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
}
MSelectionList activeSelection;
MSelectionList vertexSelection;
MGlobal::getActiveSelectionList(activeSelection);
if (destinationMesh.node().hasFn(MFn::kMesh)) { destinationMesh.pop(); }
getSelectedComponents(destinationMesh, activeSelection, vertexSelection, MFn::Type::kMeshVertComponent);
if (!vertexSelection.isEmpty())
{
vertexSelection.getDagPath(0, destinationMesh, components);
}
if (!sourceMesh.node().hasFn(MFn::kMesh))
{
sourceMesh.extendToShapeDirectlyBelow(0);
}
if (!destinationMesh.node().hasFn(MFn::kMesh))
{
destinationMesh.extendToShapeDirectlyBelow(0);
}
if (mirrorWeights || flipWeights)
{
bool cacheHit = PolySymmetryCache::getNodeFromCache(this->sourceMesh, this->polySymmetryData);
if (!cacheHit)
{
MString errorMsg("Mesh specified with the ^1s/^2s flag must have an associated ^3s node.");
errorMsg.format(errorMsg, MString(SOURCE_MESH_LONG_FLAG), MString(SOURCE_MESH_FLAG), PolySymmetryNode::NODE_NAME);
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
}
return MStatus::kSuccess;
}
MStatus PolyDeformerWeightsCommand::doIt(const MArgList& argList)
{
MStatus status;
MArgDatabase argsData(syntax(), argList, &status);
RETURN_IF_ERROR(status);
status = this->parseArguments(argsData);
RETURN_IF_ERROR(status);
status = this->validateArguments();
RETURN_IF_ERROR(status);
return this->redoIt();
}
MStatus PolyDeformerWeightsCommand::redoIt()
{
MStatus status;
MFnWeightGeometryFilter fnSourceDeformer(this->sourceDeformer, &status);
MFnWeightGeometryFilter fnDestinationDeformer(this->destinationDeformer, &status);
MObjectArray sourceOutputGeometry;
MObjectArray destinationOutputGeometry;
int numberOfVertices = MFnMesh(this->sourceMesh).numVertices();
MObject sourceComponents;
MObject destinationComponents;
getAllComponents(this->sourceMesh, sourceComponents);
getAllComponents(this->destinationMesh, destinationComponents);
MFloatArray sourceWeights(numberOfVertices);
MFloatArray destinationWeights(numberOfVertices);
oldWeightValues.setLength(numberOfVertices);
uint sourceGeometryIndex = fnSourceDeformer.indexForOutputShape(this->sourceMesh.node(), &status);
if (!status)
{
MString errorMsg("Source mesh ^1s is not deformed by deformer ^2s.");
errorMsg.format(errorMsg, this->sourceMesh.partialPathName(), MFnDependencyNode(this->sourceDeformer).name());
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
uint destinationGeometryIndex = fnDestinationDeformer.indexForOutputShape(this->destinationMesh.node(), &status);
if (!status)
{
MString errorMsg("Destination mesh ^1s is not deformed by deformer ^2s.");
errorMsg.format(errorMsg, this->destinationMesh.partialPathName(), MFnDependencyNode(this->destinationDeformer).name());
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
status = fnSourceDeformer.getWeights(sourceGeometryIndex, sourceComponents, sourceWeights);
CHECK_MSTATUS_AND_RETURN_IT(status);
status = fnDestinationDeformer.getWeights(destinationGeometryIndex, destinationComponents, oldWeightValues);
CHECK_MSTATUS_AND_RETURN_IT(status);
destinationWeights.copy(sourceWeights);
if (mirrorWeights || flipWeights)
{
vector<int> vertexSymmetry;
vector<int> vertexSides;
MFnDependencyNode fnNode(polySymmetryData);
PolySymmetryNode::getValues(fnNode, VERTEX_SYMMETRY, vertexSymmetry);
PolySymmetryNode::getValues(fnNode, VERTEX_SIDES, vertexSides);
MItGeometry itGeo(destinationMesh, components);
bool useVertexSelection = !components.isNull();
while (!itGeo.isDone())
{
int i = itGeo.index();
int o = vertexSymmetry[i];
float wti = this->getWeight(i, sourceWeights, vertexSymmetry, vertexSides);
destinationWeights.set(wti, i);
if (useVertexSelection)
{
float wto = this->getWeight(o, sourceWeights, vertexSymmetry, vertexSides);
destinationWeights.set(wto, o);
}
itGeo.next();
}
}
status = fnDestinationDeformer.setWeight(this->destinationMesh, destinationGeometryIndex, destinationComponents, destinationWeights);
CHECK_MSTATUS_AND_RETURN_IT(status);
this->geometryIndex = destinationGeometryIndex;
this->components = destinationComponents;
return MStatus::kSuccess;
}
float PolyDeformerWeightsCommand::getWeight(int vertexIndex, MFloatArray &sourceWeights, vector<int> &vertexSymmetry, vector<int> vertexSides)
{
int i = vertexIndex;
int o = vertexSymmetry[i];
float wt = sourceWeights[i];
if (flipWeights || (mirrorWeights && vertexSides[i] != direction))
{
wt = sourceWeights[o];
}
return wt;
}
MStatus PolyDeformerWeightsCommand::undoIt()
{
MStatus status;
MFnWeightGeometryFilter fnDeformer(this->destinationDeformer, &status);
status = fnDeformer.setWeight(
this->destinationMesh,
this->geometryIndex,
this->components,
this->oldWeightValues
);
CHECK_MSTATUS_AND_RETURN_IT(status);
return MStatus::kSuccess;
}<commit_msg>polyDeformerWeights uses new getAllVertices function.<commit_after>/**
Copyright (c) 2017 Ryan Porter
You may use, distribute, or modify this code under the terms of the MIT license.
*/
#include <stdio.h>
#include <vector>
#include "parseArgs.h"
#include "polyDeformerWeights.h"
#include "polySymmetryNode.h"
#include "sceneCache.h"
#include "selection.h"
#include <maya/MArgList.h>
#include <maya/MArgDatabase.h>
#include <maya/MDagPath.h>
#include <maya/MFnMesh.h>
#include <maya/MFnWeightGeometryFilter.h>
#include <maya/MFloatArray.h>
#include <maya/MGlobal.h>
#include <maya/MItGeometry.h>
#include <maya/MObject.h>
#include <maya/MObjectArray.h>
#include <maya/MPxCommand.h>
#include <maya/MSelectionList.h>
#include <maya/MString.h>
#include <maya/MStatus.h>
#include <maya/MSyntax.h>
using namespace std;
// Indicates the source deformer.
#define SOURCE_DEFORMER_FLAG "-sd"
#define SOURCE_DEFORMER_LONG_FLAG "-sourceDeformer"
// Indicates the source deformed mesh.
#define SOURCE_MESH_FLAG "-sm"
#define SOURCE_MESH_LONG_FLAG "-sourceMesh"
// Indicates the destination deformer.
#define DESTINATION_DEFORMER_FLAG "-dd"
#define DESTINATION_DEFORMER_LONG_FLAG "-destinationDeformer"
// Indicates the destination deformed shape.
#define DESTINATION_MESH_FLAG "-dm"
#define DESTINATION_MESH_LONG_FLAG "-destinationMesh"
// Indicates the direction of the mirror or flip action - 1 (left to right) or -1 (right to left)
#define DIRECTION_FLAG "-d"
#define DIRECTION_LONG_FLAG "-direction"
// Indicates that the deformer weights should be mirrored.
#define MIRROR_FLAG "-m"
#define MIRROR_LONG_FLAG "-mirror"
// Indicates that the deformer weights should be flipped.
#define FLIP_FLAG "-f"
#define FLIP_LONG_FLAG "-flip"
#define RETURN_IF_ERROR(s) if (!s) { return s; }
PolyDeformerWeightsCommand::PolyDeformerWeightsCommand() {}
PolyDeformerWeightsCommand::~PolyDeformerWeightsCommand() {}
void* PolyDeformerWeightsCommand::creator()
{
return new PolyDeformerWeightsCommand();
}
MSyntax PolyDeformerWeightsCommand::getSyntax()
{
MSyntax syntax;
syntax.addFlag(SOURCE_DEFORMER_FLAG, SOURCE_DEFORMER_LONG_FLAG, MSyntax::kSelectionItem);
syntax.addFlag(SOURCE_MESH_FLAG, SOURCE_MESH_LONG_FLAG, MSyntax::kSelectionItem);
syntax.addFlag(DESTINATION_DEFORMER_FLAG, DESTINATION_DEFORMER_LONG_FLAG, MSyntax::kSelectionItem);
syntax.addFlag(DESTINATION_MESH_FLAG, DESTINATION_MESH_LONG_FLAG, MSyntax::kSelectionItem);
syntax.addFlag(DIRECTION_FLAG, DIRECTION_LONG_FLAG, MSyntax::kLong);
syntax.addFlag(MIRROR_FLAG, MIRROR_LONG_FLAG);
syntax.addFlag(FLIP_FLAG, FLIP_LONG_FLAG);
syntax.enableEdit(false);
syntax.enableQuery(false);
return syntax;
}
MStatus PolyDeformerWeightsCommand::parseArguments(MArgDatabase &argsData)
{
MStatus status;
status = parseArgs::getNodeArgument(argsData, SOURCE_DEFORMER_FLAG, this->sourceDeformer, true);
RETURN_IF_ERROR(status);
status = parseArgs::getNodeArgument(argsData, DESTINATION_DEFORMER_FLAG, this->destinationDeformer, false);
RETURN_IF_ERROR(status);
status = parseArgs::getDagPathArgument(argsData, SOURCE_MESH_FLAG, this->sourceMesh, true);
RETURN_IF_ERROR(status);
status = parseArgs::getDagPathArgument(argsData, DESTINATION_MESH_FLAG, this->destinationMesh, false);
RETURN_IF_ERROR(status);
this->mirrorWeights = argsData.isFlagSet(MIRROR_FLAG);
this->flipWeights = argsData.isFlagSet(FLIP_FLAG);
status = argsData.getFlagArgument(DIRECTION_FLAG, 0, this->direction);
return MStatus::kSuccess;
}
MStatus PolyDeformerWeightsCommand::validateArguments()
{
MStatus status;
if (this->direction != 1 && this->direction != -1)
{
MString errorMsg("^1s/^2s flag should be 1 (left to right) or -1 (right to left)");
errorMsg.format(errorMsg, MString(DIRECTION_LONG_FLAG), MString(DIRECTION_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
if (!parseArgs::isNodeType(sourceDeformer, MFn::kWeightGeometryFilt))
{
MString errorMsg("A deformer node should be specified with the ^1s/^2s flag.");
errorMsg.format(errorMsg, MString(SOURCE_DEFORMER_LONG_FLAG), MString(SOURCE_DEFORMER_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
if (destinationDeformer.isNull())
{
destinationDeformer = sourceDeformer;
} else if (!destinationDeformer.hasFn(MFn::kWeightGeometryFilt)) {
MString errorMsg("A deformer node should be specified with the ^1s/^2s flag.");
errorMsg.format(errorMsg, MString(DESTINATION_DEFORMER_LONG_FLAG), MString(DESTINATION_DEFORMER_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
if (!parseArgs::isNodeType(this->sourceMesh, MFn::kMesh))
{
MString errorMsg("A mesh node should be specified with the ^1s/^2s flag.");
errorMsg.format(errorMsg, MString(SOURCE_MESH_LONG_FLAG), MString(SOURCE_MESH_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
if (destinationMesh.node().isNull())
{
destinationMesh.set(sourceMesh);
} else if (!destinationMesh.hasFn(MFn::kMesh)) {
MString errorMsg("A mesh node should be specified with the ^1s/^2s flag.");
errorMsg.format(errorMsg, MString(DESTINATION_MESH_LONG_FLAG), MString(DESTINATION_MESH_FLAG));
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
} else {
MFnMesh fnSourceMesh(this->sourceMesh);
MFnMesh fnDestinationMesh(this->destinationMesh);
if (fnSourceMesh.numVertices() != fnDestinationMesh.numVertices())
{
MString errorMsg("Source mesh and destination mesh are not point compatible. Cannot continue.");
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
}
MSelectionList activeSelection;
MSelectionList vertexSelection;
MGlobal::getActiveSelectionList(activeSelection);
if (destinationMesh.node().hasFn(MFn::kMesh)) { destinationMesh.pop(); }
getSelectedComponents(destinationMesh, activeSelection, vertexSelection, MFn::Type::kMeshVertComponent);
if (!vertexSelection.isEmpty())
{
vertexSelection.getDagPath(0, destinationMesh, components);
}
if (!sourceMesh.node().hasFn(MFn::kMesh))
{
sourceMesh.extendToShapeDirectlyBelow(0);
}
if (!destinationMesh.node().hasFn(MFn::kMesh))
{
destinationMesh.extendToShapeDirectlyBelow(0);
}
if (mirrorWeights || flipWeights)
{
bool cacheHit = PolySymmetryCache::getNodeFromCache(this->sourceMesh, this->polySymmetryData);
if (!cacheHit)
{
MString errorMsg("Mesh specified with the ^1s/^2s flag must have an associated ^3s node.");
errorMsg.format(errorMsg, MString(SOURCE_MESH_LONG_FLAG), MString(SOURCE_MESH_FLAG), PolySymmetryNode::NODE_NAME);
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
}
return MStatus::kSuccess;
}
MStatus PolyDeformerWeightsCommand::doIt(const MArgList& argList)
{
MStatus status;
MArgDatabase argsData(syntax(), argList, &status);
RETURN_IF_ERROR(status);
status = this->parseArguments(argsData);
RETURN_IF_ERROR(status);
status = this->validateArguments();
RETURN_IF_ERROR(status);
return this->redoIt();
}
MStatus PolyDeformerWeightsCommand::redoIt()
{
MStatus status;
MFnWeightGeometryFilter fnSourceDeformer(this->sourceDeformer, &status);
MFnWeightGeometryFilter fnDestinationDeformer(this->destinationDeformer, &status);
MObjectArray sourceOutputGeometry;
MObjectArray destinationOutputGeometry;
int numberOfVertices = MFnMesh(this->sourceMesh).numVertices();
MObject sourceComponents;
MObject destinationComponents;
getAllVertices(numberOfVertices, sourceComponents);
getAllVertices(numberOfVertices, destinationComponents);
MFloatArray sourceWeights(numberOfVertices);
MFloatArray destinationWeights(numberOfVertices);
oldWeightValues.setLength(numberOfVertices);
uint sourceGeometryIndex = fnSourceDeformer.indexForOutputShape(this->sourceMesh.node(), &status);
if (!status)
{
MString errorMsg("Source mesh ^1s is not deformed by deformer ^2s.");
errorMsg.format(errorMsg, this->sourceMesh.partialPathName(), MFnDependencyNode(this->sourceDeformer).name());
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
uint destinationGeometryIndex = fnDestinationDeformer.indexForOutputShape(this->destinationMesh.node(), &status);
if (!status)
{
MString errorMsg("Destination mesh ^1s is not deformed by deformer ^2s.");
errorMsg.format(errorMsg, this->destinationMesh.partialPathName(), MFnDependencyNode(this->destinationDeformer).name());
MGlobal::displayError(errorMsg);
return MStatus::kFailure;
}
status = fnSourceDeformer.getWeights(sourceGeometryIndex, sourceComponents, sourceWeights);
CHECK_MSTATUS_AND_RETURN_IT(status);
status = fnDestinationDeformer.getWeights(destinationGeometryIndex, destinationComponents, oldWeightValues);
CHECK_MSTATUS_AND_RETURN_IT(status);
destinationWeights.copy(sourceWeights);
if (mirrorWeights || flipWeights)
{
vector<int> vertexSymmetry;
vector<int> vertexSides;
MFnDependencyNode fnNode(polySymmetryData);
PolySymmetryNode::getValues(fnNode, VERTEX_SYMMETRY, vertexSymmetry);
PolySymmetryNode::getValues(fnNode, VERTEX_SIDES, vertexSides);
MItGeometry itGeo(destinationMesh, components);
bool useVertexSelection = !components.isNull();
while (!itGeo.isDone())
{
int i = itGeo.index();
int o = vertexSymmetry[i];
float wti = this->getWeight(i, sourceWeights, vertexSymmetry, vertexSides);
destinationWeights.set(wti, i);
if (useVertexSelection)
{
float wto = this->getWeight(o, sourceWeights, vertexSymmetry, vertexSides);
destinationWeights.set(wto, o);
}
itGeo.next();
}
}
status = fnDestinationDeformer.setWeight(this->destinationMesh, destinationGeometryIndex, destinationComponents, destinationWeights);
CHECK_MSTATUS_AND_RETURN_IT(status);
this->geometryIndex = destinationGeometryIndex;
this->components = destinationComponents;
return MStatus::kSuccess;
}
float PolyDeformerWeightsCommand::getWeight(int vertexIndex, MFloatArray &sourceWeights, vector<int> &vertexSymmetry, vector<int> vertexSides)
{
int i = vertexIndex;
int o = vertexSymmetry[i];
float wt = sourceWeights[i];
if (flipWeights || (mirrorWeights && vertexSides[i] != direction))
{
wt = sourceWeights[o];
}
return wt;
}
MStatus PolyDeformerWeightsCommand::undoIt()
{
MStatus status;
MFnWeightGeometryFilter fnDeformer(this->destinationDeformer, &status);
status = fnDeformer.setWeight(
this->destinationMesh,
this->geometryIndex,
this->components,
this->oldWeightValues
);
CHECK_MSTATUS_AND_RETURN_IT(status);
return MStatus::kSuccess;
}<|endoftext|> |
<commit_before>#include "quicksand.h"
#include "marian.h"
#if MKL_FOUND
#include "mkl.h"
#endif
#include "data/shortlist.h"
#include "translator/beam_search.h"
#include "translator/scorers.h"
#include "data/alignment.h"
#include "data/vocab_base.h"
#include "tensors/cpu/expression_graph_packable.h"
#include "layers/lsh.h"
#if USE_FBGEMM
#include "fbgemm/Utils.h"
#endif
namespace marian {
namespace quicksand {
template <class T>
void set(Ptr<Options> options, const std::string& key, const T& value) {
options->set(key, value);
}
template void set(Ptr<Options> options, const std::string& key, const size_t&);
template void set(Ptr<Options> options, const std::string& key, const int&);
template void set(Ptr<Options> options, const std::string& key, const std::string&);
template void set(Ptr<Options> options, const std::string& key, const bool&);
template void set(Ptr<Options> options, const std::string& key, const std::vector<std::string>&);
template void set(Ptr<Options> options, const std::string& key, const std::vector<int>&);
template void set(Ptr<Options> options, const std::string& key, const float&);
template void set(Ptr<Options> options, const std::string& key, const double&);
Ptr<Options> newOptions() {
return New<Options>();
}
class VocabWrapper : public IVocabWrapper {
Ptr<Vocab> pImpl_;
public:
VocabWrapper(Ptr<Vocab> vocab) : pImpl_(vocab) {}
virtual ~VocabWrapper() {}
WordIndex encode(const std::string& word) const override { return (*pImpl_)[word].toWordIndex(); }
std::string decode(WordIndex id) const override { return (*pImpl_)[Word::fromWordIndex(id)]; }
size_t size() const override { return pImpl_->size(); }
void transcodeToShortlistInPlace(WordIndex* ptr, size_t num) const override { pImpl_->transcodeToShortlistInPlace(ptr, num); }
Ptr<Vocab> getVocab() const { return pImpl_; }
};
class BeamSearchDecoder : public IBeamSearchDecoder {
private:
Ptr<ExpressionGraph> graph_;
Ptr<cpu::WrappedDevice> device_;
std::vector<Ptr<Scorer>> scorers_;
std::vector<Ptr<Vocab>> vocabs_;
public:
BeamSearchDecoder(Ptr<Options> options,
const std::vector<const void*>& ptrs,
const std::vector<Ptr<IVocabWrapper>>& vocabs)
: IBeamSearchDecoder(options, ptrs) {
// copy the vocabs
for (auto vi : vocabs)
vocabs_.push_back(std::dynamic_pointer_cast<VocabWrapper>(vi)->getVocab());
// setting 16-bit optimization to false for now. Re-enable with better caching or pre-computation
graph_ = New<ExpressionGraph>(/*inference=*/true);
DeviceId deviceId{0, DeviceType::cpu};
device_ = New<cpu::WrappedDevice>(deviceId);
graph_->setDevice(deviceId, device_);
#if MKL_FOUND
mkl_set_num_threads(options_->get<int>("mkl-threads", 1));
#endif
std::vector<std::string> models
= options_->get<std::vector<std::string>>("model");
for(int i = 0; i < models.size(); ++i) {
Ptr<Options> modelOpts = New<Options>();
YAML::Node config;
if(io::isBin(models[i]) && ptrs_[i] != nullptr)
io::getYamlFromModel(config, "special:model.yml", ptrs_[i]);
else
io::getYamlFromModel(config, "special:model.yml", models[i]);
modelOpts->merge(options_);
modelOpts->merge(config);
std::cerr << modelOpts->asYamlString() << std::flush; // @TODO: take a look at why this is even here.
auto encdec = models::createModelFromOptions(modelOpts, models::usage::translation);
if(io::isBin(models[i]) && ptrs_[i] != nullptr) {
// if file ends in *.bin and has been mapped by QuickSAND
scorers_.push_back(New<ScorerWrapper>(
encdec, "F" + std::to_string(scorers_.size()), /*weight=*/1.0f, ptrs[i]));
} else {
// it's a *.npz file or has not been mapped by QuickSAND
scorers_.push_back(New<ScorerWrapper>(
encdec, "F" + std::to_string(scorers_.size()), /*weight=*/1.0f, models[i]));
}
}
for(auto scorer : scorers_) {
scorer->init(graph_);
}
// run parameter init once, this is required for graph_->get("parameter name") to work correctly
graph_->forward();
}
void setWorkspace(uint8_t* data, size_t size) override { device_->set(data, size); }
QSNBestBatch decode(const QSBatch& qsBatch,
size_t maxLength,
const std::unordered_set<WordIndex>& shortlist) override {
std::vector<int> lshOpts = options_->get<std::vector<int>>("output-approx-knn", {});
ABORT_IF(lshOpts.size() != 0 && lshOpts.size() != 2, "--output-approx-knn takes 2 parameters");
ABORT_IF(lshOpts.size() == 2 && shortlist.size() > 0, "LSH and shortlist cannot be used at the same time");
if(lshOpts.size() == 2 || shortlist.size() > 0) {
Ptr<data::ShortlistGenerator> shortListGen;
// both ShortListGenerators are thin wrappers, hence no problem with calling this per query
if(lshOpts.size() == 2) {
// Setting abortIfDynamic to true disallows memory allocation for LSH parameters, this is specifically for use in Quicksand.
// If we want to use the LSH in Quicksand we need to create a binary model that contains the LSH parameters via conversion.
shortListGen = New<data::LSHShortlistGenerator>(lshOpts[0], lshOpts[1], vocabs_[1]->lemmaSize(), /*abortIfDynamic=*/true);
} else {
shortListGen = New<data::FakeShortlistGenerator>(shortlist);
}
for(auto scorer : scorers_)
scorer->setShortlistGenerator(shortListGen);
}
// form source batch, by interleaving the words over sentences in the batch, and setting the mask
size_t batchSize = qsBatch.size();
auto subBatch = New<data::SubBatch>(batchSize, maxLength, vocabs_[0]);
for(size_t i = 0; i < maxLength; ++i) {
for(size_t j = 0; j < batchSize; ++j) {
const auto& sent = qsBatch[j];
if(i < sent.size()) {
size_t idx = i * batchSize + j;
subBatch->data()[idx] = marian::Word::fromWordIndex(sent[i]);
subBatch->mask()[idx] = 1;
}
}
}
auto tgtSubBatch = New<data::SubBatch>(batchSize, 0, vocabs_[1]); // only holds a vocab, but data is dummy
std::vector<Ptr<data::SubBatch>> subBatches{ subBatch, tgtSubBatch };
std::vector<size_t> sentIds(batchSize, 0);
auto batch = New<data::CorpusBatch>(subBatches);
batch->setSentenceIds(sentIds);
// decode
auto search = New<BeamSearch>(options_, scorers_, vocabs_[1]);
Histories histories = search->search(graph_, batch);
// convert to QuickSAND format
QSNBestBatch qsNbestBatch;
for(const auto& history : histories) { // loop over batch entries
QSNBest qsNbest;
NBestList nbestHyps = history->nBest(SIZE_MAX); // request as many N as we have
for (const Result& result : nbestHyps) { // loop over N-best entries
// get hypothesis word sequence and normalized sentence score
auto words = std::get<0>(result);
auto score = std::get<2>(result);
// determine alignment if present
AlignmentSets alignmentSets;
if (options_->hasAndNotEmpty("alignment"))
{
float alignmentThreshold;
auto alignment = options_->get<std::string>("alignment"); // @TODO: this logic now exists three times in Marian
if (alignment == "soft")
alignmentThreshold = 0.0f;
else if (alignment == "hard")
alignmentThreshold = 1.0f;
else
alignmentThreshold = std::max(std::stof(alignment), 0.f);
auto hyp = std::get<1>(result);
data::WordAlignment align = data::ConvertSoftAlignToHardAlign(hyp->tracebackAlignment(), alignmentThreshold);
// convert to QuickSAND format
alignmentSets.resize(words.size());
for (const auto& p : align)
alignmentSets[p.tgtPos].insert({p.srcPos, p.prob}); // [trgPos] -> {(srcPos, P(srcPos|trgPos))}
}
// form hypothesis to return
qsNbest.emplace_back(toWordIndexVector(words), std::move(alignmentSets), score);
}
qsNbestBatch.push_back(qsNbest);
}
return qsNbestBatch;
}
};
Ptr<IBeamSearchDecoder> newDecoder(Ptr<Options> options,
const std::vector<const void*>& ptrs,
const std::vector<Ptr<IVocabWrapper>>& vocabs,
WordIndex eosDummy) { // @TODO: remove this parameter
marian::setThrowExceptionOnAbort(true); // globally defined to throw now
ABORT_IF(marian::Word::fromWordIndex(eosDummy) != std::dynamic_pointer_cast<VocabWrapper>(vocabs[1])->getVocab()->getEosId(), "Inconsistent eos vs. vocabs_[1]");
return New<BeamSearchDecoder>(options, ptrs, vocabs/*, eos*/);
}
std::vector<Ptr<IVocabWrapper>> loadVocabs(const std::vector<std::string>& vocabPaths) {
std::vector<Ptr<IVocabWrapper>> res(vocabPaths.size());
for (size_t i = 0; i < vocabPaths.size(); i++) {
if (i > 0 && vocabPaths[i] == vocabPaths[i-1]) {
res[i] = res[i-1];
LOG(info, "[data] Input {} sharing vocabulary with input {}", i, i-1);
}
else {
auto vocab = New<Vocab>(New<Options>(), i); // (empty options, since they are only used for creating vocabs)
auto size = vocab->load(vocabPaths[i]);
LOG(info, "[data] Loaded vocabulary size for input {} of size {}", i, size);
res[i] = New<VocabWrapper>(vocab);
}
}
return res;
}
// query CPU AVX version
DecoderCpuAvxVersion getCpuAvxVersion() {
#if USE_FBGEMM
// Default value is AVX
DecoderCpuAvxVersion cpuAvxVer = DecoderCpuAvxVersion::AVX;
if (fbgemm::fbgemmHasAvx512Support())
cpuAvxVer = DecoderCpuAvxVersion::AVX512;
else if (fbgemm::fbgemmHasAvx2Support())
cpuAvxVer = DecoderCpuAvxVersion::AVX2;
return cpuAvxVer;
#else
// Default value is AVX
return DecoderCpuAvxVersion::AVX;
#endif
}
DecoderCpuAvxVersion parseCpuAvxVersion(std::string name) {
if (name == "avx") {
return DecoderCpuAvxVersion::AVX;
} else if (name == "avx2") {
return DecoderCpuAvxVersion::AVX2;
} else if (name == "avx512") {
return DecoderCpuAvxVersion::AVX512;
} else {
ABORT("Unknown CPU Instruction Set: {}", name);
return DecoderCpuAvxVersion::AVX;
}
}
// This function converts an fp32 model into an FBGEMM based packed model.
// marian defined types are used for external project as well.
// The targetPrec is passed as int32_t for the exported function definition.
bool convertModel(std::string inputFile, std::string outputFile, int32_t targetPrec, int32_t lshNBits) {
std::cerr << "Converting from: " << inputFile << ", to: " << outputFile << ", precision: " << targetPrec << std::endl;
YAML::Node config;
std::stringstream configStr;
marian::io::getYamlFromModel(config, "special:model.yml", inputFile);
configStr << config;
auto graph = New<ExpressionGraphPackable>();
graph->setDevice(CPU0);
graph->load(inputFile);
// MJD: Note, this is a default settings which we might want to change or expose. Use this only with Polonium students.
// The LSH will not be used by default even if it exists in the model. That has to be enabled in the decoder config.
std::string lshOutputWeights = "Wemb";
bool addLsh = lshNBits > 0;
if(addLsh) {
std::cerr << "Adding LSH to model with hash size " << lshNBits << std::endl;
// Add dummy parameters for the LSH before the model gets actually initialized.
// This create the parameters with useless values in the tensors, but it gives us the memory we need.
graph->setReloaded(false);
lsh::addDummyParameters(graph, /*weights=*/lshOutputWeights, /*nBits=*/lshNBits);
graph->setReloaded(true);
}
graph->forward(); // run the initializers
if(addLsh) {
// After initialization, hijack the paramters for the LSH and force-overwrite with correct values.
// Once this is done we can just pack and save as normal.
lsh::overwriteDummyParameters(graph, /*weights=*/lshOutputWeights);
}
Type targetPrecType = (Type) targetPrec;
if (targetPrecType == Type::packed16
|| targetPrecType == Type::packed8avx2
|| targetPrecType == Type::packed8avx512) {
graph->packAndSave(outputFile, configStr.str(), targetPrecType);
std::cerr << "Conversion Finished." << std::endl;
} else {
ABORT("Target type is not supported in this funcion: {}", targetPrec);
return false;
}
return true;
}
} // namespace quicksand
} // namespace marian
<commit_msg>allow float32 conversion in QS interface<commit_after>#include "quicksand.h"
#include "marian.h"
#if MKL_FOUND
#include "mkl.h"
#endif
#include "data/shortlist.h"
#include "translator/beam_search.h"
#include "translator/scorers.h"
#include "data/alignment.h"
#include "data/vocab_base.h"
#include "tensors/cpu/expression_graph_packable.h"
#include "layers/lsh.h"
#if USE_FBGEMM
#include "fbgemm/Utils.h"
#endif
namespace marian {
namespace quicksand {
template <class T>
void set(Ptr<Options> options, const std::string& key, const T& value) {
options->set(key, value);
}
template void set(Ptr<Options> options, const std::string& key, const size_t&);
template void set(Ptr<Options> options, const std::string& key, const int&);
template void set(Ptr<Options> options, const std::string& key, const std::string&);
template void set(Ptr<Options> options, const std::string& key, const bool&);
template void set(Ptr<Options> options, const std::string& key, const std::vector<std::string>&);
template void set(Ptr<Options> options, const std::string& key, const std::vector<int>&);
template void set(Ptr<Options> options, const std::string& key, const float&);
template void set(Ptr<Options> options, const std::string& key, const double&);
Ptr<Options> newOptions() {
return New<Options>();
}
class VocabWrapper : public IVocabWrapper {
Ptr<Vocab> pImpl_;
public:
VocabWrapper(Ptr<Vocab> vocab) : pImpl_(vocab) {}
virtual ~VocabWrapper() {}
WordIndex encode(const std::string& word) const override { return (*pImpl_)[word].toWordIndex(); }
std::string decode(WordIndex id) const override { return (*pImpl_)[Word::fromWordIndex(id)]; }
size_t size() const override { return pImpl_->size(); }
void transcodeToShortlistInPlace(WordIndex* ptr, size_t num) const override { pImpl_->transcodeToShortlistInPlace(ptr, num); }
Ptr<Vocab> getVocab() const { return pImpl_; }
};
class BeamSearchDecoder : public IBeamSearchDecoder {
private:
Ptr<ExpressionGraph> graph_;
Ptr<cpu::WrappedDevice> device_;
std::vector<Ptr<Scorer>> scorers_;
std::vector<Ptr<Vocab>> vocabs_;
public:
BeamSearchDecoder(Ptr<Options> options,
const std::vector<const void*>& ptrs,
const std::vector<Ptr<IVocabWrapper>>& vocabs)
: IBeamSearchDecoder(options, ptrs) {
// copy the vocabs
for (auto vi : vocabs)
vocabs_.push_back(std::dynamic_pointer_cast<VocabWrapper>(vi)->getVocab());
// setting 16-bit optimization to false for now. Re-enable with better caching or pre-computation
graph_ = New<ExpressionGraph>(/*inference=*/true);
DeviceId deviceId{0, DeviceType::cpu};
device_ = New<cpu::WrappedDevice>(deviceId);
graph_->setDevice(deviceId, device_);
#if MKL_FOUND
mkl_set_num_threads(options_->get<int>("mkl-threads", 1));
#endif
std::vector<std::string> models
= options_->get<std::vector<std::string>>("model");
for(int i = 0; i < models.size(); ++i) {
Ptr<Options> modelOpts = New<Options>();
YAML::Node config;
if(io::isBin(models[i]) && ptrs_[i] != nullptr)
io::getYamlFromModel(config, "special:model.yml", ptrs_[i]);
else
io::getYamlFromModel(config, "special:model.yml", models[i]);
modelOpts->merge(options_);
modelOpts->merge(config);
std::cerr << modelOpts->asYamlString() << std::flush; // @TODO: take a look at why this is even here.
auto encdec = models::createModelFromOptions(modelOpts, models::usage::translation);
if(io::isBin(models[i]) && ptrs_[i] != nullptr) {
// if file ends in *.bin and has been mapped by QuickSAND
scorers_.push_back(New<ScorerWrapper>(
encdec, "F" + std::to_string(scorers_.size()), /*weight=*/1.0f, ptrs[i]));
} else {
// it's a *.npz file or has not been mapped by QuickSAND
scorers_.push_back(New<ScorerWrapper>(
encdec, "F" + std::to_string(scorers_.size()), /*weight=*/1.0f, models[i]));
}
}
for(auto scorer : scorers_) {
scorer->init(graph_);
}
// run parameter init once, this is required for graph_->get("parameter name") to work correctly
graph_->forward();
}
void setWorkspace(uint8_t* data, size_t size) override { device_->set(data, size); }
QSNBestBatch decode(const QSBatch& qsBatch,
size_t maxLength,
const std::unordered_set<WordIndex>& shortlist) override {
std::vector<int> lshOpts = options_->get<std::vector<int>>("output-approx-knn", {});
ABORT_IF(lshOpts.size() != 0 && lshOpts.size() != 2, "--output-approx-knn takes 2 parameters");
ABORT_IF(lshOpts.size() == 2 && shortlist.size() > 0, "LSH and shortlist cannot be used at the same time");
if(lshOpts.size() == 2 || shortlist.size() > 0) {
Ptr<data::ShortlistGenerator> shortListGen;
// both ShortListGenerators are thin wrappers, hence no problem with calling this per query
if(lshOpts.size() == 2) {
// Setting abortIfDynamic to true disallows memory allocation for LSH parameters, this is specifically for use in Quicksand.
// If we want to use the LSH in Quicksand we need to create a binary model that contains the LSH parameters via conversion.
shortListGen = New<data::LSHShortlistGenerator>(lshOpts[0], lshOpts[1], vocabs_[1]->lemmaSize(), /*abortIfDynamic=*/true);
} else {
shortListGen = New<data::FakeShortlistGenerator>(shortlist);
}
for(auto scorer : scorers_)
scorer->setShortlistGenerator(shortListGen);
}
// form source batch, by interleaving the words over sentences in the batch, and setting the mask
size_t batchSize = qsBatch.size();
auto subBatch = New<data::SubBatch>(batchSize, maxLength, vocabs_[0]);
for(size_t i = 0; i < maxLength; ++i) {
for(size_t j = 0; j < batchSize; ++j) {
const auto& sent = qsBatch[j];
if(i < sent.size()) {
size_t idx = i * batchSize + j;
subBatch->data()[idx] = marian::Word::fromWordIndex(sent[i]);
subBatch->mask()[idx] = 1;
}
}
}
auto tgtSubBatch = New<data::SubBatch>(batchSize, 0, vocabs_[1]); // only holds a vocab, but data is dummy
std::vector<Ptr<data::SubBatch>> subBatches{ subBatch, tgtSubBatch };
std::vector<size_t> sentIds(batchSize, 0);
auto batch = New<data::CorpusBatch>(subBatches);
batch->setSentenceIds(sentIds);
// decode
auto search = New<BeamSearch>(options_, scorers_, vocabs_[1]);
Histories histories = search->search(graph_, batch);
// convert to QuickSAND format
QSNBestBatch qsNbestBatch;
for(const auto& history : histories) { // loop over batch entries
QSNBest qsNbest;
NBestList nbestHyps = history->nBest(SIZE_MAX); // request as many N as we have
for (const Result& result : nbestHyps) { // loop over N-best entries
// get hypothesis word sequence and normalized sentence score
auto words = std::get<0>(result);
auto score = std::get<2>(result);
// determine alignment if present
AlignmentSets alignmentSets;
if (options_->hasAndNotEmpty("alignment"))
{
float alignmentThreshold;
auto alignment = options_->get<std::string>("alignment"); // @TODO: this logic now exists three times in Marian
if (alignment == "soft")
alignmentThreshold = 0.0f;
else if (alignment == "hard")
alignmentThreshold = 1.0f;
else
alignmentThreshold = std::max(std::stof(alignment), 0.f);
auto hyp = std::get<1>(result);
data::WordAlignment align = data::ConvertSoftAlignToHardAlign(hyp->tracebackAlignment(), alignmentThreshold);
// convert to QuickSAND format
alignmentSets.resize(words.size());
for (const auto& p : align)
alignmentSets[p.tgtPos].insert({p.srcPos, p.prob}); // [trgPos] -> {(srcPos, P(srcPos|trgPos))}
}
// form hypothesis to return
qsNbest.emplace_back(toWordIndexVector(words), std::move(alignmentSets), score);
}
qsNbestBatch.push_back(qsNbest);
}
return qsNbestBatch;
}
};
Ptr<IBeamSearchDecoder> newDecoder(Ptr<Options> options,
const std::vector<const void*>& ptrs,
const std::vector<Ptr<IVocabWrapper>>& vocabs,
WordIndex eosDummy) { // @TODO: remove this parameter
marian::setThrowExceptionOnAbort(true); // globally defined to throw now
ABORT_IF(marian::Word::fromWordIndex(eosDummy) != std::dynamic_pointer_cast<VocabWrapper>(vocabs[1])->getVocab()->getEosId(), "Inconsistent eos vs. vocabs_[1]");
return New<BeamSearchDecoder>(options, ptrs, vocabs/*, eos*/);
}
std::vector<Ptr<IVocabWrapper>> loadVocabs(const std::vector<std::string>& vocabPaths) {
std::vector<Ptr<IVocabWrapper>> res(vocabPaths.size());
for (size_t i = 0; i < vocabPaths.size(); i++) {
if (i > 0 && vocabPaths[i] == vocabPaths[i-1]) {
res[i] = res[i-1];
LOG(info, "[data] Input {} sharing vocabulary with input {}", i, i-1);
}
else {
auto vocab = New<Vocab>(New<Options>(), i); // (empty options, since they are only used for creating vocabs)
auto size = vocab->load(vocabPaths[i]);
LOG(info, "[data] Loaded vocabulary size for input {} of size {}", i, size);
res[i] = New<VocabWrapper>(vocab);
}
}
return res;
}
// query CPU AVX version
DecoderCpuAvxVersion getCpuAvxVersion() {
#if USE_FBGEMM
// Default value is AVX
DecoderCpuAvxVersion cpuAvxVer = DecoderCpuAvxVersion::AVX;
if (fbgemm::fbgemmHasAvx512Support())
cpuAvxVer = DecoderCpuAvxVersion::AVX512;
else if (fbgemm::fbgemmHasAvx2Support())
cpuAvxVer = DecoderCpuAvxVersion::AVX2;
return cpuAvxVer;
#else
// Default value is AVX
return DecoderCpuAvxVersion::AVX;
#endif
}
DecoderCpuAvxVersion parseCpuAvxVersion(std::string name) {
if (name == "avx") {
return DecoderCpuAvxVersion::AVX;
} else if (name == "avx2") {
return DecoderCpuAvxVersion::AVX2;
} else if (name == "avx512") {
return DecoderCpuAvxVersion::AVX512;
} else {
ABORT("Unknown CPU Instruction Set: {}", name);
return DecoderCpuAvxVersion::AVX;
}
}
// This function converts an fp32 model into an FBGEMM based packed model.
// marian defined types are used for external project as well.
// The targetPrec is passed as int32_t for the exported function definition.
bool convertModel(std::string inputFile, std::string outputFile, int32_t targetPrec, int32_t lshNBits) {
std::cerr << "Converting from: " << inputFile << ", to: " << outputFile << ", precision: " << targetPrec << std::endl;
YAML::Node config;
std::stringstream configStr;
marian::io::getYamlFromModel(config, "special:model.yml", inputFile);
configStr << config;
auto graph = New<ExpressionGraphPackable>();
graph->setDevice(CPU0);
graph->load(inputFile);
// MJD: Note, this is a default settings which we might want to change or expose. Use this only with Polonium students.
// The LSH will not be used by default even if it exists in the model. That has to be enabled in the decoder config.
std::string lshOutputWeights = "Wemb";
bool addLsh = lshNBits > 0;
if(addLsh) {
std::cerr << "Adding LSH to model with hash size " << lshNBits << std::endl;
// Add dummy parameters for the LSH before the model gets actually initialized.
// This create the parameters with useless values in the tensors, but it gives us the memory we need.
graph->setReloaded(false);
lsh::addDummyParameters(graph, /*weights=*/lshOutputWeights, /*nBits=*/lshNBits);
graph->setReloaded(true);
}
graph->forward(); // run the initializers
if(addLsh) {
// After initialization, hijack the paramters for the LSH and force-overwrite with correct values.
// Once this is done we can just pack and save as normal.
lsh::overwriteDummyParameters(graph, /*weights=*/lshOutputWeights);
}
Type targetPrecType = (Type) targetPrec;
if (targetPrecType == Type::packed16
|| targetPrecType == Type::packed8avx2
|| targetPrecType == Type::packed8avx512
|| (targetPrecType == Type::float32 && addLsh)) { // only allow non-conversion to float32 if we also use the LSH
graph->packAndSave(outputFile, configStr.str(), targetPrecType);
std::cerr << "Conversion Finished." << std::endl;
} else {
ABORT("Target type is not supported in this funcion: {}", targetPrec);
return false;
}
return true;
}
} // namespace quicksand
} // namespace marian
<|endoftext|> |
<commit_before>#include "messagedialog.h"
#include "qommunicate.h"
#include "messenger.h"
#include "constants.h"
#include "filehandler.h"
MessageDialog::MessageDialog(Member* receiver, QWidget *parent) : QDialog(parent)
{
receivers << receiver;
ui.setupUi(this);
messageTimer = NULL;
setWindowTitle(tr("Conversation: %1").arg(receiver->name()));
connect(messenger(), SIGNAL(msg_recvMsg(Message)), this, SLOT(incomingMessage(Message)));
connect(messenger(), SIGNAL(msg_recvConfirmMsg(Message)), this, SLOT(messageRecvConfirm()));
((Qommunicate*)parent)->dialogOpened(receiver);
}
MessageDialog::MessageDialog(QList<Member*> receivers, QWidget *parent) : QDialog(parent)
{
this->receivers = receivers;
ui.setupUi(this);
QStringList titleRecvs;
Member* t;
foreach(t, receivers)
titleRecvs << t->name();
setWindowTitle(tr("Conversation: %1").arg(titleRecvs.join(",")));
}
MessageDialog::MessageDialog(QWidget *parent) : QDialog(parent)
{
ui.setupUi(this);
setWindowTitle(tr("Multicast message"));
}
void MessageDialog::closeEvent(QCloseEvent *evt)
{
if(receivers.size() == 1)
((Qommunicate*) parent())->dialogClosed(receivers[0]);
evt->accept();
}
void MessageDialog::incomingMessage(Message msg)
{
ui.messageEdit->append(QString("<b style=\"color:blue;\"><%1></b> \n").arg(receivers[0]->name()));
ui.messageEdit->append(msg.payload().replace('\a', ""));
if(msg.command() & QOM_SENDCHECKOPT)
messenger()->sendMessage(QOM_RECVMSG, QByteArray::number(msg.packetNo()), receivers[0]);
}
void MessageDialog::on_sendButton_clicked()
{
if(ui.messageInput->text().trimmed().isEmpty())
return;
if(receivers.isEmpty())
{
messenger()->multicast(QOM_SENDMSG, ui.messageInput->text().toAscii());
QTimer::singleShot(500, this, SLOT(accept()));
return;
}
foreach(Member* m, receivers)
{
messenger()->sendMessage(
QOM_SENDMSG|QOM_SENDCHECKOPT |
( ui.notifyReadCB->isChecked() ? QOM_SECRETOPT | QOM_READCHECKOPT : 0 ),
//( ui.sealCB->isChecked() ? QOM_SECRETOPT : 0 ) ,
ui.messageInput->text().toAscii(), m);
}
if(receivers.size() == 1)
{
if(messageTimer != NULL)
delete messageTimer;
messageTimer = new QTimer(this);
messageTimer->setSingleShot(true);
connect(messageTimer, SIGNAL(timeout()), this, SLOT(messageTimeout()));
ui.messageInput->setEnabled(false);
messageTimer->start(5000);
}
else
{
messageRecvConfirm();
QTimer::singleShot(500, this, SLOT(accept()));
}
}
void MessageDialog::messageTimeout()
{
if(QMessageBox::warning(this,
tr("Sending Failed"),
tr("Failed to send message. To <b>retry</b> click Ok"),
QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok)
{
on_sendButton_clicked();
}
else
ui.messageInput->setEnabled(true);
}
void MessageDialog::messageRecvConfirm()
{
if(! ui.messageInput->text().trimmed().isEmpty())
ui.messageEdit->append(QString("<b style=\"color:red;\"><%1></b> %2").arg(me().name()).arg(ui.messageInput->text()));
ui.messageInput->clear();
ui.messageInput->setFocus();
ui.messageInput->setEnabled(true);
if(receivers.size() == 1 && messageTimer != NULL)
messageTimer->stop();
}
void MessageDialog::dropEvent(QDropEvent *evt)
{
QStringList files;
foreach(QUrl url, evt->mimeData()->urls())
{
files << url.toLocalFile();
}
foreach(Member* to, receivers)
{
fileHandler()->sendFilesRequest(files, to, "");
}
}<commit_msg>Strip incoming before appending<commit_after>#include "messagedialog.h"
#include "qommunicate.h"
#include "messenger.h"
#include "constants.h"
#include "filehandler.h"
MessageDialog::MessageDialog(Member* receiver, QWidget *parent) : QDialog(parent)
{
receivers << receiver;
ui.setupUi(this);
messageTimer = NULL;
setWindowTitle(tr("Conversation: %1").arg(receiver->name()));
connect(messenger(), SIGNAL(msg_recvMsg(Message)), this, SLOT(incomingMessage(Message)));
connect(messenger(), SIGNAL(msg_recvConfirmMsg(Message)), this, SLOT(messageRecvConfirm()));
((Qommunicate*)parent)->dialogOpened(receiver);
}
MessageDialog::MessageDialog(QList<Member*> receivers, QWidget *parent) : QDialog(parent)
{
this->receivers = receivers;
ui.setupUi(this);
QStringList titleRecvs;
Member* t;
foreach(t, receivers)
titleRecvs << t->name();
setWindowTitle(tr("Conversation: %1").arg(titleRecvs.join(",")));
}
MessageDialog::MessageDialog(QWidget *parent) : QDialog(parent)
{
ui.setupUi(this);
setWindowTitle(tr("Multicast message"));
}
void MessageDialog::closeEvent(QCloseEvent *evt)
{
if(receivers.size() == 1)
((Qommunicate*) parent())->dialogClosed(receivers[0]);
evt->accept();
}
void MessageDialog::incomingMessage(Message msg)
{
ui.messageEdit->append(QString("<b style=\"color:blue;\"><%1></b> \n").arg(receivers[0]->name()));
ui.messageEdit->append(msg.payload().replace('\a', "").trimmed());
if(msg.command() & QOM_SENDCHECKOPT)
messenger()->sendMessage(QOM_RECVMSG, QByteArray::number(msg.packetNo()), receivers[0]);
}
void MessageDialog::on_sendButton_clicked()
{
if(ui.messageInput->text().trimmed().isEmpty())
return;
if(receivers.isEmpty())
{
messenger()->multicast(QOM_SENDMSG, ui.messageInput->text().toAscii());
QTimer::singleShot(500, this, SLOT(accept()));
return;
}
foreach(Member* m, receivers)
{
messenger()->sendMessage(
QOM_SENDMSG|QOM_SENDCHECKOPT |
( ui.notifyReadCB->isChecked() ? QOM_SECRETOPT | QOM_READCHECKOPT : 0 ),
//( ui.sealCB->isChecked() ? QOM_SECRETOPT : 0 ) ,
ui.messageInput->text().toAscii(), m);
}
if(receivers.size() == 1)
{
if(messageTimer != NULL)
delete messageTimer;
messageTimer = new QTimer(this);
messageTimer->setSingleShot(true);
connect(messageTimer, SIGNAL(timeout()), this, SLOT(messageTimeout()));
ui.messageInput->setEnabled(false);
messageTimer->start(5000);
}
else
{
messageRecvConfirm();
QTimer::singleShot(500, this, SLOT(accept()));
}
}
void MessageDialog::messageTimeout()
{
if(QMessageBox::warning(this,
tr("Sending Failed"),
tr("Failed to send message. To <b>retry</b> click Ok"),
QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok)
{
on_sendButton_clicked();
}
else
ui.messageInput->setEnabled(true);
}
void MessageDialog::messageRecvConfirm()
{
if(! ui.messageInput->text().trimmed().isEmpty())
ui.messageEdit->append(QString("<b style=\"color:red;\"><%1></b> %2").arg(me().name()).arg(ui.messageInput->text()));
ui.messageInput->clear();
ui.messageInput->setFocus();
ui.messageInput->setEnabled(true);
if(receivers.size() == 1 && messageTimer != NULL)
messageTimer->stop();
}
void MessageDialog::dropEvent(QDropEvent *evt)
{
QStringList files;
foreach(QUrl url, evt->mimeData()->urls())
{
files << url.toLocalFile();
}
foreach(Member* to, receivers)
{
fileHandler()->sendFilesRequest(files, to, "");
}
}<|endoftext|> |
<commit_before>/**
* @file metal_scanner.cpp
* @author Alex Thorne
* @version 1.0
*/
#include "metal_scanner.h"
MetalScanner::MetalScanner(void) : ArmController()
{
//initialize
reference_inductance = 0;
origin_x = (X_MAX_BOUNDARY + X_MIN_BOUNDARY) / 2;
origin_y = (Y_MAX_BOUNDARY + Y_MIN_BOUNDARY) / 2;
origin_z = (Z_MAX_BOUNDARY + Z_MIN_BOUNDARY) / 2;
desired_delta_uH = DEFAULT_DELTA_uH;
uH_tolerance = DEFAULT_uH_TOLERANCE;
}
void MetalScanner::HardwareSetup(void)
{
metal_detector.ConnectToSensor();
metal_detector.ConfigureSensor();
AttachMotors();
}
void MetalScanner::SetReferenceInductance(void)
{
metal_detector.Update();
reference_inductance = metal_detector.GetCh0InductanceuH();
}
uint8_t MetalScanner::SetScanOrigin(float x, float y, float z)
{
if (x > X_MAX_BOUNDARY || x < X_MIN_BOUNDARY)
return 1;
if (y > Y_MAX_BOUNDARY || y < Y_MIN_BOUNDARY)
return 1;
if (z > Z_MAX_BOUNDARY || z < Z_MIN_BOUNDARY)
return 1;
origin_x = x;
origin_y = y;
origin_z = z;
return 0;
}
uint8_t MetalScanner::SetDesiredInductanceDelta(float inductance)
{
if (inductance < 0 || inductance > 3.0)
return 1;
desired_delta_uH = inductance;
return 0;
}
uint8_t MetalScanner::SetInductanceDeltaTolerance(float tolerance)
{
if (tolerance < 0)
return 1;
uH_tolerance = tolerance;
return 0;
}
<commit_msg>Adds additional sampling to SetReferenceInductance<commit_after>/**
* @file metal_scanner.cpp
* @author Alex Thorne
* @version 1.0
*/
#include "metal_scanner.h"
int float_compare(const void *val1, const void *val2);
MetalScanner::MetalScanner(void) : ArmController()
{
//initialize
reference_inductance = 0;
origin_x = (X_MAX_BOUNDARY + X_MIN_BOUNDARY) / 2;
origin_y = (Y_MAX_BOUNDARY + Y_MIN_BOUNDARY) / 2;
origin_z = (Z_MAX_BOUNDARY + Z_MIN_BOUNDARY) / 2;
desired_delta_uH = DEFAULT_DELTA_uH;
uH_tolerance = DEFAULT_uH_TOLERANCE;
}
void MetalScanner::HardwareSetup(void)
{
metal_detector.ConnectToSensor();
metal_detector.ConfigureSensor();
AttachMotors();
}
void MetalScanner::SetReferenceInductance(void)
{
float inductance_vals[20];
for (uint8_t i = 0; i < 20; i ++)
{
delay(50);
metal_detector.Update();
inductance_vals[i] = metal_detector.GetCh0InductanceuH();
}
qsort(inductance_vals, 20, sizeof(inductance_vals[0]), float_compare);
reference_inductance = (inductance_vals[9] + inductance_vals[10]) / 2.0;
}
uint8_t MetalScanner::SetScanOrigin(float x, float y, float z)
{
if (x > X_MAX_BOUNDARY || x < X_MIN_BOUNDARY)
return 1;
if (y > Y_MAX_BOUNDARY || y < Y_MIN_BOUNDARY)
return 1;
if (z > Z_MAX_BOUNDARY || z < Z_MIN_BOUNDARY)
return 1;
origin_x = x;
origin_y = y;
origin_z = z;
return 0;
}
uint8_t MetalScanner::SetDesiredInductanceDelta(float inductance)
{
if (inductance < 0 || inductance > 3.0)
return 1;
desired_delta_uH = inductance;
return 0;
}
uint8_t MetalScanner::SetInductanceDeltaTolerance(float tolerance)
{
if (tolerance < 0)
return 1;
uH_tolerance = tolerance;
return 0;
}
int float_compare(const void *val1, const void *val2)
{
float fval1 = *((float *)val1);
float fval2 = *((float *)val2);
if (fval1 < fval2)
{
return -1;
}
else if (fval1 > fval2)
{
return 1;
}
else
{
return 0;
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <set>
using namespace std;
string func_pattern;
string void_func_pattern;
set<string> filter;
void init_filter()
{
filter.clear();
#define add(x) filter.insert(#x)
add(const);
add(void);
add(int);
add(unsigned);
add(pthread_mutex_t);
add(restrict);
add(pthread_mutexattr_t);
add(struct);
add(timespec);
add(pthread_cond_t);
add(sem_t);
add(pthread_barrier_t);
add(pthread_barrierattr_t);
add(useconds_t);
add(__useconds_t);
add(sockaddr);
add(size_t);
add(ssize_t);
add(msghdr);
add(socklen_t);
add(epoll_event);
#undef add
}
inline bool goodchar(char ch)
{
return ch <= 'Z' && ch >= 'A'
|| ch <= 'z' && ch >= 'a'
|| ch <= '9' && ch >= '0'
|| ch == '_';
}
void replace(string &st, string pat, string tobe)
{
while (true)
{
int p = st.find(pat);
if (p == string::npos) return;
st = st.replace(p, pat.size(), tobe);
}
}
void print_func(
FILE *file,
const char *func_ret_type,
const char *func_name,
const char *args_with_name,
const char *args_without_name,
const char *args_only_name,
const char *lib_path
)
{
string pattern = !strcmp(func_ret_type, "void") ? void_func_pattern : func_pattern;
replace(pattern, "FUNC_RET_TYPE", func_ret_type);
replace(pattern, "FUNC_NAME", func_name);
replace(pattern, "ARGS_WITH_NAME", args_with_name);
replace(pattern, "ARGS_WITHOUT_NAME", args_without_name);
replace(pattern, "ARGS_ONLY_NAME", args_only_name);
replace(pattern, "LIB_PATH", lib_path);
fprintf(file, "%s", pattern.c_str());
}
char buffer[1024];
bool read_line(FILE *fin, string &ret)
{
while (true)
{
if (!fgets(buffer, 1024, fin)) return false;
ret = buffer;
ret.erase(ret.find_last_not_of(" \t\n\r\f\v") + 1);
if (ret.size()) return true;
}
}
void convert(FILE *fin)
{
FILE *hook_cpp = fopen("template.cpp", "w");
FILE *types = fopen("hook_type_def.h", "w");
/*
fprintf(hook_cpp, "#include <pthread.h>\n");
fprintf(hook_cpp, "#include <stdio.h>\n");
fprintf(hook_cpp, "#include <dlfcn.h>\n");
fprintf(hook_cpp, "#include <stdlib.h>\n");
fprintf(hook_cpp, "#include <sys/types.h>\n");
fprintf(hook_cpp, "#include <sys/socket.h>\n");
fprintf(hook_cpp, "#include <sys/select.h>\n");
fprintf(hook_cpp, "#include <sys/time.h>\n");
fprintf(hook_cpp, "extern \"C\" void __gxx_personality_v0(void) {} \n\n");
fprintf(hook_cpp, "#define PRINT_DEBUG\n");
*/
while (true)
{
string flag = "";
while (flag != "STARTDEF" && flag != "START_SHORT_DEFINE")
if (!read_line(fin, flag)) break;
string func_ret_type;
string func_name;
string args_with_name = "";
string args_without_name = "";
string args_only_name = "";
string lib_path = "";
if (flag == "STARTDEF")
{
if (!read_line(fin, func_ret_type)) break;
if (!read_line(fin, func_name)) break;
if (!read_line(fin, lib_path)) break;
while (read_line(fin, flag) && flag != "SECTION")
args_without_name += flag;
while (read_line(fin, flag) && flag != "SECTION")
args_with_name += flag;
while (read_line(fin, flag) && flag != "SECTION")
args_only_name += flag;
} else
if (flag == "START_SHORT_DEFINE")
{
if (!read_line(fin, lib_path)) break;
if (!read_line(fin, func_ret_type)) break;
if (!read_line(fin, func_name)) break;
string st;
if (!read_line(fin, st)) break;
while (st[0] != '(') st = st.substr(1);
while (st[st.size() - 1] != ')') st = st.substr(0, st.size() - 1);
int len = st.size();
st = st.substr(1, len - 2);
args_with_name = st;
args_only_name = "";
args_without_name = "";
do {
string token = "";
while (st.size() && goodchar(st[0]))
{
token = token + st[0];
st = st.substr(1);
}
if (token.size())
if (filter.find(token) == filter.end())
args_only_name += token;
else
args_without_name += token;
else {
if (st[0] == ',')
{
args_only_name += ',';
args_without_name += ',';
} else
args_without_name += st[0];
st = st.substr(1);
}
} while (st.size());
} else
break;
print_func(
hook_cpp,
func_ret_type.c_str(),
func_name.c_str(),
args_with_name.c_str(),
args_without_name.c_str(),
args_only_name.c_str(),
lib_path.c_str()
);
fprintf(types, "typedef %s (*__%s_funcdef)(%s);\n",
func_ret_type.c_str(),
func_name.c_str(),
args_with_name.c_str());
}
fclose(hook_cpp);
fclose(types);
}
string read_file(const char *name)
{
FILE *file = fopen(name, "r");
string ret = "";
while (fgets(buffer, 1024, file))
{
ret = ret + buffer;
}
fclose(file);
return ret;
}
int main()
{
init_filter();
func_pattern = read_file("func_template.cpp");
void_func_pattern = read_file("void_func_template.cpp");
convert(stdin);
return 0;
}
<commit_msg>fixed a bug in code_gen.cpp when argument is empty.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <set>
using namespace std;
string func_pattern;
string void_func_pattern;
set<string> filter;
void init_filter()
{
filter.clear();
#define add(x) filter.insert(#x)
add(const);
add(void);
add(int);
add(unsigned);
add(pthread_mutex_t);
add(restrict);
add(pthread_mutexattr_t);
add(struct);
add(timespec);
add(pthread_cond_t);
add(sem_t);
add(pthread_barrier_t);
add(pthread_barrierattr_t);
add(useconds_t);
add(__useconds_t);
add(sockaddr);
add(size_t);
add(ssize_t);
add(pid_t);
add(msghdr);
add(socklen_t);
add(epoll_event);
#undef add
}
inline bool goodchar(char ch)
{
return ch <= 'Z' && ch >= 'A'
|| ch <= 'z' && ch >= 'a'
|| ch <= '9' && ch >= '0'
|| ch == '_';
}
void replace(string &st, string pat, string tobe)
{
while (true)
{
int p = st.find(pat);
if (p == string::npos) return;
st = st.replace(p, pat.size(), tobe);
}
}
void print_func(
FILE *file,
const char *func_ret_type,
const char *func_name,
const char *args_with_name,
const char *args_without_name,
const char *args_only_name,
const char *lib_path
)
{
string pattern = !strcmp(func_ret_type, "void") ? void_func_pattern : func_pattern;
replace(pattern, "FUNC_RET_TYPE", func_ret_type);
replace(pattern, "FUNC_NAME", func_name);
replace(pattern, "ARGS_WITH_NAME", args_with_name);
replace(pattern, "ARGS_WITHOUT_NAME", args_without_name);
if (!strlen(args_only_name))
{
replace(pattern, ", ARGS_ONLY_NAME", args_only_name);
replace(pattern, "ARGS_ONLY_NAME", args_only_name);
} else
replace(pattern, "ARGS_ONLY_NAME", args_only_name);
replace(pattern, "LIB_PATH", lib_path);
fprintf(file, "%s", pattern.c_str());
}
char buffer[1024];
bool read_line(FILE *fin, string &ret)
{
while (true)
{
if (!fgets(buffer, 1024, fin)) return false;
ret = buffer;
ret.erase(ret.find_last_not_of(" \t\n\r\f\v") + 1);
if (ret.size()) return true;
}
}
void convert(FILE *fin)
{
FILE *hook_cpp = fopen("template.cpp", "w");
FILE *types = fopen("hook_type_def.h", "w");
/*
fprintf(hook_cpp, "#include <pthread.h>\n");
fprintf(hook_cpp, "#include <stdio.h>\n");
fprintf(hook_cpp, "#include <dlfcn.h>\n");
fprintf(hook_cpp, "#include <stdlib.h>\n");
fprintf(hook_cpp, "#include <sys/types.h>\n");
fprintf(hook_cpp, "#include <sys/socket.h>\n");
fprintf(hook_cpp, "#include <sys/select.h>\n");
fprintf(hook_cpp, "#include <sys/time.h>\n");
fprintf(hook_cpp, "extern \"C\" void __gxx_personality_v0(void) {} \n\n");
fprintf(hook_cpp, "#define PRINT_DEBUG\n");
*/
while (true)
{
string flag = "";
while (flag != "STARTDEF" && flag != "START_SHORT_DEFINE")
if (!read_line(fin, flag)) break;
string func_ret_type;
string func_name;
string args_with_name = "";
string args_without_name = "";
string args_only_name = "";
string lib_path = "";
if (flag == "STARTDEF")
{
if (!read_line(fin, func_ret_type)) break;
if (!read_line(fin, func_name)) break;
if (!read_line(fin, lib_path)) break;
while (read_line(fin, flag) && flag != "SECTION")
args_without_name += flag;
while (read_line(fin, flag) && flag != "SECTION")
args_with_name += flag;
while (read_line(fin, flag) && flag != "SECTION")
args_only_name += flag;
} else
if (flag == "START_SHORT_DEFINE")
{
if (!read_line(fin, lib_path)) break;
if (!read_line(fin, func_ret_type)) break;
if (!read_line(fin, func_name)) break;
string st;
if (!read_line(fin, st)) break;
while (st[0] != '(') st = st.substr(1);
while (st[st.size() - 1] != ')') st = st.substr(0, st.size() - 1);
int len = st.size();
st = st.substr(1, len - 2);
args_with_name = st;
args_only_name = "";
args_without_name = "";
do {
string token = "";
while (st.size() && goodchar(st[0]))
{
token = token + st[0];
st = st.substr(1);
}
if (token.size())
if (filter.find(token) == filter.end())
args_only_name += token;
else
args_without_name += token;
else {
if (!st.size()) break;
if (st[0] == ',')
{
args_only_name += ',';
args_without_name += ',';
} else
args_without_name += st[0];
st = st.substr(1);
}
} while (st.size());
} else
break;
print_func(
hook_cpp,
func_ret_type.c_str(),
func_name.c_str(),
args_with_name.c_str(),
args_without_name.c_str(),
args_only_name.c_str(),
lib_path.c_str()
);
fprintf(types, "typedef %s (*__%s_funcdef)(%s);\n",
func_ret_type.c_str(),
func_name.c_str(),
args_with_name.c_str());
}
fclose(hook_cpp);
fclose(types);
}
string read_file(const char *name)
{
FILE *file = fopen(name, "r");
string ret = "";
while (fgets(buffer, 1024, file))
{
ret = ret + buffer;
}
fclose(file);
return ret;
}
int main()
{
init_filter();
func_pattern = read_file("func_template.cpp");
void_func_pattern = read_file("void_func_template.cpp");
convert(stdin);
return 0;
}
<|endoftext|> |
<commit_before>#include "histogram.h"
#include <QPainter>
#include <QDebug>
Histogram::Histogram(QWidget* p) :QWidget(p) {
}
void
Histogram::setData(const QList<QPair<QString,quint32> >& d) {
data = d;
update();
}
typedef QPair<QString, quint32> StringUIntPair;
void
Histogram::paintEvent(QPaintEvent *) {
if (data.size() == 0) return;
int w = width();
int h = height();
int m = 5;
int bw = (w-m*(data.size()-1))/data.size();
uint max = 0;
foreach (const StringUIntPair& p, data) {
if (p.second > max) max = p.second;
}
QPainter painter(this);
painter.setPen(palette().highlightedText().color());
int offset = 0;
painter.rotate(-90);
painter.translate(-h, 0);
foreach (const StringUIntPair& p, data) {
int bh = p.second*h/max;
painter.fillRect(0, offset, bh, bw, palette().highlight());
painter.drawText(QRect(m, offset, bh-m, bw), Qt::AlignVCenter,
p.first);
offset += bw + m;
}
}
<commit_msg>Use qreal instead of int for painting.<commit_after>#include "histogram.h"
#include <QPainter>
#include <QDebug>
Histogram::Histogram(QWidget* p) :QWidget(p) {
}
void
Histogram::setData(const QList<QPair<QString,quint32> >& d) {
data = d;
update();
}
typedef QPair<QString, quint32> StringUIntPair;
void
Histogram::paintEvent(QPaintEvent *) {
if (data.size() == 0) return;
int w = width();
int h = height();
int m = 5;
int bw = (w-m*(data.size()-1))/data.size();
uint max = 0;
foreach (const StringUIntPair& p, data) {
if (p.second > max) max = p.second;
}
QPainter painter(this);
painter.setPen(palette().highlightedText().color());
qreal offset = 0;
painter.rotate(-90);
painter.translate(-h, 0);
foreach (const StringUIntPair& p, data) {
qreal bh = p.second*h/(qreal)max;
painter.fillRect(QRectF(0, offset, bh, bw), palette().highlight());
painter.drawText(QRectF(m, offset, bh-m, bw), Qt::AlignVCenter,
p.first);
offset += bw + m;
}
}
<|endoftext|> |
<commit_before>#include "parser.hh"
#include "file.hh" // SPECIAL_EOF
#include "bookmark.hh"
#include "bookmark_container.hh"
#include <iostream>
#include <map>
#include <string>
#include <cstring> // strncmp
using std::map;
using std::string;
struct Parser::Key
{
Key(Language l, State s, char e): language(l), oldState(s), event(e) {}
bool operator<(const Key& k) const
{
return (language < k.language ? true :
language > k.language ? false :
oldState < k.oldState ? true :
oldState > k.oldState ? false :
event < k.event);
}
Language language;
State oldState;
char event;
};
struct Parser::Value
{
State newState;
Action action;
};
static const char ANY = '\0';
const char* Parser::stateToString(Parser::State s)
{
switch (s)
{
case NORMAL: return "NORMAL";
case COMMENT_START: return "COMMENT_START";
case C_COMMENT: return "C_COMMENT";
case C_COMMENT_END: return "C_COMMENT_END";
case DOUBLE_QUOTE: return "DOUBLE_QUOTE";
case DOUBLE_QUOTE_1: return "DOUBLE_QUOTE_1";
case DOUBLE_QUOTE_2: return "DOUBLE_QUOTE_2";
case DOUBLE_QUOTE_3: return "DOUBLE_QUOTE_3";
case DOUBLE_QUOTE_4: return "DOUBLE_QUOTE_4";
case DOUBLE_QUOTE_5: return "DOUBLE_QUOTE_5";
case SINGLE_QUOTE_1: return "SINGLE_QUOTE_1";
case SINGLE_QUOTE_2: return "SINGLE_QUOTE_2";
case SINGLE_QUOTE_3: return "SINGLE_QUOTE_3";
case SINGLE_QUOTE_4: return "SINGLE_QUOTE_4";
case SINGLE_QUOTE_5: return "SINGLE_QUOTE_5";
case SINGLE_QUOTE: return "SINGLE_QUOTE";
case ESCAPE_DOUBLE: return "ESCAPE_DOUBLE";
case ESCAPE_SINGLE: return "ESCAPE_SINGLE";
case SKIP_TO_EOL: return "SKIP_TO_EOL";
case SPACE: return "SPACE";
case NO_STATE: return "NO_STATE";
default: return "unknown";
}
}
/**
* Reads the original text into a processed text, which is returned. Also sets
* the bookmarks to point into the two strings.
*/
const char* Parser::process(bool wordMode)
{
const Matrix& matrix = wordMode ? textBehavior() : codeBehavior();
itsProcessedText = new char[Bookmark::totalLength()];
State state = NORMAL;
for (size_t i = 0; i < Bookmark::totalLength(); ++i)
{
state = processChar(state, matrix, i);
// std::cout << stateToString(state) << ' '
// << Bookmark::getChar(i) << "\n";
}
addChar('\0', Bookmark::totalLength());
return itsProcessedText;
}
static bool lookaheadIs(const string& s, const char& c)
{
return strncmp(s.c_str(), &c, s.length()) == 0;
}
Parser::State Parser::processChar(State state,
const Matrix& matrix,
size_t i)
{
static const string imports = "import";
static const string usings = "using";
const char& c = Bookmark::getChar(i);
// Apparently there can be zeroes in the total string, but only when
// running on some machines. Don't know why.
if (c == '\0')
return state;
if (c == SPECIAL_EOF)
{
addChar(c, i);
return NORMAL;
}
Language language = getLanguage(Bookmark::getFileName(i));
Matrix::const_iterator it;
if ((it = matrix.find({ language, state, c })) != matrix.end() ||
(it = matrix.find({ language, state, ANY })) != matrix.end() ||
(it = matrix.find({ ALL, state, c })) != matrix.end() ||
(it = matrix.find({ ALL, state, ANY })) != matrix.end())
{
performAction(it->second.action, c, i);
return it->second.newState;
}
if (state == NORMAL)
{ // Handle state/event pair that can't be handled by The Matrix.
if (timeForNewBookmark && c != '}')
if (lookaheadIs(imports, c) || lookaheadIs(usings, c))
state = SKIP_TO_EOL;
else
itsContainer.addBookmark(addChar(c, i));
else
addChar(c, i);
timeForNewBookmark = false;
}
return state;
}
static bool endsWith(const std::string& str, const std::string& suffix)
{
return str.size() >= suffix.size() &&
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
Parser::Language Parser::getLanguage(const string& fileName)
{
if (endsWith(fileName, ".c") or
endsWith(fileName, ".cc") or
endsWith(fileName, ".h") or
endsWith(fileName, ".hh") or
endsWith(fileName, ".hpp") or
endsWith(fileName, ".cpp") or
endsWith(fileName, ".java"))
{
return C_FAMILY;
}
if (endsWith(fileName, ".erl") or
endsWith(fileName, ".hrl"))
{
return ERLANG;
}
if (endsWith(fileName, ".rb") or
endsWith(fileName, ".sh") or
endsWith(fileName, ".pl"))
{
return SCRIPT;
}
if (endsWith(fileName, ".py"))
{
return PYTHON;
}
return ALL;
}
void Parser::performAction(Action action, char c, size_t i)
{
switch (action)
{
case ADD_SLASH_AND_CHAR:
addChar('/', i-1);
if (not isspace(c))
addChar(c, i);
break;
case ADD_CHAR:
{
const Bookmark bm = addChar(c, i);
if (timeForNewBookmark)
itsContainer.addBookmark(bm);
timeForNewBookmark = false;
break;
}
case ADD_BOOKMARK:
timeForNewBookmark = true;
break;
case ADD_SPACE:
addChar(' ', i);
itsContainer.addBookmark(addChar(c, i));
break;
case NA:
break;
}
}
/**
* Adds a character to the processed string and sets a bookmark, which is then
* returned.
*/
Bookmark Parser::addChar(char c, int originalIndex)
{
static int procIx;
Bookmark bookmark(originalIndex, &itsProcessedText[procIx]);
itsProcessedText[procIx++] = c;
return bookmark;
}
const Parser::Matrix& Parser::codeBehavior() const
{
static Matrix m = {
// language, oldState event newState action
{ { ALL, NORMAL, '/' }, { COMMENT_START, NA } },
{ { ALL, NORMAL, '"' }, { DOUBLE_QUOTE, ADD_CHAR } },
{ { ALL, NORMAL, '\'' }, { SINGLE_QUOTE, ADD_CHAR } },
{ { ALL, NORMAL, '\n' }, { NORMAL, ADD_BOOKMARK } },
{ { ALL, NORMAL, ' ' }, { NORMAL, NA } },
{ { ALL, NORMAL, '\t' }, { NORMAL, NA } },
{ { ALL, NORMAL, '#' }, { SKIP_TO_EOL, NA } },
{ { ERLANG, NORMAL, '#' }, { NORMAL, NA } },
{ { ERLANG, NORMAL, '%' }, { SKIP_TO_EOL, NA } },
{ { PYTHON, NORMAL, '"' }, { DOUBLE_QUOTE_1, NA } },
{ { PYTHON, NORMAL, '\'' }, { SINGLE_QUOTE_1, NA } },
// See special handling of NORMAL in code.
{ { PYTHON, DOUBLE_QUOTE_1, '"' }, { DOUBLE_QUOTE_2, NA } },
{ { PYTHON, DOUBLE_QUOTE_2, '"' }, { DOUBLE_QUOTE_3, NA } },
{ { PYTHON, DOUBLE_QUOTE_2, ANY }, { NORMAL, ADD_CHAR } },
{ { PYTHON, DOUBLE_QUOTE_1, ANY }, { DOUBLE_QUOTE, ADD_CHAR } },
{ { PYTHON, DOUBLE_QUOTE_3, '"' }, { DOUBLE_QUOTE_4, NA } },
{ { PYTHON, DOUBLE_QUOTE_3, ANY }, { DOUBLE_QUOTE_3, NA } },
{ { PYTHON, DOUBLE_QUOTE_4, '"' }, { DOUBLE_QUOTE_5, NA } },
{ { PYTHON, DOUBLE_QUOTE_4, ANY }, { DOUBLE_QUOTE_3, NA } },
{ { PYTHON, DOUBLE_QUOTE_5, '"' }, { NORMAL, NA } },
{ { PYTHON, DOUBLE_QUOTE_5, ANY }, { DOUBLE_QUOTE_3, NA } },
{ { PYTHON, SINGLE_QUOTE_1, '\'' }, { SINGLE_QUOTE_2, NA } },
{ { PYTHON, SINGLE_QUOTE_2, '\'' }, { SINGLE_QUOTE_3, NA } },
{ { PYTHON, SINGLE_QUOTE_3, '\'' }, { SINGLE_QUOTE_4, NA } },
{ { PYTHON, SINGLE_QUOTE_4, '\'' }, { SINGLE_QUOTE_5, NA } },
{ { PYTHON, SINGLE_QUOTE_5, '\'' }, { NORMAL, NA } },
{ { PYTHON, SINGLE_QUOTE_1, ANY }, { SINGLE_QUOTE, ADD_CHAR } },
{ { PYTHON, SINGLE_QUOTE_2, ANY }, { NORMAL, ADD_CHAR } },
{ { PYTHON, SINGLE_QUOTE_3, ANY }, { SINGLE_QUOTE_3, NA } },
{ { PYTHON, SINGLE_QUOTE_4, ANY }, { SINGLE_QUOTE_3, NA } },
{ { PYTHON, SINGLE_QUOTE_5, ANY }, { SINGLE_QUOTE_3, NA } },
{ { ALL, DOUBLE_QUOTE, '\\' }, { ESCAPE_DOUBLE, ADD_CHAR } },
{ { ALL, DOUBLE_QUOTE, '"' }, { NORMAL, ADD_CHAR } },
{ { ALL, DOUBLE_QUOTE, ANY }, { DOUBLE_QUOTE, ADD_CHAR } },
{ { ALL, DOUBLE_QUOTE, '\n' }, { NORMAL, ADD_BOOKMARK } }, // 1
{ { ALL, SINGLE_QUOTE, '\\' }, { ESCAPE_SINGLE, ADD_CHAR } },
{ { ALL, SINGLE_QUOTE, '\'' }, { NORMAL, ADD_CHAR } },
{ { ALL, SINGLE_QUOTE, ANY }, { SINGLE_QUOTE, ADD_CHAR } },
{ { ALL, SINGLE_QUOTE, '\n' }, { NORMAL, ADD_BOOKMARK } }, // 1
{ { ALL, ESCAPE_SINGLE, ANY }, { SINGLE_QUOTE, ADD_CHAR } },
{ { ALL, ESCAPE_DOUBLE, ANY }, { DOUBLE_QUOTE, ADD_CHAR } },
// 1: probably a mistake if quote reaches end-of-line.
{ { ALL, COMMENT_START, '*' }, { C_COMMENT, NA } },
{ { ALL, COMMENT_START, '/' }, { SKIP_TO_EOL, NA } },
{ { ALL, COMMENT_START, ANY }, { NORMAL, ADD_SLASH_AND_CHAR } },
{ { ALL, SKIP_TO_EOL, '\n' }, { NORMAL, ADD_BOOKMARK } },
{ { ALL, C_COMMENT, '*' }, { C_COMMENT_END, NA } },
{ { ALL, C_COMMENT_END, '/' }, { NORMAL, NA } },
{ { ALL, C_COMMENT_END, '*' }, { C_COMMENT_END, NA } },
{ { ALL, C_COMMENT_END, ANY }, { C_COMMENT, NA } },
{ { ALL, NO_STATE, ANY }, { NO_STATE, NA } }
};
return m;
}
const Parser::Matrix& Parser::textBehavior() const
{
static Matrix m = {
// oldState event newState action
{ { ALL, NORMAL, ' ' }, { SPACE, NA } },
{ { ALL, NORMAL, '\t' }, { SPACE, NA } },
{ { ALL, NORMAL, '\r' }, { SPACE, NA } },
{ { ALL, NORMAL, '\n' }, { SPACE, NA } },
{ { ALL, NORMAL, '' }, { SPACE, NA } },
{ { ALL, NORMAL, ANY }, { NORMAL, ADD_CHAR } },
{ { ALL, SPACE, ' ' }, { SPACE, NA } },
{ { ALL, SPACE, '\t' }, { SPACE, NA } },
{ { ALL, SPACE, '\r' }, { SPACE, NA } },
{ { ALL, SPACE, '\n' }, { SPACE, NA } },
{ { ALL, SPACE, '' }, { SPACE, NA } },
{ { ALL, SPACE, ANY }, { NORMAL, ADD_SPACE } },
{ { ALL, NO_STATE, ANY }, { NO_STATE, NA } }
};
return m;
}
<commit_msg>Easier to read parser matrix for python, part 2<commit_after>#include "parser.hh"
#include "file.hh" // SPECIAL_EOF
#include "bookmark.hh"
#include "bookmark_container.hh"
#include <iostream>
#include <map>
#include <string>
#include <cstring> // strncmp
using std::map;
using std::string;
struct Parser::Key
{
Key(Language l, State s, char e): language(l), oldState(s), event(e) {}
bool operator<(const Key& k) const
{
return (language < k.language ? true :
language > k.language ? false :
oldState < k.oldState ? true :
oldState > k.oldState ? false :
event < k.event);
}
Language language;
State oldState;
char event;
};
struct Parser::Value
{
State newState;
Action action;
};
static const char ANY = '\0';
const char* Parser::stateToString(Parser::State s)
{
switch (s)
{
case NORMAL: return "NORMAL";
case COMMENT_START: return "COMMENT_START";
case C_COMMENT: return "C_COMMENT";
case C_COMMENT_END: return "C_COMMENT_END";
case DOUBLE_QUOTE: return "DOUBLE_QUOTE";
case DOUBLE_QUOTE_1: return "DOUBLE_QUOTE_1";
case DOUBLE_QUOTE_2: return "DOUBLE_QUOTE_2";
case DOUBLE_QUOTE_3: return "DOUBLE_QUOTE_3";
case DOUBLE_QUOTE_4: return "DOUBLE_QUOTE_4";
case DOUBLE_QUOTE_5: return "DOUBLE_QUOTE_5";
case SINGLE_QUOTE_1: return "SINGLE_QUOTE_1";
case SINGLE_QUOTE_2: return "SINGLE_QUOTE_2";
case SINGLE_QUOTE_3: return "SINGLE_QUOTE_3";
case SINGLE_QUOTE_4: return "SINGLE_QUOTE_4";
case SINGLE_QUOTE_5: return "SINGLE_QUOTE_5";
case SINGLE_QUOTE: return "SINGLE_QUOTE";
case ESCAPE_DOUBLE: return "ESCAPE_DOUBLE";
case ESCAPE_SINGLE: return "ESCAPE_SINGLE";
case SKIP_TO_EOL: return "SKIP_TO_EOL";
case SPACE: return "SPACE";
case NO_STATE: return "NO_STATE";
default: return "unknown";
}
}
/**
* Reads the original text into a processed text, which is returned. Also sets
* the bookmarks to point into the two strings.
*/
const char* Parser::process(bool wordMode)
{
const Matrix& matrix = wordMode ? textBehavior() : codeBehavior();
itsProcessedText = new char[Bookmark::totalLength()];
State state = NORMAL;
for (size_t i = 0; i < Bookmark::totalLength(); ++i)
{
state = processChar(state, matrix, i);
// std::cout << stateToString(state) << ' '
// << Bookmark::getChar(i) << "\n";
}
addChar('\0', Bookmark::totalLength());
return itsProcessedText;
}
static bool lookaheadIs(const string& s, const char& c)
{
return strncmp(s.c_str(), &c, s.length()) == 0;
}
Parser::State Parser::processChar(State state,
const Matrix& matrix,
size_t i)
{
static const string imports = "import";
static const string usings = "using";
const char& c = Bookmark::getChar(i);
// Apparently there can be zeroes in the total string, but only when
// running on some machines. Don't know why.
if (c == '\0')
return state;
if (c == SPECIAL_EOF)
{
addChar(c, i);
return NORMAL;
}
Language language = getLanguage(Bookmark::getFileName(i));
Matrix::const_iterator it;
if ((it = matrix.find({ language, state, c })) != matrix.end() ||
(it = matrix.find({ language, state, ANY })) != matrix.end() ||
(it = matrix.find({ ALL, state, c })) != matrix.end() ||
(it = matrix.find({ ALL, state, ANY })) != matrix.end())
{
performAction(it->second.action, c, i);
return it->second.newState;
}
if (state == NORMAL)
{ // Handle state/event pair that can't be handled by The Matrix.
if (timeForNewBookmark && c != '}')
if (lookaheadIs(imports, c) || lookaheadIs(usings, c))
state = SKIP_TO_EOL;
else
itsContainer.addBookmark(addChar(c, i));
else
addChar(c, i);
timeForNewBookmark = false;
}
return state;
}
static bool endsWith(const std::string& str, const std::string& suffix)
{
return str.size() >= suffix.size() &&
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
Parser::Language Parser::getLanguage(const string& fileName)
{
if (endsWith(fileName, ".c") or
endsWith(fileName, ".cc") or
endsWith(fileName, ".h") or
endsWith(fileName, ".hh") or
endsWith(fileName, ".hpp") or
endsWith(fileName, ".cpp") or
endsWith(fileName, ".java"))
{
return C_FAMILY;
}
if (endsWith(fileName, ".erl") or
endsWith(fileName, ".hrl"))
{
return ERLANG;
}
if (endsWith(fileName, ".rb") or
endsWith(fileName, ".sh") or
endsWith(fileName, ".pl"))
{
return SCRIPT;
}
if (endsWith(fileName, ".py"))
{
return PYTHON;
}
return ALL;
}
void Parser::performAction(Action action, char c, size_t i)
{
switch (action)
{
case ADD_SLASH_AND_CHAR:
addChar('/', i-1);
if (not isspace(c))
addChar(c, i);
break;
case ADD_CHAR:
{
const Bookmark bm = addChar(c, i);
if (timeForNewBookmark)
itsContainer.addBookmark(bm);
timeForNewBookmark = false;
break;
}
case ADD_BOOKMARK:
timeForNewBookmark = true;
break;
case ADD_SPACE:
addChar(' ', i);
itsContainer.addBookmark(addChar(c, i));
break;
case NA:
break;
}
}
/**
* Adds a character to the processed string and sets a bookmark, which is then
* returned.
*/
Bookmark Parser::addChar(char c, int originalIndex)
{
static int procIx;
Bookmark bookmark(originalIndex, &itsProcessedText[procIx]);
itsProcessedText[procIx++] = c;
return bookmark;
}
const Parser::Matrix& Parser::codeBehavior() const
{
static Matrix m = {
// language, oldState event newState action
{ { ALL, NORMAL, '/' }, { COMMENT_START, NA } },
{ { ALL, NORMAL, '"' }, { DOUBLE_QUOTE, ADD_CHAR } },
{ { ALL, NORMAL, '\'' }, { SINGLE_QUOTE, ADD_CHAR } },
{ { ALL, NORMAL, '\n' }, { NORMAL, ADD_BOOKMARK } },
{ { ALL, NORMAL, ' ' }, { NORMAL, NA } },
{ { ALL, NORMAL, '\t' }, { NORMAL, NA } },
{ { ALL, NORMAL, '#' }, { SKIP_TO_EOL, NA } },
{ { ERLANG, NORMAL, '#' }, { NORMAL, NA } },
{ { ERLANG, NORMAL, '%' }, { SKIP_TO_EOL, NA } },
{ { PYTHON, NORMAL, '"' }, { DOUBLE_QUOTE_1, NA } },
{ { PYTHON, NORMAL, '\'' }, { SINGLE_QUOTE_1, NA } },
// See special handling of NORMAL in code.
{ { PYTHON, DOUBLE_QUOTE_1, '"' }, { DOUBLE_QUOTE_2, NA } },
{ { PYTHON, DOUBLE_QUOTE_2, '"' }, { DOUBLE_QUOTE_3, NA } },
{ { PYTHON, DOUBLE_QUOTE_3, '"' }, { DOUBLE_QUOTE_4, NA } },
{ { PYTHON, DOUBLE_QUOTE_4, '"' }, { DOUBLE_QUOTE_5, NA } },
{ { PYTHON, DOUBLE_QUOTE_5, '"' }, { NORMAL, NA } },
{ { PYTHON, DOUBLE_QUOTE_1, ANY }, { DOUBLE_QUOTE, ADD_CHAR } },
{ { PYTHON, DOUBLE_QUOTE_2, ANY }, { NORMAL, ADD_CHAR } },
{ { PYTHON, DOUBLE_QUOTE_3, ANY }, { DOUBLE_QUOTE_3, NA } },
{ { PYTHON, DOUBLE_QUOTE_4, ANY }, { DOUBLE_QUOTE_3, NA } },
{ { PYTHON, DOUBLE_QUOTE_5, ANY }, { DOUBLE_QUOTE_3, NA } },
{ { PYTHON, SINGLE_QUOTE_1, '\'' }, { SINGLE_QUOTE_2, NA } },
{ { PYTHON, SINGLE_QUOTE_2, '\'' }, { SINGLE_QUOTE_3, NA } },
{ { PYTHON, SINGLE_QUOTE_3, '\'' }, { SINGLE_QUOTE_4, NA } },
{ { PYTHON, SINGLE_QUOTE_4, '\'' }, { SINGLE_QUOTE_5, NA } },
{ { PYTHON, SINGLE_QUOTE_5, '\'' }, { NORMAL, NA } },
{ { PYTHON, SINGLE_QUOTE_1, ANY }, { SINGLE_QUOTE, ADD_CHAR } },
{ { PYTHON, SINGLE_QUOTE_2, ANY }, { NORMAL, ADD_CHAR } },
{ { PYTHON, SINGLE_QUOTE_3, ANY }, { SINGLE_QUOTE_3, NA } },
{ { PYTHON, SINGLE_QUOTE_4, ANY }, { SINGLE_QUOTE_3, NA } },
{ { PYTHON, SINGLE_QUOTE_5, ANY }, { SINGLE_QUOTE_3, NA } },
{ { ALL, DOUBLE_QUOTE, '\\' }, { ESCAPE_DOUBLE, ADD_CHAR } },
{ { ALL, DOUBLE_QUOTE, '"' }, { NORMAL, ADD_CHAR } },
{ { ALL, DOUBLE_QUOTE, ANY }, { DOUBLE_QUOTE, ADD_CHAR } },
{ { ALL, DOUBLE_QUOTE, '\n' }, { NORMAL, ADD_BOOKMARK } }, // 1
{ { ALL, SINGLE_QUOTE, '\\' }, { ESCAPE_SINGLE, ADD_CHAR } },
{ { ALL, SINGLE_QUOTE, '\'' }, { NORMAL, ADD_CHAR } },
{ { ALL, SINGLE_QUOTE, ANY }, { SINGLE_QUOTE, ADD_CHAR } },
{ { ALL, SINGLE_QUOTE, '\n' }, { NORMAL, ADD_BOOKMARK } }, // 1
{ { ALL, ESCAPE_SINGLE, ANY }, { SINGLE_QUOTE, ADD_CHAR } },
{ { ALL, ESCAPE_DOUBLE, ANY }, { DOUBLE_QUOTE, ADD_CHAR } },
// 1: probably a mistake if quote reaches end-of-line.
{ { ALL, COMMENT_START, '*' }, { C_COMMENT, NA } },
{ { ALL, COMMENT_START, '/' }, { SKIP_TO_EOL, NA } },
{ { ALL, COMMENT_START, ANY }, { NORMAL, ADD_SLASH_AND_CHAR } },
{ { ALL, SKIP_TO_EOL, '\n' }, { NORMAL, ADD_BOOKMARK } },
{ { ALL, C_COMMENT, '*' }, { C_COMMENT_END, NA } },
{ { ALL, C_COMMENT_END, '/' }, { NORMAL, NA } },
{ { ALL, C_COMMENT_END, '*' }, { C_COMMENT_END, NA } },
{ { ALL, C_COMMENT_END, ANY }, { C_COMMENT, NA } },
{ { ALL, NO_STATE, ANY }, { NO_STATE, NA } }
};
return m;
}
const Parser::Matrix& Parser::textBehavior() const
{
static Matrix m = {
// oldState event newState action
{ { ALL, NORMAL, ' ' }, { SPACE, NA } },
{ { ALL, NORMAL, '\t' }, { SPACE, NA } },
{ { ALL, NORMAL, '\r' }, { SPACE, NA } },
{ { ALL, NORMAL, '\n' }, { SPACE, NA } },
{ { ALL, NORMAL, '' }, { SPACE, NA } },
{ { ALL, NORMAL, ANY }, { NORMAL, ADD_CHAR } },
{ { ALL, SPACE, ' ' }, { SPACE, NA } },
{ { ALL, SPACE, '\t' }, { SPACE, NA } },
{ { ALL, SPACE, '\r' }, { SPACE, NA } },
{ { ALL, SPACE, '\n' }, { SPACE, NA } },
{ { ALL, SPACE, '' }, { SPACE, NA } },
{ { ALL, SPACE, ANY }, { NORMAL, ADD_SPACE } },
{ { ALL, NO_STATE, ANY }, { NO_STATE, NA } }
};
return m;
}
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include "oddlib/lvlarchive.hpp"
int main(int argc, char** argv)
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
TEST(LvlArchive, FileNotFound)
{
ASSERT_THROW(Oddlib::LvlArchive("not_found.lvl"), Oddlib::Exception);
}
TEST(LvlArchive, /*DISABLED_*/Integration)
{
// Load AE lvl
Oddlib::LvlArchive lvl("MI.LVL");
const auto file = lvl.FileByName("FLYSLIG.BND");
ASSERT_NE(nullptr, file);
const auto chunk = file->ChunkById(450);
ASSERT_NE(nullptr, chunk);
ASSERT_EQ(450, chunk->Id());
const auto data = chunk->ReadData();
ASSERT_EQ(false, data.empty());
}
<commit_msg>leave integration test disabled on travis<commit_after>#include <gmock/gmock.h>
#include "oddlib/lvlarchive.hpp"
int main(int argc, char** argv)
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
TEST(LvlArchive, FileNotFound)
{
ASSERT_THROW(Oddlib::LvlArchive("not_found.lvl"), Oddlib::Exception);
}
TEST(LvlArchive, DISABLED_Integration)
{
// Load AE lvl
Oddlib::LvlArchive lvl("MI.LVL");
const auto file = lvl.FileByName("FLYSLIG.BND");
ASSERT_NE(nullptr, file);
const auto chunk = file->ChunkById(450);
ASSERT_NE(nullptr, chunk);
ASSERT_EQ(450, chunk->Id());
const auto data = chunk->ReadData();
ASSERT_EQ(false, data.empty());
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <silicium/error_or.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/filesystem/operations.hpp>
namespace buildserver
{
Si::error_or<bool> file_exists(boost::filesystem::path const &candidate)
{
boost::system::error_code ec;
boost::filesystem::file_status status = boost::filesystem::status(candidate, ec);
if (status.type() == boost::filesystem::file_not_found)
{
return false;
}
if (ec)
{
return ec;
}
return true;
}
Si::error_or<boost::optional<boost::filesystem::path>> find_file_in_directories(
boost::filesystem::path const &filename,
std::vector<boost::filesystem::path> const &directories)
{
for (auto const &directory : directories)
{
auto candidate = directory / filename;
auto result = file_exists(candidate);
if (result.is_error())
{
return result.error();
}
if (result.get())
{
return std::move(candidate);
}
}
return boost::none;
}
Si::error_or<boost::optional<boost::filesystem::path>> find_executable_unix(
boost::filesystem::path const &filename,
std::vector<boost::filesystem::path> additional_directories)
{
additional_directories.emplace_back("/bin");
additional_directories.emplace_back("/usr/bin");
additional_directories.emplace_back("/usr/local/bin");
return find_file_in_directories(filename, additional_directories);
}
struct gcc_location
{
boost::filesystem::path gcc, gxx;
};
Si::error_or<boost::optional<gcc_location>> find_gcc_unix()
{
auto gcc = find_executable_unix("gcc", {});
if (gcc.is_error())
{
return gcc.error();
}
if (!gcc.get())
{
return boost::none;
}
auto gxx = find_file_in_directories("g++", {gcc.get()->parent_path()});
return Si::map(std::move(gxx), [&gcc](boost::optional<boost::filesystem::path> gxx_path) -> boost::optional<gcc_location>
{
if (gxx_path)
{
gcc_location result;
result.gcc = std::move(*gcc.get());
result.gxx = std::move(*gxx_path);
return result;
}
else
{
return boost::none;
}
});
}
}
BOOST_AUTO_TEST_CASE(find_executable_unix_test)
{
BOOST_CHECK_EQUAL(boost::none, buildserver::find_executable_unix("does-not-exist", {}));
#ifndef _WIN32
BOOST_CHECK_EQUAL(boost::filesystem::path("/bin/sh"), buildserver::find_executable_unix("sh", {}));
BOOST_CHECK_EQUAL(boost::none, buildserver::find_file_in_directories("sh", {}));
auto gnuc = buildserver::find_gcc_unix();
BOOST_REQUIRE(gnuc.get());
BOOST_CHECK_EQUAL("/usr/bin/gcc", gnuc.get()->gcc);
BOOST_CHECK_EQUAL("/usr/bin/g++", gnuc.get()->gxx);
#endif
}
<commit_msg>implement the CMake driver for Linux in C++<commit_after>#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <silicium/error_or.hpp>
#include <silicium/override.hpp>
#include <silicium/process.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/unordered_map.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread/thread.hpp>
namespace buildserver
{
Si::error_or<bool> file_exists(boost::filesystem::path const &candidate)
{
boost::system::error_code ec;
boost::filesystem::file_status status = boost::filesystem::status(candidate, ec);
if (status.type() == boost::filesystem::file_not_found)
{
return false;
}
if (ec)
{
return ec;
}
return true;
}
Si::error_or<boost::optional<boost::filesystem::path>> find_file_in_directories(
boost::filesystem::path const &filename,
std::vector<boost::filesystem::path> const &directories)
{
for (auto const &directory : directories)
{
auto candidate = directory / filename;
auto result = file_exists(candidate);
if (result.is_error())
{
return result.error();
}
if (result.get())
{
return std::move(candidate);
}
}
return boost::none;
}
Si::error_or<boost::optional<boost::filesystem::path>> find_executable_unix(
boost::filesystem::path const &filename,
std::vector<boost::filesystem::path> additional_directories)
{
additional_directories.emplace_back("/bin");
additional_directories.emplace_back("/usr/bin");
additional_directories.emplace_back("/usr/local/bin");
return find_file_in_directories(filename, additional_directories);
}
struct gcc_location
{
boost::filesystem::path gcc, gxx;
};
Si::error_or<boost::optional<gcc_location>> find_gcc_unix()
{
auto gcc = find_executable_unix("gcc", {});
if (gcc.is_error())
{
return gcc.error();
}
if (!gcc.get())
{
return boost::none;
}
auto gxx = find_file_in_directories("g++", {gcc.get()->parent_path()});
return Si::map(std::move(gxx), [&gcc](boost::optional<boost::filesystem::path> gxx_path) -> boost::optional<gcc_location>
{
if (gxx_path)
{
gcc_location result;
result.gcc = std::move(*gcc.get());
result.gxx = std::move(*gxx_path);
return result;
}
else
{
return boost::none;
}
});
}
Si::error_or<boost::optional<boost::filesystem::path>> find_cmake_unix()
{
return find_executable_unix("cmake", {});
}
struct cmake
{
virtual ~cmake()
{
}
virtual boost::system::error_code generate(
boost::filesystem::path const &source,
boost::filesystem::path const &build,
boost::unordered_map<std::string, std::string> const &definitions
) const = 0;
virtual boost::system::error_code build(
boost::filesystem::path const &build,
unsigned cpu_parallelism
) const = 0;
};
struct cmake_exe : cmake
{
explicit cmake_exe(
boost::filesystem::path exe)
: m_exe(std::move(exe))
{
}
virtual boost::system::error_code generate(
boost::filesystem::path const &source,
boost::filesystem::path const &build,
boost::unordered_map<std::string, std::string> const &definitions
) const SILICIUM_OVERRIDE
{
std::vector<std::string> arguments;
arguments.emplace_back(source.string());
for (auto const &definition : definitions)
{
//TODO: is this properly encoded in all cases? I guess not
auto encoded = "-D" + definition.first + "=" + definition.second;
arguments.emplace_back(std::move(encoded));
}
Si::process_parameters parameters;
parameters.executable = m_exe;
parameters.current_path = build;
parameters.arguments = std::move(arguments);
int const rc = Si::run_process(parameters);
if (rc != 0)
{
throw std::runtime_error("Unexpected CMake return code");
}
return {};
}
virtual boost::system::error_code build(
boost::filesystem::path const &build,
unsigned cpu_parallelism
) const SILICIUM_OVERRIDE
{
//assuming make..
std::vector<std::string> arguments{"--build", ".", "--", "-j"};
arguments.emplace_back(boost::lexical_cast<std::string>(cpu_parallelism));
Si::process_parameters parameters;
parameters.executable = m_exe;
parameters.current_path = build;
parameters.arguments = std::move(arguments);
int const rc = Si::run_process(parameters);
if (rc != 0)
{
throw std::runtime_error("Unexpected CMake return code");
}
return {};
}
private:
boost::filesystem::path m_exe;
};
}
BOOST_AUTO_TEST_CASE(find_executable_unix_test)
{
BOOST_CHECK_EQUAL(boost::none, buildserver::find_executable_unix("does-not-exist", {}));
#ifndef _WIN32
BOOST_CHECK_EQUAL(boost::filesystem::path("/bin/sh"), buildserver::find_executable_unix("sh", {}));
BOOST_CHECK_EQUAL(boost::none, buildserver::find_file_in_directories("sh", {}));
auto gnuc = buildserver::find_gcc_unix();
BOOST_REQUIRE(gnuc.get());
BOOST_CHECK_EQUAL("/usr/bin/gcc", gnuc.get()->gcc);
BOOST_CHECK_EQUAL("/usr/bin/g++", gnuc.get()->gxx);
#endif
}
BOOST_AUTO_TEST_CASE(cmake_exe_test)
{
auto cmake = buildserver::find_cmake_unix().get();
BOOST_REQUIRE(cmake);
buildserver::cmake_exe const cmake_driver(*cmake);
boost::filesystem::path const build_path = "/tmp/buildtest123456";
boost::filesystem::remove_all(build_path);
boost::filesystem::create_directories(build_path);
boost::filesystem::path const dev_path = boost::filesystem::path(__FILE__).parent_path().parent_path().parent_path();
cmake_driver.generate(dev_path / "buildserver", build_path, {{"SILICIUM_INCLUDE_DIR", (dev_path / "silicium").string()}});
cmake_driver.build(build_path, boost::thread::hardware_concurrency());
}
<|endoftext|> |
<commit_before>#include "msg_pack.h"
#include "mpi_util.h"
//#include <exception>
//#include "log.h" // temporary include
namespace multiverso
{
//-- area of static member definition ------------------------------------/
int MPIUtil::mpi_size_ = 0;
int MPIUtil::mpi_rank_ = 0;
std::queue<std::shared_ptr<MsgPack>> MPIUtil::send_queue_;
#if defined (_MPI_VERSION_)
char MPIUtil::recv_buffer_[kMPIBufferSize];
MPI_Request MPIUtil::recv_request_ = MPI_REQUEST_NULL;
char MPIUtil::send_buffer_[kMPIBufferSize];
MPI_Request MPIUtil::send_request_ = MPI_REQUEST_NULL;
#endif
//-- end of static member definition -------------------------------------/
#if defined (_MPI_VERSION_)
// Initializes MPI environment
void MPIUtil::Init(int *argc, char **argv[])
{
int flag = 0;
MPI_Initialized(&flag); // test if MPI has been initialized
if (!flag) // if MPI not started, start it
{
MPI_Init_thread(argc, argv, MPI_THREAD_SERIALIZED, &flag);
}
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size_);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank_);
}
// Finalizes MPI environment
void MPIUtil::Close()
{
MPI_Finalize();
}
std::shared_ptr<MsgPack> MPIUtil::ProbeAndRecv()
{
int flag;
MPI_Status status;
// test if there is new message comes
MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
if (flag) // MPI message arrived
{
MPI_Recv(recv_buffer_, kMPIBufferSize, MPI_BYTE, status.MPI_SOURCE,
status.MPI_TAG, MPI_COMM_WORLD, &status);
std::shared_ptr<MsgPack> request(
new MsgPack(recv_buffer_, status.count));
return request;
}
return nullptr;
}
//// Try to receive messages with MPI non-blocking receiving method.
//std::shared_ptr<MsgPack> MPIUtil::MPIProbe()
//{
// try{
// int flag;
// MPI_Status status;
// // if there is message being received
// if (recv_request_ != MPI_REQUEST_NULL)
// {
// // test if the receiving completed
// MPI_Test(&recv_request_, &flag, &status);
// if (flag) // recv completed, deserialize the data into ZMQ messages
// {
// recv_request_ = MPI_REQUEST_NULL;
// std::shared_ptr<MsgPack> request(
// new MsgPack(recv_buffer_, status.count));
// return request;
// }
// else // recv not completed yet
// {
// return nullptr;
// }
// }
// // test if there is new message comes
// MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
// if (flag) // MPI message arrived
// {
// //MPI_Irecv(recv_buffer_, kMPIBufferSize, MPI_BYTE, status.MPI_SOURCE,
// // status.MPI_TAG, MPI_COMM_WORLD, &recv_request_);
// MPI_Recv(recv_buffer_, kMPIBufferSize, MPI_BYTE, status.MPI_SOURCE,
// status.MPI_TAG, MPI_COMM_WORLD, &status);
// std::shared_ptr<MsgPack> request(new MsgPack(recv_buffer_, status.count));
// return request;
// }
// return nullptr;
// }
// catch (std::exception e)
// {
// Log::Error("Rank=%d Probe\n", mpi_rank_);
// throw e;
// }
//}
// Send messages with MPI non-blocking sending method. Actually, it pushes
// the message into the queue (if not null), test if last sending has
// been completed, and send a new one in the queue if so.
void MPIUtil::Send(std::shared_ptr<MsgPack> msg_pack)
{
static int tag = 0;
// push the send message into the send queue
if (msg_pack.get() != nullptr)
{
send_queue_.push(msg_pack);
}
// test if the last send has been completed, return immediately if not
if (send_request_ != MPI_REQUEST_NULL)
{
MPI_Status status;
int flag;
MPI_Test(&send_request_, &flag, &status);
if (flag) // send completed
{
send_request_ = MPI_REQUEST_NULL;
}
else
{
return;
}
}
// if there is message in the send queue, send it
if (!send_queue_.empty())
{
MsgType msg_type;
MsgArrow msg_arrow;
int src, dst, size;
std::shared_ptr<MsgPack> msg_send = send_queue_.front();
send_queue_.pop();
msg_send->GetHeaderInfo(&msg_type, &msg_arrow, &src, &dst);
// serialize the message into MPI send buffer
msg_send->Serialize(send_buffer_, &size);
MPI_Isend(send_buffer_, size, MPI_BYTE, dst, tag++, MPI_COMM_WORLD,
&send_request_);
}
}
#endif
}
<commit_msg>fix bug for an irregular usage of MPI<commit_after>#include "msg_pack.h"
#include "mpi_util.h"
//#include <exception>
//#include "log.h" // temporary include
namespace multiverso
{
//-- area of static member definition ------------------------------------/
int MPIUtil::mpi_size_ = 0;
int MPIUtil::mpi_rank_ = 0;
std::queue<std::shared_ptr<MsgPack>> MPIUtil::send_queue_;
#if defined (_MPI_VERSION_)
char MPIUtil::recv_buffer_[kMPIBufferSize];
MPI_Request MPIUtil::recv_request_ = MPI_REQUEST_NULL;
char MPIUtil::send_buffer_[kMPIBufferSize];
MPI_Request MPIUtil::send_request_ = MPI_REQUEST_NULL;
#endif
//-- end of static member definition -------------------------------------/
#if defined (_MPI_VERSION_)
// Initializes MPI environment
void MPIUtil::Init(int *argc, char **argv[])
{
int flag = 0;
MPI_Initialized(&flag); // test if MPI has been initialized
if (!flag) // if MPI not started, start it
{
MPI_Init_thread(argc, argv, MPI_THREAD_SERIALIZED, &flag);
}
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size_);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank_);
}
// Finalizes MPI environment
void MPIUtil::Close()
{
MPI_Finalize();
}
std::shared_ptr<MsgPack> MPIUtil::ProbeAndRecv()
{
int flag;
int count = 0;
MPI_Status status;
// test if there is new message comes
MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
if (flag) // MPI message arrived
{
MPI_Recv(recv_buffer_, kMPIBufferSize, MPI_BYTE, status.MPI_SOURCE,
status.MPI_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_BYTE, &count);
std::shared_ptr<MsgPack> request(
new MsgPack(recv_buffer_, count));
return request;
}
return nullptr;
}
//// Try to receive messages with MPI non-blocking receiving method.
//std::shared_ptr<MsgPack> MPIUtil::MPIProbe()
//{
// try{
// int flag;
// int count = 0;
// MPI_Status status;
// // if there is message being received
// if (recv_request_ != MPI_REQUEST_NULL)
// {
// // test if the receiving completed
// MPI_Test(&recv_request_, &flag, &status);
// if (flag) // recv completed, deserialize the data into ZMQ messages
// {
// recv_request_ = MPI_REQUEST_NULL;
//MPI_Get_count(&status, MPI_BYTE, &count);
// std::shared_ptr<MsgPack> request(
// new MsgPack(recv_buffer_, count));
// return request;
// }
// else // recv not completed yet
// {
// return nullptr;
// }
// }
// // test if there is new message comes
// MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
// if (flag) // MPI message arrived
// {
// //MPI_Irecv(recv_buffer_, kMPIBufferSize, MPI_BYTE, status.MPI_SOURCE,
// // status.MPI_TAG, MPI_COMM_WORLD, &recv_request_);
// MPI_Recv(recv_buffer_, kMPIBufferSize, MPI_BYTE, status.MPI_SOURCE,
// status.MPI_TAG, MPI_COMM_WORLD, &status);
// MPI_Get_count(&status, MPI_BYTE, &count);
// std::shared_ptr<MsgPack> request(new MsgPack(recv_buffer_, count));
// return request;
// }
// return nullptr;
// }
// catch (std::exception e)
// {
// Log::Error("Rank=%d Probe\n", mpi_rank_);
// throw e;
// }
//}
// Send messages with MPI non-blocking sending method. Actually, it pushes
// the message into the queue (if not null), test if last sending has
// been completed, and send a new one in the queue if so.
void MPIUtil::Send(std::shared_ptr<MsgPack> msg_pack)
{
static int tag = 0;
// push the send message into the send queue
if (msg_pack.get() != nullptr)
{
send_queue_.push(msg_pack);
}
// test if the last send has been completed, return immediately if not
if (send_request_ != MPI_REQUEST_NULL)
{
MPI_Status status;
int flag;
MPI_Test(&send_request_, &flag, &status);
if (flag) // send completed
{
send_request_ = MPI_REQUEST_NULL;
}
else
{
return;
}
}
// if there is message in the send queue, send it
if (!send_queue_.empty())
{
MsgType msg_type;
MsgArrow msg_arrow;
int src, dst, size;
std::shared_ptr<MsgPack> msg_send = send_queue_.front();
send_queue_.pop();
msg_send->GetHeaderInfo(&msg_type, &msg_arrow, &src, &dst);
// serialize the message into MPI send buffer
msg_send->Serialize(send_buffer_, &size);
MPI_Isend(send_buffer_, size, MPI_BYTE, dst, tag++, MPI_COMM_WORLD,
&send_request_);
}
}
#endif
}
<|endoftext|> |
<commit_before>/*
* waterspout
*
* - simd abstraction library for audio/image manipulation -
*
* Copyright (c) 2013 Lucio Asnaghi
*
*
* The MIT License (MIT)
*
* 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 <waterspout.h>
#include <ctime>
#include <stdexcept>
#include <iostream>
#include <iomanip>
using namespace waterspout;
//==============================================================================
//------------------------------------------------------------------------------
/**
* The timer class to measure elapsed time and benchmarking
*/
class timer
{
public:
timer()
{
restart();
}
virtual ~timer()
{
}
void restart()
{
stopped_ = false;
clock_start_ = time_now();
cpu_start_ = clock();
}
virtual void stop()
{
stopped_ = true;
cpu_end_ = clock();
clock_end_ = time_now();
}
double cpu_elapsed()
{
// return elapsed CPU time in ms
if (! stopped_)
{
stop();
}
return ((double)(cpu_end_ - cpu_start_)) / CLOCKS_PER_SEC * 1000.0;
}
double clock_elapsed()
{
// return elapsed wall clock time in ms
if (! stopped_)
{
stop();
}
return (clock_end_ - clock_start_) * 1000.0;
}
forcedinline double time_now()
{
#if defined(WATERSPOUT_COMPILER_MSVC)
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return double(t.QuadPart) / double(f.QuadPart);
#else
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec * 1e-6;
#endif
}
protected:
double clock_start_, clock_end_;
clock_t cpu_start_, cpu_end_;
bool stopped_;
};
//------------------------------------------------------------------------------
namespace {
//------------------------------------------------------------------------------
template<typename T>
void check_buffer_is_value(T* buffer, uint32 size, T value)
{
for (uint32 i = 0; i < size; ++i)
{
if (buffer[i] != value)
{
std::clog << "Errors at index "
<< i << " (" << buffer[i] << "!=" << value << ")" << std::endl;
throw std::runtime_error("Buffer is not a specific value !");
}
}
}
template<typename T>
void check_buffer_is_zero(T* buffer, uint32 size)
{
check_buffer_is_value(buffer, size, static_cast<T>(0));
}
template<typename T>
void check_buffers_are_equal(T* a, T* b, uint32 size)
{
for (uint32 i = 0; i < size; ++i)
{
if (a[i] != b[i])
{
std::clog << "Errors at index "
<< i << " (" << a[i] << "!=" << b[i] << ")" << std::endl;
throw std::runtime_error("Buffers are not equal !");
}
}
}
//------------------------------------------------------------------------------
#define run_typed_test_by_flag(datatype) \
{ \
datatype## _buffer src_buffer_a1(s); \
datatype## _buffer src_buffer_a2(s); \
datatype## _buffer src_buffer_b1(s); \
datatype## _buffer src_buffer_b2(s); \
datatype## _buffer dst_buffer_1(s); \
datatype## _buffer dst_buffer_2(s); \
\
std::clog << " - clear_buffer_" << #datatype << std::endl; \
simd->clear_buffer_ ##datatype (src_buffer_a1.data(), s); \
fpu->clear_buffer_ ##datatype (src_buffer_a2.data(), s); \
check_buffers_are_equal(src_buffer_a1.data(), src_buffer_a2.data(), s); \
\
std::clog << " - set_buffer_" << #datatype << std::endl; \
simd->set_buffer_ ##datatype (src_buffer_a1.data(), s, (datatype)1); \
fpu->set_buffer_ ##datatype (src_buffer_a2.data(), s, (datatype)1); \
simd->set_buffer_ ##datatype (src_buffer_b1.data(), s, (datatype)500); \
fpu->set_buffer_ ##datatype (src_buffer_b2.data(), s, (datatype)500); \
check_buffers_are_equal(src_buffer_a1.data(), src_buffer_a2.data(), s); \
check_buffers_are_equal(src_buffer_b1.data(), src_buffer_b2.data(), s); \
\
std::clog << " - scale_buffer_" << #datatype << std::endl; \
simd->scale_buffer_ ##datatype (src_buffer_a1.data(), s, 2.0f); \
fpu->scale_buffer_ ##datatype (src_buffer_a2.data(), s, 2.0f); \
check_buffers_are_equal(src_buffer_a1.data(), src_buffer_a2.data(), s); \
\
std::clog << " - copy_buffer_" << #datatype << std::endl; \
simd->copy_buffer_ ##datatype (src_buffer_a1.data(), dst_buffer_1.data(), s); \
fpu->copy_buffer_ ##datatype (src_buffer_a2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << " - add_buffers_" << #datatype << std::endl; \
simd->add_buffers_ ##datatype (src_buffer_a1.data(), src_buffer_b1.data(), dst_buffer_1.data(), s); \
fpu->add_buffers_ ##datatype (src_buffer_a2.data(), src_buffer_b2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << " - subtract_buffers_" << #datatype << std::endl; \
simd->subtract_buffers_ ##datatype (src_buffer_a1.data(), src_buffer_b1.data(), dst_buffer_1.data(), s); \
fpu->subtract_buffers_ ##datatype (src_buffer_a2.data(), src_buffer_b2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << " - multiply_buffers_" << #datatype << std::endl; \
simd->multiply_buffers_ ##datatype (src_buffer_a1.data(), src_buffer_b1.data(), dst_buffer_1.data(), s); \
fpu->multiply_buffers_ ##datatype (src_buffer_a2.data(), src_buffer_b2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << " - divide_buffers_" << #datatype << std::endl; \
simd->set_buffer_ ##datatype (src_buffer_b1.data(), s, (datatype)2); \
fpu->set_buffer_ ##datatype (src_buffer_b2.data(), s, (datatype)2); \
simd->divide_buffers_ ##datatype (src_buffer_a1.data(), src_buffer_b1.data(), dst_buffer_1.data(), s); \
fpu->divide_buffers_ ##datatype (src_buffer_a2.data(), src_buffer_b2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << std::endl; \
}
#define run_all_tests_by_flag(flags) \
{ \
const uint32 s = 8192; \
math fpu(FORCE_FPU); \
math simd(flags); \
std::clog << simd.name() << ": " << std::endl; \
run_typed_test_by_flag(int8); \
run_typed_test_by_flag(uint8); \
run_typed_test_by_flag(int16); \
run_typed_test_by_flag(uint16); \
run_typed_test_by_flag(int32); \
run_typed_test_by_flag(uint32); \
run_typed_test_by_flag(int64); \
run_typed_test_by_flag(uint64); \
run_typed_test_by_flag(float); \
run_typed_test_by_flag(double); \
}
#define run_all_tests \
run_all_tests_by_flag(FORCE_MMX); \
run_all_tests_by_flag(FORCE_SSE); \
run_all_tests_by_flag(FORCE_SSE2); \
//run_all_tests_by_flag(FORCE_SSE3)
//run_all_tests_by_flag(FORCE_SSSE3)
//run_all_tests_by_flag(FORCE_SSE41)
//run_all_tests_by_flag(FORCE_SSE42)
//run_all_tests_by_flag(FORCE_AVX)
} // end namespace
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
unused(argc);
unused(argv);
run_all_tests
return 0;
}
<commit_msg>- enabled all tests (even if some classes are not implemented)<commit_after>/*
* waterspout
*
* - simd abstraction library for audio/image manipulation -
*
* Copyright (c) 2013 Lucio Asnaghi
*
*
* The MIT License (MIT)
*
* 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 <waterspout.h>
#include <ctime>
#include <stdexcept>
#include <iostream>
#include <iomanip>
using namespace waterspout;
//==============================================================================
//------------------------------------------------------------------------------
/**
* The timer class to measure elapsed time and benchmarking
*/
class timer
{
public:
timer()
{
restart();
}
virtual ~timer()
{
}
void restart()
{
stopped_ = false;
clock_start_ = time_now();
cpu_start_ = clock();
}
virtual void stop()
{
stopped_ = true;
cpu_end_ = clock();
clock_end_ = time_now();
}
double cpu_elapsed()
{
// return elapsed CPU time in ms
if (! stopped_)
{
stop();
}
return ((double)(cpu_end_ - cpu_start_)) / CLOCKS_PER_SEC * 1000.0;
}
double clock_elapsed()
{
// return elapsed wall clock time in ms
if (! stopped_)
{
stop();
}
return (clock_end_ - clock_start_) * 1000.0;
}
forcedinline double time_now()
{
#if defined(WATERSPOUT_COMPILER_MSVC)
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return double(t.QuadPart) / double(f.QuadPart);
#else
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec * 1e-6;
#endif
}
protected:
double clock_start_, clock_end_;
clock_t cpu_start_, cpu_end_;
bool stopped_;
};
//------------------------------------------------------------------------------
namespace {
//------------------------------------------------------------------------------
template<typename T>
void check_buffer_is_value(T* buffer, uint32 size, T value)
{
for (uint32 i = 0; i < size; ++i)
{
if (buffer[i] != value)
{
std::clog << "Errors at index "
<< i << " (" << buffer[i] << "!=" << value << ")" << std::endl;
throw std::runtime_error("Buffer is not a specific value !");
}
}
}
template<typename T>
void check_buffer_is_zero(T* buffer, uint32 size)
{
check_buffer_is_value(buffer, size, static_cast<T>(0));
}
template<typename T>
void check_buffers_are_equal(T* a, T* b, uint32 size)
{
for (uint32 i = 0; i < size; ++i)
{
if (a[i] != b[i])
{
std::clog << "Errors at index "
<< i << " (" << a[i] << "!=" << b[i] << ")" << std::endl;
throw std::runtime_error("Buffers are not equal !");
}
}
}
//------------------------------------------------------------------------------
#define run_typed_test_by_flag(datatype) \
{ \
datatype## _buffer src_buffer_a1(s); \
datatype## _buffer src_buffer_a2(s); \
datatype## _buffer src_buffer_b1(s); \
datatype## _buffer src_buffer_b2(s); \
datatype## _buffer dst_buffer_1(s); \
datatype## _buffer dst_buffer_2(s); \
\
std::clog << " - clear_buffer_" << #datatype << std::endl; \
simd->clear_buffer_ ##datatype (src_buffer_a1.data(), s); \
fpu->clear_buffer_ ##datatype (src_buffer_a2.data(), s); \
check_buffers_are_equal(src_buffer_a1.data(), src_buffer_a2.data(), s); \
\
std::clog << " - set_buffer_" << #datatype << std::endl; \
simd->set_buffer_ ##datatype (src_buffer_a1.data(), s, (datatype)1); \
fpu->set_buffer_ ##datatype (src_buffer_a2.data(), s, (datatype)1); \
simd->set_buffer_ ##datatype (src_buffer_b1.data(), s, (datatype)500); \
fpu->set_buffer_ ##datatype (src_buffer_b2.data(), s, (datatype)500); \
check_buffers_are_equal(src_buffer_a1.data(), src_buffer_a2.data(), s); \
check_buffers_are_equal(src_buffer_b1.data(), src_buffer_b2.data(), s); \
\
std::clog << " - scale_buffer_" << #datatype << std::endl; \
simd->scale_buffer_ ##datatype (src_buffer_a1.data(), s, 2.0f); \
fpu->scale_buffer_ ##datatype (src_buffer_a2.data(), s, 2.0f); \
check_buffers_are_equal(src_buffer_a1.data(), src_buffer_a2.data(), s); \
\
std::clog << " - copy_buffer_" << #datatype << std::endl; \
simd->copy_buffer_ ##datatype (src_buffer_a1.data(), dst_buffer_1.data(), s); \
fpu->copy_buffer_ ##datatype (src_buffer_a2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << " - add_buffers_" << #datatype << std::endl; \
simd->add_buffers_ ##datatype (src_buffer_a1.data(), src_buffer_b1.data(), dst_buffer_1.data(), s); \
fpu->add_buffers_ ##datatype (src_buffer_a2.data(), src_buffer_b2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << " - subtract_buffers_" << #datatype << std::endl; \
simd->subtract_buffers_ ##datatype (src_buffer_a1.data(), src_buffer_b1.data(), dst_buffer_1.data(), s); \
fpu->subtract_buffers_ ##datatype (src_buffer_a2.data(), src_buffer_b2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << " - multiply_buffers_" << #datatype << std::endl; \
simd->multiply_buffers_ ##datatype (src_buffer_a1.data(), src_buffer_b1.data(), dst_buffer_1.data(), s); \
fpu->multiply_buffers_ ##datatype (src_buffer_a2.data(), src_buffer_b2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << " - divide_buffers_" << #datatype << std::endl; \
simd->set_buffer_ ##datatype (src_buffer_b1.data(), s, (datatype)2); \
fpu->set_buffer_ ##datatype (src_buffer_b2.data(), s, (datatype)2); \
simd->divide_buffers_ ##datatype (src_buffer_a1.data(), src_buffer_b1.data(), dst_buffer_1.data(), s); \
fpu->divide_buffers_ ##datatype (src_buffer_a2.data(), src_buffer_b2.data(), dst_buffer_2.data(), s); \
check_buffers_are_equal(dst_buffer_1.data(), dst_buffer_2.data(), s); \
\
std::clog << std::endl; \
}
#define run_all_tests_by_flag(flags) \
{ \
const uint32 s = 8192; \
math fpu(FORCE_FPU); \
math simd(flags); \
std::clog << simd.name() << ": " << std::endl; \
run_typed_test_by_flag(int8); \
run_typed_test_by_flag(uint8); \
run_typed_test_by_flag(int16); \
run_typed_test_by_flag(uint16); \
run_typed_test_by_flag(int32); \
run_typed_test_by_flag(uint32); \
run_typed_test_by_flag(int64); \
run_typed_test_by_flag(uint64); \
run_typed_test_by_flag(float); \
run_typed_test_by_flag(double); \
}
#define run_all_tests \
run_all_tests_by_flag(FORCE_MMX); \
run_all_tests_by_flag(FORCE_SSE); \
run_all_tests_by_flag(FORCE_SSE2); \
run_all_tests_by_flag(FORCE_SSE3); \
run_all_tests_by_flag(FORCE_SSSE3); \
run_all_tests_by_flag(FORCE_SSE41); \
run_all_tests_by_flag(FORCE_SSE42); \
run_all_tests_by_flag(FORCE_AVX);
} // end namespace
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
unused(argc);
unused(argv);
run_all_tests
return 0;
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2015, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file SimpleStack.cxx
*
* A complete OpenLCB stack for use in straightforward OpenLCB nodes.
*
* @author Balazs Racz
* @date 18 Mar 2015
*/
#if defined(__linux__) || defined(__MACH__)
#include <termios.h> /* tc* functions */
#endif
#include "nmranet/SimpleStack.hxx"
#include "nmranet/SimpleNodeInfo.hxx"
namespace nmranet
{
SimpleCanStack::SimpleCanStack(const nmranet::NodeID node_id)
: node_(&ifCan_, node_id)
{
AddAliasAllocator(node_id, &ifCan_);
}
void SimpleCanStack::start_stack()
{
// Opens the eeprom file and sends configuration update commands to all
// listeners.
configUpdateFlow_.init(CONFIG_FILENAME);
// Bootstraps the alias allocation process.
ifCan_.alias_allocator()->send(ifCan_.alias_allocator()->alloc());
// Adds memory spaces.
if (config_enable_all_memory_space() == CONSTANT_TRUE)
{
auto *space = new ReadOnlyMemoryBlock(nullptr, 0xFFFFFFFFUL);
memoryConfigHandler_.registry()->insert(
nullptr, MemoryConfigDefs::SPACE_ALL_MEMORY, space);
additionalComponents_.emplace_back(space);
}
{
auto *space = new ReadOnlyMemoryBlock(
reinterpret_cast<const uint8_t *>(&SNIP_STATIC_DATA),
sizeof(SNIP_STATIC_DATA));
memoryConfigHandler_.registry()->insert(
&node_, MemoryConfigDefs::SPACE_ACDI_SYS, space);
additionalComponents_.emplace_back(space);
}
{
auto *space = new FileMemorySpace(
SNIP_DYNAMIC_FILENAME, sizeof(SimpleNodeDynamicValues));
memoryConfigHandler_.registry()->insert(
&node_, MemoryConfigDefs::SPACE_ACDI_USR, space);
additionalComponents_.emplace_back(space);
}
{
auto *space = new ReadOnlyMemoryBlock(
reinterpret_cast<const uint8_t *>(&CDI_DATA), strlen(CDI_DATA) + 1);
memoryConfigHandler_.registry()->insert(
&node_, MemoryConfigDefs::SPACE_CDI, space);
additionalComponents_.emplace_back(space);
}
if (CONFIG_FILENAME != nullptr)
{
auto *space = new FileMemorySpace(CONFIG_FILENAME, CONFIG_FILE_SIZE);
memory_config_handler()->registry()->insert(
&node_, nmranet::MemoryConfigDefs::SPACE_CONFIG, space);
additionalComponents_.emplace_back(space);
}
}
void SimpleCanStack::add_gridconnect_port(const char *path, Notifiable *on_exit)
{
int fd = ::open(path, O_RDWR);
HASSERT(fd >= 0);
LOG(INFO, "Adding device %s as fd %d", path, fd);
create_gc_port_for_can_hub(&canHub0_, fd, on_exit);
}
#if defined(__linux__) || defined(__MACH__)
void SimpleCanStack::add_gridconnect_tty(
const char *device, Notifiable *on_exit)
{
int fd = ::open(device, O_RDWR);
HASSERT(fd >= 0);
LOG(INFO, "Adding device %s as fd %d", device, fd);
create_gc_port_for_can_hub(&canHub0_, fd, on_exit);
HASSERT(!tcflush(fd, TCIOFLUSH));
struct termios settings;
HASSERT(!tcgetattr(fd, &settings));
cfmakeraw(&settings);
HASSERT(!tcsetattr(fd, TCSANOW, &settings));
}
#endif
extern Pool *const __attribute__((__weak__)) g_incoming_datagram_allocator =
init_main_buffer_pool();
} // namespace nmranet
<commit_msg>Adds baud rate setting for the simplecanstack's tty device driver.<commit_after>/** \copyright
* Copyright (c) 2015, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file SimpleStack.cxx
*
* A complete OpenLCB stack for use in straightforward OpenLCB nodes.
*
* @author Balazs Racz
* @date 18 Mar 2015
*/
#if defined(__linux__) || defined(__MACH__)
#include <termios.h> /* tc* functions */
#endif
#include "nmranet/SimpleStack.hxx"
#include "nmranet/SimpleNodeInfo.hxx"
namespace nmranet
{
SimpleCanStack::SimpleCanStack(const nmranet::NodeID node_id)
: node_(&ifCan_, node_id)
{
AddAliasAllocator(node_id, &ifCan_);
}
void SimpleCanStack::start_stack()
{
// Opens the eeprom file and sends configuration update commands to all
// listeners.
configUpdateFlow_.init(CONFIG_FILENAME);
// Bootstraps the alias allocation process.
ifCan_.alias_allocator()->send(ifCan_.alias_allocator()->alloc());
// Adds memory spaces.
if (config_enable_all_memory_space() == CONSTANT_TRUE)
{
auto *space = new ReadOnlyMemoryBlock(nullptr, 0xFFFFFFFFUL);
memoryConfigHandler_.registry()->insert(
nullptr, MemoryConfigDefs::SPACE_ALL_MEMORY, space);
additionalComponents_.emplace_back(space);
}
{
auto *space = new ReadOnlyMemoryBlock(
reinterpret_cast<const uint8_t *>(&SNIP_STATIC_DATA),
sizeof(SNIP_STATIC_DATA));
memoryConfigHandler_.registry()->insert(
&node_, MemoryConfigDefs::SPACE_ACDI_SYS, space);
additionalComponents_.emplace_back(space);
}
{
auto *space = new FileMemorySpace(
SNIP_DYNAMIC_FILENAME, sizeof(SimpleNodeDynamicValues));
memoryConfigHandler_.registry()->insert(
&node_, MemoryConfigDefs::SPACE_ACDI_USR, space);
additionalComponents_.emplace_back(space);
}
{
auto *space = new ReadOnlyMemoryBlock(
reinterpret_cast<const uint8_t *>(&CDI_DATA), strlen(CDI_DATA) + 1);
memoryConfigHandler_.registry()->insert(
&node_, MemoryConfigDefs::SPACE_CDI, space);
additionalComponents_.emplace_back(space);
}
if (CONFIG_FILENAME != nullptr)
{
auto *space = new FileMemorySpace(CONFIG_FILENAME, CONFIG_FILE_SIZE);
memory_config_handler()->registry()->insert(
&node_, nmranet::MemoryConfigDefs::SPACE_CONFIG, space);
additionalComponents_.emplace_back(space);
}
}
void SimpleCanStack::add_gridconnect_port(const char *path, Notifiable *on_exit)
{
int fd = ::open(path, O_RDWR);
HASSERT(fd >= 0);
LOG(INFO, "Adding device %s as fd %d", path, fd);
create_gc_port_for_can_hub(&canHub0_, fd, on_exit);
}
#if defined(__linux__) || defined(__MACH__)
void SimpleCanStack::add_gridconnect_tty(
const char *device, Notifiable *on_exit)
{
int fd = ::open(device, O_RDWR);
HASSERT(fd >= 0);
LOG(INFO, "Adding device %s as fd %d", device, fd);
create_gc_port_for_can_hub(&canHub0_, fd, on_exit);
HASSERT(!tcflush(fd, TCIOFLUSH));
struct termios settings;
HASSERT(!tcgetattr(fd, &settings));
cfmakeraw(&settings);
cfsetspeed(&settings, B115200);
HASSERT(!tcsetattr(fd, TCSANOW, &settings));
}
#endif
extern Pool *const __attribute__((__weak__)) g_incoming_datagram_allocator =
init_main_buffer_pool();
} // namespace nmranet
<|endoftext|> |
<commit_before>/*=============================================================================
Copyright (c) 2016-2017 Joel de Guzman
Distributed under the MIT License (https://opensource.org/licenses/MIT)
=============================================================================*/
#include <boost/detail/lightweight_test.hpp>
#include <photon/support/json.hpp>
#include <boost/fusion/include/equal_to.hpp>
namespace json = photon::json;
namespace x3 = boost::spirit::x3;
namespace fusion = boost::fusion;
template <typename T>
void test_parser(json::parser const& jp, char const* in, T n)
{
char const* f = in;
char const* l = f + std::strlen(f);
T attr;
bool r = x3::parse(f, l, jp, attr);
BOOST_TEST(r);
BOOST_TEST(attr == n);
};
void test_string1(json::parser const& jp, char const* in)
{
char const* f = in;
char const* l = f + std::strlen(f);
json::string s;
bool r = x3::parse(f, l, jp, s);
BOOST_TEST(r);
BOOST_TEST(s.begin() == in);
BOOST_TEST(s.end() == l);
};
void test_string2(json::parser const& jp, char const* in, std::string s)
{
char const* f = in;
char const* l = f + std::strlen(f);
std::string attr;
bool r = x3::parse(f, l, jp, attr);
BOOST_TEST(r);
BOOST_TEST(attr == s);
};
template <typename C>
bool same(C const& a, C const& b)
{
if (boost::size(a) != boost::size(b))
return false;
for (std::size_t i = 0; i != boost::size(a); ++i)
if (a[i] != b[i])
return false;
return true;
}
template <typename Container>
void test_array(json::parser const& jp, char const* in, Container const& c)
{
char const* f = in;
char const* l = f + std::strlen(f);
Container attr;
bool r = x3::phrase_parse(f, l, jp, x3::space, attr);
BOOST_TEST(r);
BOOST_TEST(same(attr, c));
};
struct foo
{
int i;
double d;
std::string s;
};
template <typename T>
void test_object(json::parser const& jp, char const* in, T const& obj)
{
char const* f = in;
char const* l = f + std::strlen(f);
T attr;
bool r = x3::phrase_parse(f, l, jp, x3::space, attr);
BOOST_TEST(r);
BOOST_TEST(attr == obj);
};
BOOST_FUSION_ADAPT_STRUCT(
foo,
(int, i)
(double, d)
(std::string, s)
)
using fusion::operator==;
void test_json()
{
json::parser jp;
// ints and bools
{
test_parser(jp, "1234", 1234);
test_parser(jp, "1234.45", 1234.45);
test_parser(jp, "true", true);
test_parser(jp, "false", false);
}
// strings
{
test_string1(jp, "\"This is my string\"");
test_string1(jp, "\"This is \\\"my\\\" string\"");
test_string2(jp, "\"This is my string\"", "This is my string");
test_string2(jp, "\"This is \\\"my\\\" string\"", "This is \"my\" string");
test_string2(jp, "\"Sosa did fine.\\u263A\"", u8"Sosa did fine.\u263A");
test_string2(jp, "\"Snowman: \\u2603\"", u8"Snowman: \u2603");
}
// int vector
{
std::vector<int> c = {1, 2, 3, 4};
test_array(jp, "[1, 2, 3, 4]", c);
// empty vector
std::vector<int> c2;
test_array(jp, "[]", c2);
}
// int array
{
std::array<int, 4> c = {{1, 2, 3, 4}};
test_array(jp, "[1, 2, 3, 4]", c);
int c2[4] = {1, 2, 3, 4};
test_array(jp, "[1, 2, 3, 4]", c2);
// empty array
std::array<int, 0> c3;
test_array(jp, "[]", c3);
}
// double vector
{
std::vector<double> c = {1.1, 2.2, 3.3, 4.4};
test_array(jp, "[1.1, 2.2, 3.3, 4.4]", c);
}
// string vector
{
std::vector<std::string> c = {"a", "b", "c", "d"};
test_array(jp, "[\"a\", \"b\", \"c\", \"d\"]", c);
}
// struct
{
foo obj = {1, 2.2, "hey!"};
char const* in = R"(
{
"i" : 1,
"d" : 2.2,
"s" : "hey!"
}
)";
test_object(jp, in, obj);
}
}
int main(int argc, const char* argv[])
{
test_json();
return boost::report_errors();
}
<commit_msg>hierarchical json objects!<commit_after>/*=============================================================================
Copyright (c) 2016-2017 Joel de Guzman
Distributed under the MIT License (https://opensource.org/licenses/MIT)
=============================================================================*/
#include <boost/detail/lightweight_test.hpp>
#include <photon/support/json.hpp>
#include <boost/fusion/include/equal_to.hpp>
namespace json = photon::json;
namespace x3 = boost::spirit::x3;
namespace fusion = boost::fusion;
template <typename T>
void test_parser(json::parser const& jp, char const* in, T n)
{
char const* f = in;
char const* l = f + std::strlen(f);
T attr;
bool r = x3::parse(f, l, jp, attr);
BOOST_TEST(r);
BOOST_TEST(attr == n);
};
void test_string1(json::parser const& jp, char const* in)
{
char const* f = in;
char const* l = f + std::strlen(f);
json::string s;
bool r = x3::parse(f, l, jp, s);
BOOST_TEST(r);
BOOST_TEST(s.begin() == in);
BOOST_TEST(s.end() == l);
};
void test_string2(json::parser const& jp, char const* in, std::string s)
{
char const* f = in;
char const* l = f + std::strlen(f);
std::string attr;
bool r = x3::parse(f, l, jp, attr);
BOOST_TEST(r);
BOOST_TEST(attr == s);
};
template <typename C>
bool same(C const& a, C const& b)
{
if (boost::size(a) != boost::size(b))
return false;
for (std::size_t i = 0; i != boost::size(a); ++i)
if (a[i] != b[i])
return false;
return true;
}
template <typename Container>
void test_array(json::parser const& jp, char const* in, Container const& c)
{
char const* f = in;
char const* l = f + std::strlen(f);
Container attr;
bool r = x3::phrase_parse(f, l, jp, x3::space, attr);
BOOST_TEST(r);
BOOST_TEST(same(attr, c));
};
struct foo
{
int i;
double d;
std::string s;
};
struct bar
{
int ii;
double dd;
foo ff;
};
template <typename T>
void test_object(json::parser const& jp, char const* in, T const& obj)
{
char const* f = in;
char const* l = f + std::strlen(f);
T attr;
bool r = x3::phrase_parse(f, l, jp, x3::space, attr);
BOOST_TEST(r);
BOOST_TEST(attr == obj);
};
BOOST_FUSION_ADAPT_STRUCT(
foo,
(int, i)
(double, d)
(std::string, s)
)
BOOST_FUSION_ADAPT_STRUCT(
bar,
(int, ii)
(double, dd)
(foo, ff)
)
using fusion::operator==;
void test_json()
{
json::parser jp;
// ints and bools
{
test_parser(jp, "1234", 1234);
test_parser(jp, "1234.45", 1234.45);
test_parser(jp, "true", true);
test_parser(jp, "false", false);
}
// strings
{
test_string1(jp, "\"This is my string\"");
test_string1(jp, "\"This is \\\"my\\\" string\"");
test_string2(jp, "\"This is my string\"", "This is my string");
test_string2(jp, "\"This is \\\"my\\\" string\"", "This is \"my\" string");
test_string2(jp, "\"Sosa did fine.\\u263A\"", u8"Sosa did fine.\u263A");
test_string2(jp, "\"Snowman: \\u2603\"", u8"Snowman: \u2603");
}
// int vector
{
std::vector<int> c = {1, 2, 3, 4};
test_array(jp, "[1, 2, 3, 4]", c);
// empty vector
std::vector<int> c2;
test_array(jp, "[]", c2);
}
// int array
{
std::array<int, 4> c = {{1, 2, 3, 4}};
test_array(jp, "[1, 2, 3, 4]", c);
int c2[4] = {1, 2, 3, 4};
test_array(jp, "[1, 2, 3, 4]", c2);
// empty array
std::array<int, 0> c3;
test_array(jp, "[]", c3);
}
// double vector
{
std::vector<double> c = {1.1, 2.2, 3.3, 4.4};
test_array(jp, "[1.1, 2.2, 3.3, 4.4]", c);
}
// string vector
{
std::vector<std::string> c = {"a", "b", "c", "d"};
test_array(jp, "[\"a\", \"b\", \"c\", \"d\"]", c);
}
// struct
{
foo obj = {1, 2.2, "hey!"};
bar obj2 = {8, 9.9, obj};
{
char const* in = R"(
{
"i" : 1,
"d" : 2.2,
"s" : "hey!"
}
)";
test_object(jp, in, obj);
}
{
char const* in = R"(
{
"ii" : 8,
"dd" : 9.9,
"ff" :
{
"i" : 1,
"d" : 2.2,
"s" : "hey!"
}
}
)";
test_object(jp, in, obj2);
}
}
}
int main(int argc, const char* argv[])
{
test_json();
return boost::report_errors();
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <string.h>
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/byte_buffer_reader.h"
#include "grpc/support/slice.h"
#include "byte_buffer.h"
namespace grpc {
namespace node {
using v8::Context;
using v8::Function;
using v8::Local;
using v8::Object;
using v8::Number;
using v8::Value;
grpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {
Nan::HandleScope scope;
int length = ::node::Buffer::Length(buffer);
char *data = ::node::Buffer::Data(buffer);
gpr_slice slice = gpr_slice_malloc(length);
memcpy(GPR_SLICE_START_PTR(slice), data, length);
grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));
gpr_slice_unref(slice);
return byte_buffer;
}
Local<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {
Nan::EscapableHandleScope scope;
if (buffer == NULL) {
return scope.Escape(Nan::Null());
}
size_t length = grpc_byte_buffer_length(buffer);
char *result = reinterpret_cast<char *>(calloc(length, sizeof(char)));
size_t offset = 0;
grpc_byte_buffer_reader reader;
grpc_byte_buffer_reader_init(&reader, buffer);
gpr_slice next;
while (grpc_byte_buffer_reader_next(&reader, &next) != 0) {
memcpy(result + offset, GPR_SLICE_START_PTR(next), GPR_SLICE_LENGTH(next));
offset += GPR_SLICE_LENGTH(next);
}
return scope.Escape(MakeFastBuffer(
Nan::NewBuffer(result, length).ToLocalChecked()));
}
Local<Value> MakeFastBuffer(Local<Value> slowBuffer) {
Nan::EscapableHandleScope scope;
Local<Object> globalObj = Nan::GetCurrentContext()->Global();
Local<Function> bufferConstructor = Local<Function>::Cast(
globalObj->Get(Nan::New("Buffer").ToLocalChecked()));
Local<Value> consArgs[3] = {
slowBuffer,
Nan::New<Number>(::node::Buffer::Length(slowBuffer)),
Nan::New<Number>(0)
};
Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);
return scope.Escape(fastBuffer);
}
} // namespace node
} // namespace grpc
<commit_msg>Fixes memory leak when receiving data<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <string.h>
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/byte_buffer_reader.h"
#include "grpc/support/slice.h"
#include "byte_buffer.h"
namespace grpc {
namespace node {
using v8::Context;
using v8::Function;
using v8::Local;
using v8::Object;
using v8::Number;
using v8::Value;
grpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {
Nan::HandleScope scope;
int length = ::node::Buffer::Length(buffer);
char *data = ::node::Buffer::Data(buffer);
gpr_slice slice = gpr_slice_malloc(length);
memcpy(GPR_SLICE_START_PTR(slice), data, length);
grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));
gpr_slice_unref(slice);
return byte_buffer;
}
Local<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {
Nan::EscapableHandleScope scope;
if (buffer == NULL) {
return scope.Escape(Nan::Null());
}
size_t length = grpc_byte_buffer_length(buffer);
char *result = reinterpret_cast<char *>(calloc(length, sizeof(char)));
size_t offset = 0;
grpc_byte_buffer_reader reader;
grpc_byte_buffer_reader_init(&reader, buffer);
gpr_slice next;
while (grpc_byte_buffer_reader_next(&reader, &next) != 0) {
memcpy(result + offset, GPR_SLICE_START_PTR(next), GPR_SLICE_LENGTH(next));
offset += GPR_SLICE_LENGTH(next);
gpr_slice_unref(next);
}
return scope.Escape(MakeFastBuffer(
Nan::NewBuffer(result, length).ToLocalChecked()));
}
Local<Value> MakeFastBuffer(Local<Value> slowBuffer) {
Nan::EscapableHandleScope scope;
Local<Object> globalObj = Nan::GetCurrentContext()->Global();
Local<Function> bufferConstructor = Local<Function>::Cast(
globalObj->Get(Nan::New("Buffer").ToLocalChecked()));
Local<Value> consArgs[3] = {
slowBuffer,
Nan::New<Number>(::node::Buffer::Length(slowBuffer)),
Nan::New<Number>(0)
};
Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);
return scope.Escape(fastBuffer);
}
} // namespace node
} // namespace grpc
<|endoftext|> |
<commit_before>#include <miopen.h>
#include "test.hpp"
#include <vector>
#include <array>
#include <iterator>
#include <memory>
#include <miopen/tensor_extra.hpp>
struct handle_fixture
{
miopenHandle_t handle;
#if MIOPEN_BACKEND_OPENCL
cl_command_queue q;
#endif
handle_fixture()
{
miopenCreate(&handle);
#if MIOPEN_BACKEND_OPENCL
miopenGetStream(handle, &q);
#endif
}
~handle_fixture()
{
miopenDestroy(handle);
}
};
struct input_tensor_fixture
{
miopenTensorDescriptor_t inputTensor;
input_tensor_fixture()
{
STATUS(miopenCreateTensorDescriptor(&inputTensor));
STATUS(miopenSet4dTensorDescriptor(
inputTensor,
miopenFloat,
100,
32,
8,
8));
}
~input_tensor_fixture()
{
miopenDestroyTensorDescriptor(inputTensor);
}
void run()
{
int n, c, h, w;
int nStride, cStride, hStride, wStride;
miopenDataType_t dt;
STATUS(miopenGet4dTensorDescriptor(
inputTensor,
&dt,
&n,
&c,
&h,
&w,
&nStride,
&cStride,
&hStride,
&wStride));
EXPECT(dt == 1);
EXPECT(n == 100);
EXPECT(c == 32);
EXPECT(h == 8);
EXPECT(w == 8);
EXPECT(nStride == c * cStride);
EXPECT(cStride == h * hStride);
EXPECT(hStride == w * wStride);
EXPECT(wStride == 1);
}
};
struct conv_filter_fixture : virtual handle_fixture
{
miopenTensorDescriptor_t convFilter;
miopenConvolutionDescriptor_t convDesc;
static const miopenConvolutionMode_t mode = miopenConvolution;
conv_filter_fixture()
{
STATUS(miopenCreateTensorDescriptor(&convFilter));
// weights
STATUS(miopenSet4dTensorDescriptor(
convFilter,
miopenFloat,
64, // outputs
32, // inputs
5, // kernel size
5));
STATUS(miopenCreateConvolutionDescriptor(&convDesc));
// convolution with padding 2
STATUS(miopenInitConvolutionDescriptor(convDesc,
mode,
0,
0,
1,
1,
1,
1));
}
~conv_filter_fixture()
{
miopenDestroyTensorDescriptor(convFilter);
miopenDestroyConvolutionDescriptor(convDesc);
}
void run()
{
// TODO: Update API to not require mode by pointer
miopenConvolutionMode_t lmode = mode;
int pad_w, pad_h, u, v, upx, upy;
STATUS(miopenGetConvolutionDescriptor(convDesc,
&lmode,
&pad_h, &pad_w, &u, &v,
&upx, &upy));
EXPECT(mode == 0);
EXPECT(pad_h == 0);
EXPECT(pad_w == 0);
EXPECT(u == 1);
EXPECT(v == 1);
EXPECT(upx == 1);
EXPECT(upy == 1);
}
};
struct output_tensor_fixture : conv_filter_fixture, input_tensor_fixture
{
miopenTensorDescriptor_t outputTensor;
output_tensor_fixture()
{
int x, y, z, a;
STATUS(miopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a));
STATUS(miopenCreateTensorDescriptor(&outputTensor));
STATUS(miopenSet4dTensorDescriptor(
outputTensor,
miopenFloat,
x,
y,
z,
a));
}
~output_tensor_fixture()
{
miopenDestroyTensorDescriptor(outputTensor);
}
void run()
{
int x, y, z, a;
STATUS(miopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a));
EXPECT(x == 100);
EXPECT(y == 64);
EXPECT(z == 4);
EXPECT(a == 4);
}
};
template<bool Profile>
struct conv_forward : output_tensor_fixture
{
void run()
{
STATUS(miopenEnableProfiling(handle, Profile));
int alpha = 1, beta = 1;
STATUS(miopenTransformTensor(handle,
&alpha,
inputTensor,
NULL,
&beta,
convFilter,
NULL));
// int value = 10;
// STATUS(miopenSetTensor(handle, inputTensor, NULL, &value));
// STATUS(miopenScaleTensor(handle, inputTensor, NULL, &alpha));
// Setup OpenCL buffers
int n, h, c, w;
STATUS(miopenGet4dTensorDescriptorLengths(inputTensor, &n, &c, &h, &w));
size_t sz_in = n*c*h*w;
STATUS(miopenGet4dTensorDescriptorLengths(convFilter, &n, &c, &h, &w));
size_t sz_wei = n*c*h*w;
STATUS(miopenGet4dTensorDescriptorLengths(outputTensor, &n, &c, &h, &w));
size_t sz_out = n*c*h*w;
size_t sz_fwd_workspace;
STATUS(miopenConvolutionForwardGetWorkSpaceSize(handle, convFilter, inputTensor, outputTensor, convDesc, &sz_fwd_workspace));
std::vector<float> in(sz_in);
std::vector<float> wei(sz_wei);
std::vector<float> out(sz_out);
std::vector<float> fwd_workspace(sz_fwd_workspace/4);
for(int i = 0; i < sz_in; i++) {
in[i] = rand() * (1.0 / RAND_MAX);
}
for (int i = 0; i < sz_wei; i++) {
wei[i] = static_cast<double>(rand() * (1.0 / RAND_MAX) - 0.5) * 0.001;
}
#if MIOPEN_BACKEND_OPENCL
cl_context ctx;
clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);
cl_int status = CL_SUCCESS;
cl_mem in_dev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz_in,NULL, &status);
cl_mem wei_dev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz_wei,NULL, NULL);
cl_mem out_dev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz_out,NULL, NULL);
cl_mem fwd_workspace_dev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, sz_fwd_workspace, NULL, NULL);
status = clEnqueueWriteBuffer(q, in_dev, CL_TRUE, 0, 4*sz_in, in.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, wei_dev, CL_TRUE, 0, 4*sz_wei, wei.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, out_dev, CL_TRUE, 0, 4*sz_out, out.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, fwd_workspace_dev, CL_TRUE, 0, sz_fwd_workspace, fwd_workspace.data(), 0, NULL, NULL);
EXPECT(status == CL_SUCCESS);
#elif MIOPEN_BACKEND_HIP
void * in_dev;
void * wei_dev;
void * out_dev;
void * fwd_workspace_dev;
EXPECT(hipMalloc(&in_dev, 4*sz_in) == hipSuccess);
EXPECT(hipMalloc(&wei_dev, 4*sz_wei) == hipSuccess);
EXPECT(hipMalloc(&out_dev, 4*sz_out) == hipSuccess);
EXPECT(hipMalloc(&fwd_workspace_dev, sz_fwd_workspace) == hipSuccess);
EXPECT(hipMemcpy(in_dev, in.data(), 4*sz_in, hipMemcpyHostToDevice) == hipSuccess);
EXPECT(hipMemcpy(wei_dev, wei.data(), 4*sz_wei, hipMemcpyHostToDevice) == hipSuccess);
EXPECT(hipMemcpy(out_dev, out.data(), 4*sz_out, hipMemcpyHostToDevice) == hipSuccess);
EXPECT(hipMemcpy(fwd_workspace_dev, fwd_workspace.data(), sz_fwd_workspace, hipMemcpyHostToDevice) == hipSuccess);
#endif
int ret_algo_count;
miopenConvAlgoPerf_t perf;
STATUS(miopenFindConvolutionForwardAlgorithm(handle,
inputTensor,
in_dev,
convFilter,
wei_dev,
convDesc,
outputTensor,
out_dev,
1,
&ret_algo_count,
&perf,
fwd_workspace_dev,
sz_fwd_workspace,
0)); // MD: Not performing exhaustiveSearch by default for now
STATUS(miopenConvolutionForward(handle,
&alpha,
inputTensor,
in_dev,
convFilter,
wei_dev,
convDesc,
miopenConvolutionFwdAlgoDirect,
&beta,
outputTensor,
out_dev,
fwd_workspace_dev,
sz_fwd_workspace));
float time;
STATUS(miopenGetKernelTime(handle, &time));
if (Profile)
{
CHECK(time > 0.0);
}
else
{
CHECK(time == 0.0);
}
// Potential memory leak free memory at end of function
#if MIOPEN_BACKEND_OPENCL
clReleaseMemObject(in_dev);
clReleaseMemObject(wei_dev);
clReleaseMemObject(out_dev);
clReleaseMemObject(fwd_workspace_dev);
#elif MIOPEN_BACKEND_HIP
hipFree(in_dev);
hipFree(wei_dev);
hipFree(out_dev);
hipFree(fwd_workspace_dev);
#endif
}
};
int main() {
run_test<input_tensor_fixture>();
run_test<conv_filter_fixture>();
run_test<output_tensor_fixture>();
run_test<conv_forward<true>>();
run_test<conv_forward<false>>();
}
<commit_msg>fixed forward-workspace args<commit_after>#include <miopen.h>
#include "test.hpp"
#include <vector>
#include <array>
#include <iterator>
#include <memory>
#include <miopen/tensor_extra.hpp>
struct handle_fixture
{
miopenHandle_t handle;
#if MIOPEN_BACKEND_OPENCL
cl_command_queue q;
#endif
handle_fixture()
{
miopenCreate(&handle);
#if MIOPEN_BACKEND_OPENCL
miopenGetStream(handle, &q);
#endif
}
~handle_fixture()
{
miopenDestroy(handle);
}
};
struct input_tensor_fixture
{
miopenTensorDescriptor_t inputTensor;
input_tensor_fixture()
{
STATUS(miopenCreateTensorDescriptor(&inputTensor));
STATUS(miopenSet4dTensorDescriptor(
inputTensor,
miopenFloat,
100,
32,
8,
8));
}
~input_tensor_fixture()
{
miopenDestroyTensorDescriptor(inputTensor);
}
void run()
{
int n, c, h, w;
int nStride, cStride, hStride, wStride;
miopenDataType_t dt;
STATUS(miopenGet4dTensorDescriptor(
inputTensor,
&dt,
&n,
&c,
&h,
&w,
&nStride,
&cStride,
&hStride,
&wStride));
EXPECT(dt == 1);
EXPECT(n == 100);
EXPECT(c == 32);
EXPECT(h == 8);
EXPECT(w == 8);
EXPECT(nStride == c * cStride);
EXPECT(cStride == h * hStride);
EXPECT(hStride == w * wStride);
EXPECT(wStride == 1);
}
};
struct conv_filter_fixture : virtual handle_fixture
{
miopenTensorDescriptor_t convFilter;
miopenConvolutionDescriptor_t convDesc;
static const miopenConvolutionMode_t mode = miopenConvolution;
conv_filter_fixture()
{
STATUS(miopenCreateTensorDescriptor(&convFilter));
// weights
STATUS(miopenSet4dTensorDescriptor(
convFilter,
miopenFloat,
64, // outputs
32, // inputs
5, // kernel size
5));
STATUS(miopenCreateConvolutionDescriptor(&convDesc));
// convolution with padding 2
STATUS(miopenInitConvolutionDescriptor(convDesc,
mode,
0,
0,
1,
1,
1,
1));
}
~conv_filter_fixture()
{
miopenDestroyTensorDescriptor(convFilter);
miopenDestroyConvolutionDescriptor(convDesc);
}
void run()
{
// TODO: Update API to not require mode by pointer
miopenConvolutionMode_t lmode = mode;
int pad_w, pad_h, u, v, upx, upy;
STATUS(miopenGetConvolutionDescriptor(convDesc,
&lmode,
&pad_h, &pad_w, &u, &v,
&upx, &upy));
EXPECT(mode == 0);
EXPECT(pad_h == 0);
EXPECT(pad_w == 0);
EXPECT(u == 1);
EXPECT(v == 1);
EXPECT(upx == 1);
EXPECT(upy == 1);
}
};
struct output_tensor_fixture : conv_filter_fixture, input_tensor_fixture
{
miopenTensorDescriptor_t outputTensor;
output_tensor_fixture()
{
int x, y, z, a;
STATUS(miopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a));
STATUS(miopenCreateTensorDescriptor(&outputTensor));
STATUS(miopenSet4dTensorDescriptor(
outputTensor,
miopenFloat,
x,
y,
z,
a));
}
~output_tensor_fixture()
{
miopenDestroyTensorDescriptor(outputTensor);
}
void run()
{
int x, y, z, a;
STATUS(miopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a));
EXPECT(x == 100);
EXPECT(y == 64);
EXPECT(z == 4);
EXPECT(a == 4);
}
};
template<bool Profile>
struct conv_forward : output_tensor_fixture
{
void run()
{
STATUS(miopenEnableProfiling(handle, Profile));
int alpha = 1, beta = 1;
STATUS(miopenTransformTensor(handle,
&alpha,
inputTensor,
NULL,
&beta,
convFilter,
NULL));
// int value = 10;
// STATUS(miopenSetTensor(handle, inputTensor, NULL, &value));
// STATUS(miopenScaleTensor(handle, inputTensor, NULL, &alpha));
// Setup OpenCL buffers
int n, h, c, w;
STATUS(miopenGet4dTensorDescriptorLengths(inputTensor, &n, &c, &h, &w));
size_t sz_in = n*c*h*w;
STATUS(miopenGet4dTensorDescriptorLengths(convFilter, &n, &c, &h, &w));
size_t sz_wei = n*c*h*w;
STATUS(miopenGet4dTensorDescriptorLengths(outputTensor, &n, &c, &h, &w));
size_t sz_out = n*c*h*w;
size_t sz_fwd_workspace;
STATUS(miopenConvolutionForwardGetWorkSpaceSize(handle, convFilter, inputTensor, convDesc, outputTensor, &sz_fwd_workspace));
std::vector<float> in(sz_in);
std::vector<float> wei(sz_wei);
std::vector<float> out(sz_out);
std::vector<float> fwd_workspace(sz_fwd_workspace/4);
for(int i = 0; i < sz_in; i++) {
in[i] = rand() * (1.0 / RAND_MAX);
}
for (int i = 0; i < sz_wei; i++) {
wei[i] = static_cast<double>(rand() * (1.0 / RAND_MAX) - 0.5) * 0.001;
}
#if MIOPEN_BACKEND_OPENCL
cl_context ctx;
clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);
cl_int status = CL_SUCCESS;
cl_mem in_dev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz_in,NULL, &status);
cl_mem wei_dev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz_wei,NULL, NULL);
cl_mem out_dev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz_out,NULL, NULL);
cl_mem fwd_workspace_dev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, sz_fwd_workspace, NULL, NULL);
status = clEnqueueWriteBuffer(q, in_dev, CL_TRUE, 0, 4*sz_in, in.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, wei_dev, CL_TRUE, 0, 4*sz_wei, wei.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, out_dev, CL_TRUE, 0, 4*sz_out, out.data(), 0, NULL, NULL);
status |= clEnqueueWriteBuffer(q, fwd_workspace_dev, CL_TRUE, 0, sz_fwd_workspace, fwd_workspace.data(), 0, NULL, NULL);
EXPECT(status == CL_SUCCESS);
#elif MIOPEN_BACKEND_HIP
void * in_dev;
void * wei_dev;
void * out_dev;
void * fwd_workspace_dev;
EXPECT(hipMalloc(&in_dev, 4*sz_in) == hipSuccess);
EXPECT(hipMalloc(&wei_dev, 4*sz_wei) == hipSuccess);
EXPECT(hipMalloc(&out_dev, 4*sz_out) == hipSuccess);
EXPECT(hipMalloc(&fwd_workspace_dev, sz_fwd_workspace) == hipSuccess);
EXPECT(hipMemcpy(in_dev, in.data(), 4*sz_in, hipMemcpyHostToDevice) == hipSuccess);
EXPECT(hipMemcpy(wei_dev, wei.data(), 4*sz_wei, hipMemcpyHostToDevice) == hipSuccess);
EXPECT(hipMemcpy(out_dev, out.data(), 4*sz_out, hipMemcpyHostToDevice) == hipSuccess);
EXPECT(hipMemcpy(fwd_workspace_dev, fwd_workspace.data(), sz_fwd_workspace, hipMemcpyHostToDevice) == hipSuccess);
#endif
int ret_algo_count;
miopenConvAlgoPerf_t perf;
STATUS(miopenFindConvolutionForwardAlgorithm(handle,
inputTensor,
in_dev,
convFilter,
wei_dev,
convDesc,
outputTensor,
out_dev,
1,
&ret_algo_count,
&perf,
fwd_workspace_dev,
sz_fwd_workspace,
0)); // MD: Not performing exhaustiveSearch by default for now
STATUS(miopenConvolutionForward(handle,
&alpha,
inputTensor,
in_dev,
convFilter,
wei_dev,
convDesc,
miopenConvolutionFwdAlgoDirect,
&beta,
outputTensor,
out_dev,
fwd_workspace_dev,
sz_fwd_workspace));
float time;
STATUS(miopenGetKernelTime(handle, &time));
if (Profile)
{
CHECK(time > 0.0);
}
else
{
CHECK(time == 0.0);
}
// Potential memory leak free memory at end of function
#if MIOPEN_BACKEND_OPENCL
clReleaseMemObject(in_dev);
clReleaseMemObject(wei_dev);
clReleaseMemObject(out_dev);
clReleaseMemObject(fwd_workspace_dev);
#elif MIOPEN_BACKEND_HIP
hipFree(in_dev);
hipFree(wei_dev);
hipFree(out_dev);
hipFree(fwd_workspace_dev);
#endif
}
};
int main() {
run_test<input_tensor_fixture>();
run_test<conv_filter_fixture>();
run_test<output_tensor_fixture>();
run_test<conv_forward<true>>();
run_test<conv_forward<false>>();
}
<|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.
*
**************************************************************************/
#ifndef REALM_UTIL_BIND_PTR_HPP
#define REALM_UTIL_BIND_PTR_HPP
#include <algorithm>
#include <atomic>
#include <ostream>
#include <utility>
#include <realm/util/features.h>
#include <realm/util/assert.hpp>
namespace realm {
namespace util {
class bind_ptr_base {
public:
struct adopt_tag {
};
};
/// A generic intrusive smart pointer that binds itself explicitely to
/// the target object.
///
/// This class is agnostic towards what 'binding' means for the target
/// object, but a common use is 'reference counting'. See RefCountBase
/// for an example of that.
///
/// This smart pointer implementation assumes that the target object
/// destructor never throws.
template <class T>
class bind_ptr : public bind_ptr_base {
public:
constexpr bind_ptr() noexcept
: m_ptr(nullptr)
{
}
~bind_ptr() noexcept
{
unbind();
}
explicit bind_ptr(T* p) noexcept
{
bind(p);
}
template <class U>
explicit bind_ptr(U* p) noexcept
{
bind(p);
}
bind_ptr(T* p, adopt_tag) noexcept
{
m_ptr = p;
}
template <class U>
bind_ptr(U* p, adopt_tag) noexcept
{
m_ptr = p;
}
// Copy construct
bind_ptr(const bind_ptr& p) noexcept
{
bind(p.m_ptr);
}
template <class U>
bind_ptr(const bind_ptr<U>& p) noexcept
{
bind(p.m_ptr);
}
// Copy assign
bind_ptr& operator=(const bind_ptr& p) noexcept
{
bind_ptr(p).swap(*this);
return *this;
}
template <class U>
bind_ptr& operator=(const bind_ptr<U>& p) noexcept
{
bind_ptr(p).swap(*this);
return *this;
}
// Move construct
bind_ptr(bind_ptr&& p) noexcept
: m_ptr(p.release())
{
}
template <class U>
bind_ptr(bind_ptr<U>&& p) noexcept
: m_ptr(p.release())
{
}
// Move from std::unique_ptr
bind_ptr(std::unique_ptr<T>&& p) noexcept
{
bind(p.release());
}
// Move assign
bind_ptr& operator=(bind_ptr&& p) noexcept
{
bind_ptr(std::move(p)).swap(*this);
return *this;
}
template <class U>
bind_ptr& operator=(bind_ptr<U>&& p) noexcept
{
bind_ptr(std::move(p)).swap(*this);
return *this;
}
//@{
// Comparison
template <class U>
bool operator==(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator==(U*) const noexcept;
template <class U>
bool operator!=(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator!=(U*) const noexcept;
template <class U>
bool operator<(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator<(U*) const noexcept;
template <class U>
bool operator>(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator>(U*) const noexcept;
template <class U>
bool operator<=(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator<=(U*) const noexcept;
template <class U>
bool operator>=(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator>=(U*) const noexcept;
//@}
// Dereference
T& operator*() const noexcept
{
return *m_ptr;
}
T* operator->() const noexcept
{
return m_ptr;
}
explicit operator bool() const noexcept
{
return m_ptr != 0;
}
T* get() const noexcept
{
return m_ptr;
}
void reset() noexcept
{
bind_ptr().swap(*this);
}
void reset(T* p) noexcept
{
bind_ptr(p).swap(*this);
}
template <class U>
void reset(U* p) noexcept
{
bind_ptr(p).swap(*this);
}
void reset(T* p, adopt_tag) noexcept
{
bind_ptr(p, adopt_tag{}).swap(*this);
}
template <class U>
void reset(U* p, adopt_tag) noexcept
{
bind_ptr(p, adopt_tag{}).swap(*this);
}
T* release() noexcept
{
T* const p = m_ptr;
m_ptr = nullptr;
return p;
}
void swap(bind_ptr& p) noexcept
{
std::swap(m_ptr, p.m_ptr);
}
friend void swap(bind_ptr& a, bind_ptr& b) noexcept
{
a.swap(b);
}
protected:
struct casting_move_tag {
};
template <class U>
bind_ptr(bind_ptr<U>* p, casting_move_tag) noexcept
: m_ptr(static_cast<T*>(p->release()))
{
}
private:
T* m_ptr;
void bind(T* p) noexcept
{
if (p)
p->bind_ptr();
m_ptr = p;
}
void unbind() noexcept
{
if (m_ptr)
m_ptr->unbind_ptr();
}
template <class>
friend class bind_ptr;
};
template <class T, typename... Args>
bind_ptr<T> make_bind(Args&&... __args)
{
return bind_ptr<T>(new T(std::forward<Args>(__args)...));
}
template <class C, class T, class U>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const bind_ptr<U>& p)
{
out << static_cast<const void*>(p.get());
return out;
}
//@{
// Comparison
template <class T, class U>
bool operator==(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator!=(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator<(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator>(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator<=(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator>=(T*, const bind_ptr<U>&) noexcept;
//@}
/// Polymorphic convenience base class for reference counting objects.
///
/// Together with bind_ptr, this class delivers simple instrusive
/// reference counting.
///
/// \sa bind_ptr
class RefCountBase {
public:
RefCountBase() noexcept
: m_ref_count(0)
{
}
virtual ~RefCountBase() noexcept
{
REALM_ASSERT(m_ref_count == 0);
}
RefCountBase(const RefCountBase&)
: m_ref_count(0)
{
}
void operator=(const RefCountBase&) {}
protected:
void bind_ptr() const noexcept
{
++m_ref_count;
}
void unbind_ptr() const noexcept
{
if (--m_ref_count == 0)
delete this;
}
private:
mutable unsigned long m_ref_count;
template <class>
friend class bind_ptr;
};
/// Same as RefCountBase, but this one makes the copying of, and the
/// destruction of counted references thread-safe.
///
/// \sa RefCountBase
/// \sa bind_ptr
class AtomicRefCountBase {
public:
AtomicRefCountBase() noexcept
: m_ref_count(0)
{
}
virtual ~AtomicRefCountBase() noexcept
{
REALM_ASSERT(m_ref_count == 0);
}
AtomicRefCountBase(const AtomicRefCountBase&)
: m_ref_count(0)
{
}
void operator=(const AtomicRefCountBase&) {}
protected:
// FIXME: Operators ++ and -- as used below use
// std::memory_order_seq_cst. This can be optimized.
void bind_ptr() const noexcept
{
++m_ref_count;
}
void unbind_ptr() const noexcept
{
if (--m_ref_count == 0) {
delete this;
}
}
private:
mutable std::atomic<unsigned long> m_ref_count;
template <class>
friend class bind_ptr;
};
// Implementation:
template <class T>
template <class U>
bool bind_ptr<T>::operator==(const bind_ptr<U>& p) const noexcept
{
return m_ptr == p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator==(U* p) const noexcept
{
return m_ptr == p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator!=(const bind_ptr<U>& p) const noexcept
{
return m_ptr != p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator!=(U* p) const noexcept
{
return m_ptr != p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator<(const bind_ptr<U>& p) const noexcept
{
return m_ptr < p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator<(U* p) const noexcept
{
return m_ptr < p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator>(const bind_ptr<U>& p) const noexcept
{
return m_ptr > p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator>(U* p) const noexcept
{
return m_ptr > p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator<=(const bind_ptr<U>& p) const noexcept
{
return m_ptr <= p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator<=(U* p) const noexcept
{
return m_ptr <= p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator>=(const bind_ptr<U>& p) const noexcept
{
return m_ptr >= p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator>=(U* p) const noexcept
{
return m_ptr >= p;
}
template <class T, class U>
bool operator==(T* a, const bind_ptr<U>& b) noexcept
{
return b == a;
}
template <class T, class U>
bool operator!=(T* a, const bind_ptr<U>& b) noexcept
{
return b != a;
}
template <class T, class U>
bool operator<(T* a, const bind_ptr<U>& b) noexcept
{
return b > a;
}
template <class T, class U>
bool operator>(T* a, const bind_ptr<U>& b) noexcept
{
return b < a;
}
template <class T, class U>
bool operator<=(T* a, const bind_ptr<U>& b) noexcept
{
return b >= a;
}
template <class T, class U>
bool operator>=(T* a, const bind_ptr<U>& b) noexcept
{
return b <= a;
}
} // namespace util
} // namespace realm
#endif // REALM_UTIL_BIND_PTR_HPP
<commit_msg>Add an explicit deduction guide for bind_ptr<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.
*
**************************************************************************/
#ifndef REALM_UTIL_BIND_PTR_HPP
#define REALM_UTIL_BIND_PTR_HPP
#include <algorithm>
#include <atomic>
#include <ostream>
#include <utility>
#include <realm/util/features.h>
#include <realm/util/assert.hpp>
namespace realm {
namespace util {
class bind_ptr_base {
public:
struct adopt_tag {
};
};
/// A generic intrusive smart pointer that binds itself explicitely to
/// the target object.
///
/// This class is agnostic towards what 'binding' means for the target
/// object, but a common use is 'reference counting'. See RefCountBase
/// for an example of that.
///
/// This smart pointer implementation assumes that the target object
/// destructor never throws.
template <class T>
class bind_ptr : public bind_ptr_base {
public:
constexpr bind_ptr() noexcept
: m_ptr(nullptr)
{
}
~bind_ptr() noexcept
{
unbind();
}
explicit bind_ptr(T* p) noexcept
{
bind(p);
}
template <class U>
explicit bind_ptr(U* p) noexcept
{
bind(p);
}
bind_ptr(T* p, adopt_tag) noexcept
{
m_ptr = p;
}
template <class U>
bind_ptr(U* p, adopt_tag) noexcept
{
m_ptr = p;
}
// Copy construct
bind_ptr(const bind_ptr& p) noexcept
{
bind(p.m_ptr);
}
template <class U>
bind_ptr(const bind_ptr<U>& p) noexcept
{
bind(p.m_ptr);
}
// Copy assign
bind_ptr& operator=(const bind_ptr& p) noexcept
{
bind_ptr(p).swap(*this);
return *this;
}
template <class U>
bind_ptr& operator=(const bind_ptr<U>& p) noexcept
{
bind_ptr(p).swap(*this);
return *this;
}
// Move construct
bind_ptr(bind_ptr&& p) noexcept
: m_ptr(p.release())
{
}
template <class U>
bind_ptr(bind_ptr<U>&& p) noexcept
: m_ptr(p.release())
{
}
// Move from std::unique_ptr
bind_ptr(std::unique_ptr<T>&& p) noexcept
{
bind(p.release());
}
// Move assign
bind_ptr& operator=(bind_ptr&& p) noexcept
{
bind_ptr(std::move(p)).swap(*this);
return *this;
}
template <class U>
bind_ptr& operator=(bind_ptr<U>&& p) noexcept
{
bind_ptr(std::move(p)).swap(*this);
return *this;
}
//@{
// Comparison
template <class U>
bool operator==(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator==(U*) const noexcept;
template <class U>
bool operator!=(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator!=(U*) const noexcept;
template <class U>
bool operator<(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator<(U*) const noexcept;
template <class U>
bool operator>(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator>(U*) const noexcept;
template <class U>
bool operator<=(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator<=(U*) const noexcept;
template <class U>
bool operator>=(const bind_ptr<U>&) const noexcept;
template <class U>
bool operator>=(U*) const noexcept;
//@}
// Dereference
T& operator*() const noexcept
{
return *m_ptr;
}
T* operator->() const noexcept
{
return m_ptr;
}
explicit operator bool() const noexcept
{
return m_ptr != 0;
}
T* get() const noexcept
{
return m_ptr;
}
void reset() noexcept
{
bind_ptr().swap(*this);
}
void reset(T* p) noexcept
{
bind_ptr(p).swap(*this);
}
template <class U>
void reset(U* p) noexcept
{
bind_ptr(p).swap(*this);
}
void reset(T* p, adopt_tag) noexcept
{
bind_ptr(p, adopt_tag{}).swap(*this);
}
template <class U>
void reset(U* p, adopt_tag) noexcept
{
bind_ptr(p, adopt_tag{}).swap(*this);
}
T* release() noexcept
{
T* const p = m_ptr;
m_ptr = nullptr;
return p;
}
void swap(bind_ptr& p) noexcept
{
std::swap(m_ptr, p.m_ptr);
}
friend void swap(bind_ptr& a, bind_ptr& b) noexcept
{
a.swap(b);
}
protected:
struct casting_move_tag {
};
template <class U>
bind_ptr(bind_ptr<U>* p, casting_move_tag) noexcept
: m_ptr(static_cast<T*>(p->release()))
{
}
private:
T* m_ptr;
void bind(T* p) noexcept
{
if (p)
p->bind_ptr();
m_ptr = p;
}
void unbind() noexcept
{
if (m_ptr)
m_ptr->unbind_ptr();
}
template <class>
friend class bind_ptr;
};
// Deduction guides
template <class T>
bind_ptr(T*) -> bind_ptr<T>;
template <class T>
bind_ptr(T*, bind_ptr_base::adopt_tag) -> bind_ptr<T>;
template <class T, typename... Args>
bind_ptr<T> make_bind(Args&&... __args)
{
return bind_ptr<T>(new T(std::forward<Args>(__args)...));
}
template <class C, class T, class U>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const bind_ptr<U>& p)
{
out << static_cast<const void*>(p.get());
return out;
}
//@{
// Comparison
template <class T, class U>
bool operator==(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator!=(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator<(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator>(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator<=(T*, const bind_ptr<U>&) noexcept;
template <class T, class U>
bool operator>=(T*, const bind_ptr<U>&) noexcept;
//@}
/// Polymorphic convenience base class for reference counting objects.
///
/// Together with bind_ptr, this class delivers simple instrusive
/// reference counting.
///
/// \sa bind_ptr
class RefCountBase {
public:
RefCountBase() noexcept
: m_ref_count(0)
{
}
virtual ~RefCountBase() noexcept
{
REALM_ASSERT(m_ref_count == 0);
}
RefCountBase(const RefCountBase&)
: m_ref_count(0)
{
}
void operator=(const RefCountBase&) {}
protected:
void bind_ptr() const noexcept
{
++m_ref_count;
}
void unbind_ptr() const noexcept
{
if (--m_ref_count == 0)
delete this;
}
private:
mutable unsigned long m_ref_count;
template <class>
friend class bind_ptr;
};
/// Same as RefCountBase, but this one makes the copying of, and the
/// destruction of counted references thread-safe.
///
/// \sa RefCountBase
/// \sa bind_ptr
class AtomicRefCountBase {
public:
AtomicRefCountBase() noexcept
: m_ref_count(0)
{
}
virtual ~AtomicRefCountBase() noexcept
{
REALM_ASSERT(m_ref_count == 0);
}
AtomicRefCountBase(const AtomicRefCountBase&)
: m_ref_count(0)
{
}
void operator=(const AtomicRefCountBase&) {}
protected:
// FIXME: Operators ++ and -- as used below use
// std::memory_order_seq_cst. This can be optimized.
void bind_ptr() const noexcept
{
++m_ref_count;
}
void unbind_ptr() const noexcept
{
if (--m_ref_count == 0) {
delete this;
}
}
private:
mutable std::atomic<unsigned long> m_ref_count;
template <class>
friend class bind_ptr;
};
// Implementation:
template <class T>
template <class U>
bool bind_ptr<T>::operator==(const bind_ptr<U>& p) const noexcept
{
return m_ptr == p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator==(U* p) const noexcept
{
return m_ptr == p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator!=(const bind_ptr<U>& p) const noexcept
{
return m_ptr != p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator!=(U* p) const noexcept
{
return m_ptr != p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator<(const bind_ptr<U>& p) const noexcept
{
return m_ptr < p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator<(U* p) const noexcept
{
return m_ptr < p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator>(const bind_ptr<U>& p) const noexcept
{
return m_ptr > p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator>(U* p) const noexcept
{
return m_ptr > p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator<=(const bind_ptr<U>& p) const noexcept
{
return m_ptr <= p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator<=(U* p) const noexcept
{
return m_ptr <= p;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator>=(const bind_ptr<U>& p) const noexcept
{
return m_ptr >= p.m_ptr;
}
template <class T>
template <class U>
bool bind_ptr<T>::operator>=(U* p) const noexcept
{
return m_ptr >= p;
}
template <class T, class U>
bool operator==(T* a, const bind_ptr<U>& b) noexcept
{
return b == a;
}
template <class T, class U>
bool operator!=(T* a, const bind_ptr<U>& b) noexcept
{
return b != a;
}
template <class T, class U>
bool operator<(T* a, const bind_ptr<U>& b) noexcept
{
return b > a;
}
template <class T, class U>
bool operator>(T* a, const bind_ptr<U>& b) noexcept
{
return b < a;
}
template <class T, class U>
bool operator<=(T* a, const bind_ptr<U>& b) noexcept
{
return b >= a;
}
template <class T, class U>
bool operator>=(T* a, const bind_ptr<U>& b) noexcept
{
return b <= a;
}
} // namespace util
} // namespace realm
#endif // REALM_UTIL_BIND_PTR_HPP
<|endoftext|> |
<commit_before>#include "node/solid/triangle.h"
namespace Svit
{
Triangle::Triangle (Point3 _p1, Point3 _p2, Point3 _p3)
: p1(_p1), p2(_p2), p3(_p3)
{
p1.w = 0.0f;
p2.w = 0.0f;
p3.w = 0.0f;
e1 = p2 - p1;
e2 = p3 - p1;
normal = ~(~e1 & ~e2);
}
boost::optional<Intersection>
Triangle::intersect (Ray& _ray, float _best)
{
Vector3 P = _ray.direction & e2;
float det = e1 % P;
if (det == 0.0f)
return boost::optional<Intersection>();
float inv_det = 1.0f / det;
Vector3 T = _ray.origin - p1;
float u = (T % P) * inv_det;
if (u < 0.f || u > 1.f)
return boost::optional<Intersection>();
Vector3 Q = T & e1;
float v = (_ray.direction % Q) * inv_det;
if (v < 0.f || u + v > 1.f)
return boost::optional<Intersection>();
float t = (e2 % Q) * inv_det;
if(t > 0.0f && t < _best)
{
Intersection intersection;
intersection.t = t;
intersection.point = _ray(t);
intersection.node = this;
boost::optional<Intersection> result(intersection);
return result;
}
return boost::optional<Intersection>();
}
void
Triangle::complete_intersection (Intersection *_intersection)
{
_intersection->normal = normal;
}
void
Triangle::dump (const char *_name, unsigned int _level)
{
std::cout << std::string(' ', _level*2) << _name << " = Triangle" <<
std::endl;
p1.dump("p1", _level+1);
p2.dump("p2", _level+1);
p3.dump("p3", _level+1);
}
}
<commit_msg>Bounding box computation for Triangle<commit_after>#include "node/solid/triangle.h"
namespace Svit
{
Triangle::Triangle (Point3 _p1, Point3 _p2, Point3 _p3)
: p1(_p1), p2(_p2), p3(_p3)
{
p1.w = 0.0f;
p2.w = 0.0f;
p3.w = 0.0f;
e1 = p2 - p1;
e2 = p3 - p1;
normal = ~(~e1 & ~e2);
bounding_box.extend(_p1);
bounding_box.extend(_p2);
bounding_box.extend(_p3);
}
boost::optional<Intersection>
Triangle::intersect (Ray& _ray, float _best)
{
Vector3 P = _ray.direction & e2;
float det = e1 % P;
if (det == 0.0f)
return boost::optional<Intersection>();
float inv_det = 1.0f / det;
Vector3 T = _ray.origin - p1;
float u = (T % P) * inv_det;
if (u < 0.f || u > 1.f)
return boost::optional<Intersection>();
Vector3 Q = T & e1;
float v = (_ray.direction % Q) * inv_det;
if (v < 0.f || u + v > 1.f)
return boost::optional<Intersection>();
float t = (e2 % Q) * inv_det;
if(t > 0.0f && t < _best)
{
Intersection intersection;
intersection.t = t;
intersection.point = _ray(t);
intersection.node = this;
boost::optional<Intersection> result(intersection);
return result;
}
return boost::optional<Intersection>();
}
void
Triangle::complete_intersection (Intersection *_intersection)
{
_intersection->normal = normal;
}
void
Triangle::dump (const char *_name, unsigned int _level)
{
std::cout << std::string(' ', _level*2) << _name << " = Triangle" <<
std::endl;
p1.dump("p1", _level+1);
p2.dump("p2", _level+1);
p3.dump("p3", _level+1);
}
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "core/math.h"
using namespace narukami;
TEST(math,rcp){
EXPECT_FLOAT_EQ(rcp(2.0f),0.5f);
EXPECT_FLOAT_EQ(rcp(3.0f),1.0f/3.0f);
EXPECT_FLOAT_EQ(rcp(5.0f),1.0f/5.0f);
EXPECT_FLOAT_EQ(rcp(7.0f),1.0f/7.0f);
}
TEST(math,isnan){
float x=0.0f/0.0f;
EXPECT_TRUE(isnan(x));
x=1.0f/0.0f;
EXPECT_FALSE(isnan(x));
}
TEST(math,isinf){
float x=0.0f/0.0f;
EXPECT_FALSE(isinf(x));
x=1.0f/0.0f;
EXPECT_TRUE(isinf(x));
}
TEST(math,cast_i2f){
int x=1<<23;
float y=cast_i2f(x);
EXPECT_EQ(cast_f2i(y),x);
}
TEST(math,min){
float x=10;
float y=20;
float z=30;
float w=5;
EXPECT_FLOAT_EQ(min(x,y),10);
EXPECT_FLOAT_EQ(min(x,y,z),10);
EXPECT_FLOAT_EQ(min(x,y,z,w),5);
}
TEST(math,max){
float x=10;
float y=20;
float z=30;
float w=5;
EXPECT_FLOAT_EQ(max(x,y),20);
EXPECT_FLOAT_EQ(max(x,y,z),30);
EXPECT_FLOAT_EQ(max(x,y,z,w),30);
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc,argv);
auto ret = RUN_ALL_TESTS();
return ret;
}
<commit_msg>update test<commit_after>#include "gtest/gtest.h"
#include "core/math.h"
using namespace narukami;
TEST(math,rcp){
EXPECT_FLOAT_EQ(rcp(2.0f),0.5f);
EXPECT_FLOAT_EQ(rcp(3.0f),1.0f/3.0f);
EXPECT_FLOAT_EQ(rcp(5.0f),1.0f/5.0f);
EXPECT_FLOAT_EQ(rcp(7.0f),1.0f/7.0f);
}
TEST(math,isnan){
float x=0.0f/0.0f;
EXPECT_TRUE(isnan(x));
x=1.0f/0.0f;
EXPECT_FALSE(isnan(x));
}
TEST(math,isinf){
float x=0.0f/0.0f;
EXPECT_FALSE(isinf(x));
x=1.0f/0.0f;
EXPECT_TRUE(isinf(x));
}
TEST(math,cast_i2f){
int x=1<<23;
float y=cast_i2f(x);
EXPECT_EQ(cast_f2i(y),x);
}
TEST(math,min){
float x=10;
float y=20;
float z=30;
float w=5;
EXPECT_FLOAT_EQ(min(x,y),10);
EXPECT_FLOAT_EQ(min(x,y,z),10);
EXPECT_FLOAT_EQ(min(x,y,z,w),5);
}
TEST(math,max){
float x=10;
float y=20;
float z=30;
float w=5;
EXPECT_FLOAT_EQ(max(x,y),20);
EXPECT_FLOAT_EQ(max(x,y,z),30);
EXPECT_FLOAT_EQ(max(x,y,z,w),30);
}
TEST(math,deg2rad){
float deg=180;
float rad=deg2rad(deg);
EXPECT_FLOAT_EQ(rad,3.1415927f);
}
TEST(math,rad2deg){
float rad=3.1415927f;
float deg=rad2deg(rad);
EXPECT_FLOAT_EQ(deg,180);
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc,argv);
auto ret = RUN_ALL_TESTS();
return ret;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "Completer.hpp"
int main()
{
tc::Completer complete;
complete.add("hello");
complete.add("helli");
complete.add("helloworld");
complete.add("hi");
complete.add("hellb");
complete.add("helz");
complete.add("greg");
auto ret = complete.complete("hel");
for(auto& s : ret)
std::cout << s << '\n';
std::cout << '\n';
std::cin.ignore();
return 0;
}
<commit_msg>Updated test to have more words.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include "../lib/Completer.hpp"
std::vector<std::string> readFile(const std::string& file);
int main()
{
tc::Completer complete;
auto contents = readFile("text.txt");
complete.add(contents);
std::string input = "\0";
while(true)
{
std::cout << ": ";
std::cin >> input;
if(input == "!x")
break;
auto start = std::chrono::high_resolution_clock::now().time_since_epoch();
auto ret = complete.complete(input);
auto end = std::chrono::high_resolution_clock::now().time_since_epoch();
for(auto& s : ret)
std::cout << s << '\n';
std::cout << "time to complete: " << (end - start).count() / 1000000.0 << "ms\n\n";
}
return 0;
}
std::vector<std::string> readFile(const std::string& file)
{
std::ifstream fin;
fin.open("text.txt");
if(!fin)
return {};
std::vector<std::string> contents;
std::string in;
while(fin >> in)
contents.push_back(in);
return contents;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief NES Emulator クラス @n
操作説明: @n
「1」: SELECT @n
「2」: START @n
「Z」: A-BUTTON @n
「X」: B-BUTTON @n
「↑」: UP-DIR @n
「↓」: DOWN-DIR @n
「→」: RIGHT-DIR @n
「←」: LEFT-DIR @n
「F1」: Filer @n
「F4」: Log Terminal @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "main.hpp"
#include "utils/i_scene.hpp"
#include "utils/director.hpp"
#include "widgets/widget.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_terminal.hpp"
#include "widgets/widget_filer.hpp"
#include "gl_fw/gltexfb.hpp"
#include "snd_io/pcm.hpp"
#include "utils/fifo.hpp"
extern "C" {
#include "nes.h"
#include "nesinput.h"
extern const rgb_t* get_palette();
};
namespace app {
class nesemu : public utils::i_scene {
utils::director<core>& director_;
gui::widget_frame* terminal_frame_;
gui::widget_terminal* terminal_core_;
bool terminal_;
gui::widget_filer* filer_;
gl::texfb texfb_;
static const int nes_width_ = 256;
static const int nes_height_ = 240;
static const int sample_rate_ = 44100;
static const int audio_len_ = sample_rate_ / 60;
static const int audio_queue_ = 1024;
nes_t* nes_;
bool rom_active_;
typedef utils::fifo<int16_t, audio_queue_ * 16> fifo;
fifo fifo_;
al::audio audio_;
uint8_t fb_[nes_width_ * nes_height_ * 4];
nesinput_t inp_[2];
void pad_()
{
gl::core& core = gl::core::get_instance();
const gl::device& dev = core.get_device();
inp_[0].data = 0;
inp_[1].data = 0;
// A
if(dev.get_level(gl::device::key::Z)) {
inp_[0].data |= INP_PAD_A;
}
if(dev.get_level(gl::device::key::GAME_0)) {
inp_[0].data |= INP_PAD_A;
}
// B
if(dev.get_level(gl::device::key::X)) {
inp_[0].data |= INP_PAD_B;
}
if(dev.get_level(gl::device::key::GAME_1)) {
inp_[0].data |= INP_PAD_B;
}
// SELECT
if(dev.get_level(gl::device::key::_1)) {
inp_[0].data |= INP_PAD_SELECT;
}
if(dev.get_level(gl::device::key::GAME_2)) {
inp_[0].data |= INP_PAD_SELECT;
}
// START
if(dev.get_level(gl::device::key::_2)) {
inp_[0].data |= INP_PAD_START;
}
if(dev.get_level(gl::device::key::GAME_3)) {
inp_[0].data |= INP_PAD_START;
}
if(dev.get_level(gl::device::key::LEFT)) {
inp_[0].data |= INP_PAD_LEFT;
}
if(dev.get_level(gl::device::key::GAME_LEFT)) {
inp_[0].data |= INP_PAD_LEFT;
}
if(dev.get_level(gl::device::key::RIGHT)) {
inp_[0].data |= INP_PAD_RIGHT;
}
if(dev.get_level(gl::device::key::GAME_RIGHT)) {
inp_[0].data |= INP_PAD_RIGHT;
}
if(dev.get_level(gl::device::key::UP)) {
inp_[0].data |= INP_PAD_UP;
}
if(dev.get_level(gl::device::key::GAME_UP)) {
inp_[0].data |= INP_PAD_UP;
}
if(dev.get_level(gl::device::key::DOWN)) {
inp_[0].data |= INP_PAD_DOWN;
}
if(dev.get_level(gl::device::key::GAME_DOWN)) {
inp_[0].data |= INP_PAD_DOWN;
}
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
nesemu(utils::director<core>& d) : director_(d),
terminal_frame_(nullptr), terminal_core_(nullptr), terminal_(false),
nes_(nullptr), rom_active_(false)
{ }
//-----------------------------------------------------------------//
/*!
@brief デストラクター
*/
//-----------------------------------------------------------------//
virtual ~nesemu() { }
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void initialize()
{
gl::core& core = gl::core::get_instance();
using namespace gui;
widget_director& wd = director_.at().widget_director_;
{ // ターミナル
{
widget::param wp(vtx::irect(10, 10, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(15);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
terminal_frame_->enable(terminal_);
}
{
widget::param wp(vtx::irect(0), terminal_frame_);
widget_terminal::param wp_;
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
}
}
{ // ファイラー
widget::param wp(vtx::irect(10, 10, 200, 200));
widget_filer::param wp_(core.get_current_path(), "", true);
wp_.select_file_func_ = [this](const std::string& fn) {
if(nes_insertcart(fn.c_str(), nes_) == 0) {
rom_active_ = true;
} else {
//
}
};
filer_ = wd.add_widget<widget_filer>(wp, wp_);
filer_->enable(false);
}
texfb_.initialize(nes_width_, nes_height_, 32);
nes_ = nes_create(sample_rate_, 16);
// regist input
inp_[0].type = INP_JOYPAD0;
inp_[0].data = 0;
input_register(&inp_[0]);
inp_[1].type = INP_JOYPAD1;
inp_[1].data = 0;
input_register(&inp_[1]);
audio_ = al::create_audio(al::audio_format::PCM16_MONO);
audio_->create(sample_rate_, audio_queue_);
// auto path = core.get_current_path();
// path += "/GALAXIAN.NES";
// path += "/Zombie.nes";
// path += "/DRAGONQ1.NES";
// path += "/DRAGONW2.NES";
// path += "/SOLSTICE.NES";
// path += "/GRADIUS.NES";
// nes_insertcart(path.c_str(), nes_);
// プリファレンスの取得
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->load(pre);
}
if(terminal_frame_) {
terminal_frame_->load(pre);
}
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void update()
{
gl::core& core = gl::core::get_instance();
const gl::device& dev = core.get_device();
if(dev.get_negative(gl::device::key::F1)) {
filer_->enable(!filer_->get_enable());
}
if(dev.get_negative(gl::device::key::F5)) {
terminal_ = !terminal_;
terminal_frame_->enable(terminal_);
}
gui::widget_director& wd = director_.at().widget_director_;
if(nes_ != nullptr && rom_active_) {
pad_();
nes_emulate(1);
// copy sound
int16_t tmp[audio_len_];
apu_process(tmp, audio_len_);
for(int i = 0; i < audio_len_; ++i) {
fifo_.put(tmp[i]);
}
if(fifo_.length() >= (audio_queue_ * 2) && audio_) {
al::sound& sound = director_.at().sound_;
for(int i = 0; i < audio_queue_; ++i) {
al::pcm16_m w(fifo_.get());
audio_->put(i, w);
}
sound.queue_audio(audio_);
}
// copy video
bitmap_t* v = nes_->vidbuf;
const rgb_t* lut = get_palette();
if(v != nullptr && lut != nullptr) {
for(int h = 0; h < nes_height_; ++h) {
const uint8_t* src = &v->data[h * v->pitch];
uint8_t* dst = &fb_[h * nes_width_ * 4];
for(int w = 0; w < nes_width_; ++w) {
auto idx = *src++;
idx &= 63;
*dst++ = lut[idx].r; // R
*dst++ = lut[idx].g; // G
*dst++ = lut[idx].b; // B
*dst++ = 255; // alpha
}
}
texfb_.rendering(gl::texfb::image::RGBA, (const char*)&fb_[0]);
}
}
texfb_.flip();
wd.update();
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
*/
//-----------------------------------------------------------------//
void render()
{
gl::core& core = gl::core::get_instance();
const vtx::spos& siz = core.get_rect().size;
texfb_.setup_matrix(0, 0, siz.x, siz.y);
float scale = 1.0f;
float ofsx = 0.0f;
float ofsy = 0.0f;
if(siz.x < siz.y) {
scale = static_cast<float>(siz.x) / static_cast<float>(nes_width_);
float h = static_cast<float>(nes_height_);
ofsy = (static_cast<float>(siz.y) - h * scale) * 0.5f;
} else {
scale = static_cast<float>(siz.y) / static_cast<float>(nes_height_);
float w = static_cast<float>(nes_width_);
ofsx = (static_cast<float>(siz.x) - w * scale) * 0.5f;
}
gl::glTranslate(ofsx, ofsy);
gl::glScale(scale);
texfb_.draw();
director_.at().widget_director_.service();
director_.at().widget_director_.render();
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void destroy()
{
nes_destroy(nes_);
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->save(pre);
}
if(terminal_frame_) {
terminal_frame_->save(pre);
}
}
};
}
<commit_msg>update filer setting<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief NES Emulator クラス @n
操作説明: @n
「1」: SELECT @n
「2」: START @n
「Z」: A-BUTTON @n
「X」: B-BUTTON @n
「↑」: UP-DIR @n
「↓」: DOWN-DIR @n
「→」: RIGHT-DIR @n
「←」: LEFT-DIR @n
「F1」: Filer @n
「F4」: Log Terminal @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "main.hpp"
#include "utils/i_scene.hpp"
#include "utils/director.hpp"
#include "widgets/widget.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_terminal.hpp"
#include "widgets/widget_filer.hpp"
#include "gl_fw/gltexfb.hpp"
#include "snd_io/pcm.hpp"
#include "utils/fifo.hpp"
extern "C" {
#include "nes.h"
#include "nesinput.h"
extern const rgb_t* get_palette();
};
namespace app {
class nesemu : public utils::i_scene {
utils::director<core>& director_;
gui::widget_frame* terminal_frame_;
gui::widget_terminal* terminal_core_;
bool terminal_;
gui::widget_filer* filer_;
gl::texfb texfb_;
static const int nes_width_ = 256;
static const int nes_height_ = 240;
static const int sample_rate_ = 44100;
static const int audio_len_ = sample_rate_ / 60;
static const int audio_queue_ = 1024;
nes_t* nes_;
bool rom_active_;
typedef utils::fifo<int16_t, audio_queue_ * 16> fifo;
fifo fifo_;
al::audio audio_;
uint8_t fb_[nes_width_ * nes_height_ * 4];
nesinput_t inp_[2];
void pad_()
{
gl::core& core = gl::core::get_instance();
const gl::device& dev = core.get_device();
inp_[0].data = 0;
inp_[1].data = 0;
// A
if(dev.get_level(gl::device::key::Z)) {
inp_[0].data |= INP_PAD_A;
}
if(dev.get_level(gl::device::key::GAME_0)) {
inp_[0].data |= INP_PAD_A;
}
// B
if(dev.get_level(gl::device::key::X)) {
inp_[0].data |= INP_PAD_B;
}
if(dev.get_level(gl::device::key::GAME_1)) {
inp_[0].data |= INP_PAD_B;
}
// SELECT
if(dev.get_level(gl::device::key::_1)) {
inp_[0].data |= INP_PAD_SELECT;
}
if(dev.get_level(gl::device::key::GAME_2)) {
inp_[0].data |= INP_PAD_SELECT;
}
// START
if(dev.get_level(gl::device::key::_2)) {
inp_[0].data |= INP_PAD_START;
}
if(dev.get_level(gl::device::key::GAME_3)) {
inp_[0].data |= INP_PAD_START;
}
if(dev.get_level(gl::device::key::LEFT)) {
inp_[0].data |= INP_PAD_LEFT;
}
if(dev.get_level(gl::device::key::GAME_LEFT)) {
inp_[0].data |= INP_PAD_LEFT;
}
if(dev.get_level(gl::device::key::RIGHT)) {
inp_[0].data |= INP_PAD_RIGHT;
}
if(dev.get_level(gl::device::key::GAME_RIGHT)) {
inp_[0].data |= INP_PAD_RIGHT;
}
if(dev.get_level(gl::device::key::UP)) {
inp_[0].data |= INP_PAD_UP;
}
if(dev.get_level(gl::device::key::GAME_UP)) {
inp_[0].data |= INP_PAD_UP;
}
if(dev.get_level(gl::device::key::DOWN)) {
inp_[0].data |= INP_PAD_DOWN;
}
if(dev.get_level(gl::device::key::GAME_DOWN)) {
inp_[0].data |= INP_PAD_DOWN;
}
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
nesemu(utils::director<core>& d) : director_(d),
terminal_frame_(nullptr), terminal_core_(nullptr), terminal_(false),
nes_(nullptr), rom_active_(false)
{ }
//-----------------------------------------------------------------//
/*!
@brief デストラクター
*/
//-----------------------------------------------------------------//
virtual ~nesemu() { }
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void initialize()
{
gl::core& core = gl::core::get_instance();
using namespace gui;
widget_director& wd = director_.at().widget_director_;
{ // ターミナル
{
widget::param wp(vtx::irect(10, 10, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(15);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
terminal_frame_->enable(terminal_);
}
{
widget::param wp(vtx::irect(0), terminal_frame_);
widget_terminal::param wp_;
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
}
}
{ // ファイラー
widget::param wp(vtx::irect(10, 10, 200, 200));
widget_filer::param wp_(core.get_current_path(), "");
wp_.select_file_func_ = [this](const std::string& fn) {
if(nes_insertcart(fn.c_str(), nes_) == 0) {
rom_active_ = true;
} else {
//
}
};
filer_ = wd.add_widget<widget_filer>(wp, wp_);
filer_->enable(false);
}
texfb_.initialize(nes_width_, nes_height_, 32);
nes_ = nes_create(sample_rate_, 16);
// regist input
inp_[0].type = INP_JOYPAD0;
inp_[0].data = 0;
input_register(&inp_[0]);
inp_[1].type = INP_JOYPAD1;
inp_[1].data = 0;
input_register(&inp_[1]);
audio_ = al::create_audio(al::audio_format::PCM16_MONO);
audio_->create(sample_rate_, audio_queue_);
// auto path = core.get_current_path();
// path += "/GALAXIAN.NES";
// path += "/Zombie.nes";
// path += "/DRAGONQ1.NES";
// path += "/DRAGONW2.NES";
// path += "/SOLSTICE.NES";
// path += "/GRADIUS.NES";
// nes_insertcart(path.c_str(), nes_);
// プリファレンスの取得
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->load(pre);
}
if(terminal_frame_) {
terminal_frame_->load(pre);
}
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void update()
{
gl::core& core = gl::core::get_instance();
const gl::device& dev = core.get_device();
if(dev.get_negative(gl::device::key::F1)) {
filer_->enable(!filer_->get_enable());
}
if(dev.get_negative(gl::device::key::F5)) {
terminal_ = !terminal_;
terminal_frame_->enable(terminal_);
}
gui::widget_director& wd = director_.at().widget_director_;
if(nes_ != nullptr && rom_active_) {
pad_();
nes_emulate(1);
// copy sound
int16_t tmp[audio_len_];
apu_process(tmp, audio_len_);
for(int i = 0; i < audio_len_; ++i) {
fifo_.put(tmp[i]);
}
if(fifo_.length() >= (audio_queue_ * 2) && audio_) {
al::sound& sound = director_.at().sound_;
for(int i = 0; i < audio_queue_; ++i) {
al::pcm16_m w(fifo_.get());
audio_->put(i, w);
}
sound.queue_audio(audio_);
}
// copy video
bitmap_t* v = nes_->vidbuf;
const rgb_t* lut = get_palette();
if(v != nullptr && lut != nullptr) {
for(int h = 0; h < nes_height_; ++h) {
const uint8_t* src = &v->data[h * v->pitch];
uint8_t* dst = &fb_[h * nes_width_ * 4];
for(int w = 0; w < nes_width_; ++w) {
auto idx = *src++;
idx &= 63;
*dst++ = lut[idx].r; // R
*dst++ = lut[idx].g; // G
*dst++ = lut[idx].b; // B
*dst++ = 255; // alpha
}
}
texfb_.rendering(gl::texfb::image::RGBA, (const char*)&fb_[0]);
}
}
texfb_.flip();
wd.update();
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
*/
//-----------------------------------------------------------------//
void render()
{
gl::core& core = gl::core::get_instance();
const vtx::spos& siz = core.get_rect().size;
texfb_.setup_matrix(0, 0, siz.x, siz.y);
float scale = 1.0f;
float ofsx = 0.0f;
float ofsy = 0.0f;
if(siz.x < siz.y) {
scale = static_cast<float>(siz.x) / static_cast<float>(nes_width_);
float h = static_cast<float>(nes_height_);
ofsy = (static_cast<float>(siz.y) - h * scale) * 0.5f;
} else {
scale = static_cast<float>(siz.y) / static_cast<float>(nes_height_);
float w = static_cast<float>(nes_width_);
ofsx = (static_cast<float>(siz.x) - w * scale) * 0.5f;
}
gl::glTranslate(ofsx, ofsy);
gl::glScale(scale);
texfb_.draw();
director_.at().widget_director_.service();
director_.at().widget_director_.render();
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void destroy()
{
nes_destroy(nes_);
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->save(pre);
}
if(terminal_frame_) {
terminal_frame_->save(pre);
}
}
};
}
<|endoftext|> |
<commit_before>// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org/>
#include "utest.h"
#ifdef _MSC_VER
#pragma warning(push)
// disable 'conditional expression is constant' - our examples below use this!
#pragma warning(disable : 4127)
#endif
UTEST(cpp, ASSERT_TRUE) { ASSERT_TRUE(1); }
UTEST(cpp, ASSERT_FALSE) { ASSERT_FALSE(0); }
UTEST(cpp, ASSERT_EQ) { ASSERT_EQ(1, 1); }
UTEST(cpp, ASSERT_NE) { ASSERT_NE(1, 2); }
UTEST(cpp, ASSERT_LT) { ASSERT_LT(1, 2); }
UTEST(cpp, ASSERT_LE) {
ASSERT_LE(1, 1);
ASSERT_LE(1, 2);
}
UTEST(cpp, ASSERT_GT) { ASSERT_GT(2, 1); }
UTEST(cpp, ASSERT_GE) {
ASSERT_GE(1, 1);
ASSERT_GE(2, 1);
}
UTEST(c, ASSERT_STREQ) { ASSERT_STREQ("foo", "foo"); }
UTEST(c, ASSERT_STRNE) { ASSERT_STRNE("foo", "bar"); }
UTEST(cpp, EXPECT_TRUE) { EXPECT_TRUE(1); }
UTEST(cpp, EXPECT_FALSE) { EXPECT_FALSE(0); }
UTEST(cpp, EXPECT_EQ) { EXPECT_EQ(1, 1); }
UTEST(cpp, EXPECT_NE) { EXPECT_NE(1, 2); }
UTEST(cpp, EXPECT_LT) { EXPECT_LT(1, 2); }
UTEST(cpp, EXPECT_LE) {
EXPECT_LE(1, 1);
EXPECT_LE(1, 2);
}
UTEST(cpp, EXPECT_GT) { EXPECT_GT(2, 1); }
UTEST(cpp, EXPECT_GE) {
EXPECT_GE(1, 1);
EXPECT_GE(2, 1);
}
UTEST(c, EXPECT_STREQ) { EXPECT_STREQ("foo", "foo"); }
UTEST(c, EXPECT_STRNE) { EXPECT_STRNE("foo", "bar"); }
struct MyTestF {
int foo;
};
UTEST_F_SETUP(MyTestF) {
ASSERT_EQ(0, utest_fixture->foo);
utest_fixture->foo = 42;
}
UTEST_F_TEARDOWN(MyTestF) {
ASSERT_EQ(13, utest_fixture->foo);
}
UTEST_F(MyTestF, cpp) {
ASSERT_EQ(42, utest_fixture->foo);
utest_fixture->foo = 13;
}
UTEST_F(MyTestF, cpp2) {
ASSERT_EQ(42, utest_fixture->foo);
utest_fixture->foo = 13;
}
struct MyTestI {
size_t foo;
size_t bar;
};
UTEST_I_SETUP(MyTestI) {
ASSERT_EQ(0, utest_fixture->foo);
ASSERT_EQ(0, utest_fixture->bar);
utest_fixture->foo = 42;
utest_fixture->bar = utest_index;
}
UTEST_I_TEARDOWN(MyTestI) {
ASSERT_EQ(13, utest_fixture->foo);
ASSERT_EQ(utest_index, utest_fixture->bar);
}
UTEST_I(MyTestI, cpp, 2) {
ASSERT_GT(2, utest_fixture->bar);
utest_fixture->foo = 13;
}
UTEST_I(MyTestI, cpp2, 128) {
ASSERT_GT(128, utest_fixture->bar);
utest_fixture->foo = 13;
}
<commit_msg>MR: Remove spurious pragma warning push.@<commit_after>// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org/>
#include "utest.h"
#ifdef _MSC_VER
// disable 'conditional expression is constant' - our examples below use this!
#pragma warning(disable : 4127)
#endif
UTEST(cpp, ASSERT_TRUE) { ASSERT_TRUE(1); }
UTEST(cpp, ASSERT_FALSE) { ASSERT_FALSE(0); }
UTEST(cpp, ASSERT_EQ) { ASSERT_EQ(1, 1); }
UTEST(cpp, ASSERT_NE) { ASSERT_NE(1, 2); }
UTEST(cpp, ASSERT_LT) { ASSERT_LT(1, 2); }
UTEST(cpp, ASSERT_LE) {
ASSERT_LE(1, 1);
ASSERT_LE(1, 2);
}
UTEST(cpp, ASSERT_GT) { ASSERT_GT(2, 1); }
UTEST(cpp, ASSERT_GE) {
ASSERT_GE(1, 1);
ASSERT_GE(2, 1);
}
UTEST(c, ASSERT_STREQ) { ASSERT_STREQ("foo", "foo"); }
UTEST(c, ASSERT_STRNE) { ASSERT_STRNE("foo", "bar"); }
UTEST(cpp, EXPECT_TRUE) { EXPECT_TRUE(1); }
UTEST(cpp, EXPECT_FALSE) { EXPECT_FALSE(0); }
UTEST(cpp, EXPECT_EQ) { EXPECT_EQ(1, 1); }
UTEST(cpp, EXPECT_NE) { EXPECT_NE(1, 2); }
UTEST(cpp, EXPECT_LT) { EXPECT_LT(1, 2); }
UTEST(cpp, EXPECT_LE) {
EXPECT_LE(1, 1);
EXPECT_LE(1, 2);
}
UTEST(cpp, EXPECT_GT) { EXPECT_GT(2, 1); }
UTEST(cpp, EXPECT_GE) {
EXPECT_GE(1, 1);
EXPECT_GE(2, 1);
}
UTEST(c, EXPECT_STREQ) { EXPECT_STREQ("foo", "foo"); }
UTEST(c, EXPECT_STRNE) { EXPECT_STRNE("foo", "bar"); }
struct MyTestF {
int foo;
};
UTEST_F_SETUP(MyTestF) {
ASSERT_EQ(0, utest_fixture->foo);
utest_fixture->foo = 42;
}
UTEST_F_TEARDOWN(MyTestF) {
ASSERT_EQ(13, utest_fixture->foo);
}
UTEST_F(MyTestF, cpp) {
ASSERT_EQ(42, utest_fixture->foo);
utest_fixture->foo = 13;
}
UTEST_F(MyTestF, cpp2) {
ASSERT_EQ(42, utest_fixture->foo);
utest_fixture->foo = 13;
}
struct MyTestI {
size_t foo;
size_t bar;
};
UTEST_I_SETUP(MyTestI) {
ASSERT_EQ(0, utest_fixture->foo);
ASSERT_EQ(0, utest_fixture->bar);
utest_fixture->foo = 42;
utest_fixture->bar = utest_index;
}
UTEST_I_TEARDOWN(MyTestI) {
ASSERT_EQ(13, utest_fixture->foo);
ASSERT_EQ(utest_index, utest_fixture->bar);
}
UTEST_I(MyTestI, cpp, 2) {
ASSERT_GT(2, utest_fixture->bar);
utest_fixture->foo = 13;
}
UTEST_I(MyTestI, cpp2, 128) {
ASSERT_GT(128, utest_fixture->bar);
utest_fixture->foo = 13;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
#include <../bindings/python/JointPython.h>
#include <Tests_adapters.hpp>
#include <test/core/Tests.hpp>
using namespace test;
test::TestEngine g_engine;
class Tests
{
private:
joint::Module _module;
public:
Tests(joint::Module module)
: _module(std::move(module))
{ }
void RunBasicTests()
{
ScopedTest t(g_engine, "Basic tests");
joint::Ptr<IBasicTests> basic = _module.GetRootObject<IBasicTests>("GetBasicTests");
TEST_THROWS_ANYTHING(basic->Throw());
TEST_THROWS_NOTHING(basic->ReturnI32());
TEST_EQUALS(14, basic->AddI32(2, 12));
}
};
int main()
{
try
{
Joint_SetLogLevel(JOINT_LOGLEVEL_WARNING);
JOINT_CALL( JointPython_Register() );
Tests t(joint::Module("python", "Tests"));
t.RunBasicTests();
JOINT_CALL( JointPython_Unregister() );
}
catch (const std::exception& ex)
{
std::cerr << "Uncaught exception: " << ex.what() << std::endl;
return 1;
}
return 0;
}
<commit_msg>Fixed a memory corruption in test<commit_after>#include <iostream>
#include <memory>
#include <../bindings/python/JointPython.h>
#include <Tests_adapters.hpp>
#include <test/core/Tests.hpp>
using namespace test;
test::TestEngine g_engine;
class Tests
{
private:
joint::Module _module;
public:
Tests(joint::Module module)
: _module(std::move(module))
{ }
void RunBasicTests()
{
ScopedTest t(g_engine, "Basic tests");
joint::Ptr<IBasicTests> basic = _module.GetRootObject<IBasicTests>("GetBasicTests");
TEST_THROWS_ANYTHING(basic->Throw());
TEST_THROWS_NOTHING(basic->ReturnI32());
TEST_EQUALS(14, basic->AddI32(2, 12));
}
};
int main()
{
try
{
Joint_SetLogLevel(JOINT_LOGLEVEL_WARNING);
JOINT_CALL( JointPython_Register() );
{
Tests t(joint::Module("python", "Tests"));
t.RunBasicTests();
}
JOINT_CALL( JointPython_Unregister() );
}
catch (const std::exception& ex)
{
std::cerr << "Uncaught exception: " << ex.what() << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright 2012-2016 Masanori Morise. All Rights Reserved.
// Author: mmorise [at] yamanashi.ac.jp (Masanori Morise)
//
// Test program for WORLD 0.1.2 (2012/08/19)
// Test program for WORLD 0.1.3 (2013/07/26)
// Test program for WORLD 0.1.4 (2014/04/29)
// Test program for WORLD 0.1.4_3 (2015/03/07)
// Test program for WORLD 0.2.0 (2015/05/29)
// Test program for WORLD 0.2.0_1 (2015/05/31)
// Test program for WORLD 0.2.0_2 (2015/06/06)
// Test program for WORLD 0.2.0_3 (2015/07/28)
// Test program for WORLD 0.2.0_4 (2015/11/15)
// Test program for WORLD in GitHub (2015/11/16-)
// Latest update: 2016/02/01
// test.exe input.wav outout.wav f0 spec
// input.wav : Input file
// output.wav : Output file
// f0 : F0 scaling (a positive number)
// spec : Formant scaling (a positive number)
//-----------------------------------------------------------------------------
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#if (defined (__WIN32__) || defined (_WIN32)) && !defined (__MINGW32__)
#include <conio.h>
#include <windows.h>
#pragma comment(lib, "winmm.lib")
#pragma warning(disable : 4996)
#endif
#if (defined (__linux__) || defined(__CYGWIN__) || defined(__APPLE__))
#include <stdint.h>
#include <sys/time.h>
#endif
// For .wav input/output functions.
#include "./audioio.h"
// WORLD core functions.
#include "./../src/d4c.h"
#include "./../src/dio.h"
#include "./../src/matlabfunctions.h"
#include "./../src/cheaptrick.h"
#include "./../src/stonemask.h"
#include "./../src/synthesis.h"
// Frame shift [msec]
#define FRAMEPERIOD 5.0
// F0_floor used for CheapTrick and D4C [Hz]
#define F0_FLOOR 71
#if (defined (__linux__) || defined(__CYGWIN__) || defined(__APPLE__))
// Linux porting section: implement timeGetTime() by gettimeofday(),
#ifndef DWORD
#define DWORD uint32_t
#endif
DWORD timeGetTime() {
struct timeval tv;
gettimeofday(&tv, NULL);
DWORD ret = static_cast<DWORD>(tv.tv_usec / 1000 + tv.tv_sec * 1000);
return ret;
}
#endif
namespace {
void DisplayInformation(double *x, int fs, int nbit, int x_length) {
printf("File information\n");
printf("Sampling : %d Hz %d Bit\n", fs, nbit);
printf("Length %d [sample]\n", x_length);
printf("Length %f [sec]\n", static_cast<double>(x_length) / fs);
}
void F0Estimation(double *x, int x_length, int fs, int f0_length,
DioOption *option, double *f0, double *time_axis) {
double *refined_f0 = new double[f0_length];
// Modification of the option
option->frame_period = FRAMEPERIOD;
// Valuable option.speed represents the ratio for downsampling.
// The signal is downsampled to fs / speed Hz.
// If you want to obtain the accurate result, speed should be set to 1.
option->speed = 1;
// You should not set option.f0_floor to under world::kFloorF0.
// If you want to analyze such low F0 speech, please change world::kFloorF0.
// Processing speed may sacrify, provided that the FFT length changes.
option->f0_floor = 71.0;
// You can give a positive real number as the threshold.
// Most strict value is 0, but almost all results are counted as unvoiced.
// The value from 0.02 to 0.2 would be reasonable.
option->allowed_range = 0.1;
printf("\nAnalysis\n");
DWORD elapsed_time = timeGetTime();
Dio(x, x_length, fs, option, time_axis, f0);
printf("DIO: %d [msec]\n", timeGetTime() - elapsed_time);
// StoneMask is carried out to improve the estimation performance.
elapsed_time = timeGetTime();
StoneMask(x, x_length, fs, time_axis, f0, f0_length, refined_f0);
printf("StoneMask: %d [msec]\n", timeGetTime() - elapsed_time);
for (int i = 0; i < f0_length; ++i) f0[i] = refined_f0[i];
delete[] refined_f0;
return;
}
void SpectralEnvelopeEstimation(double *x, int x_length, int fs,
double *time_axis, double *f0, int f0_length, CheapTrickOption *option,
double **spectrogram) {
option->q1 = -0.15; // This value may be better one for HMM speech synthesis.
DWORD elapsed_time = timeGetTime();
CheapTrick(x, x_length, fs, time_axis, f0, f0_length, option, spectrogram);
printf("CheapTrick: %d [msec]\n", timeGetTime() - elapsed_time);
}
void AperiodicityEstimation(double *x, int x_length, int fs, double *time_axis,
double *f0, int f0_length, int fft_size, D4COption *option,
double **aperiodicity) {
// D4COption option;
// InitializeD4COption(&option); // Initialize the option
DWORD elapsed_time = timeGetTime();
// option is not implemented in this version. This is for future update.
// We can use "NULL" as the argument.
D4C(x, x_length, fs, time_axis, f0, f0_length, fft_size, option,
aperiodicity);
printf("D4C: %d [msec]\n", timeGetTime() - elapsed_time);
}
void ParameterModification(int argc, char *argv[], int fs, int f0_length,
int fft_size, double *f0, double **spectrogram) {
// F0 scaling
if (argc >= 4) {
double shift = atof(argv[3]);
for (int i = 0; i < f0_length; ++i) f0[i] *= shift;
}
// Spectral stretching
if (argc >= 5) {
double ratio = atof(argv[4]);
double *freq_axis1 = new double[fft_size];
double *freq_axis2 = new double[fft_size];
double *spectrum1 = new double[fft_size];
double *spectrum2 = new double[fft_size];
for (int i = 0; i <= fft_size / 2; ++i) {
freq_axis1[i] = ratio * i / fft_size * fs;
freq_axis2[i] = static_cast<double>(i) / fft_size * fs;
}
for (int i = 0; i < f0_length; ++i) {
for (int j = 0; j <= fft_size / 2; ++j)
spectrum1[j] = log(spectrogram[i][j]);
interp1(freq_axis1, spectrum1, fft_size / 2 + 1, freq_axis2,
fft_size / 2 + 1, spectrum2);
for (int j = 0; j <= fft_size / 2; ++j)
spectrogram[i][j] = exp(spectrum2[j]);
if (ratio < 1.0) {
for (int j = static_cast<int>(fft_size / 2.0 * ratio);
j <= fft_size / 2; ++j)
spectrogram[i][j] =
spectrogram[i][static_cast<int>(fft_size / 2.0 * ratio) - 1];
}
}
delete[] spectrum1;
delete[] spectrum2;
delete[] freq_axis1;
delete[] freq_axis2;
}
}
void WaveformSynthesis(double *f0, int f0_length, double **spectrogram,
double **aperiodicity, int fft_size, double frame_period, int fs,
int y_length, double *y) {
DWORD elapsed_time;
// Synthesis by the aperiodicity
printf("\nSynthesis\n");
elapsed_time = timeGetTime();
Synthesis(f0, f0_length, spectrogram, aperiodicity,
fft_size, FRAMEPERIOD, fs, y_length, y);
printf("WORLD: %d [msec]\n", timeGetTime() - elapsed_time);
}
} // namespace
//-----------------------------------------------------------------------------
// Test program.
// test.exe input.wav outout.wav f0 spec flag
// input.wav : argv[1] Input file
// output.wav : argv[2] Output file
// f0 : argv[3] F0 scaling (a positive number)
// spec : argv[4] Formant shift (a positive number)
//-----------------------------------------------------------------------------
int main(int argc, char *argv[]) {
if (argc != 2 && argc != 3 && argc != 4 && argc != 5) {
printf("error\n");
return -2;
}
int fs, nbit, x_length;
// 2016/01/28: Important modification.
// Memory allocation is carried out in advanse.
// This is for compatibility with C language.
x_length = GetAudioLength(argv[1]);
if (x_length <= 0) {
if (x_length == 0)
printf("error: File not found.\n");
else
printf("error: The file is not .wav format.\n");
return -1;
}
double *x = new double[x_length];
// wavread() must be called after GetAudioLength().
wavread(argv[1], &fs, &nbit, x);
DisplayInformation(x, fs, nbit, x_length);
// Allocate memories
// The number of samples for F0
int f0_length = GetSamplesForDIO(fs, x_length, FRAMEPERIOD);
double *f0 = new double[f0_length];
double *time_axis = new double[f0_length];
DioOption dio_option;
InitializeDioOption(&dio_option); // Initialize the option
// F0 estimation
F0Estimation(x, x_length, fs, f0_length, &dio_option, f0, time_axis);
CheapTrickOption cheaptrick_option;
InitializeCheapTrickOption(&cheaptrick_option); // Initialize the option
// FFT size for CheapTrick and D4C
// Important notice (2016/02/01)
// You can control a parameter used for the lowest F0 in speech.
// You must not set the f0_floor to 0.
// You must not change the f0_floor after setting fft_size.
// It will cause a fatal error because fft_size indicates the infinity.
// You should check the fft_size before excucing the analysis/synthesis.
cheaptrick_option.f0_floor = F0_FLOOR;
int fft_size = GetFFTSizeForCheapTrick(fs, &cheaptrick_option);
printf("FFT_SIZE: %d [sample]\n", fft_size);
double **spectrogram = new double *[f0_length];
double **aperiodicity = new double *[f0_length];
for (int i = 0; i < f0_length; ++i) {
spectrogram[i] = new double[fft_size / 2 + 1];
aperiodicity[i] = new double[fft_size / 2 + 1];
}
// Spectral envelope estimation
SpectralEnvelopeEstimation(x, x_length, fs, time_axis, f0, f0_length,
&cheaptrick_option, spectrogram);
// Aperiodicity estimation by D4C
D4COption d4c_option;
InitializeD4COption(&d4c_option); // Initialize the option
AperiodicityEstimation(x, x_length, fs, time_axis, f0, f0_length,
fft_size, &d4c_option, aperiodicity);
// Note that F0 must not be changed until all parameters are estimated.
ParameterModification(argc, argv, fs, f0_length, fft_size, f0, spectrogram);
// The length of the output waveform
int y_length =
static_cast<int>((f0_length - 1) * FRAMEPERIOD / 1000.0 * fs) + 1;
double *y = new double[y_length];
// Synthesis
WaveformSynthesis(f0, f0_length, spectrogram, aperiodicity, fft_size,
FRAMEPERIOD, fs, y_length, y);
// Output
wavwrite(y, y_length, fs, 16, argv[2]);
printf("complete.\n");
delete[] x;
delete[] time_axis;
delete[] f0;
delete[] y;
for (int i = 0; i < f0_length; ++i) {
delete[] spectrogram[i];
delete[] aperiodicity[i];
}
delete[] spectrogram;
delete[] aperiodicity;
return 0;
}
<commit_msg>Modification (test.cpp) for more safe implementation<commit_after>//-----------------------------------------------------------------------------
// Copyright 2012-2016 Masanori Morise. All Rights Reserved.
// Author: mmorise [at] yamanashi.ac.jp (Masanori Morise)
//
// Test program for WORLD 0.1.2 (2012/08/19)
// Test program for WORLD 0.1.3 (2013/07/26)
// Test program for WORLD 0.1.4 (2014/04/29)
// Test program for WORLD 0.1.4_3 (2015/03/07)
// Test program for WORLD 0.2.0 (2015/05/29)
// Test program for WORLD 0.2.0_1 (2015/05/31)
// Test program for WORLD 0.2.0_2 (2015/06/06)
// Test program for WORLD 0.2.0_3 (2015/07/28)
// Test program for WORLD 0.2.0_4 (2015/11/15)
// Test program for WORLD in GitHub (2015/11/16-)
// Latest update: 2016/02/02
// test.exe input.wav outout.wav f0 spec
// input.wav : Input file
// output.wav : Output file
// f0 : F0 scaling (a positive number)
// spec : Formant scaling (a positive number)
//-----------------------------------------------------------------------------
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#if (defined (__WIN32__) || defined (_WIN32)) && !defined (__MINGW32__)
#include <conio.h>
#include <windows.h>
#pragma comment(lib, "winmm.lib")
#pragma warning(disable : 4996)
#endif
#if (defined (__linux__) || defined(__CYGWIN__) || defined(__APPLE__))
#include <stdint.h>
#include <sys/time.h>
#endif
// For .wav input/output functions.
#include "./audioio.h"
// WORLD core functions.
#include "./../src/d4c.h"
#include "./../src/dio.h"
#include "./../src/matlabfunctions.h"
#include "./../src/cheaptrick.h"
#include "./../src/stonemask.h"
#include "./../src/synthesis.h"
#if (defined (__linux__) || defined(__CYGWIN__) || defined(__APPLE__))
// Linux porting section: implement timeGetTime() by gettimeofday(),
#ifndef DWORD
#define DWORD uint32_t
#endif
DWORD timeGetTime() {
struct timeval tv;
gettimeofday(&tv, NULL);
DWORD ret = static_cast<DWORD>(tv.tv_usec / 1000 + tv.tv_sec * 1000);
return ret;
}
#endif
//-----------------------------------------------------------------------------
// struct for WORLD
// This struct is an option.
// Users are NOT forced to use this struct.
//-----------------------------------------------------------------------------
typedef struct {
double frame_period;
int fs;
double *f0;
double *time_axis;
int f0_length;
double **spectrogram;
double **aperiodicity;
int fft_size;
} WorldParameters;
namespace {
void DisplayInformation(int fs, int nbit, int x_length) {
printf("File information\n");
printf("Sampling : %d Hz %d Bit\n", fs, nbit);
printf("Length %d [sample]\n", x_length);
printf("Length %f [sec]\n", static_cast<double>(x_length) / fs);
}
void F0Estimation(double *x, int x_length, WorldParameters *world_parameters) {
DioOption option = {0};
InitializeDioOption(&option);
// Modification of the option
// When you You must set the same value.
// If a different value is used, you may suffer a fatal error because of a
// illegal memory access.
option.frame_period = world_parameters->frame_period;
// Valuable option.speed represents the ratio for downsampling.
// The signal is downsampled to fs / speed Hz.
// If you want to obtain the accurate result, speed should be set to 1.
option.speed = 1;
// You should not set option.f0_floor to under world::kFloorF0.
// If you want to analyze such low F0 speech, please change world::kFloorF0.
// Processing speed may sacrify, provided that the FFT length changes.
option.f0_floor = 71.0;
// You can give a positive real number as the threshold.
// Most strict value is 0, but almost all results are counted as unvoiced.
// The value from 0.02 to 0.2 would be reasonable.
option.allowed_range = 0.1;
// Parameters setting and memory allocation.
world_parameters->f0_length = GetSamplesForDIO(world_parameters->fs,
x_length, world_parameters->frame_period);
world_parameters->f0 = new double[world_parameters->f0_length];
world_parameters->time_axis = new double[world_parameters->f0_length];
double *refined_f0 = new double[world_parameters->f0_length];
printf("\nAnalysis\n");
DWORD elapsed_time = timeGetTime();
Dio(x, x_length, world_parameters->fs, &option, world_parameters->time_axis,
world_parameters->f0);
printf("DIO: %d [msec]\n", timeGetTime() - elapsed_time);
// StoneMask is carried out to improve the estimation performance.
elapsed_time = timeGetTime();
StoneMask(x, x_length, world_parameters->fs, world_parameters->time_axis,
world_parameters->f0, world_parameters->f0_length, refined_f0);
printf("StoneMask: %d [msec]\n", timeGetTime() - elapsed_time);
for (int i = 0; i < world_parameters->f0_length; ++i)
world_parameters->f0[i] = refined_f0[i];
delete[] refined_f0;
return;
}
void SpectralEnvelopeEstimation(double *x, int x_length,
WorldParameters *world_parameters) {
CheapTrickOption option = {0};
InitializeCheapTrickOption(&option);
// This value may be better one for HMM speech synthesis.
// Default value is -0.09.
option.q1 = -0.15;
// Important notice (2016/02/02)
// You can control a parameter used for the lowest F0 in speech.
// You must not set the f0_floor to 0.
// It will cause a fatal error because fft_size indicates the infinity.
// You must not change the f0_floor after memory allocation.
// You should check the fft_size before excucing the analysis/synthesis.
// The default value (71.0) is strongly recommended.
// On the other hand, setting the lowest F0 of speech is a good choice
// to reduce the fft_size.
option.f0_floor = 71.0;
// Parameters setting and memory allocation.
world_parameters->fft_size =
GetFFTSizeForCheapTrick(world_parameters->fs, &option);
world_parameters->spectrogram = new double *[world_parameters->f0_length];
for (int i = 0; i < world_parameters->f0_length; ++i) {
world_parameters->spectrogram[i] =
new double[world_parameters->fft_size / 2 + 1];
}
DWORD elapsed_time = timeGetTime();
CheapTrick(x, x_length, world_parameters->fs, world_parameters->time_axis,
world_parameters->f0, world_parameters->f0_length, &option,
world_parameters->spectrogram);
printf("CheapTrick: %d [msec]\n", timeGetTime() - elapsed_time);
}
void AperiodicityEstimation(double *x, int x_length,
WorldParameters *world_parameters) {
D4COption option = {0};
InitializeD4COption(&option);
// Parameters setting and memory allocation.
world_parameters->aperiodicity = new double *[world_parameters->f0_length];
for (int i = 0; i < world_parameters->f0_length; ++i) {
world_parameters->aperiodicity[i] =
new double[world_parameters->fft_size / 2 + 1];
}
DWORD elapsed_time = timeGetTime();
// option is not implemented in this version. This is for future update.
// We can use "NULL" as the argument.
D4C(x, x_length, world_parameters->fs, world_parameters->time_axis,
world_parameters->f0, world_parameters->f0_length,
world_parameters->fft_size, &option, world_parameters->aperiodicity);
printf("D4C: %d [msec]\n", timeGetTime() - elapsed_time);
}
void ParameterModification(int argc, char *argv[], int fs, int f0_length,
int fft_size, double *f0, double **spectrogram) {
// F0 scaling
if (argc >= 4) {
double shift = atof(argv[3]);
for (int i = 0; i < f0_length; ++i) f0[i] *= shift;
}
if (argc < 5) return;
// Spectral stretching
double ratio = atof(argv[4]);
double *freq_axis1 = new double[fft_size];
double *freq_axis2 = new double[fft_size];
double *spectrum1 = new double[fft_size];
double *spectrum2 = new double[fft_size];
for (int i = 0; i <= fft_size / 2; ++i) {
freq_axis1[i] = ratio * i / fft_size * fs;
freq_axis2[i] = static_cast<double>(i) / fft_size * fs;
}
for (int i = 0; i < f0_length; ++i) {
for (int j = 0; j <= fft_size / 2; ++j)
spectrum1[j] = log(spectrogram[i][j]);
interp1(freq_axis1, spectrum1, fft_size / 2 + 1, freq_axis2,
fft_size / 2 + 1, spectrum2);
for (int j = 0; j <= fft_size / 2; ++j)
spectrogram[i][j] = exp(spectrum2[j]);
if (ratio >= 1.0) continue;
for (int j = static_cast<int>(fft_size / 2.0 * ratio);
j <= fft_size / 2; ++j)
spectrogram[i][j] =
spectrogram[i][static_cast<int>(fft_size / 2.0 * ratio) - 1];
}
delete[] spectrum1;
delete[] spectrum2;
delete[] freq_axis1;
delete[] freq_axis2;
}
void WaveformSynthesis(WorldParameters *world_parameters, int fs,
int y_length, double *y) {
DWORD elapsed_time;
// Synthesis by the aperiodicity
printf("\nSynthesis\n");
elapsed_time = timeGetTime();
Synthesis(world_parameters->f0, world_parameters->f0_length,
world_parameters->spectrogram, world_parameters->aperiodicity,
world_parameters->fft_size, world_parameters->frame_period, fs,
y_length, y);
printf("WORLD: %d [msec]\n", timeGetTime() - elapsed_time);
}
void DestroyMemory(WorldParameters *world_parameters) {
delete[] world_parameters->time_axis;
delete[] world_parameters->f0;
for (int i = 0; i < world_parameters->f0_length; ++i) {
delete[] world_parameters->spectrogram[i];
delete[] world_parameters->aperiodicity[i];
}
delete[] world_parameters->spectrogram;
delete[] world_parameters->aperiodicity;
}
} // namespace
//-----------------------------------------------------------------------------
// Test program.
// test.exe input.wav outout.wav f0 spec flag
// input.wav : argv[1] Input file
// output.wav : argv[2] Output file
// f0 : argv[3] F0 scaling (a positive number)
// spec : argv[4] Formant shift (a positive number)
//-----------------------------------------------------------------------------
int main(int argc, char *argv[]) {
if (argc != 2 && argc != 3 && argc != 4 && argc != 5) {
printf("error\n");
return -2;
}
// 2016/01/28: Important modification.
// Memory allocation is carried out in advanse.
// This is for compatibility with C language.
int x_length = GetAudioLength(argv[1]);
if (x_length <= 0) {
if (x_length == 0)
printf("error: File not found.\n");
else
printf("error: The file is not .wav format.\n");
return -1;
}
double *x = new double[x_length];
// wavread() must be called after GetAudioLength().
int fs, nbit;
wavread(argv[1], &fs, &nbit, x);
DisplayInformation(fs, nbit, x_length);
//---------------------------------------------------------------------------
// Analysis part
//---------------------------------------------------------------------------
// 2016/02/02
// A new struct is introduced to implement safe program.
WorldParameters world_parameters = { 0 };
// You must set fs and frame_period before analysis/synthesis.
world_parameters.fs = fs;
// 5.0 ms is the default value.
// Generally, the inverse of the lowest F0 of speech is the best.
// However, the more elapsed time is required.
world_parameters.frame_period = 5.0;
// F0 estimation
F0Estimation(x, x_length, &world_parameters);
// Spectral envelope estimation
SpectralEnvelopeEstimation(x, x_length, &world_parameters);
// Aperiodicity estimation by D4C
AperiodicityEstimation(x, x_length, &world_parameters);
// Note that F0 must not be changed until all parameters are estimated.
ParameterModification(argc, argv, fs, world_parameters.f0_length,
world_parameters.fft_size, world_parameters.f0,
world_parameters.spectrogram);
//---------------------------------------------------------------------------
// Synthesis part
//---------------------------------------------------------------------------
// The length of the output waveform
int y_length = static_cast<int>((world_parameters.f0_length - 1) *
world_parameters.frame_period / 1000.0 * fs) + 1;
double *y = new double[y_length];
// Synthesis
WaveformSynthesis(&world_parameters, fs, y_length, y);
// Output
wavwrite(y, y_length, fs, 16, argv[2]);
delete[] y;
delete[] x;
DestroyMemory(&world_parameters);
printf("complete.\n");
return 0;
}
<|endoftext|> |
<commit_before>#include <stdint.h>
#ifndef __clockid_t_defined
#define __clockid_t_defined 1
typedef int32_t clockid_t;
#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 1
#define CLOCK_PROCESS_CPUTIME_ID 2
#define CLOCK_THREAD_CPUTIME_ID 3
#define CLOCK_MONOTONIC_RAW 4
#define CLOCK_REALTIME_COARSE 5
#define CLOCK_MONOTONIC_COARSE 6
#define CLOCK_BOOTTIME 7
#define CLOCK_REALTIME_ALARM 8
#define CLOCK_BOOTTIME_ALARM 9
#endif // __clockid_t_defined
#ifndef _STRUCT_TIMESPEC
#define _STRUCT_TIMESPEC
struct timespec {
long tv_sec; /* Seconds. */
long tv_nsec; /* Nanoseconds. */
};
#endif // _STRUCT_TIMESPEC
extern "C" {
extern int clock_gettime(clockid_t clk_id, struct timespec *tp);
WEAK bool halide_reference_clock_inited = false;
WEAK timespec halide_reference_clock;
WEAK int halide_start_clock() {
// Guard against multiple calls
if (!halide_reference_clock_inited) {
clock_gettime(CLOCK_REALTIME, &halide_reference_clock);
halide_reference_clock_inited = true;
}
return 0;
}
WEAK int64_t halide_current_time_ns() {
timespec now;
clock_gettime(CLOCK_REALTIME, &now);
int64_t d = int64_t(now.tv_sec - halide_reference_clock.tv_sec)*1000000000;
int64_t nd = (now.tv_nsec - halide_reference_clock.tv_nsec);
return d + nd;
}
}
<commit_msg>Made linux_clock do the syscall directly to dodge linking woes.<commit_after>#include <stdint.h>
#ifndef __clockid_t_defined
#define __clockid_t_defined 1
typedef int32_t clockid_t;
#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 1
#define CLOCK_PROCESS_CPUTIME_ID 2
#define CLOCK_THREAD_CPUTIME_ID 3
#define CLOCK_MONOTONIC_RAW 4
#define CLOCK_REALTIME_COARSE 5
#define CLOCK_MONOTONIC_COARSE 6
#define CLOCK_BOOTTIME 7
#define CLOCK_REALTIME_ALARM 8
#define CLOCK_BOOTTIME_ALARM 9
#endif // __clockid_t_defined
#ifndef _STRUCT_TIMESPEC
#define _STRUCT_TIMESPEC
struct timespec {
long tv_sec; /* Seconds. */
long tv_nsec; /* Nanoseconds. */
};
#endif // _STRUCT_TIMESPEC
// Should be safe to include these, given that we know we're on linux
// if we're compiling this file.
#include <sys/syscall.h>
#include <unistd.h>
extern "C" {
WEAK bool halide_reference_clock_inited = false;
WEAK timespec halide_reference_clock;
WEAK int halide_start_clock() {
// Guard against multiple calls
if (!halide_reference_clock_inited) {
syscall(SYS_clock_gettime, CLOCK_REALTIME, &halide_reference_clock);
halide_reference_clock_inited = true;
}
return 0;
}
WEAK int64_t halide_current_time_ns() {
timespec now;
// To avoid requiring people to link -lrt, we just make the syscall directly.
syscall(SYS_clock_gettime, CLOCK_REALTIME, &now);
int64_t d = int64_t(now.tv_sec - halide_reference_clock.tv_sec)*1000000000;
int64_t nd = (now.tv_nsec - halide_reference_clock.tv_nsec);
return d + nd;
}
}
<|endoftext|> |
<commit_before>#include "osg/Node"
#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool Node_readLocalData(Object& obj, Input& fr);
bool Node_writeLocalData(const Object& obj, Output& fw);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_NodeProxy
(
new osg::Node,
"Node",
"Object Node",
&Node_readLocalData,
&Node_writeLocalData
);
bool Node_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
Node& node = static_cast<Node&>(obj);
if (fr.matchSequence("name %s"))
{
node.setName(fr[1].getStr());
fr+=2;
iteratorAdvanced = true;
}
if (fr[0].matchWord("cullingActive"))
{
if (fr[1].matchWord("FALSE"))
{
node.setCullingActive(false);
iteratorAdvanced = true;
fr+=2;
}
else if (fr[1].matchWord("TRUE"))
{
node.setCullingActive(true);
iteratorAdvanced = true;
fr+=2;
}
}
// if (fr.matchSequence("user_data {"))
// {
// notify(DEBUG) << "Matched user_data {"<< std::endl;
// int entry = fr[0].getNoNestedBrackets();
// fr += 2;
//
// while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
// {
// Object* object = fr.readObject();
// if (object) setUserData(object);
// notify(DEBUG) << "read "<<object<< std::endl;
// ++fr;
// }
// iteratorAdvanced = true;
// }
while (fr.matchSequence("description {"))
{
int entry = fr[0].getNoNestedBrackets();
fr += 2;
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
node.addDescription(fr[0].getStr());
++fr;
}
iteratorAdvanced = true;
}
while (fr.matchSequence("description %s"))
{
node.addDescription(fr[1].getStr());
fr+=2;
iteratorAdvanced = true;
}
static ref_ptr<StateSet> s_drawstate = new osg::StateSet;
if (StateSet* readState = static_cast<StateSet*>(fr.readObjectOfType(*s_drawstate)))
{
node.setStateSet(readState);
iteratorAdvanced = true;
}
static ref_ptr<NodeCallback> s_nodecallback = new osg::NodeCallback;
while (fr.matchSequence("UpdateCallback {"))
{
int entry = fr[0].getNoNestedBrackets();
fr += 2;
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
NodeCallback* nodecallback = dynamic_cast<NodeCallback*>(fr.readObjectOfType(*s_nodecallback));
if (nodecallback) node.setUpdateCallback(nodecallback);
else ++fr;
}
iteratorAdvanced = true;
}
while (fr.matchSequence("CullCallback {"))
{
int entry = fr[0].getNoNestedBrackets();
fr += 2;
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
NodeCallback* nodecallback = dynamic_cast<NodeCallback*>(fr.readObjectOfType(*s_nodecallback));
if (nodecallback) node.setUpdateCallback(nodecallback);
else ++fr;
}
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool Node_writeLocalData(const Object& obj, Output& fw)
{
const Node& node = static_cast<const Node&>(obj);
if (!node.getName().empty()) fw.indent() << "name "<<fw.wrapString(node.getName())<< std::endl;
fw.indent() << "cullingActive ";
if (node.getCullingActive()) fw << "TRUE"<< std::endl;
else fw << "FALSE"<< std::endl;
// if (_userData)
// {
// Object* object = dynamic_cast<Object*>(_userData);
// if (object)
// {
// fw.indent() << "user_data {"<< std::endl;
// fw.moveIn();
// object->write(fw);
// fw.moveOut();
// fw.indent() << "}"<< std::endl;
// }
// }
if (!node.getDescriptions().empty())
{
if (node.getDescriptions().size()==1)
{
fw.indent() << "description "<<fw.wrapString(node.getDescriptions().front())<< std::endl;
}
else
{
fw.indent() << "description {"<< std::endl;
fw.moveIn();
for(Node::DescriptionList::const_iterator ditr=node.getDescriptions().begin();
ditr!=node.getDescriptions().end();
++ditr)
{
fw.indent() << fw.wrapString(*ditr)<< std::endl;
}
fw.moveOut();
fw.indent() << "}"<< std::endl;
}
}
if (node.getStateSet())
{
fw.writeObject(*node.getStateSet());
}
if (node.getUpdateCallback())
{
fw.indent() << "UpdateCallbacks {" << std::endl;
fw.moveIn();
fw.writeObject(*node.getUpdateCallback());
fw.moveOut();
fw.indent() << "}" << std::endl;
}
if (node.getCullCallback())
{
fw.indent() << "CullCallbacks {" << std::endl;
fw.moveIn();
fw.writeObject(*node.getCullCallback());
fw.moveOut();
fw.indent() << "}" << std::endl;
}
return true;
}
<commit_msg>Added if (!null) guard around description strings.<commit_after>#include "osg/Node"
#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool Node_readLocalData(Object& obj, Input& fr);
bool Node_writeLocalData(const Object& obj, Output& fw);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_NodeProxy
(
new osg::Node,
"Node",
"Object Node",
&Node_readLocalData,
&Node_writeLocalData
);
bool Node_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
Node& node = static_cast<Node&>(obj);
if (fr.matchSequence("name %s"))
{
node.setName(fr[1].getStr());
fr+=2;
iteratorAdvanced = true;
}
if (fr[0].matchWord("cullingActive"))
{
if (fr[1].matchWord("FALSE"))
{
node.setCullingActive(false);
iteratorAdvanced = true;
fr+=2;
}
else if (fr[1].matchWord("TRUE"))
{
node.setCullingActive(true);
iteratorAdvanced = true;
fr+=2;
}
}
// if (fr.matchSequence("user_data {"))
// {
// notify(DEBUG) << "Matched user_data {"<< std::endl;
// int entry = fr[0].getNoNestedBrackets();
// fr += 2;
//
// while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
// {
// Object* object = fr.readObject();
// if (object) setUserData(object);
// notify(DEBUG) << "read "<<object<< std::endl;
// ++fr;
// }
// iteratorAdvanced = true;
// }
while (fr.matchSequence("description {"))
{
int entry = fr[0].getNoNestedBrackets();
fr += 2;
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
if (fr[0].getStr()) node.addDescription(std::string(fr[0].getStr()));
++fr;
}
iteratorAdvanced = true;
}
while (fr.matchSequence("description %s"))
{
node.addDescription(fr[1].getStr());
fr+=2;
iteratorAdvanced = true;
}
static ref_ptr<StateSet> s_drawstate = new osg::StateSet;
if (StateSet* readState = static_cast<StateSet*>(fr.readObjectOfType(*s_drawstate)))
{
node.setStateSet(readState);
iteratorAdvanced = true;
}
static ref_ptr<NodeCallback> s_nodecallback = new osg::NodeCallback;
while (fr.matchSequence("UpdateCallback {"))
{
int entry = fr[0].getNoNestedBrackets();
fr += 2;
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
NodeCallback* nodecallback = dynamic_cast<NodeCallback*>(fr.readObjectOfType(*s_nodecallback));
if (nodecallback) node.setUpdateCallback(nodecallback);
else ++fr;
}
iteratorAdvanced = true;
}
while (fr.matchSequence("CullCallback {"))
{
int entry = fr[0].getNoNestedBrackets();
fr += 2;
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
NodeCallback* nodecallback = dynamic_cast<NodeCallback*>(fr.readObjectOfType(*s_nodecallback));
if (nodecallback) node.setUpdateCallback(nodecallback);
else ++fr;
}
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool Node_writeLocalData(const Object& obj, Output& fw)
{
const Node& node = static_cast<const Node&>(obj);
if (!node.getName().empty()) fw.indent() << "name "<<fw.wrapString(node.getName())<< std::endl;
fw.indent() << "cullingActive ";
if (node.getCullingActive()) fw << "TRUE"<< std::endl;
else fw << "FALSE"<< std::endl;
// if (_userData)
// {
// Object* object = dynamic_cast<Object*>(_userData);
// if (object)
// {
// fw.indent() << "user_data {"<< std::endl;
// fw.moveIn();
// object->write(fw);
// fw.moveOut();
// fw.indent() << "}"<< std::endl;
// }
// }
if (!node.getDescriptions().empty())
{
if (node.getDescriptions().size()==1)
{
fw.indent() << "description "<<fw.wrapString(node.getDescriptions().front())<< std::endl;
}
else
{
fw.indent() << "description {"<< std::endl;
fw.moveIn();
for(Node::DescriptionList::const_iterator ditr=node.getDescriptions().begin();
ditr!=node.getDescriptions().end();
++ditr)
{
fw.indent() << fw.wrapString(*ditr)<< std::endl;
}
fw.moveOut();
fw.indent() << "}"<< std::endl;
}
}
if (node.getStateSet())
{
fw.writeObject(*node.getStateSet());
}
if (node.getUpdateCallback())
{
fw.indent() << "UpdateCallbacks {" << std::endl;
fw.moveIn();
fw.writeObject(*node.getUpdateCallback());
fw.moveOut();
fw.indent() << "}" << std::endl;
}
if (node.getCullCallback())
{
fw.indent() << "CullCallbacks {" << std::endl;
fw.moveIn();
fw.writeObject(*node.getCullCallback());
fw.moveOut();
fw.indent() << "}" << std::endl;
}
return true;
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2018 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include "repo_file_handler_fs.h"
#include "../../model/repo_model_global.h"
#include "../../../lib/repo_log.h"
#include "../../../lib/repo_exception.h"
#include "../../../lib/repo_utils.h"
using namespace repo::core::handler::fileservice;
FSFileHandler::FSFileHandler(
const std::string &dir,
const int &nLevel) :
AbstractFileHandler(),
dirPath(dir),
level(nLevel)
{
if (!repo::lib::doesDirExist(dir)) {
throw repo::lib::RepoException("Cannot initialise fileshare: " + dir + " is does not exist/is not a directory");
}
}
/**
* A Deconstructor
*/
FSFileHandler::~FSFileHandler()
{
}
bool FSFileHandler::deleteFile(
const std::string &database,
const std::string &collection,
const std::string &keyName)
{
bool success = false;
auto fullPath = boost::filesystem::absolute(keyName, dirPath);
if (repo::lib::doesFileExist(fullPath)) {
auto fileStr = fullPath.string();
success = std::remove(fileStr.c_str()) == 0;
}
return success;
}
std::vector<std::string> FSFileHandler::determineHierachy(
const std::string &name
) const {
auto nameChunkLen = name.length() / level;
nameChunkLen = nameChunkLen < minChunkLength ? minChunkLength : nameChunkLen;
std::hash<std::string> stringHasher;
std::vector<std::string> levelNames;
for (int i = 0; i < level; ++i) {
auto chunkStart = (i * nameChunkLen) % (name.length() - nameChunkLen);
auto stringToHash = name.substr(i, nameChunkLen) + std::to_string((float)std::rand()/ RAND_MAX);
levelNames.push_back(std::to_string(stringHasher(stringToHash)));
}
return levelNames;
}
std::string FSFileHandler::uploadFile(
const std::string &database,
const std::string &collection,
const std::string &keyName,
const std::vector<uint8_t> &bin
)
{
auto hierachy = determineHierachy(keyName);
boost::filesystem::path path(dirPath);
std::stringstream ss;
for (const auto &levelName : hierachy) {
path /= levelName;
ss << levelName << "/";
if (!repo::lib::doesDirExist(path)) {
boost::filesystem::create_directories(path);
}
}
path /= keyName;
ss << keyName;
std::ofstream outs(path.string(), std::ios::out | std::ios::binary);
outs.write((char*)bin.data(), bin.size());
outs.close();
return ss.str();
}
<commit_msg>ISSUE #320 take the first 255 bits of the hashed value<commit_after>/**
* Copyright (C) 2018 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include "repo_file_handler_fs.h"
#include "../../model/repo_model_global.h"
#include "../../../lib/repo_log.h"
#include "../../../lib/repo_exception.h"
#include "../../../lib/repo_utils.h"
using namespace repo::core::handler::fileservice;
FSFileHandler::FSFileHandler(
const std::string &dir,
const int &nLevel) :
AbstractFileHandler(),
dirPath(dir),
level(nLevel)
{
if (!repo::lib::doesDirExist(dir)) {
throw repo::lib::RepoException("Cannot initialise fileshare: " + dir + " is does not exist/is not a directory");
}
}
/**
* A Deconstructor
*/
FSFileHandler::~FSFileHandler()
{
}
bool FSFileHandler::deleteFile(
const std::string &database,
const std::string &collection,
const std::string &keyName)
{
bool success = false;
auto fullPath = boost::filesystem::absolute(keyName, dirPath);
if (repo::lib::doesFileExist(fullPath)) {
auto fileStr = fullPath.string();
success = std::remove(fileStr.c_str()) == 0;
}
return success;
}
std::vector<std::string> FSFileHandler::determineHierachy(
const std::string &name
) const {
auto nameChunkLen = name.length() / level;
nameChunkLen = nameChunkLen < minChunkLength ? minChunkLength : nameChunkLen;
std::hash<std::string> stringHasher;
std::vector<std::string> levelNames;
for (int i = 0; i < level; ++i) {
auto chunkStart = (i * nameChunkLen) % (name.length() - nameChunkLen);
auto stringToHash = name.substr(i, nameChunkLen) + std::to_string((float)std::rand()/ RAND_MAX);
auto hashedValue = stringHasher(stringToHash) & 255;
levelNames.push_back(std::to_string(hashedValue));
}
return levelNames;
}
std::string FSFileHandler::uploadFile(
const std::string &database,
const std::string &collection,
const std::string &keyName,
const std::vector<uint8_t> &bin
)
{
auto hierachy = determineHierachy(keyName);
boost::filesystem::path path(dirPath);
std::stringstream ss;
for (const auto &levelName : hierachy) {
path /= levelName;
ss << levelName << "/";
if (!repo::lib::doesDirExist(path)) {
boost::filesystem::create_directories(path);
}
}
path /= keyName;
ss << keyName;
std::ofstream outs(path.string(), std::ios::out | std::ios::binary);
outs.write((char*)bin.data(), bin.size());
outs.close();
return ss.str();
}
<|endoftext|> |
<commit_before>#include "lib/output.h"
#include "lib/image.h"
#include "lib/lambertian.h"
#include "lib/range.h"
#include "lib/runtime.h"
#include "lib/triangle.h"
#include <assimp/Importer.hpp> // C++ importer interface
#include <assimp/scene.h> // Output data structure
#include <assimp/postprocess.h> // Post processing flags
#include <docopt.h>
#include <math.h>
#include <vector>
#include <map>
#include <iostream>
#include <chrono>
ssize_t ray_intersection(const aiRay& ray, const Triangles& triangles,
float& min_r, float& min_s, float& min_t) {
ssize_t triangle_index = -1;
min_r = -1;
float r, s, t;
for (size_t i = 0; i < triangles.size(); i++) {
auto intersect = triangles[i].intersect(ray, r, s, t);
if (intersect) {
if (triangle_index < 0 || r < min_r) {
min_r = r;
min_s = s;
min_t = t;
triangle_index = i;
}
}
}
return triangle_index;
}
Triangles triangles_from_scene(const aiScene* scene) {
Triangles triangles;
for (auto node : make_range(
scene->mRootNode->mChildren, scene->mRootNode->mNumChildren))
{
const auto& T = node->mTransformation;
if (node->mNumMeshes == 0) {
continue;
}
for (auto mesh_index : make_range(node->mMeshes, node->mNumMeshes)) {
const auto& mesh = *scene->mMeshes[mesh_index];
aiColor4D ambient, diffuse;
scene->mMaterials[mesh.mMaterialIndex]->Get(
AI_MATKEY_COLOR_AMBIENT, ambient);
scene->mMaterials[mesh.mMaterialIndex]->Get(
AI_MATKEY_COLOR_DIFFUSE, diffuse);
for (aiFace face : make_range(mesh.mFaces, mesh.mNumFaces)) {
assert(face.mNumIndices == 3);
triangles.push_back(Triangle{
// vertices
{{
T * mesh.mVertices[face.mIndices[0]],
T * mesh.mVertices[face.mIndices[1]],
T * mesh.mVertices[face.mIndices[2]]
}},
// normals
{{
T * mesh.mNormals[face.mIndices[0]],
T * mesh.mNormals[face.mIndices[1]],
T * mesh.mNormals[face.mIndices[2]]
}},
ambient,
diffuse
});
}
}
}
return triangles;
}
static const char USAGE[] =
R"(Usage: raytracer <filename> [options]
Options:
-w --width=<px> Width of the image [default: 640].
-a --aspect=<num> Aspect ratio of the image. If the model has
specified the aspect ratio, it will be used.
Otherwise default value is 1.
-b --background=<color> Background color of the world. [default: 0 0 0 0].
)";
int main(int argc, char const *argv[])
{
// parameters
std::map<std::string, docopt::value> args =
docopt::docopt(USAGE, {argv + 1, argv + argc}, true, "raytracer 0.2");
// import scene
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(
args["<filename>"].asString().c_str(),
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_GenNormals |
aiProcess_SortByPType);
if (!scene) {
std::cout << importer.GetErrorString() << std::endl;
return 1;
}
// setup camera
assert(scene->mNumCameras == 1); // we can deal only with a single camera
auto& sceneCam = *scene->mCameras[0];
if (args["--aspect"]) {
sceneCam.mAspect = std::stof(args["--aspect"].asString());
assert(sceneCam.mAspect > 0);
} else if (sceneCam.mAspect == 0) {
sceneCam.mAspect = 1.f;
}
auto* camNode = scene->mRootNode->FindNode(sceneCam.mName);
assert(camNode != nullptr);
const Camera cam(camNode->mTransformation, sceneCam);
std::cerr << "Camera" << std::endl;
std::cerr << cam << std::endl;
// setup light
assert(scene->mNumLights == 1); // we can deal only with a single light
auto& light = *scene->mLights[0];
std::cerr << "Light" << std::endl;
std::cerr << "Diffuse: " << light.mColorDiffuse << std::endl;
auto* lightNode = scene->mRootNode->FindNode(light.mName);
assert(lightNode != nullptr);
const auto& LT = lightNode->mTransformation;
std::cerr << "Light Trafo: " << LT << std::endl;
auto light_pos = LT * aiVector3D();
auto light_color = aiColor4D{
light.mColorDiffuse.r,
light.mColorDiffuse.g,
light.mColorDiffuse.b,
1};
// load triangles from the scene
auto triangles = triangles_from_scene(scene);
//
// Raytracer
//
int width = args["--width"].asLong();
assert(width > 0);
int height = width / cam.mAspect;
auto background_color = parse_color4(args["--background"].asString());
Image image(width, height);
{
auto rt = Runtime(std::cerr, "Rendering time: ");
float r, s, t;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
// intersection
auto cam_dir = cam.raster2cam(aiVector2D(x, y), width, height);
auto triangle_index = ray_intersection(
aiRay(cam.mPosition, cam_dir), triangles, r, s, t);
if (triangle_index < 0) {
image(x, y) = background_color;
continue;
}
// light direction
auto p = cam.mPosition + r * cam_dir;
auto light_dir = light_pos - p;
light_dir.Normalize();
// interpolate normal
const auto& triangle = triangles[triangle_index];
const auto& n0 = triangle.normals[0];
const auto& n1 = triangle.normals[1];
const auto& n2 = triangle.normals[2];
auto normal = ((1.f - s - t)*n0 + s*n1 + t*n2).Normalize();
// calculate shadow
float distance_to_next_triangle, s2, t2;
auto p2 = p + normal * 0.0001f;
float distance_to_light = (light_pos - p2).Length();
auto shadow_triangle = ray_intersection(
aiRay(p2, light_dir),
triangles,
distance_to_next_triangle, s2, t2);
if (shadow_triangle >= 0 &&
distance_to_next_triangle < distance_to_light)
{
image(x, y) = triangle.ambient;
continue;
}
image(x, y) += lambertian(
light_dir, normal, triangle.diffuse, light_color);
image(x, y) += triangle.ambient;
}
}
}
// output image
std::cout << image << std::endl;
return 0;
}
<commit_msg>Show progress bar.<commit_after>#include "lib/output.h"
#include "lib/image.h"
#include "lib/lambertian.h"
#include "lib/range.h"
#include "lib/runtime.h"
#include "lib/triangle.h"
#include <assimp/Importer.hpp> // C++ importer interface
#include <assimp/scene.h> // Output data structure
#include <assimp/postprocess.h> // Post processing flags
#include <docopt.h>
#include <math.h>
#include <vector>
#include <map>
#include <iostream>
#include <chrono>
ssize_t ray_intersection(const aiRay& ray, const Triangles& triangles,
float& min_r, float& min_s, float& min_t) {
ssize_t triangle_index = -1;
min_r = -1;
float r, s, t;
for (size_t i = 0; i < triangles.size(); i++) {
auto intersect = triangles[i].intersect(ray, r, s, t);
if (intersect) {
if (triangle_index < 0 || r < min_r) {
min_r = r;
min_s = s;
min_t = t;
triangle_index = i;
}
}
}
return triangle_index;
}
Triangles triangles_from_scene(const aiScene* scene) {
Triangles triangles;
for (auto node : make_range(
scene->mRootNode->mChildren, scene->mRootNode->mNumChildren))
{
const auto& T = node->mTransformation;
if (node->mNumMeshes == 0) {
continue;
}
for (auto mesh_index : make_range(node->mMeshes, node->mNumMeshes)) {
const auto& mesh = *scene->mMeshes[mesh_index];
aiColor4D ambient, diffuse;
scene->mMaterials[mesh.mMaterialIndex]->Get(
AI_MATKEY_COLOR_AMBIENT, ambient);
scene->mMaterials[mesh.mMaterialIndex]->Get(
AI_MATKEY_COLOR_DIFFUSE, diffuse);
for (aiFace face : make_range(mesh.mFaces, mesh.mNumFaces)) {
assert(face.mNumIndices == 3);
triangles.push_back(Triangle{
// vertices
{{
T * mesh.mVertices[face.mIndices[0]],
T * mesh.mVertices[face.mIndices[1]],
T * mesh.mVertices[face.mIndices[2]]
}},
// normals
{{
T * mesh.mNormals[face.mIndices[0]],
T * mesh.mNormals[face.mIndices[1]],
T * mesh.mNormals[face.mIndices[2]]
}},
ambient,
diffuse
});
}
}
}
return triangles;
}
static const char USAGE[] =
R"(Usage: raytracer <filename> [options]
Options:
-w --width=<px> Width of the image [default: 640].
-a --aspect=<num> Aspect ratio of the image. If the model has
specified the aspect ratio, it will be used.
Otherwise default value is 1.
-b --background=<color> Background color of the world. [default: 0 0 0 0].
)";
int main(int argc, char const *argv[])
{
// parameters
std::map<std::string, docopt::value> args =
docopt::docopt(USAGE, {argv + 1, argv + argc}, true, "raytracer 0.2");
// import scene
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(
args["<filename>"].asString().c_str(),
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_GenNormals |
aiProcess_SortByPType);
if (!scene) {
std::cout << importer.GetErrorString() << std::endl;
return 1;
}
// setup camera
assert(scene->mNumCameras == 1); // we can deal only with a single camera
auto& sceneCam = *scene->mCameras[0];
if (args["--aspect"]) {
sceneCam.mAspect = std::stof(args["--aspect"].asString());
assert(sceneCam.mAspect > 0);
} else if (sceneCam.mAspect == 0) {
sceneCam.mAspect = 1.f;
}
auto* camNode = scene->mRootNode->FindNode(sceneCam.mName);
assert(camNode != nullptr);
const Camera cam(camNode->mTransformation, sceneCam);
std::cerr << "Camera" << std::endl;
std::cerr << cam << std::endl;
// setup light
assert(scene->mNumLights == 1); // we can deal only with a single light
auto& light = *scene->mLights[0];
std::cerr << "Light" << std::endl;
std::cerr << "Diffuse: " << light.mColorDiffuse << std::endl;
auto* lightNode = scene->mRootNode->FindNode(light.mName);
assert(lightNode != nullptr);
const auto& LT = lightNode->mTransformation;
std::cerr << "Light Trafo: " << LT << std::endl;
auto light_pos = LT * aiVector3D();
auto light_color = aiColor4D{
light.mColorDiffuse.r,
light.mColorDiffuse.g,
light.mColorDiffuse.b,
1};
// load triangles from the scene
auto triangles = triangles_from_scene(scene);
//
// Raytracer
//
int width = args["--width"].asLong();
assert(width > 0);
int height = width / cam.mAspect;
auto background_color = parse_color4(args["--background"].asString());
Image image(width, height);
{
auto rt = Runtime(std::cerr, "Rendering time: ");
std::cerr << "Rendering ";
float r, s, t;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
// intersection
auto cam_dir = cam.raster2cam(aiVector2D(x, y), width, height);
auto triangle_index = ray_intersection(
aiRay(cam.mPosition, cam_dir), triangles, r, s, t);
if (triangle_index < 0) {
image(x, y) = background_color;
continue;
}
// light direction
auto p = cam.mPosition + r * cam_dir;
auto light_dir = light_pos - p;
light_dir.Normalize();
// interpolate normal
const auto& triangle = triangles[triangle_index];
const auto& n0 = triangle.normals[0];
const auto& n1 = triangle.normals[1];
const auto& n2 = triangle.normals[2];
auto normal = ((1.f - s - t)*n0 + s*n1 + t*n2).Normalize();
// calculate shadow
float distance_to_next_triangle, s2, t2;
auto p2 = p + normal * 0.0001f;
float distance_to_light = (light_pos - p2).Length();
auto shadow_triangle = ray_intersection(
aiRay(p2, light_dir),
triangles,
distance_to_next_triangle, s2, t2);
if (shadow_triangle >= 0 &&
distance_to_next_triangle < distance_to_light)
{
image(x, y) = triangle.ambient;
continue;
}
image(x, y) += lambertian(
light_dir, normal, triangle.diffuse, light_color);
image(x, y) += triangle.ambient;
}
// update prograss bar
auto height_fraction = height / 20;
if (y % height_fraction == 0) {
std::cerr << ".";
}
}
std::cerr << std::endl;
}
// output image
std::cout << image << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
*
* 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 "MBRBlockDevice.h"
#include <algorithm>
// On disk structures, all entries are little endian
MBED_PACKED(struct) mbr_entry {
uint8_t status;
uint8_t chs_start[3];
uint8_t type;
uint8_t chs_stop[3];
uint32_t lba_offset;
uint32_t lba_size;
};
MBED_PACKED(struct) mbr_table {
struct mbr_entry entries[4];
uint8_t signature[2];
};
// Little-endian conversion, should compile to noop
// if system is little-endian
static inline uint32_t tole32(uint32_t a)
{
union {
uint32_t u32;
uint8_t u8[4];
} w;
w.u8[0] = a >> 0;
w.u8[1] = a >> 8;
w.u8[2] = a >> 16;
w.u8[3] = a >> 24;
return w.u32;
}
static inline uint32_t fromle32(uint32_t a)
{
return tole32(a);
}
static void tochs(uint32_t lba, uint8_t chs[3])
{
uint32_t sector = std::min<uint32_t>(lba, 0xfffffd)+1;
chs[0] = (sector >> 6) & 0xff;
chs[1] = ((sector >> 0) & 0x3f) | ((sector >> 16) & 0xc0);
chs[2] = (sector >> 14) & 0xff;
}
// Partition after address are turned into absolute
// addresses, assumes bd is initialized
static int partition_absolute(
BlockDevice *bd, int part, uint8_t type,
bd_size_t offset, bd_size_t size)
{
// Allocate smallest buffer necessary to write MBR
uint32_t buffer_size = std::max<uint32_t>(bd->get_program_size(), sizeof(struct mbr_table));
uint8_t *buffer = new uint8_t[buffer_size];
// Check for existing MBR
int err = bd->read(buffer, 512-buffer_size, buffer_size);
if (err) {
delete[] buffer;
return err;
}
struct mbr_table *table = reinterpret_cast<struct mbr_table*>(
&buffer[buffer_size - sizeof(struct mbr_table)]);
if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) {
// Setup default values for MBR
table->signature[0] = 0x55;
table->signature[1] = 0xaa;
memset(table->entries, 0, sizeof(table->entries));
}
// Setup new partition
MBED_ASSERT(part >= 1 && part <= 4);
table->entries[part-1].status = 0x00; // inactive (not bootable)
table->entries[part-1].type = type;
// lba dimensions
uint32_t sector = std::max<uint32_t>(bd->get_erase_size(), 512);
uint32_t lba_offset = offset / sector;
uint32_t lba_size = size / sector;
table->entries[part-1].lba_offset = tole32(lba_offset);
table->entries[part-1].lba_size = tole32(lba_size);
// chs dimensions
tochs(lba_offset, table->entries[part-1].chs_start);
tochs(lba_offset+lba_size-1, table->entries[part-1].chs_stop);
// Write out MBR
err = bd->erase(0, bd->get_erase_size());
if (err) {
delete[] buffer;
return err;
}
err = bd->program(buffer, 512-buffer_size, buffer_size);
delete[] buffer;
return err;
}
int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start)
{
int err = bd->init();
if (err) {
return err;
}
// Calculate dimensions
bd_size_t offset = ((int64_t)start < 0) ? -start : start;
bd_size_t size = bd->size();
if (offset < 512) {
offset += std::max<uint32_t>(bd->get_erase_size(), 512);
}
size -= offset;
err = partition_absolute(bd, part, type, offset, size);
if (err) {
return err;
}
err = bd->deinit();
if (err) {
return err;
}
return 0;
}
int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type,
bd_addr_t start, bd_addr_t stop)
{
int err = bd->init();
if (err) {
return err;
}
// Calculate dimensions
bd_size_t offset = ((int64_t)start < 0) ? -start : start;
bd_size_t size = ((int64_t)stop < 0) ? -stop : stop;
if (offset < 512) {
offset += std::max<uint32_t>(bd->get_erase_size(), 512);
}
size -= offset;
err = partition_absolute(bd, part, type, offset, size);
if (err) {
return err;
}
err = bd->deinit();
if (err) {
return err;
}
return 0;
}
MBRBlockDevice::MBRBlockDevice(BlockDevice *bd, int part)
: _bd(bd), _part(part)
{
MBED_ASSERT(_part >= 1 && _part <= 4);
}
int MBRBlockDevice::init()
{
// Allocate smallest buffer necessary to write MBR
uint32_t buffer_size = std::max<uint32_t>(_bd->get_read_size(), sizeof(struct mbr_table));
uint8_t *buffer = new uint8_t[buffer_size];
int err = _bd->read(buffer, 512-buffer_size, buffer_size);
if (err) {
delete[] buffer;
return err;
}
// Check for valid table
struct mbr_table *table = reinterpret_cast<struct mbr_table*>(
&buffer[buffer_size - sizeof(struct mbr_table)]);
if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) {
delete[] buffer;
return BD_ERROR_INVALID_MBR;
}
// Check for valid entry
if (table->entries[_part-1].type == 0x00) {
delete[] buffer;
return BD_ERROR_INVALID_PARTITION;
}
// Get partition attributes
bd_size_t sector = std::max<uint32_t>(_bd->get_erase_size(), 512);
_type = table->entries[_part-1].type;
_offset = fromle32(table->entries[_part-1].lba_offset) * sector;
_size = fromle32(table->entries[_part-1].lba_size) * sector;
// Check that block addresses are valid
MBED_ASSERT(_bd->is_valid_erase(_offset, _size));
delete[] buffer;
return 0;
}
int MBRBlockDevice::deinit()
{
return _bd->deinit();
}
int MBRBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size)
{
MBED_ASSERT(is_valid_read(addr, size));
return _bd->read(b, addr + _offset, size);
}
int MBRBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size)
{
MBED_ASSERT(is_valid_program(addr, size));
return _bd->program(b, addr + _offset, size);
}
int MBRBlockDevice::erase(bd_addr_t addr, bd_size_t size)
{
MBED_ASSERT(is_valid_erase(addr, size));
return _bd->erase(addr + _offset, size);
}
bd_size_t MBRBlockDevice::get_read_size() const
{
return _bd->get_read_size();
}
bd_size_t MBRBlockDevice::get_program_size() const
{
return _bd->get_program_size();
}
bd_size_t MBRBlockDevice::get_erase_size() const
{
return _bd->get_erase_size();
}
bd_size_t MBRBlockDevice::size() const
{
return _size;
}
bd_size_t MBRBlockDevice::get_partition_start() const
{
return _offset;
}
bd_size_t MBRBlockDevice::get_partition_stop() const
{
return _offset+_size;
}
uint8_t MBRBlockDevice::get_partition_type() const
{
return _type;
}
int MBRBlockDevice::get_partition_number() const
{
return _part;
}
<commit_msg>bd: Fix missing init in MBRBlockDevice<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
*
* 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 "MBRBlockDevice.h"
#include <algorithm>
// On disk structures, all entries are little endian
MBED_PACKED(struct) mbr_entry {
uint8_t status;
uint8_t chs_start[3];
uint8_t type;
uint8_t chs_stop[3];
uint32_t lba_offset;
uint32_t lba_size;
};
MBED_PACKED(struct) mbr_table {
struct mbr_entry entries[4];
uint8_t signature[2];
};
// Little-endian conversion, should compile to noop
// if system is little-endian
static inline uint32_t tole32(uint32_t a)
{
union {
uint32_t u32;
uint8_t u8[4];
} w;
w.u8[0] = a >> 0;
w.u8[1] = a >> 8;
w.u8[2] = a >> 16;
w.u8[3] = a >> 24;
return w.u32;
}
static inline uint32_t fromle32(uint32_t a)
{
return tole32(a);
}
static void tochs(uint32_t lba, uint8_t chs[3])
{
uint32_t sector = std::min<uint32_t>(lba, 0xfffffd)+1;
chs[0] = (sector >> 6) & 0xff;
chs[1] = ((sector >> 0) & 0x3f) | ((sector >> 16) & 0xc0);
chs[2] = (sector >> 14) & 0xff;
}
// Partition after address are turned into absolute
// addresses, assumes bd is initialized
static int partition_absolute(
BlockDevice *bd, int part, uint8_t type,
bd_size_t offset, bd_size_t size)
{
// Allocate smallest buffer necessary to write MBR
uint32_t buffer_size = std::max<uint32_t>(bd->get_program_size(), sizeof(struct mbr_table));
uint8_t *buffer = new uint8_t[buffer_size];
// Check for existing MBR
int err = bd->read(buffer, 512-buffer_size, buffer_size);
if (err) {
delete[] buffer;
return err;
}
struct mbr_table *table = reinterpret_cast<struct mbr_table*>(
&buffer[buffer_size - sizeof(struct mbr_table)]);
if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) {
// Setup default values for MBR
table->signature[0] = 0x55;
table->signature[1] = 0xaa;
memset(table->entries, 0, sizeof(table->entries));
}
// Setup new partition
MBED_ASSERT(part >= 1 && part <= 4);
table->entries[part-1].status = 0x00; // inactive (not bootable)
table->entries[part-1].type = type;
// lba dimensions
uint32_t sector = std::max<uint32_t>(bd->get_erase_size(), 512);
uint32_t lba_offset = offset / sector;
uint32_t lba_size = size / sector;
table->entries[part-1].lba_offset = tole32(lba_offset);
table->entries[part-1].lba_size = tole32(lba_size);
// chs dimensions
tochs(lba_offset, table->entries[part-1].chs_start);
tochs(lba_offset+lba_size-1, table->entries[part-1].chs_stop);
// Write out MBR
err = bd->erase(0, bd->get_erase_size());
if (err) {
delete[] buffer;
return err;
}
err = bd->program(buffer, 512-buffer_size, buffer_size);
delete[] buffer;
return err;
}
int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start)
{
int err = bd->init();
if (err) {
return err;
}
// Calculate dimensions
bd_size_t offset = ((int64_t)start < 0) ? -start : start;
bd_size_t size = bd->size();
if (offset < 512) {
offset += std::max<uint32_t>(bd->get_erase_size(), 512);
}
size -= offset;
err = partition_absolute(bd, part, type, offset, size);
if (err) {
return err;
}
err = bd->deinit();
if (err) {
return err;
}
return 0;
}
int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type,
bd_addr_t start, bd_addr_t stop)
{
int err = bd->init();
if (err) {
return err;
}
// Calculate dimensions
bd_size_t offset = ((int64_t)start < 0) ? -start : start;
bd_size_t size = ((int64_t)stop < 0) ? -stop : stop;
if (offset < 512) {
offset += std::max<uint32_t>(bd->get_erase_size(), 512);
}
size -= offset;
err = partition_absolute(bd, part, type, offset, size);
if (err) {
return err;
}
err = bd->deinit();
if (err) {
return err;
}
return 0;
}
MBRBlockDevice::MBRBlockDevice(BlockDevice *bd, int part)
: _bd(bd), _part(part)
{
MBED_ASSERT(_part >= 1 && _part <= 4);
}
int MBRBlockDevice::init()
{
int err = _bd->init();
if (err) {
return err;
}
// Allocate smallest buffer necessary to write MBR
uint32_t buffer_size = std::max<uint32_t>(_bd->get_read_size(), sizeof(struct mbr_table));
uint8_t *buffer = new uint8_t[buffer_size];
err = _bd->read(buffer, 512-buffer_size, buffer_size);
if (err) {
delete[] buffer;
return err;
}
// Check for valid table
struct mbr_table *table = reinterpret_cast<struct mbr_table*>(
&buffer[buffer_size - sizeof(struct mbr_table)]);
if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) {
delete[] buffer;
return BD_ERROR_INVALID_MBR;
}
// Check for valid entry
if (table->entries[_part-1].type == 0x00) {
delete[] buffer;
return BD_ERROR_INVALID_PARTITION;
}
// Get partition attributes
bd_size_t sector = std::max<uint32_t>(_bd->get_erase_size(), 512);
_type = table->entries[_part-1].type;
_offset = fromle32(table->entries[_part-1].lba_offset) * sector;
_size = fromle32(table->entries[_part-1].lba_size) * sector;
// Check that block addresses are valid
MBED_ASSERT(_bd->is_valid_erase(_offset, _size));
delete[] buffer;
return 0;
}
int MBRBlockDevice::deinit()
{
return _bd->deinit();
}
int MBRBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size)
{
MBED_ASSERT(is_valid_read(addr, size));
return _bd->read(b, addr + _offset, size);
}
int MBRBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size)
{
MBED_ASSERT(is_valid_program(addr, size));
return _bd->program(b, addr + _offset, size);
}
int MBRBlockDevice::erase(bd_addr_t addr, bd_size_t size)
{
MBED_ASSERT(is_valid_erase(addr, size));
return _bd->erase(addr + _offset, size);
}
bd_size_t MBRBlockDevice::get_read_size() const
{
return _bd->get_read_size();
}
bd_size_t MBRBlockDevice::get_program_size() const
{
return _bd->get_program_size();
}
bd_size_t MBRBlockDevice::get_erase_size() const
{
return _bd->get_erase_size();
}
bd_size_t MBRBlockDevice::size() const
{
return _size;
}
bd_size_t MBRBlockDevice::get_partition_start() const
{
return _offset;
}
bd_size_t MBRBlockDevice::get_partition_stop() const
{
return _offset+_size;
}
uint8_t MBRBlockDevice::get_partition_type() const
{
return _type;
}
int MBRBlockDevice::get_partition_number() const
{
return _part;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under 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 <iomanip>
#include <istream>
#include <sstream>
#include <iostream>
#include <string>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include "parser/SpiritParser.hpp"
#include "lexer/SpiritLexer.hpp"
#include "ast/Program.hpp"
namespace qi = boost::spirit::qi;
using namespace eddic;
template <typename Iterator, typename AttributeT>
struct Rule {
typedef typename boost::spirit::qi::rule<Iterator, AttributeT> type;
};
template <typename Iterator, typename Lexer>
struct EddiGrammar : qi::grammar<Iterator, ast::Program()> {
EddiGrammar(const Lexer& lexer) : EddiGrammar::base_type(program, "EDDI Grammar") {
value = additiveValue.alias();
additiveValue %=
multiplicativeValue
>> *(
(lexer.addition > multiplicativeValue)
| (lexer.subtraction > multiplicativeValue)
);
multiplicativeValue %=
unaryValue
>> *(
(lexer.multiplication > unaryValue)
| (lexer.division > unaryValue)
| (lexer.modulo > unaryValue)
);
//TODO Support + - primaryValue
unaryValue = primaryValue.alias();
primaryValue =
constant
| variable
| (lexer.left_parenth >> value > lexer.right_parenth);
integer %=
qi::eps
>> lexer.integer;
variable %=
qi::eps
>> lexer.word;
litteral %=
qi::eps
>> lexer.litteral;
constant %=
integer
| litteral;
true_ %=
qi::eps
>> lexer.true_;
false_ %=
qi::eps
>> lexer.false_;
binary_condition %=
value
>> (
lexer.greater_equals
| lexer.greater
| lexer.less_equals
| lexer.less
| lexer.not_equals
| lexer.equals
)
>> value;
condition %=
true_
| false_
| binary_condition;
else_if_ %=
lexer.else_
>> lexer.if_
>> lexer.left_parenth
>> condition
>> lexer.right_parenth
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace;
else_ %=
lexer.else_
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace;
if_ %=
lexer.if_
>> lexer.left_parenth
>> condition
>> lexer.right_parenth
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace
>> *(else_if_)
>> -(else_);
for_ %=
lexer.for_
> lexer.left_parenth
> -declaration
> lexer.stop
> -condition
> lexer.stop
> -repeatable_instruction
> lexer.right_parenth
> lexer.left_brace
> (*instruction)
> lexer.right_brace;
foreach_ =
lexer.foreach_
> lexer.left_parenth
> lexer.word
> lexer.word
> lexer.from_
> lexer.integer
> lexer.to_
> lexer.integer
> lexer.right_parenth
> lexer.left_brace
> *(instruction)
> lexer.right_brace;
while_ %=
lexer.while_
> lexer.left_parenth
> condition
> lexer.right_parenth
> lexer.left_brace
> *(instruction)
> lexer.right_brace;
declaration %=
lexer.word
>> lexer.word
>> lexer.assign
>> value;
assignment %=
lexer.word
>> lexer.assign
>> value;
globalDeclaration %=
lexer.word
>> lexer.word
>> lexer.assign
>> constant
>> lexer.stop;
functionCall %=
lexer.word
>> lexer.left_parenth
>> -( value >> *( lexer.comma > value))
>> lexer.right_parenth;
swap %=
lexer.word
>> lexer.swap
>> lexer.word;
instruction %=
(functionCall > lexer.stop)
| (assignment > lexer.stop)
| (declaration > lexer.stop)
| if_
| for_
| while_
| foreach_
| (swap > lexer.stop);
repeatable_instruction = assignment | declaration | swap;
arg %=
lexer.word
>> lexer.word;
function %=
lexer.word
>> lexer.word
>> lexer.left_parenth
>> -( arg >> *( lexer.comma > arg))
>> lexer.right_parenth
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace;
program %=
qi::eps
>> *(function | globalDeclaration);
//Name the rules
globalDeclaration.name("EDDI global variable");
function.name("EDDI function declaration");
program.name("EDDI program");
}
qi::rule<Iterator, ast::Program()> program;
qi::rule<Iterator, ast::GlobalVariableDeclaration()> globalDeclaration;
qi::rule<Iterator, ast::FunctionDeclaration()> function;
qi::rule<Iterator, ast::FunctionParameter()> arg;
qi::rule<Iterator, ast::Instruction()> instruction;
qi::rule<Iterator, ast::Instruction()> repeatable_instruction;
qi::rule<Iterator, ast::Swap()> swap;
qi::rule<Iterator, ast::FunctionCall()> functionCall;
qi::rule<Iterator, ast::Declaration()> declaration;
qi::rule<Iterator, ast::Assignment()> assignment;
qi::rule<Iterator, ast::While()> while_;
qi::rule<Iterator, ast::For()> for_;
qi::rule<Iterator, ast::Foreach()> foreach_;
qi::rule<Iterator, ast::If()> if_;
qi::rule<Iterator, ast::Else()> else_;
qi::rule<Iterator, ast::ElseIf()> else_if_;
qi::rule<Iterator, ast::Value()> value;
qi::rule<Iterator, ast::Value()> primaryValue;
qi::rule<Iterator, ast::Value()> unaryValue;
qi::rule<Iterator, ast::ComposedValue()> additiveValue;
qi::rule<Iterator, ast::ComposedValue()> multiplicativeValue;
qi::rule<Iterator, ast::Value()> constant;
qi::rule<Iterator, ast::Integer()> integer;
qi::rule<Iterator, ast::Litteral()> litteral;
qi::rule<Iterator, ast::VariableValue()> variable;
qi::rule<Iterator, ast::Condition()> condition;
qi::rule<Iterator, ast::True()> true_;
qi::rule<Iterator, ast::False()> false_;
qi::rule<Iterator, ast::BinaryCondition()> binary_condition;
};
bool SpiritParser::parse(const std::string& file, ast::Program& program){
std::ifstream in(file.c_str());
in.unsetf(std::ios::skipws);
in.seekg(0, std::istream::end);
std::size_t size(static_cast<size_t>(in.tellg()));
in.seekg(0, std::istream::beg);
std::string contents(size, 0);
in.read(&contents[0], size);
pos_iterator_type position_begin(contents.begin(), contents.end(), file);
pos_iterator_type position_end;
SimpleLexer<lexer_type> lexer;
EddiGrammar<lexer_type::iterator_type, SimpleLexer<lexer_type>> grammar(lexer);
try {
bool r = lex::tokenize_and_parse(position_begin, position_end, lexer, grammar, program);
if(r && position_begin == position_end) {
return true;
} else {
std::cout << "Parsing failed" << std::endl;
const spirit::classic::file_position_base<std::string>& pos = position_begin.get_position();
std::cout <<
"Error at file " << pos.file << " line " << pos.line << " column " << pos.column << std::endl <<
"'" << position_begin.get_currentline() << "'" << std::endl <<
std::setw(pos.column) << " " << "^- here";
return false;
}
} catch (const qi::expectation_failure<lexer_type::iterator_type>& exception) {
std::cout << "Parsing failed" << std::endl;
//TODO Improve to get information from exception
const spirit::classic::file_position_base<std::string>& pos = position_begin.get_position();
std::cout <<
"Error at file " << pos.file << " line " << pos.line << " column " << pos.column << " Expecting " << exception.what_ << std::endl <<
"'" << position_begin.get_currentline() << "'" << std::endl <<
std::setw(pos.column) << " " << "^- here" << std::endl;
return false;
}
}
<commit_msg>Enable global variables to have a default value<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under 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 <iomanip>
#include <istream>
#include <sstream>
#include <iostream>
#include <string>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include "parser/SpiritParser.hpp"
#include "lexer/SpiritLexer.hpp"
#include "ast/Program.hpp"
namespace qi = boost::spirit::qi;
using namespace eddic;
template <typename Iterator, typename AttributeT>
struct Rule {
typedef typename boost::spirit::qi::rule<Iterator, AttributeT> type;
};
template <typename Iterator, typename Lexer>
struct EddiGrammar : qi::grammar<Iterator, ast::Program()> {
EddiGrammar(const Lexer& lexer) : EddiGrammar::base_type(program, "EDDI Grammar") {
value = additiveValue.alias();
additiveValue %=
multiplicativeValue
>> *(
(lexer.addition > multiplicativeValue)
| (lexer.subtraction > multiplicativeValue)
);
multiplicativeValue %=
unaryValue
>> *(
(lexer.multiplication > unaryValue)
| (lexer.division > unaryValue)
| (lexer.modulo > unaryValue)
);
//TODO Support + - primaryValue
unaryValue = primaryValue.alias();
primaryValue =
constant
| variable
| (lexer.left_parenth >> value > lexer.right_parenth);
integer %=
qi::eps
>> lexer.integer;
variable %=
qi::eps
>> lexer.word;
litteral %=
qi::eps
>> lexer.litteral;
constant %=
integer
| litteral;
true_ %=
qi::eps
>> lexer.true_;
false_ %=
qi::eps
>> lexer.false_;
binary_condition %=
value
>> (
lexer.greater_equals
| lexer.greater
| lexer.less_equals
| lexer.less
| lexer.not_equals
| lexer.equals
)
>> value;
condition %=
true_
| false_
| binary_condition;
else_if_ %=
lexer.else_
>> lexer.if_
>> lexer.left_parenth
>> condition
>> lexer.right_parenth
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace;
else_ %=
lexer.else_
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace;
if_ %=
lexer.if_
>> lexer.left_parenth
>> condition
>> lexer.right_parenth
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace
>> *(else_if_)
>> -(else_);
for_ %=
lexer.for_
> lexer.left_parenth
> -declaration
> lexer.stop
> -condition
> lexer.stop
> -repeatable_instruction
> lexer.right_parenth
> lexer.left_brace
> (*instruction)
> lexer.right_brace;
foreach_ =
lexer.foreach_
> lexer.left_parenth
> lexer.word
> lexer.word
> lexer.from_
> lexer.integer
> lexer.to_
> lexer.integer
> lexer.right_parenth
> lexer.left_brace
> *(instruction)
> lexer.right_brace;
while_ %=
lexer.while_
> lexer.left_parenth
> condition
> lexer.right_parenth
> lexer.left_brace
> *(instruction)
> lexer.right_brace;
declaration %=
lexer.word
>> lexer.word
>> lexer.assign
>> value;
assignment %=
lexer.word
>> lexer.assign
>> value;
globalDeclaration %=
lexer.word
>> lexer.word
>> -(lexer.assign >> constant)
>> lexer.stop;
functionCall %=
lexer.word
>> lexer.left_parenth
>> -( value >> *( lexer.comma > value))
>> lexer.right_parenth;
swap %=
lexer.word
>> lexer.swap
>> lexer.word;
instruction %=
(functionCall > lexer.stop)
| (assignment > lexer.stop)
| (declaration > lexer.stop)
| if_
| for_
| while_
| foreach_
| (swap > lexer.stop);
repeatable_instruction = assignment | declaration | swap;
arg %=
lexer.word
>> lexer.word;
function %=
lexer.word
>> lexer.word
>> lexer.left_parenth
>> -( arg >> *( lexer.comma > arg))
>> lexer.right_parenth
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace;
program %=
qi::eps
>> *(function | globalDeclaration);
//Name the rules
globalDeclaration.name("EDDI global variable");
function.name("EDDI function declaration");
program.name("EDDI program");
}
qi::rule<Iterator, ast::Program()> program;
qi::rule<Iterator, ast::GlobalVariableDeclaration()> globalDeclaration;
qi::rule<Iterator, ast::FunctionDeclaration()> function;
qi::rule<Iterator, ast::FunctionParameter()> arg;
qi::rule<Iterator, ast::Instruction()> instruction;
qi::rule<Iterator, ast::Instruction()> repeatable_instruction;
qi::rule<Iterator, ast::Swap()> swap;
qi::rule<Iterator, ast::FunctionCall()> functionCall;
qi::rule<Iterator, ast::Declaration()> declaration;
qi::rule<Iterator, ast::Assignment()> assignment;
qi::rule<Iterator, ast::While()> while_;
qi::rule<Iterator, ast::For()> for_;
qi::rule<Iterator, ast::Foreach()> foreach_;
qi::rule<Iterator, ast::If()> if_;
qi::rule<Iterator, ast::Else()> else_;
qi::rule<Iterator, ast::ElseIf()> else_if_;
qi::rule<Iterator, ast::Value()> value;
qi::rule<Iterator, ast::Value()> primaryValue;
qi::rule<Iterator, ast::Value()> unaryValue;
qi::rule<Iterator, ast::ComposedValue()> additiveValue;
qi::rule<Iterator, ast::ComposedValue()> multiplicativeValue;
qi::rule<Iterator, ast::Value()> constant;
qi::rule<Iterator, ast::Integer()> integer;
qi::rule<Iterator, ast::Litteral()> litteral;
qi::rule<Iterator, ast::VariableValue()> variable;
qi::rule<Iterator, ast::Condition()> condition;
qi::rule<Iterator, ast::True()> true_;
qi::rule<Iterator, ast::False()> false_;
qi::rule<Iterator, ast::BinaryCondition()> binary_condition;
};
bool SpiritParser::parse(const std::string& file, ast::Program& program){
std::ifstream in(file.c_str());
in.unsetf(std::ios::skipws);
in.seekg(0, std::istream::end);
std::size_t size(static_cast<size_t>(in.tellg()));
in.seekg(0, std::istream::beg);
std::string contents(size, 0);
in.read(&contents[0], size);
pos_iterator_type position_begin(contents.begin(), contents.end(), file);
pos_iterator_type position_end;
SimpleLexer<lexer_type> lexer;
EddiGrammar<lexer_type::iterator_type, SimpleLexer<lexer_type>> grammar(lexer);
try {
bool r = lex::tokenize_and_parse(position_begin, position_end, lexer, grammar, program);
if(r && position_begin == position_end) {
return true;
} else {
std::cout << "Parsing failed" << std::endl;
const spirit::classic::file_position_base<std::string>& pos = position_begin.get_position();
std::cout <<
"Error at file " << pos.file << " line " << pos.line << " column " << pos.column << std::endl <<
"'" << position_begin.get_currentline() << "'" << std::endl <<
std::setw(pos.column) << " " << "^- here";
return false;
}
} catch (const qi::expectation_failure<lexer_type::iterator_type>& exception) {
std::cout << "Parsing failed" << std::endl;
//TODO Improve to get information from exception
const spirit::classic::file_position_base<std::string>& pos = position_begin.get_position();
std::cout <<
"Error at file " << pos.file << " line " << pos.line << " column " << pos.column << " Expecting " << exception.what_ << std::endl <<
"'" << position_begin.get_currentline() << "'" << std::endl <<
std::setw(pos.column) << " " << "^- here" << std::endl;
return false;
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Copyright (C) 2012
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*****************************************************************************/
#define __STDC_CONSTANT_MACROS 1
#include <vlc_common.h>
#include <vlc_network.h>
#include <ctime>
#include "helper.h"
#include "htsmessage.h"
sys_common_t::~sys_common_t()
{
if(netfd >= 0)
net_Close(netfd);
}
uint32_t HTSPNextSeqNum(sys_common_t *sys)
{
uint32_t res = sys->nextSeqNum++;
if(sys->nextSeqNum > 2147483647)
sys->nextSeqNum = 1;
return res;
}
bool TransmitMessageEx(vlc_object_t *obj, sys_common_t *sys, HtsMessage m)
{
if(sys->netfd < 0)
{
msg_Dbg(obj, "Invalid netfd in TransmitMessage");
return false;
}
void *buf;
uint32_t len;
if(!m.Serialize(&len, &buf))
{
msg_Dbg(obj, "Serialising message failed");
return false;
}
if(net_Write(obj, sys->netfd, NULL, buf, len) != (ssize_t)len)
{
msg_Dbg(obj, "net_Write failed");
return false;
}
free(buf);
return true;
}
HtsMessage ReadMessageEx(vlc_object_t *obj, sys_common_t *sys)
{
char *buf;
uint32_t len;
ssize_t readSize;
if(sys->queue.size())
{
HtsMessage res = sys->queue.front();
sys->queue.pop_front();
return res;
}
time_t start = time(0);
while((readSize = net_Read(obj, sys->netfd, NULL, &len, sizeof(len), false)) != sizeof(len))
{
if(readSize == 0)
{
msg_Err(obj, "Size Read EOF!");
return HtsMessage();
}
if(readSize > 0)
{
msg_Err(obj, "Error reading from socket");
return HtsMessage();
}
if(difftime(time(0), start) > READ_TIMEOUT)
{
msg_Err(obj, "Read timed out!");
return HtsMessage();
}
}
len = ntohl(len);
if(len == 0)
return HtsMessage();
buf = (char*)malloc(len);
char *wbuf = buf;
uint32_t tlen = len;
start = time(0);
while((readSize = net_Read(obj, sys->netfd, NULL, wbuf, tlen, false)) < tlen)
{
wbuf += readSize;
tlen -= readSize;
if(difftime(time(0), start) > READ_TIMEOUT || readSize == 0)
{
if(readSize == 0)
msg_Err(obj, "Read EOF!");
else
msg_Err(obj, "Read timed out!");
free(buf);
return HtsMessage();
}
}
if(readSize > tlen)
{
msg_Dbg(obj, "WTF");
free(buf);
return HtsMessage();
}
HtsMessage result = HtsMessage::Deserialize(len, buf);
free(buf);
return result;
}
HtsMessage ReadResultEx(vlc_object_t *obj, sys_common_t *sys, HtsMessage m, bool sequence)
{
uint32_t iSequence = 0;
if(sequence)
{
iSequence = HTSPNextSeqNum(sys);
m.getRoot()->setData("seq", iSequence);
}
if(!TransmitMessageEx(obj, sys, m))
{
msg_Err(obj, "TransmitMessage failed!");
return HtsMessage();
}
std::deque<HtsMessage> queue;
sys->queue.swap(queue);
while((m = ReadMessageEx(obj, sys)).isValid())
{
if(!sequence)
break;
if(m.getRoot()->contains("seq") && m.getRoot()->getU32("seq") == iSequence)
break;
queue.push_back(m);
if(queue.size() >= MAX_QUEUE_SIZE)
{
msg_Err(obj, "Max queue size reached!");
sys->queue.swap(queue);
return HtsMessage();
}
}
sys->queue.swap(queue);
if(!m.isValid())
{
msg_Err(obj, "ReadMessage failed!");
return HtsMessage();
}
if(m.getRoot()->contains("error"))
{
msg_Err(obj, "HTSP Error: %s", m.getRoot()->getStr("error").c_str());
return HtsMessage();
}
if(m.getRoot()->getU32("noaccess") != 0)
{
msg_Err(obj, "Access Denied");
return HtsMessage();
}
return m;
}
bool ReadSuccessEx(vlc_object_t *obj, sys_common_t *sys, HtsMessage m, const std::string &action, bool sequence)
{
if(!ReadResultEx(obj, sys, m, sequence).isValid())
{
msg_Err(obj, "ReadSuccess - failed to %s", action.c_str());
return false;
}
return true;
}
<commit_msg>Let vlc handle all timing related stuff<commit_after>/*****************************************************************************
* Copyright (C) 2012
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*****************************************************************************/
#define __STDC_CONSTANT_MACROS 1
#include <vlc_common.h>
#include <vlc_network.h>
#include <ctime>
#include "helper.h"
#include "htsmessage.h"
sys_common_t::~sys_common_t()
{
if(netfd >= 0)
net_Close(netfd);
}
uint32_t HTSPNextSeqNum(sys_common_t *sys)
{
uint32_t res = sys->nextSeqNum++;
if(sys->nextSeqNum > 2147483647)
sys->nextSeqNum = 1;
return res;
}
bool TransmitMessageEx(vlc_object_t *obj, sys_common_t *sys, HtsMessage m)
{
if(sys->netfd < 0)
{
msg_Dbg(obj, "Invalid netfd in TransmitMessage");
return false;
}
void *buf;
uint32_t len;
if(!m.Serialize(&len, &buf))
{
msg_Dbg(obj, "Serialising message failed");
return false;
}
if(net_Write(obj, sys->netfd, NULL, buf, len) != (ssize_t)len)
{
msg_Dbg(obj, "net_Write failed");
return false;
}
free(buf);
return true;
}
HtsMessage ReadMessageEx(vlc_object_t *obj, sys_common_t *sys)
{
char *buf;
uint32_t len;
ssize_t readSize;
if(sys->queue.size())
{
HtsMessage res = sys->queue.front();
sys->queue.pop_front();
return res;
}
if((readSize = net_Read(obj, sys->netfd, NULL, &len, sizeof(len), true)) != sizeof(len))
{
if(readSize == 0)
{
msg_Err(obj, "Size Read EOF!");
return HtsMessage();
}
msg_Err(obj, "Error reading size: %m");
return HtsMessage();
}
len = ntohl(len);
if(len == 0)
return HtsMessage();
buf = (char*)malloc(len);
if((readSize = net_Read(obj, sys->netfd, NULL, buf, len, true)) != len)
{
if(readSize == 0)
{
msg_Err(obj, "Data Read EOF!");
return HtsMessage();
}
msg_Err(obj, "Error reading data: %m");
return HtsMessage();
}
HtsMessage result = HtsMessage::Deserialize(len, buf);
free(buf);
return result;
}
HtsMessage ReadResultEx(vlc_object_t *obj, sys_common_t *sys, HtsMessage m, bool sequence)
{
uint32_t iSequence = 0;
if(sequence)
{
iSequence = HTSPNextSeqNum(sys);
m.getRoot()->setData("seq", iSequence);
}
if(!TransmitMessageEx(obj, sys, m))
{
msg_Err(obj, "TransmitMessage failed!");
return HtsMessage();
}
std::deque<HtsMessage> queue;
sys->queue.swap(queue);
while((m = ReadMessageEx(obj, sys)).isValid())
{
if(!sequence)
break;
if(m.getRoot()->contains("seq") && m.getRoot()->getU32("seq") == iSequence)
break;
queue.push_back(m);
if(queue.size() >= MAX_QUEUE_SIZE)
{
msg_Err(obj, "Max queue size reached!");
sys->queue.swap(queue);
return HtsMessage();
}
}
sys->queue.swap(queue);
if(!m.isValid())
{
msg_Err(obj, "ReadMessage failed!");
return HtsMessage();
}
if(m.getRoot()->contains("error"))
{
msg_Err(obj, "HTSP Error: %s", m.getRoot()->getStr("error").c_str());
return HtsMessage();
}
if(m.getRoot()->getU32("noaccess") != 0)
{
msg_Err(obj, "Access Denied");
return HtsMessage();
}
return m;
}
bool ReadSuccessEx(vlc_object_t *obj, sys_common_t *sys, HtsMessage m, const std::string &action, bool sequence)
{
if(!ReadResultEx(obj, sys, m, sequence).isValid())
{
msg_Err(obj, "ReadSuccess - failed to %s", action.c_str());
return false;
}
return true;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "QUECTEL_EC2X.h"
#include "PinNames.h"
#include "AT_CellularNetwork.h"
#include "rtos/ThisThread.h"
using namespace mbed;
using namespace rtos;
using namespace events;
static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = {
AT_CellularNetwork::RegistrationModeLAC, // C_EREG
AT_CellularNetwork::RegistrationModeLAC, // C_GREG
AT_CellularNetwork::RegistrationModeLAC, // C_REG
1, // AT_CGSN_WITH_TYPE
1, // AT_CGDATA
0, // AT_CGAUTH
1, // AT_CNMI
1, // AT_CSMP
1, // AT_CMGF
1, // AT_CSDH
1, // PROPERTY_IPV4_STACK
1, // PROPERTY_IPV6_STACK
1, // PROPERTY_IPV4V6_STACK
0, // PROPERTY_NON_IP_PDP_TYPE
1, // PROPERTY_AT_CGEREP
};
QUECTEL_EC2X::QUECTEL_EC2X(FileHandle *fh, PinName pwr, PinName rst)
: AT_CellularDevice(fh),
_pwr_key(pwr, 0),
_rst(rst, 0)
{
AT_CellularBase::set_cellular_properties(cellular_properties);
}
#if MBED_CONF_QUECTEL_EC2X_PROVIDE_DEFAULT
#include "UARTSerial.h"
CellularDevice *CellularDevice::get_default_instance()
{
static UARTSerial serial(MBED_CONF_QUECTEL_EC2X_TX,
MBED_CONF_QUECTEL_EC2X_RX,
MBED_CONF_QUECTEL_EC2X_BAUDRATE);
#if defined(MBED_CONF_QUECTEL_EC2X_RTS) && defined(MBED_CONF_QUECTEL_EC2X_CTS)
serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_QUECTEL_EC2X_RTS, MBED_CONF_QUECTEL_EC2X_CTS);
#endif
static QUECTEL_EC2X device(&serial, MBED_CONF_QUECTEL_EC2X_PWR, MBED_CONF_QUECTEL_EC2X_RST);
return &device;
}
nsapi_error_t QUECTEL_EC2X::hard_power_on()
{
if (_pwr_key.is_connected()) {
_pwr_key = 1;
ThisThread::sleep_for(600);
_pwr_key = 0;
ThisThread::sleep_for(100);
}
return NSAPI_ERROR_OK;
}
nsapi_error_t QUECTEL_EC2X::hard_power_off()
{
if (_pwr_key.is_connected()) {
_pwr_key = 1;
ThisThread::sleep_for(750);
_pwr_key = 0;
ThisThread::sleep_for(100);
}
return NSAPI_ERROR_OK;
}
nsapi_error_t QUECTEL_EC2X::soft_power_on()
{
if (_rst.is_connected()) {
_rst = 1;
ThisThread::sleep_for(460);
_rst = 0;
ThisThread::sleep_for(100);
}
_at->lock();
_at->set_at_timeout(5000);
_at->resp_start();
_at->set_stop_tag("RDY");
bool rdy = _at->consume_to_stop_tag();
_at->set_stop_tag(OK);
_at->unlock();
if (!rdy) {
return NSAPI_ERROR_DEVICE_ERROR;
}
return NSAPI_ERROR_OK;
}
nsapi_error_t QUECTEL_EC2X::soft_power_off()
{
if (_pwr_key.is_connected()) {
_pwr_key = 1;
ThisThread::sleep_for(750);
_pwr_key = 0;
ThisThread::sleep_for(100);
}
return NSAPI_ERROR_OK;
}
#endif
<commit_msg>AT+CGSN with EC2X does not take parameter<commit_after>/*
* Copyright (c) 2019, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "QUECTEL_EC2X.h"
#include "PinNames.h"
#include "AT_CellularNetwork.h"
#include "rtos/ThisThread.h"
using namespace mbed;
using namespace rtos;
using namespace events;
static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = {
AT_CellularNetwork::RegistrationModeLAC, // C_EREG
AT_CellularNetwork::RegistrationModeLAC, // C_GREG
AT_CellularNetwork::RegistrationModeLAC, // C_REG
0, // AT_CGSN_WITH_TYPE
1, // AT_CGDATA
0, // AT_CGAUTH
1, // AT_CNMI
1, // AT_CSMP
1, // AT_CMGF
1, // AT_CSDH
1, // PROPERTY_IPV4_STACK
1, // PROPERTY_IPV6_STACK
1, // PROPERTY_IPV4V6_STACK
0, // PROPERTY_NON_IP_PDP_TYPE
1, // PROPERTY_AT_CGEREP
};
QUECTEL_EC2X::QUECTEL_EC2X(FileHandle *fh, PinName pwr, PinName rst)
: AT_CellularDevice(fh),
_pwr_key(pwr, 0),
_rst(rst, 0)
{
AT_CellularBase::set_cellular_properties(cellular_properties);
}
#if MBED_CONF_QUECTEL_EC2X_PROVIDE_DEFAULT
#include "UARTSerial.h"
CellularDevice *CellularDevice::get_default_instance()
{
static UARTSerial serial(MBED_CONF_QUECTEL_EC2X_TX,
MBED_CONF_QUECTEL_EC2X_RX,
MBED_CONF_QUECTEL_EC2X_BAUDRATE);
#if defined(MBED_CONF_QUECTEL_EC2X_RTS) && defined(MBED_CONF_QUECTEL_EC2X_CTS)
serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_QUECTEL_EC2X_RTS, MBED_CONF_QUECTEL_EC2X_CTS);
#endif
static QUECTEL_EC2X device(&serial, MBED_CONF_QUECTEL_EC2X_PWR, MBED_CONF_QUECTEL_EC2X_RST);
return &device;
}
nsapi_error_t QUECTEL_EC2X::hard_power_on()
{
if (_pwr_key.is_connected()) {
_pwr_key = 1;
ThisThread::sleep_for(600);
_pwr_key = 0;
ThisThread::sleep_for(100);
}
return NSAPI_ERROR_OK;
}
nsapi_error_t QUECTEL_EC2X::hard_power_off()
{
if (_pwr_key.is_connected()) {
_pwr_key = 1;
ThisThread::sleep_for(750);
_pwr_key = 0;
ThisThread::sleep_for(100);
}
return NSAPI_ERROR_OK;
}
nsapi_error_t QUECTEL_EC2X::soft_power_on()
{
if (_rst.is_connected()) {
_rst = 1;
ThisThread::sleep_for(460);
_rst = 0;
ThisThread::sleep_for(100);
}
_at->lock();
_at->set_at_timeout(5000);
_at->resp_start();
_at->set_stop_tag("RDY");
bool rdy = _at->consume_to_stop_tag();
_at->set_stop_tag(OK);
_at->unlock();
if (!rdy) {
return NSAPI_ERROR_DEVICE_ERROR;
}
return NSAPI_ERROR_OK;
}
nsapi_error_t QUECTEL_EC2X::soft_power_off()
{
if (_pwr_key.is_connected()) {
_pwr_key = 1;
ThisThread::sleep_for(750);
_pwr_key = 0;
ThisThread::sleep_for(100);
}
return NSAPI_ERROR_OK;
}
#endif
<|endoftext|> |
<commit_before>#include "server.hh"
#include "serializable.hh"
#include "networkEvents.hh"
#include "../logger.hh"
#include <atomic>
#include <memory>
#include <sstream>
using namespace std;
static atomic<unsigned int> clientIdCounter( 0 ); // Should be good enough.
Client::Client( tcp::socket socket ) : m_socket( move( socket ) )
{
m_clientId = ++clientIdCounter;
memset( m_data, 0, maxLength );
}
void Client::SetRead()
{
auto self( shared_from_this() );
m_socket.async_read_some(
asio::buffer( m_data, maxLength ),
[this, self]( boost::system::error_code ec, size_t length )
{
char buffer[USHRT_MAX];
// Check for errors
if( ec.value() )
{
LOG_ERROR( "Client::Read() got error " << ec.value() << ": '" << ec.message() << "'" );
auto partEvent = new PartEvent();
partEvent->type = NETWORK_EVENT;
partEvent->subType = NETWORK_PART;
partEvent->clientId = 0;
eventQueue->AddEvent( partEvent );
m_socket.close();
return;
}
// Apped the received data to the readStream
readStream.write( m_data, length );
// Read more if we don't have enough data even
// for the header alone
size_t streamLength = readStream.str().length();
if( streamLength < sizeof( unsigned short ) )
{
SetRead();
return;
}
// Read the package byte count
size_t packetLength = UnserializeUint16( readStream );
// Reverse the reading point back and
// wait for more data if we don't have enough
if( streamLength < packetLength )
{
long pos = static_cast<long>( readStream.tellg() );
readStream.seekg( pos - sizeof( unsigned short ) );
SetRead();
return;
}
// We got all the data for the package!
readStream.read( buffer, packetLength-2 );
stringstream packetStream(
stringstream::in |
stringstream::out |
stringstream::binary
);
packetStream.write( buffer, packetLength-2 );
// Create the event
auto dataInEvent = new DataInEvent();
dataInEvent->type = NETWORK_EVENT;
dataInEvent->subType = NETWORK_DATA_IN;
dataInEvent->clientId = m_clientId;
dataInEvent->data = packetStream.str();
eventQueue->AddEvent( dataInEvent );
// Set this as a callback again
SetRead();
});
}
void Client::Write( string msg )
{
lock_guard<mutex> writeLock( writeMutex );
boost::asio::streambuf request;
ostream requestStream( &request );
unsigned short msgLength = msg.length() + 2;
requestStream.write( reinterpret_cast<char*>( &msgLength ), 2 );
requestStream << msg;
boost::asio::write( m_socket, request );
}
Server::Server()
{
m_port = 22001;
m_socket = nullptr;
m_acceptor = nullptr;
}
Server::Server( asio::io_service& ioService, short port )
{
Init( ioService, port );
}
Server::~Server()
{
}
void Server::Init( asio::io_service& ioService, short port )
{
m_port = port;
m_socket = new asio::ip::tcp::socket( ioService );
m_acceptor = new asio::ip::tcp::acceptor(
ioService,
tcp::endpoint( tcp::v4(), port )
);
}
void Server::Accept()
{
if( !m_acceptor || !m_socket )
{
LOG_ERROR( "Server::Accept() Error: Server is uninitialized!" );
}
m_acceptor->async_accept(
*m_socket,
[this]( boost::system::error_code ec )
{
if( !ec )
{
auto client = make_shared<Client>( move( *m_socket ) );
client->SetEventQueue( eventQueue );
client->SetRead();
clientListMutex.lock();
clientList[client->m_clientId] = client;
clientListMutex.unlock();
auto joinEvent = new JoinEvent();
joinEvent->type = NETWORK_EVENT;
joinEvent->subType = NETWORK_JOIN;
joinEvent->clientId = client->m_clientId;
eventQueue->AddEvent( joinEvent );
}
Accept();
});
}
std::shared_ptr<Client> Server::GetClient( unsigned int id )
{
lock_guard<mutex> clientListLock( clientListMutex );
return clientList[id];
}
<commit_msg>Oops, surely we want to know who disconnected.<commit_after>#include "server.hh"
#include "serializable.hh"
#include "networkEvents.hh"
#include "../logger.hh"
#include <atomic>
#include <memory>
#include <sstream>
using namespace std;
static atomic<unsigned int> clientIdCounter( 0 ); // Should be good enough.
Client::Client( tcp::socket socket ) : m_socket( move( socket ) )
{
m_clientId = ++clientIdCounter;
memset( m_data, 0, maxLength );
}
void Client::SetRead()
{
auto self( shared_from_this() );
m_socket.async_read_some(
asio::buffer( m_data, maxLength ),
[this, self]( boost::system::error_code ec, size_t length )
{
char buffer[USHRT_MAX];
// Check for errors
if( ec.value() )
{
LOG_ERROR( "Client::Read() got error " << ec.value() << ": '" << ec.message() << "'" );
auto partEvent = new PartEvent();
partEvent->type = NETWORK_EVENT;
partEvent->subType = NETWORK_PART;
partEvent->clientId = m_clientId;
eventQueue->AddEvent( partEvent );
m_socket.close();
return;
}
// Apped the received data to the readStream
readStream.write( m_data, length );
// Read more if we don't have enough data even
// for the header alone
size_t streamLength = readStream.str().length();
if( streamLength < sizeof( unsigned short ) )
{
SetRead();
return;
}
// Read the package byte count
size_t packetLength = UnserializeUint16( readStream );
// Reverse the reading point back and
// wait for more data if we don't have enough
if( streamLength < packetLength )
{
long pos = static_cast<long>( readStream.tellg() );
readStream.seekg( pos - sizeof( unsigned short ) );
SetRead();
return;
}
// We got all the data for the package!
readStream.read( buffer, packetLength-2 );
stringstream packetStream(
stringstream::in |
stringstream::out |
stringstream::binary
);
packetStream.write( buffer, packetLength-2 );
// Create the event
auto dataInEvent = new DataInEvent();
dataInEvent->type = NETWORK_EVENT;
dataInEvent->subType = NETWORK_DATA_IN;
dataInEvent->clientId = m_clientId;
dataInEvent->data = packetStream.str();
eventQueue->AddEvent( dataInEvent );
// Set this as a callback again
SetRead();
});
}
void Client::Write( string msg )
{
lock_guard<mutex> writeLock( writeMutex );
boost::asio::streambuf request;
ostream requestStream( &request );
unsigned short msgLength = msg.length() + 2;
requestStream.write( reinterpret_cast<char*>( &msgLength ), 2 );
requestStream << msg;
boost::asio::write( m_socket, request );
}
Server::Server()
{
m_port = 22001;
m_socket = nullptr;
m_acceptor = nullptr;
}
Server::Server( asio::io_service& ioService, short port )
{
Init( ioService, port );
}
Server::~Server()
{
}
void Server::Init( asio::io_service& ioService, short port )
{
m_port = port;
m_socket = new asio::ip::tcp::socket( ioService );
m_acceptor = new asio::ip::tcp::acceptor(
ioService,
tcp::endpoint( tcp::v4(), port )
);
}
void Server::Accept()
{
if( !m_acceptor || !m_socket )
{
LOG_ERROR( "Server::Accept() Error: Server is uninitialized!" );
}
m_acceptor->async_accept(
*m_socket,
[this]( boost::system::error_code ec )
{
if( !ec )
{
auto client = make_shared<Client>( move( *m_socket ) );
client->SetEventQueue( eventQueue );
client->SetRead();
clientListMutex.lock();
clientList[client->m_clientId] = client;
clientListMutex.unlock();
auto joinEvent = new JoinEvent();
joinEvent->type = NETWORK_EVENT;
joinEvent->subType = NETWORK_JOIN;
joinEvent->clientId = client->m_clientId;
eventQueue->AddEvent( joinEvent );
}
Accept();
});
}
std::shared_ptr<Client> Server::GetClient( unsigned int id )
{
lock_guard<mutex> clientListLock( clientListMutex );
return clientList[id];
}
<|endoftext|> |
<commit_before>#include <qapplication.h>
#include <qlayout.h>
#include <qwt_plot.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_curve.h>
#include <qwt_legend.h>
#include <qwt_point_data.h>
#include <qwt_plot_canvas.h>
#include <qwt_plot_panner.h>
#include <qwt_plot_magnifier.h>
#include <qwt_text.h>
#include <qwt_math.h>
#include <math.h>
//-----------------------------------------------------------------
// simple.cpp
//
// A simple example which shows how to use QwtPlot connected
// to a data class without any storage, calculating each values
// on the fly.
//-----------------------------------------------------------------
class FunctionData: public QwtSyntheticPointData
{
public:
FunctionData( double( *y )( double ) ):
QwtSyntheticPointData( 100 ),
d_y( y )
{
}
virtual double y( double x ) const
{
return d_y( x );
}
private:
double( *d_y )( double );
};
class Plot : public QwtPlot
{
public:
Plot( QWidget *parent = NULL );
protected:
virtual void resizeEvent( QResizeEvent * );
private:
void populate();
void updateGradient();
};
Plot::Plot( QWidget *parent ):
QwtPlot( parent )
{
// panning with the left mouse button
( void ) new QwtPlotPanner( canvas() );
// zoom in/out with the wheel
( void ) new QwtPlotMagnifier( canvas() );
setAutoFillBackground( true );
setPalette( QPalette( QColor( 165, 193, 228 ) ) );
updateGradient();
setTitle( "A Simple QwtPlot Demonstration" );
insertLegend( new QwtLegend(), QwtPlot::RightLegend );
// axes
setAxisTitle( xBottom, "x -->" );
setAxisScale( xBottom, 0.0, 10.0 );
setAxisTitle( yLeft, "y -->" );
setAxisScale( yLeft, -1.0, 1.0 );
// canvas
canvas()->setLineWidth( 1 );
canvas()->setFrameStyle( QFrame::Box | QFrame::Plain );
canvas()->setBorderRadius( 15 );
QPalette canvasPalette( Qt::white );
canvasPalette.setColor( QPalette::Foreground, QColor( 133, 190, 232 ) );
canvas()->setPalette( canvasPalette );
populate();
}
void Plot::populate()
{
// Insert new curves
QwtPlotCurve *cSin = new QwtPlotCurve( "y = sin(x)" );
cSin->setRenderHint( QwtPlotItem::RenderAntialiased );
cSin->setLegendAttribute( QwtPlotCurve::LegendShowLine, true );
cSin->setPen( QPen( Qt::red ) );
cSin->attach( this );
QwtPlotCurve *cCos = new QwtPlotCurve( "y = cos(x)" );
cCos->setRenderHint( QwtPlotItem::RenderAntialiased );
cCos->setLegendAttribute( QwtPlotCurve::LegendShowLine, true );
cCos->setPen( QPen( Qt::blue ) );
cCos->attach( this );
// Create sin and cos data
cSin->setData( new FunctionData( ::sin ) );
cCos->setData( new FunctionData( ::cos ) );
// Insert markers
// ...a horizontal line at y = 0...
QwtPlotMarker *mY = new QwtPlotMarker();
mY->setLabel( QString::fromLatin1( "y = 0" ) );
mY->setLabelAlignment( Qt::AlignRight | Qt::AlignTop );
mY->setLineStyle( QwtPlotMarker::HLine );
mY->setYValue( 0.0 );
mY->attach( this );
// ...a vertical line at x = 2 * pi
QwtPlotMarker *mX = new QwtPlotMarker();
mX->setLabel( QString::fromLatin1( "x = 2 pi" ) );
mX->setLabelAlignment( Qt::AlignLeft | Qt::AlignBottom );
mX->setLabelOrientation( Qt::Vertical );
mX->setLineStyle( QwtPlotMarker::VLine );
mX->setLinePen( QPen( Qt::black, 0, Qt::DashDotLine ) );
mX->setXValue( 2.0 * M_PI );
mX->attach( this );
}
void Plot::updateGradient()
{
QPalette pal = palette();
const QColor buttonColor = pal.color( QPalette::Button );
#ifdef Q_WS_X11
// Qt 4.7.1: QGradient::StretchToDeviceMode is buggy on X11
QLinearGradient gradient( rect().topLeft(), rect().bottomLeft() );
gradient.setColorAt( 0.0, Qt::white );
gradient.setColorAt( 0.7, buttonColor );
gradient.setColorAt( 1.0, buttonColor );
#else
QLinearGradient gradient( 0, 0, 0, 1 );
gradient.setCoordinateMode( QGradient::StretchToDeviceMode );
gradient.setColorAt( 0.0, Qt::white );
gradient.setColorAt( 0.7, buttonColor );
gradient.setColorAt( 1.0, buttonColor );
#endif
pal.setBrush( QPalette::Window, gradient );
setPalette( pal );
}
void Plot::resizeEvent( QResizeEvent *event )
{
QwtPlot::resizeEvent( event );
#ifdef Q_WS_X11
updateGradient();
#endif
}
int main( int argc, char **argv )
{
QApplication a( argc, argv );
Plot *plot = new Plot();
// We put a dummy widget around to have
// so that Qt paints a widget background
// when resizing
QWidget window;
QHBoxLayout *layout = new QHBoxLayout( &window );
layout->setContentsMargins( 0, 0, 0, 0 );
layout->addWidget( plot );
window.resize( 600, 400 );
window.show();
return a.exec();
}
<commit_msg>Arrow symbol added <commit_after>#include <qapplication.h>
#include <qlayout.h>
#include <qwt_plot.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_curve.h>
#include <qwt_legend.h>
#include <qwt_point_data.h>
#include <qwt_plot_canvas.h>
#include <qwt_plot_panner.h>
#include <qwt_plot_magnifier.h>
#include <qwt_text.h>
#include <qwt_symbol.h>
#include <qwt_math.h>
#include <math.h>
//-----------------------------------------------------------------
// simple.cpp
//
// A simple example which shows how to use QwtPlot connected
// to a data class without any storage, calculating each values
// on the fly.
//-----------------------------------------------------------------
class FunctionData: public QwtSyntheticPointData
{
public:
FunctionData( double( *y )( double ) ):
QwtSyntheticPointData( 100 ),
d_y( y )
{
}
virtual double y( double x ) const
{
return d_y( x );
}
private:
double( *d_y )( double );
};
class ArrowSymbol: public QwtSymbol
{
public:
ArrowSymbol()
{
QPen pen( Qt::black, 0 );
pen.setJoinStyle( Qt::MiterJoin );
setPen( pen );
setBrush( Qt::red );
QPainterPath path;
path.moveTo( 0, 8 );
path.lineTo( 0, 5 );
path.lineTo( -3, 5 );
path.lineTo( 0, 0 );
path.lineTo( 3, 5 );
path.lineTo( 0, 5 );
QTransform transform;
transform.rotate( -30.0 );
path = transform.map( path );
setPath( path );
setSize( 10, 14 );
}
};
class Plot : public QwtPlot
{
public:
Plot( QWidget *parent = NULL );
protected:
virtual void resizeEvent( QResizeEvent * );
private:
void populate();
void updateGradient();
};
Plot::Plot( QWidget *parent ):
QwtPlot( parent )
{
// panning with the left mouse button
( void ) new QwtPlotPanner( canvas() );
// zoom in/out with the wheel
( void ) new QwtPlotMagnifier( canvas() );
setAutoFillBackground( true );
setPalette( QPalette( QColor( 165, 193, 228 ) ) );
updateGradient();
setTitle( "A Simple QwtPlot Demonstration" );
insertLegend( new QwtLegend(), QwtPlot::RightLegend );
// axes
setAxisTitle( xBottom, "x -->" );
setAxisScale( xBottom, 0.0, 10.0 );
setAxisTitle( yLeft, "y -->" );
setAxisScale( yLeft, -1.0, 1.0 );
// canvas
canvas()->setLineWidth( 1 );
canvas()->setFrameStyle( QFrame::Box | QFrame::Plain );
canvas()->setBorderRadius( 15 );
QPalette canvasPalette( Qt::white );
canvasPalette.setColor( QPalette::Foreground, QColor( 133, 190, 232 ) );
canvas()->setPalette( canvasPalette );
populate();
}
void Plot::populate()
{
// Insert new curves
QwtPlotCurve *cSin = new QwtPlotCurve( "y = sin(x)" );
cSin->setRenderHint( QwtPlotItem::RenderAntialiased );
cSin->setLegendAttribute( QwtPlotCurve::LegendShowLine, true );
cSin->setPen( QPen( Qt::red ) );
cSin->attach( this );
QwtPlotCurve *cCos = new QwtPlotCurve( "y = cos(x)" );
cCos->setRenderHint( QwtPlotItem::RenderAntialiased );
cCos->setLegendAttribute( QwtPlotCurve::LegendShowLine, true );
cCos->setPen( QPen( Qt::blue ) );
cCos->attach( this );
// Create sin and cos data
cSin->setData( new FunctionData( ::sin ) );
cCos->setData( new FunctionData( ::cos ) );
// Insert markers
// ...a horizontal line at y = 0...
QwtPlotMarker *mY = new QwtPlotMarker();
mY->setLabel( QString::fromLatin1( "y = 0" ) );
mY->setLabelAlignment( Qt::AlignRight | Qt::AlignTop );
mY->setLineStyle( QwtPlotMarker::HLine );
mY->setYValue( 0.0 );
mY->attach( this );
// ...a vertical line at x = 2 * pi
QwtPlotMarker *mX = new QwtPlotMarker();
mX->setLabel( QString::fromLatin1( "x = 2 pi" ) );
mX->setLabelAlignment( Qt::AlignLeft | Qt::AlignBottom );
mX->setLabelOrientation( Qt::Vertical );
mX->setLineStyle( QwtPlotMarker::VLine );
mX->setLinePen( QPen( Qt::black, 0, Qt::DashDotLine ) );
mX->setXValue( 2.0 * M_PI );
mX->attach( this );
const double x = 7.7;
// an arrow at a specific position
QwtPlotMarker *mPos = new QwtPlotMarker();
mPos->setRenderHint( QwtPlotItem::RenderAntialiased, true );
mPos->setSymbol( new ArrowSymbol() );
mPos->setValue( QPointF( x, ::sin( x ) ) );
mPos->setLabel(
QString( "( %1,%2 )" ).arg( x ).arg( ::sin( x ) ) );
mPos->setLabelAlignment( Qt::AlignRight | Qt::AlignBottom );
mPos->attach( this );
}
void Plot::updateGradient()
{
QPalette pal = palette();
const QColor buttonColor = pal.color( QPalette::Button );
#ifdef Q_WS_X11
// Qt 4.7.1: QGradient::StretchToDeviceMode is buggy on X11
QLinearGradient gradient( rect().topLeft(), rect().bottomLeft() );
gradient.setColorAt( 0.0, Qt::white );
gradient.setColorAt( 0.7, buttonColor );
gradient.setColorAt( 1.0, buttonColor );
#else
QLinearGradient gradient( 0, 0, 0, 1 );
gradient.setCoordinateMode( QGradient::StretchToDeviceMode );
gradient.setColorAt( 0.0, Qt::white );
gradient.setColorAt( 0.7, buttonColor );
gradient.setColorAt( 1.0, buttonColor );
#endif
pal.setBrush( QPalette::Window, gradient );
setPalette( pal );
}
void Plot::resizeEvent( QResizeEvent *event )
{
QwtPlot::resizeEvent( event );
#ifdef Q_WS_X11
updateGradient();
#endif
}
int main( int argc, char **argv )
{
QApplication a( argc, argv );
Plot *plot = new Plot();
// We put a dummy widget around to have
// so that Qt paints a widget background
// when resizing
QWidget window;
QHBoxLayout *layout = new QHBoxLayout( &window );
layout->setContentsMargins( 0, 0, 0, 0 );
layout->addWidget( plot );
window.resize( 600, 400 );
window.show();
return a.exec();
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// drop_plan.cpp
//
// Identification: src/planner/drop_plan.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "planner/update_plan.h"
#include "planner/project_info.h"
#include "common/types.h"
#include "storage/data_table.h"
#include "catalog/bootstrapper.h"
#include "parser/statement_update.h"
#include "parser/table_ref.h"
namespace peloton {
namespace planner {
UpdatePlan::UpdatePlan(storage::DataTable *table,
std::unique_ptr<const planner::ProjectInfo> project_info) :
target_table_(table), project_info_(std::move(project_info)), updates(
NULL), where(NULL) {
}
UpdatePlan::UpdatePlan(parser::UpdateStatement *parse_tree) {
auto t_ref = parse_tree->table;
table_name = std::string(t_ref->name);
target_table_ = catalog::Bootstrapper::global_catalog->GetTableFromDatabase(
DEFAULT_DB_NAME, table_name);
updates = new std::vector<parser::UpdateClause*>();
for(auto update : *parse_tree->updates) {
updates->emplace_back(update->Copy());
}
TargetList tlist;
DirectMapList dmlist;
oid_t col_id;
auto schema = target_table_->GetSchema();
std::vector<oid_t> columns;
for (auto update : *updates) {
// get oid_t of the column and push it to the vector;
col_id = schema->GetColumnID(std::string(update->column));
LOG_INFO("This is the column ID -------------------------> %d" , col_id);
columns.push_back(col_id);
tlist.emplace_back(col_id, update->value);
}
for (uint i = 0; i < schema->GetColumns().size(); i++) {
if(schema->GetColumns()[i].column_name != schema->GetColumns()[col_id].column_name)
dmlist.emplace_back(i,
std::pair<oid_t, oid_t>(0, i));
}
std::unique_ptr<const planner::ProjectInfo> project_info(
new planner::ProjectInfo(std::move(tlist), std::move(dmlist)));
project_info_ = std::move(project_info);
auto expr = parse_tree->where->Copy();
ReplaceColumnExpressions(expr);
std::unique_ptr<planner::SeqScanPlan> seq_scan_node(
new planner::SeqScanPlan(target_table_, expr, columns));
AddChild(std::move(seq_scan_node));
}
void UpdatePlan::ReplaceColumnExpressions(expression::AbstractExpression* expression) {
LOG_INFO("Expression Type --> %s", ExpressionTypeToString(expression->GetExpressionType()).c_str());
LOG_INFO("Left Type --> %s", ExpressionTypeToString(expression->GetLeft()->GetExpressionType()).c_str());
LOG_INFO("Right Type --> %s", ExpressionTypeToString(expression->GetRight()->GetExpressionType()).c_str());
if(expression->GetLeft()->GetExpressionType() == EXPRESSION_TYPE_COLUMN_REF) {
auto expr = expression->GetLeft();
std::string col_name(expr->getName());
LOG_INFO("Column name: %s", col_name.c_str());
delete expr;
expression->setLeft(ConvertToTupleValueExpression(col_name));
}
else if (expression->GetRight()->GetExpressionType() == EXPRESSION_TYPE_COLUMN_REF) {
auto expr = expression->GetRight();
std::string col_name(expr->getName());
LOG_INFO("Column name: %s", col_name.c_str());
delete expr;
expression->setRight(ConvertToTupleValueExpression(col_name));
}
else {
ReplaceColumnExpressions(expression->GetModifiableLeft());
ReplaceColumnExpressions(expression->GetModifiableRight());
}
}
/**
* This function generates a TupleValue expression from the column name
*/
expression::AbstractExpression* UpdatePlan::ConvertToTupleValueExpression (std::string column_name) {
auto schema = target_table_->GetSchema();
auto column_id = schema->GetColumnID(column_name);
LOG_INFO("Column id in table: %u", column_id);
expression::TupleValueExpression *expr =
new expression::TupleValueExpression(schema->GetType(column_id), 0, column_id);
return expr;
}
} // namespace planner
} // namespace peloton
<commit_msg>update_plan<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// drop_plan.cpp
//
// Identification: src/planner/drop_plan.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "planner/update_plan.h"
#include "planner/project_info.h"
#include "common/types.h"
#include "storage/data_table.h"
#include "catalog/bootstrapper.h"
#include "parser/statement_update.h"
#include "parser/table_ref.h"
namespace peloton {
namespace planner {
UpdatePlan::UpdatePlan(storage::DataTable *table,
std::unique_ptr<const planner::ProjectInfo> project_info) :
target_table_(table), project_info_(std::move(project_info)), updates(
NULL), where(NULL) {
}
UpdatePlan::UpdatePlan(parser::UpdateStatement *parse_tree) {
auto t_ref = parse_tree->table;
table_name = std::string(t_ref->name);
target_table_ = catalog::Bootstrapper::global_catalog->GetTableFromDatabase(
DEFAULT_DB_NAME, table_name);
updates = parse_tree->updates;
TargetList tlist;
DirectMapList dmlist;
oid_t col_id;
auto schema = target_table_->GetSchema();
std::vector<oid_t> columns;
for (auto update : *updates) {
// get oid_t of the column and push it to the vector;
col_id = schema->GetColumnID(std::string(update->column));
LOG_INFO("This is the column ID -------------------------> %d" , col_id);
columns.push_back(col_id);
tlist.emplace_back(col_id, update->value->Copy());
}
for (uint i = 0; i < schema->GetColumns().size(); i++) {
if(schema->GetColumns()[i].column_name != schema->GetColumns()[col_id].column_name)
dmlist.emplace_back(i,
std::pair<oid_t, oid_t>(0, i));
}
std::unique_ptr<const planner::ProjectInfo> project_info(
new planner::ProjectInfo(std::move(tlist), std::move(dmlist)));
project_info_ = std::move(project_info);
auto expr = parse_tree->where->Copy();
ReplaceColumnExpressions(expr);
std::unique_ptr<planner::SeqScanPlan> seq_scan_node(
new planner::SeqScanPlan(target_table_, expr, columns));
AddChild(std::move(seq_scan_node));
}
void UpdatePlan::ReplaceColumnExpressions(expression::AbstractExpression* expression) {
LOG_INFO("Expression Type --> %s", ExpressionTypeToString(expression->GetExpressionType()).c_str());
LOG_INFO("Left Type --> %s", ExpressionTypeToString(expression->GetLeft()->GetExpressionType()).c_str());
LOG_INFO("Right Type --> %s", ExpressionTypeToString(expression->GetRight()->GetExpressionType()).c_str());
if(expression->GetLeft()->GetExpressionType() == EXPRESSION_TYPE_COLUMN_REF) {
auto expr = expression->GetLeft();
std::string col_name(expr->getName());
LOG_INFO("Column name: %s", col_name.c_str());
delete expr;
expression->setLeft(ConvertToTupleValueExpression(col_name));
}
else if (expression->GetRight()->GetExpressionType() == EXPRESSION_TYPE_COLUMN_REF) {
auto expr = expression->GetRight();
std::string col_name(expr->getName());
LOG_INFO("Column name: %s", col_name.c_str());
delete expr;
expression->setRight(ConvertToTupleValueExpression(col_name));
}
else {
ReplaceColumnExpressions(expression->GetModifiableLeft());
ReplaceColumnExpressions(expression->GetModifiableRight());
}
}
/**
* This function generates a TupleValue expression from the column name
*/
expression::AbstractExpression* UpdatePlan::ConvertToTupleValueExpression (std::string column_name) {
auto schema = target_table_->GetSchema();
auto column_id = schema->GetColumnID(column_name);
LOG_INFO("Column id in table: %u", column_id);
expression::TupleValueExpression *expr =
new expression::TupleValueExpression(schema->GetType(column_id), 0, column_id);
return expr;
}
} // namespace planner
} // namespace peloton
<|endoftext|> |
<commit_before>#ifndef REFLECTION_BINDING_HPP
#define REFLECTION_BINDING_HPP
#include <string>
#include <type_traits>
#include <utility>
#include "any.hpp"
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <type_list.hpp>
#include <void_t.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
// address of signature
typedef any (*address_of_signature)(any&);
// dereference signature
typedef any (*dereference_signature)(any&);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
} // namespace free_function_detail
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
} // namespace member_function_detail
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
} // namespace member_variable_detail
namespace constructor_detail
{
// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out =
T{argument_array[Seq]
.get<typename std::remove_reference<ParamTypes>::type>()...};
return out;
}
};
template <class T, class... ParamTypes>
struct braced_init_selector_impl<
metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
T,
ParamTypes...>
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out =
T(argument_array[Seq]
.get<typename std::remove_reference<ParamTypes>::type>()...);
return out;
}
};
template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
argument_array, param_sequence());
}
} // namespace constructor_detail
namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;
template <>
struct conversion_specializer<void, void>;
template <class TargetType, class SourceType>
struct conversion_specializer<
TargetType,
SourceType,
std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>
{
static any
dispatch(const any& src)
{
TargetType temp = static_cast<TargetType>(src.get<SourceType>());
return temp;
}
};
template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
} // namespace conversion_detail
namespace string_serialization_detail
{
template <class T, class = void>
struct string_serialize_type_selector;
template <class T>
struct string_serialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static std::string
dispatch(const any& value)
{
return std::to_string(value.get<T>());
}
};
template <>
struct string_serialize_type_selector<std::string>
{
static std::string
dispatch(const any& value)
{
return value.get<std::string>();
}
};
template <>
struct string_serialize_type_selector<char>
{
static std::string
dispatch(const any& value)
{
std::string out;
out.push_back(value.get<char>());
return out;
}
};
template <>
struct string_serialize_type_selector<void>
{
static std::string
dispatch(const any&)
{
return "empty";
}
};
template <class T>
std::string
generic_string_serialization_bind_point(const any& value)
{
return string_serialize_type_selector<T>::dispatch(value);
}
template <class T, class = void>
struct string_deserialize_type_selector;
template <class T>
struct string_deserialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static any
dispatch(const std::string& str_value)
{
T out = std::stold(str_value);
return out;
}
};
template <>
struct string_deserialize_type_selector<char>
{
static any
dispatch(const std::string& str_value)
{
return str_value[0];
}
};
template <>
struct string_deserialize_type_selector<std::string>
{
static any
dispatch(const std::string& str_value)
{
return str_value;
}
};
template <>
struct string_deserialize_type_selector<int>
{
static any
dispatch(const std::string& str_value)
{
return std::stoi(str_value);
}
};
template <>
struct string_deserialize_type_selector<long>
{
static any
dispatch(const std::string& str_value)
{
return std::stol(str_value);
}
};
template <>
struct string_deserialize_type_selector<long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoll(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoul(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoull(str_value);
}
};
template <>
struct string_deserialize_type_selector<float>
{
static any
dispatch(const std::string& str_value)
{
return std::stof(str_value);
}
};
template <>
struct string_deserialize_type_selector<double>
{
static any
dispatch(const std::string& str_value)
{
return std::stod(str_value);
}
};
template <>
struct string_deserialize_type_selector<long double>
{
static any
dispatch(const std::string& str_value)
{
return std::stold(str_value);
}
};
template <>
struct string_deserialize_type_selector<void>
{
static any
dispatch(const std::string&)
{
return shadow::any();
}
};
template <class T>
any
generic_string_deserialization_bind_point(const std::string& str_value)
{
return string_deserialize_type_selector<T>::dispatch(str_value);
}
} // namespace string_serialization_detail
namespace pointer_detail
{
template <class T>
inline any
generic_address_of_bind_point(any& value)
{
return any(&(value.get<T>()));
}
template <>
inline any
generic_address_of_bind_point<void>(any&)
{
return any(nullptr);
}
template <class T>
inline any
generic_dereference_bind_point(any& value)
{
return any(*(value.get<T*>()));
}
template <>
inline any
generic_dereference_bind_point<void>(any&)
{
return any();
}
} // namespace pointer_detail
} // namespace shadow
#endif
<commit_msg>Use ostream operator<< for arithmetic types in generic_string_serialization_bind_point. modified: include/reflection_binding.hpp<commit_after>#ifndef REFLECTION_BINDING_HPP
#define REFLECTION_BINDING_HPP
#include <string>
#include <type_traits>
#include <utility>
#include <sstream>
#include "any.hpp"
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <type_list.hpp>
#include <void_t.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
// address of signature
typedef any (*address_of_signature)(any&);
// dereference signature
typedef any (*dereference_signature)(any&);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
} // namespace free_function_detail
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
} // namespace member_function_detail
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
} // namespace member_variable_detail
namespace constructor_detail
{
// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out =
T{argument_array[Seq]
.get<typename std::remove_reference<ParamTypes>::type>()...};
return out;
}
};
template <class T, class... ParamTypes>
struct braced_init_selector_impl<
metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
T,
ParamTypes...>
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out =
T(argument_array[Seq]
.get<typename std::remove_reference<ParamTypes>::type>()...);
return out;
}
};
template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
argument_array, param_sequence());
}
} // namespace constructor_detail
namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;
template <>
struct conversion_specializer<void, void>;
template <class TargetType, class SourceType>
struct conversion_specializer<
TargetType,
SourceType,
std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>
{
static any
dispatch(const any& src)
{
TargetType temp = static_cast<TargetType>(src.get<SourceType>());
return temp;
}
};
template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
} // namespace conversion_detail
namespace string_serialization_detail
{
template <class T, class = void>
struct string_serialize_type_selector;
template <class T>
struct string_serialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static std::string
dispatch(const any& value)
{
std::ostringstream out;
out << value.get<T>();
return out.str();
}
};
template <>
struct string_serialize_type_selector<std::string>
{
static std::string
dispatch(const any& value)
{
return value.get<std::string>();
}
};
template <>
struct string_serialize_type_selector<char>
{
static std::string
dispatch(const any& value)
{
std::string out;
out.push_back(value.get<char>());
return out;
}
};
template <>
struct string_serialize_type_selector<void>
{
static std::string
dispatch(const any&)
{
return "empty";
}
};
template <class T>
std::string
generic_string_serialization_bind_point(const any& value)
{
return string_serialize_type_selector<T>::dispatch(value);
}
template <class T, class = void>
struct string_deserialize_type_selector;
template <class T>
struct string_deserialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static any
dispatch(const std::string& str_value)
{
T out = std::stold(str_value);
return out;
}
};
template <>
struct string_deserialize_type_selector<char>
{
static any
dispatch(const std::string& str_value)
{
return str_value[0];
}
};
template <>
struct string_deserialize_type_selector<std::string>
{
static any
dispatch(const std::string& str_value)
{
return str_value;
}
};
template <>
struct string_deserialize_type_selector<int>
{
static any
dispatch(const std::string& str_value)
{
return std::stoi(str_value);
}
};
template <>
struct string_deserialize_type_selector<long>
{
static any
dispatch(const std::string& str_value)
{
return std::stol(str_value);
}
};
template <>
struct string_deserialize_type_selector<long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoll(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoul(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoull(str_value);
}
};
template <>
struct string_deserialize_type_selector<float>
{
static any
dispatch(const std::string& str_value)
{
return std::stof(str_value);
}
};
template <>
struct string_deserialize_type_selector<double>
{
static any
dispatch(const std::string& str_value)
{
return std::stod(str_value);
}
};
template <>
struct string_deserialize_type_selector<long double>
{
static any
dispatch(const std::string& str_value)
{
return std::stold(str_value);
}
};
template <>
struct string_deserialize_type_selector<void>
{
static any
dispatch(const std::string&)
{
return shadow::any();
}
};
template <class T>
any
generic_string_deserialization_bind_point(const std::string& str_value)
{
return string_deserialize_type_selector<T>::dispatch(str_value);
}
} // namespace string_serialization_detail
namespace pointer_detail
{
template <class T>
inline any
generic_address_of_bind_point(any& value)
{
return any(&(value.get<T>()));
}
template <>
inline any
generic_address_of_bind_point<void>(any&)
{
return any(nullptr);
}
template <class T>
inline any
generic_dereference_bind_point(any& value)
{
return any(*(value.get<T*>()));
}
template <>
inline any
generic_dereference_bind_point<void>(any&)
{
return any();
}
} // namespace pointer_detail
} // namespace shadow
#endif
<|endoftext|> |
<commit_before>#ifndef VIGRA_VISIT_BORDER_HXX_
#define VIGRA_VISIT_BORDER_HXX_
#include <vigra/multi_array.hxx>
namespace vigra
{
namespace visit_border_detail
{
template <unsigned int K>
struct visit_border_impl
{
template <unsigned int N, class Data, class S1,
class Label, class S2,
class Shape, class Visitor>
static void exec(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2> u_labels,
const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2> v_labels,
const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
{
static const unsigned int D = K - 1;
typedef visit_border_impl<D> next;
if(block_difference[D] == -1)
{
MultiArrayIndex last = v_data.shape(D) - 1;
next::exec(u_data.bindAt(D, 0), u_labels.bindAt(D, 0),
v_data.bindAt(D, last), v_labels.bindAt(D, last),
block_difference, neighborhood, visitor);
}
else if(block_difference[D] == 1)
{
MultiArrayIndex last = u_data.shape(D) - 1;
next::exec(u_data.bindAt(D, last), u_labels.bindAt(D, last),
v_data.bindAt(D, 0), v_labels.bindAt(D, 0),
block_difference, neighborhood, visitor);
}
else if(block_difference[D] == 0)
{
next::exec(u_data, u_labels, v_data, v_labels, block_difference, neighborhood, visitor);
}
else
{
vigra_precondition(false, "invalid block difference");
}
}
};
template <>
struct visit_border_impl<0>
{
template <class Data, class S1,
class Label, class S2,
class Shape, class Visitor>
static void exec(const MultiArrayView<0, Data, S1>& u_data, MultiArrayView<0, Label, S2> u_labels,
const MultiArrayView<0, Data, S1>& v_data, MultiArrayView<0, Label, S2> v_labels,
const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
{
visitor(u_data(0), u_labels(0), v_data(0), v_labels(0), block_difference);
}
template <unsigned int N, class Data, class S1,
class Label, class S2,
class Shape, class Visitor>
static void exec(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2> u_labels,
const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2> v_labels,
const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
{
if(neighborhood == DirectNeighborhood)
{
typedef typename MultiArrayView<N, Data, S1>::const_iterator DataIterator;
typedef typename MultiArrayView<N, Label, S2>::iterator LabelsIterator;
DataIterator u_data_it = u_data.begin();
LabelsIterator u_labels_it = u_labels.begin();
DataIterator v_data_it = v_data.begin();
LabelsIterator v_labels_it = v_labels.begin();
for( ; u_data_it != u_data.end(); ++u_data_it, ++u_labels_it, ++v_data_it, ++v_labels_it)
{
visitor(*u_data_it, *u_labels_it, *v_data_it, *v_labels_it, block_difference);
}
}
else if(neighborhood == IndirectNeighborhood)
{
typedef GridGraph<N, undirected_tag> Graph;
typedef typename Graph::NodeIt GraphScanner;
typedef typename Graph::OutArcIt NeighborIterator;
static const int global_dim_number = Shape::static_size;
TinyVector<unsigned int, N> dim_mapping; // mapping of every local dimension to their actual global dimension indices
int local_dims_pos = 0;
int global_dims_pos = 0;
for( ; global_dims_pos != global_dim_number; ++global_dims_pos)
{
if(block_difference[global_dims_pos] == 0)
{
vigra_assert(local_dims_pos != N, "");
dim_mapping[local_dims_pos] = global_dims_pos;
++local_dims_pos;
}
}
vigra_assert(local_dims_pos == N, "");
Graph graph(u_data.shape(), neighborhood);
Shape pixel_difference = block_difference;
for(GraphScanner node(graph); node != lemon::INVALID; ++node)
{
// compare neighbors that have have equal coordinates in all unbound dimensions
// their pixel-level difference is exactly block_difference
visitor(u_data[*node], u_labels[*node], v_data[*node], v_labels[*node], block_difference);
// now let unbound dimensions vary
for(NeighborIterator arc(graph, *node); arc != lemon::INVALID; ++arc)
{
for(int i = 0; i != N; ++i)
pixel_difference[dim_mapping[i]] = graph.target(*arc)[i];
visitor(u_data[*node], u_labels[*node], v_data[graph.target(*arc)], v_labels[graph.target(*arc)], pixel_difference);
}
}
}
}
};
}
template <unsigned int N, class Data, class S1,
class Label, class S2,
class Shape, class Visitor>
void visitBorder(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2>& u_labels,
const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2>& v_labels,
const Shape& difference, NeighborhoodType neighborhood, Visitor visitor)
{
vigra_precondition(u_data.shape() == u_labels.shape() && v_data.shape() == v_labels.shape(),
"differing block shapes");
visit_border_detail::visit_border_impl<N>::exec(u_data, u_labels,
v_data, v_labels,
difference, neighborhood, visitor);
}
}
#endif
<commit_msg>fix visit border pixel diff problem<commit_after>#ifndef VIGRA_VISIT_BORDER_HXX_
#define VIGRA_VISIT_BORDER_HXX_
#include <vigra/multi_array.hxx>
namespace vigra
{
namespace visit_border_detail
{
template <unsigned int K>
struct visit_border_impl
{
template <unsigned int N, class Data, class S1,
class Label, class S2,
class Shape, class Visitor>
static void exec(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2> u_labels,
const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2> v_labels,
const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
{
static const unsigned int D = K - 1;
typedef visit_border_impl<D> next;
if(block_difference[D] == -1)
{
MultiArrayIndex last = v_data.shape(D) - 1;
next::exec(u_data.bindAt(D, 0), u_labels.bindAt(D, 0),
v_data.bindAt(D, last), v_labels.bindAt(D, last),
block_difference, neighborhood, visitor);
}
else if(block_difference[D] == 1)
{
MultiArrayIndex last = u_data.shape(D) - 1;
next::exec(u_data.bindAt(D, last), u_labels.bindAt(D, last),
v_data.bindAt(D, 0), v_labels.bindAt(D, 0),
block_difference, neighborhood, visitor);
}
else if(block_difference[D] == 0)
{
next::exec(u_data, u_labels, v_data, v_labels, block_difference, neighborhood, visitor);
}
else
{
vigra_precondition(false, "invalid block difference");
}
}
};
template <>
struct visit_border_impl<0>
{
template <class Data, class S1,
class Label, class S2,
class Shape, class Visitor>
static void exec(const MultiArrayView<0, Data, S1>& u_data, MultiArrayView<0, Label, S2> u_labels,
const MultiArrayView<0, Data, S1>& v_data, MultiArrayView<0, Label, S2> v_labels,
const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
{
visitor(u_data(0), u_labels(0), v_data(0), v_labels(0), block_difference);
}
template <unsigned int N, class Data, class S1,
class Label, class S2,
class Shape, class Visitor>
static void exec(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2> u_labels,
const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2> v_labels,
const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
{
if(neighborhood == DirectNeighborhood)
{
typedef typename MultiArrayView<N, Data, S1>::const_iterator DataIterator;
typedef typename MultiArrayView<N, Label, S2>::iterator LabelsIterator;
DataIterator u_data_it = u_data.begin();
LabelsIterator u_labels_it = u_labels.begin();
DataIterator v_data_it = v_data.begin();
LabelsIterator v_labels_it = v_labels.begin();
for( ; u_data_it != u_data.end(); ++u_data_it, ++u_labels_it, ++v_data_it, ++v_labels_it)
{
visitor(*u_data_it, *u_labels_it, *v_data_it, *v_labels_it, block_difference);
}
}
else if(neighborhood == IndirectNeighborhood)
{
typedef GridGraph<N, undirected_tag> Graph;
typedef typename Graph::NodeIt GraphScanner;
typedef typename Graph::OutArcIt NeighborIterator;
static const int global_dim_number = Shape::static_size;
TinyVector<unsigned int, N> dim_mapping; // mapping of every local dimension to their actual global dimension indices
int local_dims_pos = 0;
int global_dims_pos = 0;
for( ; global_dims_pos != global_dim_number; ++global_dims_pos)
{
if(block_difference[global_dims_pos] == 0)
{
vigra_assert(local_dims_pos != N, "");
dim_mapping[local_dims_pos] = global_dims_pos;
++local_dims_pos;
}
}
vigra_assert(local_dims_pos == N, "");
Graph graph(u_data.shape(), neighborhood);
Shape pixel_difference = block_difference;
for(GraphScanner node(graph); node != lemon::INVALID; ++node)
{
// compare neighbors that have have equal coordinates in all unbound dimensions
// their pixel-level difference is exactly block_difference
visitor(u_data[*node], u_labels[*node], v_data[*node], v_labels[*node], block_difference);
// now let unbound dimensions vary
for(NeighborIterator arc(graph, *node); arc != lemon::INVALID; ++arc)
{
for(int i = 0; i != N; ++i)
pixel_difference[dim_mapping[i]] = graph.target(*arc)[i] - (*node)[i];
visitor(u_data[*node], u_labels[*node], v_data[graph.target(*arc)], v_labels[graph.target(*arc)], pixel_difference);
}
}
}
}
};
}
template <unsigned int N, class Data, class S1,
class Label, class S2,
class Shape, class Visitor>
void visitBorder(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2>& u_labels,
const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2>& v_labels,
const Shape& difference, NeighborhoodType neighborhood, Visitor visitor)
{
vigra_precondition(u_data.shape() == u_labels.shape() && v_data.shape() == v_labels.shape(),
"differing block shapes");
visit_border_detail::visit_border_impl<N>::exec(u_data, u_labels,
v_data, v_labels,
difference, neighborhood, visitor);
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2016 - 2021 [email protected]
*
* 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 <fstream>
#include <ox/clargs/clargs.hpp>
#include <ox/fs/fs.hpp>
#include "pack/pack.hpp"
static ox::Error writeFileBuff(const ox::String &path, const ox::Vector<char> &buff) noexcept {
try {
std::ofstream f(path.c_str(), std::ios::binary);
f.write(buff.data(), static_cast<intptr_t>(buff.size()));
} catch (const std::fstream::failure&) {
return OxError(2, "failed to write file");
}
return OxError(0);
}
static ox::Error run(const ox::ClArgs &args) noexcept {
ox::trace::init();
const auto argSrc = args.getString("src", "");
const auto argDst = args.getString("dst", "");
if (argSrc == "") {
oxErr("\033[31;1;1merror:\033[0m must specify a source directory\n");
return OxError(1, "must specify a source directory");
}
if (argDst == "") {
oxErr("\033[31;1;1merror:\033[0m must specify a destination ROM file\n");
return OxError(1, "must specify a destination ROM file");
}
ox::Vector<char> buff(32 * ox::units::MB);
oxReturnError(ox::FileSystem32::format(buff.data(), buff.size()));
ox::PassThroughFS src(argSrc.c_str());
ox::FileSystem32 dst(ox::FileStore32(buff.data(), buff.size()));
oxReturnError(nostalgia::pack(&src, &dst));
oxReturnError(dst.resize());
oxRequire(dstSize, dst.size());
oxOutf("new size: {}\n", dstSize);
buff.resize(dstSize);
oxReturnError(writeFileBuff(argDst, buff));
return OxError(0);
}
int main(int argc, const char **args) {
const auto err = run(ox::ClArgs(argc, args));
oxAssert(err, "pack failed");
return static_cast<int>(err);
}
<commit_msg>[nostalgia/tools/pack] Replace ox::Vector<char> with ox::Buffer<commit_after>/*
* Copyright 2016 - 2021 [email protected]
*
* 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 <fstream>
#include <ox/clargs/clargs.hpp>
#include <ox/fs/fs.hpp>
#include "pack/pack.hpp"
static ox::Error writeFileBuff(const ox::String &path, const ox::Buffer &buff) noexcept {
try {
std::ofstream f(path.c_str(), std::ios::binary);
f.write(buff.data(), static_cast<intptr_t>(buff.size()));
} catch (const std::fstream::failure&) {
return OxError(2, "failed to write file");
}
return OxError(0);
}
static ox::Error run(const ox::ClArgs &args) noexcept {
ox::trace::init();
const auto argSrc = args.getString("src", "");
const auto argDst = args.getString("dst", "");
if (argSrc == "") {
oxErr("\033[31;1;1merror:\033[0m must specify a source directory\n");
return OxError(1, "must specify a source directory");
}
if (argDst == "") {
oxErr("\033[31;1;1merror:\033[0m must specify a destination ROM file\n");
return OxError(1, "must specify a destination ROM file");
}
ox::Buffer buff(32 * ox::units::MB);
oxReturnError(ox::FileSystem32::format(buff.data(), buff.size()));
ox::PassThroughFS src(argSrc.c_str());
ox::FileSystem32 dst(ox::FileStore32(buff.data(), buff.size()));
oxReturnError(nostalgia::pack(&src, &dst));
oxReturnError(dst.resize());
oxRequire(dstSize, dst.size());
oxOutf("new size: {}\n", dstSize);
buff.resize(dstSize);
oxReturnError(writeFileBuff(argDst, buff));
return OxError(0);
}
int main(int argc, const char **args) {
const auto err = run(ox::ClArgs(argc, args));
oxAssert(err, "pack failed");
return static_cast<int>(err);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: FilteredContainer.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-08-02 14:59:57 $
*
* 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 DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
namespace dbaccess
{
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//------------------------------------------------------------------------------
/** compare two strings
*/
extern int
#if defined( WNT )
__cdecl
#endif
#if defined( ICC ) && defined( OS2 )
_Optlink
#endif
NameCompare( const void* pFirst, const void* pSecond)
{
return reinterpret_cast< const ::rtl::OUString* >(pFirst)->compareTo(*reinterpret_cast< const ::rtl::OUString* >(pSecond));
}
//------------------------------------------------------------------------------
/** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
*/
sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
{
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::rtl::OUString* pTableFilters = _rTableFilter.getArray();
::rtl::OUString* pEnd = pTableFilters + _rTableFilter.getLength();
sal_Int32 nShiftPos = 0;
for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
{
if (pTableFilters->indexOf('%') != -1)
{
_rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
}
else
{
if (nShiftPos != i)
{
_rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
}
++nShiftPos;
}
}
// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
_rTableFilter.realloc(nShiftPos);
return nShiftPos;
}
//==========================================================================
//= OViewContainer
//==========================================================================
OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const Reference< XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener,
IWarningsContainer* _pWarningsContainer)
:OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
,m_bConstructed(sal_False)
,m_xConnection(_xCon)
,m_pWarningsContainer(_pWarningsContainer)
,m_pRefreshListener(_pRefreshListener)
{
}
// -------------------------------------------------------------------------
void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
m_xMasterContainer = _rxMasterContainer;
if(m_xMasterContainer.is())
{
addMasterContainerListener();
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
connectivity::TStringVector aTableNames;
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
if(!bNoTableFilters)
{
Sequence< ::rtl::OUString > aTableFilter = _rTableFilter;
Sequence< ::rtl::OUString > aTableTypeFilter = _rTableTypeFilter;
// build sorted versions of the filter sequences, so the visibility decision is faster
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
aTableNames.push_back(*pBegin);
}
}
else
{
// no filter so insert all names
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
aTableNames = connectivity::TStringVector(pBegin,pEnd);
}
reFill(aTableNames);
m_bConstructed = sal_True;
}
else
{
construct(_rTableFilter,_rTableTypeFilter);
}
}
//------------------------------------------------------------------------------
void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
// build sorted versions of the filter sequences, so the visibility decision is faster
Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
sal_Int32 nTableFilterLen = aTableFilter.getLength();
if (nTableFilterLen)
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch;
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
try
{
if (m_xMetaData.is())
{
static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
if ( m_bConstructed && sTableTypes.getLength() == 0 )
return;
Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
if (xCurrentRow.is())
{
// after creation the set is positioned before the first record, per definitionem
::rtl::OUString sCatalog, sSchema, sName, sType;
::rtl::OUString sComposedName;
// we first collect the names and construct the OTable objects later, as the ctor of the table may need
// another result set from the connection, and some drivers support only one statement per connection
sal_Bool bFilterMatch;
while (xTables->next())
{
sCatalog = xCurrentRow->getString(1);
sSchema = xCurrentRow->getString(2);
sName = xCurrentRow->getString(3);
// we're not interested in the "wasNull", as the getStrings would return an empty string in
// that case, which is sufficient here
composeTableName(m_xMetaData, sCatalog, sSchema, sName, sComposedName, sal_False,::dbtools::eInDataManipulation);
bFilterMatch = bNoTableFilters
|| ((nTableFilterLen != 0) && (NULL != bsearch(&sComposedName, aTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare)));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && aWCSearch.size())
{ // or if one of the wildcrad expression matches
for ( ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
aLoop != aWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sComposedName);
}
if (bFilterMatch)
{ // the table name is allowed (not filtered out)
insertElement(sComposedName,NULL);
}
}
// dispose the tables result set, in case the connection can handle only one concurrent statement
// (the table object creation will need it's own statements)
disposeComponent(xTables);
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
}
catch (SQLException&)
{
OSL_ENSURE(0,"OFilteredContainer::construct : catched an SQL-Exception !");
disposing();
return;
}
m_bConstructed = sal_True;
}
//------------------------------------------------------------------------------
void OFilteredContainer::disposing()
{
OCollection::disposing();
removeMasterContainerListener();
m_xMasterContainer = NULL;
m_xMetaData = NULL;
m_pWarningsContainer = NULL;
m_pRefreshListener = NULL;
m_bConstructed = sal_False;
}
// -------------------------------------------------------------------------
void OFilteredContainer::impl_refresh() throw(RuntimeException)
{
if ( m_pRefreshListener )
{
m_bConstructed = sal_False;
Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
if ( xRefresh.is() )
xRefresh->refresh();
m_pRefreshListener->refresh(this);
}
}
// -------------------------------------------------------------------------
sal_Bool OFilteredContainer::isNameValid( const ::rtl::OUString& _rName,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter,
const ::std::vector< WildCard >& _rWCSearch) const
{
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
sal_Bool bFilterMatch = (NULL != bsearch(&_rName, _rTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && !_rWCSearch.empty())
{ // or if one of the wildcrad expression matches
String sWCCompare = (const sal_Unicode*)_rName;
for ( ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
aLoop != _rWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sWCCompare);
}
return bFilterMatch;
}
// -------------------------------------------------------------------------
Reference< XNamed > OFilteredContainer::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference< XNamed > xName(_xDescriptor,UNO_QUERY);
OSL_ENSURE(xName.is(),"Must be a XName interface here !");
return xName.is() ? createObject(xName->getName()) : Reference< XNamed >();
}
// -----------------------------------------------------------------------------
// ..............................................................................
} // namespace
// ..............................................................................
<commit_msg>INTEGRATION: CWS dba24 (1.4.80); FILE MERGED 2005/02/10 16:52:05 fs 1.4.80.2: grammar and debug diagnostics 2005/02/09 08:12:57 oj 1.4.80.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
*
* $RCSfile: FilteredContainer.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2005-03-10 16:29:48 $
*
* 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 DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
namespace dbaccess
{
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//------------------------------------------------------------------------------
/** compare two strings
*/
extern int
#if defined( WNT )
__cdecl
#endif
#if defined( ICC ) && defined( OS2 )
_Optlink
#endif
NameCompare( const void* pFirst, const void* pSecond)
{
return reinterpret_cast< const ::rtl::OUString* >(pFirst)->compareTo(*reinterpret_cast< const ::rtl::OUString* >(pSecond));
}
//------------------------------------------------------------------------------
/** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
*/
sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
{
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::rtl::OUString* pTableFilters = _rTableFilter.getArray();
::rtl::OUString* pEnd = pTableFilters + _rTableFilter.getLength();
sal_Int32 nShiftPos = 0;
for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
{
if (pTableFilters->indexOf('%') != -1)
{
_rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
}
else
{
if (nShiftPos != i)
{
_rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
}
++nShiftPos;
}
}
// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
_rTableFilter.realloc(nShiftPos);
return nShiftPos;
}
//==========================================================================
//= OViewContainer
//==========================================================================
OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const Reference< XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener,
IWarningsContainer* _pWarningsContainer)
:OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
,m_bConstructed(sal_False)
,m_xConnection(_xCon)
,m_pWarningsContainer(_pWarningsContainer)
,m_pRefreshListener(_pRefreshListener)
{
}
// -------------------------------------------------------------------------
void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
m_xMasterContainer = _rxMasterContainer;
if(m_xMasterContainer.is())
{
addMasterContainerListener();
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
connectivity::TStringVector aTableNames;
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
if(!bNoTableFilters)
{
Sequence< ::rtl::OUString > aTableFilter = _rTableFilter;
Sequence< ::rtl::OUString > aTableTypeFilter = _rTableTypeFilter;
// build sorted versions of the filter sequences, so the visibility decision is faster
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
aTableNames.push_back(*pBegin);
}
}
else
{
// no filter so insert all names
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
aTableNames = connectivity::TStringVector(pBegin,pEnd);
}
reFill(aTableNames);
m_bConstructed = sal_True;
}
else
{
construct(_rTableFilter,_rTableTypeFilter);
}
}
//------------------------------------------------------------------------------
void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
// build sorted versions of the filter sequences, so the visibility decision is faster
Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
sal_Int32 nTableFilterLen = aTableFilter.getLength();
if (nTableFilterLen)
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch;
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
try
{
if (m_xMetaData.is())
{
static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
if ( m_bConstructed && sTableTypes.getLength() == 0 )
return;
Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
if (xCurrentRow.is())
{
// after creation the set is positioned before the first record, per definitionem
::rtl::OUString sCatalog, sSchema, sName, sType;
::rtl::OUString sComposedName;
// we first collect the names and construct the OTable objects later, as the ctor of the table may need
// another result set from the connection, and some drivers support only one statement per connection
sal_Bool bFilterMatch;
while (xTables->next())
{
sCatalog = xCurrentRow->getString(1);
sSchema = xCurrentRow->getString(2);
sName = xCurrentRow->getString(3);
#if OSL_DEBUG_LEVEL > 0
::rtl::OUString sTableType = xCurrentRow->getString(4);
#endif
// we're not interested in the "wasNull", as the getStrings would return an empty string in
// that case, which is sufficient here
composeTableName(m_xMetaData, sCatalog, sSchema, sName, sComposedName, sal_False,::dbtools::eInDataManipulation);
bFilterMatch = bNoTableFilters
|| ((nTableFilterLen != 0) && (NULL != bsearch(&sComposedName, aTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare)));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && aWCSearch.size())
{ // or if one of the wildcrad expression matches
for ( ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
aLoop != aWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sComposedName);
}
if (bFilterMatch)
{ // the table name is allowed (not filtered out)
insertElement(sComposedName,NULL);
}
}
// dispose the tables result set, in case the connection can handle only one concurrent statement
// (the table object creation will need it's own statements)
disposeComponent(xTables);
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
}
catch (SQLException&)
{
OSL_ENSURE(0,"OFilteredContainer::construct: caught an SQL-Exception !");
disposing();
return;
}
m_bConstructed = sal_True;
}
//------------------------------------------------------------------------------
void OFilteredContainer::disposing()
{
OCollection::disposing();
removeMasterContainerListener();
m_xMasterContainer = NULL;
m_xMetaData = NULL;
m_pWarningsContainer = NULL;
m_pRefreshListener = NULL;
m_bConstructed = sal_False;
}
// -------------------------------------------------------------------------
void OFilteredContainer::impl_refresh() throw(RuntimeException)
{
if ( m_pRefreshListener )
{
m_bConstructed = sal_False;
Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
if ( xRefresh.is() )
xRefresh->refresh();
m_pRefreshListener->refresh(this);
}
}
// -------------------------------------------------------------------------
sal_Bool OFilteredContainer::isNameValid( const ::rtl::OUString& _rName,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter,
const ::std::vector< WildCard >& _rWCSearch) const
{
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
sal_Bool bFilterMatch = (NULL != bsearch(&_rName, _rTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && !_rWCSearch.empty())
{ // or if one of the wildcrad expression matches
String sWCCompare = (const sal_Unicode*)_rName;
for ( ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
aLoop != _rWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sWCCompare);
}
return bFilterMatch;
}
// -----------------------------------------------------------------------------
::rtl::OUString OFilteredContainer::getNameForObject(const ObjectType& _xObject)
{
OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
return ::dbtools::composeTableName(m_xMetaData,_xObject,sal_False,::dbtools::eInDataManipulation);
}
// ..............................................................................
} // namespace
// ..............................................................................
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <svtools/fltcall.hxx>
//============================ XPMWriter ==================================
class XPMWriter {
private:
SvStream& m_rOStm; // Die auszugebende XPM-Datei
sal_uInt16 mpOStmOldModus;
sal_Bool mbStatus;
sal_Bool mbTrans;
BitmapReadAccess* mpAcc;
sal_uLong mnWidth, mnHeight; // Bildausmass in Pixeln
sal_uInt16 mnColors;
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator > xStatusIndicator;
void ImplCallback( sal_uInt16 nPercent );
sal_Bool ImplWriteHeader();
void ImplWritePalette();
void ImplWriteColor( sal_uInt16 );
void ImplWriteBody();
void ImplWriteNumber( sal_Int32 );
void ImplWritePixel( sal_uLong ) const;
public:
XPMWriter(SvStream& rOStm);
~XPMWriter();
sal_Bool WriteXPM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem );
};
//=================== Methoden von XPMWriter ==============================
XPMWriter::XPMWriter(SvStream& rOStm)
: m_rOStm(rOStm)
, mbStatus(sal_True)
, mbTrans(sal_False)
, mpAcc(NULL)
{
}
// ------------------------------------------------------------------------
XPMWriter::~XPMWriter()
{
}
// ------------------------------------------------------------------------
void XPMWriter::ImplCallback( sal_uInt16 nPercent )
{
if ( xStatusIndicator.is() )
{
if ( nPercent <= 100 )
xStatusIndicator->setValue( nPercent );
}
}
// ------------------------------------------------------------------------
sal_Bool XPMWriter::WriteXPM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem)
{
Bitmap aBmp;
if ( pFilterConfigItem )
{
xStatusIndicator = pFilterConfigItem->GetStatusIndicator();
if ( xStatusIndicator.is() )
{
rtl::OUString aMsg;
xStatusIndicator->start( aMsg, 100 );
}
}
BitmapEx aBmpEx( rGraphic.GetBitmapEx() );
aBmp = aBmpEx.GetBitmap();
if ( rGraphic.IsTransparent() ) // event. transparente Farbe erzeugen
{
mbTrans = sal_True;
if ( aBmp.GetBitCount() >= 8 ) // wenn noetig Bild auf 8 bit konvertieren
aBmp.Convert( BMP_CONVERSION_8BIT_TRANS );
else
aBmp.Convert( BMP_CONVERSION_4BIT_TRANS );
aBmp.Replace( aBmpEx.GetMask(), BMP_COL_TRANS );
}
else
{
if ( aBmp.GetBitCount() > 8 ) // wenn noetig Bild auf 8 bit konvertieren
aBmp.Convert( BMP_CONVERSION_8BIT_COLORS );
}
mpAcc = aBmp.AcquireReadAccess();
if ( mpAcc )
{
mnColors = mpAcc->GetPaletteEntryCount();
mpOStmOldModus = m_rOStm.GetNumberFormatInt();
m_rOStm.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
if ( ImplWriteHeader() )
{
ImplWritePalette();
ImplWriteBody();
m_rOStm << "\x22XPMENDEXT\x22\x0a};";
}
aBmp.ReleaseAccess( mpAcc );
}
else
mbStatus = sal_False;
m_rOStm.SetNumberFormatInt( mpOStmOldModus );
if ( xStatusIndicator.is() )
xStatusIndicator->end();
return mbStatus;
}
// ------------------------------------------------------------------------
sal_Bool XPMWriter::ImplWriteHeader()
{
mnWidth = mpAcc->Width();
mnHeight = mpAcc->Height();
if ( mnWidth && mnHeight && mnColors )
{
m_rOStm << "/* XPM */\x0astatic char * image[] = \x0a{\x0a\x22";
ImplWriteNumber( mnWidth );
m_rOStm << (sal_uInt8)32;
ImplWriteNumber( mnHeight );
m_rOStm << (sal_uInt8)32;
ImplWriteNumber( mnColors );
m_rOStm << (sal_uInt8)32;
ImplWriteNumber( ( mnColors > 26 ) ? 2 : 1 );
m_rOStm << "\x22,\x0a";
}
else mbStatus = sal_False;
return mbStatus;
}
// ------------------------------------------------------------------------
void XPMWriter::ImplWritePalette()
{
sal_uInt16 nTransIndex = 0xffff;
if ( mbTrans )
nTransIndex = mpAcc->GetBestMatchingColor( BMP_COL_TRANS );
for ( sal_uInt16 i = 0; i < mnColors; i++ )
{
m_rOStm << "\x22";
ImplWritePixel( i );
m_rOStm << (sal_uInt8)32;
if ( nTransIndex != i )
{
ImplWriteColor( i );
m_rOStm << "\x22,\x0a";
}
else
m_rOStm << "c none\x22,\x0a";
}
}
// ------------------------------------------------------------------------
void XPMWriter::ImplWriteBody()
{
for ( sal_uLong y = 0; y < mnHeight; y++ )
{
ImplCallback( (sal_uInt16)( ( 100 * y ) / mnHeight ) ); // processing output in percent
m_rOStm << (sal_uInt8)0x22;
for ( sal_uLong x = 0; x < mnWidth; x++ )
{
ImplWritePixel( (sal_uInt8)(mpAcc->GetPixel( y, x ) ) );
}
m_rOStm << "\x22,\x0a";
}
}
// ------------------------------------------------------------------------
// eine Dezimalzahl im ASCII format wird in den Stream geschrieben
void XPMWriter::ImplWriteNumber(sal_Int32 nNumber)
{
const rtl::OString aNum(rtl::OString::valueOf(nNumber));
m_rOStm << aNum.getStr();
}
// ------------------------------------------------------------------------
void XPMWriter::ImplWritePixel( sal_uLong nCol ) const
{
if ( mnColors > 26 )
{
sal_uInt8 nDiff = (sal_uInt8) ( nCol / 26 );
m_rOStm << (sal_uInt8)( nDiff + 'A' );
m_rOStm << (sal_uInt8)( nCol - ( nDiff*26 ) + 'A' );
}
else
m_rOStm << (sal_uInt8)( nCol + 'A' );
}
// ------------------------------------------------------------------------
// ein Farbwert wird im Hexadezimalzahlformat in den Stream geschrieben
void XPMWriter::ImplWriteColor( sal_uInt16 nNumber )
{
sal_uLong nTmp;
sal_uInt8 j;
m_rOStm << "c #"; // # zeigt einen folgenden Hexwert an
const BitmapColor& rColor = mpAcc->GetPaletteColor( nNumber );
nTmp = ( rColor.GetRed() << 16 ) | ( rColor.GetGreen() << 8 ) | rColor.GetBlue();
for ( signed char i = 20; i >= 0 ; i-=4 )
{
if ( ( j = (sal_uInt8)( nTmp >> i ) & 0xf ) > 9 )
j += 'A' - 10;
else
j += '0';
m_rOStm << j;
}
}
// ------------------------------------------------------------------------
// ---------------------
// - exported function -
// ---------------------
#ifdef DISABLE_DYNLOADING
#define GraphicExport expGraphicExport
#endif
extern "C" SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL
GraphicExport(SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pFilterConfigItem, sal_Bool)
{
XPMWriter aXPMWriter(rStream);
return aXPMWriter.WriteXPM( rGraphic, pFilterConfigItem );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#707516: Uninitialized scalar variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <svtools/fltcall.hxx>
//============================ XPMWriter ==================================
class XPMWriter {
private:
SvStream& m_rOStm; // Die auszugebende XPM-Datei
sal_Bool mbStatus;
sal_Bool mbTrans;
BitmapReadAccess* mpAcc;
sal_uLong mnWidth, mnHeight; // Bildausmass in Pixeln
sal_uInt16 mnColors;
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator > xStatusIndicator;
void ImplCallback( sal_uInt16 nPercent );
sal_Bool ImplWriteHeader();
void ImplWritePalette();
void ImplWriteColor( sal_uInt16 );
void ImplWriteBody();
void ImplWriteNumber( sal_Int32 );
void ImplWritePixel( sal_uLong ) const;
public:
XPMWriter(SvStream& rOStm);
~XPMWriter();
sal_Bool WriteXPM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem );
};
//=================== Methoden von XPMWriter ==============================
XPMWriter::XPMWriter(SvStream& rOStm)
: m_rOStm(rOStm)
, mbStatus(sal_True)
, mbTrans(sal_False)
, mpAcc(NULL)
{
}
// ------------------------------------------------------------------------
XPMWriter::~XPMWriter()
{
}
// ------------------------------------------------------------------------
void XPMWriter::ImplCallback( sal_uInt16 nPercent )
{
if ( xStatusIndicator.is() )
{
if ( nPercent <= 100 )
xStatusIndicator->setValue( nPercent );
}
}
// ------------------------------------------------------------------------
sal_Bool XPMWriter::WriteXPM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem)
{
Bitmap aBmp;
if ( pFilterConfigItem )
{
xStatusIndicator = pFilterConfigItem->GetStatusIndicator();
if ( xStatusIndicator.is() )
{
rtl::OUString aMsg;
xStatusIndicator->start( aMsg, 100 );
}
}
BitmapEx aBmpEx( rGraphic.GetBitmapEx() );
aBmp = aBmpEx.GetBitmap();
if ( rGraphic.IsTransparent() ) // event. transparente Farbe erzeugen
{
mbTrans = sal_True;
if ( aBmp.GetBitCount() >= 8 ) // wenn noetig Bild auf 8 bit konvertieren
aBmp.Convert( BMP_CONVERSION_8BIT_TRANS );
else
aBmp.Convert( BMP_CONVERSION_4BIT_TRANS );
aBmp.Replace( aBmpEx.GetMask(), BMP_COL_TRANS );
}
else
{
if ( aBmp.GetBitCount() > 8 ) // wenn noetig Bild auf 8 bit konvertieren
aBmp.Convert( BMP_CONVERSION_8BIT_COLORS );
}
mpAcc = aBmp.AcquireReadAccess();
if ( mpAcc )
{
sal_uInt16 nOStmOldModus = m_rOStm.GetNumberFormatInt();
m_rOStm.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
mnColors = mpAcc->GetPaletteEntryCount();
if ( ImplWriteHeader() )
{
ImplWritePalette();
ImplWriteBody();
m_rOStm << "\x22XPMENDEXT\x22\x0a};";
}
m_rOStm.SetNumberFormatInt(nOStmOldModus);
aBmp.ReleaseAccess( mpAcc );
}
else
mbStatus = sal_False;
if ( xStatusIndicator.is() )
xStatusIndicator->end();
return mbStatus;
}
// ------------------------------------------------------------------------
sal_Bool XPMWriter::ImplWriteHeader()
{
mnWidth = mpAcc->Width();
mnHeight = mpAcc->Height();
if ( mnWidth && mnHeight && mnColors )
{
m_rOStm << "/* XPM */\x0astatic char * image[] = \x0a{\x0a\x22";
ImplWriteNumber( mnWidth );
m_rOStm << (sal_uInt8)32;
ImplWriteNumber( mnHeight );
m_rOStm << (sal_uInt8)32;
ImplWriteNumber( mnColors );
m_rOStm << (sal_uInt8)32;
ImplWriteNumber( ( mnColors > 26 ) ? 2 : 1 );
m_rOStm << "\x22,\x0a";
}
else mbStatus = sal_False;
return mbStatus;
}
// ------------------------------------------------------------------------
void XPMWriter::ImplWritePalette()
{
sal_uInt16 nTransIndex = 0xffff;
if ( mbTrans )
nTransIndex = mpAcc->GetBestMatchingColor( BMP_COL_TRANS );
for ( sal_uInt16 i = 0; i < mnColors; i++ )
{
m_rOStm << "\x22";
ImplWritePixel( i );
m_rOStm << (sal_uInt8)32;
if ( nTransIndex != i )
{
ImplWriteColor( i );
m_rOStm << "\x22,\x0a";
}
else
m_rOStm << "c none\x22,\x0a";
}
}
// ------------------------------------------------------------------------
void XPMWriter::ImplWriteBody()
{
for ( sal_uLong y = 0; y < mnHeight; y++ )
{
ImplCallback( (sal_uInt16)( ( 100 * y ) / mnHeight ) ); // processing output in percent
m_rOStm << (sal_uInt8)0x22;
for ( sal_uLong x = 0; x < mnWidth; x++ )
{
ImplWritePixel( (sal_uInt8)(mpAcc->GetPixel( y, x ) ) );
}
m_rOStm << "\x22,\x0a";
}
}
// ------------------------------------------------------------------------
// eine Dezimalzahl im ASCII format wird in den Stream geschrieben
void XPMWriter::ImplWriteNumber(sal_Int32 nNumber)
{
const rtl::OString aNum(rtl::OString::valueOf(nNumber));
m_rOStm << aNum.getStr();
}
// ------------------------------------------------------------------------
void XPMWriter::ImplWritePixel( sal_uLong nCol ) const
{
if ( mnColors > 26 )
{
sal_uInt8 nDiff = (sal_uInt8) ( nCol / 26 );
m_rOStm << (sal_uInt8)( nDiff + 'A' );
m_rOStm << (sal_uInt8)( nCol - ( nDiff*26 ) + 'A' );
}
else
m_rOStm << (sal_uInt8)( nCol + 'A' );
}
// ------------------------------------------------------------------------
// ein Farbwert wird im Hexadezimalzahlformat in den Stream geschrieben
void XPMWriter::ImplWriteColor( sal_uInt16 nNumber )
{
sal_uLong nTmp;
sal_uInt8 j;
m_rOStm << "c #"; // # zeigt einen folgenden Hexwert an
const BitmapColor& rColor = mpAcc->GetPaletteColor( nNumber );
nTmp = ( rColor.GetRed() << 16 ) | ( rColor.GetGreen() << 8 ) | rColor.GetBlue();
for ( signed char i = 20; i >= 0 ; i-=4 )
{
if ( ( j = (sal_uInt8)( nTmp >> i ) & 0xf ) > 9 )
j += 'A' - 10;
else
j += '0';
m_rOStm << j;
}
}
// ------------------------------------------------------------------------
// ---------------------
// - exported function -
// ---------------------
#ifdef DISABLE_DYNLOADING
#define GraphicExport expGraphicExport
#endif
extern "C" SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL
GraphicExport(SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pFilterConfigItem, sal_Bool)
{
XPMWriter aXPMWriter(rStream);
return aXPMWriter.WriteXPM( rGraphic, pFilterConfigItem );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#ifndef BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
#define BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
#include <Bull/Core/Support/Xlib/Xlib.hpp>
#include <Bull/Render/Context/ExtensionsLoader.hpp>
#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB 0x31B3
#endif // BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
<commit_msg>[Render/GlxContextNoError] Remove useless header<commit_after>#ifndef BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
#define BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB 0x31B3
#endif // BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
<|endoftext|> |
<commit_before>/**
* \file
* \brief RawFifoQueue class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \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/.
*
* \date 2015-01-01
*/
#ifndef INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
#define INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
#include "distortos/scheduler/FifoQueueBase.hpp"
namespace distortos
{
/// RawFifoQueue class is very similar to FifoQueue, but optimized for binary serializable types (like POD types). Type
/// T can be used with both RawFifoQueue and FifoQueue<T> only when std::is_trivially_copyable<T>::value == true,
/// otherwise only FifoQueue<T> use is safe, while using RawFifoQueue results in undefined behavior.
class RawFifoQueue
{
public:
/**
* \brief RawFifoQueue's constructor
*
* \param [in] storage is a memory block for elements, sufficiently large for \a maxElements, each \a elementSize
* bytes long
* \param [in] elementSize is the size of single queue element, bytes
* \param [in] maxElements is the number of elements in storage memory block
*/
RawFifoQueue(void* storage, size_t elementSize, size_t maxElements);
/**
* \brief Pops the oldest (first) element from the queue.
*
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int pop(void* buffer, size_t size);
/**
* \brief Pops the oldest (first) element from the queue.
*
* \param T is the type of data popped from the queue
*
* \param [out] buffer is a reference to object that will be used to return popped value
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
template<typename T>
int pop(T& buffer)
{
return pop(&buffer, sizeof(buffer));
}
/**
* \brief Pushes the element to the queue.
*
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(const void* data, size_t size);
/**
* \brief Pushes the element to the queue.
*
* \param T is the type of data pushed to the queue
*
* \param [in] data is a reference to data that will be pushed to RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
template<typename T>
int push(const T& data)
{
return push(&data, sizeof(data));
}
/**
* \brief Tries to pop the oldest (first) element from the queue.
*
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPop(void* buffer, size_t size);
/**
* \brief Tries to pop the oldest (first) element from the queue.
*
* \param T is the type of data popped from the queue
*
* \param [out] buffer is a reference to object that will be used to return popped value
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
template<typename T>
int tryPop(T& buffer)
{
return tryPop(&buffer, sizeof(buffer));
}
/**
* \brief Tries to pop the oldest (first) element from the queue for a given duration of time.
*
* \param [in] duration is the duration after which the call will be terminated without popping the element
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPopFor(TickClock::duration duration, void* buffer, size_t size);
/**
* \brief Tries to pop the oldest (first) element from the queue for a given duration of time.
*
* Template variant of tryPopFor(TickClock::duration, void*, size_t).
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
*
* \param [in] duration is the duration after which the call will be terminated without popping the element
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
template<typename Rep, typename Period>
int tryPopFor(const std::chrono::duration<Rep, Period> duration, void* const buffer, const size_t size)
{
return tryPopFor(std::chrono::duration_cast<TickClock::duration>(duration), buffer, size);
}
/**
* \brief Tries to pop the oldest (first) element from the queue for a given duration of time.
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
* \param T is the type of data popped from the queue
*
* \param [in] duration is the duration after which the call will be terminated without popping the element
* \param [out] buffer is a reference to object that will be used to return popped value
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
template<typename Rep, typename Period, typename T>
int tryPopFor(const std::chrono::duration<Rep, Period> duration, T& buffer)
{
return tryPopFor(std::chrono::duration_cast<TickClock::duration>(duration), &buffer, sizeof(buffer));
}
/**
* \brief Tries to push the element to the queue.
*
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPush(const void* data, size_t size);
/**
* \brief Tries to push the element to the queue.
*
* \param T is the type of data pushed to the queue
*
* \param [in] data is a reference to data that will be pushed to RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
template<typename T>
int tryPush(const T& data)
{
return tryPush(&data, sizeof(data));
}
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* \param [in] duration is the duration after which the wait will be terminated without pushing the element
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPushFor(TickClock::duration duration, const void* data, size_t size);
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* Template variant of tryPushFor(TickClock::duration, const void*, size_t).
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
*
* \param [in] duration is the duration after which the wait will be terminated without pushing the element
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
template<typename Rep, typename Period>
int tryPushFor(const std::chrono::duration<Rep, Period> duration, const void* const data, const size_t size)
{
return tryPushFor(std::chrono::duration_cast<TickClock::duration>(duration), data, size);
}
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
* \param T is the type of data pushed to the queue
*
* \param [in] duration is the duration after which the wait will be terminated without pushing the element
* \param [in] data is a reference to data that will be pushed to RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
template<typename Rep, typename Period, typename T>
int tryPushFor(const std::chrono::duration<Rep, Period> duration, const T& data)
{
return tryPushFor(std::chrono::duration_cast<TickClock::duration>(duration), &data, sizeof(data));
}
/**
* \brief Tries to push the element to the queue until a given time point.
*
* \param [in] timePoint is the time point at which the call will be terminated without pushing the element
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitUntil();
* - error codes returned by Semaphore::post();
*/
int tryPushUntil(TickClock::time_point timePoint, const void* data, size_t size);
private:
/**
* \brief Pops the oldest (first) element from the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int popInternal(const scheduler::SemaphoreFunctor& waitSemaphoreFunctor, void* buffer, size_t size);
/**
* \brief Pushes the element to the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int pushInternal(const scheduler::SemaphoreFunctor& waitSemaphoreFunctor, const void* data, size_t size);
/// contained scheduler::FifoQueueBase object which implements base functionality
scheduler::FifoQueueBase fifoQueueBase_;
/// size of single queue element, bytes
const size_t elementSize_;
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
<commit_msg>RawFifoQueue: add RawFifoQueue::tryPushUntil() variant with template time point<commit_after>/**
* \file
* \brief RawFifoQueue class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \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/.
*
* \date 2015-01-01
*/
#ifndef INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
#define INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
#include "distortos/scheduler/FifoQueueBase.hpp"
namespace distortos
{
/// RawFifoQueue class is very similar to FifoQueue, but optimized for binary serializable types (like POD types). Type
/// T can be used with both RawFifoQueue and FifoQueue<T> only when std::is_trivially_copyable<T>::value == true,
/// otherwise only FifoQueue<T> use is safe, while using RawFifoQueue results in undefined behavior.
class RawFifoQueue
{
public:
/**
* \brief RawFifoQueue's constructor
*
* \param [in] storage is a memory block for elements, sufficiently large for \a maxElements, each \a elementSize
* bytes long
* \param [in] elementSize is the size of single queue element, bytes
* \param [in] maxElements is the number of elements in storage memory block
*/
RawFifoQueue(void* storage, size_t elementSize, size_t maxElements);
/**
* \brief Pops the oldest (first) element from the queue.
*
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int pop(void* buffer, size_t size);
/**
* \brief Pops the oldest (first) element from the queue.
*
* \param T is the type of data popped from the queue
*
* \param [out] buffer is a reference to object that will be used to return popped value
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
template<typename T>
int pop(T& buffer)
{
return pop(&buffer, sizeof(buffer));
}
/**
* \brief Pushes the element to the queue.
*
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(const void* data, size_t size);
/**
* \brief Pushes the element to the queue.
*
* \param T is the type of data pushed to the queue
*
* \param [in] data is a reference to data that will be pushed to RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
template<typename T>
int push(const T& data)
{
return push(&data, sizeof(data));
}
/**
* \brief Tries to pop the oldest (first) element from the queue.
*
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPop(void* buffer, size_t size);
/**
* \brief Tries to pop the oldest (first) element from the queue.
*
* \param T is the type of data popped from the queue
*
* \param [out] buffer is a reference to object that will be used to return popped value
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
template<typename T>
int tryPop(T& buffer)
{
return tryPop(&buffer, sizeof(buffer));
}
/**
* \brief Tries to pop the oldest (first) element from the queue for a given duration of time.
*
* \param [in] duration is the duration after which the call will be terminated without popping the element
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPopFor(TickClock::duration duration, void* buffer, size_t size);
/**
* \brief Tries to pop the oldest (first) element from the queue for a given duration of time.
*
* Template variant of tryPopFor(TickClock::duration, void*, size_t).
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
*
* \param [in] duration is the duration after which the call will be terminated without popping the element
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
template<typename Rep, typename Period>
int tryPopFor(const std::chrono::duration<Rep, Period> duration, void* const buffer, const size_t size)
{
return tryPopFor(std::chrono::duration_cast<TickClock::duration>(duration), buffer, size);
}
/**
* \brief Tries to pop the oldest (first) element from the queue for a given duration of time.
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
* \param T is the type of data popped from the queue
*
* \param [in] duration is the duration after which the call will be terminated without popping the element
* \param [out] buffer is a reference to object that will be used to return popped value
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
template<typename Rep, typename Period, typename T>
int tryPopFor(const std::chrono::duration<Rep, Period> duration, T& buffer)
{
return tryPopFor(std::chrono::duration_cast<TickClock::duration>(duration), &buffer, sizeof(buffer));
}
/**
* \brief Tries to push the element to the queue.
*
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPush(const void* data, size_t size);
/**
* \brief Tries to push the element to the queue.
*
* \param T is the type of data pushed to the queue
*
* \param [in] data is a reference to data that will be pushed to RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
template<typename T>
int tryPush(const T& data)
{
return tryPush(&data, sizeof(data));
}
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* \param [in] duration is the duration after which the wait will be terminated without pushing the element
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPushFor(TickClock::duration duration, const void* data, size_t size);
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* Template variant of tryPushFor(TickClock::duration, const void*, size_t).
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
*
* \param [in] duration is the duration after which the wait will be terminated without pushing the element
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
template<typename Rep, typename Period>
int tryPushFor(const std::chrono::duration<Rep, Period> duration, const void* const data, const size_t size)
{
return tryPushFor(std::chrono::duration_cast<TickClock::duration>(duration), data, size);
}
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
* \param T is the type of data pushed to the queue
*
* \param [in] duration is the duration after which the wait will be terminated without pushing the element
* \param [in] data is a reference to data that will be pushed to RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
template<typename Rep, typename Period, typename T>
int tryPushFor(const std::chrono::duration<Rep, Period> duration, const T& data)
{
return tryPushFor(std::chrono::duration_cast<TickClock::duration>(duration), &data, sizeof(data));
}
/**
* \brief Tries to push the element to the queue until a given time point.
*
* \param [in] timePoint is the time point at which the call will be terminated without pushing the element
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitUntil();
* - error codes returned by Semaphore::post();
*/
int tryPushUntil(TickClock::time_point timePoint, const void* data, size_t size);
/**
* \brief Tries to push the element to the queue until a given time point.
*
* Template variant of tryPushUntil(TickClock::time_point, const void*, size_t).
*
* \param Duration is a std::chrono::duration type used to measure duration
*
* \param [in] timePoint is the time point at which the call will be terminated without pushing the element
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by Semaphore::tryWaitUntil();
* - error codes returned by Semaphore::post();
*/
template<typename Duration>
int tryPushUntil(const std::chrono::time_point<TickClock, Duration> timePoint, const void* const data,
const size_t size)
{
return tryPushUntil(std::chrono::time_point_cast<TickClock::duration>(timePoint), data, size);
}
private:
/**
* \brief Pops the oldest (first) element from the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
* \param [out] buffer is a pointer to buffer for popped element
* \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was popped successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int popInternal(const scheduler::SemaphoreFunctor& waitSemaphoreFunctor, void* buffer, size_t size);
/**
* \brief Pushes the element to the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] data is a pointer to data that will be pushed to RawFifoQueue
* \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
*
* \return zero if element was pushed successfully, error code otherwise:
* - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int pushInternal(const scheduler::SemaphoreFunctor& waitSemaphoreFunctor, const void* data, size_t size);
/// contained scheduler::FifoQueueBase object which implements base functionality
scheduler::FifoQueueBase fifoQueueBase_;
/// size of single queue element, bytes
const size_t elementSize_;
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
<|endoftext|> |
<commit_before>//
// Copyright (c) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_PROBLEM_SOLVER_HH
# define HPP_CORE_PROBLEM_SOLVER_HH
# include <hpp/model/fwd.hh>
# include <hpp/core/deprecated.hh>
# include <hpp/core/problem.hh>
# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>
namespace hpp {
namespace core {
/// Set and solve a path planning problem
class HPP_CORE_DLLAPI ProblemSolver {
public:
/// Constructor
ProblemSolver ();
/// Destructor
virtual ~ProblemSolver ();
/// Set robot
void robot (const DevicePtr_t& robot);
/// Get robot
const DevicePtr_t& robot () const;
/// Get pointer to problem
ProblemPtr_t problem ()
{
return problem_;
}
/// Get shared pointer to initial configuration.
const ConfigurationPtr_t& initConfig () const
{
return initConf_;
}
/// Set initial configuration.
void initConfig (const ConfigurationPtr_t& config);
/// Get number of goal configuration.
const Configurations_t& goalConfigs () const;
/// Add goal configuration.
void addGoalConfig (const ConfigurationPtr_t& config);
/// Reset the set of goal configurations
void resetGoalConfigs ();
/// Set path planner type
void pathPlannerType (const std::string& type);
/// Get path planner
const PathPlannerPtr_t& pathPlanner () const
{
return pathPlanner_;
}
/// Set path optimizer type
void pathOptimizerType (const std::string& type);
/// Get path optimizer
const PathOptimizerPtr_t& pathOptimizer () const
{
return pathOptimizer_;
}
const RoadmapPtr_t& roadmap () const
{
return roadmap_;
}
/// Add a constraint
void addConstraint (const ConstraintPtr_t& constraint);
/// Get constraint set
const ConstraintSetPtr_t& constraints () const
{
return constraints_;
}
/// Reset constraint set
void resetConstraints ();
/// Create new problem.
void resetProblem ();
/// \name Solve problem and get paths
/// \{
/// Set and solve the problem
void solve ();
/// Add a path
void addPath (const PathVectorPtr_t& path)
{
paths_.push_back (path);
}
/// Return vector of paths
const PathVectors_t& paths () const
{
return paths_;
}
/// \}
/// \name Obstacles
/// \{
/// Add obstacle to the list.
/// \param inObject a new object.
/// \param collision whether collision checking should be performed
/// for this object.
/// \param distance whether distance computation should be performed
/// for this object.
void addObstacle (const CollisionObjectPtr_t& inObject, bool collision,
bool distance);
/// \}
private:
typedef boost::function < PathPlannerPtr_t (const Problem&,
const RoadmapPtr_t&) >
PathPlannerBuilder_t;
typedef boost::function < PathOptimizerPtr_t (const Problem&) >
PathOptimizerBuilder_t;
typedef std::map < std::string, PathPlannerBuilder_t >
PathPlannerFactory_t;
///Map (string , constructor of path optimizer)
typedef std::map < std::string, PathOptimizerBuilder_t >
PathOptimizerFactory_t;
/// Robot
DevicePtr_t robot_;
bool robotChanged_;
/// Problem
ProblemPtr_t problem_;
/// Shared pointer to initial configuration.
ConfigurationPtr_t initConf_;
/// Shared pointer to goal configuration.
Configurations_t goalConfigurations_;
/// Path planner
std::string pathPlannerType_;
PathPlannerPtr_t pathPlanner_;
/// Path optimizer
std::string pathOptimizerType_;
PathOptimizerPtr_t pathOptimizer_;
/// Store roadmap
RoadmapPtr_t roadmap_;
/// Paths
PathVectors_t paths_;
/// Path planner factory
PathPlannerFactory_t pathPlannerFactory_;
/// Path optimizer factory
PathOptimizerFactory_t pathOptimizerFactory_;
/// Store constraints until call to solve.
ConstraintSetPtr_t constraints_;
/// Store obstacles until call to solve.
ObjectVector_t collisionObstacles_;
ObjectVector_t distanceObstacles_;
}; // class ProblemSolver
} // namespace core
} // namespace hpp
#endif // HPP_CORE_PROBLEM_SOLVER_HH
<commit_msg>Make ProblemSolver::robot setter virtual.<commit_after>//
// Copyright (c) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_PROBLEM_SOLVER_HH
# define HPP_CORE_PROBLEM_SOLVER_HH
# include <hpp/model/fwd.hh>
# include <hpp/core/deprecated.hh>
# include <hpp/core/problem.hh>
# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>
namespace hpp {
namespace core {
/// Set and solve a path planning problem
class HPP_CORE_DLLAPI ProblemSolver {
public:
/// Constructor
ProblemSolver ();
/// Destructor
virtual ~ProblemSolver ();
/// Set robot
virtual void robot (const DevicePtr_t& robot);
/// Get robot
const DevicePtr_t& robot () const;
/// Get pointer to problem
ProblemPtr_t problem ()
{
return problem_;
}
/// Get shared pointer to initial configuration.
const ConfigurationPtr_t& initConfig () const
{
return initConf_;
}
/// Set initial configuration.
void initConfig (const ConfigurationPtr_t& config);
/// Get number of goal configuration.
const Configurations_t& goalConfigs () const;
/// Add goal configuration.
void addGoalConfig (const ConfigurationPtr_t& config);
/// Reset the set of goal configurations
void resetGoalConfigs ();
/// Set path planner type
void pathPlannerType (const std::string& type);
/// Get path planner
const PathPlannerPtr_t& pathPlanner () const
{
return pathPlanner_;
}
/// Set path optimizer type
void pathOptimizerType (const std::string& type);
/// Get path optimizer
const PathOptimizerPtr_t& pathOptimizer () const
{
return pathOptimizer_;
}
const RoadmapPtr_t& roadmap () const
{
return roadmap_;
}
/// Add a constraint
void addConstraint (const ConstraintPtr_t& constraint);
/// Get constraint set
const ConstraintSetPtr_t& constraints () const
{
return constraints_;
}
/// Reset constraint set
void resetConstraints ();
/// Create new problem.
void resetProblem ();
/// \name Solve problem and get paths
/// \{
/// Set and solve the problem
void solve ();
/// Add a path
void addPath (const PathVectorPtr_t& path)
{
paths_.push_back (path);
}
/// Return vector of paths
const PathVectors_t& paths () const
{
return paths_;
}
/// \}
/// \name Obstacles
/// \{
/// Add obstacle to the list.
/// \param inObject a new object.
/// \param collision whether collision checking should be performed
/// for this object.
/// \param distance whether distance computation should be performed
/// for this object.
void addObstacle (const CollisionObjectPtr_t& inObject, bool collision,
bool distance);
/// \}
private:
typedef boost::function < PathPlannerPtr_t (const Problem&,
const RoadmapPtr_t&) >
PathPlannerBuilder_t;
typedef boost::function < PathOptimizerPtr_t (const Problem&) >
PathOptimizerBuilder_t;
typedef std::map < std::string, PathPlannerBuilder_t >
PathPlannerFactory_t;
///Map (string , constructor of path optimizer)
typedef std::map < std::string, PathOptimizerBuilder_t >
PathOptimizerFactory_t;
/// Robot
DevicePtr_t robot_;
bool robotChanged_;
/// Problem
ProblemPtr_t problem_;
/// Shared pointer to initial configuration.
ConfigurationPtr_t initConf_;
/// Shared pointer to goal configuration.
Configurations_t goalConfigurations_;
/// Path planner
std::string pathPlannerType_;
PathPlannerPtr_t pathPlanner_;
/// Path optimizer
std::string pathOptimizerType_;
PathOptimizerPtr_t pathOptimizer_;
/// Store roadmap
RoadmapPtr_t roadmap_;
/// Paths
PathVectors_t paths_;
/// Path planner factory
PathPlannerFactory_t pathPlannerFactory_;
/// Path optimizer factory
PathOptimizerFactory_t pathOptimizerFactory_;
/// Store constraints until call to solve.
ConstraintSetPtr_t constraints_;
/// Store obstacles until call to solve.
ObjectVector_t collisionObstacles_;
ObjectVector_t distanceObstacles_;
}; // class ProblemSolver
} // namespace core
} // namespace hpp
#endif // HPP_CORE_PROBLEM_SOLVER_HH
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_SHARED_UTILS_HPP
#define RJ_SHARED_UTILS_HPP
#include <SFML/Graphics.hpp>
#include <mlk/graphics/color.h>
#include <cmath>
namespace rj
{
template<typename T>
T round_to(T value, T to)
{return (std::round(value / to)) * to;}
template<typename T>
sf::Vector2<T> operator-(const sf::Vector2<T>& vec, T minus)
{return {vec.x - minus, vec.y - minus};}
template<typename T>
sf::Vector2<T> operator+(const sf::Vector2<T>& vec, T plus)
{return {vec.x + plus, vec.y + plus};}
template<typename T>
sf::Rect<T> bounds_from_vec(const sf::Vector2<T>& v, const sf::Vector2<T>& size = {1, 1})
{return {{v.x, v.y}, size};}
inline sf::Color to_rgb(const std::string& hex_str, std::uint8_t custom_alpha = 255)
{
mlk::gcs::color_rgb tmp{hex_str};
return {tmp.red(), tmp.green(), tmp.blue(), custom_alpha};
}
inline sf::Color operator""_rgb(const char* str, std::size_t size)
{return to_rgb({str, size});}
}
#endif // RJ_SHARED_UTILS_HPP
<commit_msg>added flip_h<T>(...)<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_SHARED_UTILS_HPP
#define RJ_SHARED_UTILS_HPP
#include <SFML/Graphics.hpp>
#include <mlk/graphics/color.h>
#include <cmath>
namespace rj
{
template<typename T>
T round_to(T value, T to)
{return (std::round(value / to)) * to;}
template<typename T>
sf::Vector2<T> operator-(const sf::Vector2<T>& vec, T minus)
{return {vec.x - minus, vec.y - minus};}
template<typename T>
sf::Vector2<T> operator+(const sf::Vector2<T>& vec, T plus)
{return {vec.x + plus, vec.y + plus};}
template<typename T>
sf::Rect<T> bounds_from_vec(const sf::Vector2<T>& v, const sf::Vector2<T>& size = {1, 1})
{return {{v.x, v.y}, size};}
template<typename T>
void flip_h(T& obj)
{obj.rotate(180.f);}
inline sf::Color to_rgb(const std::string& hex_str, std::uint8_t custom_alpha = 255)
{
mlk::gcs::color_rgb tmp{hex_str};
return {tmp.red(), tmp.green(), tmp.blue(), custom_alpha};
}
inline sf::Color operator""_rgb(const char* str, std::size_t size)
{return to_rgb({str, size});}
}
#endif // RJ_SHARED_UTILS_HPP
<|endoftext|> |
<commit_before>#include "sn_sweeper.hpp"
#include <algorithm>
#include <string>
#include "pugixml.hpp"
#include "files.hpp"
#include "string_utils.hpp"
namespace {
using namespace mocc;
BC_Size_t boundary_helper( const Mesh &mesh ) {
BC_Size_t bc_size = { (int)mesh.ny()*(int)mesh.nz(),
(int)mesh.nx()*(int)mesh.nz(),
(int)mesh.nx()*(int)mesh.ny() };
return bc_size;
}
}
namespace mocc {
namespace sn {
SnSweeper::SnSweeper( const pugi::xml_node &input, const CoreMesh& mesh ):
TransportSweeper( input ),
timer_( RootTimer.new_timer("Sn Sweeper", true) ),
timer_init_( timer_.new_timer("Initialization", true) ),
timer_sweep_( timer_.new_timer("Sweep", false) ),
mesh_( mesh ),
bc_type_( mesh.boundary() ),
flux_1g_( ),
xstr_( mesh.n_pin() ),
bc_in_( mesh.mat_lib().n_group(), ang_quad_, bc_type_,
boundary_helper(mesh) ),
bc_out_( 1, ang_quad_, bc_type_, boundary_helper(mesh) ),
gs_boundary_( true )
{
LogFile << "Constructing a base Sn sweeper" << std::endl;
// Set up the cross-section mesh. If there is <data> specified, try to
// use that, otherwise generate volume-weighted cross sections
if( input.child("data").empty() ) {
xs_mesh_ = SP_XSMesh_t( new XSMeshHomogenized(mesh) );
} else {
try {
xs_mesh_ = SP_XSMesh_t( new XSMeshHomogenized(mesh, input) );
}
catch( Exception e ) {
std::cerr << e.what() << std::endl;
throw EXCEPT("Failed to create XSMesh for Sn Sweeper.");
}
}
core_mesh_ = &mesh;
n_reg_ = mesh.n_pin();
n_group_ = xs_mesh_->n_group();
flux_.resize( n_reg_, n_group_ );
flux_old_.resize( n_reg_, n_group_ );
vol_.resize( n_reg_ );
// Set the mesh volumes. Same as the pin volumes
int ipin = 0;
for( auto &pin: mesh_ ) {
int i = mesh_.coarse_cell( mesh_.pin_position(ipin) );
vol_[i] = pin->vol();
ipin++;
}
// Make sure we have input from the XML
if( input.empty() ) {
throw EXCEPT("No input specified to initialize Sn sweeper.");
}
// Parse the number of inner iterations
int int_in = input.attribute("n_inner").as_int(-1);
if( int_in < 0 ) {
throw EXCEPT("Invalid number of inner iterations specified "
"(n_inner).");
}
n_inner_ = int_in;
// Try to read boundary update option
if( !input.attribute("boundary_update").empty() ) {
std::string in_string =
input.attribute("boundary_update").value();
sanitize(in_string);
if( (in_string == "gs") || (in_string == "gauss-seidel") ) {
gs_boundary_ = true;
} else if ( (in_string == "jacobi") || (in_string == "j") ) {
gs_boundary_ = false;
} else {
throw EXCEPT("Unrecognized option for BC update!");
}
}
// For now, the BC doesnt support parallel boundary updates, so
// disable Gauss-Seidel boundary update if we are using multiple
// threads.
/// \todo Add support for multi-threaded G-S boundary update in Sn
LogScreen << omp_get_max_threads() << " " << gs_boundary_ << std::endl;
if( (omp_get_max_threads() > 1) && gs_boundary_ ) {
gs_boundary_ = false;
LogScreen << "WARNING: Disabling Gauss-Seidel boundary update "
"in parallel Sn" << std::endl;
}
timer_.toc();
timer_init_.toc();
return;
}
/**
* Watch out, this is potentially brittle, since it assumes parity between
* the mesh regions and XS Mesh regions.
*/
ArrayB3 SnSweeper::pin_powers() const {
ArrayB3 powers(mesh_.nz(), mesh_.ny(), mesh_.nx());
powers = 0.0;
real_t tot_pow = 0.0;
for(int ireg=0; ireg<n_reg_; ireg++ ) {
auto pos = mesh_.coarse_position(ireg);
const XSMeshRegion &xsr = (*xs_mesh_)[ireg];
assert(xsr.reg().size() == 1);
assert(xsr.reg()[0] == ireg);
for( int ig=0; ig<n_group_; ig++ ) {
real_t p = vol_[ireg] * flux_(ireg, ig) * xsr.xsmackf(ig);
powers(pos.z, pos.y, pos.x) += p;
tot_pow += p;
}
}
tot_pow = powers.size()/tot_pow;
powers *= tot_pow;
return powers;
}
void SnSweeper::check_balance( int group ) const {
if( !coarse_data_ ) {
throw EXCEPT("No coarse data. Need it to look at currents.");
}
for( size_t icell=0; icell<mesh_.n_pin(); icell++ ) {
real_t b = 0.0;
// Current
b -= coarse_data_->current(
mesh_.coarse_surf(icell, Surface::EAST), group ) *
mesh_.coarse_area( icell, Surface::EAST );
b -= coarse_data_->current(
mesh_.coarse_surf(icell, Surface::NORTH), group ) *
mesh_.coarse_area( icell, Surface::NORTH );
b -= coarse_data_->current(
mesh_.coarse_surf(icell, Surface::TOP), group ) *
mesh_.coarse_area( icell, Surface::TOP );
b += coarse_data_->current(
mesh_.coarse_surf(icell, Surface::WEST), group ) *
mesh_.coarse_area( icell, Surface::WEST );
b += coarse_data_->current(
mesh_.coarse_surf(icell, Surface::SOUTH), group ) *
mesh_.coarse_area( icell, Surface::SOUTH );
b += coarse_data_->current(
mesh_.coarse_surf(icell, Surface::BOTTOM), group ) *
mesh_.coarse_area( icell, Surface::BOTTOM );
// Source
b += (*source_)[icell]*vol_[icell];
// Internal removal
b -= flux_1g_(icell) *
(*xs_mesh_)[icell].xsmacrm()[group] * vol_[icell];
std::cout << "Cell balance: " << b << std::endl;
}
std::cout << std::endl;
}
void SnSweeper::output( H5Node &node ) const {
auto dims = mesh_.dimensions();
std::reverse( dims.begin(), dims.end() );
// Make a group in the file to store the flux
node.create_group("flux");
ArrayB2 flux = this->get_pin_flux();
Normalize( flux.begin(), flux.end() );
for( int ig=0; ig<n_group_; ig++ ) {
std::stringstream setname;
setname << "flux/" << std::setfill('0') << std::setw(3) << ig+1;
ArrayB1 flux_1g = flux(blitz::Range::all(), ig);
node.write( setname.str(), flux_1g.begin(), flux_1g.end(),
dims);
}
node.write( "pin_powers", this->pin_powers() );
LogFile << "Sn Sweeper:" << std::endl;
LogFile << "Angular Quadrature:" << std::endl;
LogFile << ang_quad_ << std::endl;
LogFile << "Boundary update: ";
if( gs_boundary_ ) {
LogFile << "Gauss-Seidel" << std::endl;
} else {
LogFile << "Jacobi" << std::endl;
}
LogFile << std::endl;
xs_mesh_->output( node );
return;
}
} // namespace sn
} // namespace moc
<commit_msg>Add angular quadrature output to SnSweeper output<commit_after>#include "sn_sweeper.hpp"
#include <algorithm>
#include <string>
#include "pugixml.hpp"
#include "files.hpp"
#include "string_utils.hpp"
namespace {
using namespace mocc;
BC_Size_t boundary_helper( const Mesh &mesh ) {
BC_Size_t bc_size = { (int)mesh.ny()*(int)mesh.nz(),
(int)mesh.nx()*(int)mesh.nz(),
(int)mesh.nx()*(int)mesh.ny() };
return bc_size;
}
}
namespace mocc {
namespace sn {
SnSweeper::SnSweeper( const pugi::xml_node &input, const CoreMesh& mesh ):
TransportSweeper( input ),
timer_( RootTimer.new_timer("Sn Sweeper", true) ),
timer_init_( timer_.new_timer("Initialization", true) ),
timer_sweep_( timer_.new_timer("Sweep", false) ),
mesh_( mesh ),
bc_type_( mesh.boundary() ),
flux_1g_( ),
xstr_( mesh.n_pin() ),
bc_in_( mesh.mat_lib().n_group(), ang_quad_, bc_type_,
boundary_helper(mesh) ),
bc_out_( 1, ang_quad_, bc_type_, boundary_helper(mesh) ),
gs_boundary_( true )
{
LogFile << "Constructing a base Sn sweeper" << std::endl;
// Set up the cross-section mesh. If there is <data> specified, try to
// use that, otherwise generate volume-weighted cross sections
if( input.child("data").empty() ) {
xs_mesh_ = SP_XSMesh_t( new XSMeshHomogenized(mesh) );
} else {
try {
xs_mesh_ = SP_XSMesh_t( new XSMeshHomogenized(mesh, input) );
}
catch( Exception e ) {
std::cerr << e.what() << std::endl;
throw EXCEPT("Failed to create XSMesh for Sn Sweeper.");
}
}
core_mesh_ = &mesh;
n_reg_ = mesh.n_pin();
n_group_ = xs_mesh_->n_group();
flux_.resize( n_reg_, n_group_ );
flux_old_.resize( n_reg_, n_group_ );
vol_.resize( n_reg_ );
// Set the mesh volumes. Same as the pin volumes
int ipin = 0;
for( auto &pin: mesh_ ) {
int i = mesh_.coarse_cell( mesh_.pin_position(ipin) );
vol_[i] = pin->vol();
ipin++;
}
// Make sure we have input from the XML
if( input.empty() ) {
throw EXCEPT("No input specified to initialize Sn sweeper.");
}
// Parse the number of inner iterations
int int_in = input.attribute("n_inner").as_int(-1);
if( int_in < 0 ) {
throw EXCEPT("Invalid number of inner iterations specified "
"(n_inner).");
}
n_inner_ = int_in;
// Try to read boundary update option
if( !input.attribute("boundary_update").empty() ) {
std::string in_string =
input.attribute("boundary_update").value();
sanitize(in_string);
if( (in_string == "gs") || (in_string == "gauss-seidel") ) {
gs_boundary_ = true;
} else if ( (in_string == "jacobi") || (in_string == "j") ) {
gs_boundary_ = false;
} else {
throw EXCEPT("Unrecognized option for BC update!");
}
}
// For now, the BC doesnt support parallel boundary updates, so
// disable Gauss-Seidel boundary update if we are using multiple
// threads.
/// \todo Add support for multi-threaded G-S boundary update in Sn
LogScreen << omp_get_max_threads() << " " << gs_boundary_ << std::endl;
if( (omp_get_max_threads() > 1) && gs_boundary_ ) {
gs_boundary_ = false;
LogScreen << "WARNING: Disabling Gauss-Seidel boundary update "
"in parallel Sn" << std::endl;
}
timer_.toc();
timer_init_.toc();
return;
}
/**
* Watch out, this is potentially brittle, since it assumes parity between
* the mesh regions and XS Mesh regions.
*/
ArrayB3 SnSweeper::pin_powers() const {
ArrayB3 powers(mesh_.nz(), mesh_.ny(), mesh_.nx());
powers = 0.0;
real_t tot_pow = 0.0;
for(int ireg=0; ireg<n_reg_; ireg++ ) {
auto pos = mesh_.coarse_position(ireg);
const XSMeshRegion &xsr = (*xs_mesh_)[ireg];
assert(xsr.reg().size() == 1);
assert(xsr.reg()[0] == ireg);
for( int ig=0; ig<n_group_; ig++ ) {
real_t p = vol_[ireg] * flux_(ireg, ig) * xsr.xsmackf(ig);
powers(pos.z, pos.y, pos.x) += p;
tot_pow += p;
}
}
tot_pow = powers.size()/tot_pow;
powers *= tot_pow;
return powers;
}
void SnSweeper::check_balance( int group ) const {
if( !coarse_data_ ) {
throw EXCEPT("No coarse data. Need it to look at currents.");
}
for( size_t icell=0; icell<mesh_.n_pin(); icell++ ) {
real_t b = 0.0;
// Current
b -= coarse_data_->current(
mesh_.coarse_surf(icell, Surface::EAST), group ) *
mesh_.coarse_area( icell, Surface::EAST );
b -= coarse_data_->current(
mesh_.coarse_surf(icell, Surface::NORTH), group ) *
mesh_.coarse_area( icell, Surface::NORTH );
b -= coarse_data_->current(
mesh_.coarse_surf(icell, Surface::TOP), group ) *
mesh_.coarse_area( icell, Surface::TOP );
b += coarse_data_->current(
mesh_.coarse_surf(icell, Surface::WEST), group ) *
mesh_.coarse_area( icell, Surface::WEST );
b += coarse_data_->current(
mesh_.coarse_surf(icell, Surface::SOUTH), group ) *
mesh_.coarse_area( icell, Surface::SOUTH );
b += coarse_data_->current(
mesh_.coarse_surf(icell, Surface::BOTTOM), group ) *
mesh_.coarse_area( icell, Surface::BOTTOM );
// Source
b += (*source_)[icell]*vol_[icell];
// Internal removal
b -= flux_1g_(icell) *
(*xs_mesh_)[icell].xsmacrm()[group] * vol_[icell];
std::cout << "Cell balance: " << b << std::endl;
}
std::cout << std::endl;
}
void SnSweeper::output( H5Node &node ) const {
auto dims = mesh_.dimensions();
std::reverse( dims.begin(), dims.end() );
// Make a group in the file to store the flux
node.create_group("flux");
ArrayB2 flux = this->get_pin_flux();
Normalize( flux.begin(), flux.end() );
for( int ig=0; ig<n_group_; ig++ ) {
std::stringstream setname;
setname << "flux/" << std::setfill('0') << std::setw(3) << ig+1;
ArrayB1 flux_1g = flux(blitz::Range::all(), ig);
node.write( setname.str(), flux_1g.begin(), flux_1g.end(),
dims);
}
node.write( "pin_powers", this->pin_powers() );
ang_quad_.output( node );
LogFile << "Sn Sweeper:" << std::endl;
LogFile << "Boundary update: ";
if( gs_boundary_ ) {
LogFile << "Gauss-Seidel" << std::endl;
} else {
LogFile << "Jacobi" << std::endl;
}
LogFile << std::endl;
xs_mesh_->output( node );
return;
}
} // namespace sn
} // namespace moc
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2007 The Regents of The University of Michigan
* 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 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.
*
* Authors: Gabe Black
*/
/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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 HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_FLOATREGFILE_HH__
#define __ARCH_X86_FLOATREGFILE_HH__
#include <string>
#include "arch/x86/faults.hh"
#include "arch/x86/types.hh"
#include "arch/x86/x86_traits.hh"
class Checkpoint;
namespace X86ISA
{
std::string getFloatRegName(RegIndex);
const int NumFloatArchRegs = NumMMXRegs + NumXMMRegs;
const int NumFloatRegs = NumFloatArchRegs;
class FloatRegFile
{
protected:
double regs[NumFloatRegs];
public:
void clear();
FloatReg readReg(int floatReg, int width);
FloatRegBits readRegBits(int floatReg, int width);
Fault setReg(int floatReg, const FloatReg &val, int width);
Fault setRegBits(int floatReg, const FloatRegBits &val, int width);
void serialize(std::ostream &os);
void unserialize(Checkpoint *cp, const std::string §ion);
};
}
#endif //__ARCH_X86_FLOATREGFILE_HH__
<commit_msg>Reorganize the floating point register file a little.<commit_after>/*
* Copyright (c) 2003-2007 The Regents of The University of Michigan
* 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 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.
*
* Authors: Gabe Black
*/
/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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 HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_FLOATREGFILE_HH__
#define __ARCH_X86_FLOATREGFILE_HH__
#include <string>
#include "arch/x86/faults.hh"
#include "arch/x86/types.hh"
#include "arch/x86/x86_traits.hh"
class Checkpoint;
namespace X86ISA
{
std::string getFloatRegName(RegIndex);
const int NumFloatArchRegs = NumMMXRegs + NumXMMRegs;
const int NumFloatRegs = NumFloatArchRegs;
class FloatRegFile
{
public:
static const int SingleWidth = 32;
static const int DoubleWidth = 64;
static const int QuadWidth = 128;
protected:
union
{
uint64_t q[NumFloatRegs];
double d[NumFloatRegs];
};
public:
void clear();
FloatReg readReg(int floatReg, int width);
FloatRegBits readRegBits(int floatReg, int width);
Fault setReg(int floatReg, const FloatReg &val, int width);
Fault setRegBits(int floatReg, const FloatRegBits &val, int width);
void serialize(std::ostream &os);
void unserialize(Checkpoint *cp, const std::string §ion);
};
}
#endif //__ARCH_X86_FLOATREGFILE_HH__
<|endoftext|> |
<commit_before>/* TTElement.hpp
*
* Kubo Ryosuke
*/
#ifndef SUNFISH_TT_TTSLOT_HPP__
#define SUNFISH_TT_TTSLOT_HPP__
#include "search/eval/Score.hpp"
#include "core/move/Move.hpp"
#include "core/position/Zobrist.hpp"
#include <cstdint>
#include <cassert>
// 1st quad word
#define TT_MATE_MASK 0x0000000000000001LLU
#define TT_HASH_MASK 0xfffffffffffffffeLLU
#define TT_MATE_WIDTH 1
#define TT_HASH_WIDTH 63
#define TT_MATE_SHIFT 0
static_assert(TT_MATE_WIDTH
+ TT_HASH_WIDTH <= 64, "invalid data size");
static_assert(TT_MATE_MASK == (((1LLU << TT_MATE_WIDTH) - 1LLU) << TT_MATE_SHIFT), "invalid status");
static_assert(TT_HASH_MASK == (~((1LLU << (64 - TT_HASH_WIDTH)) - 1)), "invalid status");
// 2nd quad word
#define TT_MOVE_MASK 0x000000000000ffffLLU
#define TT_SCORE_MASK 0x00000000ffff0000LLU
#define TT_STYPE_MASK 0x0000000300000000LLU
#define TT_DEPTH_MASK 0x00000ffc00000000LLU
#define TT_CSUM_MASK 0xffff000000000000LLU
#define TT_MOVE_WIDTH 16
#define TT_SCORE_WIDTH 16
#define TT_STYPE_WIDTH 2
#define TT_DEPTH_WIDTH 10
#define TT_CSUM_WIDTH 16
#define TT_MOVE_SHIFT 0
#define TT_SCORE_SHIFT (TT_MOVE_SHIFT + TT_MOVE_WIDTH)
#define TT_STYPE_SHIFT (TT_SCORE_SHIFT + TT_SCORE_WIDTH)
#define TT_DEPTH_SHIFT (TT_STYPE_SHIFT + TT_STYPE_WIDTH)
static_assert(TT_MOVE_WIDTH
+ TT_SCORE_WIDTH
+ TT_STYPE_WIDTH
+ TT_DEPTH_WIDTH
+ TT_CSUM_WIDTH <= 64, "invalid data size");
static_assert(TT_MOVE_MASK == (((1LLU << TT_MOVE_WIDTH) - 1) << TT_MOVE_SHIFT), "invalid status");
static_assert(TT_SCORE_MASK == (((1LLU << TT_SCORE_WIDTH) - 1) << TT_SCORE_SHIFT), "invalid status");
static_assert(TT_STYPE_MASK == (((1LLU << TT_STYPE_WIDTH) - 1) << TT_STYPE_SHIFT), "invalid status");
static_assert(TT_DEPTH_MASK == (((1LLU << TT_DEPTH_WIDTH) - 1) << TT_DEPTH_SHIFT), "invalid status");
static_assert(TT_CSUM_MASK == (~((1LLU << (64 - TT_CSUM_WIDTH)) - 1)), "invalid status");
static_assert(sizeof(sunfish::Score::RawType) == 2, "invalid data size");
static_assert(TT_CSUM_WIDTH == 16, "invalid data size");
static_assert(TT_CSUM_MASK == 0xffff000000000000LLU, "invalid data size");
namespace sunfish {
enum class TTScoreType : int {
Exact = 0,
Upper, /* = 1 */
Lower, /* = 2 */
None, /* = 3 */
};
class TTElement {
public:
using QuadWord = uint64_t;
private:
QuadWord w1_;
QuadWord w2_;
bool update(Zobrist::Type newHash,
Score newScore,
TTScoreType newScoreType,
int newDepth,
int ply,
Move move,
bool mateThreat);
QuadWord calcCheckSum() const {
return
(
(w1_) ^
(w1_ << 16) ^
(w1_ << 32) ^
(w1_ << 48) ^
(w2_ << 16) ^
(w2_ << 32) ^
(w2_ << 48)
);
}
public:
TTElement() :
w1_(0),
w2_(TT_CSUM_MASK) {
}
bool update(Zobrist::Type newHash,
Score alpha,
Score beta,
Score newScore,
int newDepth, int ply,
const Move& move,
bool mateThreat) {
TTScoreType newScoreType;
if (newScore >= beta) {
newScoreType = TTScoreType::Lower;
} else if (newScore <= alpha) {
newScoreType = TTScoreType::Upper;
} else {
newScoreType = TTScoreType::Exact;
}
return update(newHash,
newScore,
newScoreType,
newDepth,
ply,
move,
mateThreat);
}
void updatePV(Zobrist::Type newHash,
Score newScore,
int newDepth,
Move move);
bool isLive() const {
return ((w2_ ^ calcCheckSum()) & TT_CSUM_MASK) == 0LLU;
}
bool checkHash(Zobrist::Type hash) const {
return ((w1_ ^ hash) & TT_HASH_MASK) == 0LLU && isLive();
}
Zobrist::Type hash() const {
return w1_ & TT_HASH_MASK;
}
Score score(int ply) const {
auto data = (w2_ & TT_SCORE_MASK) >> TT_SCORE_SHIFT;
auto u16 = static_cast<uint16_t>(data);
auto rawValue = static_cast<Score::RawType>(u16);
Score s(rawValue);
TTScoreType st = scoreType();
ASSERT(st == TTScoreType::None || s >= -Score::infinity());
ASSERT(st == TTScoreType::None || s <= Score::infinity());
if (s >= Score::mate()) {
if (st == TTScoreType::Lower) { return s - ply; }
} else if (s <= -Score::mate()) {
if (st == TTScoreType::Upper) { return s + ply; }
}
return s;
}
TTScoreType scoreType() const {
auto data = (w2_ & TT_STYPE_MASK) >> TT_STYPE_SHIFT;
return static_cast<TTScoreType>(data);
}
int depth() const {
auto data = (w2_ & TT_DEPTH_MASK) >> TT_DEPTH_SHIFT;
return static_cast<int>(data);
}
Move move() const {
auto data = (w2_ & TT_MOVE_MASK) >> TT_MOVE_SHIFT;
auto rawValue = static_cast<Move::RawType16>(data);
return Move::deserialize(rawValue);
}
bool isMateThreat() const {
return w1_ & TT_MATE_MASK;
}
};
} // namespace sunfish
inline std::ostream& operator<<(std::ostream& os, sunfish::TTScoreType scrState) {
switch (scrState) {
case sunfish::TTScoreType::Exact:
os << "Exact";
break;
case sunfish::TTScoreType::Upper:
os << "Upper";
break;
case sunfish::TTScoreType::Lower:
os << "Lower";
break;
case sunfish::TTScoreType::None:
os << "None";
break;
}
return os;
}
#endif // SUNFISH_TT_TTSLOT_HPP__
<commit_msg>Fix TT<commit_after>/* TTElement.hpp
*
* Kubo Ryosuke
*/
#ifndef SUNFISH_TT_TTSLOT_HPP__
#define SUNFISH_TT_TTSLOT_HPP__
#include "search/eval/Score.hpp"
#include "core/move/Move.hpp"
#include "core/position/Zobrist.hpp"
#include <cstdint>
#include <cassert>
// 1st quad word
#define TT_MATE_MASK 0x8000000000000000LLU
#define TT_HASH_MASK 0x7fffffffffffffffLLU
#define TT_HASH_WIDTH 63
#define TT_MATE_WIDTH 1
#define TT_MATE_SHIFT 63
static_assert(TT_MATE_WIDTH
+ TT_HASH_WIDTH <= 64, "invalid data size");
static_assert(TT_MATE_MASK == (((1LLU << TT_MATE_WIDTH) - 1LLU) << TT_MATE_SHIFT), "invalid status");
static_assert(TT_HASH_MASK == ~TT_MATE_MASK, "invalid status");
// 2nd quad word
#define TT_MOVE_MASK 0x000000000000ffffLLU
#define TT_SCORE_MASK 0x00000000ffff0000LLU
#define TT_STYPE_MASK 0x0000000300000000LLU
#define TT_DEPTH_MASK 0x00000ffc00000000LLU
#define TT_CSUM_MASK 0xffff000000000000LLU
#define TT_MOVE_WIDTH 16
#define TT_SCORE_WIDTH 16
#define TT_STYPE_WIDTH 2
#define TT_DEPTH_WIDTH 10
#define TT_CSUM_WIDTH 16
#define TT_MOVE_SHIFT 0
#define TT_SCORE_SHIFT (TT_MOVE_SHIFT + TT_MOVE_WIDTH)
#define TT_STYPE_SHIFT (TT_SCORE_SHIFT + TT_SCORE_WIDTH)
#define TT_DEPTH_SHIFT (TT_STYPE_SHIFT + TT_STYPE_WIDTH)
static_assert(TT_MOVE_WIDTH
+ TT_SCORE_WIDTH
+ TT_STYPE_WIDTH
+ TT_DEPTH_WIDTH
+ TT_CSUM_WIDTH <= 64, "invalid data size");
static_assert(TT_MOVE_MASK == (((1LLU << TT_MOVE_WIDTH) - 1) << TT_MOVE_SHIFT), "invalid status");
static_assert(TT_SCORE_MASK == (((1LLU << TT_SCORE_WIDTH) - 1) << TT_SCORE_SHIFT), "invalid status");
static_assert(TT_STYPE_MASK == (((1LLU << TT_STYPE_WIDTH) - 1) << TT_STYPE_SHIFT), "invalid status");
static_assert(TT_DEPTH_MASK == (((1LLU << TT_DEPTH_WIDTH) - 1) << TT_DEPTH_SHIFT), "invalid status");
static_assert(TT_CSUM_MASK == (~((1LLU << (64 - TT_CSUM_WIDTH)) - 1)), "invalid status");
static_assert(sizeof(sunfish::Score::RawType) == 2, "invalid data size");
static_assert(TT_CSUM_WIDTH == 16, "invalid data size");
static_assert(TT_CSUM_MASK == 0xffff000000000000LLU, "invalid data size");
namespace sunfish {
enum class TTScoreType : int {
Exact = 0,
Upper, /* = 1 */
Lower, /* = 2 */
None, /* = 3 */
};
class TTElement {
public:
using QuadWord = uint64_t;
private:
QuadWord w1_;
QuadWord w2_;
bool update(Zobrist::Type newHash,
Score newScore,
TTScoreType newScoreType,
int newDepth,
int ply,
Move move,
bool mateThreat);
QuadWord calcCheckSum() const {
return
(
(w1_) ^
(w1_ << 16) ^
(w1_ << 32) ^
(w1_ << 48) ^
(w2_ << 16) ^
(w2_ << 32) ^
(w2_ << 48)
);
}
public:
TTElement() :
w1_(0),
w2_(TT_CSUM_MASK) {
}
bool update(Zobrist::Type newHash,
Score alpha,
Score beta,
Score newScore,
int newDepth, int ply,
const Move& move,
bool mateThreat) {
TTScoreType newScoreType;
if (newScore >= beta) {
newScoreType = TTScoreType::Lower;
} else if (newScore <= alpha) {
newScoreType = TTScoreType::Upper;
} else {
newScoreType = TTScoreType::Exact;
}
return update(newHash,
newScore,
newScoreType,
newDepth,
ply,
move,
mateThreat);
}
void updatePV(Zobrist::Type newHash,
Score newScore,
int newDepth,
Move move);
bool isLive() const {
return ((w2_ ^ calcCheckSum()) & TT_CSUM_MASK) == 0LLU;
}
bool checkHash(Zobrist::Type hash) const {
return ((w1_ ^ hash) & TT_HASH_MASK) == 0LLU && isLive();
}
Zobrist::Type hash() const {
return w1_ & TT_HASH_MASK;
}
Score score(int ply) const {
auto data = (w2_ & TT_SCORE_MASK) >> TT_SCORE_SHIFT;
auto u16 = static_cast<uint16_t>(data);
auto rawValue = static_cast<Score::RawType>(u16);
Score s(rawValue);
TTScoreType st = scoreType();
ASSERT(st == TTScoreType::None || s >= -Score::infinity());
ASSERT(st == TTScoreType::None || s <= Score::infinity());
if (s >= Score::mate()) {
if (st == TTScoreType::Lower) { return s - ply; }
} else if (s <= -Score::mate()) {
if (st == TTScoreType::Upper) { return s + ply; }
}
return s;
}
TTScoreType scoreType() const {
auto data = (w2_ & TT_STYPE_MASK) >> TT_STYPE_SHIFT;
return static_cast<TTScoreType>(data);
}
int depth() const {
auto data = (w2_ & TT_DEPTH_MASK) >> TT_DEPTH_SHIFT;
return static_cast<int>(data);
}
Move move() const {
auto data = (w2_ & TT_MOVE_MASK) >> TT_MOVE_SHIFT;
auto rawValue = static_cast<Move::RawType16>(data);
return Move::deserialize(rawValue);
}
bool isMateThreat() const {
return w1_ & TT_MATE_MASK;
}
};
} // namespace sunfish
inline std::ostream& operator<<(std::ostream& os, sunfish::TTScoreType scrState) {
switch (scrState) {
case sunfish::TTScoreType::Exact:
os << "Exact";
break;
case sunfish::TTScoreType::Upper:
os << "Upper";
break;
case sunfish::TTScoreType::Lower:
os << "Lower";
break;
case sunfish::TTScoreType::None:
os << "None";
break;
}
return os;
}
#endif // SUNFISH_TT_TTSLOT_HPP__
<|endoftext|> |
<commit_before>#include "update_status_effects.h"
#include "../SCBW/api.h"
#include "../SCBW/enumerations.h"
#include "../SCBW/scbwdata.h"
#include "irradiate.h"
#include <algorithm>
namespace {
//Helper functions that should be used only in this file
u8 getAcidSporeOverlayAdjustment(const CUnit* const unit);
} //unnamed namespace
namespace hooks {
//Detour for UpdateStatusEffects() (AKA RestoreAllUnitStats())
//Original function address: 0x00492F70 (SCBW 1.16.1)
//Note: this function is called every 8 ticks (when unit->cycleCounter reaches 8 == 0)
void updateStatusEffectsHook(CUnit *unit) {
if (unit->stasisTimer) {
unit->stasisTimer--;
if (unit->stasisTimer == 0)
unit->removeStasisField();
}
if (unit->stimTimer) {
unit->stimTimer--;
if (unit->stimTimer == 0) {
unit->updateSpeed();
unit->removeOverlay(IMAGE_STIM_PACKS_EFFECT); //Remove Stim Packs effect overlay
}
}
if (unit->ensnareTimer) {
unit->ensnareTimer--;
if (unit->ensnareTimer == 0) {
unit->removeOverlay(ImageId::EnsnareOverlay_Small, ImageId::EnsnareOverlay_Large);
unit->updateSpeed();
}
}
if (unit->defensiveMatrixTimer) {
unit->defensiveMatrixTimer--;
if (unit->defensiveMatrixTimer == 0) {
unit->reduceDefensiveMatrixHp(unit->defensiveMatrixHp);
}
}
if (unit->irradiateTimer) {
unit->irradiateTimer--;
doIrradiateDamage(unit);
if (unit->irradiateTimer == 0) {
unit->removeOverlay(ImageId::Irradiate_Small, ImageId::Irradiate_Large);
unit->irradiatedBy = NULL;
unit->irradiatePlayerId = 8;
}
}
if (unit->lockdownTimer) {
unit->lockdownTimer--;
if (unit->lockdownTimer == 0)
unit->removeLockdown();
}
if (unit->maelstromTimer) {
unit->maelstromTimer--;
if (unit->maelstromTimer == 0)
unit->removeMaelstrom();
}
if (unit->plagueTimer) {
unit->plagueTimer--;
if (!(unit->status & UnitStatus::Invincible)) {
//Try to reduce the unit's HP to 1/256 without killing it
const s32 damage = (Weapon::DamageAmount[WeaponId::Plague] << 8) / 75;
if (unit->hitPoints > 1)
unit->damageHp(std::min(damage, unit->hitPoints - 1));
}
if (unit->plagueTimer == 0)
unit->removeOverlay(ImageId::PlagueOverlay_Small, ImageId::PlagueOverlay_Large);
}
if (unit->isUnderStorm)
unit->isUnderStorm--;
//Add Ocular Implants effect overlay
if (unit->isBlind) {
if (!unit->getOverlay(IMAGE_OCULAR_IMPLANTS_EFFECT))
unit->sprite->createOverlay(IMAGE_OCULAR_IMPLANTS_EFFECT, 0, -20);
}
u8 previousAcidSporeCount = unit->acidSporeCount;
for (int i = 0; i <= 8; ++i) {
if (unit->acidSporeTime[i]) {
unit->acidSporeTime[i]--;
if (unit->acidSporeTime[i] == 0)
unit->acidSporeCount--;
}
}
if (unit->acidSporeCount) {
u32 acidOverlayId = getAcidSporeOverlayAdjustment(unit) + ImageId::AcidSpores_1_Overlay_Small;
if (!unit->getOverlay(acidOverlayId)) {
unit->removeOverlay(ImageId::AcidSpores_1_Overlay_Small, ImageId::AcidSpores_6_9_Overlay_Large);
if (unit->subunit)
unit = unit->subunit;
unit->sprite->createTopOverlay(acidOverlayId);
}
}
else if (previousAcidSporeCount) {
unit->removeOverlay(ImageId::AcidSpores_1_Overlay_Small, ImageId::AcidSpores_6_9_Overlay_Large);
}
}
} //hooks
namespace {
/**** Helper function definitions. Do not change anything below this! ****/
u8 getAcidSporeOverlayAdjustment(const CUnit* const unit) {
u8 adjustment = unit->acidSporeCount >> 1;
return (adjustment < 3 ? adjustment : 3)
+ 4 * scbw::getUnitOverlayAdjustment(unit);
}
} //unnamed namespace
<commit_msg>Display the Ocular Implants graphics effect over the Siege Tank's turret.<commit_after>#include "update_status_effects.h"
#include "../SCBW/api.h"
#include "../SCBW/enumerations.h"
#include "../SCBW/scbwdata.h"
#include "irradiate.h"
#include <algorithm>
namespace {
//Helper functions that should be used only in this file
u8 getAcidSporeOverlayAdjustment(const CUnit* const unit);
} //unnamed namespace
namespace hooks {
//Detour for UpdateStatusEffects() (AKA RestoreAllUnitStats())
//Original function address: 0x00492F70 (SCBW 1.16.1)
//Note: this function is called every 8 ticks (when unit->cycleCounter reaches 8 == 0)
void updateStatusEffectsHook(CUnit *unit) {
if (unit->stasisTimer) {
unit->stasisTimer--;
if (unit->stasisTimer == 0)
unit->removeStasisField();
}
if (unit->stimTimer) {
unit->stimTimer--;
if (unit->stimTimer == 0) {
unit->updateSpeed();
unit->removeOverlay(IMAGE_STIM_PACKS_EFFECT); //Remove Stim Packs effect overlay
}
}
if (unit->ensnareTimer) {
unit->ensnareTimer--;
if (unit->ensnareTimer == 0) {
unit->removeOverlay(ImageId::EnsnareOverlay_Small, ImageId::EnsnareOverlay_Large);
unit->updateSpeed();
}
}
if (unit->defensiveMatrixTimer) {
unit->defensiveMatrixTimer--;
if (unit->defensiveMatrixTimer == 0) {
unit->reduceDefensiveMatrixHp(unit->defensiveMatrixHp);
}
}
if (unit->irradiateTimer) {
unit->irradiateTimer--;
doIrradiateDamage(unit);
if (unit->irradiateTimer == 0) {
unit->removeOverlay(ImageId::Irradiate_Small, ImageId::Irradiate_Large);
unit->irradiatedBy = NULL;
unit->irradiatePlayerId = 8;
}
}
if (unit->lockdownTimer) {
unit->lockdownTimer--;
if (unit->lockdownTimer == 0)
unit->removeLockdown();
}
if (unit->maelstromTimer) {
unit->maelstromTimer--;
if (unit->maelstromTimer == 0)
unit->removeMaelstrom();
}
if (unit->plagueTimer) {
unit->plagueTimer--;
if (!(unit->status & UnitStatus::Invincible)) {
//Try to reduce the unit's HP to 1/256 without killing it
const s32 damage = (Weapon::DamageAmount[WeaponId::Plague] << 8) / 75;
if (unit->hitPoints > 1)
unit->damageHp(std::min(damage, unit->hitPoints - 1));
}
if (unit->plagueTimer == 0)
unit->removeOverlay(ImageId::PlagueOverlay_Small, ImageId::PlagueOverlay_Large);
}
if (unit->isUnderStorm)
unit->isUnderStorm--;
//Add Ocular Implants effect overlay
if (unit->isBlind) {
//Display the sprite over the Siege Tank's turret
CUnit *theUnit = unit->subunit ? unit->subunit : unit;
if (!theUnit->getOverlay(IMAGE_OCULAR_IMPLANTS_EFFECT))
theUnit->sprite->createOverlay(IMAGE_OCULAR_IMPLANTS_EFFECT, 0, -20);
}
u8 previousAcidSporeCount = unit->acidSporeCount;
for (int i = 0; i <= 8; ++i) {
if (unit->acidSporeTime[i]) {
unit->acidSporeTime[i]--;
if (unit->acidSporeTime[i] == 0)
unit->acidSporeCount--;
}
}
if (unit->acidSporeCount) {
u32 acidOverlayId = getAcidSporeOverlayAdjustment(unit) + ImageId::AcidSpores_1_Overlay_Small;
if (!unit->getOverlay(acidOverlayId)) {
unit->removeOverlay(ImageId::AcidSpores_1_Overlay_Small, ImageId::AcidSpores_6_9_Overlay_Large);
if (unit->subunit)
unit = unit->subunit;
unit->sprite->createTopOverlay(acidOverlayId);
}
}
else if (previousAcidSporeCount) {
unit->removeOverlay(ImageId::AcidSpores_1_Overlay_Small, ImageId::AcidSpores_6_9_Overlay_Large);
}
}
} //hooks
namespace {
/**** Helper function definitions. Do not change anything below this! ****/
u8 getAcidSporeOverlayAdjustment(const CUnit* const unit) {
u8 adjustment = unit->acidSporeCount >> 1;
return (adjustment < 3 ? adjustment : 3)
+ 4 * scbw::getUnitOverlayAdjustment(unit);
}
} //unnamed namespace
<|endoftext|> |
<commit_before>#include "widget.h"
void MainWindow::CreateTrayIcon()
{
QMenu* pTrayIconMenu = new QMenu(this);
pTrayIconMenu->addAction(m_pOpenAction);
pTrayIconMenu->addSeparator();
pTrayIconMenu->addAction(m_pPostponeAction);
pTrayIconMenu->addSeparator();
pTrayIconMenu->addAction(m_pQuitAction);
if(m_pTrayIcon)
{
m_pTrayIcon->setContextMenu(pTrayIconMenu);
}
}
void MainWindow::SetTrayIcon(QString strIcon)
{
if(strIcon != m_strSetTrayIcon && m_pTrayIcon)
{
QIcon icon(strIcon);
m_pTrayIcon->setIcon(icon);
m_pTrayIcon->setVisible(true);
m_strSetTrayIcon = strIcon;
}
}
void MainWindow::LoadSettings()
{
m_pAppSettings = new QSettings(QCoreApplication::organizationName(), QCoreApplication::applicationName(), this);
qDebug() << QCoreApplication::organizationName() << QCoreApplication::applicationName();
UserTimeSettings::SetWorkTime_s(m_pAppSettings->value("work_time", UserTimeSettings::WorkTime_s()).toInt());
UserTimeSettings::SetRestTime_s(m_pAppSettings->value("rest_time", UserTimeSettings::RestTime_s()).toInt());
UserTimeSettings::SetToleranceTime_s(m_pAppSettings->value("tolerance_time", UserTimeSettings::ToleranceTime_s()).toInt());
m_pOnTopAction->setChecked(m_pAppSettings->value("always_on_top", false).toBool());
SetOnTop(m_pOnTopAction->isChecked());
m_pOnStartUpAction->setChecked(m_pAppSettings->value("run_on_startup", false).toBool());
}
void MainWindow::CreateLayout()
{
QVBoxLayout* pTimeLayout = new QVBoxLayout;
// work spin box
QHBoxLayout* pWorkLayout = new QHBoxLayout;
QLabel* pWorkLabel = new QLabel(tr("Work time [mins]"));
QSpinBox* pSpinWorkTime_s = new QSpinBox(this); // TODO - má tu být this? Nemá tu být některý child?
pSpinWorkTime_s->setValue(UserTimeSettings::WorkTime_s() / 60);
pSpinWorkTime_s->setMaximum(999);
connect(pSpinWorkTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {
UserTimeSettings::SetWorkTime_s(nNewValue * 60);
m_pAppSettings->setValue("work_time", UserTimeSettings::WorkTime_s());
});
pWorkLayout->addWidget(pWorkLabel);
pWorkLayout->addWidget(pSpinWorkTime_s);
// rest spin box
QHBoxLayout* pRestLayout = new QHBoxLayout;
QLabel* pRestLabel = new QLabel(tr("Rest time [mins]"));
QSpinBox* pSpinRestTime_s = new QSpinBox(this);
pSpinRestTime_s->setValue(UserTimeSettings::RestTime_s() / 60);
pSpinRestTime_s->setMaximum(999);
connect(pSpinRestTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {
UserTimeSettings::SetRestTime_s(nNewValue * 60);
m_pAppSettings->setValue("rest_time", UserTimeSettings::RestTime_s());
});
pRestLayout->addWidget(pRestLabel);
pRestLayout->addWidget(pSpinRestTime_s);
// tolerance spin box
QHBoxLayout* pToleranceLayout = new QHBoxLayout;
QLabel* pToleranceLabel = new QLabel(tr("Tolerance time [s]"));
QSpinBox* pSpinToleranceTime_s = new QSpinBox(this);
pSpinToleranceTime_s->setValue(UserTimeSettings::ToleranceTime_s());
pSpinToleranceTime_s->setMaximum(999);
connect(pSpinToleranceTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {
UserTimeSettings::SetToleranceTime_s(nNewValue);
m_pAppSettings->setValue("tolerance_time", UserTimeSettings::ToleranceTime_s());
});
pToleranceLayout->addWidget(pToleranceLabel);
pToleranceLayout->addWidget(pSpinToleranceTime_s);
// add all to vertical layout
pTimeLayout->addLayout(pWorkLayout);
pTimeLayout->addLayout(pRestLayout);
pTimeLayout->addLayout(pToleranceLayout);
// add label with info
m_pLabel = new QLabel;
QVBoxLayout* pMainLayout = new QVBoxLayout;
pMainLayout->addLayout(pTimeLayout);
m_pPassedToleranceBar = new QProgressBar(this);
m_pPassedToleranceBar->setMaximum(0);
m_pPassedToleranceBar->setMaximum(UserTimeSettings::ToleranceTime_s() * 1000);
m_pPassedToleranceBar->setTextVisible(false);
pMainLayout->addWidget(m_pPassedToleranceBar);
pMainLayout->addWidget(m_pLabel);
QWidget* pWidget = new QWidget(this);
pWidget->setLayout(pMainLayout);
this->setCentralWidget(pWidget);
}
void MainWindow::CreateActions()
{
m_pOpenAction = new QAction(tr("&Open"), this);
connect(m_pOpenAction, &QAction::triggered, this, &MainWindow::OpenWindow);
m_pPostponeAction = new QAction(tr("&Add 5 mins"), this);
m_pPostponeAction->setCheckable(true);
connect(m_pPostponeAction, &QAction::triggered, this, &MainWindow::PostponeTheBreak);
m_pAboutAction = new QAction(tr("A&bout..."), this);
connect(m_pAboutAction, &QAction::triggered, qApp, &QApplication::aboutQt); // NOTE - change to about App
m_pQuitAction = new QAction(tr("Really &quit"), this);
connect(m_pQuitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
m_pOnTopAction = new QAction(tr("Always on &top"), this);
m_pOnTopAction->setCheckable(true);
connect(m_pOnTopAction, &QAction::triggered, [&](bool bOnTop) {
m_pAppSettings->setValue("always_on_top", bOnTop);
SetOnTop(bOnTop);
});
m_pOnStartUpAction = new QAction(tr("Run on &startup"), this);
m_pOnStartUpAction->setCheckable(true);
connect(m_pOnStartUpAction, &QAction::triggered, [&](bool bRunOnStartUp) {
m_pAppSettings->setValue("run_on_startup", bRunOnStartUp);
SetOnStartUp(bRunOnStartUp);
});
}
void MainWindow::CreateMenu()
{
m_pAppMenu = menuBar()->addMenu(tr("&App"));
m_pAppMenu->addAction(m_pPostponeAction);
m_pAppMenu->addSeparator();
m_pAppMenu->addAction(m_pAboutAction);
m_pAppMenu->addSeparator();
m_pAppMenu->addAction(m_pQuitAction);
m_pOptionsMenu = menuBar()->addMenu(tr("&Options"));
m_pOptionsMenu->addAction(m_pOnTopAction);
m_pOptionsMenu->addAction(m_pOnStartUpAction);
}
void MainWindow::OpenWindow()
{
this->setWindowState(this->windowState() & ~Qt::WindowMinimized);
this->show();
this->activateWindow();
}
void MainWindow::PostponeTheBreak()
{
m_pPostponeAction->setEnabled(false);
m_nExtraWorkTime_ms = UserTimeSettings::ExtraWorkTime_s() * 1000;
}
void MainWindow::SetOnTop(bool bOnTop)
{
if(bOnTop)
{
this->setWindowFlags(Qt::WindowStaysOnTopHint);
}
else
{
this->setWindowFlags(this->windowFlags() & (~Qt::WindowStaysOnTopHint));
}
this->show();
this->activateWindow();
}
void MainWindow::SetOnStartUp(bool bRunOnStartUp)
{
QSettings oSettings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
if (bRunOnStartUp)
{
const QString strNativeBinPath = QDir::toNativeSeparators(qApp->applicationFilePath());
oSettings.setValue(QCoreApplication::applicationName(), strNativeBinPath);
}
else
{
oSettings.remove(QCoreApplication::applicationName());
}
}
void MainWindow::SetIconByTime()
{
int nWorkTime_ms = UserTimeSettings::WorkTime_s() * 1000 + m_nExtraWorkTime_ms;
if(m_pLastUserInput->UserActiveTime_ms() > nWorkTime_ms)
{
SetTrayIcon(":/stop_icon.png");
}
else if(m_pLastUserInput->UserActiveTime_ms() < nWorkTime_ms && m_pLastUserInput->UserActiveTime_ms() > (nWorkTime_ms - UserTimeSettings::WarningTime_s()) * 1000)
{
SetTrayIcon(":/ready_icon.png");
}
else if(m_pLastUserInput->UserIdleTime_ms() > UserTimeSettings::RestTime_s())
{
SetTrayIcon(":/go_icon.png");
}
}
MainWindow::MainWindow(QMainWindow *parent) : QMainWindow(parent)
{
m_pLastUserInput = new UserInputWatcher(new SystemInput());
m_pTrayIcon = new QSystemTrayIcon(this);
CreateActions();
CreateTrayIcon();
SetTrayIcon(":/go_icon.png");
LoadSettings();
CreateLayout();
CreateMenu();
if(QSystemTrayIcon::isSystemTrayAvailable())
{
qDebug() << "tray is avaible";
}
connect(m_pTrayIcon, &QSystemTrayIcon::activated, [&](QSystemTrayIcon::ActivationReason eReason) {
qDebug() << eReason;
switch (eReason) {
case QSystemTrayIcon::DoubleClick:
case QSystemTrayIcon::Trigger:
OpenWindow();
break;
default:
break;
}
});
connect(&m_oBeepTimer, &QTimer::timeout, [&]() {
int nWorkTime_ms = UserTimeSettings::WorkTime_s() * 1000 + m_nExtraWorkTime_ms;
if(m_pLastUserInput->UserActiveTime_ms() > nWorkTime_ms && m_pLastUserInput->PassedTolerance_ms() > 0)
{
QApplication::beep();
}
});
connect(&m_oTimer, &QTimer::timeout, [&]() {
SetIconByTime();
m_pLastUserInput->UpdateLastUserInput();
m_pPassedToleranceBar->setValue(m_pLastUserInput->PassedTolerance_ms() > m_pPassedToleranceBar->maximum() ? m_pPassedToleranceBar->maximum() : m_pLastUserInput->PassedTolerance_ms());
m_pLabel->setText(QString("User idle time\t\t%1\nUser active time\t\t%2")
.arg(TimeFormat::GetMinsAndSeconds(m_pLastUserInput->UserIdleTime_ms()))
.arg(TimeFormat::GetMinsAndSeconds(m_pLastUserInput->UserActiveTime_ms())));
m_pTrayIcon->setToolTip(QString(tr("Work time is %1 mins")).arg(TimeFormat::GetMins(m_pLastUserInput->UserActiveTime_ms())));
});
connect(m_pLastUserInput, &UserInputWatcher::NewWorkPeriod, [&]() {
m_pPostponeAction->setEnabled(true);
m_nExtraWorkTime_ms = 0;
});
m_oTimer.start(100);
m_oBeepTimer.start(1100);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if(m_pTrayIcon->isVisible())
{
hide();
event->ignore();
}
}
<commit_msg>fix in unchecking action after break time<commit_after>#include "widget.h"
void MainWindow::CreateTrayIcon()
{
QMenu* pTrayIconMenu = new QMenu(this);
pTrayIconMenu->addAction(m_pOpenAction);
pTrayIconMenu->addSeparator();
pTrayIconMenu->addAction(m_pPostponeAction);
pTrayIconMenu->addSeparator();
pTrayIconMenu->addAction(m_pQuitAction);
if(m_pTrayIcon)
{
m_pTrayIcon->setContextMenu(pTrayIconMenu);
}
}
void MainWindow::SetTrayIcon(QString strIcon)
{
if(strIcon != m_strSetTrayIcon && m_pTrayIcon)
{
QIcon icon(strIcon);
m_pTrayIcon->setIcon(icon);
m_pTrayIcon->setVisible(true);
m_strSetTrayIcon = strIcon;
}
}
void MainWindow::LoadSettings()
{
m_pAppSettings = new QSettings(QCoreApplication::organizationName(), QCoreApplication::applicationName(), this);
qDebug() << QCoreApplication::organizationName() << QCoreApplication::applicationName();
UserTimeSettings::SetWorkTime_s(m_pAppSettings->value("work_time", UserTimeSettings::WorkTime_s()).toInt());
UserTimeSettings::SetRestTime_s(m_pAppSettings->value("rest_time", UserTimeSettings::RestTime_s()).toInt());
UserTimeSettings::SetToleranceTime_s(m_pAppSettings->value("tolerance_time", UserTimeSettings::ToleranceTime_s()).toInt());
m_pOnTopAction->setChecked(m_pAppSettings->value("always_on_top", false).toBool());
SetOnTop(m_pOnTopAction->isChecked());
m_pOnStartUpAction->setChecked(m_pAppSettings->value("run_on_startup", false).toBool());
}
void MainWindow::CreateLayout()
{
QVBoxLayout* pTimeLayout = new QVBoxLayout;
// work spin box
QHBoxLayout* pWorkLayout = new QHBoxLayout;
QLabel* pWorkLabel = new QLabel(tr("Work time [mins]"));
QSpinBox* pSpinWorkTime_s = new QSpinBox(this); // TODO - má tu být this? Nemá tu být některý child?
pSpinWorkTime_s->setValue(UserTimeSettings::WorkTime_s() / 60);
pSpinWorkTime_s->setMaximum(999);
connect(pSpinWorkTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {
UserTimeSettings::SetWorkTime_s(nNewValue * 60);
m_pAppSettings->setValue("work_time", UserTimeSettings::WorkTime_s());
});
pWorkLayout->addWidget(pWorkLabel);
pWorkLayout->addWidget(pSpinWorkTime_s);
// rest spin box
QHBoxLayout* pRestLayout = new QHBoxLayout;
QLabel* pRestLabel = new QLabel(tr("Rest time [mins]"));
QSpinBox* pSpinRestTime_s = new QSpinBox(this);
pSpinRestTime_s->setValue(UserTimeSettings::RestTime_s() / 60);
pSpinRestTime_s->setMaximum(999);
connect(pSpinRestTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {
UserTimeSettings::SetRestTime_s(nNewValue * 60);
m_pAppSettings->setValue("rest_time", UserTimeSettings::RestTime_s());
});
pRestLayout->addWidget(pRestLabel);
pRestLayout->addWidget(pSpinRestTime_s);
// tolerance spin box
QHBoxLayout* pToleranceLayout = new QHBoxLayout;
QLabel* pToleranceLabel = new QLabel(tr("Tolerance time [s]"));
QSpinBox* pSpinToleranceTime_s = new QSpinBox(this);
pSpinToleranceTime_s->setValue(UserTimeSettings::ToleranceTime_s());
pSpinToleranceTime_s->setMaximum(999);
connect(pSpinToleranceTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {
UserTimeSettings::SetToleranceTime_s(nNewValue);
m_pAppSettings->setValue("tolerance_time", UserTimeSettings::ToleranceTime_s());
});
pToleranceLayout->addWidget(pToleranceLabel);
pToleranceLayout->addWidget(pSpinToleranceTime_s);
// add all to vertical layout
pTimeLayout->addLayout(pWorkLayout);
pTimeLayout->addLayout(pRestLayout);
pTimeLayout->addLayout(pToleranceLayout);
// add label with info
m_pLabel = new QLabel;
QVBoxLayout* pMainLayout = new QVBoxLayout;
pMainLayout->addLayout(pTimeLayout);
m_pPassedToleranceBar = new QProgressBar(this);
m_pPassedToleranceBar->setMaximum(0);
m_pPassedToleranceBar->setMaximum(UserTimeSettings::ToleranceTime_s() * 1000);
m_pPassedToleranceBar->setTextVisible(false);
pMainLayout->addWidget(m_pPassedToleranceBar);
pMainLayout->addWidget(m_pLabel);
QWidget* pWidget = new QWidget(this);
pWidget->setLayout(pMainLayout);
this->setCentralWidget(pWidget);
}
void MainWindow::CreateActions()
{
m_pOpenAction = new QAction(tr("&Open"), this);
connect(m_pOpenAction, &QAction::triggered, this, &MainWindow::OpenWindow);
m_pPostponeAction = new QAction(tr("&Add 5 mins"), this);
m_pPostponeAction->setCheckable(true);
connect(m_pPostponeAction, &QAction::triggered, this, &MainWindow::PostponeTheBreak);
m_pAboutAction = new QAction(tr("A&bout..."), this);
connect(m_pAboutAction, &QAction::triggered, qApp, &QApplication::aboutQt); // NOTE - change to about App
m_pQuitAction = new QAction(tr("Really &quit"), this);
connect(m_pQuitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
m_pOnTopAction = new QAction(tr("Always on &top"), this);
m_pOnTopAction->setCheckable(true);
connect(m_pOnTopAction, &QAction::triggered, [&](bool bOnTop) {
m_pAppSettings->setValue("always_on_top", bOnTop);
SetOnTop(bOnTop);
});
m_pOnStartUpAction = new QAction(tr("Run on &startup"), this);
m_pOnStartUpAction->setCheckable(true);
connect(m_pOnStartUpAction, &QAction::triggered, [&](bool bRunOnStartUp) {
m_pAppSettings->setValue("run_on_startup", bRunOnStartUp);
SetOnStartUp(bRunOnStartUp);
});
}
void MainWindow::CreateMenu()
{
m_pAppMenu = menuBar()->addMenu(tr("&App"));
m_pAppMenu->addAction(m_pPostponeAction);
m_pAppMenu->addSeparator();
m_pAppMenu->addAction(m_pAboutAction);
m_pAppMenu->addSeparator();
m_pAppMenu->addAction(m_pQuitAction);
m_pOptionsMenu = menuBar()->addMenu(tr("&Options"));
m_pOptionsMenu->addAction(m_pOnTopAction);
m_pOptionsMenu->addAction(m_pOnStartUpAction);
}
void MainWindow::OpenWindow()
{
this->setWindowState(this->windowState() & ~Qt::WindowMinimized);
this->show();
this->activateWindow();
}
void MainWindow::PostponeTheBreak()
{
m_pPostponeAction->setEnabled(false);
m_nExtraWorkTime_ms = UserTimeSettings::ExtraWorkTime_s() * 1000;
}
void MainWindow::SetOnTop(bool bOnTop)
{
if(bOnTop)
{
this->setWindowFlags(Qt::WindowStaysOnTopHint);
}
else
{
this->setWindowFlags(this->windowFlags() & (~Qt::WindowStaysOnTopHint));
}
this->show();
this->activateWindow();
}
void MainWindow::SetOnStartUp(bool bRunOnStartUp)
{
QSettings oSettings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
if (bRunOnStartUp)
{
const QString strNativeBinPath = QDir::toNativeSeparators(qApp->applicationFilePath());
oSettings.setValue(QCoreApplication::applicationName(), strNativeBinPath);
}
else
{
oSettings.remove(QCoreApplication::applicationName());
}
}
void MainWindow::SetIconByTime()
{
int nWorkTime_ms = UserTimeSettings::WorkTime_s() * 1000 + m_nExtraWorkTime_ms;
if(m_pLastUserInput->UserActiveTime_ms() > nWorkTime_ms)
{
SetTrayIcon(":/stop_icon.png");
}
else if(m_pLastUserInput->UserActiveTime_ms() < nWorkTime_ms && m_pLastUserInput->UserActiveTime_ms() > (nWorkTime_ms - UserTimeSettings::WarningTime_s()) * 1000)
{
SetTrayIcon(":/ready_icon.png");
}
else if(m_pLastUserInput->UserIdleTime_ms() > UserTimeSettings::RestTime_s())
{
SetTrayIcon(":/go_icon.png");
}
}
MainWindow::MainWindow(QMainWindow *parent) : QMainWindow(parent)
{
m_pLastUserInput = new UserInputWatcher(new SystemInput());
m_pTrayIcon = new QSystemTrayIcon(this);
CreateActions();
CreateTrayIcon();
SetTrayIcon(":/go_icon.png");
LoadSettings();
CreateLayout();
CreateMenu();
if(QSystemTrayIcon::isSystemTrayAvailable())
{
qDebug() << "tray is avaible";
}
connect(m_pTrayIcon, &QSystemTrayIcon::activated, [&](QSystemTrayIcon::ActivationReason eReason) {
qDebug() << eReason;
switch (eReason) {
case QSystemTrayIcon::DoubleClick:
case QSystemTrayIcon::Trigger:
OpenWindow();
break;
default:
break;
}
});
connect(&m_oBeepTimer, &QTimer::timeout, [&]() {
int nWorkTime_ms = UserTimeSettings::WorkTime_s() * 1000 + m_nExtraWorkTime_ms;
if(m_pLastUserInput->UserActiveTime_ms() > nWorkTime_ms && m_pLastUserInput->PassedTolerance_ms() > 0)
{
QApplication::beep();
}
});
connect(&m_oTimer, &QTimer::timeout, [&]() {
SetIconByTime();
m_pLastUserInput->UpdateLastUserInput();
m_pPassedToleranceBar->setValue(m_pLastUserInput->PassedTolerance_ms() > m_pPassedToleranceBar->maximum() ? m_pPassedToleranceBar->maximum() : m_pLastUserInput->PassedTolerance_ms());
m_pLabel->setText(QString("User idle time\t\t%1\nUser active time\t\t%2")
.arg(TimeFormat::GetMinsAndSeconds(m_pLastUserInput->UserIdleTime_ms()))
.arg(TimeFormat::GetMinsAndSeconds(m_pLastUserInput->UserActiveTime_ms())));
m_pTrayIcon->setToolTip(QString(tr("Work time is %1 mins")).arg(TimeFormat::GetMins(m_pLastUserInput->UserActiveTime_ms())));
});
connect(m_pLastUserInput, &UserInputWatcher::NewWorkPeriod, [&]() {
m_pPostponeAction->setEnabled(true);
m_pPostponeAction->setChecked(false);
m_nExtraWorkTime_ms = 0;
});
m_oTimer.start(100);
m_oBeepTimer.start(1100);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if(m_pTrayIcon->isVisible())
{
hide();
event->ignore();
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "UIControlSystem.h"
#include "UIControl.h"
#include "Core.h"
#include "Applications/ApplicationBase.h"
#include "Render/RenderWorld.h"
#include "PropertyReaders.h"
#include "Input/InputSystem.h"
#include "Input/InputSubscriber.h"
namespace SDK
{
namespace UI
{
UIControlSystem g_ui_system;
class UIControlSystem::UI_InputSubscriber : public InputSubscriber
{
private:
UIControlSystem& m_system;
public:
UI_InputSubscriber(UIControlSystem& i_system)
: m_system(i_system)
{
InputSystem::Instance().SetUISubscriber(this);
}
virtual ~UI_InputSubscriber()
{
InputSystem::Instance().SetUISubscriber(nullptr);
}
virtual bool KeyPressed(const KeyEvent& i_evt) override
{
return false;
}
virtual bool KeyReleased(const KeyEvent& i_evt) override
{
return false;
}
virtual bool MouseMoved(const MouseEvent& i_evt) override
{
return false;
}
virtual bool MousePressed(const MouseEvent& i_evt) override
{
return false;
}
virtual bool MouseReleased(const MouseEvent& i_evt) override
{
auto& controls = g_ui_system.m_controls;
for (auto& control : controls)
{
if (control.second == nullptr)
continue;
if (control.second->IsHited({ i_evt.m_x, i_evt.m_y }))
{
// TODO: need to return true/false based on HandleMessage result
g_ui_system.GetMessageDispatcher().HandleMessage(UIEvent{ UIEventType::ButtonPressed }, control.second->GetName());
return true;
}
}
return false;
}
};
namespace detail { extern void RegisterBaseUITypes(UIControlSystem&); }
UIControlSystem::UIControlSystem()
: m_current_scheme(INVALID_UISCHEME_HANDLER)
{
detail::RegisterBaseUITypes(*this);
}
UIControlSystem::~UIControlSystem()
{
for (auto& control : m_controls)
{
if (control.second == nullptr)
continue;
control.second->SetParent(INVALID_UI_HANDLER);
}
m_controls.clear();
}
UIControlHandler UIControlSystem::GetHandlerTo(UIControl* ip_pointer) const
{
auto it = std::find_if(m_controls.begin(), m_controls.end(), [ip_pointer](const UIControlPair& control)
{
return control.second != nullptr && control.second.get() == ip_pointer;
});
if (it == m_controls.end())
return INVALID_UI_HANDLER;
return it->first;
}
UIControl* UIControlSystem::AccessControl(UIControlHandler i_handler) const
{
if (!IsValid(i_handler, m_controls))
return nullptr;
return m_controls[i_handler.index].second.get();
}
void UIControlSystem::Update(float i_elapsed_time)
{
if (m_current_scheme == INVALID_UISCHEME_HANDLER)
return;
UIScheme& current = m_schemes[m_current_scheme.index];
for (auto& handler : current.m_handlers)
{
auto& control = m_controls[handler.index];
if (control.second == nullptr)
continue;
// control is updated from parent
if (control.second->GetParent() != INVALID_UI_HANDLER)
continue;
control.second->Update(i_elapsed_time);
}
}
void UIControlSystem::Draw()
{
if (m_current_scheme == INVALID_UISCHEME_HANDLER)
return;
UIScheme& current = m_schemes[m_current_scheme.index];
for (auto& handler : current.m_handlers)
{
auto& control = m_controls[handler.index];
if (control.second == nullptr)
continue;
// control is updated from parent
if (control.second->GetParent() != INVALID_UI_HANDLER)
continue;
control.second->Draw();
}
auto& render_world = Core::GetApplication()->GetRenderWorld();
render_world.Submit({Render::ProjectionType::Orthographic, Matrix4f::IDENTITY, Matrix4f::IDENTITY });
}
void UIControlSystem::SetInputSystem(InputSystem& i_input_system)
{
static UI_InputSubscriber g_subscriber(*this);
}
void UIControlSystem::OnResize(const IRect& i_new_size)
{
for (auto& control : m_controls)
{
if (control.second == nullptr)
continue;
control.second->OnResize(i_new_size);
}
}
void UIControlSystem::RemoveControl(UIControlHandler i_handler)
{
if (!IsValid(i_handler, m_controls))
return;
m_controls[i_handler.index].second.release();
m_controls[i_handler.index].first.index = -1;
}
void AddControlElement(UIControlSystem::UIScheme& o_scheme, const PropertyElement::iterator<PropertyElement>& i_it, UIControlHandler i_parent = INVALID_UI_HANDLER)
{
// type of control
auto type = i_it.element_name();
const PropertyElement& element = *i_it;
UIControlSystem::UIControlAccessor<UIControl> accessor = g_ui_system.GetFactory().Create(type);
if (!accessor.IsValid())
return;
if (i_parent != INVALID_UI_HANDLER)
accessor.GetActual()->SetParent(i_parent);
o_scheme.AddControl(accessor.GetHandler());
const auto end = element.end<PropertyElement>();
for (auto it = element.begin<PropertyElement>(); it != end; ++it)
AddControlElement(o_scheme, it, accessor.GetHandler());
}
UISchemeHandler UIControlSystem::LoadScheme(const std::string& i_file_name)
{
PropretyReader<(int)ReaderType::SDKFormat> reader;
PropertyElement root = reader.Parse(i_file_name);
std::string scheme_name = root.GetValue<std::string>("name");
const size_t hash = Utilities::hash_function(scheme_name);
// validate scheme name and existance in UISystem
{
if (scheme_name.empty())
{
assert(false && "Scheme name is empty");
return INVALID_UISCHEME_HANDLER;
}
UISchemeHandler test_handler = FindScheme(Utilities::hash_function(scheme_name));
if (test_handler != INVALID_UISCHEME_HANDLER)
{
assert(false && "Scheme with same name already exist");
return INVALID_UISCHEME_HANDLER;
}
}
UISchemeHandler scheme_handler{ static_cast<int>(m_schemes.size()), 0 };
// find empty slot
{
for (size_t i = 0; i < m_schemes.size(); ++i)
{
auto& scheme = m_schemes[i];
if (scheme.m_handler.index == -1)
{
scheme_handler = { static_cast<int>(i), scheme.m_handler.generation + 1 };
break;
}
}
}
UIScheme scheme(scheme_name, hash, scheme_handler);
const auto end = root.end<PropertyElement>();
for (auto it = root.begin<PropertyElement>(); it != end; ++it)
AddControlElement(scheme, it);
// free slots not found -> push back new
if (scheme_handler.index == m_schemes.size())
m_schemes.push_back(scheme);
else
m_schemes[scheme_handler.index] = scheme;
return scheme_handler;
}
UISchemeHandler UIControlSystem::FindScheme(size_t i_hash)
{
auto it = std::find_if(m_schemes.begin(), m_schemes.end(), [i_hash](const UIScheme& scheme)
{
return scheme.GetHandler().index != -1 && scheme.GetHash() == i_hash;
});
if (it == m_schemes.end())
return INVALID_UISCHEME_HANDLER;
else
return it->GetHandler();
}
void UIControlSystem::SetActiveScheme(const std::string& i_scheme_name)
{
m_current_scheme = FindScheme(Utilities::hash_function(i_scheme_name));
}
void UIControlSystem::SetActiveScheme(UISchemeHandler i_scheme)
{
auto it = std::find_if(m_schemes.begin(), m_schemes.end(), [i_scheme](const UIScheme& scheme)
{
return scheme.GetHandler() == i_scheme;
});
if (it == m_schemes.end())
m_current_scheme = INVALID_UISCHEME_HANDLER;
else
m_current_scheme = it->GetHandler();
}
void UIControlSystem::UnloadScheme(UISchemeHandler i_scheme)
{
if (i_scheme == INVALID_UISCHEME_HANDLER)
return;
UIScheme& current = m_schemes[i_scheme.index];
for (auto& handler : current.m_handlers)
RemoveControl(handler);
if (m_current_scheme == current.m_handler)
m_current_scheme = INVALID_UISCHEME_HANDLER;
current.m_handler.index = -1;
}
void UIControlSystem::UnloadScheme(const std::string& i_scheme)
{
UnloadScheme(FindScheme(Utilities::hash_function(i_scheme)));
}
const UIControlSystem::UIScheme* UIControlSystem::AccessScheme(UISchemeHandler i_scheme) const
{
if (i_scheme.index == -1 || static_cast<int>(m_schemes.size()) <= i_scheme.index)
return nullptr;
return &m_schemes[i_scheme.index];
}
} // UI
} // SDK<commit_msg>[Core-UI] Load elements after it creation. Good practice...<commit_after>#include "stdafx.h"
#include "UIControlSystem.h"
#include "UIControl.h"
#include "Core.h"
#include "Applications/ApplicationBase.h"
#include "Render/RenderWorld.h"
#include "PropertyReaders.h"
#include "Input/InputSystem.h"
#include "Input/InputSubscriber.h"
namespace SDK
{
namespace UI
{
UIControlSystem g_ui_system;
class UIControlSystem::UI_InputSubscriber : public InputSubscriber
{
private:
UIControlSystem& m_system;
public:
UI_InputSubscriber(UIControlSystem& i_system)
: m_system(i_system)
{
InputSystem::Instance().SetUISubscriber(this);
}
virtual ~UI_InputSubscriber()
{
InputSystem::Instance().SetUISubscriber(nullptr);
}
virtual bool KeyPressed(const KeyEvent& i_evt) override
{
return false;
}
virtual bool KeyReleased(const KeyEvent& i_evt) override
{
return false;
}
virtual bool MouseMoved(const MouseEvent& i_evt) override
{
return false;
}
virtual bool MousePressed(const MouseEvent& i_evt) override
{
return false;
}
virtual bool MouseReleased(const MouseEvent& i_evt) override
{
auto& controls = g_ui_system.m_controls;
for (auto& control : controls)
{
if (control.second == nullptr)
continue;
if (control.second->IsHited({ i_evt.m_x, i_evt.m_y }))
{
// TODO: need to return true/false based on HandleMessage result
g_ui_system.GetMessageDispatcher().HandleMessage(UIEvent{ UIEventType::ButtonPressed }, control.second->GetName());
return true;
}
}
return false;
}
};
namespace detail { extern void RegisterBaseUITypes(UIControlSystem&); }
UIControlSystem::UIControlSystem()
: m_current_scheme(INVALID_UISCHEME_HANDLER)
{
detail::RegisterBaseUITypes(*this);
}
UIControlSystem::~UIControlSystem()
{
for (auto& control : m_controls)
{
if (control.second == nullptr)
continue;
control.second->SetParent(INVALID_UI_HANDLER);
}
m_controls.clear();
}
UIControlHandler UIControlSystem::GetHandlerTo(UIControl* ip_pointer) const
{
auto it = std::find_if(m_controls.begin(), m_controls.end(), [ip_pointer](const UIControlPair& control)
{
return control.second != nullptr && control.second.get() == ip_pointer;
});
if (it == m_controls.end())
return INVALID_UI_HANDLER;
return it->first;
}
UIControl* UIControlSystem::AccessControl(UIControlHandler i_handler) const
{
if (!IsValid(i_handler, m_controls))
return nullptr;
return m_controls[i_handler.index].second.get();
}
void UIControlSystem::Update(float i_elapsed_time)
{
if (m_current_scheme == INVALID_UISCHEME_HANDLER)
return;
UIScheme& current = m_schemes[m_current_scheme.index];
for (auto& handler : current.m_handlers)
{
auto& control = m_controls[handler.index];
if (control.second == nullptr)
continue;
// control is updated from parent
if (control.second->GetParent() != INVALID_UI_HANDLER)
continue;
control.second->Update(i_elapsed_time);
}
}
void UIControlSystem::Draw()
{
if (m_current_scheme == INVALID_UISCHEME_HANDLER)
return;
UIScheme& current = m_schemes[m_current_scheme.index];
for (auto& handler : current.m_handlers)
{
auto& control = m_controls[handler.index];
if (control.second == nullptr)
continue;
// control is updated from parent
if (control.second->GetParent() != INVALID_UI_HANDLER)
continue;
control.second->Draw();
}
auto& render_world = Core::GetApplication()->GetRenderWorld();
render_world.Submit({Render::ProjectionType::Orthographic, Matrix4f::IDENTITY, Matrix4f::IDENTITY });
}
void UIControlSystem::SetInputSystem(InputSystem& i_input_system)
{
static UI_InputSubscriber g_subscriber(*this);
}
void UIControlSystem::OnResize(const IRect& i_new_size)
{
for (auto& control : m_controls)
{
if (control.second == nullptr)
continue;
control.second->OnResize(i_new_size);
}
}
void UIControlSystem::RemoveControl(UIControlHandler i_handler)
{
if (!IsValid(i_handler, m_controls))
return;
m_controls[i_handler.index].second.release();
m_controls[i_handler.index].first.index = -1;
}
void AddControlElement(UIControlSystem::UIScheme& o_scheme, const PropertyElement::iterator<PropertyElement>& i_it, UIControlHandler i_parent = INVALID_UI_HANDLER)
{
// type of control
auto type = i_it.element_name();
const PropertyElement& element = *i_it;
UIControlSystem::UIControlAccessor<UIControl> accessor = g_ui_system.GetFactory().Create(type);
if (!accessor.IsValid())
return;
accessor.GetActual()->Load(element);
if (i_parent != INVALID_UI_HANDLER)
accessor.GetActual()->SetParent(i_parent);
o_scheme.AddControl(accessor.GetHandler());
const auto end = element.end<PropertyElement>();
for (auto it = element.begin<PropertyElement>(); it != end; ++it)
AddControlElement(o_scheme, it, accessor.GetHandler());
}
UISchemeHandler UIControlSystem::LoadScheme(const std::string& i_file_name)
{
PropretyReader<(int)ReaderType::SDKFormat> reader;
PropertyElement root = reader.Parse(i_file_name);
std::string scheme_name = root.GetValue<std::string>("name");
const size_t hash = Utilities::hash_function(scheme_name);
// validate scheme name and existance in UISystem
{
if (scheme_name.empty())
{
assert(false && "Scheme name is empty");
return INVALID_UISCHEME_HANDLER;
}
UISchemeHandler test_handler = FindScheme(Utilities::hash_function(scheme_name));
if (test_handler != INVALID_UISCHEME_HANDLER)
{
assert(false && "Scheme with same name already exist");
return INVALID_UISCHEME_HANDLER;
}
}
UISchemeHandler scheme_handler{ static_cast<int>(m_schemes.size()), 0 };
// find empty slot
{
for (size_t i = 0; i < m_schemes.size(); ++i)
{
auto& scheme = m_schemes[i];
if (scheme.m_handler.index == -1)
{
scheme_handler = { static_cast<int>(i), scheme.m_handler.generation + 1 };
break;
}
}
}
UIScheme scheme(scheme_name, hash, scheme_handler);
const auto end = root.end<PropertyElement>();
for (auto it = root.begin<PropertyElement>(); it != end; ++it)
AddControlElement(scheme, it);
// free slots not found -> push back new
if (scheme_handler.index == m_schemes.size())
m_schemes.push_back(scheme);
else
m_schemes[scheme_handler.index] = scheme;
return scheme_handler;
}
UISchemeHandler UIControlSystem::FindScheme(size_t i_hash)
{
auto it = std::find_if(m_schemes.begin(), m_schemes.end(), [i_hash](const UIScheme& scheme)
{
return scheme.GetHandler().index != -1 && scheme.GetHash() == i_hash;
});
if (it == m_schemes.end())
return INVALID_UISCHEME_HANDLER;
else
return it->GetHandler();
}
void UIControlSystem::SetActiveScheme(const std::string& i_scheme_name)
{
m_current_scheme = FindScheme(Utilities::hash_function(i_scheme_name));
}
void UIControlSystem::SetActiveScheme(UISchemeHandler i_scheme)
{
auto it = std::find_if(m_schemes.begin(), m_schemes.end(), [i_scheme](const UIScheme& scheme)
{
return scheme.GetHandler() == i_scheme;
});
if (it == m_schemes.end())
m_current_scheme = INVALID_UISCHEME_HANDLER;
else
m_current_scheme = it->GetHandler();
}
void UIControlSystem::UnloadScheme(UISchemeHandler i_scheme)
{
if (i_scheme == INVALID_UISCHEME_HANDLER)
return;
UIScheme& current = m_schemes[i_scheme.index];
for (auto& handler : current.m_handlers)
RemoveControl(handler);
if (m_current_scheme == current.m_handler)
m_current_scheme = INVALID_UISCHEME_HANDLER;
current.m_handler.index = -1;
}
void UIControlSystem::UnloadScheme(const std::string& i_scheme)
{
UnloadScheme(FindScheme(Utilities::hash_function(i_scheme)));
}
const UIControlSystem::UIScheme* UIControlSystem::AccessScheme(UISchemeHandler i_scheme) const
{
if (i_scheme.index == -1 || static_cast<int>(m_schemes.size()) <= i_scheme.index)
return nullptr;
return &m_schemes[i_scheme.index];
}
} // UI
} // SDK<|endoftext|> |
<commit_before>#include <random>
#include "epidemic.hpp"
#include "WattsStrogatzModel.hpp"
#include "MLCG.h"
#include "NegExp.h"
#include "tclap/ValueArg.h"
#define NEG_EXP_OFFSET 50
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(EpidemicEvent)
std::vector<std::shared_ptr<warped::Event> > Location::createInitialEvents() {
std::vector<std::shared_ptr<warped::Event> > events;
events.emplace_back(new EpidemicEvent {this->location_name_,
this->location_state_refresh_interval_, nullptr, DISEASE_UPDATE_TRIGGER});
events.emplace_back(new EpidemicEvent {this->location_name_,
this->location_diffusion_trigger_interval_, nullptr, DIFFUSION_TRIGGER});
return events;
}
std::vector<std::shared_ptr<warped::Event> > Location::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > events;
auto epidemic_event = static_cast<const EpidemicEvent&>(event);
auto timestamp = epidemic_event.loc_arrival_timestamp_;
switch (epidemic_event.event_type_) {
case event_type_t::DISEASE_UPDATE_TRIGGER: {
disease_model_->reaction(state_->current_population_, timestamp);
events.emplace_back(new EpidemicEvent {location_name_,
timestamp + location_state_refresh_interval_,
nullptr, DISEASE_UPDATE_TRIGGER});
} break;
case event_type_t::DIFFUSION_TRIGGER: {
std::string selected_location = diffusion_network_->pickLocation();
if (selected_location != "") {
auto travel_time = diffusion_network_->travelTimeToLocation(selected_location);
unsigned int person_count = state_->current_population_->size();
if (person_count) {
unsigned int person_id = diffusion_network_->pickPerson(person_count);
auto map_iter = state_->current_population_->begin();
unsigned int temp_cnt = 0;
while (temp_cnt < person_id) {
map_iter++;
temp_cnt++;
}
std::shared_ptr<Person> person = map_iter->second;
events.emplace_back(new EpidemicEvent {selected_location,
timestamp + travel_time, person, DIFFUSION});
state_->current_population_->erase(map_iter);
}
}
events.emplace_back(new EpidemicEvent {location_name_,
timestamp + location_diffusion_trigger_interval_,
nullptr, DIFFUSION_TRIGGER});
} break;
case event_type_t::DIFFUSION: {
std::shared_ptr<Person> person = std::make_shared<Person>(
epidemic_event.pid_, epidemic_event.susceptibility_,
epidemic_event.vaccination_status_, epidemic_event.infection_state_,
timestamp, epidemic_event.prev_state_change_timestamp_);
state_->current_population_->insert(state_->current_population_->begin(),
std::pair <unsigned long, std::shared_ptr<Person>> (epidemic_event.pid_, person));
} break;
default: {}
}
return events;
}
int main(int argc, const char** argv) {
unsigned int num_regions = 1000;
unsigned int num_locations_per_region = 1000;
unsigned int num_persons_per_location = 10000;
unsigned int mean_travel_time_to_hub = 300;
unsigned int diffusion_seed = 101;
unsigned int disease_seed = 90;
unsigned int location_state_refresh_interval = 50;
unsigned int mean_location_diffusion_interval = 200;
TCLAP::ValueArg<unsigned int> num_regions_arg("n", "num-regions", "Number of regions",
false, num_regions, "unsigned int");
TCLAP::ValueArg<unsigned int> num_locations_per_region_arg("l", "num-locations-per-region",
"Number of locations per region", false, num_locations_per_region, "unsigned int");
TCLAP::ValueArg<unsigned int> num_persons_per_location_arg("p", "num-persons-per-location",
"Number of persons per location", false, num_persons_per_location, "unsigned int");
TCLAP::ValueArg<unsigned int> mean_travel_time_to_hub_arg("t", "mean-travel-time-to-hub",
"Mean travel time to hub", false, mean_travel_time_to_hub, "unsigned int");
TCLAP::ValueArg<unsigned int> diffusion_seed_arg("f", "diffusion-seed", "Diffusion seed",
false, diffusion_seed, "unsigned int");
TCLAP::ValueArg<unsigned int> disease_seed_arg("s", "disease-seed", "Disease seed",
false, disease_seed, "unsigned int");
TCLAP::ValueArg<unsigned int> location_state_refresh_interval_arg("r", "refresh-interval",
"Location state refresh interval", false, location_state_refresh_interval, "unsigned int");
TCLAP::ValueArg<unsigned int> mean_location_diffusion_interval_arg("i", "diffusion-interval",
"Mean location diffusion interval", false, mean_location_diffusion_interval, "unsigned int");
std::vector<TCLAP::Arg*> args = { &num_regions_arg,
&num_locations_per_region_arg,
&num_persons_per_location_arg,
&mean_travel_time_to_hub_arg,
&diffusion_seed_arg,
&disease_seed_arg,
&location_state_refresh_interval_arg,
&mean_location_diffusion_interval_arg
};
warped::Simulation epidemic_sim {"Epidemic Simulation", argc, argv, args};
num_regions = num_regions_arg.getValue();
num_locations_per_region = num_locations_per_region_arg.getValue();
num_persons_per_location = num_persons_per_location_arg.getValue();
mean_travel_time_to_hub = mean_travel_time_to_hub_arg.getValue();
diffusion_seed = diffusion_seed_arg.getValue();
disease_seed = disease_seed_arg.getValue();
location_state_refresh_interval = location_state_refresh_interval_arg.getValue();
mean_location_diffusion_interval = mean_location_diffusion_interval_arg.getValue();
std::shared_ptr<MLCG> rng = std::make_shared<MLCG> ();
NegativeExpntl travel_time_expo(mean_travel_time_to_hub, rng.get());
NegativeExpntl diffusion_expo(mean_location_diffusion_interval, rng.get());
// Diffusion model
unsigned int k = 8;
float beta = 0.1;
// Disease model
float transmissibility = 0.12;
unsigned int latent_dwell_time = 200;
float latent_infectivity = 0;
unsigned int incubating_dwell_time = 400;
float incubating_infectivity = 0.3;
unsigned int infectious_dwell_time = 400;
float infectious_infectivity = 1.0;
unsigned int asympt_dwell_time = 200;
float asympt_infectivity = 0.5;
float prob_ulu = 0.2;
float prob_ulv = 0.9;
float prob_urv = 0.5;
float prob_uiv = 0.1;
float prob_uiu = 0.3;
std::map<std::string, unsigned int> travel_map;
std::vector<Location> objects;
for (unsigned int region_id = 0; region_id < num_regions; region_id++) {
std::string region_name = std::string("region_") + std::to_string(region_id);
for (unsigned int location_id = 0; location_id < num_locations_per_region; location_id++) {
std::string location_name = std::string("location_") + std::to_string(location_id);
std::string location = region_name + std::string("-") + location_name;
std::vector<std::shared_ptr<Person>> population;
unsigned int travel_time_to_hub =
(unsigned int) travel_time_expo() + NEG_EXP_OFFSET;
travel_map.insert(std::pair<std::string, unsigned int>(location, travel_time_to_hub));
unsigned int location_diffusion_interval =
(unsigned int) diffusion_expo() + NEG_EXP_OFFSET;
for (unsigned int person_id = 0; person_id < num_persons_per_location; person_id++) {
unsigned long pid = region_id * location_id + person_id;
std::default_random_engine gen;
std::uniform_int_distribution<unsigned int> rand_susceptibility(0,10);
double susceptibility = ((double)rand_susceptibility(gen))/10;
std::uniform_int_distribution<unsigned int> rand_vaccination(0,1);
bool vaccination_status = (bool) rand_vaccination(gen);
std::uniform_int_distribution<unsigned int>
rand_infection(0, (unsigned int) MAX_INFECTION_STATE_NUM-1);
infection_state_t state = (infection_state_t) rand_infection(gen);
auto person = std::make_shared<Person> ( pid,
susceptibility,
vaccination_status,
state,
0,
0
);
population.push_back(person);
}
objects.emplace_back( location,
transmissibility,
latent_dwell_time,
incubating_dwell_time,
infectious_dwell_time,
asympt_dwell_time,
latent_infectivity,
incubating_infectivity,
infectious_infectivity,
asympt_infectivity,
prob_ulu,
prob_ulv,
prob_urv,
prob_uiv,
prob_uiu,
location_state_refresh_interval,
location_diffusion_interval,
population,
travel_time_to_hub,
disease_seed,
diffusion_seed
);
}
}
// Create the Watts-Strogatz model
auto ws = std::make_shared<WattsStrogatzModel>(k, beta, diffusion_seed);
std::vector<std::string> nodes;
for (auto& o : objects) {
nodes.push_back(o.getLocationName());
}
ws->populateNodes(nodes);
ws->mapNodes();
// Create the travel map
for (auto& o : objects) {
std::vector<std::string> connections = ws->fetchNodeLinks(o.getLocationName());
std::map<std::string, unsigned int> temp_travel_map;
for (auto& link : connections) {
auto travel_map_iter = travel_map.find(link);
temp_travel_map.insert(std::pair<std::string, unsigned int>
(travel_map_iter->first, travel_map_iter->second));
}
o.populateTravelDistances(temp_travel_map);
}
std::vector<warped::SimulationObject*> object_pointers;
for (auto& o : objects) {
object_pointers.push_back(&o);
}
epidemic_sim.simulate(object_pointers);
return 0;
}
<commit_msg>new version of config reader<commit_after>#include <fstream>
#include "epidemic.hpp"
#include "WattsStrogatzModel.hpp"
#include "tclap/ValueArg.h"
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(EpidemicEvent)
std::vector<std::shared_ptr<warped::Event> > Location::createInitialEvents() {
std::vector<std::shared_ptr<warped::Event> > events;
events.emplace_back(new EpidemicEvent {this->location_name_,
this->location_state_refresh_interval_, nullptr, DISEASE_UPDATE_TRIGGER});
events.emplace_back(new EpidemicEvent {this->location_name_,
this->location_diffusion_trigger_interval_, nullptr, DIFFUSION_TRIGGER});
return events;
}
std::vector<std::shared_ptr<warped::Event> > Location::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > events;
auto epidemic_event = static_cast<const EpidemicEvent&>(event);
auto timestamp = epidemic_event.loc_arrival_timestamp_;
switch (epidemic_event.event_type_) {
case event_type_t::DISEASE_UPDATE_TRIGGER: {
disease_model_->reaction(state_->current_population_, timestamp);
events.emplace_back(new EpidemicEvent {location_name_,
timestamp + location_state_refresh_interval_,
nullptr, DISEASE_UPDATE_TRIGGER});
} break;
case event_type_t::DIFFUSION_TRIGGER: {
std::string selected_location = diffusion_network_->pickLocation();
if (selected_location != "") {
auto travel_time = diffusion_network_->travelTimeToLocation(selected_location);
unsigned int person_count = state_->current_population_->size();
if (person_count) {
unsigned int person_id = diffusion_network_->pickPerson(person_count);
auto map_iter = state_->current_population_->begin();
unsigned int temp_cnt = 0;
while (temp_cnt < person_id) {
map_iter++;
temp_cnt++;
}
std::shared_ptr<Person> person = map_iter->second;
events.emplace_back(new EpidemicEvent {selected_location,
timestamp + travel_time, person, DIFFUSION});
state_->current_population_->erase(map_iter);
}
}
events.emplace_back(new EpidemicEvent {location_name_,
timestamp + location_diffusion_trigger_interval_,
nullptr, DIFFUSION_TRIGGER});
} break;
case event_type_t::DIFFUSION: {
std::shared_ptr<Person> person = std::make_shared<Person>(
epidemic_event.pid_, epidemic_event.susceptibility_,
epidemic_event.vaccination_status_, epidemic_event.infection_state_,
timestamp, epidemic_event.prev_state_change_timestamp_);
state_->current_population_->insert(state_->current_population_->begin(),
std::pair <unsigned long, std::shared_ptr<Person>> (epidemic_event.pid_, person));
} break;
default: {}
}
return events;
}
int main(int argc, const char** argv) {
std::string config_filename = "model_5k.dat";
TCLAP::ValueArg<std::string> config_arg("m", "model",
"Epidemic model config", false, config_filename, "string");
std::vector<TCLAP::Arg*> args = {&config_arg};
warped::Simulation epidemic_sim {"Epidemic Simulation", argc, argv, args};
config_filename = config_arg.getValue();
std::ifstream config_stream;
config_stream.open(config_filename);
if (!config_stream.is_open()) {
std::cerr << "Invalid configuration file - " << config_filename << std::endl;
return 0;
}
std::string buffer;
std::string delimiter = ",";
size_t pos = 0;
std::string token;
// Diffusion model
getline(config_stream, buffer);
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int diffusion_seed = (unsigned int) std::stoul(token);
buffer.erase(0, pos + delimiter.length());
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int k = (unsigned int) std::stoul(token);
buffer.erase(0, pos + delimiter.length());
float beta = std::stof(buffer);
// Disease model
getline(config_stream, buffer);
float transmissibility = std::stof(buffer);
getline(config_stream, buffer);
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int latent_dwell_time = (unsigned int) std::stoul(token);
buffer.erase(0, pos + delimiter.length());
float latent_infectivity = std::stof(buffer);
getline(config_stream, buffer);
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int incubating_dwell_time = (unsigned int) std::stoul(token);
buffer.erase(0, pos + delimiter.length());
float incubating_infectivity = std::stof(buffer);
getline(config_stream, buffer);
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int infectious_dwell_time = (unsigned int) std::stoul(token);
buffer.erase(0, pos + delimiter.length());
float infectious_infectivity = std::stof(buffer);
getline(config_stream, buffer);
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int asympt_dwell_time = (unsigned int) std::stoul(token);
buffer.erase(0, pos + delimiter.length());
float asympt_infectivity = std::stof(buffer);
getline(config_stream, buffer);
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
float prob_ulu = stof(token);
buffer.erase(0, pos + delimiter.length());
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
float prob_ulv = std::stof(token);
buffer.erase(0, pos + delimiter.length());
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
float prob_urv = std::stof(token);
buffer.erase(0, pos + delimiter.length());
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
float prob_uiv = std::stof(token);
buffer.erase(0, pos + delimiter.length());
float prob_uiu = std::stof(buffer);
getline(config_stream, buffer);
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int location_state_refresh_interval = (unsigned int) stoul(token);
buffer.erase(0, pos + delimiter.length());
unsigned int disease_seed = (unsigned int) stoul(buffer);
//Population
getline(config_stream, buffer);
unsigned int num_regions = (unsigned int) std::stoul(buffer);
std::map<std::string, unsigned int> travel_map;
std::vector<Location> objects;
for (unsigned int region_id = 0; region_id < num_regions; region_id++) {
getline(config_stream, buffer);
pos = buffer.find(delimiter);
std::string region_name = buffer.substr(0, pos);
buffer.erase(0, pos + delimiter.length());
unsigned int num_locations = (unsigned int) std::stoul(buffer);
for (unsigned int location_id = 0; location_id < num_locations; location_id++) {
getline(config_stream, buffer);
pos = buffer.find(delimiter);
std::string location_name = buffer.substr(0, pos);
std::string location = region_name + location_name;
std::cout << location << std::endl;
buffer.erase(0, pos + delimiter.length());
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int travel_time_to_hub = (unsigned int) std::stoul(token);
buffer.erase(0, pos + delimiter.length());
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned int diffusion_interval = (unsigned int) std::stoul(token);
buffer.erase(0, pos + delimiter.length());
unsigned int num_persons = (unsigned int) std::stoul(buffer);
std::vector<std::shared_ptr<Person>> population;
travel_map.insert(std::pair<std::string, unsigned int>(location, travel_time_to_hub));
for (unsigned int person_id = 0; person_id < num_persons; person_id++) {
getline(config_stream, buffer);
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
unsigned long pid = std::stoul(token);
buffer.erase(0, pos + delimiter.length());
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
double susceptibility = std::stod(buffer);
buffer.erase(0, pos + delimiter.length());
pos = buffer.find(delimiter);
token = buffer.substr(0, pos);
bool vaccination_status = (bool) std::stoi(token);
buffer.erase(0, pos + delimiter.length());
infection_state_t state = (infection_state_t) std::stoi(buffer);
auto person = std::make_shared<Person> ( pid,
susceptibility,
vaccination_status,
state,
0,
0
);
population.push_back(person);
}
objects.emplace_back( location,
transmissibility,
latent_dwell_time,
incubating_dwell_time,
infectious_dwell_time,
asympt_dwell_time,
latent_infectivity,
incubating_infectivity,
infectious_infectivity,
asympt_infectivity,
prob_ulu,
prob_ulv,
prob_urv,
prob_uiv,
prob_uiu,
location_state_refresh_interval,
diffusion_interval,
population,
travel_time_to_hub,
disease_seed,
diffusion_seed
);
}
}
config_stream.close();
// Create the Watts-Strogatz model
auto ws = std::make_shared<WattsStrogatzModel>(k, beta, diffusion_seed);
std::vector<std::string> nodes;
for (auto& o : objects) {
nodes.push_back(o.getLocationName());
}
ws->populateNodes(nodes);
ws->mapNodes();
// Create the travel map
for (auto& o : objects) {
std::vector<std::string> connections = ws->fetchNodeLinks(o.getLocationName());
std::map<std::string, unsigned int> temp_travel_map;
for (auto& link : connections) {
auto travel_map_iter = travel_map.find(link);
temp_travel_map.insert(std::pair<std::string, unsigned int>
(travel_map_iter->first, travel_map_iter->second));
}
o.populateTravelDistances(temp_travel_map);
}
std::vector<warped::SimulationObject*> object_pointers;
for (auto& o : objects) {
object_pointers.push_back(&o);
}
epidemic_sim.simulate(object_pointers);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 by Jakub Lekstan <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <v8.h>
#include <node.h>
#include <Uri.h>
#include <string.h>
static v8::Handle<v8::Value> parse(const v8::Arguments& args){
v8::HandleScope scope;
if (args.Length() == 0 || !args[0]->IsString()) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument has to be string")));
}
v8::String::Utf8Value url (args[0]->ToString());
if (url.length() == 0) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("String mustn't be empty")));
}
UriParserStateA state;
UriUriA uri;
state.uri = &uri;
if (uriParseUriA(&state, *url) != URI_SUCCESS) {
return scope.Close(v8::Boolean::New(false));
}
v8::PropertyAttribute attrib = (v8::PropertyAttribute) (v8::ReadOnly | v8::DontDelete);
v8::Local<v8::Object> data = v8::Object::New();
v8::Local<v8::String> emptyString = v8::String::New("");
v8::Local<v8::Array> emptyArray = v8::Array::New();
v8::Local<v8::Object> emptyObject = v8::Object::New();
int i, position, tmpPosition;
int hostSlashPosition = 0;
if (uri.scheme.first) {
// +1 here because we need : after protocol
data->Set(v8::String::New("protocol"), v8::String::New(uri.scheme.first, strlen(uri.scheme.first) - strlen(uri.scheme.afterLast) + 1), attrib);
} else {
data->Set(v8::String::New("protocol"), emptyString, attrib);
}
if (uri.userInfo.first) {
char *auth = (char*) uri.userInfo.first;
const char *delim = ":";
auth[strlen(uri.userInfo.first) - strlen(uri.userInfo.afterLast)] = '\0';
v8::Local<v8::Object> authData = v8::Object::New();
authData->Set(v8::String::New("user"), v8::String::New(strtok(auth, delim))), attrib;
authData->Set(v8::String::New("password"), v8::String::New(strtok(NULL, delim)), attrib);
data->Set(v8::String::New("auth"), authData, attrib);
} else {
data->Set(v8::String::New("auth"), emptyObject, attrib);
}
if (uri.hostText.first) {
//we need to find out is there anything after first / after host (or host:port)
int tmpLength = strlen(uri.hostText.first);
const char *tmp = strchr(uri.hostText.first, '/');
hostSlashPosition = tmpLength - ((tmp - uri.hostText.first) + 1);
data->Set(v8::String::New("hostname"), v8::String::New(uri.hostText.first, tmpLength - strlen(uri.hostText.afterLast)), attrib);
} else {
data->Set(v8::String::New("hostname"), emptyString, attrib);
}
/* UriIp4 ip4 = *uri.hostData.ip4;
fprintf(stderr, "HOSTDATA4: %s\n", ip4.data);
UriIp6 ip6 = *uri.hostData.ip6;
fprintf(stderr, "HOSTDATA6: %s\n", ip6.data);*/
if (uri.portText.first) {
data->Set(v8::String::New("port"), v8::String::New(uri.portText.first, strlen(uri.portText.first) - strlen(uri.portText.afterLast)), attrib);
} else {
data->Set(v8::String::New("port"), v8::Integer::New(80), attrib);
}
if (uri.query.first) {
char *query = (char*) uri.query.first;
query[strlen(uri.query.first) - strlen(uri.query.afterLast)] = '\0';
const char *amp = "&", *sum = "=";
char *queryParamPtr, *queryParam = strtok_r(query, amp, &queryParamPtr), *queryParamKey, *queryParamValue;
v8::Local<v8::Object> queryData = v8::Object::New();
while (queryParam) {
queryParamKey = strtok(queryParam, sum);
queryParamValue = strtok(NULL, sum);
queryParam = strtok_r(NULL, amp, &queryParamPtr);
queryData->Set(v8::String::New(queryParamKey), v8::String::New(queryParamValue), attrib);
}
data->Set(v8::String::New("query"), queryData, attrib);
} else {
data->Set(v8::String::New("query"), emptyObject, attrib);
}
if (uri.fragment.first) {
data->Set(v8::String::New("fragment"), v8::String::New(uri.fragment.first, strlen(uri.fragment.first) - strlen(uri.fragment.afterLast)), attrib);
} else {
data->Set(v8::String::New("fragment"), emptyString, attrib);
}
if (uri.pathHead && uri.pathHead->text.first && hostSlashPosition > 1) {
UriPathSegmentA pathHead = *uri.pathHead;
char *path = (char*) pathHead.text.first;
position = strlen(pathHead.text.first);
while (pathHead.next) {
i++;
pathHead = *pathHead.next;
}
tmpPosition = strlen(pathHead.text.afterLast);
path[position - tmpPosition] = '\0';
if (uri.absolutePath || uri.hostText.first) {
path--;
}
data->Set(v8::String::New("pathname"), v8::String::New(path), attrib);
} else {
data->Set(v8::String::New("pathname"), v8::String::New("/"), attrib);
}
/* UriPathSegmentA pathHead = *uri.pathHead;
if (pathHead.text.first) {
i = 0;
while (pathHead.next) {
i++;
pathHead = *pathHead.next;
}
pathHead = *uri.pathHead;
i = 0;
position = strlen(pathHead.text.afterLast);
tmpPosition = position - 1;
v8::Local<v8::Array> aPathHead = v8::Array::New(i + 1);
aPathHead->Set(v8::Number::New(i), v8::String::New(pathHead.text.first, strlen(pathHead.text.first) - position));
while (pathHead.next) {
i++;
pathHead = *pathHead.next;
position = strlen(pathHead.text.afterLast);
aPathHead->Set(v8::Number::New(i), v8::String::New(pathHead.text.first, tmpPosition - position));
tmpPosition = position - 1;
}
data->Set(v8::String::New("pathHead"), aPathHead);
} else {
data->Set(v8::String::New("pathHead"), emptyArray);
}*/
/* UriPathSegmentA pathTail = *uri.pathTail;
if (pathTail.text.first) {
i = 0;
while (pathTail.next) {
i++;
pathTail = *pathTail.next;
}
pathTail = *uri.pathTail;
i = 0;
position = strlen(pathTail.text.afterLast);
tmpPosition = position - 1;
v8::Local<v8::Array> aPathTail = v8::Array::New(i + 1);
aPathTail->Set(v8::Number::New(i), v8::String::New(pathTail.text.first, strlen(pathTail.text.first) - position));
while (pathTail.next) {
i++;
pathTail = *pathTail.next;
position = strlen(pathTail.text.afterLast);
aPathTail->Set(v8::Number::New(i), v8::String::New(pathTail.text.first, tmpPosition - position));
tmpPosition = position - 1;
}
data->Set(v8::String::New("pathTail"), aPathTail);
} else {
data->Set(v8::String::New("pathTail"), emptyArray);
}*/
// data->Set(v8::String::New("absolutePath"), v8::Boolean::New(uri.absolutePath));
// data->Set(v8::String::New("owner"), v8::Boolean::New(uri.owner));
uriFreeUriMembersA(&uri);
return scope.Close(data);
}
extern "C" void init (v8::Handle<v8::Object> target){
v8::HandleScope scope;
NODE_SET_METHOD(target, "parse", parse);
}
<commit_msg>Fixed segfaults, minor fixes<commit_after>/*
* Copyright (C) 2011 by Jakub Lekstan <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <v8.h>
#include <node.h>
#include <Uri.h>
#include <string.h>
static v8::Handle<v8::Value> parse(const v8::Arguments& args){
v8::HandleScope scope;
if (args.Length() == 0 || !args[0]->IsString()) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument has to be string")));
}
v8::String::Utf8Value url (args[0]->ToString());
if (url.length() == 0) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("String mustn't be empty")));
}
UriParserStateA state;
UriUriA uri;
state.uri = &uri;
if (uriParseUriA(&state, *url) != URI_SUCCESS) {
return scope.Close(v8::Boolean::New(false));
}
v8::PropertyAttribute attrib = (v8::PropertyAttribute) (v8::ReadOnly | v8::DontDelete);
v8::Local<v8::Object> data = v8::Object::New();
v8::Local<v8::String> emptyString = v8::String::New("");
v8::Local<v8::Array> emptyArray = v8::Array::New();
v8::Local<v8::Object> emptyObject = v8::Object::New();
int i, position, tmpPosition;
if (uri.scheme.first) {
// +1 here because we need : after protocol
data->Set(v8::String::New("protocol"), v8::String::New(uri.scheme.first, strlen(uri.scheme.first) - strlen(uri.scheme.afterLast) + 1), attrib);
} else {
data->Set(v8::String::New("protocol"), emptyString, attrib);
}
if (uri.userInfo.first) {
char *auth = (char*) uri.userInfo.first;
const char *delim = ":";
auth[strlen(uri.userInfo.first) - strlen(uri.userInfo.afterLast)] = '\0';
v8::Local<v8::Object> authData = v8::Object::New();
authData->Set(v8::String::New("user"), v8::String::New(strtok(auth, delim))), attrib;
authData->Set(v8::String::New("password"), v8::String::New(strtok(NULL, delim)), attrib);
data->Set(v8::String::New("auth"), authData, attrib);
} else {
data->Set(v8::String::New("auth"), emptyObject, attrib);
}
if (uri.hostText.first) {
//we need to find out is there anything after first / after host (or host:port)
int tmpLength = strlen(uri.hostText.first);
data->Set(v8::String::New("hostname"), v8::String::New(uri.hostText.first, tmpLength - strlen(uri.hostText.afterLast)), attrib);
} else {
data->Set(v8::String::New("hostname"), emptyString, attrib);
}
/* UriIp4 ip4 = *uri.hostData.ip4;
fprintf(stderr, "HOSTDATA4: %s\n", ip4.data);
UriIp6 ip6 = *uri.hostData.ip6;
fprintf(stderr, "HOSTDATA6: %s\n", ip6.data);*/
if (uri.portText.first) {
data->Set(v8::String::New("port"), v8::String::New(uri.portText.first, strlen(uri.portText.first) - strlen(uri.portText.afterLast)), attrib);
} else {
if (uri.hostText.first) {
data->Set(v8::String::New("port"), v8::Integer::New(80), attrib);
} else {
data->Set(v8::String::New("port"), emptyString, attrib);
}
}
if (uri.query.first) {
char *query = (char*) uri.query.first;
query[strlen(uri.query.first) - strlen(uri.query.afterLast)] = '\0';
const char *amp = "&", *sum = "=";
char *queryParamPtr, *queryParam = strtok_r(query, amp, &queryParamPtr), *queryParamKey, *queryParamValue;
v8::Local<v8::Object> queryData = v8::Object::New();
while (queryParam) {
queryParamKey = strtok(queryParam, sum);
queryParamValue = strtok(NULL, sum);
queryParam = strtok_r(NULL, amp, &queryParamPtr);
queryData->Set(v8::String::New(queryParamKey), queryParamValue ? v8::String::New(queryParamValue) : emptyString, attrib);
}
data->Set(v8::String::New("query"), queryData, attrib);
} else {
data->Set(v8::String::New("query"), emptyObject, attrib);
}
if (uri.fragment.first) {
data->Set(v8::String::New("fragment"), v8::String::New(uri.fragment.first, strlen(uri.fragment.first) - strlen(uri.fragment.afterLast)), attrib);
} else {
data->Set(v8::String::New("fragment"), emptyString, attrib);
}
if (uri.pathHead && uri.pathHead->text.first) {
UriPathSegmentA pathHead = *uri.pathHead;
char *path = (char*) pathHead.text.first;
position = strlen(pathHead.text.first);
while (pathHead.next) {
i++;
pathHead = *pathHead.next;
}
tmpPosition = strlen(pathHead.text.afterLast);
if ( (position - tmpPosition) > 0) {
path[position - tmpPosition] = '\0';
} else {
path = (char *) "/";
}
if ((uri.absolutePath || uri.hostText.first) && strlen(path) > 1) {
path--;
}
data->Set(v8::String::New("pathname"), v8::String::New(path), attrib);
} else {
data->Set(v8::String::New("pathname"), v8::String::New("/"), attrib);
}
/* UriPathSegmentA pathHead = *uri.pathHead;
if (pathHead.text.first) {
i = 0;
while (pathHead.next) {
i++;
pathHead = *pathHead.next;
}
pathHead = *uri.pathHead;
i = 0;
position = strlen(pathHead.text.afterLast);
tmpPosition = position - 1;
v8::Local<v8::Array> aPathHead = v8::Array::New(i + 1);
aPathHead->Set(v8::Number::New(i), v8::String::New(pathHead.text.first, strlen(pathHead.text.first) - position));
while (pathHead.next) {
i++;
pathHead = *pathHead.next;
position = strlen(pathHead.text.afterLast);
aPathHead->Set(v8::Number::New(i), v8::String::New(pathHead.text.first, tmpPosition - position));
tmpPosition = position - 1;
}
data->Set(v8::String::New("pathHead"), aPathHead);
} else {
data->Set(v8::String::New("pathHead"), emptyArray);
}*/
/* UriPathSegmentA pathTail = *uri.pathTail;
if (pathTail.text.first) {
i = 0;
while (pathTail.next) {
i++;
pathTail = *pathTail.next;
}
pathTail = *uri.pathTail;
i = 0;
position = strlen(pathTail.text.afterLast);
tmpPosition = position - 1;
v8::Local<v8::Array> aPathTail = v8::Array::New(i + 1);
aPathTail->Set(v8::Number::New(i), v8::String::New(pathTail.text.first, strlen(pathTail.text.first) - position));
while (pathTail.next) {
i++;
pathTail = *pathTail.next;
position = strlen(pathTail.text.afterLast);
aPathTail->Set(v8::Number::New(i), v8::String::New(pathTail.text.first, tmpPosition - position));
tmpPosition = position - 1;
}
data->Set(v8::String::New("pathTail"), aPathTail);
} else {
data->Set(v8::String::New("pathTail"), emptyArray);
}*/
// data->Set(v8::String::New("absolutePath"), v8::Boolean::New(uri.absolutePath));
// data->Set(v8::String::New("owner"), v8::Boolean::New(uri.owner));
uriFreeUriMembersA(&uri);
return scope.Close(data);
}
extern "C" void init (v8::Handle<v8::Object> target){
v8::HandleScope scope;
NODE_SET_METHOD(target, "parse", parse);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: libxmlutil.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:36:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if !defined INCLUDED_JVMFWK_LIBXMLUTIL_HXX
#define INCLUDED_JVMFWK_LIBXMLUTIL_HXX
#include "libxml/parser.h"
#include "libxml/xpath.h"
//#include "libxml/xpathinternals.h"
#include "rtl/ustring.hxx"
namespace jfw
{
class CXPathObjectPtr
{
xmlXPathObject* _object;
CXPathObjectPtr & operator = (const CXPathObjectPtr&);
CXPathObjectPtr(const CXPathObjectPtr&);
public:
CXPathObjectPtr();
/** Takes ownership of xmlXPathObject
*/
CXPathObjectPtr(xmlXPathObject* aObject);
~CXPathObjectPtr();
/** Takes ownership of xmlXPathObject
*/
CXPathObjectPtr & operator = (xmlXPathObject* pObj);
xmlXPathObject* operator -> ();
operator xmlXPathObject* ();
};
//===========================================================
class CXPathContextPtr
{
xmlXPathContext* _object;
CXPathContextPtr(const jfw::CXPathContextPtr&);
CXPathContextPtr & operator = (const CXPathContextPtr&);
public:
CXPathContextPtr();
CXPathContextPtr(xmlXPathContextPtr aContext);
CXPathContextPtr & operator = (xmlXPathContextPtr pObj);
~CXPathContextPtr();
xmlXPathContext* operator -> ();
operator xmlXPathContext* ();
};
//===========================================================
class CXmlDocPtr
{
xmlDoc* _object;
CXmlDocPtr(const CXmlDocPtr&);
CXmlDocPtr & operator = (const CXmlDocPtr&);
public:
CXmlDocPtr();
CXmlDocPtr(xmlDoc* aDoc);
/** Takes ownership of xmlDoc
*/
CXmlDocPtr & operator = (xmlDoc* pObj);
~CXmlDocPtr();
xmlDoc* operator -> ();
operator xmlDoc* ();
};
//===========================================================
// class CXmlNsPtr
// {
// xmlNs* _object;
// CXmlNsPtr(const CXmlNsPtr&);
// CXmlNsPtr & operator = (const CXmlNsPtr&);
// public:
// CXmlNsPtr();
// CXmlNsPtr(xmlNs* aDoc);
// /** Takes ownership of xmlDoc
// */
// CXmlNsPtr & operator = (xmlNs* pObj);
// ~CXmlNsPtr();
// xmlNs* operator -> ();
// operator xmlNs* ();
// };
//===========================================================
class CXmlCharPtr
{
xmlChar* _object;
CXmlCharPtr(const CXmlCharPtr&);
CXmlCharPtr & operator = (const CXmlCharPtr&);
public:
CXmlCharPtr();
CXmlCharPtr(xmlChar* aDoc);
~CXmlCharPtr();
CXmlCharPtr & operator = (xmlChar* pObj);
// xmlChar* operator -> ();
operator xmlChar* ();
operator rtl::OUString ();
operator rtl::OString ();
};
}
#endif
<commit_msg>INTEGRATION: CWS jl64 (1.3.80); FILE MERGED 2007/06/07 11:32:38 jl 1.3.80.2: #i76390# 2007/06/07 07:52:58 jl 1.3.80.1: #i76390# support of new bootstrap variable UNO_JAVA_JFW_INSTALL_DATA and UNO_JAVA_JFW_INSTALL_EXPIRE<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: libxmlutil.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2007-06-13 07:58:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if !defined INCLUDED_JVMFWK_LIBXMLUTIL_HXX
#define INCLUDED_JVMFWK_LIBXMLUTIL_HXX
#include "libxml/parser.h"
#include "libxml/xpath.h"
//#include "libxml/xpathinternals.h"
#include "rtl/ustring.hxx"
namespace jfw
{
class CXPathObjectPtr
{
xmlXPathObject* _object;
CXPathObjectPtr & operator = (const CXPathObjectPtr&);
CXPathObjectPtr(const CXPathObjectPtr&);
public:
CXPathObjectPtr();
/** Takes ownership of xmlXPathObject
*/
CXPathObjectPtr(xmlXPathObject* aObject);
~CXPathObjectPtr();
/** Takes ownership of xmlXPathObject
*/
CXPathObjectPtr & operator = (xmlXPathObject* pObj);
xmlXPathObject* operator -> ();
operator xmlXPathObject* ();
};
//===========================================================
class CXPathContextPtr
{
xmlXPathContext* _object;
CXPathContextPtr(const jfw::CXPathContextPtr&);
CXPathContextPtr & operator = (const CXPathContextPtr&);
public:
CXPathContextPtr();
CXPathContextPtr(xmlXPathContextPtr aContext);
CXPathContextPtr & operator = (xmlXPathContextPtr pObj);
~CXPathContextPtr();
xmlXPathContext* operator -> ();
operator xmlXPathContext* ();
};
//===========================================================
class CXmlDocPtr
{
xmlDoc* _object;
CXmlDocPtr(const CXmlDocPtr&);
public:
CXmlDocPtr & operator = (const CXmlDocPtr&);
CXmlDocPtr();
CXmlDocPtr(xmlDoc* aDoc);
/** Takes ownership of xmlDoc
*/
CXmlDocPtr & operator = (xmlDoc* pObj);
~CXmlDocPtr();
xmlDoc* operator -> ();
operator xmlDoc* ();
};
//===========================================================
// class CXmlNsPtr
// {
// xmlNs* _object;
// CXmlNsPtr(const CXmlNsPtr&);
// CXmlNsPtr & operator = (const CXmlNsPtr&);
// public:
// CXmlNsPtr();
// CXmlNsPtr(xmlNs* aDoc);
// /** Takes ownership of xmlDoc
// */
// CXmlNsPtr & operator = (xmlNs* pObj);
// ~CXmlNsPtr();
// xmlNs* operator -> ();
// operator xmlNs* ();
// };
//===========================================================
class CXmlCharPtr
{
xmlChar* _object;
CXmlCharPtr(const CXmlCharPtr&);
CXmlCharPtr & operator = (const CXmlCharPtr&);
public:
CXmlCharPtr();
CXmlCharPtr(xmlChar* aDoc);
CXmlCharPtr(const ::rtl::OUString &);
~CXmlCharPtr();
CXmlCharPtr & operator = (xmlChar* pObj);
// xmlChar* operator -> ();
operator xmlChar* ();
operator ::rtl::OUString ();
operator ::rtl::OString ();
};
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2007-2008 The Florida State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Stephen Hines
*/
#include "arch/arm/insts/macromem.hh"
#include "arch/arm/decoder.hh"
using namespace ArmISAInst;
namespace ArmISA
{
MacroMemOp::MacroMemOp(const char *mnem, ExtMachInst machInst,
OpClass __opClass, IntRegIndex rn,
bool index, bool up, bool user, bool writeback,
bool load, uint32_t reglist) :
PredMacroOp(mnem, machInst, __opClass)
{
uint32_t regs = reglist;
uint32_t ones = number_of_ones(reglist);
// Remember that writeback adds a uop
numMicroops = ones + (writeback ? 1 : 0) + 1;
microOps = new StaticInstPtr[numMicroops];
uint32_t addr = 0;
if (!up)
addr = (ones << 2) - 4;
if (!index)
addr += 4;
StaticInstPtr *uop = microOps;
StaticInstPtr wbUop;
if (writeback) {
if (up) {
wbUop = new MicroAddiUop(machInst, rn, rn, ones * 4);
} else {
wbUop = new MicroSubiUop(machInst, rn, rn, ones * 4);
}
}
// Add 0 to Rn and stick it in ureg0.
// This is equivalent to a move.
*uop = new MicroAddiUop(machInst, INTREG_UREG0, rn, 0);
// Write back at the start for loads. This covers the ldm exception return
// case where the base needs to be written in the old mode. Stores may need
// the original value of the base, but they don't change mode and can
// write back at the end like before.
if (load && writeback) {
*++uop = wbUop;
}
unsigned reg = 0;
bool force_user = user & !bits(reglist, 15);
bool exception_ret = user & bits(reglist, 15);
for (int i = 0; i < ones; i++) {
// Find the next register.
while (!bits(regs, reg))
reg++;
replaceBits(regs, reg, 0);
unsigned regIdx = reg;
if (force_user) {
regIdx = intRegInMode(MODE_USER, regIdx);
}
if (load) {
if (reg == INTREG_PC && exception_ret) {
// This must be the exception return form of ldm.
*++uop = new MicroLdrRetUop(machInst, regIdx,
INTREG_UREG0, up, addr);
} else {
*++uop = new MicroLdrUop(machInst, regIdx,
INTREG_UREG0, up, addr);
}
} else {
*++uop = new MicroStrUop(machInst, regIdx, INTREG_UREG0, up, addr);
}
if (up)
addr += 4;
else
addr -= 4;
}
if (!load && writeback) {
*++uop = wbUop;
}
(*uop)->setLastMicroop();
for (StaticInstPtr *curUop = microOps;
!(*curUop)->isLastMicroop(); curUop++) {
MicroOp * uopPtr = dynamic_cast<MicroOp *>(curUop->get());
assert(uopPtr);
uopPtr->setDelayedCommit();
}
}
MacroVFPMemOp::MacroVFPMemOp(const char *mnem, ExtMachInst machInst,
OpClass __opClass, IntRegIndex rn,
RegIndex vd, bool single, bool up,
bool writeback, bool load, uint32_t offset) :
PredMacroOp(mnem, machInst, __opClass)
{
int i = 0;
// The lowest order bit selects fldmx (set) or fldmd (clear). These seem
// to be functionally identical except that fldmx is deprecated. For now
// we'll assume they're otherwise interchangable.
int count = (single ? offset : (offset / 2));
if (count == 0 || count > NumFloatArchRegs)
warn_once("Bad offset field for VFP load/store multiple.\n");
if (count == 0) {
// Force there to be at least one microop so the macroop makes sense.
writeback = true;
}
if (count > NumFloatArchRegs)
count = NumFloatArchRegs;
numMicroops = count * (single ? 1 : 2) + (writeback ? 1 : 0);
microOps = new StaticInstPtr[numMicroops];
uint32_t addr = 0;
if (!up)
addr = 4 * offset;
bool tempUp = up;
for (int j = 0; j < count; j++) {
if (load) {
microOps[i++] = new MicroLdrFpUop(machInst, vd++, rn,
tempUp, addr);
if (!single)
microOps[i++] = new MicroLdrFpUop(machInst, vd++, rn,
tempUp, addr + 4);
} else {
microOps[i++] = new MicroStrFpUop(machInst, vd++, rn,
tempUp, addr);
if (!single)
microOps[i++] = new MicroStrFpUop(machInst, vd++, rn,
tempUp, addr + 4);
}
if (!tempUp) {
addr -= (single ? 4 : 8);
// The microops don't handle negative displacement, so turn if we
// hit zero, flip polarity and start adding.
if (addr == 0) {
tempUp = true;
}
} else {
addr += (single ? 4 : 8);
}
}
if (writeback) {
if (up) {
microOps[i++] =
new MicroAddiUop(machInst, rn, rn, 4 * offset);
} else {
microOps[i++] =
new MicroSubiUop(machInst, rn, rn, 4 * offset);
}
}
assert(numMicroops == i);
microOps[numMicroops - 1]->setLastMicroop();
for (StaticInstPtr *curUop = microOps;
!(*curUop)->isLastMicroop(); curUop++) {
MicroOp * uopPtr = dynamic_cast<MicroOp *>(curUop->get());
assert(uopPtr);
uopPtr->setDelayedCommit();
}
}
}
<commit_msg>ARM: Fix double precision load/store multiple decrement.<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2007-2008 The Florida State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Stephen Hines
*/
#include "arch/arm/insts/macromem.hh"
#include "arch/arm/decoder.hh"
using namespace ArmISAInst;
namespace ArmISA
{
MacroMemOp::MacroMemOp(const char *mnem, ExtMachInst machInst,
OpClass __opClass, IntRegIndex rn,
bool index, bool up, bool user, bool writeback,
bool load, uint32_t reglist) :
PredMacroOp(mnem, machInst, __opClass)
{
uint32_t regs = reglist;
uint32_t ones = number_of_ones(reglist);
// Remember that writeback adds a uop
numMicroops = ones + (writeback ? 1 : 0) + 1;
microOps = new StaticInstPtr[numMicroops];
uint32_t addr = 0;
if (!up)
addr = (ones << 2) - 4;
if (!index)
addr += 4;
StaticInstPtr *uop = microOps;
StaticInstPtr wbUop;
if (writeback) {
if (up) {
wbUop = new MicroAddiUop(machInst, rn, rn, ones * 4);
} else {
wbUop = new MicroSubiUop(machInst, rn, rn, ones * 4);
}
}
// Add 0 to Rn and stick it in ureg0.
// This is equivalent to a move.
*uop = new MicroAddiUop(machInst, INTREG_UREG0, rn, 0);
// Write back at the start for loads. This covers the ldm exception return
// case where the base needs to be written in the old mode. Stores may need
// the original value of the base, but they don't change mode and can
// write back at the end like before.
if (load && writeback) {
*++uop = wbUop;
}
unsigned reg = 0;
bool force_user = user & !bits(reglist, 15);
bool exception_ret = user & bits(reglist, 15);
for (int i = 0; i < ones; i++) {
// Find the next register.
while (!bits(regs, reg))
reg++;
replaceBits(regs, reg, 0);
unsigned regIdx = reg;
if (force_user) {
regIdx = intRegInMode(MODE_USER, regIdx);
}
if (load) {
if (reg == INTREG_PC && exception_ret) {
// This must be the exception return form of ldm.
*++uop = new MicroLdrRetUop(machInst, regIdx,
INTREG_UREG0, up, addr);
} else {
*++uop = new MicroLdrUop(machInst, regIdx,
INTREG_UREG0, up, addr);
}
} else {
*++uop = new MicroStrUop(machInst, regIdx, INTREG_UREG0, up, addr);
}
if (up)
addr += 4;
else
addr -= 4;
}
if (!load && writeback) {
*++uop = wbUop;
}
(*uop)->setLastMicroop();
for (StaticInstPtr *curUop = microOps;
!(*curUop)->isLastMicroop(); curUop++) {
MicroOp * uopPtr = dynamic_cast<MicroOp *>(curUop->get());
assert(uopPtr);
uopPtr->setDelayedCommit();
}
}
MacroVFPMemOp::MacroVFPMemOp(const char *mnem, ExtMachInst machInst,
OpClass __opClass, IntRegIndex rn,
RegIndex vd, bool single, bool up,
bool writeback, bool load, uint32_t offset) :
PredMacroOp(mnem, machInst, __opClass)
{
int i = 0;
// The lowest order bit selects fldmx (set) or fldmd (clear). These seem
// to be functionally identical except that fldmx is deprecated. For now
// we'll assume they're otherwise interchangable.
int count = (single ? offset : (offset / 2));
if (count == 0 || count > NumFloatArchRegs)
warn_once("Bad offset field for VFP load/store multiple.\n");
if (count == 0) {
// Force there to be at least one microop so the macroop makes sense.
writeback = true;
}
if (count > NumFloatArchRegs)
count = NumFloatArchRegs;
numMicroops = count * (single ? 1 : 2) + (writeback ? 1 : 0);
microOps = new StaticInstPtr[numMicroops];
int64_t addr = 0;
if (!up)
addr = 4 * offset;
bool tempUp = up;
for (int j = 0; j < count; j++) {
if (load) {
microOps[i++] = new MicroLdrFpUop(machInst, vd++, rn,
tempUp, addr);
if (!single)
microOps[i++] = new MicroLdrFpUop(machInst, vd++, rn, tempUp,
addr + (up ? 4 : -4));
} else {
microOps[i++] = new MicroStrFpUop(machInst, vd++, rn,
tempUp, addr);
if (!single)
microOps[i++] = new MicroStrFpUop(machInst, vd++, rn, tempUp,
addr + (up ? 4 : -4));
}
if (!tempUp) {
addr -= (single ? 4 : 8);
// The microops don't handle negative displacement, so turn if we
// hit zero, flip polarity and start adding.
if (addr <= 0) {
tempUp = true;
addr = -addr;
}
} else {
addr += (single ? 4 : 8);
}
}
if (writeback) {
if (up) {
microOps[i++] =
new MicroAddiUop(machInst, rn, rn, 4 * offset);
} else {
microOps[i++] =
new MicroSubiUop(machInst, rn, rn, 4 * offset);
}
}
assert(numMicroops == i);
microOps[numMicroops - 1]->setLastMicroop();
for (StaticInstPtr *curUop = microOps;
!(*curUop)->isLastMicroop(); curUop++) {
MicroOp * uopPtr = dynamic_cast<MicroOp *>(curUop->get());
assert(uopPtr);
uopPtr->setDelayedCommit();
}
}
}
<|endoftext|> |
<commit_before>#include<string>
#include<vector>
#include "vmf/metadatastream.hpp"
#include "../com_intel_vmf_MetadataDesc.h"
using namespace vmf;
static void throwJavaException(JNIEnv *env, const std::exception *e, const char *method)
{
std::string what = "unknown exception";
jclass je = 0;
if (e)
{
std::string exception_type = "std::exception";
if (dynamic_cast<const Exception*>(e))
{
exception_type = "vmf::Exception";
je = env->FindClass("com/intel/vmf/VmfException");
}
what = exception_type + ": " + e->what();
}
if (!je)
je = env->FindClass("java/lang/Exception");
env->ThrowNew(je, what.c_str());
VMF_LOG_ERROR(what.c_str());
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_MetadataDesc
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__ (JNIEnv *, jclass)
{
return (jlong) new MetadataDesc ();
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_MetadataDesc
* Signature: (Ljava/lang/String;J)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2J (JNIEnv *env, jclass, jstring mdName, jlong type)
{
std::string sName (env->GetStringUTFChars (mdName, NULL));
Variant::Type Type = (Variant::Type) type;
return (jlong) new MetadataDesc (sName, Type);
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_MetadataDesc
* Signature: (Ljava/lang/String;[J)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2_3J (JNIEnv *env, jclass, jstring mdName, jlongArray fieldDescs)
{
std::string sName (env->GetStringUTFChars (mdName, NULL));
std::vector <FieldDesc> descs;
jlong* cArray = env->GetLongArrayElements (fieldDescs, 0);
jsize len = env->GetArrayLength (fieldDescs);
for (int i = 0; i < len; i++)
{
FieldDesc* pFieldDesc = (FieldDesc*) cArray[i];
descs.push_back (*pFieldDesc);
}
env->ReleaseLongArrayElements (fieldDescs, cArray, 0);
return (jlong) new MetadataDesc (sName, descs);
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_MetadataDesc
* Signature: (Ljava/lang/String;[J[J)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2_3J_3J (JNIEnv *env, jclass, jstring mdName, jlongArray fieldDescs, jlongArray refDescs)
{
std::string sName (env->GetStringUTFChars (mdName, NULL));
std::vector <FieldDesc> fdVec;
std::vector<std::shared_ptr<ReferenceDesc>> rdVec;
jlong* descArray = env->GetLongArrayElements (fieldDescs, 0);
jlong* refArray = env->GetLongArrayElements (refDescs, 0);
jsize lenDescs = env->GetArrayLength (fieldDescs);
jsize lenRefs = env->GetArrayLength (refDescs);
for (int i = 0; i < lenDescs; i++)
{
FieldDesc* pFieldDesc = (FieldDesc*) descArray[i];
fdVec.push_back (*pFieldDesc);
}
for (int i = 0; i < lenRefs; i++)
{
ReferenceDesc* pRefDesc = (ReferenceDesc*) refArray[i];
std::shared_ptr<ReferenceDesc> spRefDesc(pRefDesc);
rdVec.push_back (spRefDesc);
}
env->ReleaseLongArrayElements (fieldDescs, descArray, 0);
env->ReleaseLongArrayElements (refDescs, refArray, 0);
return (jlong) new MetadataDesc (sName, fdVec, rdVec);
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getMetadataName
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_intel_vmf_MetadataDesc_n_1getMetadataName (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1getMetadataName";
try
{
MetadataDesc* obj = (MetadataDesc*) self;
std::string str = obj->getMetadataName ();
return env->NewStringUTF (str.c_str());
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getSchemaName
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_intel_vmf_MetadataDesc_n_1getSchemaName (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1getSchemaName";
try
{
MetadataDesc* obj = (MetadataDesc*) self;
std::string str = obj->getSchemaName ();
return env->NewStringUTF (str.c_str());
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getFields
* Signature: (J)[Lcom/intel/vmf/FieldDesc;
*/
JNIEXPORT jlongArray JNICALL Java_com_intel_vmf_MetadataDesc_n_1getFields (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1getFields";
try
{
MetadataDesc* obj = (MetadataDesc*) self;
std::vector<FieldDesc> vec = obj->getFields ();
jlongArray nObjs = env->NewLongArray ((jsize)vec.size());
jlong* body = env->GetLongArrayElements (nObjs, 0);
for (std::size_t i = 0; i < vec.size(); i++)
{
body[i] = (jlong) new FieldDesc (vec[i].name, vec[i].type, vec[i].optional);
}
env->ReleaseLongArrayElements (nObjs, body, 0);
return nObjs;
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getAllReferenceDescs
* Signature: (J)[Lcom/intel/vmf/ReferenceDesc;
*/
JNIEXPORT jlongArray JNICALL Java_com_intel_vmf_MetadataDesc_n_1getAllReferenceDescs (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1getAllReferenceDescs";
try
{
MetadataDesc* obj = (MetadataDesc*) self;
std::vector<std::shared_ptr<ReferenceDesc>> vec = obj->getAllReferenceDescs ();
jlongArray nObjs = env->NewLongArray ((jsize)vec.size());
jlong* body = env->GetLongArrayElements (nObjs, 0);
for (std::size_t i = 0; i < vec.size(); i++)
{
body[i] = (jlong) vec[i].get();
}
env->ReleaseLongArrayElements (nObjs, body, 0);
return nObjs;
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_declareCustomReference
* Signature: (JLjava/lang/String;Z)V
*/
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataDesc_n_1declareCustomReference (JNIEnv *env, jclass, jlong self, jstring refName, jboolean isUnique)
{
static const char method_name[] = "MetadataDesc::n_1declareCustomReference";
try
{
MetadataDesc* obj = (MetadataDesc*) self;
std::string sName (env->GetStringUTFChars (refName, NULL));
obj->declareCustomReference (sName, (isUnique == 1) ? true : false);
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getReferenceDesc
* Signature: (JLjava/lang/String;)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1getReferenceDesc (JNIEnv *env, jclass, jlong self, jstring refName)
{
static const char method_name[] = "MetadataDesc::n_1getReferenceDesc";
try
{
MetadataDesc* obj = (MetadataDesc*) self;
std::string sName (env->GetStringUTFChars (refName, NULL));
return (jlong) (obj->getReferenceDesc (sName)).get();
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getFieldDesc
* Signature: (JLcom/intel/vmf/FieldDesc;Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_com_intel_vmf_MetadataDesc_n_1getFieldDesc (JNIEnv *env, jclass, jlong self, jlong fieldDescAddr, jstring fieldName)
{
static const char method_name[] = "MetadataDesc::n_1getFieldDesc";
try
{
MetadataDesc* obj = (MetadataDesc*) self;
FieldDesc* fieldDesc = (FieldDesc*) fieldDescAddr;
std::string sName (env->GetStringUTFChars (fieldName, NULL));
return (jboolean) obj->getFieldDesc (*fieldDesc, sName);
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_delete
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataDesc_n_1delete (JNIEnv *, jclass, jlong self)
{
delete (MetadataDesc*) self;
}
<commit_msg>Add shared_ptr to JNI MetadataDesc<commit_after>#include<string>
#include<vector>
#include "vmf/metadatastream.hpp"
#include "../com_intel_vmf_MetadataDesc.h"
using namespace vmf;
static void throwJavaException(JNIEnv *env, const std::exception *e, const char *method)
{
std::string what = "unknown exception";
jclass je = 0;
if (e)
{
std::string exception_type = "std::exception";
if (dynamic_cast<const Exception*>(e))
{
exception_type = "vmf::Exception";
je = env->FindClass("com/intel/vmf/VmfException");
}
what = exception_type + ": " + e->what();
}
if (!je)
je = env->FindClass("java/lang/Exception");
env->ThrowNew(je, what.c_str());
VMF_LOG_ERROR(what.c_str());
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_MetadataDesc
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__ (JNIEnv *, jclass)
{
std::shared_ptr<MetadataDesc>* p = new std::shared_ptr<MetadataDesc>(new MetadataDesc());
return (jlong) p;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_MetadataDesc
* Signature: (Ljava/lang/String;J)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2J (JNIEnv *env, jclass, jstring mdName, jlong type)
{
std::string sName (env->GetStringUTFChars (mdName, NULL));
std::shared_ptr<MetadataDesc>* p = new std::shared_ptr<MetadataDesc>(new MetadataDesc(sName, (Variant::Type) type));
return (jlong) p;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_MetadataDesc
* Signature: (Ljava/lang/String;[J)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2_3J (JNIEnv *env, jclass, jstring mdName, jlongArray fieldDescs)
{
std::string sName (env->GetStringUTFChars (mdName, NULL));
std::vector <FieldDesc> descs;
jlong* cArray = env->GetLongArrayElements (fieldDescs, 0);
jsize len = env->GetArrayLength (fieldDescs);
for (int i = 0; i < len; i++)
{
std::shared_ptr<FieldDesc>* pFieldDesc = (std::shared_ptr<FieldDesc>*)cArray[i];
descs.push_back (**pFieldDesc);
}
env->ReleaseLongArrayElements (fieldDescs, cArray, 0);
return (jlong) new std::shared_ptr<MetadataDesc>(new MetadataDesc(sName, descs));
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_MetadataDesc
* Signature: (Ljava/lang/String;[J[J)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2_3J_3J (JNIEnv *env, jclass, jstring mdName, jlongArray fieldDescs, jlongArray refDescs)
{
std::string sName (env->GetStringUTFChars (mdName, NULL));
std::vector <FieldDesc> fdVec;
std::vector<std::shared_ptr<ReferenceDesc>> rdVec;
jlong* descArray = env->GetLongArrayElements (fieldDescs, 0);
jlong* refArray = env->GetLongArrayElements (refDescs, 0);
jsize lenDescs = env->GetArrayLength (fieldDescs);
jsize lenRefs = env->GetArrayLength (refDescs);
for (int i = 0; i < lenDescs; i++)
{
std::shared_ptr<FieldDesc>* pFieldDesc = (std::shared_ptr<FieldDesc>*) descArray[i];
fdVec.push_back (**pFieldDesc);
}
for (int i = 0; i < lenRefs; i++)
{
std::shared_ptr<ReferenceDesc>* pRefDesc = (std::shared_ptr<ReferenceDesc>*)refArray[i];
rdVec.push_back (*pRefDesc);
}
env->ReleaseLongArrayElements (fieldDescs, descArray, 0);
env->ReleaseLongArrayElements (refDescs, refArray, 0);
return (jlong) new std::shared_ptr<MetadataDesc>(new MetadataDesc(sName, fdVec, rdVec));
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getMetadataName
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_intel_vmf_MetadataDesc_n_1getMetadataName (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1getMetadataName";
try
{
std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
std::string str = (*obj)->getMetadataName ();
return env->NewStringUTF (str.c_str());
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getSchemaName
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_intel_vmf_MetadataDesc_n_1getSchemaName (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1getSchemaName";
try
{
std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
std::string str = (*obj)->getSchemaName ();
return env->NewStringUTF (str.c_str());
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getFields
* Signature: (J)[Lcom/intel/vmf/FieldDesc;
*/
JNIEXPORT jlongArray JNICALL Java_com_intel_vmf_MetadataDesc_n_1getFields (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1getFields";
try
{
std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
std::vector<FieldDesc> vec = (*obj)->getFields ();
jlongArray nObjs = env->NewLongArray ((jsize)vec.size());
jlong* body = env->GetLongArrayElements (nObjs, 0);
for (std::size_t i = 0; i < vec.size(); i++)
{
body[i] = (jlong) new std::shared_ptr<FieldDesc>(new FieldDesc (vec[i].name, vec[i].type, vec[i].optional));
}
env->ReleaseLongArrayElements (nObjs, body, 0);
return nObjs;
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getAllReferenceDescs
* Signature: (J)[Lcom/intel/vmf/ReferenceDesc;
*/
JNIEXPORT jlongArray JNICALL Java_com_intel_vmf_MetadataDesc_n_1getAllReferenceDescs (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1getAllReferenceDescs";
try
{
std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
std::vector<std::shared_ptr<ReferenceDesc>> vec = (*obj)->getAllReferenceDescs ();
jlongArray nObjs = env->NewLongArray ((jsize)vec.size());
jlong* body = env->GetLongArrayElements (nObjs, 0);
for (std::size_t i = 0; i < vec.size(); i++)
{
body[i] = (jlong) new std::shared_ptr<ReferenceDesc>(new ReferenceDesc(vec[i]->name, vec[i]->isUnique, vec[i]->isCustom));
}
env->ReleaseLongArrayElements (nObjs, body, 0);
return nObjs;
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_declareCustomReference
* Signature: (JLjava/lang/String;Z)V
*/
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataDesc_n_1declareCustomReference (JNIEnv *env, jclass, jlong self, jstring refName, jboolean isUnique)
{
static const char method_name[] = "MetadataDesc::n_1declareCustomReference";
try
{
std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
std::string sName (env->GetStringUTFChars (refName, NULL));
(*obj)->declareCustomReference (sName, (isUnique == 1) ? true : false);
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getReferenceDesc
* Signature: (JLjava/lang/String;)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1getReferenceDesc (JNIEnv *env, jclass, jlong self, jstring refName)
{
static const char method_name[] = "MetadataDesc::n_1getReferenceDesc";
try
{
std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
std::string sName (env->GetStringUTFChars (refName, NULL));
std::shared_ptr<ReferenceDesc> sp = (*obj)->getReferenceDesc(sName);
return (jlong) new std::shared_ptr<ReferenceDesc>(new ReferenceDesc (sp->name, sp->isUnique, sp->isCustom));
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_getFieldDesc
* Signature: (JLcom/intel/vmf/FieldDesc;Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_com_intel_vmf_MetadataDesc_n_1getFieldDesc (JNIEnv *env, jclass, jlong self, jlong fieldDescAddr, jstring fieldName)
{
static const char method_name[] = "MetadataDesc::n_1getFieldDesc";
try
{
std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
std::shared_ptr<FieldDesc>* fieldDesc = (std::shared_ptr<FieldDesc>*)fieldDescAddr;
std::string sName (env->GetStringUTFChars (fieldName, NULL));
return (jboolean) (*obj)->getFieldDesc (**fieldDesc, sName);
}
catch(const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
return 0;
}
/*
* Class: com_intel_vmf_MetadataDesc
* Method: n_delete
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataDesc_n_1delete (JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "MetadataDesc::n_1delete";
try
{
std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
delete obj;
}
catch (const std::exception &e)
{
throwJavaException(env, &e, method_name);
}
catch (...)
{
throwJavaException(env, 0, method_name);
}
}
<|endoftext|> |
<commit_before>#include <tiramisu/tiramisu.h>
#include "configure.h"
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("relu_tiramisu");
var i("i", 0, 4);
input parameters("parameters", {i}, p_float32);
constant C_N("C_N", cast(p_int32, parameters(0)));
constant C_FIn("C_FIn", cast(p_int32, parameters(1)));
constant C_BATCH_SIZE("C_BATCH_SIZE", cast(p_int32, parameters(2)));
var x("x", 0, C_N), y("y", 0, C_N), z("z", 0, C_FIn), n("n", 0, C_BATCH_SIZE);
input c_input("c_input", {n, z, y, x}, p_float32);
computation c_relu("c_relu", {n, z, y, x}, expr(o_max, c_input(n, z, y, x), expr((float)0)) + parameters(3) * expr(o_min, c_input(n, z, y, x), expr((float)0)));
// Layer II
int o_block = 4;
int vec_len = N / 4;
int y_block = N / 4;
if (LARGE_DATA_SET)
{
c_relu.tag_parallel_level(0);
c_relu.split(3, vec_len);
c_relu.tag_vector_level(4, vec_len);
c_relu.tag_unroll_level(5);
}
else if (MEDIUM_DATA_SET)
{
c_relu.split(3, y_block);
c_relu.tag_vector_level(5, vec_len);
c_relu.tag_unroll_level(6);
}
else if (SMALL_DATA_SET)
{
c_relu.tag_parallel_level(0);
c_relu.split(3, 32);
c_relu.tag_vector_level(4, 32);
c_relu.tag_unroll_level(5);
}
// Layer III
buffer input_buff("input_buff", {expr(C_BATCH_SIZE), expr(C_FIn), expr(C_N), expr(C_N)}, p_float32, a_input);
buffer parameters_buff("parameters_buff", {expr(4)}, p_float32, a_input);
buffer output_buff("output_buff", {expr(C_BATCH_SIZE), expr(C_FIn), expr(C_N), expr(C_N)}, p_float32, a_output);
c_input.store_in(&input_buff);
c_relu.store_in(&output_buff);
parameters.store_in(¶meters_buff);
tiramisu::codegen({&input_buff, ¶meters_buff, &output_buff}, "relu_layer_generator_tiramisu.o");
return 0;
}
<commit_msg>Delete relu_layer_generator_tiramisu.cpp<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2018 The Open-Transactions developers
// 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 "Client.hpp"
#define OT_METHOD "opentxs::notary::Client::"
namespace opentxs::notary
{
Client::Client(
const opentxs::api::client::Manager& client,
const opentxs::api::server::Manager& server,
const int network)
: client_(client)
, server_(server)
, network_(network)
, server_nym_callback_(network::zeromq::ListenCallback::Factory(
std::bind(&Client::server_nym_updated, this, std::placeholders::_1)))
, server_nym_subscriber_(
server_.ZeroMQ().SubscribeSocket(server_nym_callback_))
{
const auto started =
server_nym_subscriber_->Start(server_.Endpoints().NymDownload());
OT_ASSERT(started);
test_nym();
migrate_contract();
set_address_type();
client_.Sync().StartIntroductionServer(server_.NymID());
client_.Sync().SchedulePublishServerContract(
server_.NymID(), client_.Sync().IntroductionServer(), server_.ID());
}
void Client::import_nym() const
{
const auto serverNym = server_.Wallet().Nym(server_.NymID());
OT_ASSERT(serverNym);
proto::HDPath path{};
const auto havePath = serverNym->Path(path);
OT_ASSERT(havePath);
const auto seedID = Identifier::Factory(path.root());
OTPassword words{}, passphrase{};
words.setPassword(server_.Seeds().Words(seedID->str()));
passphrase.setPassword(server_.Seeds().Passphrase(seedID->str()));
const auto imported = client_.Seeds().ImportSeed(words, passphrase);
OT_ASSERT(imported == seedID->str());
OT_ASSERT(2 == path.child_size());
// TODO const auto index = path.child(1);
// TODO OT_ASSERT(0 == index);
{
#if OT_CRYPTO_SUPPORTED_KEY_HD
NymParameters nymParameters(proto::CREDTYPE_HD);
nymParameters.SetSeed(seedID->str());
nymParameters.SetNym(0);
nymParameters.SetDefault(false);
#else
NymParameters nymParameters(proto::CREDTYPE_LEGACY);
#endif
auto clientNym = client_.Wallet().Nym(nymParameters);
OT_ASSERT(clientNym);
OT_ASSERT(clientNym->CompareID(server_.NymID()));
}
}
void Client::migrate_contract() const
{
const auto serverContract = server_.Wallet().Server(server_.ID());
OT_ASSERT(serverContract);
auto clientContract =
client_.Wallet().Server(serverContract->PublicContract());
OT_ASSERT(clientContract);
}
void Client::migrate_nym() const
{
const auto serverNym = server_.Wallet().Nym(server_.NymID());
OT_ASSERT(serverNym);
auto clientNym = client_.Wallet().mutable_Nym(server_.NymID());
clientNym.SetContactData(serverNym->Claims().Serialize());
}
void Client::server_nym_updated(const network::zeromq::Message& message) const
{
if (1 > message.Body().size()) {
otErr << OT_METHOD << __FUNCTION__ << ": Missing nym ID." << std::endl;
return;
}
const auto& frame = message.Body_at(0);
const auto id = Identifier::Factory(frame);
if (server_.NymID() == id) { migrate_nym(); }
}
void Client::set_address_type() const
{
if (network_ != client_.ZMQ().DefaultAddressType()) {
bool notUsed{false};
client_.Config().Set_long(
"Connection", "preferred_address_type", network_, notUsed);
client_.Config().Save();
}
}
void Client::test_nym() const
{
const auto clientNym = client_.Wallet().Nym(server_.NymID());
if (false == bool(clientNym)) { import_nym(); }
migrate_nym();
}
} // namespace opentxs::notary
<commit_msg>Use OTString to Instantiate String Objects: Client.cpp<commit_after>// Copyright (c) 2018 The Open-Transactions developers
// 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 "Client.hpp"
#define OT_METHOD "opentxs::notary::Client::"
namespace opentxs::notary
{
Client::Client(
const opentxs::api::client::Manager& client,
const opentxs::api::server::Manager& server,
const int network)
: client_(client)
, server_(server)
, network_(network)
, server_nym_callback_(network::zeromq::ListenCallback::Factory(
std::bind(&Client::server_nym_updated, this, std::placeholders::_1)))
, server_nym_subscriber_(
server_.ZeroMQ().SubscribeSocket(server_nym_callback_))
{
const auto started =
server_nym_subscriber_->Start(server_.Endpoints().NymDownload());
OT_ASSERT(started);
test_nym();
migrate_contract();
set_address_type();
client_.Sync().StartIntroductionServer(server_.NymID());
client_.Sync().SchedulePublishServerContract(
server_.NymID(), client_.Sync().IntroductionServer(), server_.ID());
}
void Client::import_nym() const
{
const auto serverNym = server_.Wallet().Nym(server_.NymID());
OT_ASSERT(serverNym);
proto::HDPath path{};
const auto havePath = serverNym->Path(path);
OT_ASSERT(havePath);
const auto seedID = Identifier::Factory(path.root());
OTPassword words{}, passphrase{};
words.setPassword(server_.Seeds().Words(seedID->str()));
passphrase.setPassword(server_.Seeds().Passphrase(seedID->str()));
const auto imported = client_.Seeds().ImportSeed(words, passphrase);
OT_ASSERT(imported == seedID->str());
OT_ASSERT(2 == path.child_size());
// TODO const auto index = path.child(1);
// TODO OT_ASSERT(0 == index);
{
#if OT_CRYPTO_SUPPORTED_KEY_HD
NymParameters nymParameters(proto::CREDTYPE_HD);
nymParameters.SetSeed(seedID->str());
nymParameters.SetNym(0);
nymParameters.SetDefault(false);
#else
NymParameters nymParameters(proto::CREDTYPE_LEGACY);
#endif
auto clientNym = client_.Wallet().Nym(nymParameters);
OT_ASSERT(clientNym);
OT_ASSERT(clientNym->CompareID(server_.NymID()));
}
}
void Client::migrate_contract() const
{
const auto serverContract = server_.Wallet().Server(server_.ID());
OT_ASSERT(serverContract);
auto clientContract =
client_.Wallet().Server(serverContract->PublicContract());
OT_ASSERT(clientContract);
}
void Client::migrate_nym() const
{
const auto serverNym = server_.Wallet().Nym(server_.NymID());
OT_ASSERT(serverNym);
auto clientNym = client_.Wallet().mutable_Nym(server_.NymID());
clientNym.SetContactData(serverNym->Claims().Serialize());
}
void Client::server_nym_updated(const network::zeromq::Message& message) const
{
if (1 > message.Body().size()) {
otErr << OT_METHOD << __FUNCTION__ << ": Missing nym ID." << std::endl;
return;
}
const auto& frame = message.Body_at(0);
const auto id = Identifier::Factory(frame);
if (server_.NymID() == id) { migrate_nym(); }
}
void Client::set_address_type() const
{
if (network_ != client_.ZMQ().DefaultAddressType()) {
bool notUsed{false};
client_.Config().Set_long(
String::Factory("Connection"),
String::Factory("preferred_address_type"),
network_, notUsed);
client_.Config().Save();
}
}
void Client::test_nym() const
{
const auto clientNym = client_.Wallet().Nym(server_.NymID());
if (false == bool(clientNym)) { import_nym(); }
migrate_nym();
}
} // namespace opentxs::notary
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
#include <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Modules/Visualization/ShowField.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Utils/Exception.h>
#include <Core/Logging/Log.h>
using namespace SCIRun::Testing;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core;
using namespace SCIRun;
using namespace SCIRun::Core::Logging;
using ::testing::Values;
using ::testing::Combine;
using ::testing::Range;
class ShowFieldScalingTest : public ParameterizedModuleTest<int>
{
protected:
virtual void SetUp()
{
Log::get().setVerbose(false);
showField = makeModule("ShowField");
showField->setStateDefaults();
auto size = GetParam();
latVol = CreateEmptyLatVol(size, size, size);
stubPortNWithThisData(showField, 0, latVol);
Log::get() << INFO << "Setting up ShowField with size " << size << "^3 latvol" << std::endl;
}
UseRealModuleStateFactory f;
ModuleHandle showField;
FieldHandle latVol;
};
TEST_P(ShowFieldScalingTest, ConstructLatVolGeometry)
{
Log::get() << INFO << "Start ShowField::execute" << std::endl;
showField->execute();
Log::get() << INFO << "End ShowField::execute" << std::endl;
}
INSTANTIATE_TEST_CASE_P(
ConstructLatVolGeometry,
ShowFieldScalingTest,
Values(20, 40, 60, 80, 100
//, 120, 150, 200 //to speed up make test
//, 256 // probably runs out of memory
)
);
<commit_msg>Closes #625<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
#include <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Modules/Visualization/ShowField.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Utils/Exception.h>
#include <Core/Logging/Log.h>
using namespace SCIRun::Testing;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core;
using namespace SCIRun;
using namespace SCIRun::Core::Logging;
using ::testing::Values;
using ::testing::Combine;
using ::testing::Range;
class ShowFieldScalingTest : public ParameterizedModuleTest<int>
{
protected:
virtual void SetUp()
{
Log::get().setVerbose(false);
showField = makeModule("ShowField");
showField->setStateDefaults();
auto size = GetParam();
latVol = CreateEmptyLatVol(size, size, size);
stubPortNWithThisData(showField, 0, latVol);
Log::get() << INFO << "Setting up ShowField with size " << size << "^3 latvol" << std::endl;
}
UseRealModuleStateFactory f;
ModuleHandle showField;
FieldHandle latVol;
};
TEST_P(ShowFieldScalingTest, ConstructLatVolGeometry)
{
Log::get() << INFO << "Start ShowField::execute" << std::endl;
showField->execute();
Log::get() << INFO << "End ShowField::execute" << std::endl;
}
INSTANTIATE_TEST_CASE_P(
ConstructLatVolGeometry,
ShowFieldScalingTest,
Values(20, 40, 60, 80
//, 100, 120, 150, 200 //to speed up make test
//, 256 // probably runs out of memory
)
);
<|endoftext|> |
<commit_before>/*
This file is part of KAddressbook.
Copyright (c) 2000 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 <qlayout.h>
#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kinstance.h>
#include <klocale.h>
#include <kparts/genericfactory.h>
#include "kabcore.h"
#include "kaddressbookiface.h"
#include "libkdepim/infoextension.h"
#include "kaddressbook_part.h"
typedef KParts::GenericFactory< KAddressbookPart > KAddressbookFactory;
K_EXPORT_COMPONENT_FACTORY( libkaddressbookpart, KAddressbookFactory );
KAddressbookPart::KAddressbookPart( QWidget *parentWidget, const char *widgetName,
QObject *parent, const char *name,
const QStringList & )
: DCOPObject( "KAddressBookIface" ), KParts::ReadOnlyPart( parent, name )
{
kdDebug(5720) << "KAddressbookPart()" << endl;
kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl;
setInstance( KAddressbookFactory::instance() );
kdDebug(5720) << "KAddressbookPart()..." << endl;
kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl;
// create a canvas to insert our widget
QWidget *canvas = new QWidget( parentWidget, widgetName );
canvas->setFocusPolicy( QWidget::ClickFocus );
setWidget( canvas );
mExtension = new KAddressbookBrowserExtension( this );
QVBoxLayout *topLayout = new QVBoxLayout( canvas );
KGlobal::iconLoader()->addAppDir( "kaddressbook" );
mCore = new KABCore( this, true, canvas );
mCore->restoreSettings();
topLayout->addWidget( mCore );
KParts::InfoExtension *info = new KParts::InfoExtension( this, "KABPart" );
connect( mCore, SIGNAL( contactSelected( const QString& ) ),
info, SIGNAL( textChanged( const QString& ) ) );
connect( mCore, SIGNAL( contactSelected( const QPixmap& ) ),
info, SIGNAL( iconChanged( const QPixmap& ) ) );
setXMLFile( "kaddressbook_part.rc" );
}
KAddressbookPart::~KAddressbookPart()
{
mCore->save();
closeURL();
}
KAboutData *KAddressbookPart::createAboutData()
{
return KABCore::createAboutData();
}
void KAddressbookPart::addEmail( QString addr )
{
mCore->addEmail( addr );
}
ASYNC KAddressbookPart::showContactEditor( QString uid )
{
mCore->editContact( uid );
}
void KAddressbookPart::newContact()
{
mCore->newContact();
}
QString KAddressbookPart::getNameByPhone( QString phone )
{
return mCore->getNameByPhone( phone );
}
void KAddressbookPart::save()
{
mCore->save();
}
void KAddressbookPart::exit()
{
delete this;
}
bool KAddressbookPart::openFile()
{
kdDebug(5720) << "KAddressbookPart:openFile()" << endl;
mCore->show();
return true;
}
void KAddressbookPart::guiActivateEvent( KParts::GUIActivateEvent *e )
{
kdDebug(5720) << "KAddressbookPart::guiActivateEvent" << endl;
KParts::ReadOnlyPart::guiActivateEvent( e );
}
KAddressbookBrowserExtension::KAddressbookBrowserExtension( KAddressbookPart *parent )
: KParts::BrowserExtension( parent, "KAddressbookBrowserExtension" )
{
}
KAddressbookBrowserExtension::~KAddressbookBrowserExtension()
{
}
using namespace KParts;
#include "kaddressbook_part.moc"
<commit_msg>Pass KAboutData to Kontact<commit_after>/*
This file is part of KAddressbook.
Copyright (c) 2000 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 <qlayout.h>
#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kinstance.h>
#include <klocale.h>
#include <kparts/genericfactory.h>
#include "kabcore.h"
#include "kaddressbookiface.h"
#include "libkdepim/aboutdataextension.h"
#include "libkdepim/infoextension.h"
#include "kaddressbook_part.h"
typedef KParts::GenericFactory< KAddressbookPart > KAddressbookFactory;
K_EXPORT_COMPONENT_FACTORY( libkaddressbookpart, KAddressbookFactory );
KAddressbookPart::KAddressbookPart( QWidget *parentWidget, const char *widgetName,
QObject *parent, const char *name,
const QStringList & )
: DCOPObject( "KAddressBookIface" ), KParts::ReadOnlyPart( parent, name )
{
kdDebug(5720) << "KAddressbookPart()" << endl;
kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl;
setInstance( KAddressbookFactory::instance() );
kdDebug(5720) << "KAddressbookPart()..." << endl;
kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl;
// create a canvas to insert our widget
QWidget *canvas = new QWidget( parentWidget, widgetName );
canvas->setFocusPolicy( QWidget::ClickFocus );
setWidget( canvas );
mExtension = new KAddressbookBrowserExtension( this );
QVBoxLayout *topLayout = new QVBoxLayout( canvas );
KGlobal::iconLoader()->addAppDir( "kaddressbook" );
mCore = new KABCore( this, true, canvas );
mCore->restoreSettings();
topLayout->addWidget( mCore );
KParts::InfoExtension *info = new KParts::InfoExtension( this, "KABPart" );
connect( mCore, SIGNAL( contactSelected( const QString& ) ),
info, SIGNAL( textChanged( const QString& ) ) );
connect( mCore, SIGNAL( contactSelected( const QPixmap& ) ),
info, SIGNAL( iconChanged( const QPixmap& ) ) );
new KParts::AboutDataExtension( createAboutData(), this, "AboutData" );
setXMLFile( "kaddressbook_part.rc" );
}
KAddressbookPart::~KAddressbookPart()
{
mCore->save();
closeURL();
}
KAboutData *KAddressbookPart::createAboutData()
{
return KABCore::createAboutData();
}
void KAddressbookPart::addEmail( QString addr )
{
mCore->addEmail( addr );
}
ASYNC KAddressbookPart::showContactEditor( QString uid )
{
mCore->editContact( uid );
}
void KAddressbookPart::newContact()
{
mCore->newContact();
}
QString KAddressbookPart::getNameByPhone( QString phone )
{
return mCore->getNameByPhone( phone );
}
void KAddressbookPart::save()
{
mCore->save();
}
void KAddressbookPart::exit()
{
delete this;
}
bool KAddressbookPart::openFile()
{
kdDebug(5720) << "KAddressbookPart:openFile()" << endl;
mCore->show();
return true;
}
void KAddressbookPart::guiActivateEvent( KParts::GUIActivateEvent *e )
{
kdDebug(5720) << "KAddressbookPart::guiActivateEvent" << endl;
KParts::ReadOnlyPart::guiActivateEvent( e );
}
KAddressbookBrowserExtension::KAddressbookBrowserExtension( KAddressbookPart *parent )
: KParts::BrowserExtension( parent, "KAddressbookBrowserExtension" )
{
}
KAddressbookBrowserExtension::~KAddressbookBrowserExtension()
{
}
using namespace KParts;
#include "kaddressbook_part.moc"
<|endoftext|> |
<commit_before>/*
* plan_and_run_node.cpp
*
* Created on: Apr 10, 2015
* Author: Jorge Nicho
*/
#include <plan_and_run/demo_application.h>
int main(int argc,char** argv)
{
ros::init(argc,argv,"plan_and_run");
ros::AsyncSpinner spinner(2);
spinner.start();
// creating application
plan_and_run::DemoApplication application;
// loading parameters
application.loadParameters();
// initializing ros components
application.initRos();
// initializing descartes
application.initDescartes();
// moving to home position
application.moveHome();
// generating trajectory
plan_and_run::DescartesTrajectory traj;
application.generateTrajectory(traj);
// planning robot path
plan_and_run::DescartesTrajectory output_path;
application.planPath(traj,output_path);
// running robot path
application.runPath(output_path);
// exiting ros node
spinner.stop();
return 0;
}
<commit_msg>Added vectorization fix for 32bit machines<commit_after>/*
* plan_and_run_node.cpp
*
* Created on: Apr 10, 2015
* Author: Jorge Nicho
*/
#ifdef __i386__
#pragma message("i386 Architecture detected, disabling EIGEN VECTORIZATION")
#define EIGEN_DONT_VECTORIZE
#define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT
#else
#pragma message("64bit Architecture detected, enabling EIGEN VECTORIZATION")
#endif
#include <plan_and_run/demo_application.h>
int main(int argc,char** argv)
{
ros::init(argc,argv,"plan_and_run");
ros::AsyncSpinner spinner(2);
spinner.start();
// creating application
plan_and_run::DemoApplication application;
// loading parameters
application.loadParameters();
// initializing ros components
application.initRos();
// initializing descartes
application.initDescartes();
// moving to home position
application.moveHome();
// generating trajectory
plan_and_run::DescartesTrajectory traj;
application.generateTrajectory(traj);
// planning robot path
plan_and_run::DescartesTrajectory output_path;
application.planPath(traj,output_path);
// running robot path
application.runPath(output_path);
// exiting ros node
spinner.stop();
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.