text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
Persons Model Item
Represents one person in the model
Copyright (C) 2012 Martin Klapetek <martin.klapetek@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "person-item.h"
#include "contact-item.h"
#include <Nepomuk2/Vocabulary/PIMO>
#include <Nepomuk2/Vocabulary/NCO>
#include <Nepomuk2/Resource>
#include <Nepomuk2/Variant>
#include <Soprano/Vocabulary/NAO>
#include <KDebug>
PersonItem::PersonItem(const QUrl &personUri)
{
setData(personUri, PersonsModel::UriRole);
}
PersonItem::PersonItem(const Nepomuk2::Resource &person)
{
setData(person.uri(), PersonsModel::UriRole);
setContacts(person.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList());
kDebug() << "new person" << text() << rowCount();
}
QVariant PersonItem::queryChildrenForRole(int role) const
{
QVariant ret;
for (int i = 0; i < rowCount(); i++) {
QVariant value = child(i)->data(role);
if (!value.isNull()) {
ret = value;
break;
}
}
return ret;
}
QVariantList PersonItem::queryChildrenForRoleList(int role) const
{
QVariantList ret;
for (int i = 0; i < rowCount(); i++) {
QVariant value = child(i)->data(role);
if (value.type() == QVariant::List) {
ret += value.toList();
} else if (!value.isNull()) {
ret += value;
}
}
return ret;
}
QVariant PersonItem::data(int role) const
{
switch(role) {
case PersonsModel::NameRole:
case Qt::DisplayRole: {
QVariant value = queryChildrenForRole(Qt::DisplayRole);
if (value.isNull()) {
value = queryChildrenForRole(PersonsModel::ContactIdRole);
}
if (value.isNull()) {
return QString("PIMO:Person - %1").arg(data(PersonsModel::UriRole).toString());
} else {
return value;
}
}
case PersonsModel::StatusRole: //TODO: use a better algorithm for finding the actual status
case PersonsModel::NickRole:
case PersonsModel::LabelRole:
case PersonsModel::IMRole:
case PersonsModel::IMAccountTypeRole:
case PersonsModel::PhoneRole:
case PersonsModel::EmailRole:
case PersonsModel::ContactIdRole:
case PersonsModel::ContactTypeRole:
case PersonsModel::ContactGroupsRole: {
//we need to return empty qvariant here, otherwise we'd get a qvariant
//with empty qvariantlist, which would get parsed as non-empty qvariant
QVariantList val = queryChildrenForRoleList(role);
if (val.isEmpty()) {
return QVariant();
} else {
return val;
}
}
case Qt::DecorationRole:
case PersonsModel::PhotoRole:
return queryChildrenForRole(role);
case PersonsModel::ContactsCountRole:
return rowCount();
case PersonsModel::ResourceTypeRole:
return PersonsModel::Person;
}
return QStandardItem::data(role);
}
void PersonItem::removeContacts(const QList<QUrl> &contacts)
{
kDebug() << "remove contacts" << contacts;
for (int i = 0; i < rowCount(); ) {
QStandardItem *item = child(i);
if (item && contacts.contains(item->data(PersonsModel::UriRole).toUrl())) {
model()->invisibleRootItem()->appendRow(takeRow(i));
} else {
++i;
}
}
emitDataChanged();
}
void PersonItem::addContacts(const QList<QUrl> &_contacts)
{
QList<QUrl> contacts(_contacts);
//get existing child-contacts and remove them from the new ones
QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole);
foreach (const QVariant &uri, uris) {
contacts.removeOne(uri.toUrl());
}
//query the model for the contacts, if they are present, then need to be just moved
QList<QStandardItem*> toplevelContacts;
foreach (const QUrl &uri, contacts) {
QModelIndex contactIndex = qobject_cast<PersonsModel*>(model())->indexForUri(uri);
if (contactIndex.isValid()) {
toplevelContacts.append(qobject_cast<PersonsModel*>(model())->takeRow(contactIndex.row()));
}
}
//append the moved contacts to this person and remove them from 'contacts'
//so they are not added twice
foreach (QStandardItem *contactItem, toplevelContacts) {
ContactItem *contact = dynamic_cast<ContactItem*>(contactItem);
appendRow(contact);
contacts.removeOne(contact->uri());
}
kDebug() << "add contacts" << contacts;
QList<ContactItem*> rows;
foreach (const QUrl &uri, contacts) {
ContactItem *item = new ContactItem(uri);
item->loadData();
appendRow(item);
}
emitDataChanged();
}
void PersonItem::setContacts(const QList<QUrl> &contacts)
{
kDebug() << "set contacts" << contacts;
if (contacts.isEmpty()) {
//nothing to do here
return;
}
if (hasChildren()) {
QList<QUrl> toRemove;
QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole);
foreach (const QVariant &contact, uris) {
if (!contacts.contains(contact.toUrl()))
toRemove += contact.toUrl();
}
removeContacts(toRemove);
}
QList<QUrl> toAdd;
foreach (const QUrl &contact, contacts) {
toAdd += contact;
}
addContacts(toAdd);
Q_ASSERT(hasChildren());
}
<commit_msg>Remove useless kDebug line<commit_after>/*
Persons Model Item
Represents one person in the model
Copyright (C) 2012 Martin Klapetek <martin.klapetek@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "person-item.h"
#include "contact-item.h"
#include <Nepomuk2/Vocabulary/PIMO>
#include <Nepomuk2/Vocabulary/NCO>
#include <Nepomuk2/Resource>
#include <Nepomuk2/Variant>
#include <Soprano/Vocabulary/NAO>
#include <KDebug>
PersonItem::PersonItem(const QUrl &personUri)
{
setData(personUri, PersonsModel::UriRole);
}
PersonItem::PersonItem(const Nepomuk2::Resource &person)
{
setData(person.uri(), PersonsModel::UriRole);
setContacts(person.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList());
kDebug() << "new person" << text() << rowCount();
}
QVariant PersonItem::queryChildrenForRole(int role) const
{
QVariant ret;
for (int i = 0; i < rowCount(); i++) {
QVariant value = child(i)->data(role);
if (!value.isNull()) {
ret = value;
break;
}
}
return ret;
}
QVariantList PersonItem::queryChildrenForRoleList(int role) const
{
QVariantList ret;
for (int i = 0; i < rowCount(); i++) {
QVariant value = child(i)->data(role);
if (value.type() == QVariant::List) {
ret += value.toList();
} else if (!value.isNull()) {
ret += value;
}
}
return ret;
}
QVariant PersonItem::data(int role) const
{
switch(role) {
case PersonsModel::NameRole:
case Qt::DisplayRole: {
QVariant value = queryChildrenForRole(Qt::DisplayRole);
if (value.isNull()) {
value = queryChildrenForRole(PersonsModel::ContactIdRole);
}
if (value.isNull()) {
return QString("PIMO:Person - %1").arg(data(PersonsModel::UriRole).toString());
} else {
return value;
}
}
case PersonsModel::StatusRole: //TODO: use a better algorithm for finding the actual status
case PersonsModel::NickRole:
case PersonsModel::LabelRole:
case PersonsModel::IMRole:
case PersonsModel::IMAccountTypeRole:
case PersonsModel::PhoneRole:
case PersonsModel::EmailRole:
case PersonsModel::ContactIdRole:
case PersonsModel::ContactTypeRole:
case PersonsModel::ContactGroupsRole: {
//we need to return empty qvariant here, otherwise we'd get a qvariant
//with empty qvariantlist, which would get parsed as non-empty qvariant
QVariantList val = queryChildrenForRoleList(role);
if (val.isEmpty()) {
return QVariant();
} else {
return val;
}
}
case Qt::DecorationRole:
case PersonsModel::PhotoRole:
return queryChildrenForRole(role);
case PersonsModel::ContactsCountRole:
return rowCount();
case PersonsModel::ResourceTypeRole:
return PersonsModel::Person;
}
return QStandardItem::data(role);
}
void PersonItem::removeContacts(const QList<QUrl> &contacts)
{
kDebug() << "remove contacts" << contacts;
for (int i = 0; i < rowCount(); ) {
QStandardItem *item = child(i);
if (item && contacts.contains(item->data(PersonsModel::UriRole).toUrl())) {
model()->invisibleRootItem()->appendRow(takeRow(i));
} else {
++i;
}
}
emitDataChanged();
}
void PersonItem::addContacts(const QList<QUrl> &_contacts)
{
QList<QUrl> contacts(_contacts);
//get existing child-contacts and remove them from the new ones
QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole);
foreach (const QVariant &uri, uris) {
contacts.removeOne(uri.toUrl());
}
//query the model for the contacts, if they are present, then need to be just moved
QList<QStandardItem*> toplevelContacts;
foreach (const QUrl &uri, contacts) {
QModelIndex contactIndex = qobject_cast<PersonsModel*>(model())->indexForUri(uri);
if (contactIndex.isValid()) {
toplevelContacts.append(qobject_cast<PersonsModel*>(model())->takeRow(contactIndex.row()));
}
}
//append the moved contacts to this person and remove them from 'contacts'
//so they are not added twice
foreach (QStandardItem *contactItem, toplevelContacts) {
ContactItem *contact = dynamic_cast<ContactItem*>(contactItem);
appendRow(contact);
contacts.removeOne(contact->uri());
}
QList<ContactItem*> rows;
foreach (const QUrl &uri, contacts) {
ContactItem *item = new ContactItem(uri);
item->loadData();
appendRow(item);
}
emitDataChanged();
}
void PersonItem::setContacts(const QList<QUrl> &contacts)
{
kDebug() << "set contacts" << contacts;
if (contacts.isEmpty()) {
//nothing to do here
return;
}
if (hasChildren()) {
QList<QUrl> toRemove;
QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole);
foreach (const QVariant &contact, uris) {
if (!contacts.contains(contact.toUrl()))
toRemove += contact.toUrl();
}
removeContacts(toRemove);
}
QList<QUrl> toAdd;
foreach (const QUrl &contact, contacts) {
toAdd += contact;
}
addContacts(toAdd);
Q_ASSERT(hasChildren());
}
<|endoftext|>
|
<commit_before>#ifndef VG_PICTOGRAPHS_HPP_INCLUDED
#define VG_PICTOGRAPHS_HPP_INCLUDED
#include <vector>
#include <random>
#include <functional>
namespace vg {
using namespace std;
class Pictographs {
mt19937 rng;
public:
const string symbols = "🌀🌁🌂🌃🌄🌅🌆🌇🌈🌉🌊🌋🌌🌍🌎🌏🌐🌑🌒🌓🌔🌕🌖🌗🌘🌙🌚🌛🌜🌝🌞🌟🌠🌡🌢🌣🌤🌥🌦🌧🌨🌩🌪🌫🌬🌭🌮🌯🌰🌱🌲🌳🌴🌵🌶🌷🌸🌹🌺🌻🌼🌽🌾🌿🍀🍁🍂🍃🍄🍅🍆🍇🍈🍉🍊🍋🍌🍍🍎🍏🍐🍑🍒🍓🍔🍕🍖🍗🍘🍙🍚🍛🍜🍝🍞🍟🍠🍡🍢🍣🍤🍥🍦🍧🍨🍩🍪🍫🍬🍭🍮🍯🍰🍱🍲🍳🍴🍵🍶🍷🍸🍹🍺🍻🍼🍽🍾🍿🎀🎁🎂🎃🎄🎅🎆🎇🎈🎉🎊🎋🎌🎍🎎🎏🎐🎑🎒🎓🎔🎕🎖🎗🎘🎙🎚🎛🎜🎝🎞🎟🎠🎡🎢🎣🎤🎥🎦🎧🎨🎩🎪🎫🎬🎭🎮🎯🎰🎱🎲🎳🎴🎵🎶🎷🎸🎹🎺🎻🎼🎽🎾🎿🏀🏁🏂🏃🏄🏅🏆🏇🏈🏉🏊🏋🏌🏍🏎🏏🏐🏑🏒🏓🏔🏕🏖🏗🏘🏙🏚🏛🏜🏝🏞🏟🏠🏡🏢🏣🏤🏥🏦🏧🏨🏩🏪🏫🏬🏭🏮🏯🏰🏱🏲🏳🏴🏵🏶🏷🏸🏹🏺🏻🏼🏽🏾🏿🐀🐁🐂🐃🐄🐅🐆🐇🐈🐉🐊🐋🐌🐍🐎🐏🐐🐑🐒🐓🐔🐕🐖🐗🐘🐙🐚🐛🐜🐝🐞🐟🐠🐡🐢🐣🐤🐥🐦🐧🐨🐩🐪🐫🐬🐭🐮🐯🐰🐱🐲🐳🐴🐵🐶🐷🐸🐹🐺🐻🐼🐽🐾🐿👀👁👂👃👄👅👆👇👈👉👊👋👌👍👎👏👐👑👒👓👔👕👖👗👘👙👚👛👜👝👞👟👠👡👢👣👤👥👦👧👨👩👪👫👬👭👮👯👰👱👲👳👴👵👶👷👸👹👺👻👼👽👾👿💀💁💂💃💄💅💆💇💈💉💊💋💌💍💎💏💐💑💒💓💔💕💖💗💘💙💚💛💜💝💞💟💠💡💢💣💤💥💦💧💨💩💪💫💬💭💮💯💰💱💲💳💴💵💶💷💸💹💺💻💼💽💾💿📀📁📂📃📄📅📆📇📈📉📊📋📌📍📎📏📐📑📒📓📔📕📖📗📘📙📚📛📜📝📞📟📠📡📢📣📤📥📦📧📨📩📪📫📬📭📮📯📰📱📲📳📴📵📶📷📸📹📺📻📼📽📾📿🔀🔁🔂🔃🔄🔅🔆🔇🔈🔉🔊🔋🔌🔍🔎🔏🔐🔑🔒🔓🔔🔕🔖🔗🔘🔙🔚🔛🔜🔝🔞🔟🔠🔡🔢🔣🔤🔥🔦🔧🔨🔩🔪🔫🔬🔭🔮🔯🔰🔱🔲🔳🔴🔵🔶🔷🔸🔹🔺🔻🔼🔽🔾🔿🕀🕁🕂🕃🕄🕅🕆🕇🕈🕉🕊🕋🕌🕍🕎🕏🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🕜🕝🕞🕟🕠🕡🕢🕣🕤🕥🕦🕧🕨🕩🕪🕫🕬🕭🕮🕯🕰🕱🕲🕳🕴🕵🕶🕷🕸🕹🕻🕼🕽🕾🕿🖀🖁🖂🖃🖄🖅🖆🖇🖈🖉🖊🖋🖌🖍🖎🖏🖐🖑🖒🖓🖔🖕🖖🖗🖘🖙🖚🖛🖜🖝🖞🖟🖠🖡🖢🖣🖥🖦🖧🖨🖩🖪🖫🖬🖭🖮🖯🖰🖱🖲🖳🖴🖵🖶🖷🖸🖹🖺🖻🖼🖽🖾🖿🗀🗁🗂🗃🗄🗅🗆🗇🗈🗉🗊🗋🗌🗍🗎🗏🗐🗑🗒🗓🗔🗕🗖🗗🗘🗙🗚🗛🗜🗝🗞🗟🗠🗡🗢🗣🗤🗥🗦🗧🗨🗩🗪🗫🗬🗭🗮🗯🗰🗱🗲🗳🗴🗵🗶🗷🗸🗹🗺🗻🗼🗽🗾🗿";
const int count = 766;
Pictographs(void) { };
Pictographs(int seed_val) {
rng.seed(seed_val);
};
~Pictographs(void) { };
string hashed(const string& str) {
std::hash<std::string> hash_fn;
std::size_t str_hash = hash_fn(str);
size_t i = str_hash % count;
return symbols.substr(4*i, 4);
}
string random(void) {
uniform_int_distribution<int> dist(0, count);
size_t i = dist(rng);
return symbols.substr(4*i, 4);
}
};
}
#endif
<commit_msg>add poop emoji<commit_after>#ifndef VG_PICTOGRAPHS_HPP_INCLUDED
#define VG_PICTOGRAPHS_HPP_INCLUDED
#include <vector>
#include <random>
#include <functional>
namespace vg {
using namespace std;
class Pictographs {
mt19937 rng;
public:
const string symbols = "🌀🌁🌂🌃🌄🌅🌆🌇🌈🌉🌊🌋🌌🌍🌎🌏🌐🌑🌒🌓🌔🌕🌖🌗🌘🌙🌚🌛🌜🌝🌞🌟🌠🌡🌢🌣🌤🌥🌦🌧🌨🌩🌪🌫🌬🌭🌮🌯🌰🌱🌲🌳🌴🌵🌶🌷🌸🌹🌺🌻🌼🌽🌾🌿🍀🍁🍂🍃🍄🍅🍆🍇🍈🍉🍊🍋🍌🍍🍎🍏🍐🍑🍒🍓🍔🍕🍖🍗🍘🍙🍚🍛🍜🍝🍞🍟🍠🍡🍢🍣🍤🍥🍦🍧🍨🍩🍪🍫🍬🍭🍮🍯🍰🍱🍲🍳🍴🍵🍶🍷🍸🍹🍺🍻🍼🍽🍾🍿🎀🎁🎂🎃🎄🎅🎆🎇🎈🎉🎊🎋🎌🎍🎎🎏🎐🎑🎒🎓🎔🎕🎖🎗🎘🎙🎚🎛🎜🎝🎞🎟🎠🎡🎢🎣🎤🎥🎦🎧🎨🎩🎪🎫🎬🎭🎮🎯🎰🎱🎲🎳🎴🎵🎶🎷🎸🎹🎺🎻🎼🎽🎾🎿🏀🏁🏂🏃🏄🏅🏆🏇🏈🏉🏊🏋🏌🏍🏎🏏🏐🏑🏒🏓🏔🏕🏖🏗🏘🏙🏚🏛🏜🏝🏞🏟🏠🏡🏢🏣🏤🏥🏦🏧🏨🏩🏪🏫🏬🏭🏮🏯🏰🏱🏲🏳🏴🏵🏶🏷🏸🏹🏺🏻🏼🏽🏾🏿🐀🐁🐂🐃🐄🐅🐆🐇🐈🐉🐊🐋🐌🐍🐎🐏🐐🐑🐒🐓🐔🐕🐖🐗🐘🐙🐚🐛🐜🐝🐞🐟🐠🐡🐢🐣🐤🐥🐦🐧🐨🐩🐪🐫🐬🐭🐮🐯🐰🐱🐲🐳🐴🐵🐶🐷🐸🐹🐺🐻🐼🐽🐾🐿👀👁👂👃👄👅👆👇👈👉👊👋👌👍👎👏👐👑👒👓👔👕👖👗👘👙👚👛👜👝👞👟👠👡👢👣👤👥👦👧👨👩👪👫👬👭👮👯👰👱👲👳👴👵👶👷👸👹👺👻👼👽👾👿💀💁💂💃💄💅💆💇💈💉💊💋💌💍💎💏💐💑💒💓💔💕💖💗💘💙💚💛💜💝💞💟💠💡💢💣💤💥💦💧💨💩💪💫💬💭💮💯💰💱💲💳💴💵💶💷💸💹💺💻💼💽💾💿📀📁📂📃📄📅📆📇📈📉📊📋📌📍📎📏📐📑📒📓📔📕📖📗📘📙📚📛📜📝📞📟📠📡📢📣📤📥📦📧📨📩📪📫📬📭📮📯📰📱📲📳📴📵📶📷📸📹📺📻📼📽📾📿🔀🔁🔂🔃🔄🔅🔆🔇🔈🔉🔊🔋🔌🔍🔎🔏🔐🔑🔒🔓🔔🔕🔖🔗🔘🔙🔚🔛🔜🔝🔞🔟🔠🔡🔢🔣🔤🔥🔦🔧🔨🔩🔪🔫🔬🔭🔮🔯🔰🔱🔲🔳🔴🔵🔶🔷🔸🔹🔺🔻🔼🔽🔾🔿🕀🕁🕂🕃🕄🕅🕆🕇🕈🕉🕊🕋🕌🕍🕎🕏🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🕜🕝🕞🕟🕠🕡🕢🕣🕤🕥🕦🕧🕨🕩🕪🕫🕬🕭🕮🕯🕰🕱🕲🕳🕴🕵🕶🕷🕸🕹🕻🕼🕽🕾🕿🖀🖁🖂🖃🖄🖅🖆🖇🖈🖉🖊🖋🖌🖍🖎🖏🖐🖑🖒🖓🖔🖕🖖🖗🖘🖙🖚🖛🖜🖝🖞🖟🖠🖡🖢🖣🖥🖦🖧🖨🖩🖪🖫🖬🖭🖮🖯🖰🖱🖲🖳🖴🖵🖶🖷🖸🖹🖺🖻🖼🖽🖾🖿🗀🗁🗂🗃🗄🗅🗆🗇🗈🗉🗊🗋🗌🗍🗎🗏🗐🗑🗒🗓🗔🗕🗖🗗🗘🗙🗚🗛🗜🗝🗞🗟🗠🗡🗢🗣🗤🗥🗦🗧🗨🗩🗪🗫🗬🗭🗮🗯🗰🗱🗲🗳🗴🗵🗶🗷🗸🗹🗺🗻🗼🗽🗾🗿💩";
const int count = 766;
Pictographs(void) { };
Pictographs(int seed_val) {
rng.seed(seed_val);
};
~Pictographs(void) { };
string hashed(const string& str) {
std::hash<std::string> hash_fn;
std::size_t str_hash = hash_fn(str);
size_t i = str_hash % count;
return symbols.substr(4*i, 4);
}
string random(void) {
uniform_int_distribution<int> dist(0, count);
size_t i = dist(rng);
return symbols.substr(4*i, 4);
}
};
}
#endif
<|endoftext|>
|
<commit_before>/// \file
/// \ingroup tutorial_v7
///
/// \macro_code
///
/// \date 2015-08-08
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/// \author Axel Naumann <axel@cern.ch>
/*************************************************************************
* Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ROOT/RHist.hxx"
#include <iostream>
void histops()
{
using namespace ROOT;
// Create a 2D histogram with an X axis with equidistant bins, and a y axis
// with irregular binning.
Experimental::TH2D hist1({100, 0., 1.}, {{0., 1., 2., 3., 10.}});
// Fill weight 1. at the coordinate 0.01, 1.02.
hist1.Fill({0.01, 1.02});
Experimental::TH2D hist2({{{10, 0., 1.}, {{0., 1., 2., 3., 10.}}}});
// Fill weight 1. at the coordinate 0.01, 1.02.
hist2.Fill({0.01, 1.02});
Experimental::Add(hist1, hist2);
int binidx = hist1.GetImpl()->GetBinIndex({0.01, 1.02});
std::cout << hist1.GetImpl()->GetBinContent(binidx) << std::endl;
}
<commit_msg>[v7hist tutorial] follow RHist rename.<commit_after>/// \file
/// \ingroup tutorial_v7
///
/// \macro_code
///
/// \date 2015-08-08
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/// \author Axel Naumann <axel@cern.ch>
/*************************************************************************
* Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ROOT/RHist.hxx"
#include <iostream>
void histops()
{
using namespace ROOT;
// Create a 2D histogram with an X axis with equidistant bins, and a y axis
// with irregular binning.
Experimental::RH2D hist1({100, 0., 1.}, {{0., 1., 2., 3., 10.}});
// Fill weight 1. at the coordinate 0.01, 1.02.
hist1.Fill({0.01, 1.02});
Experimental::RH2D hist2({{{10, 0., 1.}, {{0., 1., 2., 3., 10.}}}});
// Fill weight 1. at the coordinate 0.01, 1.02.
hist2.Fill({0.01, 1.02});
Experimental::Add(hist1, hist2);
int binidx = hist1.GetImpl()->GetBinIndex({0.01, 1.02});
std::cout << hist1.GetImpl()->GetBinContent(binidx) << std::endl;
}
<|endoftext|>
|
<commit_before>#include "glm/gtc/matrix_transform.hpp"
#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/helper/screenHelpers.h"
using namespace pb;
Camera::Camera(glm::vec3 position, glm::vec3 rotation)
: Position(position)
, Rotation(rotation)
, ZNear(1)
, ZFar(1000)
{
}
Camera::~Camera()
{
}
void Camera::CalculateTransform(Viewport* viewport)
{
Frustum.Set(ViewProjectionMatrix);
}
OrthographicCamera::OrthographicCamera(glm::vec3 position, glm::vec3 rotation, glm::vec2 scale)
: Camera(position, rotation)
, Scale(scale)
{
}
Camera::CameraType OrthographicCamera::GetType()
{
return kCameraOrthographic;
}
void OrthographicCamera::CalculateTransform(Viewport* viewport)
{
glm::vec2 viewportSize = viewport->GetSize() / 2.f;
ProjectionMatrix = glm::ortho(-viewportSize.x/Scale.x, viewportSize.x/Scale.x, -viewportSize.y/Scale.y, viewportSize.y/Scale.y, ZNear, ZFar);
ViewMatrix = glm::translate(glm::mat4x4(), -Position);
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
Camera::CalculateTransform(viewport);
}
glm::vec2 OrthographicCamera::ConvertScreenToWorld(glm::vec2 screen)
{
glm::vec2 position = screen;
position[0] = position[0] - GraphicsDevice::Instance()->GetDisplayResolution()[0]/2;
position[1] = GraphicsDevice::Instance()->GetDisplayResolution()[1]/2 - position[1];
position[0] /= GraphicsDevice::Instance()->GetDisplayDensity();
position[1] /= GraphicsDevice::Instance()->GetDisplayDensity();
position /= glm::vec2(Scale[0], Scale[1]);
position += glm::vec2(Position[0], Position[1]);
return position;
}
PerspectiveCamera::PerspectiveCamera(glm::vec3 position, glm::vec3 rotation)
: Camera(position, rotation)
, FieldOfView(90.f)
{
}
Camera::CameraType PerspectiveCamera::GetType()
{
return kCameraPerspective;
}
void PerspectiveCamera::CalculateTransform(Viewport* viewport)
{
glm::vec2 viewportSize = viewport->GetSize() / 2.f;
ProjectionMatrix = glm::perspectiveFov(FieldOfView, viewportSize.x, viewportSize.y, ZNear, ZFar);
ViewMatrix = glm::rotate(glm::mat4x4(), Rotation.x, glm::vec3(1,0,0));
ViewMatrix = glm::rotate(ViewMatrix, Rotation.y, glm::vec3(0,1,0));
ViewMatrix = glm::rotate(ViewMatrix, Rotation.z, glm::vec3(0,0,1));
ViewMatrix = glm::translate(ViewMatrix, -Position);
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
Camera::CalculateTransform(viewport);
}
<commit_msg>Add rotation support to orthographic camera<commit_after>#include "glm/gtc/matrix_transform.hpp"
#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/helper/screenHelpers.h"
using namespace pb;
Camera::Camera(glm::vec3 position, glm::vec3 rotation)
: Position(position)
, Rotation(rotation)
, ZNear(1)
, ZFar(1000)
{
}
Camera::~Camera()
{
}
void Camera::CalculateTransform(Viewport* viewport)
{
Frustum.Set(ViewProjectionMatrix);
}
OrthographicCamera::OrthographicCamera(glm::vec3 position, glm::vec3 rotation, glm::vec2 scale)
: Camera(position, rotation)
, Scale(scale)
{
}
Camera::CameraType OrthographicCamera::GetType()
{
return kCameraOrthographic;
}
void OrthographicCamera::CalculateTransform(Viewport* viewport)
{
glm::vec2 viewportSize = viewport->GetSize() / 2.f;
ProjectionMatrix = glm::ortho(-viewportSize.x/Scale.x, viewportSize.x/Scale.x, -viewportSize.y/Scale.y, viewportSize.y/Scale.y, ZNear, ZFar);
ViewMatrix = glm::rotate(glm::mat4x4(), Rotation.x, glm::vec3(1,0,0));
ViewMatrix = glm::rotate(ViewMatrix, Rotation.y, glm::vec3(0,1,0));
ViewMatrix = glm::rotate(ViewMatrix, Rotation.z, glm::vec3(0,0,1));
ViewMatrix = glm::translate(ViewMatrix, -Position);
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
Camera::CalculateTransform(viewport);
}
glm::vec2 OrthographicCamera::ConvertScreenToWorld(glm::vec2 screen)
{
glm::vec2 position = screen;
position[0] = position[0] - GraphicsDevice::Instance()->GetDisplayResolution()[0]/2;
position[1] = GraphicsDevice::Instance()->GetDisplayResolution()[1]/2 - position[1];
position[0] /= GraphicsDevice::Instance()->GetDisplayDensity();
position[1] /= GraphicsDevice::Instance()->GetDisplayDensity();
position /= glm::vec2(Scale[0], Scale[1]);
position += glm::vec2(Position[0], Position[1]);
return position;
}
PerspectiveCamera::PerspectiveCamera(glm::vec3 position, glm::vec3 rotation)
: Camera(position, rotation)
, FieldOfView(90.f)
{
}
Camera::CameraType PerspectiveCamera::GetType()
{
return kCameraPerspective;
}
void PerspectiveCamera::CalculateTransform(Viewport* viewport)
{
glm::vec2 viewportSize = viewport->GetSize() / 2.f;
ProjectionMatrix = glm::perspectiveFov(FieldOfView, viewportSize.x, viewportSize.y, ZNear, ZFar);
ViewMatrix = glm::rotate(glm::mat4x4(), Rotation.x, glm::vec3(1,0,0));
ViewMatrix = glm::rotate(ViewMatrix, Rotation.y, glm::vec3(0,1,0));
ViewMatrix = glm::rotate(ViewMatrix, Rotation.z, glm::vec3(0,0,1));
ViewMatrix = glm::translate(ViewMatrix, -Position);
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
Camera::CalculateTransform(viewport);
}
<|endoftext|>
|
<commit_before>#ifndef PIXELBOOST_DISABLE_GWEN
#include "glm/glm.hpp"
#include "gwen/Controls/Canvas.h"
#include "pixelboost/framework/game.h"
#include "pixelboost/input/keyboardManager.h"
#include "pixelboost/input/mouseManager.h"
#include "pixelboost/misc/gwen/inputHandler.h"
using namespace pb;
class pb::GwenKeyboardHandler : public KeyboardHandler
{
public:
GwenKeyboardHandler(Gwen::Controls::Canvas* canvas, Gwen::Controls::Base* root)
: _Canvas(canvas)
, _Root(root)
{
}
bool OnKeyDown(KeyboardKey key, char character)
{
if (key == kKeyboardKeyCharacter)
_Canvas->InputCharacter(character);
else
_Canvas->InputKey(key, true);
Gwen::Controls::Base* keyboardFocus = Gwen::KeyboardFocus;
if (!keyboardFocus || keyboardFocus == _Root)
return false;
return true;
}
bool OnKeyUp(KeyboardKey key, char character)
{
if (key != kKeyboardKeyCharacter)
_Canvas->InputKey(key, false);
Gwen::Controls::Base* keyboardFocus = Gwen::KeyboardFocus;
if (!keyboardFocus || keyboardFocus == _Root)
return false;
return true;
}
int GetPriority()
{
return 1000;
}
private:
Gwen::Controls::Base* _Root;
Gwen::Controls::Canvas* _Canvas;
};
class pb::GwenMouseHandler : public MouseHandler
{
public:
GwenMouseHandler(Gwen::Controls::Canvas* canvas, Gwen::Controls::Base* root)
: _Canvas(canvas)
, _Root(root)
{
}
int GetPriority()
{
return 1000;
}
bool OnMouseDown(MouseButton button, ModifierKeys modifierKeys, glm::vec2 position)
{
_Canvas->InputMouseButton((int)button, true);
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseMove(glm::vec2 position)
{
glm::vec2 delta = position - _PrevMouse;
_PrevMouse = position;
_Canvas->InputMouseMoved(position.x, position.y, delta[0], delta[1]);
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseUp(MouseButton button, ModifierKeys modifierKeys, glm::vec2 position)
{
_Canvas->InputMouseButton((int)button, false);
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseScroll(ModifierKeys modifierKeys, glm::vec2 scroll)
{
_Canvas->InputMouseWheel(scroll.y*120);
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseZoom(glm::vec2 zoom)
{
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseRotate(float rotate)
{
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
private:
glm::vec2 _PrevMouse;
Gwen::Controls::Base* _Root;
Gwen::Controls::Canvas* _Canvas;
};
GwenInputHandler::GwenInputHandler(Gwen::Controls::Canvas* canvas, Gwen::Controls::Base* root)
{
_KeyboardHandler = new GwenKeyboardHandler(canvas, root);
_MouseHandler = new GwenMouseHandler(canvas, root);
pb::Game::Instance()->GetKeyboardManager()->AddHandler(_KeyboardHandler);
pb::Game::Instance()->GetMouseManager()->AddHandler(_MouseHandler);
}
GwenInputHandler::~GwenInputHandler()
{
pb::Game::Instance()->GetKeyboardManager()->RemoveHandler(_KeyboardHandler);
pb::Game::Instance()->GetMouseManager()->RemoveHandler(_MouseHandler);
}
#endif
<commit_msg>Fix gwen input handlers<commit_after>#ifndef PIXELBOOST_DISABLE_GWEN
#include "glm/glm.hpp"
#include "gwen/Controls/Canvas.h"
#include "pixelboost/framework/game.h"
#include "pixelboost/input/keyboardManager.h"
#include "pixelboost/input/mouseManager.h"
#include "pixelboost/misc/gwen/inputHandler.h"
using namespace pb;
class pb::GwenKeyboardHandler : public KeyboardHandler
{
public:
GwenKeyboardHandler(Gwen::Controls::Canvas* canvas, Gwen::Controls::Base* root)
: _Canvas(canvas)
, _Root(root)
{
SetPriority(1000);
}
bool OnKeyDown(KeyboardKey key, char character)
{
if (key == kKeyboardKeyCharacter)
_Canvas->InputCharacter(character);
else
_Canvas->InputKey(key, true);
Gwen::Controls::Base* keyboardFocus = Gwen::KeyboardFocus;
if (!keyboardFocus || keyboardFocus == _Root)
return false;
return true;
}
bool OnKeyUp(KeyboardKey key, char character)
{
if (key != kKeyboardKeyCharacter)
_Canvas->InputKey(key, false);
Gwen::Controls::Base* keyboardFocus = Gwen::KeyboardFocus;
if (!keyboardFocus || keyboardFocus == _Root)
return false;
return true;
}
private:
Gwen::Controls::Base* _Root;
Gwen::Controls::Canvas* _Canvas;
};
class pb::GwenMouseHandler : public MouseHandler
{
public:
GwenMouseHandler(Gwen::Controls::Canvas* canvas, Gwen::Controls::Base* root)
: _Canvas(canvas)
, _Root(root)
{
SetPriority(1000);
}
bool OnMouseDown(MouseButton button, ModifierKeys modifierKeys, glm::vec2 position)
{
_Canvas->InputMouseButton((int)button, true);
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseMove(glm::vec2 position)
{
glm::vec2 delta = position - _PrevMouse;
_PrevMouse = position;
_Canvas->InputMouseMoved(position.x, position.y, delta[0], delta[1]);
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseUp(MouseButton button, ModifierKeys modifierKeys, glm::vec2 position)
{
_Canvas->InputMouseButton((int)button, false);
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseScroll(ModifierKeys modifierKeys, glm::vec2 scroll)
{
_Canvas->InputMouseWheel(scroll.y*120);
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseZoom(glm::vec2 zoom)
{
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
bool OnMouseRotate(float rotate)
{
Gwen::Controls::Base* hoveredControl = Gwen::HoveredControl;
if (!hoveredControl || hoveredControl == _Root)
return false;
return true;
}
private:
glm::vec2 _PrevMouse;
Gwen::Controls::Base* _Root;
Gwen::Controls::Canvas* _Canvas;
};
GwenInputHandler::GwenInputHandler(Gwen::Controls::Canvas* canvas, Gwen::Controls::Base* root)
{
_KeyboardHandler = new GwenKeyboardHandler(canvas, root);
_MouseHandler = new GwenMouseHandler(canvas, root);
pb::Game::Instance()->GetKeyboardManager()->AddHandler(_KeyboardHandler);
pb::Game::Instance()->GetMouseManager()->AddHandler(_MouseHandler);
}
GwenInputHandler::~GwenInputHandler()
{
pb::Game::Instance()->GetKeyboardManager()->RemoveHandler(_KeyboardHandler);
pb::Game::Instance()->GetMouseManager()->RemoveHandler(_MouseHandler);
}
#endif
<|endoftext|>
|
<commit_before>//===--- ClangdMain.cpp - clangd server loop ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ClangdLSPServer.h"
#include "JSONRPCDispatcher.h"
#include "Path.h"
#include "Trace.h"
#include "index/SymbolYAML.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
using namespace clang;
using namespace clang::clangd;
namespace {
enum class PCHStorageFlag { Disk, Memory };
// Build an in-memory static index for global symbols from a YAML-format file.
// The size of global symbols should be relatively small, so that all symbols
// can be managed in memory.
std::unique_ptr<SymbolIndex> BuildStaticIndex(llvm::StringRef YamlSymbolFile) {
auto Buffer = llvm::MemoryBuffer::getFile(YamlSymbolFile);
if (!Buffer) {
llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
return nullptr;
}
auto Slab = SymbolsFromYAML(Buffer.get()->getBuffer());
SymbolSlab::Builder SymsBuilder;
for (auto Sym : Slab)
SymsBuilder.insert(Sym);
return MemIndex::build(std::move(SymsBuilder).build());
}
} // namespace
static llvm::cl::opt<Path> CompileCommandsDir(
"compile-commands-dir",
llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
"is invalid, clangd will look in the current directory and "
"parent paths of each source file."));
static llvm::cl::opt<unsigned>
WorkerThreadsCount("j",
llvm::cl::desc("Number of async workers used by clangd"),
llvm::cl::init(getDefaultAsyncThreadsCount()));
// FIXME: Flags are the wrong mechanism for user preferences.
// We should probably read a dotfile or similar.
static llvm::cl::opt<bool> IncludeIneligibleResults(
"include-ineligible-results",
llvm::cl::desc(
"Include ineligible completion results (e.g. private members)"),
llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
llvm::cl::Hidden);
static llvm::cl::opt<JSONStreamStyle> InputStyle(
"input-style", llvm::cl::desc("Input JSON stream encoding"),
llvm::cl::values(
clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
clEnumValN(JSONStreamStyle::Delimited, "delimited",
"messages delimited by --- lines, with # comment support")),
llvm::cl::init(JSONStreamStyle::Standard));
static llvm::cl::opt<bool>
PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
llvm::cl::init(false));
static llvm::cl::opt<bool> Test(
"lit-test",
llvm::cl::desc(
"Abbreviation for -input-style=delimited -pretty -run-synchronously. "
"Intended to simplify lit tests."),
llvm::cl::init(false), llvm::cl::Hidden);
static llvm::cl::opt<PCHStorageFlag> PCHStorage(
"pch-storage",
llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
"improve performance"),
llvm::cl::values(
clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
llvm::cl::init(PCHStorageFlag::Disk));
static llvm::cl::opt<int> LimitCompletionResult(
"completion-limit",
llvm::cl::desc("Limit the number of completion results returned by clangd. "
"0 means no limit."),
llvm::cl::init(100));
static llvm::cl::opt<bool> RunSynchronously(
"run-synchronously",
llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
llvm::cl::init(false), llvm::cl::Hidden);
static llvm::cl::opt<Path>
ResourceDir("resource-dir",
llvm::cl::desc("Directory for system clang headers"),
llvm::cl::init(""), llvm::cl::Hidden);
static llvm::cl::opt<Path> InputMirrorFile(
"input-mirror-file",
llvm::cl::desc(
"Mirror all LSP input to the specified file. Useful for debugging."),
llvm::cl::init(""), llvm::cl::Hidden);
static llvm::cl::opt<bool> EnableIndexBasedCompletion(
"enable-index-based-completion",
llvm::cl::desc(
"Enable index-based global code completion. "
"Clang uses an index built from symbols in opened files"),
llvm::cl::init(true));
static llvm::cl::opt<Path> YamlSymbolFile(
"yaml-symbol-file",
llvm::cl::desc(
"YAML-format global symbol file to build the static index. Clangd will "
"use the static index for global code completion.\n"
"WARNING: This option is experimental only, and will be removed "
"eventually. Don't rely on it."),
llvm::cl::init(""), llvm::cl::Hidden);
int main(int argc, char *argv[]) {
llvm::cl::ParseCommandLineOptions(argc, argv, "clangd");
if (Test) {
RunSynchronously = true;
InputStyle = JSONStreamStyle::Delimited;
PrettyPrint = true;
}
if (!RunSynchronously && WorkerThreadsCount == 0) {
llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
"specify -run-synchronously?";
return 1;
}
// Ignore -j option if -run-synchonously is used.
// FIXME: a warning should be shown here.
if (RunSynchronously)
WorkerThreadsCount = 0;
// Validate command line arguments.
llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
if (!InputMirrorFile.empty()) {
std::error_code EC;
InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC, llvm::sys::fs::F_RW);
if (EC) {
InputMirrorStream.reset();
llvm::errs() << "Error while opening an input mirror file: "
<< EC.message();
}
}
// Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
// trace flag in your editor's config is annoying, launching with
// `CLANGD_TRACE=trace.json vim` is easier.
llvm::Optional<llvm::raw_fd_ostream> TraceStream;
std::unique_ptr<trace::EventTracer> Tracer;
if (auto *TraceFile = getenv("CLANGD_TRACE")) {
std::error_code EC;
TraceStream.emplace(TraceFile, /*ref*/ EC, llvm::sys::fs::F_RW);
if (EC) {
TraceStream.reset();
llvm::errs() << "Error while opening trace file " << TraceFile << ": "
<< EC.message();
} else {
Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
}
}
llvm::Optional<trace::Session> TracingSession;
if (Tracer)
TracingSession.emplace(*Tracer);
llvm::raw_ostream &Outs = llvm::outs();
llvm::raw_ostream &Logs = llvm::errs();
JSONOutput Out(Outs, Logs,
InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
PrettyPrint);
clangd::LoggingSession LoggingSession(Out);
// If --compile-commands-dir arg was invoked, check value and override default
// path.
llvm::Optional<Path> CompileCommandsDirPath;
if (CompileCommandsDir.empty()) {
CompileCommandsDirPath = llvm::None;
} else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
!llvm::sys::fs::exists(CompileCommandsDir)) {
llvm::errs() << "Path specified by --compile-commands-dir either does not "
"exist or is not an absolute "
"path. The argument will be ignored.\n";
CompileCommandsDirPath = llvm::None;
} else {
CompileCommandsDirPath = CompileCommandsDir;
}
bool StorePreamblesInMemory;
switch (PCHStorage) {
case PCHStorageFlag::Memory:
StorePreamblesInMemory = true;
break;
case PCHStorageFlag::Disk:
StorePreamblesInMemory = false;
break;
}
llvm::Optional<StringRef> ResourceDirRef = None;
if (!ResourceDir.empty())
ResourceDirRef = ResourceDir;
// Change stdin to binary to not lose \r\n on windows.
llvm::sys::ChangeStdinToBinary();
std::unique_ptr<SymbolIndex> StaticIdx;
if (EnableIndexBasedCompletion && !YamlSymbolFile.empty())
StaticIdx = BuildStaticIndex(YamlSymbolFile);
clangd::CodeCompleteOptions CCOpts;
CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
CCOpts.Limit = LimitCompletionResult;
// Initialize and run ClangdLSPServer.
ClangdLSPServer LSPServer(Out, WorkerThreadsCount, StorePreamblesInMemory,
CCOpts, ResourceDirRef, CompileCommandsDirPath,
EnableIndexBasedCompletion, StaticIdx.get());
constexpr int NoShutdownRequestErrorCode = 1;
llvm::set_thread_name("clangd.main");
return LSPServer.run(std::cin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
}
<commit_msg>[clangd] Dump stack on crash<commit_after>//===--- ClangdMain.cpp - clangd server loop ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ClangdLSPServer.h"
#include "JSONRPCDispatcher.h"
#include "Path.h"
#include "Trace.h"
#include "index/SymbolYAML.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
using namespace clang;
using namespace clang::clangd;
namespace {
enum class PCHStorageFlag { Disk, Memory };
// Build an in-memory static index for global symbols from a YAML-format file.
// The size of global symbols should be relatively small, so that all symbols
// can be managed in memory.
std::unique_ptr<SymbolIndex> BuildStaticIndex(llvm::StringRef YamlSymbolFile) {
auto Buffer = llvm::MemoryBuffer::getFile(YamlSymbolFile);
if (!Buffer) {
llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
return nullptr;
}
auto Slab = SymbolsFromYAML(Buffer.get()->getBuffer());
SymbolSlab::Builder SymsBuilder;
for (auto Sym : Slab)
SymsBuilder.insert(Sym);
return MemIndex::build(std::move(SymsBuilder).build());
}
} // namespace
static llvm::cl::opt<Path> CompileCommandsDir(
"compile-commands-dir",
llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
"is invalid, clangd will look in the current directory and "
"parent paths of each source file."));
static llvm::cl::opt<unsigned>
WorkerThreadsCount("j",
llvm::cl::desc("Number of async workers used by clangd"),
llvm::cl::init(getDefaultAsyncThreadsCount()));
// FIXME: Flags are the wrong mechanism for user preferences.
// We should probably read a dotfile or similar.
static llvm::cl::opt<bool> IncludeIneligibleResults(
"include-ineligible-results",
llvm::cl::desc(
"Include ineligible completion results (e.g. private members)"),
llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
llvm::cl::Hidden);
static llvm::cl::opt<JSONStreamStyle> InputStyle(
"input-style", llvm::cl::desc("Input JSON stream encoding"),
llvm::cl::values(
clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
clEnumValN(JSONStreamStyle::Delimited, "delimited",
"messages delimited by --- lines, with # comment support")),
llvm::cl::init(JSONStreamStyle::Standard));
static llvm::cl::opt<bool>
PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
llvm::cl::init(false));
static llvm::cl::opt<bool> Test(
"lit-test",
llvm::cl::desc(
"Abbreviation for -input-style=delimited -pretty -run-synchronously. "
"Intended to simplify lit tests."),
llvm::cl::init(false), llvm::cl::Hidden);
static llvm::cl::opt<PCHStorageFlag> PCHStorage(
"pch-storage",
llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
"improve performance"),
llvm::cl::values(
clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
llvm::cl::init(PCHStorageFlag::Disk));
static llvm::cl::opt<int> LimitCompletionResult(
"completion-limit",
llvm::cl::desc("Limit the number of completion results returned by clangd. "
"0 means no limit."),
llvm::cl::init(100));
static llvm::cl::opt<bool> RunSynchronously(
"run-synchronously",
llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
llvm::cl::init(false), llvm::cl::Hidden);
static llvm::cl::opt<Path>
ResourceDir("resource-dir",
llvm::cl::desc("Directory for system clang headers"),
llvm::cl::init(""), llvm::cl::Hidden);
static llvm::cl::opt<Path> InputMirrorFile(
"input-mirror-file",
llvm::cl::desc(
"Mirror all LSP input to the specified file. Useful for debugging."),
llvm::cl::init(""), llvm::cl::Hidden);
static llvm::cl::opt<bool> EnableIndexBasedCompletion(
"enable-index-based-completion",
llvm::cl::desc(
"Enable index-based global code completion. "
"Clang uses an index built from symbols in opened files"),
llvm::cl::init(true));
static llvm::cl::opt<Path> YamlSymbolFile(
"yaml-symbol-file",
llvm::cl::desc(
"YAML-format global symbol file to build the static index. Clangd will "
"use the static index for global code completion.\n"
"WARNING: This option is experimental only, and will be removed "
"eventually. Don't rely on it."),
llvm::cl::init(""), llvm::cl::Hidden);
int main(int argc, char *argv[]) {
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
llvm::cl::ParseCommandLineOptions(argc, argv, "clangd");
if (Test) {
RunSynchronously = true;
InputStyle = JSONStreamStyle::Delimited;
PrettyPrint = true;
}
if (!RunSynchronously && WorkerThreadsCount == 0) {
llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
"specify -run-synchronously?";
return 1;
}
// Ignore -j option if -run-synchonously is used.
// FIXME: a warning should be shown here.
if (RunSynchronously)
WorkerThreadsCount = 0;
// Validate command line arguments.
llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
if (!InputMirrorFile.empty()) {
std::error_code EC;
InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC, llvm::sys::fs::F_RW);
if (EC) {
InputMirrorStream.reset();
llvm::errs() << "Error while opening an input mirror file: "
<< EC.message();
}
}
// Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
// trace flag in your editor's config is annoying, launching with
// `CLANGD_TRACE=trace.json vim` is easier.
llvm::Optional<llvm::raw_fd_ostream> TraceStream;
std::unique_ptr<trace::EventTracer> Tracer;
if (auto *TraceFile = getenv("CLANGD_TRACE")) {
std::error_code EC;
TraceStream.emplace(TraceFile, /*ref*/ EC, llvm::sys::fs::F_RW);
if (EC) {
TraceStream.reset();
llvm::errs() << "Error while opening trace file " << TraceFile << ": "
<< EC.message();
} else {
Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
}
}
llvm::Optional<trace::Session> TracingSession;
if (Tracer)
TracingSession.emplace(*Tracer);
llvm::raw_ostream &Outs = llvm::outs();
llvm::raw_ostream &Logs = llvm::errs();
JSONOutput Out(Outs, Logs,
InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
PrettyPrint);
clangd::LoggingSession LoggingSession(Out);
// If --compile-commands-dir arg was invoked, check value and override default
// path.
llvm::Optional<Path> CompileCommandsDirPath;
if (CompileCommandsDir.empty()) {
CompileCommandsDirPath = llvm::None;
} else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
!llvm::sys::fs::exists(CompileCommandsDir)) {
llvm::errs() << "Path specified by --compile-commands-dir either does not "
"exist or is not an absolute "
"path. The argument will be ignored.\n";
CompileCommandsDirPath = llvm::None;
} else {
CompileCommandsDirPath = CompileCommandsDir;
}
bool StorePreamblesInMemory;
switch (PCHStorage) {
case PCHStorageFlag::Memory:
StorePreamblesInMemory = true;
break;
case PCHStorageFlag::Disk:
StorePreamblesInMemory = false;
break;
}
llvm::Optional<StringRef> ResourceDirRef = None;
if (!ResourceDir.empty())
ResourceDirRef = ResourceDir;
// Change stdin to binary to not lose \r\n on windows.
llvm::sys::ChangeStdinToBinary();
std::unique_ptr<SymbolIndex> StaticIdx;
if (EnableIndexBasedCompletion && !YamlSymbolFile.empty())
StaticIdx = BuildStaticIndex(YamlSymbolFile);
clangd::CodeCompleteOptions CCOpts;
CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
CCOpts.Limit = LimitCompletionResult;
// Initialize and run ClangdLSPServer.
ClangdLSPServer LSPServer(Out, WorkerThreadsCount, StorePreamblesInMemory,
CCOpts, ResourceDirRef, CompileCommandsDirPath,
EnableIndexBasedCompletion, StaticIdx.get());
constexpr int NoShutdownRequestErrorCode = 1;
llvm::set_thread_name("clangd.main");
return LSPServer.run(std::cin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
}
<|endoftext|>
|
<commit_before>/*
<samplecode>
<abstract>
Utility class to manage DSP parameters which can change value smoothly (be ramped) while rendering, without introducing clicks or other distortion into the signal.
</abstract>
</samplecode>
*/
#ifndef ParameterRamper_h
#define ParameterRamper_h
// N.B. This is C++.
#import <AudioToolbox/AudioToolbox.h>
#import <libkern/OSAtomic.h>
class ParameterRamper {
float clampLow, clampHigh;
float _uiValue;
float _goal;
float inverseSlope;
AUAudioFrameCount samplesRemaining;
volatile int32_t changeCounter = 0;
int32_t updateCounter = 0;
void setImmediate(float value) {
// only to be called from the render thread or when resources are not allocated.
_goal = _uiValue = value;
inverseSlope = 0.0;
samplesRemaining = 0;
}
public:
ParameterRamper(float value) {
setImmediate(value);
}
void init() {
/*
Call this from the kernel init.
Updates the internal value from the UI value.
*/
setImmediate(_uiValue);
}
void reset() {
changeCounter = updateCounter = 0;
}
void setUIValue(float value) {
_uiValue = value;
OSAtomicIncrement32Barrier(&changeCounter);
}
float getUIValue() const { return _uiValue; }
void dezipperCheck(AUAudioFrameCount rampDuration)
{
// check to see if the UI has changed and if so, start a ramp to dezipper it.
int32_t changeCounterSnapshot = changeCounter;
if (updateCounter != changeCounterSnapshot) {
updateCounter = changeCounterSnapshot;
startRamp(_uiValue, rampDuration);
}
}
void startRamp(float newGoal, AUAudioFrameCount duration) {
if (duration == 0) {
setImmediate(newGoal);
}
else {
/*
Set a new ramp.
Assigning to inverseSlope must come before assigning to goal.
*/
inverseSlope = (get() - newGoal) / float(duration);
samplesRemaining = duration;
_goal = _uiValue = newGoal;
}
}
float get() const {
/*
For long ramps, integrating a sum loses precision and does not reach
the goal at the right time. So instead, a line equation is used. y = m * x + b.
*/
return inverseSlope * float(samplesRemaining) + _goal;
}
void step() {
// Do this in each inner loop iteration after getting the value.
if (samplesRemaining != 0) {
--samplesRemaining;
}
}
float getAndStep() {
// Combines get and step. Saves a multiply-add when not ramping.
if (samplesRemaining != 0) {
float value = get();
--samplesRemaining;
return value;
}
else {
return _goal;
}
}
void stepBy(AUAudioFrameCount n) {
/*
When a parameter does not participate in the current inner loop, you
will want to advance it after the end of the loop.
*/
if (n >= samplesRemaining) {
samplesRemaining = 0;
}
else {
samplesRemaining -= n;
}
}
};
#endif /* ParameterRamper_h */
<commit_msg>Allowing setImmediate to be called externally<commit_after>/*
<samplecode>
<abstract>
Utility class to manage DSP parameters which can change value smoothly (be ramped) while rendering, without introducing clicks or other distortion into the signal.
</abstract>
</samplecode>
*/
#ifndef ParameterRamper_h
#define ParameterRamper_h
// N.B. This is C++.
#import <AudioToolbox/AudioToolbox.h>
#import <libkern/OSAtomic.h>
class ParameterRamper {
float clampLow, clampHigh;
float _uiValue;
float _goal;
float inverseSlope;
AUAudioFrameCount samplesRemaining;
volatile int32_t changeCounter = 0;
int32_t updateCounter = 0;
public:
void setImmediate(float value) {
// only to be called from the render thread or when resources are not allocated.
_goal = _uiValue = value;
inverseSlope = 0.0;
samplesRemaining = 0;
}
ParameterRamper(float value) {
setImmediate(value);
}
void init() {
/*
Call this from the kernel init.
Updates the internal value from the UI value.
*/
setImmediate(_uiValue);
}
void reset() {
changeCounter = updateCounter = 0;
}
void setUIValue(float value) {
_uiValue = value;
OSAtomicIncrement32Barrier(&changeCounter);
}
float getUIValue() const { return _uiValue; }
void dezipperCheck(AUAudioFrameCount rampDuration)
{
// check to see if the UI has changed and if so, start a ramp to dezipper it.
int32_t changeCounterSnapshot = changeCounter;
if (updateCounter != changeCounterSnapshot) {
updateCounter = changeCounterSnapshot;
startRamp(_uiValue, rampDuration);
}
}
void startRamp(float newGoal, AUAudioFrameCount duration) {
if (duration == 0) {
setImmediate(newGoal);
}
else {
/*
Set a new ramp.
Assigning to inverseSlope must come before assigning to goal.
*/
inverseSlope = (get() - newGoal) / float(duration);
samplesRemaining = duration;
_goal = _uiValue = newGoal;
}
}
float get() const {
/*
For long ramps, integrating a sum loses precision and does not reach
the goal at the right time. So instead, a line equation is used. y = m * x + b.
*/
return inverseSlope * float(samplesRemaining) + _goal;
}
void step() {
// Do this in each inner loop iteration after getting the value.
if (samplesRemaining != 0) {
--samplesRemaining;
}
}
float getAndStep() {
// Combines get and step. Saves a multiply-add when not ramping.
if (samplesRemaining != 0) {
float value = get();
--samplesRemaining;
return value;
}
else {
return _goal;
}
}
void stepBy(AUAudioFrameCount n) {
/*
When a parameter does not participate in the current inner loop, you
will want to advance it after the end of the loop.
*/
if (n >= samplesRemaining) {
samplesRemaining = 0;
}
else {
samplesRemaining -= n;
}
}
};
#endif /* ParameterRamper_h */
<|endoftext|>
|
<commit_before>/*
This file is part of the Rendering library.
Copyright (C) 2007-2013 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2007-2013 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2007-2013 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "StatusHandler_sgUniforms.h"
#include "RenderingStatus.h"
#include "../../Shader/Shader.h"
#include "../../Shader/UniformRegistry.h"
namespace Rendering {
namespace StatusHandler_sgUniforms{
typedef std::vector<Uniform::UniformName> UniformNameArray_t;
//! (internal)
static UniformNameArray_t createNames(const std::string & prefix, uint8_t number, const std::string &postfix) {
UniformNameArray_t arr;
for (uint8_t i = 0; i < number; ++i)
arr.push_back(prefix + static_cast<char> ('0' + i) + postfix);
return arr;
}
static const Uniform::UniformName UNIFORM_SG_MODEL_VIEW_MATRIX("sg_modelViewMatrix");
static const Uniform::UniformName UNIFORM_SG_PROJECTION_MATRIX("sg_projectionMatrix");
static const Uniform::UniformName UNIFORM_SG_MODEL_VIEW_PROJECTION_MATRIX("sg_modelViewProjectionMatrix");
static const Uniform::UniformName UNIFORM_SG_CAMERA_MATRIX("sg_cameraMatrix");
static const Uniform::UniformName UNIFORM_SG_CAMERA_INVERSE_MATRIX("sg_cameraInverseMatrix");
static const Uniform::UniformName UNIFORM_SG_LIGHT_COUNT("sg_lightCount");
static const Uniform::UniformName UNIFORM_SG_POINT_SIZE("sg_pointSize");
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_POSITION(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].position"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_DIRECTION(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].direction"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_TYPE(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].type"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_CONSTANT(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].constant"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_LINEAR(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].linear"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_QUADRATIC(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].quadratic"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_AMBIENT(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].ambient"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_DIFFUSE(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].diffuse"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_SPECULAR(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].specular"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_EXPONENT(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].exponent"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_COSCUTOFF(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].cosCutoff"));
static const Uniform::UniformName UNIFORM_SG_TEXTURE_ENABLED("sg_textureEnabled");
static const UniformNameArray_t UNIFORM_SG_TEXTURES(createNames("sg_texture", MAX_TEXTURES, ""));
static const Uniform::UniformName UNIFORM_SG_USE_MATERIALS("sg_useMaterials");
static const Uniform::UniformName UNIFORM_SG_MATERIAL_AMBIENT("sg_Material.ambient");
static const Uniform::UniformName UNIFORM_SG_MATERIAL_DIFFUSE("sg_Material.diffuse");
static const Uniform::UniformName UNIFORM_SG_MATERIAL_SPECULAR("sg_Material.specular");
static const Uniform::UniformName UNIFORM_SG_MATERIAL_SHININESS("sg_Material.shininess");
void apply(RenderingStatus & target, const RenderingStatus & actual, bool forced){
Shader * shader = target.getShader();
std::deque<Uniform> uniforms;
// camera & inverse
bool cc = false;
if (forced || target.cameraInverseMatrixChanged(actual)) {
cc = true;
target.updateCameraMatrix(actual);
uniforms.emplace_back(UNIFORM_SG_CAMERA_MATRIX, actual.getCameraMatrix());
uniforms.emplace_back(UNIFORM_SG_CAMERA_INVERSE_MATRIX, actual.getCameraInverseMatrix());
}
// lights
if (forced || cc || target.lightsChanged(actual)) {
target.updateLights(actual);
uniforms.emplace_back(UNIFORM_SG_LIGHT_COUNT, static_cast<int> (actual.getNumEnabledLights()));
const uint_fast8_t numEnabledLights = actual.getNumEnabledLights();
for (uint_fast8_t i = 0; i < numEnabledLights; ++i) {
const LightParameters & params = actual.getEnabledLight(i);
target.updateLightParameter(i, params);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_POSITION[i], (actual.getCameraMatrix() * params.position).xyz());
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_DIRECTION[i], (actual.getCameraMatrix() * params.direction).xyz());
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_TYPE[i], static_cast<int> (params.type));
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_CONSTANT[i], params.constant);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_LINEAR[i], params.linear);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_QUADRATIC[i], params.quadratic);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_AMBIENT[i], params.ambient);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_DIFFUSE[i], params.diffuse);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_SPECULAR[i], params.specular);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_EXPONENT[i], params.exponent);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_COSCUTOFF[i], params.cosCutoff);
}
if (forced) {
LightParameters params;
for (uint_fast8_t i = numEnabledLights; i < RenderingStatus::MAX_LIGHTS; ++i) {
target.updateLightParameter(i, params);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_POSITION[i], (actual.getCameraMatrix() * params.position).xyz());
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_DIRECTION[i], (actual.getCameraMatrix() * params.direction).xyz());
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_TYPE[i], static_cast<int> (params.type));
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_CONSTANT[i], params.constant);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_LINEAR[i], params.linear);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_QUADRATIC[i], params.quadratic);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_AMBIENT[i], params.ambient);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_DIFFUSE[i], params.diffuse);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_SPECULAR[i], params.specular);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_EXPONENT[i], params.exponent);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_COSCUTOFF[i], params.cosCutoff);
}
}
}
// materials
if (forced || target.materialChanged(actual)) {
target.updateMaterial(actual);
uniforms.emplace_back(UNIFORM_SG_USE_MATERIALS, actual.isMaterialEnabled());
if (forced || actual.isMaterialEnabled()) {
const MaterialParameters & material = actual.getMaterialParameters();
uniforms.emplace_back(UNIFORM_SG_MATERIAL_AMBIENT, material.getAmbient());
uniforms.emplace_back(UNIFORM_SG_MATERIAL_DIFFUSE, material.getDiffuse());
uniforms.emplace_back(UNIFORM_SG_MATERIAL_SPECULAR, material.getSpecular());
uniforms.emplace_back(UNIFORM_SG_MATERIAL_SHININESS, material.getShininess());
}
}
// modelview & projection
{
bool pc = false;
bool mc = false;
if (forced || target.modelViewMatrixChanged(actual)) {
mc = true;
target.updateModelViewMatrix(actual);
uniforms.emplace_back(UNIFORM_SG_MODEL_VIEW_MATRIX, actual.getModelViewMatrix());
}
if (forced || target.projectionMatrixChanged(actual)) {
pc = true;
target.updateProjectionMatrix(actual);
uniforms.emplace_back(UNIFORM_SG_PROJECTION_MATRIX, actual.getProjectionMatrix());
}
if (forced || pc || mc) {
uniforms.emplace_back(UNIFORM_SG_MODEL_VIEW_PROJECTION_MATRIX, actual.getProjectionMatrix() * actual.getModelViewMatrix());
}
}
// Point
if(forced || target.pointParametersChanged(actual)) {
target.setPointParameters(actual.getPointParameters());
uniforms.emplace_back(UNIFORM_SG_POINT_SIZE, actual.getPointParameters().getSize());
}
// TEXTURE UNITS
if (forced || target.textureUnitsChanged(actual)) {
std::deque<bool> textureUnitsUsedForRendering;
for(const auto & usage : actual.getTextureUnitUsages()) {
textureUnitsUsedForRendering.emplace_back(usage != TexUnitUsageParameter::GENERAL_PURPOSE);
}
uniforms.emplace_back(UNIFORM_SG_TEXTURE_ENABLED, textureUnitsUsedForRendering);
for (uint_fast8_t i = 0; i < MAX_TEXTURES; ++i) // for each shader, this is only necessary once...
uniforms.emplace_back(UNIFORM_SG_TEXTURES[i], i);
target.updateTextureUnits(actual);
}
for(const auto & uniform : uniforms) {
shader->_getUniformRegistry()->setUniform(uniform, false, forced);
}
}
}
}
<commit_msg>Replace two loops by only one<commit_after>/*
This file is part of the Rendering library.
Copyright (C) 2007-2013 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2007-2013 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2007-2013 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "StatusHandler_sgUniforms.h"
#include "RenderingStatus.h"
#include "../../Shader/Shader.h"
#include "../../Shader/UniformRegistry.h"
namespace Rendering {
namespace StatusHandler_sgUniforms{
typedef std::vector<Uniform::UniformName> UniformNameArray_t;
//! (internal)
static UniformNameArray_t createNames(const std::string & prefix, uint8_t number, const std::string &postfix) {
UniformNameArray_t arr;
for (uint8_t i = 0; i < number; ++i)
arr.push_back(prefix + static_cast<char> ('0' + i) + postfix);
return arr;
}
static const Uniform::UniformName UNIFORM_SG_MODEL_VIEW_MATRIX("sg_modelViewMatrix");
static const Uniform::UniformName UNIFORM_SG_PROJECTION_MATRIX("sg_projectionMatrix");
static const Uniform::UniformName UNIFORM_SG_MODEL_VIEW_PROJECTION_MATRIX("sg_modelViewProjectionMatrix");
static const Uniform::UniformName UNIFORM_SG_CAMERA_MATRIX("sg_cameraMatrix");
static const Uniform::UniformName UNIFORM_SG_CAMERA_INVERSE_MATRIX("sg_cameraInverseMatrix");
static const Uniform::UniformName UNIFORM_SG_LIGHT_COUNT("sg_lightCount");
static const Uniform::UniformName UNIFORM_SG_POINT_SIZE("sg_pointSize");
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_POSITION(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].position"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_DIRECTION(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].direction"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_TYPE(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].type"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_CONSTANT(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].constant"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_LINEAR(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].linear"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_QUADRATIC(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].quadratic"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_AMBIENT(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].ambient"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_DIFFUSE(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].diffuse"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_SPECULAR(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].specular"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_EXPONENT(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].exponent"));
static const UniformNameArray_t UNIFORM_SG_LIGHT_SOURCES_COSCUTOFF(createNames("sg_LightSource[", RenderingStatus::MAX_LIGHTS, "].cosCutoff"));
static const Uniform::UniformName UNIFORM_SG_TEXTURE_ENABLED("sg_textureEnabled");
static const UniformNameArray_t UNIFORM_SG_TEXTURES(createNames("sg_texture", MAX_TEXTURES, ""));
static const Uniform::UniformName UNIFORM_SG_USE_MATERIALS("sg_useMaterials");
static const Uniform::UniformName UNIFORM_SG_MATERIAL_AMBIENT("sg_Material.ambient");
static const Uniform::UniformName UNIFORM_SG_MATERIAL_DIFFUSE("sg_Material.diffuse");
static const Uniform::UniformName UNIFORM_SG_MATERIAL_SPECULAR("sg_Material.specular");
static const Uniform::UniformName UNIFORM_SG_MATERIAL_SHININESS("sg_Material.shininess");
void apply(RenderingStatus & target, const RenderingStatus & actual, bool forced){
Shader * shader = target.getShader();
std::deque<Uniform> uniforms;
// camera & inverse
bool cc = false;
if (forced || target.cameraInverseMatrixChanged(actual)) {
cc = true;
target.updateCameraMatrix(actual);
uniforms.emplace_back(UNIFORM_SG_CAMERA_MATRIX, actual.getCameraMatrix());
uniforms.emplace_back(UNIFORM_SG_CAMERA_INVERSE_MATRIX, actual.getCameraInverseMatrix());
}
// lights
if (forced || cc || target.lightsChanged(actual)) {
target.updateLights(actual);
uniforms.emplace_back(UNIFORM_SG_LIGHT_COUNT, static_cast<int> (actual.getNumEnabledLights()));
const uint_fast8_t numEnabledLights = actual.getNumEnabledLights();
for (uint_fast8_t i = 0; i < numEnabledLights; ++i) {
const LightParameters & params = actual.getEnabledLight(i);
target.updateLightParameter(i, params);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_POSITION[i], (actual.getCameraMatrix() * params.position).xyz());
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_DIRECTION[i], (actual.getCameraMatrix() * params.direction).xyz());
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_TYPE[i], static_cast<int> (params.type));
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_CONSTANT[i], params.constant);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_LINEAR[i], params.linear);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_QUADRATIC[i], params.quadratic);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_AMBIENT[i], params.ambient);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_DIFFUSE[i], params.diffuse);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_SPECULAR[i], params.specular);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_EXPONENT[i], params.exponent);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_COSCUTOFF[i], params.cosCutoff);
}
if (forced) {
LightParameters params;
for (uint_fast8_t i = numEnabledLights; i < RenderingStatus::MAX_LIGHTS; ++i) {
target.updateLightParameter(i, params);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_POSITION[i], (actual.getCameraMatrix() * params.position).xyz());
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_DIRECTION[i], (actual.getCameraMatrix() * params.direction).xyz());
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_TYPE[i], static_cast<int> (params.type));
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_CONSTANT[i], params.constant);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_LINEAR[i], params.linear);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_QUADRATIC[i], params.quadratic);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_AMBIENT[i], params.ambient);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_DIFFUSE[i], params.diffuse);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_SPECULAR[i], params.specular);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_EXPONENT[i], params.exponent);
uniforms.emplace_back(UNIFORM_SG_LIGHT_SOURCES_COSCUTOFF[i], params.cosCutoff);
}
}
}
// materials
if (forced || target.materialChanged(actual)) {
target.updateMaterial(actual);
uniforms.emplace_back(UNIFORM_SG_USE_MATERIALS, actual.isMaterialEnabled());
if (forced || actual.isMaterialEnabled()) {
const MaterialParameters & material = actual.getMaterialParameters();
uniforms.emplace_back(UNIFORM_SG_MATERIAL_AMBIENT, material.getAmbient());
uniforms.emplace_back(UNIFORM_SG_MATERIAL_DIFFUSE, material.getDiffuse());
uniforms.emplace_back(UNIFORM_SG_MATERIAL_SPECULAR, material.getSpecular());
uniforms.emplace_back(UNIFORM_SG_MATERIAL_SHININESS, material.getShininess());
}
}
// modelview & projection
{
bool pc = false;
bool mc = false;
if (forced || target.modelViewMatrixChanged(actual)) {
mc = true;
target.updateModelViewMatrix(actual);
uniforms.emplace_back(UNIFORM_SG_MODEL_VIEW_MATRIX, actual.getModelViewMatrix());
}
if (forced || target.projectionMatrixChanged(actual)) {
pc = true;
target.updateProjectionMatrix(actual);
uniforms.emplace_back(UNIFORM_SG_PROJECTION_MATRIX, actual.getProjectionMatrix());
}
if (forced || pc || mc) {
uniforms.emplace_back(UNIFORM_SG_MODEL_VIEW_PROJECTION_MATRIX, actual.getProjectionMatrix() * actual.getModelViewMatrix());
}
}
// Point
if(forced || target.pointParametersChanged(actual)) {
target.setPointParameters(actual.getPointParameters());
uniforms.emplace_back(UNIFORM_SG_POINT_SIZE, actual.getPointParameters().getSize());
}
// TEXTURE UNITS
if (forced || target.textureUnitsChanged(actual)) {
std::deque<bool> textureUnitsUsedForRendering;
for(uint_fast8_t unit = 0; unit < MAX_TEXTURES; ++unit) {
const auto & usage = actual.getTextureUnitUsage(unit);
textureUnitsUsedForRendering.emplace_back(usage != TexUnitUsageParameter::GENERAL_PURPOSE);
// for each shader, this is only necessary once...
uniforms.emplace_back(UNIFORM_SG_TEXTURES[unit], unit);
}
uniforms.emplace_back(UNIFORM_SG_TEXTURE_ENABLED, textureUnitsUsedForRendering);
target.updateTextureUnits(actual);
}
for(const auto & uniform : uniforms) {
shader->_getUniformRegistry()->setUniform(uniform, false, forced);
}
}
}
}
<|endoftext|>
|
<commit_before>#include "testing/testing.hpp"
#include "indexer/classificator.hpp"
#include "indexer/classificator_loader.hpp"
#include "indexer/feature_visibility.hpp"
#include "indexer/feature_data.hpp"
#include "base/logging.hpp"
namespace
{
class DoCheckConsistency
{
Classificator const & m_c;
public:
DoCheckConsistency(Classificator const & c) : m_c(c) {}
void operator() (ClassifObject const * p, uint32_t type) const
{
if (p->IsDrawableAny() && !m_c.IsTypeValid(type))
TEST(false, ("Inconsistency type", type, m_c.GetFullObjectName(type)));
}
};
}
UNIT_TEST(Classificator_CheckConsistency)
{
classificator::Load();
Classificator const & c = classif();
DoCheckConsistency doCheck(c);
c.ForEachTree(doCheck);
}
using namespace feature;
namespace
{
class DoCheckStyles
{
Classificator const & m_c;
EGeomType m_geomType;
int m_rules;
public:
DoCheckStyles(Classificator const & c, EGeomType geomType, int rules)
: m_c(c), m_geomType(geomType), m_rules(rules)
{
}
void operator() (ClassifObject const * p, uint32_t type) const
{
if (p->IsDrawableAny())
{
TypesHolder holder(m_geomType);
holder(type);
pair<int, int> const range = GetDrawableScaleRangeForRules(holder, m_rules);
if (range.first == -1 || range.second == -1)
LOG(LINFO, ("No styles:", type, m_c.GetFullObjectName(type)));
}
else if (ftype::GetLevel(type) > 1)
LOG(LINFO, ("Type without any rules:", type, m_c.GetFullObjectName(type)));
}
};
void ForEachObject(Classificator const & c, vector<string> const & path,
EGeomType geomType, int rules)
{
uint32_t const type = c.GetTypeByPath(path);
ClassifObject const * pObj = c.GetObject(type);
DoCheckStyles doCheck(c, geomType, rules);
doCheck(pObj, type);
pObj->ForEachObjectInTree(doCheck, type);
}
void ForEachObject(Classificator const & c, string const & name,
EGeomType geomType, int rules)
{
vector<string> path;
strings::Tokenize(name, "-", MakeBackInsertFunctor(path));
ForEachObject(c, path, geomType, rules);
}
void CheckPointStyles(Classificator const & c, string const & name)
{
ForEachObject(c, name, GEOM_POINT, RULE_CAPTION | RULE_SYMBOL);
}
void CheckLineStyles(Classificator const & c, string const & name)
{
ForEachObject(c, name, GEOM_LINE, RULE_PATH_TEXT);
}
}
UNIT_TEST(Classificator_DrawingRules)
{
classificator::Load();
Classificator const & c = classif();
LOG(LINFO, ("--------------- Point styles ---------------"));
CheckPointStyles(c, "landuse");
CheckPointStyles(c, "amenity");
CheckPointStyles(c, "historic");
CheckPointStyles(c, "office");
CheckPointStyles(c, "place");
CheckPointStyles(c, "shop");
CheckPointStyles(c, "sport");
CheckPointStyles(c, "tourism");
CheckPointStyles(c, "highway-bus_stop");
CheckPointStyles(c, "highway-motorway_junction");
CheckPointStyles(c, "railway-station");
CheckPointStyles(c, "railway-tram_stop");
CheckPointStyles(c, "railway-halt");
LOG(LINFO, ("--------------- Linear styles ---------------"));
CheckLineStyles(c, "highway");
CheckLineStyles(c, "waterway");
//CheckLineStyles(c, "railway");
}
namespace
{
pair<int, int> GetMinMax(int level, vector<uint32_t> const & types)
{
pair<int, int> res(numeric_limits<int>::max(), numeric_limits<int>::min());
drule::KeysT keys;
feature::GetDrawRule(types, level, feature::GEOM_AREA, keys);
for (size_t i = 0; i < keys.size(); ++i)
{
if (keys[i].m_type != drule::area)
continue;
if (keys[i].m_priority < res.first)
res.first = keys[i].m_priority;
if (keys[i].m_priority > res.second)
res.second = keys[i].m_priority;
}
return res;
}
}
// Check area drawing priority according to the types order below (from downmost to upmost).
// If someone is desagree with this order, please, refer to VNG :)
// natural-coastline
// place-island = natural-land
// natural-wood,scrub,heath,grassland = landuse-grass,farm,farmland,forest
// natural-water,lake = landuse-basin
UNIT_TEST(Classificator_AreaPriority)
{
classificator::Load();
Classificator const & c = classif();
vector<vector<uint32_t> > types;
char const * arrT[][2] =
{
// 0
{"natural", "coastline"},
// 1
//{"waterway", "riverbank"}, - it's not a good idea to place it here
// 2
{"place", "island"}, {"natural", "land"},
// 3
{"natural", "wood"}, {"natural", "scrub"}, {"natural", "heath"}, {"natural", "grassland"},
{"landuse", "grass"}, {"landuse", "farm"}, {"landuse", "farmland"}, {"landuse", "forest"},
// 4
//{"leisure", "park"}, {"leisure", "garden"}, - maybe next time (too tricky to do it now)
// 5
{"natural", "water"}, {"natural", "lake"}, {"landuse", "basin"}
};
size_t arrI[] = { 1, 2, 8, 3 };
size_t ind = 0;
for (size_t i = 0; i < ARRAY_SIZE(arrI); ++i)
{
types.push_back(vector<uint32_t>());
types.back().reserve(arrI[i]);
for (size_t j = 0; j < arrI[i]; ++j)
{
types.back().push_back(c.GetTypeByPath(vector<string>(arrT[ind], arrT[ind] + 2)));
++ind;
}
}
TEST_EQUAL(ind, ARRAY_SIZE(arrT), ());
for (int level = scales::GetUpperWorldScale() + 1; level <= scales::GetUpperStyleScale(); ++level)
{
pair<int, int> minmax = GetMinMax(level, types[0]);
for (size_t i = 1; i < types.size(); ++i)
{
pair<int, int> const mm = GetMinMax(level, types[i]);
TEST_LESS(minmax.second, mm.first, (i));
minmax = mm;
}
}
}
<commit_msg>Run classificator tests for every style<commit_after>#include "testing/testing.hpp"
#include "indexer/classificator.hpp"
#include "indexer/classificator_loader.hpp"
#include "indexer/feature_visibility.hpp"
#include "indexer/feature_data.hpp"
#include "indexer/map_style_reader.hpp"
#include "base/logging.hpp"
namespace
{
class DoCheckConsistency
{
Classificator const & m_c;
public:
DoCheckConsistency(Classificator const & c) : m_c(c) {}
void operator() (ClassifObject const * p, uint32_t type) const
{
if (p->IsDrawableAny() && !m_c.IsTypeValid(type))
TEST(false, ("Inconsistency type", type, m_c.GetFullObjectName(type)));
}
};
// Some tests require MapStyleLight (legacy) set as default.
// But unfortunately current map style is stored as global variable.
// Therefore, to reset current map style to the MapStyleLight, this RAII is used.
class ResetMapStyleRAII
{
public:
ResetMapStyleRAII() = default;
~ResetMapStyleRAII()
{
GetStyleReader().SetCurrentStyle(MapStyleLight);
}
};
void RunForEveryMapStyle(std::function<void()> const & fn)
{
ResetMapStyleRAII resetMapStype;
for (size_t s = 0; s < MapStyleCount; ++s)
{
MapStyle const mapStyle = static_cast<MapStyle>(s);
GetStyleReader().SetCurrentStyle(mapStyle);
LOG(LINFO, ("Test with map style", mapStyle));
fn();
}
}
} // namespace
UNIT_TEST(Classificator_CheckConsistency)
{
RunForEveryMapStyle([]()
{
classificator::Load();
Classificator const & c = classif();
DoCheckConsistency doCheck(c);
c.ForEachTree(doCheck);
});
}
using namespace feature;
namespace
{
class DoCheckStyles
{
Classificator const & m_c;
EGeomType m_geomType;
int m_rules;
public:
DoCheckStyles(Classificator const & c, EGeomType geomType, int rules)
: m_c(c), m_geomType(geomType), m_rules(rules)
{
}
void operator() (ClassifObject const * p, uint32_t type) const
{
if (p->IsDrawableAny())
{
TypesHolder holder(m_geomType);
holder(type);
pair<int, int> const range = GetDrawableScaleRangeForRules(holder, m_rules);
if (range.first == -1 || range.second == -1)
LOG(LINFO, ("No styles:", type, m_c.GetFullObjectName(type)));
}
else if (ftype::GetLevel(type) > 1)
LOG(LINFO, ("Type without any rules:", type, m_c.GetFullObjectName(type)));
}
};
void ForEachObject(Classificator const & c, vector<string> const & path,
EGeomType geomType, int rules)
{
uint32_t const type = c.GetTypeByPath(path);
ClassifObject const * pObj = c.GetObject(type);
DoCheckStyles doCheck(c, geomType, rules);
doCheck(pObj, type);
pObj->ForEachObjectInTree(doCheck, type);
}
void ForEachObject(Classificator const & c, string const & name,
EGeomType geomType, int rules)
{
vector<string> path;
strings::Tokenize(name, "-", MakeBackInsertFunctor(path));
ForEachObject(c, path, geomType, rules);
}
void CheckPointStyles(Classificator const & c, string const & name)
{
ForEachObject(c, name, GEOM_POINT, RULE_CAPTION | RULE_SYMBOL);
}
void CheckLineStyles(Classificator const & c, string const & name)
{
ForEachObject(c, name, GEOM_LINE, RULE_PATH_TEXT);
}
} // namespace
UNIT_TEST(Classificator_DrawingRules)
{
RunForEveryMapStyle([]()
{
classificator::Load();
Classificator const & c = classif();
LOG(LINFO, ("--------------- Point styles ---------------"));
CheckPointStyles(c, "landuse");
CheckPointStyles(c, "amenity");
CheckPointStyles(c, "historic");
CheckPointStyles(c, "office");
CheckPointStyles(c, "place");
CheckPointStyles(c, "shop");
CheckPointStyles(c, "sport");
CheckPointStyles(c, "tourism");
CheckPointStyles(c, "highway-bus_stop");
CheckPointStyles(c, "highway-motorway_junction");
CheckPointStyles(c, "railway-station");
CheckPointStyles(c, "railway-tram_stop");
CheckPointStyles(c, "railway-halt");
LOG(LINFO, ("--------------- Linear styles ---------------"));
CheckLineStyles(c, "highway");
CheckLineStyles(c, "waterway");
//CheckLineStyles(c, "railway");
});
}
namespace
{
pair<int, int> GetMinMax(int level, vector<uint32_t> const & types)
{
pair<int, int> res(numeric_limits<int>::max(), numeric_limits<int>::min());
drule::KeysT keys;
feature::GetDrawRule(types, level, feature::GEOM_AREA, keys);
for (size_t i = 0; i < keys.size(); ++i)
{
if (keys[i].m_type != drule::area)
continue;
if (keys[i].m_priority < res.first)
res.first = keys[i].m_priority;
if (keys[i].m_priority > res.second)
res.second = keys[i].m_priority;
}
return res;
}
} // namespace
// Check area drawing priority according to the types order below (from downmost to upmost).
// If someone is desagree with this order, please, refer to VNG :)
// natural-coastline
// place-island = natural-land
// natural-wood,scrub,heath,grassland = landuse-grass,farm,farmland,forest
// natural-water,lake = landuse-basin
UNIT_TEST(Classificator_AreaPriority)
{
RunForEveryMapStyle([]()
{
classificator::Load();
Classificator const & c = classif();
vector<vector<uint32_t> > types;
char const * arrT[][2] =
{
// 0
{"natural", "coastline"},
// 1
//{"waterway", "riverbank"}, - it's not a good idea to place it here
// 2
{"place", "island"}, {"natural", "land"},
// 3
{"natural", "wood"}, {"natural", "scrub"}, {"natural", "heath"}, {"natural", "grassland"},
{"landuse", "grass"}, {"landuse", "farm"}, {"landuse", "farmland"}, {"landuse", "forest"},
// 4
//{"leisure", "park"}, {"leisure", "garden"}, - maybe next time (too tricky to do it now)
// 5
{"natural", "water"}, {"natural", "lake"}, {"landuse", "basin"}
};
size_t arrI[] = { 1, 2, 8, 3 };
size_t ind = 0;
for (size_t i = 0; i < ARRAY_SIZE(arrI); ++i)
{
types.push_back(vector<uint32_t>());
types.back().reserve(arrI[i]);
for (size_t j = 0; j < arrI[i]; ++j)
{
types.back().push_back(c.GetTypeByPath(vector<string>(arrT[ind], arrT[ind] + 2)));
++ind;
}
}
TEST_EQUAL(ind, ARRAY_SIZE(arrT), ());
for (int level = scales::GetUpperWorldScale() + 1; level <= scales::GetUpperStyleScale(); ++level)
{
pair<int, int> minmax = GetMinMax(level, types[0]);
for (size_t i = 1; i < types.size(); ++i)
{
pair<int, int> const mm = GetMinMax(level, types[i]);
TEST_LESS(minmax.second, mm.first, (i));
minmax = mm;
}
}
});
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
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 <organization> 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 <COPYRIGHT HOLDER> 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 <fcntl.h>
#include <sys/sysinfo.h>
#include <cstdlib>
#include <config.h>
#include <errno.h>
#include <signal.h>
#include "os/os.h"
#define READEVENT 0
#define SENDEVENT 1
//#define DEBUG_MUTEX
#include "../event.h"
libhttppp::Event::Event(ServerSocket *serversocket) {
_ServerSocket=serversocket;
_ServerSocket->setnonblocking();
_ServerSocket->listenSocket();
_EventEndloop =true;
_Cpool= new ConnectionPool(_ServerSocket);
_Events = new epoll_event[(_ServerSocket->getMaxconnections())];
_Mutex = new Mutex;
_firstConnectionContext=NULL;
_lastConnectionContext=NULL;
}
libhttppp::Event::~Event() {
#ifdef DEBUG_MUTEX
_httpexception.Note("~Event","Lock MainMutex");
#endif
_Mutex->lock();
delete _Cpool;
delete[] _Events;
delete _firstConnectionContext;
delete _Mutex;
_lastConnectionContext=NULL;
}
libhttppp::Event* _EventIns=NULL;
void libhttppp::Event::CtrlHandler(int signum) {
_EventIns->_EventEndloop=false;
}
void libhttppp::Event::runEventloop() {
_setEvent = (struct epoll_event){0};
for(int i=0; i<_ServerSocket->getMaxconnections(); i++)
_Events[i].data.fd = -1;
_epollFD = epoll_create1(0);
if (_epollFD == -1) {
_httpexception.Critical("can't create epoll");
throw _httpexception;
}
_setEvent.events = EPOLLIN;
_setEvent.data.fd = _ServerSocket->getSocket();
if (epoll_ctl(_epollFD, EPOLL_CTL_ADD, _ServerSocket->getSocket(), &_setEvent) < 0) {
_httpexception.Critical("can't create epoll");
throw _httpexception;
}
int srvssocket=_ServerSocket->getSocket();
int maxconnets=_ServerSocket->getMaxconnections();
signal(SIGPIPE, SIG_IGN);
while(_EventEndloop) {
int n = epoll_wait(_epollFD,_Events,maxconnets, EPOLLWAIT);
if(n<0){
if(errno== EINTR){
continue;
}else{
_httpexception.Critical("epoll wait failure");
throw _httpexception;
}
}
for(int i=0; i<n; i++) {
ConnectionContext *curct=NULL;
if(_Events[i].data.fd == srvssocket) {
try {
/*will create warning debug mode that normally because the check already connection
* with this socket if getconnection throw they will be create a new one
*/
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Lock MainMutex");
#endif
_Mutex->lock();
curct=addConnectionContext();
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock MainMutex");
#endif
_Mutex->unlock();
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Lock ConnectionMutex");
#endif
curct->_Mutex->lock();
ClientSocket *clientsocket=curct->_CurConnection->getClientSocket();
int fd=_ServerSocket->acceptEvent(clientsocket);
clientsocket->setnonblocking();
if(fd>0) {
_setEvent.data.ptr = (void*) curct;
_setEvent.events = EPOLLIN|EPOLLET;
if(epoll_ctl(_epollFD, EPOLL_CTL_ADD, fd, &_setEvent)==-1 && errno==EEXIST)
epoll_ctl(_epollFD, EPOLL_CTL_MOD,fd, &_setEvent);
ConnectEvent(curct->_CurConnection);
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} else {
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Lock MainMutex");
#endif
_Mutex->lock();
delConnectionContext(curct->_CurConnection);
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock MainMutex");
#endif
_Mutex->unlock();
}
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Lock MainMutex");
#endif
_Mutex->lock();
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
delConnectionContext(curct->_CurConnection);
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock MainMutex");
#endif
_Mutex->unlock();
if(e.isCritical())
throw e;
}
} else {
curct=(ConnectionContext*)_Events[i].data.ptr;
if(_Events[i].events & EPOLLIN) {
Thread curthread;
curthread.Create(ReadEvent,curct);
curthread.Detach();
}else{
CloseEvent(curct);
}
}
}
_EventIns=this;
signal(SIGINT, CtrlHandler);
}
}
libhttppp::Event::ConnectionContext::ConnectionContext(){
_CurConnection=NULL;
_CurCPool=NULL;
_CurEvent=NULL;
_Mutex=new Mutex;
_nextConnectionContext=NULL;
}
libhttppp::Event::ConnectionContext::~ConnectionContext(){
delete _Mutex;
delete _nextConnectionContext;
}
libhttppp::Event::ConnectionContext * libhttppp::Event::ConnectionContext::nextConnectionContext(){
return _nextConnectionContext;
}
libhttppp::Event::ConnectionContext * libhttppp::Event::addConnectionContext(){
if(!_firstConnectionContext){
_firstConnectionContext=new ConnectionContext();
#ifdef DEBUG_MUTEX
_httpexception.Note("addConnection","Lock ConnectionMutex");
#endif
_firstConnectionContext->_Mutex->lock();
_lastConnectionContext=_firstConnectionContext;
#ifdef DEBUG_MUTEX
_httpexception.Note("addConnection","Unlock ConnectionMutex");
#endif
_firstConnectionContext->_Mutex->unlock();
}else{
#ifdef DEBUG_MUTEX
_httpexception.Note("addConnection","Lock ConnectionMutex");
#endif
ConnectionContext *prevcon=_lastConnectionContext;
prevcon->_Mutex->lock();
_lastConnectionContext->_nextConnectionContext=new ConnectionContext();
_lastConnectionContext=_lastConnectionContext->_nextConnectionContext;
#ifdef DEBUG_MUTEX
_httpexception.Note("addConnection","Unlock ConnectionMutex");
#endif
prevcon->_Mutex->unlock();
}
_lastConnectionContext->_CurConnection=_Cpool->addConnection();
_lastConnectionContext->_CurCPool=_Cpool;
_lastConnectionContext->_CurEvent=this;
return _lastConnectionContext;
}
libhttppp::Event::ConnectionContext * libhttppp::Event::delConnectionContext(libhttppp::Connection* delcon){
ConnectionContext *prevcontext=NULL;
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","Lock MainMutex");
#endif
_Mutex->lock();
for(ConnectionContext *curcontext=_firstConnectionContext; curcontext;
curcontext=curcontext->nextConnectionContext()){
if(curcontext->_CurConnection==delcon){
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","Lock ConnectionMutex");
#endif
curcontext->_Mutex->lock();
_Cpool->delConnection(delcon);
if(prevcontext){
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","Lock prevConnectionMutex");
#endif
prevcontext->_Mutex->lock();
prevcontext->_nextConnectionContext=curcontext->_nextConnectionContext;
if(_lastConnectionContext==curcontext){
_lastConnectionContext=prevcontext;
}
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","unlock prevConnectionMutex");
#endif
prevcontext->_Mutex->unlock();
}else{
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","lock firstConnectionMutex");
#endif
_firstConnectionContext->_Mutex->lock();
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","lock lastConnectionMutex");
#endif
_lastConnectionContext->_Mutex->lock();
_firstConnectionContext=curcontext->_nextConnectionContext;
if(_lastConnectionContext->_CurConnection==delcon)
_lastConnectionContext=_firstConnectionContext;
if(_firstConnectionContext){
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","unlock firstConnectionMutex");
#endif
_firstConnectionContext->_Mutex->unlock();
}
if(_lastConnectionContext){
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","unlock lastConnectionMutex");
#endif
_lastConnectionContext->_Mutex->unlock();
}
}
curcontext->_nextConnectionContext=NULL;
delete curcontext;
break;
}
prevcontext=curcontext;
}
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","unlock MainMutex");
#endif
_Mutex->unlock();
if(prevcontext && prevcontext->_nextConnectionContext){
return prevcontext->_nextConnectionContext;
}else{
ConnectionContext *fcontext=_firstConnectionContext;
return fcontext;
}
}
/*Workers*/
void *libhttppp::Event::ReadEvent(void *curcon){
ConnectionContext *ccon=(ConnectionContext*)curcon;
Event *eventins=ccon->_CurEvent;
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("ReadEvent","lock ConnectionMutex");
#endif
ccon->_Mutex->lock();
Connection *con=(Connection*)ccon->_CurConnection;
try {
char buf[BLOCKSIZE];
int rcvsize=0;
do{
rcvsize=eventins->_ServerSocket->recvData(con->getClientSocket(),buf,BLOCKSIZE);
if(rcvsize>0)
con->addRecvQueue(buf,rcvsize);
}while(rcvsize>0);
eventins->RequestEvent(con);
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
ccon->_Mutex->unlock();
WriteEvent(ccon);
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
ccon->_Mutex->unlock();
if(e.isCritical()) {
throw e;
}
if(e.isError()){
con->cleanRecvData();
CloseEvent(ccon);
}
}
return NULL;
}
void *libhttppp::Event::WriteEvent(void* curcon){
ConnectionContext *ccon=(ConnectionContext*)curcon;
Event *eventins=ccon->_CurEvent;
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("WriteEvent","lock ConnectionMutex");
#endif
ccon->_Mutex->lock();
Connection *con=(Connection*)ccon->_CurConnection;
try {
ssize_t sended=0;
while(con->getSendData()){
sended=eventins->_ServerSocket->sendData(con->getClientSocket(),
(void*)con->getSendData()->getData(),
con->getSendData()->getDataSize());
if(sended>0)
con->resizeSendQueue(sended);
}
eventins->ResponseEvent(con);
} catch(HTTPException &e) {
CloseEvent(ccon);
}
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
ccon->_Mutex->unlock();
return NULL;
}
void *libhttppp::Event::CloseEvent(void *curcon){
ConnectionContext *ccon=(ConnectionContext*)curcon;
Event *eventins=ccon->_CurEvent;
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("CloseEvent","ConnectionMutex");
#endif
ccon->_Mutex->lock();
Connection *con=(Connection*)ccon->_CurConnection;
eventins->DisconnectEvent(con);
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
ccon->_Mutex->unlock();
try {
epoll_ctl(eventins->_epollFD, EPOLL_CTL_DEL, con->getClientSocket()->getSocket(), &eventins->_setEvent);
eventins->delConnectionContext(con);
curcon=NULL;
eventins->_httpexception.Note("Connection shutdown!");
} catch(HTTPException &e) {
eventins->_httpexception.Note("Can't do Connection shutdown!");
}
return NULL;
}
/*Event Handlers*/
void libhttppp::Event::RequestEvent(libhttppp::Connection *curcon) {
return;
}
void libhttppp::Event::ResponseEvent(libhttppp::Connection *curcon) {
return;
}
void libhttppp::Event::ConnectEvent(libhttppp::Connection *curcon) {
return;
}
void libhttppp::Event::DisconnectEvent(libhttppp::Connection *curcon) {
return;
}
<commit_msg>removed deadlock<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
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 <organization> 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 <COPYRIGHT HOLDER> 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 <fcntl.h>
#include <sys/sysinfo.h>
#include <cstdlib>
#include <config.h>
#include <errno.h>
#include <signal.h>
#include "os/os.h"
#define READEVENT 0
#define SENDEVENT 1
//#define DEBUG_MUTEX
#include "../event.h"
libhttppp::Event::Event(ServerSocket *serversocket) {
_ServerSocket=serversocket;
_ServerSocket->setnonblocking();
_ServerSocket->listenSocket();
_EventEndloop =true;
_Cpool= new ConnectionPool(_ServerSocket);
_Events = new epoll_event[(_ServerSocket->getMaxconnections())];
_Mutex = new Mutex;
_firstConnectionContext=NULL;
_lastConnectionContext=NULL;
}
libhttppp::Event::~Event() {
#ifdef DEBUG_MUTEX
_httpexception.Note("~Event","Lock MainMutex");
#endif
_Mutex->lock();
delete _Cpool;
delete[] _Events;
delete _firstConnectionContext;
delete _Mutex;
_lastConnectionContext=NULL;
}
libhttppp::Event* _EventIns=NULL;
void libhttppp::Event::CtrlHandler(int signum) {
_EventIns->_EventEndloop=false;
}
void libhttppp::Event::runEventloop() {
_setEvent = (struct epoll_event){0};
for(int i=0; i<_ServerSocket->getMaxconnections(); i++)
_Events[i].data.fd = -1;
_epollFD = epoll_create1(0);
if (_epollFD == -1) {
_httpexception.Critical("can't create epoll");
throw _httpexception;
}
_setEvent.events = EPOLLIN;
_setEvent.data.fd = _ServerSocket->getSocket();
if (epoll_ctl(_epollFD, EPOLL_CTL_ADD, _ServerSocket->getSocket(), &_setEvent) < 0) {
_httpexception.Critical("can't create epoll");
throw _httpexception;
}
int srvssocket=_ServerSocket->getSocket();
int maxconnets=_ServerSocket->getMaxconnections();
signal(SIGPIPE, SIG_IGN);
while(_EventEndloop) {
int n = epoll_wait(_epollFD,_Events,maxconnets, EPOLLWAIT);
if(n<0){
if(errno== EINTR){
continue;
}else{
_httpexception.Critical("epoll wait failure");
throw _httpexception;
}
}
for(int i=0; i<n; i++) {
ConnectionContext *curct=NULL;
if(_Events[i].data.fd == srvssocket) {
try {
/*will create warning debug mode that normally because the check already connection
* with this socket if getconnection throw they will be create a new one
*/
curct=addConnectionContext();
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Lock ConnectionMutex");
#endif
curct->_Mutex->lock();
ClientSocket *clientsocket=curct->_CurConnection->getClientSocket();
int fd=_ServerSocket->acceptEvent(clientsocket);
clientsocket->setnonblocking();
if(fd>0) {
_setEvent.data.ptr = (void*) curct;
_setEvent.events = EPOLLIN|EPOLLET;
if(epoll_ctl(_epollFD, EPOLL_CTL_ADD, fd, &_setEvent)==-1 && errno==EEXIST)
epoll_ctl(_epollFD, EPOLL_CTL_MOD,fd, &_setEvent);
ConnectEvent(curct->_CurConnection);
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} else {
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Lock MainMutex");
#endif
_Mutex->lock();
delConnectionContext(curct->_CurConnection);
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock MainMutex");
#endif
_Mutex->unlock();
}
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Lock MainMutex");
#endif
_Mutex->lock();
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
delConnectionContext(curct->_CurConnection);
#ifdef DEBUG_MUTEX
_httpexception.Note("runeventloop","Unlock MainMutex");
#endif
_Mutex->unlock();
if(e.isCritical())
throw e;
}
} else {
curct=(ConnectionContext*)_Events[i].data.ptr;
if(_Events[i].events & EPOLLIN) {
Thread curthread;
curthread.Create(ReadEvent,curct);
curthread.Detach();
}else{
CloseEvent(curct);
}
}
}
_EventIns=this;
signal(SIGINT, CtrlHandler);
}
}
libhttppp::Event::ConnectionContext::ConnectionContext(){
_CurConnection=NULL;
_CurCPool=NULL;
_CurEvent=NULL;
_Mutex=new Mutex;
_nextConnectionContext=NULL;
}
libhttppp::Event::ConnectionContext::~ConnectionContext(){
delete _Mutex;
delete _nextConnectionContext;
}
libhttppp::Event::ConnectionContext * libhttppp::Event::ConnectionContext::nextConnectionContext(){
return _nextConnectionContext;
}
libhttppp::Event::ConnectionContext * libhttppp::Event::addConnectionContext(){
if(!_firstConnectionContext){
_firstConnectionContext=new ConnectionContext();
#ifdef DEBUG_MUTEX
_httpexception.Note("addConnection","Lock ConnectionMutex");
#endif
_firstConnectionContext->_Mutex->lock();
_lastConnectionContext=_firstConnectionContext;
#ifdef DEBUG_MUTEX
_httpexception.Note("addConnection","Unlock ConnectionMutex");
#endif
_firstConnectionContext->_Mutex->unlock();
}else{
#ifdef DEBUG_MUTEX
_httpexception.Note("addConnection","Lock ConnectionMutex");
#endif
ConnectionContext *prevcon=_lastConnectionContext;
prevcon->_Mutex->lock();
_lastConnectionContext->_nextConnectionContext=new ConnectionContext();
_lastConnectionContext=_lastConnectionContext->_nextConnectionContext;
#ifdef DEBUG_MUTEX
_httpexception.Note("addConnection","Unlock ConnectionMutex");
#endif
prevcon->_Mutex->unlock();
}
_lastConnectionContext->_CurConnection=_Cpool->addConnection();
_lastConnectionContext->_CurCPool=_Cpool;
_lastConnectionContext->_CurEvent=this;
return _lastConnectionContext;
}
libhttppp::Event::ConnectionContext * libhttppp::Event::delConnectionContext(libhttppp::Connection* delcon){
ConnectionContext *prevcontext=NULL;
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","Lock MainMutex");
#endif
_Mutex->lock();
for(ConnectionContext *curcontext=_firstConnectionContext; curcontext;
curcontext=curcontext->nextConnectionContext()){
if(curcontext->_CurConnection==delcon){
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","Lock ConnectionMutex");
#endif
curcontext->_Mutex->lock();
_Cpool->delConnection(delcon);
if(prevcontext){
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","Lock prevConnectionMutex");
#endif
prevcontext->_Mutex->lock();
prevcontext->_nextConnectionContext=curcontext->_nextConnectionContext;
if(_lastConnectionContext==curcontext){
_lastConnectionContext=prevcontext;
}
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","unlock prevConnectionMutex");
#endif
prevcontext->_Mutex->unlock();
}else{
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","lock firstConnectionMutex");
#endif
_firstConnectionContext->_Mutex->lock();
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","lock lastConnectionMutex");
#endif
_lastConnectionContext->_Mutex->lock();
_firstConnectionContext=curcontext->_nextConnectionContext;
if(_lastConnectionContext->_CurConnection==delcon)
_lastConnectionContext=_firstConnectionContext;
if(_firstConnectionContext){
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","unlock firstConnectionMutex");
#endif
_firstConnectionContext->_Mutex->unlock();
}
if(_lastConnectionContext){
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","unlock lastConnectionMutex");
#endif
_lastConnectionContext->_Mutex->unlock();
}
}
curcontext->_nextConnectionContext=NULL;
delete curcontext;
break;
}
prevcontext=curcontext;
}
#ifdef DEBUG_MUTEX
_httpexception.Note("delConnection","unlock MainMutex");
#endif
_Mutex->unlock();
if(prevcontext && prevcontext->_nextConnectionContext){
return prevcontext->_nextConnectionContext;
}else{
ConnectionContext *fcontext=_firstConnectionContext;
return fcontext;
}
}
/*Workers*/
void *libhttppp::Event::ReadEvent(void *curcon){
ConnectionContext *ccon=(ConnectionContext*)curcon;
Event *eventins=ccon->_CurEvent;
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("ReadEvent","lock ConnectionMutex");
#endif
ccon->_Mutex->lock();
Connection *con=(Connection*)ccon->_CurConnection;
try {
char buf[BLOCKSIZE];
int rcvsize=0;
do{
rcvsize=eventins->_ServerSocket->recvData(con->getClientSocket(),buf,BLOCKSIZE);
if(rcvsize>0)
con->addRecvQueue(buf,rcvsize);
}while(rcvsize>0);
eventins->RequestEvent(con);
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
ccon->_Mutex->unlock();
WriteEvent(ccon);
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
ccon->_Mutex->unlock();
if(e.isCritical()) {
throw e;
}
if(e.isError()){
con->cleanRecvData();
CloseEvent(ccon);
}
}
return NULL;
}
void *libhttppp::Event::WriteEvent(void* curcon){
ConnectionContext *ccon=(ConnectionContext*)curcon;
Event *eventins=ccon->_CurEvent;
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("WriteEvent","lock ConnectionMutex");
#endif
ccon->_Mutex->lock();
Connection *con=(Connection*)ccon->_CurConnection;
try {
ssize_t sended=0;
while(con->getSendData()){
sended=eventins->_ServerSocket->sendData(con->getClientSocket(),
(void*)con->getSendData()->getData(),
con->getSendData()->getDataSize());
if(sended>0)
con->resizeSendQueue(sended);
}
eventins->ResponseEvent(con);
} catch(HTTPException &e) {
CloseEvent(ccon);
}
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
ccon->_Mutex->unlock();
return NULL;
}
void *libhttppp::Event::CloseEvent(void *curcon){
ConnectionContext *ccon=(ConnectionContext*)curcon;
Event *eventins=ccon->_CurEvent;
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("CloseEvent","ConnectionMutex");
#endif
ccon->_Mutex->lock();
Connection *con=(Connection*)ccon->_CurConnection;
eventins->DisconnectEvent(con);
#ifdef DEBUG_MUTEX
ccon->_httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
ccon->_Mutex->unlock();
try {
epoll_ctl(eventins->_epollFD, EPOLL_CTL_DEL, con->getClientSocket()->getSocket(), &eventins->_setEvent);
eventins->delConnectionContext(con);
curcon=NULL;
eventins->_httpexception.Note("Connection shutdown!");
} catch(HTTPException &e) {
eventins->_httpexception.Note("Can't do Connection shutdown!");
}
return NULL;
}
/*Event Handlers*/
void libhttppp::Event::RequestEvent(libhttppp::Connection *curcon) {
return;
}
void libhttppp::Event::ResponseEvent(libhttppp::Connection *curcon) {
return;
}
void libhttppp::Event::ConnectEvent(libhttppp::Connection *curcon) {
return;
}
void libhttppp::Event::DisconnectEvent(libhttppp::Connection *curcon) {
return;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <tr1/memory>
#include <queue>
#include <boost/multi_array.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "array2d.h"
#include "base_measures.h"
#include "monotonic_pseg.h"
#include "conditional_pseg.h"
#include "trule.h"
#include "tdict.h"
#include "stringlib.h"
#include "filelib.h"
#include "dict.h"
#include "sampler.h"
#include "ccrp_nt.h"
#include "corpus.h"
#include "ngram_base.h"
using namespace std;
using namespace tr1;
namespace po = boost::program_options;
void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("samples,s",po::value<unsigned>()->default_value(1000),"Number of samples")
("input,i",po::value<string>(),"Read parallel data from")
("random_seed,S",po::value<uint32_t>(), "Random seed");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || (conf->count("input") == 0)) {
cerr << dcmdline_options << endl;
exit(1);
}
}
shared_ptr<MT19937> prng;
struct LexicalAlignment {
unsigned char src_index;
bool is_transliteration;
vector<pair<short, short> > derivation;
};
struct AlignedSentencePair {
vector<WordID> src;
vector<WordID> trg;
vector<LexicalAlignment> a;
Array2D<short> posterior;
};
struct HierarchicalUnigramBase {
explicit HierarchicalUnigramBase(const unsigned vocab_e_size) : r(5,5), u0(1.0 / vocab_e_size) {}
// return p0 of rule.e_
prob_t operator()(const TRule& rule) const {
prob_t p = prob_t::One();
prob_t q;
for (unsigned i = 0; i < rule.e_.size(); ++i) {
q.logeq(r.logprob(rule.e_[i], log(u0)));
p *= q;
}
q.logeq(r.logprob(TD::Convert("</s>"), log(u0)));
p *= q;
return p;
}
void Increment(const TRule& rule) {
for (unsigned i = 0; i < rule.e_.size(); ++i)
r.increment(rule.e_[i]);
r.increment(TD::Convert("</s>"));
}
void Decrement(const TRule& rule) {
for (unsigned i = 0; i < rule.e_.size(); ++i)
r.decrement(rule.e_[i]);
r.decrement(TD::Convert("</s>"));
}
CCRP_NoTable<WordID> r;
prob_t u0;
};
struct HierarchicalWordBase {
explicit HierarchicalWordBase(const unsigned vocab_e_size) :
base(prob_t::One()), r(15,15), u0(-log(vocab_e_size)) {}
void ResampleHyperparameters(MT19937* rng) {
r.resample_hyperparameters(rng);
}
inline double logp0(const vector<WordID>& s) const {
return s.size() * u0;
}
// return p0 of rule.e_
prob_t operator()(const TRule& rule) const {
prob_t p; p.logeq(r.logprob(rule.e_, logp0(rule.e_)));
return p;
}
void Increment(const TRule& rule) {
if (r.increment(rule.e_)) {
prob_t p; p.logeq(logp0(rule.e_));
base *= p;
}
}
void Decrement(const TRule& rule) {
if (r.decrement(rule.e_)) {
prob_t p; p.logeq(logp0(rule.e_));
base /= p;
}
}
prob_t Likelihood() const {
prob_t p; p.logeq(r.log_crp_prob());
p *= base;
return p;
}
void Summary() const {
cerr << "NUMBER OF CUSTOMERS: " << r.num_customers() << endl;
for (CCRP_NoTable<vector<WordID> >::const_iterator it = r.begin(); it != r.end(); ++it)
cerr << " " << it->second << '\t' << TD::GetString(it->first) << endl;
}
prob_t base;
CCRP_NoTable<vector<WordID> > r;
const double u0;
};
struct BasicLexicalAlignment {
explicit BasicLexicalAlignment(const vector<vector<WordID> >& lets,
const unsigned letters_e,
vector<AlignedSentencePair>* corp) :
letters(lets),
corpus(*corp),
//up0("en.chars.1gram", letters_e),
//up0("en.words.1gram"),
up0(letters_e),
//up0("en.chars.2gram"),
tmodel(up0) {
}
void InstantiateRule(const WordID src,
const WordID trg,
TRule* rule) const {
static const WordID kX = TD::Convert("X") * -1;
rule->lhs_ = kX;
rule->e_ = letters[trg];
rule->f_ = letters[src];
}
void InitializeRandom() {
const WordID kNULL = TD::Convert("NULL");
cerr << "Initializing with random alignments ...\n";
for (unsigned i = 0; i < corpus.size(); ++i) {
AlignedSentencePair& asp = corpus[i];
asp.a.resize(asp.trg.size());
for (unsigned j = 0; j < asp.trg.size(); ++j) {
const unsigned char a_j = prng->next() * (1 + asp.src.size());
const WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
TRule r;
InstantiateRule(f_a_j, asp.trg[j], &r);
asp.a[j].is_transliteration = false;
asp.a[j].src_index = a_j;
if (tmodel.IncrementRule(r))
up0.Increment(r);
}
}
cerr << " LLH = " << Likelihood() << endl;
}
prob_t Likelihood() const {
prob_t p = tmodel.Likelihood();
p *= up0.Likelihood();
return p;
}
void ResampleHyperparemeters() {
cerr << " LLH_prev = " << Likelihood() << flush;
tmodel.ResampleHyperparameters(&*prng);
up0.ResampleHyperparameters(&*prng);
cerr << "\tLLH_post = " << Likelihood() << endl;
}
void ResampleCorpus();
const vector<vector<WordID> >& letters; // spelling dictionary
vector<AlignedSentencePair>& corpus;
//PhraseConditionalUninformativeBase up0;
//PhraseConditionalUninformativeUnigramBase up0;
//UnigramWordBase up0;
//HierarchicalUnigramBase up0;
HierarchicalWordBase up0;
//CompletelyUniformBase up0;
//FixedNgramBase up0;
//ConditionalTranslationModel<PhraseConditionalUninformativeBase> tmodel;
//ConditionalTranslationModel<PhraseConditionalUninformativeUnigramBase> tmodel;
//ConditionalTranslationModel<UnigramWordBase> tmodel;
//ConditionalTranslationModel<HierarchicalUnigramBase> tmodel;
ConditionalTranslationModel<HierarchicalWordBase> tmodel;
//ConditionalTranslationModel<FixedNgramBase> tmodel;
//ConditionalTranslationModel<CompletelyUniformBase> tmodel;
};
void BasicLexicalAlignment::ResampleCorpus() {
static const WordID kNULL = TD::Convert("NULL");
for (unsigned i = 0; i < corpus.size(); ++i) {
AlignedSentencePair& asp = corpus[i];
SampleSet<prob_t> ss; ss.resize(asp.src.size() + 1);
for (unsigned j = 0; j < asp.trg.size(); ++j) {
TRule r;
unsigned char& a_j = asp.a[j].src_index;
WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
InstantiateRule(f_a_j, asp.trg[j], &r);
if (tmodel.DecrementRule(r))
up0.Decrement(r);
for (unsigned prop_a_j = 0; prop_a_j <= asp.src.size(); ++prop_a_j) {
const WordID prop_f = (prop_a_j ? asp.src[prop_a_j - 1] : kNULL);
InstantiateRule(prop_f, asp.trg[j], &r);
ss[prop_a_j] = tmodel.RuleProbability(r);
}
a_j = prng->SelectSample(ss);
f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
InstantiateRule(f_a_j, asp.trg[j], &r);
if (tmodel.IncrementRule(r))
up0.Increment(r);
}
}
cerr << " LLH = " << tmodel.Likelihood() << endl;
}
void ExtractLetters(const set<WordID>& v, vector<vector<WordID> >* l, set<WordID>* letset = NULL) {
for (set<WordID>::const_iterator it = v.begin(); it != v.end(); ++it) {
vector<WordID>& letters = (*l)[*it];
if (letters.size()) continue; // if e and f have the same word
const string& w = TD::Convert(*it);
size_t cur = 0;
while (cur < w.size()) {
const size_t len = UTF8Len(w[cur]);
letters.push_back(TD::Convert(w.substr(cur, len)));
if (letset) letset->insert(letters.back());
cur += len;
}
}
}
void Debug(const AlignedSentencePair& asp) {
cerr << TD::GetString(asp.src) << endl << TD::GetString(asp.trg) << endl;
Array2D<bool> a(asp.src.size(), asp.trg.size());
for (unsigned j = 0; j < asp.trg.size(); ++j)
if (asp.a[j].src_index) a(asp.a[j].src_index - 1, j) = true;
cerr << a << endl;
}
void AddSample(AlignedSentencePair* asp) {
for (unsigned j = 0; j < asp->trg.size(); ++j)
asp->posterior(asp->a[j].src_index, j)++;
}
void WriteAlignments(const AlignedSentencePair& asp) {
bool first = true;
for (unsigned j = 0; j < asp.trg.size(); ++j) {
int src_index = -1;
int mc = -1;
for (unsigned i = 0; i <= asp.src.size(); ++i) {
if (asp.posterior(i, j) > mc) {
mc = asp.posterior(i, j);
src_index = i;
}
}
if (src_index) {
if (first) first = false; else cout << ' ';
cout << (src_index - 1) << '-' << j;
}
}
cout << endl;
}
int main(int argc, char** argv) {
po::variables_map conf;
InitCommandLine(argc, argv, &conf);
if (conf.count("random_seed"))
prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
else
prng.reset(new MT19937);
// MT19937& rng = *prng;
vector<vector<int> > corpuse, corpusf;
set<int> vocabe, vocabf;
corpus::ReadParallelCorpus(conf["input"].as<string>(), &corpusf, &corpuse, &vocabf, &vocabe);
cerr << "f-Corpus size: " << corpusf.size() << " sentences\n";
cerr << "f-Vocabulary size: " << vocabf.size() << " types\n";
cerr << "f-Corpus size: " << corpuse.size() << " sentences\n";
cerr << "f-Vocabulary size: " << vocabe.size() << " types\n";
assert(corpusf.size() == corpuse.size());
vector<AlignedSentencePair> corpus(corpuse.size());
for (unsigned i = 0; i < corpuse.size(); ++i) {
corpus[i].src.swap(corpusf[i]);
corpus[i].trg.swap(corpuse[i]);
corpus[i].posterior.resize(corpus[i].src.size() + 1, corpus[i].trg.size());
}
corpusf.clear(); corpuse.clear();
vocabf.insert(TD::Convert("NULL"));
vector<vector<WordID> > letters(TD::NumWords());
set<WordID> letset;
ExtractLetters(vocabe, &letters, &letset);
ExtractLetters(vocabf, &letters, NULL);
letters[TD::Convert("NULL")].clear();
BasicLexicalAlignment x(letters, letset.size(), &corpus);
x.InitializeRandom();
const unsigned samples = conf["samples"].as<unsigned>();
for (int i = 0; i < samples; ++i) {
for (int j = 431; j < 433; ++j) Debug(corpus[j]);
cerr << i << "\t" << x.tmodel.r.size() << "\t";
if (i % 10 == 0) x.ResampleHyperparemeters();
x.ResampleCorpus();
if (i > (samples / 5) && (i % 10 == 9)) for (int j = 0; j < corpus.size(); ++j) AddSample(&corpus[j]);
}
for (unsigned i = 0; i < corpus.size(); ++i)
WriteAlignments(corpus[i]);
//ModelAndData posterior(x, &corpus, vocabe, vocabf);
x.tmodel.Summary();
x.up0.Summary();
//posterior.Sample();
return 0;
}
<commit_msg>remove broken prior, add logging<commit_after>#include <iostream>
#include <tr1/memory>
#include <queue>
#include <boost/multi_array.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "array2d.h"
#include "base_measures.h"
#include "monotonic_pseg.h"
#include "conditional_pseg.h"
#include "trule.h"
#include "tdict.h"
#include "stringlib.h"
#include "filelib.h"
#include "dict.h"
#include "sampler.h"
#include "ccrp_nt.h"
#include "corpus.h"
#include "ngram_base.h"
using namespace std;
using namespace tr1;
namespace po = boost::program_options;
void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("samples,s",po::value<unsigned>()->default_value(1000),"Number of samples")
("input,i",po::value<string>(),"Read parallel data from")
("random_seed,S",po::value<uint32_t>(), "Random seed");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || (conf->count("input") == 0)) {
cerr << dcmdline_options << endl;
exit(1);
}
}
shared_ptr<MT19937> prng;
struct LexicalAlignment {
unsigned char src_index;
bool is_transliteration;
vector<pair<short, short> > derivation;
};
struct AlignedSentencePair {
vector<WordID> src;
vector<WordID> trg;
vector<LexicalAlignment> a;
Array2D<short> posterior;
};
struct HierarchicalWordBase {
explicit HierarchicalWordBase(const unsigned vocab_e_size) :
base(prob_t::One()), r(25,25,10), u0(-log(vocab_e_size)) {}
void ResampleHyperparameters(MT19937* rng) {
r.resample_hyperparameters(rng);
}
inline double logp0(const vector<WordID>& s) const {
return s.size() * u0;
}
// return p0 of rule.e_
prob_t operator()(const TRule& rule) const {
prob_t p; p.logeq(r.logprob(rule.e_, logp0(rule.e_)));
return p;
}
void Increment(const TRule& rule) {
if (r.increment(rule.e_)) {
prob_t p; p.logeq(logp0(rule.e_));
base *= p;
}
}
void Decrement(const TRule& rule) {
if (r.decrement(rule.e_)) {
prob_t p; p.logeq(logp0(rule.e_));
base /= p;
}
}
prob_t Likelihood() const {
prob_t p; p.logeq(r.log_crp_prob());
p *= base;
return p;
}
void Summary() const {
cerr << "NUMBER OF CUSTOMERS: " << r.num_customers() << " (\\alpha=" << r.concentration() << ')' << endl;
for (CCRP_NoTable<vector<WordID> >::const_iterator it = r.begin(); it != r.end(); ++it)
cerr << " " << it->second << '\t' << TD::GetString(it->first) << endl;
}
prob_t base;
CCRP_NoTable<vector<WordID> > r;
const double u0;
};
struct BasicLexicalAlignment {
explicit BasicLexicalAlignment(const vector<vector<WordID> >& lets,
const unsigned letters_e,
vector<AlignedSentencePair>* corp) :
letters(lets),
corpus(*corp),
//up0("en.chars.1gram", letters_e),
//up0("en.words.1gram"),
up0(letters_e),
//up0("en.chars.2gram"),
tmodel(up0) {
}
void InstantiateRule(const WordID src,
const WordID trg,
TRule* rule) const {
static const WordID kX = TD::Convert("X") * -1;
rule->lhs_ = kX;
rule->e_ = letters[trg];
rule->f_ = letters[src];
}
void InitializeRandom() {
const WordID kNULL = TD::Convert("NULL");
cerr << "Initializing with random alignments ...\n";
for (unsigned i = 0; i < corpus.size(); ++i) {
AlignedSentencePair& asp = corpus[i];
asp.a.resize(asp.trg.size());
for (unsigned j = 0; j < asp.trg.size(); ++j) {
const unsigned char a_j = prng->next() * (1 + asp.src.size());
const WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
TRule r;
InstantiateRule(f_a_j, asp.trg[j], &r);
asp.a[j].is_transliteration = false;
asp.a[j].src_index = a_j;
if (tmodel.IncrementRule(r))
up0.Increment(r);
}
}
cerr << " LLH = " << Likelihood() << endl;
}
prob_t Likelihood() const {
prob_t p = tmodel.Likelihood();
p *= up0.Likelihood();
return p;
}
void ResampleHyperparemeters() {
cerr << " LLH_prev = " << Likelihood() << flush;
tmodel.ResampleHyperparameters(&*prng);
up0.ResampleHyperparameters(&*prng);
cerr << "\tLLH_post = " << Likelihood() << endl;
}
void ResampleCorpus();
const vector<vector<WordID> >& letters; // spelling dictionary
vector<AlignedSentencePair>& corpus;
//PhraseConditionalUninformativeBase up0;
//PhraseConditionalUninformativeUnigramBase up0;
//UnigramWordBase up0;
//HierarchicalUnigramBase up0;
HierarchicalWordBase up0;
//CompletelyUniformBase up0;
//FixedNgramBase up0;
//ConditionalTranslationModel<PhraseConditionalUninformativeBase> tmodel;
//ConditionalTranslationModel<PhraseConditionalUninformativeUnigramBase> tmodel;
//ConditionalTranslationModel<UnigramWordBase> tmodel;
//ConditionalTranslationModel<HierarchicalUnigramBase> tmodel;
ConditionalTranslationModel<HierarchicalWordBase> tmodel;
//ConditionalTranslationModel<FixedNgramBase> tmodel;
//ConditionalTranslationModel<CompletelyUniformBase> tmodel;
};
void BasicLexicalAlignment::ResampleCorpus() {
static const WordID kNULL = TD::Convert("NULL");
for (unsigned i = 0; i < corpus.size(); ++i) {
AlignedSentencePair& asp = corpus[i];
SampleSet<prob_t> ss; ss.resize(asp.src.size() + 1);
for (unsigned j = 0; j < asp.trg.size(); ++j) {
TRule r;
unsigned char& a_j = asp.a[j].src_index;
WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
InstantiateRule(f_a_j, asp.trg[j], &r);
if (tmodel.DecrementRule(r))
up0.Decrement(r);
for (unsigned prop_a_j = 0; prop_a_j <= asp.src.size(); ++prop_a_j) {
const WordID prop_f = (prop_a_j ? asp.src[prop_a_j - 1] : kNULL);
InstantiateRule(prop_f, asp.trg[j], &r);
ss[prop_a_j] = tmodel.RuleProbability(r);
}
a_j = prng->SelectSample(ss);
f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
InstantiateRule(f_a_j, asp.trg[j], &r);
if (tmodel.IncrementRule(r))
up0.Increment(r);
}
}
cerr << " LLH = " << tmodel.Likelihood() << endl;
}
void ExtractLetters(const set<WordID>& v, vector<vector<WordID> >* l, set<WordID>* letset = NULL) {
for (set<WordID>::const_iterator it = v.begin(); it != v.end(); ++it) {
vector<WordID>& letters = (*l)[*it];
if (letters.size()) continue; // if e and f have the same word
const string& w = TD::Convert(*it);
size_t cur = 0;
while (cur < w.size()) {
const size_t len = UTF8Len(w[cur]);
letters.push_back(TD::Convert(w.substr(cur, len)));
if (letset) letset->insert(letters.back());
cur += len;
}
}
}
void Debug(const AlignedSentencePair& asp) {
cerr << TD::GetString(asp.src) << endl << TD::GetString(asp.trg) << endl;
Array2D<bool> a(asp.src.size(), asp.trg.size());
for (unsigned j = 0; j < asp.trg.size(); ++j)
if (asp.a[j].src_index) a(asp.a[j].src_index - 1, j) = true;
cerr << a << endl;
}
void AddSample(AlignedSentencePair* asp) {
for (unsigned j = 0; j < asp->trg.size(); ++j)
asp->posterior(asp->a[j].src_index, j)++;
}
void WriteAlignments(const AlignedSentencePair& asp) {
bool first = true;
for (unsigned j = 0; j < asp.trg.size(); ++j) {
int src_index = -1;
int mc = -1;
for (unsigned i = 0; i <= asp.src.size(); ++i) {
if (asp.posterior(i, j) > mc) {
mc = asp.posterior(i, j);
src_index = i;
}
}
if (src_index) {
if (first) first = false; else cout << ' ';
cout << (src_index - 1) << '-' << j;
}
}
cout << endl;
}
int main(int argc, char** argv) {
po::variables_map conf;
InitCommandLine(argc, argv, &conf);
if (conf.count("random_seed"))
prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
else
prng.reset(new MT19937);
// MT19937& rng = *prng;
vector<vector<int> > corpuse, corpusf;
set<int> vocabe, vocabf;
corpus::ReadParallelCorpus(conf["input"].as<string>(), &corpusf, &corpuse, &vocabf, &vocabe);
cerr << "f-Corpus size: " << corpusf.size() << " sentences\n";
cerr << "f-Vocabulary size: " << vocabf.size() << " types\n";
cerr << "f-Corpus size: " << corpuse.size() << " sentences\n";
cerr << "f-Vocabulary size: " << vocabe.size() << " types\n";
assert(corpusf.size() == corpuse.size());
vector<AlignedSentencePair> corpus(corpuse.size());
for (unsigned i = 0; i < corpuse.size(); ++i) {
corpus[i].src.swap(corpusf[i]);
corpus[i].trg.swap(corpuse[i]);
corpus[i].posterior.resize(corpus[i].src.size() + 1, corpus[i].trg.size());
}
corpusf.clear(); corpuse.clear();
vocabf.insert(TD::Convert("NULL"));
vector<vector<WordID> > letters(TD::NumWords());
set<WordID> letset;
ExtractLetters(vocabe, &letters, &letset);
ExtractLetters(vocabf, &letters, NULL);
letters[TD::Convert("NULL")].clear();
BasicLexicalAlignment x(letters, letset.size(), &corpus);
x.InitializeRandom();
const unsigned samples = conf["samples"].as<unsigned>();
for (int i = 0; i < samples; ++i) {
for (int j = 431; j < 433; ++j) Debug(corpus[j]);
cerr << i << "\t" << x.tmodel.r.size() << "\t";
if (i % 10 == 0) x.ResampleHyperparemeters();
x.ResampleCorpus();
if (i > (samples / 5) && (i % 10 == 9)) for (int j = 0; j < corpus.size(); ++j) AddSample(&corpus[j]);
}
for (unsigned i = 0; i < corpus.size(); ++i)
WriteAlignments(corpus[i]);
//ModelAndData posterior(x, &corpus, vocabe, vocabf);
x.tmodel.Summary();
x.up0.Summary();
//posterior.Sample();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(MUTABLENODEREFLIST_HEADER_GUARD_1357924680)
#define MUTABLENODEREFLIST_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <XPath/NodeRefList.hpp>
class XPathExecutionContext;
class XalanDocument;
class XalanNodeList;
/**
* Local implementation of MutableNodeRefList. This class is for internal use
* only.
*/
class XALAN_XPATH_EXPORT MutableNodeRefList : public NodeRefList
{
public:
/**
* Construct an empty mutable node list.
*/
explicit
MutableNodeRefList();
/**
* Construct a mutable node list from another list.
*
* @param theSource source list
*/
MutableNodeRefList(const MutableNodeRefList& theSource);
/**
* Construct a mutable node list from another list.
*
* @param theSource source list
*/
explicit
MutableNodeRefList(const NodeRefListBase& theSource);
virtual
~MutableNodeRefList();
MutableNodeRefList&
operator=(const MutableNodeRefList& theRHS);
MutableNodeRefList&
operator=(const NodeRefList& theRHS);
MutableNodeRefList&
operator=(const NodeRefListBase& theRHS);
MutableNodeRefList&
operator=(const XalanNodeList* theRHS);
/**
* Add a node at to the list.
*
* @param n node to add
*/
void
addNode(XalanNode* n);
/**
* Insert a node at a given position.
*
* @param n node to insert
* @param pos position of insertion
*/
void
insertNode(
XalanNode* n,
size_type pos);
/**
* Remove a node from the list.
*
* @param n node to insert
*/
void
removeNode(const XalanNode* n);
/**
* Remove a node from the list.
*
* @param pos position of node in list
*/
void
removeNode(size_type pos);
/**
* Remove all nodes.
*/
void
clear();
/**
* Set a item.
*
* @param pos position of node to modify
* @param n node to insert, default is empty node
*/
void
setNode(
size_type pos,
XalanNode* n = 0);
/**
* Copy NodeList members into this nodelist, adding in document order. If
* a node is null, don't add it.
*
* @param nodelist node list to add
*/
void
addNodes(const XalanNodeList& nodelist);
/**
* Copy NodeList members into this nodelist, adding in document order. If
* a node is null, don't add it.
*
* @param nodelist node list to add
*/
void
addNodes(const NodeRefListBase& nodelist);
/**
* Copy NodeList members into this nodelist, adding in document order.
*
* @param nodelist node list to add
* @param executionContext the current execution context
*/
void
addNodesInDocOrder(
const XalanNodeList& nodelist,
XPathExecutionContext& executionContext);
/**
* Copy NodeList members into this nodelist, adding in document order.
*
* @param nodelist node list to add
* @param executionContext the current execution context
*/
void
addNodesInDocOrder(
const NodeRefListBase& nodelist,
XPathExecutionContext& executionContext);
/**
* Copy NodeList members into this nodelist, adding in document order.
*
* @param nodelist node list to add
* @param executionContext the current execution context
*/
void
addNodesInDocOrder(
const MutableNodeRefList& nodelist,
XPathExecutionContext& executionContext);
/**
* Add a node into list where it should occur in document order.
*
* @param node node object to add
* @param executionContext the current execution context
*/
void
addNodeInDocOrder(
XalanNode* node,
XPathExecutionContext& executionContext);
/**
* Clear any null entries in the node list.
*/
void
clearNulls();
/**
* Reverse the nodes in the list.
*/
void
reverse();
/**
* Reserve space for the supplied number of nodes.
* This is taken as an optimization, and may be
* ignored. You might want to call this when you
* know the number of nodes you're about to add to
* this list.
*
* Remember to take into account the current size of
* the list when calling this. That means you will
* probably want to add the result of getLength() to
* the number of nodes you're planning to add.
*
* @param theCount the number of nodes to reserve space for
*/
void
reserve(size_type theCount)
{
m_nodeList.reserve(theCount);
}
/**
* Set the known order of the nodes. This should
* only be done when the order is known. Otherwise,
* disaster will ensue.
*/
void
setDocumentOrder()
{
m_order = eDocumentOrder;
}
/**
* Set the known order of the nodes. This should
* only be done when the order is known. Otherwise,
* disaster will ensue.
*/
void
setReverseDocumentOrder()
{
m_order = eReverseDocumentOrder;
}
typedef NodeListVectorType::iterator NodeListIteratorType;
class addNodeInDocOrderFunctor
{
public:
addNodeInDocOrderFunctor(
MutableNodeRefList& theList,
XPathExecutionContext& theExecutionContext) :
m_list(theList),
m_executionContext(theExecutionContext)
{
}
void
operator()(XalanNode* theNode) const
{
m_list.addNodeInDocOrder(theNode, m_executionContext);
}
private:
MutableNodeRefList& m_list;
XPathExecutionContext& m_executionContext;
};
private:
// An enum to determine what the order of the nodes is...
enum eOrder { eUnknownOrder, eDocumentOrder, eReverseDocumentOrder };
eOrder m_order;
};
#endif // MUTABLENODEREFLIST_HEADER_GUARD_1357924680
<commit_msg>Added a few accessors for ordering information.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(MUTABLENODEREFLIST_HEADER_GUARD_1357924680)
#define MUTABLENODEREFLIST_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <XPath/NodeRefList.hpp>
class XPathExecutionContext;
class XalanDocument;
class XalanNodeList;
/**
* Local implementation of MutableNodeRefList. This class is for internal use
* only.
*/
class XALAN_XPATH_EXPORT MutableNodeRefList : public NodeRefList
{
public:
/**
* Construct an empty mutable node list.
*/
explicit
MutableNodeRefList();
/**
* Construct a mutable node list from another list.
*
* @param theSource source list
*/
MutableNodeRefList(const MutableNodeRefList& theSource);
/**
* Construct a mutable node list from another list.
*
* @param theSource source list
*/
explicit
MutableNodeRefList(const NodeRefListBase& theSource);
virtual
~MutableNodeRefList();
MutableNodeRefList&
operator=(const MutableNodeRefList& theRHS);
MutableNodeRefList&
operator=(const NodeRefList& theRHS);
MutableNodeRefList&
operator=(const NodeRefListBase& theRHS);
MutableNodeRefList&
operator=(const XalanNodeList* theRHS);
/**
* Add a node at to the list.
*
* @param n node to add
*/
void
addNode(XalanNode* n);
/**
* Insert a node at a given position.
*
* @param n node to insert
* @param pos position of insertion
*/
void
insertNode(
XalanNode* n,
size_type pos);
/**
* Remove a node from the list.
*
* @param n node to insert
*/
void
removeNode(const XalanNode* n);
/**
* Remove a node from the list.
*
* @param pos position of node in list
*/
void
removeNode(size_type pos);
/**
* Remove all nodes.
*/
void
clear();
/**
* Set a item.
*
* @param pos position of node to modify
* @param n node to insert, default is empty node
*/
void
setNode(
size_type pos,
XalanNode* n = 0);
/**
* Copy NodeList members into this nodelist, adding in document order. If
* a node is null, don't add it.
*
* @param nodelist node list to add
*/
void
addNodes(const XalanNodeList& nodelist);
/**
* Copy NodeList members into this nodelist, adding in document order. If
* a node is null, don't add it.
*
* @param nodelist node list to add
*/
void
addNodes(const NodeRefListBase& nodelist);
/**
* Copy NodeList members into this nodelist, adding in document order.
*
* @param nodelist node list to add
* @param executionContext the current execution context
*/
void
addNodesInDocOrder(
const XalanNodeList& nodelist,
XPathExecutionContext& executionContext);
/**
* Copy NodeList members into this nodelist, adding in document order.
*
* @param nodelist node list to add
* @param executionContext the current execution context
*/
void
addNodesInDocOrder(
const NodeRefListBase& nodelist,
XPathExecutionContext& executionContext);
/**
* Copy NodeList members into this nodelist, adding in document order.
*
* @param nodelist node list to add
* @param executionContext the current execution context
*/
void
addNodesInDocOrder(
const MutableNodeRefList& nodelist,
XPathExecutionContext& executionContext);
/**
* Add a node into list where it should occur in document order.
*
* @param node node object to add
* @param executionContext the current execution context
*/
void
addNodeInDocOrder(
XalanNode* node,
XPathExecutionContext& executionContext);
/**
* Clear any null entries in the node list.
*/
void
clearNulls();
/**
* Reverse the nodes in the list.
*/
void
reverse();
/**
* Reserve space for the supplied number of nodes.
* This is taken as an optimization, and may be
* ignored. You might want to call this when you
* know the number of nodes you're about to add to
* this list.
*
* Remember to take into account the current size of
* the list when calling this. That means you will
* probably want to add the result of getLength() to
* the number of nodes you're planning to add.
*
* @param theCount the number of nodes to reserve space for
*/
void
reserve(size_type theCount)
{
m_nodeList.reserve(theCount);
}
/**
* See if the order of the nodes is an unknown order.
*/
bool
getUnknownOrder() const
{
return m_order == eUnknownOrder ? true : false;
}
/**
* See if the order of the nodes is document order.
*/
bool
getDocumentOrder() const
{
return m_order == eDocumentOrder ? true : false;
}
/**
* Set the known order of the nodes. This should
* only be done when the order is known. Otherwise,
* disaster will ensue.
*/
void
setDocumentOrder()
{
m_order = eDocumentOrder;
}
/**
* See if the order of the nodes is reverse document order.
*/
bool
getReverseDocumentOrder() const
{
return m_order == eReverseDocumentOrder ? true : false;
}
/**
* Set the known order of the nodes. This should
* only be done when the order is known. Otherwise,
* disaster will ensue.
*/
void
setReverseDocumentOrder()
{
m_order = eReverseDocumentOrder;
}
typedef NodeListVectorType::iterator NodeListIteratorType;
class addNodeInDocOrderFunctor
{
public:
addNodeInDocOrderFunctor(
MutableNodeRefList& theList,
XPathExecutionContext& theExecutionContext) :
m_list(theList),
m_executionContext(theExecutionContext)
{
}
void
operator()(XalanNode* theNode) const
{
m_list.addNodeInDocOrder(theNode, m_executionContext);
}
private:
MutableNodeRefList& m_list;
XPathExecutionContext& m_executionContext;
};
private:
// An enum to determine what the order of the nodes is...
enum eOrder { eUnknownOrder, eDocumentOrder, eReverseDocumentOrder };
eOrder m_order;
};
#endif // MUTABLENODEREFLIST_HEADER_GUARD_1357924680
<|endoftext|>
|
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef SERIALIZER_MERGER_HPP_
#define SERIALIZER_MERGER_HPP_
#include <vector>
#include <map>
#include <memory>
#include "buffer_cache/types.hpp"
#include "containers/scoped.hpp"
#include "serializer/serializer.hpp"
/*
* The merger serializer is a wrapper around another serializer. It limits
* the number of active index_writes. If more index_writes come in while
* `max_active_writes` index_writes are already going on, the new index
* writes are queued up.
* The advantage of this is that multiple index writes (e.g. coming from different
* hash shards) can be merged together, improving efficiency and significantly
* reducing the number of disk seeks on rotational drives.
*
*/
class merger_serializer_t : public serializer_t {
public:
merger_serializer_t(scoped_ptr_t<serializer_t> _inner, int _max_active_writes);
~merger_serializer_t();
/* serializer_t interface */
scoped_malloc_t<ser_buffer_t> malloc() { return inner->malloc(); }
scoped_malloc_t<ser_buffer_t> clone(const ser_buffer_t *b) { return inner->clone(b); }
/* Allocates a new io account for the underlying file.
Use delete to free it. */
file_account_t *make_io_account(int priority) { return inner->make_io_account(priority); }
file_account_t *make_io_account(int priority, int outstanding_requests_limit) {
return inner->make_io_account(priority, outstanding_requests_limit);
}
/* Some serializer implementations support read-ahead to speed up cache warmup.
This is supported through a serializer_read_ahead_callback_t which gets called whenever the serializer has read-ahead some buf.
The callee can then decide whether it wants to use the offered buffer of discard it.
*/
void register_read_ahead_cb(serializer_read_ahead_callback_t *cb) { inner->register_read_ahead_cb(cb); }
void unregister_read_ahead_cb(serializer_read_ahead_callback_t *cb) { inner->unregister_read_ahead_cb(cb); }
// Reading a block from the serializer. Reads a block, blocks the coroutine.
void block_read(const counted_t<standard_block_token_t> &token,
ser_buffer_t *buf, file_account_t *io_account) {
inner->block_read(token, buf, io_account);
}
/* The index stores three pieces of information for each ID:
* 1. A pointer to a data block on disk (which may be NULL)
* 2. A repli_timestamp_t, called the "recency"
* 3. A boolean, called the "delete bit" */
/* max_block_id() and get_delete_bit() are used by the buffer cache to reconstruct
the free list of unused block IDs. */
/* Returns a block ID such that every existing block has an ID less than
* that ID. Note that index_read(max_block_id() - 1) is not guaranteed to be
* non-NULL. Note that for k > 0, max_block_id() - k might have never been
* created. */
block_id_t max_block_id() { return inner->max_block_id(); }
/* Gets a block's timestamp. This may return repli_timestamp_t::invalid. */
repli_timestamp_t get_recency(block_id_t id) { return inner->get_recency(id); }
/* Reads the block's delete bit. */
bool get_delete_bit(block_id_t id) { return inner->get_delete_bit(id); }
/* Reads the block's actual data */
counted_t<standard_block_token_t> index_read(block_id_t block_id) { return inner->index_read(block_id); }
/* index_write() applies all given index operations in an atomic way */
/* This is where merger_serializer_t merges operations */
void index_write(const std::vector<index_write_op_t> &write_ops, file_account_t *io_account);
// Returns block tokens in the same order as write_infos.
std::vector<counted_t<standard_block_token_t> >
block_writes(const std::vector<buf_write_info_t> &write_infos,
file_account_t *io_account,
iocallback_t *cb) {
// Currently, we do not merge block writes, only index writes.
return inner->block_writes(write_infos, io_account, cb);
}
/* The size, in bytes, of each serializer block */
block_size_t get_block_size() const { return inner->get_block_size(); }
/* Return true if no other processes have the file locked */
bool coop_lock_and_check() { return inner->coop_lock_and_check(); }
private:
// Adds `op` to `outstanding_index_write_ops`, using `merge_index_write_op()` if necessary
void push_index_write_op(const index_write_op_t &op);
// This merges to_be_merged in-place into into_out.
void merge_index_write_op(const index_write_op_t &to_be_merged, index_write_op_t *into_out) const;
const scoped_ptr_t<serializer_t> inner;
const scoped_ptr_t<file_account_t> index_writes_io_account;
// A map of outstanding index write operations, indexed by block id
std::map<block_id_t, index_write_op_t> outstanding_index_write_ops;
// Index writes which are currently outstanding keep a pointer to this condition.
// It is pulsed once the write completes.
class counted_cond_t : public cond_t, public single_threaded_countable_t<counted_cond_t> { };
counted_t<counted_cond_t> on_inner_index_write_complete;
int num_active_writes;
int max_active_writes;
void do_index_write();
DISABLE_COPYING(merger_serializer_t);
};
#endif /* SERIALIZER_MERGER_HPP_ */
<commit_msg>Removed manual wrapping of make_io_account in merger_serializer_t.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef SERIALIZER_MERGER_HPP_
#define SERIALIZER_MERGER_HPP_
#include <vector>
#include <map>
#include <memory>
#include "buffer_cache/types.hpp"
#include "containers/scoped.hpp"
#include "serializer/serializer.hpp"
/*
* The merger serializer is a wrapper around another serializer. It limits
* the number of active index_writes. If more index_writes come in while
* `max_active_writes` index_writes are already going on, the new index
* writes are queued up.
* The advantage of this is that multiple index writes (e.g. coming from different
* hash shards) can be merged together, improving efficiency and significantly
* reducing the number of disk seeks on rotational drives.
*
*/
class merger_serializer_t : public serializer_t {
public:
merger_serializer_t(scoped_ptr_t<serializer_t> _inner, int _max_active_writes);
~merger_serializer_t();
/* serializer_t interface */
scoped_malloc_t<ser_buffer_t> malloc() { return inner->malloc(); }
scoped_malloc_t<ser_buffer_t> clone(const ser_buffer_t *b) { return inner->clone(b); }
/* Allocates a new io account for the underlying file.
Use delete to free it. */
using serializer_t::make_io_account;
file_account_t *make_io_account(int priority, int outstanding_requests_limit) {
return inner->make_io_account(priority, outstanding_requests_limit);
}
/* Some serializer implementations support read-ahead to speed up cache warmup.
This is supported through a serializer_read_ahead_callback_t which gets called whenever the serializer has read-ahead some buf.
The callee can then decide whether it wants to use the offered buffer of discard it.
*/
void register_read_ahead_cb(serializer_read_ahead_callback_t *cb) { inner->register_read_ahead_cb(cb); }
void unregister_read_ahead_cb(serializer_read_ahead_callback_t *cb) { inner->unregister_read_ahead_cb(cb); }
// Reading a block from the serializer. Reads a block, blocks the coroutine.
void block_read(const counted_t<standard_block_token_t> &token,
ser_buffer_t *buf, file_account_t *io_account) {
inner->block_read(token, buf, io_account);
}
/* The index stores three pieces of information for each ID:
* 1. A pointer to a data block on disk (which may be NULL)
* 2. A repli_timestamp_t, called the "recency"
* 3. A boolean, called the "delete bit" */
/* max_block_id() and get_delete_bit() are used by the buffer cache to reconstruct
the free list of unused block IDs. */
/* Returns a block ID such that every existing block has an ID less than
* that ID. Note that index_read(max_block_id() - 1) is not guaranteed to be
* non-NULL. Note that for k > 0, max_block_id() - k might have never been
* created. */
block_id_t max_block_id() { return inner->max_block_id(); }
/* Gets a block's timestamp. This may return repli_timestamp_t::invalid. */
repli_timestamp_t get_recency(block_id_t id) { return inner->get_recency(id); }
/* Reads the block's delete bit. */
bool get_delete_bit(block_id_t id) { return inner->get_delete_bit(id); }
/* Reads the block's actual data */
counted_t<standard_block_token_t> index_read(block_id_t block_id) { return inner->index_read(block_id); }
/* index_write() applies all given index operations in an atomic way */
/* This is where merger_serializer_t merges operations */
void index_write(const std::vector<index_write_op_t> &write_ops, file_account_t *io_account);
// Returns block tokens in the same order as write_infos.
std::vector<counted_t<standard_block_token_t> >
block_writes(const std::vector<buf_write_info_t> &write_infos,
file_account_t *io_account,
iocallback_t *cb) {
// Currently, we do not merge block writes, only index writes.
return inner->block_writes(write_infos, io_account, cb);
}
/* The size, in bytes, of each serializer block */
block_size_t get_block_size() const { return inner->get_block_size(); }
/* Return true if no other processes have the file locked */
bool coop_lock_and_check() { return inner->coop_lock_and_check(); }
private:
// Adds `op` to `outstanding_index_write_ops`, using `merge_index_write_op()` if necessary
void push_index_write_op(const index_write_op_t &op);
// This merges to_be_merged in-place into into_out.
void merge_index_write_op(const index_write_op_t &to_be_merged, index_write_op_t *into_out) const;
const scoped_ptr_t<serializer_t> inner;
const scoped_ptr_t<file_account_t> index_writes_io_account;
// A map of outstanding index write operations, indexed by block id
std::map<block_id_t, index_write_op_t> outstanding_index_write_ops;
// Index writes which are currently outstanding keep a pointer to this condition.
// It is pulsed once the write completes.
class counted_cond_t : public cond_t, public single_threaded_countable_t<counted_cond_t> { };
counted_t<counted_cond_t> on_inner_index_write_complete;
int num_active_writes;
int max_active_writes;
void do_index_write();
DISABLE_COPYING(merger_serializer_t);
};
#endif /* SERIALIZER_MERGER_HPP_ */
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include <vector>
#include <algorithm>
#ifndef M_PI
#define M_PI 3.14159265359
#endif
typedef unsigned char uchar;
// Load Hipparcos catalog
cv::Mat load_catalog(const char* filename) {
cv::Mat catalog(1, 3, CV_32FC1);
std::ifstream file(filename);
std::string line, cell;
if (!file) {
std::cerr << "Can't open catalog " << filename << std::endl;
return catalog;
}
// Skip first line
std::getline(file, line);
// Extract each line data
while (std::getline(file, line)) {
std::stringstream line_str(line);
// Read fields
double hip(0.0), mag(0.0), ra(0.0), de(0.0);
line_str >> hip; line_str.get();
line_str >> mag; line_str.get();
line_str >> ra; line_str.get();
line_str >> de; line_str.get();
// Convert angles to radians
const double deg_to_rad = M_PI / 180.0;
cv::Mat catline = (cv::Mat_<float>(1,3) << mag, ra * deg_to_rad, de * deg_to_rad);
catalog.push_back(catline);
}
return catalog;
}
struct planetarium {
// Point spread function amplitude
double psf_amplitude;
// Point spread function b parameter
double psf_sigma;
// Max size of the spread to one side in pixels
// e.g. 1 means the square of pixels modified will be 3x3
double psf_spread_size;
// Screen
double screen_distance;
double screen_width;
double screen_height;
double screen_horizontal_pixel_size;
double screen_vertical_pixel_size;
// The value of a gaussian point spread function at a given distance
float psf_gaussian(float distance) {
return psf_amplitude * exp(-(distance*distance) / psf_sigma);
}
// Draw a star at given screen coordinates
// Uses a gaussian point spread function
void draw_star(cv::Mat image, float star_x, float star_y) {
// Closest discrete pixel to the star location
const int center_x = round(star_x);
const int center_y = round(star_y);
// For each pixel around the star
for (int x = center_x - psf_spread_size; x <= center_x + psf_spread_size; x++) {
for (int y = center_y - psf_spread_size; y <= center_y + psf_spread_size; y++) {
// Get the point spread function value at that distance from the star
float distance = sqrt(pow(star_x - x, 2) + pow(star_y - y, 2));
// If within bounds, add it to current value
if (y > 0 && x > 0 && y < image.rows && x < image.cols) {
image.at<float>(y,x) += psf_gaussian(distance);
}
}
}
}
void draw_visible_stars(cv::Mat image, cv::Mat catalog) {
// For each entry in the catalog
for (int i = 0; i < catalog.rows; i++) {
const double ra = catalog.at<float>(i, 1);
const double de = catalog.at<float>(i, 2);
const double max_ra = std::atan((screen_width * screen_horizontal_pixel_size) / (2*screen_distance));
const double max_de = std::atan((screen_height * screen_vertical_pixel_size) / (2*screen_distance));
// If star is visible
// RA is in [0;2pi] but DE is in [-pi;pi]
if (ra - M_PI > -max_ra && ra - M_PI < max_ra && de > -max_de && de < max_de) {
const double x = screen_distance * tan(ra);
const double y = screen_distance * tan(de);
// Meters to pixel
const int x_screen = round(-x / screen_horizontal_pixel_size + screen_width / 2);
const int y_screen = round(-y / screen_vertical_pixel_size + screen_height / 2);
if (x_screen > 0 && x_screen < screen_width && y_screen > 0 && y_screen < screen_height) {
draw_star(image, x_screen, y_screen);
}
}
}
}
};
int main() {
cv::namedWindow("Planetarium", cv::WINDOW_AUTOSIZE);
// Black background
cv::Mat image(600, 800, CV_32FC1);
planetarium wall;
wall.psf_amplitude = 1.0;
wall.psf_sigma = 1.0;
wall.psf_spread_size = 5;
wall.screen_distance = .3;
wall.screen_width = 800;
wall.screen_height = 600;
wall.screen_horizontal_pixel_size = 0.0002 ;
wall.screen_vertical_pixel_size = 0.0002;
// Load star catalog
cv::Mat catalog = load_catalog("../hip5.tsv");
wall.draw_visible_stars(image, catalog);
// Threshold to 1.0
cv::threshold(image, image, 1.0, 0.0, cv::THRESH_TRUNC);
int k;
while((k = cvWaitKey(5)) != 27) {
cv::imshow("Planetarium", image);
if (k != -1) {
std::cout << k << std::endl;
}
}
return 0;
}
<commit_msg>added is_star_visible()<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include <vector>
#include <algorithm>
#ifndef M_PI
#define M_PI 3.14159265359
#endif
typedef unsigned char uchar;
// Load Hipparcos catalog
cv::Mat load_catalog(const char* filename) {
cv::Mat catalog(1, 3, CV_32FC1);
std::ifstream file(filename);
std::string line, cell;
if (!file) {
std::cerr << "Can't open catalog " << filename << std::endl;
return catalog;
}
// Skip first line
std::getline(file, line);
// Extract each line data
while (std::getline(file, line)) {
std::stringstream line_str(line);
// Read fields
double hip(0.0), mag(0.0), ra(0.0), de(0.0);
line_str >> hip; line_str.get();
line_str >> mag; line_str.get();
line_str >> ra; line_str.get();
line_str >> de; line_str.get();
// Convert angles to radians
const double deg_to_rad = M_PI / 180.0;
cv::Mat catline = (cv::Mat_<float>(1,3) << mag, ra * deg_to_rad, de * deg_to_rad);
catalog.push_back(catline);
}
return catalog;
}
struct planetarium {
// Point spread function amplitude
double psf_amplitude;
// Point spread function b parameter
double psf_sigma;
// Max size of the spread to one side in pixels
// e.g. 1 means the square of pixels modified will be 3x3
double psf_spread_size;
// Screen
double screen_distance;
double screen_width;
double screen_height;
double screen_horizontal_pixel_size;
double screen_vertical_pixel_size;
// The value of a gaussian point spread function at a given distance
float psf_gaussian(float distance) {
return psf_amplitude * exp(-(distance*distance) / psf_sigma);
}
// Draw a star at given screen coordinates
// Uses a gaussian point spread function
void draw_star(cv::Mat image, float star_x, float star_y) {
// Closest discrete pixel to the star location
const int center_x = round(star_x);
const int center_y = round(star_y);
// For each pixel around the star
for (int x = center_x - psf_spread_size; x <= center_x + psf_spread_size; x++) {
for (int y = center_y - psf_spread_size; y <= center_y + psf_spread_size; y++) {
// Get the point spread function value at that distance from the star
float distance = sqrt(pow(star_x - x, 2) + pow(star_y - y, 2));
// If within bounds, add it to current value
if (y > 0 && x > 0 && y < image.rows && x < image.cols) {
image.at<float>(y,x) += psf_gaussian(distance);
}
}
}
}
// True if a (ra,de) coordinate is visible on the screen
bool is_star_visible(const double ra, const double de) {
const double max_ra = std::atan((screen_width * screen_horizontal_pixel_size) / (2*screen_distance));
const double max_de = std::atan((screen_height * screen_vertical_pixel_size) / (2*screen_distance));
// RA is in [0;2pi] but DE is in [-pi;pi]
return ra - M_PI > -max_ra && ra - M_PI < max_ra && de > -max_de && de < max_de;
}
void draw_visible_stars(cv::Mat image, cv::Mat catalog) {
// For each entry in the catalog
for (int i = 0; i < catalog.rows; i++) {
const double ra = catalog.at<float>(i, 1);
const double de = catalog.at<float>(i, 2);
// If star is visible
if (is_star_visible(ra, de)) {
const double x = screen_distance * tan(ra);
const double y = screen_distance * tan(de);
// Convert between:
// Origin in the center, (x,y) in meters
// Origin in the corner, (x_screen,y_screen) in pixels
const int x_screen = round(-x / screen_horizontal_pixel_size + screen_width / 2);
const int y_screen = round(-y / screen_vertical_pixel_size + screen_height / 2);
draw_star(image, x_screen, y_screen);
}
}
}
};
int main() {
cv::namedWindow("Planetarium", cv::WINDOW_AUTOSIZE);
// Black background
cv::Mat image(600, 800, CV_32FC1);
planetarium wall;
wall.psf_amplitude = 1.0;
wall.psf_sigma = 1.0;
wall.psf_spread_size = 5;
wall.screen_distance = .3;
wall.screen_width = 800;
wall.screen_height = 600;
wall.screen_horizontal_pixel_size = 0.0002 ;
wall.screen_vertical_pixel_size = 0.0002;
// Load star catalog
cv::Mat catalog = load_catalog("../hip5.tsv");
wall.draw_visible_stars(image, catalog);
// Threshold to 1.0
cv::threshold(image, image, 1.0, 0.0, cv::THRESH_TRUNC);
int k;
while((k = cvWaitKey(5)) != 27) {
cv::imshow("Planetarium", image);
if (k != -1) {
std::cout << k << std::endl;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680)
#define XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <algorithm>
#include <map>
#include <XalanDOM/XalanDOMString.hpp>
#include <PlatformSupport/STLHelper.hpp>
#include <XPath/Function.hpp>
#include <XPath/XPathException.hpp>
/**
* Exception class thrown when an unknown function is encountered
*/
class XALAN_XPATH_EXPORT XPathExceptionFunctionNotAvailable : public XPathException
{
public:
XPathExceptionFunctionNotAvailable(
int theFunctionName,
const XalanNode* styleNode = 0);
XPathExceptionFunctionNotAvailable(
const XalanDOMString& theFunctionName,
const XalanNode* styleNode = 0);
~XPathExceptionFunctionNotAvailable();
};
/**
* Class defines a table of functions that can be called in XPath expresions.
*/
class XALAN_XPATH_EXPORT XPathFunctionTable
{
public:
#if defined(XALAN_NO_NAMESPACES)
typedef vector<Function*> CollectionType;
typedef map<XalanDOMString,
int,
less<XalanDOMString> > FunctionNameIndexMapType;
#else
typedef std::vector<Function*> CollectionType;
typedef std::map<XalanDOMString, int> FunctionNameIndexMapType;
#endif
typedef DeleteFunctor<Function> DeleteFunctorType;
/**
* Constructor.
*
* @param fCreateTable If true, the internal table will be created. Otherwise, CreateTable() must be called.
*/
XPathFunctionTable(bool fCreateTable = true);
~XPathFunctionTable();
/**
* Set up the internal table.
*/
void
CreateTable();
/**
* Destroy the internal table.
*/
void
DestroyTable();
/**
* Retrieve the function object for a specified function name.
*
* @param theFunctionName name of function
* @return function named
*/
Function&
operator[](const XalanDOMString& theFunctionName) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.find(theFunctionName);
if (i != m_FunctionNameIndex.end())
{
return *m_FunctionCollection[(*i).second];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionName);
}
}
/**
* Retrieve the function object for a specified function ID number.
*
* @param theFunctionID ID number of the function
* @return function named
*/
Function&
operator[](int theFunctionID) const
{
if (theFunctionID >= 0 &&
CollectionType::size_type(theFunctionID) < m_FunctionCollection.size())
{
return *m_FunctionCollection[theFunctionID];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionID);
}
}
enum { InvalidFunctionNumberID = -1 };
/**
* Map a function ID to the corresponding name.
*
* @param theFunctionID The ID number of the function
* @return The name of the function, or an empty string if the function doesn't exist.
*/
const XalanDOMString
idToName(int theFunctionID) const
{
XalanDOMString theName;
if (theFunctionID >= 0 &&
CollectionType::size_type(theFunctionID) < m_FunctionCollection.size())
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while (i != m_FunctionNameIndex.end())
{
if ((*i).second == theFunctionID)
{
theName = (*i).first;
break;
}
}
}
return theName;
}
/**
* Map a function name to the corresponding ID number.
*
* @param theName name of function
* @return The ID number of function, or InvalidFunctionNumberID if the function doesn't exist.
*/
int
nameToID(const XalanDOMString& theName) const
{
const FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.find(theName);
if (i != m_FunctionNameIndex.end())
{
return (*i).second;
}
else
{
return InvalidFunctionNumberID;
}
}
/**
* Insert a named function into the function table.
*
* @param theFunctionName name of function
* @param theFunction function object corresponding to name
*/
void
InstallFunction(
const XalanDOMString& theFunctionName,
const Function& theFunction);
/**
* Remove a named function from the function table.
*
* @param theFunctionName name of function
* @return true if the function was found and removed.
*/
bool
UninstallFunction(const XalanDOMString& theFunctionName);
/**
* Whether a named function is in the function table.
*
* @param theFunctionName name of function
* @return true if function is in table
*/
bool
isInstalledFunction(const XalanDOMString& theFunctionName) const
{
if (m_FunctionNameIndex.find(theFunctionName) != m_FunctionNameIndex.end())
{
return true;
}
else
{
return false;
}
}
#if defined(XALAN_NO_MEMBER_TEMPLATES)
typedef vector<XalanDOMString> InstalledFunctionNameVectorType;
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theVector vector of function name strings added to
*/
void
getInstalledFunctionNames(InstalledFunctionNameVectorType& theVector) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while(i != m_FunctionNameIndex.end())
{
theVector.push_back((*i).first);
++i;
}
}
#else
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theIterator function table iterator to append names to
*/
template<class OutputIteratorType>
void
getInstalledFunctionNames(OutputIteratorType theIterator) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while(i != m_FunctionNameIndex.end())
{
*theIterator = (*i).first;
++i;
++theIterator;
}
}
#endif
private:
CollectionType m_FunctionCollection;
FunctionNameIndexMapType m_FunctionNameIndex;
};
#endif // XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
<commit_msg>Added #ifdef XALAN_NO_NAMESPACES.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680)
#define XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <algorithm>
#include <map>
#include <XalanDOM/XalanDOMString.hpp>
#include <PlatformSupport/STLHelper.hpp>
#include <XPath/Function.hpp>
#include <XPath/XPathException.hpp>
/**
* Exception class thrown when an unknown function is encountered
*/
class XALAN_XPATH_EXPORT XPathExceptionFunctionNotAvailable : public XPathException
{
public:
XPathExceptionFunctionNotAvailable(
int theFunctionName,
const XalanNode* styleNode = 0);
XPathExceptionFunctionNotAvailable(
const XalanDOMString& theFunctionName,
const XalanNode* styleNode = 0);
~XPathExceptionFunctionNotAvailable();
};
/**
* Class defines a table of functions that can be called in XPath expresions.
*/
class XALAN_XPATH_EXPORT XPathFunctionTable
{
public:
#if defined(XALAN_NO_NAMESPACES)
typedef vector<Function*> CollectionType;
typedef map<XalanDOMString,
int,
less<XalanDOMString> > FunctionNameIndexMapType;
#else
typedef std::vector<Function*> CollectionType;
typedef std::map<XalanDOMString, int> FunctionNameIndexMapType;
#endif
typedef DeleteFunctor<Function> DeleteFunctorType;
/**
* Constructor.
*
* @param fCreateTable If true, the internal table will be created. Otherwise, CreateTable() must be called.
*/
XPathFunctionTable(bool fCreateTable = true);
~XPathFunctionTable();
/**
* Set up the internal table.
*/
void
CreateTable();
/**
* Destroy the internal table.
*/
void
DestroyTable();
/**
* Retrieve the function object for a specified function name.
*
* @param theFunctionName name of function
* @return function named
*/
Function&
operator[](const XalanDOMString& theFunctionName) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.find(theFunctionName);
if (i != m_FunctionNameIndex.end())
{
return *m_FunctionCollection[(*i).second];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionName);
}
}
/**
* Retrieve the function object for a specified function ID number.
*
* @param theFunctionID ID number of the function
* @return function named
*/
Function&
operator[](int theFunctionID) const
{
if (theFunctionID >= 0 &&
CollectionType::size_type(theFunctionID) < m_FunctionCollection.size())
{
return *m_FunctionCollection[theFunctionID];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionID);
}
}
enum { InvalidFunctionNumberID = -1 };
/**
* Map a function ID to the corresponding name.
*
* @param theFunctionID The ID number of the function
* @return The name of the function, or an empty string if the function doesn't exist.
*/
const XalanDOMString
idToName(int theFunctionID) const
{
XalanDOMString theName;
if (theFunctionID >= 0 &&
CollectionType::size_type(theFunctionID) < m_FunctionCollection.size())
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while (i != m_FunctionNameIndex.end())
{
if ((*i).second == theFunctionID)
{
theName = (*i).first;
break;
}
}
}
return theName;
}
/**
* Map a function name to the corresponding ID number.
*
* @param theName name of function
* @return The ID number of function, or InvalidFunctionNumberID if the function doesn't exist.
*/
int
nameToID(const XalanDOMString& theName) const
{
const FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.find(theName);
if (i != m_FunctionNameIndex.end())
{
return (*i).second;
}
else
{
return InvalidFunctionNumberID;
}
}
/**
* Insert a named function into the function table.
*
* @param theFunctionName name of function
* @param theFunction function object corresponding to name
*/
void
InstallFunction(
const XalanDOMString& theFunctionName,
const Function& theFunction);
/**
* Remove a named function from the function table.
*
* @param theFunctionName name of function
* @return true if the function was found and removed.
*/
bool
UninstallFunction(const XalanDOMString& theFunctionName);
/**
* Whether a named function is in the function table.
*
* @param theFunctionName name of function
* @return true if function is in table
*/
bool
isInstalledFunction(const XalanDOMString& theFunctionName) const
{
if (m_FunctionNameIndex.find(theFunctionName) != m_FunctionNameIndex.end())
{
return true;
}
else
{
return false;
}
}
#if defined(XALAN_NO_MEMBER_TEMPLATES)
#if defined(XALAN_NO_NAMESPACES)
typedef vector<XalanDOMString> InstalledFunctionNameVectorType;
#else
typedef std::vector<XalanDOMString> InstalledFunctionNameVectorType;
#endif
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theVector vector of function name strings added to
*/
void
getInstalledFunctionNames(InstalledFunctionNameVectorType& theVector) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while(i != m_FunctionNameIndex.end())
{
theVector.push_back((*i).first);
++i;
}
}
#else
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theIterator function table iterator to append names to
*/
template<class OutputIteratorType>
void
getInstalledFunctionNames(OutputIteratorType theIterator) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while(i != m_FunctionNameIndex.end())
{
*theIterator = (*i).first;
++i;
++theIterator;
}
}
#endif
private:
CollectionType m_FunctionCollection;
FunctionNameIndexMapType m_FunctionNameIndex;
};
#endif // XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
<|endoftext|>
|
<commit_before>#include "drake/systems/plants/RigidBodySystem.h"
#include <iostream>
#include <gtest/gtest.h>
#include "drake/systems/plants/RigidBodyFrame.h"
#include "drake/util/eigen_matrix_compare.h"
#include "drake/util/testUtil.h"
using std::make_shared;
using Drake::RigidBodySystem;
using Eigen::VectorXd;
using drake::util::MatrixCompareType;
namespace drake {
namespace systems {
namespace plants {
namespace {
std::string model_file_1, model_file_2;
std::shared_ptr<RigidBodyFrame> car_pose_in_world;
TEST(CompareRigidBodySystemsTest, TestAll) {
auto r1 = make_shared<RigidBodySystem>();
r1->addRobotFromFile(model_file_1, DrakeJoint::QUATERNION);
auto r2 = make_shared<RigidBodySystem>();
r2->addRobotFromFile(model_file_2, DrakeJoint::QUATERNION, car_pose_in_world);
// for debugging:
// r1->getRigidBodyTree()->drawKinematicTree("/tmp/r1.dot");
// r2->getRigidBodyTree()->drawKinematicTree("/tmp/r2.dot");
// I ran this at the console to see the output:
// dot -Tpng -O /tmp/r1.dot; dot -Tpng -O /tmp/r2.dot; open /tmp/r1.dot.png
// /tmp/r2.dot.png
EXPECT_EQ(r1->getNumStates(), r2->getNumStates());
EXPECT_EQ(r1->getNumInputs(), r2->getNumInputs());
EXPECT_EQ(r1->getNumOutputs(), r2->getNumOutputs());
for (int i = 0; i < 1000; i++) {
double t = 0.0;
VectorXd x = getInitialState(*r1);
VectorXd u = VectorXd::Random(r1->getNumInputs());
auto xdot1 = r1->dynamics(t, x, u);
auto xdot2 = r2->dynamics(t, x, u);
std::string explanation;
EXPECT_TRUE(
drake::util::CompareMatrices(xdot1, xdot2, 1e-8, MatrixCompareType::absolute, &explanation))
<< "Model mismatch!" << std::endl
<< " - initial state:" << std::endl
<< x << std::endl
<< " - inputs (joint torques?):" << std::endl
<< u << std::endl
<< " - xdot1:" << std::endl
<< xdot1.transpose() << std::endl
<< " - xdot2:" << std::endl
<< xdot2.transpose() << std::endl
<< " - error message:" << std::endl
<< explanation;
}
}
} // namespace
} // namespace plants
} // namespace systems
} // namespace drake
int main(int argc, char **argv) {
std::cout << "Running main() from compareRigidBodySystems.cpp" << std::endl;
// ::testing::GTEST_FLAG(output) = "xml:hello.xml";
std::cout << "Calling testing::InitGoogleTest(...)" << std::endl;
testing::InitGoogleTest(&argc, argv);
std::cout << "argc = " << argc << std::endl;
if (argc < 3) {
std::cerr << "Usage: " << argv[0]
<< " [options] full_path_to_robot1 full_path_to_robot2 x y z\n"
<< " The x y z parameters are optional and specify the position"
<< " of robot2 in the world, which is useful for URDF"
<< " models)" << std::endl;
return 1;
}
drake::systems::plants::model_file_1 = argv[1];
drake::systems::plants::model_file_2 = argv[2];
if (argc > 3) {
drake::systems::plants::car_pose_in_world = std::allocate_shared<RigidBodyFrame>(
Eigen::aligned_allocator<RigidBodyFrame>(), "world",
nullptr, // not used since the robot is attached to the world
Eigen::Vector3d(std::stod(argv[3]), std::stod(argv[4]),
std::stod(argv[5])), // xyz of the car's root link
Eigen::Vector3d(0, 0, 0)); // rpy of the car's root link
} else {
drake::systems::plants::car_pose_in_world = std::allocate_shared<RigidBodyFrame>(
Eigen::aligned_allocator<RigidBodyFrame>(), "world", nullptr,
Eigen::Isometry3d::Identity());
}
return RUN_ALL_TESTS();
}<commit_msg>Ran clang-format.<commit_after>#include "drake/systems/plants/RigidBodySystem.h"
#include <iostream>
#include <gtest/gtest.h>
#include "drake/systems/plants/RigidBodyFrame.h"
#include "drake/util/eigen_matrix_compare.h"
#include "drake/util/testUtil.h"
using std::make_shared;
using Drake::RigidBodySystem;
using Eigen::VectorXd;
using drake::util::MatrixCompareType;
namespace drake {
namespace systems {
namespace plants {
namespace {
std::string model_file_1, model_file_2;
std::shared_ptr<RigidBodyFrame> car_pose_in_world;
TEST(CompareRigidBodySystemsTest, TestAll) {
auto r1 = make_shared<RigidBodySystem>();
r1->addRobotFromFile(model_file_1, DrakeJoint::QUATERNION);
auto r2 = make_shared<RigidBodySystem>();
r2->addRobotFromFile(model_file_2, DrakeJoint::QUATERNION, car_pose_in_world);
// for debugging:
// r1->getRigidBodyTree()->drawKinematicTree("/tmp/r1.dot");
// r2->getRigidBodyTree()->drawKinematicTree("/tmp/r2.dot");
// I ran this at the console to see the output:
// dot -Tpng -O /tmp/r1.dot; dot -Tpng -O /tmp/r2.dot; open /tmp/r1.dot.png
// /tmp/r2.dot.png
EXPECT_EQ(r1->getNumStates(), r2->getNumStates());
EXPECT_EQ(r1->getNumInputs(), r2->getNumInputs());
EXPECT_EQ(r1->getNumOutputs(), r2->getNumOutputs());
for (int i = 0; i < 1000; i++) {
double t = 0.0;
VectorXd x = getInitialState(*r1);
VectorXd u = VectorXd::Random(r1->getNumInputs());
auto xdot1 = r1->dynamics(t, x, u);
auto xdot2 = r2->dynamics(t, x, u);
std::string explanation;
EXPECT_TRUE(drake::util::CompareMatrices(
xdot1, xdot2, 1e-8, MatrixCompareType::absolute, &explanation))
<< "Model mismatch!" << std::endl
<< " - initial state:" << std::endl
<< x << std::endl
<< " - inputs (joint torques?):" << std::endl
<< u << std::endl
<< " - xdot1:" << std::endl
<< xdot1.transpose() << std::endl
<< " - xdot2:" << std::endl
<< xdot2.transpose() << std::endl
<< " - error message:" << std::endl
<< explanation;
}
}
} // namespace
} // namespace plants
} // namespace systems
} // namespace drake
int main(int argc, char **argv) {
std::cout << "Running main() from compareRigidBodySystems.cpp" << std::endl;
// ::testing::GTEST_FLAG(output) = "xml:hello.xml";
std::cout << "Calling testing::InitGoogleTest(...)" << std::endl;
testing::InitGoogleTest(&argc, argv);
std::cout << "argc = " << argc << std::endl;
if (argc < 3) {
std::cerr << "Usage: " << argv[0]
<< " [options] full_path_to_robot1 full_path_to_robot2 x y z\n"
<< " The x y z parameters are optional and specify the position"
<< " of robot2 in the world, which is useful for URDF"
<< " models)" << std::endl;
return 1;
}
drake::systems::plants::model_file_1 = argv[1];
drake::systems::plants::model_file_2 = argv[2];
if (argc > 3) {
drake::systems::plants::car_pose_in_world =
std::allocate_shared<RigidBodyFrame>(
Eigen::aligned_allocator<RigidBodyFrame>(), "world",
nullptr, // not used since the robot is attached to the world
Eigen::Vector3d(std::stod(argv[3]), std::stod(argv[4]),
std::stod(argv[5])), // xyz of the car's root link
Eigen::Vector3d(0, 0, 0)); // rpy of the car's root link
} else {
drake::systems::plants::car_pose_in_world =
std::allocate_shared<RigidBodyFrame>(
Eigen::aligned_allocator<RigidBodyFrame>(), "world", nullptr,
Eigen::Isometry3d::Identity());
}
return RUN_ALL_TESTS();
}<|endoftext|>
|
<commit_before>// Copyright (C) 2013 Robert Giseburt <giseburt@gmail.com>
// serialport_poller.cpp Written as a part of https://github.com/voodootikigod/node-serialport
// License to use this is the same as that of node-serialport.
#include <nan.h>
#include "./serialport_poller.h"
using namespace v8;
static Nan::Persistent<v8::FunctionTemplate> serialportpoller_constructor;
SerialportPoller::SerialportPoller() : Nan::ObjectWrap() {}
SerialportPoller::~SerialportPoller() {
// printf("~SerialportPoller\n");
delete callback_;
}
void _serialportReadable(uv_poll_t *req, int status, int events) {
SerialportPoller* sp = (SerialportPoller*) req->data;
// We can stop polling until we have read all of the data...
sp->_stop();
sp->callCallback(status);
}
void SerialportPoller::callCallback(int status) {
Nan::HandleScope scope;
// uv_work_t* req = new uv_work_t;
// Call the callback to go read more data...
v8::Local<v8::Value> argv[1];
if (status != 0) {
// error handling changed in libuv, see:
// https://github.com/joyent/libuv/commit/3ee4d3f183331
#ifdef UV_ERRNO_H_
const char* err_string = uv_strerror(status);
#else
uv_err_t errno = uv_last_error(uv_default_loop());
const char* err_string = uv_strerror(errno);
#endif
snprintf(this->errorString, sizeof(this->errorString), "Error %s on polling", err_string);
argv[0] = v8::Exception::Error(Nan::New<v8::String>(this->errorString).ToLocalChecked());
} else {
argv[0] = Nan::Undefined();
}
callback_->Call(1, argv);
}
void SerialportPoller::Init(Handle<Object> target) {
Nan::HandleScope scope;
// Prepare constructor template
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New<String>("SerialportPoller").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
// SerialportPoller.close()
Nan::SetPrototypeTemplate(tpl, "close",
Nan::GetFunction(Nan::New<FunctionTemplate>(Close)).ToLocalChecked());
// SerialportPoller.start()
Nan::SetPrototypeTemplate(tpl, "start",
Nan::GetFunction(Nan::New<FunctionTemplate>(Start)).ToLocalChecked());
serialportpoller_constructor.Reset(tpl);
Nan::Set(target, Nan::New<String>("SerialportPoller").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
}
NAN_METHOD(SerialportPoller::New) {
if (!info[0]->IsInt32()) {
Nan::ThrowTypeError("First argument must be an fd");
return;
}
if (!info[1]->IsFunction()) {
Nan::ThrowTypeError("Third argument must be a function");
return;
}
SerialportPoller* obj = new SerialportPoller();
obj->fd_ = info[0]->ToInt32()->Int32Value();
obj->callback_ = new Nan::Callback(info[1].As<v8::Function>());
// obj->callCallback();
obj->Wrap(info.This());
obj->poll_handle_.data = obj;
uv_poll_init(uv_default_loop(), &obj->poll_handle_, obj->fd_);
uv_poll_start(&obj->poll_handle_, UV_READABLE, _serialportReadable);
info.GetReturnValue().Set(info.This());
}
void SerialportPoller::_start() {
uv_poll_start(&poll_handle_, UV_READABLE, _serialportReadable);
}
void SerialportPoller::_stop() {
uv_poll_stop(&poll_handle_);
}
NAN_METHOD(SerialportPoller::Start) {
SerialportPoller* obj = Nan::ObjectWrap::Unwrap<SerialportPoller>(info.This());
obj->_start();
return;
}
NAN_METHOD(SerialportPoller::Close) {
SerialportPoller* obj = Nan::ObjectWrap::Unwrap<SerialportPoller>(info.This());
obj->_stop();
// DO SOMETHING!
return;
}
<commit_msg>Avoid deprecation warnings<commit_after>// Copyright (C) 2013 Robert Giseburt <giseburt@gmail.com>
// serialport_poller.cpp Written as a part of https://github.com/voodootikigod/node-serialport
// License to use this is the same as that of node-serialport.
#include <nan.h>
#include "./serialport_poller.h"
using namespace v8;
static Nan::Persistent<v8::FunctionTemplate> serialportpoller_constructor;
SerialportPoller::SerialportPoller() : Nan::ObjectWrap() {}
SerialportPoller::~SerialportPoller() {
// printf("~SerialportPoller\n");
delete callback_;
}
void _serialportReadable(uv_poll_t *req, int status, int events) {
SerialportPoller* sp = (SerialportPoller*) req->data;
// We can stop polling until we have read all of the data...
sp->_stop();
sp->callCallback(status);
}
void SerialportPoller::callCallback(int status) {
Nan::HandleScope scope;
// uv_work_t* req = new uv_work_t;
// Call the callback to go read more data...
v8::Local<v8::Value> argv[1];
if (status != 0) {
// error handling changed in libuv, see:
// https://github.com/joyent/libuv/commit/3ee4d3f183331
#ifdef UV_ERRNO_H_
const char* err_string = uv_strerror(status);
#else
uv_err_t errno = uv_last_error(uv_default_loop());
const char* err_string = uv_strerror(errno);
#endif
snprintf(this->errorString, sizeof(this->errorString), "Error %s on polling", err_string);
argv[0] = v8::Exception::Error(Nan::New<v8::String>(this->errorString).ToLocalChecked());
} else {
argv[0] = Nan::Undefined();
}
callback_->Call(1, argv);
}
void SerialportPoller::Init(Handle<Object> target) {
Nan::HandleScope scope;
// Prepare constructor template
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New<String>("SerialportPoller").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
// SerialportPoller.close()
Nan::SetPrototypeMethod(tpl, "close", Close);
// SerialportPoller.start()
Nan::SetPrototypeMethod(tpl, "start", Start);
serialportpoller_constructor.Reset(tpl);
Nan::Set(target, Nan::New<String>("SerialportPoller").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
}
NAN_METHOD(SerialportPoller::New) {
if (!info[0]->IsInt32()) {
Nan::ThrowTypeError("First argument must be an fd");
return;
}
if (!info[1]->IsFunction()) {
Nan::ThrowTypeError("Third argument must be a function");
return;
}
SerialportPoller* obj = new SerialportPoller();
obj->fd_ = info[0]->ToInt32()->Int32Value();
obj->callback_ = new Nan::Callback(info[1].As<v8::Function>());
// obj->callCallback();
obj->Wrap(info.This());
obj->poll_handle_.data = obj;
uv_poll_init(uv_default_loop(), &obj->poll_handle_, obj->fd_);
uv_poll_start(&obj->poll_handle_, UV_READABLE, _serialportReadable);
info.GetReturnValue().Set(info.This());
}
void SerialportPoller::_start() {
uv_poll_start(&poll_handle_, UV_READABLE, _serialportReadable);
}
void SerialportPoller::_stop() {
uv_poll_stop(&poll_handle_);
}
NAN_METHOD(SerialportPoller::Start) {
SerialportPoller* obj = Nan::ObjectWrap::Unwrap<SerialportPoller>(info.This());
obj->_start();
return;
}
NAN_METHOD(SerialportPoller::Close) {
SerialportPoller* obj = Nan::ObjectWrap::Unwrap<SerialportPoller>(info.This());
obj->_stop();
// DO SOMETHING!
return;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: taskcreatorsrv.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2008-03-05 17:21:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_SERVICES_TASKCREATORSRV_HXX_
#define __FRAMEWORK_SERVICES_TASKCREATORSRV_HXX_
//_______________________________________________
// own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
//_______________________________________________
// other includes
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX_
#include <comphelper/sequenceashashmap.hxx>
#endif
//_______________________________________________
// definition
namespace framework
{
//_______________________________________________
/**
* TODO document me
*/
class TaskCreatorService : public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::lang::XSingleServiceFactory
// attention! Must be the first base class to guarentee right initialize lock ...
, private ThreadHelpBase
, public ::cppu::OWeakObject
{
//___________________________________________
// types
public:
/// [XFrame] if it's set, it will be used as parent frame for the new created frame.
static const ::rtl::OUString ARGUMENT_PARENTFRAME;
/** [OUString] if it's not a special name (beginning with "_" ... which are not allowed here!)
it will be set as the API name of the new created frame.
*/
static const ::rtl::OUString ARGUMENT_FRAMENAME;
/// [sal_Bool] If its set to TRUE we will make the new created frame visible.
static const ::rtl::OUString ARGUMENT_MAKEVISIBLE;
/** [sal_Bool] If not "ContainerWindow" property is set it force creation of a
top level window as new container window.
*/
static const ::rtl::OUString ARGUMENT_CREATETOPWINDOW;
/// [Rectangle] Place the new created frame on this place and resize the container window.
static const ::rtl::OUString ARGUMENT_POSSIZE;
/// [XWindow] an outside created window, used as container window of the new created frame.
static const ::rtl::OUString ARGUMENT_CONTAINERWINDOW;
/** [sal_Bool] enable/disable special mode, where this frame will be part of
the persistent window state feature suitable for any office module window
*/
static const ::rtl::OUString ARGUMENT_SUPPORTPERSISTENTWINDOWSTATE;
//___________________________________________
// member
private:
//---------------------------------------
/** @short the global uno service manager.
@descr Must be used to create own needed services.
*/
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
//___________________________________________
// interface
public:
TaskCreatorService(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
virtual ~TaskCreatorService( );
// XInterface, XTypeProvider, XServiceInfo
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XSingleServiceFactory
virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance()
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstanceWithArguments(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
//___________________________________________
// helper
private:
css::uno::Reference< css::awt::XWindow > implts_createContainerWindow( const css::uno::Reference< css::awt::XWindow >& xParentWindow ,
const css::awt::Rectangle& aPosSize ,
sal_Bool bTopWindow );
void implts_applyDocStyleToWindow(const css::uno::Reference< css::awt::XWindow >& xWindow) const;
css::uno::Reference< css::frame::XFrame > implts_createFrame( const css::uno::Reference< css::frame::XFrame >& xParentFrame ,
const css::uno::Reference< css::awt::XWindow >& xContainerWindow ,
const ::rtl::OUString& sName );
void implts_establishWindowStateListener( const css::uno::Reference< css::frame::XFrame >& xFrame );
void implts_establishDocModifyListener( const css::uno::Reference< css::frame::XFrame >& xFrame );
::rtl::OUString impl_filterNames( const ::rtl::OUString& sName );
};
} // namespace framework
#endif // __FRAMEWORK_SERVICES_TASKCREATORSRV_HXX_
<commit_msg>INTEGRATION: CWS titles02 (1.3.82); FILE MERGED 2008/02/12 13:27:18 as 1.3.82.2: RESYNC: (1.3-1.4); FILE MERGED 2007/10/12 13:06:37 as 1.3.82.1: #116375# support new title feature<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: taskcreatorsrv.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2008-04-04 14:10:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_SERVICES_TASKCREATORSRV_HXX_
#define __FRAMEWORK_SERVICES_TASKCREATORSRV_HXX_
//_______________________________________________
// own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
//_______________________________________________
// other includes
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX_
#include <comphelper/sequenceashashmap.hxx>
#endif
//_______________________________________________
// definition
namespace framework
{
//_______________________________________________
/**
* TODO document me
*/
class TaskCreatorService : public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::lang::XSingleServiceFactory
// attention! Must be the first base class to guarentee right initialize lock ...
, private ThreadHelpBase
, public ::cppu::OWeakObject
{
//___________________________________________
// types
public:
/// [XFrame] if it's set, it will be used as parent frame for the new created frame.
static const ::rtl::OUString ARGUMENT_PARENTFRAME;
/** [OUString] if it's not a special name (beginning with "_" ... which are not allowed here!)
it will be set as the API name of the new created frame.
*/
static const ::rtl::OUString ARGUMENT_FRAMENAME;
/// [sal_Bool] If its set to TRUE we will make the new created frame visible.
static const ::rtl::OUString ARGUMENT_MAKEVISIBLE;
/** [sal_Bool] If not "ContainerWindow" property is set it force creation of a
top level window as new container window.
*/
static const ::rtl::OUString ARGUMENT_CREATETOPWINDOW;
/// [Rectangle] Place the new created frame on this place and resize the container window.
static const ::rtl::OUString ARGUMENT_POSSIZE;
/// [XWindow] an outside created window, used as container window of the new created frame.
static const ::rtl::OUString ARGUMENT_CONTAINERWINDOW;
/** [sal_Bool] enable/disable special mode, where this frame will be part of
the persistent window state feature suitable for any office module window
*/
static const ::rtl::OUString ARGUMENT_SUPPORTPERSISTENTWINDOWSTATE;
/** [sal_Bool] enable/disable special mode, where the title bar of our
the new created frame will be updated automaticly.
Default = ON !
*/
static const ::rtl::OUString ARGUMENT_ENABLE_TITLEBARUPDATE;
//___________________________________________
// member
private:
//---------------------------------------
/** @short the global uno service manager.
@descr Must be used to create own needed services.
*/
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
//___________________________________________
// interface
public:
TaskCreatorService(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
virtual ~TaskCreatorService( );
// XInterface, XTypeProvider, XServiceInfo
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XSingleServiceFactory
virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance()
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstanceWithArguments(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
//___________________________________________
// helper
private:
css::uno::Reference< css::awt::XWindow > implts_createContainerWindow( const css::uno::Reference< css::awt::XWindow >& xParentWindow ,
const css::awt::Rectangle& aPosSize ,
sal_Bool bTopWindow );
void implts_applyDocStyleToWindow(const css::uno::Reference< css::awt::XWindow >& xWindow) const;
css::uno::Reference< css::frame::XFrame > implts_createFrame( const css::uno::Reference< css::frame::XFrame >& xParentFrame ,
const css::uno::Reference< css::awt::XWindow >& xContainerWindow ,
const ::rtl::OUString& sName );
void implts_establishWindowStateListener( const css::uno::Reference< css::frame::XFrame >& xFrame );
void implts_establishTitleBarUpdate( const css::uno::Reference< css::frame::XFrame >& xFrame );
void implts_establishDocModifyListener( const css::uno::Reference< css::frame::XFrame >& xFrame );
::rtl::OUString impl_filterNames( const ::rtl::OUString& sName );
};
} // namespace framework
#endif // __FRAMEWORK_SERVICES_TASKCREATORSRV_HXX_
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Messages.h"
Messages::Messages()
{
}
Messages::~Messages()
{
}
/**
* \brief remove all the completed on screen messages.
*/
void Messages::ClearUnused()
{
while (_collection.size() > 0)
{
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
const auto it = _collection.begin();
if (it == _collection.end())
{
break;
}
const auto dlg = static_cast<MessageDlg*>(*it);
if (dlg != nullptr)
{
if (dlg->IsRunning())
{
break;
}
}
// otherwise we can remove it from the list
_collection.erase(it);
}
}
/**
* \brief display a message
* \param wsText the message we want to display
* \param nElapse how long we want to display the message for.
* \param nFadeOut where we want to fade the window from.
* \return if we were able to display the message or not.
*/
bool Messages::Show(const std::wstring& wsText, const int nElapse, const int nFadeOut)
{
// Sanity check
if (wsText.length() == 0)
{
return false;
}
// look for old messages to remove
ClearUnused();
try
{
const auto messageDlg = new MessageDlg();
messageDlg->Create(wsText, nElapse, nFadeOut);
// start the fade message and pass a lambda
// function so we are called back when the window is deleted
// this is so we can remove it from our list here.
messageDlg->FadeShowWindow([&](CWnd* dlg)
{
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
// look for the window we want to delete.
const auto saved = std::find(_collection.begin(), _collection.end(), dlg);
if (saved != _collection.end())
{
// remove it from the list
_collection.erase(saved);
}
});
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
// add it to our list of messages.
_collection.push_back(messageDlg);
return true;
}
catch( ... )
{
return false;
}
}
/**
* \brief Kill all the currently active message windows.
*/
void Messages::KillAll()
{
// remove what is complete.
ClearUnused();
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
// kill the other messages;
for (auto it = _collection.begin();
it != _collection.end();
++it)
{
// clear what is still good.
const auto dlg = static_cast<MessageDlg*>(*it);
if (dlg != nullptr)
{
dlg->FadeKillWindow();
}
}
// now that we asked for windows to be closed.
// we can wait for them to close.
WaitForAllToComplete();
}
/**
* \brief Wait for all the active windows to complete.
*/
void Messages::WaitForAllToComplete()
{
// Wait for pending messages
// we try and get the parent window
// and if we cannot locate it, then it must be because the window no longer exists
// and as such we must wait for it.
while (true)
{
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
auto it = _collection.begin();
if (it == _collection.end())
break;
const auto dlg = static_cast<MessageDlg*>(*it);
if (dlg != nullptr)
{
// then try and process the remaining messages
// if the window has not been killed properly.
const auto hWnd = dlg->GetSafeHwnd();
if (0 != ::GetWindowLongPtr(hWnd, GWLP_HWNDPARENT))
{
// give the other apps/classes one last chance to do some work.
MessagePump(nullptr);
// let go of the thread.
std::this_thread::yield();
Sleep(1);
// just do one message at a time
// so we don't block others.
// the peek message should allow all message to be handled
MessagePump(hWnd);
// go around one last time
// to give everyone a chance to close.
continue;
}
}
// otherwise we can remove it
_collection.erase(it);
}
}
/**
* \brief pump all the messages for a given window.
* \param hWnd the handle of the window messages we are pumping.
*/
void Messages::MessagePump(const HWND hWnd)
{
// lock up to make sure we only do one at a time
MSG msg;
while (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (0 == ::GetWindowLongPtr(hWnd, GWLP_HWNDPARENT))
{
break;
}
}
}
<commit_msg>Some cleanup<commit_after>#include "stdafx.h"
#include "Messages.h"
Messages::Messages()
{
}
Messages::~Messages()
{
}
/**
* \brief remove all the completed on screen messages.
*/
void Messages::ClearUnused()
{
while (_collection.size() > 0)
{
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
const auto it = _collection.begin();
if (it == _collection.end())
{
break;
}
const auto dlg = static_cast<MessageDlg*>(*it);
if (dlg != nullptr)
{
if (dlg->IsRunning())
{
break;
}
}
// otherwise we can remove it from the list
_collection.erase(it);
}
}
/**
* \brief display a message
* \param wsText the message we want to display
* \param nElapse how long we want to display the message for.
* \param nFadeOut where we want to fade the window from.
* \return if we were able to display the message or not.
*/
bool Messages::Show(const std::wstring& wsText, const int nElapse, const int nFadeOut)
{
// Sanity check
if (wsText.length() == 0)
{
return false;
}
// look for old messages to remove
ClearUnused();
try
{
const auto messageDlg = new MessageDlg();
messageDlg->Create(wsText, nElapse, nFadeOut);
// start the fade message and pass a lambda
// function so we are called back when the window is deleted
// this is so we can remove it from our list here.
messageDlg->FadeShowWindow([&](CWnd* dlg)
{
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
// look for the window we want to delete.
const auto saved = std::find(_collection.begin(), _collection.end(), dlg);
if (saved != _collection.end())
{
// remove it from the list
_collection.erase(saved);
}
});
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
// add it to our list of messages.
_collection.push_back(messageDlg);
return true;
}
catch( ... )
{
return false;
}
}
/**
* \brief Kill all the currently active message windows.
*/
void Messages::KillAll()
{
// remove what is complete.
ClearUnused();
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
// kill the other messages;
for (auto it = _collection.begin();
it != _collection.end();
++it)
{
// clear what is still good.
const auto dlg = static_cast<MessageDlg*>(*it);
if (dlg != nullptr)
{
dlg->FadeKillWindow();
}
}
// now that we asked for windows to be closed.
// we can wait for them to close.
WaitForAllToComplete();
}
/**
* \brief Wait for all the active windows to complete.
*/
void Messages::WaitForAllToComplete()
{
// Wait for pending messages
// we try and get the parent window
// and if we cannot locate it, then it must be because the window no longer exists
// and as such we must wait for it.
while (true)
{
// protected the vector for a short while.
myodd::threads::Lock guard(_mutex);
auto it = _collection.begin();
if (it == _collection.end())
break;
const auto dlg = static_cast<MessageDlg*>(*it);
if (dlg != nullptr)
{
if (dlg->IsRunning())
{
// then try and process the remaining messages
// if the window has not been killed properly.
const auto hWnd = dlg->GetSafeHwnd();
if (0 != ::GetWindowLongPtr(hWnd, GWLP_HWNDPARENT))
{
// give the other apps/classes one last chance to do some work.
MessagePump(nullptr);
// let go of the thread.
std::this_thread::yield();
Sleep(1);
// just do one message at a time
// so we don't block others.
// the peek message should allow all message to be handled
MessagePump(hWnd);
// go around one last time
// to give everyone a chance to close.
continue;
}
}
}
// otherwise we can remove it
_collection.erase(it);
}
}
/**
* \brief pump all the messages for a given window.
* \param hWnd the handle of the window messages we are pumping.
*/
void Messages::MessagePump(const HWND hWnd)
{
// lock up to make sure we only do one at a time
MSG msg;
while (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (0 == ::GetWindowLongPtr(hWnd, GWLP_HWNDPARENT))
{
break;
}
}
}
<|endoftext|>
|
<commit_before>
// Standard C++ includes
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <assert.h>
#include <float.h>
#include <math.h>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
//return 9 cameras
// Public interface of the MySQL Connector/C++
#include <cppconn/mysql_public_iface.h>
//
#include "hClustering.h"
#include "preProcessing.h"
using namespace std;
int main(int argc, char** argv){
stringstream sql;
int clusterN;
int conFeatureN;
int catFeatureN;
int boolFeatureN;
int varNamesN;
int range;
int layer = 1;
string var;
//argument is the productName
string productName = argv[1];
string tableName = productName;
tableName.append("s");
map<const string, int> productNames;
productNames["camera"] = 1;
productNames["printer"] = 2;
switch(productNames[productName]){
case 1:
clusterN = 9;
conFeatureN= 4;
catFeatureN= 1;
boolFeatureN= 0;
varNamesN= 12;
range= 2;
break;
case 2:
clusterN = 9;
conFeatureN= 4;
catFeatureN= 1;
boolFeatureN= 0;
varNamesN= 12;
range= 2;
break;
default:
clusterN = 9;
conFeatureN= 4;
catFeatureN= 1;
boolFeatureN= 0;
varNamesN= 12;
range= 2;
break;
}
double* weights = new double [conFeatureN];
weights[0] = 2;
for (int f=1; f<conFeatureN; f++){
weights[f] = 1/2;
}
ostringstream session_idStream;
ostringstream layerStream;
layerStream<<layer;
string nodeString;
string* indicatorNames = new string [4];
string *varNames = new string[varNamesN];
string *catFeatureNames = new string[catFeatureN];
//string *boolFeatureNames = new string [boolFeatureN];
string *conFeatureNames = new string[conFeatureN];
double **conFeatureRange = new double* [conFeatureN];
double ***conFeatureRangeC = new double** [clusterN];
catFeatureNames[0] = "brand";
conFeatureNames[0]="listpriceint";
conFeatureNames[1]="displaysize";
conFeatureNames[2]="opticalzoom";
conFeatureNames[3]="maximumresolution";
double *average = new double[conFeatureN];
bool *conFilteredFeatures = new bool[conFeatureN];
bool *catFilteredFeatures = new bool[catFeatureN];
bool *boolFilteredFeatures = new bool[boolFeatureN];
for(int f=0; f<conFeatureN; f++){
conFilteredFeatures[f] = 0;
conFeatureRange[f] = new double [range];
}
for (int c=0; c<clusterN; c++){
conFeatureRangeC[c] = new double* [conFeatureN];
for(int f=0; f<conFeatureN; f++){
conFeatureRangeC[c][f] = new double [range];
}
}
for (int f=0; f<catFeatureN; f++){
catFilteredFeatures[f] = 0;
}
for (int f=0; f<boolFeatureN; f++){
boolFilteredFeatures[f] = 0;
}
// string var;
varNames[0] = "layer";
varNames[1] = "camid";
varNames[2] = "brand";
varNames[3] = "price_min";
varNames[4] = "price_max";
varNames[5] = "displaysize_min";
varNames[6] = "displaysize_max";
varNames[7] = "opticalzoom_min";
varNames[8] = "opticalzoom_max";
varNames[9] = "maximumresolution_min";
varNames[10] = "maximumresolution_max";
varNames[11] = "session_id";
//void preClustering(string* varNames, map<const string, int>productNames, string productName, string* conFeatureNames, string* catFeatureNames, string* indicatorNames)
preClustering(varNames, productNames, productName, conFeatureNames, catFeatureNames, indicatorNames);
//}
// Driver Manager
sql::mysql::MySQL_Driver *driver;
// Connection, (simple, not prepared) Statement, Result Set
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
sql::ResultSet *res2;
sql::ResultSet *resClus;
sql::ResultSet *resNodes;
string line;
string buf;
vector<string> tokens;
ifstream myfile;
int i=0;
myfile.open("/optemo/site/config/database.yml");
if (myfile.is_open()){
while (! myfile.eof()){
getline (myfile,line);
stringstream ss(line);
while(ss>>buf){
tokens.push_back(buf);
i++; }
}
myfile.close();
}
else{
cout<<"Can't open file "<<myfile<<endl;
}
string databaseString = tokens.at(findVec(tokens, "database:") + 1);
string usernameString = tokens.at(findVec(tokens, "username:") + 1);
string passwordString = tokens.at(findVec(tokens, "password:") + 1);
string hostString = tokens.at(findVec(tokens, "host:") + 1);
#define PORT "3306"
#define DB "optemo_development"
#define HOST hostString
#define USER usernameString
#define PASS passwordString
///////////////////////////////////////////////
try {
// Using the Driver to create a connection
driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect(HOST, PORT, USER, PASS);
stmt = con->createStatement();
stmt->execute("USE " DB);
//deleting the current node and cluster tables
string command = "DELETE FROM ";
command += productName;
command += "_clusters;";
stmt->execute(command);
command = "DELETE FROM ";
command += productName;
command += "_nodes;";
stmt->execute(command);
command = "SELECT * FROM ";
command += productName;
command += "s where instock=1;";
res = stmt->executeQuery(command);
int maxSize = 10000;
while (maxSize>clusterN){
for (int j=0; j<conFeatureN; j++){
average[j] = 0.0;
}
maxSize = hClustering(layer, clusterN, conFeatureN, average, conFeatureRange, conFeatureRangeC, res, res2, resClus, resNodes,
stmt, conFeatureNames, productName, weights);
layer++;
}
// setRange(stmt, res, res2, conFeatureN);
//Generating the output string
delete stmt;
delete con;
} catch (sql::mysql::MySQL_DbcException *e) {
delete e;
return EXIT_FAILURE;
} catch (sql::DbcException *e) {
/* Exception is not caused by the MySQL Server */
delete e;
return EXIT_FAILURE;
}
return 1; //EXIT_SUCCESS;
}<commit_msg>changed weights in hClustering<commit_after>
// Standard C++ includes
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <assert.h>
#include <float.h>
#include <math.h>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
//return 9 cameras
// Public interface of the MySQL Connector/C++
#include <cppconn/mysql_public_iface.h>
//
#include "hClustering.h"
#include "preProcessing.h"
using namespace std;
int main(int argc, char** argv){
stringstream sql;
int clusterN;
int conFeatureN;
int catFeatureN;
int boolFeatureN;
int varNamesN;
int range;
int layer = 1;
string var;
//argument is the productName
string productName = argv[1];
string tableName = productName;
tableName.append("s");
map<const string, int> productNames;
productNames["camera"] = 1;
productNames["printer"] = 2;
switch(productNames[productName]){
case 1:
clusterN = 9;
conFeatureN= 4;
catFeatureN= 1;
boolFeatureN= 0;
varNamesN= 12;
range= 2;
break;
case 2:
clusterN = 9;
conFeatureN= 4;
catFeatureN= 1;
boolFeatureN= 0;
varNamesN= 12;
range= 2;
break;
default:
clusterN = 9;
conFeatureN= 4;
catFeatureN= 1;
boolFeatureN= 0;
varNamesN= 12;
range= 2;
break;
}
double* weights = new double [conFeatureN];
weights[0] = 1.3;
for (int f=1; f<conFeatureN; f++){
weights[f] = 0.9;
}
ostringstream session_idStream;
ostringstream layerStream;
layerStream<<layer;
string nodeString;
string* indicatorNames = new string [4];
string *varNames = new string[varNamesN];
string *catFeatureNames = new string[catFeatureN];
//string *boolFeatureNames = new string [boolFeatureN];
string *conFeatureNames = new string[conFeatureN];
double **conFeatureRange = new double* [conFeatureN];
double ***conFeatureRangeC = new double** [clusterN];
catFeatureNames[0] = "brand";
conFeatureNames[0]="listpriceint";
conFeatureNames[1]="displaysize";
conFeatureNames[2]="opticalzoom";
conFeatureNames[3]="maximumresolution";
double *average = new double[conFeatureN];
bool *conFilteredFeatures = new bool[conFeatureN];
bool *catFilteredFeatures = new bool[catFeatureN];
bool *boolFilteredFeatures = new bool[boolFeatureN];
for(int f=0; f<conFeatureN; f++){
conFilteredFeatures[f] = 0;
conFeatureRange[f] = new double [range];
}
for (int c=0; c<clusterN; c++){
conFeatureRangeC[c] = new double* [conFeatureN];
for(int f=0; f<conFeatureN; f++){
conFeatureRangeC[c][f] = new double [range];
}
}
for (int f=0; f<catFeatureN; f++){
catFilteredFeatures[f] = 0;
}
for (int f=0; f<boolFeatureN; f++){
boolFilteredFeatures[f] = 0;
}
// string var;
varNames[0] = "layer";
varNames[1] = "camid";
varNames[2] = "brand";
varNames[3] = "price_min";
varNames[4] = "price_max";
varNames[5] = "displaysize_min";
varNames[6] = "displaysize_max";
varNames[7] = "opticalzoom_min";
varNames[8] = "opticalzoom_max";
varNames[9] = "maximumresolution_min";
varNames[10] = "maximumresolution_max";
varNames[11] = "session_id";
//void preClustering(string* varNames, map<const string, int>productNames, string productName, string* conFeatureNames, string* catFeatureNames, string* indicatorNames)
preClustering(varNames, productNames, productName, conFeatureNames, catFeatureNames, indicatorNames);
//}
// Driver Manager
sql::mysql::MySQL_Driver *driver;
// Connection, (simple, not prepared) Statement, Result Set
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
sql::ResultSet *res2;
sql::ResultSet *resClus;
sql::ResultSet *resNodes;
string line;
string buf;
vector<string> tokens;
ifstream myfile;
int i=0;
myfile.open("/optemo/site/config/database.yml");
if (myfile.is_open()){
while (! myfile.eof()){
getline (myfile,line);
stringstream ss(line);
while(ss>>buf){
tokens.push_back(buf);
i++; }
}
myfile.close();
}
else{
cout<<"Can't open file "<<myfile<<endl;
}
string databaseString = tokens.at(findVec(tokens, "database:") + 1);
string usernameString = tokens.at(findVec(tokens, "username:") + 1);
string passwordString = tokens.at(findVec(tokens, "password:") + 1);
string hostString = tokens.at(findVec(tokens, "host:") + 1);
#define PORT "3306"
#define DB "optemo_development"
#define HOST hostString
#define USER usernameString
#define PASS passwordString
///////////////////////////////////////////////
try {
// Using the Driver to create a connection
driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect(HOST, PORT, USER, PASS);
stmt = con->createStatement();
stmt->execute("USE " DB);
//deleting the current node and cluster tables
string command = "DELETE FROM ";
command += productName;
command += "_clusters;";
stmt->execute(command);
command = "DELETE FROM ";
command += productName;
command += "_nodes;";
stmt->execute(command);
command = "SELECT * FROM ";
command += productName;
command += "s where instock=1;";
res = stmt->executeQuery(command);
int maxSize = 10000;
while (maxSize>clusterN){
for (int j=0; j<conFeatureN; j++){
average[j] = 0.0;
}
maxSize = hClustering(layer, clusterN, conFeatureN, average, conFeatureRange, conFeatureRangeC, res, res2, resClus, resNodes,
stmt, conFeatureNames, productName, weights);
layer++;
}
// setRange(stmt, res, res2, conFeatureN);
//Generating the output string
delete stmt;
delete con;
} catch (sql::mysql::MySQL_DbcException *e) {
delete e;
return EXIT_FAILURE;
} catch (sql::DbcException *e) {
/* Exception is not caused by the MySQL Server */
delete e;
return EXIT_FAILURE;
}
return 1; //EXIT_SUCCESS;
}<|endoftext|>
|
<commit_before>#include "CameraManager.h"
#include "Utility.h"
using namespace Rendering;
using namespace Rendering::Light;
using namespace Core;
using namespace Rendering::Manager;
using namespace Rendering::Camera;
using namespace Structure;
CameraManager::CameraManager(){}
CameraManager::~CameraManager(){}
void CameraManager::Add(Camera::CameraForm* camera)
{
address key = reinterpret_cast<address>(camera);
ASSERT_COND_MSG(Has(key) == false, "Error, Already registed camera objeect");
VectorMap<address, Camera::CameraForm*>::Add(key, camera);
}
void CameraManager::Delete(Camera::CameraForm* camera)
{
address key = reinterpret_cast<address>(camera);
VectorMap<address, Camera::CameraForm*>::Delete(key);
SAFE_DELETE(camera);
}
void CameraManager::DeleteAll()
{
for(auto iter = _vector.begin(); iter != _vector.end(); ++iter)
{
//翬Ѱű ϴٸ.. .
// , ̽Ҷ ó.
ASSERT_MSG("Bug");
CameraForm* cam = (*iter);
SAFE_DELETE(cam);
}
VectorMap<address, Camera::CameraForm*>::DeleteAll();
}
void CameraManager::Destroy()
{
DeleteAll();
}
void CameraManager::SetMainCamera(Camera::CameraForm* cam)
{
CameraForm* curMainCam = GetMainCamera();
if(curMainCam == nullptr)
{
Add(cam);
return;
}
address key = reinterpret_cast<address>(cam);
uint vecSwapIdx = -1;
Find(key, &vecSwapIdx);
// Swap Vector Element
{
if(vecSwapIdx != -1)
std::iter_swap(_vector.begin(), _vector.begin() + vecSwapIdx);
else
{
Add(cam);
std::iter_swap(_vector.begin(), _vector.end() - 1);
}
}
// Swap Map Element
{
uint mainCamKey = reinterpret_cast<address>(GetMainCamera());
auto mainCamIter = _map.find(mainCamKey);
auto swapCamIter = _map.find(key);
uint t = mainCamIter->second;
mainCamIter->second = swapCamIter->second;
swapCamIter->second = t;
}
}
Camera::CameraForm* CameraManager::GetMainCamera() const
{
return (GetSize() != 0) ? (*_vector.begin()) : nullptr;
}<commit_msg>assert는 안나게 해둠 -ㅠ-;<commit_after>#include "CameraManager.h"
#include "Utility.h"
using namespace Rendering;
using namespace Rendering::Light;
using namespace Core;
using namespace Rendering::Manager;
using namespace Rendering::Camera;
using namespace Structure;
CameraManager::CameraManager(){}
CameraManager::~CameraManager(){}
void CameraManager::Add(Camera::CameraForm* camera)
{
address key = reinterpret_cast<address>(camera);
ASSERT_COND_MSG(Has(key) == false, "Error, Already registed camera objeect");
VectorMap<address, Camera::CameraForm*>::Add(key, camera);
}
void CameraManager::Delete(Camera::CameraForm* camera)
{
address key = reinterpret_cast<address>(camera);
VectorMap<address, Camera::CameraForm*>::Delete(key);
SAFE_DELETE(camera);
}
void CameraManager::DeleteAll()
{
for(auto iter = _vector.begin(); iter != _vector.end(); ++iter)
{
//翬Ѱű ϴٸ.. .
// , ̽Ҷ ó. Ʒ ӽ÷ óصаŴ.
CameraForm* cam = (*iter);
SAFE_DELETE(cam);
}
VectorMap<address, Camera::CameraForm*>::DeleteAll();
}
void CameraManager::Destroy()
{
DeleteAll();
}
void CameraManager::SetMainCamera(Camera::CameraForm* cam)
{
CameraForm* curMainCam = GetMainCamera();
if(curMainCam == nullptr)
{
Add(cam);
return;
}
address key = reinterpret_cast<address>(cam);
uint vecSwapIdx = -1;
Find(key, &vecSwapIdx);
// Swap Vector Element
{
if(vecSwapIdx != -1)
std::iter_swap(_vector.begin(), _vector.begin() + vecSwapIdx);
else
{
Add(cam);
std::iter_swap(_vector.begin(), _vector.end() - 1);
}
}
// Swap Map Element
{
uint mainCamKey = reinterpret_cast<address>(GetMainCamera());
auto mainCamIter = _map.find(mainCamKey);
auto swapCamIter = _map.find(key);
uint t = mainCamIter->second;
mainCamIter->second = swapCamIter->second;
swapCamIter->second = t;
}
}
Camera::CameraForm* CameraManager::GetMainCamera() const
{
return (GetSize() != 0) ? (*_vector.begin()) : nullptr;
}<|endoftext|>
|
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Native XLA implementations of indexing ops.
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/bounds_check.h"
namespace tensorflow {
namespace {
// The logic below uses a custom-call to implement argmax.
//
// Also see b/29507024 for first-class XLA support for indexing ops.
class ArgMaxCustomCallOp : public XlaOpKernel {
public:
explicit ArgMaxCustomCallOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape(0);
const TensorShape dimension_shape = ctx->InputShape(1);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(dimension_shape),
errors::InvalidArgument(
"dim must be a scalar, but received tensor of shape: ",
dimension_shape.DebugString()));
// We require that the dimension argument is a constant, since it lets us
// dispatch to a specialized custom-call function without any run-time
// overhead, when compiling ahead-of-time.
int64 dim;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(1, &dim));
OP_REQUIRES(ctx, dim >= 0, errors::InvalidArgument("dim must be >= 0"));
OP_REQUIRES(
ctx, dim < input_shape.dims(),
errors::InvalidArgument("dim must be < input rank (",
input_shape.dims(), "), but got: ", dim));
const int64 dim_size = input_shape.dim_size(dim);
OP_REQUIRES(ctx, dim_size > 0,
errors::InvalidArgument(
"Reduction axis ", dim,
" is empty in shape: ", input_shape.DebugString()));
// The output shape is the input shape contracted along dim.
TensorShape output_shape;
for (int d = 0; d < input_shape.dims() - 1; ++d) {
output_shape.AddDim(input_shape.dim_size((d < dim) ? d : d + 1));
}
// For now we use a custom-call, only for the 1d and 2d cases.
OP_REQUIRES(ctx, XlaContext::Get(ctx).allow_cpu_custom_calls(),
errors::InvalidArgument(
"ArgMax implementation requires a CustomCall on CPU"));
xla::XlaBuilder& b = *ctx->builder();
// XLA passes <out> to the function, so it is not included here.
std::vector<xla::XlaOp> args;
args.push_back(ctx->Input(0));
args.push_back(xla::ConstantLiteral(
&b, xla::LiteralUtil::CreateR1<int64>(input_shape.dim_sizes())));
if (input_shape.dims() > 1) {
// Don't bother passing the output shape and dim for the 1d case, since
// the shape is always a scalar and the dim is always 0.
args.push_back(xla::ConstantLiteral(
&b, xla::LiteralUtil::CreateR1<int64>(output_shape.dim_sizes())));
args.push_back(
xla::ConstantLiteral(&b, xla::LiteralUtil::CreateR0<int32>(dim)));
}
// The argmax function expects row-major layout.
xla::Shape xla_shape = xla::ShapeUtil::MakeShapeWithDescendingLayout(
xla::S64, output_shape.dim_sizes());
std::vector<xla::Shape> arg_shapes;
for (const xla::XlaOp& arg : args) {
auto shape_status = b.GetShape(arg);
OP_REQUIRES_OK(ctx, shape_status.status());
xla::Shape arg_shape = shape_status.ConsumeValueOrDie();
*arg_shape.mutable_layout() = xla::LayoutUtil::MakeDescendingLayout(
xla::ShapeUtil::Rank(arg_shape));
arg_shapes.push_back(std::move(arg_shape));
}
// Tell XLA to call the custom code, defined in
// index_ops_kernel_argmax_float_1d.cc.
xla::XlaOp output;
switch (input_shape.dims()) {
case 1:
output = xla::CustomCallWithLayout(&b, "argmax_float_1d_xla_impl", args,
xla_shape, arg_shapes);
break;
case 2:
output = xla::CustomCallWithLayout(&b, "argmax_float_2d_xla_impl", args,
xla_shape, arg_shapes);
break;
default:
OP_REQUIRES(ctx, false,
errors::Unimplemented(
"Argmax is only implemented for 1d and 2d tensors"
", but got shape: ",
input_shape.DebugString()));
}
ctx->SetOutput(0, output);
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(ArgMaxCustomCallOp);
};
REGISTER_XLA_OP(Name("ArgMax")
.TypeConstraint("T", DT_FLOAT)
.Device(DEVICE_CPU_XLA_JIT)
.CompileTimeConstantInput("dimension"),
ArgMaxCustomCallOp);
} // namespace
} // namespace tensorflow
<commit_msg>[TF:XLA] Fix the output type of ArgMaxCustomCallOp.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Native XLA implementations of indexing ops.
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/bounds_check.h"
namespace tensorflow {
namespace {
// The logic below uses a custom-call to implement argmax.
//
// Also see b/29507024 for first-class XLA support for indexing ops.
class ArgMaxCustomCallOp : public XlaOpKernel {
public:
explicit ArgMaxCustomCallOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape(0);
const TensorShape dimension_shape = ctx->InputShape(1);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(dimension_shape),
errors::InvalidArgument(
"dim must be a scalar, but received tensor of shape: ",
dimension_shape.DebugString()));
// We require that the dimension argument is a constant, since it lets us
// dispatch to a specialized custom-call function without any run-time
// overhead, when compiling ahead-of-time.
int64 dim;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(1, &dim));
OP_REQUIRES(ctx, dim >= 0, errors::InvalidArgument("dim must be >= 0"));
OP_REQUIRES(
ctx, dim < input_shape.dims(),
errors::InvalidArgument("dim must be < input rank (",
input_shape.dims(), "), but got: ", dim));
const int64 dim_size = input_shape.dim_size(dim);
OP_REQUIRES(ctx, dim_size > 0,
errors::InvalidArgument(
"Reduction axis ", dim,
" is empty in shape: ", input_shape.DebugString()));
// The output shape is the input shape contracted along dim.
TensorShape output_shape;
for (int d = 0; d < input_shape.dims() - 1; ++d) {
output_shape.AddDim(input_shape.dim_size((d < dim) ? d : d + 1));
}
// For now we use a custom-call, only for the 1d and 2d cases.
OP_REQUIRES(ctx, XlaContext::Get(ctx).allow_cpu_custom_calls(),
errors::InvalidArgument(
"ArgMax implementation requires a CustomCall on CPU"));
xla::XlaBuilder& b = *ctx->builder();
// XLA passes <out> to the function, so it is not included here.
std::vector<xla::XlaOp> args;
args.push_back(ctx->Input(0));
args.push_back(xla::ConstantLiteral(
&b, xla::LiteralUtil::CreateR1<int64>(input_shape.dim_sizes())));
if (input_shape.dims() > 1) {
// Don't bother passing the output shape and dim for the 1d case, since
// the shape is always a scalar and the dim is always 0.
args.push_back(xla::ConstantLiteral(
&b, xla::LiteralUtil::CreateR1<int64>(output_shape.dim_sizes())));
args.push_back(
xla::ConstantLiteral(&b, xla::LiteralUtil::CreateR0<int32>(dim)));
}
// The argmax function expects row-major layout.
xla::Shape xla_shape = xla::ShapeUtil::MakeShapeWithDescendingLayout(
xla::S64, output_shape.dim_sizes());
std::vector<xla::Shape> arg_shapes;
for (const xla::XlaOp& arg : args) {
auto shape_status = b.GetShape(arg);
OP_REQUIRES_OK(ctx, shape_status.status());
xla::Shape arg_shape = shape_status.ConsumeValueOrDie();
*arg_shape.mutable_layout() = xla::LayoutUtil::MakeDescendingLayout(
xla::ShapeUtil::Rank(arg_shape));
arg_shapes.push_back(std::move(arg_shape));
}
// Tell XLA to call the custom code, defined in
// index_ops_kernel_argmax_float_1d.cc.
xla::XlaOp output;
switch (input_shape.dims()) {
case 1:
output = xla::CustomCallWithLayout(&b, "argmax_float_1d_xla_impl", args,
xla_shape, arg_shapes);
break;
case 2:
output = xla::CustomCallWithLayout(&b, "argmax_float_2d_xla_impl", args,
xla_shape, arg_shapes);
break;
default:
OP_REQUIRES(ctx, false,
errors::Unimplemented(
"Argmax is only implemented for 1d and 2d tensors"
", but got shape: ",
input_shape.DebugString()));
}
const DataType dtype = output_type(0);
xla::PrimitiveType output_type;
OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dtype, &output_type));
output = xla::ConvertElementType(output, output_type);
ctx->SetOutput(0, output);
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(ArgMaxCustomCallOp);
};
REGISTER_XLA_OP(Name("ArgMax")
.TypeConstraint("T", DT_FLOAT)
.Device(DEVICE_CPU_XLA_JIT)
.CompileTimeConstantInput("dimension"),
ArgMaxCustomCallOp);
} // namespace
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
// On mobile we do not provide optimize dataset op because not all of its
// dependencies are available there. The op is replaced with a no-op.
#if !defined(IS_MOBILE_PLATFORM)
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the live experiment names and for how much percentage
// of the Borg jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments = {
{"enable_gradient_descent", 0},
{"map_parallelization", 0}
};
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the live experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The live experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// The vector stores the graduated experiment names which will be turned on
// for all input pipelines.
// clang-format off
std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"};
// clang-format on
// Add the graduated experiments to the optimization list and log them.
for (auto& experiment : graduated_experiments) {
if (std::find(optimizations.begin(), optimizations.end(), experiment) ==
optimizations.end()) {
optimizations.push_back(experiment);
}
VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied.";
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#else // !IS_MOBILE_PLATFORM
namespace tensorflow {
namespace data {
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
input->Ref();
*output = input;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#endif // !IS_MOBILE_PLATFORM
<commit_msg>[tf.data] Rolls out the optimization `map_parallelization` as experiment to 1% of Borg jobs.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
// On mobile we do not provide optimize dataset op because not all of its
// dependencies are available there. The op is replaced with a no-op.
#if !defined(IS_MOBILE_PLATFORM)
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the live experiment names and for how much percentage
// of the Borg jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments = {
{"enable_gradient_descent", 0},
{"map_parallelization", 1}
};
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the live experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The live experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// The vector stores the graduated experiment names which will be turned on
// for all input pipelines.
// clang-format off
std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"};
// clang-format on
// Add the graduated experiments to the optimization list and log them.
for (auto& experiment : graduated_experiments) {
if (std::find(optimizations.begin(), optimizations.end(), experiment) ==
optimizations.end()) {
optimizations.push_back(experiment);
}
VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied.";
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#else // !IS_MOBILE_PLATFORM
namespace tensorflow {
namespace data {
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
input->Ref();
*output = input;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#endif // !IS_MOBILE_PLATFORM
<|endoftext|>
|
<commit_before>/***********************************
Copyright 2020 Ravishankar Mathur
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.
***********************************/
/**
Demonstrates use of CustomLineSegments to connect ReferenceFrames with line segments
**/
#include <OpenFrames/CustomLineSegments.hpp>
#include <OpenFrames/CurveArtist.hpp>
#include <OpenFrames/DrawableTrajectory.hpp>
#include <OpenFrames/FrameManager.hpp>
#include <OpenFrames/FrameTransform.hpp>
#include <OpenFrames/MarkerArtist.hpp>
#include <OpenFrames/Trajectory.hpp>
#include <OpenFrames/TrajectoryFollower.hpp>
#include <OpenFrames/WindowProxy.hpp>
#include <osg/Math>
using namespace OpenFrames;
ReferenceFrame *root;
WindowProxy *theWindow;
/** The function called when the user presses a key */
void KeyPressCallback(unsigned int *winID, unsigned int *row, unsigned int *col, int *key)
{
// Pause/unpause animation
if(*key == 'p')
{
theWindow->pauseTime(!theWindow->isTimePaused());
}
// Reset time to epoch. All ReferenceFrames that are following
// a Trajectory will return to their starting positions.
else if(*key == 'r')
{
theWindow->setTime(0.0);
}
// Speed up time
else if((*key == '+') || (*key == '='))
{
theWindow->setTimeScale(theWindow->getTimeScale() + 0.01);
}
// Slow down time
else if((*key == '-') || (*key == '_'))
{
theWindow->setTimeScale(theWindow->getTimeScale() - 0.01);
}
}
/** Callback that dynamicall computes the line segment vertex data */
class LineSegmentCallback : public CustomLineSegments::Callback
{
public:
LineSegmentCallback() {}
// Required: get number of segments
virtual unsigned int getNumSegments() const
{
return _framePairs.size();
}
// Required: get data for given segment
virtual void getSegmentData(const unsigned int &segID, osg::Vec3 &posA, osg::Vec4 &colorA, osg::Vec3 &posB, osg::Vec4 &colorB) const
{
// Vertex A corresponds to Frame A
ReferenceFrame *frameA = _framePairs[segID].first;
posA.set(frameA->getPosition());
colorA = frameA->getColor();
colorA.a() = 0.4; // Make line color slightly transparent
// Vertex B corresponds to Frame B
ReferenceFrame *frameB = _framePairs[segID].second;
posB.set(frameB->getPosition());
colorB = frameB->getColor();
colorB.a() = 0.4; // Make line color slightly transparent
}
// Add a pair of ReferenceFrames that will have a line segment drawn between them
void addSegment(ReferenceFrame *frameA, ReferenceFrame *frameB)
{
_framePairs.push_back(FramePair(frameA, frameB));
}
protected:
virtual ~LineSegmentCallback() {}
typedef std::pair<ReferenceFrame*, ReferenceFrame*> FramePair;
std::vector<FramePair> _framePairs;
};
int main()
{
// Create the interface that represents a window
osg::ref_ptr<WindowProxy> myWindow = new WindowProxy(30, 30, 1024, 768, 1, 1, false);
myWindow->setKeyPressCallback(KeyPressCallback); // Specify keypress callback
theWindow = myWindow;
// Create a root ReferenceFrame
root = new ReferenceFrame("drawtraj", 1, 0, 0, 0.9);
root->showAxes(ReferenceFrame::NO_AXES);
root->showAxesLabels(ReferenceFrame::NO_AXES);
root->showNameLabel(false);
/***************
Frame 1: Circular trajectory
*/
osg::ref_ptr<Trajectory> traj1 = new Trajectory;
double pos[3];
double rmag = 1.0;
const double eps = 1.0e-14;
for(double t = 0.0; t <= 2.0*osg::PI + eps; t += osg::PI / 90.0)
{
// Compute position along circle
pos[0] = rmag * cos(t);
pos[1] = 0.0;
pos[2] = rmag * sin(t);
// Add position
traj1->addTime(t);
traj1->addPosition(pos);
}
// Follow the trajectory (by default in LOOP mode)
TrajectoryFollower *tf1 = new TrajectoryFollower(traj1);
// Create a frame to follow the trajectory
Sphere *frame1 = new Sphere("Circle", 1, 0, 0, 1);
frame1->setRadius(0.1);
frame1->showAxes(ReferenceFrame::NO_AXES);
frame1->showAxesLabels(ReferenceFrame::NO_AXES);
frame1->getTransform()->setUpdateCallback(tf1);
root->addChild(frame1);
/***************
Frame 2: Vertical trajectory
*/
osg::ref_ptr<Trajectory> traj2 = new Trajectory;
{ // First point along x-axis
traj2->addTime(0.0);
traj2->addPosition(rmag + 1.0, 0.0, 0.0);
}
{ // Second point above first
traj2->addTime(5.0);
traj2->addPosition(rmag + 1.0, 0.0, 5.0);
}
// Follow the trajectory (by default in LOOP mode)
TrajectoryFollower *tf2 = new TrajectoryFollower(traj2);
// Create a frame to follow the trajectory
Sphere *frame2 = new Sphere("Vertical", 0, 1, 0, 1);
frame2->setRadius(0.1);
frame2->showAxes(ReferenceFrame::NO_AXES);
frame2->showAxesLabels(ReferenceFrame::NO_AXES);
frame2->getTransform()->setUpdateCallback(tf2);
root->addChild(frame2);
/***************
Line segments between frames
*/
LineSegmentCallback *lsCallback = new LineSegmentCallback;
lsCallback->addSegment(frame1, frame2); // Segment between frames 1 and 2
CustomLineSegments *cls = new CustomLineSegments("CustomLineSegment", 1, 1, 1, 1);
cls->setLineSegmentCallback(lsCallback);
cls->setLineWidth(2.0);
cls->setLineShader("Shaders/Line_Pulse.frag");
cls->showAxes(ReferenceFrame::NO_AXES);
cls->showAxesLabels(ReferenceFrame::NO_AXES);
root->addChild(cls);
// Create a manager to handle access to the scene
FrameManager* fm = new FrameManager;
fm->setFrame(root);
// Add the scene to the window
myWindow->setScene(fm, 0, 0);
myWindow->getGridPosition(0, 0)->setBackgroundColor(0, 0, 0); // Black background
myWindow->startThread(); // Start window animation
myWindow->join(); // Wait for window animation to finish
return 0;
}
<commit_msg>Add another frame to ofcustomlinesegments example<commit_after>/***********************************
Copyright 2020 Ravishankar Mathur
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.
***********************************/
/**
Demonstrates use of CustomLineSegments to connect ReferenceFrames with line segments
**/
#include <OpenFrames/CustomLineSegments.hpp>
#include <OpenFrames/CurveArtist.hpp>
#include <OpenFrames/DrawableTrajectory.hpp>
#include <OpenFrames/FrameManager.hpp>
#include <OpenFrames/FrameTransform.hpp>
#include <OpenFrames/MarkerArtist.hpp>
#include <OpenFrames/Trajectory.hpp>
#include <OpenFrames/TrajectoryFollower.hpp>
#include <OpenFrames/WindowProxy.hpp>
#include <osg/Math>
using namespace OpenFrames;
ReferenceFrame *root;
WindowProxy *theWindow;
/** The function called when the user presses a key */
void KeyPressCallback(unsigned int *winID, unsigned int *row, unsigned int *col, int *key)
{
// Pause/unpause animation
if(*key == 'p')
{
theWindow->pauseTime(!theWindow->isTimePaused());
}
// Reset time to epoch. All ReferenceFrames that are following
// a Trajectory will return to their starting positions.
else if(*key == 'r')
{
theWindow->setTime(0.0);
}
// Speed up time
else if((*key == '+') || (*key == '='))
{
theWindow->setTimeScale(theWindow->getTimeScale() + 0.01);
}
// Slow down time
else if((*key == '-') || (*key == '_'))
{
theWindow->setTimeScale(theWindow->getTimeScale() - 0.01);
}
}
/** Callback that dynamicall computes the line segment vertex data */
class LineSegmentCallback : public CustomLineSegments::Callback
{
public:
LineSegmentCallback() {}
// Required: get number of segments
virtual unsigned int getNumSegments() const
{
return _framePairs.size();
}
// Required: get data for given segment
virtual void getSegmentData(const unsigned int &segID, osg::Vec3 &posA, osg::Vec4 &colorA, osg::Vec3 &posB, osg::Vec4 &colorB) const
{
// Vertex A corresponds to Frame A
ReferenceFrame *frameA = _framePairs[segID].first;
posA.set(frameA->getPosition());
colorA = frameA->getColor();
colorA.a() = 0.4; // Make line color slightly transparent
// Vertex B corresponds to Frame B
ReferenceFrame *frameB = _framePairs[segID].second;
posB.set(frameB->getPosition());
colorB = frameB->getColor();
colorB.a() = 0.4; // Make line color slightly transparent
}
// Add a pair of ReferenceFrames that will have a line segment drawn between them
void addSegment(ReferenceFrame *frameA, ReferenceFrame *frameB)
{
_framePairs.push_back(FramePair(frameA, frameB));
}
protected:
virtual ~LineSegmentCallback() {}
typedef std::pair<ReferenceFrame*, ReferenceFrame*> FramePair;
std::vector<FramePair> _framePairs;
};
int main()
{
// Create the interface that represents a window
osg::ref_ptr<WindowProxy> myWindow = new WindowProxy(30, 30, 1024, 768, 1, 1, false);
myWindow->setKeyPressCallback(KeyPressCallback); // Specify keypress callback
theWindow = myWindow;
// Create a root ReferenceFrame
root = new ReferenceFrame("drawtraj", 1, 0, 0, 0.9);
root->showAxes(ReferenceFrame::NO_AXES);
root->showAxesLabels(ReferenceFrame::NO_AXES);
root->showNameLabel(false);
/***************
Frame 1: Circular trajectory
*/
osg::ref_ptr<Trajectory> traj1 = new Trajectory;
double pos[3];
double rmag = 1.0;
const double eps = 1.0e-14;
for(double t = 0.0; t <= 2.0*osg::PI + eps; t += osg::PI / 90.0)
{
// Compute position along circle
pos[0] = rmag * cos(t);
pos[1] = 0.0;
pos[2] = rmag * sin(t);
// Add position
traj1->addTime(t);
traj1->addPosition(pos);
}
// Follow the trajectory (by default in LOOP mode)
TrajectoryFollower *tf1 = new TrajectoryFollower(traj1);
// Create a frame to follow the trajectory
Sphere *frame1 = new Sphere("Circle", 1, 0, 0, 1);
frame1->setRadius(0.1);
frame1->showAxes(ReferenceFrame::NO_AXES);
frame1->showAxesLabels(ReferenceFrame::NO_AXES);
frame1->getTransform()->setUpdateCallback(tf1);
root->addChild(frame1);
/***************
Frame 2: Vertical trajectory
*/
osg::ref_ptr<Trajectory> traj2 = new Trajectory;
{ // First point along x-axis
traj2->addTime(0.0);
traj2->addPosition(rmag + 1.0, 0.0, 0.0);
}
{ // Second point above first
traj2->addTime(5.0);
traj2->addPosition(rmag + 1.0, 0.0, 4.0);
}
{ // Third point same as first
traj2->addTime(7.0);
traj2->addPosition(rmag + 1.0, 0.0, 0.0);
}
// Follow the trajectory (by default in LOOP mode)
TrajectoryFollower *tf2 = new TrajectoryFollower(traj2);
// Create a frame to follow the trajectory
Sphere *frame2 = new Sphere("Vertical", 0, 1, 0, 1);
frame2->setRadius(0.1);
frame2->showAxes(ReferenceFrame::NO_AXES);
frame2->showAxesLabels(ReferenceFrame::NO_AXES);
frame2->getTransform()->setUpdateCallback(tf2);
root->addChild(frame2);
/***************
Frame 3: Horizontal trajectory
*/
osg::ref_ptr<Trajectory> traj3 = new Trajectory;
{ // First point along z-axis
traj3->addTime(0.0);
traj3->addPosition(0.0, 0.0, rmag + 1.0);
}
{ // Second point left of first
traj3->addTime(3.0);
traj3->addPosition(-5.0, 0.0, rmag + 1.0);
}
{ // Third point same as first
traj3->addTime(5.0);
traj3->addPosition(0.0, 0.0, rmag + 1.0);
}
// Follow the trajectory (by default in LOOP mode)
TrajectoryFollower *tf3 = new TrajectoryFollower(traj3);
// Create a frame to follow the trajectory
Sphere *frame3 = new Sphere("Horizontal", 0, 0, 1, 1);
frame3->setRadius(0.1);
frame3->showAxes(ReferenceFrame::NO_AXES);
frame3->showAxesLabels(ReferenceFrame::NO_AXES);
frame3->getTransform()->setUpdateCallback(tf3);
root->addChild(frame3);
/***************
Line segments between frames
*/
LineSegmentCallback *lsCallback = new LineSegmentCallback;
lsCallback->addSegment(frame1, frame2); // Segment between frames 1 and 2
lsCallback->addSegment(frame2, frame3); // Segment between frames 2 and 3
CustomLineSegments *cls = new CustomLineSegments("CustomLineSegment", 1, 1, 1, 1);
cls->setLineSegmentCallback(lsCallback);
cls->setLineWidth(2.0);
cls->setLineShader("Shaders/Line_Pulse.frag");
cls->showAxes(ReferenceFrame::NO_AXES);
cls->showAxesLabels(ReferenceFrame::NO_AXES);
root->addChild(cls);
// Create a manager to handle access to the scene
FrameManager* fm = new FrameManager;
fm->setFrame(root);
// Add the scene to the window
myWindow->setScene(fm, 0, 0);
myWindow->getGridPosition(0, 0)->setBackgroundColor(0, 0, 0); // Black background
myWindow->startThread(); // Start window animation
myWindow->join(); // Wait for window animation to finish
return 0;
}
<|endoftext|>
|
<commit_before>
#include "EffekseerTool.Renderer.h"
#include "EffekseerTool.Culling.h"
#include "EffekseerTool.Grid.h"
#include "EffekseerTool.Guide.h"
#include "EffekseerTool.Paste.h"
#include "../EffekseerRendererCommon/EffekseerRenderer.PngTextureLoader.h"
#include "../RenderedEffectGenerator.h"
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/spdlog.h>
namespace EffekseerTool
{
MainScreenRenderedEffectGenerator::~MainScreenRenderedEffectGenerator()
{
if (backgroundTexture_ != nullptr)
{
textureLoader_->Unload(backgroundTexture_);
backgroundTexture_.Reset();
}
}
bool MainScreenRenderedEffectGenerator::InitializedPrePost()
{
grid_ = std::shared_ptr<::EffekseerRenderer::Grid>(::EffekseerRenderer::Grid::Create(graphics_->GetGraphicsDevice()));
if (grid_ == nullptr)
{
return false;
}
spdlog::trace("OK Grid");
guide_ = std::shared_ptr<::EffekseerRenderer::Guide>(::EffekseerRenderer::Guide::Create(graphics_->GetGraphicsDevice()));
if (guide_ == nullptr)
{
return false;
}
spdlog::trace("OK Guide");
culling_ = std::shared_ptr<::EffekseerRenderer::Culling>(::EffekseerRenderer::Culling::Create(graphics_->GetGraphicsDevice()));
if (culling_ == nullptr)
{
return false;
}
spdlog::trace("OK Culling");
textureLoader_ = renderer_->CreateTextureLoader();
return true;
}
void MainScreenRenderedEffectGenerator::OnAfterClear()
{
const auto cameraMat = renderer_->GetCameraMatrix();
const auto projMat = renderer_->GetProjectionMatrix();
if (config_.RenderingMethod != Effekseer::Tool::RenderingMethodType::Overdraw)
{
if (IsGridShown)
{
grid_->SetLength(GridLength);
grid_->IsShownXY = IsGridXYShown;
grid_->IsShownXZ = IsGridXZShown;
grid_->IsShownYZ = IsGridYZShown;
grid_->Rendering(GridColor, IsRightHand, cameraMat, projMat);
}
{
culling_->IsShown = IsCullingShown;
culling_->Radius = CullingRadius;
culling_->X = CullingPosition.X;
culling_->Y = CullingPosition.Y;
culling_->Z = CullingPosition.Z;
culling_->Rendering(IsRightHand, cameraMat, projMat);
}
}
}
void MainScreenRenderedEffectGenerator::OnBeforePostprocess()
{
if (RendersGuide)
{
guide_->Rendering(screenSize_.X, screenSize_.Y, GuideWidth, GuideHeight);
}
}
void MainScreenRenderedEffectGenerator::LoadBackgroundImage(const char16_t* path)
{
if (backgroundPath == path)
return;
backgroundPath = path;
if (backgroundTexture_ != nullptr)
{
textureLoader_->Unload(backgroundTexture_);
backgroundTexture_.Reset();
}
backgroundTexture_ = textureLoader_->Load(path, Effekseer::TextureType::Color);
}
} // namespace EffekseerTool
<commit_msg>Fix compile<commit_after>
#include "EffekseerTool.Renderer.h"
#include "EffekseerTool.Culling.h"
#include "EffekseerTool.Grid.h"
#include "EffekseerTool.Guide.h"
#include "../EffekseerRendererCommon/EffekseerRenderer.PngTextureLoader.h"
#include "../RenderedEffectGenerator.h"
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/spdlog.h>
namespace EffekseerTool
{
MainScreenRenderedEffectGenerator::~MainScreenRenderedEffectGenerator()
{
if (backgroundTexture_ != nullptr)
{
textureLoader_->Unload(backgroundTexture_);
backgroundTexture_.Reset();
}
}
bool MainScreenRenderedEffectGenerator::InitializedPrePost()
{
grid_ = std::shared_ptr<::EffekseerRenderer::Grid>(::EffekseerRenderer::Grid::Create(graphics_->GetGraphicsDevice()));
if (grid_ == nullptr)
{
return false;
}
spdlog::trace("OK Grid");
guide_ = std::shared_ptr<::EffekseerRenderer::Guide>(::EffekseerRenderer::Guide::Create(graphics_->GetGraphicsDevice()));
if (guide_ == nullptr)
{
return false;
}
spdlog::trace("OK Guide");
culling_ = std::shared_ptr<::EffekseerRenderer::Culling>(::EffekseerRenderer::Culling::Create(graphics_->GetGraphicsDevice()));
if (culling_ == nullptr)
{
return false;
}
spdlog::trace("OK Culling");
textureLoader_ = renderer_->CreateTextureLoader();
return true;
}
void MainScreenRenderedEffectGenerator::OnAfterClear()
{
const auto cameraMat = renderer_->GetCameraMatrix();
const auto projMat = renderer_->GetProjectionMatrix();
if (config_.RenderingMethod != Effekseer::Tool::RenderingMethodType::Overdraw)
{
if (IsGridShown)
{
grid_->SetLength(GridLength);
grid_->IsShownXY = IsGridXYShown;
grid_->IsShownXZ = IsGridXZShown;
grid_->IsShownYZ = IsGridYZShown;
grid_->Rendering(GridColor, IsRightHand, cameraMat, projMat);
}
{
culling_->IsShown = IsCullingShown;
culling_->Radius = CullingRadius;
culling_->X = CullingPosition.X;
culling_->Y = CullingPosition.Y;
culling_->Z = CullingPosition.Z;
culling_->Rendering(IsRightHand, cameraMat, projMat);
}
}
}
void MainScreenRenderedEffectGenerator::OnBeforePostprocess()
{
if (RendersGuide)
{
guide_->Rendering(screenSize_.X, screenSize_.Y, GuideWidth, GuideHeight);
}
}
void MainScreenRenderedEffectGenerator::LoadBackgroundImage(const char16_t* path)
{
if (backgroundPath == path)
return;
backgroundPath = path;
if (backgroundTexture_ != nullptr)
{
textureLoader_->Unload(backgroundTexture_);
backgroundTexture_.Reset();
}
backgroundTexture_ = textureLoader_->Load(path, Effekseer::TextureType::Color);
}
} // namespace EffekseerTool
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <osmesa.h>
#include <conio.h> // For kbhit, getch, textmode (console access)
#include <dpmi.h> // For __dpmi_int (mouse access)
#include <go32.h> // For _dos_ds (VRAM access)
#include <sys/movedata.h> // For movedata (VRAM access)
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <GL/glu.h> // GLU = OpenGL utility library
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <memory>
#include <iostream>
#include <map>
#include <array>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <pc.h>
#include "NativeBitmap.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"
#include "IFileLoaderDelegate.h"
#include "Vec2i.h"
#include "NativeBitmap.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "NoudarDungeonSnapshot.h"
#include "GameNativeAPI.h"
#include "WindowOperations.h"
#include "Common.h"
#include "LoadPNG.h"
bool inGraphics = true;
namespace PC {
const unsigned W = 320, H = 200;
unsigned ImageBuffer[W * H];
int selector;
void Init() {
__dpmi_regs r;
r.x.ax = 0x13;
__dpmi_int(0x10, &r);
outp(0x03c8, 0);
for ( int r = 0; r < 4; ++r ) {
for ( int g = 0; g < 4; ++g ) {
for ( int b = 0; b < 4; ++b ) {
outp(0x03c9, (r * 85));
outp(0x03c9, (g * 85));
outp(0x03c9, (b * 85));
}
}
}
}
void renderPalette() {
_farsetsel(_dos_ds);
int offset = 0;
int fullSize = 320 * 200;
for (int r = 0; r < 255; ++r) {
for (int x = 0; x < 50; ++x) {
int shade = 0;
int origin = r << 16;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + r, shade);
}
}
for (int g = 0; g < 255; ++g) {
for (int x = 50; x < 100; ++x) {
int shade = 0;
int origin = g << 8;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + g, shade);
}
}
for (int b = 0; b < 255; ++b) {
for (int x = 100; x < 150; ++x) {
int shade = 0;
int origin = b;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + b, shade);
}
}
for (int b = 0; b < 255; ++b) {
for (int x = 150; x < 200; ++x) {
_farnspokeb(0xA0000 + (320 * x) + b, b);
}
}
std::fill(std::end(ImageBuffer) - (320 * 200), std::end(ImageBuffer), 0x0);
}
void Render() {
_farsetsel(_dos_ds);
auto pixelData = (*gunState)->getPixelData();
int offset = 0;
int fullSize = 320 * 200;
for (int y = 100; y < 200; ++y) {
for (int x = 80; x < 240; ++x) {
offset = (320 * y) + x;
auto origin = ImageBuffer[offset];
offset = (320 * (200 - (2 * (y - 100)))) + (((x - 80) * 320) / 160);
if (pixelData[offset] & 0xFF000000) {
origin = pixelData[offset];
}
int shade = 0;
shade += (((((origin & 0x0000FF) ) ) / 85 ) );
shade += (((((origin & 0x00FF00) >> 8 ) ) / 85 ) ) << 2;
shade += (((((origin & 0xFF0000) >> 16) ) / 85 ) ) << 4;
_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);
_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);
_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);
_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);
}
}
std::fill(std::end(ImageBuffer) - (320 * 100), std::end(ImageBuffer), 0x0);
}
void Close() // End graphics
{
textmode(C80); // Set textmode again.
}
}
void setGraphics() {
inGraphics = true;
PC::Init();
}
void setTextMode() {
inGraphics = false;
__dpmi_regs r;
r.x.ax = 3;
__dpmi_int(0x10, &r);
}
const int winWidth = 320, winHeight = 200;
bool done = false;
bool isActive = false;
std::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() {
std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn;
toReturn.push_back( loadPNG( "res/grass.ppm") );
toReturn.push_back( loadPNG( "res/stonef1.ppm") );
toReturn.push_back( loadPNG( "res/bricks.ppm") );
toReturn.push_back( loadPNG( "res/arch.ppm") );
toReturn.push_back( loadPNG( "res/bars.ppm") );
toReturn.push_back( loadPNG( "res/begin.ppm") );
toReturn.push_back( loadPNG( "res/exit.ppm") );
toReturn.push_back( loadPNG( "res/bricks2.ppm") );
toReturn.push_back( loadPNG( "res/bricks3.ppm") );
toReturn.push_back( loadPNG( "res/foe0.ppm") );
toReturn.push_back( loadPNG( "res/foe1.ppm") );
toReturn.push_back( loadPNG( "res/foe2.ppm") );
toReturn.push_back( loadPNG( "res/foe3.ppm") );
toReturn.push_back( loadPNG( "res/foe4.ppm") );
toReturn.push_back( loadPNG( "res/foe5.ppm") );
toReturn.push_back( loadPNG( "res/crusad0.ppm") );
toReturn.push_back( loadPNG( "res/crusad1.ppm") );
toReturn.push_back( loadPNG( "res/crusad2.ppm") );
toReturn.push_back( loadPNG( "res/shadow.ppm") );
toReturn.push_back( loadPNG( "res/ceilin.ppm") );
toReturn.push_back( loadPNG( "res/ceigdr.ppm") );
toReturn.push_back( loadPNG( "res/ceigbgn.ppm") );
toReturn.push_back( loadPNG( "res/ceilend.ppm") );
toReturn.push_back( loadPNG( "res/splat0.ppm") );
toReturn.push_back( loadPNG( "res/splat1.ppm") );
toReturn.push_back( loadPNG( "res/splat2.ppm") );
toReturn.push_back( loadPNG( "res/ceilbar.ppm") );
toReturn.push_back( loadPNG( "res/clouds.ppm"));
toReturn.push_back( loadPNG( "res/stngrsf.ppm"));
toReturn.push_back( loadPNG( "res/grsstnf.ppm"));
toReturn.push_back( loadPNG( "res/stngrsn.ppm"));
toReturn.push_back( loadPNG( "res/grsstnn.ppm"));
toReturn.push_back( loadPNG( "res/cross.ppm"));
return toReturn;
}
void initWindow() {
auto textures = loadTextures();
OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL);
OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H);
PC::Init();
auto gVertexShader = "";
auto gFragmentShader = "";
setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures);
auto soundListener = std::make_shared<odb::SoundListener>();
std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;
std::string filenames[] {
"res/grasssteps.wav",
"res/stepsstones.wav",
"res/bgnoise.wav",
"res/monsterdamage.wav",
"res/monsterdead.wav",
"res/playerdamage.wav",
"res/playerdead.wav",
"res/swing.wav"
};
for ( auto filename : filenames ) {
FILE *file = fopen( filename.c_str(), "r");
auto soundClip = odb::makeSoundClipFrom( file );
sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) );
}
setSoundEmitters( sounds, soundListener );
}
void tick() {
//if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined
if ( inGraphics ) {
gameLoopTick( 250 );
renderFrame( 250 );
PC::Render();
}
}
void setMainLoop() {
while ( !done ) {
while(kbhit())
switch(getch()) {
case 27: done = true; break;
case '1':
setGraphics();
break;
case '2':
setTextMode();
break;
case 'w':
moveUp();
break;
case 's':
moveDown();
break;
case 'd':
moveRight();
break;
case 'a':
moveLeft();
break;
case 'e':
rotateCameraRight();
break;
case 'q':
rotateCameraLeft();
break;
}
tick();
}
}
void destroyWindow() {
shutdown();
}
<commit_msg>Makes H shoot with hitscan attack<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <osmesa.h>
#include <conio.h> // For kbhit, getch, textmode (console access)
#include <dpmi.h> // For __dpmi_int (mouse access)
#include <go32.h> // For _dos_ds (VRAM access)
#include <sys/movedata.h> // For movedata (VRAM access)
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <GL/glu.h> // GLU = OpenGL utility library
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <memory>
#include <iostream>
#include <map>
#include <array>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <pc.h>
#include "NativeBitmap.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"
#include "IFileLoaderDelegate.h"
#include "Vec2i.h"
#include "NativeBitmap.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "NoudarDungeonSnapshot.h"
#include "GameNativeAPI.h"
#include "WindowOperations.h"
#include "Common.h"
#include "LoadPNG.h"
bool inGraphics = true;
namespace PC {
const unsigned W = 320, H = 200;
unsigned ImageBuffer[W * H];
int selector;
void Init() {
__dpmi_regs r;
r.x.ax = 0x13;
__dpmi_int(0x10, &r);
outp(0x03c8, 0);
for ( int r = 0; r < 4; ++r ) {
for ( int g = 0; g < 4; ++g ) {
for ( int b = 0; b < 4; ++b ) {
outp(0x03c9, (r * 85));
outp(0x03c9, (g * 85));
outp(0x03c9, (b * 85));
}
}
}
}
void renderPalette() {
_farsetsel(_dos_ds);
int offset = 0;
int fullSize = 320 * 200;
for (int r = 0; r < 255; ++r) {
for (int x = 0; x < 50; ++x) {
int shade = 0;
int origin = r << 16;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + r, shade);
}
}
for (int g = 0; g < 255; ++g) {
for (int x = 50; x < 100; ++x) {
int shade = 0;
int origin = g << 8;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + g, shade);
}
}
for (int b = 0; b < 255; ++b) {
for (int x = 100; x < 150; ++x) {
int shade = 0;
int origin = b;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + b, shade);
}
}
for (int b = 0; b < 255; ++b) {
for (int x = 150; x < 200; ++x) {
_farnspokeb(0xA0000 + (320 * x) + b, b);
}
}
std::fill(std::end(ImageBuffer) - (320 * 200), std::end(ImageBuffer), 0x0);
}
void Render() {
_farsetsel(_dos_ds);
auto pixelData = (*gunState)->getPixelData();
int offset = 0;
int fullSize = 320 * 200;
for (int y = 100; y < 200; ++y) {
for (int x = 80; x < 240; ++x) {
offset = (320 * y) + x;
auto origin = ImageBuffer[offset];
offset = (320 * (200 - (2 * (y - 100)))) + (((x - 80) * 320) / 160);
if (pixelData[offset] & 0xFF000000) {
origin = pixelData[offset];
}
int shade = 0;
shade += (((((origin & 0x0000FF) ) ) / 85 ) );
shade += (((((origin & 0x00FF00) >> 8 ) ) / 85 ) ) << 2;
shade += (((((origin & 0xFF0000) >> 16) ) / 85 ) ) << 4;
_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);
_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);
_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);
_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);
}
}
std::fill(std::end(ImageBuffer) - (320 * 100), std::end(ImageBuffer), 0x0);
}
void Close() // End graphics
{
textmode(C80); // Set textmode again.
}
}
void setGraphics() {
inGraphics = true;
PC::Init();
}
void setTextMode() {
inGraphics = false;
__dpmi_regs r;
r.x.ax = 3;
__dpmi_int(0x10, &r);
}
const int winWidth = 320, winHeight = 200;
bool done = false;
bool isActive = false;
std::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() {
std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn;
toReturn.push_back( loadPNG( "res/grass.ppm") );
toReturn.push_back( loadPNG( "res/stonef1.ppm") );
toReturn.push_back( loadPNG( "res/bricks.ppm") );
toReturn.push_back( loadPNG( "res/arch.ppm") );
toReturn.push_back( loadPNG( "res/bars.ppm") );
toReturn.push_back( loadPNG( "res/begin.ppm") );
toReturn.push_back( loadPNG( "res/exit.ppm") );
toReturn.push_back( loadPNG( "res/bricks2.ppm") );
toReturn.push_back( loadPNG( "res/bricks3.ppm") );
toReturn.push_back( loadPNG( "res/foe0.ppm") );
toReturn.push_back( loadPNG( "res/foe1.ppm") );
toReturn.push_back( loadPNG( "res/foe2.ppm") );
toReturn.push_back( loadPNG( "res/foe3.ppm") );
toReturn.push_back( loadPNG( "res/foe4.ppm") );
toReturn.push_back( loadPNG( "res/foe5.ppm") );
toReturn.push_back( loadPNG( "res/crusad0.ppm") );
toReturn.push_back( loadPNG( "res/crusad1.ppm") );
toReturn.push_back( loadPNG( "res/crusad2.ppm") );
toReturn.push_back( loadPNG( "res/shadow.ppm") );
toReturn.push_back( loadPNG( "res/ceilin.ppm") );
toReturn.push_back( loadPNG( "res/ceigdr.ppm") );
toReturn.push_back( loadPNG( "res/ceigbgn.ppm") );
toReturn.push_back( loadPNG( "res/ceilend.ppm") );
toReturn.push_back( loadPNG( "res/splat0.ppm") );
toReturn.push_back( loadPNG( "res/splat1.ppm") );
toReturn.push_back( loadPNG( "res/splat2.ppm") );
toReturn.push_back( loadPNG( "res/ceilbar.ppm") );
toReturn.push_back( loadPNG( "res/clouds.ppm"));
toReturn.push_back( loadPNG( "res/stngrsf.ppm"));
toReturn.push_back( loadPNG( "res/grsstnf.ppm"));
toReturn.push_back( loadPNG( "res/stngrsn.ppm"));
toReturn.push_back( loadPNG( "res/grsstnn.ppm"));
toReturn.push_back( loadPNG( "res/cross.ppm"));
return toReturn;
}
void initWindow() {
auto textures = loadTextures();
OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL);
OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H);
PC::Init();
auto gVertexShader = "";
auto gFragmentShader = "";
setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures);
auto soundListener = std::make_shared<odb::SoundListener>();
std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;
std::string filenames[] {
"res/grasssteps.wav",
"res/stepsstones.wav",
"res/bgnoise.wav",
"res/monsterdamage.wav",
"res/monsterdead.wav",
"res/playerdamage.wav",
"res/playerdead.wav",
"res/swing.wav"
};
for ( auto filename : filenames ) {
FILE *file = fopen( filename.c_str(), "r");
auto soundClip = odb::makeSoundClipFrom( file );
sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) );
}
setSoundEmitters( sounds, soundListener );
}
void tick() {
//if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined
if ( inGraphics ) {
gameLoopTick( 250 );
renderFrame( 250 );
PC::Render();
}
}
void setMainLoop() {
while ( !done ) {
while(kbhit())
switch(getch()) {
case 27: done = true; break;
case '1':
setGraphics();
break;
case '2':
setTextMode();
break;
case 'w':
moveUp();
break;
case 's':
moveDown();
break;
case 'd':
moveRight();
break;
case 'a':
moveLeft();
break;
case 'h':
interact();
break;
case 'e':
rotateCameraRight();
break;
case 'q':
rotateCameraLeft();
break;
}
tick();
}
}
void destroyWindow() {
shutdown();
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_METADATA_HPP_
#define CLUSTERING_ADMINISTRATION_METADATA_HPP_
#include <list>
#include <map>
#include <string>
#include <vector>
#include <utility>
// TODO: Probably some of these headers could be moved to the .cc.
#include "clustering/administration/database_metadata.hpp"
#include "clustering/administration/issues/local.hpp"
#include "clustering/administration/issues/outdated_index.hpp"
#include "clustering/administration/log_transfer.hpp"
#include "clustering/administration/namespace_metadata.hpp"
#include "clustering/administration/servers/machine_metadata.hpp"
#include "clustering/administration/servers/name_metadata.hpp"
#include "clustering/administration/stat_manager.hpp"
#include "containers/cow_ptr.hpp"
#include "containers/auth_key.hpp"
#include "http/json/json_adapter.hpp"
#include "rpc/semilattice/joins/cow_ptr.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/serialize_macros.hpp"
class cluster_semilattice_metadata_t {
public:
cluster_semilattice_metadata_t() { }
cow_ptr_t<namespaces_semilattice_metadata_t> rdb_namespaces;
machines_semilattice_metadata_t machines;
databases_semilattice_metadata_t databases;
};
RDB_DECLARE_SERIALIZABLE(cluster_semilattice_metadata_t);
RDB_DECLARE_SEMILATTICE_JOINABLE(cluster_semilattice_metadata_t);
RDB_DECLARE_EQUALITY_COMPARABLE(cluster_semilattice_metadata_t);
class auth_semilattice_metadata_t {
public:
auth_semilattice_metadata_t() { }
versioned_t<auth_key_t> auth_key;
};
RDB_DECLARE_SERIALIZABLE(auth_semilattice_metadata_t);
RDB_DECLARE_SEMILATTICE_JOINABLE(auth_semilattice_metadata_t);
RDB_DECLARE_EQUALITY_COMPARABLE(auth_semilattice_metadata_t);
enum cluster_directory_peer_type_t {
SERVER_PEER,
PROXY_PEER
};
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(cluster_directory_peer_type_t, int8_t, SERVER_PEER, PROXY_PEER);
class cluster_directory_metadata_t {
public:
cluster_directory_metadata_t() { }
cluster_directory_metadata_t(
machine_id_t _server_id,
peer_id_t _peer_id,
const std::string &_version,
uint64_t _cache_size,
microtime_t _time_started,
int64_t _pid,
const std::string &_hostname,
uint16_t _cluster_port,
uint16_t _reql_port,
boost::optional<uint16_t> _http_admin_port,
const get_stats_mailbox_address_t& _stats_mailbox,
const outdated_index_issue_server_t::request_address_t& _outdated_indexes_mailbox,
const log_server_business_card_t &lmb,
const boost::optional<server_name_business_card_t> &nsbc,
cluster_directory_peer_type_t _peer_type) :
machine_id(_server_id),
peer_id(_peer_id),
version(_version),
cache_size(_cache_size),
time_started(_time_started),
pid(_pid),
hostname(_hostname),
cluster_port(_cluster_port),
reql_port(_reql_port),
http_admin_port(_http_admin_port),
get_stats_mailbox_address(_stats_mailbox),
get_outdated_indexes_mailbox(_outdated_indexes_mailbox),
log_mailbox(lmb),
server_name_business_card(nsbc),
peer_type(_peer_type) { }
/* Move constructor */
cluster_directory_metadata_t(cluster_directory_metadata_t &&other) = default;
cluster_directory_metadata_t(const cluster_directory_metadata_t &other) = default;
cluster_directory_metadata_t &operator=(cluster_directory_metadata_t &&other)
= default;
cluster_directory_metadata_t &operator=(const cluster_directory_metadata_t &other)
= default;
namespaces_directory_metadata_t rdb_namespaces;
machine_id_t machine_id;
/* this is redundant, since a directory entry is always associated with a peer */
peer_id_t peer_id;
/* This group of fields are for showing in `rethinkdb.server_status` */
std::string version;
uint64_t cache_size;
microtime_t time_started;
int64_t pid; /* really a `pid_t`, but we need a platform-independent type */
std::string hostname;
uint16_t cluster_port, reql_port;
boost::optional<uint16_t> http_admin_port;
get_stats_mailbox_address_t get_stats_mailbox_address;
outdated_index_issue_server_t::request_address_t get_outdated_indexes_mailbox;
log_server_business_card_t log_mailbox;
boost::optional<server_name_business_card_t> server_name_business_card;
std::list<local_issue_t> local_issues;
cluster_directory_peer_type_t peer_type;
};
RDB_DECLARE_SERIALIZABLE(cluster_directory_metadata_t);
// ctx-less json adapter for directory_echo_wrapper_t
template <class T>
json_adapter_if_t::json_adapter_map_t get_json_subfields(directory_echo_wrapper_t<T> *target) {
return get_json_subfields(&target->internal);
}
template <class T>
cJSON *render_as_json(directory_echo_wrapper_t<T> *target) {
return render_as_json(&target->internal);
}
template <class T>
void apply_json_to(cJSON *change, directory_echo_wrapper_t<T> *target) {
apply_json_to(change, &target->internal);
}
// ctx-less json adapter concept for cluster_directory_metadata_t
json_adapter_if_t::json_adapter_map_t get_json_subfields(cluster_directory_metadata_t *target);
cJSON *render_as_json(cluster_directory_metadata_t *target);
void apply_json_to(cJSON *change, cluster_directory_metadata_t *target);
// ctx-less json adapter for cluster_directory_peer_type_t
json_adapter_if_t::json_adapter_map_t get_json_subfields(cluster_directory_peer_type_t *);
cJSON *render_as_json(cluster_directory_peer_type_t *peer_type);
void apply_json_to(cJSON *, cluster_directory_peer_type_t *);
enum metadata_search_status_t {
METADATA_SUCCESS, METADATA_ERR_NONE, METADATA_ERR_MULTIPLE
};
/* A helper class to search through metadata in various ways. Can be
constructed from a pointer to the internal map of the metadata,
e.g. `metadata.databases.databases`. Look in rdb_protocol/query_language.cc
for examples on how to use.
`generic_metadata_searcher_t` should not be directly used. Instead there
are two variants defined below:
`const_metadata_searcher_t` for const maps
and `metadata_searcher_t` for non-const maps. */
template<class T, class metamap_t, class iterator_t>
class generic_metadata_searcher_t {
public:
typedef iterator_t iterator;
iterator begin() {return map->begin();}
iterator end() {return map->end();}
explicit generic_metadata_searcher_t(metamap_t *_map): map(_map) { }
template<class callable_t>
/* Find the next iterator >= [start] matching [predicate]. */
iterator find_next(iterator start, const callable_t& predicate) {
iterator it;
for (it = start; it != end(); ++it) {
if (it->second.is_deleted()) continue;
if (predicate(it->second.get_ref())) break;
}
return it;
}
/* Find the next iterator >= [start] (as above, but predicate always true). */
iterator find_next(iterator start) {
iterator it;
for (it = start; it != end(); ++it) {
if (!it->second.is_deleted()) {
break;
}
}
return it;
}
/* Find the unique entry matching [predicate]. If there is no unique entry,
return [end()] and set the optional status parameter appropriately. */
template<class callable_t>
iterator find_uniq(const callable_t& predicate, metadata_search_status_t *out = 0) {
iterator it, retval;
if (out) *out = METADATA_SUCCESS;
retval = it = find_next(begin(), predicate);
if (it == end()) {
if (out) *out = METADATA_ERR_NONE;
} else if (find_next(++it, predicate) != end()) {
if (out) *out = METADATA_ERR_MULTIPLE;
retval = end();
}
return retval;
}
/* As above, but matches by name instead of a predicate. */
iterator find_uniq(const name_string_t &name, metadata_search_status_t *out = 0) {
return find_uniq(name_predicate_t(&name), out);
}
struct name_predicate_t {
bool operator()(T metadata) const {
return metadata.name.get_ref() == *name;
}
explicit name_predicate_t(const name_string_t *_name): name(_name) { }
private:
const name_string_t *name;
};
private:
metamap_t *map;
};
template<class T>
class metadata_searcher_t :
public generic_metadata_searcher_t<T,
typename std::map<uuid_u, deletable_t<T> >,
typename std::map<uuid_u, deletable_t<T> >::iterator> {
public:
typedef typename std::map<uuid_u, deletable_t<T> >::iterator iterator;
typedef typename std::map<uuid_u, deletable_t<T> > metamap_t;
explicit metadata_searcher_t(metamap_t *_map) :
generic_metadata_searcher_t<T, metamap_t, iterator>(_map) { }
};
template<class T>
class const_metadata_searcher_t :
public generic_metadata_searcher_t<T,
const typename std::map<uuid_u, deletable_t<T> >,
typename std::map<uuid_u, deletable_t<T> >::const_iterator> {
public:
typedef typename std::map<uuid_u, deletable_t<T> >::const_iterator iterator;
typedef const typename std::map<uuid_u, deletable_t<T> > metamap_t;
explicit const_metadata_searcher_t(metamap_t *_map) :
generic_metadata_searcher_t<T, metamap_t, iterator>(_map) { }
};
class namespace_predicate_t {
public:
bool operator()(const namespace_semilattice_metadata_t &ns) const {
if (name && ns.name.get_ref() != *name) {
return false;
} else if (db_id && ns.database.get_ref() != *db_id) {
return false;
}
return true;
}
explicit namespace_predicate_t(const name_string_t *_name): name(_name), db_id(NULL) { }
explicit namespace_predicate_t(const uuid_u *_db_id): name(NULL), db_id(_db_id) { }
namespace_predicate_t(const name_string_t *_name, const uuid_u *_db_id):
name(_name), db_id(_db_id) { }
private:
const name_string_t *name;
const uuid_u *db_id;
DISABLE_COPYING(namespace_predicate_t);
};
#endif // CLUSTERING_ADMINISTRATION_METADATA_HPP_
<commit_msg>Add comment clarifying the 'version' field of the directory metadata<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_METADATA_HPP_
#define CLUSTERING_ADMINISTRATION_METADATA_HPP_
#include <list>
#include <map>
#include <string>
#include <vector>
#include <utility>
// TODO: Probably some of these headers could be moved to the .cc.
#include "clustering/administration/database_metadata.hpp"
#include "clustering/administration/issues/local.hpp"
#include "clustering/administration/issues/outdated_index.hpp"
#include "clustering/administration/log_transfer.hpp"
#include "clustering/administration/namespace_metadata.hpp"
#include "clustering/administration/servers/machine_metadata.hpp"
#include "clustering/administration/servers/name_metadata.hpp"
#include "clustering/administration/stat_manager.hpp"
#include "containers/cow_ptr.hpp"
#include "containers/auth_key.hpp"
#include "http/json/json_adapter.hpp"
#include "rpc/semilattice/joins/cow_ptr.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/serialize_macros.hpp"
class cluster_semilattice_metadata_t {
public:
cluster_semilattice_metadata_t() { }
cow_ptr_t<namespaces_semilattice_metadata_t> rdb_namespaces;
machines_semilattice_metadata_t machines;
databases_semilattice_metadata_t databases;
};
RDB_DECLARE_SERIALIZABLE(cluster_semilattice_metadata_t);
RDB_DECLARE_SEMILATTICE_JOINABLE(cluster_semilattice_metadata_t);
RDB_DECLARE_EQUALITY_COMPARABLE(cluster_semilattice_metadata_t);
class auth_semilattice_metadata_t {
public:
auth_semilattice_metadata_t() { }
versioned_t<auth_key_t> auth_key;
};
RDB_DECLARE_SERIALIZABLE(auth_semilattice_metadata_t);
RDB_DECLARE_SEMILATTICE_JOINABLE(auth_semilattice_metadata_t);
RDB_DECLARE_EQUALITY_COMPARABLE(auth_semilattice_metadata_t);
enum cluster_directory_peer_type_t {
SERVER_PEER,
PROXY_PEER
};
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(cluster_directory_peer_type_t, int8_t, SERVER_PEER, PROXY_PEER);
class cluster_directory_metadata_t {
public:
cluster_directory_metadata_t() { }
cluster_directory_metadata_t(
machine_id_t _server_id,
peer_id_t _peer_id,
const std::string &_version,
uint64_t _cache_size,
microtime_t _time_started,
int64_t _pid,
const std::string &_hostname,
uint16_t _cluster_port,
uint16_t _reql_port,
boost::optional<uint16_t> _http_admin_port,
const get_stats_mailbox_address_t& _stats_mailbox,
const outdated_index_issue_server_t::request_address_t& _outdated_indexes_mailbox,
const log_server_business_card_t &lmb,
const boost::optional<server_name_business_card_t> &nsbc,
cluster_directory_peer_type_t _peer_type) :
machine_id(_server_id),
peer_id(_peer_id),
version(_version),
cache_size(_cache_size),
time_started(_time_started),
pid(_pid),
hostname(_hostname),
cluster_port(_cluster_port),
reql_port(_reql_port),
http_admin_port(_http_admin_port),
get_stats_mailbox_address(_stats_mailbox),
get_outdated_indexes_mailbox(_outdated_indexes_mailbox),
log_mailbox(lmb),
server_name_business_card(nsbc),
peer_type(_peer_type) { }
/* Move constructor */
cluster_directory_metadata_t(cluster_directory_metadata_t &&other) = default;
cluster_directory_metadata_t(const cluster_directory_metadata_t &other) = default;
cluster_directory_metadata_t &operator=(cluster_directory_metadata_t &&other)
= default;
cluster_directory_metadata_t &operator=(const cluster_directory_metadata_t &other)
= default;
namespaces_directory_metadata_t rdb_namespaces;
machine_id_t machine_id;
/* this is redundant, since a directory entry is always associated with a peer */
peer_id_t peer_id;
/* This group of fields are for showing in `rethinkdb.server_status` */
std::string version; /* server version string, e.g. "rethinkdb 1.X.Y ..." */
uint64_t cache_size;
microtime_t time_started;
int64_t pid; /* really a `pid_t`, but we need a platform-independent type */
std::string hostname;
uint16_t cluster_port, reql_port;
boost::optional<uint16_t> http_admin_port;
get_stats_mailbox_address_t get_stats_mailbox_address;
outdated_index_issue_server_t::request_address_t get_outdated_indexes_mailbox;
log_server_business_card_t log_mailbox;
boost::optional<server_name_business_card_t> server_name_business_card;
std::list<local_issue_t> local_issues;
cluster_directory_peer_type_t peer_type;
};
RDB_DECLARE_SERIALIZABLE(cluster_directory_metadata_t);
// ctx-less json adapter for directory_echo_wrapper_t
template <class T>
json_adapter_if_t::json_adapter_map_t get_json_subfields(directory_echo_wrapper_t<T> *target) {
return get_json_subfields(&target->internal);
}
template <class T>
cJSON *render_as_json(directory_echo_wrapper_t<T> *target) {
return render_as_json(&target->internal);
}
template <class T>
void apply_json_to(cJSON *change, directory_echo_wrapper_t<T> *target) {
apply_json_to(change, &target->internal);
}
// ctx-less json adapter concept for cluster_directory_metadata_t
json_adapter_if_t::json_adapter_map_t get_json_subfields(cluster_directory_metadata_t *target);
cJSON *render_as_json(cluster_directory_metadata_t *target);
void apply_json_to(cJSON *change, cluster_directory_metadata_t *target);
// ctx-less json adapter for cluster_directory_peer_type_t
json_adapter_if_t::json_adapter_map_t get_json_subfields(cluster_directory_peer_type_t *);
cJSON *render_as_json(cluster_directory_peer_type_t *peer_type);
void apply_json_to(cJSON *, cluster_directory_peer_type_t *);
enum metadata_search_status_t {
METADATA_SUCCESS, METADATA_ERR_NONE, METADATA_ERR_MULTIPLE
};
/* A helper class to search through metadata in various ways. Can be
constructed from a pointer to the internal map of the metadata,
e.g. `metadata.databases.databases`. Look in rdb_protocol/query_language.cc
for examples on how to use.
`generic_metadata_searcher_t` should not be directly used. Instead there
are two variants defined below:
`const_metadata_searcher_t` for const maps
and `metadata_searcher_t` for non-const maps. */
template<class T, class metamap_t, class iterator_t>
class generic_metadata_searcher_t {
public:
typedef iterator_t iterator;
iterator begin() {return map->begin();}
iterator end() {return map->end();}
explicit generic_metadata_searcher_t(metamap_t *_map): map(_map) { }
template<class callable_t>
/* Find the next iterator >= [start] matching [predicate]. */
iterator find_next(iterator start, const callable_t& predicate) {
iterator it;
for (it = start; it != end(); ++it) {
if (it->second.is_deleted()) continue;
if (predicate(it->second.get_ref())) break;
}
return it;
}
/* Find the next iterator >= [start] (as above, but predicate always true). */
iterator find_next(iterator start) {
iterator it;
for (it = start; it != end(); ++it) {
if (!it->second.is_deleted()) {
break;
}
}
return it;
}
/* Find the unique entry matching [predicate]. If there is no unique entry,
return [end()] and set the optional status parameter appropriately. */
template<class callable_t>
iterator find_uniq(const callable_t& predicate, metadata_search_status_t *out = 0) {
iterator it, retval;
if (out) *out = METADATA_SUCCESS;
retval = it = find_next(begin(), predicate);
if (it == end()) {
if (out) *out = METADATA_ERR_NONE;
} else if (find_next(++it, predicate) != end()) {
if (out) *out = METADATA_ERR_MULTIPLE;
retval = end();
}
return retval;
}
/* As above, but matches by name instead of a predicate. */
iterator find_uniq(const name_string_t &name, metadata_search_status_t *out = 0) {
return find_uniq(name_predicate_t(&name), out);
}
struct name_predicate_t {
bool operator()(T metadata) const {
return metadata.name.get_ref() == *name;
}
explicit name_predicate_t(const name_string_t *_name): name(_name) { }
private:
const name_string_t *name;
};
private:
metamap_t *map;
};
template<class T>
class metadata_searcher_t :
public generic_metadata_searcher_t<T,
typename std::map<uuid_u, deletable_t<T> >,
typename std::map<uuid_u, deletable_t<T> >::iterator> {
public:
typedef typename std::map<uuid_u, deletable_t<T> >::iterator iterator;
typedef typename std::map<uuid_u, deletable_t<T> > metamap_t;
explicit metadata_searcher_t(metamap_t *_map) :
generic_metadata_searcher_t<T, metamap_t, iterator>(_map) { }
};
template<class T>
class const_metadata_searcher_t :
public generic_metadata_searcher_t<T,
const typename std::map<uuid_u, deletable_t<T> >,
typename std::map<uuid_u, deletable_t<T> >::const_iterator> {
public:
typedef typename std::map<uuid_u, deletable_t<T> >::const_iterator iterator;
typedef const typename std::map<uuid_u, deletable_t<T> > metamap_t;
explicit const_metadata_searcher_t(metamap_t *_map) :
generic_metadata_searcher_t<T, metamap_t, iterator>(_map) { }
};
class namespace_predicate_t {
public:
bool operator()(const namespace_semilattice_metadata_t &ns) const {
if (name && ns.name.get_ref() != *name) {
return false;
} else if (db_id && ns.database.get_ref() != *db_id) {
return false;
}
return true;
}
explicit namespace_predicate_t(const name_string_t *_name): name(_name), db_id(NULL) { }
explicit namespace_predicate_t(const uuid_u *_db_id): name(NULL), db_id(_db_id) { }
namespace_predicate_t(const name_string_t *_name, const uuid_u *_db_id):
name(_name), db_id(_db_id) { }
private:
const name_string_t *name;
const uuid_u *db_id;
DISABLE_COPYING(namespace_predicate_t);
};
#endif // CLUSTERING_ADMINISTRATION_METADATA_HPP_
<|endoftext|>
|
<commit_before>#include <cmd_quest_pass_handler.h>
#include <runtasks.h>
#include <log.h>
#include <utils.h>
#include <QJsonArray>
#include <QCryptographicHash>
CmdQuestPassHandler::CmdQuestPassHandler(){
m_vInputs.push_back(CmdInputDef("questid").integer_().required().description("Quest ID"));
m_vInputs.push_back(CmdInputDef("answer").string_().required().description("Answer"));
TAG = "CmdQuestPassHandler";
}
QString CmdQuestPassHandler::cmd(){
return "quest_pass";
}
bool CmdQuestPassHandler::accessUnauthorized(){
return false;
}
bool CmdQuestPassHandler::accessUser(){
return true;
}
bool CmdQuestPassHandler::accessTester(){
return true;
}
bool CmdQuestPassHandler::accessAdmin(){
return true;
}
const QVector<CmdInputDef> &CmdQuestPassHandler::inputs(){
return m_vInputs;
};
QString CmdQuestPassHandler::description(){
return "Update the quest info";
}
QStringList CmdQuestPassHandler::errors(){
QStringList list;
return list;
}
void CmdQuestPassHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){
QJsonObject jsonData;
jsonData["cmd"] = QJsonValue(cmd());
QSqlDatabase db = *(pWebSocketServer->database());
IUserToken *pUserToken = pWebSocketServer->getUserToken(pClient);
int nUserID = 0;
QString sNick = "";
if(pUserToken != NULL) {
nUserID = pUserToken->userid();
sNick = pUserToken->nick();
}
int nQuestID = obj["questid"].toInt();
QString sUserAnswer = obj["answer"].toString().trimmed();
QString sState = "";
QString sQuestAnswer = "";
QString sQuestName = "";
int nGameID = 0;
{
QSqlQuery query(db);
query.prepare("SELECT * FROM quest WHERE idquest = :questid");
query.bindValue(":questid", nQuestID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
sState = record.value("state").toString();
sQuestAnswer = record.value("answer").toString().trimmed();
sQuestName = record.value("name").toString().trimmed();
nGameID = record.value("gameid").toInt();
}else{
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Quest not found"));
return;
}
}
{
QSqlQuery query(db);
query.prepare("SELECT * FROM games WHERE id = 2 AND (NOW() < date_stop OR NOW() > date_restart)");
query.bindValue(":gameid", nGameID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (!query.next()) {
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Game ended. Please "));
return;
}
}
// check passed quest
{
QSqlQuery query(db);
query.prepare("SELECT COUNT(*) as cnt FROM users_quests WHERE questid = :questid AND userid = :userid");
query.bindValue(":questid", nQuestID);
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
if(record.value("cnt").toInt() > 0){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Quest already passed"));
return;
}
}
}
// check answer
{
QSqlQuery query(db);
query.prepare("SELECT COUNT(*) as cnt FROM users_quests_answers WHERE user_answer = :user_asnwer AND questid = :questid AND userid = :userid");
query.bindValue(":user_answer", sUserAnswer);
query.bindValue(":questid", nQuestID);
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
if(record.value("cnt").toInt() > 0){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Your already try this answer."));
return;
}
}
}
bool bPassed = sQuestAnswer.toUpper() == sUserAnswer.toUpper();
QString sPassed = bPassed ? "Yes" : "No";
// insert to user tries
{
QSqlQuery query(db);
query.prepare("INSERT INTO users_quests_answers(userid, questid, user_answer, quest_answer, passed, levenshtein, dt) "
"VALUES(:userid, :questid, :user_answer, :quest_answer, :passed, :levenshtein, NOW())");
query.bindValue(":userid", nUserID);
query.bindValue(":questid", nQuestID);
query.bindValue(":user_answer", sUserAnswer);
query.bindValue(":quest_answer", sQuestAnswer);
query.bindValue(":passed", sPassed);
int nLevenshtein = UtilsLevenshtein::distance(sUserAnswer.toUpper(), sQuestAnswer.toUpper());
query.bindValue(":levenshtein", nLevenshtein);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
}
if(!bPassed){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Answer incorrect"));
return;
}
// insert to user passed quests
{
QSqlQuery query(db);
query.prepare("INSERT INTO users_quests(userid, questid, dt_passed) "
"VALUES(:userid, :questid, NOW())");
query.bindValue(":userid", nUserID);
query.bindValue(":questid", nQuestID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
}
RunTasks::AddPublicEvents(pWebSocketServer, "quests", "User #" + QString::number(nUserID) + " " + sNick
+ " passed quest #" + QString::number(nQuestID) + " " + sQuestName);
RunTasks::UpdateUserRating(pWebSocketServer, nUserID);
RunTasks::UpdateQuestSolved(pWebSocketServer, nQuestID);
jsonData["result"] = QJsonValue("DONE");
jsonData["m"] = QJsonValue(m);
pWebSocketServer->sendMessage(pClient, jsonData);
}
<commit_msg>Fixed critical bug with game ended<commit_after>#include <cmd_quest_pass_handler.h>
#include <runtasks.h>
#include <log.h>
#include <utils.h>
#include <QJsonArray>
#include <QCryptographicHash>
CmdQuestPassHandler::CmdQuestPassHandler(){
m_vInputs.push_back(CmdInputDef("questid").integer_().required().description("Quest ID"));
m_vInputs.push_back(CmdInputDef("answer").string_().required().description("Answer"));
TAG = "CmdQuestPassHandler";
}
QString CmdQuestPassHandler::cmd(){
return "quest_pass";
}
bool CmdQuestPassHandler::accessUnauthorized(){
return false;
}
bool CmdQuestPassHandler::accessUser(){
return true;
}
bool CmdQuestPassHandler::accessTester(){
return true;
}
bool CmdQuestPassHandler::accessAdmin(){
return true;
}
const QVector<CmdInputDef> &CmdQuestPassHandler::inputs(){
return m_vInputs;
};
QString CmdQuestPassHandler::description(){
return "Update the quest info";
}
QStringList CmdQuestPassHandler::errors(){
QStringList list;
return list;
}
void CmdQuestPassHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){
QJsonObject jsonData;
jsonData["cmd"] = QJsonValue(cmd());
QSqlDatabase db = *(pWebSocketServer->database());
IUserToken *pUserToken = pWebSocketServer->getUserToken(pClient);
int nUserID = 0;
QString sNick = "";
if(pUserToken != NULL) {
nUserID = pUserToken->userid();
sNick = pUserToken->nick();
}
int nQuestID = obj["questid"].toInt();
QString sUserAnswer = obj["answer"].toString().trimmed();
QString sState = "";
QString sQuestAnswer = "";
QString sQuestName = "";
int nGameID = 0;
{
QSqlQuery query(db);
query.prepare("SELECT * FROM quest WHERE idquest = :questid");
query.bindValue(":questid", nQuestID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
sState = record.value("state").toString();
sQuestAnswer = record.value("answer").toString().trimmed();
sQuestName = record.value("name").toString().trimmed();
nGameID = record.value("gameid").toInt();
}else{
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Quest not found"));
return;
}
}
{
QSqlQuery query(db);
query.prepare("SELECT * FROM games WHERE id = :gameid AND (NOW() < date_stop OR NOW() > date_restart)");
query.bindValue(":gameid", nGameID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (!query.next()) {
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Game ended. Please wait date of restart."));
return;
}
}
// check passed quest
{
QSqlQuery query(db);
query.prepare("SELECT COUNT(*) as cnt FROM users_quests WHERE questid = :questid AND userid = :userid");
query.bindValue(":questid", nQuestID);
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
if(record.value("cnt").toInt() > 0){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Quest already passed"));
return;
}
}
}
// check answer
{
QSqlQuery query(db);
query.prepare("SELECT COUNT(*) as cnt FROM users_quests_answers WHERE user_answer = :user_asnwer AND questid = :questid AND userid = :userid");
query.bindValue(":user_answer", sUserAnswer);
query.bindValue(":questid", nQuestID);
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
if(record.value("cnt").toInt() > 0){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Your already try this answer."));
return;
}
}
}
bool bPassed = sQuestAnswer.toUpper() == sUserAnswer.toUpper();
QString sPassed = bPassed ? "Yes" : "No";
// insert to user tries
{
QSqlQuery query(db);
query.prepare("INSERT INTO users_quests_answers(userid, questid, user_answer, quest_answer, passed, levenshtein, dt) "
"VALUES(:userid, :questid, :user_answer, :quest_answer, :passed, :levenshtein, NOW())");
query.bindValue(":userid", nUserID);
query.bindValue(":questid", nQuestID);
query.bindValue(":user_answer", sUserAnswer);
query.bindValue(":quest_answer", sQuestAnswer);
query.bindValue(":passed", sPassed);
int nLevenshtein = UtilsLevenshtein::distance(sUserAnswer.toUpper(), sQuestAnswer.toUpper());
query.bindValue(":levenshtein", nLevenshtein);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
}
if(!bPassed){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Answer incorrect"));
return;
}
// insert to user passed quests
{
QSqlQuery query(db);
query.prepare("INSERT INTO users_quests(userid, questid, dt_passed) "
"VALUES(:userid, :questid, NOW())");
query.bindValue(":userid", nUserID);
query.bindValue(":questid", nQuestID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
}
RunTasks::AddPublicEvents(pWebSocketServer, "quests", "User #" + QString::number(nUserID) + " " + sNick
+ " passed quest #" + QString::number(nQuestID) + " " + sQuestName);
RunTasks::UpdateUserRating(pWebSocketServer, nUserID);
RunTasks::UpdateQuestSolved(pWebSocketServer, nQuestID);
jsonData["result"] = QJsonValue("DONE");
jsonData["m"] = QJsonValue(m);
pWebSocketServer->sendMessage(pClient, jsonData);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <boost/signals2.hpp>
#include <map>
#include <memory>
#include "basewrapper.h"
using FuncSig = void();
class MySig : BaseWrapper, public boost::signals2::signal<FuncSig> {
// This class is just a boost::signals2::signal<FuncSig>
// with a bit of extra-stuff for monitoring constructor/destructor behaviour (via BaseWrapper)
public:
MySig() : BaseWrapper{"sig"}, boost::signals2::signal<FuncSig>{}
{}
};
using Signal_t = MySig;
template<typename T>
inline bool inner_unique_ptr_valid(const std::shared_ptr<std::unique_ptr<T>> &p)
{
return (p // shared_pointer holding an actual pointer
&&
*p); // unique_pointer holding an actual pointer
}
class Functor : BaseWrapper {
// Functor that we'll be using as a slot
public:
Functor(std::shared_ptr<std::unique_ptr<Signal_t>> sig_p_, const std::string &name_, bool destruct_sig_ = false)
: BaseWrapper{name_}, sig_p{sig_p_}, destruct_sig{destruct_sig_}
{
}
Functor(const Functor &other)
: BaseWrapper{other}, sig_p{other.sig_p}, destruct_sig{other.destruct_sig}
{
}
~Functor()
{
}
void operator()() {
std::cout << " >>>>>>>>>>>>>>>>>>>>>>\n"
<< " (" << get_name() << ") Functor::operator()()" << std::endl;
if (destruct_sig) {
if (inner_unique_ptr_valid(sig_p)) {
(*sig_p).reset(); // reset unique_ptr (it's content is replaced with nullptr, and the previous ptr-content deleted)
std::cout << " Deleted sig" << std::endl;
} else {
std::cout << " sig already deleted" << std::endl;
}
}
std::cout << " (" << get_name() << ") Done -- Functor::operator()()\n"
<< " -----------------------" << std::endl;
}
private:
std::shared_ptr<std::unique_ptr<Signal_t>> sig_p;
bool destruct_sig;
};
void my_connect(const std::shared_ptr<std::unique_ptr<Signal_t>> &sig_p, const Signal_t::slot_type &slot)
{
if (inner_unique_ptr_valid(sig_p)) {
(*sig_p)->connect(slot); // connect to slot (functor)
}
}
int main()
{
std::shared_ptr<std::unique_ptr<Signal_t>> sig_p = std::make_shared<std::unique_ptr<Signal_t>>(new Signal_t);
/* Background on the above type:
This should behave like shared_ptr, but one whose content can be globally destructed from anywhere.
Anybody still having access, needs to check if it has been destructed.
If nobody has access anymore, it needs to destruct itself.
// The usage is thus:
if (inner_unique_ptr_valid(sig_p)) { // check if still valid
(**sig_p).member(); // access
}
// The two steps above would need to be mutex-protected in a multithreaded environment
// To globally destruct:
if (sig_p) { // check that shared_ptr is actually holding a pointer (in this case a unique_ptr)
(*sig_p).reset(); // reset the unique_ptr
}
*/
#define DELETE_SIG_IN_FUNCTOR_SLOT
{
Functor f1{sig_p, "f1"};
my_connect(sig_p, f1);
Functor f2{sig_p, "f2"};
my_connect(sig_p, f2);
Functor f3{sig_p, "f3"
#ifdef DELETE_SIG_IN_FUNCTOR_SLOT
, true // this functor-slot, should destruct the signal
#endif
};
my_connect(sig_p, f3);
Functor f4{sig_p, "f4"};
my_connect(sig_p, f4);
Functor f5{sig_p, "f5"};
my_connect(sig_p, f5);
// local functors go out of scope!
}
if (inner_unique_ptr_valid(sig_p)) {
(**sig_p)(); // emit signal
std::cout << "signal emit - Finished" << std::endl;
}
if (inner_unique_ptr_valid(sig_p)) {
(*sig_p).reset();
std::cout << "sig deleted in main(); not in functor" << std::endl;
}
std::cout << "End" << std::endl;
return 0;
}
<commit_msg>map not needed<commit_after>#include <iostream>
#include <boost/signals2.hpp>
#include <memory>
#include "basewrapper.h"
using FuncSig = void();
class MySig : BaseWrapper, public boost::signals2::signal<FuncSig> {
// This class is just a boost::signals2::signal<FuncSig>
// with a bit of extra-stuff for monitoring constructor/destructor behaviour (via BaseWrapper)
public:
MySig() : BaseWrapper{"sig"}, boost::signals2::signal<FuncSig>{}
{}
};
using Signal_t = MySig;
template<typename T>
inline bool inner_unique_ptr_valid(const std::shared_ptr<std::unique_ptr<T>> &p)
{
return (p // shared_pointer holding an actual pointer
&&
*p); // unique_pointer holding an actual pointer
}
class Functor : BaseWrapper {
// Functor that we'll be using as a slot
public:
Functor(std::shared_ptr<std::unique_ptr<Signal_t>> sig_p_, const std::string &name_, bool destruct_sig_ = false)
: BaseWrapper{name_}, sig_p{sig_p_}, destruct_sig{destruct_sig_}
{
}
Functor(const Functor &other)
: BaseWrapper{other}, sig_p{other.sig_p}, destruct_sig{other.destruct_sig}
{
}
~Functor()
{
}
void operator()() {
std::cout << " >>>>>>>>>>>>>>>>>>>>>>\n"
<< " (" << get_name() << ") Functor::operator()()" << std::endl;
if (destruct_sig) {
if (inner_unique_ptr_valid(sig_p)) {
(*sig_p).reset(); // reset unique_ptr (it's content is replaced with nullptr, and the previous ptr-content deleted)
std::cout << " Deleted sig" << std::endl;
} else {
std::cout << " sig already deleted" << std::endl;
}
}
std::cout << " (" << get_name() << ") Done -- Functor::operator()()\n"
<< " -----------------------" << std::endl;
}
private:
std::shared_ptr<std::unique_ptr<Signal_t>> sig_p;
bool destruct_sig;
};
void my_connect(const std::shared_ptr<std::unique_ptr<Signal_t>> &sig_p, const Signal_t::slot_type &slot)
{
if (inner_unique_ptr_valid(sig_p)) {
(*sig_p)->connect(slot); // connect to slot (functor)
}
}
int main()
{
std::shared_ptr<std::unique_ptr<Signal_t>> sig_p = std::make_shared<std::unique_ptr<Signal_t>>(new Signal_t);
/* Background on the above type:
This should behave like shared_ptr, but one whose content can be globally destructed from anywhere.
Anybody still having access, needs to check if it has been destructed.
If nobody has access anymore, it needs to destruct itself.
// The usage is thus:
if (inner_unique_ptr_valid(sig_p)) { // check if still valid
(**sig_p).member(); // access
}
// The two steps above would need to be mutex-protected in a multithreaded environment
// To globally destruct:
if (sig_p) { // check that shared_ptr is actually holding a pointer (in this case a unique_ptr)
(*sig_p).reset(); // reset the unique_ptr
}
*/
#define DELETE_SIG_IN_FUNCTOR_SLOT
{
Functor f1{sig_p, "f1"};
my_connect(sig_p, f1);
Functor f2{sig_p, "f2"};
my_connect(sig_p, f2);
Functor f3{sig_p, "f3"
#ifdef DELETE_SIG_IN_FUNCTOR_SLOT
, true // this functor-slot, should destruct the signal
#endif
};
my_connect(sig_p, f3);
Functor f4{sig_p, "f4"};
my_connect(sig_p, f4);
Functor f5{sig_p, "f5"};
my_connect(sig_p, f5);
// local functors go out of scope!
}
if (inner_unique_ptr_valid(sig_p)) {
(**sig_p)(); // emit signal
std::cout << "signal emit - Finished" << std::endl;
}
if (inner_unique_ptr_valid(sig_p)) {
(*sig_p).reset();
std::cout << "sig deleted in main(); not in functor" << std::endl;
}
std::cout << "End" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003 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.
*/
#include <assert.h>
#include "base/callback.hh"
#include "base/inifile.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/configfile.hh"
#include "sim/host.hh"
#include "sim/sim_object.hh"
#include "sim/sim_stats.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// SimObject member definitions
//
////////////////////////////////////////////////////////////////////////
//
// static list of all SimObjects, used for initialization etc.
//
SimObject::SimObjectList SimObject::simObjectList;
//
// SimObject constructor: used to maintain static simObjectList
//
SimObject::SimObject(const string &_name)
: objName(_name)
{
simObjectList.push_back(this);
}
void
SimObject::init()
{
}
//
// no default statistics, so nothing to do in base implementation
//
void
SimObject::regStats()
{
}
void
SimObject::regFormulas()
{
}
void
SimObject::resetStats()
{
}
//
// no default extra output
//
void
SimObject::printExtraOutput(ostream &os)
{
}
//
// static function:
// call regStats() on all SimObjects and then regFormulas() on all
// SimObjects.
//
struct SimObjectResetCB : public Callback
{
virtual void process() { SimObject::resetAllStats(); }
};
namespace {
static SimObjectResetCB StatResetCB;
}
void
SimObject::regAllStats()
{
SimObjectList::iterator i;
SimObjectList::iterator end = simObjectList.end();
/**
* @todo change cprintfs to DPRINTFs
*/
for (i = simObjectList.begin(); i != end; ++i) {
#ifdef STAT_DEBUG
cprintf("registering stats for %s\n", (*i)->name());
#endif
(*i)->regStats();
}
for (i = simObjectList.begin(); i != end; ++i) {
#ifdef STAT_DEBUG
cprintf("registering formulas for %s\n", (*i)->name());
#endif
(*i)->regFormulas();
}
Statistics::registerResetCallback(&StatResetCB);
}
//
// static function: call init() on all SimObjects.
//
void
SimObject::initAll()
{
SimObjectList::iterator i = simObjectList.begin();
SimObjectList::iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
obj->init();
}
}
//
// static function: call resetStats() on all SimObjects.
//
void
SimObject::resetAllStats()
{
SimObjectList::iterator i = simObjectList.begin();
SimObjectList::iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
obj->resetStats();
}
}
//
// static function: call printExtraOutput() on all SimObjects.
//
void
SimObject::printAllExtraOutput(ostream &os)
{
SimObjectList::iterator i = simObjectList.begin();
SimObjectList::iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
obj->printExtraOutput(os);
}
}
//
// static function: serialize all SimObjects.
//
void
SimObject::serializeAll(ostream &os)
{
SimObjectList::iterator i = simObjectList.begin();
SimObjectList::iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
obj->nameOut(os);
obj->serialize(os);
}
}
<commit_msg>Change order of serialization<commit_after>/*
* Copyright (c) 2003 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.
*/
#include <assert.h>
#include "base/callback.hh"
#include "base/inifile.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/configfile.hh"
#include "sim/host.hh"
#include "sim/sim_object.hh"
#include "sim/sim_stats.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// SimObject member definitions
//
////////////////////////////////////////////////////////////////////////
//
// static list of all SimObjects, used for initialization etc.
//
SimObject::SimObjectList SimObject::simObjectList;
//
// SimObject constructor: used to maintain static simObjectList
//
SimObject::SimObject(const string &_name)
: objName(_name)
{
simObjectList.push_back(this);
}
void
SimObject::init()
{
}
//
// no default statistics, so nothing to do in base implementation
//
void
SimObject::regStats()
{
}
void
SimObject::regFormulas()
{
}
void
SimObject::resetStats()
{
}
//
// no default extra output
//
void
SimObject::printExtraOutput(ostream &os)
{
}
//
// static function:
// call regStats() on all SimObjects and then regFormulas() on all
// SimObjects.
//
struct SimObjectResetCB : public Callback
{
virtual void process() { SimObject::resetAllStats(); }
};
namespace {
static SimObjectResetCB StatResetCB;
}
void
SimObject::regAllStats()
{
SimObjectList::iterator i;
SimObjectList::iterator end = simObjectList.end();
/**
* @todo change cprintfs to DPRINTFs
*/
for (i = simObjectList.begin(); i != end; ++i) {
#ifdef STAT_DEBUG
cprintf("registering stats for %s\n", (*i)->name());
#endif
(*i)->regStats();
}
for (i = simObjectList.begin(); i != end; ++i) {
#ifdef STAT_DEBUG
cprintf("registering formulas for %s\n", (*i)->name());
#endif
(*i)->regFormulas();
}
Statistics::registerResetCallback(&StatResetCB);
}
//
// static function: call init() on all SimObjects.
//
void
SimObject::initAll()
{
SimObjectList::iterator i = simObjectList.begin();
SimObjectList::iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
obj->init();
}
}
//
// static function: call resetStats() on all SimObjects.
//
void
SimObject::resetAllStats()
{
SimObjectList::iterator i = simObjectList.begin();
SimObjectList::iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
obj->resetStats();
}
}
//
// static function: call printExtraOutput() on all SimObjects.
//
void
SimObject::printAllExtraOutput(ostream &os)
{
SimObjectList::iterator i = simObjectList.begin();
SimObjectList::iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
obj->printExtraOutput(os);
}
}
//
// static function: serialize all SimObjects.
//
void
SimObject::serializeAll(ostream &os)
{
SimObjectList::reverse_iterator ri = simObjectList.rbegin();
SimObjectList::reverse_iterator rend = simObjectList.rend();
for (; ri != rend; ++ri) {
SimObject *obj = *ri;
obj->nameOut(os);
obj->serialize(os);
}
}
<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2015, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Particles/ParticlesCollisionRepresentation.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/ParticlesShape.h"
#include "SurgSim/Math/Shape.h"
#include "SurgSim/Particles/Representation.h"
namespace SurgSim
{
namespace Particles
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Particles::ParticlesCollisionRepresentation,
ParticlesCollisionRepresentation);
ParticlesCollisionRepresentation::ParticlesCollisionRepresentation(const std::string& name) :
SurgSim::Collision::Representation(name),
m_shape(std::make_shared<SurgSim::Math::ParticlesShape>())
{
m_shape->setRadius(0.005);
}
ParticlesCollisionRepresentation::~ParticlesCollisionRepresentation()
{
}
void ParticlesCollisionRepresentation::update(const double& dt)
{
*m_shape = getParticleRepresentation()->getParticles().unsafeGet();
invalidatePosedShape();
}
bool ParticlesCollisionRepresentation::doInitialize()
{
return true;
}
bool ParticlesCollisionRepresentation::doWakeUp()
{
auto particleRepresentation = m_particleRepresentation.lock();
if (particleRepresentation == nullptr)
{
SURGSIM_LOG_SEVERE(SurgSim::Framework::Logger::getDefaultLogger()) << getName()
<< ": does not have a Particle Representation.";
return false;
}
m_shape->getVertices().reserve(particleRepresentation->getMaxParticles());
update(0.0);
return true;
}
int ParticlesCollisionRepresentation::getShapeType() const
{
return m_shape->getType();
}
const std::shared_ptr<SurgSim::Math::Shape> ParticlesCollisionRepresentation::getShape() const
{
return m_shape;
}
void ParticlesCollisionRepresentation::setParticleRepresentation(
std::shared_ptr<SurgSim::Particles::Representation> representation)
{
m_particleRepresentation = representation;
}
const std::shared_ptr<SurgSim::Particles::Representation> ParticlesCollisionRepresentation::getParticleRepresentation()
const
{
auto particleRepresentation = m_particleRepresentation.lock();
SURGSIM_ASSERT(particleRepresentation != nullptr) <<
"Failed to get the Particle Representation. The ParticlesCollisionRepresentation either was not "
"attached to a Particle Representation or the Particle Representation has expired.";
return particleRepresentation;
}
void ParticlesCollisionRepresentation::setParticleRadius(double radius)
{
m_shape->setRadius(radius);
}
double ParticlesCollisionRepresentation::getParticleRadius() const
{
return m_shape->getRadius();
}
};
};
<commit_msg>Changes default particle size in the collisio rep<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2015, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Particles/ParticlesCollisionRepresentation.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/ParticlesShape.h"
#include "SurgSim/Math/Shape.h"
#include "SurgSim/Particles/Representation.h"
namespace SurgSim
{
namespace Particles
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Particles::ParticlesCollisionRepresentation,
ParticlesCollisionRepresentation);
ParticlesCollisionRepresentation::ParticlesCollisionRepresentation(const std::string& name) :
SurgSim::Collision::Representation(name),
m_shape(std::make_shared<SurgSim::Math::ParticlesShape>())
{
m_shape->setRadius(0.01);
}
ParticlesCollisionRepresentation::~ParticlesCollisionRepresentation()
{
}
void ParticlesCollisionRepresentation::update(const double& dt)
{
*m_shape = getParticleRepresentation()->getParticles().unsafeGet();
invalidatePosedShape();
}
bool ParticlesCollisionRepresentation::doInitialize()
{
return true;
}
bool ParticlesCollisionRepresentation::doWakeUp()
{
auto particleRepresentation = m_particleRepresentation.lock();
if (particleRepresentation == nullptr)
{
SURGSIM_LOG_SEVERE(SurgSim::Framework::Logger::getDefaultLogger()) << getName()
<< ": does not have a Particle Representation.";
return false;
}
m_shape->getVertices().reserve(particleRepresentation->getMaxParticles());
update(0.0);
return true;
}
int ParticlesCollisionRepresentation::getShapeType() const
{
return m_shape->getType();
}
const std::shared_ptr<SurgSim::Math::Shape> ParticlesCollisionRepresentation::getShape() const
{
return m_shape;
}
void ParticlesCollisionRepresentation::setParticleRepresentation(
std::shared_ptr<SurgSim::Particles::Representation> representation)
{
m_particleRepresentation = representation;
}
const std::shared_ptr<SurgSim::Particles::Representation> ParticlesCollisionRepresentation::getParticleRepresentation()
const
{
auto particleRepresentation = m_particleRepresentation.lock();
SURGSIM_ASSERT(particleRepresentation != nullptr) <<
"Failed to get the Particle Representation. The ParticlesCollisionRepresentation either was not "
"attached to a Particle Representation or the Particle Representation has expired.";
return particleRepresentation;
}
void ParticlesCollisionRepresentation::setParticleRadius(double radius)
{
m_shape->setRadius(radius);
}
double ParticlesCollisionRepresentation::getParticleRadius() const
{
return m_shape->getRadius();
}
};
};
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbMacro.h"
#include "itkExceptionObject.h"
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include <iostream>
#include "itkParametricPath.h"
#include "itkPolyLineParametricPath.h"
#include "itkVectorContainer.h"
#include "otbImageFileReader.h"
#include "otbImageToPathListAlignFilter.h"
#include "itkPath.h"
#include "itkPathSource.h"
#include "otbPathListSource.h"
#include "otbImageToPathListFilter.h"
#include "itkContinuousIndex.h"
#include <stdio.h>
int otbAlignImageToPath(int argc, char * argv[])
{
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
typedef double InputPixelType;
typedef double OutputPixelType;
typedef double RealPixelType;
const unsigned int Dimension = 2;
typedef itk::Image<InputPixelType, Dimension> InputImageType;
typedef itk::Image<RealPixelType, Dimension> RealImageType;
typedef itk::PolyLineParametricPath<Dimension> PathType;
typedef PathType::Pointer PathTypePointer;
PathType::Pointer ltoto = PathType::New();
typedef itk::Image<OutputPixelType, Dimension> OutputImageType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::ImageToPathListAlignFilter<InputImageType, PathType> ListAlignFilterType;
typedef itk::ImageFileWriter<OutputImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
InputImageType::Pointer ImageIn = InputImageType::New();
typedef otb::ImageToPathListAlignFilter<InputImageType, PathType> TestType;
TestType::Pointer testList = TestType::New();
reader->SetFileName(inputFilename);
//OTB-FA-00010-CS
testList->SetInput(reader->GetOutput());
typedef ListAlignFilterType::OutputPathListType ListAlignFilterOutputPathListType;
otbGenericMsgDebugMacro(<< "Before update");
testList->Update();
otbGenericMsgDebugMacro(<< "After update");
ListAlignFilterOutputPathListType * sortiePath = testList->GetOutput();
otbGenericMsgDebugMacro(<< "Writing :");
FILE *file = fopen(outputFilename, "w");
if (file == NULL)
{
fprintf(stderr, "Error, can't open file");
exit(-1);
}
typedef itk::ContinuousIndex<double, 2> VertexType;
typedef itk::VectorContainer<unsigned, VertexType> VertexListType;
typedef VertexListType::ConstPointer VertexListTypePointer;
VertexListTypePointer vertexList;
VertexType cindex;
double x1, y1, x2, y2;
int nbPath = sortiePath->Size();
otbGenericMsgDebugMacro(<< "NbSegment: " << nbPath);
fprintf(file, "Nb Segment: %d\n", nbPath);
for (int i = 0; i < nbPath; i++)
{
vertexList = sortiePath->GetNthElement(i)->GetVertexList();
cindex = vertexList->GetElement(0);
x1 = cindex[0];
y1 = cindex[1];
cindex = vertexList->GetElement(1);
x2 = cindex[0];
y2 = cindex[1];
fprintf(file, "%8.3f %8.3f\n", x1, y1);
}
fclose(file);
// writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>ENH: add more coverage for otbAlignImageToPath class<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbMacro.h"
#include "itkExceptionObject.h"
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include <iostream>
#include "itkParametricPath.h"
#include "itkPolyLineParametricPath.h"
#include "itkVectorContainer.h"
#include "otbImageFileReader.h"
#include "otbImageToPathListAlignFilter.h"
#include "itkPath.h"
#include "itkPathSource.h"
#include "otbPathListSource.h"
#include "otbImageToPathListFilter.h"
#include "itkContinuousIndex.h"
#include <stdio.h>
int otbAlignImageToPath(int argc, char * argv[])
{
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
typedef double InputPixelType;
typedef double OutputPixelType;
typedef double RealPixelType;
const unsigned int Dimension = 2;
typedef itk::Image<InputPixelType, Dimension> InputImageType;
typedef itk::Image<RealPixelType, Dimension> RealImageType;
typedef itk::PolyLineParametricPath<Dimension> PathType;
typedef PathType::Pointer PathTypePointer;
PathType::Pointer ltoto = PathType::New();
typedef itk::Image<OutputPixelType, Dimension> OutputImageType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::ImageToPathListAlignFilter<InputImageType, PathType> ListAlignFilterType;
typedef ListAlignFilterType::ValueType ValueType;
typedef ListAlignFilterType::SizeType SizeType;
typedef itk::ImageFileWriter<OutputImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
InputImageType::Pointer ImageIn = InputImageType::New();
ListAlignFilterType::Pointer testList = ListAlignFilterType::New();
reader->SetFileName(inputFilename);
//OTB-FA-00010-CS
testList->SetInput(reader->GetOutput());
typedef ListAlignFilterType::OutputPathListType ListAlignFilterOutputPathListType;
otbGenericMsgDebugMacro(<< "Before update");
testList->Update();
otbGenericMsgDebugMacro(<< "After update");
ValueType pathValue;
pathValue = testList->GetPathValue();
testList->SetPathValue(pathValue);
ValueType backgroundValue;
backgroundValue = testList->GetBackgroundValue();
testList->SetBackgroundValue(backgroundValue);
SizeType size;
size = testList->GetSize();
testList->SetSize(size);
bool isMeaningfulSegment;
isMeaningfulSegment = testList->GetisMeaningfulSegment();
testList->SetisMeaningfulSegment(isMeaningfulSegment);
int NbGradDirection;
NbGradDirection = testList->GetNbGradDirection();
testList->SetNbGradDirection(NbGradDirection);
int NbLineDirection;
NbLineDirection = testList->GetNbLineDirection();
testList->SetNbLineDirection(NbLineDirection);
double MinGradNorm;
MinGradNorm = testList->GetMinGradNorm();
testList->SetMinGradNorm(MinGradNorm);
double Eps;
Eps = testList->GetEps();
testList->SetEps(Eps);
ListAlignFilterOutputPathListType * sortiePath = testList->GetOutput();
otbGenericMsgDebugMacro(<< "Writing :");
FILE *file = fopen(outputFilename, "w");
if (file == NULL)
{
fprintf(stderr, "Error, can't open file");
exit(-1);
}
typedef itk::ContinuousIndex<double, 2> VertexType;
typedef itk::VectorContainer<unsigned, VertexType> VertexListType;
typedef VertexListType::ConstPointer VertexListTypePointer;
VertexListTypePointer vertexList;
VertexType cindex;
double x1, y1, x2, y2;
int nbPath = sortiePath->Size();
otbGenericMsgDebugMacro(<< "NbSegment: " << nbPath);
fprintf(file, "Nb Segment: %d\n", nbPath);
for (int i = 0; i < nbPath; i++)
{
vertexList = sortiePath->GetNthElement(i)->GetVertexList();
cindex = vertexList->GetElement(0);
x1 = cindex[0];
y1 = cindex[1];
cindex = vertexList->GetElement(1);
x2 = cindex[0];
y2 = cindex[1];
fprintf(file, "%8.3f %8.3f\n", x1, y1);
}
fclose(file);
// writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Programme : OTB (ORFEO ToolBox)
Auteurs : CS - T.Feuvrier
Language : C++
Date : 11 janvier 2005
Version :
Role : Test l'extraction d'une ROI dans une image mono ou multi canal, dont les valeurs sont codes en "unsigned char"
Les parametres de la ROI ne sont pas obligatoire, tout comme les canaux. Dans ce cas, les valeurs par dfaut
de la classe sont utilises
$Id$
=========================================================================*/
#include "itkExceptionObject.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
int otbMultiToMonoChannelExtractROISAR ( int argc, char ** argv )
{
try
{
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
typedef std::complex<int> InputPixelType;
typedef std::complex<int> OutputPixelType;
typedef otb::MultiToMonoChannelExtractROI< InputPixelType,
OutputPixelType > ExtractROIFilterType;
ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
extractROIFilter->SetStartX( 10 );
extractROIFilter->SetStartY( 10 );
extractROIFilter->SetSizeX( 100 );
extractROIFilter->SetSizeY( 100 );
extractROIFilter->SetChannel( 1 );
// Resume de la ligne de commande
std::cout << " ROI selectionnee : startX "<<extractROIFilter->GetStartX()<<std::endl;
std::cout << " startY "<<extractROIFilter->GetStartY()<<std::endl;
std::cout << " sizeX "<<extractROIFilter->GetSizeX()<<std::endl;
std::cout << " sizeY "<<extractROIFilter->GetSizeY()<<std::endl;
std::cout << " Canal selectionne : ("<<extractROIFilter->GetChannel()<<") : ";
typedef otb::ImageFileReader< ExtractROIFilterType::InputImageType > ReaderType;
typedef otb::ImageFileWriter< ExtractROIFilterType::OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
extractROIFilter->SetInput( reader->GetOutput() );
writer->SetInput( extractROIFilter->GetOutput() );
writer->Update();
std::cout << " Nb canaux dans l'image d'entree : "<< reader->GetOutput()->GetNumberOfComponentsPerPixel()<<std::endl;
std::cout << " Nb canaux dans l'image de sortie : "<<extractROIFilter->GetOutput()->GetNumberOfComponentsPerPixel() <<std::endl;
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Exception levee inconnue !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Modification de std::complex<int> en std::complex<float><commit_after>/*=========================================================================
Programme : OTB (ORFEO ToolBox)
Auteurs : CS - T.Feuvrier
Language : C++
Date : 11 janvier 2005
Version :
Role : Test l'extraction d'une ROI dans une image mono ou multi canal, dont les valeurs sont codes en "unsigned char"
Les parametres de la ROI ne sont pas obligatoire, tout comme les canaux. Dans ce cas, les valeurs par dfaut
de la classe sont utilises
$Id$
=========================================================================*/
#include "itkExceptionObject.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
int otbMultiToMonoChannelExtractROISAR ( int argc, char ** argv )
{
try
{
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
typedef std::complex<float> InputPixelType;
typedef std::complex<float> OutputPixelType;
typedef otb::MultiToMonoChannelExtractROI< InputPixelType,
OutputPixelType > ExtractROIFilterType;
ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
extractROIFilter->SetStartX( 10 );
extractROIFilter->SetStartY( 10 );
extractROIFilter->SetSizeX( 100 );
extractROIFilter->SetSizeY( 100 );
extractROIFilter->SetChannel( 1 );
// Resume de la ligne de commande
std::cout << " ROI selectionnee : startX "<<extractROIFilter->GetStartX()<<std::endl;
std::cout << " startY "<<extractROIFilter->GetStartY()<<std::endl;
std::cout << " sizeX "<<extractROIFilter->GetSizeX()<<std::endl;
std::cout << " sizeY "<<extractROIFilter->GetSizeY()<<std::endl;
std::cout << " Canal selectionne : ("<<extractROIFilter->GetChannel()<<") : ";
typedef otb::ImageFileReader< ExtractROIFilterType::InputImageType > ReaderType;
typedef otb::ImageFileWriter< ExtractROIFilterType::OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
extractROIFilter->SetInput( reader->GetOutput() );
writer->SetInput( extractROIFilter->GetOutput() );
writer->Update();
std::cout << " Nb canaux dans l'image d'entree : "<< reader->GetOutput()->GetNumberOfComponentsPerPixel()<<std::endl;
std::cout << " Nb canaux dans l'image de sortie : "<<extractROIFilter->GetOutput()->GetNumberOfComponentsPerPixel() <<std::endl;
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Exception levee inconnue !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#ifndef _Stroika_Foundation_Cache_TimedCache_inl_
#define _Stroika_Foundation_Cache_TimedCache_inl_ 1
#include "../Debug/Assertions.h"
#include "../Debug/Trace.h"
#include "../Execution/Common.h"
namespace Stroika {
namespace Foundation {
namespace Cache {
/*
********************************************************************************
************************ TimedCacheSupport::Stats_Basic ************************
********************************************************************************
*/
inline TimedCacheSupport::Stats_Basic::Stats_Basic ()
: fCachedCollected_Hits (0)
, fCachedCollected_Misses (0)
{
}
inline void TimedCacheSupport::Stats_Basic::IncrementHits ()
{
fCachedCollected_Hits++;
}
inline void TimedCacheSupport::Stats_Basic::IncrementMisses ()
{
fCachedCollected_Misses++;
}
inline void TimedCacheSupport::Stats_Basic::DbgTraceStats (const SDKChar* label) const
{
size_t total = fCachedCollected_Hits + fCachedCollected_Misses;
if (total == 0) {
total = 1; // avoid divide by zero
}
DbgTrace (SDKSTR ("%s stats: hits=%d, misses=%d, hit%% %f."), label, fCachedCollected_Hits, fCachedCollected_Misses, float (fCachedCollected_Hits) / (float (total)));
}
/*
********************************************************************************
************************ TimedCacheSupport::Stats_Null *************************
********************************************************************************
*/
inline void TimedCacheSupport::Stats_Null::IncrementHits ()
{
}
inline void TimedCacheSupport::Stats_Null::IncrementMisses ()
{
}
inline void TimedCacheSupport::Stats_Null::DbgTraceStats (const SDKChar* label) const
{
}
/*
********************************************************************************
************************ TimedCache<KEY,RESULT,TRAITS> *************************
********************************************************************************
*/
template <typename KEY, typename RESULT, typename TRAITS>
TimedCache<KEY, RESULT, TRAITS>::TimedCache (bool accessFreshensDate, Stroika::Foundation::Time::DurationSecondsType timeoutInSeconds)
: fMap_ ()
, fAccessFreshensDate_ (accessFreshensDate)
, fTimeout_ (timeoutInSeconds)
, fNextAutoClearAt_ (Time::GetTickCount () + timeoutInSeconds)
, fStats ()
{
Require (fTimeout_ > 0.0f);
}
template <typename KEY, typename RESULT, typename TRAITS>
void TimedCache<KEY, RESULT, TRAITS>::SetTimeout (Stroika::Foundation::Time::DurationSecondsType timeoutInSeconds)
{
Require (timeoutInSeconds > 0.0f);
#if qDebug
#if qCompilerAndStdLib_make_unique_lock_IsSlow
MACRO_LOCK_GUARD_CONTEXT (fMutex_);
#else
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
#endif
if (fTimeout_ != timeoutInSeconds) {
ClearIfNeeded_ ();
fTimeout_ = timeoutInSeconds;
ClearIfNeeded_ ();
}
}
template <typename KEY, typename RESULT, typename TRAITS>
Memory::Optional<RESULT> TimedCache<KEY, RESULT, TRAITS>::AccessElement (const KEY& key)
{
#if qDebug
#if qCompilerAndStdLib_make_unique_lock_IsSlow
MACRO_LOCK_GUARD_CONTEXT (fMutex_);
#else
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
#endif
ClearIfNeeded_ ();
typename map<KEY, MyResult_>::iterator i = fMap_.find (key);
if (i == fMap_.end ()) {
fStats.IncrementMisses ();
return Memory::Optional<RESULT> ();
}
else {
if (fAccessFreshensDate_) {
i->second.fLastAccessedAt = Time::GetTickCount ();
}
fStats.IncrementHits ();
return Memory::Optional<RESULT> (i->second.fResult);
}
}
template <typename KEY, typename RESULT, typename TRAITS>
inline bool TimedCache<KEY, RESULT, TRAITS>::AccessElement (const KEY& key, RESULT* result)
{
Memory::Optional<RESULT> r = AccessElement (key);
if (r.IsPresent () and result != nullptr) {
*result = *r;
}
return r.IsPresent ();
}
template <typename KEY, typename RESULT, typename TRAITS>
void TimedCache<KEY, RESULT, TRAITS>::AddElement (const KEY& key, const RESULT& result)
{
#if qDebug
#if qCompilerAndStdLib_make_unique_lock_IsSlow
MACRO_LOCK_GUARD_CONTEXT (fMutex_);
#else
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
#endif
ClearIfNeeded_ ();
typename map<KEY, MyResult_>::iterator i = fMap_.find (key);
if (i == fMap_.end ()) {
fMap_.insert (map<KEY, MyResult_>::value_type (key, MyResult_ (result)));
}
else {
i->second = MyResult_ (result); // overwrite if its already there
}
}
template <typename KEY, typename RESULT, typename TRAITS>
void TimedCache<KEY, RESULT, TRAITS>::Remove (const KEY& key)
{
#if qDebug
#if qCompilerAndStdLib_make_unique_lock_IsSlow
MACRO_LOCK_GUARD_CONTEXT (fMutex_);
#else
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
#endif
fMap_.erase (key);
}
template <typename KEY, typename RESULT, typename TRAITS>
inline void TimedCache<KEY, RESULT, TRAITS>::DoBookkeeping ()
{
#if qDebug
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
ClearOld_ ();
}
template <typename KEY, typename RESULT, typename TRAITS>
inline void TimedCache<KEY, RESULT, TRAITS>::ClearIfNeeded_ ()
{
if (fNextAutoClearAt_ < Time::GetTickCount ()) {
ClearOld_ ();
}
}
template <typename KEY, typename RESULT, typename TRAITS>
void TimedCache<KEY, RESULT, TRAITS>::ClearOld_ ()
{
Stroika::Foundation::Time::DurationSecondsType now = Time::GetTickCount ();
fNextAutoClearAt_ = now + fTimeout_ / 2.0f; // somewhat arbitrary how far into the future we do this...
Stroika::Foundation::Time::DurationSecondsType lastAccessThreshold = now - fTimeout_;
for (typename map<KEY, MyResult_>::iterator i = fMap_.begin (); i != fMap_.end (); ) {
if (i->second.fLastAccessedAt < lastAccessThreshold) {
i = fMap_.erase (i);
}
else {
++i;
}
}
}
}
}
}
#endif /*_Stroika_Foundation_Cache_TimedCache_inl_*/
<commit_msg>cleanup TimedCache code:<commit_after>
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#ifndef _Stroika_Foundation_Cache_TimedCache_inl_
#define _Stroika_Foundation_Cache_TimedCache_inl_ 1
#include "../Debug/Assertions.h"
#include "../Debug/Trace.h"
#include "../Execution/Common.h"
namespace Stroika {
namespace Foundation {
namespace Cache {
/*
********************************************************************************
************************ TimedCacheSupport::Stats_Basic ************************
********************************************************************************
*/
inline TimedCacheSupport::Stats_Basic::Stats_Basic ()
: fCachedCollected_Hits (0)
, fCachedCollected_Misses (0)
{
}
inline void TimedCacheSupport::Stats_Basic::IncrementHits ()
{
fCachedCollected_Hits++;
}
inline void TimedCacheSupport::Stats_Basic::IncrementMisses ()
{
fCachedCollected_Misses++;
}
inline void TimedCacheSupport::Stats_Basic::DbgTraceStats (const SDKChar* label) const
{
size_t total = fCachedCollected_Hits + fCachedCollected_Misses;
if (total == 0) {
total = 1; // avoid divide by zero
}
DbgTrace (SDKSTR ("%s stats: hits=%d, misses=%d, hit%% %f."), label, fCachedCollected_Hits, fCachedCollected_Misses, float (fCachedCollected_Hits) / (float (total)));
}
/*
********************************************************************************
************************ TimedCacheSupport::Stats_Null *************************
********************************************************************************
*/
inline void TimedCacheSupport::Stats_Null::IncrementHits ()
{
}
inline void TimedCacheSupport::Stats_Null::IncrementMisses ()
{
}
inline void TimedCacheSupport::Stats_Null::DbgTraceStats (const SDKChar* label) const
{
}
/*
********************************************************************************
************************ TimedCache<KEY,RESULT,TRAITS> *************************
********************************************************************************
*/
template <typename KEY, typename RESULT, typename TRAITS>
TimedCache<KEY, RESULT, TRAITS>::TimedCache (bool accessFreshensDate, Stroika::Foundation::Time::DurationSecondsType timeoutInSeconds)
: fAccessFreshensDate_ (accessFreshensDate)
, fTimeout_ (timeoutInSeconds)
, fNextAutoClearAt_ (Time::GetTickCount () + timeoutInSeconds)
{
Require (fTimeout_ > 0.0f);
}
template <typename KEY, typename RESULT, typename TRAITS>
void TimedCache<KEY, RESULT, TRAITS>::SetTimeout (Stroika::Foundation::Time::DurationSecondsType timeoutInSeconds)
{
Require (timeoutInSeconds > 0.0f);
#if qDebug
#if qCompilerAndStdLib_make_unique_lock_IsSlow
MACRO_LOCK_GUARD_CONTEXT (fMutex_);
#else
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
#endif
if (fTimeout_ != timeoutInSeconds) {
ClearIfNeeded_ ();
fTimeout_ = timeoutInSeconds;
ClearIfNeeded_ ();
}
}
template <typename KEY, typename RESULT, typename TRAITS>
Memory::Optional<RESULT> TimedCache<KEY, RESULT, TRAITS>::AccessElement (const KEY& key)
{
#if qDebug
#if qCompilerAndStdLib_make_unique_lock_IsSlow
MACRO_LOCK_GUARD_CONTEXT (fMutex_);
#else
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
#endif
ClearIfNeeded_ ();
typename map<KEY, MyResult_>::iterator i = fMap_.find (key);
if (i == fMap_.end ()) {
fStats.IncrementMisses ();
return Memory::Optional<RESULT> ();
}
else {
if (fAccessFreshensDate_) {
i->second.fLastAccessedAt = Time::GetTickCount ();
}
fStats.IncrementHits ();
return Memory::Optional<RESULT> (i->second.fResult);
}
}
template <typename KEY, typename RESULT, typename TRAITS>
inline bool TimedCache<KEY, RESULT, TRAITS>::AccessElement (const KEY& key, RESULT* result)
{
Memory::Optional<RESULT> r = AccessElement (key);
if (r.IsPresent () and result != nullptr) {
*result = *r;
}
return r.IsPresent ();
}
template <typename KEY, typename RESULT, typename TRAITS>
void TimedCache<KEY, RESULT, TRAITS>::AddElement (const KEY& key, const RESULT& result)
{
#if qDebug
#if qCompilerAndStdLib_make_unique_lock_IsSlow
MACRO_LOCK_GUARD_CONTEXT (fMutex_);
#else
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
#endif
ClearIfNeeded_ ();
typename map<KEY, MyResult_>::iterator i = fMap_.find (key);
if (i == fMap_.end ()) {
fMap_.insert (typename map<KEY, MyResult_>::value_type (key, MyResult_ (result)));
}
else {
i->second = MyResult_ (result); // overwrite if its already there
}
}
template <typename KEY, typename RESULT, typename TRAITS>
void TimedCache<KEY, RESULT, TRAITS>::Remove (const KEY& key)
{
#if qDebug
#if qCompilerAndStdLib_make_unique_lock_IsSlow
MACRO_LOCK_GUARD_CONTEXT (fMutex_);
#else
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
#endif
fMap_.erase (key);
}
template <typename KEY, typename RESULT, typename TRAITS>
inline void TimedCache<KEY, RESULT, TRAITS>::DoBookkeeping ()
{
#if qDebug
auto critSec { Execution::make_unique_lock (fMutex_) };
#endif
ClearOld_ ();
}
template <typename KEY, typename RESULT, typename TRAITS>
inline void TimedCache<KEY, RESULT, TRAITS>::ClearIfNeeded_ ()
{
if (fNextAutoClearAt_ < Time::GetTickCount ()) {
ClearOld_ ();
}
}
template <typename KEY, typename RESULT, typename TRAITS>
void TimedCache<KEY, RESULT, TRAITS>::ClearOld_ ()
{
Stroika::Foundation::Time::DurationSecondsType now = Time::GetTickCount ();
fNextAutoClearAt_ = now + fTimeout_ / 2.0f; // somewhat arbitrary how far into the future we do this...
Stroika::Foundation::Time::DurationSecondsType lastAccessThreshold = now - fTimeout_;
for (typename map<KEY, MyResult_>::iterator i = fMap_.begin (); i != fMap_.end (); ) {
if (i->second.fLastAccessedAt < lastAccessThreshold) {
i = fMap_.erase (i);
}
else {
++i;
}
}
}
}
}
}
#endif /*_Stroika_Foundation_Cache_TimedCache_inl_*/
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include <sys/stat.h>
#include <sys/resource.h>
#include <pwd.h>
#include "rhodes/JNIRhodes.h"
#include "common/AutoPointer.h"
#include "common/RhoStd.h"
#include "common/RhoConf.h"
#include "common/RhodesAppBase.h"
#include "sqlite/sqlite3.h"
#include "logging/RhoLogConf.h"
//--------------------------------------------------------------------------------------------------
static rho::common::CAutoPtr<rho::common::AndroidLogSink> s_logSink(new rho::common::AndroidLogSink());
static rho::String s_root_path;
static rho::String s_sqlite_path;
//--------------------------------------------------------------------------------------------------
RHO_GLOBAL void android_set_path(const rho::String& root, const rho::String& sqlite)
{
s_root_path = root;
s_sqlite_path = sqlite;
}
//--------------------------------------------------------------------------------------------------
rho::String const &rho_root_path()
{
return s_root_path;
}
//--------------------------------------------------------------------------------------------------
const char* rho_native_rhopath()
{
return rho_root_path().c_str();
}
//--------------------------------------------------------------------------------------------------
rho::String rho_cur_path()
{
char buf[PATH_MAX];
if (::getcwd(buf, sizeof(buf)) == NULL)
return "";
return buf;
}
//--------------------------------------------------------------------------------------------------
static bool set_posix_environment(JNIEnv *env, jclass clsRE)
{
// Set USER variable
struct passwd *pwd = ::getpwuid(::getuid());
if (!pwd)
{
env->ThrowNew(clsRE, "Can't find user name for current user");
return false;
}
size_t len = ::strlen(pwd->pw_name) + 16;
char *buf = (char *)::malloc(len + 1);
buf[len] = '\0';
::snprintf(buf, len, "USER=%s", pwd->pw_name);
int e = ::putenv(buf);
::free(buf);
if (e != 0)
{
env->ThrowNew(clsRE, "Can't set USER environment variable");
return false;
}
// Set HOME variable
std::string root_path = rho_root_path();
if (!root_path.empty() && root_path[root_path.size() - 1] == '/')
root_path.erase(root_path.size() - 1);
len = root_path.size() + 16;
buf = (char *)::malloc(len + 1);
buf[len] = '\0';
::snprintf(buf, len, "HOME=%s", root_path.c_str());
e = ::putenv(buf);
::free(buf);
if (e != 0)
{
env->ThrowNew(clsRE, "Can't set HOME environment variable");
return false;
}
// Set TMP variable
len = root_path.size() + 32;
buf = (char *)::malloc(len + 1);
buf[len] = '\0';
::snprintf(buf, len, "TMP=%s/tmp", root_path.c_str());
e = ::putenv(buf);
::free(buf);
if (e != 0)
{
env->ThrowNew(clsRE, "Can't set TMP environment variable");
return false;
}
return true;
}
//--------------------------------------------------------------------------------------------------
RHO_GLOBAL void android_setup(JNIEnv *env)
{
jclass clsRE = getJNIClass(RHODES_JAVA_CLASS_RUNTIME_EXCEPTION);
if (!clsRE)
return;
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
{
env->ThrowNew(clsRE, "Can not get maximum number of open files");
return;
}
if (rlim.rlim_max < (unsigned long)RHO_FD_BASE)
{
env->ThrowNew(clsRE, "Current limit of open files is less then RHO_FD_BASE");
return;
}
if (rlim.rlim_cur > (unsigned long)RHO_FD_BASE)
{
rlim.rlim_cur = RHO_FD_BASE;
rlim.rlim_max = RHO_FD_BASE;
if (setrlimit(RLIMIT_NOFILE, &rlim) == -1)
{
env->ThrowNew(clsRE, "Can not set maximum number of open files");
return;
}
}
if (!set_posix_environment(env, clsRE)) return;
if (::chdir(rho_root_path().c_str()) == -1)
{
env->ThrowNew(clsRE, "Can not chdir to HOME directory");
return;
}
// Init SQLite temp directory
sqlite3_temp_directory = (char*)s_sqlite_path.c_str();
// Init logconf
rho_logconf_Init(rho_native_rhopath(), "");
// Disable log to stdout as on android all stdout redirects to /dev/null
RHOCONF().setBool("LogToOutput", false, true);
LOGCONF().setLogToOutput(false);
// Add android system log sink
LOGCONF().setLogView(s_logSink);
}
//--------------------------------------------------------------------------------------------------
RHO_GLOBAL void *rho_nativethread_start()
{
JNIEnv *env;
jvm()->AttachCurrentThread(&env, NULL);
store_thr_jnienv(env);
return NULL;
}
//--------------------------------------------------------------------------------------------------
RHO_GLOBAL void rho_nativethread_end(void *)
{
jvm()->DetachCurrentThread();
}
//--------------------------------------------------------------------------------------------------
<commit_msg>android: build fix<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include <sys/stat.h>
#include <sys/resource.h>
#include <pwd.h>
#include "rhodes/JNIRhodes.h"
#include "common/AutoPointer.h"
#include "common/RhoStd.h"
#include "common/RhoConf.h"
#include "common/RhodesAppBase.h"
#include "sqlite/sqlite3.h"
#include "logging/RhoLogConf.h"
//--------------------------------------------------------------------------------------------------
static rho::common::CAutoPtr<rho::common::AndroidLogSink> s_logSink(new rho::common::AndroidLogSink());
static rho::String s_root_path;
static rho::String s_sqlite_path;
//--------------------------------------------------------------------------------------------------
RHO_GLOBAL void android_set_path(const rho::String& root, const rho::String& sqlite)
{
s_root_path = root;
s_sqlite_path = sqlite;
}
//--------------------------------------------------------------------------------------------------
rho::String const &rho_root_path()
{
return s_root_path;
}
//--------------------------------------------------------------------------------------------------
const char* rho_native_rhopath()
{
return rho_root_path().c_str();
}
//--------------------------------------------------------------------------------------------------
const char* rho_native_reruntimepath()
{
return rho_root_path().c_str();
}
//--------------------------------------------------------------------------------------------------
rho::String rho_cur_path()
{
char buf[PATH_MAX];
if (::getcwd(buf, sizeof(buf)) == NULL)
return "";
return buf;
}
//--------------------------------------------------------------------------------------------------
static bool set_posix_environment(JNIEnv *env, jclass clsRE)
{
// Set USER variable
struct passwd *pwd = ::getpwuid(::getuid());
if (!pwd)
{
env->ThrowNew(clsRE, "Can't find user name for current user");
return false;
}
size_t len = ::strlen(pwd->pw_name) + 16;
char *buf = (char *)::malloc(len + 1);
buf[len] = '\0';
::snprintf(buf, len, "USER=%s", pwd->pw_name);
int e = ::putenv(buf);
::free(buf);
if (e != 0)
{
env->ThrowNew(clsRE, "Can't set USER environment variable");
return false;
}
// Set HOME variable
std::string root_path = rho_root_path();
if (!root_path.empty() && root_path[root_path.size() - 1] == '/')
root_path.erase(root_path.size() - 1);
len = root_path.size() + 16;
buf = (char *)::malloc(len + 1);
buf[len] = '\0';
::snprintf(buf, len, "HOME=%s", root_path.c_str());
e = ::putenv(buf);
::free(buf);
if (e != 0)
{
env->ThrowNew(clsRE, "Can't set HOME environment variable");
return false;
}
// Set TMP variable
len = root_path.size() + 32;
buf = (char *)::malloc(len + 1);
buf[len] = '\0';
::snprintf(buf, len, "TMP=%s/tmp", root_path.c_str());
e = ::putenv(buf);
::free(buf);
if (e != 0)
{
env->ThrowNew(clsRE, "Can't set TMP environment variable");
return false;
}
return true;
}
//--------------------------------------------------------------------------------------------------
RHO_GLOBAL void android_setup(JNIEnv *env)
{
jclass clsRE = getJNIClass(RHODES_JAVA_CLASS_RUNTIME_EXCEPTION);
if (!clsRE)
return;
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
{
env->ThrowNew(clsRE, "Can not get maximum number of open files");
return;
}
if (rlim.rlim_max < (unsigned long)RHO_FD_BASE)
{
env->ThrowNew(clsRE, "Current limit of open files is less then RHO_FD_BASE");
return;
}
if (rlim.rlim_cur > (unsigned long)RHO_FD_BASE)
{
rlim.rlim_cur = RHO_FD_BASE;
rlim.rlim_max = RHO_FD_BASE;
if (setrlimit(RLIMIT_NOFILE, &rlim) == -1)
{
env->ThrowNew(clsRE, "Can not set maximum number of open files");
return;
}
}
if (!set_posix_environment(env, clsRE)) return;
if (::chdir(rho_root_path().c_str()) == -1)
{
env->ThrowNew(clsRE, "Can not chdir to HOME directory");
return;
}
// Init SQLite temp directory
sqlite3_temp_directory = (char*)s_sqlite_path.c_str();
// Init logconf
rho_logconf_Init(rho_native_rhopath(), "");
// Disable log to stdout as on android all stdout redirects to /dev/null
RHOCONF().setBool("LogToOutput", false, true);
LOGCONF().setLogToOutput(false);
// Add android system log sink
LOGCONF().setLogView(s_logSink);
}
//--------------------------------------------------------------------------------------------------
RHO_GLOBAL void *rho_nativethread_start()
{
JNIEnv *env;
jvm()->AttachCurrentThread(&env, NULL);
store_thr_jnienv(env);
return NULL;
}
//--------------------------------------------------------------------------------------------------
RHO_GLOBAL void rho_nativethread_end(void *)
{
jvm()->DetachCurrentThread();
}
//--------------------------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_Thread_inl_
#define _Stroika_Foundation_Execution_Thread_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <atomic>
#include <list>
#include "WaitableEvent.h"
#include "ThreadAbortException.h"
namespace Stroika {
namespace Foundation {
namespace Execution {
// experiment with this - turned off -- LGP 2014-01-14
#define qUSE_MUTEX_FOR_STATUS_FIELD_ 0
/*
********************************************************************************
********************************* Thread::Rep_ *********************************
********************************************************************************
*/
class Thread::Rep_ {
public:
Rep_ (const IRunnablePtr& runnable);
~Rep_ ();
public:
static void DoCreate (shared_ptr<Rep_>* repSharedPtr);
public:
nonvirtual void Start ();
public:
nonvirtual Thread::IDType GetID () const;
public:
nonvirtual Thread::NativeHandleType GetNativeHandle ();
private:
nonvirtual void Run_ ();
private:
// Called - typically from ANOTHER thread (but could be this thread). By default this does nothing,
// and is just called by Thread::Abort (). It sets (indirectly) the thread-local-storage aborted
// flag for the target thread. And if called from an aborting thread, it may throw
nonvirtual void NotifyOfAbortFromAnyThread_ ();
private:
static void ThreadMain_ (shared_ptr<Rep_>* thisThreadRep) noexcept;
private:
#if qPlatform_POSIX
static void CalledInRepThreadAbortProc_ (SignalID signal);
#elif qPlatform_Windows
static void CALLBACK CalledInRepThreadAbortProc_ (ULONG_PTR lpParameter);
#endif
private:
#if qCompilerAndStdLib_thread_local_with_atomic_keyword_Buggy
using AbortFlagType_ = volatile bool;
#else
using AbortFlagType_ = atomic<bool>;
#endif
private:
shared_ptr<IRunnable> fRunnable_;
// We use a global variable (thread local) to store the abort flag. But we must access it from ANOTHER thread typically - using
// a pointer. This is that pointer - so another thread can terminate/abort this thread.
AbortFlagType_* fTLSAbortFlag_;
std::thread fThread_;
#if qUSE_MUTEX_FOR_STATUS_FIELD_
mutable recursive_mutex fStatusCriticalSection_;
#endif
std::atomic<Status> fStatus_;
WaitableEvent fRefCountBumpedEvent_;
WaitableEvent fOK2StartEvent_;
WaitableEvent fThreadDone_;
wstring fThreadName_;
private:
friend class Thread;
};
/*
********************************************************************************
*********************************** Thread::Rep_ *******************************
********************************************************************************
*/
inline void Thread::Rep_::Start ()
{
fOK2StartEvent_.Set ();
}
/*
********************************************************************************
************************************* Thread ***********************************
********************************************************************************
*/
template <typename FUNCTION>
inline Thread::Thread (FUNCTION f, typename is_function<FUNCTION>::type*) :
Thread (function<void()>(f))
{
}
#if qPlatform_POSIX
inline SignalID Thread::GetSignalUsedForThreadAbort ()
{
return sSignalUsedForThreadAbort_;
}
#endif
inline Thread::IDType Thread::GetID () const
{
if (fRep_.get () == nullptr) {
#if qPlatform_POSIX
return Thread::IDType ();
#endif
}
return fRep_->GetID ();
}
inline Thread::NativeHandleType Thread::GetNativeHandle () noexcept {
if (fRep_.get () == nullptr)
{
return Thread::NativeHandleType (nullptr);
}
return fRep_->GetNativeHandle ();
}
inline shared_ptr<IRunnable> Thread::GetRunnable () const
{
if (fRep_.get () == nullptr) {
return shared_ptr<IRunnable> ();
}
return fRep_->fRunnable_;
}
inline bool Thread::operator< (const Thread& rhs) const
{
return fRep_ < rhs.fRep_;
}
inline Thread::Status Thread::GetStatus () const noexcept
{
if (fRep_.get () == nullptr) {
return Status::eNull;
}
return GetStatus_ ();
}
inline wstring Thread::GetThreadName () const
{
Require (GetStatus () != Status::eNull);
return fRep_->fThreadName_;
}
inline void Thread::WaitForDone (Time::DurationSecondsType timeout) const
{
WaitForDoneUntil (timeout + Time::GetTickCount ());
}
/*
********************************************************************************
*************************** GetCurrentThreadID *********************************
********************************************************************************
*/
inline Thread::IDType GetCurrentThreadID () noexcept {
return this_thread::get_id ();
}
/*
********************************************************************************
************************* CheckForThreadAborting *******************************
********************************************************************************
*/
template <unsigned int kEveryNTimes>
void CheckForThreadAborting ()
{
static unsigned int n = 0;
if (++n % kEveryNTimes == kEveryNTimes - 1) {
CheckForThreadAborting ();
}
}
}
}
}
#endif /*_Stroika_Foundation_Execution_Thread_inl_*/
<commit_msg>comments<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_Thread_inl_
#define _Stroika_Foundation_Execution_Thread_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <atomic>
#include <list>
#include "WaitableEvent.h"
#include "ThreadAbortException.h"
namespace Stroika {
namespace Foundation {
namespace Execution {
// experiment with this - turned off -- LGP 2014-01-14
#define qUSE_MUTEX_FOR_STATUS_FIELD_ 0
/*
********************************************************************************
********************************* Thread::Rep_ *********************************
********************************************************************************
*/
class Thread::Rep_ {
public:
Rep_ (const IRunnablePtr& runnable);
~Rep_ ();
public:
static void DoCreate (shared_ptr<Rep_>* repSharedPtr);
public:
nonvirtual void Start ();
public:
nonvirtual Thread::IDType GetID () const;
public:
nonvirtual Thread::NativeHandleType GetNativeHandle ();
private:
nonvirtual void Run_ ();
private:
// Called - typically from ANOTHER thread (but could be this thread). By default this does nothing,
// and is just called by Thread::Abort (). It sets (indirectly) the thread-local-storage aborted
// flag for the target thread. And if called from an aborting thread, it may throw
nonvirtual void NotifyOfAbortFromAnyThread_ ();
private:
static void ThreadMain_ (shared_ptr<Rep_>* thisThreadRep) noexcept;
private:
#if qPlatform_POSIX
static void CalledInRepThreadAbortProc_ (SignalID signal);
#elif qPlatform_Windows
static void CALLBACK CalledInRepThreadAbortProc_ (ULONG_PTR lpParameter);
#endif
private:
#if qCompilerAndStdLib_thread_local_with_atomic_keyword_Buggy
using AbortFlagType_ = volatile bool;
#else
using AbortFlagType_ = atomic<bool>;
#endif
private:
shared_ptr<IRunnable> fRunnable_;
// We use a global variable (thread local) to store the abort flag. But we must access it from ANOTHER thread typically - using
// a pointer. This is that pointer - so another thread can terminate/abort this thread.
AbortFlagType_* fTLSAbortFlag_;
std::thread fThread_;
#if qUSE_MUTEX_FOR_STATUS_FIELD_
mutable recursive_mutex fStatusCriticalSection_;
#endif
std::atomic<Status> fStatus_;
WaitableEvent fRefCountBumpedEvent_;
WaitableEvent fOK2StartEvent_;
WaitableEvent fThreadDone_;
wstring fThreadName_;
private:
friend class Thread;
};
/*
********************************************************************************
*********************************** Thread::Rep_ *******************************
********************************************************************************
*/
inline void Thread::Rep_::Start ()
{
fOK2StartEvent_.Set ();
}
/*
********************************************************************************
************************************* Thread ***********************************
********************************************************************************
*/
template <typename FUNCTION>
inline Thread::Thread (FUNCTION f, typename is_function<FUNCTION>::type*) :
Thread (function<void()>(f))
{
}
#if qPlatform_POSIX
inline SignalID Thread::GetSignalUsedForThreadAbort ()
{
return sSignalUsedForThreadAbort_;
}
#endif
inline Thread::IDType Thread::GetID () const
{
if (fRep_.get () == nullptr) {
#if qPlatform_POSIX
return Thread::IDType ();
#endif
}
return fRep_->GetID ();
}
inline Thread::NativeHandleType Thread::GetNativeHandle () noexcept {
if (fRep_.get () == nullptr)
{
return Thread::NativeHandleType (nullptr);
}
return fRep_->GetNativeHandle ();
}
inline shared_ptr<IRunnable> Thread::GetRunnable () const
{
if (fRep_.get () == nullptr) {
return shared_ptr<IRunnable> ();
}
return fRep_->fRunnable_;
}
inline bool Thread::operator< (const Thread& rhs) const
{
return fRep_ < rhs.fRep_;
}
inline Thread::Status Thread::GetStatus () const noexcept
{
if (fRep_.get () == nullptr) {
return Status::eNull;
}
return GetStatus_ ();
}
inline wstring Thread::GetThreadName () const
{
Require (GetStatus () != Status::eNull);
return fRep_->fThreadName_;
}
inline void Thread::WaitForDone (Time::DurationSecondsType timeout) const
{
WaitForDoneUntil (timeout + Time::GetTickCount ());
}
/*
********************************************************************************
*************************** GetCurrentThreadID *********************************
********************************************************************************
*/
inline Thread::IDType GetCurrentThreadID () noexcept {
return this_thread::get_id ();
}
/*
********************************************************************************
************************* CheckForThreadAborting *******************************
********************************************************************************
*/
template <unsigned int kEveryNTimes>
void CheckForThreadAborting ()
{
// note that it is not important that this be protected/thread safe, since the value is just advisory/hint
static unsigned int n = 0;
if (++n % kEveryNTimes == kEveryNTimes - 1) {
CheckForThreadAborting ();
}
}
}
}
}
#endif /*_Stroika_Foundation_Execution_Thread_inl_*/
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/pm/p10_update_ec_state.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/// @file p10_update_ec_state.C
/// @brief Update the core configured data in CCSR register and then deals with
/// deconfigured cores to verify the chiplet state..if it is still running then
/// will put the core to stop 11 state
///
/// *HWP HW Owner : Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner : Prasad Bg Ranganath <prasadbgr@in.ibm.com>
/// *HWP Team : PM
/// *HWP Level : 2
/// *HWP Consumed by : HB,PGPE,CME,OCC
///
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "p10_update_ec_state.H"
#include "p10_hcd_common.H"
#include "p10_hcd_cache_stopclocks.H"
#include "p10_hcd_core_poweroff.H"
#include "p10_hcd_l3_purge.H"
#include "p10_hcd_l2_purge.H"
#include "p10_hcd_powerbus_purge.H"
#include "p10_hcd_l2_tlbie_quiesce.H"
#include "p10_hcd_ncu_purge.H"
#include "p10_hcd_chtm_purge.H"
#include "p10_hcd_core_stopclocks.H"
#include "p10_hcd_cache_poweroff.H"
#include "p10_hcd_core_shadows_disable.H"
#include "p10_hcd_core_stopgrid.H"
#include <p10_scom_proc.H>
#include <p10_scom_c.H>
#include <p10_scom_eq.H>
using namespace scomt;
using namespace proc;
using namespace c;
using namespace eq;
// -----------------------------------------------------------------------------
// Function prototypes
// -----------------------------------------------------------------------------
static fapi2::ReturnCode update_ec_config(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
fapi2::ReturnCode verify_ec_hw_state(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
fapi2::ReturnCode p10_check_core_l3_clock_power_state(
const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,
uint8_t i_core_unit_pos);
// -----------------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------------
// See .H for documentation
fapi2::ReturnCode p10_update_ec_state(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
uint8_t i_qssr_skip)
{
FAPI_IMP("> p10_update_ec_state");
FAPI_TRY(update_ec_config(i_target),
"Error update_core_config detected");
//TODO Need to find the right way to get deconfigured target
FAPI_TRY(verify_ec_hw_state(i_target));
fapi_try_exit:
FAPI_INF("< p10_update_ec_state");
return fapi2::current_err;
} // END p10_update_ec_state
fapi2::ReturnCode verify_ec_hw_state(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_INF (">>verify_hw_state");
#if 0
uint8_t l_present_core_unit_pos;
uint8_t l_functional_core_unit_pos;
uint8_t l_core_match = 0;
//Get the perv target lists
auto l_core_present_target_vector = i_target.getChildren<fapi2::TARGET_TYPE_CORE>(
fapi2::TARGET_STATE_PRESENT);
//Get the functional lists
auto l_core_functional_vector =
i_target.getChildren<fapi2::TARGET_TYPE_CORE>
(fapi2::TARGET_STATE_FUNCTIONAL);
//Verify Core state
for (auto core_present_it : l_core_present_target_vector)
{
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
core_present_it,
l_present_core_unit_pos));
l_core_match = 1;
FAPI_INF("Present core %d ", l_present_core_unit_pos);
for (auto core_functional_it : l_core_functional_vector)
{
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
core_functional_it,
l_functional_core_unit_pos));
FAPI_INF(" Functional EC %d",
l_functional_core_unit_pos);
if (l_functional_core_unit_pos == l_present_core_unit_pos)
{
l_core_match = 1;
break;
}
else
{
l_core_match = 0;
}
}//end of functional
if (!l_core_match)
{
for ( auto l_core_target : core_present_it.getChildren<fapi2::TARGET_TYPE_CORE>(fapi2::TARGET_STATE_PRESENT) )
{
FAPI_INF("Core present but non functional %d",
l_present_core_unit_pos);
//Check the clock state and power state
FAPI_TRY(p10_check_core_l3_clock_power_state(l_core_target, l_present_core_unit_pos));
}
}
}//end of present
#endif
fapi_try_exit:
FAPI_INF("< update_core_config...");
return fapi2::current_err;
}
/// @brief Update the CCSR for cores
///
/// @param[in] i_target Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode update_ec_config(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_INF("> update_core_config...");
uint8_t l_present_core_unit_pos;
uint8_t l_functional_core_unit_pos;
fapi2::buffer<uint64_t> l_core_config = 0;
fapi2::buffer<uint64_t> l_pscom_config = 0;
auto l_core_present_vector =
i_target.getChildren<fapi2::TARGET_TYPE_CORE>
(fapi2::TARGET_STATE_PRESENT);
auto l_core_functional_vector =
i_target.getChildren<fapi2::TARGET_TYPE_CORE>
(fapi2::TARGET_STATE_FUNCTIONAL);
FAPI_INF(" Number of present cores = %d; Number of functional cores = %d",
l_core_present_vector.size(),
l_core_functional_vector.size());
// For each present core, set multicast groups and the CCSR
for (auto core_present_it : l_core_present_vector)
{
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
core_present_it,
l_present_core_unit_pos));
FAPI_INF(" Checking if present EC %d is functional",
l_present_core_unit_pos);
for (auto core_functional_it : l_core_functional_vector)
{
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
core_functional_it,
l_functional_core_unit_pos));
FAPI_DBG(" Functional EC %d",
l_functional_core_unit_pos);
if (l_functional_core_unit_pos == l_present_core_unit_pos)
{
// Set the appropriate bit in the Core Configuration Status
// Register buffer
FAPI_INF(" Setting EC %d as good in value to be written to CCSR",
l_present_core_unit_pos);
l_core_config.setBit(l_present_core_unit_pos);
auto l_eq = core_functional_it.getParent<fapi2::TARGET_TYPE_EQ>();
l_present_core_unit_pos = l_present_core_unit_pos % 4;
//Update the pscom enable bit
l_pscom_config.setBit(l_present_core_unit_pos + 5);
FAPI_TRY(fapi2::putScom(l_eq, CPLT_CTRL3_WO_OR, l_pscom_config));
break;
} // Current core
} // Functional core loop
} // Present core loop
// Write the recalculated OCC Core Configuration Status Register
FAPI_INF(" Writing OCC CCSR");
FAPI_TRY(fapi2::putScom(i_target, TP_TPCHIP_OCC_OCI_OCB_CCSR_RW, l_core_config));
fapi_try_exit:
FAPI_INF("< update_core_config...");
return fapi2::current_err;
}
#define CORE_START_POSITION 5
#define CACHE_START_POSITION 9
fapi2::ReturnCode p10_check_core_l3_clock_power_state(
const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,
uint8_t i_core_unit_pos)
{
fapi2::buffer<uint64_t> l_data = 0;
uint64_t l_pfet_sense = 0;
uint8_t l_core_relative_pos = i_core_unit_pos % 4;
uint8_t l_l3_relative_pos = i_core_unit_pos % 4;
uint8_t l_core_clock_State = 0;
uint8_t l_l3_clock_State = 0;
do
{
auto l_eq_target = i_core_target.getParent<fapi2::TARGET_TYPE_EQ>();
//Read the power state of core/l2
FAPI_TRY(GET_CPMS_CL2_PFETSTAT(i_core_target, l_data));
GET_CPMS_CL2_PFETSTAT_VDD_PFETS_ENABLED_SENSE(l_data, l_pfet_sense);
//verify L3/core clocks are on
FAPI_TRY(GET_CLOCK_STAT_SL(l_eq_target, l_data));
l_core_clock_State = l_data & BIT64(l_core_relative_pos + CORE_START_POSITION);
l_l3_clock_State = l_data & BIT64(l_l3_relative_pos + CACHE_START_POSITION);
//Verify core is powered on
//If core is powered on
// then if core(ECl2) clocks are on
// then need to purge the l2 and stop the core clocks
// if L3 clocks are on
// then purge L3 and stop the l3 clocks
// Power off the core and L3
if( l_pfet_sense)
{
if (!l_core_clock_State)
{
FAPI_TRY(p10_hcd_l2_purge(i_core_target));
FAPI_TRY(p10_hcd_l2_tlbie_quiesce(i_core_target));
FAPI_TRY(p10_hcd_ncu_purge(i_core_target));
FAPI_TRY(p10_hcd_core_shadows_disable(i_core_target));
FAPI_TRY(p10_hcd_core_stopclocks(i_core_target));
FAPI_TRY(p10_hcd_core_stopgrid(i_core_target));
}
FAPI_TRY(p10_hcd_core_poweroff(i_core_target));
if (!l_l3_clock_State)
{
FAPI_TRY(p10_hcd_chtm_purge(i_core_target));
FAPI_TRY(p10_hcd_l3_purge(i_core_target));
FAPI_TRY(p10_hcd_powerbus_purge(i_core_target));
FAPI_TRY(p10_hcd_cache_stopclocks(i_core_target));
}
FAPI_TRY(p10_hcd_cache_poweroff(i_core_target));
}
}
while(0);
fapi_try_exit:
FAPI_INF("< p10_check_core_clock_power_state...");
return fapi2::current_err;
}
<commit_msg>Fix compile error in p10_update_ec_state (hostboot environment)<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/pm/p10_update_ec_state.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/// @file p10_update_ec_state.C
/// @brief Update the core configured data in CCSR register and then deals with
/// deconfigured cores to verify the chiplet state..if it is still running then
/// will put the core to stop 11 state
///
/// *HWP HW Owner : Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner : Prasad Bg Ranganath <prasadbgr@in.ibm.com>
/// *HWP Team : PM
/// *HWP Level : 2
/// *HWP Consumed by : HB,PGPE,CME,OCC
///
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "p10_update_ec_state.H"
#include "p10_hcd_common.H"
#include "p10_hcd_cache_stopclocks.H"
#include "p10_hcd_core_poweroff.H"
#include "p10_hcd_l3_purge.H"
#include "p10_hcd_l2_purge.H"
#include "p10_hcd_powerbus_purge.H"
#include "p10_hcd_l2_tlbie_quiesce.H"
#include "p10_hcd_ncu_purge.H"
#include "p10_hcd_chtm_purge.H"
#include "p10_hcd_core_stopclocks.H"
#include "p10_hcd_cache_poweroff.H"
#include "p10_hcd_core_shadows_disable.H"
#include "p10_hcd_core_stopgrid.H"
#include <p10_scom_proc.H>
#include <p10_scom_c.H>
#include <p10_scom_eq.H>
using namespace scomt;
using namespace proc;
using namespace c;
using namespace eq;
// -----------------------------------------------------------------------------
// Function prototypes
// -----------------------------------------------------------------------------
static fapi2::ReturnCode update_ec_config(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
fapi2::ReturnCode verify_ec_hw_state(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
fapi2::ReturnCode p10_check_core_l3_clock_power_state(
const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,
uint8_t i_core_unit_pos);
// -----------------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------------
// See .H for documentation
fapi2::ReturnCode p10_update_ec_state(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
uint8_t i_qssr_skip)
{
FAPI_IMP("> p10_update_ec_state");
FAPI_TRY(update_ec_config(i_target),
"Error update_core_config detected");
//TODO Need to find the right way to get deconfigured target
FAPI_TRY(verify_ec_hw_state(i_target));
fapi_try_exit:
FAPI_INF("< p10_update_ec_state");
return fapi2::current_err;
} // END p10_update_ec_state
fapi2::ReturnCode verify_ec_hw_state(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_INF (">>verify_hw_state");
#if 0
uint8_t l_present_core_unit_pos;
uint8_t l_functional_core_unit_pos;
uint8_t l_core_match = 0;
//Get the perv target lists
auto l_core_present_target_vector = i_target.getChildren<fapi2::TARGET_TYPE_CORE>(
fapi2::TARGET_STATE_PRESENT);
//Get the functional lists
auto l_core_functional_vector =
i_target.getChildren<fapi2::TARGET_TYPE_CORE>
(fapi2::TARGET_STATE_FUNCTIONAL);
//Verify Core state
for (auto core_present_it : l_core_present_target_vector)
{
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
core_present_it,
l_present_core_unit_pos));
l_core_match = 1;
FAPI_INF("Present core %d ", l_present_core_unit_pos);
for (auto core_functional_it : l_core_functional_vector)
{
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
core_functional_it,
l_functional_core_unit_pos));
FAPI_INF(" Functional EC %d",
l_functional_core_unit_pos);
if (l_functional_core_unit_pos == l_present_core_unit_pos)
{
l_core_match = 1;
break;
}
else
{
l_core_match = 0;
}
}//end of functional
if (!l_core_match)
{
for ( auto l_core_target : core_present_it.getChildren<fapi2::TARGET_TYPE_CORE>(fapi2::TARGET_STATE_PRESENT) )
{
FAPI_INF("Core present but non functional %d",
l_present_core_unit_pos);
//Check the clock state and power state
FAPI_TRY(p10_check_core_l3_clock_power_state(l_core_target, l_present_core_unit_pos));
}
}
}//end of present
fapi_try_exit:
#endif
FAPI_INF("< update_core_config...");
return fapi2::current_err;
}
/// @brief Update the CCSR for cores
///
/// @param[in] i_target Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode update_ec_config(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_INF("> update_core_config...");
uint8_t l_present_core_unit_pos;
uint8_t l_functional_core_unit_pos;
fapi2::buffer<uint64_t> l_core_config = 0;
fapi2::buffer<uint64_t> l_pscom_config = 0;
auto l_core_present_vector =
i_target.getChildren<fapi2::TARGET_TYPE_CORE>
(fapi2::TARGET_STATE_PRESENT);
auto l_core_functional_vector =
i_target.getChildren<fapi2::TARGET_TYPE_CORE>
(fapi2::TARGET_STATE_FUNCTIONAL);
FAPI_INF(" Number of present cores = %d; Number of functional cores = %d",
l_core_present_vector.size(),
l_core_functional_vector.size());
// For each present core, set multicast groups and the CCSR
for (auto core_present_it : l_core_present_vector)
{
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
core_present_it,
l_present_core_unit_pos));
FAPI_INF(" Checking if present EC %d is functional",
l_present_core_unit_pos);
for (auto core_functional_it : l_core_functional_vector)
{
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
core_functional_it,
l_functional_core_unit_pos));
FAPI_DBG(" Functional EC %d",
l_functional_core_unit_pos);
if (l_functional_core_unit_pos == l_present_core_unit_pos)
{
// Set the appropriate bit in the Core Configuration Status
// Register buffer
FAPI_INF(" Setting EC %d as good in value to be written to CCSR",
l_present_core_unit_pos);
l_core_config.setBit(l_present_core_unit_pos);
auto l_eq = core_functional_it.getParent<fapi2::TARGET_TYPE_EQ>();
l_present_core_unit_pos = l_present_core_unit_pos % 4;
//Update the pscom enable bit
l_pscom_config.setBit(l_present_core_unit_pos + 5);
FAPI_TRY(fapi2::putScom(l_eq, CPLT_CTRL3_WO_OR, l_pscom_config));
break;
} // Current core
} // Functional core loop
} // Present core loop
// Write the recalculated OCC Core Configuration Status Register
FAPI_INF(" Writing OCC CCSR");
FAPI_TRY(fapi2::putScom(i_target, TP_TPCHIP_OCC_OCI_OCB_CCSR_RW, l_core_config));
fapi_try_exit:
FAPI_INF("< update_core_config...");
return fapi2::current_err;
}
#define CORE_START_POSITION 5
#define CACHE_START_POSITION 9
fapi2::ReturnCode p10_check_core_l3_clock_power_state(
const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,
uint8_t i_core_unit_pos)
{
fapi2::buffer<uint64_t> l_data = 0;
uint64_t l_pfet_sense = 0;
uint8_t l_core_relative_pos = i_core_unit_pos % 4;
uint8_t l_l3_relative_pos = i_core_unit_pos % 4;
uint8_t l_core_clock_State = 0;
uint8_t l_l3_clock_State = 0;
do
{
auto l_eq_target = i_core_target.getParent<fapi2::TARGET_TYPE_EQ>();
//Read the power state of core/l2
FAPI_TRY(GET_CPMS_CL2_PFETSTAT(i_core_target, l_data));
GET_CPMS_CL2_PFETSTAT_VDD_PFETS_ENABLED_SENSE(l_data, l_pfet_sense);
//verify L3/core clocks are on
FAPI_TRY(GET_CLOCK_STAT_SL(l_eq_target, l_data));
l_core_clock_State = l_data & BIT64(l_core_relative_pos + CORE_START_POSITION);
l_l3_clock_State = l_data & BIT64(l_l3_relative_pos + CACHE_START_POSITION);
//Verify core is powered on
//If core is powered on
// then if core(ECl2) clocks are on
// then need to purge the l2 and stop the core clocks
// if L3 clocks are on
// then purge L3 and stop the l3 clocks
// Power off the core and L3
if( l_pfet_sense)
{
if (!l_core_clock_State)
{
FAPI_TRY(p10_hcd_l2_purge(i_core_target));
FAPI_TRY(p10_hcd_l2_tlbie_quiesce(i_core_target));
FAPI_TRY(p10_hcd_ncu_purge(i_core_target));
FAPI_TRY(p10_hcd_core_shadows_disable(i_core_target));
FAPI_TRY(p10_hcd_core_stopclocks(i_core_target));
FAPI_TRY(p10_hcd_core_stopgrid(i_core_target));
}
FAPI_TRY(p10_hcd_core_poweroff(i_core_target));
if (!l_l3_clock_State)
{
FAPI_TRY(p10_hcd_chtm_purge(i_core_target));
FAPI_TRY(p10_hcd_l3_purge(i_core_target));
FAPI_TRY(p10_hcd_powerbus_purge(i_core_target));
FAPI_TRY(p10_hcd_cache_stopclocks(i_core_target));
}
FAPI_TRY(p10_hcd_cache_poweroff(i_core_target));
}
}
while(0);
fapi_try_exit:
FAPI_INF("< p10_check_core_clock_power_state...");
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_switch_rec_attn.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_switch_rec_attn.C
///
/// @brief Switch recoverable/special attentions from host back to FSP
//------------------------------------------------------------------------------
// *HWP HW Owner : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team : Perv
// *HWP Level : 1
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_switch_rec_attn.H"
fapi2::ReturnCode p9_switch_rec_attn(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet)
{
FAPI_DBG("Entering ...");
FAPI_DBG("Exiting ...");
return fapi2::FAPI2_RC_SUCCESS;
}
<commit_msg>Update hardware procedure metadata<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_switch_rec_attn.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_switch_rec_attn.C
///
/// @brief Switch recoverable/special attentions from host back to FSP
//------------------------------------------------------------------------------
// *HWP HW Owner : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team : Perv
// *HWP Level : 3
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_switch_rec_attn.H"
fapi2::ReturnCode p9_switch_rec_attn(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet)
{
FAPI_DBG("Entering ...");
FAPI_DBG("Exiting ...");
return fapi2::FAPI2_RC_SUCCESS;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_block_wakeup_intr.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/// @file p9_block_wakeup_intr.H
/// @brief Set/reset the BLOCK_REG_WKUP_SOURCES bit in the PPM
/// associated with an EX chiplet
///
// *HWP HWP Owner: Amit Kumar <akumar3@us.ibm.com>
// *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner: Bilicon Patil <bilpatil@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 1
// *HWP Consumed by: FSP:HS
///
///-----------------------------------------------------------------------------
#ifndef _P9_BLKWKUP_H_
#define _P9_BLKWKUP_H_
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_pm.H>
#include <fapi2.H>
#include <p9_misc_scom_addresses.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
namespace p9pmblockwkup
{
static const uint8_t NUM_OPS = 2;
enum OP_TYPE
{
SET,
CLEAR
};
} // namespace p9pmblockwkup
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_block_wakeup_intr_FP_t) (
const fapi2::Target<fapi2::TARGET_TYPE_CORE>&,
const p9pmblockwkup::OP_TYPE);
extern "C" {
//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
/// @brief @brief Set/reset the BLOCK_REG_WKUP_SOURCES bit in the PPM
/// associated with an EX chiplet
///
/// @param[in] i_core_target Core target
/// @param[in] i_operation SET, CLEAR
///
/// @retval ECMD_SUCCESS
/// @retval ERROR only those from called functions or MACROs
fapi2::ReturnCode
p9_block_wakeup_intr( const fapi2::Target<fapi2::TARGET_TYPE_CORE>&
i_core_target,
p9pmblockwkup::OP_TYPE i_operation);
} // extern "C"
#endif // _P9_BLKWKUP_H_
<commit_msg>p9_block_wakeup_intr Level 2<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_block_wakeup_intr.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/// @file p9_block_wakeup_intr.H
/// @brief Set/reset the BLOCK_REG_WKUP_SOURCES bit in the PPM
/// associated with an EX chiplet
///
// *HWP HWP Owner: Amit Kumar <akumar3@us.ibm.com>
// *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner: Bilicon Patil <bilpatil@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 1
// *HWP Consumed by: FSP:HS
///
///-----------------------------------------------------------------------------
#ifndef _P9_BLKWKUP_H_
#define _P9_BLKWKUP_H_
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_quad_scom_addresses.H>
#include <p9_quad_scom_addresses_fld.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
namespace p9pmblockwkup
{
enum OP_TYPE
{
SET = 0,
SET_NOSPWUP = 1,
CLEAR = 2
};
// Used by checking infrasture checking code
static const uint32_t END_OP = CLEAR;
} // namespace p9pmblockwkup
//
// CPMMR Bit definitions
const uint32_t BLOCK_REG_WKUP_EVENTS = 6;
// GPMMR Address mappings (for clarity)
static const uint64_t C_PPM_GPMMR = C_PPM_GPMMR_SCOM;
static const uint64_t C_PPM_GPMMR_CLEAR = C_PPM_GPMMR_SCOM1;
static const uint64_t C_PPM_GPMMR_OR = C_PPM_GPMMR_SCOM2;
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_block_wakeup_intr_FP_t) (
const fapi2::Target<fapi2::TARGET_TYPE_CORE>&,
const p9pmblockwkup::OP_TYPE);
extern "C"
{
//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
/// @brief @brief Set/reset the BLOCK_REG_WKUP_SOURCES bit in the PPM
/// associated with an EX chiplet
///
/// @param[in] i_core_target Core target
/// @param[in] i_operation SET, CLEAR
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
fapi2::ReturnCode
p9_block_wakeup_intr(
const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,
const p9pmblockwkup::OP_TYPE i_operation);
} // extern "C"
#endif // _P9_BLKWKUP_H_
<|endoftext|>
|
<commit_before>#ifndef ElastixFilter_hxx
#define ElastixFilter_hxx
namespace selx {
template< typename TFixedImage, typename TMovingImage >
ElastixFilter< TFixedImage, TMovingImage >
::ElastixFilter( void )
{
this->AddRequiredInputName( "FixedImage" );
this->AddRequiredInputName( "MovingImage" );
this->AddRequiredInputName( "ParameterObject");
this->SetPrimaryInputName( "FixedImage" );
this->SetPrimaryOutputName( "ResultImage" );
this->m_FixedImageContainer = DataObjectContainerType::New();
this->m_MovingImageContainer = DataObjectContainerType::New();
this->m_FixedMeshFileName = std::string();
this->m_MovingMeshFileName = std::string();
this->m_OutputDirectory = std::string();
this->m_LogFileName = std::string();
this->LogToConsoleOff();
this->LogToFileOff();
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::GenerateData( void )
{
// Initialize variables here so they don't go out of scope between iterations of the main loop
ElastixMainObjectPointer transform = 0;
DataObjectContainerPointer fixedImageContainer = DataObjectContainerType::New();
DataObjectContainerPointer movingImageContainer = DataObjectContainerType::New();
DataObjectContainerPointer fixedMaskContainer = 0;
DataObjectContainerPointer movingMaskContainer = 0;
DataObjectContainerPointer resultImageContainer = 0;
ParameterMapListType TransformParameterMapList;
FlatDirectionCosinesType fixedImageOriginalDirection;
// Split input images into two seperate fixed and moving image containers
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if( this->IsFixedImage( inputNames[ i ] ) )
{
fixedImageContainer->push_back( this->GetInput( inputNames[ i ] ) );
}
if( this->IsMovingImage( inputNames[ i ] ) )
{
movingImageContainer->push_back( this->GetInput( inputNames[ i ] ) );
}
}
// Fixed mask (optional)
if( this->HasInput( "FixedMask" ) )
{
fixedMaskContainer = DataObjectContainerType::New();
fixedMaskContainer->CreateElementAt( 0 ) = this->GetInput( "FixedMask" );
}
// Moving mask (optional)
if( this->HasInput( "MovingMask" ) )
{
movingMaskContainer = DataObjectContainerType::New();
movingMaskContainer->CreateElementAt( 0 ) = this->GetInput( "MovingMask" );
}
ArgumentMapType argumentMap;
if( this->GetOutputDirectory().empty() ) {
// There must be an "-out", this is checked later in the code
argumentMap.insert( ArgumentMapEntryType( "-out", "output_path_not_set" ) );
}
else
{
argumentMap.insert( ArgumentMapEntryType( "-out", this->GetOutputDirectory() ) );
}
// Fixed mesh (optional)
if( !this->m_FixedMeshFileName.empty() )
{
argumentMap.insert( ArgumentMapEntryType( "-fp", std::string( this->m_FixedMeshFileName ) ) );
}
// Moving mesh (optional)
if( !this->m_MovingMeshFileName.empty() )
{
argumentMap.insert( ArgumentMapEntryType( "-mp", std::string( this->m_MovingMeshFileName ) ) );
}
// Setup xout
std::string logFileName;
if( this->GetLogToFile() )
{
if( this->GetOutputDirectory().empty() )
{
itkExceptionMacro( "LogToFileOn() requires an output directory to be specified. Use SetOutputDirectory().")
}
if( !itksys::SystemTools::FileExists( this->GetOutputDirectory() ) )
{
itkExceptionMacro( "Output directory \"" << this->GetOutputDirectory() << "\" does not exist." )
}
if( this->GetOutputDirectory().back() != '/' || this->GetOutputDirectory().back() != '\\' )
{
this->SetOutputDirectory( this->GetOutputDirectory() + "/" );
}
if( this->GetLogFileName().empty() )
{
logFileName = this->GetOutputDirectory() + "transformix.log";
}
else
{
logFileName = this->GetOutputDirectory() + this->GetLogFileName();
}
}
if( elx::xoutSetup( logFileName.c_str(), this->GetLogToFile(), this->GetLogToConsole() ) )
{
itkExceptionMacro( "ERROR while setting up xout" );
}
// Get ParameterMap
ParameterObjectConstPointer parameterObject = static_cast< const ParameterObject* >( this->GetInput( "ParameterObject" ) );
ParameterMapListType parameterMapList = parameterObject->GetParameterMapList();
// Run the (possibly multiple) registration(s)
for( unsigned int i = 0; i < parameterMapList.size(); ++i )
{
// Create another instance of ElastixMain
ElastixMainPointer elastix = ElastixMainType::New();
// Set the current elastix-level
elastix->SetElastixLevel( i );
elastix->SetTotalNumberOfElastixLevels( parameterMapList.size() );
// Set stuff we get from a previous registration
elastix->SetInitialTransform( transform );
elastix->SetFixedImageContainer( fixedImageContainer );
elastix->SetMovingImageContainer( movingImageContainer );
elastix->SetFixedMaskContainer( fixedMaskContainer );
elastix->SetMovingMaskContainer( movingMaskContainer );
elastix->SetResultImageContainer( resultImageContainer );
elastix->SetOriginalFixedImageDirectionFlat( fixedImageOriginalDirection );
// Start registration
unsigned int isError = 0;
try
{
unsigned int isError = elastix->Run( argumentMap, parameterMapList[ i ] );
}
catch( itk::ExceptionObject &e )
{
itkExceptionMacro( << "Errors occurred during registration: " << e.what() );
}
if( isError == -2 )
{
itkExceptionMacro( << "Errors occurred during registration: Output directory does not exist." );
}
if( isError != 0 )
{
itkExceptionMacro( << "Uncought errors occurred during registration." );
}
// Get the transform, the fixedImage and the movingImage
// in order to put it in the next registration
transform = elastix->GetFinalTransform();
fixedImageContainer = elastix->GetFixedImageContainer();
movingImageContainer = elastix->GetMovingImageContainer();
fixedMaskContainer = elastix->GetFixedMaskContainer();
movingMaskContainer = elastix->GetMovingMaskContainer();
resultImageContainer = elastix->GetResultImageContainer();
fixedImageOriginalDirection = elastix->GetOriginalFixedImageDirectionFlat();
TransformParameterMapList.push_back( elastix->GetTransformParametersMap() );
// Set initial transform to an index number instead of a parameter filename
if( i > 0 )
{
std::stringstream index;
index << ( i - 1 );
TransformParameterMapList[ i ][ "InitialTransformParametersFileName" ][ 0 ] = index.str();
}
} // End loop over registrations
// Save result image
if( resultImageContainer.IsNotNull() && resultImageContainer->Size() > 0 )
{
this->SetPrimaryOutput( resultImageContainer->ElementAt( 0 ) );
}
// Save parameter map
ParameterObject::Pointer TransformParameters = ParameterObject::New();
TransformParameters->SetParameterMapList( TransformParameterMapList );
this->SetOutput( "TransformParameterObject", static_cast< itk::DataObject* >( TransformParameters ) );
// Close the modules
ElastixMainType::UnloadComponents();
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetParameterObject( ParameterObjectPointer parameterObject )
{
this->SetInput( "ParameterObject", static_cast< itk::DataObject* >( parameterObject ) );
}
template< typename TFixedImage, typename TMovingImage >
typename selx::ElastixFilter< TFixedImage, TMovingImage >::ParameterObjectPointer
ElastixFilter< TFixedImage, TMovingImage >
::GetTransformParameters( void )
{
// Make sure the transform parameters are up to date
this->Update();
return static_cast< ParameterObject* >( itk::ProcessObject::GetOutput( "TransformParameterObject" ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedImage( FixedImagePointer fixedImage )
{
// Free references to fixed images that has already been set
this->RemoveFixedImages();
this->SetInput( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedImage( DataObjectContainerPointer fixedImages )
{
if( fixedImages->Size() == 0 )
{
itkExceptionMacro( "Cannot set fixed images from empty container.")
}
// Free references to fixed images that has already been set
this->RemoveFixedImages();
// The first image will be used as the "FixedImage" required input.
// The rest of the images will be appended to the input container
// suffixed with _1, _2, etc. This allows us to read out only the
// fixed images for elastix fixed image container at a later stage
DataObjectContainerIterator fixedImageIterator = fixedImages->Begin();
this->SetInput( "FixedImage", fixedImageIterator->Value() );
++fixedImageIterator;
while( fixedImageIterator != fixedImages->End() )
{
this->AddInputAutoIncrementName( "FixedImage", fixedImageIterator->Value() );
++fixedImageIterator;
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddFixedImage( FixedImagePointer fixedImage )
{
if( !this->HasInput( "FixedImage") )
{
this->SetInput( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
else
{
this->AddInputAutoIncrementName( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingImage( MovingImagePointer movingImage )
{
// Free references to moving images that has already been set
this->RemoveMovingImages();
this->SetInput( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingImage( DataObjectContainerPointer movingImages )
{
if( movingImages->Size() == 0 )
{
itkExceptionMacro( "Cannot set moving images from empty container.")
}
// Free references to fixed images that has already been set
this->RemoveMovingImages();
// The first image will be used as the "MovingImage" required input.
// The rest of the images will be appended to the input container
// suffixed with _1, _2, etc. This allows us to read out only the
// moving images for elastix moving image container at a later stage
DataObjectContainerIterator movingImageIterator = movingImages->Begin();
this->SetInput( "MovingImage", movingImageIterator->Value() );
++movingImageIterator;
while( movingImageIterator != movingImages->End() )
{
this->AddInputAutoIncrementName( "MovingImage", static_cast< itk::DataObject* >( movingImageIterator->Value() ) );
++movingImageIterator;
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddMovingImage( MovingImagePointer movingImage )
{
if( !this->HasInput( "MovingImage") )
{
this->SetInput( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
else
{
this->AddInputAutoIncrementName( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedMask( FixedImagePointer fixedMask )
{
this->SetInput( "FixedMask", static_cast< itk::DataObject* >( fixedMask ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingMask( MovingImagePointer movingMask )
{
this->SetInput( "MovingMask", static_cast< itk::DataObject* >( movingMask ) );
}
/*
* Adds a named input to the first null position in the input list
* Expands the list memory if necessary
*/
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddInputAutoIncrementName( DataObjectIdentifierType key, itk::DataObject* input )
{
for ( unsigned idx = 0; idx < this->GetNumberOfIndexedInputs(); ++idx )
{
if ( !this->GetInput( idx ) )
{
key += this->MakeNameFromInputIndex( idx );
this->SetInput( key, input );
return;
}
}
key += this->MakeNameFromInputIndex( this->GetNumberOfIndexedInputs() );
this->SetInput( key, input );
return;
}
template< typename TFixedImage, typename TMovingImage >
bool
ElastixFilter< TFixedImage, TMovingImage >
::IsFixedImage( DataObjectIdentifierType key )
{
return std::strncmp( "FixedImage", key.c_str(), 10 ) == 0;
}
template< typename TFixedImage, typename TMovingImage >
bool
ElastixFilter< TFixedImage, TMovingImage >
::IsMovingImage( DataObjectIdentifierType key )
{
return std::strncmp( "MovingImage", key.c_str(), 11 ) == 0;
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::RemoveFixedImages( void )
{
// Free references to fixed images that has already been set
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if ( this->IsFixedImage( inputNames[ i ] ) )
{
this->RemoveInput( inputNames[ i ] );
}
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::RemoveMovingImages( void )
{
// Free references to fixed images that has already been set
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if ( this->IsMovingImage( inputNames[ i ] ) )
{
this->RemoveInput( inputNames[ i ] );
}
}
}
} // namespace selx
#endif // ElastixFilter_hxx<commit_msg>ENH: Reuse SetMovingImage and SetFixedImage<commit_after>#ifndef ElastixFilter_hxx
#define ElastixFilter_hxx
namespace selx {
template< typename TFixedImage, typename TMovingImage >
ElastixFilter< TFixedImage, TMovingImage >
::ElastixFilter( void )
{
this->AddRequiredInputName( "FixedImage" );
this->AddRequiredInputName( "MovingImage" );
this->AddRequiredInputName( "ParameterObject");
this->SetPrimaryInputName( "FixedImage" );
this->SetPrimaryOutputName( "ResultImage" );
this->m_FixedImageContainer = DataObjectContainerType::New();
this->m_MovingImageContainer = DataObjectContainerType::New();
this->m_FixedMeshFileName = std::string();
this->m_MovingMeshFileName = std::string();
this->m_OutputDirectory = std::string();
this->m_LogFileName = std::string();
this->LogToConsoleOff();
this->LogToFileOff();
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::GenerateData( void )
{
// Initialize variables here so they don't go out of scope between iterations of the main loop
ElastixMainObjectPointer transform = 0;
DataObjectContainerPointer fixedImageContainer = DataObjectContainerType::New();
DataObjectContainerPointer movingImageContainer = DataObjectContainerType::New();
DataObjectContainerPointer fixedMaskContainer = 0;
DataObjectContainerPointer movingMaskContainer = 0;
DataObjectContainerPointer resultImageContainer = 0;
ParameterMapListType TransformParameterMapList;
FlatDirectionCosinesType fixedImageOriginalDirection;
// Split input images into two seperate fixed and moving image containers
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if( this->IsFixedImage( inputNames[ i ] ) )
{
fixedImageContainer->push_back( this->GetInput( inputNames[ i ] ) );
}
if( this->IsMovingImage( inputNames[ i ] ) )
{
movingImageContainer->push_back( this->GetInput( inputNames[ i ] ) );
}
}
// Fixed mask (optional)
if( this->HasInput( "FixedMask" ) )
{
fixedMaskContainer = DataObjectContainerType::New();
fixedMaskContainer->CreateElementAt( 0 ) = this->GetInput( "FixedMask" );
}
// Moving mask (optional)
if( this->HasInput( "MovingMask" ) )
{
movingMaskContainer = DataObjectContainerType::New();
movingMaskContainer->CreateElementAt( 0 ) = this->GetInput( "MovingMask" );
}
ArgumentMapType argumentMap;
if( this->GetOutputDirectory().empty() ) {
// There must be an "-out", this is checked later in the code
argumentMap.insert( ArgumentMapEntryType( "-out", "output_path_not_set" ) );
}
else
{
argumentMap.insert( ArgumentMapEntryType( "-out", this->GetOutputDirectory() ) );
}
// Fixed mesh (optional)
if( !this->m_FixedMeshFileName.empty() )
{
argumentMap.insert( ArgumentMapEntryType( "-fp", std::string( this->m_FixedMeshFileName ) ) );
}
// Moving mesh (optional)
if( !this->m_MovingMeshFileName.empty() )
{
argumentMap.insert( ArgumentMapEntryType( "-mp", std::string( this->m_MovingMeshFileName ) ) );
}
// Setup xout
std::string logFileName;
if( this->GetLogToFile() )
{
if( this->GetOutputDirectory().empty() )
{
itkExceptionMacro( "LogToFileOn() requires an output directory to be specified. Use SetOutputDirectory().")
}
if( !itksys::SystemTools::FileExists( this->GetOutputDirectory() ) )
{
itkExceptionMacro( "Output directory \"" << this->GetOutputDirectory() << "\" does not exist." )
}
if( this->GetOutputDirectory().back() != '/' || this->GetOutputDirectory().back() != '\\' )
{
this->SetOutputDirectory( this->GetOutputDirectory() + "/" );
}
if( this->GetLogFileName().empty() )
{
logFileName = this->GetOutputDirectory() + "transformix.log";
}
else
{
logFileName = this->GetOutputDirectory() + this->GetLogFileName();
}
}
if( elx::xoutSetup( logFileName.c_str(), this->GetLogToFile(), this->GetLogToConsole() ) )
{
itkExceptionMacro( "ERROR while setting up xout" );
}
// Get ParameterMap
ParameterObjectConstPointer parameterObject = static_cast< const ParameterObject* >( this->GetInput( "ParameterObject" ) );
ParameterMapListType parameterMapList = parameterObject->GetParameterMapList();
// Run the (possibly multiple) registration(s)
for( unsigned int i = 0; i < parameterMapList.size(); ++i )
{
// Create another instance of ElastixMain
ElastixMainPointer elastix = ElastixMainType::New();
// Set the current elastix-level
elastix->SetElastixLevel( i );
elastix->SetTotalNumberOfElastixLevels( parameterMapList.size() );
// Set stuff we get from a previous registration
elastix->SetInitialTransform( transform );
elastix->SetFixedImageContainer( fixedImageContainer );
elastix->SetMovingImageContainer( movingImageContainer );
elastix->SetFixedMaskContainer( fixedMaskContainer );
elastix->SetMovingMaskContainer( movingMaskContainer );
elastix->SetResultImageContainer( resultImageContainer );
elastix->SetOriginalFixedImageDirectionFlat( fixedImageOriginalDirection );
// Start registration
unsigned int isError = 0;
try
{
unsigned int isError = elastix->Run( argumentMap, parameterMapList[ i ] );
}
catch( itk::ExceptionObject &e )
{
itkExceptionMacro( << "Errors occurred during registration: " << e.what() );
}
if( isError == -2 )
{
itkExceptionMacro( << "Errors occurred during registration: Output directory does not exist." );
}
if( isError != 0 )
{
itkExceptionMacro( << "Uncought errors occurred during registration." );
}
// Get the transform, the fixedImage and the movingImage
// in order to put it in the next registration
transform = elastix->GetFinalTransform();
fixedImageContainer = elastix->GetFixedImageContainer();
movingImageContainer = elastix->GetMovingImageContainer();
fixedMaskContainer = elastix->GetFixedMaskContainer();
movingMaskContainer = elastix->GetMovingMaskContainer();
resultImageContainer = elastix->GetResultImageContainer();
fixedImageOriginalDirection = elastix->GetOriginalFixedImageDirectionFlat();
TransformParameterMapList.push_back( elastix->GetTransformParametersMap() );
// Set initial transform to an index number instead of a parameter filename
if( i > 0 )
{
std::stringstream index;
index << ( i - 1 );
TransformParameterMapList[ i ][ "InitialTransformParametersFileName" ][ 0 ] = index.str();
}
} // End loop over registrations
// Save result image
if( resultImageContainer.IsNotNull() && resultImageContainer->Size() > 0 )
{
this->SetPrimaryOutput( resultImageContainer->ElementAt( 0 ) );
}
// Save parameter map
ParameterObject::Pointer TransformParameters = ParameterObject::New();
TransformParameters->SetParameterMapList( TransformParameterMapList );
this->SetOutput( "TransformParameterObject", static_cast< itk::DataObject* >( TransformParameters ) );
// Close the modules
ElastixMainType::UnloadComponents();
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetParameterObject( ParameterObjectPointer parameterObject )
{
this->SetInput( "ParameterObject", static_cast< itk::DataObject* >( parameterObject ) );
}
template< typename TFixedImage, typename TMovingImage >
typename selx::ElastixFilter< TFixedImage, TMovingImage >::ParameterObjectPointer
ElastixFilter< TFixedImage, TMovingImage >
::GetTransformParameters( void )
{
// Make sure the transform parameters are up to date
this->Update();
return static_cast< ParameterObject* >( itk::ProcessObject::GetOutput( "TransformParameterObject" ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedImage( FixedImagePointer fixedImage )
{
// Free references to fixed images that has already been set
this->RemoveFixedImages();
this->SetInput( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedImage( DataObjectContainerPointer fixedImages )
{
if( fixedImages->Size() == 0 )
{
itkExceptionMacro( "Cannot set fixed images from empty container.")
}
// Free references to fixed images that has already been set
this->RemoveFixedImages();
// The first image will be used as the "FixedImage" required input.
// The rest of the images will be appended to the input container
// suffixed with _1, _2, etc. This allows us to read out only the
// fixed images for elastix fixed image container at a later stage
DataObjectContainerIterator fixedImageIterator = fixedImages->Begin();
this->SetInput( "FixedImage", fixedImageIterator->Value() );
++fixedImageIterator;
while( fixedImageIterator != fixedImages->End() )
{
this->AddInputAutoIncrementName( "FixedImage", fixedImageIterator->Value() );
++fixedImageIterator;
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddFixedImage( FixedImagePointer fixedImage )
{
if( !this->HasInput( "FixedImage") )
{
this->SetFixedImage( fixedImage );
}
else
{
this->AddInputAutoIncrementName( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingImage( MovingImagePointer movingImage )
{
// Free references to moving images that has already been set
this->RemoveMovingImages();
this->SetInput( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingImage( DataObjectContainerPointer movingImages )
{
if( movingImages->Size() == 0 )
{
itkExceptionMacro( "Cannot set moving images from empty container.")
}
// Free references to fixed images that has already been set
this->RemoveMovingImages();
// The first image will be used as the "MovingImage" required input.
// The rest of the images will be appended to the input container
// suffixed with _1, _2, etc. This allows us to read out only the
// moving images for elastix moving image container at a later stage
DataObjectContainerIterator movingImageIterator = movingImages->Begin();
this->SetInput( "MovingImage", movingImageIterator->Value() );
++movingImageIterator;
while( movingImageIterator != movingImages->End() )
{
this->AddInputAutoIncrementName( "MovingImage", static_cast< itk::DataObject* >( movingImageIterator->Value() ) );
++movingImageIterator;
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddMovingImage( MovingImagePointer movingImage )
{
if( !this->HasInput( "MovingImage") )
{
this->SetMovingImage( movingImage );
}
else
{
this->AddInputAutoIncrementName( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedMask( FixedImagePointer fixedMask )
{
this->SetInput( "FixedMask", static_cast< itk::DataObject* >( fixedMask ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingMask( MovingImagePointer movingMask )
{
this->SetInput( "MovingMask", static_cast< itk::DataObject* >( movingMask ) );
}
/*
* Adds a named input to the first null position in the input list
* Expands the list memory if necessary
*/
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddInputAutoIncrementName( DataObjectIdentifierType key, itk::DataObject* input )
{
for ( unsigned idx = 0; idx < this->GetNumberOfIndexedInputs(); ++idx )
{
if ( !this->GetInput( idx ) )
{
key += this->MakeNameFromInputIndex( idx );
this->SetInput( key, input );
return;
}
}
key += this->MakeNameFromInputIndex( this->GetNumberOfIndexedInputs() );
this->SetInput( key, input );
return;
}
template< typename TFixedImage, typename TMovingImage >
bool
ElastixFilter< TFixedImage, TMovingImage >
::IsFixedImage( DataObjectIdentifierType key )
{
return std::strncmp( "FixedImage", key.c_str(), 10 ) == 0;
}
template< typename TFixedImage, typename TMovingImage >
bool
ElastixFilter< TFixedImage, TMovingImage >
::IsMovingImage( DataObjectIdentifierType key )
{
return std::strncmp( "MovingImage", key.c_str(), 11 ) == 0;
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::RemoveFixedImages( void )
{
// Free references to fixed images that has already been set
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if ( this->IsFixedImage( inputNames[ i ] ) )
{
this->RemoveInput( inputNames[ i ] );
}
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::RemoveMovingImages( void )
{
// Free references to fixed images that has already been set
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if ( this->IsMovingImage( inputNames[ i ] ) )
{
this->RemoveInput( inputNames[ i ] );
}
}
}
} // namespace selx
#endif // ElastixFilter_hxx<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2010-05-13 17:32:17 +0200 (Do, 13 Mai 2010) $
Version: $Revision: 18029 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkPlanarArrow.h"
#include "mitkGeometry2D.h"
mitk::PlanarArrow::PlanarArrow()
: FEATURE_ID_LENGTH( this->AddFeature( "Length", "mm" ) )
{
// Directed arrow has two control points
this->ResetNumberOfControlPoints( 2 );
m_PolyLines->InsertElement( 0, VertexContainerType::New());
// Create helper polyline object (for drawing the orthogonal orientation line)
m_HelperPolyLines->InsertElement( 0, VertexContainerType::New());
m_HelperPolyLines->InsertElement( 1, VertexContainerType::New());
m_HelperPolyLines->ElementAt( 0 )->Reserve( 2 );
m_HelperPolyLines->ElementAt( 1 )->Reserve( 2 );
m_HelperPolyLinesToBePainted->InsertElement( 0, false );
m_HelperPolyLinesToBePainted->InsertElement( 1, false );
}
mitk::PlanarArrow::~PlanarArrow()
{
}
//void mitk::PlanarArrow::Initialize()
//{
// // Default initialization of line control points
//
// mitk::Geometry2D *geometry2D =
// dynamic_cast< mitk::Geometry2D * >( this->GetGeometry( 0 ) );
//
// if ( geometry2D == NULL )
// {
// MITK_ERROR << "Missing Geometry2D for PlanarArrow";
// return;
// }
//
// mitk::ScalarType width = geometry2D->GetBounds()[1];
// mitk::ScalarType height = geometry2D->GetBounds()[3];
//
// mitk::Point2D &startPoint = m_ControlPoints->ElementAt( 0 );
// mitk::Point2D &endPoint = m_ControlPoints->ElementAt( 1 );
//
// startPoint[0] = width / 2.0;
// startPoint[1] = height / 2.0;
//
// endPoint[0] = startPoint[0] + 20.0;
// endPoint[1] = startPoint[1] + 20.0;
//}
void mitk::PlanarArrow::GeneratePolyLine()
{
// TODO: start line at specified start point...
// Generate poly-line
m_PolyLines->ElementAt( 0 )->Reserve( 2 );
m_PolyLines->ElementAt( 0 )->ElementAt( 0 ) = m_ControlPoints->ElementAt( 0 );
m_PolyLines->ElementAt( 0 )->ElementAt( 1 ) = m_ControlPoints->ElementAt( 1 );
}
void mitk::PlanarArrow::GenerateHelperPolyLine(double mmPerDisplayUnit, unsigned int displayHeight)
{
// Generate helper polyline (orientation line orthogonal to first line)
// if the third control point is currently being set
if ( this->GetNumberOfControlPoints() != 2 )
{
m_HelperPolyLinesToBePainted->SetElement( 0, false );
m_HelperPolyLinesToBePainted->SetElement( 1, false );
return;
}
m_HelperPolyLinesToBePainted->SetElement( 0, true );
m_HelperPolyLinesToBePainted->SetElement( 1, true );
//Fixed size radius depending on screen size for the angle
double nonScalingLength = displayHeight * mmPerDisplayUnit * 0.025;
// Calculate arrow peak
const Point2D& p1 = m_ControlPoints->ElementAt( 0 );
const Point2D& p2 = m_ControlPoints->ElementAt( 1 );
Vector2D n1 = p1 - p2;
n1.Normalize();
double degrees = 100.0;
Vector2D temp;
temp[0] = n1[0] * cos(degrees) - n1[1] * sin(degrees);
temp[1] = n1[0] * sin(degrees) + n1[1] * cos(degrees);
Vector2D temp2;
temp2[0] = n1[0] * cos(-degrees) - n1[1] * sin(-degrees);
temp2[1] = n1[0] * sin(-degrees) + n1[1] * cos(-degrees);
m_HelperPolyLines->ElementAt( 0 )->ElementAt( 0 ) = p1;
m_HelperPolyLines->ElementAt( 0 )->ElementAt( 1 ) = p1 - temp * nonScalingLength;
m_HelperPolyLines->ElementAt( 1 )->ElementAt( 0 ) = p1;
m_HelperPolyLines->ElementAt( 1 )->ElementAt( 1 ) = p1 - temp2 * nonScalingLength;
}
void mitk::PlanarArrow::EvaluateFeaturesInternal()
{
// Calculate line length
const Point3D &p0 = this->GetWorldControlPoint( 0 );
const Point3D &p1 = this->GetWorldControlPoint( 1 );
double length = p0.EuclideanDistanceTo( p1 );
this->SetQuantity( FEATURE_ID_LENGTH, length );
}
void mitk::PlanarArrow::PrintSelf( std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf( os, indent );
}
<commit_msg>CHG (#4157): reduced arrow size from 0.025 to 0.015 * displayheight * mmPerDisplayUnit<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2010-05-13 17:32:17 +0200 (Do, 13 Mai 2010) $
Version: $Revision: 18029 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkPlanarArrow.h"
#include "mitkGeometry2D.h"
mitk::PlanarArrow::PlanarArrow()
: FEATURE_ID_LENGTH( this->AddFeature( "Length", "mm" ) )
{
// Directed arrow has two control points
this->ResetNumberOfControlPoints( 2 );
m_PolyLines->InsertElement( 0, VertexContainerType::New());
// Create helper polyline object (for drawing the orthogonal orientation line)
m_HelperPolyLines->InsertElement( 0, VertexContainerType::New());
m_HelperPolyLines->InsertElement( 1, VertexContainerType::New());
m_HelperPolyLines->ElementAt( 0 )->Reserve( 2 );
m_HelperPolyLines->ElementAt( 1 )->Reserve( 2 );
m_HelperPolyLinesToBePainted->InsertElement( 0, false );
m_HelperPolyLinesToBePainted->InsertElement( 1, false );
}
mitk::PlanarArrow::~PlanarArrow()
{
}
//void mitk::PlanarArrow::Initialize()
//{
// // Default initialization of line control points
//
// mitk::Geometry2D *geometry2D =
// dynamic_cast< mitk::Geometry2D * >( this->GetGeometry( 0 ) );
//
// if ( geometry2D == NULL )
// {
// MITK_ERROR << "Missing Geometry2D for PlanarArrow";
// return;
// }
//
// mitk::ScalarType width = geometry2D->GetBounds()[1];
// mitk::ScalarType height = geometry2D->GetBounds()[3];
//
// mitk::Point2D &startPoint = m_ControlPoints->ElementAt( 0 );
// mitk::Point2D &endPoint = m_ControlPoints->ElementAt( 1 );
//
// startPoint[0] = width / 2.0;
// startPoint[1] = height / 2.0;
//
// endPoint[0] = startPoint[0] + 20.0;
// endPoint[1] = startPoint[1] + 20.0;
//}
void mitk::PlanarArrow::GeneratePolyLine()
{
// TODO: start line at specified start point...
// Generate poly-line
m_PolyLines->ElementAt( 0 )->Reserve( 2 );
m_PolyLines->ElementAt( 0 )->ElementAt( 0 ) = m_ControlPoints->ElementAt( 0 );
m_PolyLines->ElementAt( 0 )->ElementAt( 1 ) = m_ControlPoints->ElementAt( 1 );
}
void mitk::PlanarArrow::GenerateHelperPolyLine(double mmPerDisplayUnit, unsigned int displayHeight)
{
// Generate helper polyline (orientation line orthogonal to first line)
// if the third control point is currently being set
if ( this->GetNumberOfControlPoints() != 2 )
{
m_HelperPolyLinesToBePainted->SetElement( 0, false );
m_HelperPolyLinesToBePainted->SetElement( 1, false );
return;
}
m_HelperPolyLinesToBePainted->SetElement( 0, true );
m_HelperPolyLinesToBePainted->SetElement( 1, true );
//Fixed size depending on screen size for the angle
double nonScalingLength = displayHeight * mmPerDisplayUnit * 0.015;
// Calculate arrow peak
const Point2D& p1 = m_ControlPoints->ElementAt( 0 );
const Point2D& p2 = m_ControlPoints->ElementAt( 1 );
Vector2D n1 = p1 - p2;
n1.Normalize();
double degrees = 100.0;
Vector2D temp;
temp[0] = n1[0] * cos(degrees) - n1[1] * sin(degrees);
temp[1] = n1[0] * sin(degrees) + n1[1] * cos(degrees);
Vector2D temp2;
temp2[0] = n1[0] * cos(-degrees) - n1[1] * sin(-degrees);
temp2[1] = n1[0] * sin(-degrees) + n1[1] * cos(-degrees);
m_HelperPolyLines->ElementAt( 0 )->ElementAt( 0 ) = p1;
m_HelperPolyLines->ElementAt( 0 )->ElementAt( 1 ) = p1 - temp * nonScalingLength;
m_HelperPolyLines->ElementAt( 1 )->ElementAt( 0 ) = p1;
m_HelperPolyLines->ElementAt( 1 )->ElementAt( 1 ) = p1 - temp2 * nonScalingLength;
}
void mitk::PlanarArrow::EvaluateFeaturesInternal()
{
// Calculate line length
const Point3D &p0 = this->GetWorldControlPoint( 0 );
const Point3D &p1 = this->GetWorldControlPoint( 1 );
double length = p0.EuclideanDistanceTo( p1 );
this->SetQuantity( FEATURE_ID_LENGTH, length );
}
void mitk::PlanarArrow::PrintSelf( std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf( os, indent );
}
<|endoftext|>
|
<commit_before>#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#include <set>
#include <queue>
#include "PipeBuffer.h"
#include "dcloudgahp_commands.h"
#include "dcloudgahp_common.h"
#define DCLOUD_GAHP_VERSION "0.0.1"
#define GAHP_COMMAND_ASYNC_MODE_ON "ASYNC_MODE_ON"
#define GAHP_COMMAND_ASYNC_MODE_OFF "ASYNC_MODE_OFF"
#define GAHP_COMMAND_RESULTS "RESULTS"
#define GAHP_COMMAND_QUIT "QUIT"
#define GAHP_COMMAND_VERSION "VERSION"
#define GAHP_COMMAND_COMMANDS "COMMANDS"
#define GAHP_RESULT_SUCCESS "S"
#define GAHP_RESULT_ERROR "E"
#define GAHP_RESULT_FAILURE "F"
#define DCLOUD_COMMAND_VM_SUBMIT "DCLOUD_VM_SUBMIT"
#define DCLOUD_COMMAND_VM_STATUS_ALL "DCLOUD_VM_STATUS_ALL"
#define DCLOUD_COMMAND_VM_ACTION "DCLOUD_VM_ACTION"
#define DCLOUD_COMMAND_VM_INFO "DCLOUD_VM_INFO"
#define DCLOUD_COMMAND_VM_FIND "DCLOUD_VM_FIND"
const char * version = "$GahpVersion " DCLOUD_GAHP_VERSION " Feb 4 2010 Condor\\ DCLOUDGAHP $";
static std::set<DcloudGahpCommand*> dcloud_gahp_commands;
FILE *logfp;
static pthread_mutex_t async_mutex = PTHREAD_MUTEX_INITIALIZER;
static bool async_mode = false;
static bool async_results_signalled = false;
static std::queue<std::string> results_list;
static pthread_mutex_t results_list_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t stdout_mutex = PTHREAD_MUTEX_INITIALIZER;
static void safe_printf(const char *fmt, ...)
{
va_list va_args;
pthread_mutex_lock(&stdout_mutex);
va_start(va_args, fmt);
vprintf(fmt, va_args);
va_end(va_args);
fflush(stdout);
pthread_mutex_unlock(&stdout_mutex);
}
static int parse_gahp_command(const char *raw, Gahp_Args *args)
{
int beginning = 0;
int len = strlen(raw);
char *buff;
int buff_len = 0;
if (!raw) {
dcloudprintf("NULL command!\n");
return FALSE;
}
buff = (char *)malloc(len+1);
if (buff == NULL) {
dcloudprintf("Failed to allocate memory\n");
return FALSE;
}
args->reset();
for (int i = 0; i<len; i++) {
if ( raw[i] == '\\' ) {
i++; // skip this char
if (i<(len-1))
buff[buff_len++] = raw[i];
continue;
}
/* Check if character read was whitespace */
if ( raw[i]==' ' || raw[i]=='\t' || raw[i]=='\r' || raw[i] == '\n') {
/* Handle Transparency: we would only see these chars
* if they WEREN'T escaped, so treat them as arg separators
*/
buff[buff_len++] = '\0';
args->add_arg( strdup(buff) );
buff_len = 0; // re-set temporary buffer
beginning = i+1; // next char will be one after whitespace
}
else {
// It's just a regular character, save it
buff[buff_len++] = raw[i];
}
}
/* Copy the last portion */
buff[buff_len++] = '\0';
args->add_arg( strdup(buff) );
free (buff);
return TRUE;
}
static void gahp_output_return(const char **results, const int count)
{
int i;
for (i = 0; i < count; i++) {
safe_printf("%s", results[i]);
if (i < (count - 1))
safe_printf(" ");
}
safe_printf("\n");
}
static void gahp_output_return_success(void)
{
const char *result[] = {GAHP_RESULT_SUCCESS};
gahp_output_return(result, 1);
}
static void gahp_output_return_error(void)
{
const char* result[] = {GAHP_RESULT_ERROR};
gahp_output_return(result, 1);
}
static void unregisterAllDcloudCommands(void)
{
std::set<DcloudGahpCommand*>::iterator itr;
for (itr = dcloud_gahp_commands.begin(); itr != dcloud_gahp_commands.end(); itr++) {
delete *itr;
}
}
static void handle_command_results(Gahp_Args *args)
{
// Print number of results
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
pthread_mutex_lock(&results_list_mutex);
safe_printf("%s %d\n", GAHP_RESULT_SUCCESS, results_list.size());
while (!results_list.empty()) {
safe_printf("%s", results_list.front().c_str());
results_list.pop();
}
pthread_mutex_unlock(&results_list_mutex);
async_results_signalled = false;
}
static void handle_command_version(Gahp_Args *args)
{
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
safe_printf(GAHP_RESULT_SUCCESS " %s\n", version);
}
static void handle_command_async_on(Gahp_Args *args)
{
// Turn on async mode
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
pthread_mutex_lock(&async_mutex);
async_mode = true;
async_results_signalled = false;
pthread_mutex_unlock(&async_mutex);
gahp_output_return_success();
}
static void handle_command_async_off(Gahp_Args *args)
{
// Turn off async mode
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
pthread_mutex_lock(&async_mutex);
async_mode = false;
pthread_mutex_unlock(&async_mutex);
gahp_output_return_success();
}
static void handle_command_commands(Gahp_Args *args)
{
const char **commands;
int i = 0;
const char **tmp;
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
commands = (const char **)malloc(7 * sizeof(char *));
if (commands == NULL) {
dcloudprintf("failed to allocate memory\n");
gahp_output_return_error();
return;
}
commands[i++] = GAHP_RESULT_SUCCESS;
commands[i++] = GAHP_COMMAND_ASYNC_MODE_ON;
commands[i++] = GAHP_COMMAND_ASYNC_MODE_OFF;
commands[i++] = GAHP_COMMAND_RESULTS;
commands[i++] = GAHP_COMMAND_QUIT;
commands[i++] = GAHP_COMMAND_VERSION;
commands[i++] = GAHP_COMMAND_COMMANDS;
std::set<DcloudGahpCommand*>::iterator itr;
for (itr = dcloud_gahp_commands.begin(); itr != dcloud_gahp_commands.end();
itr++ ) {
tmp = (const char **)realloc(commands, (i+1) * sizeof(char *));
if (tmp == NULL) {
dcloudprintf("failed to realloc memory\n");
gahp_output_return_error();
free(commands);
return;
}
commands = tmp;
commands[i++] = (*itr)->command.c_str();
}
gahp_output_return(commands, i);
free(commands);
}
struct workerdata {
char *fullcommand;
workerfn worker;
};
static void *worker_function(void *ptr)
{
struct workerdata *data = (struct workerdata *)ptr;
Gahp_Args args;
std::string output_string = "";
if (!parse_gahp_command(data->fullcommand, &args)) {
/* this should really never happen; we successfully parsed it
* earlier, so there is no reason we can't parse it again.
*/
dcloudprintf("Failed to parse command again\n");
output_string = create_failure(0, "Command_Parse_Failure");
goto cleanup;
}
/* even if the worker function fails, there should still be an error
* message in output_string that we want to add
*/
dcloudprintf("Worker started\n");
data->worker(args.argc, args.argv, output_string);
dcloudprintf("Worker done!\n");
cleanup:
pthread_mutex_lock(&results_list_mutex);
results_list.push(output_string);
pthread_mutex_unlock(&results_list_mutex);
pthread_mutex_lock(&async_mutex);
if (async_mode && !async_results_signalled) {
safe_printf("R\n");
async_results_signalled = true;
}
pthread_mutex_unlock(&async_mutex);
free(data->fullcommand);
free(data);
return NULL;
}
static void handle_dcloud_commands(const char *cmd, const char *fullcommand)
{
pthread_t thread;
struct workerdata *data;
std::set<DcloudGahpCommand*>::iterator itr;
for (itr = dcloud_gahp_commands.begin(); itr != dcloud_gahp_commands.end();
itr++ ) {
if (STRCASEEQ((*itr)->command.c_str(), cmd)) {
data = (struct workerdata *)malloc(sizeof(struct workerdata));
if (data == NULL) {
dcloudprintf("Failed to allocate memory for new thread\n");
gahp_output_return_error();
return;
}
data->fullcommand = strdup(fullcommand);
if (data->fullcommand == NULL) {
dcloudprintf("Failed to allocate memory for command\n");
gahp_output_return_error();
free(data);
return;
}
data->worker = (*itr)->workerfunction;
if (pthread_create(&thread, NULL, worker_function, data) < 0) {
dcloudprintf("Failed to create new thread\n");
gahp_output_return_error();
free(data->fullcommand);
free(data);
return;
}
pthread_detach(thread);
gahp_output_return_success();
return;
}
}
/* if we reached here, we didn't find the command to execute */
gahp_output_return_error();
}
static void handlePipe(int stdin_pipe)
{
std::string *line;
PipeBuffer m_stdin_buffer;
m_stdin_buffer.setPipeEnd(stdin_pipe);
while ((line = m_stdin_buffer.GetNextLine()) != NULL) {
const char *command = line->c_str();
Gahp_Args args;
dcloudprintf("Handling line %s\n", command);
if (parse_gahp_command(command, &args)) {
if (STRCASEEQ(args.argv[0], GAHP_COMMAND_RESULTS))
handle_command_results(&args);
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_VERSION))
handle_command_version(&args);
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_QUIT)) {
gahp_output_return_success();
unregisterAllDcloudCommands();
/* Since we are exiting, free the line to avoid a
* valgrind warning
*/
args.reset();
delete line;
exit(0);
}
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_ASYNC_MODE_ON))
handle_command_async_on(&args);
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_ASYNC_MODE_OFF))
handle_command_async_off(&args);
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_COMMANDS))
handle_command_commands(&args);
else
/* note that we pass "command" into handle_dcloud_commands
* instead of the already parsed Gahp_Args. This is because
* the dcloud commands are all going to be handled in a
* separate thread, so there is no elegant way for us to handle
* this. Therefore, the dcloud_commands will just re-parse
* the command. Kind of ugly, but really better than the
* alternatives.
*/
handle_dcloud_commands(args.argv[0], command);
}
else
gahp_output_return_error();
delete line;
}
}
static void registerDcloudGahpCommand(const char *command, workerfn workerfunc)
{
DcloudGahpCommand *newcommand;
if (command == NULL) {
dcloudprintf("tried to register NULL command\n");
return;
}
newcommand = new DcloudGahpCommand(command, workerfunc);
dcloud_gahp_commands.insert(newcommand);
}
static void registerAllDcloudCommands(void)
{
dcloudprintf("\n");
if (dcloud_gahp_commands.size() > 0) {
dcloudprintf("already called\n");
return;
}
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_SUBMIT,
dcloud_start_worker);
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_ACTION,
dcloud_action_worker);
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_INFO,
dcloud_info_worker);
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_STATUS_ALL,
dcloud_statusall_worker);
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_FIND,
dcloud_find_worker);
}
int main(int argc, char *argv[])
{
logfp = fopen("/tmp/dcloud_gahp.debug", "a");
if (!logfp) {
fprintf(stderr, "Could not open log file /tmp/dcloud_gahp.debug: %s\n",
strerror(errno));
return 1;
}
dcloudprintf("Starting dcloud GAHP\n");
registerAllDcloudCommands();
safe_printf("%s\n", version);
while (1)
/* handle input from stdin */
handlePipe(0);
return 0;
}
<commit_msg>Improve dcloud_gahp's reading of stdin. #1271<commit_after>#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#include <set>
#include <queue>
#include "PipeBuffer.h"
#include "dcloudgahp_commands.h"
#include "dcloudgahp_common.h"
#define DCLOUD_GAHP_VERSION "0.0.1"
#define GAHP_COMMAND_ASYNC_MODE_ON "ASYNC_MODE_ON"
#define GAHP_COMMAND_ASYNC_MODE_OFF "ASYNC_MODE_OFF"
#define GAHP_COMMAND_RESULTS "RESULTS"
#define GAHP_COMMAND_QUIT "QUIT"
#define GAHP_COMMAND_VERSION "VERSION"
#define GAHP_COMMAND_COMMANDS "COMMANDS"
#define GAHP_RESULT_SUCCESS "S"
#define GAHP_RESULT_ERROR "E"
#define GAHP_RESULT_FAILURE "F"
#define DCLOUD_COMMAND_VM_SUBMIT "DCLOUD_VM_SUBMIT"
#define DCLOUD_COMMAND_VM_STATUS_ALL "DCLOUD_VM_STATUS_ALL"
#define DCLOUD_COMMAND_VM_ACTION "DCLOUD_VM_ACTION"
#define DCLOUD_COMMAND_VM_INFO "DCLOUD_VM_INFO"
#define DCLOUD_COMMAND_VM_FIND "DCLOUD_VM_FIND"
const char * version = "$GahpVersion " DCLOUD_GAHP_VERSION " Feb 4 2010 Condor\\ DCLOUDGAHP $";
static std::set<DcloudGahpCommand*> dcloud_gahp_commands;
FILE *logfp;
static PipeBuffer m_stdin_buffer;
static pthread_mutex_t async_mutex = PTHREAD_MUTEX_INITIALIZER;
static bool async_mode = false;
static bool async_results_signalled = false;
static std::queue<std::string> results_list;
static pthread_mutex_t results_list_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t stdout_mutex = PTHREAD_MUTEX_INITIALIZER;
static void safe_printf(const char *fmt, ...)
{
va_list va_args;
pthread_mutex_lock(&stdout_mutex);
va_start(va_args, fmt);
vprintf(fmt, va_args);
va_end(va_args);
fflush(stdout);
pthread_mutex_unlock(&stdout_mutex);
}
static int parse_gahp_command(const char *raw, Gahp_Args *args)
{
int beginning = 0;
int len = strlen(raw);
char *buff;
int buff_len = 0;
if (!raw) {
dcloudprintf("NULL command!\n");
return FALSE;
}
buff = (char *)malloc(len+1);
if (buff == NULL) {
dcloudprintf("Failed to allocate memory\n");
return FALSE;
}
args->reset();
for (int i = 0; i<len; i++) {
if ( raw[i] == '\\' ) {
i++; // skip this char
if (i<(len-1))
buff[buff_len++] = raw[i];
continue;
}
/* Check if character read was whitespace */
if ( raw[i]==' ' || raw[i]=='\t' || raw[i]=='\r' || raw[i] == '\n') {
/* Handle Transparency: we would only see these chars
* if they WEREN'T escaped, so treat them as arg separators
*/
buff[buff_len++] = '\0';
args->add_arg( strdup(buff) );
buff_len = 0; // re-set temporary buffer
beginning = i+1; // next char will be one after whitespace
}
else {
// It's just a regular character, save it
buff[buff_len++] = raw[i];
}
}
/* Copy the last portion */
buff[buff_len++] = '\0';
args->add_arg( strdup(buff) );
free (buff);
return TRUE;
}
static void gahp_output_return(const char **results, const int count)
{
int i;
for (i = 0; i < count; i++) {
safe_printf("%s", results[i]);
if (i < (count - 1))
safe_printf(" ");
}
safe_printf("\n");
}
static void gahp_output_return_success(void)
{
const char *result[] = {GAHP_RESULT_SUCCESS};
gahp_output_return(result, 1);
}
static void gahp_output_return_error(void)
{
const char* result[] = {GAHP_RESULT_ERROR};
gahp_output_return(result, 1);
}
static void unregisterAllDcloudCommands(void)
{
std::set<DcloudGahpCommand*>::iterator itr;
for (itr = dcloud_gahp_commands.begin(); itr != dcloud_gahp_commands.end(); itr++) {
delete *itr;
}
}
static void handle_command_results(Gahp_Args *args)
{
// Print number of results
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
pthread_mutex_lock(&results_list_mutex);
safe_printf("%s %d\n", GAHP_RESULT_SUCCESS, results_list.size());
while (!results_list.empty()) {
safe_printf("%s", results_list.front().c_str());
results_list.pop();
}
pthread_mutex_unlock(&results_list_mutex);
async_results_signalled = false;
}
static void handle_command_version(Gahp_Args *args)
{
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
safe_printf(GAHP_RESULT_SUCCESS " %s\n", version);
}
static void handle_command_async_on(Gahp_Args *args)
{
// Turn on async mode
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
pthread_mutex_lock(&async_mutex);
async_mode = true;
async_results_signalled = false;
pthread_mutex_unlock(&async_mutex);
gahp_output_return_success();
}
static void handle_command_async_off(Gahp_Args *args)
{
// Turn off async mode
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
pthread_mutex_lock(&async_mutex);
async_mode = false;
pthread_mutex_unlock(&async_mutex);
gahp_output_return_success();
}
static void handle_command_commands(Gahp_Args *args)
{
const char **commands;
int i = 0;
const char **tmp;
if (args->argc != 1) {
dcloudprintf("Expected 1 argument, saw %d\n", args->argc);
gahp_output_return_error();
return;
}
commands = (const char **)malloc(7 * sizeof(char *));
if (commands == NULL) {
dcloudprintf("failed to allocate memory\n");
gahp_output_return_error();
return;
}
commands[i++] = GAHP_RESULT_SUCCESS;
commands[i++] = GAHP_COMMAND_ASYNC_MODE_ON;
commands[i++] = GAHP_COMMAND_ASYNC_MODE_OFF;
commands[i++] = GAHP_COMMAND_RESULTS;
commands[i++] = GAHP_COMMAND_QUIT;
commands[i++] = GAHP_COMMAND_VERSION;
commands[i++] = GAHP_COMMAND_COMMANDS;
std::set<DcloudGahpCommand*>::iterator itr;
for (itr = dcloud_gahp_commands.begin(); itr != dcloud_gahp_commands.end();
itr++ ) {
tmp = (const char **)realloc(commands, (i+1) * sizeof(char *));
if (tmp == NULL) {
dcloudprintf("failed to realloc memory\n");
gahp_output_return_error();
free(commands);
return;
}
commands = tmp;
commands[i++] = (*itr)->command.c_str();
}
gahp_output_return(commands, i);
free(commands);
}
struct workerdata {
char *fullcommand;
workerfn worker;
};
static void *worker_function(void *ptr)
{
struct workerdata *data = (struct workerdata *)ptr;
Gahp_Args args;
std::string output_string = "";
if (!parse_gahp_command(data->fullcommand, &args)) {
/* this should really never happen; we successfully parsed it
* earlier, so there is no reason we can't parse it again.
*/
dcloudprintf("Failed to parse command again\n");
output_string = create_failure(0, "Command_Parse_Failure");
goto cleanup;
}
/* even if the worker function fails, there should still be an error
* message in output_string that we want to add
*/
dcloudprintf("Worker started\n");
data->worker(args.argc, args.argv, output_string);
dcloudprintf("Worker done!\n");
cleanup:
pthread_mutex_lock(&results_list_mutex);
results_list.push(output_string);
pthread_mutex_unlock(&results_list_mutex);
pthread_mutex_lock(&async_mutex);
if (async_mode && !async_results_signalled) {
safe_printf("R\n");
async_results_signalled = true;
}
pthread_mutex_unlock(&async_mutex);
free(data->fullcommand);
free(data);
return NULL;
}
static void handle_dcloud_commands(const char *cmd, const char *fullcommand)
{
pthread_t thread;
struct workerdata *data;
std::set<DcloudGahpCommand*>::iterator itr;
for (itr = dcloud_gahp_commands.begin(); itr != dcloud_gahp_commands.end();
itr++ ) {
if (STRCASEEQ((*itr)->command.c_str(), cmd)) {
data = (struct workerdata *)malloc(sizeof(struct workerdata));
if (data == NULL) {
dcloudprintf("Failed to allocate memory for new thread\n");
gahp_output_return_error();
return;
}
data->fullcommand = strdup(fullcommand);
if (data->fullcommand == NULL) {
dcloudprintf("Failed to allocate memory for command\n");
gahp_output_return_error();
free(data);
return;
}
data->worker = (*itr)->workerfunction;
if (pthread_create(&thread, NULL, worker_function, data) < 0) {
dcloudprintf("Failed to create new thread\n");
gahp_output_return_error();
free(data->fullcommand);
free(data);
return;
}
pthread_detach(thread);
gahp_output_return_success();
return;
}
}
/* if we reached here, we didn't find the command to execute */
gahp_output_return_error();
}
static void handlePipe()
{
std::string *line;
while ((line = m_stdin_buffer.GetNextLine()) != NULL) {
const char *command = line->c_str();
Gahp_Args args;
dcloudprintf("Handling line %s\n", command);
if (parse_gahp_command(command, &args)) {
if (STRCASEEQ(args.argv[0], GAHP_COMMAND_RESULTS))
handle_command_results(&args);
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_VERSION))
handle_command_version(&args);
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_QUIT)) {
gahp_output_return_success();
unregisterAllDcloudCommands();
/* Since we are exiting, free the line to avoid a
* valgrind warning
*/
args.reset();
delete line;
exit(0);
}
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_ASYNC_MODE_ON))
handle_command_async_on(&args);
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_ASYNC_MODE_OFF))
handle_command_async_off(&args);
else if (STRCASEEQ(args.argv[0], GAHP_COMMAND_COMMANDS))
handle_command_commands(&args);
else
/* note that we pass "command" into handle_dcloud_commands
* instead of the already parsed Gahp_Args. This is because
* the dcloud commands are all going to be handled in a
* separate thread, so there is no elegant way for us to handle
* this. Therefore, the dcloud_commands will just re-parse
* the command. Kind of ugly, but really better than the
* alternatives.
*/
handle_dcloud_commands(args.argv[0], command);
}
else
gahp_output_return_error();
delete line;
}
// check if GetNextLine() returned NULL because of an error or EOF
if (m_stdin_buffer.IsError() || m_stdin_buffer.IsEOF()) {
dcloudprintf("stdin buffer closed, exiting\n");
exit(1);
}
}
static void registerDcloudGahpCommand(const char *command, workerfn workerfunc)
{
DcloudGahpCommand *newcommand;
if (command == NULL) {
dcloudprintf("tried to register NULL command\n");
return;
}
newcommand = new DcloudGahpCommand(command, workerfunc);
dcloud_gahp_commands.insert(newcommand);
}
static void registerAllDcloudCommands(void)
{
dcloudprintf("\n");
if (dcloud_gahp_commands.size() > 0) {
dcloudprintf("already called\n");
return;
}
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_SUBMIT,
dcloud_start_worker);
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_ACTION,
dcloud_action_worker);
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_INFO,
dcloud_info_worker);
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_STATUS_ALL,
dcloud_statusall_worker);
registerDcloudGahpCommand(DCLOUD_COMMAND_VM_FIND,
dcloud_find_worker);
}
int main(int argc, char *argv[])
{
logfp = fopen("/tmp/dcloud_gahp.debug", "a");
if (!logfp) {
fprintf(stderr, "Could not open log file /tmp/dcloud_gahp.debug: %s\n",
strerror(errno));
return 1;
}
dcloudprintf("Starting dcloud GAHP\n");
registerAllDcloudCommands();
safe_printf("%s\n", version);
m_stdin_buffer.setPipeEnd(0);
while (1)
/* handle input from stdin */
handlePipe();
return 0;
}
<|endoftext|>
|
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not 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 <config.h>
#include <libtest/common.h>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fnmatch.h>
#include <iostream>
#include <fstream>
#include <memory>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
using namespace libtest;
static void stats_print(libtest::Framework *frame)
{
if (frame->failed() == 0 and frame->success() == 0)
{
return;
}
Outn();
Out << "Collections\t\t\t\t\t" << frame->total();
Out << "\tFailed\t\t\t\t\t" << frame->failed();
Out << "\tSkipped\t\t\t\t\t" << frame->skipped();
Out << "\tSucceeded\t\t\t\t" << frame->success();
Outn();
Out << "Tests\t\t\t\t\t" << frame->sum_total();
Out << "\tFailed\t\t\t\t" << frame->sum_failed();
Out << "\tSkipped\t\t\t\t" << frame->sum_skipped();
Out << "\tSucceeded\t\t\t" << frame->sum_success();
}
#include <getopt.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
Out << "BEGIN:" << argv[0];
bool opt_massive= false;
unsigned long int opt_repeat= 1; // Run all tests once
bool opt_quiet= false;
std::string collection_to_run;
std::string wildcard;
std::string binary_name;
const char *just_filename= rindex(argv[0], '/');
if (just_filename)
{
just_filename++;
}
else
{
just_filename= argv[0];
}
if (just_filename[0] == 'l' and just_filename[1] == 't' and just_filename[2] == '-')
{
just_filename+= 3;
}
binary_name.append(just_filename);
/*
Valgrind does not currently work reliably, or sometimes at all, on OSX
- Fri Jun 15 11:24:07 EDT 2012
*/
#if defined(TARGET_OS_OSX) && TARGET_OS_OSX
if (valgrind_is_caller())
{
return EXIT_SKIP;
}
#endif
// Options parsing
{
enum long_option_t {
OPT_LIBYATL_VERSION,
OPT_LIBYATL_MATCH_COLLECTION,
OPT_LIBYATL_MASSIVE,
OPT_LIBYATL_QUIET,
OPT_LIBYATL_MATCH_WILDCARD,
OPT_LIBYATL_REPEAT
};
static struct option long_options[]=
{
{ "version", no_argument, NULL, OPT_LIBYATL_VERSION },
{ "quiet", no_argument, NULL, OPT_LIBYATL_QUIET },
{ "repeat", no_argument, NULL, OPT_LIBYATL_REPEAT },
{ "collection", required_argument, NULL, OPT_LIBYATL_MATCH_COLLECTION },
{ "wildcard", required_argument, NULL, OPT_LIBYATL_MATCH_WILDCARD },
{ "massive", no_argument, NULL, OPT_LIBYATL_MASSIVE },
{ 0, 0, 0, 0 }
};
int option_index= 0;
while (1)
{
int option_rv= getopt_long(argc, argv, "", long_options, &option_index);
if (option_rv == -1)
{
break;
}
switch (option_rv)
{
case OPT_LIBYATL_VERSION:
break;
case OPT_LIBYATL_QUIET:
opt_quiet= true;
break;
case OPT_LIBYATL_REPEAT:
opt_repeat= strtoul(optarg, (char **) NULL, 10);
break;
case OPT_LIBYATL_MATCH_COLLECTION:
collection_to_run= optarg;
break;
case OPT_LIBYATL_MATCH_WILDCARD:
wildcard= optarg;
break;
case OPT_LIBYATL_MASSIVE:
opt_massive= true;
break;
case '?':
/* getopt_long already printed an error message. */
Error << "unknown option to getopt_long()";
exit(EXIT_FAILURE);
default:
break;
}
}
}
srandom((unsigned int)time(NULL));
if (bool(getenv("YATL_REPEAT")) and (strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10) > 1))
{
opt_repeat= strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10);
}
if ((bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "0") == 0)) or opt_quiet)
{
opt_quiet= true;
}
else if (getenv("JENKINS_URL"))
{
if (bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "1") == 0))
{ }
else
{
opt_quiet= true;
}
}
if ((bool(getenv("YATL_RUN_MASSIVE_TESTS"))) or opt_massive)
{
opt_massive= true;
}
if (opt_quiet)
{
close(STDOUT_FILENO);
}
if (opt_massive)
{
is_massive(opt_massive);
}
char tmp_directory[1024];
if (getenv("LIBTEST_TMP"))
{
snprintf(tmp_directory, sizeof(tmp_directory), "%s", getenv("LIBTEST_TMP"));
}
else
{
snprintf(tmp_directory, sizeof(tmp_directory), "%s", LIBTEST_TEMP);
}
if (chdir(tmp_directory) == -1)
{
char getcwd_buffer[1024];
char *dir= getcwd(getcwd_buffer, sizeof(getcwd_buffer));
Error << "Unable to chdir() from " << dir << " to " << tmp_directory << " errno:" << strerror(errno);
return EXIT_FAILURE;
}
if (libtest::libtool() == NULL)
{
Error << "Failed to locate libtool";
return EXIT_FAILURE;
}
if (getenv("YATL_COLLECTION_TO_RUN"))
{
if (strlen(getenv("YATL_COLLECTION_TO_RUN")))
{
collection_to_run= getenv("YATL_COLLECTION_TO_RUN");
}
}
if (collection_to_run.compare("none") == 0)
{
return EXIT_SUCCESS;
}
if (collection_to_run.empty() == false)
{
Out << "Only testing " << collection_to_run;
}
int exit_code;
try
{
do
{
exit_code= EXIT_SUCCESS;
fatal_assert(sigignore(SIGPIPE) == 0);
libtest::SignalThread signal;
if (signal.setup() == false)
{
Error << "Failed to setup signals";
return EXIT_FAILURE;
}
std::auto_ptr<libtest::Framework> frame(new libtest::Framework(signal, binary_name, collection_to_run, wildcard));
// Run create(), bail on error.
{
switch (frame->create())
{
case TEST_SUCCESS:
break;
case TEST_SKIPPED:
return EXIT_SKIP;
case TEST_FAILURE:
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "frame->create()" << std::endl;
return EXIT_FAILURE;
}
}
frame->exec();
if (signal.is_shutdown() == false)
{
signal.set_shutdown(SHUTDOWN_GRACEFUL);
}
shutdown_t status= signal.get_shutdown();
if (status == SHUTDOWN_FORCED)
{
Out << "Tests were aborted.";
exit_code= EXIT_FAILURE;
}
else if (frame->failed())
{
Out << "Some test failed.";
exit_code= EXIT_FAILURE;
}
else if (frame->skipped() and frame->failed() and frame->success())
{
Out << "Some tests were skipped.";
}
else if (frame->success() and (frame->failed() == 0))
{
Out;
Out << "All tests completed successfully.";
}
stats_print(frame.get());
std::ofstream xml_file;
std::string file_name;
file_name.append(tmp_directory);
file_name.append(frame->name());
file_name.append(".xml");
xml_file.open(file_name.c_str(), std::ios::trunc);
libtest::Formatter::xml(*frame, xml_file);
Outn(); // Generate a blank to break up the messages if make check/test has been run
} while (exit_code == EXIT_SUCCESS and --opt_repeat);
}
catch (libtest::fatal& e)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "FATAL:" << e.what() << std::endl;
exit_code= EXIT_FAILURE;
}
catch (libtest::disconnected& e)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "Unhandled disconnection occurred:" << e.what() << std::endl;
exit_code= EXIT_FAILURE;
}
catch (std::exception& e)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "std::exception:" << e.what() << std::endl;
exit_code= EXIT_FAILURE;
}
catch (char const*)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "Exception:" << std::endl;
exit_code= EXIT_FAILURE;
}
catch (...)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "Unknown exception halted execution." << std::endl;
exit_code= EXIT_FAILURE;
}
Out << "END:" << argv[0];
return exit_code;
}
<commit_msg>Remove BEGIN/END<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not 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 <config.h>
#include <libtest/common.h>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fnmatch.h>
#include <iostream>
#include <fstream>
#include <memory>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
using namespace libtest;
static void stats_print(libtest::Framework *frame)
{
if (frame->failed() == 0 and frame->success() == 0)
{
return;
}
Outn();
Out << "Collections\t\t\t\t\t" << frame->total();
Out << "\tFailed\t\t\t\t\t" << frame->failed();
Out << "\tSkipped\t\t\t\t\t" << frame->skipped();
Out << "\tSucceeded\t\t\t\t" << frame->success();
Outn();
Out << "Tests\t\t\t\t\t" << frame->sum_total();
Out << "\tFailed\t\t\t\t" << frame->sum_failed();
Out << "\tSkipped\t\t\t\t" << frame->sum_skipped();
Out << "\tSucceeded\t\t\t" << frame->sum_success();
}
#include <getopt.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
bool opt_massive= false;
unsigned long int opt_repeat= 1; // Run all tests once
bool opt_quiet= false;
std::string collection_to_run;
std::string wildcard;
std::string binary_name;
const char *just_filename= rindex(argv[0], '/');
if (just_filename)
{
just_filename++;
}
else
{
just_filename= argv[0];
}
if (just_filename[0] == 'l' and just_filename[1] == 't' and just_filename[2] == '-')
{
just_filename+= 3;
}
binary_name.append(just_filename);
/*
Valgrind does not currently work reliably, or sometimes at all, on OSX
- Fri Jun 15 11:24:07 EDT 2012
*/
#if defined(TARGET_OS_OSX) && TARGET_OS_OSX
if (valgrind_is_caller())
{
return EXIT_SKIP;
}
#endif
// Options parsing
{
enum long_option_t {
OPT_LIBYATL_VERSION,
OPT_LIBYATL_MATCH_COLLECTION,
OPT_LIBYATL_MASSIVE,
OPT_LIBYATL_QUIET,
OPT_LIBYATL_MATCH_WILDCARD,
OPT_LIBYATL_REPEAT
};
static struct option long_options[]=
{
{ "version", no_argument, NULL, OPT_LIBYATL_VERSION },
{ "quiet", no_argument, NULL, OPT_LIBYATL_QUIET },
{ "repeat", no_argument, NULL, OPT_LIBYATL_REPEAT },
{ "collection", required_argument, NULL, OPT_LIBYATL_MATCH_COLLECTION },
{ "wildcard", required_argument, NULL, OPT_LIBYATL_MATCH_WILDCARD },
{ "massive", no_argument, NULL, OPT_LIBYATL_MASSIVE },
{ 0, 0, 0, 0 }
};
int option_index= 0;
while (1)
{
int option_rv= getopt_long(argc, argv, "", long_options, &option_index);
if (option_rv == -1)
{
break;
}
switch (option_rv)
{
case OPT_LIBYATL_VERSION:
break;
case OPT_LIBYATL_QUIET:
opt_quiet= true;
break;
case OPT_LIBYATL_REPEAT:
opt_repeat= strtoul(optarg, (char **) NULL, 10);
break;
case OPT_LIBYATL_MATCH_COLLECTION:
collection_to_run= optarg;
break;
case OPT_LIBYATL_MATCH_WILDCARD:
wildcard= optarg;
break;
case OPT_LIBYATL_MASSIVE:
opt_massive= true;
break;
case '?':
/* getopt_long already printed an error message. */
Error << "unknown option to getopt_long()";
exit(EXIT_FAILURE);
default:
break;
}
}
}
srandom((unsigned int)time(NULL));
if (bool(getenv("YATL_REPEAT")) and (strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10) > 1))
{
opt_repeat= strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10);
}
if ((bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "0") == 0)) or opt_quiet)
{
opt_quiet= true;
}
else if (getenv("JENKINS_URL"))
{
if (bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "1") == 0))
{ }
else
{
opt_quiet= true;
}
}
if ((bool(getenv("YATL_RUN_MASSIVE_TESTS"))) or opt_massive)
{
opt_massive= true;
}
if (opt_quiet)
{
close(STDOUT_FILENO);
}
if (opt_massive)
{
is_massive(opt_massive);
}
char tmp_directory[1024];
if (getenv("LIBTEST_TMP"))
{
snprintf(tmp_directory, sizeof(tmp_directory), "%s", getenv("LIBTEST_TMP"));
}
else
{
snprintf(tmp_directory, sizeof(tmp_directory), "%s", LIBTEST_TEMP);
}
if (chdir(tmp_directory) == -1)
{
char getcwd_buffer[1024];
char *dir= getcwd(getcwd_buffer, sizeof(getcwd_buffer));
Error << "Unable to chdir() from " << dir << " to " << tmp_directory << " errno:" << strerror(errno);
return EXIT_FAILURE;
}
if (libtest::libtool() == NULL)
{
Error << "Failed to locate libtool";
return EXIT_FAILURE;
}
if (getenv("YATL_COLLECTION_TO_RUN"))
{
if (strlen(getenv("YATL_COLLECTION_TO_RUN")))
{
collection_to_run= getenv("YATL_COLLECTION_TO_RUN");
}
}
if (collection_to_run.compare("none") == 0)
{
return EXIT_SUCCESS;
}
if (collection_to_run.empty() == false)
{
Out << "Only testing " << collection_to_run;
}
int exit_code;
try
{
do
{
exit_code= EXIT_SUCCESS;
fatal_assert(sigignore(SIGPIPE) == 0);
libtest::SignalThread signal;
if (signal.setup() == false)
{
Error << "Failed to setup signals";
return EXIT_FAILURE;
}
std::auto_ptr<libtest::Framework> frame(new libtest::Framework(signal, binary_name, collection_to_run, wildcard));
// Run create(), bail on error.
{
switch (frame->create())
{
case TEST_SUCCESS:
break;
case TEST_SKIPPED:
return EXIT_SKIP;
case TEST_FAILURE:
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "frame->create()" << std::endl;
return EXIT_FAILURE;
}
}
frame->exec();
if (signal.is_shutdown() == false)
{
signal.set_shutdown(SHUTDOWN_GRACEFUL);
}
shutdown_t status= signal.get_shutdown();
if (status == SHUTDOWN_FORCED)
{
Out << "Tests were aborted.";
exit_code= EXIT_FAILURE;
}
else if (frame->failed())
{
Out << "Some test failed.";
exit_code= EXIT_FAILURE;
}
else if (frame->skipped() and frame->failed() and frame->success())
{
Out << "Some tests were skipped.";
}
else if (frame->success() and (frame->failed() == 0))
{
Out;
Out << "All tests completed successfully.";
}
stats_print(frame.get());
std::ofstream xml_file;
std::string file_name;
file_name.append(tmp_directory);
file_name.append(frame->name());
file_name.append(".xml");
xml_file.open(file_name.c_str(), std::ios::trunc);
libtest::Formatter::xml(*frame, xml_file);
Outn(); // Generate a blank to break up the messages if make check/test has been run
} while (exit_code == EXIT_SUCCESS and --opt_repeat);
}
catch (libtest::fatal& e)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "FATAL:" << e.what() << std::endl;
exit_code= EXIT_FAILURE;
}
catch (libtest::disconnected& e)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "Unhandled disconnection occurred:" << e.what() << std::endl;
exit_code= EXIT_FAILURE;
}
catch (std::exception& e)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "std::exception:" << e.what() << std::endl;
exit_code= EXIT_FAILURE;
}
catch (char const*)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "Exception:" << std::endl;
exit_code= EXIT_FAILURE;
}
catch (...)
{
std::cerr << __FILE__ << ":" << __LINE__ << ": " << "Unknown exception halted execution." << std::endl;
exit_code= EXIT_FAILURE;
}
return exit_code;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#define MAX 10004
using namespace std;
int rick[MAX],morty[MAX];
int main(int argc, char const *argv[]) {
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++){
int x;
cin>>x;
bool flg=0;
for(int j=0;j<x;j++){
int a;
cin>>a;
int b=(a*(-1));
if(a<0){
rick[b]=i;
if(rick[b]==morty[b]){
// cout<<"NO";
flg=1;
}
}
else{
morty[a]=i;
if(rick[a]==morty[a]){
// cout<<"NO";
flg=1;
}
}
}
if(flg==0) {cout<<"YES";return 0;}
}
cout<<"NO";
return 0;
}
<commit_msg>adding<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#define MAX 10004
using namespace std;
int rick[MAX],morty[MAX];
int main(int argc, char const *argv[]) {
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++){
int x;
cin>>x;
bool flg=0;
for(int j=0;j<x;j++){
int a;
cin>>a;
int b=(a*(-1));
if(a<0){
rick[b]=i;
if(rick[b]==morty[b]){
// cout<<"NO";
flg=1;
}
}
else{
morty[a]=i;
if(rick[a]==morty[a]){
// cout<<"NO";
flg=1;
}
}
}
if(flg==0) {cout<<"YES";return 0;}
}
cout<<"NO";
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>make output directory separately<commit_after><|endoftext|>
|
<commit_before>/* __ __ *\
** __ /_// / ___ lila API **
** / / __ / / / _ | (c) 2016, Christian Krause **
** / /__ / // /__/ __ | **
** /____//_//____/_/ | | **
\* |/ */
#include <fstream>
#include <iostream>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include "codegen.hpp"
#include "parser.hpp"
using namespace lila::codegen;
using namespace lila::parser;
int main(int argc, char** argv) {
// ---------------------------------------------------------------------------
// read code and tokenize it
// ---------------------------------------------------------------------------
vector<unique_ptr<Token>> tokens;
if (argc == 1) {
tokenize(&cin, &tokens);
} else {
char * filename = argv[1];
ifstream is(filename);
if (is) {
tokenize(&is, &tokens);
is.close();
} else {
fprintf(stderr, "error opening file\n");
return 1;
}
}
for (auto it = tokens.begin() ; it != tokens.end(); ++it) {
Token * token = it->get();
cerr << "[debug] [token] \"" << token->toString().c_str() << "\"" << endl;
}
// ---------------------------------------------------------------------------
// parse the tokens to AST
// ---------------------------------------------------------------------------
Parser parser(&tokens);
unique_ptr<ASTNode> ast;
try {
ast = parser.parse();
} catch (const char * msg) {
cerr << msg << endl;
return 1;
}
cerr << "[debug] [ast] " << ast->toString() << endl;
// ---------------------------------------------------------------------------
// generate LLVM IR code
// ---------------------------------------------------------------------------
CodeGen codegen("lilamodule", llvm::getGlobalContext());
codegen.generateCode(move(ast));
// ---------------------------------------------------------------------------
// write LLVM IR code
// ---------------------------------------------------------------------------
std::error_code ec;
llvm::raw_fd_ostream out("anonymous.bc", ec, llvm::sys::fs::F_None);
if (0 != ec.value()) {
cerr << "error: " << ec.message() << endl;
return ec.value();
}
llvm::WriteBitcodeToFile(codegen.module.get(), out);
// ---------------------------------------------------------------------------
// end
// ---------------------------------------------------------------------------
return 0;
}
<commit_msg>parse cli options for help verbose input output<commit_after>/* __ __ *\
** __ /_// / ___ lila API **
** / / __ / / / _ | (c) 2016, Christian Krause **
** / /__ / // /__/ __ | **
** /____//_//____/_/ | | **
\* |/ */
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Bitcode/ReaderWriter.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "codegen.hpp"
#include "parser.hpp"
using namespace lila::codegen;
using namespace lila::parser;
int main(int argc, char** argv) {
const char *input = "-";
const char *output = "a.out.bc";
bool verbose = false;
// ---------------------------------------------------------------------------
// parse command line options
// ---------------------------------------------------------------------------
char usage [1024];
snprintf(usage,
1024,
"%s\n"
"\n"
"usage: lilac [OPTIONS] INPUT\n"
"\n"
"options:\n"
" -o FILENAME write output to FILENAME\n"
" if omitted, writes to %s\n"
" -v verbose output\n"
" INPUT read source code from INPUT\n"
" if omitted or %s, reads from STDIN\n"
"\n",
PACKAGE_STRING,
output,
input
);
int c;
while ((c = getopt (argc, argv, "ho:v")) != -1)
switch (c) {
case 'h':
cout << usage;
return 0;
case 'o':
output = optarg;
break;
case 'v':
verbose = true;
break;
default:
cerr << usage;
return 1;
}
if (optind < argc) {
input = argv[optind];
}
// ---------------------------------------------------------------------------
// read code and tokenize it
// ---------------------------------------------------------------------------
vector<unique_ptr<Token>> tokens;
if (strcmp(input, "-") == 0) {
tokenize(&cin, &tokens);
} else {
ifstream is(input);
if (is) {
tokenize(&is, &tokens);
is.close();
} else {
cerr << "error opening file: " << input << endl;
return 1;
}
}
if (verbose)
for (auto it = tokens.begin() ; it != tokens.end(); ++it) {
Token * token = it->get();
cerr << "[debug] [token] \"" << token->toString().c_str() << "\"" << endl;
}
// ---------------------------------------------------------------------------
// parse the tokens to AST
// ---------------------------------------------------------------------------
Parser parser(&tokens);
unique_ptr<ASTNode> ast;
try {
ast = parser.parse();
} catch (const char * msg) {
cerr << msg << endl;
return 1;
}
if (verbose)
cerr << "[debug] [ast] " << ast->toString() << endl;
// ---------------------------------------------------------------------------
// generate LLVM IR code
// ---------------------------------------------------------------------------
CodeGen codegen("lilamodule", llvm::getGlobalContext());
codegen.generateCode(move(ast));
// ---------------------------------------------------------------------------
// write LLVM IR code
// ---------------------------------------------------------------------------
std::error_code ec;
llvm::raw_fd_ostream out(output, ec, llvm::sys::fs::F_None);
if (0 != ec.value()) {
cerr << "error: " << ec.message() << endl;
return ec.value();
}
llvm::WriteBitcodeToFile(codegen.module.get(), out);
// ---------------------------------------------------------------------------
// end
// ---------------------------------------------------------------------------
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012, Prevas A/S
* 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 Prevas A/S 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.
*/
/**
*
*
* \author Morten Kjaergaard
*/
#pragma once
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/signal.hpp>
#include <darc/id.hpp>
#include <darc/distributed_container/container_base.hpp>
#include <darc/distributed_container/container_manager.hpp>
#include <darc/distributed_container/control_packet.hpp>
#include <darc/distributed_container/header_packet.hpp>
#include <darc/distributed_container/control_packet.hpp>
#include <darc/distributed_container/update_packet.hpp>
#include <darc/inbound_data.hpp>
#include <darc/outbound_data.hpp>
#include <darc/serializer/boost.hpp>
#include <beam/static_scope.hpp>
#include <darc/id_arg.hpp>
namespace boost
{
namespace serialization
{
template<class Archive, class Key, class T>
void serialize(Archive & ar, std::pair<Key, T>& set, const unsigned int version)
{
ar & set.first;
ar & set.second;
}
}
}
namespace darc
{
namespace distributed_container
{
template<typename Key, typename T>
class shared_set;
template<typename Key, typename T>
class connection
{
public:
typedef std::pair<ID/*origin*/, T> entry_type;
typedef std::map<Key, entry_type> list_type;
protected:
typedef std::pair<Key, entry_type> transfer_type;
ID remote_location_id_; // location we are connected to
ID remote_instance_id_; // instance we are connected to
container_manager * manager_;
shared_set<Key, T> * parent_;
uint32_t last_sent_index_;
uint32_t last_received_index_;
list_type list_;
public:
connection(container_manager * manager,
shared_set<Key, T> * parent,
const ID& remote_location_id,
const ID& remote_instance_id) :
remote_location_id_(remote_location_id),
remote_instance_id_(remote_instance_id),
manager_(manager),
parent_(parent),
last_sent_index_(0),
last_received_index_(0)
{
}
void do_connect()
{
control_packet ctrl;
ctrl.command = control_packet::connect;
outbound_data<serializer::boost_serializer, control_packet> o_ctrl(ctrl);
manager_->send_to_location(
parent_->id(),
remote_location_id_,
remote_instance_id_,
header_packet::control,
o_ctrl);
}
// called when we have a new map entry to send to remote
void increment(const ID& informer, // where we got the info from
const Key& key,
const ID& origin,
const T& value,
uint32_t state_index)
{
entry_type entry(origin, value);
last_sent_index_ = state_index;
if(informer != remote_instance_id_) // dont send to informer
{
update_packet update;
update.start_index = state_index;
update.end_index = state_index;
update.type = update_packet::partial;
update.num_entries = 1;
outbound_data<serializer::boost_serializer, update_packet> o_update(update);
transfer_type item(key, entry);
outbound_data<serializer::boost_serializer, transfer_type> o_item(item);
outbound_pair o_data(o_update, o_item);
manager_->send_to_location(parent_->id(),
remote_location_id_,
remote_instance_id_,
header_packet::update,
o_data);
}
}
void handle_update(const header_packet& header,
const update_packet& update,
buffer::shared_buffer data);
void full_update(typename list_type::iterator begin,
typename list_type::iterator end,
uint32_t state_index)
{
if(begin != end)
{
update_packet update;
update.start_index = 0;
update.end_index = state_index;
update.type = update_packet::complete;
update.num_entries = 0;
// todo: smarter iterator count
for(typename list_type::iterator it = begin;
it != end;
it++)
{
++update.num_entries;
}
outbound_data<serializer::boost_serializer, update_packet> o_update(update);
outbound_list<serializer::boost_serializer, typename list_type::iterator> o_item(begin, end);
outbound_pair o_data(o_update, o_item);
manager_->send_to_location(parent_->id(),
remote_location_id_,
remote_instance_id_,
header_packet::update,
o_data);
}
last_sent_index_ = 0;
}
};
template<typename Key, typename T>
class shared_set : public container_base, public beam::static_scope<beam::Info>
{
friend class connection<Key, T>;
protected:
typedef connection<Key, T> connection_type;
public:
typedef typename connection_type::entry_type entry_type;
typedef typename connection_type::list_type list_type;
typedef typename list_type::iterator iterator;
boost::signal<void(const ID&, const ID&, const Key&, const T&)> signal_;
protected:
typedef boost::shared_ptr<connection_type> connection_ptr;
typedef std::map</*informer*/ID, connection_ptr> connection_list_type;
connection_list_type connection_list_;
list_type list_;
uint32_t state_index_;
public:
shared_set() :
state_index_(0)
{
}
iterator begin()
{
return list_.begin();
}
iterator end()
{
return list_.end();
}
const list_type& list() const
{
return list_;
}
list_type& list()
{
return list_;
}
void insert(const Key& key, const T& value)
{
remote_insert(id(), key, id(), value);
}
void connect(const ID& remote_location_id,
const ID& remote_instance_id)
{
assert(connection_list_.find(remote_instance_id) == connection_list_.end());
connection_ptr c = boost::make_shared<connection_type >(
manager_,
this,
remote_location_id,
remote_instance_id);
connection_list_.insert(
typename connection_list_type::value_type(remote_instance_id, c));
c->do_connect();
full_update(remote_instance_id);
}
protected:
void remote_insert(const ID& informer, //informer
const Key& key, // Key
const ID& origin, // origin
const T& value) // entry
{
slog<beam::Trace>("remote_insert",
"key", beam::arg<Key>(key),
"value", beam::arg<T>(value));
entry_type entry(origin, value);
list_.insert(
typename list_type::value_type(key, entry));
state_index_++;
signal_(id(), origin, key, value);
// do it in flush instead
for(typename connection_list_type::iterator it = connection_list_.begin();
it != connection_list_.end();
it++)
{
it->second->increment(informer, key, origin, value, state_index_);
}
}
void full_update(const ID& remote_instance_id)
{
typename connection_list_type::iterator item = connection_list_.find(remote_instance_id);
assert(item != connection_list_.end());
item->second->full_update(list_.begin(),
list_.end(),
state_index_);
}
void recv(const ID& src_location_id, const header_packet& hdr, darc::buffer::shared_buffer data)
{
switch(hdr.payload_type)
{
case header_packet::control:
{
inbound_data<serializer::boost_serializer, control_packet> i_control(data);
handle_ctrl(src_location_id, hdr, i_control.get());
}
break;
case header_packet::update:
{
inbound_data<serializer::boost_serializer, update_packet> i_update(data);
handle_update(src_location_id, hdr, i_update.get(), data);
}
break;
default:
{
assert(false);
}
}
}
void handle_ctrl(const ID& src_location_id, const header_packet& header, const control_packet& ctrl)
{
assert(ctrl.command == control_packet::connect);
assert(connection_list_.find(header.src_instance_id) == connection_list_.end());
connection_ptr c = boost::make_shared<connection_type>(
manager_,
this,
src_location_id,
header.src_instance_id);
connection_list_.insert(
typename connection_list_type::value_type(header.src_instance_id, c));
full_update(header.src_instance_id);
}
void handle_update(const ID& src_location_id,
const header_packet& header,
const update_packet& update,
darc::buffer::shared_buffer data)
{
typename connection_list_type::iterator item = connection_list_.find(header.src_instance_id);
assert(item != connection_list_.end());
item->second->handle_update(header, update, data);
}
};
// Connection impl
template<typename Key, typename T>
void connection<Key, T>::handle_update(const header_packet& header,
const update_packet& update,
buffer::shared_buffer data)
{
if(update.type == update_packet::complete)
{
// todo: handle more intelligent since this might cause duplicate callbacks
list_.clear();
}
else if(update.start_index != last_received_index_ + 1)
{
// todo: request full update
assert(false);
}
last_received_index_ = update.end_index;
for(size_t i = 0; i < update.num_entries; i++)
{
inbound_data<serializer::boost_serializer, transfer_type> i_item(data);
typename list_type::value_type value(i_item.get().first, i_item.get().second);
list_.insert(value);
parent_->remote_insert(remote_instance_id_, //informer
value.first, // Key
value.second.first, // origin
value.second.second); // entry
}
}
}
}
<commit_msg>added get_peer_id method<commit_after>/*
* Copyright (c) 2012, Prevas A/S
* 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 Prevas A/S 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.
*/
/**
*
*
* \author Morten Kjaergaard
*/
#pragma once
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/signal.hpp>
#include <darc/id.hpp>
#include <darc/distributed_container/container_base.hpp>
#include <darc/distributed_container/container_manager.hpp>
#include <darc/distributed_container/control_packet.hpp>
#include <darc/distributed_container/header_packet.hpp>
#include <darc/distributed_container/control_packet.hpp>
#include <darc/distributed_container/update_packet.hpp>
#include <darc/inbound_data.hpp>
#include <darc/outbound_data.hpp>
#include <darc/serializer/boost.hpp>
#include <beam/static_scope.hpp>
#include <darc/id_arg.hpp>
namespace boost
{
namespace serialization
{
template<class Archive, class Key, class T>
void serialize(Archive & ar, std::pair<Key, T>& set, const unsigned int version)
{
ar & set.first;
ar & set.second;
}
}
}
namespace darc
{
namespace distributed_container
{
template<typename Key, typename T>
class shared_set;
template<typename Key, typename T>
class connection
{
public:
typedef std::pair<ID/*origin*/, T> entry_type;
typedef std::map<Key, entry_type> list_type;
protected:
typedef std::pair<Key, entry_type> transfer_type;
ID remote_location_id_; // location we are connected to
ID remote_instance_id_; // instance we are connected to
container_manager * manager_;
shared_set<Key, T> * parent_;
uint32_t last_sent_index_;
uint32_t last_received_index_;
list_type list_;
public:
connection(container_manager * manager,
shared_set<Key, T> * parent,
const ID& remote_location_id,
const ID& remote_instance_id) :
remote_location_id_(remote_location_id),
remote_instance_id_(remote_instance_id),
manager_(manager),
parent_(parent),
last_sent_index_(0),
last_received_index_(0)
{
}
void do_connect()
{
control_packet ctrl;
ctrl.command = control_packet::connect;
outbound_data<serializer::boost_serializer, control_packet> o_ctrl(ctrl);
manager_->send_to_location(
parent_->id(),
remote_location_id_,
remote_instance_id_,
header_packet::control,
o_ctrl);
}
// called when we have a new map entry to send to remote
void increment(const ID& informer, // where we got the info from
const Key& key,
const ID& origin,
const T& value,
uint32_t state_index)
{
entry_type entry(origin, value);
last_sent_index_ = state_index;
if(informer != remote_instance_id_) // dont send to informer
{
update_packet update;
update.start_index = state_index;
update.end_index = state_index;
update.type = update_packet::partial;
update.num_entries = 1;
outbound_data<serializer::boost_serializer, update_packet> o_update(update);
transfer_type item(key, entry);
outbound_data<serializer::boost_serializer, transfer_type> o_item(item);
outbound_pair o_data(o_update, o_item);
manager_->send_to_location(parent_->id(),
remote_location_id_,
remote_instance_id_,
header_packet::update,
o_data);
}
}
void handle_update(const header_packet& header,
const update_packet& update,
buffer::shared_buffer data);
void full_update(typename list_type::iterator begin,
typename list_type::iterator end,
uint32_t state_index)
{
if(begin != end)
{
update_packet update;
update.start_index = 0;
update.end_index = state_index;
update.type = update_packet::complete;
update.num_entries = 0;
// todo: smarter iterator count
for(typename list_type::iterator it = begin;
it != end;
it++)
{
++update.num_entries;
}
outbound_data<serializer::boost_serializer, update_packet> o_update(update);
outbound_list<serializer::boost_serializer, typename list_type::iterator> o_item(begin, end);
outbound_pair o_data(o_update, o_item);
manager_->send_to_location(parent_->id(),
remote_location_id_,
remote_instance_id_,
header_packet::update,
o_data);
}
last_sent_index_ = 0;
}
const ID& peer_id()
{
return remote_location_id_;
}
};
template<typename Key, typename T>
class shared_set : public container_base, public beam::static_scope<beam::Info>
{
friend class connection<Key, T>;
protected:
typedef connection<Key, T> connection_type;
public:
typedef typename connection_type::entry_type entry_type;
typedef typename connection_type::list_type list_type;
typedef typename list_type::iterator iterator;
boost::signal<void(const ID&, const ID&, const Key&, const T&)> signal_;
protected:
typedef boost::shared_ptr<connection_type> connection_ptr;
typedef std::map</*informer*/ID, connection_ptr> connection_list_type;
connection_list_type connection_list_;
list_type list_;
uint32_t state_index_;
public:
shared_set() :
state_index_(0)
{
}
iterator begin()
{
return list_.begin();
}
iterator end()
{
return list_.end();
}
const list_type& list() const
{
return list_;
}
list_type& list()
{
return list_;
}
void insert(const Key& key, const T& value)
{
remote_insert(id(), key, id(), value);
}
void connect(const ID& remote_location_id,
const ID& remote_instance_id)
{
assert(connection_list_.find(remote_instance_id) == connection_list_.end());
connection_ptr c = boost::make_shared<connection_type >(
manager_,
this,
remote_location_id,
remote_instance_id);
connection_list_.insert(
typename connection_list_type::value_type(remote_instance_id, c));
c->do_connect();
full_update(remote_instance_id);
}
const ID& get_peer_id(const ID& instance_id)
{
typename connection_list_type::iterator item = connection_list_.find(instance_id);
assert(item != connection_list_.end());
return item->second->peer_id();
}
protected:
void remote_insert(const ID& informer, //informer
const Key& key, // Key
const ID& origin, // origin
const T& value) // entry
{
slog<beam::Trace>("remote_insert",
"key", beam::arg<Key>(key),
"value", beam::arg<T>(value));
entry_type entry(origin, value);
list_.insert(
typename list_type::value_type(key, entry));
state_index_++;
signal_(id(), origin, key, value);
// do it in flush instead
for(typename connection_list_type::iterator it = connection_list_.begin();
it != connection_list_.end();
it++)
{
it->second->increment(informer, key, origin, value, state_index_);
}
}
void full_update(const ID& remote_instance_id)
{
typename connection_list_type::iterator item = connection_list_.find(remote_instance_id);
assert(item != connection_list_.end());
item->second->full_update(list_.begin(),
list_.end(),
state_index_);
}
void recv(const ID& src_location_id, const header_packet& hdr, darc::buffer::shared_buffer data)
{
switch(hdr.payload_type)
{
case header_packet::control:
{
inbound_data<serializer::boost_serializer, control_packet> i_control(data);
handle_ctrl(src_location_id, hdr, i_control.get());
}
break;
case header_packet::update:
{
inbound_data<serializer::boost_serializer, update_packet> i_update(data);
handle_update(src_location_id, hdr, i_update.get(), data);
}
break;
default:
{
assert(false);
}
}
}
void handle_ctrl(const ID& src_location_id, const header_packet& header, const control_packet& ctrl)
{
assert(ctrl.command == control_packet::connect);
assert(connection_list_.find(header.src_instance_id) == connection_list_.end());
connection_ptr c = boost::make_shared<connection_type>(
manager_,
this,
src_location_id,
header.src_instance_id);
connection_list_.insert(
typename connection_list_type::value_type(header.src_instance_id, c));
full_update(header.src_instance_id);
}
void handle_update(const ID& src_location_id,
const header_packet& header,
const update_packet& update,
darc::buffer::shared_buffer data)
{
typename connection_list_type::iterator item = connection_list_.find(header.src_instance_id);
assert(item != connection_list_.end());
item->second->handle_update(header, update, data);
}
};
// Connection impl
template<typename Key, typename T>
void connection<Key, T>::handle_update(const header_packet& header,
const update_packet& update,
buffer::shared_buffer data)
{
if(update.type == update_packet::complete)
{
// todo: handle more intelligent since this might cause duplicate callbacks
list_.clear();
}
else if(update.start_index != last_received_index_ + 1)
{
// todo: request full update
assert(false);
}
last_received_index_ = update.end_index;
for(size_t i = 0; i < update.num_entries; i++)
{
inbound_data<serializer::boost_serializer, transfer_type> i_item(data);
typename list_type::value_type value(i_item.get().first, i_item.get().second);
list_.insert(value);
parent_->remote_insert(remote_instance_id_, //informer
value.first, // Key
value.second.first, // origin
value.second.second); // entry
}
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xmllib_export.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ab $ $Date: 2001-11-07 18:21:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <xmlscript/xmllib_imexp.hxx>
#include <xmlscript/xml_helper.hxx>
using namespace com::sun::star::uno;
using namespace com::sun::star;
using namespace rtl;
namespace xmlscript
{
static OUString aTrueStr ( RTL_CONSTASCII_USTRINGPARAM("true") );
static OUString aFalseStr( RTL_CONSTASCII_USTRINGPARAM("false") );
//##################################################################################################
//==================================================================================================
SAL_DLLEXPORT void
SAL_CALL exportLibraryContainer(
Reference< xml::sax::XExtendedDocumentHandler > const & xOut,
const LibDescriptorArray* pLibArray )
SAL_THROW( (Exception) )
{
xOut->startDocument();
OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
"<!DOCTYPE library:libraries PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\""
" \"libraries.dtd\">" ) );
xOut->unknown( aDocTypeStr );
xOut->ignorableWhitespace( OUString() );
OUString aLibrariesName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":libraries") );
XMLElement* pLibsElement = new XMLElement( aLibrariesName );
Reference< xml::sax::XAttributeList > xAttributes( pLibsElement );
pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ),
OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );
pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_XLINK_PREFIX) ),
OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_URI) ) );
xOut->ignorableWhitespace( OUString() );
xOut->startElement( aLibrariesName, xAttributes );
int nLibCount = pLibArray->mnLibCount;
for( sal_Int32 i = 0 ; i < nLibCount ; i++ )
{
LibDescriptor& rLib = pLibArray->mpLibs[i];
OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") );
XMLElement* pLibElement = new XMLElement( aLibraryName );
Reference< xml::sax::XAttributeList > xLibElementAttribs;
xLibElementAttribs = static_cast< xml::sax::XAttributeList* >( pLibElement );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
rLib.aName );
if( rLib.aStorageURL.getLength() )
{
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":href") ),
rLib.aStorageURL );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":type") ),
OUString( RTL_CONSTASCII_USTRINGPARAM("simple") ) );
}
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":link") ),
rLib.bLink ? aTrueStr : aFalseStr );
pLibElement->dump( xOut );
}
xOut->ignorableWhitespace( OUString() );
xOut->endElement( aLibrariesName );
xOut->endDocument();
}
//==================================================================================================
SAL_DLLEXPORT void
SAL_CALL exportLibrary(
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XExtendedDocumentHandler > const & xOut,
const LibDescriptor& rLib )
SAL_THROW( (::com::sun::star::uno::Exception) )
{
xOut->startDocument();
OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
"<!DOCTYPE library:library PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\""
" \"library.dtd\">" ) );
xOut->unknown( aDocTypeStr );
xOut->ignorableWhitespace( OUString() );
OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") );
XMLElement* pLibElement = new XMLElement( aLibraryName );
Reference< xml::sax::XAttributeList > xAttributes( pLibElement );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ),
OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
rLib.aName );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ),
rLib.bReadOnly ? aTrueStr : aFalseStr );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":passwordprotected") ),
rLib.bPasswordProtected ? aTrueStr : aFalseStr );
sal_Int32 nElementCount = rLib.aElementNames.getLength();
if( nElementCount )
{
const OUString* pElementNames = rLib.aElementNames.getConstArray();
for( sal_Int32 i = 0 ; i < nElementCount ; i++ )
{
XMLElement* pElement = new XMLElement( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":element" ) ) );
Reference< xml::sax::XAttributeList > xElementAttribs;
xElementAttribs = static_cast< xml::sax::XAttributeList* >( pElement );
pElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
pElementNames[i] );
pLibElement->addSubElement( pElement );
}
}
pLibElement->dump( xOut );
xOut->endDocument();
}
};
<commit_msg>#86383# readonly flag for library links<commit_after>/*************************************************************************
*
* $RCSfile: xmllib_export.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ab $ $Date: 2001-12-14 12:12:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <xmlscript/xmllib_imexp.hxx>
#include <xmlscript/xml_helper.hxx>
using namespace com::sun::star::uno;
using namespace com::sun::star;
using namespace rtl;
namespace xmlscript
{
static OUString aTrueStr ( RTL_CONSTASCII_USTRINGPARAM("true") );
static OUString aFalseStr( RTL_CONSTASCII_USTRINGPARAM("false") );
//##################################################################################################
//==================================================================================================
SAL_DLLEXPORT void
SAL_CALL exportLibraryContainer(
Reference< xml::sax::XExtendedDocumentHandler > const & xOut,
const LibDescriptorArray* pLibArray )
SAL_THROW( (Exception) )
{
xOut->startDocument();
OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
"<!DOCTYPE library:libraries PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\""
" \"libraries.dtd\">" ) );
xOut->unknown( aDocTypeStr );
xOut->ignorableWhitespace( OUString() );
OUString aLibrariesName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":libraries") );
XMLElement* pLibsElement = new XMLElement( aLibrariesName );
Reference< xml::sax::XAttributeList > xAttributes( pLibsElement );
pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ),
OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );
pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_XLINK_PREFIX) ),
OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_URI) ) );
xOut->ignorableWhitespace( OUString() );
xOut->startElement( aLibrariesName, xAttributes );
int nLibCount = pLibArray->mnLibCount;
for( sal_Int32 i = 0 ; i < nLibCount ; i++ )
{
LibDescriptor& rLib = pLibArray->mpLibs[i];
OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") );
XMLElement* pLibElement = new XMLElement( aLibraryName );
Reference< xml::sax::XAttributeList > xLibElementAttribs;
xLibElementAttribs = static_cast< xml::sax::XAttributeList* >( pLibElement );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
rLib.aName );
if( rLib.aStorageURL.getLength() )
{
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":href") ),
rLib.aStorageURL );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":type") ),
OUString( RTL_CONSTASCII_USTRINGPARAM("simple") ) );
}
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":link") ),
rLib.bLink ? aTrueStr : aFalseStr );
if( rLib.bLink )
{
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ),
rLib.bReadOnly ? aTrueStr : aFalseStr );
}
pLibElement->dump( xOut );
}
xOut->ignorableWhitespace( OUString() );
xOut->endElement( aLibrariesName );
xOut->endDocument();
}
//==================================================================================================
SAL_DLLEXPORT void
SAL_CALL exportLibrary(
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XExtendedDocumentHandler > const & xOut,
const LibDescriptor& rLib )
SAL_THROW( (::com::sun::star::uno::Exception) )
{
xOut->startDocument();
OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
"<!DOCTYPE library:library PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\""
" \"library.dtd\">" ) );
xOut->unknown( aDocTypeStr );
xOut->ignorableWhitespace( OUString() );
OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") );
XMLElement* pLibElement = new XMLElement( aLibraryName );
Reference< xml::sax::XAttributeList > xAttributes( pLibElement );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ),
OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
rLib.aName );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ),
rLib.bReadOnly ? aTrueStr : aFalseStr );
pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":passwordprotected") ),
rLib.bPasswordProtected ? aTrueStr : aFalseStr );
sal_Int32 nElementCount = rLib.aElementNames.getLength();
if( nElementCount )
{
const OUString* pElementNames = rLib.aElementNames.getConstArray();
for( sal_Int32 i = 0 ; i < nElementCount ; i++ )
{
XMLElement* pElement = new XMLElement( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":element" ) ) );
Reference< xml::sax::XAttributeList > xElementAttribs;
xElementAttribs = static_cast< xml::sax::XAttributeList* >( pElement );
pElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
pElementNames[i] );
pLibElement->addSubElement( pElement );
}
}
pLibElement->dump( xOut );
xOut->endDocument();
}
};
<|endoftext|>
|
<commit_before>#include "util.cpp"
void placeServers(Input &input) {
//fill me
}
<commit_msg>placeservers temporary result<commit_after>#include "util.cpp"
/*
//util classes
struct Server {
//input
int capacity, size;
//output
int row = -1, slot = -1, pool = -1;
};
struct Input {
int r, s, u, p, m;
vector<vector<int>> blocked_slots;//first index: row, second index: slot
vector<Server> servers;
};
*/
struct Row {
int num, area, capacity;
};
bool sort_servers(const Server &a, const Server &b) {
if (a.capacity*b.size != b.capacity*a.size)
return a.capacity*b.size > b.capacity*a.size;
else
return a.size < b.size;
}
bool sort_rows(const Row &a, const Row &b) {
if (a.capacity*b.area != b.capacity*a.area)
return a.capacity*b.area > b.capacity*a.area;
else
return a.area < b.area;
}
void place_blocked_slots(vector<vector<int>>& field, int row_index, vector<int>& slots) {
for (int i = 0; i < slots.size(); i++)
{
field[row_index][slots[i]] = 1;
row[row_index].area--;
}
}
void assign_server_to_row(Server &s, int row_index) {
}
void placeServers(Input &input) {
sort(input.servers.begin(),input.servers.end(),sort_servers);
for (int i = 0; i < input.r; i++)
{
rows[i].num = i;
rows[i].area = input.s;
place_blocked_slots(i,input.blocked_slots[i]);
}
// iterate through all servers
for (int i = 0; i < input.m; i++)
{
sort(rows,rows+input.r,sort_rows);
// try to assign each server to worst possible row
for (int j = 0; j < input.r; j++)
{
if (assign_server_to_row(input.servers[i],j))
{
rows[j].area -= input.servers[i].size;
rows[j].capacity += input.servers[i].capacity;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
mvxxx 2017
https://github.com/mvxxx
*/
#pragma once
#include <SFML/System/Vector2.hpp>
class Math
{
/* ===Objects=== */
public:
protected:
private:
/* ===Methods=== */
public:
static sf::Vector2i convertToUnitPosition( const sf::Vector2f& pxPos, const sf::Vector2f& cellDim )
{
return sf::Vector2i( pxPos.x / cellDim.x, pxPos.y / cellDim.y );
}
protected:
private:
};<commit_msg>Mouse pos computing in Math.hpp<commit_after>/*
mvxxx 2017
https://github.com/mvxxx
*/
#pragma once
#include <SFML/System/Vector2.hpp>
#include <SFML/Window/Mouse.hpp>
#include "scene/Scene.hpp"
class Math
{
/* ===Objects=== */
public:
protected:
private:
/* ===Methods=== */
public:
static sf::Vector2i convertToUnitPosition( const sf::Vector2f& pxPos, const sf::Vector2f& cellDim )
{
return sf::Vector2i( pxPos.x / cellDim.x, pxPos.y / cellDim.y );
}
static sf::Vector2f mouseWorldPosition( std::shared_ptr<Scene> scene )
{
return scene->getWindow()->mapPixelToCoords( sf::Mouse::getPosition( *scene->getWindow() ) );
}
protected:
private:
};
<|endoftext|>
|
<commit_before>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#include "hadesmem/module.hpp"
#include <utility>
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <boost/scope_exit.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/detail/smart_handle.hpp"
#include "hadesmem/detail/to_upper_ordinal.hpp"
namespace hadesmem
{
namespace
{
FARPROC FindProcedureInternal(Module const& module, LPCSTR name)
{
BOOST_ASSERT(name != nullptr);
// Do not continue if Shim Engine is enabled for local process,
// otherwise it could interfere with the address resolution.
// TODO: Work around this with 'manual' export lookup or similar.
HMODULE const shim_eng_mod = ::GetModuleHandle(L"ShimEng.dll");
if (shim_eng_mod)
{
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("Shims enabled for local process."));
}
HMODULE const local_module = ::LoadLibraryEx(module.GetPath().c_str(),
nullptr, DONT_RESOLVE_DLL_REFERENCES);
if (!local_module)
{
DWORD const last_error = ::GetLastError();
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("LoadLibraryEx failed.") <<
ErrorCodeWinLast(last_error));
}
BOOST_SCOPE_EXIT_ALL(&)
{
BOOST_VERIFY(::FreeLibrary(local_module));
};
FARPROC const local_func = ::GetProcAddress(local_module, name);
if (!local_func)
{
DWORD const last_error = ::GetLastError();
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("GetProcAddress failed.") <<
ErrorCodeWinLast(last_error));
}
auto const func_delta = reinterpret_cast<DWORD_PTR>(local_func) -
reinterpret_cast<DWORD_PTR>(local_module);
auto const remote_func = reinterpret_cast<FARPROC>(
reinterpret_cast<DWORD_PTR>(module.GetHandle()) + func_delta);
return remote_func;
}
}
struct Module::Impl
{
explicit Impl(Process const& process, HMODULE handle)
: process_(&process),
handle_(nullptr),
size_(0),
name_(),
path_()
{
Initialize(handle);
}
explicit Impl(Process const& process, std::wstring const& path)
: process_(&process),
handle_(nullptr),
size_(0),
name_(),
path_()
{
Initialize(path);
}
explicit Impl(Process const& process, MODULEENTRY32 const& entry)
: process_(&process),
handle_(nullptr),
size_(0),
name_(),
path_()
{
Initialize(entry);
}
void Initialize(HMODULE handle)
{
auto handle_check =
[&] (MODULEENTRY32 const& entry) -> bool
{
if (entry.hModule == handle || !handle)
{
return true;
}
return false;
};
InitializeIf(handle_check);
}
void Initialize(std::wstring const& path)
{
bool const is_path = (path.find(L'\\') != std::wstring::npos) ||
(path.find(L'/') != std::wstring::npos);
std::wstring const path_upper = detail::ToUpperOrdinal(path);
auto path_check =
[&] (MODULEENTRY32 const& entry) -> bool
{
if (is_path)
{
if (boost::filesystem::equivalent(path, entry.szExePath))
{
return true;
}
}
else
{
if (path_upper == detail::ToUpperOrdinal(entry.szModule))
{
return true;
}
}
return false;
};
InitializeIf(path_check);
}
void Initialize(MODULEENTRY32 const& entry)
{
handle_ = entry.hModule;
size_ = entry.modBaseSize;
name_ = entry.szModule;
path_ = entry.szExePath;
}
typedef std::function<bool (MODULEENTRY32 const&)> EntryCallback;
void InitializeIf(EntryCallback const& check_func)
{
detail::SmartHandle snap(::CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE, process_->GetId()), INVALID_HANDLE_VALUE);
if (!snap.IsValid())
{
if (GetLastError() == ERROR_BAD_LENGTH)
{
snap = ::CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE, process_->GetId());
if (!snap.IsValid())
{
DWORD const last_error = ::GetLastError();
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
}
else
{
DWORD const last_error = ::GetLastError();
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
}
MODULEENTRY32 entry;
::ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
for (BOOL more_mods = ::Module32First(snap.GetHandle(), &entry); more_mods;
more_mods = ::Module32Next(snap.GetHandle(), &entry))
{
if (check_func(entry))
{
Initialize(entry);
return;
}
}
DWORD const last_error = ::GetLastError();
if (last_error == ERROR_NO_MORE_FILES)
{
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("Could not find module.") <<
ErrorCodeWinLast(last_error));
}
else
{
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("Module enumeration failed.") <<
ErrorCodeWinLast(last_error));
}
}
Process const* process_;
HMODULE handle_;
DWORD size_;
std::wstring name_;
std::wstring path_;
};
Module::Module(Process const& process, HMODULE handle)
: impl_(new Impl(process, handle))
{ }
Module::Module(Process const& process, std::wstring const& path)
: impl_(new Impl(process, path))
{ }
Module::Module(Process const& process, MODULEENTRY32 const& entry)
: impl_(new Impl(process, entry))
{ }
Module::Module(Module const& other)
: impl_(new Impl(*other.impl_))
{ }
Module& Module::operator=(Module const& other)
{
impl_ = std::unique_ptr<Impl>(new Impl(*other.impl_));
return *this;
}
Module::Module(Module&& other) HADESMEM_NOEXCEPT
: impl_(std::move(other.impl_))
{ }
Module& Module::operator=(Module&& other) HADESMEM_NOEXCEPT
{
impl_ = std::move(other.impl_);
return *this;
}
Module::~Module()
{ }
HMODULE Module::GetHandle() const HADESMEM_NOEXCEPT
{
return impl_->handle_;
}
DWORD Module::GetSize() const HADESMEM_NOEXCEPT
{
return impl_->size_;
}
std::wstring Module::GetName() const
{
return impl_->name_;
}
std::wstring Module::GetPath() const
{
return impl_->path_;
}
bool operator==(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() == rhs.GetHandle();
}
bool operator!=(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return !(lhs == rhs);
}
bool operator<(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() < rhs.GetHandle();
}
bool operator<=(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() <= rhs.GetHandle();
}
bool operator>(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() > rhs.GetHandle();
}
bool operator>=(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() >= rhs.GetHandle();
}
std::ostream& operator<<(std::ostream& lhs, Module const& rhs)
{
return (lhs << rhs.GetHandle());
}
std::wostream& operator<<(std::wostream& lhs, Module const& rhs)
{
return (lhs << rhs.GetHandle());
}
FARPROC FindProcedure(Module const& module, std::string const& name)
{
return FindProcedureInternal(module, name.c_str());
}
FARPROC FindProcedure(Module const& module, WORD ordinal)
{
return FindProcedureInternal(module, MAKEINTRESOURCEA(ordinal));
}
}
<commit_msg>* Add asserts.<commit_after>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#include "hadesmem/module.hpp"
#include <utility>
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <boost/scope_exit.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/detail/smart_handle.hpp"
#include "hadesmem/detail/to_upper_ordinal.hpp"
namespace hadesmem
{
namespace
{
FARPROC FindProcedureInternal(Module const& module, LPCSTR name)
{
BOOST_ASSERT(name != nullptr);
// Do not continue if Shim Engine is enabled for local process,
// otherwise it could interfere with the address resolution.
// TODO: Work around this with 'manual' export lookup or similar.
HMODULE const shim_eng_mod = ::GetModuleHandle(L"ShimEng.dll");
if (shim_eng_mod)
{
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("Shims enabled for local process."));
}
HMODULE const local_module = ::LoadLibraryEx(module.GetPath().c_str(),
nullptr, DONT_RESOLVE_DLL_REFERENCES);
if (!local_module)
{
DWORD const last_error = ::GetLastError();
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("LoadLibraryEx failed.") <<
ErrorCodeWinLast(last_error));
}
BOOST_SCOPE_EXIT_ALL(&)
{
BOOST_VERIFY(::FreeLibrary(local_module));
};
FARPROC const local_func = ::GetProcAddress(local_module, name);
if (!local_func)
{
DWORD const last_error = ::GetLastError();
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("GetProcAddress failed.") <<
ErrorCodeWinLast(last_error));
}
BOOST_ASSERT(reinterpret_cast<void const*>(local_func) > local_module);
auto const func_delta = reinterpret_cast<DWORD_PTR>(local_func) -
reinterpret_cast<DWORD_PTR>(local_module);
BOOST_ASSERT(module.GetSize() > func_delta);
auto const remote_func = reinterpret_cast<FARPROC>(
reinterpret_cast<DWORD_PTR>(module.GetHandle()) + func_delta);
return remote_func;
}
}
struct Module::Impl
{
explicit Impl(Process const& process, HMODULE handle)
: process_(&process),
handle_(nullptr),
size_(0),
name_(),
path_()
{
Initialize(handle);
}
explicit Impl(Process const& process, std::wstring const& path)
: process_(&process),
handle_(nullptr),
size_(0),
name_(),
path_()
{
Initialize(path);
}
explicit Impl(Process const& process, MODULEENTRY32 const& entry)
: process_(&process),
handle_(nullptr),
size_(0),
name_(),
path_()
{
Initialize(entry);
}
void Initialize(HMODULE handle)
{
auto handle_check =
[&] (MODULEENTRY32 const& entry) -> bool
{
if (entry.hModule == handle || !handle)
{
return true;
}
return false;
};
InitializeIf(handle_check);
}
void Initialize(std::wstring const& path)
{
bool const is_path = (path.find(L'\\') != std::wstring::npos) ||
(path.find(L'/') != std::wstring::npos);
std::wstring const path_upper = detail::ToUpperOrdinal(path);
auto path_check =
[&] (MODULEENTRY32 const& entry) -> bool
{
if (is_path)
{
if (boost::filesystem::equivalent(path, entry.szExePath))
{
return true;
}
}
else
{
if (path_upper == detail::ToUpperOrdinal(entry.szModule))
{
return true;
}
}
return false;
};
InitializeIf(path_check);
}
void Initialize(MODULEENTRY32 const& entry)
{
handle_ = entry.hModule;
size_ = entry.modBaseSize;
name_ = entry.szModule;
path_ = entry.szExePath;
}
typedef std::function<bool (MODULEENTRY32 const&)> EntryCallback;
void InitializeIf(EntryCallback const& check_func)
{
detail::SmartHandle snap(::CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE, process_->GetId()), INVALID_HANDLE_VALUE);
if (!snap.IsValid())
{
if (GetLastError() == ERROR_BAD_LENGTH)
{
snap = ::CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE, process_->GetId());
if (!snap.IsValid())
{
DWORD const last_error = ::GetLastError();
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
}
else
{
DWORD const last_error = ::GetLastError();
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
}
MODULEENTRY32 entry;
::ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
for (BOOL more_mods = ::Module32First(snap.GetHandle(), &entry); more_mods;
more_mods = ::Module32Next(snap.GetHandle(), &entry))
{
if (check_func(entry))
{
Initialize(entry);
return;
}
}
DWORD const last_error = ::GetLastError();
if (last_error == ERROR_NO_MORE_FILES)
{
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("Could not find module.") <<
ErrorCodeWinLast(last_error));
}
else
{
HADESMEM_THROW_EXCEPTION(Error() <<
ErrorString("Module enumeration failed.") <<
ErrorCodeWinLast(last_error));
}
}
Process const* process_;
HMODULE handle_;
DWORD size_;
std::wstring name_;
std::wstring path_;
};
Module::Module(Process const& process, HMODULE handle)
: impl_(new Impl(process, handle))
{ }
Module::Module(Process const& process, std::wstring const& path)
: impl_(new Impl(process, path))
{ }
Module::Module(Process const& process, MODULEENTRY32 const& entry)
: impl_(new Impl(process, entry))
{ }
Module::Module(Module const& other)
: impl_(new Impl(*other.impl_))
{ }
Module& Module::operator=(Module const& other)
{
impl_ = std::unique_ptr<Impl>(new Impl(*other.impl_));
return *this;
}
Module::Module(Module&& other) HADESMEM_NOEXCEPT
: impl_(std::move(other.impl_))
{ }
Module& Module::operator=(Module&& other) HADESMEM_NOEXCEPT
{
impl_ = std::move(other.impl_);
return *this;
}
Module::~Module()
{ }
HMODULE Module::GetHandle() const HADESMEM_NOEXCEPT
{
return impl_->handle_;
}
DWORD Module::GetSize() const HADESMEM_NOEXCEPT
{
return impl_->size_;
}
std::wstring Module::GetName() const
{
return impl_->name_;
}
std::wstring Module::GetPath() const
{
return impl_->path_;
}
bool operator==(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() == rhs.GetHandle();
}
bool operator!=(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return !(lhs == rhs);
}
bool operator<(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() < rhs.GetHandle();
}
bool operator<=(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() <= rhs.GetHandle();
}
bool operator>(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() > rhs.GetHandle();
}
bool operator>=(Module const& lhs, Module const& rhs) HADESMEM_NOEXCEPT
{
return lhs.GetHandle() >= rhs.GetHandle();
}
std::ostream& operator<<(std::ostream& lhs, Module const& rhs)
{
return (lhs << rhs.GetHandle());
}
std::wostream& operator<<(std::wostream& lhs, Module const& rhs)
{
return (lhs << rhs.GetHandle());
}
FARPROC FindProcedure(Module const& module, std::string const& name)
{
return FindProcedureInternal(module, name.c_str());
}
FARPROC FindProcedure(Module const& module, WORD ordinal)
{
return FindProcedureInternal(module, MAKEINTRESOURCEA(ordinal));
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 1998 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include "sysdef.h"
#include "cs2d/openglcommon/glcommon2d.h"
#include "cs3d/opengl/ogl_txtmgr.h"
#include "cscom/com.h"
#include "csinput/csevent.h"
#include "csinput/csinput.h"
#include "cssys/unix/iunix.h"
#include "csutil/csrect.h"
#include "isystem.h"
#include "itexture.h"
csGraphics2DOpenGLFontServer *csGraphics2DGLCommon::LocalFontServer = NULL;
OpenGLTextureCache *csGraphics2DGLCommon::texture_cache = NULL;
// csGraphics2DGLCommon function
csGraphics2DGLCommon::csGraphics2DGLCommon (ISystem* piSystem) :
csGraphics2D (piSystem)
{
System = piSystem;
}
void csGraphics2DGLCommon::Initialize ()
{
csGraphics2D::Initialize ();
DrawPixel = DrawPixelGL;
WriteChar = WriteCharGL;
GetPixelAt = GetPixelAtGL;
DrawSprite = DrawSpriteGL;
}
csGraphics2DGLCommon::~csGraphics2DGLCommon ()
{
// Destroy your graphic interface
Close ();
}
bool csGraphics2DGLCommon::Open(const char *Title)
{
if (glGetString (GL_RENDERER))
CsPrintf (MSG_INITIALIZATION, "Renderer %s ", glGetString(GL_RENDERER) );
if (glGetString (GL_VERSION))
CsPrintf (MSG_INITIALIZATION, "Version %s", glGetString(GL_VERSION));
CsPrintf (MSG_INITIALIZATION, "\n");
// Open your graphic interface
if (!csGraphics2D::Open (Title))
return false;
// load font 'server'
if (LocalFontServer == NULL)
{
CsPrintf(MSG_INITIALIZATION,"Loading fonts...");
LocalFontServer = new csGraphics2DOpenGLFontServer(&FontList[0]);
for (int fontindex=1;
fontindex < 8;
fontindex++)
{
CsPrintf(MSG_INITIALIZATION,"%d...",fontindex);
LocalFontServer->AddFont(FontList[fontindex]);
}
CsPrintf(MSG_INITIALIZATION,"\n");
}
// make our own local texture cache for 2D sprites
if (texture_cache == NULL)
{
CHK (texture_cache = new OpenGLTextureCache(1<<24,24));
}
Clear (0);
return true;
}
void csGraphics2DGLCommon::Close(void)
{
// Close your graphic interface
csGraphics2D::Close ();
// CHK (delete [] Memory);
CHK (delete LocalFontServer);
LocalFontServer = NULL;
CHK (delete texture_cache);
texture_cache = NULL;
}
void csGraphics2DGLCommon::Clear(int color)
{
switch (pfmt.PixelBytes)
{
case 1: // paletted colors
glClearColor(Palette[color].red,
Palette[color].green,
Palette[color].blue,0.);
break;
case 2: // 16bit color
case 4: // truecolor
glClearColor( ( (color & pfmt.RedMask) >> pfmt.RedShift ) / (float)pfmt.RedBits,
( (color & pfmt.GreenMask) >> pfmt.GreenShift ) / (float)pfmt.GreenBits,
( (color & pfmt.BlueMask) >> pfmt.BlueShift ) / (float)pfmt.BlueBits,
0. );
break;
}
glClear(GL_COLOR_BUFFER_BIT);
}
void csGraphics2DGLCommon::SetRGB(int i, int r, int g, int b)
{
csGraphics2D::SetRGB (i, r, g, b);
}
void csGraphics2DGLCommon::setGLColorfromint(int color)
{
switch (pfmt.PixelBytes)
{
case 1: // paletted colors
glColor3i(Palette[color].red,
Palette[color].green,
Palette[color].blue);
break;
case 2: // 16bit color
case 4: // truecolor
glColor3f( ( (color & pfmt.RedMask) >> pfmt.RedShift ) / (float)pfmt.RedBits,
( (color & pfmt.GreenMask) >> pfmt.GreenShift ) / (float)pfmt.GreenBits,
( (color & pfmt.BlueMask) >> pfmt.BlueShift ) / (float)pfmt.BlueBits);
break;
}
}
void csGraphics2DGLCommon::DrawLine (int x1, int y1, int x2, int y2, int color)
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_BLEND);
glDisable (GL_DEPTH_TEST);
setGLColorfromint(color);
glBegin (GL_LINES);
glVertex2i (x1, Height-y1-1);
glVertex2i (x2, Height-y2-1);
glEnd ();
}
void csGraphics2DGLCommon::DrawBox (int x, int y, int w, int h, int color)
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_BLEND);
glDisable (GL_DEPTH_TEST);
setGLColorfromint(color);
glBegin (GL_QUADS);
glVertex2i (x, Height - y - 1);
glVertex2i (x + w - 1, Height - y - 1);
glVertex2i (x + w - 1, Height - (y + h - 1) - 1);
glVertex2i (x, Height - (y + h - 1) - 1);
glEnd ();
}
void csGraphics2DGLCommon::DrawPixelGL (int x, int y, int color)
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_BLEND);
glDisable (GL_DEPTH_TEST);
setGLColorfromint(color);
glBegin (GL_POINTS);
glVertex2i (x, Height-y-1);
glEnd ();
}
void csGraphics2DGLCommon::WriteCharGL (int x, int y, int fg, int /*bg*/, char c)
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_BLEND);
glDisable (GL_DEPTH_TEST);
setGLColorfromint(fg);
// in fact the WriteCharacter() method properly shifts over
// the current modelview transform on each call, so that characters
// are drawn left-to-write. But we bypass that because we know the
// exact x,y location of each letter. We manipulate the transform
// directly, so any shift in WriteCharacter() is effectively ignored
// due to the Push/PopMatrix calls
glPushMatrix();
glTranslatef (x, Height-y-FontList[Font].Height,0.0);
LocalFontServer->WriteCharacter(c,Font);
glPopMatrix();
}
void csGraphics2DGLCommon::DrawSpriteGL (ITextureHandle *hTex, int sx, int sy,
int sw, int sh, int tx, int ty, int tw, int th)
{
texture_cache->Add (hTex);
// cache the texture if we haven't already.
csTextureMMOpenGL* txt_mm = (csTextureMMOpenGL*)GetcsTextureMMFromITextureHandle (hTex);
HighColorCache_Data *cachedata;
cachedata = txt_mm->get_hicolorcache ();
GLuint texturehandle = *( (GLuint *) (cachedata->pData) );
// as we are drawing in 2D, we disable some of the commonly used features
// for fancy 3D drawing
glShadeModel(GL_FLAT);
glDisable (GL_DEPTH_TEST);
// if the texture has transparent bits, we have to tweak the
// OpenGL blend mode so that it handles the transparent pixels correctly
if (txt_mm->get_transparent())
{
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
}
else
glDisable (GL_BLEND);
glEnable(GL_TEXTURE_2D);
glColor4f(1.,1.,1.,1.);
glBindTexture(GL_TEXTURE_2D,texturehandle);
int bitmapwidth=0, bitmapheight=0;
hTex->GetBitmapDimensions(bitmapwidth,bitmapheight);
// convert texture coords given above to normalized (0-1.0) texture coordinates
float ntx1,nty1,ntx2,nty2;
ntx1 = tx/bitmapwidth;
ntx2 = (tx+tw)/bitmapwidth;
nty1 = ty/bitmapheight;
nty2 = (ty+th)/bitmapheight;
// draw the bitmap - we could use GL_QUADS, but why?
glBegin(GL_TRIANGLE_FAN);
glTexCoord2f(ntx1,nty1);
glVertex2i(sx,Height-sy-1);
glTexCoord2f(ntx2,nty1);
glVertex2i(sx+sw,Height-sy-1);
glTexCoord2f(ntx2,nty2);
glVertex2i(sx+sw,Height-sy-sh-1);
glTexCoord2f(ntx1,nty2);
glVertex2i(sx,Height-sy-sh-1);
glEnd();
}
unsigned char* csGraphics2DGLCommon::GetPixelAtGL (int /*x*/, int /*y*/)
{
return NULL;
}
// Used to printf through system driver
void csGraphics2DGLCommon::CsPrintf (int msgtype, const char *format, ...)
{
va_list arg;
char buf[256];
va_start (arg, format);
vsprintf (buf, format, arg);
va_end (arg);
System->Print (msgtype, buf);
}
<commit_msg>Removed printing of "Loading fonts" message upon startup.<commit_after>/*
Copyright (C) 1998 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include "sysdef.h"
#include "cs2d/openglcommon/glcommon2d.h"
#include "cs3d/opengl/ogl_txtmgr.h"
#include "cscom/com.h"
#include "csinput/csevent.h"
#include "csinput/csinput.h"
#include "cssys/unix/iunix.h"
#include "csutil/csrect.h"
#include "isystem.h"
#include "itexture.h"
csGraphics2DOpenGLFontServer *csGraphics2DGLCommon::LocalFontServer = NULL;
OpenGLTextureCache *csGraphics2DGLCommon::texture_cache = NULL;
// csGraphics2DGLCommon function
csGraphics2DGLCommon::csGraphics2DGLCommon (ISystem* piSystem) :
csGraphics2D (piSystem)
{
System = piSystem;
}
void csGraphics2DGLCommon::Initialize ()
{
csGraphics2D::Initialize ();
DrawPixel = DrawPixelGL;
WriteChar = WriteCharGL;
GetPixelAt = GetPixelAtGL;
DrawSprite = DrawSpriteGL;
}
csGraphics2DGLCommon::~csGraphics2DGLCommon ()
{
// Destroy your graphic interface
Close ();
}
bool csGraphics2DGLCommon::Open(const char *Title)
{
if (glGetString (GL_RENDERER))
CsPrintf (MSG_INITIALIZATION, "Renderer %s ", glGetString(GL_RENDERER) );
if (glGetString (GL_VERSION))
CsPrintf (MSG_INITIALIZATION, "Version %s", glGetString(GL_VERSION));
CsPrintf (MSG_INITIALIZATION, "\n");
// Open your graphic interface
if (!csGraphics2D::Open (Title))
return false;
// load font 'server'
if (LocalFontServer == NULL)
{
// CsPrintf(MSG_INITIALIZATION,"Loading fonts...");
LocalFontServer = new csGraphics2DOpenGLFontServer(&FontList[0]);
for (int fontindex=1;
fontindex < 8;
fontindex++)
{
// CsPrintf(MSG_INITIALIZATION,"%d...",fontindex);
LocalFontServer->AddFont(FontList[fontindex]);
}
CsPrintf(MSG_INITIALIZATION,"\n");
}
// make our own local texture cache for 2D sprites
if (texture_cache == NULL)
{
CHK (texture_cache = new OpenGLTextureCache(1<<24,24));
}
Clear (0);
return true;
}
void csGraphics2DGLCommon::Close(void)
{
// Close your graphic interface
csGraphics2D::Close ();
// CHK (delete [] Memory);
CHK (delete LocalFontServer);
LocalFontServer = NULL;
CHK (delete texture_cache);
texture_cache = NULL;
}
void csGraphics2DGLCommon::Clear(int color)
{
switch (pfmt.PixelBytes)
{
case 1: // paletted colors
glClearColor(Palette[color].red,
Palette[color].green,
Palette[color].blue,0.);
break;
case 2: // 16bit color
case 4: // truecolor
glClearColor( ( (color & pfmt.RedMask) >> pfmt.RedShift ) / (float)pfmt.RedBits,
( (color & pfmt.GreenMask) >> pfmt.GreenShift ) / (float)pfmt.GreenBits,
( (color & pfmt.BlueMask) >> pfmt.BlueShift ) / (float)pfmt.BlueBits,
0. );
break;
}
glClear(GL_COLOR_BUFFER_BIT);
}
void csGraphics2DGLCommon::SetRGB(int i, int r, int g, int b)
{
csGraphics2D::SetRGB (i, r, g, b);
}
void csGraphics2DGLCommon::setGLColorfromint(int color)
{
switch (pfmt.PixelBytes)
{
case 1: // paletted colors
glColor3i(Palette[color].red,
Palette[color].green,
Palette[color].blue);
break;
case 2: // 16bit color
case 4: // truecolor
glColor3f( ( (color & pfmt.RedMask) >> pfmt.RedShift ) / (float)pfmt.RedBits,
( (color & pfmt.GreenMask) >> pfmt.GreenShift ) / (float)pfmt.GreenBits,
( (color & pfmt.BlueMask) >> pfmt.BlueShift ) / (float)pfmt.BlueBits);
break;
}
}
void csGraphics2DGLCommon::DrawLine (int x1, int y1, int x2, int y2, int color)
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_BLEND);
glDisable (GL_DEPTH_TEST);
setGLColorfromint(color);
glBegin (GL_LINES);
glVertex2i (x1, Height-y1-1);
glVertex2i (x2, Height-y2-1);
glEnd ();
}
void csGraphics2DGLCommon::DrawBox (int x, int y, int w, int h, int color)
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_BLEND);
glDisable (GL_DEPTH_TEST);
setGLColorfromint(color);
glBegin (GL_QUADS);
glVertex2i (x, Height - y - 1);
glVertex2i (x + w - 1, Height - y - 1);
glVertex2i (x + w - 1, Height - (y + h - 1) - 1);
glVertex2i (x, Height - (y + h - 1) - 1);
glEnd ();
}
void csGraphics2DGLCommon::DrawPixelGL (int x, int y, int color)
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_BLEND);
glDisable (GL_DEPTH_TEST);
setGLColorfromint(color);
glBegin (GL_POINTS);
glVertex2i (x, Height-y-1);
glEnd ();
}
void csGraphics2DGLCommon::WriteCharGL (int x, int y, int fg, int /*bg*/, char c)
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_BLEND);
glDisable (GL_DEPTH_TEST);
setGLColorfromint(fg);
// in fact the WriteCharacter() method properly shifts over
// the current modelview transform on each call, so that characters
// are drawn left-to-write. But we bypass that because we know the
// exact x,y location of each letter. We manipulate the transform
// directly, so any shift in WriteCharacter() is effectively ignored
// due to the Push/PopMatrix calls
glPushMatrix();
glTranslatef (x, Height-y-FontList[Font].Height,0.0);
LocalFontServer->WriteCharacter(c,Font);
glPopMatrix();
}
void csGraphics2DGLCommon::DrawSpriteGL (ITextureHandle *hTex, int sx, int sy,
int sw, int sh, int tx, int ty, int tw, int th)
{
texture_cache->Add (hTex);
// cache the texture if we haven't already.
csTextureMMOpenGL* txt_mm = (csTextureMMOpenGL*)GetcsTextureMMFromITextureHandle (hTex);
HighColorCache_Data *cachedata;
cachedata = txt_mm->get_hicolorcache ();
GLuint texturehandle = *( (GLuint *) (cachedata->pData) );
// as we are drawing in 2D, we disable some of the commonly used features
// for fancy 3D drawing
glShadeModel(GL_FLAT);
glDisable (GL_DEPTH_TEST);
// if the texture has transparent bits, we have to tweak the
// OpenGL blend mode so that it handles the transparent pixels correctly
if (txt_mm->get_transparent())
{
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
}
else
glDisable (GL_BLEND);
glEnable(GL_TEXTURE_2D);
glColor4f(1.,1.,1.,1.);
glBindTexture(GL_TEXTURE_2D,texturehandle);
int bitmapwidth=0, bitmapheight=0;
hTex->GetBitmapDimensions(bitmapwidth,bitmapheight);
// convert texture coords given above to normalized (0-1.0) texture coordinates
float ntx1,nty1,ntx2,nty2;
ntx1 = tx/bitmapwidth;
ntx2 = (tx+tw)/bitmapwidth;
nty1 = ty/bitmapheight;
nty2 = (ty+th)/bitmapheight;
// draw the bitmap - we could use GL_QUADS, but why?
glBegin(GL_TRIANGLE_FAN);
glTexCoord2f(ntx1,nty1);
glVertex2i(sx,Height-sy-1);
glTexCoord2f(ntx2,nty1);
glVertex2i(sx+sw,Height-sy-1);
glTexCoord2f(ntx2,nty2);
glVertex2i(sx+sw,Height-sy-sh-1);
glTexCoord2f(ntx1,nty2);
glVertex2i(sx,Height-sy-sh-1);
glEnd();
}
unsigned char* csGraphics2DGLCommon::GetPixelAtGL (int /*x*/, int /*y*/)
{
return NULL;
}
// Used to printf through system driver
void csGraphics2DGLCommon::CsPrintf (int msgtype, const char *format, ...)
{
va_list arg;
char buf[256];
va_start (arg, format);
vsprintf (buf, format, arg);
va_end (arg);
System->Print (msgtype, buf);
}
<|endoftext|>
|
<commit_before>#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>
#define WSVERS MAKEWORD(2,0)
#define BUFFESIZE 200
#define SEGMENTSIZE 70
WSADATA wsadata;
int main(int argc, char *argv[])
{
//*******************************************************************
// Initialization
//*******************************************************************
struct sockaddr_in remoteaddr;
struct hostent *h;
SOCKET s;
char send_buffer[BUFFESIZE], receive_buffer[BUFFESIZE];
int n, bytes;
memset(&remoteaddr, 0, sizeof(remoteaddr)); //clean up
//*******************************************************************
//WSASTARTUP
//*******************************************************************
if (WSAStartup(WSVERS, &wsadata) != 0) {
WSACleanup();
printf("WSAStartup failed\n");
exit(1);
}
if (argc != 3) {
printf("USAGE: client IP-address port\n");
exit(1);
}
else {
remoteaddr.sin_addr.s_addr = inet_addr(argv[1]);//IP address
remoteaddr.sin_port = htons((u_short)atoi(argv[2]));//Port number
}
//*******************************************************************
//CREATE CLIENT'S SOCKET
//*******************************************************************
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
printf("socket failed\n");
exit(1);
}
remoteaddr.sin_family = AF_INET;
//*******************************************************************
//CONNECT
//*******************************************************************
if (connect(s, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr)) != 0) {
printf("connect failed\n");
exit(1);
}
//*******************************************************************
//Get input while user don't type "."
//*******************************************************************
memset(&send_buffer, 0, BUFFESIZE);
fgets(send_buffer, SEGMENTSIZE, stdin);
while (strncmp(send_buffer, ".", 1) != 0) {
#if defined __unix__ || defined __APPLE__
send_buffer[strlen(send_buffer) - 1] = '\0';//strip send_buffer from '\n'
printf("lenght is %d \n", (int)strlen(send_buffer));
#elif defined _WIN32
send_buffer[strlen(send_buffer) - 1] = '\0';//strip send_buffer from '\n'
//nothing to do
#endif
printf(">>> %s\n", send_buffer);//line sent
strcat(send_buffer, "\r\n");
//*******************************************************************
//SEND
//*******************************************************************
bytes = send(s, send_buffer, strlen(send_buffer), 0);
if (bytes < 0) {
printf("send failed\n");
exit(1);
}
n = 0;
while (1) {
//*******************************************************************
//RECEIVE
//*******************************************************************
bytes = recv(s, &receive_buffer[n], 1, 0);
if ((bytes <= 0)) {
printf("recv failed\n");
exit(1);
}
if (receive_buffer[n] == '\n') { /*end on a LF*/
receive_buffer[n] = '\0';
break;
}
if (receive_buffer[n] != '\r') n++; /*ignore CR's*/
}
printf("%s \n", receive_buffer);// line received
memset(&send_buffer, 0, BUFFESIZE);
fgets(send_buffer, SEGMENTSIZE, stdin);
}
//*******************************************************************
//CLOSESOCKET
//*******************************************************************
#if defined __unix__ || defined __APPLE__
close(s);
#elif defined _WIN32
closesocket(s);
#endif
return 0;
}
<commit_msg> modified: src/2015a3/client2015.cpp<commit_after>#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>
#define WSVERS MAKEWORD(2,0)
#define BUFFESIZE 200
#define SEGMENTSIZE 70
WSADATA wsadata;
int main(int argc, char *argv[])
{
// Initialization
struct sockaddr_in remoteaddr;
struct hostent *h;
SOCKET s;
char send_buffer[BUFFESIZE], receive_buffer[BUFFESIZE];
int n, bytes;
memset(&remoteaddr, 0, sizeof(remoteaddr)); //clean up
//WSASTARTUP
if (WSAStartup(WSVERS, &wsadata) != 0)
{
WSACleanup();
printf("WSAStartup failed\n");
exit(1);
}
if (argc != 3)
{
printf("USAGE: client IP-address port\n");
exit(1);
}
else
{
remoteaddr.sin_addr.s_addr = inet_addr(argv[1]); //IP address
remoteaddr.sin_port = htons((u_short)atoi(argv[2]));//Port number
}
//CREATE CLIENT'S SOCKET
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0)
{
printf("socket failed\n");
exit(1);
}
remoteaddr.sin_family = AF_INET;
//*******************************************************************
//CONNECT
//*******************************************************************
if (connect(s, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr)) != 0) {
printf("connect failed\n");
exit(1);
}
//*******************************************************************
//Get input while user don't type "."
//*******************************************************************
memset(&send_buffer, 0, BUFFESIZE);
fgets(send_buffer, SEGMENTSIZE, stdin);
while (strncmp(send_buffer, ".", 1) != 0)
{
send_buffer[strlen(send_buffer) - 1] = '\0';//strip send_buffer from '\n'
strcat(send_buffer, "\r\n");
//*******************************************************************
//SEND
//*******************************************************************
bytes = send(s, send_buffer, strlen(send_buffer), 0);
if (bytes < 0) {
printf("send failed\n");
exit(1);
}
n = 0;
while (1) {
//*******************************************************************
//RECEIVE
//*******************************************************************
bytes = recv(s, &receive_buffer[n], 1, 0);
if ((bytes <= 0)) {
printf("recv failed\n");
exit(1);
}
if (receive_buffer[n] == '\n') { /*end on a LF*/
receive_buffer[n] = '\0';
break;
}
if (receive_buffer[n] != '\r') n++; /*ignore CR's*/
}
printf("%s \n", receive_buffer);// line received
memset(&send_buffer, 0, BUFFESIZE);
fgets(send_buffer, SEGMENTSIZE, stdin);
}
//*******************************************************************
//CLOSESOCKET
//*******************************************************************
#if defined __unix__ || defined __APPLE__
close(s);
#elif defined _WIN32
closesocket(s);
#endif
return 0;
}
<|endoftext|>
|
<commit_before>// hashtbl.cc see license.txt for copyright and terms of use
// code for hashtbl.h
#include "hashtbl.h" // this module
#include "xassert.h" // xassert
#include <string.h> // memset
unsigned HashTable::hashFunction(void const *key) const
{
return coreHashFn(key) % (unsigned)tableSize;
}
HashTable::HashTable(GetKeyFn gk, HashFn hf, EqualKeyFn ek, int initSize)
: getKey(gk),
coreHashFn(hf),
equalKeys(ek),
enableShrink(true)
{
makeTable(initSize);
}
HashTable::~HashTable()
{
delete[] hashTable;
}
void HashTable::makeTable(int size)
{
hashTable = new void*[size];
tableSize = size;
memset(hashTable, 0, sizeof(void*) * tableSize);
numEntries = 0;
}
inline int HashTable::getEntry(void const *key) const
{
int index = hashFunction(key);
int originalIndex = index;
for(;;) {
if (hashTable[index] == NULL) {
// unmapped
return index;
}
if (equalKeys(key, getKey(hashTable[index]))) {
// mapped here
return index;
}
// this entry is mapped, but not with this key, i.e.
// we have a collision -- so just go to the next entry,
// wrapping as necessary
index = nextIndex(index);
// detect infinite looping
xassert(index != originalIndex);
}
}
void *HashTable::get(void const *key) const
{
return hashTable[getEntry(key)];
}
void HashTable::resizeTable(int newSize)
{
// Make sure newSize is not the result of an overflowed computation, and
// that we're not going to resizeTable again right away in the add() call.
xassert(newSize >= numEntries);
xassert(newSize/3*2 >= numEntries-1);
// save old stuff
void **oldTable = hashTable;
int oldSize = tableSize;
int entries = numEntries;
// make the new table
makeTable(newSize);
// set this now so that we increment a local instead of instance member
numEntries = entries;
// move entries to the new table
for (int i=0; i<oldSize; i++) {
if (oldTable[i] != NULL) {
// inline the following call:
// add(getKey(oldTable[i]), oldTable[i]);
// This function is worth optimizing; it accounts for 12% of qualcc
// runtime. This simple inlining reduces resizeTable()'s impact from
// 12% to 2%.
int newIndex = getEntry(getKey(oldTable[i]));
xassertdb(hashTable[newIndex] == NULL); // must not be a mapping yet
hashTable[newIndex] = oldTable[i];
entries--;
}
}
xassert(entries == 0);
// deallocate the old table
delete[] oldTable;
}
void HashTable::add(void const *key, void *value)
{
if (numEntries+1 > tableSize*2/3) {
// we're over the usage threshold; increase table size
// TODO: increase the new size
resizeTable(tableSize * 2 + 1);
}
// make sure above didn't fail due to integer overflow
xassert(numEntries+1 < tableSize);
int index = getEntry(key);
xassert(hashTable[index] == NULL); // must not be a mapping yet
hashTable[index] = value;
numEntries++;
}
void *HashTable::remove(void const *key)
{
if (enableShrink &&
numEntries-1 < tableSize/5 &&
tableSize > defaultSize) {
// we're below threshold; reduce table size
resizeTable(tableSize / 2);
}
int index = getEntry(key);
xassert(hashTable[index] != NULL); // must be a mapping to remove
// remove this entry
void *retval = hashTable[index];
hashTable[index] = NULL;
numEntries--;
// now, if we ever inserted something and it collided with this one,
// leaving things like this would prevent us from finding that other
// mapping because the search stops as soon as a NULL entry is
// discovered; so we must examine all entries that could have
// collided, and re-insert them
int originalIndex = index;
for(;;) {
index = nextIndex(index);
xassert(index != originalIndex); // prevent infinite loops
if (hashTable[index] == NULL) {
// we've reached the end of the list of possible colliders
break;
}
// remove this one
void *data = hashTable[index];
hashTable[index] = NULL;
numEntries--;
// add it back
add(getKey(data), data);
}
return retval;
}
void HashTable::empty(int initSize)
{
delete[] hashTable;
makeTable(initSize);
}
void HashTable::selfCheck() const
{
int ct=0;
for (int i=0; i<tableSize; i++) {
if (hashTable[i] != NULL) {
checkEntry(i);
ct++;
}
}
xassert(ct == numEntries);
}
void HashTable::checkEntry(int entry) const
{
int index = getEntry(getKey(hashTable[entry]));
int originalIndex = index;
for(;;) {
if (index == entry) {
// the entry lives where it will be found, so that's good
return;
}
if (hashTable[index] == NULL) {
// the search for this entry would stop before finding it,
// so that's bad!
xfailure("checkEntry: entry in wrong slot");
}
// collision; keep looking
index = nextIndex(index);
xassert(index != originalIndex);
}
}
// ------------------ HashTableIter --------------------
HashTableIter::HashTableIter(HashTable &t)
: table(t)
{
index = 0;
moveToSth();
}
void HashTableIter::adv()
{
xassert(!isDone());
// move off the current item
index++;
// keep moving until we find something
moveToSth();
}
void HashTableIter::moveToSth()
{
while (index < table.tableSize &&
table.hashTable[index] == NULL) {
index++;
}
if (index == table.tableSize) {
index = -1; // mark as done
}
}
void *HashTableIter::data() const
{
xassert(!isDone());
return table.hashTable[index];
}
STATICDEF void const *HashTable::identityKeyFn(void *data)
{
return data;
}
unsigned lcprngTwoSteps(unsigned v)
{
// this is the core of the LC PRNG in one of the many libcs
// running around the net
v = (v * 1103515245) + 12345;
// do it again for good measure
v = (v * 1103515245) + 12345;
return v;
}
STATICDEF unsigned HashTable::lcprngHashFn(void const *key)
{
return lcprngTwoSteps((unsigned)pointerToInteger(key));
}
STATICDEF bool HashTable::
pointerEqualKeyFn(void const *key1, void const *key2)
{
return key1 == key2;
}
<commit_msg>Optimize HashTable::add call to resizeTable()<commit_after>// hashtbl.cc see license.txt for copyright and terms of use
// code for hashtbl.h
#include "hashtbl.h" // this module
#include "xassert.h" // xassert
#include <string.h> // memset
unsigned HashTable::hashFunction(void const *key) const
{
return coreHashFn(key) % (unsigned)tableSize;
}
HashTable::HashTable(GetKeyFn gk, HashFn hf, EqualKeyFn ek, int initSize)
: getKey(gk),
coreHashFn(hf),
equalKeys(ek),
enableShrink(true)
{
makeTable(initSize);
}
HashTable::~HashTable()
{
delete[] hashTable;
}
void HashTable::makeTable(int size)
{
hashTable = new void*[size];
tableSize = size;
memset(hashTable, 0, sizeof(void*) * tableSize);
numEntries = 0;
}
inline int HashTable::getEntry(void const *key) const
{
int index = hashFunction(key);
int originalIndex = index;
for(;;) {
if (hashTable[index] == NULL) {
// unmapped
return index;
}
if (equalKeys(key, getKey(hashTable[index]))) {
// mapped here
return index;
}
// this entry is mapped, but not with this key, i.e.
// we have a collision -- so just go to the next entry,
// wrapping as necessary
index = nextIndex(index);
// detect infinite looping
xassert(index != originalIndex);
}
}
void *HashTable::get(void const *key) const
{
return hashTable[getEntry(key)];
}
void HashTable::resizeTable(int newSize)
{
// Make sure newSize is not the result of an overflowed computation, and
// that we're not going to resizeTable again right away in the add() call.
xassert(newSize >= numEntries);
xassert(newSize/3*2 >= numEntries-1);
// save old stuff
void **oldTable = hashTable;
int oldSize = tableSize;
int entries = numEntries;
// make the new table
makeTable(newSize);
// set this now so that we increment a local instead of instance member
numEntries = entries;
// move entries to the new table
for (int i=0; i<oldSize; i++) {
if (oldTable[i] != NULL) {
// inline the following call:
// add(getKey(oldTable[i]), oldTable[i]);
// This function is worth optimizing; it accounts for 12% of qualcc
// runtime. This simple inlining reduces resizeTable()'s impact from
// 12% to 2%.
int newIndex = getEntry(getKey(oldTable[i]));
xassertdb(hashTable[newIndex] == NULL); // must not be a mapping yet
hashTable[newIndex] = oldTable[i];
entries--;
}
}
xassert(entries == 0);
// deallocate the old table
delete[] oldTable;
}
void HashTable::add(void const *key, void *value)
{
if (numEntries+1 > tableSize/2) {
// We're over the usage threshold; increase table size.
//
// Resizing by numEntries*4 instead of tableSize*2 gives 42% speedup in
// total time used by resizeTable().
resizeTable(numEntries*4 + 1);
}
// make sure above didn't fail due to integer overflow
xassert(numEntries+1 < tableSize);
int index = getEntry(key);
xassert(hashTable[index] == NULL); // must not be a mapping yet
hashTable[index] = value;
numEntries++;
}
void *HashTable::remove(void const *key)
{
if (enableShrink &&
numEntries-1 < tableSize/5 &&
tableSize > defaultSize) {
// we're below threshold; reduce table size
resizeTable(tableSize / 2);
}
int index = getEntry(key);
xassert(hashTable[index] != NULL); // must be a mapping to remove
// remove this entry
void *retval = hashTable[index];
hashTable[index] = NULL;
numEntries--;
// now, if we ever inserted something and it collided with this one,
// leaving things like this would prevent us from finding that other
// mapping because the search stops as soon as a NULL entry is
// discovered; so we must examine all entries that could have
// collided, and re-insert them
int originalIndex = index;
for(;;) {
index = nextIndex(index);
xassert(index != originalIndex); // prevent infinite loops
if (hashTable[index] == NULL) {
// we've reached the end of the list of possible colliders
break;
}
// remove this one
void *data = hashTable[index];
hashTable[index] = NULL;
numEntries--;
// add it back
add(getKey(data), data);
}
return retval;
}
void HashTable::empty(int initSize)
{
delete[] hashTable;
makeTable(initSize);
}
void HashTable::selfCheck() const
{
int ct=0;
for (int i=0; i<tableSize; i++) {
if (hashTable[i] != NULL) {
checkEntry(i);
ct++;
}
}
xassert(ct == numEntries);
}
void HashTable::checkEntry(int entry) const
{
int index = getEntry(getKey(hashTable[entry]));
int originalIndex = index;
for(;;) {
if (index == entry) {
// the entry lives where it will be found, so that's good
return;
}
if (hashTable[index] == NULL) {
// the search for this entry would stop before finding it,
// so that's bad!
xfailure("checkEntry: entry in wrong slot");
}
// collision; keep looking
index = nextIndex(index);
xassert(index != originalIndex);
}
}
// ------------------ HashTableIter --------------------
HashTableIter::HashTableIter(HashTable &t)
: table(t)
{
index = 0;
moveToSth();
}
void HashTableIter::adv()
{
xassert(!isDone());
// move off the current item
index++;
// keep moving until we find something
moveToSth();
}
void HashTableIter::moveToSth()
{
while (index < table.tableSize &&
table.hashTable[index] == NULL) {
index++;
}
if (index == table.tableSize) {
index = -1; // mark as done
}
}
void *HashTableIter::data() const
{
xassert(!isDone());
return table.hashTable[index];
}
STATICDEF void const *HashTable::identityKeyFn(void *data)
{
return data;
}
unsigned lcprngTwoSteps(unsigned v)
{
// this is the core of the LC PRNG in one of the many libcs
// running around the net
v = (v * 1103515245) + 12345;
// do it again for good measure
v = (v * 1103515245) + 12345;
return v;
}
STATICDEF unsigned HashTable::lcprngHashFn(void const *key)
{
return lcprngTwoSteps((unsigned)pointerToInteger(key));
}
STATICDEF bool HashTable::
pointerEqualKeyFn(void const *key1, void const *key2)
{
return key1 == key2;
}
<|endoftext|>
|
<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright 2016 [bk]door.maus
#ifndef LIBGLURG_COMMON_SNAPPY_ADAPTER_HPP
#define LIBGLURG_COMMON_SNAPPY_ADAPTER_HPP
#include <stdexcept>
#include <type_traits>
#include <list>
#include "glurg/common/fileStream.hpp"
namespace glurg
{
class SnappyAdapterBase
{
public:
~SnappyAdapterBase();
protected:
explicit SnappyAdapterBase(std::size_t block_size);
void snappy_write(
FileStream* stream, const std::uint8_t* data, std::size_t length);
void snappy_read(
FileStream* stream, std::uint8_t* data, std::size_t length);
void snappy_seek(FileStream* stream, std::size_t virtual_offset);
std::size_t snappy_tell();
void snappy_flush_write_buffer(FileStream* stream);
void snappy_reset_state();
private:
bool snappy_fetch_read_buffer(FileStream* stream);
void snappy_add_block(
std::size_t physical_position, std::size_t physical_size,
std::size_t virtual_size);
void snappy_get_last_block_info(
std::size_t& max_physical_position,
std::size_t& max_virtual_position);
struct snappy_block
{
std::size_t physical_position;
std::size_t physical_size;
std::size_t virtual_position;
std::size_t virtual_size;
};
std::list<snappy_block> snappy_blocks;
std::size_t snappy_current_block_virtual_position;
std::uint8_t* snappy_output_buffer;
std::size_t snappy_output_buffer_size;
std::uint8_t* snappy_write_buffer;
std::size_t max_snappy_write_buffer_size;
std::size_t cur_snappy_write_buffer_size;
std::uint8_t* snappy_read_buffer;
std::size_t snappy_read_buffer_size;
std::size_t snappy_read_buffer_offset;
};
template <typename FileStreamImpl>
class SnappyAdapter :
public SnappyAdapterBase,
public std::enable_if<std::is_base_of<FileStream, FileStreamImpl>::value, FileStreamImpl>::type
{
public:
// Default compressed block size, in bytes.
static const std::size_t DEFAULT_BLOCK_SIZE = 1 * 1024 * 1024;
explicit SnappyAdapter(std::size_t block_size = DEFAULT_BLOCK_SIZE);
~SnappyAdapter() = default;
void write(const std::uint8_t* data, std::size_t length) override;
void read(std::uint8_t* data, std::size_t length) override;
void close() override;
private:
// At least as of 7.1, apitrace's trace files insert these characters at
// the beginning of a trace file using Snappy compression.
static const char MAGIC_BYTE_1 = 'a';
static const char MAGIC_BYTE_2 = 't';
bool is_new;
};
}
template <typename FileStreamImpl>
glurg::SnappyAdapter<FileStreamImpl>::SnappyAdapter(std::size_t block_size)
: SnappyAdapterBase(block_size)
{
this->is_new = true;
}
template <typename FileStreamImpl>
void glurg::SnappyAdapter<FileStreamImpl>::write(
const std::uint8_t* data, std::size_t length)
{
this->snappy_write(this, data, length);
}
template <typename FileStreamImpl>
void glurg::SnappyAdapter<FileStreamImpl>::read(
std::uint8_t *data, std::size_t length)
{
if (this->is_new)
{
char magic[2];
FileStreamImpl::read((char*)magic, 2);
if (magic[0] != MAGIC_BYTE_1 || magic[1] != MAGIC_BYTE_2)
{
throw std::runtime_error("magic bytes are incorrect");
}
this->is_new = false;
}
this->snappy_read(this, data, length);
}
template <typename FileStreamImpl>
void glurg::SnappyAdapter<FileStreamImpl>::close()
{
this->snappy_flush_write_buffer(this);
this->snappy_reset_state();
this->is_new = true;
}
#endif
<commit_msg>Finished implementing seek support in glurg::SnappyAdapter.<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright 2016 [bk]door.maus
#ifndef LIBGLURG_COMMON_SNAPPY_ADAPTER_HPP
#define LIBGLURG_COMMON_SNAPPY_ADAPTER_HPP
#include <stdexcept>
#include <type_traits>
#include <list>
#include "glurg/common/fileStream.hpp"
namespace glurg
{
class SnappyAdapterBase
{
public:
~SnappyAdapterBase();
protected:
explicit SnappyAdapterBase(std::size_t block_size);
void snappy_write(
FileStream* stream, const std::uint8_t* data, std::size_t length);
void snappy_read(
FileStream* stream, std::uint8_t* data, std::size_t length);
void snappy_seek(FileStream* stream, std::size_t virtual_offset);
std::size_t snappy_tell();
void snappy_flush_write_buffer(FileStream* stream);
void snappy_reset_state();
private:
bool snappy_fetch_read_buffer(FileStream* stream);
void snappy_add_block(
std::size_t physical_position, std::size_t physical_size,
std::size_t virtual_size);
void snappy_get_last_block_info(
std::size_t& max_physical_position,
std::size_t& max_virtual_position);
struct snappy_block
{
std::size_t physical_position;
std::size_t physical_size;
std::size_t virtual_position;
std::size_t virtual_size;
};
std::list<snappy_block> snappy_blocks;
std::size_t snappy_current_block_virtual_position;
std::uint8_t* snappy_output_buffer;
std::size_t snappy_output_buffer_size;
std::uint8_t* snappy_write_buffer;
std::size_t max_snappy_write_buffer_size;
std::size_t cur_snappy_write_buffer_size;
std::uint8_t* snappy_read_buffer;
std::size_t snappy_read_buffer_size;
std::size_t snappy_read_buffer_offset;
};
template <typename FileStreamImpl>
class SnappyAdapter :
public SnappyAdapterBase,
public std::enable_if<std::is_base_of<FileStream, FileStreamImpl>::value, FileStreamImpl>::type
{
public:
// Default compressed block size, in bytes.
static const std::size_t DEFAULT_BLOCK_SIZE = 1 * 1024 * 1024;
explicit SnappyAdapter(std::size_t block_size = DEFAULT_BLOCK_SIZE);
~SnappyAdapter() = default;
void write(const std::uint8_t* data, std::size_t length) override;
void read(std::uint8_t* data, std::size_t length) override;
std::size_t get_position() override;
void set_position(std::size_t position) override;
void close() override;
private:
// At least as of 7.1, apitrace's trace files insert these characters at
// the beginning of a trace file using Snappy compression.
static const char MAGIC_BYTE_1 = 'a';
static const char MAGIC_BYTE_2 = 't';
bool is_new;
};
}
template <typename FileStreamImpl>
glurg::SnappyAdapter<FileStreamImpl>::SnappyAdapter(std::size_t block_size)
: SnappyAdapterBase(block_size)
{
this->is_new = true;
}
template <typename FileStreamImpl>
void glurg::SnappyAdapter<FileStreamImpl>::write(
const std::uint8_t* data, std::size_t length)
{
this->snappy_write(this, data, length);
}
template <typename FileStreamImpl>
void glurg::SnappyAdapter<FileStreamImpl>::read(
std::uint8_t *data, std::size_t length)
{
if (this->is_new)
{
char magic[2];
FileStreamImpl::read((char*)magic, 2);
if (magic[0] != MAGIC_BYTE_1 || magic[1] != MAGIC_BYTE_2)
{
throw std::runtime_error("magic bytes are incorrect");
}
this->is_new = false;
}
this->snappy_read(this, data, length);
}
template <typename FileStreamImpl>
std::size_t glurg::SnappyAdapter<FileStreamImpl>::get_position()
{
return this->snappy_tell();
}
template <typename FileStreamImpl>
void glurg::SnappyAdapter<FileStreamImpl>::set_position(std::size_t position)
{
this->snappy_seek(position);
}
template <typename FileStreamImpl>
void glurg::SnappyAdapter<FileStreamImpl>::close()
{
this->snappy_flush_write_buffer(this);
this->snappy_reset_state();
this->is_new = true;
}
#endif
<|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 COPYING 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.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif
// interface headers
#include "TextureManager.h"
// system headers
#include <vector>
#include <string>
// common implementation headers
#include "TextUtils.h"
#include "global.h"
#include "MediaFile.h"
#include "ErrorHandler.h"
#include "OSFile.h"
/*const int NO_VARIANT = (-1); */
// initialize the singleton
template <>
TextureManager* Singleton<TextureManager>::_instance = (TextureManager*)0;
static int noiseProc(ProcTextureInit &init);
ProcTextureInit procLoader[1];
TextureManager::TextureManager()
{
configFilterValues[Off] = "no";
configFilterValues[Nearest] = "nearest";
configFilterValues[Linear] = "linear";
configFilterValues[NearestMipmapNearest] = "nearestmipmapnearest";
configFilterValues[LinearMipmapNearest] = "linearmipmapnearest";
configFilterValues[NearestMipmapLinear] = "nearestmipmaplinear";
configFilterValues[LinearMipmapLinear] = "linearmipmaplinear";
// init the default filter methods
currentMaxFilter = Max;
// fill out the standard proc textures
procLoader[0].name = "noise";
procLoader[0].filter = Nearest;
procLoader[0].proc = noiseProc;
lastImageID = -1;
lastBoundID = -1;
int i, numTextures;
numTextures = countof(procLoader);
for (i = 0; i < numTextures; i++) {
procLoader[i].manager = this;
procLoader[i].proc(procLoader[i]);
}
}
TextureManager::~TextureManager()
{
// we are done remove all textures
for (TextureNameMap::iterator it = textureNames.begin(); it != textureNames.end(); ++it) {
ImageInfo &tex = it->second;
if (tex.texture != NULL) {
delete tex.texture;
}
}
textureNames.clear();
textureIDs.clear();
}
int TextureManager::getTextureID( const char* name, bool reportFail )
{
if (!name) {
DEBUG2("Could not get texture ID; no provided name\n");
return -1;
}
OSFile osFilename(name);
std::string texName = osFilename.getOSName();
// see if we have the texture
TextureNameMap::iterator it = textureNames.find(texName);
if (it != textureNames.end()) {
return it->second.id;
} else { // we don't have it so try and load it
FileTextureInit file;
file.filter = LinearMipmapLinear;
file.name = texName;
ImageInfo info;
OpenGLTexture *image = loadTexture(file, reportFail);
if (!image) {
DEBUG2("Image not found or unloadable: %s\n", name);
return -1;
}
return addTexture(name, image);
}
return -1;
}
bool TextureManager::bind ( int id )
{
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end()) {
DEBUG1("Unable to bind texture (by id): %d\n", id);
return false;
}
if (id != lastBoundID) {
it->second->texture->execute();
lastBoundID = id;
}
return true;
}
bool TextureManager::bind ( const char* name )
{
std::string nameStr = name;
TextureNameMap::iterator it = textureNames.find(nameStr);
if (it == textureNames.end()) {
DEBUG1("Unable to bind texture (by name): %s\n", name);
return false;
}
int id = it->second.id;
if (id != lastBoundID) {
it->second.texture->execute();
lastBoundID = id;
}
return true;
}
std::string TextureManager::getMaxFilterName ( void )
{
return configFilterValues[static_cast<int>(currentMaxFilter)];
}
void TextureManager::setMaxFilter ( std::string filter )
{
eTextureFilter realFilter = Max;
for (int i = 0; i < (int)Max; i++) {
if (filter == configFilterValues[i])
realFilter = (eTextureFilter)i;
}
setMaxFilter(realFilter);
}
void TextureManager::setMaxFilter ( eTextureFilter filter )
{
currentMaxFilter = filter;
// flush all the textures so they get rebuilt on next use
TextureNameMap::iterator itr = textureNames.begin();
while (itr != textureNames.end()) {
FileTextureInit fileInit;
fileInit.filter = currentMaxFilter;
fileInit.name = itr->second.name;
OpenGLTexture *newTexture = loadTexture(fileInit, false);
delete(itr->second.texture);
itr->second.texture = newTexture;
itr++;
}
// rebuild proc textures
for (int i = 0; i < (int)countof(procLoader); i++) {
procLoader[i].manager = this;
procLoader[i].proc(procLoader[i]);
}
}
float TextureManager::GetAspectRatio ( int id )
{
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return 0.0;
return (float)it->second->y/(float)it->second->x;
}
const ImageInfo& TextureManager::getInfo ( int id )
{
static ImageInfo crapInfo;
crapInfo.id = -1;
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return crapInfo;
return *(it->second);
}
const ImageInfo& TextureManager::getInfo ( const char* name )
{
static ImageInfo crapInfo;
crapInfo.id = -1;
std::string nameStr = name;
TextureNameMap::iterator it = textureNames.find(nameStr);
if (it == textureNames.end())
return crapInfo;
return it->second;
}
int TextureManager::addTexture( const char* name, OpenGLTexture *texture )
{
if (!name || !texture)
return -1;
// if the texture already exists kill it
// this is why IDs are way better than objects for this stuff
TextureNameMap::iterator it = textureNames.find(name);
if (it != textureNames.end()) {
DEBUG3("Texture %s already exists, overwriting\n", name);
textureIDs.erase(textureIDs.find(it->second.id));
delete it->second.texture;
}
ImageInfo info;
info.name = name;
info.texture = texture;
info.id = ++lastImageID;
info.alpha = texture->hasAlpha();
info.x = texture->getWidth();
info.y = texture->getHeight();
textureNames[name] = info;
textureIDs[info.id] = &textureNames[name];
DEBUG4("Added texture %s: id %d\n", name, info.id);
return info.id;
}
OpenGLTexture* TextureManager::loadTexture(FileTextureInit &init, bool reportFail)
{
int width, height;
std::string nameToTry = init.name;
unsigned char* image = NULL;
if (nameToTry.size() && nameToTry.c_str())
image = MediaFile::readImage(nameToTry, &width, &height);
if (!image)
image = MediaFile::readImage(init.name, &width, &height);
if (!image) {
if (reportFail) {
std::vector<std::string> args;
args.push_back(init.name);
printError("cannot load texture: {1}", &args);
}
return NULL;
}
OpenGLTexture::Filter RealFilter;
if (init.filter > currentMaxFilter)
RealFilter = (OpenGLTexture::Filter)currentMaxFilter;
else
RealFilter = (OpenGLTexture::Filter)init.filter;
OpenGLTexture *texture = new OpenGLTexture(width, height, image, RealFilter, true);
delete[] image;
return texture;
}
int TextureManager::newTexture(const char* name, int x, int y, unsigned char* data, eTextureFilter filter, bool repeat, int format)
{
OpenGLTexture::Filter RealFilter;
if (filter > currentMaxFilter)
RealFilter = (OpenGLTexture::Filter)currentMaxFilter;
else
RealFilter = (OpenGLTexture::Filter)filter;
return addTexture(name, new OpenGLTexture(x, y, data, RealFilter, repeat, format));
}
/* --- Procs --- */
int noiseProc(ProcTextureInit &init)
{
int noizeSize = 128;
const int size = 4 * noizeSize * noizeSize;
unsigned char* noise = new unsigned char[size];
for (int i = 0; i < size; i += 4 ) {
unsigned char n = (unsigned char)floor(256.0 * bzfrand());
noise[i+0] = n;
noise[i+1] = n;
noise[i+2] = n;
noise[i+3] = n;
}
int texture = init.manager->newTexture(init.name.c_str(), noizeSize, noizeSize, noise, init.filter);
delete[] noise;
return texture;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>remove useless checks<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 COPYING 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.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif
// interface headers
#include "TextureManager.h"
// system headers
#include <vector>
#include <string>
// common implementation headers
#include "TextUtils.h"
#include "global.h"
#include "MediaFile.h"
#include "ErrorHandler.h"
#include "OSFile.h"
/*const int NO_VARIANT = (-1); */
// initialize the singleton
template <>
TextureManager* Singleton<TextureManager>::_instance = (TextureManager*)0;
static int noiseProc(ProcTextureInit &init);
ProcTextureInit procLoader[1];
TextureManager::TextureManager()
{
configFilterValues[Off] = "no";
configFilterValues[Nearest] = "nearest";
configFilterValues[Linear] = "linear";
configFilterValues[NearestMipmapNearest] = "nearestmipmapnearest";
configFilterValues[LinearMipmapNearest] = "linearmipmapnearest";
configFilterValues[NearestMipmapLinear] = "nearestmipmaplinear";
configFilterValues[LinearMipmapLinear] = "linearmipmaplinear";
// init the default filter methods
currentMaxFilter = Max;
// fill out the standard proc textures
procLoader[0].name = "noise";
procLoader[0].filter = Nearest;
procLoader[0].proc = noiseProc;
lastImageID = -1;
lastBoundID = -1;
int i, numTextures;
numTextures = countof(procLoader);
for (i = 0; i < numTextures; i++) {
procLoader[i].manager = this;
procLoader[i].proc(procLoader[i]);
}
}
TextureManager::~TextureManager()
{
// we are done remove all textures
for (TextureNameMap::iterator it = textureNames.begin(); it != textureNames.end(); ++it) {
ImageInfo &tex = it->second;
if (tex.texture != NULL) {
delete tex.texture;
}
}
textureNames.clear();
textureIDs.clear();
}
int TextureManager::getTextureID( const char* name, bool reportFail )
{
if (!name) {
DEBUG2("Could not get texture ID; no provided name\n");
return -1;
}
OSFile osFilename(name);
std::string texName = osFilename.getOSName();
// see if we have the texture
TextureNameMap::iterator it = textureNames.find(texName);
if (it != textureNames.end()) {
return it->second.id;
} else { // we don't have it so try and load it
FileTextureInit file;
file.filter = LinearMipmapLinear;
file.name = texName;
ImageInfo info;
OpenGLTexture *image = loadTexture(file, reportFail);
if (!image) {
DEBUG2("Image not found or unloadable: %s\n", name);
return -1;
}
return addTexture(name, image);
}
return -1;
}
bool TextureManager::bind ( int id )
{
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end()) {
DEBUG1("Unable to bind texture (by id): %d\n", id);
return false;
}
if (id != lastBoundID) {
it->second->texture->execute();
lastBoundID = id;
}
return true;
}
bool TextureManager::bind ( const char* name )
{
std::string nameStr = name;
TextureNameMap::iterator it = textureNames.find(nameStr);
if (it == textureNames.end()) {
DEBUG1("Unable to bind texture (by name): %s\n", name);
return false;
}
int id = it->second.id;
if (id != lastBoundID) {
it->second.texture->execute();
lastBoundID = id;
}
return true;
}
std::string TextureManager::getMaxFilterName ( void )
{
return configFilterValues[static_cast<int>(currentMaxFilter)];
}
void TextureManager::setMaxFilter ( std::string filter )
{
eTextureFilter realFilter = Max;
for (int i = 0; i < (int)Max; i++) {
if (filter == configFilterValues[i])
realFilter = (eTextureFilter)i;
}
setMaxFilter(realFilter);
}
void TextureManager::setMaxFilter ( eTextureFilter filter )
{
currentMaxFilter = filter;
// flush all the textures so they get rebuilt on next use
TextureNameMap::iterator itr = textureNames.begin();
while (itr != textureNames.end()) {
FileTextureInit fileInit;
fileInit.filter = currentMaxFilter;
fileInit.name = itr->second.name;
OpenGLTexture *newTexture = loadTexture(fileInit, false);
delete(itr->second.texture);
itr->second.texture = newTexture;
itr++;
}
// rebuild proc textures
for (int i = 0; i < (int)countof(procLoader); i++) {
procLoader[i].manager = this;
procLoader[i].proc(procLoader[i]);
}
}
float TextureManager::GetAspectRatio ( int id )
{
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return 0.0;
return (float)it->second->y/(float)it->second->x;
}
const ImageInfo& TextureManager::getInfo ( int id )
{
static ImageInfo crapInfo;
crapInfo.id = -1;
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return crapInfo;
return *(it->second);
}
const ImageInfo& TextureManager::getInfo ( const char* name )
{
static ImageInfo crapInfo;
crapInfo.id = -1;
std::string nameStr = name;
TextureNameMap::iterator it = textureNames.find(nameStr);
if (it == textureNames.end())
return crapInfo;
return it->second;
}
int TextureManager::addTexture( const char* name, OpenGLTexture *texture )
{
if (!name || !texture)
return -1;
// if the texture already exists kill it
// this is why IDs are way better than objects for this stuff
TextureNameMap::iterator it = textureNames.find(name);
if (it != textureNames.end()) {
DEBUG3("Texture %s already exists, overwriting\n", name);
textureIDs.erase(textureIDs.find(it->second.id));
delete it->second.texture;
}
ImageInfo info;
info.name = name;
info.texture = texture;
info.id = ++lastImageID;
info.alpha = texture->hasAlpha();
info.x = texture->getWidth();
info.y = texture->getHeight();
textureNames[name] = info;
textureIDs[info.id] = &textureNames[name];
DEBUG4("Added texture %s: id %d\n", name, info.id);
return info.id;
}
OpenGLTexture* TextureManager::loadTexture(FileTextureInit &init, bool reportFail)
{
int width, height;
unsigned char* image = MediaFile::readImage(init.name, &width, &height);
if (!image) {
if (reportFail) {
std::vector<std::string> args;
args.push_back(init.name);
printError("cannot load texture: {1}", &args);
}
return NULL;
}
OpenGLTexture::Filter RealFilter;
if (init.filter > currentMaxFilter)
RealFilter = (OpenGLTexture::Filter)currentMaxFilter;
else
RealFilter = (OpenGLTexture::Filter)init.filter;
OpenGLTexture *texture = new OpenGLTexture(width, height, image, RealFilter, true);
delete[] image;
return texture;
}
int TextureManager::newTexture(const char* name, int x, int y, unsigned char* data, eTextureFilter filter, bool repeat, int format)
{
OpenGLTexture::Filter RealFilter;
if (filter > currentMaxFilter)
RealFilter = (OpenGLTexture::Filter)currentMaxFilter;
else
RealFilter = (OpenGLTexture::Filter)filter;
return addTexture(name, new OpenGLTexture(x, y, data, RealFilter, repeat, format));
}
/* --- Procs --- */
int noiseProc(ProcTextureInit &init)
{
int noizeSize = 128;
const int size = 4 * noizeSize * noizeSize;
unsigned char* noise = new unsigned char[size];
for (int i = 0; i < size; i += 4 ) {
unsigned char n = (unsigned char)floor(256.0 * bzfrand());
noise[i+0] = n;
noise[i+1] = n;
noise[i+2] = n;
noise[i+3] = n;
}
int texture = init.manager->newTexture(init.name.c_str(), noizeSize, noizeSize, noise, init.filter);
delete[] noise;
return texture;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/compiler/generate/t_generator.h>
#include <thrift/compiler/generate/t_mstch_generator.h>
using namespace std;
namespace apache {
namespace thrift {
namespace compiler {
void t_generator_registry::register_generator(t_generator_factory* factory) {
gen_map_t& the_map = get_generator_map();
if (the_map.find(factory->get_short_name()) != the_map.end()) {
failure(
"Duplicate generators for language \"%s\"!\n",
factory->get_short_name().c_str());
}
the_map[factory->get_short_name()] = factory;
}
t_generator* t_generator_registry::get_generator(
t_program* program,
t_generation_context context,
const string& options) {
string::size_type colon = options.find(':');
string language = options.substr(0, colon);
map<string, string> parsed_options;
if (colon != string::npos) {
string::size_type pos = colon + 1;
while (pos != string::npos && pos < options.size()) {
string::size_type next_pos = options.find(',', pos);
string option = options.substr(pos, next_pos - pos);
pos = ((next_pos == string::npos) ? next_pos : next_pos + 1);
string::size_type separator = option.find('=');
string key, value;
if (separator == string::npos) {
key = option;
value = "";
} else {
key = option.substr(0, separator);
value = option.substr(separator + 1);
}
parsed_options[key] = value;
}
}
gen_map_t& the_map = get_generator_map();
gen_map_t::iterator iter = the_map.find(language);
if (iter == the_map.end()) {
return nullptr;
}
return iter->second->get_generator(program, context, parsed_options, options);
}
t_generator_registry::gen_map_t& t_generator_registry::get_generator_map() {
// http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12
static gen_map_t* the_map = new gen_map_t();
return *the_map;
}
t_generator_factory::t_generator_factory(
const std::string& short_name,
const std::string& long_name,
const std::string& documentation)
: short_name_(short_name),
long_name_(long_name),
documentation_(documentation) {
t_generator_registry::register_generator(this);
}
} // namespace compiler
} // namespace thrift
} // namespace apache
<commit_msg>remove unused includes<commit_after>/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/compiler/generate/t_generator.h>
using namespace std;
namespace apache {
namespace thrift {
namespace compiler {
void t_generator_registry::register_generator(t_generator_factory* factory) {
gen_map_t& the_map = get_generator_map();
if (the_map.find(factory->get_short_name()) != the_map.end()) {
failure(
"Duplicate generators for language \"%s\"!\n",
factory->get_short_name().c_str());
}
the_map[factory->get_short_name()] = factory;
}
t_generator* t_generator_registry::get_generator(
t_program* program,
t_generation_context context,
const string& options) {
string::size_type colon = options.find(':');
string language = options.substr(0, colon);
map<string, string> parsed_options;
if (colon != string::npos) {
string::size_type pos = colon + 1;
while (pos != string::npos && pos < options.size()) {
string::size_type next_pos = options.find(',', pos);
string option = options.substr(pos, next_pos - pos);
pos = ((next_pos == string::npos) ? next_pos : next_pos + 1);
string::size_type separator = option.find('=');
string key, value;
if (separator == string::npos) {
key = option;
value = "";
} else {
key = option.substr(0, separator);
value = option.substr(separator + 1);
}
parsed_options[key] = value;
}
}
gen_map_t& the_map = get_generator_map();
gen_map_t::iterator iter = the_map.find(language);
if (iter == the_map.end()) {
return nullptr;
}
return iter->second->get_generator(program, context, parsed_options, options);
}
t_generator_registry::gen_map_t& t_generator_registry::get_generator_map() {
// http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12
static gen_map_t* the_map = new gen_map_t();
return *the_map;
}
t_generator_factory::t_generator_factory(
const std::string& short_name,
const std::string& long_name,
const std::string& documentation)
: short_name_(short_name),
long_name_(long_name),
documentation_(documentation) {
t_generator_registry::register_generator(this);
}
} // namespace compiler
} // namespace thrift
} // namespace apache
<|endoftext|>
|
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "streamed_value_index.h"
#include "streamed_value_utils.h"
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/visit_ranges.h>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.tensor.streamed_value_index");
namespace vespalib::eval {
namespace {
struct StreamedFilterView : Value::Index::View
{
LabelBlockStream label_blocks;
std::vector<size_t> view_dims;
std::vector<vespalib::stringref> to_match;
StreamedFilterView(LabelBlockStream labels, std::vector<size_t> view_dims_in)
: label_blocks(std::move(labels)),
view_dims(std::move(view_dims_in)),
to_match()
{
to_match.reserve(view_dims.size());
}
void lookup(ConstArrayRef<const vespalib::stringref*> addr) override {
label_blocks.reset();
to_match.clear();
for (auto ptr : addr) {
to_match.push_back(*ptr);
}
assert(view_dims.size() == to_match.size());
}
bool next_result(ConstArrayRef<vespalib::stringref*> addr_out, size_t &idx_out) override {
while (const auto block = label_blocks.next_block()) {
idx_out = block.ss_idx;
bool matches = true;
size_t out_idx = 0;
size_t vdm_idx = 0;
for (size_t dim = 0; dim < block.address.size(); ++dim) {
if (vdm_idx < view_dims.size() && (view_dims[vdm_idx] == dim)) {
if (block.address[dim] != to_match[vdm_idx]) {
matches = false;
}
++vdm_idx;
} else {
*addr_out[out_idx++] = block.address[dim];
}
}
assert(out_idx == addr_out.size());
assert(vdm_idx == view_dims.size());
if (matches) return true;
}
return false;
}
};
struct StreamedIterationView : Value::Index::View
{
LabelBlockStream label_blocks;
StreamedIterationView(LabelBlockStream labels)
: label_blocks(std::move(labels))
{}
void lookup(ConstArrayRef<const vespalib::stringref*> addr) override {
label_blocks.reset();
assert(addr.size() == 0);
}
bool next_result(ConstArrayRef<vespalib::stringref*> addr_out, size_t &idx_out) override {
if (auto block = label_blocks.next_block()) {
idx_out = block.ss_idx;
size_t i = 0;
for (auto ptr : addr_out) {
*ptr = block.address[i++];
}
assert(i == block.address.size());
return true;
}
return false;
}
};
} // namespace <unnamed>
std::unique_ptr<Value::Index::View>
StreamedValueIndex::create_view(const std::vector<size_t> &dims) const
{
LabelBlockStream label_stream(_data.num_subspaces, _data.labels_buffer, _data.num_mapped_dims);
if (dims.empty()) {
return std::make_unique<StreamedIterationView>(std::move(label_stream));
}
return std::make_unique<StreamedFilterView>(std::move(label_stream), dims);
}
} // namespace vespalib::eval
<commit_msg>more elegant filter; move assert earlier<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "streamed_value_index.h"
#include "streamed_value_utils.h"
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/visit_ranges.h>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.tensor.streamed_value_index");
namespace vespalib::eval {
namespace {
struct StreamedFilterView : Value::Index::View
{
LabelBlockStream label_blocks;
std::vector<size_t> view_dims;
std::vector<vespalib::stringref> to_match;
StreamedFilterView(LabelBlockStream labels, std::vector<size_t> view_dims_in)
: label_blocks(std::move(labels)),
view_dims(std::move(view_dims_in)),
to_match()
{
to_match.reserve(view_dims.size());
}
void lookup(ConstArrayRef<const vespalib::stringref*> addr) override {
label_blocks.reset();
to_match.clear();
for (auto ptr : addr) {
to_match.push_back(*ptr);
}
assert(view_dims.size() == to_match.size());
}
bool next_result(ConstArrayRef<vespalib::stringref*> addr_out, size_t &idx_out) override {
while (const auto block = label_blocks.next_block()) {
idx_out = block.ss_idx;
bool matches = true;
size_t out_idx = 0;
size_t vdm_idx = 0;
for (size_t dim = 0; dim < block.address.size(); ++dim) {
if (vdm_idx < view_dims.size() && (view_dims[vdm_idx] == dim)) {
matches &= (block.address[dim] == to_match[vdm_idx++]);
} else {
*addr_out[out_idx++] = block.address[dim];
}
}
assert(out_idx == addr_out.size());
assert(vdm_idx == view_dims.size());
if (matches) return true;
}
return false;
}
};
struct StreamedIterationView : Value::Index::View
{
LabelBlockStream label_blocks;
StreamedIterationView(LabelBlockStream labels)
: label_blocks(std::move(labels))
{}
void lookup(ConstArrayRef<const vespalib::stringref*> addr) override {
label_blocks.reset();
assert(addr.size() == 0);
}
bool next_result(ConstArrayRef<vespalib::stringref*> addr_out, size_t &idx_out) override {
if (auto block = label_blocks.next_block()) {
idx_out = block.ss_idx;
size_t i = 0;
assert(addr_out.size() == block.address.size());
for (auto ptr : addr_out) {
*ptr = block.address[i++];
}
return true;
}
return false;
}
};
} // namespace <unnamed>
std::unique_ptr<Value::Index::View>
StreamedValueIndex::create_view(const std::vector<size_t> &dims) const
{
LabelBlockStream label_stream(_data.num_subspaces, _data.labels_buffer, _data.num_mapped_dims);
if (dims.empty()) {
return std::make_unique<StreamedIterationView>(std::move(label_stream));
}
return std::make_unique<StreamedFilterView>(std::move(label_stream), dims);
}
} // namespace vespalib::eval
<|endoftext|>
|
<commit_before>/*
* Stateplex - A server-side actor model library.
*
* net/hbdpconnection.cpp
*
* (c) 2013 Henrik Hedberg <henrik.hedberg@innologies.fi>
*
* 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.
*
* Authors: Henrik Hedberg
*/
#include "hbdpconnection.h"
namespace Stateplex {
bool HbdpConnection::HbdpRequest::receiveHeader(Buffer<> *name, Buffer<> *value)
{
return true;
}
bool HbdpConnection::HbdpRequest::receiveData(Buffer<> *data)
{
mHbdpConnection->receiveData(data);
return true;
}
void HbdpConnection::HbdpRequest::receiveEnd()
{
mHbdpConnection->handleEnd();
}
void HbdpConnection::HbdpRequest::receiveAbort()
{
// TODO: Handle failure.
}
HbdpConnection::HbdpRequest::HbdpRequest(HttpConnection *httpConnection, HbdpConnection *hbdpConnection)
: HttpRequest(httpConnection), mHbdpConnection(hbdpConnection)
{ }
HttpRequest *HbdpConnection::instantiateHttpRequest(const HttpRequest::Embryo *embryo, Size serialNumber)
{
if (mSerialNumber != serialNumber) {
return new SimpleHttpRequest(embryo->httpConnection, "410 Gone");
}
mSerialNumber++;
if (mHbdpRequest)
endRequest();
mHbdpRequest = new HbdpRequest(embryo->httpConnection, this);
}
void HbdpConnection::handleEnd()
{
if (mOut.length() > 0) {
mHbdpRequest->sendData(&mOut);
mOut.poppedAll();
endRequest();
}
}
void HbdpConnection::endRequest() {
mHbdpRequest->sendEnd();
delete mHbdpRequest;
mHbdpRequest = 0;
}
void HbdpConnection::close()
{
// TODO
}
HbdpServer *HbdpConnection::hbdpServer() const
{
return mHbdpServer;
}
void HbdpConnection::write(Buffer<> *data)
{
if (!mHbdpRequest) {
mOut.append(data);
return;
}
mHbdpRequest->sendData(data);
endRequest();
}
void HbdpConnection::write(const String *data)
{
if (!mHbdpRequest) {
mOut.append(data);
return;
}
mHbdpRequest->sendData(data->chars(), data->length());
endRequest();
}
void HbdpConnection::write(const char *data, Size dataLength)
{
if (!mHbdpRequest) {
mOut.append(data);
return;
}
mHbdpRequest->sendData(data, dataLength);
endRequest();
}
}
<commit_msg>HbdpConnection: fixed instantiateHttpRequest()<commit_after>/*
* Stateplex - A server-side actor model library.
*
* net/hbdpconnection.cpp
*
* (c) 2013 Henrik Hedberg <henrik.hedberg@innologies.fi>
*
* 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.
*
* Authors: Henrik Hedberg
*/
#include "hbdpconnection.h"
namespace Stateplex {
bool HbdpConnection::HbdpRequest::receiveHeader(Buffer<> *name, Buffer<> *value)
{
return true;
}
bool HbdpConnection::HbdpRequest::receiveData(Buffer<> *data)
{
mHbdpConnection->receiveData(data);
return true;
}
void HbdpConnection::HbdpRequest::receiveEnd()
{
mHbdpConnection->handleEnd();
}
void HbdpConnection::HbdpRequest::receiveAbort()
{
// TODO: Handle failure.
}
HbdpConnection::HbdpRequest::HbdpRequest(HttpConnection *httpConnection, HbdpConnection *hbdpConnection)
: HttpRequest(httpConnection), mHbdpConnection(hbdpConnection)
{ }
HttpRequest *HbdpConnection::instantiateHttpRequest(const HttpRequest::Embryo *embryo, Size serialNumber)
{
if (mSerialNumber != serialNumber) {
return new SimpleHttpRequest(embryo->httpConnection, "410 Gone");
}
mSerialNumber++;
if (mHbdpRequest)
endRequest();
mHbdpRequest = new HbdpRequest(embryo->httpConnection, this);
return mHbdpRequest;
}
void HbdpConnection::handleEnd()
{
if (mOut.length() > 0) {
mHbdpRequest->sendData(&mOut);
mOut.poppedAll();
endRequest();
}
}
void HbdpConnection::endRequest() {
mHbdpRequest->sendEnd();
delete mHbdpRequest;
mHbdpRequest = 0;
}
void HbdpConnection::close()
{
// TODO
}
HbdpServer *HbdpConnection::hbdpServer() const
{
return mHbdpServer;
}
void HbdpConnection::write(Buffer<> *data)
{
if (!mHbdpRequest) {
mOut.append(data);
return;
}
mHbdpRequest->sendData(data);
endRequest();
}
void HbdpConnection::write(const String *data)
{
if (!mHbdpRequest) {
mOut.append(data);
return;
}
mHbdpRequest->sendData(data->chars(), data->length());
endRequest();
}
void HbdpConnection::write(const char *data, Size dataLength)
{
if (!mHbdpRequest) {
mOut.append(data);
return;
}
mHbdpRequest->sendData(data, dataLength);
endRequest();
}
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <fstream>
#include <streambuf>
#include "const.hpp"
#include "util.hpp"
#include "printer.hpp"
#include "ram.hpp"
#include "cpu.hpp"
#include "renderer.hpp"
using namespace std;
extern "C" {
void setEnvironment();
void setOutput();
void printCharXY(char c, int x, int y);
void printString(const char s[], int x, int y);
typedef void (*callback_function)(void);
void redrawScreen(callback_function draw);
void resetEnvironment();
}
// const int WORD_SIZE = 8;
// const int ADDR_SIZE = 4;
// const int RAM_SIZE = ADDR_SIZE*ADDR_SIZE-1;
bool debug = true;
int ROWS = 25;
bool automatic = true;
int fq = 300;
string TEST_FILE = "/fibbBin";
std::ifstream testStream(TEST_FILE);
std::string testString((std::istreambuf_iterator<char>(testStream)),
std::istreambuf_iterator<char>());
Printer printer;
Ram ram;
Cpu cpu;
/*
* PRINTER
*/
void Printer::print(string sIn) {
output += sIn;
printerOutputUpdated = false;
}
string Printer::getOutput() {
return output;
}
string Printer::getPrinterOutput() {
if (!printerOutputUpdated) {
printerOutput = renderPrinterOutput();
printerOutputUpdated = true;
}
return printerOutput;
}
void Printer::clear() {
output = "";
printerOutputUpdated = false;
}
string Printer::renderPrinterOutput() {
if (output.length() <= 0) {
return "|0|______________|0|";
}
vector<string> outputLines = Util::splitString(output);
reverse(outputLines.begin(), outputLines.end());
for (string line : outputLines) {
line = "|0| " + line + " |0|";
}
outputLines.push_back("|0|______________|0|");
return Util::makeString(outputLines);
}
/*
* RAM
*/
vector<bool> Ram::get(vector<bool> adr) {
int address = Util::getInt(adr);
// return random if last address (reserved for output)
if (address == RAM_SIZE-1) {
vector<bool> wordOut = Util::getRandomWord();
return wordOut;
}
vector<bool> wordOut(WORD_SIZE);
for (int i = 0; i < WORD_SIZE; i++) {
wordOut[i] = state[address][i];
}
return wordOut;
}
void Ram::set(vector<bool> adr, vector<bool> wordIn) {
int address = Util::getInt(adr);
if (address < RAM_SIZE) {
for (int i = 0; i < WORD_SIZE; i++) {
state[address][i] = wordIn[i];
}
} else {
char formatedInt [10];
sprintf(formatedInt, "%3d", Util::getInt(wordIn));
string outputLine = Util::getString(wordIn) + " " + formatedInt + "\n";
printer.print(outputLine);
if (!debug) {
cout << outputLine;
}
}
}
const bool CANONICAL = false;
const int RAM_X = 7;
const int RAM_Y = 5;
int cursorX = 0;
int cursorY = 0;
vector<string> buffer;
void highlightCursor(bool highlight) {
char c;
try {
c = buffer.at(cursorY+RAM_Y).at(cursorX+RAM_X);
} catch (int e) {
cout << "Cursor out of bounds. Exception Nr. " << e << '\n';
return;
}
if (highlight) {
printf("\e[%dm\e[%dm", 30, 47);
} else {
printf("\e[%dm\e[%dm", 37, 40);
}
printCharXY(c, cursorX+RAM_X, cursorY+RAM_Y);
}
void switchBit() {
ram.state.at(cursorY).at(cursorX) = !ram.state.at(cursorY).at(cursorX);
string out = Renderer::renderState(printer, ram, cpu);
buffer = Util::splitString(out);
}
void userInput() {
while(1) {
char c = getc(stdin);
highlightCursor(false);
switch (c) {
case 65: // up
if (cursorY > 0) {
cursorY--;
}
break;
case 66: // down
if (cursorY < RAM_SIZE-1) {
cursorY++;
}
break;
case 67: // right
if (cursorX < WORD_SIZE-1) {
cursorX++;
}
break;
case 68: // left
if (cursorX > 0) {
cursorX--;
}
break;
case 32: // space
switchBit();
break;
case 10: // enter
cpu.exec();
getc(stdin);
break;
}
highlightCursor(true);
}
}
void drawScreen() {
string out = Renderer::renderState(printer, ram, cpu);
buffer = Util::splitString(out);
int i = 0;
for (string line : buffer) {
printString(line.c_str(), 0, i++);
}
}
/*
* CPU
*/
void Cpu::exec() {
if (Util::getInt(pc) >= RAM_SIZE) {
exit(0);
}
vector<bool> tmp = ram.get(pc);
vector<bool> instruction = Util::getFirstNibble(tmp);
vector<bool> adr = Util::getSecondNibble(tmp);
if (debug) {
redrawScreen(&drawScreen);
if (automatic) {
usleep(fq*1000);
} else {
getchar();
}
}
int instCode = Util::getInt(instruction);
switch (instCode) {
case 0:
read(adr);
break;
case 1:
write(adr);
break;
case 2:
add(adr);
break;
case 3:
sub(adr);
break;
case 4:
jump(adr);
break;
case 5:
readPointer(adr);
break;
case 6:
jumpIf(adr);
break;
case 7:
jumpIfSmaller(adr);
break;
default:
read(adr);
}
cycle++;
exec();
}
// TODO check if safe!!!
vector<bool> Cpu::getReg() {
return reg;
}
vector<bool> Cpu::getPc() {
return pc;
}
void Cpu::increasePc() {
pc = Util::getBoolNibb(Util::getInt(pc) + 1);
}
void Cpu::read(vector<bool> adr) {
reg = ram.get(adr);
increasePc();
}
void Cpu::write(vector<bool> adr) {
ram.set(adr, reg);
increasePc();
}
void Cpu::add(vector<bool> adr) {
reg = Util::getBoolByte(Util::getInt(reg) + Util::getInt(adr));
increasePc();
}
void Cpu::sub(vector<bool> adr) {
reg = Util::getBoolByte(Util::getInt(reg) - Util::getInt(adr));
increasePc();
}
void Cpu::jump(vector<bool> adr) {
pc = adr;
}
void Cpu::readPointer(vector<bool> adr) {
reg = ram.get(Util::getSecondNibble(reg));
increasePc();
}
void Cpu::jumpIf(vector<bool> adr) {
if (Util::getInt(reg) >= 127) {
pc = adr;
} else {
increasePc();
}
}
void Cpu::jumpIfSmaller(vector<bool> adr) {
if (Util::getInt(reg) >= 127) {
pc = adr;
} else {
increasePc();
}
}
/*
* MAIN
*/
int main(int argc, const char* argv[]) {
setEnvironment();
setOutput();
ram.state = Util::getRamFromString(testString);
redrawScreen(&drawScreen);
userInput();
}
<commit_msg>fixed one off bug with random<commit_after>#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <fstream>
#include <streambuf>
#include "const.hpp"
#include "util.hpp"
#include "printer.hpp"
#include "ram.hpp"
#include "cpu.hpp"
#include "renderer.hpp"
using namespace std;
extern "C" {
void setEnvironment();
void setOutput();
void printCharXY(char c, int x, int y);
void printString(const char s[], int x, int y);
typedef void (*callback_function)(void);
void redrawScreen(callback_function draw);
void resetEnvironment();
}
// const int WORD_SIZE = 8;
// const int ADDR_SIZE = 4;
// const int RAM_SIZE = ADDR_SIZE*ADDR_SIZE-1;
bool debug = true;
int ROWS = 25;
bool automatic = true;
int fq = 300;
string TEST_FILE = "/fibbBin";
std::ifstream testStream(TEST_FILE);
std::string testString((std::istreambuf_iterator<char>(testStream)),
std::istreambuf_iterator<char>());
Printer printer;
Ram ram;
Cpu cpu;
/*
* PRINTER
*/
void Printer::print(string sIn) {
output += sIn;
printerOutputUpdated = false;
}
string Printer::getOutput() {
return output;
}
string Printer::getPrinterOutput() {
if (!printerOutputUpdated) {
printerOutput = renderPrinterOutput();
printerOutputUpdated = true;
}
return printerOutput;
}
void Printer::clear() {
output = "";
printerOutputUpdated = false;
}
string Printer::renderPrinterOutput() {
if (output.length() <= 0) {
return "|0|______________|0|";
}
vector<string> outputLines = Util::splitString(output);
reverse(outputLines.begin(), outputLines.end());
for (string line : outputLines) {
line = "|0| " + line + " |0|";
}
outputLines.push_back("|0|______________|0|");
return Util::makeString(outputLines);
}
/*
* RAM
*/
vector<bool> Ram::get(vector<bool> adr) {
int address = Util::getInt(adr);
// return random if last address (reserved for output)
if (address == RAM_SIZE) {
vector<bool> wordOut = Util::getRandomWord();
return wordOut;
}
vector<bool> wordOut(WORD_SIZE);
for (int i = 0; i < WORD_SIZE; i++) {
wordOut[i] = state[address][i];
}
return wordOut;
}
void Ram::set(vector<bool> adr, vector<bool> wordIn) {
int address = Util::getInt(adr);
// Save word
if (address < RAM_SIZE) {
for (int i = 0; i < WORD_SIZE; i++) {
state[address][i] = wordIn[i];
}
// Send word to printer
} else {
char formatedInt [10];
sprintf(formatedInt, "%3d", Util::getInt(wordIn));
string outputLine = Util::getString(wordIn) + " " + formatedInt + "\n";
printer.print(outputLine);
if (!debug) {
cout << outputLine;
}
}
}
const int RAM_X = 7;
const int RAM_Y = 5;
int cursorX = 0;
int cursorY = 0;
vector<string> buffer;
void highlightCursor(bool highlight) {
char c;
try {
c = buffer.at(cursorY+RAM_Y).at(cursorX+RAM_X);
} catch (int e) {
cout << "Cursor out of bounds. Exception Nr. " << e << '\n';
return;
}
if (highlight) {
printf("\e[%dm\e[%dm", 30, 47);
} else {
printf("\e[%dm\e[%dm", 37, 40);
}
printCharXY(c, cursorX+RAM_X, cursorY+RAM_Y);
}
void switchBit() {
ram.state.at(cursorY).at(cursorX) = !ram.state.at(cursorY).at(cursorX);
string out = Renderer::renderState(printer, ram, cpu);
buffer = Util::splitString(out);
}
void userInput() {
while(1) {
char c = getc(stdin);
highlightCursor(false);
switch (c) {
case 65: // up
if (cursorY > 0) {
cursorY--;
}
break;
case 66: // down
if (cursorY < RAM_SIZE-1) {
cursorY++;
}
break;
case 67: // right
if (cursorX < WORD_SIZE-1) {
cursorX++;
}
break;
case 68: // left
if (cursorX > 0) {
cursorX--;
}
break;
case 32: // space
switchBit();
break;
case 10: // enter
cpu.exec();
getc(stdin);
ram = Ram();
cpu = Cpu();
break;
}
highlightCursor(true);
}
}
void drawScreen() {
string out = Renderer::renderState(printer, ram, cpu);
buffer = Util::splitString(out);
int i = 0;
for (string line : buffer) {
printString(line.c_str(), 0, i++);
}
}
/*
* CPU
*/
void Cpu::exec() {
if (Util::getInt(pc) >= RAM_SIZE) {
return;
}
vector<bool> tmp = ram.get(pc);
vector<bool> instruction = Util::getFirstNibble(tmp);
vector<bool> adr = Util::getSecondNibble(tmp);
if (debug) {
redrawScreen(&drawScreen);
if (automatic) {
usleep(fq*1000);
} else {
getchar();
}
}
int instCode = Util::getInt(instruction);
switch (instCode) {
case 0:
read(adr);
break;
case 1:
write(adr);
break;
case 2:
add(adr);
break;
case 3:
sub(adr);
break;
case 4:
jump(adr);
break;
case 5:
readPointer(adr);
break;
case 6:
jumpIf(adr);
break;
case 7:
jumpIfSmaller(adr);
break;
default:
read(adr);
}
cycle++;
exec();
}
// TODO check if safe!!!
vector<bool> Cpu::getReg() {
return reg;
}
vector<bool> Cpu::getPc() {
return pc;
}
void Cpu::increasePc() {
pc = Util::getBoolNibb(Util::getInt(pc) + 1);
}
void Cpu::read(vector<bool> adr) {
reg = ram.get(adr);
increasePc();
}
void Cpu::write(vector<bool> adr) {
ram.set(adr, reg);
increasePc();
}
void Cpu::add(vector<bool> adr) {
reg = Util::getBoolByte(Util::getInt(reg) + Util::getInt(adr));
increasePc();
}
void Cpu::sub(vector<bool> adr) {
reg = Util::getBoolByte(Util::getInt(reg) - Util::getInt(adr));
increasePc();
}
void Cpu::jump(vector<bool> adr) {
pc = adr;
}
void Cpu::readPointer(vector<bool> adr) {
reg = ram.get(Util::getSecondNibble(reg));
increasePc();
}
void Cpu::jumpIf(vector<bool> adr) {
if (Util::getInt(reg) >= 127) {
pc = adr;
} else {
increasePc();
}
}
void Cpu::jumpIfSmaller(vector<bool> adr) {
if (Util::getInt(reg) >= 127) {
pc = adr;
} else {
increasePc();
}
}
/*
* MAIN
*/
int main(int argc, const char* argv[]) {
setEnvironment();
setOutput();
ram.state = Util::getRamFromString(testString);
redrawScreen(&drawScreen);
userInput();
}
<|endoftext|>
|
<commit_before>#include <gui/cursesui.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#define CMD_PROMPT "cmd: "
cursesui::cursesui(){
/* init ncurses */
setlocale(LC_ALL, "");
initscr();
noecho();
/* init class members */
nwin = 0;
max_win = 2;
windows = (window_t**)malloc(sizeof(window_t*) * max_win);
if(windows == 0)
goto err_0;
memset(windows, 0x0, sizeof(window_t*) * max_win);
pthread_mutex_init(&mutex, 0);
line_len = 255;
line = (char*)malloc(line_len * sizeof(char));
if(line == 0)
goto err_1;
return;
term = new tty;
if(term == 0)
goto err_2;
constructor_ok = true;
return;
err_2:
free(line);
err_1:
free(windows);
err_0:
constructor_ok = false;
}
cursesui::~cursesui(){
unsigned int i;
/* free allocated windows */
for(i=0; i<max_win; i++){
if(windows[i] == 0)
continue;
delwin(windows[i]->win);
delwin(windows[i]->frame);
free(windows[i]);
}
free(windows);
/* stop ncurses */
endwin();
}
/**
* \brief read user input from gui
*
* \return != 0 pointer to line
* 0 error
*/
char* cursesui::readline(){
char c;
unsigned int i;
if(line == 0 || term == 0)
return 0;
i = 0;
print(WIN_CMD, CMD_PROMPT);
while(1){
term->read(&c, 1);
if(c == '\n' || c == '\r'){
line[i] = 0;
print(WIN_CMD, "\n");
return line;
}
else if(c == 127){
if(i <= 0)
continue;
line[--i] = 0;
clearline(WIN_CMD);
print(WIN_CMD, CMD_PROMPT "%s", line);
}
else{
print(WIN_CMD, "%c", c);
line[i++] = c;
if(i >= line_len){
line_len *= 2;
line = (char*)realloc(line, line_len);
if(line == 0)
return 0;
}
}
}
}
/**
* \brief create new cursesui window
*
* \param title window title
* \param oneline if true, the window width is maximised
*
* \return >=0 window id
* <0 error
*/
int cursesui::win_create(const char* title, bool oneline, unsigned int height){
int i, id;
/* realloc if now enough space to store windows */
if(nwin + 1 > max_win){
windows = (window_t**)realloc(windows, sizeof(window_t*) * max_win * 2);
memset(windows + max_win, 0x0, sizeof(window_t*) * max_win);
max_win *= 2;
}
/* search free id */
id = -1;
for(i=0; i<max_win; i++){
if(windows[i] == 0){
id = i;
break;
}
}
if(id == -1)
return -1;
/* allocated cursesui window */
windows[id] = new window_t;
windows[id]->win = newwin(2, 2, 0, 0); // arbitrary width and height, final
windows[id]->frame = newwin(2, 2, 0, 0); // values are set in win_resize()
windows[id]->title = (char*)title;
windows[id]->oneline = (height > 0) ? true : oneline;
windows[id]->height = height;
scrollok(windows[id]->win, true); // enable auto-scroll
nwin++;
/* update size of all windows */
if(win_resize() < 0){
win_destroy(id);
return -1;
}
return id;
}
int cursesui::win_destroy(int win_id){
if(win_id >= max_win || windows[win_id] == 0)
return -1;
/* de-init window and free memory */
delwin(windows[win_id]->win);
delwin(windows[win_id]->frame);
free(windows[win_id]);
windows[win_id] = 0;
nwin--;
/* update screen */
win_resize();
return 0;
}
void cursesui::win_write(int win_id, const char* fmt, ...){
va_list lst;
va_start(lst, fmt);
win_vwrite(win_id, fmt, lst);
va_end(lst);
}
void cursesui::win_vwrite(int win_id, const char* fmt, va_list lst){
pthread_mutex_lock(&mutex);
vwprintw(windows[win_id]->win, fmt, lst);
wrefresh(windows[win_id]->win);
pthread_mutex_unlock(&mutex);
}
void cursesui::win_clear(int win_id){
pthread_mutex_lock(&mutex);
wclear(windows[win_id]->win);
wrefresh(windows[win_id]->win);
pthread_mutex_unlock(&mutex);
}
void cursesui::win_clrline(int win_id){
int x, y;
pthread_mutex_lock(&mutex);
getyx(windows[win_id]->win, y, x);
wmove(windows[win_id]->win, y, 0);
wclrtoeol(windows[win_id]->win);
wrefresh(windows[win_id]->win);
pthread_mutex_unlock(&mutex);
}
/**
* \brief resize and rearange windows
*
* \return 0 success
* <0 error
*/
int cursesui::win_resize(){
unsigned int i, j, width, height, fixed_height, nfixed_height, win, line, ncols[nwin + 1], split[nwin + 1], nsplit, nlines, max_cols;
if(nwin == 0)
return 0;
memset(split, 0x0, sizeof(unsigned int) * (nwin + 1));
memset(ncols, 0x0, sizeof(unsigned int) * (nwin + 1));
/* split windows in lines with normal windows and
* horizontally maximised windows
*
* split number of windows before the next 'oneline' window
* nsplit entries in split
*/
nsplit = 0;
fixed_height = 0;
nfixed_height = 0;
for(i=0; i<max_win; i++){
if(windows[i] == 0)
continue;
// check if window is horizontally maximised
if(windows[i]->oneline){
if(split[nsplit] != 0)
nsplit++;
split[nsplit++] = 1;
}
else
split[nsplit]++;
// accumulate height for windows that specify it
// (default is 0)
if(windows[i]->height > 0){
fixed_height += windows[i]->height;
nfixed_height++;
}
}
if(split[nsplit] > 0)
nsplit++;
/* identify number of windows per line
*
* ncols[i] number of windows for line i
* nlines entries in ncols
*/
max_cols = COLS / min_win_width;
nlines = 0;
for(i=0; i<nsplit; i++){
if(split[i] <= max_cols){
ncols[nlines++] = split[i];
}
else{
for(j=0; j<split[i] / max_cols; j++)
ncols[nlines++] = max_cols;
if(split[i] % max_cols)
ncols[nlines++] = split[i] % max_cols;
}
}
if(ncols[nlines] > 0)
nlines++;
/* update windows */
height = 0;
if(nlines - nfixed_height > 0){
height = (LINES - fixed_height) / (nlines - nfixed_height);
if(height < min_win_height)
return -1;
}
if((LINES - fixed_height) < 0)
return -1;
// clear screen
erase();
refresh();
win = 0;
line = 0;
for(i=0; i<nlines; i++){
width = COLS / ncols[i];
if(width < min_win_width)
return -1;
for(j=0; j<ncols[i]; j++){
for(;win<max_win; win++){
if(windows[win] != 0)
break;
}
// update window frame
wresize(windows[win]->frame, (windows[win]->height > 0) ? windows[win]->height : height, width);
mvwin(windows[win]->frame, line, j * width);
box(windows[win]->frame, 0, 0);
mvwprintw(windows[win]->frame, 0, 2, "[ %s ]", windows[win]->title);
wrefresh(windows[win]->frame);
// update window text area
wresize(windows[win]->win, ((windows[win]->height > 0) ? windows[win]->height : height) - 2, width - 2);
mvwin(windows[win]->win, line + 1, j * width + 1);
wrefresh(windows[win]->win);
win++;
}
line += (windows[win - 1]->height > 0) ? windows[win - 1]->height : height;
}
return 0;
}
<commit_msg>[fix gui: curses]<commit_after>#include <gui/cursesui.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#define CMD_PROMPT "cmd: "
cursesui::cursesui(){
/* init ncurses */
setlocale(LC_ALL, "");
initscr();
noecho();
/* init class members */
nwin = 0;
max_win = 2;
windows = (window_t**)malloc(sizeof(window_t*) * max_win);
if(windows == 0)
goto err_0;
memset(windows, 0x0, sizeof(window_t*) * max_win);
pthread_mutex_init(&mutex, 0);
line_len = 255;
line = (char*)malloc(line_len * sizeof(char));
if(line == 0)
goto err_1;
term = new tty;
if(term == 0)
goto err_2;
constructor_ok = true;
return;
err_2:
free(line);
err_1:
free(windows);
err_0:
constructor_ok = false;
}
cursesui::~cursesui(){
unsigned int i;
/* free allocated windows */
for(i=0; i<max_win; i++){
if(windows[i] == 0)
continue;
delwin(windows[i]->win);
delwin(windows[i]->frame);
free(windows[i]);
}
free(windows);
/* stop ncurses */
endwin();
}
/**
* \brief read user input from gui
*
* \return != 0 pointer to line
* 0 error
*/
char* cursesui::readline(){
char c;
unsigned int i;
if(line == 0 || term == 0)
return 0;
i = 0;
print(WIN_CMD, CMD_PROMPT);
while(1){
term->read(&c, 1);
if(c == '\n' || c == '\r'){
line[i] = 0;
print(WIN_CMD, "\n");
return line;
}
else if(c == 127){
if(i <= 0)
continue;
line[--i] = 0;
clearline(WIN_CMD);
print(WIN_CMD, CMD_PROMPT "%s", line);
}
else{
print(WIN_CMD, "%c", c);
line[i++] = c;
if(i >= line_len){
line_len *= 2;
line = (char*)realloc(line, line_len);
if(line == 0)
return 0;
}
}
}
}
/**
* \brief create new cursesui window
*
* \param title window title
* \param oneline if true, the window width is maximised
*
* \return >=0 window id
* <0 error
*/
int cursesui::win_create(const char* title, bool oneline, unsigned int height){
int i, id;
/* realloc if now enough space to store windows */
if(nwin + 1 > max_win){
windows = (window_t**)realloc(windows, sizeof(window_t*) * max_win * 2);
memset(windows + max_win, 0x0, sizeof(window_t*) * max_win);
max_win *= 2;
}
/* search free id */
id = -1;
for(i=0; i<max_win; i++){
if(windows[i] == 0){
id = i;
break;
}
}
if(id == -1)
return -1;
/* allocated cursesui window */
windows[id] = new window_t;
windows[id]->win = newwin(2, 2, 0, 0); // arbitrary width and height, final
windows[id]->frame = newwin(2, 2, 0, 0); // values are set in win_resize()
windows[id]->title = (char*)title;
windows[id]->oneline = (height > 0) ? true : oneline;
windows[id]->height = height;
scrollok(windows[id]->win, true); // enable auto-scroll
nwin++;
/* update size of all windows */
if(win_resize() < 0){
win_destroy(id);
return -1;
}
return id;
}
int cursesui::win_destroy(int win_id){
if(win_id >= max_win || windows[win_id] == 0)
return -1;
/* de-init window and free memory */
delwin(windows[win_id]->win);
delwin(windows[win_id]->frame);
free(windows[win_id]);
windows[win_id] = 0;
nwin--;
/* update screen */
win_resize();
return 0;
}
void cursesui::win_write(int win_id, const char* fmt, ...){
va_list lst;
va_start(lst, fmt);
win_vwrite(win_id, fmt, lst);
va_end(lst);
}
void cursesui::win_vwrite(int win_id, const char* fmt, va_list lst){
pthread_mutex_lock(&mutex);
vwprintw(windows[win_id]->win, fmt, lst);
wrefresh(windows[win_id]->win);
pthread_mutex_unlock(&mutex);
}
void cursesui::win_clear(int win_id){
pthread_mutex_lock(&mutex);
wclear(windows[win_id]->win);
wrefresh(windows[win_id]->win);
pthread_mutex_unlock(&mutex);
}
void cursesui::win_clrline(int win_id){
int x, y;
pthread_mutex_lock(&mutex);
getyx(windows[win_id]->win, y, x);
wmove(windows[win_id]->win, y, 0);
wclrtoeol(windows[win_id]->win);
wrefresh(windows[win_id]->win);
pthread_mutex_unlock(&mutex);
}
/**
* \brief resize and rearange windows
*
* \return 0 success
* <0 error
*/
int cursesui::win_resize(){
unsigned int i, j, width, height, fixed_height, nfixed_height, win, line, ncols[nwin + 1], split[nwin + 1], nsplit, nlines, max_cols;
if(nwin == 0)
return 0;
memset(split, 0x0, sizeof(unsigned int) * (nwin + 1));
memset(ncols, 0x0, sizeof(unsigned int) * (nwin + 1));
/* split windows in lines with normal windows and
* horizontally maximised windows
*
* split number of windows before the next 'oneline' window
* nsplit entries in split
*/
nsplit = 0;
fixed_height = 0;
nfixed_height = 0;
for(i=0; i<max_win; i++){
if(windows[i] == 0)
continue;
// check if window is horizontally maximised
if(windows[i]->oneline){
if(split[nsplit] != 0)
nsplit++;
split[nsplit++] = 1;
}
else
split[nsplit]++;
// accumulate height for windows that specify it
// (default is 0)
if(windows[i]->height > 0){
fixed_height += windows[i]->height;
nfixed_height++;
}
}
if(split[nsplit] > 0)
nsplit++;
/* identify number of windows per line
*
* ncols[i] number of windows for line i
* nlines entries in ncols
*/
max_cols = COLS / min_win_width;
nlines = 0;
for(i=0; i<nsplit; i++){
if(split[i] <= max_cols){
ncols[nlines++] = split[i];
}
else{
for(j=0; j<split[i] / max_cols; j++)
ncols[nlines++] = max_cols;
if(split[i] % max_cols)
ncols[nlines++] = split[i] % max_cols;
}
}
if(ncols[nlines] > 0)
nlines++;
/* update windows */
height = 0;
if(nlines - nfixed_height > 0){
height = (LINES - fixed_height) / (nlines - nfixed_height);
if(height < min_win_height)
return -1;
}
if((LINES - fixed_height) < 0)
return -1;
// clear screen
erase();
refresh();
win = 0;
line = 0;
for(i=0; i<nlines; i++){
width = COLS / ncols[i];
if(width < min_win_width)
return -1;
for(j=0; j<ncols[i]; j++){
for(;win<max_win; win++){
if(windows[win] != 0)
break;
}
// update window frame
wresize(windows[win]->frame, (windows[win]->height > 0) ? windows[win]->height : height, width);
mvwin(windows[win]->frame, line, j * width);
box(windows[win]->frame, 0, 0);
mvwprintw(windows[win]->frame, 0, 2, "[ %s ]", windows[win]->title);
wrefresh(windows[win]->frame);
// update window text area
wresize(windows[win]->win, ((windows[win]->height > 0) ? windows[win]->height : height) - 2, width - 2);
mvwin(windows[win]->win, line + 1, j * width + 1);
wrefresh(windows[win]->win);
win++;
}
line += (windows[win - 1]->height > 0) ? windows[win - 1]->height : height;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <nds.h>
#include <maxmod9.h>
#include <stdio.h>
#include "ball.h"
#include "geometry.h"
#include "player.h"
#include "stats.h"
// Sprites
#include "spriteBall.h"
// Audio
#include "soundbank.h"
#include "soundbank_bin.h"
// Methods
void initBall(ball *b) {
b->speed = 1.5;
b->box.pos.x = 100;
b->box.pos.y = 30;
b->box.width = 12;
b->box.height = 12;
b->direction.x = 1;
b->direction.y = 1;
b->sprite_offx = -2;
b->sprite_offy = -2;
b->sprite_size = SpriteSize_16x16;
b->sprite_format = SpriteColorFormat_256Color;
b->sprite_gfx = oamAllocateGfx(&oamMain, b->sprite_size, b->sprite_format);
b->sfx_wall = { { SFX_WALL }, 1024, 0, 255, 128 };
b->sfx_panel = { { SFX_PANEL }, 1024, 0, 255, 128 };
b->sfx_scoring = { { SFX_READY }, 1024, 0, 255, 128 };
dmaCopy(spriteBallPal, SPRITE_PALETTE, 512);
dmaCopy(spriteBallTiles,b->sprite_gfx, spriteBallTilesLen);
}
void drawBall(ball *b) {
oamSet( &oamMain, 0, b->box.pos.x + b->sprite_offx, b->box.pos.y + b->sprite_offy, 0, 0,
b->sprite_size, b->sprite_format, b->sprite_gfx,
-1,false,false,false,false,false);
}
/**
* @param ball b
* @return void
*/
void moveBall(ball *b, player *p1, player *p2, scoreBox *sBox) {
b->box.pos.x += b->direction.x * b->speed;
b->box.pos.y += b->direction.y * b->speed;
// horizontal collision
if (b->box.pos.x <= 0) {
scoring(1, b, sBox);
} else if (b->box.pos.x + b->box.width >= SCREEN_WIDTH) {
scoring(0, b, sBox);
} else if (intersect(b->box, p1->box) || intersect(b->box, p2->box)) {
// calculate relative position to player box, then set direction according to that relative position
// if relative position is low (i.e. closer to 0, the ball hit the paddle early),
// then it goes back in an acute angle, arriving at the enemy faster
// if relative position is high (i.e. closer to 1, the ball hit the paddle late),
// then it goes back in an obtuse angle, arriving at the enemy slower
float relativePos;
if (intersect(b->box, p1->box)) {
// player 1
relativePos = (b->box.pos.y - p1->box.pos.y) / (p1->box.height);
} else {
// player 2
relativePos = (b->box.pos.y - p2->box.pos.y) / (p2->box.height);
}
// y is negative, so the ball is flying up: reverse relative position
if (b->direction.y < 0) {
relativePos = 1 - relativePos;
}
b->direction.x = 1.2 - relativePos;
b->direction.y = 0.2 + relativePos;
// reverse x direction
b->direction.x *= -1;
mmEffect( SFX_PANEL );
mmEffectEx( &b->sfx_panel );
}
// vertical collision
if (b->box.pos.y <= 0 || b->box.pos.y + b->box.height >= SCREEN_HEIGHT) {
b->direction.y *= -1;
mmEffect( SFX_WALL );
mmEffectEx( &b->sfx_wall );
}
}
void scoring(int player, ball *b, scoreBox *sBox) {
b->box.pos.x = SCREEN_WIDTH / 2;
b->box.pos.y = SCREEN_HEIGHT / 2;
b->direction.x *= -1;
countPoint(sBox, player);
mmEffectEx( &b->sfx_scoring );
mmEffect( SFX_READY );
}
<commit_msg>fixed direction bug for left side<commit_after>#include <nds.h>
#include <maxmod9.h>
#include <stdio.h>
#include "ball.h"
#include "geometry.h"
#include "player.h"
#include "stats.h"
// Sprites
#include "spriteBall.h"
// Audio
#include "soundbank.h"
#include "soundbank_bin.h"
// Methods
void initBall(ball *b) {
b->speed = 1.5;
b->box.pos.x = 100;
b->box.pos.y = 30;
b->box.width = 12;
b->box.height = 12;
b->direction.x = 1;
b->direction.y = 1;
b->sprite_offx = -2;
b->sprite_offy = -2;
b->sprite_size = SpriteSize_16x16;
b->sprite_format = SpriteColorFormat_256Color;
b->sprite_gfx = oamAllocateGfx(&oamMain, b->sprite_size, b->sprite_format);
b->sfx_wall = { { SFX_WALL }, 1024, 0, 255, 128 };
b->sfx_panel = { { SFX_PANEL }, 1024, 0, 255, 128 };
b->sfx_scoring = { { SFX_READY }, 1024, 0, 255, 128 };
dmaCopy(spriteBallPal, SPRITE_PALETTE, 512);
dmaCopy(spriteBallTiles,b->sprite_gfx, spriteBallTilesLen);
}
void drawBall(ball *b) {
oamSet( &oamMain, 0, b->box.pos.x + b->sprite_offx, b->box.pos.y + b->sprite_offy, 0, 0,
b->sprite_size, b->sprite_format, b->sprite_gfx,
-1,false,false,false,false,false);
}
/**
* @param ball b
* @return void
*/
void moveBall(ball *b, player *p1, player *p2, scoreBox *sBox) {
b->box.pos.x += b->direction.x * b->speed;
b->box.pos.y += b->direction.y * b->speed;
// horizontal collision
if (b->box.pos.x <= 0) {
scoring(1, b, sBox);
} else if (b->box.pos.x + b->box.width >= SCREEN_WIDTH) {
scoring(0, b, sBox);
} else if (intersect(b->box, p1->box) || intersect(b->box, p2->box)) {
// calculate relative position to player box, then set direction according to that relative position
// if relative position is low (i.e. closer to 0, the ball hit the paddle early),
// then it goes back in an acute angle, arriving at the enemy faster
// if relative position is high (i.e. closer to 1, the ball hit the paddle late),
// then it goes back in an obtuse angle, arriving at the enemy slower
float relativePos;
if (intersect(b->box, p1->box)) {
// player 1
relativePos = (b->box.pos.y - p1->box.pos.y) / (p1->box.height);
} else {
// player 2
relativePos = (b->box.pos.y - p2->box.pos.y) / (p2->box.height);
}
// y is negative, so the ball is flying up: reverse relative position
if (b->direction.y < 0) {
relativePos = 1 - relativePos;
}
// new x direction, reverse the sign
b->direction.x = (b->direction.x > 0) ? -1 : 1;
b->direction.x *= 1.2 - relativePos;
// new y direction
b->direction.y = 0.2 + relativePos;
mmEffect( SFX_PANEL );
mmEffectEx( &b->sfx_panel );
}
// vertical collision
if (b->box.pos.y <= 0 || b->box.pos.y + b->box.height >= SCREEN_HEIGHT) {
b->direction.y *= -1;
mmEffect( SFX_WALL );
mmEffectEx( &b->sfx_wall );
}
}
void scoring(int player, ball *b, scoreBox *sBox) {
b->box.pos.x = SCREEN_WIDTH / 2;
b->box.pos.y = SCREEN_HEIGHT / 2;
b->direction.x *= -1;
countPoint(sBox, player);
mmEffectEx( &b->sfx_scoring );
mmEffect( SFX_READY );
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_PATH_EXPRESSIONS_GRAMMAR_X3_DEF_HPP
#define MAPNIK_PATH_EXPRESSIONS_GRAMMAR_X3_DEF_HPP
// mapnik
#include <mapnik/path_expression_grammar_x3.hpp>
#include <mapnik/attribute.hpp>
namespace mapnik { namespace grammar {
namespace x3 = boost::spirit::x3;
using x3::standard_wide::char_;
using x3::lexeme;
auto create_string = [](auto & ctx) { _val(ctx).push_back(_attr(ctx)); };
auto create_attribute = [](auto & ctx) { _val(ctx).push_back(mapnik::attribute(_attr(ctx))); };
// top-most rule
path_expression_grammar_type const path_expression("path_expression");
// rules
x3::rule<class attr_expression, std::string> const attr_expression("attribute");
x3::rule<class str_expression, std::string> const str_expression("string");
auto const attr_expression_def = +(char_ - ']');
auto const str_expression_def = lexeme[+(char_ -'[')];
auto const path_expression_def = *(str_expression[create_string] | '[' > attr_expression[create_attribute] > ']');
BOOST_SPIRIT_DEFINE(
path_expression,
attr_expression,
str_expression
);
}}
namespace mapnik {
grammar::path_expression_grammar_type const& path_expression_grammar()
{
return grammar::path_expression;
}
}
#endif //MAPNIK_PATH_EXPRESSIONS_GRAMMAR_X3_DEF_HPP
<commit_msg>add parentheses to supress gcc warning [-Wparentheses]<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_PATH_EXPRESSIONS_GRAMMAR_X3_DEF_HPP
#define MAPNIK_PATH_EXPRESSIONS_GRAMMAR_X3_DEF_HPP
// mapnik
#include <mapnik/path_expression_grammar_x3.hpp>
#include <mapnik/attribute.hpp>
namespace mapnik { namespace grammar {
namespace x3 = boost::spirit::x3;
using x3::standard_wide::char_;
using x3::lexeme;
auto create_string = [](auto & ctx) { _val(ctx).push_back(_attr(ctx)); };
auto create_attribute = [](auto & ctx) { _val(ctx).push_back(mapnik::attribute(_attr(ctx))); };
// top-most rule
path_expression_grammar_type const path_expression("path_expression");
// rules
x3::rule<class attr_expression, std::string> const attr_expression("attribute");
x3::rule<class str_expression, std::string> const str_expression("string");
auto const attr_expression_def = +(char_ - ']');
auto const str_expression_def = lexeme[+(char_ -'[')];
auto const path_expression_def = *(str_expression[create_string] | ('[' > attr_expression[create_attribute] > ']'));
BOOST_SPIRIT_DEFINE(
path_expression,
attr_expression,
str_expression
);
}}
namespace mapnik {
grammar::path_expression_grammar_type const& path_expression_grammar()
{
return grammar::path_expression;
}
}
#endif //MAPNIK_PATH_EXPRESSIONS_GRAMMAR_X3_DEF_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright 2001 - 2009 Todd Richmond
*
* This file is part of Blister - a light weight, scalable, high performance
* C++ server infrastructure.
*
* Blister 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 any later version.
*
* Blister 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 details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Blister. If not, see <http://www.gnu.org/licenses/>.
*/
#include "stdapi.h"
#include <algorithm>
#include "Timing.h"
// UNIX loaders may try to construct static objects > 1 time
static Timing &_dtiming(void) {
static Timing timing;
return timing;
}
Timing &dtiming(_dtiming());
void Timing::add(const tchar *key, timing_t diff) {
SpinLocker lkr(lck);
timingmap::const_iterator it = tmap.find(key);
uint slot;
Stats *stats;
static timing_t limits[TIMINGSLOTS] = {
10, 100, 1000, 10000, 100000, 1000000, 5000000, 10000000, 30000000,
60000000
};
if (it == tmap.end()) {
key = tstrdup(key);
stats = tmap[key] = new Stats(key);
} else {
stats = it->second;
}
stats->cnt++;
for (slot = 0; slot < TIMINGSLOTS; slot++) {
if (diff <= limits[slot])
break;
}
stats->cnts[slot]++;
stats->tot += diff;
}
void Timing::clear() {
timingmap::iterator it;
SpinLocker lkr(lck);
while ((it = tmap.begin()) != tmap.end()) {
const tchar *p = it->first;
delete it->second;
tmap.erase(it);
free((tchar *)p);
}
}
const tstring Timing::data(bool sortbyname, uint columns) const {
timingmap::const_iterator it;
uint last = 0, start = 0;
SpinLocker lkr(lck);
bool msec = true;
tstring s;
vector<const Stats *>::const_iterator sit;
vector<const Stats *> sorted;
const Stats *stats;
uint u;
static const tchar *hdrs[TIMINGSLOTS] = {
T("10u"), T(".1m"), T(" 1m"), T("10m"), T(".1s"), T(" 1s"), T(" 5s"),
T("10s"), T("30s"), T(" 1M")
};
for (it = tmap.begin(); it != tmap.end(); it++)
sorted.push_back(it->second);
sort(sorted.begin(), sorted.end(), sortbyname ? less_name : less_time);
for (sit = sorted.begin(); sit != sorted.end(); sit++) {
stats = *sit;
if (stats->tot > 1000000)
msec = false;
for (u = TIMINGSLOTS - 1; u > last; u--) {
if (stats->cnts[u]) {
last = u;
break;
}
}
}
last = 7;
if (columns) {
if (columns > TIMINGSLOTS)
columns = TIMINGSLOTS;
start = last < columns ? 0 : last - columns + 1;
s = T("key ");
s += msec ? T("msec") : T(" sec");
s += T(" cnt avg");
for (u = start; u <= last; u++) {
s += (tchar)' ';
s += hdrs[u];
}
s += (tchar)'\n';
}
for (sit = sorted.begin(); sit != sorted.end(); sit++) {
tchar abuf[16], buf[128], cbuf[16], sbuf[16];
ulong sum = 0;
timing_t tot;
stats = *sit;
tot = stats->tot;
if (columns) {
for (u = 0; u <= start; u++)
sum += stats->cnts[u];
if (stats->cnt >= 100000000)
tsprintf(cbuf, T("%5luM"), (stats->cnt + 499999) / 1000);
else if (stats->cnt >= 100000)
tsprintf(cbuf, T("%5luK"), (stats->cnt + 499) / 1000);
else
tsprintf(cbuf, T("%5lu"), stats->cnt);
if (msec)
tot *= 1000;
if (tot)
tsprintf(buf, T("%-29s%6s%6s%6s"), stats->name, format(tot,
sbuf), cbuf, format(tot / stats->cnt, abuf));
else
tsprintf(buf, T("%-35s%6s"), stats->name, cbuf);
} else {
if (!s.empty())
s += (tchar)',';
tsprintf(buf, T("%s,%s,%lu"), stats->name, format(tot, sbuf),
stats->cnt);
}
s += buf;
for (u = start; u <= last && tot; u++) {
ulong cnt = (columns && u == start) ? sum : stats->cnts[u];
if (!columns) {
tsprintf(buf, T(",%lu"), cnt);
s += buf;
} else if (cnt == 0) {
s += T(" ");
} else if (cnt < 100) {
tsprintf(buf, T(" %3lu"), cnt);
s += buf;
} else if (cnt == stats->cnt) {
s += T(" *");
} else {
tsprintf(buf, T(" %2u%%"), (uint)(cnt * 100 / stats->cnt));
s += buf;
}
}
if (columns)
s += (tchar)'\n';
}
return s;
}
void Timing::erase(const tchar *key) {
SpinLocker lkr(lck);
timingmap::iterator it = tmap.find(key);
if (it != tmap.end()) {
const tchar *p = it->first;
delete it->second;
tmap.erase(it);
free((tchar *)p);
}
}
timing_t Timing::record(const tchar *key) {
tstring caller;
timing_t diff;
timing_t n = now();
Tlsdata *tlsd = tls.get();
do {
vector<tstring>::reverse_iterator it = tlsd->callers.rbegin();
if (it == tlsd->callers.rend()) {
tcerr << T("timing mismatch for ") << (key ? key : T("stack")) <<
endl;
return 0;
}
caller = *it;
tlsd->callers.pop_back();
if (!key)
key = caller.c_str();
diff = n - *(tlsd->starts.rbegin());
tlsd->starts.pop_back();
} while (!caller.empty() && caller != key);
if (!caller.empty() && !tlsd->callers.empty()) {
tstring s;
for (vector<tstring>::const_iterator it = tlsd->callers.begin();
it != tlsd->callers.end(); it++) {
if (!s.empty())
s += T("->");
s += *it;
}
s += T("->");
s += key;
add(s.c_str(), diff);
}
add(key, diff);
return now();
}
timing_t Timing::start(const tchar *key) {
timing_t n;
Tlsdata *tlsd = tls.get();
tlsd->callers.push_back(key ? key : T(""));
tlsd->starts.push_back(n = now());
return n;
}
void Timing::stop(uint lvl) {
Tlsdata *tlsd = tls.get();
while (lvl-- && !tlsd->callers.empty()) {
tlsd->callers.pop_back();
tlsd->starts.pop_back();
}
}
const tchar *Timing::format(timing_t t, tchar *buf) {
float f(t / 1000000.0f);
if (f < 9.9995)
tsprintf(buf, T("%.3f"), f);
else if (f < 99.995)
tsprintf(buf, T("%.2f"), f);
else
tsprintf(buf, T("%.0f"), f + .4999);
return buf;
}
<commit_msg>remove ability to print in seconds - that prevents msec resolutions from being readable<commit_after>/*
* Copyright 2001 - 2009 Todd Richmond
*
* This file is part of Blister - a light weight, scalable, high performance
* C++ server infrastructure.
*
* Blister 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 any later version.
*
* Blister 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 details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Blister. If not, see <http://www.gnu.org/licenses/>.
*/
#include "stdapi.h"
#include <algorithm>
#include "Timing.h"
// UNIX loaders may try to construct static objects > 1 time
static Timing &_dtiming(void) {
static Timing timing;
return timing;
}
Timing &dtiming(_dtiming());
void Timing::add(const tchar *key, timing_t diff) {
SpinLocker lkr(lck);
timingmap::const_iterator it = tmap.find(key);
uint slot;
Stats *stats;
static timing_t limits[TIMINGSLOTS] = {
10, 100, 1000, 10000, 100000, 1000000, 5000000, 10000000, 30000000,
60000000
};
if (it == tmap.end()) {
key = tstrdup(key);
stats = tmap[key] = new Stats(key);
} else {
stats = it->second;
}
stats->cnt++;
for (slot = 0; slot < TIMINGSLOTS; slot++) {
if (diff <= limits[slot])
break;
}
stats->cnts[slot]++;
stats->tot += diff;
}
void Timing::clear() {
timingmap::iterator it;
SpinLocker lkr(lck);
while ((it = tmap.begin()) != tmap.end()) {
const tchar *p = it->first;
delete it->second;
tmap.erase(it);
free((tchar *)p);
}
}
const tstring Timing::data(bool sortbyname, uint columns) const {
timingmap::const_iterator it;
uint last = 0, start = 0;
SpinLocker lkr(lck);
tstring s;
vector<const Stats *>::const_iterator sit;
vector<const Stats *> sorted;
const Stats *stats;
uint u;
static const tchar *hdrs[TIMINGSLOTS] = {
T("10u"), T(".1m"), T(" 1m"), T("10m"), T(".1s"), T(" 1s"), T(" 5s"),
T("10s"), T("30s"), T(" 1M")
};
for (it = tmap.begin(); it != tmap.end(); it++)
sorted.push_back(it->second);
sort(sorted.begin(), sorted.end(), sortbyname ? less_name : less_time);
for (sit = sorted.begin(); sit != sorted.end(); sit++) {
stats = *sit;
for (u = TIMINGSLOTS - 1; u > last; u--) {
if (stats->cnts[u]) {
last = u;
break;
}
}
}
if (columns) {
if (columns > TIMINGSLOTS)
columns = TIMINGSLOTS;
start = last < columns ? 0 : last - columns + 1;
s = T("key msec cnt avg");
for (u = start; u <= last; u++) {
s += (tchar)' ';
s += hdrs[u];
}
s += (tchar)'\n';
}
for (sit = sorted.begin(); sit != sorted.end(); sit++) {
tchar abuf[16], buf[128], cbuf[16], sbuf[16];
ulong sum = 0;
timing_t tot;
stats = *sit;
tot = stats->tot;
if (columns) {
for (u = 0; u <= start; u++)
sum += stats->cnts[u];
if (stats->cnt >= 100000000)
tsprintf(cbuf, T("%5lum"), (stats->cnt + 499999) / 1000000);
else if (stats->cnt >= 100000)
tsprintf(cbuf, T("%5luk"), (stats->cnt + 499) / 1000);
else
tsprintf(cbuf, T("%5lu"), stats->cnt);
if (tot)
tsprintf(buf, T("%-29s%6s%6s%6s"), stats->name, format(tot,
sbuf), cbuf, format(tot / stats->cnt, abuf));
else
tsprintf(buf, T("%-35s%6s"), stats->name, cbuf);
} else {
if (!s.empty())
s += (tchar)',';
tsprintf(buf, T("%s,%s,%lu"), stats->name, format(tot, sbuf),
stats->cnt);
}
s += buf;
for (u = start; u <= last && tot; u++) {
ulong cnt = (columns && u == start) ? sum : stats->cnts[u];
if (!columns) {
tsprintf(buf, T(",%lu"), cnt);
s += buf;
} else if (cnt == 0) {
s += T(" ");
} else if (cnt < 100) {
tsprintf(buf, T(" %3lu"), cnt);
s += buf;
} else if (cnt == stats->cnt) {
s += T(" *");
} else {
tsprintf(buf, T(" %2u%%"), (uint)(cnt * 100 / stats->cnt));
s += buf;
}
}
if (columns)
s += (tchar)'\n';
}
return s;
}
void Timing::erase(const tchar *key) {
SpinLocker lkr(lck);
timingmap::iterator it = tmap.find(key);
if (it != tmap.end()) {
const tchar *p = it->first;
delete it->second;
tmap.erase(it);
free((tchar *)p);
}
}
timing_t Timing::record(const tchar *key) {
tstring caller;
timing_t diff;
timing_t n = now();
Tlsdata *tlsd = tls.get();
do {
vector<tstring>::reverse_iterator it = tlsd->callers.rbegin();
if (it == tlsd->callers.rend()) {
tcerr << T("timing mismatch for ") << (key ? key : T("stack")) <<
endl;
return 0;
}
caller = *it;
tlsd->callers.pop_back();
if (!key)
key = caller.c_str();
diff = n - *(tlsd->starts.rbegin());
tlsd->starts.pop_back();
} while (!caller.empty() && caller != key);
if (!caller.empty() && !tlsd->callers.empty()) {
tstring s;
for (vector<tstring>::const_iterator it = tlsd->callers.begin();
it != tlsd->callers.end(); it++) {
if (!s.empty())
s += T("->");
s += *it;
}
s += T("->");
s += key;
add(s.c_str(), diff);
}
add(key, diff);
return now();
}
timing_t Timing::start(const tchar *key) {
timing_t n;
Tlsdata *tlsd = tls.get();
tlsd->callers.push_back(key ? key : T(""));
tlsd->starts.push_back(n = now());
return n;
}
void Timing::stop(uint lvl) {
Tlsdata *tlsd = tls.get();
while (lvl-- && !tlsd->callers.empty()) {
tlsd->callers.pop_back();
tlsd->starts.pop_back();
}
}
const tchar *Timing::format(timing_t t, tchar *buf) {
float f(t / 1000.0f);
if (f < 10)
tsprintf(buf, T("%.3f"), f);
else if (f < 100)
tsprintf(buf, T("%.2f"), f);
else if (f < 10000)
tsprintf(buf, T("%.0f"), f);
else if (f < 1000000)
tsprintf(buf, T("%.0fk"), f / 1000);
else
tsprintf(buf, T("%.0fm"), f / 1000000);
return buf;
}
<|endoftext|>
|
<commit_before>#include "codec.h"
#include <muduo/base/Logging.h>
#include <muduo/base/Mutex.h>
#include <muduo/base/ThreadLocalSingleton.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpServer.h>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <set>
#include <stdio.h>
using namespace muduo;
using namespace muduo::net;
class ChatServer : boost::noncopyable
{
public:
ChatServer(EventLoop* loop,
const InetAddress& listenAddr)
: loop_(loop),
server_(loop, listenAddr, "ChatServer"),
codec_(boost::bind(&ChatServer::onStringMessage, this, _1, _2, _3))
{
server_.setConnectionCallback(
boost::bind(&ChatServer::onConnection, this, _1));
server_.setMessageCallback(
boost::bind(&LengthHeaderCodec::onMessage, &codec_, _1, _2, _3));
}
void setThreadNum(int numThreads)
{
server_.setThreadNum(numThreads);
}
void start()
{
server_.setThreadInitCallback(boost::bind(&ChatServer::threadInit, this, _1));
server_.start();
}
private:
void onConnection(const TcpConnectionPtr& conn)
{
LOG_INFO << conn->localAddress().toIpPort() << " -> "
<< conn->peerAddress().toIpPort() << " is "
<< (conn->connected() ? "UP" : "DOWN");
if (conn->connected())
{
connections_.instance().insert(conn);
}
else
{
connections_.instance().erase(conn);
}
}
void onStringMessage(const TcpConnectionPtr&,
const string& message,
Timestamp)
{
EventLoop::Functor f = boost::bind(&ChatServer::distributeMessage, this, message);
LOG_DEBUG;
MutexLockGuard lock(mutex_);
for (std::set<EventLoop*>::iterator it = loops_.begin();
it != loops_.end();
++it)
{
(*it)->queueInLoop(f);
}
LOG_DEBUG;
}
typedef std::set<TcpConnectionPtr> ConnectionList;
void distributeMessage(const string& message)
{
LOG_DEBUG << "begin";
for (ConnectionList::iterator it = connections_.instance().begin();
it != connections_.instance().end();
++it)
{
codec_.send(get_pointer(*it), message);
}
LOG_DEBUG << "end";
}
void threadInit(EventLoop* loop)
{
assert(connections_.pointer() == NULL);
connections_.instance();
assert(connections_.pointer() != NULL);
MutexLockGuard lock(mutex_);
loops_.insert(loop);
}
EventLoop* loop_;
TcpServer server_;
LengthHeaderCodec codec_;
ThreadLocalSingleton<ConnectionList> connections_;
MutexLock mutex_;
std::set<EventLoop*> loops_;
};
int main(int argc, char* argv[])
{
LOG_INFO << "pid = " << getpid();
if (argc > 1)
{
EventLoop loop;
uint16_t port = static_cast<uint16_t>(atoi(argv[1]));
InetAddress serverAddr(port);
ChatServer server(&loop, serverAddr);
if (argc > 2)
{
server.setThreadNum(atoi(argv[2]));
}
server.start();
loop.loop();
}
else
{
printf("Usage: %s port [thread_num]\n", argv[0]);
}
}
<commit_msg>fix usage of ThreadLocalSingleton.<commit_after>#include "codec.h"
#include <muduo/base/Logging.h>
#include <muduo/base/Mutex.h>
#include <muduo/base/ThreadLocalSingleton.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpServer.h>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <set>
#include <stdio.h>
using namespace muduo;
using namespace muduo::net;
class ChatServer : boost::noncopyable
{
public:
ChatServer(EventLoop* loop,
const InetAddress& listenAddr)
: loop_(loop),
server_(loop, listenAddr, "ChatServer"),
codec_(boost::bind(&ChatServer::onStringMessage, this, _1, _2, _3))
{
server_.setConnectionCallback(
boost::bind(&ChatServer::onConnection, this, _1));
server_.setMessageCallback(
boost::bind(&LengthHeaderCodec::onMessage, &codec_, _1, _2, _3));
}
void setThreadNum(int numThreads)
{
server_.setThreadNum(numThreads);
}
void start()
{
server_.setThreadInitCallback(boost::bind(&ChatServer::threadInit, this, _1));
server_.start();
}
private:
void onConnection(const TcpConnectionPtr& conn)
{
LOG_INFO << conn->localAddress().toIpPort() << " -> "
<< conn->peerAddress().toIpPort() << " is "
<< (conn->connected() ? "UP" : "DOWN");
if (conn->connected())
{
LocalConnections::instance().insert(conn);
}
else
{
LocalConnections::instance().erase(conn);
}
}
void onStringMessage(const TcpConnectionPtr&,
const string& message,
Timestamp)
{
EventLoop::Functor f = boost::bind(&ChatServer::distributeMessage, this, message);
LOG_DEBUG;
MutexLockGuard lock(mutex_);
for (std::set<EventLoop*>::iterator it = loops_.begin();
it != loops_.end();
++it)
{
(*it)->queueInLoop(f);
}
LOG_DEBUG;
}
typedef std::set<TcpConnectionPtr> ConnectionList;
void distributeMessage(const string& message)
{
LOG_DEBUG << "begin";
for (ConnectionList::iterator it = LocalConnections::instance().begin();
it != LocalConnections::instance().end();
++it)
{
codec_.send(get_pointer(*it), message);
}
LOG_DEBUG << "end";
}
void threadInit(EventLoop* loop)
{
assert(LocalConnections::pointer() == NULL);
LocalConnections::instance();
assert(LocalConnections::pointer() != NULL);
MutexLockGuard lock(mutex_);
loops_.insert(loop);
}
EventLoop* loop_;
TcpServer server_;
LengthHeaderCodec codec_;
typedef ThreadLocalSingleton<ConnectionList> LocalConnections;
MutexLock mutex_;
std::set<EventLoop*> loops_;
};
int main(int argc, char* argv[])
{
LOG_INFO << "pid = " << getpid();
if (argc > 1)
{
EventLoop loop;
uint16_t port = static_cast<uint16_t>(atoi(argv[1]));
InetAddress serverAddr(port);
ChatServer server(&loop, serverAddr);
if (argc > 2)
{
server.setThreadNum(atoi(argv[2]));
}
server.start();
loop.loop();
}
else
{
printf("Usage: %s port [thread_num]\n", argv[0]);
}
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
// See the manual for a description of the correct XML input format.
#include "Input_Parser.hxx"
#include "../../SDP.hxx"
#include <boost/filesystem.hpp>
#include <boost/property_tree/xml_parser.hpp>
namespace
{
void start_element_callback(void *user_data, const xmlChar *name,
const xmlChar **)
{
Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
input_parser->on_start_element(reinterpret_cast<const char *>(name));
}
void end_element_callback(void *user_data, const xmlChar *name)
{
Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
input_parser->on_end_element(reinterpret_cast<const char *>(name));
}
void
characters_callback(void *user_data, const xmlChar *characters, int length)
{
Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
input_parser->on_characters(characters, length);
}
}
void bootstrap(const std::vector<El::BigFloat> &objective,
const std::vector<Polynomial_Vector_Matrix> &polVectorMatrices,
SDP &sdp);
Polynomial_Vector_Matrix
parse_polynomial_vector_matrix(const boost::property_tree::ptree &tree);
SDP::SDP(const std::vector<boost::filesystem::path> &sdp_files)
// FIXME: This assigns one core per block. We may want to do
// something more sophisticated for larger blocks.
: grid(El::mpi::COMM_SELF)
{
LIBXML_TEST_VERSION;
std::vector<El::BigFloat> objective;
std::vector<Polynomial_Vector_Matrix> polynomialVectorMatrices;
for(auto &sdp_file : sdp_files)
{
Input_Parser input_parser;
xmlSAXHandler xml_handlers = {0};
xml_handlers.startElement = start_element_callback;
xml_handlers.endElement = end_element_callback;
xml_handlers.characters = characters_callback;
if(xmlSAXUserParseFile(&xml_handlers, &input_parser, sdp_file.c_str())
< 0)
{
throw std::runtime_error("Ill-formed input file: "
+ sdp_file.string());
}
std::swap(input_parser.objective_state.value, objective);
std::swap(input_parser.polynomial_vector_matrices_state.value,
polynomialVectorMatrices);
}
bootstrap(objective, polynomialVectorMatrices, *this);
}
<commit_msg>Properly initialize xml_handlers and setup warning and error callbacks<commit_after>//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
// See the manual for a description of the correct XML input format.
#include "Input_Parser.hxx"
#include "../../SDP.hxx"
#include <boost/filesystem.hpp>
#include <boost/property_tree/xml_parser.hpp>
namespace
{
void start_element_callback(void *user_data, const xmlChar *name,
const xmlChar **)
{
Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
input_parser->on_start_element(reinterpret_cast<const char *>(name));
}
void end_element_callback(void *user_data, const xmlChar *name)
{
Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
input_parser->on_end_element(reinterpret_cast<const char *>(name));
}
void
characters_callback(void *user_data, const xmlChar *characters, int length)
{
Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
input_parser->on_characters(characters, length);
}
void warning_callback(void *, const char *msg, ...)
{
va_list args;
va_start(args, msg);
vprintf(msg, args);
va_end(args);
}
void error_callback(void *, const char *msg, ...)
{
va_list args;
va_start(args, msg);
vprintf(msg, args);
va_end(args);
throw std::runtime_error("Invalid Input file");
}
}
void bootstrap(const std::vector<El::BigFloat> &objective,
const std::vector<Polynomial_Vector_Matrix> &polVectorMatrices,
SDP &sdp);
Polynomial_Vector_Matrix
parse_polynomial_vector_matrix(const boost::property_tree::ptree &tree);
SDP::SDP(const std::vector<boost::filesystem::path> &sdp_files)
// FIXME: This assigns one core per block. We may want to do
// something more sophisticated for larger blocks.
: grid(El::mpi::COMM_SELF)
{
LIBXML_TEST_VERSION;
std::vector<El::BigFloat> objective;
std::vector<Polynomial_Vector_Matrix> polynomialVectorMatrices;
for(auto &sdp_file : sdp_files)
{
Input_Parser input_parser;
xmlSAXHandler xml_handlers;
// This feels unclean.
memset(&xml_handlers, 0, sizeof(xml_handlers));
xml_handlers.startElement = start_element_callback;
xml_handlers.endElement = end_element_callback;
xml_handlers.characters = characters_callback;
xml_handlers.warning = warning_callback;
xml_handlers.error = error_callback;
if(xmlSAXUserParseFile(&xml_handlers, &input_parser, sdp_file.c_str())
< 0)
{
throw std::runtime_error("Ill-formed input file: "
+ sdp_file.string());
}
std::swap(input_parser.objective_state.value, objective);
std::swap(input_parser.polynomial_vector_matrices_state.value,
polynomialVectorMatrices);
}
bootstrap(objective, polynomialVectorMatrices, *this);
}
<|endoftext|>
|
<commit_before>/**
* Compile-time sieve of Eratosthenes.
*
* See it in action at:
*
* Presently, this will only build with gcc-7.0.0 (experimental version) or later. To build, invoke g++ with the -std=c++17 flag.
*
* Copyright Dr Robert H Crowston, 2017, all rights reserved.
* Use and redistribution is permitted under the BSD Licence available at https://opensource.org/licenses/bsd-license.php.
*
* Bugs and to do:
* o This is not a true implementation of Eratosthenes’ method because every factor will be checked even if it was
* already encountered as a multiple of a lower factor.
*
*/
#include <cassert>
#include <climits>
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <type_traits>
#include <utility>
namespace rhc
{
namespace detail
{
template <typename T,
typename = std::enable_if_t<std::is_integral<T>::value>
>
constexpr T ceil(float number)
{ // Note: std::ceil is not constexpr, so own implementation here.
return (static_cast<float>(static_cast<T>(number)) == number) ?
static_cast<T>(number) : static_cast<T>(number) + ((number > 0) ? 1 : 0);
}
}
using std::size_t;
template <size_t Size>
class bit_array
{
constexpr static size_t bits = Size;
constexpr static size_t bytes = detail::ceil<size_t>(static_cast<float>(bits) / CHAR_BIT);
std::byte storage[bytes]; // Raw backing storage.
static constexpr size_t index_to_byte (const size_t index)
{ // Logical index to byte map.
return index/CHAR_BIT;
}
static constexpr size_t index_to_offset (const size_t index)
{ // Get the offset within one byte.
return index - CHAR_BIT*(index/CHAR_BIT);
}
public:
constexpr bit_array() : storage{} { ; }
template <typename T,
typename = std::enable_if_t<std::is_integral<T>::value>
>
constexpr bit_array (const T integer)
: storage{*reinterpret_cast<const std::byte*>(&integer)}
{ ; }
constexpr bit_array (const std::initializer_list<bool>& list) : storage {}
{
assert(list.size() <= bits);
size_t index = 0;
for (const auto& bit : list)
{
storage[index_to_byte(index)] |= std::byte(bit << index_to_offset(index));
++index;
}
}
constexpr bit_array (const bit_array<Size>& ) = default;
constexpr bool operator[](const std::size_t index) const
{
return static_cast<bool>(
(storage[index_to_byte(index)] >> index_to_offset(index)) & std::byte(0x1)
);
}
}; // End of class bit_array.
} // End of namespace rhc.
namespace rhc::primes
{
using uint_t = std::uintmax_t;
using index_t = std::size_t;
using std::size_t;
// I omit storing the primality of 0, 1, and the even numbers because each is trivially known.
// Little helper to remap from number to array index.
constexpr index_t to_index (const uint_t number)
{
return (number-3)/2;
}
// And the reverse.
constexpr uint_t to_number (const index_t idx)
{
return idx*2 + 3;
}
template <uint_t Size>
using table = rhc::bit_array<Size>;
template <uint_t Size, uint_t Factor, index_t ... Is>
constexpr auto get_factor_table(std::index_sequence<Is ...> )
-> table<Size>
{ // NB. this line does not compile on Clang 3.9.1.
return { to_number(Is) % Factor == 0 && to_number(Is) > Factor ... };
}
template <uint_t Size, index_t ... Is>
constexpr auto merge_factors(const table<Size> lhs, const table<Size> rhs, std::index_sequence<Is ...> )
-> table<Size>
{
return { static_cast<bool>(lhs[Is] | rhs[Is]) ... };
}
template <uint_t Size, uint_t MaxFactor, uint_t PresentFactor>
struct merged_factor_table
{
//static_assert(MaxFactor == 2*Size+1);
constexpr static auto get()
-> table<Size>
{
using Indices = std::make_index_sequence<Size>;
constexpr auto preceding_composites = merged_factor_table<Size, MaxFactor, PresentFactor-2>::get();
if (preceding_composites[to_index(PresentFactor)])
// Known composite; skip.
return preceding_composites;
else
return merge_factors(
get_factor_table<Size, PresentFactor>(Indices()),
preceding_composites,
Indices()
);
}
};
template <uint_t Size, uint_t MaxFactor>
struct merged_factor_table<Size, MaxFactor, 3>
{
constexpr static auto get()
-> table<Size>
{
using Indices = std::make_index_sequence<Size>;
return get_factor_table<Size, 3>(Indices());
}
};
template <size_t MaxNumber>
constexpr bool check(const uint_t num)
{
constexpr size_t Size = MaxNumber/2;
if (num == 0 || num == 1) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
constexpr auto composites = merged_factor_table<Size, MaxNumber, MaxNumber>::get();
return !composites[to_index(num)];
}
// Arbitrary check list.
static_assert(!check<17>( 0));
static_assert(!check< 7>( 1));
static_assert( check< 7>( 2));
static_assert( check< 7>( 3));
static_assert(!check< 7>( 4));
static_assert( check<71>( 5));
static_assert(!check<71>( 6));
static_assert( check<71>( 7));
static_assert( check<71>(29));
static_assert(!check<71>(33));
} // namespace rhc::primes.
bool is_prime(const rhc::primes::uint_t num)
{
return rhc::primes::check<1001>(num);
}
<commit_msg>Multiples of known composites are now skipped.<commit_after>/**
* Compile-time sieve of Eratosthenes.
*
* See it in action at:
*
* Presently, this will only build with gcc-7.0.0 (experimental version) or later. To build, invoke g++ with the -std=c++17 flag.
*
* Copyright Dr Robert H Crowston, 2017, all rights reserved.
* Use and redistribution is permitted under the BSD Licence available at https://opensource.org/licenses/bsd-license.php.
*
* Bugs and to do:
* o Check whether this use of fold expresions is really permissible.
*
*/
#include <cassert>
#include <climits>
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <type_traits>
#include <utility>
namespace rhc
{
namespace detail
{
template <typename T,
typename = std::enable_if_t<std::is_integral<T>::value>
>
constexpr T ceil(float number)
{ // Note: std::ceil is not constexpr, so own implementation here.
return (static_cast<float>(static_cast<T>(number)) == number) ?
static_cast<T>(number) : static_cast<T>(number) + ((number > 0) ? 1 : 0);
}
}
using std::size_t;
template <size_t Size>
class bit_array
{
constexpr static size_t bits = Size;
constexpr static size_t bytes = detail::ceil<size_t>(static_cast<float>(bits) / CHAR_BIT);
std::byte storage[bytes]; // Raw backing storage.
static constexpr size_t index_to_byte (const size_t index)
{ // Logical index to byte map.
return index/CHAR_BIT;
}
static constexpr size_t index_to_offset (const size_t index)
{ // Get the offset within one byte.
return index - CHAR_BIT*(index/CHAR_BIT);
}
public:
constexpr bit_array() : storage{} { ; }
template <typename T,
typename = std::enable_if_t<std::is_integral<T>::value>
>
constexpr bit_array (const T integer)
: storage{*reinterpret_cast<const std::byte*>(&integer)}
{ ; }
constexpr bit_array (const std::initializer_list<bool>& list) : storage {}
{
assert(list.size() <= bits);
size_t index = 0;
for (const auto& bit : list)
{
storage[index_to_byte(index)] |= std::byte(bit << index_to_offset(index));
++index;
}
}
constexpr bit_array (const bit_array<Size>& ) = default;
constexpr bool operator[](const std::size_t index) const
{
return static_cast<bool>(
(storage[index_to_byte(index)] >> index_to_offset(index)) & std::byte(0x1)
);
}
}; // End of class bit_array.
} // End of namespace rhc.
namespace rhc::primes
{
using uint_t = std::uintmax_t;
using index_t = std::size_t;
using std::size_t;
// I omit storing the primality of 0, 1, and the even numbers because each is trivially known.
// Little helper to remap from number to array index.
constexpr index_t to_index (const uint_t number)
{
return (number-3)/2;
}
// And the reverse.
constexpr uint_t to_number (const index_t idx)
{
return idx*2 + 3;
}
template <uint_t Size>
using table = rhc::bit_array<Size>;
template <uint_t Size, uint_t Factor, index_t ... Is>
constexpr auto get_factor_table(std::index_sequence<Is ...> )
-> table<Size>
{ // NB. this line does not compile on Clang 3.9.1.
return { to_number(Is) % Factor == 0 && to_number(Is) > Factor ... };
}
template <uint_t Size, index_t ... Is>
constexpr auto merge_factors(const table<Size> lhs, const table<Size> rhs, std::index_sequence<Is ...> )
-> table<Size>
{
return { static_cast<bool>(lhs[Is] | rhs[Is]) ... };
}
template <uint_t Size, uint_t MaxFactor, uint_t PresentFactor>
struct merged_factor_table
{
//static_assert(MaxFactor == 2*Size+1);
constexpr static auto get()
-> table<Size>
{
using Indices = std::make_index_sequence<Size>;
constexpr auto preceding_composites = merged_factor_table<Size, MaxFactor, PresentFactor-2>::get();
if (preceding_composites[to_index(PresentFactor)])
// Known composite; skip.
return preceding_composites;
else
return merge_factors(
get_factor_table<Size, PresentFactor>(Indices()),
preceding_composites,
Indices()
);
}
};
template <uint_t Size, uint_t MaxFactor>
struct merged_factor_table<Size, MaxFactor, 3>
{
constexpr static auto get()
-> table<Size>
{
using Indices = std::make_index_sequence<Size>;
return get_factor_table<Size, 3>(Indices());
}
};
template <size_t MaxNumber>
constexpr bool check(const uint_t num)
{
constexpr size_t Size = MaxNumber/2;
if (num == 0 || num == 1) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
constexpr auto composites = merged_factor_table<Size, MaxNumber, MaxNumber>::get();
return !composites[to_index(num)];
}
// Arbitrary check list.
static_assert(!check<17>( 0));
static_assert(!check< 7>( 1));
static_assert( check< 7>( 2));
static_assert( check< 7>( 3));
static_assert(!check< 7>( 4));
static_assert( check<71>( 5));
static_assert(!check<71>( 6));
static_assert( check<71>( 7));
static_assert( check<71>(29));
static_assert(!check<71>(33));
} // namespace rhc::primes.
bool is_prime(const rhc::primes::uint_t num)
{
return rhc::primes::check<1001>(num);
}
<|endoftext|>
|
<commit_before>#include "RoadRoller.h"
RoadRoller::RoadRoller()
{
}
void RoadRoller::build()
{
Vector nullVec = Vector(0.0f, 0.0f, 0.0f);
Circle* wheelSide = new Circle(0.0f, 0.0f, 0.3f, 1.0f);
Cylinder* wheel = new Cylinder(0.0f, 0.0f, 1.0f, 2.0f, 1.0f);
Cylinder* exhaust = new Cylinder(0.0f, 0.0f, 0.16f, 2.0f, 1.0f);
_acceleration = _velocity = _position = nullVec;
_rotateVelocity = 0.0f;
_rotateFi = 0.0f;
_boundingRadius = 1.5f;
Cube* chassisBottom = new Cube(1.0f, 1.0f, 1.0f, 2.0f, 1.0f, 2.0f);
Cube* chassisMiddle = new Cube(3.0f, 1.5f, 1.0f, 6.0f, 0.5f, 2.0f);
Cube* chassisCockpit = new Cube(1.0f, 1.5f, 0.7f, 2.0f, -1.5f, 1.4f);
Cube* chassisTop = new Cube(1.13f, 3.0f, 1.13f, 2.26f, -0.13f, 2.26f);
chassisBottom->tesselate();
chassisMiddle->tesselate();
chassisCockpit->tesselate();
chassisTop->tesselate();
wheelSide->tesselate();
wheel->tesselate();
exhaust->tesselate();
_wheelSide = wheelSide;
_wheel = wheel;
_exhaust = exhaust;
_chassis[0] = chassisBottom;
_chassis[1] = chassisMiddle;
_chassis[2] = chassisCockpit;
_chassis[3] = chassisTop;
_chassisMaterial.kAmbient = Color(1.0f, 0.843f, 0.0f);
_chassisMaterial.kDiffuse = Color(1.0f, 0.843f, 0.0f);
_chassisMaterial.isSpecular = true;
_chassisMaterial.kSpecular = Color(1.0f, 1.0f, 1.0f);
_chassisMaterial.shininess = 40.0f;
_wheelMaterial.kAmbient = Color(0.412f, 0.412f, 0.412f);
_wheelMaterial.kDiffuse = Color(0.412f, 0.412f, 0.412f);
_wheelMaterial.isSpecular = false;
_wheelMaterial.kSpecular = Color(0.0f, 0.0f, 0.0f);
_wheelMaterial.shininess = 0.0f;
_texture.generate();
}
void RoadRoller::render()
{
if (!_isShadowMode)
_wheelMaterial.setup_gl();
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glTranslatef(2.0f, 0.0f, 1.0f);
glRotatef(_rotateFi, 0.0f, 0.0f, 1.0f);
_wheelSide->render();
glPopMatrix();
glPushMatrix();
glTranslatef(2.0f, 0.0f, -1.0f);
glRotatef(_rotateFi, 0.0f, 0.0f, 1.0f);
_wheelSide->render();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.0f, 0.0f, 1.0f);
glRotatef(_rotateFi, 0.0f, 0.0f, 1.0f);
_wheelSide->render();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.0f, 0.0f, -1.0f);
glRotatef(_rotateFi, 0.0f, 0.0f, 1.0f);
_wheelSide->render();
glPopMatrix();
if (!_isShadowMode)
_texture.setup_gl();
glPushMatrix();
glTranslatef(2.0f, 0.0f, -1.0f);
glRotatef(_rotateFi, 0.0f, 0.0f, 1.0f);
_wheel->render();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.0f, 0.0f, -1.0f);
glRotatef(_rotateFi, 0.0f, 0.0f, 1.0f);
_wheel->render();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
if (!_isShadowMode)
_chassisMaterial.setup_gl();
_chassis[0]->render();
_chassis[1]->render();
_chassisMaterial.kAmbient = Color(0.138f, 0.42f, 0.557f);
_chassisMaterial.kDiffuse = Color(0.138f, 0.42f, 0.557f);
_chassisMaterial.shininess = 200.0f;
if (!_isShadowMode)
_chassisMaterial.setup_gl();
_chassis[2]->render();
_chassisMaterial.kAmbient = Color(1.0f, 0.843f, 0.0f);
_chassisMaterial.kDiffuse = Color(1.0f, 0.843f, 0.0f);
_chassisMaterial.shininess = 40.0f;
if (!_isShadowMode)
_chassisMaterial.setup_gl();
_chassis[3]->render();
if (!_isShadowMode)
_wheelMaterial.setup_gl();
glPushMatrix();
glTranslatef(1.8f, 3.0f, -0.7f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
_exhaust->render();
glPopMatrix();
}
void RoadRoller::setTransformations()
{
glTranslatef(_position.x, 1.0f + _position.y, _position.z);
}
void RoadRoller::update(float deltaT)
{
_velocity += _acceleration * deltaT;
_position += _velocity * deltaT;
_rotateVelocity += 0.3f * _acceleration.x * deltaT;
_rotateFi -= _rotateVelocity * deltaT * 0.3183f * 180.0f;
}
RoadRoller::~RoadRoller()
{
if (_wheelSide != nullptr)
{
delete _wheelSide;
}
if (_wheel != nullptr)
{
delete _wheel;
}
if (_exhaust != nullptr)
{
delete _exhaust;
}
//if (_chassis != nullptr)
//{
// delete _chassis;
//}
}<commit_msg>Fixed the updated primitives in the RoadRoller game object.<commit_after>#include "RoadRoller.h"
RoadRoller::RoadRoller()
{
}
void RoadRoller::build()
{
Vector nullVec = Vector(0.0f, 0.0f, 0.0f);
Circle* wheelSide = new Circle(0.0f, 0.0f, 0.3f, 1.0f);
Cylinder* wheel = new Cylinder(1.0f, 2.0f, 1.0f);
Cylinder* exhaust = new Cylinder(0.16f, 2.0f, 1.0f);
_acceleration = _velocity = _position = nullVec;
_rotateVelocity = 0.0f;
_rotateFi = 0.0f;
_boundingRadius = 1.5f;
Cube* chassisBottom = new Cube(1.0f, 1.0f, 1.0f, 2.0f, 1.0f, 2.0f);
Cube* chassisMiddle = new Cube(3.0f, 1.5f, 1.0f, 6.0f, 0.5f, 2.0f);
Cube* chassisCockpit = new Cube(1.0f, 1.5f, 0.7f, 2.0f, -1.5f, 1.4f);
Cube* chassisTop = new Cube(1.13f, 3.0f, 1.13f, 2.26f, -0.13f, 2.26f);
chassisBottom->tesselate();
chassisMiddle->tesselate();
chassisCockpit->tesselate();
chassisTop->tesselate();
wheelSide->tesselate();
wheel->tesselate();
exhaust->tesselate();
_wheelSide = wheelSide;
_wheel = wheel;
_exhaust = exhaust;
_chassis[0] = chassisBottom;
_chassis[1] = chassisMiddle;
_chassis[2] = chassisCockpit;
_chassis[3] = chassisTop;
_chassisMaterial.kAmbient = Color(1.0f, 0.843f, 0.0f);
_chassisMaterial.kDiffuse = Color(1.0f, 0.843f, 0.0f);
_chassisMaterial.isSpecular = true;
_chassisMaterial.kSpecular = Color(1.0f, 1.0f, 1.0f);
_chassisMaterial.shininess = 40.0f;
_wheelMaterial.kAmbient = Color(0.412f, 0.412f, 0.412f);
_wheelMaterial.kDiffuse = Color(0.412f, 0.412f, 0.412f);
_wheelMaterial.isSpecular = false;
_wheelMaterial.kSpecular = Color(0.0f, 0.0f, 0.0f);
_wheelMaterial.shininess = 0.0f;
_texture.generate();
}
void RoadRoller::render()
{
if (!_isShadowMode)
_wheelMaterial.setup_gl();
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glTranslatef(2.0f, 0.0f, 1.0f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glRotatef(_rotateFi, 0.0f, 1.0f, 0.0f);
_wheelSide->render();
glPopMatrix();
glPushMatrix();
glTranslatef(2.0f, 0.0f, -1.0f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glRotatef(_rotateFi, 0.0f, 1.0f, 0.0f);
_wheelSide->render();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.0f, 0.0f, 1.0f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glRotatef(_rotateFi, 0.0f, 1.0f, 0.0f);
_wheelSide->render();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.0f, 0.0f, -1.0f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glRotatef(_rotateFi, 0.0f, 1.0f, 0.0f);
_wheelSide->render();
glPopMatrix();
if (!_isShadowMode)
_texture.setup_gl();
glPushMatrix();
glTranslatef(2.0f, 0.0f, -1.0f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glRotatef(_rotateFi, 0.0f, 1.0f, 0.0f);
_wheel->render();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.0f, 0.0f, -1.0f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glRotatef(_rotateFi, 0.0f, 1.0f, 0.0f);
_wheel->render();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
if (!_isShadowMode)
_chassisMaterial.setup_gl();
_chassis[0]->render();
_chassis[1]->render();
_chassisMaterial.kAmbient = Color(0.138f, 0.42f, 0.557f);
_chassisMaterial.kDiffuse = Color(0.138f, 0.42f, 0.557f);
_chassisMaterial.shininess = 200.0f;
if (!_isShadowMode)
_chassisMaterial.setup_gl();
_chassis[2]->render();
_chassisMaterial.kAmbient = Color(1.0f, 0.843f, 0.0f);
_chassisMaterial.kDiffuse = Color(1.0f, 0.843f, 0.0f);
_chassisMaterial.shininess = 40.0f;
if (!_isShadowMode)
_chassisMaterial.setup_gl();
_chassis[3]->render();
if (!_isShadowMode)
_wheelMaterial.setup_gl();
glPushMatrix();
glTranslatef(1.8f, 1.0f, -0.7f);
_exhaust->render();
glPopMatrix();
}
void RoadRoller::setTransformations()
{
glTranslatef(_position.x, 1.0f + _position.y, _position.z);
}
void RoadRoller::update(float deltaT)
{
_velocity += _acceleration * deltaT;
_position += _velocity * deltaT;
_rotateVelocity += 0.3f * _acceleration.x * deltaT;
_rotateFi -= _rotateVelocity * deltaT * 0.3183f * 180.0f;
}
RoadRoller::~RoadRoller()
{
if (_wheelSide != nullptr)
{
delete _wheelSide;
}
if (_wheel != nullptr)
{
delete _wheel;
}
if (_exhaust != nullptr)
{
delete _exhaust;
}
//if (_chassis != nullptr)
//{
// delete _chassis;
//}
}<|endoftext|>
|
<commit_before>//
// peglint.cc
//
// Copyright (c) 2015 Yuji Hirose. All rights reserved.
// MIT License
//
#include <peglib.h>
#include <fstream>
using namespace std;
bool read_file(const char* path, vector<char>& buff)
{
ifstream ifs(path, ios::in | ios::binary);
if (ifs.fail()) {
return false;
}
buff.resize(static_cast<unsigned int>(ifs.seekg(0, ios::end).tellg()));
if (!buff.empty()) {
ifs.seekg(0, ios::beg).read(&buff[0], static_cast<streamsize>(buff.size()));
}
return true;
}
int main(int argc, const char** argv)
{
if (argc < 2 || string("--help") == argv[1]) {
cerr << "usage: peglint [grammar file path] [source file path]" << endl;
return 1;
}
// Check PEG grammar
auto syntax_path = argv[1];
vector<char> syntax;
if (!read_file(syntax_path, syntax)) {
cerr << "can't open the grammar file." << endl;
return -1;
}
peglib::peg peg;
peg.log = [&](size_t ln, size_t col, const string& msg) {
cerr << syntax_path << ":" << ln << ":" << col << ": " << msg << endl;
};
if (!peg.load_grammar(syntax.data(), syntax.size())) {
return -1;
}
if (argc < 3) {
return 0;
}
// Check source
auto source_path = argv[2];
vector<char> source;
if (!read_file(source_path, source)) {
cerr << "can't open the source file." << endl;
return -1;
}
peg.log = [&](size_t ln, size_t col, const string& msg) {
cerr << source_path << ":" << ln << ":" << col << ": " << msg << endl;
};
if (!peg.parse_n(source.data(), source.size())) {
return -1;
}
return 0;
}
// vim: et ts=4 sw=4 cin cino={1s ff=unix
<commit_msg>Added AST and command line string features in peglint.<commit_after>//
// peglint.cc
//
// Copyright (c) 2015 Yuji Hirose. All rights reserved.
// MIT License
//
#include <peglib.h>
#include <fstream>
using namespace std;
bool read_file(const char* path, vector<char>& buff)
{
ifstream ifs(path, ios::in | ios::binary);
if (ifs.fail()) {
return false;
}
buff.resize(static_cast<unsigned int>(ifs.seekg(0, ios::end).tellg()));
if (!buff.empty()) {
ifs.seekg(0, ios::beg).read(&buff[0], static_cast<streamsize>(buff.size()));
}
return true;
}
int main(int argc, const char** argv)
{
auto opt_ast = false;
auto opt_help = false;
vector<const char*> path_list;
int argi = 1;
while (argi < argc) {
auto arg = argv[argi++];
if (string("--help") == arg) {
opt_help = true;
} else if (string("--ast") == arg) {
opt_ast = true;
} else {
path_list.push_back(arg);
}
}
if (path_list.empty() || opt_help) {
cerr << "usage: peglint [--ast] [grammar file path] [source file path]" << endl;
return 1;
}
// Check PEG grammar
auto syntax_path = path_list[0];
vector<char> syntax;
if (!read_file(syntax_path, syntax)) {
cerr << "can't open the grammar file." << endl;
return -1;
}
peglib::peg peg;
peg.log = [&](size_t ln, size_t col, const string& msg) {
cerr << syntax_path << ":" << ln << ":" << col << ": " << msg << endl;
};
if (!peg.load_grammar(syntax.data(), syntax.size())) {
return -1;
}
if (path_list.size() < 2) {
return 0;
}
// Check source
auto source_path = path_list[1];
vector<char> source;
if (!read_file(source_path, source)) {
auto beg = source_path;
auto end = source_path + strlen(source_path);
source.assign(beg, end);
source_path = "[commendline]";
}
peg.log = [&](size_t ln, size_t col, const string& msg) {
cerr << source_path << ":" << ln << ":" << col << ": " << msg << endl;
};
if (opt_ast) {
peg.enable_ast();
std::shared_ptr<peglib::Ast> ast;
if (!peg.parse_n(source.data(), source.size(), ast)) {
return -1;
}
peglib::AstPrint().print(*ast);
} else {
if (!peg.parse_n(source.data(), source.size())) {
return -1;
}
}
return 0;
}
// vim: et ts=4 sw=4 cin cino={1s ff=unix
<|endoftext|>
|
<commit_before>/*
* event_server.cpp
* PHD Guiding
*
* Created by Andy Galasso.
* Copyright (c) 2013 Andy Galasso.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs 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 "phd.h"
#include <wx/sstream.h>
#include <wx/sckstrm.h>
EventServer EvtServer;
BEGIN_EVENT_TABLE(EventServer, wxEvtHandler)
EVT_SOCKET(EVENT_SERVER_ID, EventServer::OnEventServerEvent)
EVT_SOCKET(EVENT_SERVER_CLIENT_ID, EventServer::OnEventServerClientEvent)
END_EVENT_TABLE()
static wxString state_name(EXPOSED_STATE st)
{
switch (st)
{
case EXPOSED_STATE_NONE: return "Stopped";
case EXPOSED_STATE_SELECTED: return "Selected";
case EXPOSED_STATE_CALIBRATING: return "Calibrating";
case EXPOSED_STATE_GUIDING_LOCKED: return "Guiding";
case EXPOSED_STATE_GUIDING_LOST: return "LostLock";
case EXPOSED_STATE_PAUSED: return "Paused";
case EXPOSED_STATE_LOOPING: return "Looping";
default: return "Unknown";
}
}
// name-value pair
struct NV
{
wxString n;
wxString v;
NV(const wxString& n_, const wxString& v_) : n(n_), v('"'+v_+'"') { }
NV(const wxString& n_, int v_) : n(n_), v(wxString::Format("%d", v_)) { }
NV(const wxString& n_, double v_) : n(n_), v(wxString::Format("%g", v_)) { }
NV(const wxString& n_, double v_, int prec) : n(n_), v(wxString::Format("%.*f", prec, v_)) { }
};
NV NVMount(const Mount *mount)
{
return NV("Mount", mount->Name());
}
struct JObj
{
wxString m_s;
bool m_first;
bool m_closed;
JObj() : m_first(true), m_closed(false) { m_s << "{"; }
void close() { m_s << "}"; m_closed = true; }
wxString str() { if (!m_closed) close(); return m_s; }
};
JObj& operator<<(JObj& j, const NV& nv)
{
if (j.m_first)
j.m_first = false;
else
j.m_s << ',';
j.m_s << '"' << nv.n << "\":" << nv.v;
return j;
}
JObj& operator<<(JObj& j, const PHD_Point& pt)
{
j << NV("X", pt.X, 3) << NV("Y", pt.Y, 3);
return j;
}
struct Ev : public JObj
{
Ev(const wxString& event)
{
double const now = ::wxGetUTCTimeMillis().ToDouble() / 1000.0;
*this << NV("Event", event)
<< NV("Timestamp", now, 3)
<< NV("Host", wxGetHostName())
<< NV("Inst", pFrame->GetInstanceNumber());
}
};
static Ev ev_set_lock_position(const PHD_Point& xy)
{
Ev ev("LockPositionSet");
ev << xy;
return ev;
}
static Ev ev_calibration_complete(Mount *mount)
{
Ev ev("CalibrationComplete");
ev << NVMount(mount);
return ev;
}
static Ev ev_star_selected(const PHD_Point& pos)
{
Ev ev("StarSelected");
ev << pos;
return ev;
}
static Ev ev_start_guiding()
{
return Ev("StartGuiding");
}
static Ev ev_paused()
{
return Ev("Paused");
}
static Ev ev_start_calibration(Mount *mount)
{
Ev ev("StartCalibration");
ev << NVMount(mount);
return ev;
}
static Ev ev_app_state(EXPOSED_STATE st = Guider::GetExposedState())
{
Ev ev("AppState");
ev << NV("State", state_name(st));
return ev;
}
static void send_buf(wxSocketClient *client, const wxCharBuffer& buf)
{
client->Write(buf.data(), buf.length());
client->Write("\r\n", 2);
}
static void do_notify1(wxSocketClient *client, const JObj& jj)
{
send_buf(client, JObj(jj).str().ToUTF8());
}
static void do_notify(const EventServer::CliSockSet& cli, const JObj& jj)
{
wxCharBuffer buf = JObj(jj).str().ToUTF8();
for (EventServer::CliSockSet::const_iterator it = cli.begin();
it != cli.end(); ++it)
{
send_buf(*it, buf);
}
}
inline static void simple_notify(const EventServer::CliSockSet& cli, const wxString& ev)
{
if (!cli.empty())
do_notify(cli, Ev(ev));
}
inline static void simple_notify_ev(const EventServer::CliSockSet& cli, const Ev& ev)
{
if (!cli.empty())
do_notify(cli, ev);
}
#define SIMPLE_NOTIFY(s) simple_notify(m_eventServerClients, s)
#define SIMPLE_NOTIFY_EV(ev) simple_notify_ev(m_eventServerClients, ev)
static void send_catchup_events(wxSocketClient *cli)
{
EXPOSED_STATE st = Guider::GetExposedState();
if (pFrame->pGuider)
{
if (pFrame->pGuider->LockPosition().IsValid())
do_notify1(cli, ev_set_lock_position(pFrame->pGuider->LockPosition()));
if (pFrame->pGuider->CurrentPosition().IsValid())
do_notify1(cli, ev_star_selected(pFrame->pGuider->CurrentPosition()));
}
if (pMount && pMount->IsCalibrated())
do_notify1(cli, ev_calibration_complete(pMount));
if (pSecondaryMount && pSecondaryMount->IsCalibrated())
do_notify1(cli, ev_calibration_complete(pSecondaryMount));
if (st == EXPOSED_STATE_GUIDING_LOCKED)
{
do_notify1(cli, ev_start_guiding());
}
else if (st == EXPOSED_STATE_CALIBRATING)
{
Mount *mount = pMount;
if (pFrame->pGuider->GetState() == STATE_CALIBRATING_SECONDARY)
mount = pSecondaryMount;
do_notify1(cli, ev_start_calibration(mount));
}
else if (st == EXPOSED_STATE_PAUSED) {
do_notify1(cli, ev_paused());
}
do_notify1(cli, ev_app_state());
}
EventServer::EventServer()
{
}
EventServer::~EventServer()
{
}
bool EventServer::EventServerStart(unsigned int instanceId)
{
if (m_serverSocket)
{
Debug.AddLine("attempt to start event server when it is already started?");
return false;
}
unsigned int port = 4400 + instanceId - 1;
wxIPV4address eventServerAddr;
eventServerAddr.Service(port);
m_serverSocket = new wxSocketServer(eventServerAddr);
if (!m_serverSocket->Ok())
{
wxLogStatus(wxString::Format("Event server failed to start - Could not listen at port %u", port));
delete m_serverSocket;
m_serverSocket = NULL;
return true;
}
m_serverSocket->SetEventHandler(*this, EVENT_SERVER_ID);
m_serverSocket->SetNotify(wxSOCKET_CONNECTION_FLAG);
m_serverSocket->Notify(true);
Debug.AddLine(wxString::Format("event server started, listening on port %u", port));
return false;
}
void EventServer::EventServerStop()
{
if (!m_serverSocket)
return;
for (CliSockSet::const_iterator it = m_eventServerClients.begin();
it != m_eventServerClients.end(); ++it)
{
(*it)->Destroy();
}
m_eventServerClients.clear();
delete m_serverSocket;
m_serverSocket = NULL;
Debug.AddLine("event server stopped");
}
void EventServer::OnEventServerEvent(wxSocketEvent& event)
{
wxSocketServer *server = static_cast<wxSocketServer *>(event.GetSocket());
if (event.GetSocketEvent() != wxSOCKET_CONNECTION)
return;
wxSocketClient *client = static_cast<wxSocketClient *>(server->Accept(false));
if (!client)
return;
Debug.AddLine("event server client connected");
client->SetEventHandler(*this, EVENT_SERVER_CLIENT_ID);
client->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
client->SetFlags(wxSOCKET_NOWAIT);
client->Notify(true);
send_catchup_events(client);
m_eventServerClients.insert(client);
}
void EventServer::OnEventServerClientEvent(wxSocketEvent& event)
{
wxSocketClient *cli = static_cast<wxSocketClient *>(event.GetSocket());
if (event.GetSocketEvent() == wxSOCKET_LOST)
{
Debug.AddLine("event server client disconnected");
unsigned int const n = m_eventServerClients.erase(cli);
if (n != 1)
Debug.AddLine("client disconnected but not present in client set!");
cli->Destroy();
}
else if (event.GetSocketEvent() == wxSOCKET_INPUT)
{
// consume the input
// TODO: parse input message
wxSocketInputStream sis(*cli);
while (sis.CanRead())
{
char buf[4096];
sis.Read(buf, sizeof(buf));
if (sis.LastRead() == 0)
break;
}
do_notify1(cli, ev_app_state());
}
else
{
Debug.AddLine("unexpected client socket event %d", event.GetSocketEvent());
}
}
void EventServer::NotifyStartCalibration(Mount *mount)
{
SIMPLE_NOTIFY_EV(ev_start_calibration(mount));
}
void EventServer::NotifyCalibrationFailed(Mount *mount, const wxString& msg)
{
if (m_eventServerClients.empty())
return;
Ev ev("CalibrationFailed");
ev << NVMount(mount) << NV("Reason", msg);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifyCalibrationComplete(Mount *mount)
{
if (m_eventServerClients.empty())
return;
do_notify(m_eventServerClients, ev_calibration_complete(mount));
}
void EventServer::NotifyCalibrationDataFlipped(Mount *mount)
{
if (m_eventServerClients.empty())
return;
Ev ev("CalibrationDataFlipped");
ev << NVMount(mount);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifyLooping(unsigned int exposure)
{
if (m_eventServerClients.empty())
return;
Ev ev("LoopingExposures");
ev << NV("Frame", (int) exposure);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifyLoopingStopped()
{
SIMPLE_NOTIFY("LoopingExposuresStopped");
}
void EventServer::NotifyStarSelected(const PHD_Point& pt)
{
SIMPLE_NOTIFY_EV(ev_star_selected(pt));
}
void EventServer::NotifyStarLost()
{
SIMPLE_NOTIFY("StarLost");
}
void EventServer::NotifyStartGuiding()
{
SIMPLE_NOTIFY_EV(ev_start_guiding());
}
void EventServer::NotifyGuidingStopped()
{
SIMPLE_NOTIFY("GuidingStopped");
}
void EventServer::NotifyPaused()
{
SIMPLE_NOTIFY_EV(ev_paused());
}
void EventServer::NotifyResumed()
{
SIMPLE_NOTIFY("Resumed");
}
void EventServer::NotifyGuideStep(Mount *pGuideMount, const PHD_Point& vectorEndpoint, double RADuration, double RADistance,
double DECDuration, double DECDistance, int errorCode)
{
if (m_eventServerClients.empty())
return;
Ev ev("GuideStep");
ev << NV("Frame", (int) pFrame->m_frameCounter)
<< NV("Time", (wxDateTime::UNow() - pFrame->m_guidingStarted).GetMilliseconds().ToDouble() / 1000.0, 3)
<< NV("mount", pGuideMount->Name())
<< NV("dx", vectorEndpoint.X, 3)
<< NV("dy", vectorEndpoint.Y, 3)
<< NV("Theta", vectorEndpoint.Angle(PHD_Point(0., 0.)), 3)
<< NV("RADuration", RADuration, 3)
<< NV("RADistance", RADistance, 3)
<< NV("RADirection", RADistance >= 0.0 ? "E" : "W")
<< NV("DECDuration", DECDuration, 3)
<< NV("DECDistance", DECDistance, 3)
<< NV("DECDirection", DECDistance >= 0.0 ? "S" : "N")
<< NV("StarMass", pFrame->pGuider->StarMass(), 0)
<< NV("SNR", pFrame->pGuider->SNR(), 2);
if (errorCode)
ev << NV("ErrorCode", errorCode);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifyGuidingDithered(double dx, double dy)
{
if (m_eventServerClients.empty())
return;
Ev ev("GuidingDithered");
ev << NV("dx", dx, 3) << NV("dy", dy, 3);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifySetLockPosition(const PHD_Point& xy)
{
if (m_eventServerClients.empty())
return;
do_notify(m_eventServerClients, ev_set_lock_position(xy));
}
void EventServer::NotifyLockPositionLost()
{
SIMPLE_NOTIFY("LockPositionLost");
}
void EventServer::NotifyAppState()
{
if (m_eventServerClients.empty())
return;
do_notify(m_eventServerClients, ev_app_state());
}
<commit_msg>event server: send version message when client connects<commit_after>/*
* event_server.cpp
* PHD Guiding
*
* Created by Andy Galasso.
* Copyright (c) 2013 Andy Galasso.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs 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 "phd.h"
#include <wx/sstream.h>
#include <wx/sckstrm.h>
EventServer EvtServer;
BEGIN_EVENT_TABLE(EventServer, wxEvtHandler)
EVT_SOCKET(EVENT_SERVER_ID, EventServer::OnEventServerEvent)
EVT_SOCKET(EVENT_SERVER_CLIENT_ID, EventServer::OnEventServerClientEvent)
END_EVENT_TABLE()
enum
{
MSG_PROTOCOL_VERSION = 1,
};
static wxString state_name(EXPOSED_STATE st)
{
switch (st)
{
case EXPOSED_STATE_NONE: return "Stopped";
case EXPOSED_STATE_SELECTED: return "Selected";
case EXPOSED_STATE_CALIBRATING: return "Calibrating";
case EXPOSED_STATE_GUIDING_LOCKED: return "Guiding";
case EXPOSED_STATE_GUIDING_LOST: return "LostLock";
case EXPOSED_STATE_PAUSED: return "Paused";
case EXPOSED_STATE_LOOPING: return "Looping";
default: return "Unknown";
}
}
// name-value pair
struct NV
{
wxString n;
wxString v;
NV(const wxString& n_, const wxString& v_) : n(n_), v('"'+v_+'"') { }
NV(const wxString& n_, int v_) : n(n_), v(wxString::Format("%d", v_)) { }
NV(const wxString& n_, double v_) : n(n_), v(wxString::Format("%g", v_)) { }
NV(const wxString& n_, double v_, int prec) : n(n_), v(wxString::Format("%.*f", prec, v_)) { }
};
NV NVMount(const Mount *mount)
{
return NV("Mount", mount->Name());
}
struct JObj
{
wxString m_s;
bool m_first;
bool m_closed;
JObj() : m_first(true), m_closed(false) { m_s << "{"; }
void close() { m_s << "}"; m_closed = true; }
wxString str() { if (!m_closed) close(); return m_s; }
};
JObj& operator<<(JObj& j, const NV& nv)
{
if (j.m_first)
j.m_first = false;
else
j.m_s << ',';
j.m_s << '"' << nv.n << "\":" << nv.v;
return j;
}
JObj& operator<<(JObj& j, const PHD_Point& pt)
{
j << NV("X", pt.X, 3) << NV("Y", pt.Y, 3);
return j;
}
struct Ev : public JObj
{
Ev(const wxString& event)
{
double const now = ::wxGetUTCTimeMillis().ToDouble() / 1000.0;
*this << NV("Event", event)
<< NV("Timestamp", now, 3)
<< NV("Host", wxGetHostName())
<< NV("Inst", pFrame->GetInstanceNumber());
}
};
static Ev ev_message_version()
{
Ev ev("Version");
ev << NV("PHDVersion", VERSION)
<< NV("PHDSubver", PHDSUBVER)
<< NV("MsgVersion", MSG_PROTOCOL_VERSION);
return ev;
}
static Ev ev_set_lock_position(const PHD_Point& xy)
{
Ev ev("LockPositionSet");
ev << xy;
return ev;
}
static Ev ev_calibration_complete(Mount *mount)
{
Ev ev("CalibrationComplete");
ev << NVMount(mount);
return ev;
}
static Ev ev_star_selected(const PHD_Point& pos)
{
Ev ev("StarSelected");
ev << pos;
return ev;
}
static Ev ev_start_guiding()
{
return Ev("StartGuiding");
}
static Ev ev_paused()
{
return Ev("Paused");
}
static Ev ev_start_calibration(Mount *mount)
{
Ev ev("StartCalibration");
ev << NVMount(mount);
return ev;
}
static Ev ev_app_state(EXPOSED_STATE st = Guider::GetExposedState())
{
Ev ev("AppState");
ev << NV("State", state_name(st));
return ev;
}
static void send_buf(wxSocketClient *client, const wxCharBuffer& buf)
{
client->Write(buf.data(), buf.length());
client->Write("\r\n", 2);
}
static void do_notify1(wxSocketClient *client, const JObj& jj)
{
send_buf(client, JObj(jj).str().ToUTF8());
}
static void do_notify(const EventServer::CliSockSet& cli, const JObj& jj)
{
wxCharBuffer buf = JObj(jj).str().ToUTF8();
for (EventServer::CliSockSet::const_iterator it = cli.begin();
it != cli.end(); ++it)
{
send_buf(*it, buf);
}
}
inline static void simple_notify(const EventServer::CliSockSet& cli, const wxString& ev)
{
if (!cli.empty())
do_notify(cli, Ev(ev));
}
inline static void simple_notify_ev(const EventServer::CliSockSet& cli, const Ev& ev)
{
if (!cli.empty())
do_notify(cli, ev);
}
#define SIMPLE_NOTIFY(s) simple_notify(m_eventServerClients, s)
#define SIMPLE_NOTIFY_EV(ev) simple_notify_ev(m_eventServerClients, ev)
static void send_catchup_events(wxSocketClient *cli)
{
EXPOSED_STATE st = Guider::GetExposedState();
do_notify1(cli, ev_message_version());
if (pFrame->pGuider)
{
if (pFrame->pGuider->LockPosition().IsValid())
do_notify1(cli, ev_set_lock_position(pFrame->pGuider->LockPosition()));
if (pFrame->pGuider->CurrentPosition().IsValid())
do_notify1(cli, ev_star_selected(pFrame->pGuider->CurrentPosition()));
}
if (pMount && pMount->IsCalibrated())
do_notify1(cli, ev_calibration_complete(pMount));
if (pSecondaryMount && pSecondaryMount->IsCalibrated())
do_notify1(cli, ev_calibration_complete(pSecondaryMount));
if (st == EXPOSED_STATE_GUIDING_LOCKED)
{
do_notify1(cli, ev_start_guiding());
}
else if (st == EXPOSED_STATE_CALIBRATING)
{
Mount *mount = pMount;
if (pFrame->pGuider->GetState() == STATE_CALIBRATING_SECONDARY)
mount = pSecondaryMount;
do_notify1(cli, ev_start_calibration(mount));
}
else if (st == EXPOSED_STATE_PAUSED) {
do_notify1(cli, ev_paused());
}
do_notify1(cli, ev_app_state());
}
EventServer::EventServer()
{
}
EventServer::~EventServer()
{
}
bool EventServer::EventServerStart(unsigned int instanceId)
{
if (m_serverSocket)
{
Debug.AddLine("attempt to start event server when it is already started?");
return false;
}
unsigned int port = 4400 + instanceId - 1;
wxIPV4address eventServerAddr;
eventServerAddr.Service(port);
m_serverSocket = new wxSocketServer(eventServerAddr);
if (!m_serverSocket->Ok())
{
wxLogStatus(wxString::Format("Event server failed to start - Could not listen at port %u", port));
delete m_serverSocket;
m_serverSocket = NULL;
return true;
}
m_serverSocket->SetEventHandler(*this, EVENT_SERVER_ID);
m_serverSocket->SetNotify(wxSOCKET_CONNECTION_FLAG);
m_serverSocket->Notify(true);
Debug.AddLine(wxString::Format("event server started, listening on port %u", port));
return false;
}
void EventServer::EventServerStop()
{
if (!m_serverSocket)
return;
for (CliSockSet::const_iterator it = m_eventServerClients.begin();
it != m_eventServerClients.end(); ++it)
{
(*it)->Destroy();
}
m_eventServerClients.clear();
delete m_serverSocket;
m_serverSocket = NULL;
Debug.AddLine("event server stopped");
}
void EventServer::OnEventServerEvent(wxSocketEvent& event)
{
wxSocketServer *server = static_cast<wxSocketServer *>(event.GetSocket());
if (event.GetSocketEvent() != wxSOCKET_CONNECTION)
return;
wxSocketClient *client = static_cast<wxSocketClient *>(server->Accept(false));
if (!client)
return;
Debug.AddLine("event server client connected");
client->SetEventHandler(*this, EVENT_SERVER_CLIENT_ID);
client->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
client->SetFlags(wxSOCKET_NOWAIT);
client->Notify(true);
send_catchup_events(client);
m_eventServerClients.insert(client);
}
void EventServer::OnEventServerClientEvent(wxSocketEvent& event)
{
wxSocketClient *cli = static_cast<wxSocketClient *>(event.GetSocket());
if (event.GetSocketEvent() == wxSOCKET_LOST)
{
Debug.AddLine("event server client disconnected");
unsigned int const n = m_eventServerClients.erase(cli);
if (n != 1)
Debug.AddLine("client disconnected but not present in client set!");
cli->Destroy();
}
else if (event.GetSocketEvent() == wxSOCKET_INPUT)
{
// consume the input
// TODO: parse input message
wxSocketInputStream sis(*cli);
while (sis.CanRead())
{
char buf[4096];
sis.Read(buf, sizeof(buf));
if (sis.LastRead() == 0)
break;
}
do_notify1(cli, ev_app_state());
}
else
{
Debug.AddLine("unexpected client socket event %d", event.GetSocketEvent());
}
}
void EventServer::NotifyStartCalibration(Mount *mount)
{
SIMPLE_NOTIFY_EV(ev_start_calibration(mount));
}
void EventServer::NotifyCalibrationFailed(Mount *mount, const wxString& msg)
{
if (m_eventServerClients.empty())
return;
Ev ev("CalibrationFailed");
ev << NVMount(mount) << NV("Reason", msg);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifyCalibrationComplete(Mount *mount)
{
if (m_eventServerClients.empty())
return;
do_notify(m_eventServerClients, ev_calibration_complete(mount));
}
void EventServer::NotifyCalibrationDataFlipped(Mount *mount)
{
if (m_eventServerClients.empty())
return;
Ev ev("CalibrationDataFlipped");
ev << NVMount(mount);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifyLooping(unsigned int exposure)
{
if (m_eventServerClients.empty())
return;
Ev ev("LoopingExposures");
ev << NV("Frame", (int) exposure);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifyLoopingStopped()
{
SIMPLE_NOTIFY("LoopingExposuresStopped");
}
void EventServer::NotifyStarSelected(const PHD_Point& pt)
{
SIMPLE_NOTIFY_EV(ev_star_selected(pt));
}
void EventServer::NotifyStarLost()
{
SIMPLE_NOTIFY("StarLost");
}
void EventServer::NotifyStartGuiding()
{
SIMPLE_NOTIFY_EV(ev_start_guiding());
}
void EventServer::NotifyGuidingStopped()
{
SIMPLE_NOTIFY("GuidingStopped");
}
void EventServer::NotifyPaused()
{
SIMPLE_NOTIFY_EV(ev_paused());
}
void EventServer::NotifyResumed()
{
SIMPLE_NOTIFY("Resumed");
}
void EventServer::NotifyGuideStep(Mount *pGuideMount, const PHD_Point& vectorEndpoint, double RADuration, double RADistance,
double DECDuration, double DECDistance, int errorCode)
{
if (m_eventServerClients.empty())
return;
Ev ev("GuideStep");
ev << NV("Frame", (int) pFrame->m_frameCounter)
<< NV("Time", (wxDateTime::UNow() - pFrame->m_guidingStarted).GetMilliseconds().ToDouble() / 1000.0, 3)
<< NV("mount", pGuideMount->Name())
<< NV("dx", vectorEndpoint.X, 3)
<< NV("dy", vectorEndpoint.Y, 3)
<< NV("Theta", vectorEndpoint.Angle(PHD_Point(0., 0.)), 3)
<< NV("RADuration", RADuration, 3)
<< NV("RADistance", RADistance, 3)
<< NV("RADirection", RADistance >= 0.0 ? "E" : "W")
<< NV("DECDuration", DECDuration, 3)
<< NV("DECDistance", DECDistance, 3)
<< NV("DECDirection", DECDistance >= 0.0 ? "S" : "N")
<< NV("StarMass", pFrame->pGuider->StarMass(), 0)
<< NV("SNR", pFrame->pGuider->SNR(), 2);
if (errorCode)
ev << NV("ErrorCode", errorCode);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifyGuidingDithered(double dx, double dy)
{
if (m_eventServerClients.empty())
return;
Ev ev("GuidingDithered");
ev << NV("dx", dx, 3) << NV("dy", dy, 3);
do_notify(m_eventServerClients, ev);
}
void EventServer::NotifySetLockPosition(const PHD_Point& xy)
{
if (m_eventServerClients.empty())
return;
do_notify(m_eventServerClients, ev_set_lock_position(xy));
}
void EventServer::NotifyLockPositionLost()
{
SIMPLE_NOTIFY("LockPositionLost");
}
void EventServer::NotifyAppState()
{
if (m_eventServerClients.empty())
return;
do_notify(m_eventServerClients, ev_app_state());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Performs basic inspection of the disk cache files with minimal disruption
// to the actual files (they still may change if an error is detected on the
// files).
#include <stdio.h>
#include <string>
#include "base/file_util.h"
#include "base/message_loop.h"
#include "net/base/file_stream.h"
#include "net/disk_cache/block_files.h"
#include "net/disk_cache/disk_format.h"
#include "net/disk_cache/mapped_file.h"
#include "net/disk_cache/storage_block.h"
namespace {
const wchar_t kIndexName[] = L"index";
const wchar_t kDataPrefix[] = L"data_";
// Reads the |header_size| bytes from the beginning of file |name|.
bool ReadHeader(const std::wstring name, char* header, int header_size) {
net::FileStream file;
file.Open(name, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ);
if (!file.IsOpen()) {
printf("Unable to open file %ls\n", name.c_str());
return false;
}
int read = file.Read(header, header_size, NULL);
if (read != header_size) {
printf("Unable to read file %ls\n", name.c_str());
return false;
}
return true;
}
int GetMajorVersionFromFile(const std::wstring name) {
disk_cache::IndexHeader header;
if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header)))
return 0;
return header.version >> 16;
}
// Dumps the contents of the Index-file header.
void DumpIndexHeader(const std::wstring name) {
disk_cache::IndexHeader header;
if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header)))
return;
printf("Index file:\n");
printf("magic: %x\n", header.magic);
printf("version: %d.%d\n", header.version >> 16, header.version & 0xffff);
printf("entries: %d\n", header.num_entries);
printf("total bytes: %d\n", header.num_bytes);
printf("last file number: %d\n", header.last_file);
printf("current id: %d\n", header.this_id);
printf("table length: %d\n", header.table_len);
printf("last crash: %d\n", header.crash);
printf("experiment: %d\n", header.experiment);
for (int i = 0; i < 5; i++) {
printf("head %d: 0x%x\n", i, header.lru.heads[i]);
printf("tail %d: 0x%x\n", i, header.lru.tails[i]);
}
printf("transaction: 0x%x\n", header.lru.transaction);
printf("operation: %d\n", header.lru.operation);
printf("operation list: %d\n", header.lru.operation_list);
printf("-------------------------\n\n");
}
// Dumps the contents of a block-file header.
void DumpBlockHeader(const std::wstring name) {
disk_cache::BlockFileHeader header;
if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header)))
return;
std::wstring file_name = file_util::GetFilenameFromPath(name);
printf("Block file: %ls\n", file_name.c_str());
printf("magic: %x\n", header.magic);
printf("version: %d.%d\n", header.version >> 16, header.version & 0xffff);
printf("file id: %d\n", header.this_file);
printf("next file id: %d\n", header.next_file);
printf("entry size: %d\n", header.entry_size);
printf("current entries: %d\n", header.num_entries);
printf("max entries: %d\n", header.max_entries);
printf("updating: %d\n", header.updating);
printf("empty sz 1: %d\n", header.empty[0]);
printf("empty sz 2: %d\n", header.empty[1]);
printf("empty sz 3: %d\n", header.empty[2]);
printf("empty sz 4: %d\n", header.empty[3]);
printf("user 0: 0x%x\n", header.user[0]);
printf("user 1: 0x%x\n", header.user[1]);
printf("user 2: 0x%x\n", header.user[2]);
printf("user 3: 0x%x\n", header.user[3]);
printf("-------------------------\n\n");
}
// Simple class that interacts with the set of cache files.
class CacheDumper {
public:
explicit CacheDumper(const std::wstring path)
: path_(path), block_files_(path), index_(NULL) {}
bool Init();
// Reads an entry from disk. Return false when all entries have been already
// returned.
bool GetEntry(disk_cache::EntryStore* entry);
// Loads a specific block from the block files.
bool LoadEntry(disk_cache::CacheAddr addr, disk_cache::EntryStore* entry);
bool LoadRankings(disk_cache::CacheAddr addr,
disk_cache::RankingsNode* rankings);
private:
std::wstring path_;
disk_cache::BlockFiles block_files_;
scoped_refptr<disk_cache::MappedFile> index_file_;
disk_cache::Index* index_;
int current_hash_;
disk_cache::CacheAddr next_addr_;
DISALLOW_COPY_AND_ASSIGN(CacheDumper);
};
bool CacheDumper::Init() {
if (!block_files_.Init(false)) {
printf("Unable to init block files\n");
return false;
}
std::wstring index_name(path_);
file_util::AppendToPath(&index_name, kIndexName);
index_file_ = new disk_cache::MappedFile;
index_ =
reinterpret_cast<disk_cache::Index*>(index_file_->Init(index_name, 0));
if (!index_) {
printf("Unable to map index\n");
return false;
}
current_hash_ = 0;
next_addr_ = 0;
return true;
}
bool CacheDumper::GetEntry(disk_cache::EntryStore* entry) {
if (next_addr_) {
if (LoadEntry(next_addr_, entry)) {
next_addr_ = entry->next;
if (!next_addr_)
current_hash_++;
return true;
} else {
printf("Unable to load entry at address 0x%x\n", next_addr_);
next_addr_ = 0;
current_hash_++;
}
}
for (int i = current_hash_; i < index_->header.table_len; i++) {
// Yes, we'll crash if the table is shorter than expected, but only after
// dumping every entry that we can find.
if (index_->table[i]) {
current_hash_ = i;
if (LoadEntry(index_->table[i], entry)) {
next_addr_ = entry->next;
if (!next_addr_)
current_hash_++;
return true;
} else {
printf("Unable to load entry at address 0x%x\n", index_->table[i]);
}
}
}
return false;
}
bool CacheDumper::LoadEntry(disk_cache::CacheAddr addr,
disk_cache::EntryStore* entry) {
disk_cache::Addr address(addr);
disk_cache::MappedFile* file = block_files_.GetFile(address);
if (!file)
return false;
disk_cache::CacheEntryBlock entry_block(file, address);
if (!entry_block.Load())
return false;
memcpy(entry, entry_block.Data(), sizeof(*entry));
printf("Entry at 0x%x\n", addr);
return true;
}
bool CacheDumper::LoadRankings(disk_cache::CacheAddr addr,
disk_cache::RankingsNode* rankings) {
disk_cache::Addr address(addr);
disk_cache::MappedFile* file = block_files_.GetFile(address);
if (!file)
return false;
disk_cache::CacheRankingsBlock rank_block(file, address);
if (!rank_block.Load())
return false;
memcpy(rankings, rank_block.Data(), sizeof(*rankings));
printf("Rankings at 0x%x\n", addr);
return true;
}
void DumpEntry(const disk_cache::EntryStore& entry) {
std::string key;
if (!entry.long_key) {
key = entry.key;
if (key.size() > 50)
key.resize(50);
}
printf("hash: 0x%x\n", entry.hash);
printf("next entry: 0x%x\n", entry.next);
printf("rankings: 0x%x\n", entry.rankings_node);
printf("key length: %d\n", entry.key_len);
printf("key: \"%s\"\n", key.c_str());
printf("key addr: 0x%x\n", entry.long_key);
printf("reuse count: %d\n", entry.reuse_count);
printf("refetch count: %d\n", entry.refetch_count);
printf("state: %d\n", entry.state);
for (int i = 0; i < 4; i++) {
printf("data size %d: %d\n", i, entry.data_size[i]);
printf("data addr %d: 0x%x\n", i, entry.data_addr[i]);
}
printf("----------\n\n");
}
void DumpRankings(const disk_cache::RankingsNode& rankings) {
printf("next: 0x%x\n", rankings.next);
printf("prev: 0x%x\n", rankings.prev);
printf("entry: 0x%x\n", rankings.contents);
printf("dirty: %d\n", rankings.dirty);
printf("pointer: 0x%x\n", rankings.pointer);
printf("----------\n\n");
}
} // namespace.
// -----------------------------------------------------------------------
int GetMajorVersion(const std::wstring input_path) {
std::wstring index_name(input_path);
file_util::AppendToPath(&index_name, kIndexName);
int version = GetMajorVersionFromFile(index_name);
if (!version)
return 0;
std::wstring data_name(input_path);
file_util::AppendToPath(&data_name, L"data_0");
if (version != GetMajorVersionFromFile(data_name))
return 0;
data_name = input_path;
file_util::AppendToPath(&data_name, L"data_1");
if (version != GetMajorVersionFromFile(data_name))
return 0;
return version;
}
// Dumps the headers of all files.
int DumpHeaders(const std::wstring input_path) {
std::wstring index_name(input_path);
file_util::AppendToPath(&index_name, kIndexName);
DumpIndexHeader(index_name);
std::wstring pattern(kDataPrefix);
pattern.append(L"*");
file_util::FileEnumerator iter(FilePath::FromWStringHack(input_path), false,
file_util::FileEnumerator::FILES, pattern);
for (std::wstring file = iter.Next().ToWStringHack(); !file.empty();
file = iter.Next().ToWStringHack()) {
DumpBlockHeader(file);
}
return 0;
}
// Dumps all entries from the cache.
int DumpContents(const std::wstring input_path) {
DumpHeaders(input_path);
// We need a message loop, although we really don't run any task.
MessageLoop loop(MessageLoop::TYPE_IO);
CacheDumper dumper(input_path);
if (!dumper.Init())
return -1;
disk_cache::EntryStore entry;
while (dumper.GetEntry(&entry)) {
DumpEntry(entry);
disk_cache::RankingsNode rankings;
if (dumper.LoadRankings(entry.rankings_node, &rankings))
DumpRankings(rankings);
}
printf("Done.\n");
return 0;
}
<commit_msg>Fix compile error in dump_files (didn't catch the error since dump_cache isn't in chrome.sln).<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Performs basic inspection of the disk cache files with minimal disruption
// to the actual files (they still may change if an error is detected on the
// files).
#include <stdio.h>
#include <string>
#include "base/file_util.h"
#include "base/message_loop.h"
#include "net/base/file_stream.h"
#include "net/disk_cache/block_files.h"
#include "net/disk_cache/disk_format.h"
#include "net/disk_cache/mapped_file.h"
#include "net/disk_cache/storage_block.h"
namespace {
const wchar_t kIndexName[] = L"index";
const wchar_t kDataPrefix[] = L"data_";
// Reads the |header_size| bytes from the beginning of file |name|.
bool ReadHeader(const std::wstring name, char* header, int header_size) {
net::FileStream file;
file.Open(FilePath::FromWStringHack(name),
base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ);
if (!file.IsOpen()) {
printf("Unable to open file %ls\n", name.c_str());
return false;
}
int read = file.Read(header, header_size, NULL);
if (read != header_size) {
printf("Unable to read file %ls\n", name.c_str());
return false;
}
return true;
}
int GetMajorVersionFromFile(const std::wstring name) {
disk_cache::IndexHeader header;
if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header)))
return 0;
return header.version >> 16;
}
// Dumps the contents of the Index-file header.
void DumpIndexHeader(const std::wstring name) {
disk_cache::IndexHeader header;
if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header)))
return;
printf("Index file:\n");
printf("magic: %x\n", header.magic);
printf("version: %d.%d\n", header.version >> 16, header.version & 0xffff);
printf("entries: %d\n", header.num_entries);
printf("total bytes: %d\n", header.num_bytes);
printf("last file number: %d\n", header.last_file);
printf("current id: %d\n", header.this_id);
printf("table length: %d\n", header.table_len);
printf("last crash: %d\n", header.crash);
printf("experiment: %d\n", header.experiment);
for (int i = 0; i < 5; i++) {
printf("head %d: 0x%x\n", i, header.lru.heads[i]);
printf("tail %d: 0x%x\n", i, header.lru.tails[i]);
}
printf("transaction: 0x%x\n", header.lru.transaction);
printf("operation: %d\n", header.lru.operation);
printf("operation list: %d\n", header.lru.operation_list);
printf("-------------------------\n\n");
}
// Dumps the contents of a block-file header.
void DumpBlockHeader(const std::wstring name) {
disk_cache::BlockFileHeader header;
if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header)))
return;
std::wstring file_name = file_util::GetFilenameFromPath(name);
printf("Block file: %ls\n", file_name.c_str());
printf("magic: %x\n", header.magic);
printf("version: %d.%d\n", header.version >> 16, header.version & 0xffff);
printf("file id: %d\n", header.this_file);
printf("next file id: %d\n", header.next_file);
printf("entry size: %d\n", header.entry_size);
printf("current entries: %d\n", header.num_entries);
printf("max entries: %d\n", header.max_entries);
printf("updating: %d\n", header.updating);
printf("empty sz 1: %d\n", header.empty[0]);
printf("empty sz 2: %d\n", header.empty[1]);
printf("empty sz 3: %d\n", header.empty[2]);
printf("empty sz 4: %d\n", header.empty[3]);
printf("user 0: 0x%x\n", header.user[0]);
printf("user 1: 0x%x\n", header.user[1]);
printf("user 2: 0x%x\n", header.user[2]);
printf("user 3: 0x%x\n", header.user[3]);
printf("-------------------------\n\n");
}
// Simple class that interacts with the set of cache files.
class CacheDumper {
public:
explicit CacheDumper(const std::wstring path)
: path_(path), block_files_(path), index_(NULL) {}
bool Init();
// Reads an entry from disk. Return false when all entries have been already
// returned.
bool GetEntry(disk_cache::EntryStore* entry);
// Loads a specific block from the block files.
bool LoadEntry(disk_cache::CacheAddr addr, disk_cache::EntryStore* entry);
bool LoadRankings(disk_cache::CacheAddr addr,
disk_cache::RankingsNode* rankings);
private:
std::wstring path_;
disk_cache::BlockFiles block_files_;
scoped_refptr<disk_cache::MappedFile> index_file_;
disk_cache::Index* index_;
int current_hash_;
disk_cache::CacheAddr next_addr_;
DISALLOW_COPY_AND_ASSIGN(CacheDumper);
};
bool CacheDumper::Init() {
if (!block_files_.Init(false)) {
printf("Unable to init block files\n");
return false;
}
std::wstring index_name(path_);
file_util::AppendToPath(&index_name, kIndexName);
index_file_ = new disk_cache::MappedFile;
index_ =
reinterpret_cast<disk_cache::Index*>(index_file_->Init(index_name, 0));
if (!index_) {
printf("Unable to map index\n");
return false;
}
current_hash_ = 0;
next_addr_ = 0;
return true;
}
bool CacheDumper::GetEntry(disk_cache::EntryStore* entry) {
if (next_addr_) {
if (LoadEntry(next_addr_, entry)) {
next_addr_ = entry->next;
if (!next_addr_)
current_hash_++;
return true;
} else {
printf("Unable to load entry at address 0x%x\n", next_addr_);
next_addr_ = 0;
current_hash_++;
}
}
for (int i = current_hash_; i < index_->header.table_len; i++) {
// Yes, we'll crash if the table is shorter than expected, but only after
// dumping every entry that we can find.
if (index_->table[i]) {
current_hash_ = i;
if (LoadEntry(index_->table[i], entry)) {
next_addr_ = entry->next;
if (!next_addr_)
current_hash_++;
return true;
} else {
printf("Unable to load entry at address 0x%x\n", index_->table[i]);
}
}
}
return false;
}
bool CacheDumper::LoadEntry(disk_cache::CacheAddr addr,
disk_cache::EntryStore* entry) {
disk_cache::Addr address(addr);
disk_cache::MappedFile* file = block_files_.GetFile(address);
if (!file)
return false;
disk_cache::CacheEntryBlock entry_block(file, address);
if (!entry_block.Load())
return false;
memcpy(entry, entry_block.Data(), sizeof(*entry));
printf("Entry at 0x%x\n", addr);
return true;
}
bool CacheDumper::LoadRankings(disk_cache::CacheAddr addr,
disk_cache::RankingsNode* rankings) {
disk_cache::Addr address(addr);
disk_cache::MappedFile* file = block_files_.GetFile(address);
if (!file)
return false;
disk_cache::CacheRankingsBlock rank_block(file, address);
if (!rank_block.Load())
return false;
memcpy(rankings, rank_block.Data(), sizeof(*rankings));
printf("Rankings at 0x%x\n", addr);
return true;
}
void DumpEntry(const disk_cache::EntryStore& entry) {
std::string key;
if (!entry.long_key) {
key = entry.key;
if (key.size() > 50)
key.resize(50);
}
printf("hash: 0x%x\n", entry.hash);
printf("next entry: 0x%x\n", entry.next);
printf("rankings: 0x%x\n", entry.rankings_node);
printf("key length: %d\n", entry.key_len);
printf("key: \"%s\"\n", key.c_str());
printf("key addr: 0x%x\n", entry.long_key);
printf("reuse count: %d\n", entry.reuse_count);
printf("refetch count: %d\n", entry.refetch_count);
printf("state: %d\n", entry.state);
for (int i = 0; i < 4; i++) {
printf("data size %d: %d\n", i, entry.data_size[i]);
printf("data addr %d: 0x%x\n", i, entry.data_addr[i]);
}
printf("----------\n\n");
}
void DumpRankings(const disk_cache::RankingsNode& rankings) {
printf("next: 0x%x\n", rankings.next);
printf("prev: 0x%x\n", rankings.prev);
printf("entry: 0x%x\n", rankings.contents);
printf("dirty: %d\n", rankings.dirty);
printf("pointer: 0x%x\n", rankings.pointer);
printf("----------\n\n");
}
} // namespace.
// -----------------------------------------------------------------------
int GetMajorVersion(const std::wstring input_path) {
std::wstring index_name(input_path);
file_util::AppendToPath(&index_name, kIndexName);
int version = GetMajorVersionFromFile(index_name);
if (!version)
return 0;
std::wstring data_name(input_path);
file_util::AppendToPath(&data_name, L"data_0");
if (version != GetMajorVersionFromFile(data_name))
return 0;
data_name = input_path;
file_util::AppendToPath(&data_name, L"data_1");
if (version != GetMajorVersionFromFile(data_name))
return 0;
return version;
}
// Dumps the headers of all files.
int DumpHeaders(const std::wstring input_path) {
std::wstring index_name(input_path);
file_util::AppendToPath(&index_name, kIndexName);
DumpIndexHeader(index_name);
std::wstring pattern(kDataPrefix);
pattern.append(L"*");
file_util::FileEnumerator iter(FilePath::FromWStringHack(input_path), false,
file_util::FileEnumerator::FILES, pattern);
for (std::wstring file = iter.Next().ToWStringHack(); !file.empty();
file = iter.Next().ToWStringHack()) {
DumpBlockHeader(file);
}
return 0;
}
// Dumps all entries from the cache.
int DumpContents(const std::wstring input_path) {
DumpHeaders(input_path);
// We need a message loop, although we really don't run any task.
MessageLoop loop(MessageLoop::TYPE_IO);
CacheDumper dumper(input_path);
if (!dumper.Init())
return -1;
disk_cache::EntryStore entry;
while (dumper.GetEntry(&entry)) {
DumpEntry(entry);
disk_cache::RankingsNode rankings;
if (dumper.LoadRankings(entry.rankings_node, &rankings))
DumpRankings(rankings);
}
printf("Done.\n");
return 0;
}
<|endoftext|>
|
<commit_before>/*
* MaxClique.cpp
*
* Created on: 08.12.2014
* Author: Henning
*/
#include "MaxClique.h"
namespace NetworKit {
MaxClique::MaxClique(const Graph& G): G(G), maxi(0) {
}
void MaxClique::clique(std::set<node>& U, count size) {
if (U.empty()) {
if (size > maxi) {
maxi = size;
}
}
while (U.size() > 0) {
// pruning 4
if (size + U.size() <= maxi) {
return;
}
// extract arbitrary element from U
node x = (* U.begin());
U.erase(U.begin());
// pruning 5: compute set of nodes in U that are neighbors of x and have at least degree maxi
std::set<node> X = U;
for (auto elem : X) {
if ((! G.hasEdge(x, elem)) || (U.find(elem) == U.end()) || (G.degree(elem) < maxi)) {
X.erase(elem);
}
}
// recursive call
clique(X, size + 1);
}
}
count MaxClique::run(count lb) {
maxi = lb;
G.forNodes([&](node u) {
if (G.degree(u) >= maxi) { // pruning 1
std::set<node> U;
G.forNeighborsOf(u, [&](node v) {
if (v > u) { // pruning 2
if (G.degree(v) >= maxi) { // pruning 3
U.insert(v);
}
}
});
clique(U, 1);
}
});
return maxi;
}
} /* namespace NetworKit */
<commit_msg>bugfix in max clique<commit_after>/*
* MaxClique.cpp
*
* Created on: 08.12.2014
* Author: Henning
*/
#include "MaxClique.h"
namespace NetworKit {
MaxClique::MaxClique(const Graph& G): G(G), maxi(0) {
}
void MaxClique::clique(std::set<node>& U, count size) {
if (U.empty()) {
if (size > maxi) {
maxi = size;
}
}
while (U.size() > 0) {
// pruning 4
if (size + U.size() <= maxi) {
return;
}
// extract arbitrary element from U
node x = (* U.begin());
U.erase(x);
// pruning 5: compute set of nodes in U that are neighbors of x and have at least degree maxi
std::set<node> X;
G.forNeighborsOf(x, [&](node v) {
if ((G.degree(v) >= maxi) && (U.count(v) > 0)) {
X.insert(v);
}
});
// recursive call
clique(X, size + 1);
}
}
count MaxClique::run(count lb) {
maxi = lb;
G.forNodes([&](node u) {
if (G.degree(u) >= maxi) { // pruning 1
std::set<node> U;
G.forNeighborsOf(u, [&](node v) {
if (v > u) { // pruning 2
if (G.degree(v) >= maxi) { // pruning 3
U.insert(v);
}
}
});
clique(U, 1);
}
});
return maxi;
}
} /* namespace NetworKit */
<|endoftext|>
|
<commit_before>#include"core.hpp"
#include<stdexcept>
#include<fcntl.h> // for open FLAGS
#include<unistd.h> // for tty checks
#include<cstring> // for memset
ics::Core::~Core() noexcept {
tcsetattr(fd, TCSANOW, &oldTio);
close(fd);
}
const ics::Core& ics::Core::getReference(const char* path, speed_t baudrate = B115200) {
static const Core core {path, baudrate}; // update plan: mutable path and baudrate
return core;
}
void ics::Core::communicate(std::vector<unsigned char>& tx, std::vector<unsigned char>& rx) const {
write(fd, tx.data(), tx.size()); // send
for (auto& receive : rx) read(fd, &receive, 1); // receive
// check section
auto receive = rx.begin();
for (const auto& send : tx) {
if (send != *receive) throw std::runtime_error {"Loopback falied"};
receive++;
}
if ((tx[0] & 0x7F) != *receive) throw std::runtime_error {"Receive failed"};
}
ics::Core::Core(const char* path, speed_t baudrate)
: fd {open(path, O_RDWR | O_NOCTTY)},
oldTio {}
{
if (fd < 0)
throw std::runtime_error {"Cannot open deveice"};
try {
if (!isatty(fd))
throw std::invalid_argument {"Not tty device"};
if (tcgetattr(fd, &oldTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
termios newTio {getTermios()};
if (cfsetispeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (cfsetospeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (tcsetattr(fd, TCSANOW, &newTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
} catch (...) {
close(fd);
throw;
}
}
termios ics::Core::getTermios() noexcept {
termios newTio;
std::memset(&newTio, 0, sizeof(newTio));
newTio.c_iflag = 0;
newTio.c_oflag = 0;
newTio.c_cflag = CS8 | CREAD | CLOCAL | PARENB;
newTio.c_lflag = 0;
newTio.c_cc[VMIN] = 0;
newTio.c_cc[VTIME] = 1;
return newTio;
}
<commit_msg>Fix tirmios init<commit_after>#include"core.hpp"
#include<stdexcept>
#include<fcntl.h> // for open FLAGS
#include<unistd.h> // for tty checks
#include<cstring> // for memset
ics::Core::~Core() noexcept {
tcsetattr(fd, TCSANOW, &oldTio);
close(fd);
}
const ics::Core& ics::Core::getReference(const char* path, speed_t baudrate = B115200) {
static const Core core {path, baudrate}; // update plan: mutable path and baudrate
return core;
}
void ics::Core::communicate(std::vector<unsigned char>& tx, std::vector<unsigned char>& rx) const {
write(fd, tx.data(), tx.size()); // send
for (auto& receive : rx) read(fd, &receive, 1); // receive
// check section
auto receive = rx.begin();
for (const auto& send : tx) {
if (send != *receive) throw std::runtime_error {"Loopback falied"};
receive++;
}
if ((tx[0] & 0x7F) != *receive) throw std::runtime_error {"Receive failed"};
}
ics::Core::Core(const char* path, speed_t baudrate)
: fd {open(path, O_RDWR | O_NOCTTY)},
oldTio {}
{
if (fd < 0)
throw std::runtime_error {"Cannot open deveice"};
try {
if (!isatty(fd))
throw std::invalid_argument {"Not tty device"};
if (tcgetattr(fd, &oldTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
auto newTio = getTermios();
if (cfsetispeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (cfsetospeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (tcsetattr(fd, TCSANOW, &newTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
} catch (...) {
close(fd);
throw;
}
}
termios ics::Core::getTermios() noexcept {
termios newTio;
std::memset(&newTio, 0, sizeof(newTio));
newTio.c_iflag = 0;
newTio.c_oflag = 0;
newTio.c_cflag = CS8 | CREAD | CLOCAL | PARENB;
newTio.c_lflag = 0;
newTio.c_cc[VMIN] = 0;
newTio.c_cc[VTIME] = 1;
return newTio;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
*
* Copyright (C) 1990-2018, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "file_modified_trigger.h"
#if defined( LINUX )
#include <sys/inotify.h>
#include <poll.h>
FileModifiedTrigger::FileModifiedTrigger( const std::string & f ) :
filename( f ), initialized( false ), inotify_fd( -1 )
{
inotify_fd = inotify_init1( IN_NONBLOCK );
if( inotify_fd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): inotify_init() failed: %s (%d).\n", filename.c_str(), strerror(errno), errno );
return;
}
int wd = inotify_add_watch( inotify_fd, filename.c_str(), IN_MODIFY );
if( wd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): inotify_add_watch() failed: %s (%d).\n", filename.c_str(), strerror( errno ), errno );
return;
}
initialized = true;
}
FileModifiedTrigger::~FileModifiedTrigger() {
if( initialized && inotify_fd != -1 ) {
close( inotify_fd );
}
}
int
FileModifiedTrigger::read_inotify_events( void ) {
// Magic from 'man inotify'.
char buf[ sizeof(struct inotify_event) + NAME_MAX + 1 ]
__attribute__ ((aligned(__alignof__(struct inotify_event))));
while( true ) {
ssize_t len = read( inotify_fd, buf, sizeof( buf ) );
if( len == -1 && errno != EAGAIN ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): failed to ready from inotify fd.\n", filename.c_str() );
return -1;
}
// We're done reading events for now.
if( len <= 0 ) { return 1; }
char * ptr = buf;
for( ; ptr < buf + len; ptr += sizeof(struct inotify_event) + ((struct inotify_event *)ptr)->len ) {
const struct inotify_event * event = (struct inotify_event *)ptr;
if(! (event->mask & IN_MODIFY) ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): inotify gave me an event I didn't ask for.\n", filename.c_str() );
return -1;
}
}
// We don't worry about partial reads because we're only watching
// one file for one event type, and the kernel will coalesce
// identical events, so we should only ever see one. Nonetheless,
// we'll verify here that we read only complete events.
if( ptr != buf + len ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): partial inotify read.\n", filename.c_str() );
return -1;
}
}
return 1;
}
int
FileModifiedTrigger::wait( int timeout ) {
if(! initialized) {
return -1;
}
struct pollfd pollfds[1];
pollfds[0].fd = inotify_fd;
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
int events = poll( pollfds, 1, timeout );
switch( events ) {
case -1:
return -1;
case 0:
return 0;
default:
if( pollfds[0].revents & POLLIN ) {
return read_inotify_events();
} else {
dprintf( D_ALWAYS, "FileModifiedTrigger::wait(): poll() returned an event I didn't ask for.\n" );
return -1;
}
break;
}
}
#endif
<commit_msg>(#6736) Build fix.<commit_after>/******************************************************************************
*
* Copyright (C) 1990-2018, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "file_modified_trigger.h"
#if defined( LINUX )
#include <sys/inotify.h>
#include <poll.h>
FileModifiedTrigger::FileModifiedTrigger( const std::string & f ) :
filename( f ), initialized( false ), inotify_fd( -1 )
{
inotify_fd = inotify_init1( IN_NONBLOCK );
if( inotify_fd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): inotify_init() failed: %s (%d).\n", filename.c_str(), strerror(errno), errno );
return;
}
int wd = inotify_add_watch( inotify_fd, filename.c_str(), IN_MODIFY );
if( wd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): inotify_add_watch() failed: %s (%d).\n", filename.c_str(), strerror( errno ), errno );
return;
}
initialized = true;
}
FileModifiedTrigger::~FileModifiedTrigger() {
if( initialized && inotify_fd != -1 ) {
close( inotify_fd );
}
}
int
FileModifiedTrigger::read_inotify_events( void ) {
// Magic from 'man inotify'.
char buf[ sizeof(struct inotify_event) + NAME_MAX + 1 ]
__attribute__ ((aligned(__alignof__(struct inotify_event))));
while( true ) {
ssize_t len = read( inotify_fd, buf, sizeof( buf ) );
if( len == -1 && errno != EAGAIN ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): failed to ready from inotify fd.\n", filename.c_str() );
return -1;
}
// We're done reading events for now.
if( len <= 0 ) { return 1; }
char * ptr = buf;
for( ; ptr < buf + len; ptr += sizeof(struct inotify_event) + ((struct inotify_event *)ptr)->len ) {
const struct inotify_event * event = (struct inotify_event *)ptr;
if(! (event->mask & IN_MODIFY) ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): inotify gave me an event I didn't ask for.\n", filename.c_str() );
return -1;
}
}
// We don't worry about partial reads because we're only watching
// one file for one event type, and the kernel will coalesce
// identical events, so we should only ever see one. Nonetheless,
// we'll verify here that we read only complete events.
if( ptr != buf + len ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): partial inotify read.\n", filename.c_str() );
return -1;
}
}
return 1;
}
int
FileModifiedTrigger::wait( int timeout ) {
if(! initialized) {
return -1;
}
struct pollfd pollfds[1];
pollfds[0].fd = inotify_fd;
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
int events = poll( pollfds, 1, timeout );
switch( events ) {
case -1:
return -1;
case 0:
return 0;
default:
if( pollfds[0].revents & POLLIN ) {
return read_inotify_events();
} else {
dprintf( D_ALWAYS, "FileModifiedTrigger::wait(): poll() returned an event I didn't ask for.\n" );
return -1;
}
break;
}
}
#else
//
// Stubs for other platforms. We should replace these with (a) a Windows-
// specific blocking interface and (b) a "unix" (MacOSX) fallback that polls.
//
// Collected as its own block for clarity.
//
FileModifiedTrigger::FileModifiedTrigger( const std::string & f ) :
filename( f ), initialized( false ) { }
FileModifiedTrigger::~FileModifiedTrigger() { }
int
FileModifiedTrigger::wait( int milliseconds ) {
return -1;
}
#endif
<|endoftext|>
|
<commit_before>#include "pc6001v.h"
#include "config.h"
#include "cpum.h"
#include "p6vm.h"
////////////////////////////////////////////////////////////////
// コンストラクタ
////////////////////////////////////////////////////////////////
CPU6::CPU6( VM6 *vm, const ID& id ) : Device(vm,id) {}
////////////////////////////////////////////////////////////////
// デストラクタ
////////////////////////////////////////////////////////////////
CPU6::~CPU6( void ){}
////////////////////////////////////////////////////////////////
// フェッチ(M1)
////////////////////////////////////////////////////////////////
BYTE CPU6::Fetch( WORD addr, int *m1wait )
{
return vm->MemFetch( addr, m1wait );
}
////////////////////////////////////////////////////////////////
// メモリアクセス(ウェイトなし)
////////////////////////////////////////////////////////////////
BYTE CPU6::ReadMemNW( WORD addr )
{
return vm->MemRead( addr );
}
////////////////////////////////////////////////////////////////
// メモリアクセス(ウェイトあり)
////////////////////////////////////////////////////////////////
BYTE CPU6::ReadMem( WORD addr )
{
return vm->MemRead( addr, &mstate );
}
void CPU6::WriteMem( WORD addr, BYTE data)
{
vm->MemWrite( addr, data, &mstate );
}
////////////////////////////////////////////////////////////////
// I/Oポートアクセス
////////////////////////////////////////////////////////////////
BYTE CPU6::ReadIO( int addr )
{
return vm->IomIn( addr, &mstate );
}
void CPU6::WriteIO( int addr, BYTE data )
{
vm->IomOut( addr, data, &mstate );
}
////////////////////////////////////////////////////////////////
// 割込みベクタ取得
////////////////////////////////////////////////////////////////
int CPU6::GetIntrVector( void )
{
return vm->IntIntrCheck();
}
////////////////////////////////////////////////////////////////
// バスリクエスト区間停止フラグ取得
////////////////////////////////////////////////////////////////
bool CPU6::IsBUSREQ( void )
{
return
#ifndef NOMONITOR // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
vm->ElIsMonitor() ? false :
#endif // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
vm->VdgIsBusReqStop();
}
////////////////////////////////////////////////////////////////
// どこでもSAVE
////////////////////////////////////////////////////////////////
bool CPU6::DokoSave( cIni *Ini )
{
if( !Ini ) return false;
Ini->PutEntry( "Z80", NULL, "AF", "0x%04X", AF.W );
Ini->PutEntry( "Z80", NULL, "BC", "0x%04X", BC.W );
Ini->PutEntry( "Z80", NULL, "DE", "0x%04X", DE.W );
Ini->PutEntry( "Z80", NULL, "HL", "0x%04X", HL.W );
Ini->PutEntry( "Z80", NULL, "IX", "0x%04X", IX.W );
Ini->PutEntry( "Z80", NULL, "IY", "0x%04X", IY.W );
Ini->PutEntry( "Z80", NULL, "PC", "0x%04X", PC.W );
Ini->PutEntry( "Z80", NULL, "SP", "0x%04X", SP.W );
Ini->PutEntry( "Z80", NULL, "AF1", "0x%04X", AF1.W );
Ini->PutEntry( "Z80", NULL, "BC1", "0x%04X", BC1.W );
Ini->PutEntry( "Z80", NULL, "DE1", "0x%04X", DE1.W );
Ini->PutEntry( "Z80", NULL, "HL1", "0x%04X", HL1.W );
Ini->PutEntry( "Z80", NULL, "I", "0x%02X", I );
Ini->PutEntry( "Z80", NULL, "R", "0x%02X", R );
Ini->PutEntry( "Z80", NULL, "R_saved", "0x%02X", R_saved );
Ini->PutEntry( "Z80", NULL, "IFF", "0x%02X", IFF );
Ini->PutEntry( "Z80", NULL, "IFF2", "0x%02X", IFF2 );
Ini->PutEntry( "Z80", NULL, "IM", "0x%02X", IM );
Ini->PutEntry( "Z80", NULL, "Halt", "0x%02X", Halt );
Ini->PutEntry( "Z80", NULL, "mstate", "%d", mstate );
return true;
}
////////////////////////////////////////////////////////////////
// どこでもLOAD
////////////////////////////////////////////////////////////////
bool CPU6::DokoLoad( cIni *Ini )
{
int st;
if( !Ini ) return false;
Ini->GetInt( "Z80", "AF", &st, AF.W ); AF.W = st;
Ini->GetInt( "Z80", "BC", &st, BC.W ); BC.W = st;
Ini->GetInt( "Z80", "DE", &st, DE.W ); DE.W = st;
Ini->GetInt( "Z80", "HL", &st, HL.W ); HL.W = st;
Ini->GetInt( "Z80", "IX", &st, IX.W ); IX.W = st;
Ini->GetInt( "Z80", "IY", &st, IY.W ); IY.W = st;
Ini->GetInt( "Z80", "PC", &st, PC.W ); PC.W = st;
Ini->GetInt( "Z80", "SP", &st, SP.W ); SP.W = st;
Ini->GetInt( "Z80", "AF1", &st, AF1.W ); AF1.W = st;
Ini->GetInt( "Z80", "BC1", &st, BC1.W ); BC1.W = st;
Ini->GetInt( "Z80", "DE1", &st, DE1.W ); DE1.W = st;
Ini->GetInt( "Z80", "HL1", &st, HL1.W ); HL1.W = st;
Ini->GetInt( "Z80", "I", &st, I ); I = st;
Ini->GetInt( "Z80", "R", &st, R ); R = st;
Ini->GetInt( "Z80", "R_saved", &st, R_saved ); R_saved = st;
Ini->GetInt( "Z80", "IFF", &st, IFF ); IFF = st;
Ini->GetInt( "Z80", "IFF2", &st, IFF2 ); IFF2 = st;
Ini->GetInt( "Z80", "IM", &st, IM ); IM = st;
Ini->GetInt( "Z80", "Halt", &st, Halt ); Halt = st;
Ini->GetInt( "Z80", "mstate", &mstate, mstate );
return true;
}
<commit_msg>インデントを修正<commit_after>#include "pc6001v.h"
#include "config.h"
#include "cpum.h"
#include "p6vm.h"
////////////////////////////////////////////////////////////////
// コンストラクタ
////////////////////////////////////////////////////////////////
CPU6::CPU6( VM6 *vm, const ID& id ) : Device(vm,id) {}
////////////////////////////////////////////////////////////////
// デストラクタ
////////////////////////////////////////////////////////////////
CPU6::~CPU6( void ){}
////////////////////////////////////////////////////////////////
// フェッチ(M1)
////////////////////////////////////////////////////////////////
BYTE CPU6::Fetch( WORD addr, int *m1wait )
{
return vm->MemFetch( addr, m1wait );
}
////////////////////////////////////////////////////////////////
// メモリアクセス(ウェイトなし)
////////////////////////////////////////////////////////////////
BYTE CPU6::ReadMemNW( WORD addr )
{
return vm->MemRead( addr );
}
////////////////////////////////////////////////////////////////
// メモリアクセス(ウェイトあり)
////////////////////////////////////////////////////////////////
BYTE CPU6::ReadMem( WORD addr )
{
return vm->MemRead( addr, &mstate );
}
void CPU6::WriteMem( WORD addr, BYTE data)
{
vm->MemWrite( addr, data, &mstate );
}
////////////////////////////////////////////////////////////////
// I/Oポートアクセス
////////////////////////////////////////////////////////////////
BYTE CPU6::ReadIO( int addr )
{
return vm->IomIn( addr, &mstate );
}
void CPU6::WriteIO( int addr, BYTE data )
{
vm->IomOut( addr, data, &mstate );
}
////////////////////////////////////////////////////////////////
// 割込みベクタ取得
////////////////////////////////////////////////////////////////
int CPU6::GetIntrVector( void )
{
return vm->IntIntrCheck();
}
////////////////////////////////////////////////////////////////
// バスリクエスト区間停止フラグ取得
////////////////////////////////////////////////////////////////
bool CPU6::IsBUSREQ( void )
{
return
#ifndef NOMONITOR // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
vm->ElIsMonitor() ? false :
#endif // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
vm->VdgIsBusReqStop();
}
////////////////////////////////////////////////////////////////
// どこでもSAVE
////////////////////////////////////////////////////////////////
bool CPU6::DokoSave( cIni *Ini )
{
if( !Ini ) return false;
Ini->PutEntry( "Z80", NULL, "AF", "0x%04X", AF.W );
Ini->PutEntry( "Z80", NULL, "BC", "0x%04X", BC.W );
Ini->PutEntry( "Z80", NULL, "DE", "0x%04X", DE.W );
Ini->PutEntry( "Z80", NULL, "HL", "0x%04X", HL.W );
Ini->PutEntry( "Z80", NULL, "IX", "0x%04X", IX.W );
Ini->PutEntry( "Z80", NULL, "IY", "0x%04X", IY.W );
Ini->PutEntry( "Z80", NULL, "PC", "0x%04X", PC.W );
Ini->PutEntry( "Z80", NULL, "SP", "0x%04X", SP.W );
Ini->PutEntry( "Z80", NULL, "AF1", "0x%04X", AF1.W );
Ini->PutEntry( "Z80", NULL, "BC1", "0x%04X", BC1.W );
Ini->PutEntry( "Z80", NULL, "DE1", "0x%04X", DE1.W );
Ini->PutEntry( "Z80", NULL, "HL1", "0x%04X", HL1.W );
Ini->PutEntry( "Z80", NULL, "I", "0x%02X", I );
Ini->PutEntry( "Z80", NULL, "R", "0x%02X", R );
Ini->PutEntry( "Z80", NULL, "R_saved", "0x%02X", R_saved );
Ini->PutEntry( "Z80", NULL, "IFF", "0x%02X", IFF );
Ini->PutEntry( "Z80", NULL, "IFF2", "0x%02X", IFF2 );
Ini->PutEntry( "Z80", NULL, "IM", "0x%02X", IM );
Ini->PutEntry( "Z80", NULL, "Halt", "0x%02X", Halt );
Ini->PutEntry( "Z80", NULL, "mstate", "%d", mstate );
return true;
}
////////////////////////////////////////////////////////////////
// どこでもLOAD
////////////////////////////////////////////////////////////////
bool CPU6::DokoLoad( cIni *Ini )
{
int st;
if( !Ini ) return false;
Ini->GetInt( "Z80", "AF", &st, AF.W ); AF.W = st;
Ini->GetInt( "Z80", "BC", &st, BC.W ); BC.W = st;
Ini->GetInt( "Z80", "DE", &st, DE.W ); DE.W = st;
Ini->GetInt( "Z80", "HL", &st, HL.W ); HL.W = st;
Ini->GetInt( "Z80", "IX", &st, IX.W ); IX.W = st;
Ini->GetInt( "Z80", "IY", &st, IY.W ); IY.W = st;
Ini->GetInt( "Z80", "PC", &st, PC.W ); PC.W = st;
Ini->GetInt( "Z80", "SP", &st, SP.W ); SP.W = st;
Ini->GetInt( "Z80", "AF1", &st, AF1.W ); AF1.W = st;
Ini->GetInt( "Z80", "BC1", &st, BC1.W ); BC1.W = st;
Ini->GetInt( "Z80", "DE1", &st, DE1.W ); DE1.W = st;
Ini->GetInt( "Z80", "HL1", &st, HL1.W ); HL1.W = st;
Ini->GetInt( "Z80", "I", &st, I ); I = st;
Ini->GetInt( "Z80", "R", &st, R ); R = st;
Ini->GetInt( "Z80", "R_saved", &st, R_saved ); R_saved = st;
Ini->GetInt( "Z80", "IFF", &st, IFF ); IFF = st;
Ini->GetInt( "Z80", "IFF2", &st, IFF2 ); IFF2 = st;
Ini->GetInt( "Z80", "IM", &st, IM ); IM = st;
Ini->GetInt( "Z80", "Halt", &st, Halt ); Halt = st;
Ini->GetInt( "Z80", "mstate", &mstate, mstate );
return true;
}
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2005, 2006 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <base/utilities.h>
#include <base/exceptions.h>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <cerrno>
#include <cmath>
#include <unistd.h>
#include <sys/types.h>
#include <sstream>
#ifdef HAVE_STD_NUMERIC_LIMITS
# include <limits>
#else
# include <limits.h>
#endif
DEAL_II_NAMESPACE_OPEN
namespace Utilities
{
DeclException2 (ExcInvalidNumber2StringConversersion,
unsigned int, unsigned int,
<< "When trying to convert " << arg1
<< " to a string with " << arg2 << " digits");
DeclException1 (ExcInvalidNumber,
unsigned int,
<< "Invalid number " << arg1);
DeclException1 (ExcCantConvertString,
std::string,
<< "Can't convert the string " << arg1
<< " to the desired type");
std::string
int_to_string (const unsigned int i,
const unsigned int digits)
{
// if second argument is invalid, then do
// not pad the resulting string at all
if (digits == deal_II_numbers::invalid_unsigned_int)
return int_to_string (i, needed_digits(i));
AssertThrow ( ! ((digits==1 && i>=10) ||
(digits==2 && i>=100) ||
(digits==3 && i>=1000) ||
(digits==4 && i>=10000)||
(i>=100000)),
ExcInvalidNumber2StringConversersion(i, digits));
std::string s;
switch (digits)
{
case 4:
s += '0' + i/1000;
case 3:
s += '0' + (i%1000)/100;
case 2:
s += '0' + (i%100)/10;
case 1:
s += '0' + i%10;
break;
default:
s += "invalid digits information";
};
return s;
}
unsigned int
needed_digits (const unsigned int max_number)
{
if (max_number < 10)
return 1;
if (max_number < 100)
return 2;
if (max_number < 1000)
return 3;
if (max_number < 10000)
return 4;
if (max_number < 100000)
return 5;
if (max_number < 1000000)
return 6;
AssertThrow (false, ExcInvalidNumber(max_number));
return 0;
}
int
string_to_int (const std::string &s)
{
std::istringstream ss(s);
#ifdef HAVE_STD_NUMERIC_LIMITS
static const int max_int = std::numeric_limits<int>::max();
#else
static const int max_int = INT_MAX;
#endif
int i = max_int;
ss >> i;
// check for errors
AssertThrow (i != max_int, ExcCantConvertString (s));
return i;
}
std::vector<int>
string_to_int (const std::vector<std::string> &s)
{
std::vector<int> tmp (s.size());
for (unsigned int i=0; i<s.size(); ++i)
tmp[i] = string_to_int (s[i]);
return tmp;
}
std::vector<std::string>
split_string_list (const std::string &s,
const char delimiter)
{
std::string tmp = s;
std::vector<std::string> split_list;
split_list.reserve (std::count (tmp.begin(), tmp.end(), delimiter)+1);
// split the input list
while (tmp.length() != 0)
{
std::string name;
name = tmp;
if (name.find(delimiter) != std::string::npos)
{
name.erase (name.find(delimiter), std::string::npos);
tmp.erase (0, tmp.find(delimiter)+1);
}
else
tmp = "";
while ((name.length() != 0) &&
(name[0] == ' '))
name.erase (0,1);
while (name[name.length()-1] == ' ')
name.erase (name.length()-1, 1);
split_list.push_back (name);
}
return split_list;
}
std::vector<std::string>
break_text_into_lines (const std::string &original_text,
const unsigned int width,
const char delimiter)
{
std::string text = original_text;
std::vector<std::string> lines;
// remove trailing spaces
while ((text.length() != 0) && (text[text.length()-1] == delimiter))
text.erase(text.length()-1,1);
// then split the text into lines
while (text.length() != 0)
{
// in each iteration, first remove
// leading spaces
while ((text.length() != 0) && (text[0] == delimiter))
text.erase(0, 1);
// if we can fit everything into one
// line, then do so. otherwise, we have
// to keep breaking
if (text.length() < width)
{
lines.push_back (text);
text = "";
}
else
{
// starting at position width, find the
// location of the previous space, so
// that we can break around there
int location = std::min<int>(width,text.length()-1);
for (; location>0; --location)
if (text[location] == delimiter)
break;
// if there are no spaces, then try if
// there are spaces coming up
if (location == 0)
for (location = std::min<int>(width,text.length()-1);
location<static_cast<int>(text.length());
++location)
if (text[location] == delimiter)
break;
// now take the text up to the found
// location and put it into a single
// line, and remove it from 'text'
lines.push_back (std::string (text, 0, location));
text.erase (0, location);
}
}
return lines;
}
bool
match_at_string_start (const std::string &name,
const std::string &pattern)
{
if (pattern.size() > name.size())
return false;
for (unsigned int i=0; i<pattern.size(); ++i)
if (pattern[i] != name[i])
return false;
return true;
}
std::pair<int, unsigned int>
get_integer_at_position (const std::string &name,
const unsigned int position)
{
Assert (position < name.size(), ExcInternalError());
const std::string test_string (name.begin()+position,
name.end());
std::istringstream str(test_string);
int i;
if (str >> i)
{
// compute the number of
// digits of i. assuming it
// is less than 6 is likely
// ok
if (i<10)
return std::make_pair (i, 1U);
else if (i<100)
return std::make_pair (i, 2U);
else if (i<1000)
return std::make_pair (i, 3U);
else if (i<10000)
return std::make_pair (i, 4U);
else if (i<100000)
return std::make_pair (i, 5U);
else
{
Assert (false, ExcNotImplemented());
return std::make_pair (-1, deal_II_numbers::invalid_unsigned_int);
}
}
else
return std::make_pair (-1, deal_II_numbers::invalid_unsigned_int);
}
double
generate_normal_random_number (const double a,
const double sigma)
{
// if no noise: return now
if (sigma == 0)
return a;
#ifdef HAVE_RAND_R
static unsigned int seed = 0xabcd1234;
const double y = 1.0*rand_r(&seed)/RAND_MAX;
#else
const double y = 1.0*rand()/RAND_MAX;
#endif
// find x such that y=erf(x). do so
// using a Newton method to find
// the zero of F(x)=erf(x)-y. start
// at x=0
double x = 0;
unsigned int iteration = 0;
while (true)
{
const double residual = 0.5+erf(x/std::sqrt(2.)/sigma)/2-y;
if (std::fabs(residual) < 1e-7)
break;
const double F_prime = 1./std::sqrt(2*3.1415926536)/sigma *
std::exp(-x*x/sigma/sigma/2);
x += -residual / F_prime;
// make sure that we don't
// recurse endlessly
++iteration;
Assert (iteration < 20, ExcInternalError());
};
return x+a;
}
namespace System
{
#if defined(__linux__)
double get_cpu_load ()
{
std::ifstream cpuinfo;
cpuinfo.open("/proc/loadavg");
AssertThrow(cpuinfo, ExcIO());
double load;
cpuinfo >> load;
return load;
}
#else
double get_cpu_load ()
{
return 0.;
}
#endif
std::string get_hostname ()
{
const unsigned int N=1024;
char hostname[N];
gethostname (&(hostname[0]), N-1);
return hostname;
}
std::string get_time ()
{
std::time_t time1= std::time (0);
std::tm *time = std::localtime(&time1);
std::ostringstream o;
o << time->tm_hour << ":"
<< (time->tm_min < 10 ? "0" : "") << time->tm_min << ":"
<< (time->tm_sec < 10 ? "0" : "") << time->tm_sec;
return o.str();
}
#ifdef DEAL_II_USE_PETSC
// Unfortunately, we have to work
// around an oddity in the way PETSc
// and some gcc versions interact. If
// we use PETSc's MPI dummy
// implementation, it expands the
// calls to the two MPI functions
// basically as ``(n_jobs=1, 0)'',
// i.e. it assigns the number one to
// the variable holding the number of
// jobs, and then uses the comma
// operator to let the entire
// expression have the value zero. The
// latter is important, since
// ``MPI_Comm_size'' returns an error
// code that we may want to check (we
// don't here, but one could in
// principle), and the trick with the
// comma operator makes sure that both
// the number of jobs is correctly
// assigned, and the return value is
// zero. Unfortunately, if some recent
// versions of gcc detect that the
// comma expression just stands by
// itself, i.e. the result is not
// assigned to another variable, then
// they warn ``right-hand operand of
// comma has no effect''. This
// unwanted side effect can be
// suppressed by casting the result of
// the entire expression to type
// ``void'' -- not beautiful, but
// helps calming down unwarranted
// compiler warnings...
unsigned int get_n_mpi_processes (
const MPI_Comm &mpi_communicator)
{
int n_jobs=1;
(void) MPI_Comm_size (mpi_communicator, &n_jobs);
return n_jobs;
}
unsigned int get_this_mpi_process (
const MPI_Comm &mpi_communicator)
{
int rank=0;
(void) MPI_Comm_rank (mpi_communicator, &rank);
return rank;
}
#else
unsigned int get_n_mpi_processes (const MPI_Comm &)
{
return 1;
}
unsigned int get_this_mpi_process (const MPI_Comm &)
{
return 0;
}
#endif
}
}
DEAL_II_NAMESPACE_CLOSE
<commit_msg>allow larger integer numbers to be read from a string<commit_after>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2005, 2006 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <base/utilities.h>
#include <base/exceptions.h>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <cerrno>
#include <cmath>
#include <unistd.h>
#include <sys/types.h>
#include <sstream>
#ifdef HAVE_STD_NUMERIC_LIMITS
# include <limits>
#else
# include <limits.h>
#endif
DEAL_II_NAMESPACE_OPEN
namespace Utilities
{
DeclException2 (ExcInvalidNumber2StringConversersion,
unsigned int, unsigned int,
<< "When trying to convert " << arg1
<< " to a string with " << arg2 << " digits");
DeclException1 (ExcInvalidNumber,
unsigned int,
<< "Invalid number " << arg1);
DeclException1 (ExcCantConvertString,
std::string,
<< "Can't convert the string " << arg1
<< " to the desired type");
std::string
int_to_string (const unsigned int i,
const unsigned int digits)
{
// if second argument is invalid, then do
// not pad the resulting string at all
if (digits == deal_II_numbers::invalid_unsigned_int)
return int_to_string (i, needed_digits(i));
AssertThrow ( ! ((digits==1 && i>=10) ||
(digits==2 && i>=100) ||
(digits==3 && i>=1000) ||
(digits==4 && i>=10000)||
(i>=100000)),
ExcInvalidNumber2StringConversersion(i, digits));
std::string s;
switch (digits)
{
case 4:
s += '0' + i/1000;
case 3:
s += '0' + (i%1000)/100;
case 2:
s += '0' + (i%100)/10;
case 1:
s += '0' + i%10;
break;
default:
s += "invalid digits information";
};
return s;
}
unsigned int
needed_digits (const unsigned int max_number)
{
if (max_number < 10)
return 1;
if (max_number < 100)
return 2;
if (max_number < 1000)
return 3;
if (max_number < 10000)
return 4;
if (max_number < 100000)
return 5;
if (max_number < 1000000)
return 6;
AssertThrow (false, ExcInvalidNumber(max_number));
return 0;
}
int
string_to_int (const std::string &s)
{
std::istringstream ss(s);
#ifdef HAVE_STD_NUMERIC_LIMITS
static const int max_int = std::numeric_limits<int>::max();
#else
static const int max_int = INT_MAX;
#endif
int i = max_int;
ss >> i;
// check for errors
AssertThrow (i != max_int, ExcCantConvertString (s));
return i;
}
std::vector<int>
string_to_int (const std::vector<std::string> &s)
{
std::vector<int> tmp (s.size());
for (unsigned int i=0; i<s.size(); ++i)
tmp[i] = string_to_int (s[i]);
return tmp;
}
std::vector<std::string>
split_string_list (const std::string &s,
const char delimiter)
{
std::string tmp = s;
std::vector<std::string> split_list;
split_list.reserve (std::count (tmp.begin(), tmp.end(), delimiter)+1);
// split the input list
while (tmp.length() != 0)
{
std::string name;
name = tmp;
if (name.find(delimiter) != std::string::npos)
{
name.erase (name.find(delimiter), std::string::npos);
tmp.erase (0, tmp.find(delimiter)+1);
}
else
tmp = "";
while ((name.length() != 0) &&
(name[0] == ' '))
name.erase (0,1);
while (name[name.length()-1] == ' ')
name.erase (name.length()-1, 1);
split_list.push_back (name);
}
return split_list;
}
std::vector<std::string>
break_text_into_lines (const std::string &original_text,
const unsigned int width,
const char delimiter)
{
std::string text = original_text;
std::vector<std::string> lines;
// remove trailing spaces
while ((text.length() != 0) && (text[text.length()-1] == delimiter))
text.erase(text.length()-1,1);
// then split the text into lines
while (text.length() != 0)
{
// in each iteration, first remove
// leading spaces
while ((text.length() != 0) && (text[0] == delimiter))
text.erase(0, 1);
// if we can fit everything into one
// line, then do so. otherwise, we have
// to keep breaking
if (text.length() < width)
{
lines.push_back (text);
text = "";
}
else
{
// starting at position width, find the
// location of the previous space, so
// that we can break around there
int location = std::min<int>(width,text.length()-1);
for (; location>0; --location)
if (text[location] == delimiter)
break;
// if there are no spaces, then try if
// there are spaces coming up
if (location == 0)
for (location = std::min<int>(width,text.length()-1);
location<static_cast<int>(text.length());
++location)
if (text[location] == delimiter)
break;
// now take the text up to the found
// location and put it into a single
// line, and remove it from 'text'
lines.push_back (std::string (text, 0, location));
text.erase (0, location);
}
}
return lines;
}
bool
match_at_string_start (const std::string &name,
const std::string &pattern)
{
if (pattern.size() > name.size())
return false;
for (unsigned int i=0; i<pattern.size(); ++i)
if (pattern[i] != name[i])
return false;
return true;
}
std::pair<int, unsigned int>
get_integer_at_position (const std::string &name,
const unsigned int position)
{
Assert (position < name.size(), ExcInternalError());
const std::string test_string (name.begin()+position,
name.end());
std::istringstream str(test_string);
int i;
if (str >> i)
{
// compute the number of
// digits of i. assuming it
// is less than 8 is likely
// ok
if (i<10)
return std::make_pair (i, 1U);
else if (i<100)
return std::make_pair (i, 2U);
else if (i<1000)
return std::make_pair (i, 3U);
else if (i<10000)
return std::make_pair (i, 4U);
else if (i<100000)
return std::make_pair (i, 5U);
else if (i<1000000)
return std::make_pair (i, 6U);
else if (i<10000000)
return std::make_pair (i, 7U);
else
{
Assert (false, ExcNotImplemented());
return std::make_pair (-1, deal_II_numbers::invalid_unsigned_int);
}
}
else
return std::make_pair (-1, deal_II_numbers::invalid_unsigned_int);
}
double
generate_normal_random_number (const double a,
const double sigma)
{
// if no noise: return now
if (sigma == 0)
return a;
#ifdef HAVE_RAND_R
static unsigned int seed = 0xabcd1234;
const double y = 1.0*rand_r(&seed)/RAND_MAX;
#else
const double y = 1.0*rand()/RAND_MAX;
#endif
// find x such that y=erf(x). do so
// using a Newton method to find
// the zero of F(x)=erf(x)-y. start
// at x=0
double x = 0;
unsigned int iteration = 0;
while (true)
{
const double residual = 0.5+erf(x/std::sqrt(2.)/sigma)/2-y;
if (std::fabs(residual) < 1e-7)
break;
const double F_prime = 1./std::sqrt(2*3.1415926536)/sigma *
std::exp(-x*x/sigma/sigma/2);
x += -residual / F_prime;
// make sure that we don't
// recurse endlessly
++iteration;
Assert (iteration < 20, ExcInternalError());
};
return x+a;
}
namespace System
{
#if defined(__linux__)
double get_cpu_load ()
{
std::ifstream cpuinfo;
cpuinfo.open("/proc/loadavg");
AssertThrow(cpuinfo, ExcIO());
double load;
cpuinfo >> load;
return load;
}
#else
double get_cpu_load ()
{
return 0.;
}
#endif
std::string get_hostname ()
{
const unsigned int N=1024;
char hostname[N];
gethostname (&(hostname[0]), N-1);
return hostname;
}
std::string get_time ()
{
std::time_t time1= std::time (0);
std::tm *time = std::localtime(&time1);
std::ostringstream o;
o << time->tm_hour << ":"
<< (time->tm_min < 10 ? "0" : "") << time->tm_min << ":"
<< (time->tm_sec < 10 ? "0" : "") << time->tm_sec;
return o.str();
}
#ifdef DEAL_II_USE_PETSC
// Unfortunately, we have to work
// around an oddity in the way PETSc
// and some gcc versions interact. If
// we use PETSc's MPI dummy
// implementation, it expands the
// calls to the two MPI functions
// basically as ``(n_jobs=1, 0)'',
// i.e. it assigns the number one to
// the variable holding the number of
// jobs, and then uses the comma
// operator to let the entire
// expression have the value zero. The
// latter is important, since
// ``MPI_Comm_size'' returns an error
// code that we may want to check (we
// don't here, but one could in
// principle), and the trick with the
// comma operator makes sure that both
// the number of jobs is correctly
// assigned, and the return value is
// zero. Unfortunately, if some recent
// versions of gcc detect that the
// comma expression just stands by
// itself, i.e. the result is not
// assigned to another variable, then
// they warn ``right-hand operand of
// comma has no effect''. This
// unwanted side effect can be
// suppressed by casting the result of
// the entire expression to type
// ``void'' -- not beautiful, but
// helps calming down unwarranted
// compiler warnings...
unsigned int get_n_mpi_processes (
const MPI_Comm &mpi_communicator)
{
int n_jobs=1;
(void) MPI_Comm_size (mpi_communicator, &n_jobs);
return n_jobs;
}
unsigned int get_this_mpi_process (
const MPI_Comm &mpi_communicator)
{
int rank=0;
(void) MPI_Comm_rank (mpi_communicator, &rank);
return rank;
}
#else
unsigned int get_n_mpi_processes (const MPI_Comm &)
{
return 1;
}
unsigned int get_this_mpi_process (const MPI_Comm &)
{
return 0;
}
#endif
}
}
DEAL_II_NAMESPACE_CLOSE
<|endoftext|>
|
<commit_before>#include <memory>
#include "draw.hh"
#include "chart.hh"
#include "acmacs-draw/surface-cairo.hh"
// ----------------------------------------------------------------------
void ChartDraw::prepare()
{
std::unique_ptr<BoundingBall> bb(mChart.projection(mProjectionNo).layout().minimum_bounding_ball());
mViewport.set_from_center_size(bb->center(), bb->diameter());
mViewport.whole_width();
// std::cerr << mViewport << std::endl;
} // ChartDraw::prepare
// ----------------------------------------------------------------------
void ChartDraw::draw(Surface& aSurface)
{
double pix = 0.01;
aSurface.grid(Scaled{1}, "cyan3", Pixels{pix});
aSurface.border("blue", Pixels{pix * 5});
aSurface.circle({0, 0}, Scaled{1}, 1, 0, "pink", Pixels{pix});
} // ChartDraw::draw
// ----------------------------------------------------------------------
void ChartDraw::draw(std::string aFilename, double aSize)
{
PdfCairo surface(aFilename, aSize, aSize);
// surface.resize(mViewport.size.width);
Surface& rescaled = surface.subsurface({0, 0}, Scaled{surface.viewport().size.width}, mViewport, true);
draw(rescaled);
} // ChartDraw::draw
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>porting to the new surface system (from acmacs-draw)<commit_after>#include <memory>
#include "draw.hh"
#include "chart.hh"
#include "acmacs-draw/surface-cairo.hh"
// ----------------------------------------------------------------------
void ChartDraw::prepare()
{
std::unique_ptr<BoundingBall> bb(mChart.projection(mProjectionNo).layout().minimum_bounding_ball());
mViewport.set_from_center_size(bb->center(), bb->diameter());
mViewport.whole_width();
// std::cerr << mViewport << std::endl;
} // ChartDraw::prepare
// ----------------------------------------------------------------------
void ChartDraw::draw(Surface& aSurface)
{
double pix = 1;
aSurface.grid(Scaled{1}, "cyan3", Pixels{pix});
aSurface.border("blue", Pixels{pix * 5});
aSurface.circle(mViewport.center(), Scaled{1}, 1, 0, "pink", Pixels{pix});
} // ChartDraw::draw
// ----------------------------------------------------------------------
void ChartDraw::draw(std::string aFilename, double aSize)
{
PdfCairo surface(aFilename, aSize, aSize);
// surface.resize(mViewport.size.width);
Surface& rescaled = surface.subsurface({0, 0}, Scaled{surface.viewport().size.width}, mViewport, true);
draw(rescaled);
} // ChartDraw::draw
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>/****************************************************************
*
* Copyright (c) 2011
* All rights reserved.
*
* Hochschule Bonn-Rhein-Sieg
* University of Applied Sciences
* Computer Science Department
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Author:
* Jan Paulus, Nico Hochgeschwender, Michael Reckhaus, Azamat Shakhimardanov
* Supervised by:
* Gerhard K. Kraetzschmar
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* This sofware is published under a dual-license: GNU Lesser General Public
* License LGPL 2.1 and BSD license. The dual-license implies that users of this
* code may choose which terms they prefer.
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* 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 Hochschule Bonn-Rhein-Sieg nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version or the BSD license.
*
* 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 LGPL and the BSD license for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL and BSD license along with this program.
*
****************************************************************/
#include "base-kinematic/FourSwedishWheelOmniBaseKinematic.hpp"
namespace youbot {
FourSwedishWheelOmniBaseKinematic::FourSwedishWheelOmniBaseKinematic() {
// Bouml preserved body begin 000513F1
this->lastWheelPositionInitialized = false;
// Bouml preserved body end 000513F1
}
FourSwedishWheelOmniBaseKinematic::~FourSwedishWheelOmniBaseKinematic() {
// Bouml preserved body begin 00051471
// Bouml preserved body end 00051471
}
///Calculates from the cartesian velocity the individual wheel velocities
///@param longitudinalVelocity is the forward or backward velocity
///@param transversalVelocity is the sideway velocity
///@param angularVelocity is the rotational velocity around the center of the YouBot
///@param wheelVelocities are the individual wheel velocities
void FourSwedishWheelOmniBaseKinematic::cartesianVelocityToWheelVelocities(const quantity<si::velocity>& longitudinalVelocity, const quantity<si::velocity>& transversalVelocity, const quantity<si::angular_velocity>& angularVelocity, std::vector<quantity<angular_velocity> >& wheelVelocities) {
// Bouml preserved body begin 0004C071
quantity<angular_velocity> RadPerSec_FromX;
quantity<angular_velocity> RadPerSec_FromY;
quantity<angular_velocity> RadPerSec_FromTheta;
wheelVelocities.assign(4, RadPerSec_FromX);
if (config.wheelRadius.value() == 0 || config.rotationRatio == 0 || config.slideRatio == 0) {
throw std::out_of_range("The wheelRadius, RotationRatio or the SlideRatio are not allowed to be zero");
}
// RadPerSec_FromX = longitudinalVelocity / config.wheelRadius;
RadPerSec_FromX = longitudinalVelocity.value() / config.wheelRadius.value() * radian_per_second;
RadPerSec_FromY = transversalVelocity.value() / (config.wheelRadius.value() * config.slideRatio) * radian_per_second;
// Calculate Rotation Component
RadPerSec_FromTheta = ((config.lengthBetweenFrontAndRearWheels + config.lengthBetweenFrontWheels) / (2.0 * config.wheelRadius)) * angularVelocity;
wheelVelocities[0] = -RadPerSec_FromX + RadPerSec_FromY + RadPerSec_FromTheta;
wheelVelocities[1] = RadPerSec_FromX + RadPerSec_FromY + RadPerSec_FromTheta;
wheelVelocities[2] = -RadPerSec_FromX - RadPerSec_FromY + RadPerSec_FromTheta;
wheelVelocities[3] = RadPerSec_FromX - RadPerSec_FromY + RadPerSec_FromTheta;
return;
// Bouml preserved body end 0004C071
}
///Calculates from the wheel velocities the cartesian velocity
///@param wheelVelocities are the velocities of the individual wheels
///@param longitudinalVelocity is the forward or backward velocity
///@param transversalVelocity is the sideway velocity
///@param angularVelocity is the rotational velocity around the center of the YouBot
void FourSwedishWheelOmniBaseKinematic::wheelVelocitiesToCartesianVelocity(const std::vector<quantity<angular_velocity> >& wheelVelocities, quantity<si::velocity>& longitudinalVelocity, quantity<si::velocity>& transversalVelocity, quantity<angular_velocity>& angularVelocity) {
// Bouml preserved body begin 0004C0F1
if (wheelVelocities.size() < 4)
throw std::out_of_range("To less wheel velocities");
if (config.lengthBetweenFrontAndRearWheels.value() == 0 || config.lengthBetweenFrontWheels.value() == 0) {
throw std::out_of_range("The lengthBetweenFrontAndRearWheels or the lengthBetweenFrontWheels are not allowed to be zero");
}
quantity<si::length> wheel_radius_per4 = config.wheelRadius / 4.0;
quantity<si::length> geom_factor = (config.lengthBetweenFrontAndRearWheels / 2.0) + (config.lengthBetweenFrontWheels / 2.0);
//now convert this to a vx,vy,vtheta
longitudinalVelocity = (-wheelVelocities[0] + wheelVelocities[1] - wheelVelocities[2] + wheelVelocities[3]).value() * wheel_radius_per4.value() * meter_per_second;
transversalVelocity = (wheelVelocities[0] + wheelVelocities[1] - wheelVelocities[2] - wheelVelocities[3]).value() * wheel_radius_per4.value() * meter_per_second;
angularVelocity = (wheelVelocities[0] + wheelVelocities[1] + wheelVelocities[2] + wheelVelocities[3]) * (wheel_radius_per4 / geom_factor).value();
// Bouml preserved body end 0004C0F1
}
///Calculates from the wheel positions the cartesian position
///@param wheelPositions are the individual positions of the wheels
///@param longitudinalPosition is the forward or backward position
///@param transversalPosition is the sideway position
///@param orientation is the rotation around the center
void FourSwedishWheelOmniBaseKinematic::wheelPositionsToCartesianPosition(const std::vector<quantity<plane_angle> >& wheelPositions, quantity<si::length>& longitudinalPosition, quantity<si::length>& transversalPosition, quantity<plane_angle>& orientation) {
// Bouml preserved body begin 00051371
if (wheelPositions.size() < 4)
throw std::out_of_range("To less wheel positions");
if (config.lengthBetweenFrontAndRearWheels.value() == 0 || config.lengthBetweenFrontWheels.value() == 0) {
throw std::out_of_range("The lengthBetweenFrontAndRearWheels or the lengthBetweenFrontWheels are not allowed to be zero");
}
if (this->lastWheelPositionInitialized == false) {
lastWheelPositions = wheelPositions;
longitudinalPos = 0 * meter;
transversalPos = 0 * meter;
angle = 0 * radian;
this->lastWheelPositionInitialized = true;
}
quantity<si::length> wheel_radius_per4 = config.wheelRadius / 4.0;
quantity<si::length> geom_factor = (config.lengthBetweenFrontAndRearWheels / 2.0) + (config.lengthBetweenFrontWheels / 2.0);
quantity<plane_angle> deltaPositionW1 = (wheelPositions[0] - lastWheelPositions[0]);
quantity<plane_angle> deltaPositionW2 = (wheelPositions[1] - lastWheelPositions[1]);
quantity<plane_angle> deltaPositionW3 = (wheelPositions[2] - lastWheelPositions[2]);
quantity<plane_angle> deltaPositionW4 = (wheelPositions[3] - lastWheelPositions[3]);
lastWheelPositions[0] = wheelPositions[0];
lastWheelPositions[1] = wheelPositions[1];
lastWheelPositions[2] = wheelPositions[2];
lastWheelPositions[3] = wheelPositions[3];
longitudinalPos += (-deltaPositionW1 + deltaPositionW2 - deltaPositionW3 + deltaPositionW4).value() * wheel_radius_per4.value() * meter;
transversalPos += (deltaPositionW1 + deltaPositionW2 - deltaPositionW3 - deltaPositionW4).value() * wheel_radius_per4.value() * meter;
angle += (deltaPositionW1 + deltaPositionW2 + deltaPositionW3 + deltaPositionW4) * (wheel_radius_per4 / geom_factor).value();
longitudinalPosition = longitudinalPos;
transversalPosition = transversalPos;
orientation = angle;
// Bouml preserved body end 00051371
}
void FourSwedishWheelOmniBaseKinematic::setConfiguration(const FourSwedishWheelOmniBaseKinematicConfiguration& configuration) {
// Bouml preserved body begin 0004C171
this->config = configuration;
// Bouml preserved body end 0004C171
}
void FourSwedishWheelOmniBaseKinematic::getConfiguration(FourSwedishWheelOmniBaseKinematicConfiguration& configuration) const {
// Bouml preserved body begin 0004C1F1
configuration = this->config;
// Bouml preserved body end 0004C1F1
}
} // namespace youbot
<commit_msg>Fixed bug in wheelPositionsToCartesianPosition<commit_after>/****************************************************************
*
* Copyright (c) 2011
* All rights reserved.
*
* Hochschule Bonn-Rhein-Sieg
* University of Applied Sciences
* Computer Science Department
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Author:
* Jan Paulus, Nico Hochgeschwender, Michael Reckhaus, Azamat Shakhimardanov
* Supervised by:
* Gerhard K. Kraetzschmar
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* This sofware is published under a dual-license: GNU Lesser General Public
* License LGPL 2.1 and BSD license. The dual-license implies that users of this
* code may choose which terms they prefer.
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* 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 Hochschule Bonn-Rhein-Sieg nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version or the BSD license.
*
* 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 LGPL and the BSD license for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL and BSD license along with this program.
*
****************************************************************/
#include "base-kinematic/FourSwedishWheelOmniBaseKinematic.hpp"
namespace youbot {
FourSwedishWheelOmniBaseKinematic::FourSwedishWheelOmniBaseKinematic() {
// Bouml preserved body begin 000513F1
this->lastWheelPositionInitialized = false;
// Bouml preserved body end 000513F1
}
FourSwedishWheelOmniBaseKinematic::~FourSwedishWheelOmniBaseKinematic() {
// Bouml preserved body begin 00051471
// Bouml preserved body end 00051471
}
///Calculates from the cartesian velocity the individual wheel velocities
///@param longitudinalVelocity is the forward or backward velocity
///@param transversalVelocity is the sideway velocity
///@param angularVelocity is the rotational velocity around the center of the YouBot
///@param wheelVelocities are the individual wheel velocities
void FourSwedishWheelOmniBaseKinematic::cartesianVelocityToWheelVelocities(const quantity<si::velocity>& longitudinalVelocity, const quantity<si::velocity>& transversalVelocity, const quantity<si::angular_velocity>& angularVelocity, std::vector<quantity<angular_velocity> >& wheelVelocities) {
// Bouml preserved body begin 0004C071
quantity<angular_velocity> RadPerSec_FromX;
quantity<angular_velocity> RadPerSec_FromY;
quantity<angular_velocity> RadPerSec_FromTheta;
wheelVelocities.assign(4, RadPerSec_FromX);
if (config.wheelRadius.value() == 0 || config.rotationRatio == 0 || config.slideRatio == 0) {
throw std::out_of_range("The wheelRadius, RotationRatio or the SlideRatio are not allowed to be zero");
}
// RadPerSec_FromX = longitudinalVelocity / config.wheelRadius;
RadPerSec_FromX = longitudinalVelocity.value() / config.wheelRadius.value() * radian_per_second;
RadPerSec_FromY = transversalVelocity.value() / (config.wheelRadius.value() * config.slideRatio) * radian_per_second;
// Calculate Rotation Component
RadPerSec_FromTheta = ((config.lengthBetweenFrontAndRearWheels + config.lengthBetweenFrontWheels) / (2.0 * config.wheelRadius)) * angularVelocity;
wheelVelocities[0] = -RadPerSec_FromX + RadPerSec_FromY + RadPerSec_FromTheta;
wheelVelocities[1] = RadPerSec_FromX + RadPerSec_FromY + RadPerSec_FromTheta;
wheelVelocities[2] = -RadPerSec_FromX - RadPerSec_FromY + RadPerSec_FromTheta;
wheelVelocities[3] = RadPerSec_FromX - RadPerSec_FromY + RadPerSec_FromTheta;
return;
// Bouml preserved body end 0004C071
}
///Calculates from the wheel velocities the cartesian velocity
///@param wheelVelocities are the velocities of the individual wheels
///@param longitudinalVelocity is the forward or backward velocity
///@param transversalVelocity is the sideway velocity
///@param angularVelocity is the rotational velocity around the center of the YouBot
void FourSwedishWheelOmniBaseKinematic::wheelVelocitiesToCartesianVelocity(const std::vector<quantity<angular_velocity> >& wheelVelocities, quantity<si::velocity>& longitudinalVelocity, quantity<si::velocity>& transversalVelocity, quantity<angular_velocity>& angularVelocity) {
// Bouml preserved body begin 0004C0F1
if (wheelVelocities.size() < 4)
throw std::out_of_range("To less wheel velocities");
if (config.lengthBetweenFrontAndRearWheels.value() == 0 || config.lengthBetweenFrontWheels.value() == 0) {
throw std::out_of_range("The lengthBetweenFrontAndRearWheels or the lengthBetweenFrontWheels are not allowed to be zero");
}
quantity<si::length> wheel_radius_per4 = config.wheelRadius / 4.0;
quantity<si::length> geom_factor = (config.lengthBetweenFrontAndRearWheels / 2.0) + (config.lengthBetweenFrontWheels / 2.0);
//now convert this to a vx,vy,vtheta
longitudinalVelocity = (-wheelVelocities[0] + wheelVelocities[1] - wheelVelocities[2] + wheelVelocities[3]).value() * wheel_radius_per4.value() * meter_per_second;
transversalVelocity = (wheelVelocities[0] + wheelVelocities[1] - wheelVelocities[2] - wheelVelocities[3]).value() * wheel_radius_per4.value() * meter_per_second;
angularVelocity = (wheelVelocities[0] + wheelVelocities[1] + wheelVelocities[2] + wheelVelocities[3]) * (wheel_radius_per4 / geom_factor).value();
// Bouml preserved body end 0004C0F1
}
///Calculates from the wheel positions the cartesian position
///@param wheelPositions are the individual positions of the wheels
///@param longitudinalPosition is the forward or backward position
///@param transversalPosition is the sideway position
///@param orientation is the rotation around the center
void FourSwedishWheelOmniBaseKinematic::wheelPositionsToCartesianPosition(const std::vector<quantity<plane_angle> >& wheelPositions, quantity<si::length>& longitudinalPosition, quantity<si::length>& transversalPosition, quantity<plane_angle>& orientation) {
// Bouml preserved body begin 00051371
if (wheelPositions.size() < 4)
throw std::out_of_range("To less wheel positions");
if (config.lengthBetweenFrontAndRearWheels.value() == 0 || config.lengthBetweenFrontWheels.value() == 0) {
throw std::out_of_range("The lengthBetweenFrontAndRearWheels or the lengthBetweenFrontWheels are not allowed to be zero");
}
if (this->lastWheelPositionInitialized == false) {
lastWheelPositions = wheelPositions;
longitudinalPos = 0 * meter;
transversalPos = 0 * meter;
angle = 0 * radian;
this->lastWheelPositionInitialized = true;
}
quantity<si::length> deltaLongitudinalPos;
quantity<si::length> deltaTransversalPos;
quantity<si::length> wheel_radius_per4 = config.wheelRadius / 4.0;
quantity<si::length> geom_factor = (config.lengthBetweenFrontAndRearWheels / 2.0) + (config.lengthBetweenFrontWheels / 2.0);
quantity<plane_angle> deltaPositionW1 = (wheelPositions[0] - lastWheelPositions[0]);
quantity<plane_angle> deltaPositionW2 = (wheelPositions[1] - lastWheelPositions[1]);
quantity<plane_angle> deltaPositionW3 = (wheelPositions[2] - lastWheelPositions[2]);
quantity<plane_angle> deltaPositionW4 = (wheelPositions[3] - lastWheelPositions[3]);
lastWheelPositions[0] = wheelPositions[0];
lastWheelPositions[1] = wheelPositions[1];
lastWheelPositions[2] = wheelPositions[2];
lastWheelPositions[3] = wheelPositions[3];
deltaLongitudinalPos = (-deltaPositionW1 + deltaPositionW2 - deltaPositionW3 + deltaPositionW4).value() * wheel_radius_per4.value() * meter;
deltaTransversalPos = (deltaPositionW1 + deltaPositionW2 - deltaPositionW3 - deltaPositionW4).value() * wheel_radius_per4.value() * meter;
angle += (deltaPositionW1 + deltaPositionW2 + deltaPositionW3 + deltaPositionW4) * (wheel_radius_per4 / geom_factor).value();
longitudinalPos += deltaLongitudinalPos * cos(angle) - deltaTransversalPos * sin(angle);
transversalPos += deltaLongitudinalPos * sin(angle) + deltaTransversalPos * cos(angle);
longitudinalPosition = longitudinalPos;
transversalPosition = transversalPos;
orientation = angle;
// Bouml preserved body end 00051371
}
void FourSwedishWheelOmniBaseKinematic::setConfiguration(const FourSwedishWheelOmniBaseKinematicConfiguration& configuration) {
// Bouml preserved body begin 0004C171
this->config = configuration;
// Bouml preserved body end 0004C171
}
void FourSwedishWheelOmniBaseKinematic::getConfiguration(FourSwedishWheelOmniBaseKinematicConfiguration& configuration) const {
// Bouml preserved body begin 0004C1F1
configuration = this->config;
// Bouml preserved body end 0004C1F1
}
} // namespace youbot
<|endoftext|>
|
<commit_before><commit_msg>keep only those macros compiled that really need to<commit_after><|endoftext|>
|
<commit_before>#include "HUDobject_Animated.h"
#include <cstring>
#include <GLFW/glfw3.h>
void HUDobject_Animated::graphicsUpdate(GLuint program, const GraphicsObjectManager& graphicsObjectManager)
{
if (!m_isAnimating)
return;
double currentTime = glfwGetTime();
if (currentTime < m_animationEndTime)
{
float progressPercentage = float((currentTime - m_animationStartTime) / (m_animationEndTime - m_animationStartTime));
for (int i = 0; i < 8; i += 2)
{
m_vertexData[i] = m_vertexDataAnimationOrigin[i] + (m_vertexDataAnimationDestination[i] - m_vertexDataAnimationOrigin[i]) * progressPercentage;
m_vertexData[i + 1] = m_vertexDataAnimationOrigin[i + 1] + (m_vertexDataAnimationDestination[i + 1] - m_vertexDataAnimationOrigin[i + 1]) * progressPercentage;
}
m_dirtyFlag = true;
} else if (m_isAnimating)
{
for (int i = 0; i < 8; i += 2)
{
m_vertexData[i] = m_vertexDataAnimationDestination[i];
m_vertexData[i + 1] = m_vertexDataAnimationDestination[i + 1];
}
m_dirtyFlag = true;
m_isAnimating = false;
}
}
void HUDobject_Animated::setCoords(glm::vec2 pos, GLfloat width, GLfloat height, float animationDuration)
{
void* args[]{ &pos, &width, &height };
animate(SET_COORDS, args, animationDuration);
}
void HUDobject_Animated::setWidth(GLfloat width, float animationDuration)
{
void* args[]{ &width };
animate(SET_WIDTH, args, animationDuration);
}
void HUDobject_Animated::setHeight(GLfloat height, float animationDuration)
{
void* args[]{ &height };
animate(SET_HEIGHT, args, animationDuration);
}
void HUDobject_Animated::move(glm::vec2 direction, float animationDuration)
{
void* args[]{ &direction };
animate(MOVE, args, animationDuration);
}
void HUDobject_Animated::moveTo(glm::vec2 pos, float animationDuration)
{
void* args[]{ &pos };
animate(MOVE_TO, args, animationDuration);
}
void HUDobject_Animated::zoom(GLfloat percentage, float animationDuration, glm::vec2 focus)
{
void* args[]{ &percentage, &focus };
animate(ZOOM, args, animationDuration);
}
void HUDobject_Animated::animate(animationFunction func, void* args[], float animationDuration)
{
if (animationDuration > 0.0f)
{
m_animationStartTime = glfwGetTime();
if (!m_isAnimating)
{
std::memcpy(m_vertexDataAnimationOrigin, m_vertexData, sizeof(m_vertexDataAnimationOrigin));
std::memcpy(m_vertexDataAnimationDestination, m_vertexData, sizeof(m_vertexDataAnimationDestination));
invoke(func, args, *this, m_vertexDataAnimationDestination);
m_isAnimating = true;
} else
invoke(func, args, *this, m_vertexDataAnimationDestination);
m_animationEndTime = m_animationStartTime + animationDuration;
} else if (m_isAnimating)
{
invoke(func, args, *this, m_vertexDataAnimationOrigin);
invoke(func, args, *this, m_vertexDataAnimationDestination);
} else
invoke(func, args, *this, m_vertexData);
}
constexpr void HUDobject_Animated::invoke(animationFunction func, void* args[], HUDobject_Dynamic& obj, GLfloat vertexData[])
{
switch (func)
{
case SET_COORDS:
_setCoords(*static_cast<glm::vec2*>(args[0]), *static_cast<GLfloat*>(args[1]), *static_cast<GLfloat*>(args[2]), obj, vertexData);
break;
case SET_WIDTH:
_setWidth(*static_cast<GLfloat*>(args[0]), obj, vertexData);
break;
case SET_HEIGHT:
_setHeight(*static_cast<GLfloat*>(args[0]), obj, vertexData);
break;
case MOVE:
_move(*static_cast<glm::vec2*>(args[0]), obj, vertexData);
break;
case MOVE_TO:
_moveTo(*static_cast<glm::vec2*>(args[0]), obj, vertexData);
break;
case ZOOM:
_zoom(*static_cast<GLfloat*>(args[0]), *static_cast<glm::vec2*>(args[1]), obj, vertexData);
break;
}
}
<commit_msg>Fixed animation stuttering<commit_after>#include "HUDobject_Animated.h"
#include <cstring>
#include <GLFW/glfw3.h>
void HUDobject_Animated::graphicsUpdate(GLuint program, const GraphicsObjectManager& graphicsObjectManager)
{
if (!m_isAnimating)
return;
double currentTime = glfwGetTime();
if (currentTime < m_animationEndTime)
{
float progressPercentage = float((currentTime - m_animationStartTime) / (m_animationEndTime - m_animationStartTime));
for (int i = 0; i < 8; i += 2)
{
m_vertexData[i] = m_vertexDataAnimationOrigin[i] + (m_vertexDataAnimationDestination[i] - m_vertexDataAnimationOrigin[i]) * progressPercentage;
m_vertexData[i + 1] = m_vertexDataAnimationOrigin[i + 1] + (m_vertexDataAnimationDestination[i + 1] - m_vertexDataAnimationOrigin[i + 1]) * progressPercentage;
}
m_dirtyFlag = true;
} else if (m_isAnimating)
{
for (int i = 0; i < 8; i += 2)
{
m_vertexData[i] = m_vertexDataAnimationDestination[i];
m_vertexData[i + 1] = m_vertexDataAnimationDestination[i + 1];
}
m_dirtyFlag = true;
m_isAnimating = false;
}
}
void HUDobject_Animated::setCoords(glm::vec2 pos, GLfloat width, GLfloat height, float animationDuration)
{
void* args[]{ &pos, &width, &height };
animate(SET_COORDS, args, animationDuration);
}
void HUDobject_Animated::setWidth(GLfloat width, float animationDuration)
{
void* args[]{ &width };
animate(SET_WIDTH, args, animationDuration);
}
void HUDobject_Animated::setHeight(GLfloat height, float animationDuration)
{
void* args[]{ &height };
animate(SET_HEIGHT, args, animationDuration);
}
void HUDobject_Animated::move(glm::vec2 direction, float animationDuration)
{
void* args[]{ &direction };
animate(MOVE, args, animationDuration);
}
void HUDobject_Animated::moveTo(glm::vec2 pos, float animationDuration)
{
void* args[]{ &pos };
animate(MOVE_TO, args, animationDuration);
}
void HUDobject_Animated::zoom(GLfloat percentage, float animationDuration, glm::vec2 focus)
{
void* args[]{ &percentage, &focus };
animate(ZOOM, args, animationDuration);
}
void HUDobject_Animated::animate(animationFunction func, void* args[], float animationDuration)
{
if (animationDuration > 0.0f)
{
m_animationStartTime = glfwGetTime();
if (!m_isAnimating)
{
std::memcpy(m_vertexDataAnimationOrigin, m_vertexData, sizeof(m_vertexDataAnimationOrigin));
std::memcpy(m_vertexDataAnimationDestination, m_vertexData, sizeof(m_vertexDataAnimationDestination));
invoke(func, args, *this, m_vertexDataAnimationDestination);
m_isAnimating = true;
} else
{
std::memcpy(m_vertexDataAnimationOrigin, m_vertexData, sizeof(m_vertexDataAnimationOrigin));
invoke(func, args, *this, m_vertexDataAnimationDestination);
}
m_animationEndTime = m_animationStartTime + animationDuration;
} else if (m_isAnimating)
{
invoke(func, args, *this, m_vertexDataAnimationOrigin);
invoke(func, args, *this, m_vertexDataAnimationDestination);
} else
invoke(func, args, *this, m_vertexData);
}
constexpr void HUDobject_Animated::invoke(animationFunction func, void* args[], HUDobject_Dynamic& obj, GLfloat vertexData[])
{
switch (func)
{
case SET_COORDS:
_setCoords(*static_cast<glm::vec2*>(args[0]), *static_cast<GLfloat*>(args[1]), *static_cast<GLfloat*>(args[2]), obj, vertexData);
break;
case SET_WIDTH:
_setWidth(*static_cast<GLfloat*>(args[0]), obj, vertexData);
break;
case SET_HEIGHT:
_setHeight(*static_cast<GLfloat*>(args[0]), obj, vertexData);
break;
case MOVE:
_move(*static_cast<glm::vec2*>(args[0]), obj, vertexData);
break;
case MOVE_TO:
_moveTo(*static_cast<glm::vec2*>(args[0]), obj, vertexData);
break;
case ZOOM:
_zoom(*static_cast<GLfloat*>(args[0]), *static_cast<glm::vec2*>(args[1]), obj, vertexData);
break;
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
* Authors:
* - Paul Asmuth <paul@zscale.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include "unistd.h"
#include <eventql/util/logging.h>
#include <eventql/util/wallclock.h>
#include <eventql/util/application.h>
#include <eventql/db/ReplicationWorker.h>
#include <eventql/db/Partition.h>
#include <eventql/server/server_stats.h>
#include "eventql/eventql.h"
namespace eventql {
ReplicationWorker::ReplicationWorker(
RefPtr<ReplicationScheme> repl_scheme,
PartitionMap* pmap,
http::HTTPConnectionPool* http) :
repl_scheme_(repl_scheme),
pmap_(pmap),
http_(http),
queue_([] (
const Pair<uint64_t, RefPtr<Partition>>& a,
const Pair<uint64_t, RefPtr<Partition>>& b) {
return a.first < b.first;
}),
running_(false) {
pmap->subscribeToPartitionChanges([this] (
RefPtr<eventql::PartitionChangeNotification> change) {
enqueuePartition(change->partition);
});
start();
}
ReplicationWorker::~ReplicationWorker() {
stop();
}
void ReplicationWorker::enqueuePartition(RefPtr<Partition> partition) {
std::unique_lock<std::mutex> lk(mutex_);
enqueuePartitionWithLock(partition);
}
void ReplicationWorker::enqueuePartition(
RefPtr<Partition> partition,
uint64_t delay_usecs) {
std::unique_lock<std::mutex> lk(mutex_);
enqueuePartitionWithLock(partition);
}
void ReplicationWorker::enqueuePartitionWithLock(
RefPtr<Partition> partition,
uint64_t delay_usecs /* = 0 */) {
auto uuid = partition->uuid();
if (waitset_.count(uuid) > 0) {
return;
}
queue_.emplace(
WallClock::unixMicros() + kReplicationCorkWindowMicros + delay_usecs,
partition);
z1stats()->replication_queue_length.set(queue_.size());
waitset_.emplace(uuid);
cv_.notify_all();
}
void ReplicationWorker::start() {
running_ = true;
for (int i = 0; i < 8; ++i) {
threads_.emplace_back(std::bind(&ReplicationWorker::work, this));
}
}
void ReplicationWorker::stop() {
if (!running_) {
return;
}
running_ = false;
cv_.notify_all();
for (auto& t : threads_) {
t.join();
}
}
void ReplicationWorker::work() {
Application::setCurrentThreadName("z1d-replication");
std::unique_lock<std::mutex> lk(mutex_);
while (running_) {
if (queue_.size() == 0) {
cv_.wait(lk);
}
if (queue_.size() == 0) {
continue;
}
auto now = WallClock::unixMicros();
if (now < queue_.begin()->first) {
cv_.wait_for(
lk,
std::chrono::microseconds(queue_.begin()->first - now));
continue;
}
auto partition = queue_.begin()->second;
queue_.erase(queue_.begin());
auto repl_scheme = repl_scheme_;
RefPtr<PartitionReplication> repl;
bool success = true;
{
lk.unlock();
try {
repl = partition->getReplicationStrategy(repl_scheme, http_);
success = repl->replicate();
} catch (const StandardException& e) {
logError("tsdb", e, "ReplicationWorker error");
success = false;
}
lk.lock();
}
if (success) {
waitset_.erase(partition->uuid());
repl = partition->getReplicationStrategy(repl_scheme, http_);
if (repl->needsReplication()) {
enqueuePartitionWithLock(partition);
} else {
auto snap = partition->getSnapshot();
auto full_copies = repl->numFullRemoteCopies();
if (!repl_scheme->hasLocalReplica(snap->key) &&
full_copies >= repl_scheme->minNumCopies()) {
auto dropped =
pmap_->dropLocalPartition(
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key);
if (!dropped) {
enqueuePartitionWithLock(partition);
}
}
}
} else {
auto delay = 600 * kMicrosPerSecond; // FIXPAUL increasing delay..
queue_.emplace(now + delay, partition);
}
z1stats()->replication_queue_length.set(queue_.size());
}
}
} // namespace eventql
<commit_msg>disable replication<commit_after>/**
* Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
* Authors:
* - Paul Asmuth <paul@zscale.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include "unistd.h"
#include <eventql/util/logging.h>
#include <eventql/util/wallclock.h>
#include <eventql/util/application.h>
#include <eventql/db/ReplicationWorker.h>
#include <eventql/db/Partition.h>
#include <eventql/server/server_stats.h>
#include "eventql/eventql.h"
namespace eventql {
ReplicationWorker::ReplicationWorker(
RefPtr<ReplicationScheme> repl_scheme,
PartitionMap* pmap,
http::HTTPConnectionPool* http) :
repl_scheme_(repl_scheme),
pmap_(pmap),
http_(http),
queue_([] (
const Pair<uint64_t, RefPtr<Partition>>& a,
const Pair<uint64_t, RefPtr<Partition>>& b) {
return a.first < b.first;
}),
running_(false) {
pmap->subscribeToPartitionChanges([this] (
RefPtr<eventql::PartitionChangeNotification> change) {
enqueuePartition(change->partition);
});
start();
}
ReplicationWorker::~ReplicationWorker() {
stop();
}
void ReplicationWorker::enqueuePartition(RefPtr<Partition> partition) {
std::unique_lock<std::mutex> lk(mutex_);
enqueuePartitionWithLock(partition);
}
void ReplicationWorker::enqueuePartition(
RefPtr<Partition> partition,
uint64_t delay_usecs) {
std::unique_lock<std::mutex> lk(mutex_);
enqueuePartitionWithLock(partition);
}
void ReplicationWorker::enqueuePartitionWithLock(
RefPtr<Partition> partition,
uint64_t delay_usecs /* = 0 */) {
auto uuid = partition->uuid();
if (waitset_.count(uuid) > 0) {
return;
}
queue_.emplace(
WallClock::unixMicros() + kReplicationCorkWindowMicros + delay_usecs,
partition);
z1stats()->replication_queue_length.set(queue_.size());
waitset_.emplace(uuid);
cv_.notify_all();
}
void ReplicationWorker::start() {
running_ = true;
for (int i = 0; i < 0; ++i) {
threads_.emplace_back(std::bind(&ReplicationWorker::work, this));
}
}
void ReplicationWorker::stop() {
if (!running_) {
return;
}
running_ = false;
cv_.notify_all();
for (auto& t : threads_) {
t.join();
}
}
void ReplicationWorker::work() {
Application::setCurrentThreadName("z1d-replication");
std::unique_lock<std::mutex> lk(mutex_);
while (running_) {
if (queue_.size() == 0) {
cv_.wait(lk);
}
if (queue_.size() == 0) {
continue;
}
auto now = WallClock::unixMicros();
if (now < queue_.begin()->first) {
cv_.wait_for(
lk,
std::chrono::microseconds(queue_.begin()->first - now));
continue;
}
auto partition = queue_.begin()->second;
queue_.erase(queue_.begin());
auto repl_scheme = repl_scheme_;
RefPtr<PartitionReplication> repl;
bool success = true;
{
lk.unlock();
try {
repl = partition->getReplicationStrategy(repl_scheme, http_);
success = repl->replicate();
} catch (const StandardException& e) {
logError("tsdb", e, "ReplicationWorker error");
success = false;
}
lk.lock();
}
if (success) {
waitset_.erase(partition->uuid());
repl = partition->getReplicationStrategy(repl_scheme, http_);
if (repl->needsReplication()) {
enqueuePartitionWithLock(partition);
} else {
auto snap = partition->getSnapshot();
auto full_copies = repl->numFullRemoteCopies();
if (!repl_scheme->hasLocalReplica(snap->key) &&
full_copies >= repl_scheme->minNumCopies()) {
auto dropped =
pmap_->dropLocalPartition(
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key);
if (!dropped) {
enqueuePartitionWithLock(partition);
}
}
}
} else {
auto delay = 600 * kMicrosPerSecond; // FIXPAUL increasing delay..
queue_.emplace(now + delay, partition);
}
z1stats()->replication_queue_length.set(queue_.size());
}
}
} // namespace eventql
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// CoinQ_peer_io.cpp
//
// Copyright (c) 2012-2013 Eric Lombrozo
//
// All Rights Reserved.
#include "CoinQ_peer_io.h"
#include <logger/logger.h>
#include <sstream>
using namespace CoinQ;
using namespace std;
const unsigned char Peer::DEFAULT_Ipv6[] = {0,0,0,0,0,0,0,0,0,0,255,255,127,0,0,1};
void Peer::do_handshake()
{
if (!bRunning) return;
// Send version message
Coin::NetworkAddress peerAddress;
peerAddress.set(NODE_NETWORK, DEFAULT_Ipv6, strtoul(port_.c_str(), NULL, 0));
Coin::VersionMessage versionMessage(protocol_version_, NODE_NETWORK, time(NULL), peerAddress, peerAddress, getRandomNonce64(), user_agent_.c_str(), start_height_, relay_);
Coin::CoinNodeMessage msg(magic_bytes_, &versionMessage);
LOGGER(trace) << "Sending version message." << endl;
do_send(msg);
// Give peer 5 seconds to respond
timer_.expires_from_now(boost::posix_time::seconds(5));
timer_.async_wait([this](const boost::system::error_code& ec) {
if (!bRunning) return;
LOGGER(trace) << "Peer timer handler" << std::endl;
if (ec == boost::asio::error::operation_aborted) return;
if (bHandshakeComplete) return;
boost::lock_guard<boost::mutex> lock(handshakeMutex);
if (bHandshakeComplete) return;
do_stop();
notifyTimeout(*this);
});
}
void Peer::do_read()
{
boost::asio::async_read(socket_, boost::asio::buffer(read_buffer, READ_BUFFER_SIZE), boost::asio::transfer_at_least(MIN_MESSAGE_HEADER_SIZE),
strand_.wrap([this](const boost::system::error_code& ec, std::size_t bytes_read) {
if (!bRunning) return;
if (ec)
{
if (ec == boost::asio::error::operation_aborted) return;
read_message.clear();
do_stop();
stringstream err;
err << "Peer read error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
return;
}
read_message += uchar_vector(read_buffer, bytes_read);
while (read_message.size() >= MIN_MESSAGE_HEADER_SIZE)
{
// Find the first occurrence of the magic bytes, discard anything before it.
// If magic bytes are not found, read new buffer.
// TODO: detect misbehaving node and disconnect.
uchar_vector::iterator it = std::search(read_message.begin(), read_message.end(), magic_bytes_vector_.begin(), magic_bytes_vector_.end());
if (it == read_message.end())
{
read_message.clear();
break;
}
read_message.assign(it, read_message.end());
if (read_message.size() < MIN_MESSAGE_HEADER_SIZE) break;
// Get command
unsigned char command[13];
command[12] = 0;
uchar_vector(read_message.begin() + 4, read_message.begin() + 16).copyToArray(command);
// Get payload size
unsigned int payloadSize = vch_to_uint<uint32_t>(uchar_vector(read_message.begin() + 16, read_message.begin() + 20), _BIG_ENDIAN);
if (read_message.size() < MIN_MESSAGE_HEADER_SIZE + payloadSize) break;
try
{
Coin::CoinNodeMessage peerMessage(read_message);
if (!peerMessage.isChecksumValid()) throw std::runtime_error("Invalid checksum.");
std::string command = peerMessage.getCommand();
if (command == "verack") {
LOGGER(trace) << "Peer read handler - VERACK" << std::endl;
// Signal completion of handshake
if (bHandshakeComplete) throw std::runtime_error("Second verack received.");
boost::unique_lock<boost::mutex> lock(handshakeMutex);
if (bHandshakeComplete) throw std::runtime_error("Second verack received.");
timer_.cancel();
bHandshakeComplete = true;
lock.unlock();
bWriteReady = true;
notifyOpen(*this);
}
else if (command == "version")
{
LOGGER(trace) << "Peer read handler - VERSION" << std::endl;
// TODO: Check version information
Coin::VerackMessage verackMessage;
Coin::CoinNodeMessage msg(magic_bytes_, &verackMessage);
do_send(msg);
}
else if (command == "inv")
{
LOGGER(trace) << "Peer read handler - INV" << std::endl;
Coin::Inventory* pInventory = static_cast<Coin::Inventory*>(peerMessage.getPayload());
notifyInv(*this, *pInventory);
}
else if (command == "tx")
{
LOGGER(trace) << "Peer read handler - TX" << std::endl;
Coin::Transaction* pTx = static_cast<Coin::Transaction*>(peerMessage.getPayload());
notifyTx(*this, *pTx);
}
else if (command == "block")
{
LOGGER(trace) << "Peer read handler - BLOCK" << std::endl;
Coin::CoinBlock* pBlock = static_cast<Coin::CoinBlock*>(peerMessage.getPayload());
notifyBlock(*this, *pBlock);
}
else if (command == "merkleblock")
{
LOGGER(trace) << "Peer read handler - MERKLEBLOCK" << std::endl;
Coin::MerkleBlock* pMerkleBlock = static_cast<Coin::MerkleBlock*>(peerMessage.getPayload());
notifyMerkleBlock(*this, *pMerkleBlock);
}
else if (command == "addr")
{
LOGGER(trace) << "Peer read handler - ADDR" << std::endl;
Coin::AddrMessage* pAddr = static_cast<Coin::AddrMessage*>(peerMessage.getPayload());
notifyAddr(*this, *pAddr);
}
else if (command == "headers")
{
LOGGER(trace) << "Peer read handler - HEADERS" << std::endl;
Coin::HeadersMessage* pHeaders = static_cast<Coin::HeadersMessage*>(peerMessage.getPayload());
notifyHeaders(*this, *pHeaders);
}
else
{
LOGGER(error) << "Peer read handler - command not implemented: " << command << std::endl;
std::stringstream err;
err << "Command type not implemented: " << command;
notifyProtocolError(*this, err.str(), -1);
}
notifyMessage(*this, peerMessage);
}
catch (const std::exception& e)
{
std::stringstream err;
err << "Message decode error: " << e.what();
notifyProtocolError(*this, err.str(), -1);
}
read_message.assign(read_message.begin() + MIN_MESSAGE_HEADER_SIZE + payloadSize, read_message.end());
}
do_read();
}));
}
void Peer::do_write(boost::shared_ptr<uchar_vector> data)
{
if (!bRunning) return;
boost::asio::async_write(socket_, boost::asio::buffer(*data), boost::asio::transfer_all(),
strand_.wrap([this](const boost::system::error_code& ec, std::size_t bytes_written) {
if (!bRunning) return;
LOGGER(trace) << "Peer write handler." << std::endl;
if (ec)
{
if (ec == boost::asio::error::operation_aborted) return;
stringstream err;
err << "Peer write error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
return;
}
boost::lock_guard<boost::mutex> sendLock(sendMutex);
sendQueue.pop();
if (!sendQueue.empty()) { do_write(sendQueue.front()); }
}));
}
void Peer::do_send(const Coin::CoinNodeMessage& message)
{
boost::shared_ptr<uchar_vector> data(new uchar_vector(message.getSerialized()));
boost::lock_guard<boost::mutex> sendLock(sendMutex);
sendQueue.push(data);
if (sendQueue.size() == 1) { strand_.post(boost::bind(&Peer::do_write, this, data)); }
}
void Peer::do_connect(tcp::resolver::iterator iter)
{
boost::asio::async_connect(socket_, iter, strand_.wrap([this](const boost::system::error_code& ec, tcp::resolver::iterator) {
if (!bRunning) return;
LOGGER(trace) << "Peer connect handler." << std::endl;
if (ec)
{
if (ec == boost::asio::error::operation_aborted) return;
do_stop();
stringstream err;
err << "Peer connect error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
return;
}
try
{
do_read();
do_handshake();
}
catch (const boost::system::error_code& ec)
{
do_stop();
notifyConnectionError(*this, ec.message(), ec.value());
}
catch (const std::exception& e)
{
do_stop();
notifyConnectionError(*this, e.what(), -1);
}
}));
}
void Peer::do_stop()
{
bRunning = false;
bHandshakeComplete = false;
bWriteReady = false;
notifyClose(*this);
notifyStop(*this);
}
void Peer::start()
{
if (bRunning) throw std::runtime_error("Peer already started.");
boost::unique_lock<boost::shared_mutex> lock(mutex);
if (bRunning) throw std::runtime_error("Peer already started.");
bRunning = true;
bHandshakeComplete = false;
bWriteReady = false;
tcp::resolver::query query(host_, port_);
resolver_.async_resolve(query, [this](const boost::system::error_code& ec, tcp::resolver::iterator iterator) {
if (!bRunning) return;
LOGGER(trace) << "Peer resolve handler." << std::endl;
if (ec)
{
if (ec == boost::asio::error::operation_aborted) return;
do_stop();
stringstream err;
err << "Peer resolve error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
return;
}
endpoint_ = *iterator;
strand_.post(boost::bind(&Peer::do_connect, this, iterator));
});
}
void Peer::stop()
{
{
if (!bRunning) return;
boost::unique_lock<boost::shared_mutex> lock(mutex);
if (!bRunning) return;
bRunning = false;
// socket_.cancel();
socket_.close();
do_clearSendQueue();
bHandshakeComplete = false;
bWriteReady = false;
}
notifyClose(*this);
notifyStop(*this);
}
bool Peer::send(Coin::CoinNodeStructure& message)
{
boost::shared_lock<boost::shared_mutex> runLock(mutex);
if (!bRunning || !bWriteReady) return false;
Coin::CoinNodeMessage wrappedMessage(magic_bytes_, &message);
do_send(wrappedMessage);
return true;
}
void Peer::do_clearSendQueue()
{
boost::lock_guard<boost::mutex> sendLock(sendMutex);
while (!sendQueue.empty()) { sendQueue.pop(); }
}
<commit_msg>call socket::shutdown() before disconnecting.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// CoinQ_peer_io.cpp
//
// Copyright (c) 2012-2013 Eric Lombrozo
//
// All Rights Reserved.
#include "CoinQ_peer_io.h"
#include <logger/logger.h>
#include <sstream>
using namespace CoinQ;
using namespace std;
const unsigned char Peer::DEFAULT_Ipv6[] = {0,0,0,0,0,0,0,0,0,0,255,255,127,0,0,1};
void Peer::do_handshake()
{
if (!bRunning) return;
// Send version message
Coin::NetworkAddress peerAddress;
peerAddress.set(NODE_NETWORK, DEFAULT_Ipv6, strtoul(port_.c_str(), NULL, 0));
Coin::VersionMessage versionMessage(protocol_version_, NODE_NETWORK, time(NULL), peerAddress, peerAddress, getRandomNonce64(), user_agent_.c_str(), start_height_, relay_);
Coin::CoinNodeMessage msg(magic_bytes_, &versionMessage);
LOGGER(trace) << "Sending version message." << endl;
do_send(msg);
// Give peer 5 seconds to respond
timer_.expires_from_now(boost::posix_time::seconds(5));
timer_.async_wait([this](const boost::system::error_code& ec) {
if (!bRunning) return;
LOGGER(trace) << "Peer timer handler" << std::endl;
if (ec == boost::asio::error::operation_aborted) return;
if (bHandshakeComplete) return;
boost::lock_guard<boost::mutex> lock(handshakeMutex);
if (bHandshakeComplete) return;
do_stop();
notifyTimeout(*this);
});
}
void Peer::do_read()
{
boost::asio::async_read(socket_, boost::asio::buffer(read_buffer, READ_BUFFER_SIZE), boost::asio::transfer_at_least(MIN_MESSAGE_HEADER_SIZE),
strand_.wrap([this](const boost::system::error_code& ec, std::size_t bytes_read) {
if (!bRunning) return;
if (ec)
{
if (ec == boost::asio::error::operation_aborted) return;
read_message.clear();
do_stop();
stringstream err;
err << "Peer read error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
return;
}
read_message += uchar_vector(read_buffer, bytes_read);
while (read_message.size() >= MIN_MESSAGE_HEADER_SIZE)
{
// Find the first occurrence of the magic bytes, discard anything before it.
// If magic bytes are not found, read new buffer.
// TODO: detect misbehaving node and disconnect.
uchar_vector::iterator it = std::search(read_message.begin(), read_message.end(), magic_bytes_vector_.begin(), magic_bytes_vector_.end());
if (it == read_message.end())
{
read_message.clear();
break;
}
read_message.assign(it, read_message.end());
if (read_message.size() < MIN_MESSAGE_HEADER_SIZE) break;
// Get command
unsigned char command[13];
command[12] = 0;
uchar_vector(read_message.begin() + 4, read_message.begin() + 16).copyToArray(command);
// Get payload size
unsigned int payloadSize = vch_to_uint<uint32_t>(uchar_vector(read_message.begin() + 16, read_message.begin() + 20), _BIG_ENDIAN);
if (read_message.size() < MIN_MESSAGE_HEADER_SIZE + payloadSize) break;
try
{
Coin::CoinNodeMessage peerMessage(read_message);
if (!peerMessage.isChecksumValid()) throw std::runtime_error("Invalid checksum.");
std::string command = peerMessage.getCommand();
if (command == "verack") {
LOGGER(trace) << "Peer read handler - VERACK" << std::endl;
// Signal completion of handshake
if (bHandshakeComplete) throw std::runtime_error("Second verack received.");
boost::unique_lock<boost::mutex> lock(handshakeMutex);
if (bHandshakeComplete) throw std::runtime_error("Second verack received.");
timer_.cancel();
bHandshakeComplete = true;
lock.unlock();
bWriteReady = true;
notifyOpen(*this);
}
else if (command == "version")
{
LOGGER(trace) << "Peer read handler - VERSION" << std::endl;
// TODO: Check version information
Coin::VerackMessage verackMessage;
Coin::CoinNodeMessage msg(magic_bytes_, &verackMessage);
do_send(msg);
}
else if (command == "inv")
{
LOGGER(trace) << "Peer read handler - INV" << std::endl;
Coin::Inventory* pInventory = static_cast<Coin::Inventory*>(peerMessage.getPayload());
notifyInv(*this, *pInventory);
}
else if (command == "tx")
{
LOGGER(trace) << "Peer read handler - TX" << std::endl;
Coin::Transaction* pTx = static_cast<Coin::Transaction*>(peerMessage.getPayload());
notifyTx(*this, *pTx);
}
else if (command == "block")
{
LOGGER(trace) << "Peer read handler - BLOCK" << std::endl;
Coin::CoinBlock* pBlock = static_cast<Coin::CoinBlock*>(peerMessage.getPayload());
notifyBlock(*this, *pBlock);
}
else if (command == "merkleblock")
{
LOGGER(trace) << "Peer read handler - MERKLEBLOCK" << std::endl;
Coin::MerkleBlock* pMerkleBlock = static_cast<Coin::MerkleBlock*>(peerMessage.getPayload());
notifyMerkleBlock(*this, *pMerkleBlock);
}
else if (command == "addr")
{
LOGGER(trace) << "Peer read handler - ADDR" << std::endl;
Coin::AddrMessage* pAddr = static_cast<Coin::AddrMessage*>(peerMessage.getPayload());
notifyAddr(*this, *pAddr);
}
else if (command == "headers")
{
LOGGER(trace) << "Peer read handler - HEADERS" << std::endl;
Coin::HeadersMessage* pHeaders = static_cast<Coin::HeadersMessage*>(peerMessage.getPayload());
notifyHeaders(*this, *pHeaders);
}
else
{
LOGGER(error) << "Peer read handler - command not implemented: " << command << std::endl;
std::stringstream err;
err << "Command type not implemented: " << command;
notifyProtocolError(*this, err.str(), -1);
}
notifyMessage(*this, peerMessage);
}
catch (const std::exception& e)
{
std::stringstream err;
err << "Message decode error: " << e.what();
notifyProtocolError(*this, err.str(), -1);
}
read_message.assign(read_message.begin() + MIN_MESSAGE_HEADER_SIZE + payloadSize, read_message.end());
}
do_read();
}));
}
void Peer::do_write(boost::shared_ptr<uchar_vector> data)
{
if (!bRunning) return;
boost::asio::async_write(socket_, boost::asio::buffer(*data), boost::asio::transfer_all(),
strand_.wrap([this](const boost::system::error_code& ec, std::size_t bytes_written) {
if (!bRunning) return;
LOGGER(trace) << "Peer write handler." << std::endl;
if (ec)
{
if (ec == boost::asio::error::operation_aborted) return;
stringstream err;
err << "Peer write error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
return;
}
boost::lock_guard<boost::mutex> sendLock(sendMutex);
sendQueue.pop();
if (!sendQueue.empty()) { do_write(sendQueue.front()); }
}));
}
void Peer::do_send(const Coin::CoinNodeMessage& message)
{
boost::shared_ptr<uchar_vector> data(new uchar_vector(message.getSerialized()));
boost::lock_guard<boost::mutex> sendLock(sendMutex);
sendQueue.push(data);
if (sendQueue.size() == 1) { strand_.post(boost::bind(&Peer::do_write, this, data)); }
}
void Peer::do_connect(tcp::resolver::iterator iter)
{
boost::asio::async_connect(socket_, iter, strand_.wrap([this](const boost::system::error_code& ec, tcp::resolver::iterator) {
if (!bRunning) return;
LOGGER(trace) << "Peer connect handler." << std::endl;
if (ec)
{
if (ec == boost::asio::error::operation_aborted) return;
do_stop();
stringstream err;
err << "Peer connect error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
return;
}
try
{
do_read();
do_handshake();
}
catch (const boost::system::error_code& ec)
{
do_stop();
notifyConnectionError(*this, ec.message(), ec.value());
}
catch (const std::exception& e)
{
do_stop();
notifyConnectionError(*this, e.what(), -1);
}
}));
}
void Peer::do_stop()
{
bRunning = false;
bHandshakeComplete = false;
bWriteReady = false;
notifyClose(*this);
notifyStop(*this);
}
void Peer::start()
{
if (bRunning) throw std::runtime_error("Peer already started.");
boost::unique_lock<boost::shared_mutex> lock(mutex);
if (bRunning) throw std::runtime_error("Peer already started.");
bRunning = true;
bHandshakeComplete = false;
bWriteReady = false;
tcp::resolver::query query(host_, port_);
resolver_.async_resolve(query, [this](const boost::system::error_code& ec, tcp::resolver::iterator iterator) {
if (!bRunning) return;
LOGGER(trace) << "Peer resolve handler." << std::endl;
if (ec)
{
if (ec == boost::asio::error::operation_aborted) return;
do_stop();
stringstream err;
err << "Peer resolve error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
return;
}
endpoint_ = *iterator;
strand_.post(boost::bind(&Peer::do_connect, this, iterator));
});
}
void Peer::stop()
{
{
if (!bRunning) return;
boost::unique_lock<boost::shared_mutex> lock(mutex);
if (!bRunning) return;
bRunning = false;
boost::system::error_code ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
if (ec)
{
stringstream err;
err << "Peer shutdown error: " << ec.message();
notifyConnectionError(*this, err.str(), ec.value());
}
socket_.close();
do_clearSendQueue();
bHandshakeComplete = false;
bWriteReady = false;
}
notifyClose(*this);
notifyStop(*this);
}
bool Peer::send(Coin::CoinNodeStructure& message)
{
boost::shared_lock<boost::shared_mutex> runLock(mutex);
if (!bRunning || !bWriteReady) return false;
Coin::CoinNodeMessage wrappedMessage(magic_bytes_, &message);
do_send(wrappedMessage);
return true;
}
void Peer::do_clearSendQueue()
{
boost::lock_guard<boost::mutex> sendLock(sendMutex);
while (!sendQueue.empty()) { sendQueue.pop(); }
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdio.h>
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
bool conntest(string x){
int i = x.size() - 1;
if(x == "&&" || x == ";" || x == "||"){
//cout << "a" << endl;
return true;
}
else if(x.at(i) == ';' || x.at(i) == '&'
|| x.at(i) == '|')
{
//cout << "b" << endl;
return true;
}
else{
return false;
}
}
bool endswith(string x){
int i = x.size() - 1;
if(x.at(i) == ';' || x.at(i) == '&'
|| x.at(i) == '|')
{
//cout << "b" << endl;
return true;
}
else{
return false;
}
}
int findend(string x){
for(int i = 0; i < x.size(); i++){
if(x.at(i) == '&' || x.at(i) == ';'
|| x.at(i) == '|')
{
return i;
}
}
return -1;
}
int main(){
string input;
cout << "$ ";
getline(cin, input);
char str[input.size()+1];
strcpy(str, input.c_str());
char* pch;
bool sucs;
char conn;
vector<string> cmd;
int cnt = 0;
pch = strtok(str, " ");
while(cnt < 100){
/*if(isexit(pch)){
return 0;
}*/
if(pch == NULL || conntest(pch)){
if(pch != NULL && endswith(pch)){
string tmp = pch;
int loc = findend(pch);
if(loc > 0){
tmp = tmp.substr(0, loc);
cmd.push_back(tmp);
}
}
int pid = fork();
if(pid == 0){
char* argc[cmd.size() + 1];
for(int i = 0 ; i < cmd.size(); i++ ){
argc[i] = new char[cmd.at(i).size()];
strcpy(argc[i], cmd.at(i).c_str());
}
argc[cmd.size()] = NULL;
if(-1 == execvp(argc[0], argc)){
perror("There was an error in execvp");
}
}
else{
wait(NULL);
return 0;
}
}
else{
cnt++;
if(pch != " ")
cmd.push_back(pch);
pch = strtok(NULL, " ");
}
}
return 0;
}
<commit_msg>updated hw0.cpp<commit_after>#include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
bool conntest(string x){
int i = x.size() - 1;
if(x == "&&" || x == ";" || x == "||"){
//cout << "a" << endl;
return true;
}
else if(x.at(i) == ';' || x.at(i) == '&'
|| x.at(i) == '|')
{
return true;
}
else{
return false;
}
}
bool endswith(string x){
int i = x.size() - 1;
if(x.at(i) == ';' || x.at(i) == '&'
|| x.at(i) == '|')
{
return true;
}
else{
return false;
}
}
int findend(string x){
for(int i = 0; i < x.size(); i++){
if(x.at(i) == '&' || x.at(i) == ';'
|| x.at(i) == '|')
{
return i;
}
}
return -1;
}
int main(){
string input;
cout << "$ ";
getline(cin, input);
char str[input.size()+1];
strcpy(str, input.c_str());
char* pch;
bool sucs;
char conn;
vector<string> cmd;
int cnt = 0;
pch = strtok(str, " ");
while(cnt < 100){
//add exit check here
if(pch == NULL || conntest(pch)){
if(pch != NULL && endswith(pch)){
string tmp = pch;
int loc = findend(pch);
if(loc > 0){
tmp = tmp.substr(0, loc);
cmd.push_back(tmp);
}
}
int pid = fork();
if(pid == 0){
char* argc[cmd.size() + 1];
for(int i = 0 ; i < cmd.size(); i++ ){
argc[i] = new char[cmd.at(i).size()];
strcpy(argc[i], cmd.at(i).c_str());
}
argc[cmd.size()] = NULL;
if(-1 == execvp(argc[0], argc)){
perror("There was an error in execvp");
}
}
else{
wait(NULL);
return 0;
}
}
else{
cnt++;
if(pch != " ")
cmd.push_back(pch);
pch = strtok(NULL, " ");
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "utils/PVLog.hpp"
//#include "utils/conversions.h"
#include <cmath>
#include <cstring>
namespace PV {
template <class T>
Buffer<T>::Buffer(int width, int height, int features) {
resize(width, height, features);
}
template <class T>
Buffer<T>::Buffer() {
resize(1, 1, 1);
}
template <class T>
Buffer<T>::Buffer(const std::vector<T> &data, int width, int height, int features) {
set(data, width, height, features);
}
// This constructor is for backwards compatibility with raw float buffers.
// It lacks bounds checking and should be removed when layers used Buffers
// instead of malloc'd floats.
template <class T>
Buffer<T>::Buffer(const T *data, int width, int height, int features) {
set(data, width, height, features);
}
template <class T>
T const Buffer<T>::at(int x, int y, int feature) const {
return at(index(x, y, feature));
}
template <class T>
T const Buffer<T>::at(int k) const {
return mData.at(k);
}
template <class T>
void Buffer<T>::set(int x, int y, int feature, T value) {
set(index(x, y, feature), value);
}
template <class T>
void Buffer<T>::set(int k, T value) {
mData.at(k) = value;
}
template <class T>
void Buffer<T>::set(const std::vector<T> &vector, int width, int height, int features) {
FatalIf(
vector.size() != width * height * features,
"Invalid vector size: Expected %d elements, vector contained %d elements.\n",
width * height * features,
vector.size());
mData = vector;
mWidth = width;
mHeight = height;
mFeatures = features;
}
template <class T>
void Buffer<T>::set(const T *data, int width, int height, int features) {
std::vector<T> tempVector(width * height * features);
for (size_t i = 0; i < tempVector.size(); ++i) {
tempVector.at(i) = data[i];
}
set(tempVector, width, height, features);
}
template <class T>
void Buffer<T>::set(Buffer<T> other) {
set(other.asVector(), other.getWidth(), other.getHeight(), other.getFeatures());
}
// Resizing a Buffer will clear its contents. Use rescale, crop, or grow to preserve values.
template <class T>
void Buffer<T>::resize(int width, int height, int features) {
mData.clear();
mData.resize(height * width * features);
mWidth = width;
mHeight = height;
mFeatures = features;
}
// Grows a buffer
template <class T>
void Buffer<T>::grow(int newWidth, int newHeight, enum Anchor anchor) {
if (newWidth < getWidth() && newHeight < getHeight()) {
return;
}
int offsetX = getAnchorX(anchor, getWidth(), newWidth);
int offsetY = getAnchorY(anchor, getHeight(), newHeight);
Buffer bigger(newWidth, newHeight, getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = x + offsetX;
int destY = y + offsetY;
if (destX < 0 || destX >= newWidth)
continue;
if (destY < 0 || destY >= newHeight)
continue;
bigger.set(destX, destY, f, at(x, y, f));
}
}
}
set(bigger.asVector(), newWidth, newHeight, getFeatures());
}
// Crops a buffer down to the specified size
template <class T>
void Buffer<T>::crop(int newWidth, int newHeight, enum Anchor anchor) {
if (newWidth >= getWidth() && newHeight >= getHeight()) {
return;
}
int offsetX = getAnchorX(anchor, newWidth, getWidth());
int offsetY = getAnchorY(anchor, newHeight, getHeight());
Buffer cropped(newWidth, newHeight, getFeatures());
for (int destY = 0; destY < newHeight; ++destY) {
for (int destX = 0; destX < newWidth; ++destX) {
for (int f = 0; f < getFeatures(); ++f) {
int sourceX = destX + offsetX;
int sourceY = destY + offsetY;
if (sourceX < 0 || sourceX >= getWidth())
continue;
if (sourceY < 0 || sourceY >= getHeight())
continue;
cropped.set(destX, destY, f, at(sourceX, sourceY, f));
}
}
}
set(cropped.asVector(), newWidth, newHeight, getFeatures());
}
// Shift a buffer, clipping any values that land out of bounds
template <class T>
void Buffer<T>::translate(int xShift, int yShift) {
if (xShift == 0 && yShift == 0) {
return;
}
Buffer result(getWidth(), getHeight(), getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = x + xShift;
int destY = y + yShift;
if (destX < 0 || destX >= getWidth())
continue;
if (destY < 0 || destY >= getHeight())
continue;
result.set(destX, destY, f, at(x, y, f));
}
}
}
set(result.asVector(), getWidth(), getHeight(), getFeatures());
}
template <class T>
int Buffer<T>::getAnchorX(enum Anchor anchor, int smallerWidth, int biggerWidth) {
switch (anchor) {
case NORTHWEST:
case WEST:
case SOUTHWEST: return 0;
case NORTH:
case CENTER:
case SOUTH: return biggerWidth / 2 - smallerWidth / 2;
case NORTHEAST:
case EAST:
case SOUTHEAST: return biggerWidth - smallerWidth;
default: return 0;
}
return 0; // Statement included to suppress warnings about missing return type.
}
template <class T>
int Buffer<T>::getAnchorY(enum Anchor anchor, int smallerHeight, int biggerHeight) {
switch (anchor) {
case NORTHWEST:
case NORTH:
case NORTHEAST: return 0;
case WEST:
case CENTER:
case EAST: return biggerHeight / 2 - smallerHeight / 2;
case SOUTHWEST:
case SOUTH:
case SOUTHEAST: return biggerHeight - smallerHeight;
default: return 0;
}
return 0; // Statement included to suppress warnings about missing return type.
}
} // end namespace PV
<commit_msg>Eliminates nvcc warnings from Buffer.tpp methods<commit_after>#include "utils/PVLog.hpp"
//#include "utils/conversions.h"
#include <cmath>
#include <cstring>
namespace PV {
template <class T>
Buffer<T>::Buffer(int width, int height, int features) {
resize(width, height, features);
}
template <class T>
Buffer<T>::Buffer() {
resize(1, 1, 1);
}
template <class T>
Buffer<T>::Buffer(const std::vector<T> &data, int width, int height, int features) {
set(data, width, height, features);
}
// This constructor is for backwards compatibility with raw float buffers.
// It lacks bounds checking and should be removed when layers used Buffers
// instead of malloc'd floats.
template <class T>
Buffer<T>::Buffer(const T *data, int width, int height, int features) {
set(data, width, height, features);
}
template <class T>
T const Buffer<T>::at(int x, int y, int feature) const {
return at(index(x, y, feature));
}
template <class T>
T const Buffer<T>::at(int k) const {
return mData.at(k);
}
template <class T>
void Buffer<T>::set(int x, int y, int feature, T value) {
set(index(x, y, feature), value);
}
template <class T>
void Buffer<T>::set(int k, T value) {
mData.at(k) = value;
}
template <class T>
void Buffer<T>::set(const std::vector<T> &vector, int width, int height, int features) {
FatalIf(
vector.size() != width * height * features,
"Invalid vector size: Expected %d elements, vector contained %d elements.\n",
width * height * features,
vector.size());
mData = vector;
mWidth = width;
mHeight = height;
mFeatures = features;
}
template <class T>
void Buffer<T>::set(const T *data, int width, int height, int features) {
std::vector<T> tempVector(width * height * features);
for (size_t i = 0; i < tempVector.size(); ++i) {
tempVector.at(i) = data[i];
}
set(tempVector, width, height, features);
}
template <class T>
void Buffer<T>::set(Buffer<T> other) {
set(other.asVector(), other.getWidth(), other.getHeight(), other.getFeatures());
}
// Resizing a Buffer will clear its contents. Use rescale, crop, or grow to preserve values.
template <class T>
void Buffer<T>::resize(int width, int height, int features) {
mData.clear();
mData.resize(height * width * features);
mWidth = width;
mHeight = height;
mFeatures = features;
}
// Grows a buffer
template <class T>
void Buffer<T>::grow(int newWidth, int newHeight, enum Anchor anchor) {
if (newWidth < getWidth() && newHeight < getHeight()) {
return;
}
int offsetX = getAnchorX(anchor, getWidth(), newWidth);
int offsetY = getAnchorY(anchor, getHeight(), newHeight);
Buffer bigger(newWidth, newHeight, getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = x + offsetX;
int destY = y + offsetY;
if (destX < 0 || destX >= newWidth)
continue;
if (destY < 0 || destY >= newHeight)
continue;
bigger.set(destX, destY, f, at(x, y, f));
}
}
}
set(bigger.asVector(), newWidth, newHeight, getFeatures());
}
// Crops a buffer down to the specified size
template <class T>
void Buffer<T>::crop(int newWidth, int newHeight, enum Anchor anchor) {
if (newWidth >= getWidth() && newHeight >= getHeight()) {
return;
}
int offsetX = getAnchorX(anchor, newWidth, getWidth());
int offsetY = getAnchorY(anchor, newHeight, getHeight());
Buffer cropped(newWidth, newHeight, getFeatures());
for (int destY = 0; destY < newHeight; ++destY) {
for (int destX = 0; destX < newWidth; ++destX) {
for (int f = 0; f < getFeatures(); ++f) {
int sourceX = destX + offsetX;
int sourceY = destY + offsetY;
if (sourceX < 0 || sourceX >= getWidth())
continue;
if (sourceY < 0 || sourceY >= getHeight())
continue;
cropped.set(destX, destY, f, at(sourceX, sourceY, f));
}
}
}
set(cropped.asVector(), newWidth, newHeight, getFeatures());
}
// Shift a buffer, clipping any values that land out of bounds
template <class T>
void Buffer<T>::translate(int xShift, int yShift) {
if (xShift == 0 && yShift == 0) {
return;
}
Buffer result(getWidth(), getHeight(), getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = x + xShift;
int destY = y + yShift;
if (destX < 0 || destX >= getWidth())
continue;
if (destY < 0 || destY >= getHeight())
continue;
result.set(destX, destY, f, at(x, y, f));
}
}
}
set(result.asVector(), getWidth(), getHeight(), getFeatures());
}
template <class T>
int Buffer<T>::getAnchorX(enum Anchor anchor, int smallerWidth, int biggerWidth) {
int resultX;
switch (anchor) {
case NORTHWEST:
case WEST:
case SOUTHWEST: resultX = 0; break;
case NORTH:
case CENTER:
case SOUTH: resultX = biggerWidth / 2 - smallerWidth / 2; break;
case NORTHEAST:
case EAST:
case SOUTHEAST: resultX = biggerWidth - smallerWidth; break;
default: resultX = 0; break;
}
return resultX;
}
template <class T>
int Buffer<T>::getAnchorY(enum Anchor anchor, int smallerHeight, int biggerHeight) {
int resultY;
switch (anchor) {
case NORTHWEST:
case NORTH:
case NORTHEAST: resultY = 0; break;
case WEST:
case CENTER:
case EAST: resultY = biggerHeight / 2 - smallerHeight / 2; break;
case SOUTHWEST:
case SOUTH:
case SOUTHEAST: resultY = biggerHeight - smallerHeight; break;
default: resultY = 0; break;
}
return resultY;
}
} // end namespace PV
<|endoftext|>
|
<commit_before>/*
* Copyright 2015-2018 Kacper Kasper <kacperkasper@gmail.com>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "Languages.h"
#include <algorithm>
#include <functional>
#include <map>
#include <string>
#include <Catalog.h>
#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
#include <String.h>
#include <SciLexer.h>
#include <yaml-cpp/yaml.h>
#include "Editor.h"
#include "EditorWindow.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Languages"
std::vector<std::string> Languages::sLanguages;
std::map<std::string, std::string> Languages::sMenuItems;
std::map<std::string, std::string> Languages::sExtensions;
namespace {
/**
* Executes a specified function for each data directory, going from system to
* user, packaged to non-packaged. The path is available as a parameter to the
* user supplied function.
*/
void
DoInAllDataDirectories(std::function<void(const BPath&)> func) {
BPath dataPath;
find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
func(dataPath);
find_directory(B_USER_DATA_DIRECTORY, &dataPath);
func(dataPath);
find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
func(dataPath);
find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
func(dataPath);
}
}
/* static */ bool
Languages::GetLanguageForExtension(const std::string ext, std::string& lang)
{
lang = "text";
if(sExtensions.count(ext) > 0) {
lang = sExtensions[ext];
return true;
}
return false;
}
/* static */ void
Languages::SortAlphabetically()
{
std::sort(sLanguages.begin(), sLanguages.end());
}
/**
* Reads YAML files from all data directories and creates a single style map,
* where repeated keys are overridden (user non-packaged being final).
*/
/* static */ std::map<int, int>
Languages::ApplyLanguage(Editor* editor, const char* lang)
{
editor->SendMessage(SCI_FREESUBSTYLES);
std::map<int, int> styleMapping;
DoInAllDataDirectories([&](const BPath& path) {
try {
auto m = _ApplyLanguage(editor, lang, path);
m.merge(styleMapping);
std::swap(styleMapping, m);
} catch (YAML::BadFile &) {}
});
return styleMapping;
}
/**
* Loads YAML file with language specification:
* lexer: int if supplied with Scintilla, string if external (required)
* properties: (string|string) map -> SCI_SETPROPERTY
* keywords: (index(int)|string) map -> SCI_SETKEYWORDS
* identifiers: (lexem class id(int)|(string array)) map -> SCI_SETIDENTIFIERS
* comments:
* line: string
* block: pair of strings
* styles: (lexem class id(int)|Koder style id(int)) map
* substyles: (lexem class id(int)|(Koder style id(int)) array) map
*
* For substyles, strings in identifiers array are matched with styles in
* substyles array. Array instead of map is used because substyles are allocated
* contiguously. Theoretically there is no limit on how many substyles there
* can be. Substyling of lexem class id must be supported by the lexer.
*
* Substyle ids are created using starting id returned by SCI_ALLOCATESUBSTYLE.
* For example if it returns 128, then 1st id = 128, 2nd = 129, 3rd = 130.
* These are then passed to SCI_SETIDENTIFIERS and merged into regular styles
* map to be handled by the Styler class.
*/
/* static */ std::map<int, int>
Languages::_ApplyLanguage(Editor* editor, const char* lang, const BPath &path)
{
BPath p(path);
p.Append(gAppName);
p.Append("languages");
p.Append(lang);
const YAML::Node language = YAML::LoadFile(std::string(p.Path()) + ".yaml");
try {
int lexerID = language["lexer"].as<int>();
editor->SendMessage(SCI_SETLEXER, static_cast<uptr_t>(lexerID), 0);
} catch(YAML::TypedBadConversion<int>&) {
std::string lexerName = language["lexer"].as<std::string>();
editor->SendMessage(SCI_SETLEXERLANGUAGE, 0,
reinterpret_cast<const sptr_t>(lexerName.c_str()));
}
for(const auto& property : language["properties"]) {
auto name = property.first.as<std::string>();
auto value = property.second.as<std::string>();
editor->SendMessage(SCI_SETPROPERTY, (uptr_t) name.c_str(), (sptr_t) value.c_str());
}
for(const auto& keyword : language["keywords"]) {
auto num = keyword.first.as<int>();
auto words = keyword.second.as<std::string>();
editor->SendMessage(SCI_SETKEYWORDS, num, (sptr_t) words.c_str());
}
std::unordered_map<int, int> substyleStartMap;
const auto& identifiers = language["identifiers"];
if(identifiers && identifiers.IsMap()) {
for(const auto& id : identifiers) {
if(!id.second.IsSequence())
continue;
const int substyleId = id.first.as<int>();
// TODO: allocate only once
const int start = editor->SendMessage(SCI_ALLOCATESUBSTYLES,
substyleId, id.second.size());
substyleStartMap.emplace(substyleId, start);
int i = 0;
for(const auto& idents : id.second) {
editor->SendMessage(SCI_SETIDENTIFIERS, start + i++,
reinterpret_cast<sptr_t>(idents.as<std::string>().c_str()));
}
}
}
const YAML::Node comments = language["comment"];
if(comments) {
const YAML::Node line = comments["line"];
if(line)
editor->SetCommentLineToken(line.as<std::string>());
const YAML::Node block = comments["block"];
if(block && block.IsSequence())
editor->SetCommentBlockTokens(block[0].as<std::string>(),
block[1].as<std::string>());
}
std::map<int, int> styleMap;
const YAML::Node styles = language["styles"];
if(styles) {
styleMap = styles.as<std::map<int, int>>();
}
const YAML::Node substyles = language["substyles"];
if(substyles && substyles.IsMap()) {
for(const auto& id : substyles) {
if(!id.second.IsSequence())
continue;
int i = 0;
for(const auto& styleId : id.second) {
const int substyleStart = substyleStartMap[id.first.as<int>()];
styleMap.emplace(substyleStart + i++, styleId.as<int>());
}
}
}
return styleMap;
}
/* static */ void
Languages::LoadLanguages()
{
DoInAllDataDirectories([](const BPath& path) {
try {
_LoadLanguages(path);
} catch (YAML::BadFile &) {}
});
}
/* static */ void
Languages::_LoadLanguages(const BPath& path)
{
BPath p(path);
p.Append(gAppName);
p.Append("languages");
const YAML::Node languages = YAML::LoadFile(std::string(p.Path()) + ".yaml");
for(const auto& language : languages) {
auto name = language.first.as<std::string>();
auto menuitem = language.second["name"].as<std::string>();
auto extensions = language.second["extensions"].as<std::vector<std::string>>();
for(auto extension : extensions) {
sExtensions[extension] = name;
}
if(std::find(sLanguages.begin(), sLanguages.end(), name) == sLanguages.end())
sLanguages.push_back(name);
sMenuItems[name] = menuitem;
}
}
/* static */ void
Languages::LoadExternalLexers(Editor* editor)
{
DoInAllDataDirectories([&](const BPath& path) {
_LoadExternalLexers(path, editor);
});
}
/**
* Iterates through all files in path/scintilla/lexers and loads them as lexers
* into editor.
*/
/* static */ void
Languages::_LoadExternalLexers(const BPath& path, Editor* editor)
{
BPath p(path);
p.Append("scintilla");
p.Append("lexers");
BDirectory lexersDir(p.Path());
if (lexersDir.InitCheck() != B_OK)
return;
BEntry lexerEntry;
while(lexersDir.GetNextEntry(&lexerEntry, true) == B_OK) {
if(lexerEntry.IsDirectory())
continue;
BPath lexerPath;
lexerEntry.GetPath(&lexerPath);
editor->SendMessage(SCI_LOADLEXERLIBRARY, 0,
reinterpret_cast<const sptr_t>(lexerPath.Path()));
}
}
<commit_msg>Fix comment line/block feature<commit_after>/*
* Copyright 2015-2018 Kacper Kasper <kacperkasper@gmail.com>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "Languages.h"
#include <algorithm>
#include <functional>
#include <map>
#include <string>
#include <Catalog.h>
#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
#include <String.h>
#include <SciLexer.h>
#include <yaml-cpp/yaml.h>
#include "Editor.h"
#include "EditorWindow.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Languages"
std::vector<std::string> Languages::sLanguages;
std::map<std::string, std::string> Languages::sMenuItems;
std::map<std::string, std::string> Languages::sExtensions;
namespace {
/**
* Executes a specified function for each data directory, going from system to
* user, packaged to non-packaged. The path is available as a parameter to the
* user supplied function.
*/
void
DoInAllDataDirectories(std::function<void(const BPath&)> func) {
BPath dataPath;
find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
func(dataPath);
find_directory(B_USER_DATA_DIRECTORY, &dataPath);
func(dataPath);
find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
func(dataPath);
find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
func(dataPath);
}
}
/* static */ bool
Languages::GetLanguageForExtension(const std::string ext, std::string& lang)
{
lang = "text";
if(sExtensions.count(ext) > 0) {
lang = sExtensions[ext];
return true;
}
return false;
}
/* static */ void
Languages::SortAlphabetically()
{
std::sort(sLanguages.begin(), sLanguages.end());
}
/**
* Reads YAML files from all data directories and creates a single style map,
* where repeated keys are overridden (user non-packaged being final).
*/
/* static */ std::map<int, int>
Languages::ApplyLanguage(Editor* editor, const char* lang)
{
editor->SendMessage(SCI_FREESUBSTYLES);
std::map<int, int> styleMapping;
DoInAllDataDirectories([&](const BPath& path) {
try {
auto m = _ApplyLanguage(editor, lang, path);
m.merge(styleMapping);
std::swap(styleMapping, m);
} catch (YAML::BadFile &) {}
});
return styleMapping;
}
/**
* Loads YAML file with language specification:
* lexer: int if supplied with Scintilla, string if external (required)
* properties: (string|string) map -> SCI_SETPROPERTY
* keywords: (index(int)|string) map -> SCI_SETKEYWORDS
* identifiers: (lexem class id(int)|(string array)) map -> SCI_SETIDENTIFIERS
* comments:
* line: string
* block: pair of strings
* styles: (lexem class id(int)|Koder style id(int)) map
* substyles: (lexem class id(int)|(Koder style id(int)) array) map
*
* For substyles, strings in identifiers array are matched with styles in
* substyles array. Array instead of map is used because substyles are allocated
* contiguously. Theoretically there is no limit on how many substyles there
* can be. Substyling of lexem class id must be supported by the lexer.
*
* Substyle ids are created using starting id returned by SCI_ALLOCATESUBSTYLE.
* For example if it returns 128, then 1st id = 128, 2nd = 129, 3rd = 130.
* These are then passed to SCI_SETIDENTIFIERS and merged into regular styles
* map to be handled by the Styler class.
*/
/* static */ std::map<int, int>
Languages::_ApplyLanguage(Editor* editor, const char* lang, const BPath &path)
{
BPath p(path);
p.Append(gAppName);
p.Append("languages");
p.Append(lang);
const YAML::Node language = YAML::LoadFile(std::string(p.Path()) + ".yaml");
try {
int lexerID = language["lexer"].as<int>();
editor->SendMessage(SCI_SETLEXER, static_cast<uptr_t>(lexerID), 0);
} catch(YAML::TypedBadConversion<int>&) {
std::string lexerName = language["lexer"].as<std::string>();
editor->SendMessage(SCI_SETLEXERLANGUAGE, 0,
reinterpret_cast<const sptr_t>(lexerName.c_str()));
}
for(const auto& property : language["properties"]) {
auto name = property.first.as<std::string>();
auto value = property.second.as<std::string>();
editor->SendMessage(SCI_SETPROPERTY, (uptr_t) name.c_str(), (sptr_t) value.c_str());
}
for(const auto& keyword : language["keywords"]) {
auto num = keyword.first.as<int>();
auto words = keyword.second.as<std::string>();
editor->SendMessage(SCI_SETKEYWORDS, num, (sptr_t) words.c_str());
}
std::unordered_map<int, int> substyleStartMap;
const auto& identifiers = language["identifiers"];
if(identifiers && identifiers.IsMap()) {
for(const auto& id : identifiers) {
if(!id.second.IsSequence())
continue;
const int substyleId = id.first.as<int>();
// TODO: allocate only once
const int start = editor->SendMessage(SCI_ALLOCATESUBSTYLES,
substyleId, id.second.size());
substyleStartMap.emplace(substyleId, start);
int i = 0;
for(const auto& idents : id.second) {
editor->SendMessage(SCI_SETIDENTIFIERS, start + i++,
reinterpret_cast<sptr_t>(idents.as<std::string>().c_str()));
}
}
}
const YAML::Node comments = language["comments"];
if(comments) {
const YAML::Node line = comments["line"];
if(line)
editor->SetCommentLineToken(line.as<std::string>());
const YAML::Node block = comments["block"];
if(block && block.IsSequence())
editor->SetCommentBlockTokens(block[0].as<std::string>(),
block[1].as<std::string>());
}
std::map<int, int> styleMap;
const YAML::Node styles = language["styles"];
if(styles) {
styleMap = styles.as<std::map<int, int>>();
}
const YAML::Node substyles = language["substyles"];
if(substyles && substyles.IsMap()) {
for(const auto& id : substyles) {
if(!id.second.IsSequence())
continue;
int i = 0;
for(const auto& styleId : id.second) {
const int substyleStart = substyleStartMap[id.first.as<int>()];
styleMap.emplace(substyleStart + i++, styleId.as<int>());
}
}
}
return styleMap;
}
/* static */ void
Languages::LoadLanguages()
{
DoInAllDataDirectories([](const BPath& path) {
try {
_LoadLanguages(path);
} catch (YAML::BadFile &) {}
});
}
/* static */ void
Languages::_LoadLanguages(const BPath& path)
{
BPath p(path);
p.Append(gAppName);
p.Append("languages");
const YAML::Node languages = YAML::LoadFile(std::string(p.Path()) + ".yaml");
for(const auto& language : languages) {
auto name = language.first.as<std::string>();
auto menuitem = language.second["name"].as<std::string>();
auto extensions = language.second["extensions"].as<std::vector<std::string>>();
for(auto extension : extensions) {
sExtensions[extension] = name;
}
if(std::find(sLanguages.begin(), sLanguages.end(), name) == sLanguages.end())
sLanguages.push_back(name);
sMenuItems[name] = menuitem;
}
}
/* static */ void
Languages::LoadExternalLexers(Editor* editor)
{
DoInAllDataDirectories([&](const BPath& path) {
_LoadExternalLexers(path, editor);
});
}
/**
* Iterates through all files in path/scintilla/lexers and loads them as lexers
* into editor.
*/
/* static */ void
Languages::_LoadExternalLexers(const BPath& path, Editor* editor)
{
BPath p(path);
p.Append("scintilla");
p.Append("lexers");
BDirectory lexersDir(p.Path());
if (lexersDir.InitCheck() != B_OK)
return;
BEntry lexerEntry;
while(lexersDir.GetNextEntry(&lexerEntry, true) == B_OK) {
if(lexerEntry.IsDirectory())
continue;
BPath lexerPath;
lexerEntry.GetPath(&lexerPath);
editor->SendMessage(SCI_LOADLEXERLIBRARY, 0,
reinterpret_cast<const sptr_t>(lexerPath.Path()));
}
}
<|endoftext|>
|
<commit_before>#include <ctrcommon/app.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <sys/dirent.h>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "FBI v1.3.2" << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
if(ninjhax) {
stream << "START - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](u64 pos, u64 totalSize) {
std::stringstream details;
details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
details << "Press B to cancel.";
u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
inputPoll();
return !inputIsPressed(BUTTON_B);
};
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
if(netInstall && !exit) {
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
if(file.fd == NULL) {
netInstall = false;
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string fileName = (*it).name;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
}
} else {
if(!fsDelete(path)) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << platformGetErrorString(platformGetError()) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
} else {
updateList = true;
}
}
}
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
std::stringstream resultMsg;
if(mode == INSTALL_CIA) {
resultMsg << "Install ";
} else {
resultMsg << "Delete ";
}
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
} else {
if(fsDelete(path)) {
updateList = true;
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError()) << "\n";
}
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
} else {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<commit_msg>Display current item during batch processes.<commit_after>#include <ctrcommon/app.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <sys/dirent.h>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "FBI v1.3.3" << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
if(ninjhax) {
stream << "START - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
std::string batchInfo = "";
auto onProgress = [&](u64 pos, u64 totalSize) {
std::stringstream details;
details << batchInfo;
details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
details << "Press B to cancel.";
u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
inputPoll();
return !inputIsPressed(BUTTON_B);
};
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
if(netInstall && !exit) {
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
if(file.fd == NULL) {
netInstall = false;
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
u32 currItem = 0;
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string fileName = (*it).name;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
if(mode == INSTALL_CIA) {
std::stringstream batchInstallStream;
batchInstallStream << fileName << " (" << currItem << ")" << "\n";
batchInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, onProgress);
batchInfo = "";
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
}
} else {
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << fileName << " (" << currItem << ")" << "\n";
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(!fsDelete(path)) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << platformGetErrorString(platformGetError()) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
} else {
updateList = true;
}
}
}
currItem++;
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
std::stringstream resultMsg;
if(mode == INSTALL_CIA) {
resultMsg << "Install ";
} else {
resultMsg << "Delete ";
}
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
} else {
uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
if(fsDelete(path)) {
updateList = true;
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError()) << "\n";
}
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
} else {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<|endoftext|>
|
<commit_before>/* Nom: main.cpp
* Description: module sous-système de contrôle: gestion du dialogue avec l'utilisateur et interface graphique
* Date: 08.02.2014
* version : 1.0
* responsable du module : Pauline Maury Laribière
* groupe : Alexandre Devienne, Pauline Maury Laribière
*/
extern "C"
{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "error.h"
#include "sim.h"
#include "main.h"
}
int main (int argc, char *argv[])
{
enum Mode mode;
mode = read_mode(argv[1]);
if(argc!=3)
{
printf("syntaxe attendue : sim.x [Error|Force|Integration|Graphic|Simulation,nom_fichier]\n");
}
else
{
switch(mode)
{
case ERROR: sim_error(argv[2]);
break;
case FORCE: sim_force(argv[2]);
break;
case INTEGRATION: //sim_integration(argv[2]);
break;
case GRAPHIC: //sim_graphic(argv[2]);
break;
case SIMULATION: //sim_simulation(argv[2]);
break;
case MODE_UNSET: printf("syntaxe attendue : sim.x [Error|Force|Integration|Graphic|Simulation,nom_fichier]\n");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
MODE read_mode(char string[])
{
MODE mode;
if(strcmp(string, "Error" ) == 0)
{
mode = ERROR;
}
else if (strcmp(string, "Force" ) == 0)
{
mode = FORCE;
}
else if (strcmp(string, "Integration" ) == 0)
{
mode = INTEGRATION;
}
else if (strcmp(string, "Graphic" ) == 0)
{
mode = GRAPHIC;
}
else if (strcmp(string, "Simulation" ) == 0)
{
mode = SIMULATION;
}
else
{
mode = MODE_UNSET;
}
return mode;
}
<commit_msg>Clean main<commit_after>/* Nom: main.cpp
* Description: module sous-système de contrôle: gestion du dialogue avec l'utilisateur et interface graphique
* Date: 08.02.2014
* version : 1.0
* responsable du module : Pauline Maury Laribière
* groupe : Alexandre Devienne, Pauline Maury Laribière
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern "C"
{
#include "sim.h"
}
enum Mode {ERROR, FORCE, INTEGRATION, GRAPHIC, SIMULATION, MODE_UNSET};
typedef enum Mode MODE;
MODE read_mode(char string[]);
int main (int argc, char *argv[])
{
enum Mode mode;
mode = read_mode(argv[1]);
if(argc!=3)
{
printf("syntaxe attendue : sim.x [Error|Force|Integration|Graphic|Simulation,nom_fichier]\n");
}
else
{
switch(mode)
{
case ERROR: sim_error(argv[2]);
break;
case FORCE: sim_force(argv[2]);
break;
case INTEGRATION: //sim_integration(argv[2]);
break;
case GRAPHIC: //sim_graphic(argv[2]);
break;
case SIMULATION: //sim_simulation(argv[2]);
break;
case MODE_UNSET: printf("syntaxe attendue : sim.x [Error|Force|Integration|Graphic|Simulation,nom_fichier]\n");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
MODE read_mode(char string[])
{
MODE mode;
if(strcmp(string, "Error" ) == 0)
{
mode = ERROR;
}
else if (strcmp(string, "Force" ) == 0)
{
mode = FORCE;
}
else if (strcmp(string, "Integration" ) == 0)
{
mode = INTEGRATION;
}
else if (strcmp(string, "Graphic" ) == 0)
{
mode = GRAPHIC;
}
else if (strcmp(string, "Simulation" ) == 0)
{
mode = SIMULATION;
}
else
{
mode = MODE_UNSET;
}
return mode;
}
<|endoftext|>
|
<commit_before>#include <ctrcommon/app.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <sys/dirent.h>
#include <sys/errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "FBI v1.3.8" << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
if(ninjhax) {
stream << "START - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
std::string batchInfo = "";
int prevProgress = -1;
auto onProgress = [&](u64 pos, u64 totalSize) {
u32 progress = (u32) ((pos * 100) / totalSize);
if(prevProgress != (int) progress) {
prevProgress = (int) progress;
std::stringstream details;
details << batchInfo;
details << "Press B to cancel.";
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
}
inputPoll();
return !inputIsPressed(BUTTON_B);
};
bool showNetworkPrompts = true;
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
if(netInstall && !exit) {
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
if(inputIsPressed(BUTTON_A)) {
showNetworkPrompts = !showNetworkPrompts;
}
infoStream << "\n";
infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
infoStream << "Press A to toggle prompts." << "\n";
});
if(file.fd == NULL) {
netInstall = false;
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
prevProgress = -1;
if(showNetworkPrompts || ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
}
fclose(file.fd);
continue;
}
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
u32 currItem = 0;
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
std::string displayFileName = (*it).name;
if(displayFileName.length() > 40) {
displayFileName.resize(40);
displayFileName += "...";
}
if(mode == INSTALL_CIA) {
std::stringstream batchInstallStream;
batchInstallStream << displayFileName << " (" << currItem << ")" << "\n";
batchInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, onProgress);
prevProgress = -1;
batchInfo = "";
if(ret != APP_SUCCESS) {
Error error = platformGetError();
platformSetError(error);
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << displayFileName << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) {
failed = true;
break;
}
}
} else {
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << displayFileName << " (" << currItem << ")" << "\n";
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(remove(path.c_str()) != 0) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << displayFileName << "\n";
resultMsg << strerror(errno) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
} else {
updateList = true;
}
}
}
currItem++;
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
std::stringstream resultMsg;
if(mode == INSTALL_CIA) {
resultMsg << "Install ";
} else {
resultMsg << "Delete ";
}
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
prevProgress = -1;
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
} else {
uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
if(remove(path.c_str()) != 0) {
updateList = true;
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << strerror(errno) << "\n";
}
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
} else {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<commit_msg>Update for ctrcommon changes.<commit_after>#include <ctrcommon/app.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <sys/dirent.h>
#include <sys/errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
if(ninjhax) {
stream << "START - Exit to launcher" << "\n";
}
std::string str = stream.str();
const std::string title = "FBI v1.3.8";
gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 2)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 2) + gputGetStringHeight(str)) / 2, 2);
gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str)) / 2, 4);
return breakLoop;
};
std::string batchInfo = "";
int prevProgress = -1;
auto onProgress = [&](u64 pos, u64 totalSize) {
u32 progress = (u32) ((pos * 100) / totalSize);
if(prevProgress != (int) progress) {
prevProgress = (int) progress;
std::stringstream details;
details << batchInfo;
details << "Press B to cancel.";
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
}
inputPoll();
return !inputIsPressed(BUTTON_B);
};
bool showNetworkPrompts = true;
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
if(netInstall && !exit) {
gpuClearScreens();
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
if(inputIsPressed(BUTTON_A)) {
showNetworkPrompts = !showNetworkPrompts;
}
infoStream << "\n";
infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
infoStream << "Press A to toggle prompts." << "\n";
});
if(file.fd == NULL) {
netInstall = false;
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
prevProgress = -1;
if(showNetworkPrompts || ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
}
fclose(file.fd);
continue;
}
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
u32 currItem = 0;
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
std::string displayFileName = (*it).name;
if(displayFileName.length() > 40) {
displayFileName.resize(40);
displayFileName += "...";
}
if(mode == INSTALL_CIA) {
std::stringstream batchInstallStream;
batchInstallStream << displayFileName << " (" << currItem << ")" << "\n";
batchInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, onProgress);
prevProgress = -1;
batchInfo = "";
if(ret != APP_SUCCESS) {
Error error = platformGetError();
platformSetError(error);
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << displayFileName << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) {
failed = true;
break;
}
}
} else {
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << displayFileName << " (" << currItem << ")" << "\n";
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(remove(path.c_str()) != 0) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << displayFileName << "\n";
resultMsg << strerror(errno) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
} else {
updateList = true;
}
}
}
currItem++;
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
std::stringstream resultMsg;
if(mode == INSTALL_CIA) {
resultMsg << "Install ";
} else {
resultMsg << "Delete ";
}
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
prevProgress = -1;
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
} else {
uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
if(remove(path.c_str()) != 0) {
updateList = true;
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << strerror(errno) << "\n";
}
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
} else {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<|endoftext|>
|
<commit_before>#include <math.h>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>
#include "Game.h"
#include "SpotLight.h"
#include "Light/LightPost.h"
#include "Model/Texture/TextureManager.h"
#include "AntTweakHelper.h"
#ifdef __APPLE__
#include <Glut/glut.h>
#else
#define FREEGLUT_STATIC
#include <GL/glut.h>
#endif
// PI
#define GL_PI 3.14159f
// Current size of window.
GLint width = 700;
GLint height = 500;
// old values for the window (used to come back from fullscreen)
GLint oldWidth = width;
GLint oldHeight = height;
// Current position of the window (used to come back from fullscreen)
int winPosX = 0;
int winPosY = 0;
bool isInFullScreenMode;
bool showHelpWindow = false;
// Bounds of viewing frustum.
GLfloat nearPlane = 1.0f;
GLfloat farPlane = 100.0f;
bool keyStates[256];
bool funcKeyStates[256];
int keyModifier = 0;
TextureManager *te;
static bool isDebugMode = false;
bool isTwoPlayerGame = false;
int viewStates = 0; //states of the camera views
Game* game;
AntTweakHelper antTweakHelper;
//second window for help menu
int mainWindow = 0;
void reshapeMainWindow (int newWidth, int newHeight)
{
width = newWidth;
height = newHeight;
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
TwWindowSize(width, height);
}
void toggleTwoPlayerSplitscreen()
{
isTwoPlayerGame = !isTwoPlayerGame;
if (isTwoPlayerGame)
{
game->p1->selectRobotView(game->p1->robots.at(0));
game->p1->changeCamera(CAMERA_ROBOT);
game->p2->selectRobotView(game->p2->robots.at(0));
game->p2->changeCamera(CAMERA_ROBOT);
}
else
{
game->p1->changeCamera(CAMERA_COMMANDER);
game->p2->changeCamera(CAMERA_COMMANDER);
}
}
void toggleFullScreen()
{
isInFullScreenMode = !isInFullScreenMode;
if (isInFullScreenMode)
{
oldWidth = width;
oldHeight = height;
winPosX = glutGet(GLUT_WINDOW_X);
winPosY = glutGet(GLUT_WINDOW_Y);
glutFullScreen();
}
else
{
glutPositionWindow(winPosX, winPosY);
glutReshapeWindow(oldWidth, oldHeight);
}
}
void rasterText(GLfloat x, GLfloat y, void *font, char *c, int cWidth){
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glLoadIdentity();
glRasterPos2f(x, y);
for (int i = 0; i < cWidth; i++)
{
glutBitmapCharacter(font, c[i]);
}
glPopMatrix();
}
void help_display(){
glPushMatrix();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//creating ortho view since text is only 2D
glOrtho(0, width-5, 0, height-5, 0.0, 0.1);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_LIGHTING);
int lineSpace = 15;
int lineHeight = height-20;
ifstream openfile;
string fileLoad = "keyInput.txt";
openfile.open((TextureManager::getResourcePath() + fileLoad).c_str(), ios::in);
glColor3f(1.0f, 1.0f, 1.0f);
if (openfile.is_open()) {
string s;
getline(openfile, s);
char *title = (char*)s.c_str();
rasterText((GLfloat)width/2-35,(GLfloat)lineHeight,GLUT_BITMAP_HELVETICA_12, title,s.size());
lineHeight -= 5;
while(!openfile.eof())
{
getline(openfile, s);
char *readLine = (char*)s.c_str();
lineHeight -= lineSpace;
rasterText(15.0f,(GLfloat)lineHeight,GLUT_BITMAP_HELVETICA_10, readLine,s.size());
}
openfile.close();
}
glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
glBegin(GL_QUADS);
glVertex2f(0.0f, 0.0f);
glVertex2f((GLfloat)width, 0.0f);
glVertex2f((GLfloat)width, (GLfloat)height);
glVertex2f(0.0f, (GLfloat)height);
glEnd();
glEnable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
void render()
{
static time_t lastUpdate = time(NULL);
static time_t currentTime = time(NULL);
static GLuint fps = 0;
static GLuint prevFps = 0;
//clears the buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if(showHelpWindow){
help_display();
}
if (isTwoPlayerGame)
{
game->p1->view();
game->render();
glViewport(0, 0, (GLsizei)width, (GLsizei)height / 2);
game->p2->view();
game->render();
glViewport(0, (GLint)height / 2, (GLsizei)width, (GLsizei)height / 2);
}
else
{
game->render();
game->p1->view();
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
}
game->getInput(keyModifier); // Gets user input
//((HumanPlayer*)(game->p1))->view(); // Camera update (leave as it is for now)
if (isDebugMode) {
antTweakHelper.draw();
}
fps++;
currentTime = time(NULL);
if ((currentTime - lastUpdate) >= 1.0f)
{
lastUpdate = currentTime;
prevFps = fps;
fps = 0;
}
stringstream sFps;
sFps << prevFps;
string prefixAndFps = "FPS: " + sFps.str();
glPushMatrix();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, 0.0f, 0.1f);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_LIGHTING);
glColor3f(1.0f, 1.0f, 1.0f);
rasterText(20.0f, 20.0f, GLUT_BITMAP_HELVETICA_18, (char *)prefixAndFps.c_str(), prefixAndFps.size());
glEnable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
void functionKeyUp(int key, int x, int y)
{
funcKeyStates[key] = false;
glutPostRedisplay();
}
void toggleDifferentView(){
++viewStates;
//normal settings
glShadeModel(GL_FLAT);
glEnable(GL_DEPTH_TEST);
glPolygonMode(GL_FRONT, GL_FILL);
if (game->lr->getIsSkySphere())
glPolygonMode(GL_BACK, GL_FILL);
if(viewStates==1){ //wireFrame
glDisable(GL_DEPTH_TEST);
glPolygonMode(GL_FRONT, GL_LINE);
if (game->lr->getIsSkySphere())
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else if(viewStates==2){ //smoothShading
glShadeModel(GL_SMOOTH);
glPolygonMode(GL_FRONT, GL_FILL);
if (game->lr->getIsSkySphere())
glPolygonMode(GL_BACK, GL_FILL);
}
else{//back to normal
viewStates=0;
}
}
void windowFuncKeyOps(){
if (funcKeyStates[GLUT_KEY_F1]) {
toggleDifferentView();
}
else if (funcKeyStates[GLUT_KEY_F6]) {
TextureManager::getInstance()->toggleSkins();
}
if (funcKeyStates[GLUT_KEY_F8])
toggleTwoPlayerSplitscreen();
}
void functionKeysPressed(int key, int x, int y)
{
funcKeyStates[key] = true;
windowFuncKeyOps();
}
void windowKeyOps()
{
if (keyModifier == GLUT_ACTIVE_ALT && keyStates[13]) //alt + enter
{
toggleFullScreen();
}
if (keyStates[98]) //b
{
isDebugMode = !isDebugMode;
if (isDebugMode)
glutSetCursor(GLUT_CURSOR_RIGHT_ARROW);
else
glutSetCursor(GLUT_CURSOR_NONE);
}
if(keyStates[104]){//h
showHelpWindow = !showHelpWindow;
}
if (keyStates[115])//s
{
game->lr->toggleSkySphere();
}
if (keyStates[27]) //ESC
{
if (game != NULL)
{
delete game;
}
exit(0);
}
}
void keyboardKeysUp(unsigned char key, int x, int y)
{
keyStates[key] = false;
keyModifier = 0;
//Checks for uppercase
if (key >= 65 && key <= 90)
keyStates[key + 32] = false;
}
void keyboardKeysPressed(unsigned char key, int x, int y)
{
keyStates[key] = true;
keyModifier = glutGetModifiers();
//Checks for uppercase
if (key >= 65 && key <= 90)
keyStates[key + 32] = true;
windowKeyOps();
}
void OnKey(unsigned char key, int x, int y) {
TwEventKeyboardGLUT(key, x, y);
keyboardKeysPressed(key, x, y);
}
void initAntTweak() {
// antTweakHelper.bindCamera(game->p1->getCurrentCamera());
//antTweakHelper.bindLightPosts(light1, light2, light3, light4);
}
void init()
{
glGenLists(7);
te = TextureManager::getInstance();
game = new Game(width, height, nearPlane, farPlane, keyStates, funcKeyStates);
glEnable(GL_DEPTH_TEST);
isInFullScreenMode = false;
glCullFace( GL_BACK );
glEnable( GL_CULL_FACE );
for (int i = 0; i < 256; i++)
{
keyStates[i] = false;
funcKeyStates[i] = false;
}
glutSetCursor(GLUT_CURSOR_NONE);
initAntTweak();
glEnable(GL_NORMALIZE);
}
//mouse movement functions, primarily used to modify the view
void passiveMotionFunc(int x, int y)
{
game->playerInput1->mousePassiveOperations(x, y);
}
void motionFunc(int x, int y)
{
game->playerInput1->mousePassiveOperations(x, y);
}
void joystickFunc(unsigned int button, int xaxis, int yaxis, int zaxis)
{
game->playerInput2->joystickOperations(button, xaxis, yaxis, zaxis);
}
int main (int argc, char **argv)
{
// GLUT initialization.
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(width, height);
mainWindow = glutCreateWindow("Battle Royale Near Earth");
//callbacks
glutReshapeFunc(reshapeMainWindow);
glutSpecialFunc(functionKeysPressed);
glutSpecialUpFunc(functionKeyUp);
glutKeyboardFunc(keyboardKeysPressed);
glutKeyboardUpFunc(keyboardKeysUp);
glutDisplayFunc(render);
glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT);
glutKeyboardFunc((GLUTkeyboardfun)OnKey);
//mouse motion
glutMotionFunc(motionFunc);
glutPassiveMotionFunc(passiveMotionFunc);
glutJoystickFunc(joystickFunc, 150);
init();
glutMainLoop();
return 0;
}
<commit_msg>remaped key to change skybox style from s to z<commit_after>#include <math.h>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>
#include "Game.h"
#include "SpotLight.h"
#include "Light/LightPost.h"
#include "Model/Texture/TextureManager.h"
#include "AntTweakHelper.h"
#ifdef __APPLE__
#include <Glut/glut.h>
#else
#define FREEGLUT_STATIC
#include <GL/glut.h>
#endif
// PI
#define GL_PI 3.14159f
// Current size of window.
GLint width = 700;
GLint height = 500;
// old values for the window (used to come back from fullscreen)
GLint oldWidth = width;
GLint oldHeight = height;
// Current position of the window (used to come back from fullscreen)
int winPosX = 0;
int winPosY = 0;
bool isInFullScreenMode;
bool showHelpWindow = false;
// Bounds of viewing frustum.
GLfloat nearPlane = 1.0f;
GLfloat farPlane = 100.0f;
bool keyStates[256];
bool funcKeyStates[256];
int keyModifier = 0;
TextureManager *te;
static bool isDebugMode = false;
bool isTwoPlayerGame = false;
int viewStates = 0; //states of the camera views
Game* game;
AntTweakHelper antTweakHelper;
//second window for help menu
int mainWindow = 0;
void reshapeMainWindow (int newWidth, int newHeight)
{
width = newWidth;
height = newHeight;
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
TwWindowSize(width, height);
}
void toggleTwoPlayerSplitscreen()
{
isTwoPlayerGame = !isTwoPlayerGame;
if (isTwoPlayerGame)
{
game->p1->selectRobotView(game->p1->robots.at(0));
game->p1->changeCamera(CAMERA_ROBOT);
game->p2->selectRobotView(game->p2->robots.at(0));
game->p2->changeCamera(CAMERA_ROBOT);
}
else
{
game->p1->changeCamera(CAMERA_COMMANDER);
game->p2->changeCamera(CAMERA_COMMANDER);
}
}
void toggleFullScreen()
{
isInFullScreenMode = !isInFullScreenMode;
if (isInFullScreenMode)
{
oldWidth = width;
oldHeight = height;
winPosX = glutGet(GLUT_WINDOW_X);
winPosY = glutGet(GLUT_WINDOW_Y);
glutFullScreen();
}
else
{
glutPositionWindow(winPosX, winPosY);
glutReshapeWindow(oldWidth, oldHeight);
}
}
void rasterText(GLfloat x, GLfloat y, void *font, char *c, int cWidth){
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glLoadIdentity();
glRasterPos2f(x, y);
for (int i = 0; i < cWidth; i++)
{
glutBitmapCharacter(font, c[i]);
}
glPopMatrix();
}
void help_display(){
glPushMatrix();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//creating ortho view since text is only 2D
glOrtho(0, width-5, 0, height-5, 0.0, 0.1);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_LIGHTING);
int lineSpace = 15;
int lineHeight = height-20;
ifstream openfile;
string fileLoad = "keyInput.txt";
openfile.open((TextureManager::getResourcePath() + fileLoad).c_str(), ios::in);
glColor3f(1.0f, 1.0f, 1.0f);
if (openfile.is_open()) {
string s;
getline(openfile, s);
char *title = (char*)s.c_str();
rasterText((GLfloat)width/2-35,(GLfloat)lineHeight,GLUT_BITMAP_HELVETICA_12, title,s.size());
lineHeight -= 5;
while(!openfile.eof())
{
getline(openfile, s);
char *readLine = (char*)s.c_str();
lineHeight -= lineSpace;
rasterText(15.0f,(GLfloat)lineHeight,GLUT_BITMAP_HELVETICA_10, readLine,s.size());
}
openfile.close();
}
glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
glBegin(GL_QUADS);
glVertex2f(0.0f, 0.0f);
glVertex2f((GLfloat)width, 0.0f);
glVertex2f((GLfloat)width, (GLfloat)height);
glVertex2f(0.0f, (GLfloat)height);
glEnd();
glEnable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
void render()
{
static time_t lastUpdate = time(NULL);
static time_t currentTime = time(NULL);
static GLuint fps = 0;
static GLuint prevFps = 0;
//clears the buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if(showHelpWindow){
help_display();
}
if (isTwoPlayerGame)
{
game->p1->view();
game->render();
glViewport(0, 0, (GLsizei)width, (GLsizei)height / 2);
game->p2->view();
game->render();
glViewport(0, (GLint)height / 2, (GLsizei)width, (GLsizei)height / 2);
}
else
{
game->render();
game->p1->view();
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
}
game->getInput(keyModifier); // Gets user input
//((HumanPlayer*)(game->p1))->view(); // Camera update (leave as it is for now)
if (isDebugMode) {
antTweakHelper.draw();
}
fps++;
currentTime = time(NULL);
if ((currentTime - lastUpdate) >= 1.0f)
{
lastUpdate = currentTime;
prevFps = fps;
fps = 0;
}
stringstream sFps;
sFps << prevFps;
string prefixAndFps = "FPS: " + sFps.str();
glPushMatrix();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, 0.0f, 0.1f);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_LIGHTING);
glColor3f(1.0f, 1.0f, 1.0f);
rasterText(20.0f, 20.0f, GLUT_BITMAP_HELVETICA_18, (char *)prefixAndFps.c_str(), prefixAndFps.size());
glEnable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
void functionKeyUp(int key, int x, int y)
{
funcKeyStates[key] = false;
glutPostRedisplay();
}
void toggleDifferentView(){
++viewStates;
//normal settings
glShadeModel(GL_FLAT);
glEnable(GL_DEPTH_TEST);
glPolygonMode(GL_FRONT, GL_FILL);
if (game->lr->getIsSkySphere())
glPolygonMode(GL_BACK, GL_FILL);
if(viewStates==1){ //wireFrame
glDisable(GL_DEPTH_TEST);
glPolygonMode(GL_FRONT, GL_LINE);
if (game->lr->getIsSkySphere())
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else if(viewStates==2){ //smoothShading
glShadeModel(GL_SMOOTH);
glPolygonMode(GL_FRONT, GL_FILL);
if (game->lr->getIsSkySphere())
glPolygonMode(GL_BACK, GL_FILL);
}
else{//back to normal
viewStates=0;
}
}
void windowFuncKeyOps(){
if (funcKeyStates[GLUT_KEY_F1]) {
toggleDifferentView();
}
else if (funcKeyStates[GLUT_KEY_F6]) {
TextureManager::getInstance()->toggleSkins();
}
if (funcKeyStates[GLUT_KEY_F8])
toggleTwoPlayerSplitscreen();
}
void functionKeysPressed(int key, int x, int y)
{
funcKeyStates[key] = true;
windowFuncKeyOps();
}
void windowKeyOps()
{
if (keyModifier == GLUT_ACTIVE_ALT && keyStates[13]) //alt + enter
{
toggleFullScreen();
}
if (keyStates[98]) //b
{
isDebugMode = !isDebugMode;
if (isDebugMode)
glutSetCursor(GLUT_CURSOR_RIGHT_ARROW);
else
glutSetCursor(GLUT_CURSOR_NONE);
}
if(keyStates[104]){//h
showHelpWindow = !showHelpWindow;
}
if (keyStates['z'])
{
game->lr->toggleSkySphere();
}
if (keyStates[27]) //ESC
{
if (game != NULL)
{
delete game;
}
exit(0);
}
}
void keyboardKeysUp(unsigned char key, int x, int y)
{
keyStates[key] = false;
keyModifier = 0;
//Checks for uppercase
if (key >= 65 && key <= 90)
keyStates[key + 32] = false;
}
void keyboardKeysPressed(unsigned char key, int x, int y)
{
keyStates[key] = true;
keyModifier = glutGetModifiers();
//Checks for uppercase
if (key >= 65 && key <= 90)
keyStates[key + 32] = true;
windowKeyOps();
}
void OnKey(unsigned char key, int x, int y) {
TwEventKeyboardGLUT(key, x, y);
keyboardKeysPressed(key, x, y);
}
void initAntTweak() {
// antTweakHelper.bindCamera(game->p1->getCurrentCamera());
//antTweakHelper.bindLightPosts(light1, light2, light3, light4);
}
void init()
{
glGenLists(7);
te = TextureManager::getInstance();
game = new Game(width, height, nearPlane, farPlane, keyStates, funcKeyStates);
glEnable(GL_DEPTH_TEST);
isInFullScreenMode = false;
glCullFace( GL_BACK );
glEnable( GL_CULL_FACE );
for (int i = 0; i < 256; i++)
{
keyStates[i] = false;
funcKeyStates[i] = false;
}
glutSetCursor(GLUT_CURSOR_NONE);
initAntTweak();
glEnable(GL_NORMALIZE);
}
//mouse movement functions, primarily used to modify the view
void passiveMotionFunc(int x, int y)
{
game->playerInput1->mousePassiveOperations(x, y);
}
void motionFunc(int x, int y)
{
game->playerInput1->mousePassiveOperations(x, y);
}
void joystickFunc(unsigned int button, int xaxis, int yaxis, int zaxis)
{
game->playerInput2->joystickOperations(button, xaxis, yaxis, zaxis);
}
int main (int argc, char **argv)
{
// GLUT initialization.
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(width, height);
mainWindow = glutCreateWindow("Battle Royale Near Earth");
//callbacks
glutReshapeFunc(reshapeMainWindow);
glutSpecialFunc(functionKeysPressed);
glutSpecialUpFunc(functionKeyUp);
glutKeyboardFunc(keyboardKeysPressed);
glutKeyboardUpFunc(keyboardKeysUp);
glutDisplayFunc(render);
glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT);
glutKeyboardFunc((GLUTkeyboardfun)OnKey);
//mouse motion
glutMotionFunc(motionFunc);
glutPassiveMotionFunc(passiveMotionFunc);
glutJoystickFunc(joystickFunc, 150);
init();
glutMainLoop();
return 0;
}
<|endoftext|>
|
<commit_before>#include "FreeListAllocator.h"
#include "Utils.h" /* CalculatePaddingWithHeader */
#include <stdlib.h> /* malloc, free */
#include <cassert> /* assert */
#include <limits> /* limits_max */
#ifdef _DEBUG
#include <iostream>
#endif
FreeListAllocator::FreeListAllocator(const std::size_t totalSize, enum PlacementPolicy pPolicy, enum sPolicy);
: Allocator(totalSize) {
m_pPolicy = pPolicy;
m_sPolicy = sPolicy;
}
void FreeListAllocator::Init() {
if (m_freeList != nullptr){
delete m_freeList;
}
if (m_start_ptr != nullptr){
free(m_start_ptr);
m_start_ptr = nullptr;
}
// Init linkedlist with only one element
m_start_ptr = malloc(m_totalSize);
m_freeList = (FreeBlock *) m_start_ptr;
m_freeList.m_head->size = m_totalSize;
m_freeList.m_head->previous = NULL;
m_freeList.m_head->next = NULL;
}
FreeListAllocator::~FreeListAllocator(){
free(m_start_ptr);
m_start_ptr = nullptr;
}
void* FreeListAllocator::Allocate(const std::size_t size, const std::size_t alignment){
// Search through the free list for a free block that has enough space to allocate our data
FreeBlock * affectedBlock = this->Find(size);
const int rest = affectedBlock->size - size;
if (rest == 0){
// We have to split the block into the data block and a free block of size 'rest'
FreeBlock * newFreeBlock = (FreeBlock *)((std::size_t) affectedBlock + size + 1);
//TODO: linkedlist insert!!!!!
//TODO: linkedlist delete!!!!!
affectedBlock->previous->next = newFreeBlock;
newFreeBlock->previous = affectedBlock->previous;
newFreeBlock->next = affectedBlock->next;
newFreeBlock->size = rest;
}else {
// Delete block from free list
//TODO: linkedlist delete!!!!!
affectedBlock->previous->next = affectedBlock->next;
}
#ifdef _DEBUG
std::cout << "A" << "\t@C " << (void*) affectedBlock << std::endl;
#endif
return (void*) affectedBlock;
}
FreeBlock * FreeListAllocator::Find(const std::size_t size){
switch(m_pPolicy){
case FIND_FIRST:
return FindFirst(size);
case FIND_BEST:
return FindBest(size);
default:
return nullptr;
}
}
FreeBlock * FreeListAllocator::FindFirst(const std::size_t size){
//Iterate list and return the first free block with a size >= than given size
FreeBlock * it = m_freeList;
while(it != nullptr){
if (it->size >= size){
return it;
}
it = it->next;
}
return nullptr;
}
FreeBlock * FreeListAllocator::FindBest(const std::size_t size){
// Iterate WHOLE list keeping a pointer to the best fit
std::size_t smallestDiff = std::numeric_limits<T>::max();
FreeBlock * bestBlock = nullptr;
FreeBlock * it = m_freeList;
while(it != nullptr){
if (it->size >= size && (it->size - size < smallestDiff)){
bestBlock = it;
}
it = it->next;
}
return bestBlock;
}
void FreeListAllocator::Free(void* ptr){
FreeBlock * freeBlock = InsertFree(ptr);
Coalescence(freeBlock);
}
FreeBlock * FreeListAllocator::InsertFree(void * ptr){
switch(m_sPolicy){
case LIFO:
return InsertFreeLIFO(ptr);
case SORTED:
return InsertFreeSorted(ptr);
}
}
FreeBlock * FreeListAllocator::InsertFreeLIFO(void * ptr){
// Insert it in a LIFO (or stack) fashion (at the beginning)
//TODO: linkedlist insert!!!!!
FreeBlock * freeBlock = (FreeBlock *) ptr;
freeBlock->next = m_freeList.next;
freeBlock->next->previous = freeBlock;
freeBlock->previous = m_start_ptr;
freeBlock->size = 7; // TODO SIZE ??????????
m_freeList.next = freeBlock;
return freeBlock;
}
FreeBlock * FreeListAllocator::InsertFreeSorted(void * ptr){
// Insert it in a sorted position by the address number
FreeBlock * freeBlock = (FreeBlock *) ptr;
FreeBlock * it = m_freeList;
while(it != nullptr){
if ((std::size_t) ptr < (std::size_t) it){
//TODO: linkedlist insert!!!!!
break;
}
it = it->next;
}
return freeBlock;
}
void FreeListAllocator::Coalescence(FreeBlock * freeBlock){
// TODO: Merge with previous and/or next, or neither
}
void FreeListAllocator::Reset() {
m_freeList = (FreeBlock *) m_start_ptr;
m_freeList.m_head->size = m_totalSize;
m_freeList.m_head->previous = NULL;
m_freeList.m_head->next = NULL;
}
<commit_msg>Added conditions to coalescence<commit_after>#include "FreeListAllocator.h"
#include "Utils.h" /* CalculatePaddingWithHeader */
#include <stdlib.h> /* malloc, free */
#include <cassert> /* assert */
#include <limits> /* limits_max */
#ifdef _DEBUG
#include <iostream>
#endif
FreeListAllocator::FreeListAllocator(const std::size_t totalSize, enum PlacementPolicy pPolicy, enum sPolicy);
: Allocator(totalSize) {
m_pPolicy = pPolicy;
m_sPolicy = sPolicy;
}
void FreeListAllocator::Init() {
if (m_freeList != nullptr){
delete m_freeList;
}
if (m_start_ptr != nullptr){
free(m_start_ptr);
m_start_ptr = nullptr;
}
// Init linkedlist with only one element
m_start_ptr = malloc(m_totalSize);
m_freeList = (FreeBlock *) m_start_ptr;
m_freeList.m_head->size = m_totalSize;
m_freeList.m_head->previous = NULL;
m_freeList.m_head->next = NULL;
}
FreeListAllocator::~FreeListAllocator(){
free(m_start_ptr);
m_start_ptr = nullptr;
}
void* FreeListAllocator::Allocate(const std::size_t size, const std::size_t alignment){
// Search through the free list for a free block that has enough space to allocate our data
FreeBlock * affectedBlock = this->Find(size);
const int rest = affectedBlock->size - size;
if (rest == 0){
// We have to split the block into the data block and a free block of size 'rest'
FreeBlock * newFreeBlock = (FreeBlock *)((std::size_t) affectedBlock + size + 1);
//TODO: linkedlist insert!!!!!
//TODO: linkedlist delete!!!!!
affectedBlock->previous->next = newFreeBlock;
newFreeBlock->previous = affectedBlock->previous;
newFreeBlock->next = affectedBlock->next;
newFreeBlock->size = rest;
}else {
// Delete block from free list
//TODO: linkedlist delete!!!!!
affectedBlock->previous->next = affectedBlock->next;
}
#ifdef _DEBUG
std::cout << "A" << "\t@C " << (void*) affectedBlock << std::endl;
#endif
return (void*) affectedBlock;
}
FreeBlock * FreeListAllocator::Find(const std::size_t size){
switch(m_pPolicy){
case FIND_FIRST:
return FindFirst(size);
case FIND_BEST:
return FindBest(size);
default:
return nullptr;
}
}
FreeBlock * FreeListAllocator::FindFirst(const std::size_t size){
//Iterate list and return the first free block with a size >= than given size
FreeBlock * it = m_freeList;
while(it != nullptr){
if (it->size >= size){
return it;
}
it = it->next;
}
return nullptr;
}
FreeBlock * FreeListAllocator::FindBest(const std::size_t size){
// Iterate WHOLE list keeping a pointer to the best fit
std::size_t smallestDiff = std::numeric_limits<T>::max();
FreeBlock * bestBlock = nullptr;
FreeBlock * it = m_freeList;
while(it != nullptr){
if (it->size >= size && (it->size - size < smallestDiff)){
bestBlock = it;
}
it = it->next;
}
return bestBlock;
}
void FreeListAllocator::Free(void* ptr){
FreeBlock * freeBlock = InsertFree(ptr);
Coalescence(freeBlock);
}
FreeBlock * FreeListAllocator::InsertFree(void * ptr){
switch(m_sPolicy){
case LIFO:
return InsertFreeLIFO(ptr);
case SORTED:
return InsertFreeSorted(ptr);
}
}
FreeBlock * FreeListAllocator::InsertFreeLIFO(void * ptr){
// Insert it in a LIFO (or stack) fashion (at the beginning)
//TODO: linkedlist insert!!!!!
FreeBlock * freeBlock = (FreeBlock *) ptr;
freeBlock->next = m_freeList.next;
freeBlock->next->previous = freeBlock;
freeBlock->previous = m_start_ptr;
freeBlock->size = 7; // TODO SIZE ??????????
m_freeList.next = freeBlock;
return freeBlock;
}
FreeBlock * FreeListAllocator::InsertFreeSorted(void * ptr){
// Insert it in a sorted position by the address number
FreeBlock * freeBlock = (FreeBlock *) ptr;
FreeBlock * it = m_freeList;
while(it != nullptr){
if ((std::size_t) ptr < (std::size_t) it){
//TODO: linkedlist insert!!!!!
break;
}
it = it->next;
}
return freeBlock;
}
void FreeListAllocator::Coalescence(FreeBlock * freeBlock){
// TODO: Merge with previous and/or next, or neither
if ((std::size_t) freeBlock->previous +
(std::size_t) freeBlock->previous->size + 1 == (std::size_t) freeBlock){
//Merge with current and previous
}
if ((std::size_t) freeBlock +
(std::size_t) freeBlock->size + 1 == (std::size_t) freeBlock->next){
//Merge with current with next
}
}
void FreeListAllocator::Reset() {
m_freeList = (FreeBlock *) m_start_ptr;
m_freeList.m_head->size = m_totalSize;
m_freeList.m_head->previous = NULL;
m_freeList.m_head->next = NULL;
}
/*
Linked List generic methods:
INSERT (AFTER_PTR, PTR);
DELETE (PTR);
SPLIT (PTR, OUT_PTR1, OUT_PTR2);
MERGE(PTR1, PTR2)
*/
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2015 CNRS
//
// This file is part of Pinocchio
// Pinocchio 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.
//
// Pinocchio 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
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_constraint_hpp__
#define __se3_constraint_hpp__
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/motion.hpp"
// S : v \in M^6 -> v_J \in lie(Q) ~= R^nv
// S^T : f_J \in lie(Q)^* ~= R^nv -> f \in F^6
namespace se3
{
template<int _Dim, typename _Scalar, int _Options=0> class ConstraintTpl;
template< class Derived>
class ConstraintBase
{
protected:
typedef Derived Derived_t;
SPATIAL_TYPEDEF_TEMPLATE(Derived_t);
typedef typename traits<Derived_t>::JointMotion JointMotion;
typedef typename traits<Derived_t>::JointForce JointForce;
typedef typename traits<Derived_t>::DenseBase DenseBase;
public:
Derived_t & derived() { return *static_cast<Derived_t*>(this); }
const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); }
Motion operator* (const JointMotion& vj) const { return derived().__mult__(vj); }
DenseBase & matrix() { return derived().matrix_impl(); }
const DenseBase & matrix() const { return derived().matrix_impl(); }
int nv() const { return derived().nv_impl(); }
}; // class ConstraintBase
template<int D, typename T, int U>
struct traits< ConstraintTpl<D, T, U> >
{
typedef T Scalar_t;
typedef Eigen::Matrix<T,3,1,U> Vector3;
typedef Eigen::Matrix<T,4,1,U> Vector4;
typedef Eigen::Matrix<T,6,1,U> Vector6;
typedef Eigen::Matrix<T,3,3,U> Matrix3;
typedef Eigen::Matrix<T,4,4,U> Matrix4;
typedef Eigen::Matrix<T,6,6,U> Matrix6;
typedef Matrix3 Angular_t;
typedef Vector3 Linear_t;
typedef Matrix6 ActionMatrix_t;
typedef Eigen::Quaternion<T,U> Quaternion_t;
typedef SE3Tpl<T,U> SE3;
typedef ForceTpl<T,U> Force;
typedef MotionTpl<T,U> Motion;
typedef Symmetric3Tpl<T,U> Symmetric3;
enum {
LINEAR = 0,
ANGULAR = 3
};
typedef Eigen::Matrix<Scalar_t,D,1,U> JointMotion;
typedef Eigen::Matrix<Scalar_t,D,1,U> JointForce;
typedef Eigen::Matrix<Scalar_t,6,D> DenseBase;
}; // traits ConstraintTpl
namespace internal
{
template<int Dim, typename Scalar, int Options>
struct ActionReturn<ConstraintTpl<Dim,Scalar,Options> >
{ typedef Eigen::Matrix<Scalar,6,Dim> Type; };
}
template<int _Dim, typename _Scalar, int _Options>
class ConstraintTpl : public ConstraintBase<ConstraintTpl < _Dim, _Scalar, _Options > >
{
public:
friend class ConstraintBase< ConstraintTpl< _Dim, _Scalar, _Options > >;
SPATIAL_TYPEDEF_TEMPLATE(ConstraintTpl);
enum { NV = _Dim, Options = _Options };
typedef typename traits<ConstraintTpl>::JointMotion JointMotion;
typedef typename traits<ConstraintTpl>::JointForce JointForce;
typedef typename traits<ConstraintTpl>::DenseBase DenseBase;
public:
template<typename D>
ConstraintTpl( const Eigen::MatrixBase<D> & _S ) : S(_S) {}
ConstraintTpl() : S()
{
#ifndef NDEBUG
S.fill( NAN );
#endif
}
ConstraintTpl(const int dim) : S(6,dim)
{
#ifndef NDEBUG
S.fill( NAN );
#endif
}
Motion __mult__(const JointMotion& vj) const
{
return Motion(S*vj);
}
struct Transpose
{
const ConstraintTpl & ref;
Transpose( const ConstraintTpl & ref ) : ref(ref) {}
JointForce operator* (const Force& f) const
{ return ref.S.transpose()*f.toVector(); }
template<typename D>
typename Eigen::Matrix<_Scalar,NV,Eigen::Dynamic>
operator*( const Eigen::MatrixBase<D> & F )
{
return ref.S.transpose()*F;
}
};
Transpose transpose() const { return Transpose(*this); }
DenseBase & matrix_impl() { return S; }
const DenseBase & matrix_impl() const { return S; }
int nv_impl() const { return NV; }
//template<int Dim,typename Scalar,int Options>
friend Eigen::Matrix<_Scalar,6,_Dim>
operator*( const InertiaTpl<_Scalar,_Options> & Y,const ConstraintTpl<_Dim,_Scalar,_Options> & S)
{ return Y.matrix()*S.S; }
Eigen::Matrix<_Scalar,6,NV> se3Action(const SE3 & m) const
{
return m.toActionMatrix()*S;
}
private:
DenseBase S;
}; // class ConstraintTpl
typedef ConstraintTpl<1,double,0> Constraint1d;
typedef ConstraintTpl<3,double,0> Constraint3d;
typedef ConstraintTpl<6,double,0> Constraint6d;
typedef ConstraintTpl<Eigen::Dynamic,double,0> ConstraintXd;
} // namespace se3
#endif // ifndef __se3_constraint_hpp__
<commit_msg>[C++] Add operator disp in Constraint class<commit_after>//
// Copyright (c) 2015 CNRS
//
// This file is part of Pinocchio
// Pinocchio 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.
//
// Pinocchio 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
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_constraint_hpp__
#define __se3_constraint_hpp__
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/motion.hpp"
// S : v \in M^6 -> v_J \in lie(Q) ~= R^nv
// S^T : f_J \in lie(Q)^* ~= R^nv -> f \in F^6
namespace se3
{
template<int _Dim, typename _Scalar, int _Options=0> class ConstraintTpl;
template< class Derived>
class ConstraintBase
{
protected:
typedef Derived Derived_t;
SPATIAL_TYPEDEF_TEMPLATE(Derived_t);
typedef typename traits<Derived_t>::JointMotion JointMotion;
typedef typename traits<Derived_t>::JointForce JointForce;
typedef typename traits<Derived_t>::DenseBase DenseBase;
public:
Derived_t & derived() { return *static_cast<Derived_t*>(this); }
const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); }
Motion operator* (const JointMotion& vj) const { return derived().__mult__(vj); }
DenseBase & matrix() { return derived().matrix_impl(); }
const DenseBase & matrix() const { return derived().matrix_impl(); }
int nv() const { return derived().nv_impl(); }
void disp(std::ostream & os) const { static_cast<const Derived_t*>(this)->disp_impl(os); }
friend std::ostream & operator << (std::ostream & os,const ConstraintBase<Derived> & X)
{
X.disp(os);
return os;
}
}; // class ConstraintBase
template<int D, typename T, int U>
struct traits< ConstraintTpl<D, T, U> >
{
typedef T Scalar_t;
typedef Eigen::Matrix<T,3,1,U> Vector3;
typedef Eigen::Matrix<T,4,1,U> Vector4;
typedef Eigen::Matrix<T,6,1,U> Vector6;
typedef Eigen::Matrix<T,3,3,U> Matrix3;
typedef Eigen::Matrix<T,4,4,U> Matrix4;
typedef Eigen::Matrix<T,6,6,U> Matrix6;
typedef Matrix3 Angular_t;
typedef Vector3 Linear_t;
typedef Matrix6 ActionMatrix_t;
typedef Eigen::Quaternion<T,U> Quaternion_t;
typedef SE3Tpl<T,U> SE3;
typedef ForceTpl<T,U> Force;
typedef MotionTpl<T,U> Motion;
typedef Symmetric3Tpl<T,U> Symmetric3;
enum {
LINEAR = 0,
ANGULAR = 3
};
typedef Eigen::Matrix<Scalar_t,D,1,U> JointMotion;
typedef Eigen::Matrix<Scalar_t,D,1,U> JointForce;
typedef Eigen::Matrix<Scalar_t,6,D> DenseBase;
}; // traits ConstraintTpl
namespace internal
{
template<int Dim, typename Scalar, int Options>
struct ActionReturn<ConstraintTpl<Dim,Scalar,Options> >
{ typedef Eigen::Matrix<Scalar,6,Dim> Type; };
}
template<int _Dim, typename _Scalar, int _Options>
class ConstraintTpl : public ConstraintBase<ConstraintTpl < _Dim, _Scalar, _Options > >
{
public:
friend class ConstraintBase< ConstraintTpl< _Dim, _Scalar, _Options > >;
SPATIAL_TYPEDEF_TEMPLATE(ConstraintTpl);
enum { NV = _Dim, Options = _Options };
typedef typename traits<ConstraintTpl>::JointMotion JointMotion;
typedef typename traits<ConstraintTpl>::JointForce JointForce;
typedef typename traits<ConstraintTpl>::DenseBase DenseBase;
public:
template<typename D>
ConstraintTpl( const Eigen::MatrixBase<D> & _S ) : S(_S) {}
ConstraintTpl() : S()
{
#ifndef NDEBUG
S.fill( NAN );
#endif
}
ConstraintTpl(const int dim) : S(6,dim)
{
#ifndef NDEBUG
S.fill( NAN );
#endif
}
Motion __mult__(const JointMotion& vj) const
{
return Motion(S*vj);
}
struct Transpose
{
const ConstraintTpl & ref;
Transpose( const ConstraintTpl & ref ) : ref(ref) {}
JointForce operator* (const Force& f) const
{ return ref.S.transpose()*f.toVector(); }
template<typename D>
typename Eigen::Matrix<_Scalar,NV,Eigen::Dynamic>
operator*( const Eigen::MatrixBase<D> & F )
{
return ref.S.transpose()*F;
}
};
Transpose transpose() const { return Transpose(*this); }
DenseBase & matrix_impl() { return S; }
const DenseBase & matrix_impl() const { return S; }
int nv_impl() const { return NV; }
//template<int Dim,typename Scalar,int Options>
friend Eigen::Matrix<_Scalar,6,_Dim>
operator*( const InertiaTpl<_Scalar,_Options> & Y,const ConstraintTpl<_Dim,_Scalar,_Options> & S)
{ return Y.matrix()*S.S; }
Eigen::Matrix<_Scalar,6,NV> se3Action(const SE3 & m) const
{
return m.toActionMatrix()*S;
}
void disp_impl(std::ostream & os) const { os << "S =\n" << S << std::endl;}
private:
DenseBase S;
}; // class ConstraintTpl
typedef ConstraintTpl<1,double,0> Constraint1d;
typedef ConstraintTpl<3,double,0> Constraint3d;
typedef ConstraintTpl<6,double,0> Constraint6d;
typedef ConstraintTpl<Eigen::Dynamic,double,0> ConstraintXd;
} // namespace se3
#endif // ifndef __se3_constraint_hpp__
<|endoftext|>
|
<commit_before>
/*
* Copyright (c) 2014, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael X. Grey <mxgrey@gatech.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include "dart/dynamics/SimpleFrame.h"
#include "dart/math/Helpers.h"
#include "TestHelpers.h"
using namespace dart;
using namespace dynamics;
void randomize_transforms(std::vector<Eigen::Isometry3d>& tfs)
{
for(size_t i=0; i<tfs.size(); ++i)
{
Eigen::Vector3d v;
for(size_t i=0; i<3; ++i)
v[i] = math::random(-100, 100);
Eigen::Vector3d theta;
for(size_t i=0; i<3; ++i)
theta[i] = math::random(-100, 100);
Eigen::Isometry3d& tf = tfs[i];
tf.setIdentity();
tf.translate(v);
if(theta.norm()>0)
tf.rotate(Eigen::AngleAxisd(theta.norm(), theta.normalized()));
}
}
template<int N>
Eigen::Matrix<double,N,1> random_vec()
{
Eigen::Matrix<double,N,1> v;
for(size_t i=0; i<N; ++i)
v[i] = math::random(-100, 100);
return v;
}
void compute_spatial_velocity(const Eigen::Vector6d& v_parent,
const Eigen::Vector6d& v_relative,
const Eigen::Isometry3d& tf_rel,
Eigen::Vector6d& v_child)
{
v_child = math::AdInvT(tf_rel, v_parent) + v_relative;
}
// TODO: Consider reference frame
void compute_velocity(const Eigen::Vector3d& v_parent,
const Eigen::Vector3d& w_parent,
const Eigen::Vector3d& v_rel,
const Eigen::Vector3d& w_rel,
const Eigen::Vector3d& offset,
Eigen::Vector3d& v_child,
Eigen::Vector3d& w_child)
{
v_child = v_parent + v_rel + w_parent.cross(offset);
w_child = w_parent + w_rel;
}
void compute_acceleration(const Eigen::Vector3d& a_parent,
const Eigen::Vector3d& alpha_parent,
const Eigen::Vector3d& w_parent,
const Eigen::Vector3d& a_rel,
const Eigen::Vector3d& alpha_rel,
const Eigen::Vector3d& v_rel,
const Eigen::Vector3d& offset,
Eigen::Vector3d& a_child,
Eigen::Vector3d& alpha_child)
{
a_child = a_parent + a_rel
+ alpha_parent.cross(offset)
+ 2*w_parent.cross(v_rel)
+ w_parent.cross(w_parent.cross(offset));
alpha_child = alpha_parent + alpha_rel + alpha_parent.cross(alpha_rel);
}
TEST(FRAMES, FORWARD_KINEMATICS_CHAIN)
{
std::vector<SimpleFrame*> frames;
double tolerance = 1e-8;
SimpleFrame A(Frame::World(), "A");
frames.push_back(&A);
SimpleFrame B(&A, "B");
frames.push_back(&B);
SimpleFrame C(&B, "C");
frames.push_back(&C);
SimpleFrame D(&C, "D");
frames.push_back(&D);
// -- Test Position --------------------------------------------------------
EXPECT_TRUE( equals(D.getTransform().matrix(),
Eigen::Isometry3d::Identity().matrix(),
tolerance));
std::vector<Eigen::Isometry3d> tfs;
tfs.resize(frames.size(), Eigen::Isometry3d::Identity());
randomize_transforms(tfs);
for(size_t i=0; i<frames.size(); ++i)
{
SimpleFrame* F = frames[i];
F->setRelativeTransform(tfs[i]);
}
for(size_t i=0; i<frames.size(); ++i)
{
Frame* F = frames[i];
Eigen::Isometry3d expectation(Eigen::Isometry3d::Identity());
for(size_t j=0; j<=i; ++j)
{
expectation = expectation * tfs[j];
}
Eigen::Isometry3d actual = F->getTransform();
EXPECT_TRUE( equals(actual.matrix(), expectation.matrix(), tolerance));
}
randomize_transforms(tfs);
for(size_t i=0; i<frames.size(); ++i)
{
SimpleFrame* F = frames[i];
F->setRelativeTransform(tfs[i]);
}
Eigen::Isometry3d expectation(Eigen::Isometry3d::Identity());
for(size_t j=0; j<frames.size(); ++j)
expectation = expectation * tfs[j];
EXPECT_TRUE( equals(frames.back()->getTransform().matrix(),
expectation.matrix(),
tolerance) );
// -- Test Velocity --------------------------------------------------------
std::vector<Eigen::Vector6d> v_rels(frames.size());
std::vector<Eigen::Vector6d> v_total(frames.size());
for(size_t i=0; i<frames.size(); ++i)
{
v_rels[i] = random_vec<6>();
SimpleFrame* F = frames[i];
F->setRelativeSpatialVelocity(v_rels[i]);
}
v_total[0] = v_rels[0];
for(size_t i=1; i<frames.size(); ++i)
{
SimpleFrame* F = frames[i];
compute_spatial_velocity(v_total[i-1], v_rels[i],
F->getRelativeTransform(), v_total[i]);
}
for(size_t i=0; i<frames.size(); ++i)
{
SimpleFrame* F = frames[i];
Eigen::Vector6d v_actual = F->getSpatialVelocity();
EXPECT_TRUE( equals(v_total[i], v_actual) );
}
// std::vector<Eigen::Vector3d> v_rels(frames.size());
// std::vector<Eigen::Vector3d> w_rels(frames.size());
// std::vector<Eigen::Vector3d> v_total(frames.size());
// std::vector<Eigen::Vector3d> w_total(frames.size());
// for(size_t i=0; i<frames.size(); ++i)
// {
// v_rels[i] = random_vec();
// w_rels[i] = random_vec();
// Eigen::Vector6d spatial_v;
// spatial_v << w_rels[i], v_rels[i];
// SimpleFrame* F = frames[i];
// F->setRelativeSpatialVelocity(spatial_v, F->getParentFrame());
// }
// v_total[0] = v_rels[0];
// w_total[0] = w_rels[0];
// for(size_t i=1; i<frames.size(); ++i)
// {
// SimpleFrame* F = frames[i];
// Eigen::Vector3d offset = F->getRelativeTransform().translation();
// compute_velocity(v_total[i-1], w_total[i-1], v_rels[i], w_rels[i],
// offset, v_total[i], w_total[i]);
// }
// for(size_t i=0; i<frames.size(); ++i)
// {
// std::cout << "Trial #" << i << "\n";
// SimpleFrame* F = frames[i];
//// Eigen::Vector3d v_actual = F->getLinearVelocity();
//// Eigen::Vector3d w_actual = F->getAngularVelocity();
// Eigen::Vector6d v = F->getSpatialVelocity(Frame::World());
// Eigen::Vector3d v_actual = v.tail<3>();
// Eigen::Vector3d w_actual = v.head<3>();
// EXPECT_TRUE( equals(v_total[i], v_actual, tolerance) );
// EXPECT_TRUE( equals(w_total[i], w_actual, tolerance) );
// std::cout << "expected: " << v_total[i].transpose()
// << "\nactual: " << v_actual.transpose() << "\n";
// }
}
int main(int argc, char* argv[])
{
math::seedRand();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>working on test for velocity conversions<commit_after>
/*
* Copyright (c) 2014, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael X. Grey <mxgrey@gatech.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include "dart/dynamics/SimpleFrame.h"
#include "dart/math/Helpers.h"
#include "TestHelpers.h"
using namespace dart;
using namespace dynamics;
void randomize_transforms(std::vector<Eigen::Isometry3d>& tfs)
{
for(size_t i=0; i<tfs.size(); ++i)
{
Eigen::Vector3d v;
for(size_t i=0; i<3; ++i)
v[i] = math::random(-100, 100);
Eigen::Vector3d theta;
for(size_t i=0; i<3; ++i)
theta[i] = math::random(-100, 100);
Eigen::Isometry3d& tf = tfs[i];
tf.setIdentity();
tf.translate(v);
if(theta.norm()>0)
tf.rotate(Eigen::AngleAxisd(theta.norm(), theta.normalized()));
}
}
template<int N>
Eigen::Matrix<double,N,1> random_vec()
{
Eigen::Matrix<double,N,1> v;
for(size_t i=0; i<N; ++i)
v[i] = math::random(-100, 100);
return v;
}
void compute_spatial_velocity(const Eigen::Vector6d& v_parent,
const Eigen::Vector6d& v_relative,
const Eigen::Isometry3d& tf_rel,
Eigen::Vector6d& v_child)
{
v_child = math::AdInvT(tf_rel, v_parent) + v_relative;
}
void compute_velocity(const Eigen::Vector3d& v_parent,
const Eigen::Vector3d& w_parent,
const Eigen::Vector3d& v_rel,
const Eigen::Vector3d& w_rel,
const Eigen::Vector3d& offset,
const Eigen::Isometry3d& tf_parent,
Eigen::Vector3d& v_child,
Eigen::Vector3d& w_child)
{
const Eigen::Matrix3d& R = tf_parent.rotation();
v_child = v_parent + R*v_rel + w_parent.cross(R*offset);
w_child = w_parent + R*w_rel;
}
void compute_acceleration(const Eigen::Vector3d& a_parent,
const Eigen::Vector3d& alpha_parent,
const Eigen::Vector3d& w_parent,
const Eigen::Vector3d& a_rel,
const Eigen::Vector3d& alpha_rel,
const Eigen::Vector3d& v_rel,
const Eigen::Vector3d& offset,
const Eigen::Isometry3d& tf_parent,
Eigen::Vector3d& a_child,
Eigen::Vector3d& alpha_child)
{
const Eigen::Matrix3d& R = tf_parent.rotation();
a_child = a_parent + R*a_rel
+ alpha_parent.cross(R*offset)
+ 2*w_parent.cross(R*v_rel)
+ w_parent.cross(w_parent.cross(R*offset));
alpha_child = alpha_parent + R*alpha_rel + alpha_parent.cross(R*alpha_rel);
}
TEST(FRAMES, FORWARD_KINEMATICS_CHAIN)
{
std::vector<SimpleFrame*> frames;
double tolerance = 1e-8;
SimpleFrame A(Frame::World(), "A");
frames.push_back(&A);
SimpleFrame B(&A, "B");
frames.push_back(&B);
SimpleFrame C(&B, "C");
frames.push_back(&C);
SimpleFrame D(&C, "D");
frames.push_back(&D);
// -- Test Position --------------------------------------------------------
EXPECT_TRUE( equals(D.getTransform().matrix(),
Eigen::Isometry3d::Identity().matrix(),
tolerance));
std::vector<Eigen::Isometry3d> tfs;
tfs.resize(frames.size(), Eigen::Isometry3d::Identity());
randomize_transforms(tfs);
for(size_t i=0; i<frames.size(); ++i)
{
SimpleFrame* F = frames[i];
F->setRelativeTransform(tfs[i]);
}
for(size_t i=0; i<frames.size(); ++i)
{
Frame* F = frames[i];
Eigen::Isometry3d expectation(Eigen::Isometry3d::Identity());
for(size_t j=0; j<=i; ++j)
{
expectation = expectation * tfs[j];
}
Eigen::Isometry3d actual = F->getTransform();
EXPECT_TRUE( equals(actual.matrix(), expectation.matrix(), tolerance));
}
randomize_transforms(tfs);
for(size_t i=0; i<frames.size(); ++i)
{
SimpleFrame* F = frames[i];
F->setRelativeTransform(tfs[i]);
}
Eigen::Isometry3d expectation(Eigen::Isometry3d::Identity());
for(size_t j=0; j<frames.size(); ++j)
expectation = expectation * tfs[j];
EXPECT_TRUE( equals(frames.back()->getTransform().matrix(),
expectation.matrix(),
tolerance) );
// -- Test Velocity --------------------------------------------------------
// Basic forward spatial velocity computation
{ // The brackets are to recycle variable names
std::vector<Eigen::Vector6d> v_rels(frames.size());
std::vector<Eigen::Vector6d> v_total(frames.size());
for(size_t i=0; i<frames.size(); ++i)
{
v_rels[i] = random_vec<6>();
SimpleFrame* F = frames[i];
F->setRelativeSpatialVelocity(v_rels[i]);
}
v_total[0] = v_rels[0];
for(size_t i=1; i<frames.size(); ++i)
{
SimpleFrame* F = frames[i];
compute_spatial_velocity(v_total[i-1], v_rels[i],
F->getRelativeTransform(), v_total[i]);
}
for(size_t i=0; i<frames.size(); ++i)
{
SimpleFrame* F = frames[i];
Eigen::Vector6d v_actual = F->getSpatialVelocity();
EXPECT_TRUE( equals(v_total[i], v_actual) );
}
}
// Testing conversion beteween spatial and classical velocities
// {
// std::vector<Eigen::Vector3d> v_rels(frames.size());
// std::vector<Eigen::Vector3d> w_rels(frames.size());
// std::vector<Eigen::Vector3d> v_total(frames.size());
// std::vector<Eigen::Vector3d> w_total(frames.size());
// for(size_t i=0; i<frames.size(); ++i)
// {
// v_rels[i] = random_vec<3>();
// w_rels[i] = random_vec<3>();
// Eigen::Vector6d spatial_v;
// spatial_v << w_rels[i], v_rels[i];
// SimpleFrame* F = frames[i];
// F->setRelativeSpatialVelocity(spatial_v, F->getParentFrame());
// }
// v_total[0] = v_rels[0];
// w_total[0] = w_rels[0];
// for(size_t i=1; i<frames.size(); ++i)
// {
// SimpleFrame* F = frames[i];
// Eigen::Vector3d offset = F->getRelativeTransform().translation();
// Eigen::Isometry3d tf = frames[i-1]->getTransform();
// compute_velocity(v_total[i-1], w_total[i-1], v_rels[i], w_rels[i],
// offset, tf, v_total[i], w_total[i]);
// }
// for(size_t i=0; i<frames.size(); ++i)
// {
// std::cout << "Trial #" << i << "\n";
// SimpleFrame* F = frames[i];
// // Eigen::Vector3d v_actual = F->getLinearVelocity();
// // Eigen::Vector3d w_actual = F->getAngularVelocity();
// Eigen::Vector6d v = F->getSpatialVelocity(Frame::World());
// Eigen::Vector3d v_actual = v.tail<3>();
// Eigen::Vector3d w_actual = v.head<3>();
// EXPECT_TRUE( equals(v_total[i], v_actual, tolerance) );
// EXPECT_TRUE( equals(w_total[i], w_actual, tolerance) );
// std::cout << "expected: " << v_total[i].transpose()
// << "\nactual: " << v_actual.transpose() << "\n";
// }
// }
}
int main(int argc, char* argv[])
{
math::seedRand();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#include <Eigen/Sparse>
#include <Eigen/SPQRSupport>
#include <Eigen/OrderingMethods>
#include <Eigen/SparseQR>
#include <Eigen/Dense>
#include <iostream>
#include <fstream>
#include <vector>
// declares a column-major sparse matrix type of double
typedef Eigen::SparseMatrix<float> SparseMatrix;
typedef Eigen::Triplet<float> Triplet;
typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMajorMatrixXf;
const float MIN_X = 0;
const float MAX_X = 359.9999;
const float MIN_Y = 30;
const float MAX_Y = 150;
template <typename T>
T clamp(const T& v, const T& min_v, const T& max_v)
{
return v < min_v ? min_v : (v > max_v ? max_v : v);
}
void saveAsBitmap(const Eigen::VectorXf& x, size_t rows, size_t cols, const char* fname)
{
std::ofstream ofs(fname);
ofs << "P2\n" << cols << " " << rows << "\n255\n";
for(size_t rr = 0; rr < rows; rr++) {
for(size_t cc = 0; cc < cols; cc++) {
ofs << clamp<int>((int)x[rr * cols + cc], 0, 255) << " ";
}
ofs << "\n";
}
}
inline
int wrap(int v, int min_v, int max_v)
{
int width = max_v - min_v + 1;
while(v < min_v) v += width;
while(v > max_v) v -= width;
return v;
}
inline
float sqr(float x)
{
return x*x;
}
inline
float cube(float x)
{
return x*x*x;
}
inline
float bspline(float x)
{
if(x < -2) {
return 0;
} else if(x < -1) {
return (cube(x+2)/6.0);
} else if(x < 0) {
return (-3*cube(x+2-1)+3*sqr(x+2-1)+3*(x+2-1)+1)/6;
} else if(x < 1) {
return ((3*cube(x+2-2) - 6*sqr(x+2-2) + 4)/6);
} else if(x < 2) {
return cube(1 - (x + 2 - 3))/6.0;
} else {
return 0;
}
}
float kernel(float x, float width=4)
{
// bspline width is 4
width /= 4;
return bspline(x / width ) / width;
}
inline
size_t grid_index(size_t width, size_t height, size_t grid_x, size_t grid_y)
{
return grid_y * width + grid_x;
}
struct BSpline
{
float grid_dx = 5;
float grid_dy = 5;
float grid_min_x = MIN_Y;
float grid_max_x = MAX_X;
float grid_min_y = MIN_Y;
float grid_max_y = MAX_Y;
size_t x_knots = (grid_max_x - grid_min_x) / grid_dx;
size_t y_knots = (grid_max_y - grid_min_y) / grid_dy;
size_t n_knots = x_knots * y_knots;
SparseMatrix getWeights(const Eigen::MatrixXf& points) const
{
assert(points.cols() >= 2);
std::vector<Triplet> coeffs;
coeffs.reserve(points.size()*5);
for(size_t pp = 0; pp < points.rows(); pp++) {
const auto& pt = points.row(pp);
float c_xbin = x_knots * (pt.x() - grid_min_x)/(grid_max_x - grid_min_x);
float c_ybin = y_knots * (pt.y() - grid_min_y)/(grid_max_y - grid_min_y);
// add weights to adjacent knots
for(int ii = -2; ii <= 2; ii++) {
for(int jj = -2; jj <= 2; jj++) {
int raw_xbin = (int)c_xbin + ii;
int wrapped_xbin = wrap(raw_xbin, 0, x_knots - 1);
int ybin = (int)c_ybin + jj;
if(ybin < 0 || ybin >= y_knots)
continue;
float w = kernel(c_xbin - raw_xbin)*kernel(c_ybin - ybin);
size_t grid_ind = grid_index(x_knots, y_knots, wrapped_xbin, ybin);
coeffs.push_back(Triplet(pp, grid_ind, w));
}
}
}
size_t num_points = points.rows();
SparseMatrix Bmat(num_points, n_knots);
Bmat.setFromTriplets(coeffs.begin(), coeffs.end());
return Bmat;
}
};
Eigen::VectorXf solve(const BSpline& spl, const Eigen::MatrixXf& points)
{
auto Bmat = spl.getWeights(points);
// auto tmp = (RowMajorMatrixXf::Identity(Bmat.rows(), Bmat.rows()) * Bmat);
// for(size_t rr = 0; rr < Bmat.rows(); rr++) {
// RowMajorMatrixXf row = tmp.row(rr);
// Eigen::Map<RowMajorMatrixXf> rmap(row.data(), spl.y_knots, spl.x_knots);
// std::cerr << "\n-------\n" << rmap << "\n-----\n" << std::endl;
// }
// std::cerr << (RowMajorMatrixXf::Identity(Bmat.rows(), Bmat.rows()) * Bmat) << std::endl;
// make it dense :(
auto tmp = (RowMajorMatrixXf::Identity(Bmat.rows(), Bmat.rows()) * Bmat);
Eigen::ColPivHouseholderQR<Eigen::MatrixXf> qr(tmp);
// Right now this doesn't seem to work ...
// Bmat.makeCompressed();
//Eigen::SparseQR<SparseMatrix, Eigen::NaturalOrdering<int>> qr;
//Eigen::SparseQR<SparseMatrix, Eigen::COLAMDOrdering<int>> qr;
//Eigen::SPQR<SparseMatrix> qr;
//qr.compute(Bmat);
//Eigen::SparseLU<SparseMatrix> qr(Bmat);
return qr.solve(points.col(2));
};
Eigen::VectorXf interpolate(const BSpline& spl,
const Eigen::VectorXf& knot_values, const Eigen::MatrixXf& points)
{
auto bmat = spl.getWeights(points);
return bmat * knot_values;
}
void drawPoints(const BSpline& spl, const Eigen::MatrixXf& points, const char* fname)
{
size_t x_bins = spl.x_knots * 10;
size_t y_bins = spl.y_knots * 10;
Eigen::VectorXf raster(x_bins * y_bins);
raster.fill(0);
for(size_t rr = 0; rr < points.rows(); rr++) {
float x = points(rr, 0);
float y = points(rr, 1);
float c_xbin = x_bins * (x - spl.grid_min_x) / (spl.grid_max_x - spl.grid_min_x);
float c_ybin = y_bins * (y - spl.grid_min_y) / (spl.grid_max_y - spl.grid_min_y);
raster[(int)c_xbin + (int)c_ybin * x_bins] = 255;
}
saveAsBitmap(raster, y_bins, x_bins, fname);
}
int main(int argc, char** argv)
{
size_t num_points = 30;
Eigen::MatrixXf points = Eigen::MatrixXf::Random(num_points, 3); // x, y, value
for(size_t rr = 0; rr < points.rows(); rr++) {
points(rr, 0) = MIN_X + std::abs(points(rr, 0)) * (MAX_X - MIN_X);
points(rr, 1) = MIN_Y + std::abs(points(rr, 1)) * (MAX_Y - MIN_Y);
points(rr, 2) = 1;
}
BSpline spl;
drawPoints(spl, points, "orig.pgm");
// Matrix maps from knots to known points
// v = Bx
//
// x is the value of the knots, B is the weights of values at each knot s.t.
// the values reflect the positions of the input points and v is the value
// at the input points
Eigen::VectorXf knots = solve(spl, points);
// Use the known knots to solve for the actual values at each knot location
Eigen::MatrixXf grid_points(spl.x_knots*spl.y_knots, 2);
for(size_t yy = 0; yy < spl.y_knots; yy++) {
for(size_t xx = 0; xx < spl.x_knots; xx++) {
grid_points(yy * spl.x_knots + xx, 0) = spl.grid_min_x + xx * spl.grid_dx;
grid_points(yy * spl.x_knots + xx, 1) = spl.grid_min_y + yy * spl.grid_dy;
}
}
Eigen::VectorXf interpolated = interpolate(spl, knots, grid_points);
//Eigen::VectorXf interpolated = interpolate(spl, knots, points);
saveAsBitmap(255*interpolated, spl.y_knots, spl.x_knots, "smoothed.pgm");
return 0;
}
<commit_msg>don't work<commit_after>#include <Eigen/Sparse>
#include <Eigen/SPQRSupport>
#include <Eigen/OrderingMethods>
#include <Eigen/SparseQR>
#include <Eigen/Dense>
#include <iostream>
#include <fstream>
#include <vector>
// declares a column-major sparse matrix type of double
typedef Eigen::SparseMatrix<float> SparseMatrix;
typedef Eigen::Triplet<float> Triplet;
typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMajorMatrixXf;
const float GRID_DX = 0.1;
const float GRID_DY = 1;
const float MIN_X = 0;
const float MAX_X = 359.9999;
const float MIN_Y = 30;
const float MAX_Y = 150;
template <typename T>
T clamp(const T& v, const T& min_v, const T& max_v)
{
return v < min_v ? min_v : (v > max_v ? max_v : v);
}
void saveAsBitmap(const Eigen::VectorXf& x, size_t rows, size_t cols, const char* fname)
{
std::ofstream ofs(fname);
ofs << "P2\n" << cols << " " << rows << "\n255\n";
for(size_t rr = 0; rr < rows; rr++) {
for(size_t cc = 0; cc < cols; cc++) {
ofs << clamp<int>((int)x[rr * cols + cc], 0, 255) << " ";
}
ofs << "\n";
}
}
inline
int wrap(int v, int min_v, int max_v)
{
int width = max_v - min_v + 1;
while(v < min_v) v += width;
while(v > max_v) v -= width;
return v;
}
inline
float sqr(float x)
{
return x*x;
}
inline
float cube(float x)
{
return x*x*x;
}
inline
float bspline(float x)
{
if(x < -2) {
return 0;
} else if(x < -1) {
return (cube(x+2)/6.0);
} else if(x < 0) {
return (-3*cube(x+2-1)+3*sqr(x+2-1)+3*(x+2-1)+1)/6;
} else if(x < 1) {
return ((3*cube(x+2-2) - 6*sqr(x+2-2) + 4)/6);
} else if(x < 2) {
return cube(1 - (x + 2 - 3))/6.0;
} else {
return 0;
}
}
float kernel(float x, float width=4)
{
// bspline width is 4
width /= 4;
return bspline(x / width ) / width;
}
inline
size_t grid_index(size_t width, size_t height, size_t grid_x, size_t grid_y)
{
return grid_y * width + grid_x;
}
struct BSpline
{
float grid_dx = GRID_DX;
float grid_dy = GRID_DY;
float grid_min_x = MIN_Y;
float grid_max_x = MAX_X;
float grid_min_y = MIN_Y;
float grid_max_y = MAX_Y;
size_t x_knots = (grid_max_x - grid_min_x) / grid_dx;
size_t y_knots = (grid_max_y - grid_min_y) / grid_dy;
size_t n_knots = x_knots * y_knots;
SparseMatrix getWeights(const Eigen::MatrixXf& points) const
{
assert(points.cols() >= 2);
std::vector<Triplet> coeffs;
coeffs.reserve(points.size()*5);
for(size_t pp = 0; pp < points.rows(); pp++) {
const auto& pt = points.row(pp);
float c_xbin = x_knots * (pt.x() - grid_min_x)/(grid_max_x - grid_min_x);
float c_ybin = y_knots * (pt.y() - grid_min_y)/(grid_max_y - grid_min_y);
// add weights to adjacent knots
for(int ii = -2; ii <= 2; ii++) {
for(int jj = -2; jj <= 2; jj++) {
int raw_xbin = (int)c_xbin + ii;
int wrapped_xbin = wrap(raw_xbin, 0, x_knots - 1);
int ybin = (int)c_ybin + jj;
if(ybin < 0 || ybin >= y_knots)
continue;
float w = kernel(c_xbin - raw_xbin)*kernel(c_ybin - ybin);
size_t grid_ind = grid_index(x_knots, y_knots, wrapped_xbin, ybin);
coeffs.push_back(Triplet(pp, grid_ind, w));
}
}
}
size_t num_points = points.rows();
SparseMatrix Bmat(num_points, n_knots);
Bmat.setFromTriplets(coeffs.begin(), coeffs.end());
return Bmat;
}
};
Eigen::VectorXf solve(const BSpline& spl, const Eigen::MatrixXf& points)
{
std::cerr << "Filling Weights" << std::endl;
auto Bmat = spl.getWeights(points);
Bmat.makeCompressed();
std::cerr << "Done" << std::endl;
//Eigen::SparseQR<SparseMatrix, Eigen::NaturalOrdering<int>> qr;
std::cerr << "QR" << std::endl;
Eigen::SparseQR<SparseMatrix, Eigen::COLAMDOrdering<int>> qr(Bmat);
std::cerr << "Done" << std::endl;
//Eigen::SPQR<SparseMatrix> qr;
//qr.compute(Bmat);
//Eigen::SparseLU<SparseMatrix> qr(Bmat);
std::cerr << "Solving: "<< std::endl;
Eigen::VectorXf sol = qr.solve(points.col(2));
std::cerr << "Done" << std::endl;
return sol;
};
Eigen::VectorXf interpolate(const BSpline& spl,
const Eigen::VectorXf& knot_values, const Eigen::MatrixXf& points)
{
auto bmat = spl.getWeights(points);
return bmat * knot_values;
}
void drawPoints(const BSpline& spl, const Eigen::MatrixXf& points, const char* fname)
{
size_t x_bins = spl.x_knots;
size_t y_bins = spl.y_knots;
Eigen::VectorXf raster(x_bins * y_bins);
raster.fill(0);
for(size_t rr = 0; rr < points.rows(); rr++) {
float x = points(rr, 0);
float y = points(rr, 1);
float c_xbin = x_bins * (x - spl.grid_min_x) / (spl.grid_max_x - spl.grid_min_x);
float c_ybin = y_bins * (y - spl.grid_min_y) / (spl.grid_max_y - spl.grid_min_y);
raster[(int)c_xbin + (int)c_ybin * x_bins] = 255;
}
saveAsBitmap(raster, y_bins, x_bins, fname);
}
int main(int argc, char** argv)
{
size_t num_points = 30;
Eigen::MatrixXf points = Eigen::MatrixXf::Random(num_points, 3); // x, y, value
for(size_t rr = 0; rr < points.rows(); rr++) {
points(rr, 0) = MIN_X + std::abs(points(rr, 0)) * (MAX_X - MIN_X);
points(rr, 1) = MIN_Y + std::abs(points(rr, 1)) * (MAX_Y - MIN_Y);
points(rr, 2) = 1;
}
BSpline spl;
drawPoints(spl, points, "orig.pgm");
// Matrix maps from knots to known points
// v = Bx
//
// x is the value of the knots, B is the weights of values at each knot s.t.
// the values reflect the positions of the input points and v is the value
// at the input points
Eigen::VectorXf knots = solve(spl, points);
// Use the known knots to solve for the actual values at each knot location
Eigen::MatrixXf grid_points(spl.x_knots*spl.y_knots, 2);
for(size_t yy = 0; yy < spl.y_knots; yy++) {
for(size_t xx = 0; xx < spl.x_knots; xx++) {
grid_points(yy * spl.x_knots + xx, 0) = spl.grid_min_x + xx * spl.grid_dx;
grid_points(yy * spl.x_knots + xx, 1) = spl.grid_min_y + yy * spl.grid_dy;
}
}
Eigen::VectorXf interpolated = interpolate(spl, knots, grid_points);
//Eigen::VectorXf interpolated = interpolate(spl, knots, points);
saveAsBitmap(255*interpolated, spl.y_knots, spl.x_knots, "smoothed.pgm");
return 0;
}
<|endoftext|>
|
<commit_before>
#include "numerics/unbounded_arrays.hpp"
#include "gtest/gtest.h"
namespace principia {
namespace numerics {
class UnboundedArraysTest : public ::testing::Test {
protected:
UnboundedArraysTest()
: v3_({10, 31, -47}),
v4_({-3, -3, 1, 4}),
l4_({1, 2, 3, 5, 8, 13, 21, 34, 55, 89}) {}
UnboundedVector<double> v3_;
UnboundedVector<double> v4_;
UnboundedLowerTriangularMatrix<double> l4_;
};
TEST_F(UnboundedArraysTest, Assignment) {
UnboundedVector<double> u2({1, 2});
UnboundedVector<double> v2 = {{1, 2}};
UnboundedVector<double> w2(2);
w2 = {{1, 2}};
EXPECT_EQ(u2, v2);
EXPECT_EQ(u2, w2);
UnboundedLowerTriangularMatrix<double> l3({1, 2, 3, 4, 5, 6});
UnboundedLowerTriangularMatrix<double> m3 = {{1, 2, 3, 4, 5, 6}};
UnboundedLowerTriangularMatrix<double> n3 = {{0, 0, 0, 0, 0, 0}};
UnboundedLowerTriangularMatrix<double> o3(3);
EXPECT_EQ(o3, n3);
n3 = {{1, 2, 3, 4, 5, 6}};
EXPECT_EQ(l3, m3);
EXPECT_EQ(l3, n3);
}
TEST_F(UnboundedArraysTest, VectorIndexing) {
EXPECT_EQ(31, v3_[1]);
v3_[2] = -666;
EXPECT_EQ(-666, v3_[2]);
}
TEST_F(UnboundedArraysTest, LowerTriangularMatrixIndexing) {
EXPECT_EQ(10, l4_.dimension());
EXPECT_EQ(1, l4_[0][0]);
EXPECT_EQ(2, l4_[1][0]);
EXPECT_EQ(3, l4_[1][1]);
EXPECT_EQ(5, l4_[2][0]);
EXPECT_EQ(8, l4_[2][1]);
EXPECT_EQ(13, l4_[2][2]);
EXPECT_EQ(21, l4_[3][0]);
EXPECT_EQ(34, l4_[3][1]);
EXPECT_EQ(55, l4_[3][2]);
EXPECT_EQ(89, l4_[3][3]);
l4_[3][1] = -666;
EXPECT_EQ(-666, l4_[3][1]);
}
TEST_F(UnboundedArraysTest, Extend) {
UnboundedVector<double> u2({1, 2});
UnboundedVector<double> u4({1, 2, 3, 4});
u2.Extend({3, 4});
EXPECT_EQ(u2, u4);
UnboundedLowerTriangularMatrix<double> l3({1, 2, 3, 4, 5, 6});
UnboundedLowerTriangularMatrix<double> l4({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
l3.Extend({7, 8, 9, 10});
EXPECT_EQ(l3, l4);
}
} // namespace numerics
} // namespace principia
<commit_msg>Revert "Readying for review."<commit_after>
#include "numerics/unbounded_arrays.hpp"
#include "gtest/gtest.h"
namespace principia {
namespace numerics {
class UnboundedArraysTest : public ::testing::Test {
protected:
UnboundedArraysTest()
: v3_({10, 31, -47}),
v4_({-3, -3, 1, 4}),
l4_({ 1,
2, 3,
5, 8, 13,
21, 34, 55, 89}) {}
UnboundedVector<double> v3_;
UnboundedVector<double> v4_;
UnboundedLowerTriangularMatrix<double> l4_;
};
TEST_F(UnboundedArraysTest, Assignment) {
UnboundedVector<double> u2({1, 2});
UnboundedVector<double> v2 = {{1, 2}};
UnboundedVector<double> w2(2);
w2 = {{1, 2}};
EXPECT_EQ(u2, v2);
EXPECT_EQ(u2, w2);
UnboundedLowerTriangularMatrix<double> l3({1,
2, 3,
4, 5, 6});
UnboundedLowerTriangularMatrix<double> m3 = {{1,
2, 3,
4, 5, 6}};
UnboundedLowerTriangularMatrix<double> n3 = {{0,
0, 0,
0, 0, 0}};
UnboundedLowerTriangularMatrix<double> o3(3);
EXPECT_EQ(o3, n3);
n3 = {{1,
2, 3,
4, 5, 6}};
EXPECT_EQ(l3, m3);
EXPECT_EQ(l3, n3);
}
TEST_F(UnboundedArraysTest, VectorIndexing) {
EXPECT_EQ(31, v3_[1]);
v3_[2] = -666;
EXPECT_EQ(-666, v3_[2]);
}
TEST_F(UnboundedArraysTest, LowerTriangularMatrixIndexing) {
EXPECT_EQ(10, l4_.dimension());
EXPECT_EQ(1, l4_[0][0]);
EXPECT_EQ(2, l4_[1][0]);
EXPECT_EQ(3, l4_[1][1]);
EXPECT_EQ(5, l4_[2][0]);
EXPECT_EQ(8, l4_[2][1]);
EXPECT_EQ(13, l4_[2][2]);
EXPECT_EQ(21, l4_[3][0]);
EXPECT_EQ(34, l4_[3][1]);
EXPECT_EQ(55, l4_[3][2]);
EXPECT_EQ(89, l4_[3][3]);
l4_[3][1] = -666;
EXPECT_EQ(-666, l4_[3][1]);
}
TEST_F(UnboundedArraysTest, Extend) {
UnboundedVector<double> u2({1, 2});
UnboundedVector<double> u4({1, 2, 3, 4});
u2.Extend({3, 4});
EXPECT_EQ(u2, u4);
UnboundedLowerTriangularMatrix<double> l3({1,
2, 3,
4, 5, 6});
UnboundedLowerTriangularMatrix<double> l4({1,
2, 3,
4, 5, 6,
7, 8, 9, 10});
l3.Extend({7, 8, 9, 10});
EXPECT_EQ(l3, l4);
}
} // namespace numerics
} // namespace principia
<|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/chromeos/dbus/power_manager_client.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/format_macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/time.h"
#include "base/timer.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_proxy.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
PowerSupplyStatus::PowerSupplyStatus()
: line_power_on(false),
battery_is_present(false),
battery_is_full(false),
battery_seconds_to_empty(0),
battery_seconds_to_full(0),
battery_percentage(0) {
}
const std::string& PowerSupplyStatus::ToString() const {
static std::string result = "";
base::StringAppendF(&result,
"line_power_on = %s ",
line_power_on ? "true" : "false");
base::StringAppendF(&result,
"battery_is_present = %s ",
battery_is_present ? "true" : "false");
base::StringAppendF(&result,
"battery_is_full = %s ",
battery_is_full ? "true" : "false");
base::StringAppendF(&result,
"battery_percentage = %f ",
battery_percentage);
base::StringAppendF(&result,
"battery_seconds_to_empty = %"PRId64" ",
battery_seconds_to_empty);
base::StringAppendF(&result,
"battery_seconds_to_full = %"PRId64" ",
battery_seconds_to_full);
return result;
}
// The PowerManagerClient implementation used in production.
class PowerManagerClientImpl : public PowerManagerClient {
public:
explicit PowerManagerClientImpl(dbus::Bus* bus)
: power_manager_proxy_(NULL),
weak_ptr_factory_(this) {
power_manager_proxy_ = bus->GetObjectProxy(
power_manager::kPowerManagerServiceName,
power_manager::kPowerManagerServicePath);
// Monitor the D-Bus signal for brightness changes. Only the power
// manager knows the actual brightness level. We don't cache the
// brightness level in Chrome as it'll make things less reliable.
power_manager_proxy_->ConnectToSignal(
power_manager::kPowerManagerInterface,
power_manager::kBrightnessChangedSignal,
base::Bind(&PowerManagerClientImpl::BrightnessChangedReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&PowerManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
// Monitor the D-Bus signal for power supply polling signals.
power_manager_proxy_->ConnectToSignal(
power_manager::kPowerManagerInterface,
power_manager::kPowerSupplyPollSignal,
base::Bind(&PowerManagerClientImpl::PowerSupplyPollReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&PowerManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
}
virtual ~PowerManagerClientImpl() {
}
// PowerManagerClient override.
virtual void AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
// PowerManagerClient override.
virtual void RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
// PowerManagerClient override.
virtual void DecreaseScreenBrightness(bool allow_off) {
dbus::MethodCall method_call(
power_manager::kPowerManagerInterface,
power_manager::kDecreaseScreenBrightness);
dbus::MessageWriter writer(&method_call);
writer.AppendBool(allow_off);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&PowerManagerClientImpl::OnDecreaseScreenBrightness,
weak_ptr_factory_.GetWeakPtr()));
}
// PowerManagerClient override.
virtual void IncreaseScreenBrightness() {
dbus::MethodCall method_call(
power_manager::kPowerManagerInterface,
power_manager::kIncreaseScreenBrightness);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&PowerManagerClientImpl::OnIncreaseScreenBrightness,
weak_ptr_factory_.GetWeakPtr()));
}
// PowerManagerClient override.
virtual void RequestStatusUpdate() OVERRIDE {
dbus::MethodCall method_call(power_manager::kPowerManagerInterface,
power_manager::kGetAllPropertiesMethod);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&PowerManagerClientImpl::OnGetAllPropertiesMethod,
weak_ptr_factory_.GetWeakPtr()));
}
// Requests restart of the system.
virtual void RequestRestart() OVERRIDE {
dbus::MethodCall method_call(power_manager::kPowerManagerInterface,
power_manager::kRequestRestartMethod);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
};
// Requests shutdown of the system.
virtual void RequestShutdown() OVERRIDE {
dbus::MethodCall method_call(power_manager::kPowerManagerInterface,
power_manager::kRequestShutdownMethod);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
private:
// Called when a dbus signal is initially connected.
void SignalConnected(const std::string& interface_name,
const std::string& signal_name,
bool success) {
LOG_IF(WARNING, !success) << "Failed to connect to signal "
<< signal_name << ".";
}
// Called when a brightness change signal is received.
void BrightnessChangedReceived(dbus::Signal* signal) {
dbus::MessageReader reader(signal);
int32 brightness_level = 0;
bool user_initiated = 0;
if (!(reader.PopInt32(&brightness_level) &&
reader.PopBool(&user_initiated))) {
LOG(ERROR) << "Brightness changed signal had incorrect parameters: "
<< signal->ToString();
return;
}
VLOG(1) << "Brightness changed to " << brightness_level
<< ": user initiated " << user_initiated;
FOR_EACH_OBSERVER(Observer, observers_,
BrightnessChanged(brightness_level, user_initiated));
}
// Called when a response for DecreaseScreenBrightness() is received.
void OnDecreaseScreenBrightness(dbus::Response* response) {
if (!response) {
LOG(ERROR) << "Failed to decrease screen brightness";
return;
}
VLOG(1) << "screen brightness increased: " << response->ToString();
}
// Called when a response for IncreaseScreenBrightness() is received.
void OnIncreaseScreenBrightness(dbus::Response* response) {
if (!response) {
LOG(ERROR) << "Failed to increase screen brightness";
return;
}
VLOG(1) << "screen brightness increased: " << response->ToString();
}
// Called when a power supply polling signal is received.
void PowerSupplyPollReceived(dbus::Signal* unused_signal) {
VLOG(1) << "Received power supply poll signal.";
RequestStatusUpdate();
}
// Called when GetAllPropertiesMethod call is complete.
void OnGetAllPropertiesMethod(dbus::Response* response) {
if (!response) {
LOG(ERROR) << "Error calling " << power_manager::kGetAllPropertiesMethod;
return;
}
dbus::MessageReader reader(response);
PowerSupplyStatus status;
double unused_battery_voltage = 0.0;
double unused_battery_energy = 0.0;
double unused_battery_energy_rate = 0.0;
if (!reader.PopBool(&status.line_power_on) ||
!reader.PopDouble(&unused_battery_energy) ||
!reader.PopDouble(&unused_battery_energy_rate) ||
!reader.PopDouble(&unused_battery_voltage) ||
!reader.PopInt64(&status.battery_seconds_to_empty) ||
!reader.PopInt64(&status.battery_seconds_to_full) ||
!reader.PopDouble(&status.battery_percentage) ||
!reader.PopBool(&status.battery_is_present) ||
!reader.PopBool(&status.battery_is_full)) {
LOG(ERROR) << "Error reading response from powerd: "
<< response->ToString();
return;
}
VLOG(1) << "Power status: " << status.ToString();
FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(status));
}
dbus::ObjectProxy* power_manager_proxy_;
ObserverList<Observer> observers_;
base::WeakPtrFactory<PowerManagerClientImpl> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(PowerManagerClientImpl);
};
// The PowerManagerClient implementation used on Linux desktop,
// which does nothing.
class PowerManagerClientStubImpl : public PowerManagerClient {
public:
PowerManagerClientStubImpl()
: discharging_(true),
battery_percentage_(80),
pause_count_(0) {
}
virtual ~PowerManagerClientStubImpl() {}
// PowerManagerClient override.
virtual void AddObserver(Observer* observer) OVERRIDE {
observers_.AddObserver(observer);
}
// PowerManagerClient override.
virtual void RemoveObserver(Observer* observer) OVERRIDE {
observers_.RemoveObserver(observer);
}
// PowerManagerClient override.
virtual void DecreaseScreenBrightness(bool allow_off) OVERRIDE {
VLOG(1) << "Requested to descrease screen brightness";
}
// PowerManagerClient override.
virtual void IncreaseScreenBrightness() OVERRIDE {
VLOG(1) << "Requested to increase screen brightness";
}
virtual void RequestStatusUpdate() OVERRIDE {
if (!timer_.IsRunning()) {
timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(100),
this,
&PowerManagerClientStubImpl::Update);
} else {
timer_.Stop();
}
}
virtual void RequestRestart() OVERRIDE {}
virtual void RequestShutdown() OVERRIDE {}
private:
void Update() {
// We pause at 0 and 100% so that it's easier to check those conditions.
if (pause_count_ > 1) {
pause_count_--;
return;
}
if (battery_percentage_ == 0 || battery_percentage_ == 100) {
if (pause_count_) {
pause_count_ = 0;
discharging_ = !discharging_;
} else {
pause_count_ = 20;
return;
}
}
battery_percentage_ += (discharging_ ? -1 : 1);
PowerSupplyStatus status;
status.line_power_on = !discharging_;
status.battery_is_present = true;
status.battery_percentage = battery_percentage_;
status.battery_seconds_to_empty =
std::max(1, battery_percentage_ * 180 / 100);
status.battery_seconds_to_full =
std::max(static_cast<int64>(1), 180 - status.battery_seconds_to_empty);
FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(status));
}
bool discharging_;
int battery_percentage_;
int pause_count_;
ObserverList<Observer> observers_;
base::RepeatingTimer<PowerManagerClientStubImpl> timer_;
};
PowerManagerClient::PowerManagerClient() {
}
PowerManagerClient::~PowerManagerClient() {
}
PowerManagerClient* PowerManagerClient::Create(dbus::Bus* bus) {
if (system::runtime_environment::IsRunningOnChromeOS()) {
return new PowerManagerClientImpl(bus);
} else {
return new PowerManagerClientStubImpl();
}
}
} // namespace chromeos
<commit_msg>Increased battery time to empty sent by power manager client stub implementation.<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/chromeos/dbus/power_manager_client.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/format_macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/time.h"
#include "base/timer.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_proxy.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
PowerSupplyStatus::PowerSupplyStatus()
: line_power_on(false),
battery_is_present(false),
battery_is_full(false),
battery_seconds_to_empty(0),
battery_seconds_to_full(0),
battery_percentage(0) {
}
const std::string& PowerSupplyStatus::ToString() const {
static std::string result = "";
base::StringAppendF(&result,
"line_power_on = %s ",
line_power_on ? "true" : "false");
base::StringAppendF(&result,
"battery_is_present = %s ",
battery_is_present ? "true" : "false");
base::StringAppendF(&result,
"battery_is_full = %s ",
battery_is_full ? "true" : "false");
base::StringAppendF(&result,
"battery_percentage = %f ",
battery_percentage);
base::StringAppendF(&result,
"battery_seconds_to_empty = %"PRId64" ",
battery_seconds_to_empty);
base::StringAppendF(&result,
"battery_seconds_to_full = %"PRId64" ",
battery_seconds_to_full);
return result;
}
// The PowerManagerClient implementation used in production.
class PowerManagerClientImpl : public PowerManagerClient {
public:
explicit PowerManagerClientImpl(dbus::Bus* bus)
: power_manager_proxy_(NULL),
weak_ptr_factory_(this) {
power_manager_proxy_ = bus->GetObjectProxy(
power_manager::kPowerManagerServiceName,
power_manager::kPowerManagerServicePath);
// Monitor the D-Bus signal for brightness changes. Only the power
// manager knows the actual brightness level. We don't cache the
// brightness level in Chrome as it'll make things less reliable.
power_manager_proxy_->ConnectToSignal(
power_manager::kPowerManagerInterface,
power_manager::kBrightnessChangedSignal,
base::Bind(&PowerManagerClientImpl::BrightnessChangedReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&PowerManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
// Monitor the D-Bus signal for power supply polling signals.
power_manager_proxy_->ConnectToSignal(
power_manager::kPowerManagerInterface,
power_manager::kPowerSupplyPollSignal,
base::Bind(&PowerManagerClientImpl::PowerSupplyPollReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&PowerManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
}
virtual ~PowerManagerClientImpl() {
}
// PowerManagerClient override.
virtual void AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
// PowerManagerClient override.
virtual void RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
// PowerManagerClient override.
virtual void DecreaseScreenBrightness(bool allow_off) {
dbus::MethodCall method_call(
power_manager::kPowerManagerInterface,
power_manager::kDecreaseScreenBrightness);
dbus::MessageWriter writer(&method_call);
writer.AppendBool(allow_off);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&PowerManagerClientImpl::OnDecreaseScreenBrightness,
weak_ptr_factory_.GetWeakPtr()));
}
// PowerManagerClient override.
virtual void IncreaseScreenBrightness() {
dbus::MethodCall method_call(
power_manager::kPowerManagerInterface,
power_manager::kIncreaseScreenBrightness);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&PowerManagerClientImpl::OnIncreaseScreenBrightness,
weak_ptr_factory_.GetWeakPtr()));
}
// PowerManagerClient override.
virtual void RequestStatusUpdate() OVERRIDE {
dbus::MethodCall method_call(power_manager::kPowerManagerInterface,
power_manager::kGetAllPropertiesMethod);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&PowerManagerClientImpl::OnGetAllPropertiesMethod,
weak_ptr_factory_.GetWeakPtr()));
}
// Requests restart of the system.
virtual void RequestRestart() OVERRIDE {
dbus::MethodCall method_call(power_manager::kPowerManagerInterface,
power_manager::kRequestRestartMethod);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
};
// Requests shutdown of the system.
virtual void RequestShutdown() OVERRIDE {
dbus::MethodCall method_call(power_manager::kPowerManagerInterface,
power_manager::kRequestShutdownMethod);
power_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
private:
// Called when a dbus signal is initially connected.
void SignalConnected(const std::string& interface_name,
const std::string& signal_name,
bool success) {
LOG_IF(WARNING, !success) << "Failed to connect to signal "
<< signal_name << ".";
}
// Called when a brightness change signal is received.
void BrightnessChangedReceived(dbus::Signal* signal) {
dbus::MessageReader reader(signal);
int32 brightness_level = 0;
bool user_initiated = 0;
if (!(reader.PopInt32(&brightness_level) &&
reader.PopBool(&user_initiated))) {
LOG(ERROR) << "Brightness changed signal had incorrect parameters: "
<< signal->ToString();
return;
}
VLOG(1) << "Brightness changed to " << brightness_level
<< ": user initiated " << user_initiated;
FOR_EACH_OBSERVER(Observer, observers_,
BrightnessChanged(brightness_level, user_initiated));
}
// Called when a response for DecreaseScreenBrightness() is received.
void OnDecreaseScreenBrightness(dbus::Response* response) {
if (!response) {
LOG(ERROR) << "Failed to decrease screen brightness";
return;
}
VLOG(1) << "screen brightness increased: " << response->ToString();
}
// Called when a response for IncreaseScreenBrightness() is received.
void OnIncreaseScreenBrightness(dbus::Response* response) {
if (!response) {
LOG(ERROR) << "Failed to increase screen brightness";
return;
}
VLOG(1) << "screen brightness increased: " << response->ToString();
}
// Called when a power supply polling signal is received.
void PowerSupplyPollReceived(dbus::Signal* unused_signal) {
VLOG(1) << "Received power supply poll signal.";
RequestStatusUpdate();
}
// Called when GetAllPropertiesMethod call is complete.
void OnGetAllPropertiesMethod(dbus::Response* response) {
if (!response) {
LOG(ERROR) << "Error calling " << power_manager::kGetAllPropertiesMethod;
return;
}
dbus::MessageReader reader(response);
PowerSupplyStatus status;
double unused_battery_voltage = 0.0;
double unused_battery_energy = 0.0;
double unused_battery_energy_rate = 0.0;
if (!reader.PopBool(&status.line_power_on) ||
!reader.PopDouble(&unused_battery_energy) ||
!reader.PopDouble(&unused_battery_energy_rate) ||
!reader.PopDouble(&unused_battery_voltage) ||
!reader.PopInt64(&status.battery_seconds_to_empty) ||
!reader.PopInt64(&status.battery_seconds_to_full) ||
!reader.PopDouble(&status.battery_percentage) ||
!reader.PopBool(&status.battery_is_present) ||
!reader.PopBool(&status.battery_is_full)) {
LOG(ERROR) << "Error reading response from powerd: "
<< response->ToString();
return;
}
VLOG(1) << "Power status: " << status.ToString();
FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(status));
}
dbus::ObjectProxy* power_manager_proxy_;
ObserverList<Observer> observers_;
base::WeakPtrFactory<PowerManagerClientImpl> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(PowerManagerClientImpl);
};
// The PowerManagerClient implementation used on Linux desktop,
// which does nothing.
class PowerManagerClientStubImpl : public PowerManagerClient {
public:
PowerManagerClientStubImpl()
: discharging_(true),
battery_percentage_(80),
pause_count_(0) {
}
virtual ~PowerManagerClientStubImpl() {}
// PowerManagerClient override.
virtual void AddObserver(Observer* observer) OVERRIDE {
observers_.AddObserver(observer);
}
// PowerManagerClient override.
virtual void RemoveObserver(Observer* observer) OVERRIDE {
observers_.RemoveObserver(observer);
}
// PowerManagerClient override.
virtual void DecreaseScreenBrightness(bool allow_off) OVERRIDE {
VLOG(1) << "Requested to descrease screen brightness";
}
// PowerManagerClient override.
virtual void IncreaseScreenBrightness() OVERRIDE {
VLOG(1) << "Requested to increase screen brightness";
}
virtual void RequestStatusUpdate() OVERRIDE {
if (!timer_.IsRunning()) {
timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(1000),
this,
&PowerManagerClientStubImpl::Update);
} else {
timer_.Stop();
}
}
virtual void RequestRestart() OVERRIDE {}
virtual void RequestShutdown() OVERRIDE {}
private:
void Update() {
// We pause at 0 and 100% so that it's easier to check those conditions.
if (pause_count_ > 1) {
pause_count_--;
return;
}
if (battery_percentage_ == 0 || battery_percentage_ == 100) {
if (pause_count_) {
pause_count_ = 0;
discharging_ = !discharging_;
} else {
// Pause twice (i.e. skip updating the menu), including the current
// call to this function.
pause_count_ = 2;
return;
}
}
battery_percentage_ += (discharging_ ? -1 : 1);
const int kSecondsToEmptyFullBattery(3 * 60 * 60); // 3 hours.
PowerSupplyStatus status;
status.line_power_on = !discharging_;
status.battery_is_present = true;
status.battery_percentage = battery_percentage_;
status.battery_seconds_to_empty =
std::max(1, battery_percentage_ * kSecondsToEmptyFullBattery / 100);
status.battery_seconds_to_full =
std::max(static_cast<int64>(1),
kSecondsToEmptyFullBattery - status.battery_seconds_to_empty);
FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(status));
}
bool discharging_;
int battery_percentage_;
int pause_count_;
ObserverList<Observer> observers_;
base::RepeatingTimer<PowerManagerClientStubImpl> timer_;
};
PowerManagerClient::PowerManagerClient() {
}
PowerManagerClient::~PowerManagerClient() {
}
PowerManagerClient* PowerManagerClient::Create(dbus::Bus* bus) {
if (system::runtime_environment::IsRunningOnChromeOS()) {
return new PowerManagerClientImpl(bus);
} else {
return new PowerManagerClientStubImpl();
}
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>//===--- Errors.cpp - Error reporting utilities ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Utilities for reporting errors to stderr, system console, and crash logs.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include <stdarg.h>
#include "swift/Runtime/Debug.h"
#include "swift/Runtime/Mutex.h"
#include "swift/Basic/Demangle.h"
#include <cxxabi.h>
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
// execinfo.h is not available on Android. Checks in this file ensure that
// fatalError behaves as expected, but without stack traces.
#include <execinfo.h>
#endif
#ifdef __APPLE__
#include <asl.h>
#endif
namespace FatalErrorFlags {
enum: uint32_t {
ReportBacktrace = 1 << 0
};
} // end namespace FatalErrorFlags
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
LLVM_ATTRIBUTE_ALWAYS_INLINE
static bool
isIdentifier(char c)
{
return isalnum(c) || c == '_' || c == '$';
}
static bool
demangledLinePrefix(std::string line, std::string prefix,
std::string &out,
bool (*demangle)(std::string, std::string &))
{
int symbolStart = -1;
int symbolEnd = -1;
for (size_t i = 0; i < line.size(); i++) {
char c = line[i];
bool hasBegun = symbolStart != -1;
bool isIdentifierChar = isIdentifier(c);
bool isEndOfSymbol = hasBegun && !isIdentifierChar;
bool isEndOfLine = i == line.size() - 1;
if (isEndOfLine || isEndOfSymbol) {
symbolEnd = i;
break;
}
bool canFindPrefix = (line.size() - 2) - i > prefix.size();
if (!hasBegun && canFindPrefix && !isIdentifierChar &&
line.substr(i + 1, prefix.size()) == prefix) {
symbolStart = i + 1;
continue;
}
}
if (symbolStart == -1 || symbolEnd == -1) {
out = line;
return false;
} else {
auto symbol = line.substr(symbolStart, symbolEnd - symbolStart);
std::string demangled;
bool success = demangle(symbol, demangled);
if (success) {
line.replace(symbolStart, symbolEnd - symbolStart, demangled);
}
out = line;
return success;
}
}
static std::string
demangledLine(std::string line) {
std::string res;
bool success = false;
auto cppPrefix = "_Z"; // not sure how to check for DARWIN's __Z here.
success = demangledLinePrefix(line, cppPrefix, res,
[](std::string symbol, std::string &out) {
int status;
auto demangled = abi::__cxa_demangle(symbol.c_str(), 0, 0, &status);
if (demangled == NULL || status != 0) {
out = symbol;
return false;
} else {
out = demangled;
free(demangled);
return true;
}
});
if (success) return res;
success = demangledLinePrefix(line, "_T", res,
[](std::string symbol, std::string &out) {
out = swift::Demangle::demangleSymbolAsString(symbol);
return true;
});
if (success) return res;
return line;
}
const int STACK_DEPTH = 128;
static char **
reportBacktrace(int *count)
{
void **addrs = (void **)malloc(sizeof(void *) * STACK_DEPTH);
if (addrs == NULL) {
if (count) *count = 0;
return NULL;
}
int symbolCount = backtrace(addrs, STACK_DEPTH);
if (count) *count = symbolCount;
char **symbols = backtrace_symbols(addrs, symbolCount);
free(addrs);
if (symbols == NULL) {
if (count) *count = 0;
return NULL;
}
return symbols;
}
#endif
#ifdef SWIFT_HAVE_CRASHREPORTERCLIENT
#include <malloc/malloc.h>
// Instead of linking to CrashReporterClient.a (because it complicates the
// build system), define the only symbol from that static archive ourselves.
//
// The layout of this struct is CrashReporter ABI, so there are no ABI concerns
// here.
extern "C" {
CRASH_REPORTER_CLIENT_HIDDEN
struct crashreporter_annotations_t gCRAnnotations
__attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0};
}
// Report a message to any forthcoming crash log.
static void
reportOnCrash(uint32_t flags, const char *message)
{
// We must use an "unsafe" mutex in this pathway since the normal "safe"
// mutex calls fatalError when an error is detected and fatalError ends up
// calling us. In other words we could get infinite recursion if the
// mutex errors.
static StaticUnsafeMutex crashlogLock();
crashlogLock.lock();
char *oldMessage = (char *)CRGetCrashLogMessage();
char *newMessage;
if (oldMessage) {
asprintf(&newMessage, "%s%s", oldMessage, message);
if (malloc_size(oldMessage)) free(oldMessage);
} else {
newMessage = strdup(message);
}
CRSetCrashLogMessage(newMessage);
crashlogLock.unlock();
}
#else
static void
reportOnCrash(uint32_t flags, const char *message)
{
// empty
}
#endif
// Report a message to system console and stderr.
static void
reportNow(uint32_t flags, const char *message)
{
write(STDERR_FILENO, message, strlen(message));
#ifdef __APPLE__
asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", message);
#endif
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
if (flags & FatalErrorFlags::ReportBacktrace) {
fputs("Current stack trace:\n", stderr);
int count = 0;
char **trace = reportBacktrace(&count);
for (int i = 0; i < count; i++) {
fprintf(stderr, "%s\n", demangledLine(trace[i]).c_str());
}
free(trace);
}
#endif
}
/// Report a fatal error to system console, stderr, and crash logs.
/// Does not crash by itself.
void swift::swift_reportError(uint32_t flags,
const char *message) {
reportNow(flags, message);
reportOnCrash(flags, message);
}
// Report a fatal error to system console, stderr, and crash logs, then abort.
LLVM_ATTRIBUTE_NORETURN
void
swift::fatalError(uint32_t flags, const char *format, ...)
{
va_list args;
va_start(args, format);
char *log;
vasprintf(&log, format, args);
swift_reportError(flags, log);
abort();
}
// Crash when a deleted method is called by accident.
SWIFT_RUNTIME_EXPORT
LLVM_ATTRIBUTE_NORETURN
extern "C" void
swift_deletedMethodError() {
swift::fatalError(/* flags = */ 0,
"fatal error: call of deleted method\n");
}
<commit_msg>Changed StaticUnsafeMutex to have the swift:: namespace to fix upstream clang build errors.<commit_after>//===--- Errors.cpp - Error reporting utilities ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Utilities for reporting errors to stderr, system console, and crash logs.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include <stdarg.h>
#include "swift/Runtime/Debug.h"
#include "swift/Runtime/Mutex.h"
#include "swift/Basic/Demangle.h"
#include <cxxabi.h>
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
// execinfo.h is not available on Android. Checks in this file ensure that
// fatalError behaves as expected, but without stack traces.
#include <execinfo.h>
#endif
#ifdef __APPLE__
#include <asl.h>
#endif
namespace FatalErrorFlags {
enum: uint32_t {
ReportBacktrace = 1 << 0
};
} // end namespace FatalErrorFlags
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
LLVM_ATTRIBUTE_ALWAYS_INLINE
static bool
isIdentifier(char c)
{
return isalnum(c) || c == '_' || c == '$';
}
static bool
demangledLinePrefix(std::string line, std::string prefix,
std::string &out,
bool (*demangle)(std::string, std::string &))
{
int symbolStart = -1;
int symbolEnd = -1;
for (size_t i = 0; i < line.size(); i++) {
char c = line[i];
bool hasBegun = symbolStart != -1;
bool isIdentifierChar = isIdentifier(c);
bool isEndOfSymbol = hasBegun && !isIdentifierChar;
bool isEndOfLine = i == line.size() - 1;
if (isEndOfLine || isEndOfSymbol) {
symbolEnd = i;
break;
}
bool canFindPrefix = (line.size() - 2) - i > prefix.size();
if (!hasBegun && canFindPrefix && !isIdentifierChar &&
line.substr(i + 1, prefix.size()) == prefix) {
symbolStart = i + 1;
continue;
}
}
if (symbolStart == -1 || symbolEnd == -1) {
out = line;
return false;
} else {
auto symbol = line.substr(symbolStart, symbolEnd - symbolStart);
std::string demangled;
bool success = demangle(symbol, demangled);
if (success) {
line.replace(symbolStart, symbolEnd - symbolStart, demangled);
}
out = line;
return success;
}
}
static std::string
demangledLine(std::string line) {
std::string res;
bool success = false;
auto cppPrefix = "_Z"; // not sure how to check for DARWIN's __Z here.
success = demangledLinePrefix(line, cppPrefix, res,
[](std::string symbol, std::string &out) {
int status;
auto demangled = abi::__cxa_demangle(symbol.c_str(), 0, 0, &status);
if (demangled == NULL || status != 0) {
out = symbol;
return false;
} else {
out = demangled;
free(demangled);
return true;
}
});
if (success) return res;
success = demangledLinePrefix(line, "_T", res,
[](std::string symbol, std::string &out) {
out = swift::Demangle::demangleSymbolAsString(symbol);
return true;
});
if (success) return res;
return line;
}
const int STACK_DEPTH = 128;
static char **
reportBacktrace(int *count)
{
void **addrs = (void **)malloc(sizeof(void *) * STACK_DEPTH);
if (addrs == NULL) {
if (count) *count = 0;
return NULL;
}
int symbolCount = backtrace(addrs, STACK_DEPTH);
if (count) *count = symbolCount;
char **symbols = backtrace_symbols(addrs, symbolCount);
free(addrs);
if (symbols == NULL) {
if (count) *count = 0;
return NULL;
}
return symbols;
}
#endif
#ifdef SWIFT_HAVE_CRASHREPORTERCLIENT
#include <malloc/malloc.h>
// Instead of linking to CrashReporterClient.a (because it complicates the
// build system), define the only symbol from that static archive ourselves.
//
// The layout of this struct is CrashReporter ABI, so there are no ABI concerns
// here.
extern "C" {
CRASH_REPORTER_CLIENT_HIDDEN
struct crashreporter_annotations_t gCRAnnotations
__attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0};
}
// Report a message to any forthcoming crash log.
static void
reportOnCrash(uint32_t flags, const char *message)
{
// We must use an "unsafe" mutex in this pathway since the normal "safe"
// mutex calls fatalError when an error is detected and fatalError ends up
// calling us. In other words we could get infinite recursion if the
// mutex errors.
static swift::StaticUnsafeMutex crashlogLock();
crashlogLock.lock();
char *oldMessage = (char *)CRGetCrashLogMessage();
char *newMessage;
if (oldMessage) {
asprintf(&newMessage, "%s%s", oldMessage, message);
if (malloc_size(oldMessage)) free(oldMessage);
} else {
newMessage = strdup(message);
}
CRSetCrashLogMessage(newMessage);
crashlogLock.unlock();
}
#else
static void
reportOnCrash(uint32_t flags, const char *message)
{
// empty
}
#endif
// Report a message to system console and stderr.
static void
reportNow(uint32_t flags, const char *message)
{
write(STDERR_FILENO, message, strlen(message));
#ifdef __APPLE__
asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", message);
#endif
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
if (flags & FatalErrorFlags::ReportBacktrace) {
fputs("Current stack trace:\n", stderr);
int count = 0;
char **trace = reportBacktrace(&count);
for (int i = 0; i < count; i++) {
fprintf(stderr, "%s\n", demangledLine(trace[i]).c_str());
}
free(trace);
}
#endif
}
/// Report a fatal error to system console, stderr, and crash logs.
/// Does not crash by itself.
void swift::swift_reportError(uint32_t flags,
const char *message) {
reportNow(flags, message);
reportOnCrash(flags, message);
}
// Report a fatal error to system console, stderr, and crash logs, then abort.
LLVM_ATTRIBUTE_NORETURN
void
swift::fatalError(uint32_t flags, const char *format, ...)
{
va_list args;
va_start(args, format);
char *log;
vasprintf(&log, format, args);
swift_reportError(flags, log);
abort();
}
// Crash when a deleted method is called by accident.
SWIFT_RUNTIME_EXPORT
LLVM_ATTRIBUTE_NORETURN
extern "C" void
swift_deletedMethodError() {
swift::fatalError(/* flags = */ 0,
"fatal error: call of deleted method\n");
}
<|endoftext|>
|
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.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:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "nomlib/system/GameStates.hpp"
namespace nom {
// Initialize our static vars
std::vector<std::unique_ptr<IState>> GameStates::states;
// Default constructor; something is terribly amiss if you ever see this
// initialized!
GameStates::GameStates ( void )
{
NOM_LOG_TRACE ( NOM );
}
void GameStates::onEvent ( void* event )
{
// let the state handle events
states.back()->HandleInput ( event );
}
void GameStates::Update ( float delta_time )
{
// let the state update the scene with regard to the delta (change) in timing
states.back()->Update ( delta_time );
}
void GameStates::Draw ( void* video_buffer )
{
// let the state draw the scene onto the display buffer
states.back()->Draw ( video_buffer );
}
void GameStates::ChangeState ( std::unique_ptr<IState> state )
{
// cleanup the current state
if ( ! states.empty() )
{
states.back()->onExit();
states.pop_back();
}
NOM_ASSERT ( state );
// store the new state
states.push_back( std::move( state ) );
states.back()->onInit();
}
void GameStates::PushState ( std::unique_ptr<IState> state )
{
NOM_ASSERT ( state );
// pause current state
if ( ! states.empty() )
{
states.back()->Pause();
}
// store the new state
states.push_back( std::move( state ) );
states.back()->onInit();
}
void GameStates::PopState ( void )
{
// cleanup the current state
if ( ! states.empty() )
{
states.pop_back();
}
// resume previous state
states.back()->Resume();
}
void GameStates::PopStateThenChangeState ( std::unique_ptr<IState> state )
void GameStates::PopState ( int32 response )
{
// cleanup the current state
if ( ! states.empty() )
{
states.pop_back();
}
// resume previous state
states.back()->Resume( response );
}
{
// cleanup the current state
if ( ! states.empty() )
{
states.pop_back();
}
NOM_ASSERT ( state );
//if ( ! states.empty () )
GameStates::ChangeState( std::move( state ) );
}
} // namespace nom
<commit_msg>Nothing to see here, move along...<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.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:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "nomlib/system/GameStates.hpp"
namespace nom {
// Initialize our static vars
std::vector<std::unique_ptr<IState>> GameStates::states;
// Default constructor; something is terribly amiss if you ever see this
// initialized!
GameStates::GameStates ( void )
{
NOM_LOG_TRACE ( NOM );
}
void GameStates::onEvent ( void* event )
{
// let the state handle events
states.back()->HandleInput ( event );
}
void GameStates::Update ( float delta_time )
{
// let the state update the scene with regard to the delta (change) in timing
states.back()->Update ( delta_time );
}
void GameStates::Draw ( void* video_buffer )
{
// let the state draw the scene onto the display buffer
states.back()->Draw ( video_buffer );
}
void GameStates::ChangeState ( std::unique_ptr<IState> state )
{
// cleanup the current state
if ( ! states.empty() )
{
states.back()->onExit();
states.pop_back();
}
NOM_ASSERT ( state );
// store the new state
states.push_back( std::move( state ) );
states.back()->onInit();
}
void GameStates::PushState ( std::unique_ptr<IState> state )
{
NOM_ASSERT ( state );
// pause current state
if ( ! states.empty() )
{
states.back()->Pause();
}
// store the new state
states.push_back( std::move( state ) );
states.back()->onInit();
}
void GameStates::PopState ( void )
{
// cleanup the current state
if ( ! states.empty() )
{
states.pop_back();
}
// resume previous state
states.back()->Resume();
}
void GameStates::PopState ( int32 response )
{
// cleanup the current state
if ( ! states.empty() )
{
states.pop_back();
}
// resume previous state
states.back()->Resume ( response );
}
void GameStates::PopStateThenChangeState ( std::unique_ptr<IState> state )
{
// cleanup the current state
if ( ! states.empty() )
{
states.pop_back();
}
NOM_ASSERT ( state );
//if ( ! states.empty () )
GameStates::ChangeState( std::move( state ) );
}
} // namespace nom
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRandomScalerContext.h"
#include "SkGlyph.h"
#include "SkPath.h"
#include "SkCanvas.h"
#include "SkRasterizer.h"
class SkRandomScalerContext : public SkScalerContext {
public:
SkRandomScalerContext(SkRandomTypeface*, const SkDescriptor*, bool fFakeIt);
virtual ~SkRandomScalerContext();
protected:
unsigned generateGlyphCount() override;
uint16_t generateCharToGlyph(SkUnichar) override;
void generateAdvance(SkGlyph*) override;
void generateMetrics(SkGlyph*) override;
void generateImage(const SkGlyph&) override;
void generatePath(const SkGlyph&, SkPath*) override;
void generateFontMetrics(SkPaint::FontMetrics*) override;
private:
SkRandomTypeface* fFace;
SkScalerContext* fProxy;
bool fFakeIt;
};
#define STD_SIZE 1
#include "SkDescriptor.h"
SkRandomScalerContext::SkRandomScalerContext(SkRandomTypeface* face, const SkDescriptor* desc,
bool fakeIt)
: SkScalerContext(face, desc)
, fFace(face)
, fFakeIt(fakeIt) {
fProxy = face->proxy()->createScalerContext(desc);
}
SkRandomScalerContext::~SkRandomScalerContext() { delete fProxy; }
unsigned SkRandomScalerContext::generateGlyphCount() {
return fProxy->getGlyphCount();
}
uint16_t SkRandomScalerContext::generateCharToGlyph(SkUnichar uni) {
return fProxy->charToGlyphID(uni);
}
void SkRandomScalerContext::generateAdvance(SkGlyph* glyph) {
fProxy->getAdvance(glyph);
}
void SkRandomScalerContext::generateMetrics(SkGlyph* glyph) {
// Here we will change the mask format of the glyph
// NOTE this is being overridden by the base class
SkMask::Format format;
switch (glyph->getGlyphID() % 4) {
case 0:
format = SkMask::kLCD16_Format;
break;
case 1:
format = SkMask::kA8_Format;
break;
case 2:
format = SkMask::kARGB32_Format;
break;
case 3:
format = SkMask::kBW_Format;
break;
}
fProxy->getMetrics(glyph);
glyph->fMaskFormat = format;
if (fFakeIt) {
return;
}
if (SkMask::kARGB32_Format == format) {
SkPath path;
fProxy->getPath(*glyph, &path);
SkRect storage;
const SkPaint& paint = fFace->paint();
const SkRect& newBounds = paint.doComputeFastBounds(path.getBounds(),
&storage,
SkPaint::kFill_Style);
SkIRect ibounds;
newBounds.roundOut(&ibounds);
glyph->fLeft = ibounds.fLeft;
glyph->fTop = ibounds.fTop;
glyph->fWidth = ibounds.width();
glyph->fHeight = ibounds.height();
} else {
SkPath devPath, fillPath;
SkMatrix fillToDevMatrix;
this->internalGetPath(*glyph, &fillPath, &devPath, &fillToDevMatrix);
// just use devPath
const SkIRect ir = devPath.getBounds().roundOut();
if (ir.isEmpty() || !ir.is16Bit()) {
glyph->fLeft = 0;
glyph->fTop = 0;
glyph->fWidth = 0;
glyph->fHeight = 0;
return;
}
glyph->fLeft = ir.fLeft;
glyph->fTop = ir.fTop;
glyph->fWidth = SkToU16(ir.width());
glyph->fHeight = SkToU16(ir.height());
if (glyph->fWidth > 0) {
switch (glyph->fMaskFormat) {
case SkMask::kLCD16_Format:
glyph->fWidth += 2;
glyph->fLeft -= 1;
break;
default:
break;
}
}
}
}
void SkRandomScalerContext::generateImage(const SkGlyph& glyph) {
SkMask::Format format = (SkMask::Format)glyph.fMaskFormat;
switch (glyph.getGlyphID() % 4) {
case 0:
format = SkMask::kLCD16_Format;
break;
case 1:
format = SkMask::kA8_Format;
break;
case 2:
format = SkMask::kARGB32_Format;
break;
case 3:
format = SkMask::kBW_Format;
break;
}
const_cast<SkGlyph&>(glyph).fMaskFormat = format;
// if the format is ARGB, we just draw the glyph from path ourselves. Otherwise, we force
// our proxy context to generate the image from paths.
if (!fFakeIt) {
if (SkMask::kARGB32_Format == glyph.fMaskFormat) {
SkPath path;
fProxy->getPath(glyph, &path);
SkBitmap bm;
bm.installPixels(SkImageInfo::MakeN32Premul(glyph.fWidth, glyph.fHeight),
glyph.fImage, glyph.rowBytes());
bm.eraseColor(0);
SkCanvas canvas(bm);
canvas.translate(-SkIntToScalar(glyph.fLeft),
-SkIntToScalar(glyph.fTop));
canvas.drawPath(path, fFace->paint());
} else {
fProxy->forceGenerateImageFromPath();
fProxy->getImage(glyph);
fProxy->forceOffGenerateImageFromPath();
}
} else {
sk_bzero(glyph.fImage, glyph.computeImageSize());
}
}
void SkRandomScalerContext::generatePath(const SkGlyph& glyph, SkPath* path) {
fProxy->getPath(glyph, path);
}
void SkRandomScalerContext::generateFontMetrics(SkPaint::FontMetrics* metrics) {
fProxy->getFontMetrics(metrics);
}
///////////////////////////////////////////////////////////////////////////////
#include "SkTypefaceCache.h"
SkRandomTypeface::SkRandomTypeface(SkTypeface* proxy, const SkPaint& paint, bool fakeIt)
: SkTypeface(proxy->fontStyle(), SkTypefaceCache::NewFontID(), false)
, fProxy(SkRef(proxy))
, fPaint(paint)
, fFakeIt(fakeIt) {}
SkRandomTypeface::~SkRandomTypeface() {
fProxy->unref();
}
SkScalerContext* SkRandomTypeface::onCreateScalerContext(
const SkDescriptor* desc) const {
return new SkRandomScalerContext(const_cast<SkRandomTypeface*>(this), desc, fFakeIt);
}
void SkRandomTypeface::onFilterRec(SkScalerContextRec* rec) const {
fProxy->filterRec(rec);
rec->setHinting(SkPaint::kNo_Hinting);
rec->fMaskFormat = SkMask::kARGB32_Format;
}
SkAdvancedTypefaceMetrics* SkRandomTypeface::onGetAdvancedTypefaceMetrics(
PerGlyphInfo info,
const uint32_t* glyphIDs,
uint32_t glyphIDsCount) const {
return fProxy->getAdvancedTypefaceMetrics(info, glyphIDs, glyphIDsCount);
}
SkStreamAsset* SkRandomTypeface::onOpenStream(int* ttcIndex) const {
return fProxy->openStream(ttcIndex);
}
void SkRandomTypeface::onGetFontDescriptor(SkFontDescriptor* desc,
bool* isLocal) const {
fProxy->getFontDescriptor(desc, isLocal);
}
int SkRandomTypeface::onCharsToGlyphs(const void* chars, Encoding encoding,
uint16_t glyphs[], int glyphCount) const {
return fProxy->charsToGlyphs(chars, encoding, glyphs, glyphCount);
}
int SkRandomTypeface::onCountGlyphs() const {
return fProxy->countGlyphs();
}
int SkRandomTypeface::onGetUPEM() const {
return fProxy->getUnitsPerEm();
}
void SkRandomTypeface::onGetFamilyName(SkString* familyName) const {
fProxy->getFamilyName(familyName);
}
SkTypeface::LocalizedStrings* SkRandomTypeface::onCreateFamilyNameIterator() const {
return fProxy->createFamilyNameIterator();
}
int SkRandomTypeface::onGetTableTags(SkFontTableTag tags[]) const {
return fProxy->getTableTags(tags);
}
size_t SkRandomTypeface::onGetTableData(SkFontTableTag tag, size_t offset,
size_t length, void* data) const {
return fProxy->getTableData(tag, offset, length, data);
}
<commit_msg>"Fix" compiler issue in SkRandomScalerContext<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRandomScalerContext.h"
#include "SkGlyph.h"
#include "SkPath.h"
#include "SkCanvas.h"
#include "SkRasterizer.h"
class SkRandomScalerContext : public SkScalerContext {
public:
SkRandomScalerContext(SkRandomTypeface*, const SkDescriptor*, bool fFakeIt);
virtual ~SkRandomScalerContext();
protected:
unsigned generateGlyphCount() override;
uint16_t generateCharToGlyph(SkUnichar) override;
void generateAdvance(SkGlyph*) override;
void generateMetrics(SkGlyph*) override;
void generateImage(const SkGlyph&) override;
void generatePath(const SkGlyph&, SkPath*) override;
void generateFontMetrics(SkPaint::FontMetrics*) override;
private:
SkRandomTypeface* fFace;
SkScalerContext* fProxy;
bool fFakeIt;
};
#define STD_SIZE 1
#include "SkDescriptor.h"
SkRandomScalerContext::SkRandomScalerContext(SkRandomTypeface* face, const SkDescriptor* desc,
bool fakeIt)
: SkScalerContext(face, desc)
, fFace(face)
, fFakeIt(fakeIt) {
fProxy = face->proxy()->createScalerContext(desc);
}
SkRandomScalerContext::~SkRandomScalerContext() { delete fProxy; }
unsigned SkRandomScalerContext::generateGlyphCount() {
return fProxy->getGlyphCount();
}
uint16_t SkRandomScalerContext::generateCharToGlyph(SkUnichar uni) {
return fProxy->charToGlyphID(uni);
}
void SkRandomScalerContext::generateAdvance(SkGlyph* glyph) {
fProxy->getAdvance(glyph);
}
void SkRandomScalerContext::generateMetrics(SkGlyph* glyph) {
// Here we will change the mask format of the glyph
// NOTE this is being overridden by the base class
SkMask::Format format = SkMask::kARGB32_Format; // init to handle defective compilers
switch (glyph->getGlyphID() % 4) {
case 0:
format = SkMask::kLCD16_Format;
break;
case 1:
format = SkMask::kA8_Format;
break;
case 2:
format = SkMask::kARGB32_Format;
break;
case 3:
format = SkMask::kBW_Format;
break;
}
fProxy->getMetrics(glyph);
glyph->fMaskFormat = format;
if (fFakeIt) {
return;
}
if (SkMask::kARGB32_Format == format) {
SkPath path;
fProxy->getPath(*glyph, &path);
SkRect storage;
const SkPaint& paint = fFace->paint();
const SkRect& newBounds = paint.doComputeFastBounds(path.getBounds(),
&storage,
SkPaint::kFill_Style);
SkIRect ibounds;
newBounds.roundOut(&ibounds);
glyph->fLeft = ibounds.fLeft;
glyph->fTop = ibounds.fTop;
glyph->fWidth = ibounds.width();
glyph->fHeight = ibounds.height();
} else {
SkPath devPath, fillPath;
SkMatrix fillToDevMatrix;
this->internalGetPath(*glyph, &fillPath, &devPath, &fillToDevMatrix);
// just use devPath
const SkIRect ir = devPath.getBounds().roundOut();
if (ir.isEmpty() || !ir.is16Bit()) {
glyph->fLeft = 0;
glyph->fTop = 0;
glyph->fWidth = 0;
glyph->fHeight = 0;
return;
}
glyph->fLeft = ir.fLeft;
glyph->fTop = ir.fTop;
glyph->fWidth = SkToU16(ir.width());
glyph->fHeight = SkToU16(ir.height());
if (glyph->fWidth > 0) {
switch (glyph->fMaskFormat) {
case SkMask::kLCD16_Format:
glyph->fWidth += 2;
glyph->fLeft -= 1;
break;
default:
break;
}
}
}
}
void SkRandomScalerContext::generateImage(const SkGlyph& glyph) {
SkMask::Format format = (SkMask::Format)glyph.fMaskFormat;
switch (glyph.getGlyphID() % 4) {
case 0:
format = SkMask::kLCD16_Format;
break;
case 1:
format = SkMask::kA8_Format;
break;
case 2:
format = SkMask::kARGB32_Format;
break;
case 3:
format = SkMask::kBW_Format;
break;
}
const_cast<SkGlyph&>(glyph).fMaskFormat = format;
// if the format is ARGB, we just draw the glyph from path ourselves. Otherwise, we force
// our proxy context to generate the image from paths.
if (!fFakeIt) {
if (SkMask::kARGB32_Format == glyph.fMaskFormat) {
SkPath path;
fProxy->getPath(glyph, &path);
SkBitmap bm;
bm.installPixels(SkImageInfo::MakeN32Premul(glyph.fWidth, glyph.fHeight),
glyph.fImage, glyph.rowBytes());
bm.eraseColor(0);
SkCanvas canvas(bm);
canvas.translate(-SkIntToScalar(glyph.fLeft),
-SkIntToScalar(glyph.fTop));
canvas.drawPath(path, fFace->paint());
} else {
fProxy->forceGenerateImageFromPath();
fProxy->getImage(glyph);
fProxy->forceOffGenerateImageFromPath();
}
} else {
sk_bzero(glyph.fImage, glyph.computeImageSize());
}
}
void SkRandomScalerContext::generatePath(const SkGlyph& glyph, SkPath* path) {
fProxy->getPath(glyph, path);
}
void SkRandomScalerContext::generateFontMetrics(SkPaint::FontMetrics* metrics) {
fProxy->getFontMetrics(metrics);
}
///////////////////////////////////////////////////////////////////////////////
#include "SkTypefaceCache.h"
SkRandomTypeface::SkRandomTypeface(SkTypeface* proxy, const SkPaint& paint, bool fakeIt)
: SkTypeface(proxy->fontStyle(), SkTypefaceCache::NewFontID(), false)
, fProxy(SkRef(proxy))
, fPaint(paint)
, fFakeIt(fakeIt) {}
SkRandomTypeface::~SkRandomTypeface() {
fProxy->unref();
}
SkScalerContext* SkRandomTypeface::onCreateScalerContext(
const SkDescriptor* desc) const {
return new SkRandomScalerContext(const_cast<SkRandomTypeface*>(this), desc, fFakeIt);
}
void SkRandomTypeface::onFilterRec(SkScalerContextRec* rec) const {
fProxy->filterRec(rec);
rec->setHinting(SkPaint::kNo_Hinting);
rec->fMaskFormat = SkMask::kARGB32_Format;
}
SkAdvancedTypefaceMetrics* SkRandomTypeface::onGetAdvancedTypefaceMetrics(
PerGlyphInfo info,
const uint32_t* glyphIDs,
uint32_t glyphIDsCount) const {
return fProxy->getAdvancedTypefaceMetrics(info, glyphIDs, glyphIDsCount);
}
SkStreamAsset* SkRandomTypeface::onOpenStream(int* ttcIndex) const {
return fProxy->openStream(ttcIndex);
}
void SkRandomTypeface::onGetFontDescriptor(SkFontDescriptor* desc,
bool* isLocal) const {
fProxy->getFontDescriptor(desc, isLocal);
}
int SkRandomTypeface::onCharsToGlyphs(const void* chars, Encoding encoding,
uint16_t glyphs[], int glyphCount) const {
return fProxy->charsToGlyphs(chars, encoding, glyphs, glyphCount);
}
int SkRandomTypeface::onCountGlyphs() const {
return fProxy->countGlyphs();
}
int SkRandomTypeface::onGetUPEM() const {
return fProxy->getUnitsPerEm();
}
void SkRandomTypeface::onGetFamilyName(SkString* familyName) const {
fProxy->getFamilyName(familyName);
}
SkTypeface::LocalizedStrings* SkRandomTypeface::onCreateFamilyNameIterator() const {
return fProxy->createFamilyNameIterator();
}
int SkRandomTypeface::onGetTableTags(SkFontTableTag tags[]) const {
return fProxy->getTableTags(tags);
}
size_t SkRandomTypeface::onGetTableData(SkFontTableTag tag, size_t offset,
size_t length, void* data) const {
return fProxy->getTableData(tag, offset, length, data);
}
<|endoftext|>
|
<commit_before>/*
* SessionConsole.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionConsole.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/system/OutputCapture.hpp>
#include <r/RExec.hpp>
#include <r/session/RConsoleActions.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core;
namespace session {
namespace modules {
namespace console {
namespace {
bool suppressOutput(const std::string& output)
{
// tokens to suppress
const char * const kGlibWarningToken = "GLib-WARNING **: getpwuid_r()";
const char * const kAutoreleaseNoPool = "NSAutoreleaseNoPool";
const char * const kSelectInterrupted = "select: Interrupted system call";
const char * const kNotAGitRepo = "Not a git repository";
const char * const kIsOutsideRepo = "is outside repository";
// check tokens
if (boost::algorithm::contains(output, kGlibWarningToken) ||
boost::algorithm::contains(output, kAutoreleaseNoPool) ||
boost::algorithm::contains(output, kSelectInterrupted) ||
boost::algorithm::contains(output, kNotAGitRepo) ||
boost::algorithm::contains(output, kIsOutsideRepo))
{
return true;
}
else
{
return false;
}
}
void writeStandardOutput(const std::string& output)
{
module_context::consoleWriteOutput(output);
}
void writeStandardError(const std::string& output)
{
if (!suppressOutput(output))
module_context::consoleWriteError(output);
}
Error initializeOutputCapture()
{
// only capture stderr if it isn't connected to a terminal
boost::function<void(const std::string&)> stderrHandler;
if (!core::system::stderrIsTerminal())
stderrHandler = writeStandardError;
// initialize
return core::system::captureStandardStreams(writeStandardOutput,
stderrHandler);
}
FilePath s_lastWorkingDirectory;
void detectWorkingDirectoryChanged()
{
FilePath currentWorkingDirectory = module_context::safeCurrentPath();
if ( s_lastWorkingDirectory.empty() ||
(currentWorkingDirectory != s_lastWorkingDirectory) )
{
// fire event
std::string path = module_context::createAliasedPath(currentWorkingDirectory);
ClientEvent event(client_events::kWorkingDirChanged, path);
module_context::enqueClientEvent(event);
// update state
s_lastWorkingDirectory = currentWorkingDirectory;
}
}
void onClientInit()
{
// reset state to force wd changed event
s_lastWorkingDirectory = FilePath();
detectWorkingDirectoryChanged();
}
void onDetectChanges(module_context::ChangeSource source)
{
// print warnings after all RPC and URI handlers (not required
// for REPL because R already does this for us)
if (source != module_context::ChangeSourceREPL)
r::exec::printWarnings();
// check for working directory changed
detectWorkingDirectoryChanged();
}
Error resetConsoleActions(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
r::session::consoleActions().reset();
return Success();
}
} // anonymous namespace
Error initialize()
{
if (!session::options().verifyInstallation())
{
// capture standard streams
Error error = initializeOutputCapture();
if (error)
return error;
}
// subscribe to events
using boost::bind;
using namespace module_context;
events().onClientInit.connect(bind(onClientInit));
events().onDetectChanges.connect(bind(onDetectChanges, _1));
// more initialization
using boost::bind;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(sourceModuleRFile, "SessionConsole.R"))
(bind(registerRpcMethod, "reset_console_actions", resetConsoleActions));
return initBlock.execute();
}
} // namespace console
} // namespace modules
} // namesapce session
<commit_msg>change AutoreleaseNoPool output filter to pick up ox 10.7 variation of message<commit_after>/*
* SessionConsole.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionConsole.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/system/OutputCapture.hpp>
#include <r/RExec.hpp>
#include <r/session/RConsoleActions.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core;
namespace session {
namespace modules {
namespace console {
namespace {
bool suppressOutput(const std::string& output)
{
// tokens to suppress
const char * const kGlibWarningToken = "GLib-WARNING **: getpwuid_r()";
const char * const kAutoreleaseNoPool = "utoreleaseNoPool";
const char * const kSelectInterrupted = "select: Interrupted system call";
const char * const kNotAGitRepo = "Not a git repository";
const char * const kIsOutsideRepo = "is outside repository";
// check tokens
if (boost::algorithm::contains(output, kGlibWarningToken) ||
boost::algorithm::contains(output, kAutoreleaseNoPool) ||
boost::algorithm::contains(output, kSelectInterrupted) ||
boost::algorithm::contains(output, kNotAGitRepo) ||
boost::algorithm::contains(output, kIsOutsideRepo))
{
return true;
}
else
{
return false;
}
}
void writeStandardOutput(const std::string& output)
{
module_context::consoleWriteOutput(output);
}
void writeStandardError(const std::string& output)
{
if (!suppressOutput(output))
module_context::consoleWriteError(output);
}
Error initializeOutputCapture()
{
// only capture stderr if it isn't connected to a terminal
boost::function<void(const std::string&)> stderrHandler;
if (!core::system::stderrIsTerminal())
stderrHandler = writeStandardError;
// initialize
return core::system::captureStandardStreams(writeStandardOutput,
stderrHandler);
}
FilePath s_lastWorkingDirectory;
void detectWorkingDirectoryChanged()
{
FilePath currentWorkingDirectory = module_context::safeCurrentPath();
if ( s_lastWorkingDirectory.empty() ||
(currentWorkingDirectory != s_lastWorkingDirectory) )
{
// fire event
std::string path = module_context::createAliasedPath(currentWorkingDirectory);
ClientEvent event(client_events::kWorkingDirChanged, path);
module_context::enqueClientEvent(event);
// update state
s_lastWorkingDirectory = currentWorkingDirectory;
}
}
void onClientInit()
{
// reset state to force wd changed event
s_lastWorkingDirectory = FilePath();
detectWorkingDirectoryChanged();
}
void onDetectChanges(module_context::ChangeSource source)
{
// print warnings after all RPC and URI handlers (not required
// for REPL because R already does this for us)
if (source != module_context::ChangeSourceREPL)
r::exec::printWarnings();
// check for working directory changed
detectWorkingDirectoryChanged();
}
Error resetConsoleActions(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
r::session::consoleActions().reset();
return Success();
}
} // anonymous namespace
Error initialize()
{
if (!session::options().verifyInstallation())
{
// capture standard streams
Error error = initializeOutputCapture();
if (error)
return error;
}
// subscribe to events
using boost::bind;
using namespace module_context;
events().onClientInit.connect(bind(onClientInit));
events().onDetectChanges.connect(bind(onDetectChanges, _1));
// more initialization
using boost::bind;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(sourceModuleRFile, "SessionConsole.R"))
(bind(registerRpcMethod, "reset_console_actions", resetConsoleActions));
return initBlock.execute();
}
} // namespace console
} // namespace modules
} // namesapce session
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 MIPS Technologies, 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 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: Korey Sewell
*
*/
#include <list>
#include <vector>
#include "cpu/inorder/resources/mult_div_unit.hh"
#include "cpu/inorder/cpu.hh"
#include "cpu/inorder/resource_pool.hh"
#include "cpu/op_class.hh"
#include "debug/InOrderMDU.hh"
#include "debug/Resource.hh"
using namespace std;
using namespace ThePipeline;
MultDivUnit::MultDivUnit(string res_name, int res_id, int res_width,
int res_latency, InOrderCPU *_cpu,
ThePipeline::Params *params)
: Resource(res_name, res_id, res_width, res_latency, _cpu),
multRepeatRate(params->multRepeatRate),
multLatency(params->multLatency),
div8RepeatRate(params->div8RepeatRate),
div8Latency(params->div8Latency),
div16RepeatRate(params->div16RepeatRate),
div16Latency(params->div16Latency),
div24RepeatRate(params->div24RepeatRate),
div24Latency(params->div24Latency),
div32RepeatRate(params->div32RepeatRate),
div32Latency(params->div32Latency),
lastMDUCycle(0), lastOpType(No_OpClass)
{ }
void
MultDivUnit::regStats()
{
multiplies
.name(name() + ".multiplies")
.desc("Number of Multipy Operations Executed");
divides
.name(name() + ".divides")
.desc("Number of Divide Operations Executed");
Resource::regStats();
}
void
MultDivUnit::init()
{
// Set Up Resource Events to Appropriate Resource BandWidth
resourceEvent = new MDUEvent[width];
for (int i = 0; i < width; i++) {
reqs[i] = new ResourceRequest(this);
}
initSlots();
}
//@TODO: Should we push this behavior into base-class to generically
// accomodate all multicyle resources?
void
MultDivUnit::requestAgain(DynInstPtr inst, bool &service_request)
{
ResReqPtr mult_div_req = findRequest(inst);
assert(mult_div_req);
service_request = true;
// Check to see if this instruction is requesting the same command
// or a different one
if (mult_div_req->cmd != inst->curSkedEntry->cmd) {
// If different, then update command in the request
mult_div_req->cmd = inst->curSkedEntry->cmd;
DPRINTF(InOrderMDU,
"[tid:%i]: [sn:%i]: Updating the command for this "
"instruction\n", inst->readTid(), inst->seqNum);
} else {
// If same command, just check to see if access was completed
// but dont try to re-execute
DPRINTF(InOrderMDU,
"[tid:%i]: [sn:%i]: requesting this resource again\n",
inst->readTid(), inst->seqNum);
}
}
int
MultDivUnit::getSlot(DynInstPtr inst)
{
// If MDU already has instruction, return current slot.
int slot_num = findSlot(inst);
// If we have this instruction's request already then return
if (slot_num != -1 &&
inst->curSkedEntry->cmd == reqs[slot_num]->cmd)
return slot_num;
unsigned repeat_rate = 0;
/** Enforce MDU dependencies after a multiply is seen last */
if (lastOpType == IntMultOp) {
repeat_rate = multRepeatRate;
}
/** Enforce dependencies after a divide is seen last */
if (lastOpType == IntDivOp) {
switch (lastDivSize) {
case 8:
repeat_rate = div8RepeatRate;
break;
case 16:
repeat_rate = div16RepeatRate;
break;
case 24:
repeat_rate = div24RepeatRate;
break;
case 32:
repeat_rate = div32RepeatRate;
break;
}
}
if (lastMDUCycle + repeat_rate > curTick()) {
DPRINTF(InOrderMDU, "MDU not ready to process another inst. until %i, "
"denying request.\n", lastMDUCycle + repeat_rate);
return -1;
} else {
int rval = Resource::getSlot(inst);
DPRINTF(InOrderMDU, "MDU request should pass: %i.\n",
rval);
if (rval != -1) {
lastMDUCycle = curTick();
lastOpType = inst->opClass();
lastInstName = inst->staticInst->getName();
}
return rval;
}
}
int
MultDivUnit::getDivOpSize(DynInstPtr inst)
{
// Get RT Register from instruction (index #1)
uint32_t div_op = inst->readIntSrc(1);
if (div_op <= 0xFF) {
return 8;
} else if (div_op <= 0xFFFF) {
return 16;
} else if (div_op <= 0xFFFFFF) {
return 24;
} else {
return 32;
}
}
void
MultDivUnit::execute(int slot_num)
{
ResourceRequest* mult_div_req = reqs[slot_num];
DynInstPtr inst = reqs[slot_num]->inst;
if (inst->fault != NoFault) {
DPRINTF(InOrderMDU,
"[tid:%i]: [sn:%i]: Detected %s fault @ %x. Forwarding to "
"next stage.\n", inst->readTid(), inst->seqNum, inst->fault->name(),
inst->pcState());
mult_div_req->done();
return;
}
DPRINTF(InOrderMDU, "Executing [sn:%i] ...\n", slot_num);
switch (mult_div_req->cmd)
{
case StartMultDiv:
{
DPRINTF(InOrderMDU, "Start MDU called ...\n");
OpClass op_class = inst->opClass();
if (op_class == IntMultOp) {
scheduleEvent(slot_num, multLatency);
} else if (op_class == IntDivOp) {
int op_size = getDivOpSize(inst);
switch (op_size)
{
case 8:
scheduleEvent(slot_num, div8Latency);
break;
case 16:
scheduleEvent(slot_num, div16Latency);
break;
case 24:
scheduleEvent(slot_num, div24Latency);
break;
case 32:
scheduleEvent(slot_num, div32Latency);
break;
}
lastDivSize = op_size;
}
// Allow to pass through to next stage while
// event processes
mult_div_req->setProcessing();
mult_div_req->setCompleted();
}
break;
case MultDiv:
DPRINTF(InOrderMDU, "Execute MDU called ...\n");
exeMulDiv(slot_num);
mult_div_req->done();
break;
case EndMultDiv:
//@TODO: Why not allow high-latency requests to sleep
// within stage until event wakes up????
// Seems wasteful to continually check to see if
// this is done when we have a event in parallel
// counting down the time
{
DPRINTF(InOrderMDU, "End MDU called ...\n");
if (!mult_div_req->isProcessing()) {
DPRINTF(InOrderMDU, "Mult/Div finished.\n");
mult_div_req->done();
} else {
mult_div_req->setCompleted(false);
}
}
break;
default:
fatal("Unrecognized command to %s", resName);
}
}
void
MultDivUnit::exeMulDiv(int slot_num)
{
ResourceRequest* mult_div_req = reqs[slot_num];
DynInstPtr inst = reqs[slot_num]->inst;
inst->fault = inst->execute();
if (inst->opClass() == IntMultOp) {
multiplies++;
} else if (inst->opClass() == IntDivOp) {
divides++;
}
if (inst->fault == NoFault) {
inst->setExecuted();
DPRINTF(InOrderMDU, "[tid:%i]: The result of execution is 0x%x.\n",
inst->readTid(), inst->readIntResult(0));
} else {
DPRINTF(InOrderMDU, "[tid:%i]: [sn:%i]: had a %s "
"fault.\n", inst->readTid(), inst->seqNum, inst->fault->name());
}
mult_div_req->setProcessing(false);
}
void
MultDivUnit::squash(DynInstPtr inst, int stage_num, InstSeqNum squash_seq_num,
ThreadID tid)
{
for (int i = 0; i < width; i++) {
ResReqPtr req_ptr = reqs[i];
DynInstPtr inst = req_ptr->getInst();
if (req_ptr->valid &&
inst->readTid() == tid &&
inst->seqNum > squash_seq_num) {
DPRINTF(InOrderMDU, "[tid:%i]: Squashing [sn:%i].\n",
req_ptr->getInst()->readTid(),
req_ptr->getInst()->seqNum);
req_ptr->setSquashed();
int req_slot_num = req_ptr->getSlot();
if (req_ptr->isProcessing())
DPRINTF(InOrderMDU, "[tid:%i]: Squashed [sn:%i], but "
"waiting for MDU operation to complete.\n",
req_ptr->getInst()->readTid(),
req_ptr->getInst()->seqNum);
else
freeSlot(req_slot_num);
}
}
}
MDUEvent::MDUEvent()
: ResourceEvent()
{ }
void
MDUEvent::process()
{
MultDivUnit* mdu_res = reinterpret_cast<MultDivUnit*>(resource);
mdu_res->exeMulDiv(slotIdx);
ResourceRequest* mult_div_req = resource->reqs[slotIdx];
if (mult_div_req->isSquashed())
mdu_res->freeSlot(slotIdx);
}
<commit_msg>inorder: MDU deadlock fix<commit_after>/*
* Copyright (c) 2007 MIPS Technologies, 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 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: Korey Sewell
*
*/
#include <list>
#include <vector>
#include "cpu/inorder/resources/mult_div_unit.hh"
#include "cpu/inorder/cpu.hh"
#include "cpu/inorder/resource_pool.hh"
#include "cpu/op_class.hh"
#include "debug/InOrderMDU.hh"
#include "debug/Resource.hh"
using namespace std;
using namespace ThePipeline;
MultDivUnit::MultDivUnit(string res_name, int res_id, int res_width,
int res_latency, InOrderCPU *_cpu,
ThePipeline::Params *params)
: Resource(res_name, res_id, res_width, res_latency, _cpu),
multRepeatRate(params->multRepeatRate),
multLatency(params->multLatency),
div8RepeatRate(params->div8RepeatRate),
div8Latency(params->div8Latency),
div16RepeatRate(params->div16RepeatRate),
div16Latency(params->div16Latency),
div24RepeatRate(params->div24RepeatRate),
div24Latency(params->div24Latency),
div32RepeatRate(params->div32RepeatRate),
div32Latency(params->div32Latency),
lastMDUCycle(0), lastOpType(No_OpClass)
{ }
void
MultDivUnit::regStats()
{
multiplies
.name(name() + ".multiplies")
.desc("Number of Multipy Operations Executed");
divides
.name(name() + ".divides")
.desc("Number of Divide Operations Executed");
Resource::regStats();
}
void
MultDivUnit::init()
{
// Set Up Resource Events to Appropriate Resource BandWidth
resourceEvent = new MDUEvent[width];
for (int i = 0; i < width; i++) {
reqs[i] = new ResourceRequest(this);
}
initSlots();
}
//@TODO: Should we push this behavior into base-class to generically
// accomodate all multicyle resources?
void
MultDivUnit::requestAgain(DynInstPtr inst, bool &service_request)
{
ResReqPtr mult_div_req = findRequest(inst);
assert(mult_div_req);
service_request = true;
// Check to see if this instruction is requesting the same command
// or a different one
if (mult_div_req->cmd != inst->curSkedEntry->cmd) {
// If different, then update command in the request
mult_div_req->cmd = inst->curSkedEntry->cmd;
DPRINTF(InOrderMDU,
"[tid:%i]: [sn:%i]: Updating the command for this "
"instruction\n", inst->readTid(), inst->seqNum);
} else {
// If same command, just check to see if access was completed
// but dont try to re-execute
DPRINTF(InOrderMDU,
"[tid:%i]: [sn:%i]: requesting this resource again\n",
inst->readTid(), inst->seqNum);
}
}
int
MultDivUnit::getSlot(DynInstPtr inst)
{
// If MDU already has instruction, return current slot.
int slot_num = findSlot(inst);
// If we have this instruction's request already then return
if (slot_num != -1 &&
inst->curSkedEntry->cmd == reqs[slot_num]->cmd)
return slot_num;
unsigned repeat_rate = 0;
/** Enforce MDU dependencies after a multiply is seen last */
if (lastOpType == IntMultOp) {
repeat_rate = multRepeatRate;
}
/** Enforce dependencies after a divide is seen last */
if (lastOpType == IntDivOp) {
switch (lastDivSize) {
case 8:
repeat_rate = div8RepeatRate;
break;
case 16:
repeat_rate = div16RepeatRate;
break;
case 24:
repeat_rate = div24RepeatRate;
break;
case 32:
repeat_rate = div32RepeatRate;
break;
}
}
if (lastMDUCycle + repeat_rate > curTick()) {
DPRINTF(InOrderMDU, "MDU not ready to process another inst. until %i, "
"denying request.\n", lastMDUCycle + repeat_rate);
return -1;
} else {
int rval = Resource::getSlot(inst);
DPRINTF(InOrderMDU, "MDU request should pass: %i.\n",
rval);
if (rval != -1) {
lastMDUCycle = curTick();
lastOpType = inst->opClass();
lastInstName = inst->staticInst->getName();
}
return rval;
}
}
int
MultDivUnit::getDivOpSize(DynInstPtr inst)
{
// Get RT Register from instruction (index #1)
uint32_t div_op = inst->readIntSrc(1);
if (div_op <= 0xFF) {
return 8;
} else if (div_op <= 0xFFFF) {
return 16;
} else if (div_op <= 0xFFFFFF) {
return 24;
} else {
return 32;
}
}
void
MultDivUnit::execute(int slot_num)
{
ResourceRequest* mult_div_req = reqs[slot_num];
DynInstPtr inst = reqs[slot_num]->inst;
if (inst->fault != NoFault) {
DPRINTF(InOrderMDU,
"[tid:%i]: [sn:%i]: Detected %s fault @ %x. Forwarding to "
"next stage.\n", inst->readTid(), inst->seqNum, inst->fault->name(),
inst->pcState());
mult_div_req->done();
return;
}
DPRINTF(InOrderMDU, "Executing [sn:%i] ...\n", slot_num);
switch (mult_div_req->cmd)
{
case StartMultDiv:
{
DPRINTF(InOrderMDU, "Start MDU called ...\n");
OpClass op_class = inst->opClass();
if (op_class == IntMultOp) {
scheduleEvent(slot_num, multLatency);
} else if (op_class == IntDivOp) {
int op_size = getDivOpSize(inst);
switch (op_size)
{
case 8:
scheduleEvent(slot_num, div8Latency);
break;
case 16:
scheduleEvent(slot_num, div16Latency);
break;
case 24:
scheduleEvent(slot_num, div24Latency);
break;
case 32:
scheduleEvent(slot_num, div32Latency);
break;
}
lastDivSize = op_size;
}
// Allow to pass through to next stage while
// event processes
mult_div_req->setProcessing();
mult_div_req->setCompleted();
}
break;
case MultDiv:
DPRINTF(InOrderMDU, "Execute MDU called ...\n");
exeMulDiv(slot_num);
mult_div_req->done();
break;
case EndMultDiv:
//@TODO: Why not allow high-latency requests to sleep
// within stage until event wakes up????
// Seems wasteful to continually check to see if
// this is done when we have a event in parallel
// counting down the time
{
DPRINTF(InOrderMDU, "End MDU called ...\n");
if (!mult_div_req->isProcessing()) {
DPRINTF(InOrderMDU, "Mult/Div finished.\n");
mult_div_req->done();
} else {
mult_div_req->setCompleted(false);
}
}
break;
default:
fatal("Unrecognized command to %s", resName);
}
}
void
MultDivUnit::exeMulDiv(int slot_num)
{
ResourceRequest* mult_div_req = reqs[slot_num];
DynInstPtr inst = reqs[slot_num]->inst;
inst->fault = inst->execute();
if (inst->opClass() == IntMultOp) {
multiplies++;
} else if (inst->opClass() == IntDivOp) {
divides++;
}
if (inst->fault == NoFault) {
inst->setExecuted();
DPRINTF(InOrderMDU, "[tid:%i]: The result of execution is 0x%x.\n",
inst->readTid(), inst->readIntResult(0));
} else {
DPRINTF(InOrderMDU, "[tid:%i]: [sn:%i]: had a %s "
"fault.\n", inst->readTid(), inst->seqNum, inst->fault->name());
}
mult_div_req->setProcessing(false);
cpu->wakeCPU();
}
void
MultDivUnit::squash(DynInstPtr inst, int stage_num, InstSeqNum squash_seq_num,
ThreadID tid)
{
for (int i = 0; i < width; i++) {
ResReqPtr req_ptr = reqs[i];
DynInstPtr inst = req_ptr->getInst();
if (req_ptr->valid &&
inst->readTid() == tid &&
inst->seqNum > squash_seq_num) {
DPRINTF(InOrderMDU, "[tid:%i]: Squashing [sn:%i].\n",
req_ptr->getInst()->readTid(),
req_ptr->getInst()->seqNum);
req_ptr->setSquashed();
int req_slot_num = req_ptr->getSlot();
if (req_ptr->isProcessing())
DPRINTF(InOrderMDU, "[tid:%i]: Squashed [sn:%i], but "
"waiting for MDU operation to complete.\n",
req_ptr->getInst()->readTid(),
req_ptr->getInst()->seqNum);
else
freeSlot(req_slot_num);
}
}
}
MDUEvent::MDUEvent()
: ResourceEvent()
{ }
void
MDUEvent::process()
{
MultDivUnit* mdu_res = reinterpret_cast<MultDivUnit*>(resource);
mdu_res->exeMulDiv(slotIdx);
ResourceRequest* mult_div_req = resource->reqs[slotIdx];
if (mult_div_req->isSquashed())
mdu_res->freeSlot(slotIdx);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.