text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/mac/os_compatibility.h"
#include <servers/bootstrap.h>
#include <unistd.h>
#include "base/mac/mac_util.h"
namespace sandbox {
namespace {
// Verified from launchd-329.3.3 (10.6.8).
struct look_up2_request_10_6 {
mach_msg_header_t Head;
NDR_record_t NDR;
name_t servicename;
pid_t targetpid;
uint64_t flags;
};
struct look_up2_reply_10_6 {
mach_msg_header_t Head;
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t service_port;
};
// Verified from:
// launchd-392.39 (10.7.5)
// launchd-442.26.2 (10.8.5)
// launchd-842.1.4 (10.9.0)
struct look_up2_request_10_7 {
mach_msg_header_t Head;
NDR_record_t NDR;
name_t servicename;
pid_t targetpid;
uuid_t instanceid;
uint64_t flags;
};
// look_up2_reply_10_7 is the same as the 10_6 version.
// Verified from:
// launchd-329.3.3 (10.6.8)
// launchd-392.39 (10.7.5)
// launchd-442.26.2 (10.8.5)
// launchd-842.1.4 (10.9.0)
typedef int vproc_gsk_t; // Defined as an enum in liblaunch/vproc_priv.h.
struct swap_integer_request_10_6 {
mach_msg_header_t Head;
NDR_record_t NDR;
vproc_gsk_t inkey;
vproc_gsk_t outkey;
int64_t inval;
};
// TODO(rsesek): Libc provides strnlen() starting in 10.7.
size_t strnlen(const char* str, size_t maxlen) {
size_t len = 0;
for (; len < maxlen; ++len, ++str) {
if (*str == '\0')
break;
}
return len;
}
uint64_t MachGetMessageID(const IPCMessage message) {
return message.mach->msgh_id;
}
template <typename R>
std::string LaunchdLookUp2GetRequestName(const IPCMessage message) {
mach_msg_header_t* header = message.mach;
DCHECK_EQ(sizeof(R), header->msgh_size);
const R* request = reinterpret_cast<const R*>(header);
// Make sure the name is properly NUL-terminated.
const size_t name_length =
strnlen(request->servicename, BOOTSTRAP_MAX_NAME_LEN);
std::string name = std::string(request->servicename, name_length);
return name;
}
template <typename R>
void LaunchdLookUp2FillReply(IPCMessage message, mach_port_t port) {
R* reply = reinterpret_cast<R*>(message.mach);
reply->Head.msgh_size = sizeof(R);
reply->Head.msgh_bits =
MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MOVE_SEND_ONCE) |
MACH_MSGH_BITS_COMPLEX;
reply->msgh_body.msgh_descriptor_count = 1;
reply->service_port.name = port;
reply->service_port.disposition = MACH_MSG_TYPE_COPY_SEND;
reply->service_port.type = MACH_MSG_PORT_DESCRIPTOR;
}
template <typename R>
bool LaunchdSwapIntegerIsGetOnly(const IPCMessage message) {
const R* request = reinterpret_cast<const R*>(message.mach);
return request->inkey == 0 && request->inval == 0 && request->outkey != 0;
}
} // namespace
const LaunchdCompatibilityShim GetLaunchdCompatibilityShim() {
LaunchdCompatibilityShim shim = {
.ipc_message_get_id = &MachGetMessageID,
.msg_id_look_up2 = 404,
.msg_id_swap_integer = 416,
.look_up2_fill_reply = &LaunchdLookUp2FillReply<look_up2_reply_10_6>,
.swap_integer_is_get_only =
&LaunchdSwapIntegerIsGetOnly<swap_integer_request_10_6>,
};
if (base::mac::IsOSSnowLeopard()) {
shim.look_up2_get_request_name =
&LaunchdLookUp2GetRequestName<look_up2_request_10_6>;
} else if (base::mac::IsOSLionOrLater() &&
!base::mac::IsOSYosemiteOrLater()) {
shim.look_up2_get_request_name =
&LaunchdLookUp2GetRequestName<look_up2_request_10_7>;
} else {
DLOG(ERROR) << "Unknown OS, using launchd compatibility shim from 10.7.";
shim.look_up2_get_request_name =
&LaunchdLookUp2GetRequestName<look_up2_request_10_7>;
}
return shim;
}
} // namespace sandbox
<commit_msg>Fix Mac bootstrap sandbox for 64-bit builds<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/mac/os_compatibility.h"
#include <servers/bootstrap.h>
#include <unistd.h>
#include "base/mac/mac_util.h"
namespace sandbox {
namespace {
#pragma pack(push, 4)
// Verified from launchd-329.3.3 (10.6.8).
struct look_up2_request_10_6 {
mach_msg_header_t Head;
NDR_record_t NDR;
name_t servicename;
pid_t targetpid;
uint64_t flags;
};
struct look_up2_reply_10_6 {
mach_msg_header_t Head;
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t service_port;
};
// Verified from:
// launchd-392.39 (10.7.5)
// launchd-442.26.2 (10.8.5)
// launchd-842.1.4 (10.9.0)
struct look_up2_request_10_7 {
mach_msg_header_t Head;
NDR_record_t NDR;
name_t servicename;
pid_t targetpid;
uuid_t instanceid;
uint64_t flags;
};
// look_up2_reply_10_7 is the same as the 10_6 version.
// Verified from:
// launchd-329.3.3 (10.6.8)
// launchd-392.39 (10.7.5)
// launchd-442.26.2 (10.8.5)
// launchd-842.1.4 (10.9.0)
typedef int vproc_gsk_t; // Defined as an enum in liblaunch/vproc_priv.h.
struct swap_integer_request_10_6 {
mach_msg_header_t Head;
NDR_record_t NDR;
vproc_gsk_t inkey;
vproc_gsk_t outkey;
int64_t inval;
};
#pragma pack(pop)
// TODO(rsesek): Libc provides strnlen() starting in 10.7.
size_t strnlen(const char* str, size_t maxlen) {
size_t len = 0;
for (; len < maxlen; ++len, ++str) {
if (*str == '\0')
break;
}
return len;
}
uint64_t MachGetMessageID(const IPCMessage message) {
return message.mach->msgh_id;
}
template <typename R>
std::string LaunchdLookUp2GetRequestName(const IPCMessage message) {
mach_msg_header_t* header = message.mach;
DCHECK_EQ(sizeof(R), header->msgh_size);
const R* request = reinterpret_cast<const R*>(header);
// Make sure the name is properly NUL-terminated.
const size_t name_length =
strnlen(request->servicename, BOOTSTRAP_MAX_NAME_LEN);
std::string name = std::string(request->servicename, name_length);
return name;
}
template <typename R>
void LaunchdLookUp2FillReply(IPCMessage message, mach_port_t port) {
R* reply = reinterpret_cast<R*>(message.mach);
reply->Head.msgh_size = sizeof(R);
reply->Head.msgh_bits =
MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MOVE_SEND_ONCE) |
MACH_MSGH_BITS_COMPLEX;
reply->msgh_body.msgh_descriptor_count = 1;
reply->service_port.name = port;
reply->service_port.disposition = MACH_MSG_TYPE_COPY_SEND;
reply->service_port.type = MACH_MSG_PORT_DESCRIPTOR;
}
template <typename R>
bool LaunchdSwapIntegerIsGetOnly(const IPCMessage message) {
const R* request = reinterpret_cast<const R*>(message.mach);
return request->inkey == 0 && request->inval == 0 && request->outkey != 0;
}
} // namespace
const LaunchdCompatibilityShim GetLaunchdCompatibilityShim() {
LaunchdCompatibilityShim shim = {
.ipc_message_get_id = &MachGetMessageID,
.msg_id_look_up2 = 404,
.msg_id_swap_integer = 416,
.look_up2_fill_reply = &LaunchdLookUp2FillReply<look_up2_reply_10_6>,
.swap_integer_is_get_only =
&LaunchdSwapIntegerIsGetOnly<swap_integer_request_10_6>,
};
if (base::mac::IsOSSnowLeopard()) {
shim.look_up2_get_request_name =
&LaunchdLookUp2GetRequestName<look_up2_request_10_6>;
} else if (base::mac::IsOSLionOrLater() &&
!base::mac::IsOSYosemiteOrLater()) {
shim.look_up2_get_request_name =
&LaunchdLookUp2GetRequestName<look_up2_request_10_7>;
} else {
DLOG(ERROR) << "Unknown OS, using launchd compatibility shim from 10.7.";
shim.look_up2_get_request_name =
&LaunchdLookUp2GetRequestName<look_up2_request_10_7>;
}
return shim;
}
} // namespace sandbox
<|endoftext|>
|
<commit_before>// sound.cxx -- Sound class implementation
//
// Started by Erik Hofman, February 2002
// (Reuses some code from fg_fx.cxx created by David Megginson)
//
// Copyright (C) 2002 Curtis L. Olson - http://www.flightgear.org/~curt
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
#include <simgear/compiler.h>
#ifdef SG_HAVE_STD_INCLUDES
# include <cmath>
#else
# include <math.h>
#endif
#include <string.h>
#include <simgear/debug/logstream.hxx>
#include <simgear/props/condition.hxx>
#include <simgear/math/fastmath.hxx>
#include "xmlsound.hxx"
// static double _snd_lin(double v) { return v; }
static double _snd_inv(double v) { return (v == 0) ? 1e99 : 1/v; }
static double _snd_abs(double v) { return (v >= 0) ? v : -v; }
static double _snd_sqrt(double v) { return (v < 0) ? sqrt(-v) : sqrt(v); }
static double _snd_log10(double v) { return (v < 1) ? 0 : fast_log10(v); }
static double _snd_log(double v) { return (v < 1) ? 0 : fast_log(v); }
// static double _snd_sqr(double v) { return v*v; }
// static double _snd_pow3(double v) { return v*v*v; }
static const struct {
char *name;
double (*fn)(double);
} __sound_fn[] = {
// {"lin", _snd_lin},
{"inv", _snd_inv},
{"abs", _snd_abs},
{"sqrt", _snd_sqrt},
{"log", _snd_log10},
{"ln", _snd_log},
// {"sqr", _snd_sqr},
// {"pow3", _snd_pow3},
{"", NULL}
};
SGXmlSound::SGXmlSound()
: _sample(NULL),
_condition(NULL),
_property(NULL),
_active(false),
_name(""),
_mode(SGXmlSound::ONCE),
_prev_value(0),
_dt_play(0.0),
_dt_stop(0.0),
_stopping(0.0)
{
}
SGXmlSound::~SGXmlSound()
{
_sample->stop();
delete _property;
delete _condition;
_volume.clear();
_pitch.clear();
delete _sample;
}
void
SGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node, SGSoundMgr *sndmgr,
const string &path)
{
//
// set global sound properties
//
_name = node->getStringValue("name", "");
SG_LOG(SG_GENERAL, SG_INFO, "Loading sound information for: " << _name );
const char *mode_str = node->getStringValue("mode", "");
if ( !strcmp(mode_str, "looped") ) {
_mode = SGXmlSound::LOOPED;
} else if ( !strcmp(mode_str, "in-transit") ) {
_mode = SGXmlSound::IN_TRANSIT;
} else {
_mode = SGXmlSound::ONCE;
if ( strcmp(mode_str, "") )
SG_LOG(SG_GENERAL,SG_INFO, " Unknown sound mode, default to 'once'");
}
_property = root->getNode(node->getStringValue("property", ""), true);
SGPropertyNode *condition = node->getChild("condition");
if (condition != NULL)
_condition = sgReadCondition(root, condition);
if (!_property && !_condition)
SG_LOG(SG_GENERAL, SG_WARN,
" Neither a condition nor a property specified");
//
// set volume properties
//
unsigned int i;
float v = 0.0;
vector<SGPropertyNode_ptr> kids = node->getChildren("volume");
for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
_snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false};
if (strcmp(kids[i]->getStringValue("property"), ""))
volume.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
const char *intern_str = kids[i]->getStringValue("internal", "");
if (!strcmp(intern_str, "dt_play"))
volume.intern = &_dt_play;
else if (!strcmp(intern_str, "dt_stop"))
volume.intern = &_dt_stop;
if ((volume.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
if (volume.factor < 0.0) {
volume.factor = -volume.factor;
volume.subtract = true;
}
const char *type_str = kids[i]->getStringValue("type", "");
if ( strcmp(type_str, "") ) {
for (int j=0; __sound_fn[j].fn; j++)
if ( !strcmp(type_str, __sound_fn[j].name) ) {
volume.fn = __sound_fn[j].fn;
break;
}
if (!volume.fn)
SG_LOG(SG_GENERAL,SG_INFO,
" Unknown volume type, default to 'lin'");
}
volume.offset = kids[i]->getDoubleValue("offset", 0.0);
if ((volume.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
SG_LOG( SG_GENERAL, SG_WARN,
"Volume minimum value below 0. Forced to 0.");
volume.max = kids[i]->getDoubleValue("max", 0.0);
if (volume.max && (volume.max < volume.min) )
SG_LOG(SG_GENERAL,SG_ALERT,
" Volume maximum below minimum. Neglected.");
_volume.push_back(volume);
v += volume.offset;
}
float reference_dist = node->getDoubleValue("reference-dist", 500.0);
float max_dist = node->getDoubleValue("max-dist", 3000.0);
//
// set pitch properties
//
float p = 0.0;
kids = node->getChildren("pitch");
for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
_snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false};
if (strcmp(kids[i]->getStringValue("property", ""), ""))
pitch.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
const char *intern_str = kids[i]->getStringValue("internal", "");
if (!strcmp(intern_str, "dt_play"))
pitch.intern = &_dt_play;
else if (!strcmp(intern_str, "dt_stop"))
pitch.intern = &_dt_stop;
if ((pitch.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
if (pitch.factor < 0.0) {
pitch.factor = -pitch.factor;
pitch.subtract = true;
}
const char *type_str = kids[i]->getStringValue("type", "");
if ( strcmp(type_str, "") ) {
for (int j=0; __sound_fn[j].fn; j++)
if ( !strcmp(type_str, __sound_fn[j].name) ) {
pitch.fn = __sound_fn[j].fn;
break;
}
if (!pitch.fn)
SG_LOG(SG_GENERAL,SG_INFO,
" Unknown pitch type, default to 'lin'");
}
pitch.offset = kids[i]->getDoubleValue("offset", 1.0);
if ((pitch.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
SG_LOG(SG_GENERAL,SG_WARN,
" Pitch minimum value below 0. Forced to 0.");
pitch.max = kids[i]->getDoubleValue("max", 0.0);
if (pitch.max && (pitch.max < pitch.min) )
SG_LOG(SG_GENERAL,SG_ALERT,
" Pitch maximum below minimum. Neglected");
_pitch.push_back(pitch);
p += pitch.offset;
}
//
// Relative position
//
sgVec3 offset_pos;
sgSetVec3( offset_pos, 0.0, 0.0, 0.0 );
SGPropertyNode_ptr pos = node->getChild("position");
if ( pos != NULL ) {
offset_pos[0] = pos->getDoubleValue("x", 0.0);
offset_pos[1] = pos->getDoubleValue("y", 0.0);
offset_pos[2] = pos->getDoubleValue("z", 0.0);
}
//
// Orientation
//
sgVec3 dir;
float inner, outer, outer_gain;
sgSetVec3( dir, 0.0, 0.0, 0.0 );
inner = outer = 360.0;
outer_gain = 0.0;
pos = node->getChild("orientation");
if ( pos != NULL ) {
dir[0] = pos->getDoubleValue("x", 0.0);
dir[1] = pos->getDoubleValue("y", 0.0);
dir[2] = pos->getDoubleValue("z", 0.0);
inner = pos->getDoubleValue("inner-angle", 360.0);
outer = pos->getDoubleValue("outer-angle", 360.0);
outer_gain = pos->getDoubleValue("outer-gain", 0.0);
}
//
// Initialize the sample
//
_mgr = sndmgr;
if ( (_sample = _mgr->find(_name)) == NULL ) {
_sample = new SGSoundSample( path.c_str(),
node->getStringValue("path", ""),
true );
_mgr->add( _sample, _name );
}
_sample->set_offset_pos( offset_pos );
_sample->set_orientation(dir, inner, outer, outer_gain);
_sample->set_volume(v);
_sample->set_reference_dist( reference_dist );
_sample->set_max_dist( max_dist );
_sample->set_pitch(p);
}
void
SGXmlSound::update (double dt)
{
double curr_value = 0.0;
//
// If the state changes to false, stop playing.
//
if (_property)
curr_value = _property->getDoubleValue();
if ( // Lisp, anyone?
(_condition && !_condition->test()) ||
(!_condition && _property &&
(
!curr_value ||
( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) )
)
)
)
{
if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME)) {
if (_sample->is_playing()) {
SG_LOG(SG_GENERAL, SG_INFO, "Stopping audio after " << _dt_play
<< " sec: " << _name );
_sample->stop();
}
_active = false;
_dt_stop += dt;
_dt_play = 0.0;
} else {
_stopping += dt;
}
return;
}
//
// If the mode is ONCE and the sound is still playing,
// we have nothing to do anymore.
//
if (_active && (_mode == SGXmlSound::ONCE)) {
if (!_sample->is_playing()) {
_dt_stop += dt;
_dt_play = 0.0;
} else {
_dt_play += dt;
}
return;
}
//
// Update the playing time, cache the current value and
// clear the delay timer.
//
_dt_play += dt;
_prev_value = curr_value;
_stopping = 0.0;
//
// Update the volume
//
int i;
int max = _volume.size();
double volume = 1.0;
double volume_offset = 0.0;
for(i = 0; i < max; i++) {
double v = 1.0;
if (_volume[i].prop)
v = _volume[i].prop->getDoubleValue();
else if (_volume[i].intern)
v = *_volume[i].intern;
if (_volume[i].fn)
v = _volume[i].fn(v);
v *= _volume[i].factor;
if (_volume[i].max && (v > _volume[i].max))
v = _volume[i].max;
else if (v < _volume[i].min)
v = _volume[i].min;
if (_volume[i].subtract) // Hack!
volume = _volume[i].offset - v;
else {
volume_offset += _volume[i].offset;
volume *= v;
}
}
//
// Update the pitch
//
max = _pitch.size();
double pitch = 1.0;
double pitch_offset = 0.0;
for(i = 0; i < max; i++) {
double p = 1.0;
if (_pitch[i].prop)
p = _pitch[i].prop->getDoubleValue();
else if (_pitch[i].intern)
p = *_pitch[i].intern;
if (_pitch[i].fn)
p = _pitch[i].fn(p);
p *= _pitch[i].factor;
if (_pitch[i].max && (p > _pitch[i].max))
p = _pitch[i].max;
else if (p < _pitch[i].min)
p = _pitch[i].min;
if (_pitch[i].subtract) // Hack!
pitch = _pitch[i].offset - p;
else {
pitch_offset += _pitch[i].offset;
pitch *= p;
}
}
//
// Change sample state
//
_sample->set_pitch( pitch_offset + pitch );
if ((volume_offset + volume ) > 1.0)
{
_sample->set_volume( 1.0 );
SG_LOG(SG_GENERAL, SG_WARN,
"Volume larger than 1.0 in configuration for '" << _name
<< "', clipping.");
} else
_sample->set_volume( volume_offset + volume );
//
// Do we need to start playing the sample?
//
if (!_active) {
if (_mode == SGXmlSound::ONCE)
_sample->play(false);
else
_sample->play(true);
SG_LOG(SG_GENERAL, SG_INFO, "Playing audio after " << _dt_stop
<< " sec: " << _name);
SG_LOG(SG_GENERAL, SG_BULK,
"Playing " << ((_mode == ONCE) ? "once" : "looped"));
_active = true;
_dt_stop = 0.0;
}
}
<commit_msg>Add a code comment for future thought.<commit_after>// sound.cxx -- Sound class implementation
//
// Started by Erik Hofman, February 2002
// (Reuses some code from fg_fx.cxx created by David Megginson)
//
// Copyright (C) 2002 Curtis L. Olson - http://www.flightgear.org/~curt
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
#include <simgear/compiler.h>
#ifdef SG_HAVE_STD_INCLUDES
# include <cmath>
#else
# include <math.h>
#endif
#include <string.h>
#include <simgear/debug/logstream.hxx>
#include <simgear/props/condition.hxx>
#include <simgear/math/fastmath.hxx>
#include "xmlsound.hxx"
// static double _snd_lin(double v) { return v; }
static double _snd_inv(double v) { return (v == 0) ? 1e99 : 1/v; }
static double _snd_abs(double v) { return (v >= 0) ? v : -v; }
static double _snd_sqrt(double v) { return (v < 0) ? sqrt(-v) : sqrt(v); }
static double _snd_log10(double v) { return (v < 1) ? 0 : fast_log10(v); }
static double _snd_log(double v) { return (v < 1) ? 0 : fast_log(v); }
// static double _snd_sqr(double v) { return v*v; }
// static double _snd_pow3(double v) { return v*v*v; }
static const struct {
char *name;
double (*fn)(double);
} __sound_fn[] = {
// {"lin", _snd_lin},
{"inv", _snd_inv},
{"abs", _snd_abs},
{"sqrt", _snd_sqrt},
{"log", _snd_log10},
{"ln", _snd_log},
// {"sqr", _snd_sqr},
// {"pow3", _snd_pow3},
{"", NULL}
};
SGXmlSound::SGXmlSound()
: _sample(NULL),
_condition(NULL),
_property(NULL),
_active(false),
_name(""),
_mode(SGXmlSound::ONCE),
_prev_value(0),
_dt_play(0.0),
_dt_stop(0.0),
_stopping(0.0)
{
}
SGXmlSound::~SGXmlSound()
{
_sample->stop();
delete _property;
delete _condition;
_volume.clear();
_pitch.clear();
delete _sample;
}
void
SGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node, SGSoundMgr *sndmgr,
const string &path)
{
//
// set global sound properties
//
_name = node->getStringValue("name", "");
SG_LOG(SG_GENERAL, SG_INFO, "Loading sound information for: " << _name );
const char *mode_str = node->getStringValue("mode", "");
if ( !strcmp(mode_str, "looped") ) {
_mode = SGXmlSound::LOOPED;
} else if ( !strcmp(mode_str, "in-transit") ) {
_mode = SGXmlSound::IN_TRANSIT;
} else {
_mode = SGXmlSound::ONCE;
if ( strcmp(mode_str, "") )
SG_LOG(SG_GENERAL,SG_INFO, " Unknown sound mode, default to 'once'");
}
_property = root->getNode(node->getStringValue("property", ""), true);
SGPropertyNode *condition = node->getChild("condition");
if (condition != NULL)
_condition = sgReadCondition(root, condition);
if (!_property && !_condition)
SG_LOG(SG_GENERAL, SG_WARN,
" Neither a condition nor a property specified");
//
// set volume properties
//
unsigned int i;
float v = 0.0;
vector<SGPropertyNode_ptr> kids = node->getChildren("volume");
for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
_snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false};
if (strcmp(kids[i]->getStringValue("property"), ""))
volume.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
const char *intern_str = kids[i]->getStringValue("internal", "");
if (!strcmp(intern_str, "dt_play"))
volume.intern = &_dt_play;
else if (!strcmp(intern_str, "dt_stop"))
volume.intern = &_dt_stop;
if ((volume.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
if (volume.factor < 0.0) {
volume.factor = -volume.factor;
volume.subtract = true;
}
const char *type_str = kids[i]->getStringValue("type", "");
if ( strcmp(type_str, "") ) {
for (int j=0; __sound_fn[j].fn; j++)
if ( !strcmp(type_str, __sound_fn[j].name) ) {
volume.fn = __sound_fn[j].fn;
break;
}
if (!volume.fn)
SG_LOG(SG_GENERAL,SG_INFO,
" Unknown volume type, default to 'lin'");
}
volume.offset = kids[i]->getDoubleValue("offset", 0.0);
if ((volume.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
SG_LOG( SG_GENERAL, SG_WARN,
"Volume minimum value below 0. Forced to 0.");
volume.max = kids[i]->getDoubleValue("max", 0.0);
if (volume.max && (volume.max < volume.min) )
SG_LOG(SG_GENERAL,SG_ALERT,
" Volume maximum below minimum. Neglected.");
_volume.push_back(volume);
v += volume.offset;
}
float reference_dist = node->getDoubleValue("reference-dist", 500.0);
float max_dist = node->getDoubleValue("max-dist", 3000.0);
//
// set pitch properties
//
float p = 0.0;
kids = node->getChildren("pitch");
for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
_snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false};
if (strcmp(kids[i]->getStringValue("property", ""), ""))
pitch.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
const char *intern_str = kids[i]->getStringValue("internal", "");
if (!strcmp(intern_str, "dt_play"))
pitch.intern = &_dt_play;
else if (!strcmp(intern_str, "dt_stop"))
pitch.intern = &_dt_stop;
if ((pitch.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
if (pitch.factor < 0.0) {
pitch.factor = -pitch.factor;
pitch.subtract = true;
}
const char *type_str = kids[i]->getStringValue("type", "");
if ( strcmp(type_str, "") ) {
for (int j=0; __sound_fn[j].fn; j++)
if ( !strcmp(type_str, __sound_fn[j].name) ) {
pitch.fn = __sound_fn[j].fn;
break;
}
if (!pitch.fn)
SG_LOG(SG_GENERAL,SG_INFO,
" Unknown pitch type, default to 'lin'");
}
pitch.offset = kids[i]->getDoubleValue("offset", 1.0);
if ((pitch.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
SG_LOG(SG_GENERAL,SG_WARN,
" Pitch minimum value below 0. Forced to 0.");
pitch.max = kids[i]->getDoubleValue("max", 0.0);
if (pitch.max && (pitch.max < pitch.min) )
SG_LOG(SG_GENERAL,SG_ALERT,
" Pitch maximum below minimum. Neglected");
_pitch.push_back(pitch);
p += pitch.offset;
}
//
// Relative position
//
sgVec3 offset_pos;
sgSetVec3( offset_pos, 0.0, 0.0, 0.0 );
SGPropertyNode_ptr pos = node->getChild("position");
if ( pos != NULL ) {
offset_pos[0] = pos->getDoubleValue("x", 0.0);
offset_pos[1] = pos->getDoubleValue("y", 0.0);
offset_pos[2] = pos->getDoubleValue("z", 0.0);
}
//
// Orientation
//
sgVec3 dir;
float inner, outer, outer_gain;
sgSetVec3( dir, 0.0, 0.0, 0.0 );
inner = outer = 360.0;
outer_gain = 0.0;
pos = node->getChild("orientation");
if ( pos != NULL ) {
dir[0] = pos->getDoubleValue("x", 0.0);
dir[1] = pos->getDoubleValue("y", 0.0);
dir[2] = pos->getDoubleValue("z", 0.0);
inner = pos->getDoubleValue("inner-angle", 360.0);
outer = pos->getDoubleValue("outer-angle", 360.0);
outer_gain = pos->getDoubleValue("outer-gain", 0.0);
}
//
// Initialize the sample
//
_mgr = sndmgr;
if ( (_sample = _mgr->find(_name)) == NULL ) {
// FIXME: Does it make sense to overwrite a previous entry's
// configuration just because a new entry has the same name?
// Note that we can't match on identical "path" because we the
// new entry could be at a different location with different
// configuration so we need a new sample which creates a new
// "alSource". The semantics of what is going on here seems
// confused and needs to be thought through more carefully.
_sample = new SGSoundSample( path.c_str(),
node->getStringValue("path", ""),
true );
_mgr->add( _sample, _name );
}
_sample->set_offset_pos( offset_pos );
_sample->set_orientation(dir, inner, outer, outer_gain);
_sample->set_volume(v);
_sample->set_reference_dist( reference_dist );
_sample->set_max_dist( max_dist );
_sample->set_pitch(p);
}
void
SGXmlSound::update (double dt)
{
double curr_value = 0.0;
//
// If the state changes to false, stop playing.
//
if (_property)
curr_value = _property->getDoubleValue();
if ( // Lisp, anyone?
(_condition && !_condition->test()) ||
(!_condition && _property &&
(
!curr_value ||
( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) )
)
)
)
{
if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME)) {
if (_sample->is_playing()) {
SG_LOG(SG_GENERAL, SG_INFO, "Stopping audio after " << _dt_play
<< " sec: " << _name );
_sample->stop();
}
_active = false;
_dt_stop += dt;
_dt_play = 0.0;
} else {
_stopping += dt;
}
return;
}
//
// If the mode is ONCE and the sound is still playing,
// we have nothing to do anymore.
//
if (_active && (_mode == SGXmlSound::ONCE)) {
if (!_sample->is_playing()) {
_dt_stop += dt;
_dt_play = 0.0;
} else {
_dt_play += dt;
}
return;
}
//
// Update the playing time, cache the current value and
// clear the delay timer.
//
_dt_play += dt;
_prev_value = curr_value;
_stopping = 0.0;
//
// Update the volume
//
int i;
int max = _volume.size();
double volume = 1.0;
double volume_offset = 0.0;
for(i = 0; i < max; i++) {
double v = 1.0;
if (_volume[i].prop)
v = _volume[i].prop->getDoubleValue();
else if (_volume[i].intern)
v = *_volume[i].intern;
if (_volume[i].fn)
v = _volume[i].fn(v);
v *= _volume[i].factor;
if (_volume[i].max && (v > _volume[i].max))
v = _volume[i].max;
else if (v < _volume[i].min)
v = _volume[i].min;
if (_volume[i].subtract) // Hack!
volume = _volume[i].offset - v;
else {
volume_offset += _volume[i].offset;
volume *= v;
}
}
//
// Update the pitch
//
max = _pitch.size();
double pitch = 1.0;
double pitch_offset = 0.0;
for(i = 0; i < max; i++) {
double p = 1.0;
if (_pitch[i].prop)
p = _pitch[i].prop->getDoubleValue();
else if (_pitch[i].intern)
p = *_pitch[i].intern;
if (_pitch[i].fn)
p = _pitch[i].fn(p);
p *= _pitch[i].factor;
if (_pitch[i].max && (p > _pitch[i].max))
p = _pitch[i].max;
else if (p < _pitch[i].min)
p = _pitch[i].min;
if (_pitch[i].subtract) // Hack!
pitch = _pitch[i].offset - p;
else {
pitch_offset += _pitch[i].offset;
pitch *= p;
}
}
//
// Change sample state
//
_sample->set_pitch( pitch_offset + pitch );
if ((volume_offset + volume ) > 1.0)
{
_sample->set_volume( 1.0 );
SG_LOG(SG_GENERAL, SG_WARN,
"Volume larger than 1.0 in configuration for '" << _name
<< "', clipping.");
} else
_sample->set_volume( volume_offset + volume );
//
// Do we need to start playing the sample?
//
if (!_active) {
if (_mode == SGXmlSound::ONCE)
_sample->play(false);
else
_sample->play(true);
SG_LOG(SG_GENERAL, SG_INFO, "Playing audio after " << _dt_stop
<< " sec: " << _name);
SG_LOG(SG_GENERAL, SG_BULK,
"Playing " << ((_mode == ONCE) ? "once" : "looped"));
_active = true;
_dt_stop = 0.0;
}
}
<|endoftext|>
|
<commit_before>#include "earth.h"
//
// CONSTRUCTORS ////////////////////////////////////////////////////////////////
//
Earth::Earth()
: Planet( ":/texture/earth.jpg" )
{
transform.setScale( 0.09158f );
moon = new EarthMoon();
}
//
// OVERRIDDEN FUNCTIONS
//
void Earth::initializeGL()
{
Planet::initializeGL();
moon->initializeGL();
}
void Earth::paintGL( Camera3D& camera, QMatrix4x4& projection )
{
Planet::paintGL( camera, projection );
moon->paintGL( camera, projection );
}
void Earth::update()
{
if( Planet::SCALED )
updateScaled();
else
updateReal();
moon->update();
}
void Earth::teardownGL()
{
moon->teardownGL();
Planet::teardownGL();
}
//
// PRIVATE HELPER FUNCTIONS ////////////////////////////////////////////////////
//
void Earth::updateScaled()
{
// EARTH
{
transform.rotate( 1.0f, 0, 1, 0 );
}
// MOON
{
moon->transform.setScale(0.011f);
static float translationAngle = 0.0;
translationAngle += 0.0070;
moon->transform.setTranslation(
transform.translation().x() + 1.5f * sin(translationAngle),
transform.translation().y(),
transform.translation().z() + 1.5f * cos(translationAngle));
}
}
void Earth::updateReal()
{
}
<commit_msg>fixed realistic moon speed<commit_after>#include "earth.h"
//
// CONSTRUCTORS ////////////////////////////////////////////////////////////////
//
Earth::Earth()
: Planet( ":/texture/earth.jpg" )
{
transform.setScale( 0.09158f );
moon = new EarthMoon();
}
//
// OVERRIDDEN FUNCTIONS
//
void Earth::initializeGL()
{
Planet::initializeGL();
moon->initializeGL();
}
void Earth::paintGL( Camera3D& camera, QMatrix4x4& projection )
{
Planet::paintGL( camera, projection );
moon->paintGL( camera, projection );
}
void Earth::update()
{
if( Planet::SCALED )
updateScaled();
else
updateReal();
moon->update();
}
void Earth::teardownGL()
{
moon->teardownGL();
Planet::teardownGL();
}
//
// PRIVATE HELPER FUNCTIONS ////////////////////////////////////////////////////
//
void Earth::updateScaled()
{
// EARTH
{
transform.rotate( 1.0f, 0, 1, 0 );
}
// MOON
{
moon->transform.setScale(0.011f);
static float translationAngle = 0.0;
translationAngle += 0.70;
moon->transform.setTranslation(
transform.translation().x() + 1.5f * sin(translationAngle),
transform.translation().y(),
transform.translation().z() + 1.5f * cos(translationAngle));
}
}
void Earth::updateReal()
{
}
<|endoftext|>
|
<commit_before>#include <tests/Base.hh>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cmath>
#include <aleph/geometry/CoverTree.hh>
using namespace aleph::geometry;
template <class T> struct SimpleMetric
{
T operator()( T a, T b )
{
return std::abs( a - b );
}
};
template <class T> void testSimple()
{
ALEPH_TEST_BEGIN( "Simple" );
CoverTree<T,
SimpleMetric<T> > ct;
ct.insert( 7 );
ct.insert( 13 );
ct.insert( 10 );
ct.insert( 8 );
ct.insert( 9 );
ct.insert( 11 );
ct.insert( 12 );
ct.print( std::cerr );
ALEPH_ASSERT_THROW( ct.checkLevelInvariant() );
ALEPH_ASSERT_THROW( ct.checkCoveringInvariant() );
ALEPH_ASSERT_THROW( ct.checkSeparatingInvariant() );
ALEPH_TEST_END();
}
template <class T> void testSimplePermutations()
{
ALEPH_TEST_BEGIN( "Simple (using permutations)" );
std::vector<T> data = {7,8,9,10,11,12,13};
do
{
CoverTree<T,
SimpleMetric<T> > ct;
// Debug output ----------------------------------------------------
std::cerr << "Permutation: ";
for( auto&& x : data )
std::cerr << x << " ";
std::cerr << "\n";
// Check validity of tree ------------------------------------------
for( auto&& x : data )
ct.insert( x );
ALEPH_ASSERT_THROW( ct.checkLevelInvariant() );
ALEPH_ASSERT_THROW( ct.checkCoveringInvariant() );
ALEPH_ASSERT_THROW( ct.checkSeparatingInvariant() );
}
while( std::next_permutation( data.begin(), data.end() ) );
ALEPH_TEST_END();
}
template <class T> struct Point
{
T x;
T y;
bool operator<( const Point& other ) const noexcept
{
if( x == other.x )
return y < other.y;
else
return x < other.x;
}
};
template <class T> std::ostream& operator<<( std::ostream& o, const Point<T>& p )
{
o << p.x << "," << p.y;
return o;
}
template <class T> struct EuclideanMetric
{
T operator()( Point<T> a, Point<T> b )
{
return std::sqrt( std::pow( a.x - b.x, T(2) ) + std::pow( a.y - b.y, T(2) ) );
}
};
template <class T> bool contains( const Point<T>& centre, const Point<T>& p, T r )
{
EuclideanMetric<T> metric;
return metric( centre, p ) <= r;
}
template <class T> T distance( const Point<T>& centre, const Point<T>& p )
{
EuclideanMetric<T> metric;
return metric( centre, p );
}
template <class T> void test2D()
{
ALEPH_TEST_BEGIN( "2D" );
using Point = Point<T>;
using Metric = EuclideanMetric<T>;
using CoverTree = CoverTree<Point, Metric>;
CoverTree ct;
std::ifstream in( CMAKE_SOURCE_DIR + std::string( "/tests/input/Cover_tree_simple.txt" ) );
ALEPH_ASSERT_THROW( in );
std::vector<Point> points;
std::string line;
while( std::getline( in, line ) )
{
std::stringstream converter( line );
T x = T();
T y = T();
converter >> x
>> y;
ALEPH_ASSERT_THROW( not converter.fail() );
points.push_back( {x,y} );
}
ALEPH_ASSERT_EQUAL( points.size(), 15 );
for( auto&& p : points )
ct.insert( p );
ALEPH_ASSERT_THROW( ct.isValid() );
auto&& nodesByLevel = ct.getNodesByLevel();
// Determine radii, i.e. *level* of the original data set. Afterwards,
// using the corresponding point as the centre, we can check how often
// certain points are being covered.
std::map<Point, unsigned > covered;
std::multimap<Point, long> levels;
std::multimap<Point, T > distances;
for( auto&& pair : nodesByLevel )
{
auto&& level = pair.first;
auto&& centre = pair.second;
for( auto&& p : points )
{
// TODO: fix radius/level calculation; is this an implementation
// detail of the tree?
if( contains( centre, p, T( std::pow( T(2), level ) ) ) )
{
covered[p] += 1;
levels.insert( std::make_pair( p, level ) );
distances.insert( std::make_pair( p, distance( centre, p ) ) );
}
}
}
std::cerr << "# Cover counter\n";
for( auto&& pair : covered )
std::cerr << pair.first << ": " << pair.second << "\n";
std::cerr << "# Levels counter\n";
for( auto&& p : points )
{
std::cerr << p << ": ";
auto range = levels.equal_range( p );
for( auto it = range.first; it != range.second; ++it )
std::cerr << it->second << " ";
std::cerr << "\n";
}
std::cerr << "# Distances counter\n";
for( auto&& p : points )
{
std::cerr << p << ": ";
auto range = distances.equal_range( p );
for( auto it = range.first; it != range.second; ++it )
std::cerr << it->second << " ";
std::cerr << "\n";
}
std::cerr << "# Basic cover distance density\n";
for( auto&& p : points )
{
std::cerr << p << ": ";
auto range = distances.equal_range( p );
double distance = 0.0;
for( auto it = range.first; it != range.second; ++it )
distance += it->second;
distance /= static_cast<T>( std::distance( range.first, range.second ) );
std::cerr << distance << "\n";
}
ALEPH_ASSERT_EQUAL( nodesByLevel.size(), points.size() );
ALEPH_TEST_END();
}
int main( int, char** )
{
testSimple<double>();
testSimple<float> ();
testSimplePermutations<double>();
testSimplePermutations<float> ();
test2D<double>();
test2D<float> ();
}
<commit_msg>Debug output for visualization<commit_after>#include <tests/Base.hh>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cmath>
#include <aleph/geometry/CoverTree.hh>
using namespace aleph::geometry;
template <class T> struct SimpleMetric
{
T operator()( T a, T b )
{
return std::abs( a - b );
}
};
template <class T> void testSimple()
{
ALEPH_TEST_BEGIN( "Simple" );
CoverTree<T,
SimpleMetric<T> > ct;
ct.insert( 7 );
ct.insert( 13 );
ct.insert( 10 );
ct.insert( 8 );
ct.insert( 9 );
ct.insert( 11 );
ct.insert( 12 );
ct.print( std::cerr );
ALEPH_ASSERT_THROW( ct.checkLevelInvariant() );
ALEPH_ASSERT_THROW( ct.checkCoveringInvariant() );
ALEPH_ASSERT_THROW( ct.checkSeparatingInvariant() );
ALEPH_TEST_END();
}
template <class T> void testSimplePermutations()
{
ALEPH_TEST_BEGIN( "Simple (using permutations)" );
std::vector<T> data = {7,8,9,10,11,12,13};
do
{
CoverTree<T,
SimpleMetric<T> > ct;
// Debug output ----------------------------------------------------
std::cerr << "Permutation: ";
for( auto&& x : data )
std::cerr << x << " ";
std::cerr << "\n";
// Check validity of tree ------------------------------------------
for( auto&& x : data )
ct.insert( x );
ALEPH_ASSERT_THROW( ct.checkLevelInvariant() );
ALEPH_ASSERT_THROW( ct.checkCoveringInvariant() );
ALEPH_ASSERT_THROW( ct.checkSeparatingInvariant() );
}
while( std::next_permutation( data.begin(), data.end() ) );
ALEPH_TEST_END();
}
template <class T> struct Point
{
T x;
T y;
bool operator<( const Point& other ) const noexcept
{
if( x == other.x )
return y < other.y;
else
return x < other.x;
}
};
template <class T> std::ostream& operator<<( std::ostream& o, const Point<T>& p )
{
o << p.x << "," << p.y;
return o;
}
template <class T> struct EuclideanMetric
{
T operator()( Point<T> a, Point<T> b )
{
return std::sqrt( std::pow( a.x - b.x, T(2) ) + std::pow( a.y - b.y, T(2) ) );
}
};
template <class T> bool contains( const Point<T>& centre, const Point<T>& p, T r )
{
EuclideanMetric<T> metric;
return metric( centre, p ) <= r;
}
template <class T> T distance( const Point<T>& centre, const Point<T>& p )
{
EuclideanMetric<T> metric;
return metric( centre, p );
}
template <class T> void test2D()
{
ALEPH_TEST_BEGIN( "2D" );
using Point = Point<T>;
using Metric = EuclideanMetric<T>;
using CoverTree = CoverTree<Point, Metric>;
CoverTree ct;
std::ifstream in( CMAKE_SOURCE_DIR + std::string( "/tests/input/Cover_tree_simple.txt" ) );
ALEPH_ASSERT_THROW( in );
std::vector<Point> points;
std::string line;
while( std::getline( in, line ) )
{
std::stringstream converter( line );
T x = T();
T y = T();
converter >> x
>> y;
ALEPH_ASSERT_THROW( not converter.fail() );
points.push_back( {x,y} );
}
ALEPH_ASSERT_EQUAL( points.size(), 15 );
for( auto&& p : points )
ct.insert( p );
ALEPH_ASSERT_THROW( ct.isValid() );
auto&& nodesByLevel = ct.getNodesByLevel();
// Determine radii, i.e. *level* of the original data set. Afterwards,
// using the corresponding point as the centre, we can check how often
// certain points are being covered.
std::map<Point, unsigned > covered;
std::multimap<Point, long> levels;
std::multimap<Point, T > distances;
for( auto&& pair : nodesByLevel )
{
auto&& level = pair.first;
auto&& centre = pair.second;
for( auto&& p : points )
{
// TODO: fix radius/level calculation; is this an implementation
// detail of the tree?
if( contains( centre, p, T( std::pow( T(2), level ) ) ) )
{
covered[p] += 1;
levels.insert( std::make_pair( p, level ) );
distances.insert( std::make_pair( p, distance( centre, p ) ) );
}
}
}
std::cerr << "# Cover counter\n";
for( auto&& pair : covered )
std::cerr << pair.first << ": " << pair.second << "\n";
std::cerr << "# Levels counter\n";
for( auto&& p : points )
{
std::cerr << p << ": ";
auto range = levels.equal_range( p );
for( auto it = range.first; it != range.second; ++it )
std::cerr << it->second << " ";
std::cerr << "\n";
}
std::cerr << "# Distances counter\n";
for( auto&& p : points )
{
std::cerr << p << ": ";
auto range = distances.equal_range( p );
for( auto it = range.first; it != range.second; ++it )
std::cerr << it->second << " ";
std::cerr << "\n";
}
std::cerr << "# Basic cover distance density\n";
for( auto&& p : points )
{
std::cerr << p << ": ";
auto range = distances.equal_range( p );
double distance = 0.0;
for( auto it = range.first; it != range.second; ++it )
distance += it->second;
distance /= static_cast<T>( std::distance( range.first, range.second ) );
std::cerr << distance << "\n";
}
// DEBUG: output of cover radii --------------------------------------
{
std::ofstream out( "/tmp/C.txt" );
for( auto&& pair : nodesByLevel )
{
auto&& level = pair.first;
auto&& centre = pair.second;
auto r = std::pow( T(2), level );
out << centre << " " << r << "\n";
}
}
ALEPH_ASSERT_EQUAL( nodesByLevel.size(), points.size() );
ALEPH_TEST_END();
}
int main( int, char** )
{
testSimple<double>();
testSimple<float> ();
testSimplePermutations<double>();
testSimplePermutations<float> ();
test2D<double>();
test2D<float> ();
}
<|endoftext|>
|
<commit_before>#include "FitsObject.h"
#include <stdexcept>
using namespace std;
Fits::Fits(const string &filename)
: m_status(0), m_filename(filename)
{
fits_open_file(&*this->fptr(), this->m_filename.c_str(), READWRITE, &this->status());
this->check();
}
Fits::Fits() {}
Fits::~Fits()
{
fits_close_file(*this->fptr(), &this->status());
this->check();
}
void Fits::check()
{
if (this->status())
{
char buf[FLEN_STATUS];
fits_get_errstatus(this->status(), buf);
//Have to set the status back to 0 otherwise
//when the destructor is called and the file is closed
//then another exception will be thrown
this->status() = 0;
// Ensure the marks are not visible
fits_clear_errmsg();
throw runtime_error(buf);
}
}
void Fits::moveHDU(const string &hduname)
{
fits_movnam_hdu(*this->fptr(), ANY_HDU, const_cast<char*>(hduname.c_str()), 0, &this->status());
this->check();
}
void Fits::moveHDU(int hdunum)
{
int hdutype;
fits_movabs_hdu(*this->fptr(), hdunum, &hdutype, &this->status());
this->check();
}
void Fits::checkForTable()
{
/* Checks for a table extension */
int hdutype;
fits_get_hdu_type(*this->fptr(), &hdutype, &this->status());
this->check();
if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL))
{
throw runtime_error("Non-table hdu found");
}
}
int Fits::columnNumber(const std::string &colname)
{
this->checkForTable();
int colnum;
fits_get_colnum(*this->fptr(), CASEINSEN, const_cast<char*>(colname.c_str()), &colnum, &this->status());
this->check();
return colnum;
}
long Fits::nrows()
{
// Ensure the current hdu is a (binary) table
this->checkForTable();
int hdutype;
fits_get_hdu_type(*this->fptr(), &hdutype, &this->status());
this->check();
if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL))
{
throw runtime_error("Non-table hdu found");
}
long nrows;
fits_get_num_rows(*this->fptr(), &nrows, &this->status());
this->check();
return nrows;
}
fitsfile **Fits::fptr() { return &this->m_fptr; }
int &Fits::status() { return this->m_status; }
void Fits::check(int status)
{
if (status)
{
char buf[FLEN_STATUS];
fits_get_errstatus(status, buf);
throw runtime_error(buf);
}
}
const string Fits::hduname()
{
char buf[FLEN_VALUE];
fits_read_key(*this->fptr(), TSTRING, "EXTNAME", buf, NULL, &this->status());
this->check();
return string(buf);
}
NewFits::NewFits(const string &filename)
{
this->m_filename = filename;
this->status() = 0;
fits_create_file(&*this->fptr(), filename.c_str(), &this->status());
this->check();
/* Ensure the basic keywords are there */
long naxes[] = {0, 0};
fits_create_img(*this->fptr(), BYTE_IMG, 0, naxes, &this->status());
this->check();
}
vector<string> Fits::stringColumn(const string &columnname)
{
int colno = this->columnNumber(columnname);
long nrows = this->nrows();
int dispwidth;
fits_get_col_display_width(*this->fptr(), colno, &dispwidth, &this->status());
vector<string> Objects;
for (int i=0; i<nrows; ++i)
{
char Name[dispwidth+1], *nptr=(char*)Name;
fits_read_col_str(*this->fptr(), colno, i+1, 1, 1, "", &nptr, NULL, &this->status());
this->check();
Objects.push_back(Name);
}
return Objects;
}
<commit_msg>checking at the end of new function<commit_after>#include "FitsObject.h"
#include <stdexcept>
using namespace std;
Fits::Fits(const string &filename)
: m_status(0), m_filename(filename)
{
fits_open_file(&*this->fptr(), this->m_filename.c_str(), READWRITE, &this->status());
this->check();
}
Fits::Fits() {}
Fits::~Fits()
{
fits_close_file(*this->fptr(), &this->status());
this->check();
}
void Fits::check()
{
if (this->status())
{
char buf[FLEN_STATUS];
fits_get_errstatus(this->status(), buf);
//Have to set the status back to 0 otherwise
//when the destructor is called and the file is closed
//then another exception will be thrown
this->status() = 0;
// Ensure the marks are not visible
fits_clear_errmsg();
throw runtime_error(buf);
}
}
void Fits::moveHDU(const string &hduname)
{
fits_movnam_hdu(*this->fptr(), ANY_HDU, const_cast<char*>(hduname.c_str()), 0, &this->status());
this->check();
}
void Fits::moveHDU(int hdunum)
{
int hdutype;
fits_movabs_hdu(*this->fptr(), hdunum, &hdutype, &this->status());
this->check();
}
void Fits::checkForTable()
{
/* Checks for a table extension */
int hdutype;
fits_get_hdu_type(*this->fptr(), &hdutype, &this->status());
this->check();
if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL))
{
throw runtime_error("Non-table hdu found");
}
}
int Fits::columnNumber(const std::string &colname)
{
this->checkForTable();
int colnum;
fits_get_colnum(*this->fptr(), CASEINSEN, const_cast<char*>(colname.c_str()), &colnum, &this->status());
this->check();
return colnum;
}
long Fits::nrows()
{
// Ensure the current hdu is a (binary) table
this->checkForTable();
int hdutype;
fits_get_hdu_type(*this->fptr(), &hdutype, &this->status());
this->check();
if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL))
{
throw runtime_error("Non-table hdu found");
}
long nrows;
fits_get_num_rows(*this->fptr(), &nrows, &this->status());
this->check();
return nrows;
}
fitsfile **Fits::fptr() { return &this->m_fptr; }
int &Fits::status() { return this->m_status; }
void Fits::check(int status)
{
if (status)
{
char buf[FLEN_STATUS];
fits_get_errstatus(status, buf);
throw runtime_error(buf);
}
}
const string Fits::hduname()
{
char buf[FLEN_VALUE];
fits_read_key(*this->fptr(), TSTRING, "EXTNAME", buf, NULL, &this->status());
this->check();
return string(buf);
}
NewFits::NewFits(const string &filename)
{
this->m_filename = filename;
this->status() = 0;
fits_create_file(&*this->fptr(), filename.c_str(), &this->status());
this->check();
/* Ensure the basic keywords are there */
long naxes[] = {0, 0};
fits_create_img(*this->fptr(), BYTE_IMG, 0, naxes, &this->status());
this->check();
}
vector<string> Fits::stringColumn(const string &columnname)
{
int colno = this->columnNumber(columnname);
long nrows = this->nrows();
int dispwidth;
fits_get_col_display_width(*this->fptr(), colno, &dispwidth, &this->status());
vector<string> Objects;
for (int i=0; i<nrows; ++i)
{
char Name[dispwidth+1], *nptr=(char*)Name;
fits_read_col_str(*this->fptr(), colno, i+1, 1, 1, "", &nptr, NULL, &this->status());
this->check();
Objects.push_back(Name);
}
this->check();
return Objects;
}
<|endoftext|>
|
<commit_before>// Eflags register
#define FL_CF 0x00000001 // Carry Flag
#define FL_PF 0x00000004 // Parity Flag
#define FL_AF 0x00000010 // Auxiliary carry Flag
#define FL_ZF 0x00000040 // Zero Flag
#define FL_SF 0x00000080 // Sign Flag
#define FL_TF 0x00000100 // Trap Flag
#define FL_IF 0x00000200 // Interrupt Enable
#define FL_DF 0x00000400 // Direction Flag
#define FL_OF 0x00000800 // Overflow Flag
#define FL_IOPL_MASK 0x00003000 // I/O Privilege Level bitmask
#define FL_IOPL_0 0x00000000 // IOPL == 0
#define FL_IOPL_1 0x00001000 // IOPL == 1
#define FL_IOPL_2 0x00002000 // IOPL == 2
#define FL_IOPL_3 0x00003000 // IOPL == 3
#define FL_NT 0x00004000 // Nested Task
#define FL_RF 0x00010000 // Resume Flag
#define FL_VM 0x00020000 // Virtual 8086 mode
#define FL_AC 0x00040000 // Alignment Check
#define FL_VIF 0x00080000 // Virtual Interrupt Flag
#define FL_VIP 0x00100000 // Virtual Interrupt Pending
#define FL_ID 0x00200000 // ID flag
// Page fault error codes
#define FEC_PR 0x1 // Page fault caused by protection violation
#define FEC_WR 0x2 // Page fault caused by a write
#define FEC_U 0x4 // Page fault occured while in user mode
// Control Register flags
#define CR0_PE 0x00000001 // Protection Enable
#define CR0_MP 0x00000002 // Monitor coProcessor
#define CR0_EM 0x00000004 // Emulation
#define CR0_TS 0x00000008 // Task Switched
#define CR0_ET 0x00000010 // Extension Type
#define CR0_NE 0x00000020 // Numeric Errror
#define CR0_WP 0x00010000 // Write Protect
#define CR0_AM 0x00040000 // Alignment Mask
#define CR0_NW 0x20000000 // Not Writethrough
#define CR0_CD 0x40000000 // Cache Disable
#define CR0_PG 0x80000000 // Paging
#define CR4_PCE 0x100 // RDPMC at CPL > 0
// FS/GS base registers
#define MSR_FS_BASE 0xc0000100
#define MSR_GS_BASE 0xc0000101
#define MSR_GS_KERNBASE 0xc0000102
// SYSCALL and SYSRET registers
#define MSR_STAR 0xc0000081
#define MSR_LSTAR 0xc0000082
#define MSR_CSTAR 0xc0000083
#define MSR_SFMASK 0xc0000084
// AMD performance event-select registers
#define MSR_AMD_PERF_SEL0 0xC0010000
#define MSR_AMD_PERF_SEL1 0xC0010001
#define MSR_AMD_PERF_SEL2 0xC0010002
#define MSR_AMD_PERF_SEL3 0xC0010003
// AMD performance event-count registers
#define MSR_AMD_PERF_CNT0 0xC0010004
#define MSR_AMD_PERF_CNT1 0xC0010005
#define MSR_AMD_PERF_CNT2 0xC0010006
#define MSR_AMD_PERF_CNT3 0xC0010007
// Intel performance event-select registers
#define MSR_INTEL_PERF_SEL0 0x00000186
#define MSR_INTEL_PERF_SEL1 0x00000187
// Intel performance event-count registers
#define MSR_INTEL_PERF_CNT0 0x000000c1
#define MSR_INTEL_PERF_CNT1 0x000000c2
// Common event-select bits
#define PERF_SEL_USR (1ULL << 16)
#define PERF_SEL_OS (1ULL << 17)
#define PERF_SEL_EDGE (1ULL << 18)
#define PERF_SEL_INT (1ULL << 20)
#define PERF_SEL_ENABLE (1ULL << 22)
#define PERF_SEL_INV (1ULL << 23)
// CPUID function 0x00000001
#define CPUID_FEATURES 0x00000001
#define FEATURE_ECX_MWAIT (1 << 3)
#define FEATURE_EBX_APIC(x) (((x) >> 24) & 0xff)
#define FEATURE_EDX_APIC (1 << 8) // "APIC on chip"
// CPUID function 0x00000005
#define CPUID_MWAIT 0x00000005
// APIC Base Address Register MSR
#define MSR_APIC_BAR 0x0000001b
#define APIC_BAR_XAPIC_EN (1 << 11)
#define APIC_BAR_X2APIC_EN (1 << 10)
<commit_msg>Oops. Fix incorrect CPUID APIC bit definition<commit_after>// Eflags register
#define FL_CF 0x00000001 // Carry Flag
#define FL_PF 0x00000004 // Parity Flag
#define FL_AF 0x00000010 // Auxiliary carry Flag
#define FL_ZF 0x00000040 // Zero Flag
#define FL_SF 0x00000080 // Sign Flag
#define FL_TF 0x00000100 // Trap Flag
#define FL_IF 0x00000200 // Interrupt Enable
#define FL_DF 0x00000400 // Direction Flag
#define FL_OF 0x00000800 // Overflow Flag
#define FL_IOPL_MASK 0x00003000 // I/O Privilege Level bitmask
#define FL_IOPL_0 0x00000000 // IOPL == 0
#define FL_IOPL_1 0x00001000 // IOPL == 1
#define FL_IOPL_2 0x00002000 // IOPL == 2
#define FL_IOPL_3 0x00003000 // IOPL == 3
#define FL_NT 0x00004000 // Nested Task
#define FL_RF 0x00010000 // Resume Flag
#define FL_VM 0x00020000 // Virtual 8086 mode
#define FL_AC 0x00040000 // Alignment Check
#define FL_VIF 0x00080000 // Virtual Interrupt Flag
#define FL_VIP 0x00100000 // Virtual Interrupt Pending
#define FL_ID 0x00200000 // ID flag
// Page fault error codes
#define FEC_PR 0x1 // Page fault caused by protection violation
#define FEC_WR 0x2 // Page fault caused by a write
#define FEC_U 0x4 // Page fault occured while in user mode
// Control Register flags
#define CR0_PE 0x00000001 // Protection Enable
#define CR0_MP 0x00000002 // Monitor coProcessor
#define CR0_EM 0x00000004 // Emulation
#define CR0_TS 0x00000008 // Task Switched
#define CR0_ET 0x00000010 // Extension Type
#define CR0_NE 0x00000020 // Numeric Errror
#define CR0_WP 0x00010000 // Write Protect
#define CR0_AM 0x00040000 // Alignment Mask
#define CR0_NW 0x20000000 // Not Writethrough
#define CR0_CD 0x40000000 // Cache Disable
#define CR0_PG 0x80000000 // Paging
#define CR4_PCE 0x100 // RDPMC at CPL > 0
// FS/GS base registers
#define MSR_FS_BASE 0xc0000100
#define MSR_GS_BASE 0xc0000101
#define MSR_GS_KERNBASE 0xc0000102
// SYSCALL and SYSRET registers
#define MSR_STAR 0xc0000081
#define MSR_LSTAR 0xc0000082
#define MSR_CSTAR 0xc0000083
#define MSR_SFMASK 0xc0000084
// AMD performance event-select registers
#define MSR_AMD_PERF_SEL0 0xC0010000
#define MSR_AMD_PERF_SEL1 0xC0010001
#define MSR_AMD_PERF_SEL2 0xC0010002
#define MSR_AMD_PERF_SEL3 0xC0010003
// AMD performance event-count registers
#define MSR_AMD_PERF_CNT0 0xC0010004
#define MSR_AMD_PERF_CNT1 0xC0010005
#define MSR_AMD_PERF_CNT2 0xC0010006
#define MSR_AMD_PERF_CNT3 0xC0010007
// Intel performance event-select registers
#define MSR_INTEL_PERF_SEL0 0x00000186
#define MSR_INTEL_PERF_SEL1 0x00000187
// Intel performance event-count registers
#define MSR_INTEL_PERF_CNT0 0x000000c1
#define MSR_INTEL_PERF_CNT1 0x000000c2
// Common event-select bits
#define PERF_SEL_USR (1ULL << 16)
#define PERF_SEL_OS (1ULL << 17)
#define PERF_SEL_EDGE (1ULL << 18)
#define PERF_SEL_INT (1ULL << 20)
#define PERF_SEL_ENABLE (1ULL << 22)
#define PERF_SEL_INV (1ULL << 23)
// CPUID function 0x00000001
#define CPUID_FEATURES 0x00000001
#define FEATURE_ECX_MWAIT (1 << 3)
#define FEATURE_EBX_APIC(x) (((x) >> 24) & 0xff)
#define FEATURE_EDX_APIC (1 << 9) // "APIC on chip"
// CPUID function 0x00000005
#define CPUID_MWAIT 0x00000005
// APIC Base Address Register MSR
#define MSR_APIC_BAR 0x0000001b
#define APIC_BAR_XAPIC_EN (1 << 11)
#define APIC_BAR_X2APIC_EN (1 << 10)
<|endoftext|>
|
<commit_before>#include "Common.hpp"
#include "raycaster/Raycaster.hpp"
#include "helpers/Random.hpp"
#include "input/Input.hpp"
#include "input/InputCallbacks.hpp"
#include "input/ControllableCamera.hpp"
#include "helpers/System.hpp"
#include "resources/ResourcesManager.hpp"
#include "graphics/ScreenQuad.hpp"
#include "Config.hpp"
#include <thread>
/**
\defgroup RaytracerDemo Raytracer demo
\brief A basic ray tracing demo.
\ingroup Applications
*/
/**
The main function of the demo.
\param argc the number of input arguments.
\param argv a pointer to the raw input arguments.
\return a general error code.
\ingroup RaytracerDemo
*/
int main(int argc, char** argv) {
// Initialize random generator;
Random::seed();
Resources::manager().addResources("../../../resources/pbrdemo");
// Load geometry and create raycaster.
const MeshInfos * mesh = Resources::manager().getMesh("dragon", Storage::CPU);
Log::Info() << mesh->geometry.positions.size() << " vertices, " << mesh->geometry.indices.size()/3 << " triangles." << std::endl;
Raycaster raycaster;
raycaster.addMesh(mesh->geometry);
raycaster.updateHierarchy();
// Load model texture.
TextureInfos *texture = Resources::manager().getTexture("dragon_texture_color", {}, Storage::CPU);
Image & image = texture->images[0];
// Light direction.
const glm::vec3 l = glm::normalize(glm::vec3(1.0));
// Result image.
Image render(512, 512, 3);
// Setup camera.
Camera camera;
camera.pose(glm::vec3(0.0f, 0.0f, 2.0f), glm::vec3(0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
camera.projection(1.0, 2.5f, 0.01f, 100.0f);
// We only care about the X,Y transformation of the projection matrix.
const glm::mat3 invP = glm::mat3(glm::inverse(glm::mat2(camera.projection())));
const glm::mat3 invVP = glm::inverse(glm::mat3(camera.view())) * invP;
// Start chrono.
auto start = std::chrono::steady_clock::now();
// Get the maximum number of threads.
const size_t threadsCount = std::max(std::thread::hardware_concurrency(), unsigned(1));
std::vector<std::thread> threads(threadsCount);
for(size_t tid = 0; tid < threadsCount; ++tid){
// For each thread, create the same lambda, with different loop bounds values passed as arguments.
const unsigned int loopLow = (unsigned int)(tid) * render.height / (unsigned int)(threadsCount);
const unsigned int loopHigh = (tid == threadsCount - 1) ? render.height : ((unsigned int)(tid) + 1) * render.height/ (unsigned int)(threadsCount);
threads[tid] = std::thread(std::bind( [&](const unsigned int lo, const unsigned int hi) {
// This is the loop we want to parallelize.
// Loop over all the pixels.
for(unsigned int y = lo; y < hi; ++y){
for(unsigned int x = 0; x < render.width; ++x){
// Derive a position on the image plane from the pixel.
glm::vec2 ndcSpace = 2.0f*(glm::vec2(x,y) + 0.5f) / glm::vec2(render.width, render.height) - 1.0f;
ndcSpace.y *= -1.0f;
// Place the point on the near plane in clip space.
const glm::vec3 worldPos = invVP * glm::vec3(ndcSpace, -1.0f);
const glm::vec3 worldDir = worldPos - camera.position();
// Query closest intersection.
const Raycaster::RayHit hit = raycaster.intersects(camera.position(), worldDir);
// If no hit, background.
if(!hit.hit){
render.rgb(x,y) = glm::vec3(0.0f, 0.0f, 0.0f);
continue;
}
// Else, compute third barycentric coordinates...
const float w = 1.0f - hit.u - hit.v;
// Fetch geometry infos...
const unsigned long triangleId = hit.localId;
const unsigned long i0 = mesh->geometry.indices[triangleId];
const unsigned long i1 = mesh->geometry.indices[triangleId+1];
const unsigned long i2 = mesh->geometry.indices[triangleId+2];
// And interpolate the UVs and normal.
const glm::vec2 uv = w * mesh->geometry.texcoords[i0]
+ hit.u * mesh->geometry.texcoords[i1]
+ hit.v * mesh->geometry.texcoords[i2];
const glm::vec3 n = glm::normalize(w * mesh->geometry.normals[i0] + hit.u * mesh->geometry.normals[i1] + hit.v * mesh->geometry.normals[i2]);
// Compute lighting.
const float diffuse = std::max(0.0f, glm::dot(n, l));
// Fetch base color from texture.
const glm::vec3 baseColor = image.rgb(int(std::floor(uv.x * float(image.width))), int(std::floor(uv.y * float(image.height))));
// Done.
render.rgb(x,y) = diffuse * baseColor;
}
}
}, loopLow, loopHigh));
}
// Wait for all threads to finish.
std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});
// Display duration.
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);
Log::Info() << "Generation took " << duration.count() << " ms at " << render.width << "x" << render.height << "." << std::endl;
// Save image.
ImageUtilities::saveLDRImage("./test.png", render, false);
return 0;
}
<commit_msg>Raytracer: use a scene and the new parallel for.<commit_after>#include "Common.hpp"
#include "Config.hpp"
#include "raycaster/Raycaster.hpp"
#include "input/Input.hpp"
#include "input/InputCallbacks.hpp"
#include "input/ControllableCamera.hpp"
#include "scene/Scene.hpp"
#include "resources/ResourcesManager.hpp"
#include "graphics/ScreenQuad.hpp"
#include "helpers/Random.hpp"
#include "helpers/System.hpp"
#include <thread>
/**
\defgroup RaytracerDemo Raytracer demo
\brief A basic ray tracing demo.
\ingroup Applications
*/
/**
The main function of the demo.
\param argc the number of input arguments.
\param argv a pointer to the raw input arguments.
\return a general error code.
\ingroup RaytracerDemo
*/
int main(int argc, char** argv) {
// Initialize random generator;
Random::seed();
Resources::manager().addResources("../../../resources/pbrdemo");
Resources::manager().addResources("../../../resources/additional");
// Load geometry and create raycaster.
Scene scene("cornellbox");
scene.init(Storage::CPU);
Raycaster raycaster;
for(const auto & obj : scene.objects){
raycaster.addMesh(obj.mesh()->geometry);
}
raycaster.updateHierarchy();
// Light direction.
const glm::vec3 l = glm::normalize(glm::vec3(1.0));
// Result image.
Image render(512, 512, 3);
// Setup camera.
Camera camera;
camera.pose(glm::vec3(0.0f, 1.0f, 2.0f), glm::vec3(0.0f, 1.5f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
camera.projection(1.0, 2.5f, 0.01f, 100.0f);
// We only care about the X,Y transformation of the projection matrix.
const glm::mat3 invP = glm::mat3(glm::inverse(glm::mat2(camera.projection())));
const glm::mat3 invVP = glm::inverse(glm::mat3(camera.view())) * invP;
// Start chrono.
auto start = std::chrono::steady_clock::now();
// Get the maximum number of threads.
System::forParallel(0, render.height, [&](size_t y){
for(unsigned int x = 0; x < render.width; ++x){
// Derive a position on the image plane from the pixel.
glm::vec2 ndcSpace = 2.0f*(glm::vec2(x,y) + 0.5f) / glm::vec2(render.width, render.height) - 1.0f;
ndcSpace.y *= -1.0f;
// Place the point on the near plane in clip space.
const glm::vec3 worldPos = invVP * glm::vec3(ndcSpace, -1.0f);
const glm::vec3 worldDir = worldPos - camera.position();
// Query closest intersection.
const Raycaster::RayHit hit = raycaster.intersects(camera.position(), worldDir);
// If no hit, background.
if(!hit.hit){
render.rgb(x,y) = glm::vec3(0.0f, 0.0f, 0.0f);
continue;
}
// Fetch geometry infos...
const unsigned long meshId = hit.meshId;
const auto * mesh = scene.objects[meshId].mesh();
const glm::vec3 n = Raycaster::interpolateNormal(hit, mesh->geometry);
const glm::vec2 uv = Raycaster::interpolateUV(hit, mesh->geometry);
// Compute lighting.
const float diffuse = std::max(0.0f, glm::dot(n, l)) + 0.1;
// Fetch base color from texture.
const Image & image = scene.objects[meshId].textures()[0]->images[0];
const int px = int(std::floor(uv.x * float(image.width)));
const int py = int(std::floor(uv.y * float(image.height)));
const glm::vec3 baseColor = image.rgbc(px, py);
// Modulate and store.
render.rgb(x,y) = diffuse * baseColor;
}
});
// Display duration.
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);
Log::Info() << "Generation took " << duration.count() << " ms at " << render.width << "x" << render.height << "." << std::endl;
// Save image.
ImageUtilities::saveLDRImage("./test.png", render, false);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Jamoma DSP Wavetable Oscillator
* Copyright © 2003, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTWavetable.h"
#define thisTTClass TTWavetable
#define thisTTClassName "wavetable"
#define thisTTClassTags "audio, generator, oscillator, buffer"
TT_AUDIO_CONSTRUCTOR,
mIndex(0.0),
mIndexDelta(0.0),
mBuffer(NULL)
{
TTUInt16 initialMaxNumChannels = arguments;
addAttributeWithSetter(Frequency, kTypeFloat64);
addAttributeWithSetter(Mode, kTypeSymbol);
addAttributeWithSetter(Gain, kTypeFloat64);
addAttributeWithSetter(Interpolation, kTypeSymbol);
addAttributeWithSetter(Size, kTypeUInt32);
addUpdates(SampleRate);
TTObjectInstantiate(TT("buffer"), (TTObjectPtr*)&mBuffer, kTTValNONE);
if (!mBuffer)
throw TTException("Could not create internal buffer object");
mBuffer->setNumChannels(TTUInt32(1));
// Set Defaults...
setAttributeValue(TT("maxNumChannels"), initialMaxNumChannels);
setAttributeValue(TT("size"), 8192);
setAttributeValue(TT("mode"), kTTSym_sine);
setAttributeValue(TT("frequency"), 440.0);
setAttributeValue(TT("gain"), 0.0); // 0 dB
setAttributeValue(TT("interpolation"), TT("linear"));
}
TTWavetable::~TTWavetable()
{
TTObjectRelease((TTObject**)&mBuffer);
}
TTErr TTWavetable::updateSampleRate(const TTValue&, TTValue&)
{
setAttributeValue(TT("frequency"), mFrequency);
return kTTErrNone;
}
TTErr TTWavetable::setFrequency(const TTValue& newValue)
{
mFrequency = TTClip<TTFloat64>(newValue, 0.0, sr/2.0);
mIndexDelta = mFrequency * mSize * srInv;
return kTTErrNone;
}
TTErr TTWavetable::setMode(const TTValue& newValue)
{
mMode = newValue; // TODO: should be newValue[0]
if (mMode != TT("externalBuffer"))
return mBuffer->fill(newValue, kTTValNONE);
else {
// TODO: implement the ability to use an externally defined buffer
return kTTErrInvalidValue;
}
}
TTErr TTWavetable::setInterpolation(const TTValue& newValue)
{
mMode = newValue;
if (mMode == TT("linear"))
setProcessMethod(processWithLinearInterpolation);
else if (mMode == TT("lfo"))
setProcessMethod(processAsLFO);
else
setProcessMethod(processWithNoInterpolation);
return kTTErrNone;
}
TTErr TTWavetable::setGain(const TTValue& newValue)
{
mGain = newValue;
mLinearGain = TTDecibelsToLinearGain(mGain);
return kTTErrNone;
}
TTErr TTWavetable::setSize(const TTValue& newSize)
{
mSize = newSize;
mBuffer->setLengthInSamples(mSize);
return setFrequency(mFrequency); // touch the frequency so that the step size is updated
}
// LFO mode only updates values once per vector in order to be as fast as possible
// LFO mode cannot be modulated
TTErr TTWavetable::processAsLFO(TTAudioSignalArrayPtr, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& out = outputs->getSignal(0);
TTSampleValue tempSample;
TTUInt16 vs = out.getVectorSizeAsInt();
TTUInt16 i=0;
TTUInt16 numChannels = out.getNumChannelsAsInt();
TTUInt16 channel;
TTUInt64 p1 = (TTUInt64)mIndex; // playback index
TTSampleMatrixPtr contents = NULL;
mBuffer->checkOutMatrix(contents);
// Move the play head
mIndex += (mIndexDelta * vs);
// Wrap the play head
if (mIndex >= mSize)
mIndex -= mSize;
else if (mIndex < 0)
mIndex += mSize;
// table lookup (no interpolation)
// CURRENTLY: this is hard coded to look only at the first channel, and all other channels in the buffer are ignored
contents->peek(p1,0,tempSample);
tempSample *= mLinearGain;
// TODO: in TTBlue 0.2.x this code only assigned the first sample value to save cpu -- should we bring this back as an option?
while (vs--) {
for (channel=0; channel<numChannels; channel++)
out.mSampleVectors[channel][i] = tempSample;
i++;
}
mBuffer->checkInMatrix(contents);
return kTTErrNone;
}
TTErr TTWavetable::processWithNoInterpolation(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignalPtr in; // can't call getSignal if there is no signal! = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTSampleValue *inSample = NULL;
TTSampleValue tempSample;
TTUInt16 vs = out.getVectorSizeAsInt();
TTUInt16 i=0;
TTUInt16 numChannels = out.getNumChannelsAsInt();
TTUInt16 channel;
TTBoolean hasModulation = true;
TTSampleMatrixPtr contents = NULL;
mBuffer->checkOutMatrix(contents);
// If the input and output signals are the same, then there really isn't an input signal
// In that case we don't modulate the oscillator with it
if (inputs->numAudioSignals == 0)
hasModulation = false;
else {
in = &inputs->getSignal(0);
inSample = in->mSampleVectors[0];
}
while (vs--) {
TTUInt64 p1 = (TTUInt64)mIndex; // playback index
// TODO: all of this access of mIndex and mIndexDelta etc is really going to be dereference pointers in our struct/class
// This likely means that the values are not cached (or at least not cached together) in the processors registers
// We should copy these to local variables at the vector start and then copy them back at the vector's end
// Move the play head
mIndex += mIndexDelta;
// Apply modulation to the play head
if (hasModulation)
mIndex += *inSample++ * mSize / sr;
// Wrap the play head
if (mIndex >= mSize)
mIndex -= mSize;
else if (mIndex < 0)
mIndex += mSize;
// table lookup (no interpolation)
// CURRENTLY: this is hard coded to look only at the first channel, and all other channels in the buffer are ignored
contents->peek(p1,0,tempSample);
tempSample *= mLinearGain;
for (channel=0; channel<numChannels; channel++)
out.mSampleVectors[channel][i] = tempSample;
i++;
}
mBuffer->checkInMatrix(contents);
return kTTErrNone;
}
TTErr TTWavetable::processWithLinearInterpolation(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignalPtr in; // can't call getSignal if there is no signal! = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTSampleValue *inSample = NULL;
TTSampleValue tempSample;
TTUInt16 vs = out.getVectorSizeAsInt();
TTUInt16 i=0;
TTUInt16 numChannels = out.getNumChannelsAsInt();
TTUInt16 channel;
TTBoolean hasModulation = true;
TTUInt32 p1, p2; // two playback indices
TTFloat64 diff;
TTSampleMatrixPtr contents = NULL;
mBuffer->checkOutMatrix(contents);
// If the input and output signals are the same, then there really isn't an input signal
// In that case we don't modulate the oscillator with it
if (inputs->numAudioSignals == 0)
hasModulation = false;
else {
in = &inputs->getSignal(0);
inSample = in->mSampleVectors[0];
}
while (vs--) {
// Move the play head
mIndex += mIndexDelta;
// Apply modulation to the play head
if (hasModulation)
mIndex += *inSample++ * mSize / sr;
// Wrap the play head
if (mIndex >= mSize)
mIndex -= mSize;
else if (mIndex < 0)
mIndex += mSize;
// table lookup (linear interpolation)
// CURRENTLY: this is hard coded to look only at the first channel, and all other channels in the buffer are ignored
contents->peek(mIndex,0,tempSample);
tempSample *= mLinearGain;
for (channel=0; channel<numChannels; channel++)
out.mSampleVectors[channel][i] = tempSample;
i++;
}
mBuffer->checkInMatrix(contents);
return kTTErrNone;
}
<commit_msg>Wavetable: silly indentation cleaning<commit_after>/*
* Jamoma DSP Wavetable Oscillator
* Copyright © 2003, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTWavetable.h"
#define thisTTClass TTWavetable
#define thisTTClassName "wavetable"
#define thisTTClassTags "audio, generator, oscillator, buffer"
TT_AUDIO_CONSTRUCTOR,
mIndex(0.0),
mIndexDelta(0.0),
mBuffer(NULL)
{
TTUInt16 initialMaxNumChannels = arguments;
addAttributeWithSetter(Frequency, kTypeFloat64);
addAttributeWithSetter(Mode, kTypeSymbol);
addAttributeWithSetter(Gain, kTypeFloat64);
addAttributeWithSetter(Interpolation, kTypeSymbol);
addAttributeWithSetter(Size, kTypeUInt32);
addUpdates(SampleRate);
TTObjectInstantiate(TT("buffer"), (TTObjectPtr*)&mBuffer, kTTValNONE);
if (!mBuffer)
throw TTException("Could not create internal buffer object");
mBuffer->setNumChannels(TTUInt32(1));
// Set Defaults...
setAttributeValue(TT("maxNumChannels"), initialMaxNumChannels);
setAttributeValue(TT("size"), 8192);
setAttributeValue(TT("mode"), kTTSym_sine);
setAttributeValue(TT("frequency"), 440.0);
setAttributeValue(TT("gain"), 0.0); // 0 dB
setAttributeValue(TT("interpolation"), TT("linear"));
}
TTWavetable::~TTWavetable()
{
TTObjectRelease((TTObject**)&mBuffer);
}
TTErr TTWavetable::updateSampleRate(const TTValue&, TTValue&)
{
setAttributeValue(TT("frequency"), mFrequency);
return kTTErrNone;
}
TTErr TTWavetable::setFrequency(const TTValue& newValue)
{
mFrequency = TTClip<TTFloat64>(newValue, 0.0, sr/2.0);
mIndexDelta = mFrequency * mSize * srInv;
return kTTErrNone;
}
TTErr TTWavetable::setMode(const TTValue& newValue)
{
mMode = newValue; // TODO: should be newValue[0]
if (mMode != TT("externalBuffer"))
return mBuffer->fill(newValue, kTTValNONE);
else {
// TODO: implement the ability to use an externally defined buffer
return kTTErrInvalidValue;
}
}
TTErr TTWavetable::setInterpolation(const TTValue& newValue)
{
mMode = newValue;
if (mMode == TT("linear"))
setProcessMethod(processWithLinearInterpolation);
else if (mMode == TT("lfo"))
setProcessMethod(processAsLFO);
else
setProcessMethod(processWithNoInterpolation);
return kTTErrNone;
}
TTErr TTWavetable::setGain(const TTValue& newValue)
{
mGain = newValue;
mLinearGain = TTDecibelsToLinearGain(mGain);
return kTTErrNone;
}
TTErr TTWavetable::setSize(const TTValue& newSize)
{
mSize = newSize;
mBuffer->setLengthInSamples(mSize);
return setFrequency(mFrequency); // touch the frequency so that the step size is updated
}
// LFO mode only updates values once per vector in order to be as fast as possible
// LFO mode cannot be modulated
TTErr TTWavetable::processAsLFO(TTAudioSignalArrayPtr, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& out = outputs->getSignal(0);
TTSampleValue tempSample;
TTUInt16 vs = out.getVectorSizeAsInt();
TTUInt16 i=0;
TTUInt16 numChannels = out.getNumChannelsAsInt();
TTUInt16 channel;
TTUInt64 p1 = (TTUInt64)mIndex; // playback index
TTSampleMatrixPtr contents = NULL;
mBuffer->checkOutMatrix(contents);
// Move the play head
mIndex += (mIndexDelta * vs);
// Wrap the play head
if (mIndex >= mSize)
mIndex -= mSize;
else if (mIndex < 0)
mIndex += mSize;
// table lookup (no interpolation)
// CURRENTLY: this is hard coded to look only at the first channel, and all other channels in the buffer are ignored
contents->peek(p1,0,tempSample);
tempSample *= mLinearGain;
// TODO: in TTBlue 0.2.x this code only assigned the first sample value to save cpu -- should we bring this back as an option?
while (vs--) {
for (channel=0; channel<numChannels; channel++)
out.mSampleVectors[channel][i] = tempSample;
i++;
}
mBuffer->checkInMatrix(contents);
return kTTErrNone;
}
TTErr TTWavetable::processWithNoInterpolation(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignalPtr in; // can't call getSignal if there is no signal! = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTSampleValue *inSample = NULL;
TTSampleValue tempSample;
TTUInt16 vs = out.getVectorSizeAsInt();
TTUInt16 i=0;
TTUInt16 numChannels = out.getNumChannelsAsInt();
TTUInt16 channel;
TTBoolean hasModulation = true;
TTSampleMatrixPtr contents = NULL;
mBuffer->checkOutMatrix(contents);
// If the input and output signals are the same, then there really isn't an input signal
// In that case we don't modulate the oscillator with it
if (inputs->numAudioSignals == 0)
hasModulation = false;
else {
in = &inputs->getSignal(0);
inSample = in->mSampleVectors[0];
}
while (vs--) {
TTUInt64 p1 = (TTUInt64)mIndex; // playback index
// TODO: all of this access of mIndex and mIndexDelta etc is really going to be dereference pointers in our struct/class
// This likely means that the values are not cached (or at least not cached together) in the processors registers
// We should copy these to local variables at the vector start and then copy them back at the vector's end
// Move the play head
mIndex += mIndexDelta;
// Apply modulation to the play head
if (hasModulation)
mIndex += *inSample++ * mSize / sr;
// Wrap the play head
if (mIndex >= mSize)
mIndex -= mSize;
else if (mIndex < 0)
mIndex += mSize;
// table lookup (no interpolation)
// CURRENTLY: this is hard coded to look only at the first channel, and all other channels in the buffer are ignored
contents->peek(p1,0,tempSample);
tempSample *= mLinearGain;
for (channel=0; channel<numChannels; channel++)
out.mSampleVectors[channel][i] = tempSample;
i++;
}
mBuffer->checkInMatrix(contents);
return kTTErrNone;
}
TTErr TTWavetable::processWithLinearInterpolation(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignalPtr in; // can't call getSignal if there is no signal! = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTSampleValue *inSample = NULL;
TTSampleValue tempSample;
TTUInt16 vs = out.getVectorSizeAsInt();
TTUInt16 i=0;
TTUInt16 numChannels = out.getNumChannelsAsInt();
TTUInt16 channel;
TTBoolean hasModulation = true;
TTUInt32 p1, p2; // two playback indices
TTFloat64 diff;
TTSampleMatrixPtr contents = NULL;
mBuffer->checkOutMatrix(contents);
// If the input and output signals are the same, then there really isn't an input signal
// In that case we don't modulate the oscillator with it
if (inputs->numAudioSignals == 0)
hasModulation = false;
else {
in = &inputs->getSignal(0);
inSample = in->mSampleVectors[0];
}
while (vs--) {
// Move the play head
mIndex += mIndexDelta;
// Apply modulation to the play head
if (hasModulation)
mIndex += *inSample++ * mSize / sr;
// Wrap the play head
if (mIndex >= mSize)
mIndex -= mSize;
else if (mIndex < 0)
mIndex += mSize;
// table lookup (linear interpolation)
// CURRENTLY: this is hard coded to look only at the first channel, and all other channels in the buffer are ignored
contents->peek(mIndex,0,tempSample);
tempSample *= mLinearGain;
for (channel=0; channel<numChannels; channel++)
out.mSampleVectors[channel][i] = tempSample;
i++;
}
mBuffer->checkInMatrix(contents);
return kTTErrNone;
}
<|endoftext|>
|
<commit_before>//The MIT License (MIT)
//
// Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Description:
// Core project header, containing build option preprocessor switches, and
// main macros used trough the library code.
//
// Author:
// Relja Ljubobratovic, ljubobratovic.relja@gmail.com
#ifndef FWD_HPP_1F9LO7BS
#define FWD_HPP_1F9LO7BS
#if defined(_MSC_VER)
// Microsoft Visual Compiler, and DLL compilation
#define CV_EXPORT __declspec(dllexport)
#define CV_IMPORT __declspec(dllimport)
#define CV_PRAGMA(arg) __pragma(arg)
#define CV_TYPENAME typename
#define CV_WINDOWS
#elif defined(__GNUG__) // GNU Compiler
#define CV_EXPORT __attribute__((visibility("default")))
#define CV_PRAGMA(arg) _Pragma(#arg)
#define CV_IMPORT
#define CV_TYPENAME typename
#define CV_LINUX
#else // arbitrary compiler, not expected and handled.
#error Unrecognized compiler
#define CV_EXPORT
#define CV_IMPORT
#define CV_TYPENAME typename
#define CV_PRAGMA(arg)
#endif
#define PI (double)3.14159265358979323846264338327950288 /*!< Pi value. */
#define RAD_TO_DEG(val) (double)( val * (180.0 / PI)) /*!< Convert radians to degrees. */
#define DEG_TO_RAD(val) (double)( val * (PI / 180.0)) /*!< Convert degrees to radians. */
#define LOOP_FOR(from,to,by) for(int i=from;i<to;i+=by)
#define LOOP_FOR_TO(to) LOOP_FOR(0,to,1)
#define NEST_FOR(from,to,by,from_nest,to_nest,by_nest) for(int i=from;i<to;i+=by) for(int j=from_nest;j<to_nest;j+=by_nest)
#define NEST_FOR_TO(to,to_nest) NEST_FOR(0,to,1,0,to_nest,1)
#define OMP_PARALLEL_FOR CV_PRAGMA(omp parallel for) //!< OpenMP parallel for pragma initializer macro.
#define OMP_INIT CV_PRAGMA(omp parallel) { //!< OpenMP parallel pragma initializer macro.
#define OMP_END } //!< OpenMP parallel for pragma deinitializer macro.
#define OMP_FOR CV_PRAGMA(omp for) //!< OpenMP for for pragma initializer macro.
#define OMP_ATOMIC CV_PRAGMA(omp atomic) //!< Perform OpenMP atomic increment.
#define OMP_CRITICAL CV_PRAGMA(omp critical) //!< Start OpenMP critical segment.
#define LOOP_OMP_FOR(cnti) OMP_FOR LOOP_FOR_TO(cnti) //!< OpenMP for pragma initializer with loop macro.
#define LOOP_PARALLEL_FOR(from,to,by) OMP_PARALLEL_FOR LOOP_FOR(from,to,by) //!< OpenMP parallel for pragma initializer with loop macro.
#define LOOP_PARALLEL_FOR_TO(cnt) OMP_PARALLEL_FOR LOOP_FOR_TO(cnt) //!< OpenMP parallel for pragma initializer macro.
#define NEST_PARALLEL_FOR_TO(cnti, cntj) LOOP_PARALLEL_FOR_TO(cnti) for(int j = 0; j < cntj; j++) //!< OpenMP parallel for pragma initializer with nested loop macro.
#define NEST_OMP_FOR_TO(cnti, cntj) OMP_FOR NEST_FOR_TO(cnti, cntj) //!< OpenMP parallel for pragma initializer with nested loop macro.
#define FOREACH(iter, cnt) for(auto iter = cnt.begin(); iter != cnt.end(); iter++)
#define ITERATE(iter, begin, end) for (auto iter = begin; iter != end; iter++)
typedef unsigned char byte;
typedef byte uchar;
typedef unsigned int uint;
#ifdef CV_REAL_TYPE_DOUBLE
typedef double real_t;
#else
typedef float real_t;
#endif
#define INTERPRET_INDEX(idx,length) (idx >= 0) ? idx : length + idx
enum parallelization_module {
CV_OPENMP,
CV_TBB,
CV_OCL
};
#ifndef CV_PARALLELIZATION_MODULE
#ifdef _OPENMP
#define CV_PARALLELIZATION_MODULE CV_OPENMP
#endif
#endif
#ifndef VECTOR_PARALLELIZATION_THRESHOLD
/*!
\def VECTOR_PARALLELIZATION_THRESHOLD
This value represents a threshold after which some of algorithms over vectors will be paralellized on the CPU/GPU.
For instance, small vectors (e.g. with size less than 1000) will take more time to allocate thread stack space
(or allocating device memory for GPU), than to simply evaluate an algorithm on a single CPU core. For larger
vectors (default value is 100000), parallelization of defined type (default is OpenMP) will be initialized.
\note
This value is initialized in fwd.hpp header, but will be overriden if preprocessor define with the same
name is defined in compilation setup. (/DVECTOR_PARALLELIZATION_THRESHOLD=100000)
*/
#define VECTOR_PARALLELIZATION_THRESHOLD 100000
#endif
typedef unsigned refcount_type;
#define REF_INCREMENT(ref) if(ref) ++(*ref) //!< Increment reference counter - assumes given value (int*) is initialized.
#define REF_DECREMENT(ref) if(ref) --(*ref) //!< Decrement reference counter - assumes given value (int*) is initialized.
#define REF_CHECK(ref) ((*ref) <= 0) ? false : true //!< Check if reference counter is equal to 0 - assumes given value (int*) is initialized.
#define REF_NEW new refcount_type(1) //!< Instatiate new reference counter.
#define REF_DESTROY(ref) delete ref //!< Destroy reference counter.
#define REF_INIT(ref) REF_DESTROY(ref), ref = REF_NEW //!< Initialize reference counter, will first delete existing, then instantiate a new one.
/*!
* Runtime assertion check.
*/
#if(defined(NDEBUG) || defined(NO_ASSERT))
#define ASSERT(cond) // empty macro - skip runtime assertion checks in the release mode.
#else
#define ASSERT(cond) \
do \
{ \
if (!(cond)) \
{ \
throw std::runtime_error(("Assertion check failed at condition: " #cond ", at line: ") + \
std::to_string(__LINE__) + (", in file " __FILE__)); \
} \
} while(0)
#endif
/*!
@brief Computer Vision core namespace.
Contains data structures and basic algorithms used in
image processing and computer vision tasks.
Used as libcv base namespace.
*/
namespace cv {
//! Type of region of interest data.
enum class RoiType {
REFERENCE, //!< Referenced data.
COPY //!< Copy data.
};
//! Type of region of interest edge menagement.
enum class RoiEdge {
MIRROR, //!< Mirrored edges.
ZEROS //!< Zero edges.
};
//! Norm type.
enum class Norm {
MINMAX, //!< Min-Max norm.
INF, //!< Infinite norm.
L0, //!< Zero norm - L0.
L1, //!< L1 Norm.
L1_SQRT, //!< L! squared norm.
L2, //!< Eucledian norm.
};
enum class InterpolationType //! Interpolation value_type used by some functions.
{
NN, /*!< Nearest neighbour interpolation. */
LINEAR, /*!< Bilinear interpolation. */
CUBIC, /*!< Bicubic interpolation. */
NO_INTER //!< No interpolation used.
};
enum ColorConvertion {
};
enum class ImageDepth {
ANY = 0,
BYTE_8 = 1,
SHORT_16 = 2,
FLOAT_32 = 4,
DOUBLE_64 = 8
};
enum class ImageFormat {
ANY = 0,
GRAY = 1,
RGB = 3,
RGBA = 4
};
}
#endif /* end of include guard: FWD_HPP_1F9LO7BS*/
<commit_msg>BPQ initial value define<commit_after>//The MIT License (MIT)
//
// Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Description:
// Core project header, containing build option preprocessor switches, and
// main macros used trough the library code.
//
// Author:
// Relja Ljubobratovic, ljubobratovic.relja@gmail.com
#ifndef FWD_HPP_1F9LO7BS
#define FWD_HPP_1F9LO7BS
#if defined(_MSC_VER)
// Microsoft Visual Compiler, and DLL compilation
#define CV_EXPORT __declspec(dllexport)
#define CV_IMPORT __declspec(dllimport)
#define CV_PRAGMA(arg) __pragma(arg)
#define CV_TYPENAME typename
#define CV_WINDOWS
#elif defined(__GNUG__) // GNU Compiler
#define CV_EXPORT __attribute__((visibility("default")))
#define CV_PRAGMA(arg) _Pragma(#arg)
#define CV_IMPORT
#define CV_TYPENAME typename
#define CV_LINUX
#else // arbitrary compiler, not expected and handled.
#error Unrecognized compiler
#define CV_EXPORT
#define CV_IMPORT
#define CV_TYPENAME typename
#define CV_PRAGMA(arg)
#endif
#define PI (double)3.14159265358979323846264338327950288 /*!< Pi value. */
#define RAD_TO_DEG(val) (double)( val * (180.0 / PI)) /*!< Convert radians to degrees. */
#define DEG_TO_RAD(val) (double)( val * (PI / 180.0)) /*!< Convert degrees to radians. */
#define LOOP_FOR(from,to,by) for(int i=from;i<to;i+=by)
#define LOOP_FOR_TO(to) LOOP_FOR(0,to,1)
#define NEST_FOR(from,to,by,from_nest,to_nest,by_nest) for(int i=from;i<to;i+=by) for(int j=from_nest;j<to_nest;j+=by_nest)
#define NEST_FOR_TO(to,to_nest) NEST_FOR(0,to,1,0,to_nest,1)
#define OMP_PARALLEL_FOR CV_PRAGMA(omp parallel for) //!< OpenMP parallel for pragma initializer macro.
#define OMP_INIT CV_PRAGMA(omp parallel) { //!< OpenMP parallel pragma initializer macro.
#define OMP_END } //!< OpenMP parallel for pragma deinitializer macro.
#define OMP_FOR CV_PRAGMA(omp for) //!< OpenMP for for pragma initializer macro.
#define OMP_ATOMIC CV_PRAGMA(omp atomic) //!< Perform OpenMP atomic increment.
#define OMP_CRITICAL CV_PRAGMA(omp critical) //!< Start OpenMP critical segment.
#define LOOP_OMP_FOR(cnti) OMP_FOR LOOP_FOR_TO(cnti) //!< OpenMP for pragma initializer with loop macro.
#define LOOP_PARALLEL_FOR(from,to,by) OMP_PARALLEL_FOR LOOP_FOR(from,to,by) //!< OpenMP parallel for pragma initializer with loop macro.
#define LOOP_PARALLEL_FOR_TO(cnt) OMP_PARALLEL_FOR LOOP_FOR_TO(cnt) //!< OpenMP parallel for pragma initializer macro.
#define NEST_PARALLEL_FOR_TO(cnti, cntj) LOOP_PARALLEL_FOR_TO(cnti) for(int j = 0; j < cntj; j++) //!< OpenMP parallel for pragma initializer with nested loop macro.
#define NEST_OMP_FOR_TO(cnti, cntj) OMP_FOR NEST_FOR_TO(cnti, cntj) //!< OpenMP parallel for pragma initializer with nested loop macro.
#define FOREACH(iter, cnt) for(auto iter = cnt.begin(); iter != cnt.end(); iter++)
#define ITERATE(iter, begin, end) for (auto iter = begin; iter != end; iter++)
typedef unsigned char byte;
typedef byte uchar;
typedef unsigned int uint;
#ifdef CV_REAL_TYPE_DOUBLE
typedef double real_t;
#else
typedef float real_t;
#endif
#define INTERPRET_INDEX(idx,length) (idx >= 0) ? idx : length + idx
enum parallelization_module {
CV_OPENMP,
CV_TBB,
CV_OCL
};
#ifndef CV_PARALLELIZATION_MODULE
#ifdef _OPENMP
#define CV_PARALLELIZATION_MODULE CV_OPENMP
#endif
#endif
#ifndef VECTOR_PARALLELIZATION_THRESHOLD
/*!
\def VECTOR_PARALLELIZATION_THRESHOLD
This value represents a threshold after which some of algorithms over vectors will be paralellized on the CPU/GPU.
For instance, small vectors (e.g. with size less than 1000) will take more time to allocate thread stack space
(or allocating device memory for GPU), than to simply evaluate an algorithm on a single CPU core. For larger
vectors (default value is 100000), parallelization of defined type (default is OpenMP) will be initialized.
\note
This value is initialized in fwd.hpp header, but will be overriden if preprocessor define with the same
name is defined in compilation setup. (/DVECTOR_PARALLELIZATION_THRESHOLD=100000)
*/
#define VECTOR_PARALLELIZATION_THRESHOLD 100000
#endif
#ifndef CV_BPQ_INIT_VALUE
#define CV_BPQ_INIT_VALUE 10e+30
#endif
typedef unsigned refcount_type;
#define REF_INCREMENT(ref) if(ref) ++(*ref) //!< Increment reference counter - assumes given value (int*) is initialized.
#define REF_DECREMENT(ref) if(ref) --(*ref) //!< Decrement reference counter - assumes given value (int*) is initialized.
#define REF_CHECK(ref) ((*ref) <= 0) ? false : true //!< Check if reference counter is equal to 0 - assumes given value (int*) is initialized.
#define REF_NEW new refcount_type(1) //!< Instatiate new reference counter.
#define REF_DESTROY(ref) delete ref //!< Destroy reference counter.
#define REF_INIT(ref) REF_DESTROY(ref), ref = REF_NEW //!< Initialize reference counter, will first delete existing, then instantiate a new one.
/*!
* Runtime assertion check.
*/
#if(defined(NDEBUG) || defined(NO_ASSERT))
#define ASSERT(cond) // empty macro - skip runtime assertion checks in the release mode.
#else
#define ASSERT(cond) \
do \
{ \
if (!(cond)) \
{ \
throw std::runtime_error(("Assertion check failed at condition: " #cond ", at line: ") + \
std::to_string(__LINE__) + (", in file " __FILE__)); \
} \
} while(0)
#endif
/*!
@brief Computer Vision core namespace.
Contains data structures and basic algorithms used in
image processing and computer vision tasks.
Used as libcv base namespace.
*/
namespace cv {
//! Type of region of interest data.
enum class RoiType {
REFERENCE, //!< Referenced data.
COPY //!< Copy data.
};
//! Type of region of interest edge menagement.
enum class RoiEdge {
MIRROR, //!< Mirrored edges.
ZEROS //!< Zero edges.
};
//! Norm type.
enum class Norm {
MINMAX, //!< Min-Max norm.
INF, //!< Infinite norm.
L0, //!< Zero norm - L0.
L1, //!< L1 Norm.
L1_SQRT, //!< L! squared norm.
L2, //!< Eucledian norm.
};
enum class InterpolationType //! Interpolation value_type used by some functions.
{
NN, /*!< Nearest neighbour interpolation. */
LINEAR, /*!< Bilinear interpolation. */
CUBIC, /*!< Bicubic interpolation. */
NO_INTER //!< No interpolation used.
};
enum ColorConvertion {
};
enum class ImageDepth {
ANY = 0,
BYTE_8 = 1,
SHORT_16 = 2,
FLOAT_32 = 4,
DOUBLE_64 = 8
};
enum class ImageFormat {
ANY = 0,
GRAY = 1,
RGB = 3,
RGBA = 4
};
}
#endif /* end of include guard: FWD_HPP_1F9LO7BS*/
<|endoftext|>
|
<commit_before>// Copyright (C) 2012-2017 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "IPCTestUtils.h"
#include <leapipc/CircularBufferEndpoint.h>
#include <autowiring/autowiring.h>
#include <autowiring/CoreThread.h>
#include <cstdio>
#include <thread>
#include <gtest/gtest.h>
using namespace leap::ipc;
class CircularBufferEndpointTest :
public testing::Test
{};
TEST_F(CircularBufferEndpointTest, WriteReadSequence)
{
auto cbuf = std::make_shared<CircularBufferEndpoint>(32);
// read from buffer in separate thread
std::thread reader([cbuf] {
char t[16];
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
});
// write to buffer
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
reader.join();
}
TEST_F(CircularBufferEndpointTest, IncreaseSize)
{
auto cbuf = std::make_shared<CircularBufferEndpoint>(16);
// read from buffer in separate thread
std::thread reader([cbuf] {
char t[16];
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
});
// write to buffer
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
reader.join();
}
<commit_msg>Reduce dependency on shared_ptr in test<commit_after>// Copyright (C) 2012-2017 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "IPCTestUtils.h"
#include <leapipc/CircularBufferEndpoint.h>
#include <autowiring/autowiring.h>
#include <autowiring/CoreThread.h>
#include <cstdio>
#include <thread>
#include <gtest/gtest.h>
using namespace leap::ipc;
class CircularBufferEndpointTest :
public testing::Test
{};
TEST_F(CircularBufferEndpointTest, WriteReadSequence)
{
CircularBufferEndpoint cbuf(32);
// read from buffer in separate thread
std::thread reader([&cbuf] {
char t[16];
cbuf.ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf.ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf.ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf.ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf.ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
cbuf.ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf.ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf.ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf.ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf.ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
});
// write to buffer
cbuf.WriteRaw("abcdef", 6);
cbuf.WriteRaw("ghijkl", 6);
cbuf.WriteRaw("mnopqr", 6);
cbuf.WriteRaw("01234567899876543210", 20);
cbuf.WriteRaw("abcdef", 6);
cbuf.WriteRaw("ghijkl", 6);
cbuf.WriteRaw("mnopqr", 6);
cbuf.WriteRaw("01234567899876543210", 20);
reader.join();
}
TEST_F(CircularBufferEndpointTest, IncreaseSize)
{
CircularBufferEndpoint cbuf(16);
// read from buffer in separate thread
std::thread reader([&cbuf] {
char t[16];
cbuf.ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf.ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf.ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf.ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf.ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
cbuf.ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf.ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf.ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf.ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf.ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
});
// write to buffer
cbuf.WriteRaw("abcdef", 6);
cbuf.WriteRaw("ghijkl", 6);
cbuf.WriteRaw("mnopqr", 6);
cbuf.WriteRaw("01234567899876543210", 20);
cbuf.WriteRaw("abcdef", 6);
cbuf.WriteRaw("ghijkl", 6);
cbuf.WriteRaw("mnopqr", 6);
cbuf.WriteRaw("01234567899876543210", 20);
reader.join();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xlroot.hxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: rt $ $Date: 2005-03-29 13:47:15 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XLROOT_HXX
#define SC_XLROOT_HXX
#ifndef _SOT_STORAGE_HXX
#include <sot/storage.hxx>
#endif
#ifndef SC_XLCONST_HXX
#include "xlconst.hxx"
#endif
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
// Forward declarations of objects in public use ==============================
struct XclAddress;
struct XclRange;
class XclRangeList;
// Global data ================================================================
#ifdef DBG_UTIL
/** Counts the number of created root objects. */
struct XclDebugObjCounter
{
sal_Int32 mnObjCnt;
inline explicit XclDebugObjCounter() : mnObjCnt( 0 ) {}
~XclDebugObjCounter();
};
#endif
// ----------------------------------------------------------------------------
class SfxMedium;
class ScEditEngineDefaulter;
class ScHeaderEditEngine;
class EditEngine;
class ScExtDocOptions;
class XclTracer;
struct RootData;//!
/** Stores global buffers and data needed elsewhere in the Excel filters. */
struct XclRootData
#ifdef DBG_UTIL
: public XclDebugObjCounter
#endif
{
typedef ScfRef< ScEditEngineDefaulter > ScEEDefaulterRef;
typedef ScfRef< ScHeaderEditEngine > ScHeaderEERef;
typedef ScfRef< EditEngine > EditEngineRef;
typedef ScfRef< ScExtDocOptions > ScExtDocOptRef;
typedef ScfRef< XclTracer > XclTracerRef;
typedef ScfRef< RootData > RootDataRef;
XclBiff meBiff; /// Current BIFF version.
SfxMedium& mrMedium; /// The medium to import from.
SotStorageRef mxRootStrg; /// The root OLE storage of imported/exported file.
SvStream& mrBookStrm; /// The workbook stream of imported/exported file.
ScDocument& mrDoc; /// The source or destination document.
String maDocUrl; /// Document URL of imported/exported file.
String maBasePath; /// Base path of imported/exported file (path of maDocUrl).
String maPassw; /// Entered password for stream encryption/decryption.
CharSet meCharSet; /// Character set to import/export byte strings.
LanguageType meSysLang; /// System language.
LanguageType meDocLang; /// Document language (import: from file, export: from system).
LanguageType meUILang; /// UI language (import: from file, export: from system).
ScAddress maScMaxPos; /// Highest Calc cell position.
ScAddress maXclMaxPos; /// Highest Excel cell position.
ScAddress maMaxPos; /// Highest position valid in Calc and Excel.
ScEEDefaulterRef mxEditEngine; /// Edit engine for rich strings etc.
ScHeaderEERef mxHFEditEngine; /// Edit engine for header/footer.
EditEngineRef mxDrawEditEng; /// Edit engine for text boxes.
ScExtDocOptRef mxExtDocOpt; /// Extended document options.
XclTracerRef mxTracer; /// Filter tracer.
RootDataRef mxRD; /// Old RootData struct. Will be removed.
long mnCharWidth; /// Width of '0' in default font (twips).
SCTAB mnScTab; /// Current Calc sheet index.
const bool mbExport; /// false = Import, true = Export.
bool mbHasPassw; /// true = Password already querried.
explicit XclRootData( XclBiff eBiff, SfxMedium& rMedium,
SotStorageRef xRootStrg, SvStream& rBookStrm,
ScDocument& rDoc, CharSet eCharSet, bool bExport );
virtual ~XclRootData();
};
// ----------------------------------------------------------------------------
class SfxObjectShell;
class ScModelObj;
class SfxPrinter;
class SvNumberFormatter;
class SdrPage;
class ScDocumentPool;
class ScStyleSheetPool;
class ScRangeName;
class ScDBCollection;
struct XclFontData;
/** Access to global data for a filter object (imported or exported document) from other classes. */
class XclRoot
{
public:
explicit XclRoot( XclRootData& rRootData );
XclRoot( const XclRoot& rRoot );
virtual ~XclRoot();
XclRoot& operator=( const XclRoot& rRoot );
/** Returns this root instance - for code readability in derived classes. */
inline const XclRoot& GetRoot() const { return *this; }
/** Returns old RootData struct. Deprecated. */
inline RootData& GetOldRoot() const { return *mrData.mxRD; }
/** Returns the current BIFF version of the importer/exporter. */
inline XclBiff GetBiff() const { return mrData.meBiff; }
/** Returns true, if currently a document is imported. */
inline bool IsImport() const { return !mrData.mbExport; }
/** Returns true, if currently a document is exported. */
inline bool IsExport() const { return mrData.mbExport; }
/** Returns the system language, i.e. for number formats. */
inline LanguageType GetSysLanguage() const { return mrData.meSysLang; }
/** Returns the document language. */
inline LanguageType GetDocLanguage() const { return mrData.meDocLang; }
/** Returns the UI language. */
inline LanguageType GetUILanguage() const { return mrData.meUILang; }
/** Returns the character set to import/export byte strings. */
inline CharSet GetCharSet() const { return mrData.meCharSet; }
/** Returns the width of the '0' character (default font) for the current printer (twips). */
inline long GetCharWidth() const { return mrData.mnCharWidth; }
/** Returns the current Calc sheet index. */
inline bool IsInGlobals() const { return mrData.mnScTab == SCTAB_GLOBAL; }
/** Returns the current Calc sheet index. */
inline SCTAB GetCurrScTab() const { return mrData.mnScTab; }
/** Returns the medium to import from. */
inline SfxMedium& GetMedium() const { return mrData.mrMedium; }
/** Returns the document URL of the imported/exported file. */
inline const String& GetDocUrl() const { return mrData.maDocUrl; }
/** Returns the base path of the imported/exported file. */
inline const String& GetBasePath() const { return mrData.maBasePath; }
/** Queries a password from the user and returns it (empty string -> input cancelled). */
const String& QueryPassword() const;
/** Returns the OLE2 root storage of the imported/exported file.
@return Pointer to root storage or 0, if the file is a simple stream. */
inline SotStorageRef GetRootStorage() const { return mrData.mxRootStrg; }
/** Returns the main import/export stream in the Excel file. */
inline SvStream& GetBookStream() const { return mrData.mrBookStrm; }
/** Returns true, if the document contains a VBA storage. */
bool HasVbaStorage() const;
/** Tries to open a storage as child of the specified storage for reading or writing. */
SotStorageRef OpenStorage( SotStorageRef xStrg, const String& rStrgName ) const;
/** Tries to open a storage as child of the root storage for reading or writing. */
SotStorageRef OpenStorage( const String& rStrgName ) const;
/** Tries to open a new stream in the specified storage for reading or writing. */
SotStorageStreamRef OpenStream( SotStorageRef xStrg, const String& rStrmName ) const;
/** Tries to open a new stream in the root storage for reading or writing. */
SotStorageStreamRef OpenStream( const String& rStrmName ) const;
/** Returns the destination document (import) or source document (export). */
inline ScDocument& GetDoc() const { return mrData.mrDoc; }
/** Returns pointer to the destination document (import) or source document (export). */
inline ScDocument* GetDocPtr() const { return &mrData.mrDoc; }
/** Returns the object shell of the Calc document. May be 0 (i.e. import from clipboard). */
SfxObjectShell* GetDocShell() const;
/** Returns the object model of the Calc document. */
ScModelObj* GetDocModelObj() const;
/** Returns pointer to the printer of the Calc document. */
SfxPrinter* GetPrinter() const;
/** Returns the number formatter of the Calc document. */
SvNumberFormatter& GetFormatter() const;
/** Returns the style sheet pool of the Calc document. */
ScStyleSheetPool& GetStyleSheetPool() const;
/** Returns the defined names container of the Calc document. */
ScRangeName& GetNamedRanges() const;
/** Returns the database ranges container of the Calc document. */
ScDBCollection& GetDatabaseRanges() const;
/** Returns the drawing layer page of the passed sheet, if present. */
SdrPage* GetSdrPage( SCTAB nScTab ) const;
/** Returns the edit engine for import/export of rich strings etc. */
ScEditEngineDefaulter& GetEditEngine() const;
/** Returns the edit engine for import/export of headers/footers. */
ScHeaderEditEngine& GetHFEditEngine() const;
/** Returns the edit engine for import/export of drawing text boxes. */
EditEngine& GetDrawEditEngine() const;
/** Returns the extended document options. */
ScExtDocOptions& GetExtDocOptions() const;
/** Returns the filter tracer. */
XclTracer& GetTracer() const;
/** Returns the highest possible cell address in a Calc document. */
inline const ScAddress& GetScMaxPos() const { return mrData.maScMaxPos; }
/** Returns the highest possible cell address in an Excel document (using current BIFF version). */
inline const ScAddress& GetXclMaxPos() const { return mrData.maXclMaxPos; }
/** Returns the highest possible cell address valid in Calc and Excel (using current BIFF version). */
inline const ScAddress& GetMaxPos() const { return mrData.maMaxPos; }
/** Sets the document language. */
inline void SetDocLanguage( LanguageType eLang ) { mrData.meDocLang = eLang; }
/** Sets the UI language, i.e. if it has been read from a file. */
inline void SetUILanguage( LanguageType eLang ) { mrData.meUILang = eLang; }
/** Sets the character set to import/export byte strings. */
inline void SetCharSet( CharSet eCharSet ) { mrData.meCharSet = eCharSet; }
/** Sets the width of the '0' character (default font) for the current printer (twips).
@param rFontData The font used for the '0' character. */
void SetCharWidth( const XclFontData& rFontData );
/** Sets the current Calc sheet index. */
inline void SetCurrScTab( SCTAB nScTab ) { mrData.mnScTab = nScTab; }
/** Increases the current Calc sheet index by 1. */
inline void IncCurrScTab() { ++mrData.mnScTab; }
private:
mutable XclRootData& mrData; /// Reference to the global data struct.
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.21.116); FILE MERGED 2005/09/05 15:03:01 rt 1.21.116.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xlroot.hxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:38:06 $
*
* 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 SC_XLROOT_HXX
#define SC_XLROOT_HXX
#ifndef _SOT_STORAGE_HXX
#include <sot/storage.hxx>
#endif
#ifndef SC_XLCONST_HXX
#include "xlconst.hxx"
#endif
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
// Forward declarations of objects in public use ==============================
struct XclAddress;
struct XclRange;
class XclRangeList;
// Global data ================================================================
#ifdef DBG_UTIL
/** Counts the number of created root objects. */
struct XclDebugObjCounter
{
sal_Int32 mnObjCnt;
inline explicit XclDebugObjCounter() : mnObjCnt( 0 ) {}
~XclDebugObjCounter();
};
#endif
// ----------------------------------------------------------------------------
class SfxMedium;
class ScEditEngineDefaulter;
class ScHeaderEditEngine;
class EditEngine;
class ScExtDocOptions;
class XclTracer;
struct RootData;//!
/** Stores global buffers and data needed elsewhere in the Excel filters. */
struct XclRootData
#ifdef DBG_UTIL
: public XclDebugObjCounter
#endif
{
typedef ScfRef< ScEditEngineDefaulter > ScEEDefaulterRef;
typedef ScfRef< ScHeaderEditEngine > ScHeaderEERef;
typedef ScfRef< EditEngine > EditEngineRef;
typedef ScfRef< ScExtDocOptions > ScExtDocOptRef;
typedef ScfRef< XclTracer > XclTracerRef;
typedef ScfRef< RootData > RootDataRef;
XclBiff meBiff; /// Current BIFF version.
SfxMedium& mrMedium; /// The medium to import from.
SotStorageRef mxRootStrg; /// The root OLE storage of imported/exported file.
SvStream& mrBookStrm; /// The workbook stream of imported/exported file.
ScDocument& mrDoc; /// The source or destination document.
String maDocUrl; /// Document URL of imported/exported file.
String maBasePath; /// Base path of imported/exported file (path of maDocUrl).
String maPassw; /// Entered password for stream encryption/decryption.
CharSet meCharSet; /// Character set to import/export byte strings.
LanguageType meSysLang; /// System language.
LanguageType meDocLang; /// Document language (import: from file, export: from system).
LanguageType meUILang; /// UI language (import: from file, export: from system).
ScAddress maScMaxPos; /// Highest Calc cell position.
ScAddress maXclMaxPos; /// Highest Excel cell position.
ScAddress maMaxPos; /// Highest position valid in Calc and Excel.
ScEEDefaulterRef mxEditEngine; /// Edit engine for rich strings etc.
ScHeaderEERef mxHFEditEngine; /// Edit engine for header/footer.
EditEngineRef mxDrawEditEng; /// Edit engine for text boxes.
ScExtDocOptRef mxExtDocOpt; /// Extended document options.
XclTracerRef mxTracer; /// Filter tracer.
RootDataRef mxRD; /// Old RootData struct. Will be removed.
long mnCharWidth; /// Width of '0' in default font (twips).
SCTAB mnScTab; /// Current Calc sheet index.
const bool mbExport; /// false = Import, true = Export.
bool mbHasPassw; /// true = Password already querried.
explicit XclRootData( XclBiff eBiff, SfxMedium& rMedium,
SotStorageRef xRootStrg, SvStream& rBookStrm,
ScDocument& rDoc, CharSet eCharSet, bool bExport );
virtual ~XclRootData();
};
// ----------------------------------------------------------------------------
class SfxObjectShell;
class ScModelObj;
class SfxPrinter;
class SvNumberFormatter;
class SdrPage;
class ScDocumentPool;
class ScStyleSheetPool;
class ScRangeName;
class ScDBCollection;
struct XclFontData;
/** Access to global data for a filter object (imported or exported document) from other classes. */
class XclRoot
{
public:
explicit XclRoot( XclRootData& rRootData );
XclRoot( const XclRoot& rRoot );
virtual ~XclRoot();
XclRoot& operator=( const XclRoot& rRoot );
/** Returns this root instance - for code readability in derived classes. */
inline const XclRoot& GetRoot() const { return *this; }
/** Returns old RootData struct. Deprecated. */
inline RootData& GetOldRoot() const { return *mrData.mxRD; }
/** Returns the current BIFF version of the importer/exporter. */
inline XclBiff GetBiff() const { return mrData.meBiff; }
/** Returns true, if currently a document is imported. */
inline bool IsImport() const { return !mrData.mbExport; }
/** Returns true, if currently a document is exported. */
inline bool IsExport() const { return mrData.mbExport; }
/** Returns the system language, i.e. for number formats. */
inline LanguageType GetSysLanguage() const { return mrData.meSysLang; }
/** Returns the document language. */
inline LanguageType GetDocLanguage() const { return mrData.meDocLang; }
/** Returns the UI language. */
inline LanguageType GetUILanguage() const { return mrData.meUILang; }
/** Returns the character set to import/export byte strings. */
inline CharSet GetCharSet() const { return mrData.meCharSet; }
/** Returns the width of the '0' character (default font) for the current printer (twips). */
inline long GetCharWidth() const { return mrData.mnCharWidth; }
/** Returns the current Calc sheet index. */
inline bool IsInGlobals() const { return mrData.mnScTab == SCTAB_GLOBAL; }
/** Returns the current Calc sheet index. */
inline SCTAB GetCurrScTab() const { return mrData.mnScTab; }
/** Returns the medium to import from. */
inline SfxMedium& GetMedium() const { return mrData.mrMedium; }
/** Returns the document URL of the imported/exported file. */
inline const String& GetDocUrl() const { return mrData.maDocUrl; }
/** Returns the base path of the imported/exported file. */
inline const String& GetBasePath() const { return mrData.maBasePath; }
/** Queries a password from the user and returns it (empty string -> input cancelled). */
const String& QueryPassword() const;
/** Returns the OLE2 root storage of the imported/exported file.
@return Pointer to root storage or 0, if the file is a simple stream. */
inline SotStorageRef GetRootStorage() const { return mrData.mxRootStrg; }
/** Returns the main import/export stream in the Excel file. */
inline SvStream& GetBookStream() const { return mrData.mrBookStrm; }
/** Returns true, if the document contains a VBA storage. */
bool HasVbaStorage() const;
/** Tries to open a storage as child of the specified storage for reading or writing. */
SotStorageRef OpenStorage( SotStorageRef xStrg, const String& rStrgName ) const;
/** Tries to open a storage as child of the root storage for reading or writing. */
SotStorageRef OpenStorage( const String& rStrgName ) const;
/** Tries to open a new stream in the specified storage for reading or writing. */
SotStorageStreamRef OpenStream( SotStorageRef xStrg, const String& rStrmName ) const;
/** Tries to open a new stream in the root storage for reading or writing. */
SotStorageStreamRef OpenStream( const String& rStrmName ) const;
/** Returns the destination document (import) or source document (export). */
inline ScDocument& GetDoc() const { return mrData.mrDoc; }
/** Returns pointer to the destination document (import) or source document (export). */
inline ScDocument* GetDocPtr() const { return &mrData.mrDoc; }
/** Returns the object shell of the Calc document. May be 0 (i.e. import from clipboard). */
SfxObjectShell* GetDocShell() const;
/** Returns the object model of the Calc document. */
ScModelObj* GetDocModelObj() const;
/** Returns pointer to the printer of the Calc document. */
SfxPrinter* GetPrinter() const;
/** Returns the number formatter of the Calc document. */
SvNumberFormatter& GetFormatter() const;
/** Returns the style sheet pool of the Calc document. */
ScStyleSheetPool& GetStyleSheetPool() const;
/** Returns the defined names container of the Calc document. */
ScRangeName& GetNamedRanges() const;
/** Returns the database ranges container of the Calc document. */
ScDBCollection& GetDatabaseRanges() const;
/** Returns the drawing layer page of the passed sheet, if present. */
SdrPage* GetSdrPage( SCTAB nScTab ) const;
/** Returns the edit engine for import/export of rich strings etc. */
ScEditEngineDefaulter& GetEditEngine() const;
/** Returns the edit engine for import/export of headers/footers. */
ScHeaderEditEngine& GetHFEditEngine() const;
/** Returns the edit engine for import/export of drawing text boxes. */
EditEngine& GetDrawEditEngine() const;
/** Returns the extended document options. */
ScExtDocOptions& GetExtDocOptions() const;
/** Returns the filter tracer. */
XclTracer& GetTracer() const;
/** Returns the highest possible cell address in a Calc document. */
inline const ScAddress& GetScMaxPos() const { return mrData.maScMaxPos; }
/** Returns the highest possible cell address in an Excel document (using current BIFF version). */
inline const ScAddress& GetXclMaxPos() const { return mrData.maXclMaxPos; }
/** Returns the highest possible cell address valid in Calc and Excel (using current BIFF version). */
inline const ScAddress& GetMaxPos() const { return mrData.maMaxPos; }
/** Sets the document language. */
inline void SetDocLanguage( LanguageType eLang ) { mrData.meDocLang = eLang; }
/** Sets the UI language, i.e. if it has been read from a file. */
inline void SetUILanguage( LanguageType eLang ) { mrData.meUILang = eLang; }
/** Sets the character set to import/export byte strings. */
inline void SetCharSet( CharSet eCharSet ) { mrData.meCharSet = eCharSet; }
/** Sets the width of the '0' character (default font) for the current printer (twips).
@param rFontData The font used for the '0' character. */
void SetCharWidth( const XclFontData& rFontData );
/** Sets the current Calc sheet index. */
inline void SetCurrScTab( SCTAB nScTab ) { mrData.mnScTab = nScTab; }
/** Increases the current Calc sheet index by 1. */
inline void IncCurrScTab() { ++mrData.mnScTab; }
private:
mutable XclRootData& mrData; /// Reference to the global data struct.
};
// ============================================================================
#endif
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993-2011 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 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "LinuxMedia.h"
#include <math.h>
#include <fcntl.h>
#ifdef BSD
#include <machine/endian.h>
#else
#include <endian.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include "bzsignal.h"
#include <sys/soundcard.h>
#include <sys/ioctl.h>
#include <TimeKeeper.h>
#include <errno.h>
#include <string.h>
#ifdef HALF_RATE_AUDIO
static const int defaultAudioRate=11025;
#else
static const int defaultAudioRate=22050;
#endif
//
// LinuxMedia
//
LinuxMedia::LinuxMedia() : BzfMedia(), audioReady(false),
audioBufferSize(defaultAudioRate),
audioPortFd(-1),
queueIn(-1), queueOut(-1),
outputBuffer(NULL),
childProcID(0),
audio8Bit(false),
getospaceBroken(false)
{
// do nothing
}
LinuxMedia::~LinuxMedia()
{
// do nothing
}
double LinuxMedia::getTime()
{
struct timeval tv;
gettimeofday(&tv, 0);
return (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec;
}
double LinuxMedia::stopwatch(bool start)
{
if (start) {
stopwatchTime = getTime();
return 0.0;
}
return getTime() - stopwatchTime;
}
bool LinuxMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
// check for and open audio hardware
if (!checkForAudioHardware() || !openAudioHardware()) return false;
// open communication channel (FIFO pipe). close on exec.
int fd[2];
if (pipe(fd)<0) {
closeAudio();
return false;
}
queueIn = fd[1];
queueOut = fd[0];
fcntl(queueIn, F_SETFL, fcntl(queueIn, F_GETFL, 0) | O_NDELAY);
fcntl(queueOut, F_SETFL, fcntl(queueOut, F_GETFL, 0) | O_NDELAY);
fcntl(queueIn, F_SETFD, fcntl(queueIn, F_GETFD, 0) | FD_CLOEXEC);
fcntl(queueOut, F_SETFD, fcntl(queueOut, F_GETFD, 0) | FD_CLOEXEC);
// compute maxFd for use in select() call
maxFd = queueOut;
if (maxFd<audioPortFd) maxFd = audioPortFd;
maxFd++;
// make an output buffer
outputBuffer = new short[audioBufferSize];
// Set default no thread
childProcID=0;
// ready to go
audioReady = true;
return true;
}
bool LinuxMedia::checkForAudioHardware()
{
bool flag=false;
if (!access("/dev/dsp", W_OK)) flag=true;
if (!access("/dev/sound/dsp", W_OK)) flag=true;
return flag;
}
bool LinuxMedia::openIoctl(
int cmd, void* value, bool req)
{
if (audioPortFd == -1)
return false;
if (ioctl(audioPortFd, cmd, value) < 0) {
fprintf(stderr, "audio ioctl failed (cmd %x, err %d)... ", cmd, errno);
if (req) {
close(audioPortFd);
audioPortFd = -1;
fprintf(stderr, "giving up on audio\n");
}
else {
fprintf(stderr, "ignored\n");
}
return false;
}
return true;
}
static const int NumChunks = 4;
bool LinuxMedia::openAudioHardware()
{
int format, n;
// what's the audio format?
#if BYTE_ORDER == BIG_ENDIAN
format = AFMT_S16_BE;
#else
format = AFMT_S16_LE;
#endif
// what the frequency?
audioOutputRate = defaultAudioRate;
// how big a fragment to use? we want to hold at around 1/10th of
// a second.
int fragmentSize = (int)(0.08f * (float)audioOutputRate);
n = 0;
while ((1 << n) < fragmentSize)
++n;
// samples are two bytes each and we're in stereo so quadruple the size
fragmentSize = n + 2;
// now how many fragments and what's the low water mark (in fragments)?
int fragmentInfo = (NumChunks << 16) | fragmentSize;
audioLowWaterMark = 2;
// open device (but don't wait for it)
audioPortFd = open("/dev/dsp", O_WRONLY | O_NDELAY, 0);
if (audioPortFd == -1) {
audioPortFd = open("/dev/sound/dsp", O_WRONLY | O_NDELAY, 0);
if (audioPortFd == -1) {
fprintf(stderr, "Failed to open audio device /dev/dsp or /dev/sound/dsp (%d)\n", errno);
return false;
}
}
// back to blocking I/O
fcntl(audioPortFd, F_SETFL, fcntl(audioPortFd, F_GETFL, 0) & ~O_NDELAY);
/* close audio on exec so launched server doesn't hold sound device */
fcntl(audioPortFd, F_SETFD, fcntl(audioPortFd, F_GETFD) | FD_CLOEXEC);
// initialize device
openIoctl(SNDCTL_DSP_RESET, 0);
n = fragmentInfo;
noSetFragment = false;
if (!openIoctl(SNDCTL_DSP_SETFRAGMENT, &n, false)) {
// this is not good. we can't set the size of the fragment
// buffers. we'd like something short to minimize latencies
// and the default is probably too long. we've got two
// options here: accept the latency or try to force the
// driver to play partial fragments. we'll try the later
// unless BZF_AUDIO_NOPOST is in the environment
if (!getenv("BZF_AUDIO_NOPOST"))
noSetFragment = true;
}
n = format;
openIoctl(SNDCTL_DSP_SETFMT, &n, false);
if (n != format) {
audio8Bit = true;
n = AFMT_U8;
openIoctl(SNDCTL_DSP_SETFMT, &n);
}
n = 1;
openIoctl(SNDCTL_DSP_STEREO, &n);
n = defaultAudioRate;
openIoctl(SNDCTL_DSP_SPEED, &n);
// set audioBufferSize, which is the number of samples (not bytes)
// in each fragment. there are two bytes per sample so divide the
// fragment size by two unless we're in audio8Bit mode. also, if
// we couldn't set the fragment size then force the buffer size to
// the size we would've asked for. we'll force the buffer to be
// flushed after we write that much data to keep latency low.
if (noSetFragment ||
!openIoctl(SNDCTL_DSP_GETBLKSIZE, &audioBufferSize, false) ||
audioBufferSize > (1 << fragmentSize)) {
audioBufferSize = 1 << fragmentSize;
noSetFragment = true;
}
if (!audio8Bit)
audioBufferSize >>= 1;
// SNDCTL_DSP_GETOSPACE not supported on all platforms. check if
// it fails here and, if so, do a workaround by using the wall
// clock. *shudder*
if (audioPortFd != -1) {
audio_buf_info info;
if (!openIoctl(SNDCTL_DSP_GETOSPACE, &info, false)) {
getospaceBroken = true;
chunksPending = 0;
chunksPerSecond = (double)getAudioOutputRate() /
(double)getAudioBufferChunkSize();
}
}
return (audioPortFd != -1);
}
void LinuxMedia::closeAudio()
{
delete [] outputBuffer;
if (audioPortFd>=0) close(audioPortFd);
if (queueIn!=-1) close(queueIn);
if (queueOut!=-1) close(queueOut);
audioReady=false;
audioPortFd=-1;
queueIn=-1;
queueOut=-1;
outputBuffer=0;
}
bool LinuxMedia::startAudioThread(
void (*proc)(void*), void* data)
{
// if no audio thread then just call proc and return
if (!hasAudioThread()) {
proc(data);
return true;
}
// has an audio thread so fork and call proc
if (childProcID) return true;
if ((childProcID=fork()) > 0) {
close(queueOut);
close(audioPortFd);
return true;
}
else if (childProcID < 0) {
return false;
}
close(queueIn);
proc(data);
exit(0);
}
void LinuxMedia::stopAudioThread()
{
if (childProcID != 0) kill(childProcID, SIGTERM);
childProcID=0;
}
bool LinuxMedia::hasAudioThread() const
{
#if defined(NO_AUDIO_THREAD)
return false;
#else
return true;
#endif
}
void LinuxMedia::audioThreadInit(void*)
{
}
void LinuxMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audioReady) return;
write(queueIn, cmd, len);
}
bool LinuxMedia::readSoundCommand(void* cmd, int len)
{
return (read(queueOut, cmd, len)==len);
}
int LinuxMedia::getAudioOutputRate() const
{
return audioOutputRate;
}
int LinuxMedia::getAudioBufferSize() const
{
return NumChunks*(audioBufferSize>>1);
}
int LinuxMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
bool LinuxMedia::isAudioTooEmpty() const
{
if (getospaceBroken) {
if (chunksPending > 0) {
// get time elapsed since chunkTime
const double dt = getTime() - chunkTime;
// how many chunks could've played in the elapsed time?
const int numChunks = (int)(dt * chunksPerSecond);
// remove pending chunks
LinuxMedia* self = (LinuxMedia*)this;
self->chunksPending -= numChunks;
if (chunksPending < 0)
self->chunksPending = 0;
else
self->chunkTime += (double)numChunks / chunksPerSecond;
}
return chunksPending < audioLowWaterMark;
}
else {
audio_buf_info info;
if (ioctl(audioPortFd, SNDCTL_DSP_GETOSPACE, &info) < 0)
return false;
return info.fragments > info.fragstotal - audioLowWaterMark;
}
}
void LinuxMedia::writeAudioFrames8Bit(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
char *smOutputBuffer;
smOutputBuffer=(char*)outputBuffer;
while (numSamples > 0) {
if (numSamples>audioBufferSize) limit=audioBufferSize;
else limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] <= -32767.0) smOutputBuffer[j] = 0;
else if (samples[j] >= 32767.0) smOutputBuffer[j] = 255;
else smOutputBuffer[j] = char((samples[j]+32767)/257);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
smOutputBuffer[j] = 127;
limit = audioBufferSize;
}
write(audioPortFd, smOutputBuffer, limit);
samples += limit;
numSamples -= limit;
}
}
void LinuxMedia::writeAudioFrames16Bit(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit = 0;
while (numSamples > 0) {
if (numSamples>audioBufferSize) limit=audioBufferSize;
else limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0) outputBuffer[j] = -32767;
else if (samples[j] > 32767.0) outputBuffer[j] = 32767;
else outputBuffer[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
outputBuffer[j] = 0;
limit = audioBufferSize;
}
write(audioPortFd, outputBuffer, 2*limit);
samples += limit;
numSamples -= limit;
}
}
void LinuxMedia::writeAudioFrames(
const float* samples, int numFrames)
{
if (audio8Bit) writeAudioFrames8Bit(samples, numFrames);
else writeAudioFrames16Bit(samples, numFrames);
// if we couldn't set the fragment size then force the driver
// to play the short buffer.
if (noSetFragment) {
int dummy = 0;
ioctl(audioPortFd, SNDCTL_DSP_POST, &dummy);
}
if (getospaceBroken) {
if (chunksPending == 0)
chunkTime = getTime();
chunksPending += (numFrames + getAudioBufferChunkSize() - 1) /
getAudioBufferChunkSize();
}
}
void LinuxMedia::audioSleep(
bool checkLowWater, double endTime)
{
fd_set commandSelectSet;
struct timeval tv;
// To do both these operations at once, we need to poll.
if (checkLowWater) {
// start looping
TimeKeeper start = TimeKeeper::getCurrent();
do {
// break if buffer has drained enough
if (isAudioTooEmpty()) break;
FD_ZERO(&commandSelectSet);
FD_SET((unsigned int)queueOut, &commandSelectSet);
tv.tv_sec=0;
tv.tv_usec=50000;
if (select(maxFd, &commandSelectSet, 0, 0, &tv)) break;
} while (endTime<0.0 || (TimeKeeper::getCurrent()-start)<endTime);
} else {
FD_ZERO(&commandSelectSet);
FD_SET((unsigned int)queueOut, &commandSelectSet);
tv.tv_sec=int(endTime);
tv.tv_usec=int(1.0e6*(endTime-floor(endTime)));
select(maxFd, &commandSelectSet, 0, 0, (endTime>=0.0)?&tv : 0);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Explicitly cast some constants to prevent "overflow in implicit constant conversion" warnings.<commit_after>/* bzflag
* Copyright (c) 1993-2012 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 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "LinuxMedia.h"
#include <math.h>
#include <fcntl.h>
#ifdef BSD
#include <machine/endian.h>
#else
#include <endian.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include "bzsignal.h"
#include <sys/soundcard.h>
#include <sys/ioctl.h>
#include <TimeKeeper.h>
#include <errno.h>
#include <string.h>
#ifdef HALF_RATE_AUDIO
static const int defaultAudioRate=11025;
#else
static const int defaultAudioRate=22050;
#endif
//
// LinuxMedia
//
LinuxMedia::LinuxMedia() : BzfMedia(), audioReady(false),
audioBufferSize(defaultAudioRate),
audioPortFd(-1),
queueIn(-1), queueOut(-1),
outputBuffer(NULL),
childProcID(0),
audio8Bit(false),
getospaceBroken(false)
{
// do nothing
}
LinuxMedia::~LinuxMedia()
{
// do nothing
}
double LinuxMedia::getTime()
{
struct timeval tv;
gettimeofday(&tv, 0);
return (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec;
}
double LinuxMedia::stopwatch(bool start)
{
if (start) {
stopwatchTime = getTime();
return 0.0;
}
return getTime() - stopwatchTime;
}
bool LinuxMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
// check for and open audio hardware
if (!checkForAudioHardware() || !openAudioHardware()) return false;
// open communication channel (FIFO pipe). close on exec.
int fd[2];
if (pipe(fd)<0) {
closeAudio();
return false;
}
queueIn = fd[1];
queueOut = fd[0];
fcntl(queueIn, F_SETFL, fcntl(queueIn, F_GETFL, 0) | O_NDELAY);
fcntl(queueOut, F_SETFL, fcntl(queueOut, F_GETFL, 0) | O_NDELAY);
fcntl(queueIn, F_SETFD, fcntl(queueIn, F_GETFD, 0) | FD_CLOEXEC);
fcntl(queueOut, F_SETFD, fcntl(queueOut, F_GETFD, 0) | FD_CLOEXEC);
// compute maxFd for use in select() call
maxFd = queueOut;
if (maxFd<audioPortFd) maxFd = audioPortFd;
maxFd++;
// make an output buffer
outputBuffer = new short[audioBufferSize];
// Set default no thread
childProcID=0;
// ready to go
audioReady = true;
return true;
}
bool LinuxMedia::checkForAudioHardware()
{
bool flag=false;
if (!access("/dev/dsp", W_OK)) flag=true;
if (!access("/dev/sound/dsp", W_OK)) flag=true;
return flag;
}
bool LinuxMedia::openIoctl(
int cmd, void* value, bool req)
{
if (audioPortFd == -1)
return false;
if (ioctl(audioPortFd, cmd, value) < 0) {
fprintf(stderr, "audio ioctl failed (cmd %x, err %d)... ", cmd, errno);
if (req) {
close(audioPortFd);
audioPortFd = -1;
fprintf(stderr, "giving up on audio\n");
}
else {
fprintf(stderr, "ignored\n");
}
return false;
}
return true;
}
static const int NumChunks = 4;
bool LinuxMedia::openAudioHardware()
{
int format, n;
// what's the audio format?
#if BYTE_ORDER == BIG_ENDIAN
format = AFMT_S16_BE;
#else
format = AFMT_S16_LE;
#endif
// what the frequency?
audioOutputRate = defaultAudioRate;
// how big a fragment to use? we want to hold at around 1/10th of
// a second.
int fragmentSize = (int)(0.08f * (float)audioOutputRate);
n = 0;
while ((1 << n) < fragmentSize)
++n;
// samples are two bytes each and we're in stereo so quadruple the size
fragmentSize = n + 2;
// now how many fragments and what's the low water mark (in fragments)?
int fragmentInfo = (NumChunks << 16) | fragmentSize;
audioLowWaterMark = 2;
// open device (but don't wait for it)
audioPortFd = open("/dev/dsp", O_WRONLY | O_NDELAY, 0);
if (audioPortFd == -1) {
audioPortFd = open("/dev/sound/dsp", O_WRONLY | O_NDELAY, 0);
if (audioPortFd == -1) {
fprintf(stderr, "Failed to open audio device /dev/dsp or /dev/sound/dsp (%d)\n", errno);
return false;
}
}
// back to blocking I/O
fcntl(audioPortFd, F_SETFL, fcntl(audioPortFd, F_GETFL, 0) & ~O_NDELAY);
/* close audio on exec so launched server doesn't hold sound device */
fcntl(audioPortFd, F_SETFD, fcntl(audioPortFd, F_GETFD) | FD_CLOEXEC);
// initialize device
openIoctl(SNDCTL_DSP_RESET, 0);
n = fragmentInfo;
noSetFragment = false;
if (!openIoctl((int)SNDCTL_DSP_SETFRAGMENT, &n, false)) {
// this is not good. we can't set the size of the fragment
// buffers. we'd like something short to minimize latencies
// and the default is probably too long. we've got two
// options here: accept the latency or try to force the
// driver to play partial fragments. we'll try the later
// unless BZF_AUDIO_NOPOST is in the environment
if (!getenv("BZF_AUDIO_NOPOST"))
noSetFragment = true;
}
n = format;
openIoctl((int)SNDCTL_DSP_SETFMT, &n, false);
if (n != format) {
audio8Bit = true;
n = AFMT_U8;
openIoctl((int)SNDCTL_DSP_SETFMT, &n);
}
n = 1;
openIoctl((int)SNDCTL_DSP_STEREO, &n);
n = defaultAudioRate;
openIoctl((int)SNDCTL_DSP_SPEED, &n);
// set audioBufferSize, which is the number of samples (not bytes)
// in each fragment. there are two bytes per sample so divide the
// fragment size by two unless we're in audio8Bit mode. also, if
// we couldn't set the fragment size then force the buffer size to
// the size we would've asked for. we'll force the buffer to be
// flushed after we write that much data to keep latency low.
if (noSetFragment ||
!openIoctl((int)SNDCTL_DSP_GETBLKSIZE, &audioBufferSize, false) ||
audioBufferSize > (1 << fragmentSize)) {
audioBufferSize = 1 << fragmentSize;
noSetFragment = true;
}
if (!audio8Bit)
audioBufferSize >>= 1;
// SNDCTL_DSP_GETOSPACE not supported on all platforms. check if
// it fails here and, if so, do a workaround by using the wall
// clock. *shudder*
if (audioPortFd != -1) {
audio_buf_info info;
if (!openIoctl((int)SNDCTL_DSP_GETOSPACE, &info, false)) {
getospaceBroken = true;
chunksPending = 0;
chunksPerSecond = (double)getAudioOutputRate() /
(double)getAudioBufferChunkSize();
}
}
return (audioPortFd != -1);
}
void LinuxMedia::closeAudio()
{
delete [] outputBuffer;
if (audioPortFd>=0) close(audioPortFd);
if (queueIn!=-1) close(queueIn);
if (queueOut!=-1) close(queueOut);
audioReady=false;
audioPortFd=-1;
queueIn=-1;
queueOut=-1;
outputBuffer=0;
}
bool LinuxMedia::startAudioThread(
void (*proc)(void*), void* data)
{
// if no audio thread then just call proc and return
if (!hasAudioThread()) {
proc(data);
return true;
}
// has an audio thread so fork and call proc
if (childProcID) return true;
if ((childProcID=fork()) > 0) {
close(queueOut);
close(audioPortFd);
return true;
}
else if (childProcID < 0) {
return false;
}
close(queueIn);
proc(data);
exit(0);
}
void LinuxMedia::stopAudioThread()
{
if (childProcID != 0) kill(childProcID, SIGTERM);
childProcID=0;
}
bool LinuxMedia::hasAudioThread() const
{
#if defined(NO_AUDIO_THREAD)
return false;
#else
return true;
#endif
}
void LinuxMedia::audioThreadInit(void*)
{
}
void LinuxMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audioReady) return;
write(queueIn, cmd, len);
}
bool LinuxMedia::readSoundCommand(void* cmd, int len)
{
return (read(queueOut, cmd, len)==len);
}
int LinuxMedia::getAudioOutputRate() const
{
return audioOutputRate;
}
int LinuxMedia::getAudioBufferSize() const
{
return NumChunks*(audioBufferSize>>1);
}
int LinuxMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
bool LinuxMedia::isAudioTooEmpty() const
{
if (getospaceBroken) {
if (chunksPending > 0) {
// get time elapsed since chunkTime
const double dt = getTime() - chunkTime;
// how many chunks could've played in the elapsed time?
const int numChunks = (int)(dt * chunksPerSecond);
// remove pending chunks
LinuxMedia* self = (LinuxMedia*)this;
self->chunksPending -= numChunks;
if (chunksPending < 0)
self->chunksPending = 0;
else
self->chunkTime += (double)numChunks / chunksPerSecond;
}
return chunksPending < audioLowWaterMark;
}
else {
audio_buf_info info;
if (ioctl(audioPortFd, SNDCTL_DSP_GETOSPACE, &info) < 0)
return false;
return info.fragments > info.fragstotal - audioLowWaterMark;
}
}
void LinuxMedia::writeAudioFrames8Bit(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
char *smOutputBuffer;
smOutputBuffer=(char*)outputBuffer;
while (numSamples > 0) {
if (numSamples>audioBufferSize) limit=audioBufferSize;
else limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] <= -32767.0) smOutputBuffer[j] = 0;
else if (samples[j] >= 32767.0) smOutputBuffer[j] = (char)255;
else smOutputBuffer[j] = char((samples[j]+32767)/257);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
smOutputBuffer[j] = 127;
limit = audioBufferSize;
}
write(audioPortFd, smOutputBuffer, limit);
samples += limit;
numSamples -= limit;
}
}
void LinuxMedia::writeAudioFrames16Bit(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit = 0;
while (numSamples > 0) {
if (numSamples>audioBufferSize) limit=audioBufferSize;
else limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0) outputBuffer[j] = -32767;
else if (samples[j] > 32767.0) outputBuffer[j] = 32767;
else outputBuffer[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
outputBuffer[j] = 0;
limit = audioBufferSize;
}
write(audioPortFd, outputBuffer, 2*limit);
samples += limit;
numSamples -= limit;
}
}
void LinuxMedia::writeAudioFrames(
const float* samples, int numFrames)
{
if (audio8Bit) writeAudioFrames8Bit(samples, numFrames);
else writeAudioFrames16Bit(samples, numFrames);
// if we couldn't set the fragment size then force the driver
// to play the short buffer.
if (noSetFragment) {
int dummy = 0;
ioctl(audioPortFd, SNDCTL_DSP_POST, &dummy);
}
if (getospaceBroken) {
if (chunksPending == 0)
chunkTime = getTime();
chunksPending += (numFrames + getAudioBufferChunkSize() - 1) /
getAudioBufferChunkSize();
}
}
void LinuxMedia::audioSleep(
bool checkLowWater, double endTime)
{
fd_set commandSelectSet;
struct timeval tv;
// To do both these operations at once, we need to poll.
if (checkLowWater) {
// start looping
TimeKeeper start = TimeKeeper::getCurrent();
do {
// break if buffer has drained enough
if (isAudioTooEmpty()) break;
FD_ZERO(&commandSelectSet);
FD_SET((unsigned int)queueOut, &commandSelectSet);
tv.tv_sec=0;
tv.tv_usec=50000;
if (select(maxFd, &commandSelectSet, 0, 0, &tv)) break;
} while (endTime<0.0 || (TimeKeeper::getCurrent()-start)<endTime);
} else {
FD_ZERO(&commandSelectSet);
FD_SET((unsigned int)queueOut, &commandSelectSet);
tv.tv_sec=int(endTime);
tv.tv_usec=int(1.0e6*(endTime-floor(endTime)));
select(maxFd, &commandSelectSet, 0, 0, (endTime>=0.0)?&tv : 0);
}
}
// 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 (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "RendererOGL.h"
#include "TextureOGL.h"
#include "RenderTargetOGL.h"
#include "ShaderOGL.h"
#include "MeshBufferOGL.h"
#include "Engine.h"
#include "Scene.h"
#include "Camera.h"
#include "Utils.h"
#if defined(SUPPORTS_OPENGL)
#include "ColorPSOGL.h"
#include "ColorVSOGL.h"
#include "TexturePSOGL.h"
#include "TextureVSOGL.h"
#endif
#if defined(SUPPORTS_OPENGLES)
#include "ColorPSOGLES.h"
#include "ColorVSOGLES.h"
#include "TexturePSOGLES.h"
#include "TextureVSOGLES.h"
#endif
namespace ouzel
{
RendererOGL::RendererOGL(const Size2& size, bool resiazble, bool fullscreen):
Renderer(size, resiazble, fullscreen, Driver::OPENGL)
{
recalculateProjection();
}
RendererOGL::~RendererOGL()
{
}
bool RendererOGL::initOpenGL(uint32_t width, uint32_t height)
{
_size.width = static_cast<float>(width);
_size.height = static_cast<float>(height);
//glEnable(GL_DEPTH_TEST);
glClearColor(_clearColor.getR(), _clearColor.getG(), _clearColor.getB(), _clearColor.getA());
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
//glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
// precomputed alpha
//glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
//glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
if (checkOpenGLErrors())
{
return false;
}
Shader* textureShader = loadShaderFromBuffers(TEXTURE_PIXEL_SHADER_OGL, sizeof(TEXTURE_PIXEL_SHADER_OGL), TEXTURE_VERTEX_SHADER_OGL, sizeof(TEXTURE_VERTEX_SHADER_OGL), VertexPCT::ATTRIBUTES);
if (textureShader)
{
_shaders[SHADER_TEXTURE] = textureShader;
}
Shader* colorShader = loadShaderFromBuffers(COLOR_PIXEL_SHADER_OGL, sizeof(COLOR_PIXEL_SHADER_OGL), COLOR_VERTEX_SHADER_OGL, sizeof(COLOR_VERTEX_SHADER_OGL), VertexPC::ATTRIBUTES);
if (colorShader)
{
_shaders[SHADER_COLOR] = colorShader;
}
_ready = true;
recalculateProjection();
Engine::getInstance()->begin();
return true;
}
bool RendererOGL::checkOpenGLErrors()
{
bool error = false;
while (GLenum error = glGetError() != GL_NO_ERROR)
{
const char* errorStr = "Unknown error";
switch (error)
{
case GL_INVALID_ENUM: errorStr = "GL_INVALID_ENUM"; break;
case GL_INVALID_VALUE: errorStr = "GL_INVALID_VALUE"; break;
case GL_INVALID_OPERATION: errorStr = "GL_INVALID_OPERATION"; break;
case GL_OUT_OF_MEMORY: errorStr = "GL_OUT_OF_MEMORY"; break;
case GL_INVALID_FRAMEBUFFER_OPERATION: errorStr = "GL_INVALID_FRAMEBUFFER_OPERATION"; break;
}
log("OpenGL error: %s (%x)", errorStr, error);
error = true;
}
return error;
}
void RendererOGL::setClearColor(Color color)
{
Renderer::setClearColor(color);
glClearColor(_clearColor.getR(), _clearColor.getG(), _clearColor.getB(), _clearColor.getA());
}
void RendererOGL::recalculateProjection()
{
Renderer::recalculateProjection();
if (_ready)
{
glViewport(0, 0, _size.width, _size.height);
}
}
void RendererOGL::clear()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
checkOpenGLErrors();
}
void RendererOGL::flush()
{
glFlush();
checkOpenGLErrors();
}
Texture* RendererOGL::loadTextureFromFile(const std::string& filename)
{
TextureOGL* texture = new TextureOGL();
if (!texture->initFromFile(filename))
{
delete texture;
texture = nullptr;
}
return texture;
}
bool RendererOGL::activateTexture(Texture* texture, uint32_t layer)
{
if (!Renderer::activateTexture(texture, layer))
{
return false;
}
if (texture)
{
TextureOGL* textureOGL = static_cast<TextureOGL*>(texture);
glActiveTexture(GL_TEXTURE0 + layer);
glBindTexture(GL_TEXTURE_2D, textureOGL->getTextureId());
if (checkOpenGLErrors())
{
return false;
}
}
else
{
glBindTexture(GL_TEXTURE_2D, 0);
}
return true;
}
Shader* RendererOGL::loadShaderFromFiles(const std::string& fragmentShader, const std::string& vertexShader, uint32_t vertexAttributes)
{
ShaderOGL* shader = new ShaderOGL();
if (!shader->initFromFiles(fragmentShader, vertexShader, vertexAttributes))
{
delete shader;
shader = nullptr;
}
return shader;
}
Shader* RendererOGL::loadShaderFromBuffers(const uint8_t* fragmentShader, uint32_t fragmentShaderSize, const uint8_t* vertexShader, uint32_t vertexShaderSize, uint32_t vertexAttributes)
{
ShaderOGL* shader = new ShaderOGL();
if (!shader->initFromBuffers(fragmentShader, fragmentShaderSize, vertexShader, vertexShaderSize, vertexAttributes))
{
delete shader;
shader = nullptr;
}
return shader;
}
bool RendererOGL::activateShader(Shader* shader)
{
if (!Renderer::activateShader(shader))
{
return false;
}
if (shader)
{
ShaderOGL* shaderOGL = static_cast<ShaderOGL*>(shader);
glUseProgram(shaderOGL->getProgramId());
if (checkOpenGLErrors())
{
return false;
}
}
else
{
glUseProgram(0);
}
return true;
}
MeshBuffer* RendererOGL::createMeshBuffer(const std::vector<uint16_t>& indices, const std::vector<VertexPCT>& vertices, bool dynamicIndexBuffer, bool dynamicVertexBuffer)
{
MeshBufferOGL* meshBuffer = new MeshBufferOGL();
if (!meshBuffer->initFromData(indices, vertices, dynamicIndexBuffer, dynamicVertexBuffer))
{
delete meshBuffer;
meshBuffer = nullptr;
}
return meshBuffer;
}
bool RendererOGL::drawMeshBuffer(MeshBuffer* meshBuffer)
{
if (!Renderer::drawMeshBuffer(meshBuffer))
{
return false;
}
MeshBufferOGL* meshBufferOGL = static_cast<MeshBufferOGL*>(meshBuffer);
glBindVertexArray(meshBufferOGL->getVertexArrayId());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshBufferOGL->getIndexBufferId());
glDrawElements(GL_TRIANGLES, meshBufferOGL->getIndexCount(), GL_UNSIGNED_SHORT, nullptr);
if (checkOpenGLErrors())
{
return false;
}
return true;
}
void RendererOGL::drawLine(const Vector2& start, const Vector2& finish, const Color& color, const Matrix4& transform)
{
GLuint vertexArray = 0;
GLuint vertexBuffer = 0;
GLuint indexBuffer = 0;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
GLfloat vertices[] = {
start.x, start.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(),
finish.x, finish.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA()
};
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(12));
GLubyte indices[] = {0, 1};
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
ShaderOGL* colorShader = static_cast<ShaderOGL*>(getShader(SHADER_COLOR));
activateShader(colorShader);
Matrix4 modelViewProj = _projection * Scene::getInstance()->getCamera()->getTransform() * transform;
uint32_t uniModelViewProj = colorShader->getVertexShaderConstantId("modelViewProj");
colorShader->setVertexShaderConstant(uniModelViewProj, { modelViewProj });
glBindVertexArray(vertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glDrawElements(GL_LINE_STRIP, 2, GL_UNSIGNED_BYTE, nullptr);
// delete buffers
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
}
void RendererOGL::drawRectangle(const Rectangle& rectangle, const Color& color, const Matrix4& transform)
{
GLuint vertexArray = 0;
GLuint vertexBuffer = 0;
GLuint indexBuffer = 0;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
GLfloat vertices[] = {
rectangle.x, rectangle.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(),
rectangle.x + rectangle.width, rectangle.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(),
rectangle.x, rectangle.y + rectangle.height, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(),
rectangle.x + rectangle.width, rectangle.y + rectangle.height, 0.0f, color.getR(), color.getG(), color.getB(), color.getA()
};
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(12));
GLubyte indices[] = {0, 1, 3, 2, 0};
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
ShaderOGL* colorShader = static_cast<ShaderOGL*>(getShader(SHADER_COLOR));
activateShader(colorShader);
Matrix4 modelViewProj = _projection * Scene::getInstance()->getCamera()->getTransform() * transform;
uint32_t uniModelViewProj = colorShader->getVertexShaderConstantId("modelViewProj");
colorShader->setVertexShaderConstant(uniModelViewProj, { modelViewProj });
glBindVertexArray(vertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glDrawElements(GL_LINE_STRIP, 5, GL_UNSIGNED_BYTE, nullptr);
// delete buffers
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
}
void RendererOGL::drawQuad(const Rectangle& rectangle, const Color& color, const Matrix4& transform)
{
GLuint vertexArray = 0;
GLuint vertexBuffer = 0;
GLuint indexBuffer = 0;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
GLfloat vertices[] = {
rectangle.x, rectangle.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(), 0.0f, 1.0f,
rectangle.x + rectangle.width, rectangle.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(), 1.0f, 1.0f,
rectangle.x, rectangle.y + rectangle.height, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(), 0.0f, 0.0f,
rectangle.x + rectangle.width, rectangle.y + rectangle.height, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(), 1.0f, 0.0f
};
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(12));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(16));
GLubyte indices[] = {0, 1, 2, 1, 3, 2};
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
ShaderOGL* colorShader = static_cast<ShaderOGL*>(getShader(SHADER_TEXTURE));
activateShader(colorShader);
Matrix4 modelViewProj = _projection * Scene::getInstance()->getCamera()->getTransform() * transform;
uint32_t uniModelViewProj = colorShader->getVertexShaderConstantId("modelViewProj");
colorShader->setVertexShaderConstant(uniModelViewProj, { modelViewProj });
glBindVertexArray(vertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, nullptr);
// delete buffers
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
}
}
<commit_msg>Activate correct texture layer if setting texture to 0<commit_after>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "RendererOGL.h"
#include "TextureOGL.h"
#include "RenderTargetOGL.h"
#include "ShaderOGL.h"
#include "MeshBufferOGL.h"
#include "Engine.h"
#include "Scene.h"
#include "Camera.h"
#include "Utils.h"
#if defined(SUPPORTS_OPENGL)
#include "ColorPSOGL.h"
#include "ColorVSOGL.h"
#include "TexturePSOGL.h"
#include "TextureVSOGL.h"
#endif
#if defined(SUPPORTS_OPENGLES)
#include "ColorPSOGLES.h"
#include "ColorVSOGLES.h"
#include "TexturePSOGLES.h"
#include "TextureVSOGLES.h"
#endif
namespace ouzel
{
RendererOGL::RendererOGL(const Size2& size, bool resiazble, bool fullscreen):
Renderer(size, resiazble, fullscreen, Driver::OPENGL)
{
recalculateProjection();
}
RendererOGL::~RendererOGL()
{
}
bool RendererOGL::initOpenGL(uint32_t width, uint32_t height)
{
_size.width = static_cast<float>(width);
_size.height = static_cast<float>(height);
//glEnable(GL_DEPTH_TEST);
glClearColor(_clearColor.getR(), _clearColor.getG(), _clearColor.getB(), _clearColor.getA());
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
//glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
// precomputed alpha
//glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
//glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
if (checkOpenGLErrors())
{
return false;
}
Shader* textureShader = loadShaderFromBuffers(TEXTURE_PIXEL_SHADER_OGL, sizeof(TEXTURE_PIXEL_SHADER_OGL), TEXTURE_VERTEX_SHADER_OGL, sizeof(TEXTURE_VERTEX_SHADER_OGL), VertexPCT::ATTRIBUTES);
if (textureShader)
{
_shaders[SHADER_TEXTURE] = textureShader;
}
Shader* colorShader = loadShaderFromBuffers(COLOR_PIXEL_SHADER_OGL, sizeof(COLOR_PIXEL_SHADER_OGL), COLOR_VERTEX_SHADER_OGL, sizeof(COLOR_VERTEX_SHADER_OGL), VertexPC::ATTRIBUTES);
if (colorShader)
{
_shaders[SHADER_COLOR] = colorShader;
}
_ready = true;
recalculateProjection();
Engine::getInstance()->begin();
return true;
}
bool RendererOGL::checkOpenGLErrors()
{
bool error = false;
while (GLenum error = glGetError() != GL_NO_ERROR)
{
const char* errorStr = "Unknown error";
switch (error)
{
case GL_INVALID_ENUM: errorStr = "GL_INVALID_ENUM"; break;
case GL_INVALID_VALUE: errorStr = "GL_INVALID_VALUE"; break;
case GL_INVALID_OPERATION: errorStr = "GL_INVALID_OPERATION"; break;
case GL_OUT_OF_MEMORY: errorStr = "GL_OUT_OF_MEMORY"; break;
case GL_INVALID_FRAMEBUFFER_OPERATION: errorStr = "GL_INVALID_FRAMEBUFFER_OPERATION"; break;
}
log("OpenGL error: %s (%x)", errorStr, error);
error = true;
}
return error;
}
void RendererOGL::setClearColor(Color color)
{
Renderer::setClearColor(color);
glClearColor(_clearColor.getR(), _clearColor.getG(), _clearColor.getB(), _clearColor.getA());
}
void RendererOGL::recalculateProjection()
{
Renderer::recalculateProjection();
if (_ready)
{
glViewport(0, 0, _size.width, _size.height);
}
}
void RendererOGL::clear()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
checkOpenGLErrors();
}
void RendererOGL::flush()
{
glFlush();
checkOpenGLErrors();
}
Texture* RendererOGL::loadTextureFromFile(const std::string& filename)
{
TextureOGL* texture = new TextureOGL();
if (!texture->initFromFile(filename))
{
delete texture;
texture = nullptr;
}
return texture;
}
bool RendererOGL::activateTexture(Texture* texture, uint32_t layer)
{
if (!Renderer::activateTexture(texture, layer))
{
return false;
}
glActiveTexture(GL_TEXTURE0 + layer);
if (texture)
{
TextureOGL* textureOGL = static_cast<TextureOGL*>(texture);
glBindTexture(GL_TEXTURE_2D, textureOGL->getTextureId());
}
else
{
glBindTexture(GL_TEXTURE_2D, 0);
}
if (checkOpenGLErrors())
{
return false;
}
return true;
}
Shader* RendererOGL::loadShaderFromFiles(const std::string& fragmentShader, const std::string& vertexShader, uint32_t vertexAttributes)
{
ShaderOGL* shader = new ShaderOGL();
if (!shader->initFromFiles(fragmentShader, vertexShader, vertexAttributes))
{
delete shader;
shader = nullptr;
}
return shader;
}
Shader* RendererOGL::loadShaderFromBuffers(const uint8_t* fragmentShader, uint32_t fragmentShaderSize, const uint8_t* vertexShader, uint32_t vertexShaderSize, uint32_t vertexAttributes)
{
ShaderOGL* shader = new ShaderOGL();
if (!shader->initFromBuffers(fragmentShader, fragmentShaderSize, vertexShader, vertexShaderSize, vertexAttributes))
{
delete shader;
shader = nullptr;
}
return shader;
}
bool RendererOGL::activateShader(Shader* shader)
{
if (!Renderer::activateShader(shader))
{
return false;
}
if (shader)
{
ShaderOGL* shaderOGL = static_cast<ShaderOGL*>(shader);
glUseProgram(shaderOGL->getProgramId());
if (checkOpenGLErrors())
{
return false;
}
}
else
{
glUseProgram(0);
}
return true;
}
MeshBuffer* RendererOGL::createMeshBuffer(const std::vector<uint16_t>& indices, const std::vector<VertexPCT>& vertices, bool dynamicIndexBuffer, bool dynamicVertexBuffer)
{
MeshBufferOGL* meshBuffer = new MeshBufferOGL();
if (!meshBuffer->initFromData(indices, vertices, dynamicIndexBuffer, dynamicVertexBuffer))
{
delete meshBuffer;
meshBuffer = nullptr;
}
return meshBuffer;
}
bool RendererOGL::drawMeshBuffer(MeshBuffer* meshBuffer)
{
if (!Renderer::drawMeshBuffer(meshBuffer))
{
return false;
}
MeshBufferOGL* meshBufferOGL = static_cast<MeshBufferOGL*>(meshBuffer);
glBindVertexArray(meshBufferOGL->getVertexArrayId());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshBufferOGL->getIndexBufferId());
glDrawElements(GL_TRIANGLES, meshBufferOGL->getIndexCount(), GL_UNSIGNED_SHORT, nullptr);
if (checkOpenGLErrors())
{
return false;
}
return true;
}
void RendererOGL::drawLine(const Vector2& start, const Vector2& finish, const Color& color, const Matrix4& transform)
{
GLuint vertexArray = 0;
GLuint vertexBuffer = 0;
GLuint indexBuffer = 0;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
GLfloat vertices[] = {
start.x, start.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(),
finish.x, finish.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA()
};
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(12));
GLubyte indices[] = {0, 1};
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
ShaderOGL* colorShader = static_cast<ShaderOGL*>(getShader(SHADER_COLOR));
activateShader(colorShader);
Matrix4 modelViewProj = _projection * Scene::getInstance()->getCamera()->getTransform() * transform;
uint32_t uniModelViewProj = colorShader->getVertexShaderConstantId("modelViewProj");
colorShader->setVertexShaderConstant(uniModelViewProj, { modelViewProj });
glBindVertexArray(vertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glDrawElements(GL_LINE_STRIP, 2, GL_UNSIGNED_BYTE, nullptr);
// delete buffers
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
}
void RendererOGL::drawRectangle(const Rectangle& rectangle, const Color& color, const Matrix4& transform)
{
GLuint vertexArray = 0;
GLuint vertexBuffer = 0;
GLuint indexBuffer = 0;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
GLfloat vertices[] = {
rectangle.x, rectangle.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(),
rectangle.x + rectangle.width, rectangle.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(),
rectangle.x, rectangle.y + rectangle.height, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(),
rectangle.x + rectangle.width, rectangle.y + rectangle.height, 0.0f, color.getR(), color.getG(), color.getB(), color.getA()
};
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(12));
GLubyte indices[] = {0, 1, 3, 2, 0};
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
ShaderOGL* colorShader = static_cast<ShaderOGL*>(getShader(SHADER_COLOR));
activateShader(colorShader);
Matrix4 modelViewProj = _projection * Scene::getInstance()->getCamera()->getTransform() * transform;
uint32_t uniModelViewProj = colorShader->getVertexShaderConstantId("modelViewProj");
colorShader->setVertexShaderConstant(uniModelViewProj, { modelViewProj });
glBindVertexArray(vertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glDrawElements(GL_LINE_STRIP, 5, GL_UNSIGNED_BYTE, nullptr);
// delete buffers
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
}
void RendererOGL::drawQuad(const Rectangle& rectangle, const Color& color, const Matrix4& transform)
{
GLuint vertexArray = 0;
GLuint vertexBuffer = 0;
GLuint indexBuffer = 0;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
GLfloat vertices[] = {
rectangle.x, rectangle.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(), 0.0f, 1.0f,
rectangle.x + rectangle.width, rectangle.y, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(), 1.0f, 1.0f,
rectangle.x, rectangle.y + rectangle.height, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(), 0.0f, 0.0f,
rectangle.x + rectangle.width, rectangle.y + rectangle.height, 0.0f, color.getR(), color.getG(), color.getB(), color.getA(), 1.0f, 0.0f
};
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(12));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), reinterpret_cast<const GLvoid*>(16));
GLubyte indices[] = {0, 1, 2, 1, 3, 2};
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
ShaderOGL* colorShader = static_cast<ShaderOGL*>(getShader(SHADER_TEXTURE));
activateShader(colorShader);
Matrix4 modelViewProj = _projection * Scene::getInstance()->getCamera()->getTransform() * transform;
uint32_t uniModelViewProj = colorShader->getVertexShaderConstantId("modelViewProj");
colorShader->setVertexShaderConstant(uniModelViewProj, { modelViewProj });
glBindVertexArray(vertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, nullptr);
// delete buffers
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: tbinsert.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2004-11-19 11:15:30 $
*
* 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): _______________________________________
*
*
************************************************************************/
// System - Includes -----------------------------------------------------
#include <string> // HACK: prevent conflict between STLPORT and Workshop headers
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include <tools/shl.hxx>
#include <svtools/intitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/imagemgr.hxx>
#include "tbinsert.hxx"
#include "tbinsert.hrc"
#include "global.hxx"
#include "scmod.hxx"
#include "scresid.hxx"
#include "sc.hrc"
// -----------------------------------------------------------------------
SFX_IMPL_TOOLBOX_CONTROL( ScTbxInsertCtrl, SfxUInt16Item);
//------------------------------------------------------------------
//
// ToolBox - Controller
//
//------------------------------------------------------------------
ScTbxInsertCtrl::ScTbxInsertCtrl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
SfxToolBoxControl( nSlotId, nId, rTbx ),
nLastSlotId(0)
{
rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
}
__EXPORT ScTbxInsertCtrl::~ScTbxInsertCtrl()
{
}
void __EXPORT ScTbxInsertCtrl::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState )
{
GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );
if( eState == SFX_ITEM_AVAILABLE )
{
const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );
if(pItem)
{
nLastSlotId = pItem->GetValue();
USHORT nImageId = nLastSlotId ? nLastSlotId : GetSlotId();
rtl::OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( "slot:" ));
aSlotURL += rtl::OUString::valueOf( sal_Int32( nImageId ));
Image aImage = GetImage( m_xFrame,
aSlotURL,
hasBigImages(),
GetToolBox().GetDisplayBackground().GetColor().IsDark() );
GetToolBox().SetItemImage(GetId(), aImage);
}
}
}
SfxPopupWindow* __EXPORT ScTbxInsertCtrl::CreatePopupWindow()
{
USHORT nWinResId, nTbxResId;
USHORT nSlotId = GetSlotId();
if (nSlotId == SID_TBXCTL_INSERT)
{
rtl::OUString aInsertBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertbar" ));
createAndPositionSubToolBar( aInsertBarResStr );
// nWinResId = RID_TBXCTL_INSERT;
// nTbxResId = RID_TOOLBOX_INSERT;
}
else if (nSlotId == SID_TBXCTL_INSCELLS)
{
rtl::OUString aInsertCellsBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertcellsbar" ));
createAndPositionSubToolBar( aInsertCellsBarResStr );
// nWinResId = RID_TBXCTL_INSCELLS;
// nTbxResId = RID_TOOLBOX_INSCELLS;
}
else /* SID_TBXCTL_INSOBJ */
{
rtl::OUString aInsertObjectBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertobjectbar" ));
createAndPositionSubToolBar( aInsertObjectBarResStr );
// nWinResId = RID_TBXCTL_INSOBJ;
// nTbxResId = RID_TOOLBOX_INSOBJ;
}
/*
WindowAlign eNewAlign = ( GetToolBox().IsHorizontal() ) ? WINDOWALIGN_LEFT : WINDOWALIGN_TOP;
ScTbxInsertPopup *pWin = new ScTbxInsertPopup( nSlotId, eNewAlign,
ScResId(nWinResId), ScResId(nTbxResId), GetBindings() );
pWin->StartPopupMode(&GetToolBox(), TRUE);
pWin->StartSelection();
pWin->Show();
return pWin;
*/
return NULL;
}
SfxPopupWindowType __EXPORT ScTbxInsertCtrl::GetPopupWindowType() const
{
return nLastSlotId ? SFX_POPUPWINDOW_ONTIMEOUT : SFX_POPUPWINDOW_ONCLICK;
}
void __EXPORT ScTbxInsertCtrl::Select( BOOL bMod1 )
{
SfxViewShell* pCurSh( SfxViewShell::Current() );
SfxDispatcher* pDispatch( 0 );
if ( pCurSh )
{
SfxViewFrame* pViewFrame = pCurSh->GetViewFrame();
if ( pViewFrame )
pDispatch = pViewFrame->GetDispatcher();
}
if ( pDispatch )
pDispatch->Execute(nLastSlotId);
}
/*
//------------------------------------------------------------------
//
// Popup - Window
//
//------------------------------------------------------------------
ScTbxInsertPopup::ScTbxInsertPopup( USHORT nId, WindowAlign eNewAlign,
const ResId& rRIdWin, const ResId& rRIdTbx,
SfxBindings& rBindings ) :
SfxPopupWindow ( nId, rRIdWin, rBindings),
aTbx ( this, GetBindings(), rRIdTbx ),
aRIdWinTemp(rRIdWin),
aRIdTbxTemp(rRIdTbx)
{
aTbx.UseDefault();
FreeResource();
aTbx.GetToolBox().SetAlign( eNewAlign );
if (eNewAlign == WINDOWALIGN_LEFT || eNewAlign == WINDOWALIGN_RIGHT)
SetText( EMPTY_STRING );
Size aSize = aTbx.CalcWindowSizePixel();
aTbx.SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
aTbx.GetToolBox().SetSelectHdl( LINK(this, ScTbxInsertPopup, TbxSelectHdl));
aTbxClickHdl = aTbx.GetToolBox().GetClickHdl();
aTbx.GetToolBox().SetClickHdl( LINK(this, ScTbxInsertPopup, TbxClickHdl));
}
ScTbxInsertPopup::~ScTbxInsertPopup()
{
}
SfxPopupWindow* __EXPORT ScTbxInsertPopup::Clone() const
{
return new ScTbxInsertPopup( GetId(), aTbx.GetToolBox().GetAlign(),
aRIdWinTemp, aRIdTbxTemp,
(SfxBindings&) GetBindings() );
}
void ScTbxInsertPopup::StartSelection()
{
aTbx.GetToolBox().StartSelection();
}
IMPL_LINK(ScTbxInsertPopup, TbxSelectHdl, ToolBox*, pBox)
{
EndPopupMode();
USHORT nLastSlotId = pBox->GetCurItemId();
SfxUInt16Item aItem( GetId(), nLastSlotId );
SfxDispatcher* pDisp = GetBindings().GetDispatcher();
pDisp->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
pDisp->Execute( nLastSlotId, SFX_CALLMODE_ASYNCHRON );
return 0;
}
IMPL_LINK(ScTbxInsertPopup, TbxClickHdl, ToolBox*, pBox)
{
USHORT nLastSlotId = pBox->GetCurItemId();
SfxUInt16Item aItem( GetId(), nLastSlotId );
GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
if(aTbxClickHdl.IsSet())
aTbxClickHdl.Call(pBox);
return 0;
}
void __EXPORT ScTbxInsertPopup::PopupModeEnd()
{
aTbx.GetToolBox().EndSelection();
SfxPopupWindow::PopupModeEnd();
}
*/
<commit_msg>INTEGRATION: CWS fwkbugfix04 (1.6.2); FILE MERGED 2004/12/16 11:36:46 mba 1.6.2.1: remove obsolete sfx headers<commit_after>/*************************************************************************
*
* $RCSfile: tbinsert.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2005-01-18 15:47:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// System - Includes -----------------------------------------------------
#include <string> // HACK: prevent conflict between STLPORT and Workshop headers
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include <tools/shl.hxx>
#include <svtools/intitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/imagemgr.hxx>
#include <vcl/toolbox.hxx>
#include "tbinsert.hxx"
#include "tbinsert.hrc"
#include "global.hxx"
#include "scmod.hxx"
#include "scresid.hxx"
#include "sc.hrc"
// -----------------------------------------------------------------------
SFX_IMPL_TOOLBOX_CONTROL( ScTbxInsertCtrl, SfxUInt16Item);
//------------------------------------------------------------------
//
// ToolBox - Controller
//
//------------------------------------------------------------------
ScTbxInsertCtrl::ScTbxInsertCtrl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
SfxToolBoxControl( nSlotId, nId, rTbx ),
nLastSlotId(0)
{
rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
}
__EXPORT ScTbxInsertCtrl::~ScTbxInsertCtrl()
{
}
void __EXPORT ScTbxInsertCtrl::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState )
{
GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );
if( eState == SFX_ITEM_AVAILABLE )
{
const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );
if(pItem)
{
nLastSlotId = pItem->GetValue();
USHORT nImageId = nLastSlotId ? nLastSlotId : GetSlotId();
rtl::OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( "slot:" ));
aSlotURL += rtl::OUString::valueOf( sal_Int32( nImageId ));
Image aImage = GetImage( m_xFrame,
aSlotURL,
hasBigImages(),
GetToolBox().GetDisplayBackground().GetColor().IsDark() );
GetToolBox().SetItemImage(GetId(), aImage);
}
}
}
SfxPopupWindow* __EXPORT ScTbxInsertCtrl::CreatePopupWindow()
{
USHORT nWinResId, nTbxResId;
USHORT nSlotId = GetSlotId();
if (nSlotId == SID_TBXCTL_INSERT)
{
rtl::OUString aInsertBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertbar" ));
createAndPositionSubToolBar( aInsertBarResStr );
// nWinResId = RID_TBXCTL_INSERT;
// nTbxResId = RID_TOOLBOX_INSERT;
}
else if (nSlotId == SID_TBXCTL_INSCELLS)
{
rtl::OUString aInsertCellsBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertcellsbar" ));
createAndPositionSubToolBar( aInsertCellsBarResStr );
// nWinResId = RID_TBXCTL_INSCELLS;
// nTbxResId = RID_TOOLBOX_INSCELLS;
}
else /* SID_TBXCTL_INSOBJ */
{
rtl::OUString aInsertObjectBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertobjectbar" ));
createAndPositionSubToolBar( aInsertObjectBarResStr );
// nWinResId = RID_TBXCTL_INSOBJ;
// nTbxResId = RID_TOOLBOX_INSOBJ;
}
/*
WindowAlign eNewAlign = ( GetToolBox().IsHorizontal() ) ? WINDOWALIGN_LEFT : WINDOWALIGN_TOP;
ScTbxInsertPopup *pWin = new ScTbxInsertPopup( nSlotId, eNewAlign,
ScResId(nWinResId), ScResId(nTbxResId), GetBindings() );
pWin->StartPopupMode(&GetToolBox(), TRUE);
pWin->StartSelection();
pWin->Show();
return pWin;
*/
return NULL;
}
SfxPopupWindowType __EXPORT ScTbxInsertCtrl::GetPopupWindowType() const
{
return nLastSlotId ? SFX_POPUPWINDOW_ONTIMEOUT : SFX_POPUPWINDOW_ONCLICK;
}
void __EXPORT ScTbxInsertCtrl::Select( BOOL bMod1 )
{
SfxViewShell* pCurSh( SfxViewShell::Current() );
SfxDispatcher* pDispatch( 0 );
if ( pCurSh )
{
SfxViewFrame* pViewFrame = pCurSh->GetViewFrame();
if ( pViewFrame )
pDispatch = pViewFrame->GetDispatcher();
}
if ( pDispatch )
pDispatch->Execute(nLastSlotId);
}
/*
//------------------------------------------------------------------
//
// Popup - Window
//
//------------------------------------------------------------------
ScTbxInsertPopup::ScTbxInsertPopup( USHORT nId, WindowAlign eNewAlign,
const ResId& rRIdWin, const ResId& rRIdTbx,
SfxBindings& rBindings ) :
SfxPopupWindow ( nId, rRIdWin, rBindings),
aTbx ( this, GetBindings(), rRIdTbx ),
aRIdWinTemp(rRIdWin),
aRIdTbxTemp(rRIdTbx)
{
aTbx.UseDefault();
FreeResource();
aTbx.GetToolBox().SetAlign( eNewAlign );
if (eNewAlign == WINDOWALIGN_LEFT || eNewAlign == WINDOWALIGN_RIGHT)
SetText( EMPTY_STRING );
Size aSize = aTbx.CalcWindowSizePixel();
aTbx.SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
aTbx.GetToolBox().SetSelectHdl( LINK(this, ScTbxInsertPopup, TbxSelectHdl));
aTbxClickHdl = aTbx.GetToolBox().GetClickHdl();
aTbx.GetToolBox().SetClickHdl( LINK(this, ScTbxInsertPopup, TbxClickHdl));
}
ScTbxInsertPopup::~ScTbxInsertPopup()
{
}
SfxPopupWindow* __EXPORT ScTbxInsertPopup::Clone() const
{
return new ScTbxInsertPopup( GetId(), aTbx.GetToolBox().GetAlign(),
aRIdWinTemp, aRIdTbxTemp,
(SfxBindings&) GetBindings() );
}
void ScTbxInsertPopup::StartSelection()
{
aTbx.GetToolBox().StartSelection();
}
IMPL_LINK(ScTbxInsertPopup, TbxSelectHdl, ToolBox*, pBox)
{
EndPopupMode();
USHORT nLastSlotId = pBox->GetCurItemId();
SfxUInt16Item aItem( GetId(), nLastSlotId );
SfxDispatcher* pDisp = GetBindings().GetDispatcher();
pDisp->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
pDisp->Execute( nLastSlotId, SFX_CALLMODE_ASYNCHRON );
return 0;
}
IMPL_LINK(ScTbxInsertPopup, TbxClickHdl, ToolBox*, pBox)
{
USHORT nLastSlotId = pBox->GetCurItemId();
SfxUInt16Item aItem( GetId(), nLastSlotId );
GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
if(aTbxClickHdl.IsSet())
aTbxClickHdl.Call(pBox);
return 0;
}
void __EXPORT ScTbxInsertPopup::PopupModeEnd()
{
aTbx.GetToolBox().EndSelection();
SfxPopupWindow::PopupModeEnd();
}
*/
<|endoftext|>
|
<commit_before>#ifndef NPA_HPP
#define NPA_HPP
#include "npafile.hpp"
#include "mapfile.hpp"
#include "nsbfile.hpp"
#endif
<commit_msg>Remove npa.hpp<commit_after><|endoftext|>
|
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#pragma once
#ifndef VSNRAY_DETAIL_WHITTED_INL
#define VSNRAY_DETAIL_WHITTED_INL 1
#include <array>
#include <cstddef>
#include <visionaray/get_surface.h>
#include <visionaray/result_record.h>
#include <visionaray/traverse.h>
namespace visionaray
{
namespace whitted
{
namespace detail
{
//-------------------------------------------------------------------------------------------------
// TODO: consolidate this with "real" brdf sampling
// TODO: user should be able to customize this behavior
//
template <typename Vec3, typename Scalar>
struct bounce_result
{
Vec3 reflected_dir;
Vec3 refracted_dir;
Scalar kr;
Scalar kt;
};
// reflection
template <typename V, typename S>
VSNRAY_FUNC
inline auto make_bounce_result(V const& reflected_dir, S kr)
-> bounce_result<V, S>
{
return {
reflected_dir,
V(),
kr,
0.0f
};
}
// reflection and refraction
template <typename V, typename S>
VSNRAY_FUNC
inline auto make_bounce_result(
V const& reflected_dir,
V const& refracted_dir,
S kr,
S kt
)
-> bounce_result<V, S>
{
return {
reflected_dir,
refracted_dir,
kr,
kt
};
}
//-------------------------------------------------------------------------------------------------
// specular_bounce() overloads for some materials
//
// fall-through, e.g. for plastic, assigns a dflt. reflectivity and no refraction
template <typename V, typename M>
VSNRAY_FUNC
inline auto specular_bounce(
M const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
VSNRAY_UNUSED(mat);
return make_bounce_result(
reflect(view_dir, normal),
typename V::value_type(0.1)
);
}
// matte, no specular reflectivity, returns an arbitrary direction
template <typename V, typename S>
VSNRAY_FUNC
inline auto specular_bounce(
matte<S> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
VSNRAY_UNUSED(mat);
VSNRAY_UNUSED(view_dir);
VSNRAY_UNUSED(normal);
return make_bounce_result(
V(),
typename V::value_type(0.0)
);
}
// mirror material, here we know kr
template <typename V, typename S>
VSNRAY_FUNC
inline auto specular_bounce(
mirror<S> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
return make_bounce_result(
reflect(view_dir, normal),
mat.get_kr()
);
}
//-------------------------------------------------------------------------------------------------
// some special treatment for generic materials
//
template <typename V>
struct visitor
{
using return_type = decltype( make_bounce_result(V(), typename V::value_type()) );
VSNRAY_FUNC visitor(V const& vd, V const& n)
: view_dir(vd)
, normal(n)
{
}
template <typename X>
VSNRAY_FUNC
return_type operator()(X const& ref) const
{
return specular_bounce(ref, view_dir, normal);
}
V const& view_dir;
V const& normal;
};
template <typename V, typename ...Ts>
VSNRAY_FUNC
inline auto specular_bounce(
generic_material<Ts...> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
return apply_visitor(visitor<V>(view_dir, normal), mat);
}
template <
size_t N,
typename ...Ts,
typename T,
typename = typename std::enable_if<simd::is_simd_vector<T>::value>::type
>
inline auto specular_bounce(
simd::generic_material<N, Ts...> const& mat,
vector<3, T> const& view_dir,
vector<3, T> const& normal
)
-> bounce_result<vector<3, T>, T>
{
using float_array = simd::aligned_array_t<T>;
auto ms = unpack(mat);
auto vds = unpack(view_dir);
auto ns = unpack(normal);
std::array<vector<3, float>, N> refl_dir;
std::array<vector<3, float>, N> refr_dir;
float_array kr;
float_array kt;
for (size_t i = 0; i < N; ++i)
{
auto res = specular_bounce(ms[i], vds[i], ns[i]);
refl_dir[i] = res.reflected_dir;
refr_dir[i] = res.refracted_dir;
kr[i] = res.kr;
kt[i] = res.kt;
}
return make_bounce_result(
simd::pack(refl_dir),
simd::pack(refr_dir),
T(kr),
T(kt)
);
}
} // detail
//-------------------------------------------------------------------------------------------------
// Whitted kernel
//
template <typename Params>
struct kernel
{
Params params;
template <typename Intersector, typename R>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(Intersector& isect, R ray) const
{
using S = typename R::scalar_type;
using V = typename result_record<S>::vec_type;
using C = spectrum<S>;
result_record<S> result;
auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
if (any(hit_rec.hit))
{
result.hit = hit_rec.hit;
result.isect_pos = ray.ori + ray.dir * hit_rec.t;
}
else
{
result.hit = false;
result.color = params.bg_color;
return result;
}
C color(0.0);
unsigned depth = 0;
C no_hit_color(from_rgba(params.bg_color));
S throughput(1.0);
while (any(hit_rec.hit) && any(throughput > S(params.epsilon)) && depth++ < params.num_bounces)
{
hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;
auto surf = get_surface(hit_rec, params);
auto ambient = surf.material.ambient() * C(from_rgba(params.ambient_color));
auto shaded_clr = select( hit_rec.hit, ambient, C(from_rgba(params.bg_color)) );
auto view_dir = -ray.dir;
auto n = surf.shading_normal;
#if 1 // two-sided
n = faceforward( n, view_dir, surf.geometric_normal );
#endif
for (auto it = params.lights.begin; it != params.lights.end; ++it)
{
auto light_dir = normalize( V(it->position()) - hit_rec.isect_pos );
R shadow_ray
(
hit_rec.isect_pos + light_dir * S(params.epsilon),
light_dir
);
// only cast a shadow if occluder between light source and hit pos
auto shadow_rec = any_hit(
shadow_ray,
params.prims.begin,
params.prims.end,
length(hit_rec.isect_pos - V(it->position())),
isect
);
auto active_rays = hit_rec.hit & !shadow_rec.hit;
auto sr = make_shade_record<Params, S>();
sr.active = active_rays;
sr.isect_pos = hit_rec.isect_pos;
sr.normal = n;
sr.view_dir = view_dir;
sr.light_dir = light_dir;
sr.light = *it;
auto clr = surf.shade(sr);
shaded_clr += select( active_rays, clr, C(0.0) );
}
color += select( hit_rec.hit, shaded_clr, no_hit_color ) * throughput;
auto bounce = detail::specular_bounce(surf.material, view_dir, surf.shading_normal);
if (any(bounce.kr > S(0.0)))
{
auto dir = bounce.reflected_dir;
ray = R(
hit_rec.isect_pos + dir * S(params.epsilon),
dir
);
hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
}
throughput *= bounce.kr;
no_hit_color = C(0.0);
}
result.color = select( result.hit, to_rgba(color), params.bg_color );
return result;
}
template <typename R>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(R ray) const
{
default_intersector ignore;
return (*this)(ignore, ray);
}
};
} // whitted
} // visionaray
#endif // VSNRAY_DETAIL_WHITTED_INL
<commit_msg>Missing header<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#pragma once
#ifndef VSNRAY_DETAIL_WHITTED_INL
#define VSNRAY_DETAIL_WHITTED_INL 1
#include <array>
#include <cstddef>
#include <type_traits>
#include <visionaray/get_surface.h>
#include <visionaray/result_record.h>
#include <visionaray/traverse.h>
namespace visionaray
{
namespace whitted
{
namespace detail
{
//-------------------------------------------------------------------------------------------------
// TODO: consolidate this with "real" brdf sampling
// TODO: user should be able to customize this behavior
//
template <typename Vec3, typename Scalar>
struct bounce_result
{
Vec3 reflected_dir;
Vec3 refracted_dir;
Scalar kr;
Scalar kt;
};
// reflection
template <typename V, typename S>
VSNRAY_FUNC
inline auto make_bounce_result(V const& reflected_dir, S kr)
-> bounce_result<V, S>
{
return {
reflected_dir,
V(),
kr,
0.0f
};
}
// reflection and refraction
template <typename V, typename S>
VSNRAY_FUNC
inline auto make_bounce_result(
V const& reflected_dir,
V const& refracted_dir,
S kr,
S kt
)
-> bounce_result<V, S>
{
return {
reflected_dir,
refracted_dir,
kr,
kt
};
}
//-------------------------------------------------------------------------------------------------
// specular_bounce() overloads for some materials
//
// fall-through, e.g. for plastic, assigns a dflt. reflectivity and no refraction
template <typename V, typename M>
VSNRAY_FUNC
inline auto specular_bounce(
M const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
VSNRAY_UNUSED(mat);
return make_bounce_result(
reflect(view_dir, normal),
typename V::value_type(0.1)
);
}
// matte, no specular reflectivity, returns an arbitrary direction
template <typename V, typename S>
VSNRAY_FUNC
inline auto specular_bounce(
matte<S> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
VSNRAY_UNUSED(mat);
VSNRAY_UNUSED(view_dir);
VSNRAY_UNUSED(normal);
return make_bounce_result(
V(),
typename V::value_type(0.0)
);
}
// mirror material, here we know kr
template <typename V, typename S>
VSNRAY_FUNC
inline auto specular_bounce(
mirror<S> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
return make_bounce_result(
reflect(view_dir, normal),
mat.get_kr()
);
}
//-------------------------------------------------------------------------------------------------
// some special treatment for generic materials
//
template <typename V>
struct visitor
{
using return_type = decltype( make_bounce_result(V(), typename V::value_type()) );
VSNRAY_FUNC visitor(V const& vd, V const& n)
: view_dir(vd)
, normal(n)
{
}
template <typename X>
VSNRAY_FUNC
return_type operator()(X const& ref) const
{
return specular_bounce(ref, view_dir, normal);
}
V const& view_dir;
V const& normal;
};
template <typename V, typename ...Ts>
VSNRAY_FUNC
inline auto specular_bounce(
generic_material<Ts...> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
return apply_visitor(visitor<V>(view_dir, normal), mat);
}
template <
size_t N,
typename ...Ts,
typename T,
typename = typename std::enable_if<simd::is_simd_vector<T>::value>::type
>
inline auto specular_bounce(
simd::generic_material<N, Ts...> const& mat,
vector<3, T> const& view_dir,
vector<3, T> const& normal
)
-> bounce_result<vector<3, T>, T>
{
using float_array = simd::aligned_array_t<T>;
auto ms = unpack(mat);
auto vds = unpack(view_dir);
auto ns = unpack(normal);
std::array<vector<3, float>, N> refl_dir;
std::array<vector<3, float>, N> refr_dir;
float_array kr;
float_array kt;
for (size_t i = 0; i < N; ++i)
{
auto res = specular_bounce(ms[i], vds[i], ns[i]);
refl_dir[i] = res.reflected_dir;
refr_dir[i] = res.refracted_dir;
kr[i] = res.kr;
kt[i] = res.kt;
}
return make_bounce_result(
simd::pack(refl_dir),
simd::pack(refr_dir),
T(kr),
T(kt)
);
}
} // detail
//-------------------------------------------------------------------------------------------------
// Whitted kernel
//
template <typename Params>
struct kernel
{
Params params;
template <typename Intersector, typename R>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(Intersector& isect, R ray) const
{
using S = typename R::scalar_type;
using V = typename result_record<S>::vec_type;
using C = spectrum<S>;
result_record<S> result;
auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
if (any(hit_rec.hit))
{
result.hit = hit_rec.hit;
result.isect_pos = ray.ori + ray.dir * hit_rec.t;
}
else
{
result.hit = false;
result.color = params.bg_color;
return result;
}
C color(0.0);
unsigned depth = 0;
C no_hit_color(from_rgba(params.bg_color));
S throughput(1.0);
while (any(hit_rec.hit) && any(throughput > S(params.epsilon)) && depth++ < params.num_bounces)
{
hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;
auto surf = get_surface(hit_rec, params);
auto ambient = surf.material.ambient() * C(from_rgba(params.ambient_color));
auto shaded_clr = select( hit_rec.hit, ambient, C(from_rgba(params.bg_color)) );
auto view_dir = -ray.dir;
auto n = surf.shading_normal;
#if 1 // two-sided
n = faceforward( n, view_dir, surf.geometric_normal );
#endif
for (auto it = params.lights.begin; it != params.lights.end; ++it)
{
auto light_dir = normalize( V(it->position()) - hit_rec.isect_pos );
R shadow_ray
(
hit_rec.isect_pos + light_dir * S(params.epsilon),
light_dir
);
// only cast a shadow if occluder between light source and hit pos
auto shadow_rec = any_hit(
shadow_ray,
params.prims.begin,
params.prims.end,
length(hit_rec.isect_pos - V(it->position())),
isect
);
auto active_rays = hit_rec.hit & !shadow_rec.hit;
auto sr = make_shade_record<Params, S>();
sr.active = active_rays;
sr.isect_pos = hit_rec.isect_pos;
sr.normal = n;
sr.view_dir = view_dir;
sr.light_dir = light_dir;
sr.light = *it;
auto clr = surf.shade(sr);
shaded_clr += select( active_rays, clr, C(0.0) );
}
color += select( hit_rec.hit, shaded_clr, no_hit_color ) * throughput;
auto bounce = detail::specular_bounce(surf.material, view_dir, surf.shading_normal);
if (any(bounce.kr > S(0.0)))
{
auto dir = bounce.reflected_dir;
ray = R(
hit_rec.isect_pos + dir * S(params.epsilon),
dir
);
hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
}
throughput *= bounce.kr;
no_hit_color = C(0.0);
}
result.color = select( result.hit, to_rgba(color), params.bg_color );
return result;
}
template <typename R>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(R ray) const
{
default_intersector ignore;
return (*this)(ignore, ray);
}
};
} // whitted
} // visionaray
#endif // VSNRAY_DETAIL_WHITTED_INL
<|endoftext|>
|
<commit_before>///
/// @file PreSieve.cpp
/// @brief Pre-sieve multiples of small primes to speed up the
/// sieve of Eratosthenes.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/PreSieve.hpp>
#include <primesieve/EratSmall.hpp>
#include <stdint.h>
#include <cstring>
using namespace std;
using namespace primesieve;
namespace {
const uint_t primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
const uint_t primeProduct[] = { 2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870 };
}
namespace primesieve {
PreSieve::PreSieve(uint64_t start, uint64_t stop) :
limit_(7),
preSieve_(NULL)
{
uint64_t interval = stop - start;
// only use a large preSieve_ buffer if the sieve
// interval is sufficiently large
for (int i = 4; i < 8; i++)
if (interval / 10 > primeProduct[i])
limit_ = primes[i];
init();
}
PreSieve::~PreSieve()
{
delete[] preSieve_;
}
/// Cross-off the multiples of small primes <= limit_
/// in the preSieve_ array.
///
void PreSieve::init()
{
for (int i = 0; primes[i] <= limit_; i++)
primeProduct_ = primeProduct[i];
size_ = primeProduct_ / NUMBERS_PER_BYTE;
preSieve_ = new byte_t[size_];
memset(preSieve_, 0xff, size_);
uint_t stop = primeProduct_ * 2;
EratSmall eratSmall(stop, size_, limit_);
for (int i = 3; primes[i] <= limit_; i++)
eratSmall.addSievingPrime(primes[i], primeProduct_);
// sieve [primeProduct_, primeProduct_ * 2]
eratSmall.crossOff(preSieve_, &preSieve_[size_]);
}
/// Pre-sieve the multiples of small primes <= limit_
/// by copying preSieve_ to sieve.
///
void PreSieve::doIt(byte_t* sieve,
uint_t sieveSize,
uint64_t segmentLow) const
{
// map segmentLow to the preSieve_ array
uint_t remainder = static_cast<uint_t>(segmentLow % primeProduct_);
uint_t index = remainder / NUMBERS_PER_BYTE;
uint_t sizeLeft = size_ - index;
if (sieveSize <= sizeLeft)
memcpy(sieve, &preSieve_[index], sieveSize);
else
{
// copy the last remaining bytes at the end of preSieve_
// to the beginning of the sieve array
memcpy(sieve, &preSieve_[index], sizeLeft);
// restart copying at the beginning of preSieve_
for (index = sizeLeft; index + size_ < sieveSize; index += size_)
memcpy(&sieve[index], preSieve_, size_);
memcpy(&sieve[index], preSieve_, sieveSize - index);
}
}
} // namespace
<commit_msg>Performance tuning<commit_after>///
/// @file PreSieve.cpp
/// @brief Pre-sieve multiples of small primes to speed up the
/// sieve of Eratosthenes.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/PreSieve.hpp>
#include <primesieve/EratSmall.hpp>
#include <stdint.h>
#include <cstring>
using namespace std;
using namespace primesieve;
namespace {
const uint_t primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
const uint_t primeProduct[] = { 2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870 };
}
namespace primesieve {
PreSieve::PreSieve(uint64_t start, uint64_t stop) :
limit_(7),
preSieve_(NULL)
{
// only use a large preSieve_ buffer if the
// sieve interval is sufficiently large
uint64_t interval = stop - start;
uint64_t threshold = max(isqrt(stop), interval) / 10;
for (int i = 4; i < 8; i++)
if (threshold > primeProduct[i])
limit_ = primes[i];
init();
}
PreSieve::~PreSieve()
{
delete[] preSieve_;
}
/// Cross-off the multiples of small primes <= limit_
/// in the preSieve_ array.
///
void PreSieve::init()
{
for (int i = 0; primes[i] <= limit_; i++)
primeProduct_ = primeProduct[i];
size_ = primeProduct_ / NUMBERS_PER_BYTE;
preSieve_ = new byte_t[size_];
memset(preSieve_, 0xff, size_);
uint_t stop = primeProduct_ * 2;
EratSmall eratSmall(stop, size_, limit_);
for (int i = 3; primes[i] <= limit_; i++)
eratSmall.addSievingPrime(primes[i], primeProduct_);
// sieve [primeProduct_, primeProduct_ * 2]
eratSmall.crossOff(preSieve_, &preSieve_[size_]);
}
/// Pre-sieve the multiples of small primes <= limit_
/// by copying preSieve_ to sieve.
///
void PreSieve::doIt(byte_t* sieve,
uint_t sieveSize,
uint64_t segmentLow) const
{
// map segmentLow to the preSieve_ array
uint_t remainder = static_cast<uint_t>(segmentLow % primeProduct_);
uint_t index = remainder / NUMBERS_PER_BYTE;
uint_t sizeLeft = size_ - index;
if (sieveSize <= sizeLeft)
memcpy(sieve, &preSieve_[index], sieveSize);
else
{
// copy the last remaining bytes at the end of preSieve_
// to the beginning of the sieve array
memcpy(sieve, &preSieve_[index], sizeLeft);
// restart copying at the beginning of preSieve_
for (index = sizeLeft; index + size_ < sieveSize; index += size_)
memcpy(&sieve[index], preSieve_, size_);
memcpy(&sieve[index], preSieve_, sieveSize - index);
}
}
} // namespace
<|endoftext|>
|
<commit_before>#include <ctime>
#include <string>
#include <map>
#include <vector>
#include <sstream>
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
typedef map<int, string, less<int> > names;
typedef map<string, int, less<string> > points;
int number(int from, int to)
{
return ((random() % (to - from + 1)) + from);
}
class elimination
{
public:
elimination() : _votes(MAX_VOTES), _turn(0)
{
}
void load()
{
ifstream file(_filename.c_str());
if (file.is_open() && file.good()) {
int i = 0;
string line;
while (getline(file, line)) {
// sloppy trim
line.erase(line.find_last_not_of(" \n\r\t") + 1);
_names[++i] = line;
}
file.close();
}
}
void list()
{
auto it = _names.begin();
while (it != _names.end()) {
cout << (*it).second << endl;
it++;
}
}
void print(string *pbuf = NULL, string *mbuf = NULL)
{
// Print out current score.
cout << "Turn " << setw(3) << setfill(' ') << _turn << " " << setfill('-') << setw(38) << "" << endl;
if (pbuf && !pbuf->empty()) {
cout << *pbuf << endl;
}
if (mbuf && !mbuf->empty()) {
cout << *mbuf << endl;
}
cout << endl;
auto scit = _points.begin();
while (scit != _points.end()) {
if (_points.size() == 1) {
cout << "Winner: " << endl;
}
cout << left << setfill(' ') << setw(34) << scit->first << " [" << scit->second << "]" << endl;
scit++;
}
cout << endl << "Eliminated:" << endl;
auto nit = _elims.begin();
while (nit != _elims.end()) {
cout << right << setw(3) << setfill(' ') << (*nit).first << ". " << (*nit).second << endl;
nit++;
}
cout << endl;
}
void sim()
{
auto it = _names.begin();
while (it != _names.end()) {
_points.insert(make_pair((*it).second, _votes));
it++;
}
while (_points.size() > 1) {
++_turn;
string pbuf, mbuf;
int plus = number(1, _points.size());
int minus = plus;
while (minus == plus) {
minus = number(1, _points.size());
}
int i = 1;
stringstream ss;
// Brute force
auto pit = _points.begin();
for (; pit != _points.end(); i++, ++pit) {
if (i == plus) {
pit->second += UP_VOTE;
ss.str(string()); // reset
ss << pit->first << " [" << pit->second << "] " << UP_VOTE;
pbuf = ss.str();
} else if (i == minus) {
pit->second += DOWN_VOTE;
ss.str(string()); // reset
ss << pit->first << " [" << pit->second << "] " << DOWN_VOTE;
mbuf = ss.str();
if (pit->second <= 0) {
_elims.insert(make_pair(_names.size() - _elims.size(), pit->first));
_points.erase(pit);
pit = _points.begin();
i = 0; // reset
}
}
}
print(&pbuf, &mbuf);
// getline (cin, pbuf);
}
}
inline void setFilename(string filename)
{
_filename = filename;
}
private:
static const int MAX_VOTES = 20;
static const int UP_VOTE = 1;
static const int DOWN_VOTE = -2;
int _votes;
int _turn;
string _filename;
names _names;
points _points;
names _elims;
};
int main(int argc, char *argv[], char *envp[])
{
srandom(time(0));
if (argc > 1) {
elimination elim;
elim.setFilename(argv[1]);
elim.load();
elim.sim();
}
return 0;
}
<commit_msg>Get rid of brute force method and use std::advance instead to move iterator.<commit_after>#include <ctime>
#include <string>
#include <map>
#include <sstream>
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
typedef map<int, string, less<int> > names;
typedef map<string, int, less<string> > points;
int number(int from, int to)
{
return ((random() % (to - from + 1)) + from);
}
class elimination
{
public:
elimination() : _votes(MAX_VOTES), _turn(0)
{
}
void load()
{
ifstream file(_filename.c_str());
if (file.is_open() && file.good()) {
int i = 0;
string line;
while (getline(file, line)) {
// sloppy trim
line.erase(line.find_last_not_of(" \n\r\t") + 1);
_names[++i] = line;
}
file.close();
}
}
void list()
{
auto it = _names.begin();
while (it != _names.end()) {
cout << (*it).second << endl;
it++;
}
}
void print(string *pbuf = NULL, string *mbuf = NULL)
{
// Print out current score.
cout << "Turn " << setw(3) << setfill(' ') << _turn << " " << setfill('-') << setw(38) << "" << endl;
if (pbuf && !pbuf->empty()) {
cout << *pbuf << endl;
}
if (mbuf && !mbuf->empty()) {
cout << *mbuf << endl;
}
cout << endl;
auto scit = _points.begin();
while (scit != _points.end()) {
if (_points.size() == 1) {
cout << "Winner: " << endl;
}
cout << left << setfill(' ') << setw(34) << scit->first << " [" << scit->second << "]" << endl;
scit++;
}
if (_elims.size() > 0) {
cout << endl << "Eliminated:" << endl;
auto nit = _elims.begin();
while (nit != _elims.end()) {
cout << right << setw(3) << setfill(' ') << (*nit).first << ". " << (*nit).second << endl;
nit++;
}
}
cout << endl;
}
void sim()
{
// Build the points for each story
auto it = _names.begin();
while (it != _names.end()) {
_points.insert(make_pair((*it).second, _votes));
it++;
}
while (_points.size() > 1) {
++_turn;
string pbuf, mbuf;
int plus = number(1, _points.size());
int minus = plus;
while (minus == plus) {
minus = number(1, _points.size());
}
stringstream ss;
auto pit = _points.begin();
// Adjust the plus story
advance(pit, plus - 1);
pit->second += UP_VOTE;
ss << pit->first << " [" << pit->second << "] " << UP_VOTE;
pbuf = ss.str();
pit = _points.begin();
// Adjust the minus story
advance(pit, minus - 1);
pit->second += DOWN_VOTE;
ss.str(string()); // reset
ss << pit->first << " [" << pit->second << "] " << DOWN_VOTE;
mbuf = ss.str();
// Was minus story eliminated?
if (pit->second <= 0) {
_elims.insert(make_pair(_names.size() - _elims.size(), pit->first));
_points.erase(pit);
pit = _points.begin();
}
print(&pbuf, &mbuf);
// getline (cin, pbuf);
}
}
inline void setFilename(string filename)
{
_filename = filename;
}
private:
static const int MAX_VOTES = 20;
static const int UP_VOTE = 1;
static const int DOWN_VOTE = -2;
int _votes;
int _turn;
string _filename;
names _names;
points _points;
names _elims;
};
int main(int argc, char *argv[], char *envp[])
{
srandom(time(0));
if (argc > 1) {
elimination elim;
elim.setFilename(argv[1]);
elim.load();
elim.sim();
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "ImGuiToolSystem.hpp"
#include "EntityManager.hpp"
#include "components/ImGuiComponent.hpp"
#include "imgui.h"
#include "to_string.hpp"
#ifndef KENGINE_IMGUI_TOOLS_SAVE_FILE
# define KENGINE_IMGUI_TOOLS_SAVE_FILE "tools.cnf"
#endif
class ConfFile {
public:
void parse() {
std::ifstream f(KENGINE_IMGUI_TOOLS_SAVE_FILE);
if (!f)
return;
for (std::string line; std::getline(f, line);)
addLine(line);
}
void addLine(const std::string & line) {
const auto index = line.find(';');
_values[line.substr(0, index)] = putils::parse<bool>(line.substr(index + 1).c_str());
}
bool getValue(const char * name) const {
const auto it = _values.find(name);
if (it == _values.end())
return false;
return it->second;
}
private:
std::unordered_map<std::string, bool> _values;
};
static ConfFile g_confFile;
static void saveTools(kengine::EntityManager & em) {
std::ofstream f(KENGINE_IMGUI_TOOLS_SAVE_FILE);
assert(f);
for (const auto & [e, tool] : em.getEntities<kengine::ImGuiToolComponent>())
f << tool.name << ';' << std::boolalpha << tool.enabled << std::noboolalpha << '\n';
f.flush();
}
static auto ToolsController(kengine::EntityManager & em) {
return [&](kengine::Entity & e) {
e += kengine::ImGuiComponent([&] {
if (ImGui::BeginMainMenuBar()) {
bool mustSave = false;
if (ImGui::BeginMenu("Tools")) {
if (ImGui::MenuItem("Disable all"))
for (auto & [e, tool] : em.getEntities<kengine::ImGuiToolComponent>())
tool.enabled = false;
for (auto & [e, tool] : em.getEntities<kengine::ImGuiToolComponent>())
if (ImGui::MenuItem(tool.name)) {
tool.enabled = !tool.enabled;
mustSave = true;
}
ImGui::EndMenu();
}
if (mustSave)
saveTools(em);
}
ImGui::EndMainMenuBar();
});
};
}
namespace kengine {
ImGuiToolSystem::ImGuiToolSystem(EntityManager & em) : System(em), _em(em) {
onLoad("");
g_confFile.parse();
}
void ImGuiToolSystem::onLoad(const char *) noexcept {
_em += ToolsController(_em);
}
void ImGuiToolSystem::handle(packets::RegisterEntity p) noexcept {
if (!p.e.has<ImGuiToolComponent>())
return;
auto & tool = p.e.get<ImGuiToolComponent>();
tool.enabled = g_confFile.getValue(tool.name);
}
}<commit_msg>fix alignment<commit_after>#include "ImGuiToolSystem.hpp"
#include "EntityManager.hpp"
#include "components/ImGuiComponent.hpp"
#include "imgui.h"
#include "to_string.hpp"
#ifndef KENGINE_IMGUI_TOOLS_SAVE_FILE
# define KENGINE_IMGUI_TOOLS_SAVE_FILE "tools.cnf"
#endif
class ConfFile {
public:
void parse() {
std::ifstream f(KENGINE_IMGUI_TOOLS_SAVE_FILE);
if (!f)
return;
for (std::string line; std::getline(f, line);)
addLine(line);
}
void addLine(const std::string & line) {
const auto index = line.find(';');
_values[line.substr(0, index)] = putils::parse<bool>(line.substr(index + 1).c_str());
}
bool getValue(const char * name) const {
const auto it = _values.find(name);
if (it == _values.end())
return false;
return it->second;
}
private:
std::unordered_map<std::string, bool> _values;
};
static ConfFile g_confFile;
static void saveTools(kengine::EntityManager & em) {
std::ofstream f(KENGINE_IMGUI_TOOLS_SAVE_FILE);
assert(f);
for (const auto & [e, tool] : em.getEntities<kengine::ImGuiToolComponent>())
f << tool.name << ';' << std::boolalpha << tool.enabled << std::noboolalpha << '\n';
f.flush();
}
static auto ToolsController(kengine::EntityManager & em) {
return [&](kengine::Entity & e) {
e += kengine::ImGuiComponent([&] {
if (ImGui::BeginMainMenuBar()) {
bool mustSave = false;
if (ImGui::BeginMenu("Tools")) {
if (ImGui::MenuItem("Disable all"))
for (auto & [e, tool] : em.getEntities<kengine::ImGuiToolComponent>())
tool.enabled = false;
for (auto & [e, tool] : em.getEntities<kengine::ImGuiToolComponent>())
if (ImGui::MenuItem(tool.name)) {
tool.enabled = !tool.enabled;
mustSave = true;
}
ImGui::EndMenu();
}
if (mustSave)
saveTools(em);
}
ImGui::EndMainMenuBar();
});
};
}
namespace kengine {
ImGuiToolSystem::ImGuiToolSystem(EntityManager & em) : System(em), _em(em) {
onLoad("");
g_confFile.parse();
}
void ImGuiToolSystem::onLoad(const char *) noexcept {
_em += ToolsController(_em);
}
void ImGuiToolSystem::handle(packets::RegisterEntity p) noexcept {
if (!p.e.has<ImGuiToolComponent>())
return;
auto & tool = p.e.get<ImGuiToolComponent>();
tool.enabled = g_confFile.getValue(tool.name);
}
}<|endoftext|>
|
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd.hpp"
#include "flusspferd/spidermonkey/init.hpp"
#include "flusspferd/spidermonkey/object.hpp"
#include <boost/spirit/home/phoenix/core.hpp>
#include <boost/spirit/home/phoenix/bind.hpp>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <cctype>
#include <string>
#include <list>
#ifdef HAVE_EDITLINE
#include <editline/readline.h>
#ifdef HAVE_EDITLINE_HISTORY_H
#include <editline/history.h>
#endif
#elif HAVE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#define HAVE_EDITLINE
#endif
#ifndef HISTORY_FILE_DEFAULT
#define HISTORY_FILE_DEFAULT "~/.flusspferd-history"
#endif
namespace phoenix = boost::phoenix;
namespace args = phoenix::arg_names;
class flusspferd_repl {
bool interactive;
bool machine_mode;
std::istream in;
bool config_loaded;
char const *config_file;
flusspferd::context co;
flusspferd::current_context_scope scope;
bool running;
int exit_code;
std::string history_file;
int argc;
char ** argv;
enum Type { File, Expression, IncludePath, Module };
// Returns list of files / expressions to execute
std::list<std::pair<std::string, Type> > parse_cmdline();
void load_config();
bool getline(std::string &source, const char* prompt = "> ");
void quit(int code) {
running = false;
exit_code = code;
throw flusspferd::js_quit();
}
public:
flusspferd_repl(int argc, char** argv);
int run();
};
flusspferd_repl::flusspferd_repl(int argc, char **argv)
: interactive(true),
machine_mode(false),
//file("typein"),
in(std::cin.rdbuf()),
config_loaded(false),
// Default - can be changed by -c cmd line option
config_file(INSTALL_PREFIX "/etc/flusspferd/jsrepl.js"),
co(flusspferd::context::create()),
scope(flusspferd::current_context_scope(co)),
running(false),
exit_code(0),
history_file(HISTORY_FILE_DEFAULT),
argc(argc),
argv(argv)
{
flusspferd::object g = flusspferd::global();
// g.prototype() is available everywhere
flusspferd::security::create(g.prototype());
flusspferd::load_core(g.prototype());
flusspferd::create_native_function<void (int)>(
g, "quit",
phoenix::bind(&flusspferd_repl::quit, this, args::arg1));
flusspferd::create_native_function(g, "gc", &flusspferd::gc);
flusspferd::gc();
}
int flusspferd_repl::run() {
std::list<std::pair<std::string, Type> > files = parse_cmdline();
if (!config_loaded)
load_config();
flusspferd::object require_obj =
flusspferd::global()
.prototype()
.get_property_object("require");
typedef std::list<std::pair<std::string, Type> >::const_iterator iter;
for (iter i = files.begin(), e = files.end(); i != e; ++i) {
switch (i->second) {
case File:
flusspferd::execute(i->first.c_str());
break;
case Expression:
flusspferd::evaluate(i->first, "[command line]", 0);
break;
case IncludePath:
require_obj.get_property_object("paths").call("unshift", i->first);
break;
case Module:
require_obj.call(flusspferd::global(), i->first);
break;
}
}
if (!interactive)
return exit_code;
#ifdef HAVE_EDITLINE
if (!machine_mode && !history_file.empty()) {
if(history_file.size() > 1 && history_file[0] == '~') {
char const *const HOME = std::getenv("HOME");
if (HOME && *HOME) {
history_file = std::string(HOME) + history_file.substr(1);
}
else {
throw std::runtime_error("Couldn't open history file `" + history_file
+ "' because $HOME is not set");
}
}
read_history(history_file.c_str());
}
#endif
std::string source;
unsigned int line = 0;
running = true;
while (running && getline(source)) {
unsigned int startline = ++line;
for (;;) {
JSBool compilable =
JS_BufferIsCompilableUnit(
flusspferd::Impl::current_context(),
flusspferd::Impl::get_object(flusspferd::global()),
source.data(),
source.size());
if (compilable)
break;
std::string appendix;
getline(appendix, "? ");
source += appendix;
++line;
}
try {
flusspferd::value v = flusspferd::evaluate(source, "[typein]", startline);
if (!v.is_undefined())
std::cout << v << '\n';
}
catch(std::exception &e) {
std::cerr << "ERROR: " << e.what() << '\n';
}
flusspferd::gc();
}
#ifdef HAVE_EDITLINE
if (!machine_mode && !history_file.empty())
write_history(history_file.c_str());
#endif
return exit_code;
}
void print_help(char const *argv0) {
std::cerr << "usage: " << argv0 <<
" [option] ... [file | -] [arg] ...\n\n"
"Options\n"
" -h Displays this message.\n"
"\n"
" -v\n"
" --version Print version and exit.\n"
"\n"
" -c <file>\n"
" --config <file> Load config from file.\n"
"\n"
" -i\n"
" --interactive Enter interactive mode (after files).\n"
"\n"
" -0 (Interactive) machine command mode (separator\n"
" '\\0').\n"
"\n"
" -e <expr>\n"
" --expression <expr> Evaluate the expression.\n"
"\n"
" -f <file>\n"
" --file <file> Run this file before standard script handling.\n"
"\n"
" -I <path>\n Add include path."
"\n"
" -M <module>\n Load module."
"\n"
" --no-global-history\n Do not use a global history in interactive mode\n"
"\n"
" --history-file <file>\n Sets history file (default: ~/.flusspferd-history)\n"
"\n"
" -- Stop processing options.\n\n";
}
void print_version() {
std::cout << "flusspferd shell version: " << FLUSSPFERD_VERSION << '\n';
std::cout << "flusspferd library version: " << flusspferd::version() << '\n';
std::cout.flush();
}
void flusspferd_repl::load_config() {
flusspferd::execute(config_file);
config_loaded = true;
// Get the prelude and execute it too
flusspferd::value prelude = co.global().get_property("prelude");
if (!prelude.is_undefined_or_null()) {
flusspferd::execute(prelude.to_string().c_str(), flusspferd::global().prototype());
}
}
std::list<std::pair<std::string, flusspferd_repl::Type> >
flusspferd_repl::parse_cmdline() {
bool interactive_set = false;
std::list<std::pair<std::string, Type> > files;
int i=1;
for (i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
if (std::strcmp(argv[i], "--") == 0)
{
i++;
break;
}
else if (std::strcmp(argv[i], "-h") == 0 ||
std::strcmp(argv[i], "--help") == 0)
{
print_help(argv[0]);
throw flusspferd::js_quit();
}
else if (std::strcmp(argv[i], "-v") == 0 ||
std::strcmp(argv[i], "--version") == 0)
{
print_version();
throw flusspferd::js_quit();
}
else if (std::strcmp(argv[i], "-c") == 0 ||
std::strcmp(argv[i], "--config") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected filename after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
config_file = argv[i];
}
else if (std::strcmp(argv[i], "-i") == 0 ||
std::strcmp(argv[i], "--interactive") == 0)
{
interactive = true;
interactive_set = true;
}
else if (std::strcmp(argv[i], "-0") == 0)
{
interactive = true;
interactive_set = true;
machine_mode = true;
}
else if (std::strcmp(argv[i], "-f") == 0 ||
std::strcmp(argv[i], "--file") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected filename after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
std::string file = argv[i];
if (!interactive_set)
interactive = false;
files.push_back(std::make_pair(file, File));
}
else if (std::strcmp(argv[i], "-e") == 0 ||
std::strcmp(argv[i], "--expression") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected expression after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
std::string file = argv[i];
if (!interactive_set)
interactive = false;
files.push_back(std::make_pair(file, Expression));
}
else if (std::strcmp(argv[i], "-I") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected expression after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
std::string path = argv[i];
files.push_back(std::make_pair(path, IncludePath));
}
else if (std::strcmp(argv[i], "-M") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected expression after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
std::string path = argv[i];
files.push_back(std::make_pair(path, Module));
}
else if (std::strcmp(argv[i], "--no-global-history") == 0)
{
history_file.clear();
}
else if (std::strcmp(argv[i], "--history-file") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected expression after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
history_file = argv[i];
}
else
{
print_help(argv[0]);
throw std::runtime_error(std::string("invalid option: ")+argv[i]+"\n");
}
}
else
break; // Not an option, stop looking for one
}
if (!config_loaded)
load_config();
flusspferd::array args =
flusspferd::global()
.call("require", "system").to_object()
.get_property_object("args");
args.set_element(0, flusspferd::value("-"));
if (i < argc) {
// some cmd line args left.
// first one is file
// others go into arguments array
std::string file = argv[i++];
if (file != "-") { // TODO: Maybe check if stdin is actualy connected to a terminal?
files.push_back(std::make_pair(file, File));
if (!interactive_set)
interactive = false;
}
args.set_element(0, flusspferd::value(file));
int x = 1;
for (; i < argc; ++i) {
args.set_element(
x++,
flusspferd::value(const_cast<char const*>(argv[i])));
}
}
return files;
}
namespace {
bool all_whitespace_p(char const *in) {
assert(in);
while(*in) {
if(!std::isspace(*in)) {
return false;
}
++in;
}
return true;
}
}
bool flusspferd_repl::getline(std::string &source, const char* prompt) {
if (machine_mode) {
return std::getline(in, source, '\0');
}
else
#ifdef HAVE_EDITLINE
if (interactive) {
char* linep = readline(prompt);
if (!linep) {
std::cout << std::endl;
return false;
}
if (linep[0] != '\0' && !all_whitespace_p(linep))
add_history(linep);
source = linep;
source += '\n';
std::free(linep);
return true;
}
else
#endif
{
std::cout << prompt;
return std::getline(in, source);
}
}
int main(int argc, char **argv) {
try {
flusspferd::init::initialize();
flusspferd_repl repl(argc, argv);
return repl.run();
} catch (flusspferd::js_quit&) {
} catch (std::exception &e) {
std::cerr << "ERROR: " << e.what() << '\n';
return 1;
}
}
<commit_msg>repl: removed editline/history.h since we do not test for it in configure anyway<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd.hpp"
#include "flusspferd/spidermonkey/init.hpp"
#include "flusspferd/spidermonkey/object.hpp"
#include <boost/spirit/home/phoenix/core.hpp>
#include <boost/spirit/home/phoenix/bind.hpp>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <cctype>
#include <string>
#include <list>
#ifdef HAVE_EDITLINE
#include <editline/readline.h>
#elif HAVE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#define HAVE_EDITLINE
#endif
#ifndef HISTORY_FILE_DEFAULT
#define HISTORY_FILE_DEFAULT "~/.flusspferd-history"
#endif
namespace phoenix = boost::phoenix;
namespace args = phoenix::arg_names;
class flusspferd_repl {
bool interactive;
bool machine_mode;
std::istream in;
bool config_loaded;
char const *config_file;
flusspferd::context co;
flusspferd::current_context_scope scope;
bool running;
int exit_code;
std::string history_file;
int argc;
char ** argv;
enum Type { File, Expression, IncludePath, Module };
// Returns list of files / expressions to execute
std::list<std::pair<std::string, Type> > parse_cmdline();
void load_config();
bool getline(std::string &source, const char* prompt = "> ");
void quit(int code) {
running = false;
exit_code = code;
throw flusspferd::js_quit();
}
public:
flusspferd_repl(int argc, char** argv);
int run();
};
flusspferd_repl::flusspferd_repl(int argc, char **argv)
: interactive(true),
machine_mode(false),
//file("typein"),
in(std::cin.rdbuf()),
config_loaded(false),
// Default - can be changed by -c cmd line option
config_file(INSTALL_PREFIX "/etc/flusspferd/jsrepl.js"),
co(flusspferd::context::create()),
scope(flusspferd::current_context_scope(co)),
running(false),
exit_code(0),
history_file(HISTORY_FILE_DEFAULT),
argc(argc),
argv(argv)
{
flusspferd::object g = flusspferd::global();
// g.prototype() is available everywhere
flusspferd::security::create(g.prototype());
flusspferd::load_core(g.prototype());
flusspferd::create_native_function<void (int)>(
g, "quit",
phoenix::bind(&flusspferd_repl::quit, this, args::arg1));
flusspferd::create_native_function(g, "gc", &flusspferd::gc);
flusspferd::gc();
}
int flusspferd_repl::run() {
std::list<std::pair<std::string, Type> > files = parse_cmdline();
if (!config_loaded)
load_config();
flusspferd::object require_obj =
flusspferd::global()
.prototype()
.get_property_object("require");
typedef std::list<std::pair<std::string, Type> >::const_iterator iter;
for (iter i = files.begin(), e = files.end(); i != e; ++i) {
switch (i->second) {
case File:
flusspferd::execute(i->first.c_str());
break;
case Expression:
flusspferd::evaluate(i->first, "[command line]", 0);
break;
case IncludePath:
require_obj.get_property_object("paths").call("unshift", i->first);
break;
case Module:
require_obj.call(flusspferd::global(), i->first);
break;
}
}
if (!interactive)
return exit_code;
#ifdef HAVE_EDITLINE
if (!machine_mode && !history_file.empty()) {
if(history_file.size() > 1 && history_file[0] == '~') {
char const *const HOME = std::getenv("HOME");
if (HOME && *HOME) {
history_file = std::string(HOME) + history_file.substr(1);
}
else {
throw std::runtime_error("Couldn't open history file `" + history_file
+ "' because $HOME is not set");
}
}
read_history(history_file.c_str());
}
#endif
std::string source;
unsigned int line = 0;
running = true;
while (running && getline(source)) {
unsigned int startline = ++line;
for (;;) {
JSBool compilable =
JS_BufferIsCompilableUnit(
flusspferd::Impl::current_context(),
flusspferd::Impl::get_object(flusspferd::global()),
source.data(),
source.size());
if (compilable)
break;
std::string appendix;
getline(appendix, "? ");
source += appendix;
++line;
}
try {
flusspferd::value v = flusspferd::evaluate(source, "[typein]", startline);
if (!v.is_undefined())
std::cout << v << '\n';
}
catch(std::exception &e) {
std::cerr << "ERROR: " << e.what() << '\n';
}
flusspferd::gc();
}
#ifdef HAVE_EDITLINE
if (!machine_mode && !history_file.empty())
write_history(history_file.c_str());
#endif
return exit_code;
}
void print_help(char const *argv0) {
std::cerr << "usage: " << argv0 <<
" [option] ... [file | -] [arg] ...\n\n"
"Options\n"
" -h Displays this message.\n"
"\n"
" -v\n"
" --version Print version and exit.\n"
"\n"
" -c <file>\n"
" --config <file> Load config from file.\n"
"\n"
" -i\n"
" --interactive Enter interactive mode (after files).\n"
"\n"
" -0 (Interactive) machine command mode (separator\n"
" '\\0').\n"
"\n"
" -e <expr>\n"
" --expression <expr> Evaluate the expression.\n"
"\n"
" -f <file>\n"
" --file <file> Run this file before standard script handling.\n"
"\n"
" -I <path>\n Add include path."
"\n"
" -M <module>\n Load module."
"\n"
" --no-global-history\n Do not use a global history in interactive mode\n"
"\n"
" --history-file <file>\n Sets history file (default: ~/.flusspferd-history)\n"
"\n"
" -- Stop processing options.\n\n";
}
void print_version() {
std::cout << "flusspferd shell version: " << FLUSSPFERD_VERSION << '\n';
std::cout << "flusspferd library version: " << flusspferd::version() << '\n';
std::cout.flush();
}
void flusspferd_repl::load_config() {
flusspferd::execute(config_file);
config_loaded = true;
// Get the prelude and execute it too
flusspferd::value prelude = co.global().get_property("prelude");
if (!prelude.is_undefined_or_null()) {
flusspferd::execute(prelude.to_string().c_str(), flusspferd::global().prototype());
}
}
std::list<std::pair<std::string, flusspferd_repl::Type> >
flusspferd_repl::parse_cmdline() {
bool interactive_set = false;
std::list<std::pair<std::string, Type> > files;
int i=1;
for (i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
if (std::strcmp(argv[i], "--") == 0)
{
i++;
break;
}
else if (std::strcmp(argv[i], "-h") == 0 ||
std::strcmp(argv[i], "--help") == 0)
{
print_help(argv[0]);
throw flusspferd::js_quit();
}
else if (std::strcmp(argv[i], "-v") == 0 ||
std::strcmp(argv[i], "--version") == 0)
{
print_version();
throw flusspferd::js_quit();
}
else if (std::strcmp(argv[i], "-c") == 0 ||
std::strcmp(argv[i], "--config") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected filename after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
config_file = argv[i];
}
else if (std::strcmp(argv[i], "-i") == 0 ||
std::strcmp(argv[i], "--interactive") == 0)
{
interactive = true;
interactive_set = true;
}
else if (std::strcmp(argv[i], "-0") == 0)
{
interactive = true;
interactive_set = true;
machine_mode = true;
}
else if (std::strcmp(argv[i], "-f") == 0 ||
std::strcmp(argv[i], "--file") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected filename after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
std::string file = argv[i];
if (!interactive_set)
interactive = false;
files.push_back(std::make_pair(file, File));
}
else if (std::strcmp(argv[i], "-e") == 0 ||
std::strcmp(argv[i], "--expression") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected expression after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
std::string file = argv[i];
if (!interactive_set)
interactive = false;
files.push_back(std::make_pair(file, Expression));
}
else if (std::strcmp(argv[i], "-I") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected expression after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
std::string path = argv[i];
files.push_back(std::make_pair(path, IncludePath));
}
else if (std::strcmp(argv[i], "-M") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected expression after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
std::string path = argv[i];
files.push_back(std::make_pair(path, Module));
}
else if (std::strcmp(argv[i], "--no-global-history") == 0)
{
history_file.clear();
}
else if (std::strcmp(argv[i], "--history-file") == 0)
{
++i;
if (i == argc) {
print_help(argv[0]);
std::string msg = "expected expression after ";
msg += argv[i-1];
msg += " option\n";
throw std::runtime_error(msg);
}
history_file = argv[i];
}
else
{
print_help(argv[0]);
throw std::runtime_error(std::string("invalid option: ")+argv[i]+"\n");
}
}
else
break; // Not an option, stop looking for one
}
if (!config_loaded)
load_config();
flusspferd::array args =
flusspferd::global()
.call("require", "system").to_object()
.get_property_object("args");
args.set_element(0, flusspferd::value("-"));
if (i < argc) {
// some cmd line args left.
// first one is file
// others go into arguments array
std::string file = argv[i++];
if (file != "-") { // TODO: Maybe check if stdin is actualy connected to a terminal?
files.push_back(std::make_pair(file, File));
if (!interactive_set)
interactive = false;
}
args.set_element(0, flusspferd::value(file));
int x = 1;
for (; i < argc; ++i) {
args.set_element(
x++,
flusspferd::value(const_cast<char const*>(argv[i])));
}
}
return files;
}
namespace {
bool all_whitespace_p(char const *in) {
assert(in);
while(*in) {
if(!std::isspace(*in)) {
return false;
}
++in;
}
return true;
}
}
bool flusspferd_repl::getline(std::string &source, const char* prompt) {
if (machine_mode) {
return std::getline(in, source, '\0');
}
else
#ifdef HAVE_EDITLINE
if (interactive) {
char* linep = readline(prompt);
if (!linep) {
std::cout << std::endl;
return false;
}
if (linep[0] != '\0' && !all_whitespace_p(linep))
add_history(linep);
source = linep;
source += '\n';
std::free(linep);
return true;
}
else
#endif
{
std::cout << prompt;
return std::getline(in, source);
}
}
int main(int argc, char **argv) {
try {
flusspferd::init::initialize();
flusspferd_repl repl(argc, argv);
return repl.run();
} catch (flusspferd::js_quit&) {
} catch (std::exception &e) {
std::cerr << "ERROR: " << e.what() << '\n';
return 1;
}
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Copyright (c) 2013, Art Clarke. All rights reserved.
*
* This file is part of Humble-Video.
*
* Humble-Video 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.
*
* Humble-Video 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 Humble-Video. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
/*
* MediaSubtitle.cpp
*
* Created on: Jul 23, 2013
* Author: aclarke
*/
#include "MediaSubtitle.h"
#include <io/humble/ferry/RefPointer.h>
using namespace io::humble::ferry;
namespace io {
namespace humble {
namespace video {
MediaSubtitle::MediaSubtitle() : mCtx(0) {
}
MediaSubtitle::~MediaSubtitle() {
}
MediaSubtitle*
MediaSubtitle::make(AVSubtitle* ctx)
{
if (!ctx)
throw HumbleInvalidArgument("no context");
RefPointer<MediaSubtitle> retval = MediaSubtitle::make();
retval->mCtx = ctx;
return retval.get();
}
MediaSubtitleRectangle*
MediaSubtitle::getRectangle(int32_t n)
{
if (n < 0 || n >= (int32_t)mCtx->num_rects)
throw HumbleInvalidArgument("attempt to get out-of-range rectangle");
if (!mCtx->rects)
throw HumbleRuntimeError("no rectangles");
return MediaSubtitleRectangle::make(mCtx->rects[n]);
}
MediaSubtitleRectangle*
MediaSubtitleRectangle::make(AVSubtitleRect* ctx) {
if (!ctx)
throw HumbleInvalidArgument("no context");
RefPointer<MediaSubtitleRectangle> retval = make();
retval->mCtx = ctx;
return retval.get();
}
int32_t
MediaSubtitleRectangle::getPictureLinesize(int line) {
if (line < 0 || line >= 4)
throw HumbleInvalidArgument("line must be between 0 and 3");
return mCtx->pict.linesize[line];
}
IBuffer*
MediaSubtitleRectangle::getPictureData(int line)
{
if (line < 0 || line >= 4)
throw HumbleInvalidArgument("line must be between 0 and 3");
// add ref ourselves for the IBuffer
this->acquire();
// create a buffer
RefPointer<IBuffer> retval = IBuffer::make(this, mCtx->pict.data[line], mCtx->pict.linesize[line],
IBuffer::refCountedFreeFunc, this);
if (!retval)
this->release();
return retval.get();
}
} /* namespace video */
} /* namespace humble */
} /* namespace io */
<commit_msg>remove warning<commit_after>/*******************************************************************************
* Copyright (c) 2013, Art Clarke. All rights reserved.
*
* This file is part of Humble-Video.
*
* Humble-Video 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.
*
* Humble-Video 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 Humble-Video. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
/*
* MediaSubtitle.cpp
*
* Created on: Jul 23, 2013
* Author: aclarke
*/
#include "MediaSubtitle.h"
#include <io/humble/ferry/RefPointer.h>
using namespace io::humble::ferry;
namespace io {
namespace humble {
namespace video {
MediaSubtitle::MediaSubtitle() : mCtx(0), mComplete(false){
}
MediaSubtitle::~MediaSubtitle() {
}
MediaSubtitle*
MediaSubtitle::make(AVSubtitle* ctx)
{
if (!ctx)
throw HumbleInvalidArgument("no context");
RefPointer<MediaSubtitle> retval = MediaSubtitle::make();
retval->mCtx = ctx;
return retval.get();
}
MediaSubtitleRectangle*
MediaSubtitle::getRectangle(int32_t n)
{
if (n < 0 || n >= (int32_t)mCtx->num_rects)
throw HumbleInvalidArgument("attempt to get out-of-range rectangle");
if (!mCtx->rects)
throw HumbleRuntimeError("no rectangles");
return MediaSubtitleRectangle::make(mCtx->rects[n]);
}
MediaSubtitleRectangle*
MediaSubtitleRectangle::make(AVSubtitleRect* ctx) {
if (!ctx)
throw HumbleInvalidArgument("no context");
RefPointer<MediaSubtitleRectangle> retval = make();
retval->mCtx = ctx;
return retval.get();
}
int32_t
MediaSubtitleRectangle::getPictureLinesize(int line) {
if (line < 0 || line >= 4)
throw HumbleInvalidArgument("line must be between 0 and 3");
return mCtx->pict.linesize[line];
}
IBuffer*
MediaSubtitleRectangle::getPictureData(int line)
{
if (line < 0 || line >= 4)
throw HumbleInvalidArgument("line must be between 0 and 3");
// add ref ourselves for the IBuffer
this->acquire();
// create a buffer
RefPointer<IBuffer> retval = IBuffer::make(this, mCtx->pict.data[line], mCtx->pict.linesize[line],
IBuffer::refCountedFreeFunc, this);
if (!retval)
this->release();
return retval.get();
}
} /* namespace video */
} /* namespace humble */
} /* namespace io */
<|endoftext|>
|
<commit_before>/**
* @file lloutputmonitorctrl.cpp
* @brief LLOutputMonitorCtrl base class
*
* $LicenseInfo:firstyear=2001&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "lloutputmonitorctrl.h"
// library includes
#include "llfloaterreg.h"
#include "llui.h"
// viewer includes
#include "llvoiceclient.h"
#include "llmutelist.h"
#include "llagent.h"
// default options set in output_monitor.xml
static LLDefaultChildRegistry::Register<LLOutputMonitorCtrl> r("output_monitor");
// The defaults will be initialized in the constructor.
//LLColor4 LLOutputMonitorCtrl::sColorMuted;
//LLColor4 LLOutputMonitorCtrl::sColorOverdriven;
//LLColor4 LLOutputMonitorCtrl::sColorNormal;
LLColor4 LLOutputMonitorCtrl::sColorBound;
//S32 LLOutputMonitorCtrl::sRectsNumber = 0;
//F32 LLOutputMonitorCtrl::sRectWidthRatio = 0.f;
//F32 LLOutputMonitorCtrl::sRectHeightRatio = 0.f;
LLOutputMonitorCtrl::Params::Params()
: draw_border("draw_border"),
image_mute("image_mute"),
image_off("image_off"),
image_on("image_on"),
image_level_1("image_level_1"),
image_level_2("image_level_2"),
image_level_3("image_level_3"),
auto_update("auto_update"),
speaker_id("speaker_id")
{
};
LLOutputMonitorCtrl::LLOutputMonitorCtrl(const LLOutputMonitorCtrl::Params& p)
: LLView(p),
mPower(0),
mImageMute(p.image_mute),
mImageOff(p.image_off),
mImageOn(p.image_on),
mImageLevel1(p.image_level_1),
mImageLevel2(p.image_level_2),
mImageLevel3(p.image_level_3),
mAutoUpdate(p.auto_update),
mSpeakerId(p.speaker_id),
mIsAgentControl(false),
mIsSwitchDirty(false),
mShouldSwitchOn(false),
mShowParticipantsTalking(false)
{
//static LLUIColor output_monitor_muted_color = LLUIColorTable::instance().getColor("OutputMonitorMutedColor", LLColor4::orange);
//static LLUIColor output_monitor_overdriven_color = LLUIColorTable::instance().getColor("OutputMonitorOverdrivenColor", LLColor4::red);
//static LLUIColor output_monitor_normal_color = LLUIColorTable::instance().getColor("OutputMonitorNotmalColor", LLColor4::green);
static LLUIColor output_monitor_bound_color = LLUIColorTable::instance().getColor("OutputMonitorBoundColor", LLColor4::white);
//static LLUICachedControl<S32> output_monitor_rects_number("OutputMonitorRectanglesNumber", 20);
//static LLUICachedControl<F32> output_monitor_rect_width_ratio("OutputMonitorRectangleWidthRatio", 0.5f);
//static LLUICachedControl<F32> output_monitor_rect_height_ratio("OutputMonitorRectangleHeightRatio", 0.8f);
// IAN BUG compare to existing pattern where these are members - some will change per-widget and need to be anyway
// sent feedback to PE
// *TODO: it looks suboptimal to load the defaults every time an output monitor is constructed.
//sColorMuted = output_monitor_muted_color;
//sColorOverdriven = output_monitor_overdriven_color;
//sColorNormal = output_monitor_normal_color;
sColorBound = output_monitor_bound_color;
//sRectsNumber = output_monitor_rects_number;
//sRectWidthRatio = output_monitor_rect_width_ratio;
//sRectHeightRatio = output_monitor_rect_height_ratio;
mBorder = p.draw_border;
//with checking mute state
setSpeakerId(mSpeakerId);
}
LLOutputMonitorCtrl::~LLOutputMonitorCtrl()
{
LLMuteList::getInstance()->removeObserver(this);
LLSpeakingIndicatorManager::unregisterSpeakingIndicator(mSpeakerId, this);
}
void LLOutputMonitorCtrl::setPower(F32 val)
{
mPower = llmax(0.f, llmin(1.f, val));
}
void LLOutputMonitorCtrl::draw()
{
// see also switchIndicator()
if (mIsSwitchDirty)
{
mIsSwitchDirty = false;
if (mShouldSwitchOn)
{
// just notify parent visibility may have changed
notifyParentVisibilityChanged();
}
else
{
// make itself invisible and notify parent about this
setVisible(FALSE);
notifyParentVisibilityChanged();
// no needs to render for invisible element
return;
}
}
// Copied from llmediaremotectrl.cpp
// *TODO: Give the LLOutputMonitorCtrl an agent-id to monitor, then
// call directly into LLVoiceClient::getInstance() to ask if that agent-id is muted, is
// speaking, and what power. This avoids duplicating data, which can get
// out of sync.
const F32 LEVEL_0 = LLVoiceClient::OVERDRIVEN_POWER_LEVEL / 3.f;
const F32 LEVEL_1 = LLVoiceClient::OVERDRIVEN_POWER_LEVEL * 2.f / 3.f;
const F32 LEVEL_2 = LLVoiceClient::OVERDRIVEN_POWER_LEVEL;
if (getVisible() && mAutoUpdate && !mIsMuted && mSpeakerId.notNull())
{
setPower(LLVoiceClient::getInstance()->getCurrentPower(mSpeakerId));
if(mIsAgentControl)
{
setIsTalking(LLVoiceClient::getInstance()->getUserPTTState());
}
else
{
setIsTalking(LLVoiceClient::getInstance()->getIsSpeaking(mSpeakerId));
}
}
if ((mPower == 0.f && !mIsTalking) && mShowParticipantsTalking)
{
std::set<LLUUID> participant_uuids;
LLVoiceClient::instance().getParticipantList(participant_uuids);
std::set<LLUUID>::const_iterator part_it = participant_uuids.begin();
F32 power = 0;
for (; part_it != participant_uuids.end(); ++part_it)
{
if (power = LLVoiceClient::instance().getCurrentPower(*part_it))
{
mPower = power;
break;
}
}
}
LLPointer<LLUIImage> icon;
if (mIsMuted)
{
icon = mImageMute;
}
else if (mPower == 0.f && !mIsTalking)
{
// only show off if PTT is not engaged
icon = mImageOff;
}
else if (mPower < LEVEL_0)
{
// PTT is on, possibly with quiet background noise
icon = mImageOn;
}
else if (mPower < LEVEL_1)
{
icon = mImageLevel1;
}
else if (mPower < LEVEL_2)
{
icon = mImageLevel2;
}
else
{
// overdriven
icon = mImageLevel3;
}
if (icon)
{
icon->draw(0, 0);
}
//
// Fill the monitor with a bunch of small rectangles.
// The rectangles will be filled with gradient color,
// beginning with sColorNormal and ending with sColorOverdriven.
//
// *TODO: would using a (partially drawn) pixmap instead be faster?
//
const int monh = getRect().getHeight();
const int monw = getRect().getWidth();
//int maxrects = sRectsNumber;
//const int period = llmax(1, monw / maxrects, 0, 0); // "1" - min value for the period
//const int rectw = llmax(1, llfloor(period * sRectWidthRatio), 0, 0); // "1" - min value for the rect's width
//const int recth = llfloor(monh * sRectHeightRatio);
//if(period == 1 && rectw == 1) //if we have so small control, then "maxrects = monitor's_width - 2*monitor_border's_width
// maxrects = monw-2;
//const int nrects = mIsMuted ? maxrects : llfloor(mPower * maxrects); // how many rects to draw?
//const int rectbtm = (monh - recth) / 2;
//const int recttop = rectbtm + recth;
//
//LLColor4 rect_color;
//
//for (int i=1, xpos = 0; i <= nrects; i++)
//{
// // Calculate color to use for the current rectangle.
// if (mIsMuted)
// {
// rect_color = sColorMuted;
// }
// else
// {
// F32 frac = (mPower * i/nrects) / LLVoiceClient::OVERDRIVEN_POWER_LEVEL;
// // Use overdriven color if the power exceeds overdriven level.
// if (frac > 1.0f)
// frac = 1.0f;
// rect_color = lerp(sColorNormal, sColorOverdriven, frac);
// }
// // Draw rectangle filled with the color.
// gl_rect_2d(xpos, recttop, xpos+rectw, rectbtm, rect_color, TRUE);
// xpos += period;
//}
//
// Draw bounding box.
//
if(mBorder)
gl_rect_2d(0, monh, monw, 0, sColorBound, FALSE);
}
// virtual
BOOL LLOutputMonitorCtrl::handleMouseUp(S32 x, S32 y, MASK mask)
{
if (mSpeakerId != gAgentID)
{
LLFloaterReg::showInstance("floater_voice_volume", LLSD().with("avatar_id", mSpeakerId));
}
return TRUE;
}
void LLOutputMonitorCtrl::setSpeakerId(const LLUUID& speaker_id, const LLUUID& session_id/* = LLUUID::null*/)
{
if (speaker_id.isNull() && mSpeakerId.notNull())
{
LLSpeakingIndicatorManager::unregisterSpeakingIndicator(mSpeakerId, this);
}
if (speaker_id.isNull() || speaker_id == mSpeakerId) return;
if (mSpeakerId.notNull())
{
// Unregister previous registration to avoid crash. EXT-4782.
LLSpeakingIndicatorManager::unregisterSpeakingIndicator(mSpeakerId, this);
}
mSpeakerId = speaker_id;
LLSpeakingIndicatorManager::registerSpeakingIndicator(mSpeakerId, this, session_id);
//mute management
if (mAutoUpdate)
{
if (speaker_id == gAgentID)
{
setIsMuted(false);
}
else
{
// check only blocking on voice. EXT-3542
setIsMuted(LLMuteList::getInstance()->isMuted(mSpeakerId, LLMute::flagVoiceChat));
LLMuteList::getInstance()->addObserver(this);
}
}
}
void LLOutputMonitorCtrl::onChange()
{
// check only blocking on voice. EXT-3542
setIsMuted(LLMuteList::getInstance()->isMuted(mSpeakerId, LLMute::flagVoiceChat));
}
// virtual
void LLOutputMonitorCtrl::switchIndicator(bool switch_on)
{
// ensure indicator is visible in case it is not in visible chain
// to be called when parent became visible next time to notify parent that visibility is changed.
setVisible(TRUE);
// if parent is in visible chain apply switch_on state and notify it immediately
if (getParent() && getParent()->isInVisibleChain())
{
LL_DEBUGS("SpeakingIndicator") << "Indicator is in visible chain, notifying parent: " << mSpeakerId << LL_ENDL;
setVisible((BOOL)switch_on);
notifyParentVisibilityChanged();
}
// otherwise remember necessary state and mark itself as dirty.
// State will be applied in next draw when parents chain becomes visible.
else
{
LL_DEBUGS("SpeakingIndicator") << "Indicator is not in visible chain, parent won't be notified: " << mSpeakerId << LL_ENDL;
mIsSwitchDirty = true;
mShouldSwitchOn = switch_on;
}
}
//////////////////////////////////////////////////////////////////////////
// PRIVATE SECTION
//////////////////////////////////////////////////////////////////////////
void LLOutputMonitorCtrl::notifyParentVisibilityChanged()
{
LL_DEBUGS("SpeakingIndicator") << "Notify parent that visibility was changed: " << mSpeakerId << ", new_visibility: " << getVisible() << LL_ENDL;
LLSD params = LLSD().with("visibility_changed", getVisible());
notifyParent(params);
}
// EOF
<commit_msg>CHUI-344 : Fix Mac build issue introduced by previous fix attempt<commit_after>/**
* @file lloutputmonitorctrl.cpp
* @brief LLOutputMonitorCtrl base class
*
* $LicenseInfo:firstyear=2001&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "lloutputmonitorctrl.h"
// library includes
#include "llfloaterreg.h"
#include "llui.h"
// viewer includes
#include "llvoiceclient.h"
#include "llmutelist.h"
#include "llagent.h"
// default options set in output_monitor.xml
static LLDefaultChildRegistry::Register<LLOutputMonitorCtrl> r("output_monitor");
// The defaults will be initialized in the constructor.
//LLColor4 LLOutputMonitorCtrl::sColorMuted;
//LLColor4 LLOutputMonitorCtrl::sColorOverdriven;
//LLColor4 LLOutputMonitorCtrl::sColorNormal;
LLColor4 LLOutputMonitorCtrl::sColorBound;
//S32 LLOutputMonitorCtrl::sRectsNumber = 0;
//F32 LLOutputMonitorCtrl::sRectWidthRatio = 0.f;
//F32 LLOutputMonitorCtrl::sRectHeightRatio = 0.f;
LLOutputMonitorCtrl::Params::Params()
: draw_border("draw_border"),
image_mute("image_mute"),
image_off("image_off"),
image_on("image_on"),
image_level_1("image_level_1"),
image_level_2("image_level_2"),
image_level_3("image_level_3"),
auto_update("auto_update"),
speaker_id("speaker_id")
{
};
LLOutputMonitorCtrl::LLOutputMonitorCtrl(const LLOutputMonitorCtrl::Params& p)
: LLView(p),
mPower(0),
mImageMute(p.image_mute),
mImageOff(p.image_off),
mImageOn(p.image_on),
mImageLevel1(p.image_level_1),
mImageLevel2(p.image_level_2),
mImageLevel3(p.image_level_3),
mAutoUpdate(p.auto_update),
mSpeakerId(p.speaker_id),
mIsAgentControl(false),
mIsSwitchDirty(false),
mShouldSwitchOn(false),
mShowParticipantsTalking(false)
{
//static LLUIColor output_monitor_muted_color = LLUIColorTable::instance().getColor("OutputMonitorMutedColor", LLColor4::orange);
//static LLUIColor output_monitor_overdriven_color = LLUIColorTable::instance().getColor("OutputMonitorOverdrivenColor", LLColor4::red);
//static LLUIColor output_monitor_normal_color = LLUIColorTable::instance().getColor("OutputMonitorNotmalColor", LLColor4::green);
static LLUIColor output_monitor_bound_color = LLUIColorTable::instance().getColor("OutputMonitorBoundColor", LLColor4::white);
//static LLUICachedControl<S32> output_monitor_rects_number("OutputMonitorRectanglesNumber", 20);
//static LLUICachedControl<F32> output_monitor_rect_width_ratio("OutputMonitorRectangleWidthRatio", 0.5f);
//static LLUICachedControl<F32> output_monitor_rect_height_ratio("OutputMonitorRectangleHeightRatio", 0.8f);
// IAN BUG compare to existing pattern where these are members - some will change per-widget and need to be anyway
// sent feedback to PE
// *TODO: it looks suboptimal to load the defaults every time an output monitor is constructed.
//sColorMuted = output_monitor_muted_color;
//sColorOverdriven = output_monitor_overdriven_color;
//sColorNormal = output_monitor_normal_color;
sColorBound = output_monitor_bound_color;
//sRectsNumber = output_monitor_rects_number;
//sRectWidthRatio = output_monitor_rect_width_ratio;
//sRectHeightRatio = output_monitor_rect_height_ratio;
mBorder = p.draw_border;
//with checking mute state
setSpeakerId(mSpeakerId);
}
LLOutputMonitorCtrl::~LLOutputMonitorCtrl()
{
LLMuteList::getInstance()->removeObserver(this);
LLSpeakingIndicatorManager::unregisterSpeakingIndicator(mSpeakerId, this);
}
void LLOutputMonitorCtrl::setPower(F32 val)
{
mPower = llmax(0.f, llmin(1.f, val));
}
void LLOutputMonitorCtrl::draw()
{
// see also switchIndicator()
if (mIsSwitchDirty)
{
mIsSwitchDirty = false;
if (mShouldSwitchOn)
{
// just notify parent visibility may have changed
notifyParentVisibilityChanged();
}
else
{
// make itself invisible and notify parent about this
setVisible(FALSE);
notifyParentVisibilityChanged();
// no needs to render for invisible element
return;
}
}
// Copied from llmediaremotectrl.cpp
// *TODO: Give the LLOutputMonitorCtrl an agent-id to monitor, then
// call directly into LLVoiceClient::getInstance() to ask if that agent-id is muted, is
// speaking, and what power. This avoids duplicating data, which can get
// out of sync.
const F32 LEVEL_0 = LLVoiceClient::OVERDRIVEN_POWER_LEVEL / 3.f;
const F32 LEVEL_1 = LLVoiceClient::OVERDRIVEN_POWER_LEVEL * 2.f / 3.f;
const F32 LEVEL_2 = LLVoiceClient::OVERDRIVEN_POWER_LEVEL;
if (getVisible() && mAutoUpdate && !mIsMuted && mSpeakerId.notNull())
{
setPower(LLVoiceClient::getInstance()->getCurrentPower(mSpeakerId));
if(mIsAgentControl)
{
setIsTalking(LLVoiceClient::getInstance()->getUserPTTState());
}
else
{
setIsTalking(LLVoiceClient::getInstance()->getIsSpeaking(mSpeakerId));
}
}
if ((mPower == 0.f && !mIsTalking) && mShowParticipantsTalking)
{
std::set<LLUUID> participant_uuids;
LLVoiceClient::instance().getParticipantList(participant_uuids);
std::set<LLUUID>::const_iterator part_it = participant_uuids.begin();
F32 power = 0;
for (; part_it != participant_uuids.end(); ++part_it)
{
power = LLVoiceClient::instance().getCurrentPower(*part_it);
if (power)
{
mPower = power;
break;
}
}
}
LLPointer<LLUIImage> icon;
if (mIsMuted)
{
icon = mImageMute;
}
else if (mPower == 0.f && !mIsTalking)
{
// only show off if PTT is not engaged
icon = mImageOff;
}
else if (mPower < LEVEL_0)
{
// PTT is on, possibly with quiet background noise
icon = mImageOn;
}
else if (mPower < LEVEL_1)
{
icon = mImageLevel1;
}
else if (mPower < LEVEL_2)
{
icon = mImageLevel2;
}
else
{
// overdriven
icon = mImageLevel3;
}
if (icon)
{
icon->draw(0, 0);
}
//
// Fill the monitor with a bunch of small rectangles.
// The rectangles will be filled with gradient color,
// beginning with sColorNormal and ending with sColorOverdriven.
//
// *TODO: would using a (partially drawn) pixmap instead be faster?
//
const int monh = getRect().getHeight();
const int monw = getRect().getWidth();
//int maxrects = sRectsNumber;
//const int period = llmax(1, monw / maxrects, 0, 0); // "1" - min value for the period
//const int rectw = llmax(1, llfloor(period * sRectWidthRatio), 0, 0); // "1" - min value for the rect's width
//const int recth = llfloor(monh * sRectHeightRatio);
//if(period == 1 && rectw == 1) //if we have so small control, then "maxrects = monitor's_width - 2*monitor_border's_width
// maxrects = monw-2;
//const int nrects = mIsMuted ? maxrects : llfloor(mPower * maxrects); // how many rects to draw?
//const int rectbtm = (monh - recth) / 2;
//const int recttop = rectbtm + recth;
//
//LLColor4 rect_color;
//
//for (int i=1, xpos = 0; i <= nrects; i++)
//{
// // Calculate color to use for the current rectangle.
// if (mIsMuted)
// {
// rect_color = sColorMuted;
// }
// else
// {
// F32 frac = (mPower * i/nrects) / LLVoiceClient::OVERDRIVEN_POWER_LEVEL;
// // Use overdriven color if the power exceeds overdriven level.
// if (frac > 1.0f)
// frac = 1.0f;
// rect_color = lerp(sColorNormal, sColorOverdriven, frac);
// }
// // Draw rectangle filled with the color.
// gl_rect_2d(xpos, recttop, xpos+rectw, rectbtm, rect_color, TRUE);
// xpos += period;
//}
//
// Draw bounding box.
//
if(mBorder)
gl_rect_2d(0, monh, monw, 0, sColorBound, FALSE);
}
// virtual
BOOL LLOutputMonitorCtrl::handleMouseUp(S32 x, S32 y, MASK mask)
{
if (mSpeakerId != gAgentID)
{
LLFloaterReg::showInstance("floater_voice_volume", LLSD().with("avatar_id", mSpeakerId));
}
return TRUE;
}
void LLOutputMonitorCtrl::setSpeakerId(const LLUUID& speaker_id, const LLUUID& session_id/* = LLUUID::null*/)
{
if (speaker_id.isNull() && mSpeakerId.notNull())
{
LLSpeakingIndicatorManager::unregisterSpeakingIndicator(mSpeakerId, this);
}
if (speaker_id.isNull() || speaker_id == mSpeakerId) return;
if (mSpeakerId.notNull())
{
// Unregister previous registration to avoid crash. EXT-4782.
LLSpeakingIndicatorManager::unregisterSpeakingIndicator(mSpeakerId, this);
}
mSpeakerId = speaker_id;
LLSpeakingIndicatorManager::registerSpeakingIndicator(mSpeakerId, this, session_id);
//mute management
if (mAutoUpdate)
{
if (speaker_id == gAgentID)
{
setIsMuted(false);
}
else
{
// check only blocking on voice. EXT-3542
setIsMuted(LLMuteList::getInstance()->isMuted(mSpeakerId, LLMute::flagVoiceChat));
LLMuteList::getInstance()->addObserver(this);
}
}
}
void LLOutputMonitorCtrl::onChange()
{
// check only blocking on voice. EXT-3542
setIsMuted(LLMuteList::getInstance()->isMuted(mSpeakerId, LLMute::flagVoiceChat));
}
// virtual
void LLOutputMonitorCtrl::switchIndicator(bool switch_on)
{
// ensure indicator is visible in case it is not in visible chain
// to be called when parent became visible next time to notify parent that visibility is changed.
setVisible(TRUE);
// if parent is in visible chain apply switch_on state and notify it immediately
if (getParent() && getParent()->isInVisibleChain())
{
LL_DEBUGS("SpeakingIndicator") << "Indicator is in visible chain, notifying parent: " << mSpeakerId << LL_ENDL;
setVisible((BOOL)switch_on);
notifyParentVisibilityChanged();
}
// otherwise remember necessary state and mark itself as dirty.
// State will be applied in next draw when parents chain becomes visible.
else
{
LL_DEBUGS("SpeakingIndicator") << "Indicator is not in visible chain, parent won't be notified: " << mSpeakerId << LL_ENDL;
mIsSwitchDirty = true;
mShouldSwitchOn = switch_on;
}
}
//////////////////////////////////////////////////////////////////////////
// PRIVATE SECTION
//////////////////////////////////////////////////////////////////////////
void LLOutputMonitorCtrl::notifyParentVisibilityChanged()
{
LL_DEBUGS("SpeakingIndicator") << "Notify parent that visibility was changed: " << mSpeakerId << ", new_visibility: " << getVisible() << LL_ENDL;
LLSD params = LLSD().with("visibility_changed", getVisible());
notifyParent(params);
}
// EOF
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/fileapi/file_system_quota.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_number_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
using namespace fileapi;
class FileSystemQuotaTest : public testing::Test {
public:
FileSystemQuotaTest() { }
void SetUp() {
quota_.reset(new FileSystemQuota);
}
FileSystemQuota* quota() const { return quota_.get(); }
protected:
scoped_ptr<FileSystemQuota> quota_;
DISALLOW_COPY_AND_ASSIGN(FileSystemQuotaTest);
};
namespace {
static const char* const kTestOrigins[] = {
"https://a.com/",
"http://b.com/",
"http://c.com:1/",
"file:///",
};
} // anonymous namespace
TEST_F(FileSystemQuotaTest, CheckOriginQuotaNotAllowed) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message() << "CheckOriginQuotaNotAllowed #"
<< i << " " << kTestOrigins[i]);
// Should fail no matter how much size is requested.
EXPECT_FALSE(quota()->CheckOriginQuota(GURL(kTestOrigins[i]), -1));
EXPECT_FALSE(quota()->CheckOriginQuota(GURL(kTestOrigins[i]), 0));
EXPECT_FALSE(quota()->CheckOriginQuota(GURL(kTestOrigins[i]), 100));
}
}
TEST_F(FileSystemQuotaTest, CheckOriginQuotaUnlimited) {
// Tests if SetOriginQuotaUnlimited and ResetOriginQuotaUnlimited
// are working as expected.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message() << "CheckOriginQuotaUnlimited #"
<< i << " " << kTestOrigins[i]);
GURL url(kTestOrigins[i]);
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
quota()->SetOriginQuotaUnlimited(url);
EXPECT_TRUE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
EXPECT_TRUE(quota()->CheckOriginQuota(url, -1));
EXPECT_TRUE(quota()->CheckOriginQuota(url, 0));
EXPECT_TRUE(quota()->CheckOriginQuota(url, 100));
quota()->ResetOriginQuotaUnlimited(url);
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
EXPECT_FALSE(quota()->CheckOriginQuota(url, -1));
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
EXPECT_FALSE(quota()->CheckOriginQuota(url, 100));
}
}
TEST_F(FileSystemQuotaTest, CheckOriginQuotaWithMixedSet) {
// Tests setting unlimited quota for some urls doesn't affect
// other urls.
GURL test_url1("http://foo.bar.com/");
GURL test_url2("http://example.com/");
quota()->SetOriginQuotaUnlimited(test_url1);
quota()->SetOriginQuotaUnlimited(test_url2);
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message() << "CheckOriginQuotaMixedSet #"
<< i << " " << kTestOrigins[i]);
GURL url(kTestOrigins[i]);
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
}
}
TEST_F(FileSystemQuotaTest, CheckOriginQuotaMixedWithDifferentScheme) {
// Tests setting unlimited quota for urls doesn't affect
// pages in the same hosts but with different scheme.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
GURL url(kTestOrigins[i]);
if (url.SchemeIsFile())
continue;
DCHECK(url == url.GetOrigin());
std::string new_scheme = "https";
if (url.SchemeIsSecure())
new_scheme = "http";
else
DCHECK(url.SchemeIs("http"));
std::string new_url_string = new_scheme + "://" + url.host();
if (url.has_port())
new_url_string += ":" + url.port();
quota()->SetOriginQuotaUnlimited(GURL(new_url_string));
}
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message()
<< "CheckOriginQuotaMixedWithDifferentScheme #"
<< i << " " << kTestOrigins[i]);
GURL url(kTestOrigins[i]);
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
}
}
TEST_F(FileSystemQuotaTest, CheckOriginQuotaMixedWithDifferentPort) {
// Tests setting unlimited quota for urls doesn't affect
// pages in the same scheme/hosts but with different port number.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
GURL url(kTestOrigins[i]);
if (url.SchemeIsFile())
continue;
DCHECK(url == url.GetOrigin());
int port = 81;
if (url.has_port())
port = url.IntPort() + 1;
GURL new_url(url.scheme() + "://" + url.host() + ":" +
base::IntToString(port));
quota()->SetOriginQuotaUnlimited(new_url);
}
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message()
<< "CheckOriginQuotaMixedWithDifferentPort #"
<< i << " " << kTestOrigins[i]);
GURL url(kTestOrigins[i]);
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
}
}
<commit_msg>Replace DCHECK in the FileSystemQuota test code with ASSERT_TRUE.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/fileapi/file_system_quota.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_number_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
using namespace fileapi;
class FileSystemQuotaTest : public testing::Test {
public:
FileSystemQuotaTest() { }
void SetUp() {
quota_.reset(new FileSystemQuota);
}
FileSystemQuota* quota() const { return quota_.get(); }
protected:
scoped_ptr<FileSystemQuota> quota_;
DISALLOW_COPY_AND_ASSIGN(FileSystemQuotaTest);
};
namespace {
static const char* const kTestOrigins[] = {
"https://a.com/",
"http://b.com/",
"http://c.com:1/",
"file:///",
};
} // anonymous namespace
TEST_F(FileSystemQuotaTest, CheckOriginQuotaNotAllowed) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message() << "CheckOriginQuotaNotAllowed #"
<< i << " " << kTestOrigins[i]);
// Should fail no matter how much size is requested.
EXPECT_FALSE(quota()->CheckOriginQuota(GURL(kTestOrigins[i]), -1));
EXPECT_FALSE(quota()->CheckOriginQuota(GURL(kTestOrigins[i]), 0));
EXPECT_FALSE(quota()->CheckOriginQuota(GURL(kTestOrigins[i]), 100));
}
}
TEST_F(FileSystemQuotaTest, CheckOriginQuotaUnlimited) {
// Tests if SetOriginQuotaUnlimited and ResetOriginQuotaUnlimited
// are working as expected.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message() << "CheckOriginQuotaUnlimited #"
<< i << " " << kTestOrigins[i]);
GURL url(kTestOrigins[i]);
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
quota()->SetOriginQuotaUnlimited(url);
EXPECT_TRUE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
EXPECT_TRUE(quota()->CheckOriginQuota(url, -1));
EXPECT_TRUE(quota()->CheckOriginQuota(url, 0));
EXPECT_TRUE(quota()->CheckOriginQuota(url, 100));
quota()->ResetOriginQuotaUnlimited(url);
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
EXPECT_FALSE(quota()->CheckOriginQuota(url, -1));
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
EXPECT_FALSE(quota()->CheckOriginQuota(url, 100));
}
}
TEST_F(FileSystemQuotaTest, CheckOriginQuotaWithMixedSet) {
// Tests setting unlimited quota for some urls doesn't affect
// other urls.
GURL test_url1("http://foo.bar.com/");
GURL test_url2("http://example.com/");
quota()->SetOriginQuotaUnlimited(test_url1);
quota()->SetOriginQuotaUnlimited(test_url2);
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message() << "CheckOriginQuotaMixedSet #"
<< i << " " << kTestOrigins[i]);
GURL url(kTestOrigins[i]);
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
}
}
TEST_F(FileSystemQuotaTest, CheckOriginQuotaMixedWithDifferentScheme) {
// Tests setting unlimited quota for urls doesn't affect
// pages in the same hosts but with different scheme.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
GURL url(kTestOrigins[i]);
if (url.SchemeIsFile())
continue;
ASSERT_TRUE(url == url.GetOrigin());
std::string new_scheme = "https";
if (url.SchemeIsSecure())
new_scheme = "http";
else
ASSERT_TRUE(url.SchemeIs("http"));
std::string new_url_string = new_scheme + "://" + url.host();
if (url.has_port())
new_url_string += ":" + url.port();
quota()->SetOriginQuotaUnlimited(GURL(new_url_string));
}
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message()
<< "CheckOriginQuotaMixedWithDifferentScheme #"
<< i << " " << kTestOrigins[i]);
GURL url(kTestOrigins[i]);
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
}
}
TEST_F(FileSystemQuotaTest, CheckOriginQuotaMixedWithDifferentPort) {
// Tests setting unlimited quota for urls doesn't affect
// pages in the same scheme/hosts but with different port number.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
GURL url(kTestOrigins[i]);
if (url.SchemeIsFile())
continue;
ASSERT_TRUE(url == url.GetOrigin());
int port = 81;
if (url.has_port())
port = url.IntPort() + 1;
GURL new_url(url.scheme() + "://" + url.host() + ":" +
base::IntToString(port));
quota()->SetOriginQuotaUnlimited(new_url);
}
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestOrigins); ++i) {
SCOPED_TRACE(testing::Message()
<< "CheckOriginQuotaMixedWithDifferentPort #"
<< i << " " << kTestOrigins[i]);
GURL url(kTestOrigins[i]);
EXPECT_FALSE(quota()->CheckOriginQuota(url, 0));
EXPECT_FALSE(quota()->CheckIfOriginGrantedUnlimitedQuota(url));
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pfuncache.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-07-21 15:06:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <tools/multisel.hxx>
#include "pfuncache.hxx"
#include "printfun.hxx"
#include "docsh.hxx"
#include "markdata.hxx"
#include "prevloc.hxx"
//------------------------------------------------------------------------
ScPrintFuncCache::ScPrintFuncCache( ScDocShell* pD, const ScMarkData& rMark,
const ScPrintSelectionStatus& rStatus ) :
aSelection( rStatus ),
pDocSh( pD ),
nTotalPages( 0 ),
bLocInitialized( false )
{
// page count uses the stored cell widths for the printer anyway,
// so ScPrintFunc with the document's printer can be used to count
SfxPrinter* pPrinter = pDocSh->GetPrinter();
ScRange aRange;
const ScRange* pSelRange = NULL;
if ( rMark.IsMarked() )
{
rMark.GetMarkArea( aRange );
pSelRange = &aRange;
}
ScDocument* pDoc = pDocSh->GetDocument();
SCTAB nTabCount = pDoc->GetTableCount();
SCTAB nTab;
for ( nTab=0; nTab<nTabCount; nTab++ )
{
long nAttrPage = nTab > 0 ? nFirstAttr[nTab-1] : 1;
long nThisTab = 0;
if ( rMark.GetTableSelect( nTab ) )
{
ScPrintFunc aFunc( pDocSh, pPrinter, nTab, nAttrPage, 0, pSelRange );
nThisTab = aFunc.GetTotalPages();
nFirstAttr[nTab] = aFunc.GetFirstPageNo(); // from page style or previous sheet
}
else
nFirstAttr[nTab] = nAttrPage;
nPages[nTab] = nThisTab;
nTotalPages += nThisTab;
}
}
ScPrintFuncCache::~ScPrintFuncCache()
{
}
void ScPrintFuncCache::InitLocations( const ScMarkData& rMark, OutputDevice* pDev )
{
if ( bLocInitialized )
return; // initialize only once
ScRange aRange;
const ScRange* pSelRange = NULL;
if ( rMark.IsMarked() )
{
rMark.GetMarkArea( aRange );
pSelRange = &aRange;
}
long nRenderer = 0; // 0-based physical page number across sheets
long nTabStart = 0;
ScDocument* pDoc = pDocSh->GetDocument();
SCTAB nTabCount = pDoc->GetTableCount();
for ( SCTAB nTab=0; nTab<nTabCount; nTab++ )
{
if ( rMark.GetTableSelect( nTab ) )
{
ScPrintFunc aFunc( pDev, pDocSh, nTab, nFirstAttr[nTab], nTotalPages, pSelRange );
aFunc.SetRenderFlag( TRUE );
long nDisplayStart = GetDisplayStart( nTab );
for ( long nPage=0; nPage<nPages[nTab]; nPage++ )
{
Range aPageRange( nRenderer+1, nRenderer+1 );
MultiSelection aPage( aPageRange );
aPage.SetTotalRange( Range(0,RANGE_MAX) );
aPage.Select( aPageRange );
ScPreviewLocationData aLocData( pDoc, pDev );
aFunc.DoPrint( aPage, nTabStart, nDisplayStart, FALSE, NULL, &aLocData );
ScRange aCellRange;
Rectangle aPixRect;
if ( aLocData.GetMainCellRange( aCellRange, aPixRect ) )
aLocations.push_back( ScPrintPageLocation( nRenderer, aCellRange, aPixRect ) );
++nRenderer;
}
nTabStart += nPages[nTab];
}
}
bLocInitialized = true;
}
bool ScPrintFuncCache::FindLocation( const ScAddress& rCell, ScPrintPageLocation& rLocation ) const
{
for ( std::vector<ScPrintPageLocation>::const_iterator aIter(aLocations.begin());
aIter != aLocations.end(); aIter++ )
{
if ( aIter->aCellRange.In( rCell ) )
{
rLocation = *aIter;
return true;
}
}
return false; // not found
}
BOOL ScPrintFuncCache::IsSameSelection( const ScPrintSelectionStatus& rStatus ) const
{
return aSelection == rStatus;
}
SCTAB ScPrintFuncCache::GetTabForPage( long nPage ) const
{
ScDocument* pDoc = pDocSh->GetDocument();
SCTAB nTabCount = pDoc->GetTableCount();
SCTAB nTab = 0;
while ( nTab < nTabCount && nPage >= nPages[nTab] )
nPage -= nPages[nTab++];
return nTab;
}
long ScPrintFuncCache::GetTabStart( SCTAB nTab ) const
{
long nRet = 0;
for ( SCTAB i=0; i<nTab; i++ )
nRet += nPages[i];
return nRet;
}
long ScPrintFuncCache::GetDisplayStart( SCTAB nTab ) const
{
//! merge with lcl_GetDisplayStart in preview?
long nDisplayStart = 0;
ScDocument* pDoc = pDocSh->GetDocument();
for (SCTAB i=0; i<nTab; i++)
{
if ( pDoc->NeedPageResetAfterTab(i) )
nDisplayStart = 0;
else
nDisplayStart += nPages[i];
}
return nDisplayStart;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.492); FILE MERGED 2008/03/31 17:20:00 rt 1.5.492.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pfuncache.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <tools/multisel.hxx>
#include "pfuncache.hxx"
#include "printfun.hxx"
#include "docsh.hxx"
#include "markdata.hxx"
#include "prevloc.hxx"
//------------------------------------------------------------------------
ScPrintFuncCache::ScPrintFuncCache( ScDocShell* pD, const ScMarkData& rMark,
const ScPrintSelectionStatus& rStatus ) :
aSelection( rStatus ),
pDocSh( pD ),
nTotalPages( 0 ),
bLocInitialized( false )
{
// page count uses the stored cell widths for the printer anyway,
// so ScPrintFunc with the document's printer can be used to count
SfxPrinter* pPrinter = pDocSh->GetPrinter();
ScRange aRange;
const ScRange* pSelRange = NULL;
if ( rMark.IsMarked() )
{
rMark.GetMarkArea( aRange );
pSelRange = &aRange;
}
ScDocument* pDoc = pDocSh->GetDocument();
SCTAB nTabCount = pDoc->GetTableCount();
SCTAB nTab;
for ( nTab=0; nTab<nTabCount; nTab++ )
{
long nAttrPage = nTab > 0 ? nFirstAttr[nTab-1] : 1;
long nThisTab = 0;
if ( rMark.GetTableSelect( nTab ) )
{
ScPrintFunc aFunc( pDocSh, pPrinter, nTab, nAttrPage, 0, pSelRange );
nThisTab = aFunc.GetTotalPages();
nFirstAttr[nTab] = aFunc.GetFirstPageNo(); // from page style or previous sheet
}
else
nFirstAttr[nTab] = nAttrPage;
nPages[nTab] = nThisTab;
nTotalPages += nThisTab;
}
}
ScPrintFuncCache::~ScPrintFuncCache()
{
}
void ScPrintFuncCache::InitLocations( const ScMarkData& rMark, OutputDevice* pDev )
{
if ( bLocInitialized )
return; // initialize only once
ScRange aRange;
const ScRange* pSelRange = NULL;
if ( rMark.IsMarked() )
{
rMark.GetMarkArea( aRange );
pSelRange = &aRange;
}
long nRenderer = 0; // 0-based physical page number across sheets
long nTabStart = 0;
ScDocument* pDoc = pDocSh->GetDocument();
SCTAB nTabCount = pDoc->GetTableCount();
for ( SCTAB nTab=0; nTab<nTabCount; nTab++ )
{
if ( rMark.GetTableSelect( nTab ) )
{
ScPrintFunc aFunc( pDev, pDocSh, nTab, nFirstAttr[nTab], nTotalPages, pSelRange );
aFunc.SetRenderFlag( TRUE );
long nDisplayStart = GetDisplayStart( nTab );
for ( long nPage=0; nPage<nPages[nTab]; nPage++ )
{
Range aPageRange( nRenderer+1, nRenderer+1 );
MultiSelection aPage( aPageRange );
aPage.SetTotalRange( Range(0,RANGE_MAX) );
aPage.Select( aPageRange );
ScPreviewLocationData aLocData( pDoc, pDev );
aFunc.DoPrint( aPage, nTabStart, nDisplayStart, FALSE, NULL, &aLocData );
ScRange aCellRange;
Rectangle aPixRect;
if ( aLocData.GetMainCellRange( aCellRange, aPixRect ) )
aLocations.push_back( ScPrintPageLocation( nRenderer, aCellRange, aPixRect ) );
++nRenderer;
}
nTabStart += nPages[nTab];
}
}
bLocInitialized = true;
}
bool ScPrintFuncCache::FindLocation( const ScAddress& rCell, ScPrintPageLocation& rLocation ) const
{
for ( std::vector<ScPrintPageLocation>::const_iterator aIter(aLocations.begin());
aIter != aLocations.end(); aIter++ )
{
if ( aIter->aCellRange.In( rCell ) )
{
rLocation = *aIter;
return true;
}
}
return false; // not found
}
BOOL ScPrintFuncCache::IsSameSelection( const ScPrintSelectionStatus& rStatus ) const
{
return aSelection == rStatus;
}
SCTAB ScPrintFuncCache::GetTabForPage( long nPage ) const
{
ScDocument* pDoc = pDocSh->GetDocument();
SCTAB nTabCount = pDoc->GetTableCount();
SCTAB nTab = 0;
while ( nTab < nTabCount && nPage >= nPages[nTab] )
nPage -= nPages[nTab++];
return nTab;
}
long ScPrintFuncCache::GetTabStart( SCTAB nTab ) const
{
long nRet = 0;
for ( SCTAB i=0; i<nTab; i++ )
nRet += nPages[i];
return nRet;
}
long ScPrintFuncCache::GetDisplayStart( SCTAB nTab ) const
{
//! merge with lcl_GetDisplayStart in preview?
long nDisplayStart = 0;
ScDocument* pDoc = pDocSh->GetDocument();
for (SCTAB i=0; i<nTab; i++)
{
if ( pDoc->NeedPageResetAfterTab(i) )
nDisplayStart = 0;
else
nDisplayStart += nPages[i];
}
return nDisplayStart;
}
<|endoftext|>
|
<commit_before>/**
* syntaxhighlighter.cpp
*
* Copyright (c) 2003 Trolltech AS
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "syntaxhighlighter.h"
#include <klocale.h>
#include <qcolor.h>
#include <qregexp.h>
#include <qsyntaxhighlighter.h>
#include <qtimer.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kspell.h>
#include <kmkernel.h>
#include <kapplication.h>
static int dummy, dummy2;
static int *Okay = &dummy;
static int *NotOkay = &dummy2;
namespace KMail {
MessageHighlighter::MessageHighlighter( QTextEdit *textEdit, SyntaxMode mode )
: QSyntaxHighlighter( textEdit ), sMode( mode )
{
KConfig *config = KMKernel::config();
// block defines the lifetime of KConfigGroupSaver
KConfigGroupSaver saver(config, "Reader");
QColor defaultColor1( 0x00, 0x80, 0x00 ); // defaults from kmreaderwin.cpp
QColor defaultColor2( 0x00, 0x70, 0x00 );
QColor defaultColor3( 0x00, 0x60, 0x00 );
col1 = QColor(kapp->palette().active().text());
col2 = config->readColorEntry( "QuotedText3", &defaultColor3 );
col3 = config->readColorEntry( "QuotedText2", &defaultColor2 );
col4 = config->readColorEntry( "QuotedText1", &defaultColor1 );
col5 = col1;
}
MessageHighlighter::~MessageHighlighter()
{
}
int MessageHighlighter::highlightParagraph( const QString &text, int )
{
QString simplified = text;
simplified = simplified.replace( QRegExp( "\\s" ), "" );
if ( simplified.startsWith( ">>>>" ) )
setFormat( 0, text.length(), col1 );
else if ( simplified.startsWith( ">>>" ) || simplified.startsWith( "> > >" ) )
setFormat( 0, text.length(), col2 );
else if ( simplified.startsWith( ">>" ) || simplified.startsWith( "> >" ) )
setFormat( 0, text.length(), col3 );
else if ( simplified.startsWith( ">" ) )
setFormat( 0, text.length(), col4 );
else
setFormat( 0, text.length(), col5 );
return 0;
}
SpellChecker::SpellChecker( QTextEdit *textEdit )
: MessageHighlighter( textEdit ), alwaysEndsWithSpace( TRUE )
{
KConfig *config = KMKernel::config();
KConfigGroupSaver saver(config, "Reader");
QColor c = QColor("red");
mColor = config->readColorEntry("NewMessage", &c);
}
SpellChecker::~SpellChecker()
{
}
int SpellChecker::highlightParagraph( const QString& text,
int endStateOfLastPara )
{
// leave German, Norwegian, and Swedish alone
QRegExp norwegian( "[\xc4-\xc6\xd6\xd8\xdc\xdf\xe4-\xe6\xf6\xf8\xfc]" );
// leave #includes, diffs, and quoted replies alone
QString diffAndCo( "#+-<>" );
bool isCode = ( text.stripWhiteSpace().endsWith(";") ||
diffAndCo.find(text[0]) != -1 );
bool isNorwegian = ( text.find(norwegian) != -1 );
isNorwegian = false; //DS: disable this, hopefully KSpell can handle these languages.
isCode = false; //DS: disable this, can put it back if there is demand.
if ( !text.endsWith(" ") )
alwaysEndsWithSpace = FALSE;
MessageHighlighter::highlightParagraph( text, endStateOfLastPara );
if ( !isCode && !isNorwegian ) {
int len = text.length();
if ( alwaysEndsWithSpace )
len--;
currentPos = 0;
currentWord = "";
for ( int i = 0; i < len; i++ ) {
if ( text[i].isSpace() || text[i] == '-' ) {
flushCurrentWord();
currentPos = i + 1;
} else {
currentWord += text[i];
}
}
if ( !text[len - 1].isLetter() )
flushCurrentWord();
}
return endStateOfLastPara;
}
QStringList SpellChecker::personalWords()
{
QStringList l;
l.append( "KMail" );
l.append( "KOrganizer" );
l.append( "KHTML" );
l.append( "KIO" );
l.append( "KJS" );
l.append( "Konqueror" );
return l;
}
void SpellChecker::flushCurrentWord()
{
while ( currentWord[0].isPunct() ) {
currentWord = currentWord.mid( 1 );
currentPos++;
}
QChar ch;
while ( (ch = currentWord[(int) currentWord.length() - 1]).isPunct() &&
ch != '(' && ch != '@' )
currentWord.truncate( currentWord.length() - 1 );
if ( !currentWord.isEmpty() ) {
if ( isMisspelled(currentWord) )
setFormat( currentPos, currentWord.length(), mColor );
}
currentWord = "";
}
QDict<int> DictSpellChecker::dict( 50021 );
QObject *DictSpellChecker::sDictionaryMonitor = 0;
DictSpellChecker::DictSpellChecker( QTextEdit *textEdit )
: SpellChecker( textEdit )
{
mRehighlightRequested = false;
mSpell = 0;
mSpellKey = spellKey();
if (!sDictionaryMonitor)
sDictionaryMonitor = new QObject();
slotDictionaryChanged();
startTimer(2*1000);
}
DictSpellChecker::~DictSpellChecker()
{
delete mSpell;
}
void DictSpellChecker::slotSpellReady( KSpell *spell )
{
connect( sDictionaryMonitor, SIGNAL( destroyed() ),
this, SLOT( slotDictionaryChanged() ));
mSpell = spell;
QStringList l = SpellChecker::personalWords();
for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) {
mSpell->addPersonal( *it );
}
connect( spell, SIGNAL( misspelling (const QString &, const QStringList &, unsigned int) ),
this, SLOT( slotMisspelling (const QString &, const QStringList &, unsigned int)));
if (!mRehighlightRequested) {
mRehighlightRequested = true;
QTimer::singleShot(0, this, SLOT(slotRehighlight()));
}
}
bool DictSpellChecker::isMisspelled( const QString& word )
{
// Normally isMisspelled would look up a dictionary and return
// true or false, but kspell is asynchronous and slow so things
// get tricky...
// "dict" is used as a cache to store the results of KSpell
if (!dict.isEmpty() && dict[word] == NotOkay)
return true;
if (!dict.isEmpty() && dict[word] == Okay)
return false;
// there is no 'spelt correctly' signal so default to Okay
dict.replace( word, Okay );
// yes I tried checkWord, the docs lie and it didn't give useful signals :-(
if (mSpell)
mSpell->check( word, false );
return false;
}
void DictSpellChecker::slotMisspelling (const QString & originalword, const QStringList & suggestions, unsigned int)
{
kdDebug(5006) << suggestions.join(" ").latin1() << endl;
dict.replace( originalword, NotOkay );
// this is slow but since kspell is async this will have to do for now
if (!mRehighlightRequested) {
mRehighlightRequested = true;
QTimer::singleShot(0, this, SLOT(slotRehighlight()));
}
}
void DictSpellChecker::dictionaryChanged()
{
QObject *oldMonitor = sDictionaryMonitor;
sDictionaryMonitor = new QObject();
dict.clear();
delete oldMonitor;
}
void DictSpellChecker::slotRehighlight()
{
mRehighlightRequested = false;
rehighlight();
}
void DictSpellChecker::slotDictionaryChanged()
{
delete mSpell;
mSpell = 0;
new KSpell(0, i18n("Incremental Spellcheck - KMail"), this,
SLOT(slotSpellReady(KSpell*)));
}
QString DictSpellChecker::spellKey()
{
KConfig *config = KGlobal::config();
KConfigGroupSaver cs(config,"KSpell");
config->reparseConfiguration();
QString key;
key += QString::number(config->readNumEntry("KSpell_NoRootAffix", 0));
key += '/';
key += QString::number(config->readNumEntry("KSpell_RunTogether", 0));
key += '/';
key += config->readEntry("KSpell_Dictionary", "");
key += '/';
key += QString::number(config->readNumEntry("KSpell_DictFromList", FALSE));
key += '/';
key += QString::number(config->readNumEntry ("KSpell_Encoding", KS_E_ASCII));
key += '/';
key += QString::number(config->readNumEntry ("KSpell_Client", KS_CLIENT_ISPELL));
return key;
}
void DictSpellChecker::timerEvent(QTimerEvent *e)
{
if (mSpell && mSpellKey != spellKey()) {
mSpellKey = spellKey();
DictSpellChecker::dictionaryChanged();
}
}
} //namespace KMail
#include "syntaxhighlighter.moc"
<commit_msg>Add a note.<commit_after>/**
* syntaxhighlighter.cpp
*
* Copyright (c) 2003 Trolltech AS
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "syntaxhighlighter.h"
#include <klocale.h>
#include <qcolor.h>
#include <qregexp.h>
#include <qsyntaxhighlighter.h>
#include <qtimer.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kspell.h>
#include <kmkernel.h>
#include <kapplication.h>
static int dummy, dummy2;
static int *Okay = &dummy;
static int *NotOkay = &dummy2;
namespace KMail {
MessageHighlighter::MessageHighlighter( QTextEdit *textEdit, SyntaxMode mode )
: QSyntaxHighlighter( textEdit ), sMode( mode )
{
KConfig *config = KMKernel::config();
// block defines the lifetime of KConfigGroupSaver
KConfigGroupSaver saver(config, "Reader");
QColor defaultColor1( 0x00, 0x80, 0x00 ); // defaults from kmreaderwin.cpp
QColor defaultColor2( 0x00, 0x70, 0x00 );
QColor defaultColor3( 0x00, 0x60, 0x00 );
col1 = QColor(kapp->palette().active().text());
col2 = config->readColorEntry( "QuotedText3", &defaultColor3 );
col3 = config->readColorEntry( "QuotedText2", &defaultColor2 );
col4 = config->readColorEntry( "QuotedText1", &defaultColor1 );
col5 = col1;
}
MessageHighlighter::~MessageHighlighter()
{
}
int MessageHighlighter::highlightParagraph( const QString &text, int )
{
QString simplified = text;
simplified = simplified.replace( QRegExp( "\\s" ), "" );
if ( simplified.startsWith( ">>>>" ) )
setFormat( 0, text.length(), col1 );
else if ( simplified.startsWith( ">>>" ) || simplified.startsWith( "> > >" ) )
setFormat( 0, text.length(), col2 );
else if ( simplified.startsWith( ">>" ) || simplified.startsWith( "> >" ) )
setFormat( 0, text.length(), col3 );
else if ( simplified.startsWith( ">" ) )
setFormat( 0, text.length(), col4 );
else
setFormat( 0, text.length(), col5 );
return 0;
}
SpellChecker::SpellChecker( QTextEdit *textEdit )
: MessageHighlighter( textEdit ), alwaysEndsWithSpace( TRUE )
{
KConfig *config = KMKernel::config();
KConfigGroupSaver saver(config, "Reader");
QColor c = QColor("red");
mColor = config->readColorEntry("NewMessage", &c);
}
SpellChecker::~SpellChecker()
{
}
int SpellChecker::highlightParagraph( const QString& text,
int endStateOfLastPara )
{
// leave German, Norwegian, and Swedish alone
QRegExp norwegian( "[\xc4-\xc6\xd6\xd8\xdc\xdf\xe4-\xe6\xf6\xf8\xfc]" );
// leave #includes, diffs, and quoted replies alone
QString diffAndCo( "#+-<>" );
bool isCode = ( text.stripWhiteSpace().endsWith(";") ||
diffAndCo.find(text[0]) != -1 );
bool isNorwegian = ( text.find(norwegian) != -1 );
isNorwegian = false; //DS: disable this, hopefully KSpell can handle these languages.
isCode = false; //DS: disable this, can put it back if there is demand.
if ( !text.endsWith(" ") )
alwaysEndsWithSpace = FALSE;
MessageHighlighter::highlightParagraph( text, endStateOfLastPara );
if ( !isCode && !isNorwegian ) {
int len = text.length();
if ( alwaysEndsWithSpace )
len--;
currentPos = 0;
currentWord = "";
for ( int i = 0; i < len; i++ ) {
if ( text[i].isSpace() || text[i] == '-' ) {
flushCurrentWord();
currentPos = i + 1;
} else {
currentWord += text[i];
}
}
if ( !text[len - 1].isLetter() )
flushCurrentWord();
}
return endStateOfLastPara;
}
QStringList SpellChecker::personalWords()
{
QStringList l;
l.append( "KMail" );
l.append( "KOrganizer" );
l.append( "KHTML" );
l.append( "KIO" );
l.append( "KJS" );
l.append( "Konqueror" );
return l;
}
void SpellChecker::flushCurrentWord()
{
while ( currentWord[0].isPunct() ) {
currentWord = currentWord.mid( 1 );
currentPos++;
}
QChar ch;
while ( (ch = currentWord[(int) currentWord.length() - 1]).isPunct() &&
ch != '(' && ch != '@' )
currentWord.truncate( currentWord.length() - 1 );
if ( !currentWord.isEmpty() ) {
if ( isMisspelled(currentWord) )
setFormat( currentPos, currentWord.length(), mColor );
}
currentWord = "";
}
QDict<int> DictSpellChecker::dict( 50021 );
QObject *DictSpellChecker::sDictionaryMonitor = 0;
DictSpellChecker::DictSpellChecker( QTextEdit *textEdit )
: SpellChecker( textEdit )
{
mRehighlightRequested = false;
mSpell = 0;
mSpellKey = spellKey();
if (!sDictionaryMonitor)
sDictionaryMonitor = new QObject();
slotDictionaryChanged();
startTimer(2*1000);
}
DictSpellChecker::~DictSpellChecker()
{
delete mSpell;
}
void DictSpellChecker::slotSpellReady( KSpell *spell )
{
connect( sDictionaryMonitor, SIGNAL( destroyed() ),
this, SLOT( slotDictionaryChanged() ));
mSpell = spell;
QStringList l = SpellChecker::personalWords();
for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) {
mSpell->addPersonal( *it );
}
connect( spell, SIGNAL( misspelling (const QString &, const QStringList &, unsigned int) ),
this, SLOT( slotMisspelling (const QString &, const QStringList &, unsigned int)));
if (!mRehighlightRequested) {
mRehighlightRequested = true;
QTimer::singleShot(0, this, SLOT(slotRehighlight()));
}
}
bool DictSpellChecker::isMisspelled( const QString& word )
{
// Normally isMisspelled would look up a dictionary and return
// true or false, but kspell is asynchronous and slow so things
// get tricky...
// "dict" is used as a cache to store the results of KSpell
if (!dict.isEmpty() && dict[word] == NotOkay)
return true;
if (!dict.isEmpty() && dict[word] == Okay)
return false;
// there is no 'spelt correctly' signal so default to Okay
dict.replace( word, Okay );
// yes I tried checkWord, the docs lie and it didn't give useful signals :-(
if (mSpell)
mSpell->check( word, false );
return false;
}
void DictSpellChecker::slotMisspelling (const QString & originalword, const QStringList & suggestions, unsigned int)
{
kdDebug(5006) << suggestions.join(" ").latin1() << endl;
dict.replace( originalword, NotOkay );
// this is slow but since kspell is async this will have to do for now
if (!mRehighlightRequested) {
mRehighlightRequested = true;
QTimer::singleShot(0, this, SLOT(slotRehighlight()));
}
}
void DictSpellChecker::dictionaryChanged()
{
QObject *oldMonitor = sDictionaryMonitor;
sDictionaryMonitor = new QObject();
dict.clear();
delete oldMonitor;
}
void DictSpellChecker::slotRehighlight()
{
mRehighlightRequested = false;
rehighlight();
}
void DictSpellChecker::slotDictionaryChanged()
{
delete mSpell;
mSpell = 0;
new KSpell(0, i18n("Incremental Spellcheck - KMail"), this,
SLOT(slotSpellReady(KSpell*)));
}
QString DictSpellChecker::spellKey()
{
//Note: Yes polling with timerEvent and reading directly from kglobals
//Note: is evil. It would be nice if there was some kind of inter-process
//Note: signal emitted when spelling configuration options are changed.
KConfig *config = KGlobal::config();
KConfigGroupSaver cs(config,"KSpell");
config->reparseConfiguration();
QString key;
key += QString::number(config->readNumEntry("KSpell_NoRootAffix", 0));
key += '/';
key += QString::number(config->readNumEntry("KSpell_RunTogether", 0));
key += '/';
key += config->readEntry("KSpell_Dictionary", "");
key += '/';
key += QString::number(config->readNumEntry("KSpell_DictFromList", FALSE));
key += '/';
key += QString::number(config->readNumEntry ("KSpell_Encoding", KS_E_ASCII));
key += '/';
key += QString::number(config->readNumEntry ("KSpell_Client", KS_CLIENT_ISPELL));
return key;
}
void DictSpellChecker::timerEvent(QTimerEvent *e)
{
if (mSpell && mSpellKey != spellKey()) {
mSpellKey = spellKey();
DictSpellChecker::dictionaryChanged();
}
}
} //namespace KMail
#include "syntaxhighlighter.moc"
<|endoftext|>
|
<commit_before>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Array.hpp>
#include <math.hpp>
namespace cpu
{
namespace kernel
{
template<typename T>
void stridedCopy(T* dst, af::dim4 const & ostrides, T const * src,
af::dim4 const & dims, af::dim4 const & strides, unsigned dim)
{
if(dim == 0) {
if(strides[dim] == 1) {
//FIXME: Check for errors / exceptions
memcpy(dst, src, dims[dim] * sizeof(T));
} else {
for(dim_t i = 0; i < dims[dim]; i++) {
dst[i] = src[strides[dim]*i];
}
}
} else {
for(dim_t i = dims[dim]; i > 0; i--) {
stridedCopy<T>(dst, ostrides, src, dims, strides, dim - 1);
src += strides[dim];
dst += ostrides[dim];
}
}
}
template<typename OutT, typename InT>
void copyElemwise(Array<OutT> dst, Array<InT> const src, OutT default_value, double factor)
{
af::dim4 src_dims = src.dims();
af::dim4 dst_dims = dst.dims();
af::dim4 src_strides = src.strides();
af::dim4 dst_strides = dst.strides();
InT const * const src_ptr = src.get();
OutT * dst_ptr = dst.get();
dim_t trgt_l = std::min(dst_dims[3], src_dims[3]);
dim_t trgt_k = std::min(dst_dims[2], src_dims[2]);
dim_t trgt_j = std::min(dst_dims[1], src_dims[1]);
dim_t trgt_i = std::min(dst_dims[0], src_dims[0]);
for(dim_t l=0; l<dst_dims[3]; ++l) {
dim_t src_loff = l*src_strides[3];
dim_t dst_loff = l*dst_strides[3];
bool isLvalid = l<trgt_l;
for(dim_t k=0; k<dst_dims[2]; ++k) {
dim_t src_koff = k*src_strides[2];
dim_t dst_koff = k*dst_strides[2];
bool isKvalid = k<trgt_k;
for(dim_t j=0; j<dst_dims[1]; ++j) {
dim_t src_joff = j*src_strides[1];
dim_t dst_joff = j*dst_strides[1];
bool isJvalid = j<trgt_j;
for(dim_t i=0; i<dst_dims[0]; ++i) {
OutT temp = default_value;
if (isLvalid && isKvalid && isJvalid && i<trgt_i) {
dim_t src_idx = i*src_strides[0] + src_joff + src_koff + src_loff;
temp = OutT(src_ptr[src_idx])*OutT(factor);
}
dim_t dst_idx = i*dst_strides[0] + dst_joff + dst_koff + dst_loff;
dst_ptr[dst_idx] = temp;
}
}
}
}
}
template<typename OutT, typename InT>
struct CopyImpl
{
static void copy(Array<OutT> dst, Array<InT> const src)
{
copyElemwise(dst, src, scalar<OutT>(0), 1.0);
}
};
template<typename T>
struct CopyImpl<T, T>
{
static void copy(Array<T> dst, Array<T> const src)
{
af::dim4 src_dims = src.dims();
af::dim4 dst_dims = dst.dims();
af::dim4 src_strides = src.strides();
af::dim4 dst_strides = dst.strides();
T const * const src_ptr = src.get();
T * dst_ptr = dst.get();
// find the major-most dimension, which is linear in both arrays
int linear_end = 0;
dim_t count = 1;
while (linear_end < 4
&& count == src_strides[linear_end]
&& count == dst_strides[linear_end]) {
++linear_end;
count *= src_dims[linear_end];
}
// traverse through the array using strides only until neccessary
if (linear_end == 4) {
std::memcpy(dst_ptr, src_ptr, sizeof(T) * src.elements());
} else {
for(dim_t l=0; l<dst_dims[3]; ++l) {
dim_t src_loff = l*src_strides[3];
dim_t dst_loff = l*dst_strides[3];
if (linear_end == 3) {
dim_t dst_idx = dst_loff;
dim_t src_idx = src_loff;
std::memcpy(dst_ptr + dst_idx, src_ptr + src_idx, sizeof(T) * src_strides[3]);
} else {
for(dim_t k=0; k<dst_dims[2]; ++k) {
dim_t src_koff = k*src_strides[2];
dim_t dst_koff = k*dst_strides[2];
if (linear_end == 2) {
dim_t dst_idx = dst_koff + dst_loff;
dim_t src_idx = src_koff + src_loff;
std::memcpy(dst_ptr + dst_idx, src_ptr + src_idx, sizeof(T) * src_strides[2]);
} else {
for(dim_t j=0; j<dst_dims[1]; ++j) {
dim_t src_joff = j*src_strides[1];
dim_t dst_joff = j*dst_strides[1];
if (linear_end == 1) {
dim_t dst_idx = dst_joff + dst_koff + dst_loff;
dim_t src_idx = src_joff + src_koff + src_loff;
std::memcpy(dst_ptr + dst_idx, src_ptr + src_idx, sizeof(T) * src_strides[1]);
} else {
for(dim_t i=0; i<dst_dims[0]; ++i) {
dim_t dst_idx = i*dst_strides[0] + dst_joff + dst_koff + dst_loff;
dim_t src_idx = i*src_strides[0] + src_joff + src_koff + src_loff;
dst_ptr[dst_idx] = src_ptr[src_idx];
}
}
}
}
}
}
}
}
}
};
template<typename OutT, typename InT>
void copy(Array<OutT> dst, Array<InT> const src)
{
CopyImpl<OutT, InT>::copy(dst, src);
}
}
}
<commit_msg>Simplify code using recursion instead of nested loops.<commit_after>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Array.hpp>
#include <math.hpp>
namespace cpu
{
namespace kernel
{
template<typename T>
void stridedCopy(T* dst, af::dim4 const & ostrides, T const * src,
af::dim4 const & dims, af::dim4 const & strides, unsigned dim)
{
if(dim == 0) {
if(strides[dim] == 1) {
//FIXME: Check for errors / exceptions
memcpy(dst, src, dims[dim] * sizeof(T));
} else {
for(dim_t i = 0; i < dims[dim]; i++) {
dst[i] = src[strides[dim]*i];
}
}
} else {
for(dim_t i = dims[dim]; i > 0; i--) {
stridedCopy<T>(dst, ostrides, src, dims, strides, dim - 1);
src += strides[dim];
dst += ostrides[dim];
}
}
}
template<typename OutT, typename InT>
void copyElemwise(Array<OutT> dst, Array<InT> const src, OutT default_value, double factor)
{
af::dim4 src_dims = src.dims();
af::dim4 dst_dims = dst.dims();
af::dim4 src_strides = src.strides();
af::dim4 dst_strides = dst.strides();
InT const * const src_ptr = src.get();
OutT * dst_ptr = dst.get();
dim_t trgt_l = std::min(dst_dims[3], src_dims[3]);
dim_t trgt_k = std::min(dst_dims[2], src_dims[2]);
dim_t trgt_j = std::min(dst_dims[1], src_dims[1]);
dim_t trgt_i = std::min(dst_dims[0], src_dims[0]);
for(dim_t l=0; l<dst_dims[3]; ++l) {
dim_t src_loff = l*src_strides[3];
dim_t dst_loff = l*dst_strides[3];
bool isLvalid = l<trgt_l;
for(dim_t k=0; k<dst_dims[2]; ++k) {
dim_t src_koff = k*src_strides[2];
dim_t dst_koff = k*dst_strides[2];
bool isKvalid = k<trgt_k;
for(dim_t j=0; j<dst_dims[1]; ++j) {
dim_t src_joff = j*src_strides[1];
dim_t dst_joff = j*dst_strides[1];
bool isJvalid = j<trgt_j;
for(dim_t i=0; i<dst_dims[0]; ++i) {
OutT temp = default_value;
if (isLvalid && isKvalid && isJvalid && i<trgt_i) {
dim_t src_idx = i*src_strides[0] + src_joff + src_koff + src_loff;
temp = OutT(src_ptr[src_idx])*OutT(factor);
}
dim_t dst_idx = i*dst_strides[0] + dst_joff + dst_koff + dst_loff;
dst_ptr[dst_idx] = temp;
}
}
}
}
}
template<typename OutT, typename InT>
struct CopyImpl
{
static void copy(Array<OutT> dst, Array<InT> const src)
{
copyElemwise(dst, src, scalar<OutT>(0), 1.0);
}
};
template<typename T>
struct CopyImpl<T, T>
{
static void copy(Array<T> dst, Array<T> const src)
{
af::dim4 src_dims = src.dims();
af::dim4 dst_dims = dst.dims();
af::dim4 src_strides = src.strides();
af::dim4 dst_strides = dst.strides();
T const * src_ptr = src.get();
T * dst_ptr = dst.get();
// find the major-most dimension, which is linear in both arrays
int linear_end = 0;
dim_t count = 1;
while (linear_end < 4
&& count == src_strides[linear_end]
&& count == dst_strides[linear_end]) {
++linear_end;
count *= src_dims[linear_end];
}
// traverse through the array using strides only until neccessary
if (linear_end == 4)
std::memcpy(dst_ptr, src_ptr, sizeof(T) * src.elements());
else
copy_go(dst_ptr, dst_strides, dst_dims, src_ptr, src_strides, src_dims, 3, linear_end);
}
static void copy_go(
T * dst_ptr, const af::dim4 & dst_strides, const af::dim4 & dst_dims,
T const * src_ptr, const af::dim4 & src_strides, const af::dim4 & src_dims,
int dim, int linear_end)
{
for(dim_t i=0; i<dst_dims[dim]; ++i) {
// 0th dimension is recursion bottom - copy element by element
if (dim == 0)
*dst_ptr = *src_ptr;
// if we are in a higher dimension, copy the entire stride if possible
else if (linear_end == dim)
std::memcpy(dst_ptr, src_ptr, sizeof(T) * src_strides[dim]);
// otherwise recurse to a lower dimenstion
else
copy_go(dst_ptr, dst_strides, dst_dims, src_ptr, src_strides, src_dims, dim - 1, linear_end);
dst_ptr += dst_strides[dim];
src_ptr += src_strides[dim];
}
}
};
template<typename OutT, typename InT>
void copy(Array<OutT> dst, Array<InT> const src)
{
CopyImpl<OutT, InT>::copy(dst, src);
}
}
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////
//
// Author: Mateusz Jurczyk (mjurczyk@google.com)
//
// Copyright 2017-2018 Google LLC
//
// 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 "common.h"
#include <set>
#include <vector>
#include "cpu/cpu.h"
#include "logging.pb.h"
#include "symbols.h"
// See instrumentation.h for globals' documentation.
namespace globals {
bochspwn_config config;
std::vector<module_info *> special_modules;
std::vector<module_info *> modules;
std::set<bx_address> known_callstack_item;
bx_address nt_base;
uint8_t *pool_taint_alloc;
uint8_t *stack_taint_alloc;
bool rep_movs;
bool esp_change;
uint32_t esp_value;
bool bp_active;
uint32_t bp_address;
uint8_t bp_orig_byte;
} // namespace globals
// Given a kernel-mode virtual address, returns the image base of the
// corresponding module or NULL, if one is not found. Assuming that every
// executed address belongs to a valid PE address at any given time, not finding
// an address should be interpreted as a signal to update the current module
// database.
module_info* find_module(bx_address item) {
unsigned int sz = globals::special_modules.size();
// Prioritize the special_modules list, as it contains the most commonly
// encountered images (e.g. ntoskrnl, win32k for Windows).
for (unsigned int i = 0; i < sz; i++) {
if (globals::special_modules[i]->module_base <= item &&
globals::special_modules[i]->module_base + globals::special_modules[i]->module_size > item) {
return globals::special_modules[i];
}
}
// Search through the remaining known modules.
sz = globals::modules.size();
for (unsigned int i = 0; i < sz; i++) {
if (globals::modules[i]->module_base <= item &&
globals::modules[i]->module_base + globals::modules[i]->module_size > item) {
return globals::modules[i];
}
}
return NULL;
}
// Given a kernel driver name, returns an index of the corresponding module
// descriptor in globals::modules, or -1, if it's not found.
module_info* find_module_by_name(const std::string& module) {
unsigned int sz = globals::special_modules.size();
// Prioritize the special_modules list, as it contains the most commonly
// encountered images (e.g. ntoskrnl, win32k for Windows).
for (unsigned int i = 0; i < sz; i++) {
if (!strcmp(globals::special_modules[i]->module_name, module.c_str())) {
return globals::special_modules[i];
}
}
// Search through the remaining known modules.
sz = globals::modules.size();
for (unsigned int i = 0; i < sz; i++) {
if (!strcmp(globals::modules[i]->module_name, module.c_str())) {
return globals::modules[i];
}
}
return NULL;
}
std::string format_hex(const std::string& data) {
std::string output;
char buffer[256];
for (size_t i = 0; i < data.size(); i += 16) {
snprintf(buffer, sizeof(buffer), "%.8x: ", i);
output += buffer;
for (size_t j = 0; j < 16; j++) {
if (i + j < data.size()) {
snprintf(buffer, sizeof(buffer), "%.2x ", (unsigned char)data[i + j]);
} else {
strncpy(buffer, "?? ", sizeof(buffer));
}
output += buffer;
}
for (size_t j = 0; j < 16; j++) {
if (i + j < data.size() && data[i + j] >= 0x20 && data[i + j] <= 0x7e) {
snprintf(buffer, sizeof(buffer), "%c", data[i + j]);
} else {
strncpy(buffer, ".", sizeof(buffer));
}
output += buffer;
}
output += "\n";
}
return output;
}
const char *translate_mem_access(bug_report_t::mem_access_type type) {
switch (type) {
case bug_report_t::MEM_READ: return "READ";
case bug_report_t::MEM_WRITE: return "WRITE";
case bug_report_t::MEM_EXEC: return "EXEC";
case bug_report_t::MEM_RW: return "R/W";
}
return "INVALID";
}
void invoke_guest_int3(BX_CPU_C *pcpu) {
// Save information about the original code, so that it can be restored when
// the breakpoint fires.
globals::bp_active = true;
globals::bp_address = pcpu->gen_reg[BX_32BIT_REG_EIP].rrx;
globals::bp_orig_byte = 0xcc;
read_lin_mem(pcpu, pcpu->gen_reg[BX_32BIT_REG_EIP].rrx, 1, &globals::bp_orig_byte);
// Overwrite the next instruction with an INT3, which will trigger a
// guest breakpoint.
write_lin_mem(pcpu, pcpu->gen_reg[BX_32BIT_REG_EIP].rrx, 1, (void *)"\xcc");
}
<commit_msg>Update common.cc<commit_after>/////////////////////////////////////////////////////////////////////////
//
// Author: Mateusz Jurczyk (mjurczyk@google.com)
//
// Copyright 2017-2018 Google LLC
//
// 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 "common.h"
#include <set>
#include <vector>
#include "cpu/cpu.h"
#include "logging.pb.h"
#include "symbols.h"
// See instrumentation.h for globals' documentation.
namespace globals {
bochspwn_config config;
std::vector<module_info *> special_modules;
std::vector<module_info *> modules;
std::set<bx_address> known_callstack_item;
bx_address nt_base;
uint8_t *pool_taint_alloc;
uint8_t *stack_taint_alloc;
bool rep_movs;
bool esp_change;
uint32_t esp_value;
bool bp_active;
uint32_t bp_address;
uint8_t bp_orig_byte;
} // namespace globals
// Given a kernel-mode virtual address, returns the image base of the
// corresponding module or NULL, if one is not found. Assuming that every
// executed address belongs to a valid PE address at any given time, not finding
// an address should be interpreted as a signal to update the current module
// database.
module_info* find_module(bx_address item) {
unsigned int sz = globals::special_modules.size();
// Prioritize the special_modules list, as it contains the most commonly
// encountered images (e.g. ntoskrnl, win32k for Windows).
for (unsigned int i = 0; i < sz; i++) {
if (globals::special_modules[i]->module_base <= item &&
globals::special_modules[i]->module_base + globals::special_modules[i]->module_size > item) {
return globals::special_modules[i];
}
}
// Search through the remaining known modules.
sz = globals::modules.size();
for (unsigned int i = 0; i < sz; i++) {
if (globals::modules[i]->module_base <= item &&
globals::modules[i]->module_base + globals::modules[i]->module_size > item) {
return globals::modules[i];
}
}
return NULL;
}
// Given a kernel driver name, returns an index of the corresponding module
// descriptor in globals::modules, or -1, if it's not found.
module_info* find_module_by_name(const std::string& module) {
unsigned int sz = globals::special_modules.size();
// Prioritize the special_modules list, as it contains the most commonly
// encountered images (e.g. ntoskrnl, win32k for Windows).
for (unsigned int i = 0; i < sz; i++) {
if (!strcmp(globals::special_modules[i]->module_name, module.c_str())) {
return globals::special_modules[i];
}
}
// Search through the remaining known modules.
sz = globals::modules.size();
for (unsigned int i = 0; i < sz; i++) {
if (!strcmp(globals::modules[i]->module_name, module.c_str())) {
return globals::modules[i];
}
}
return NULL;
}
std::string format_hex(const std::string& data) {
std::string output;
char buffer[256];
for (size_t i = 0; i < data.size(); i += 16) {
snprintf(buffer, sizeof(buffer), "%.8x: ", i);
output += buffer;
for (size_t j = 0; j < 16; j++) {
if (i + j < data.size()) {
snprintf(buffer, sizeof(buffer), "%.2x ", (unsigned char)data[i + j]);
} else {
strncpy(buffer, "?? ", sizeof(buffer));
}
output += buffer;
}
for (size_t j = 0; j < 16; j++) {
if (i + j < data.size() && data[i + j] >= 0x20 && data[i + j] <= 0x7e) {
snprintf(buffer, sizeof(buffer), "%c", data[i + j]);
} else {
strncpy(buffer, ".", sizeof(buffer));
}
output += buffer;
}
output += "\n";
}
return output;
}
const char *translate_mem_access(bug_report_t::mem_access_type type) {
switch (type) {
case bug_report_t::MEM_READ: return "READ";
case bug_report_t::MEM_WRITE: return "WRITE";
case bug_report_t::MEM_EXEC: return "EXEC";
case bug_report_t::MEM_RW: return "R/W";
}
return "INVALID";
}
void invoke_guest_int3(BX_CPU_C *pcpu) {
// Save information about the original code, so that it can be restored when
// the breakpoint fires.
globals::bp_active = true;
globals::bp_address = pcpu->gen_reg[BX_32BIT_REG_EIP].dword.erx;
globals::bp_orig_byte = 0xcc;
read_lin_mem(pcpu, pcpu->gen_reg[BX_32BIT_REG_EIP].dword.erx, 1, &globals::bp_orig_byte);
// Overwrite the next instruction with an INT3, which will trigger a
// guest breakpoint.
write_lin_mem(pcpu, pcpu->gen_reg[BX_32BIT_REG_EIP].dword.erx, 1, (void *)"\xcc");
}
<|endoftext|>
|
<commit_before>// tsukasa.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int main(int argc, char *argv[])
{
#ifdef _WIN32
_setmode(_fileno(stdin), _O_BINARY);
#endif
int i;
unsigned int j;
int data_pos;
int audio_stream_number = 0;
/* Object ID */
unsigned char asf_stream_bitrate_properties_object[16] = { 0xce, 0x75, 0xf8, 0x7b, 0x8d, 0x46, 0xd1, 0x11, 0x8d, 0x82, 0x00, 0x60, 0x97, 0xc9, 0xa2, 0xb2 };
unsigned char asf_file_properties_object[16] = { 0xa1, 0xdc, 0xab, 0x8c, 0x47, 0xa9, 0xcf, 0x11, 0x8e, 0xe4, 0x00, 0xc0, 0xc, 0x20, 0x53, 0x65 };
unsigned char asf_stream_properties_object[16] = { 0x91, 0x7, 0xdc, 0xb7, 0xb7, 0xa9, 0xcf, 0x11, 0x8e, 0xe6, 0x00, 0xc0, 0xc, 0x20, 0x53, 0x65 };
unsigned char asf_audio_media[16] = { 0x40, 0x9e, 0x69, 0xf8, 0x4d, 0x5b, 0xcf, 0x11, 0xa8, 0xfd, 0x00, 0x80, 0x5f, 0x5c, 0x44, 0x2b };
unsigned char asf_no_error_correction[16] = { 0x00, 0x57, 0xfb, 0x20, 0x55, 0x5b, 0xcf, 0x11, 0xa8, 0xfd, 0x00, 0x80, 0x5f, 0x5c, 0x44, 0x2b };
/* 8bit */
unsigned char framing_header[12];
unsigned char *data;
char bitrate_records[127] = "";
/* 16bit */
unsigned short data_size;
unsigned short old_data_size;
/* 32bit */
unsigned long number_of_header_objects = 0;
unsigned long maximum_bitrate = 0;
unsigned long average_number_of_bytes_per_second = 0;
/* 64bit */
unsigned long long header_object_size = 0;
unsigned long long object_size;
if (argc == 1)
{
exit(EXIT_FAILURE);
}
Poco::URI uri(argv[1]);
Poco::Net::HTTPClientSession client(uri.getHost(), uri.getPort());
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, uri.getPathAndQuery(), Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTTPResponse response;
request.setContentType("application/x-wms-pushsetup");
request.set("Cookie", "push-id=0");
client.sendRequest(request);
client.receiveResponse(response);
std::string cookie = response.get("Set-Cookie");
request.setContentType("application/x-wms-pushstart");
request.set("Cookie", cookie);
/* framing_headerをSTDINから読み込む */
std::cin.read((char *)framing_header, 12);
if (std::cin.gcount() < 12)
{
exit(EXIT_FAILURE);
}
/* PacketIDのエラーチェック */
if (framing_header[0] != '$' || framing_header[1] != 'H')
{
exit(EXIT_FAILURE);
}
/* MMS Data Packetのエラーチェック */
/* LocationIdとIncarnationが0以外はエラー */
for (i = 0; i < 5; i++)
{
if (framing_header[4 + i] != 0)
{
exit(EXIT_FAILURE);
}
}
/* AFFlagsが12以外はエラー */
if (framing_header[9] != 12)
{
exit(EXIT_FAILURE);
}
/* PacketSizeがPacketLengthとサイズが違うとエラー */
for (i = 0; i < 2; i++) {
if (framing_header[10 + i] != framing_header[2 + i])
{
exit(EXIT_FAILURE);
}
}
/* data_sizeを取得、8バイトのMMS Data Packetをdata_sizeから引く */
data_size = 0;
for (i = 0; i < 2; i++)
{
data_size += (unsigned short)framing_header[2 + i] << 8 * i;
}
data_size -= 8;
/* dataにdata_size+792のメモリを確保 */
/* 792はasf_stream_bitrate_properties_objectの最大サイズ(788)とFraming Headerのサイズ(4)の合計 */
/* 788 = 26 + 6 * 127 */
data = new unsigned char[data_size + 792];
std::memcpy(data, framing_header, 2);
/* STDINからデータを読み込む */
std::cin.read((char *)data + 4, data_size);
if (std::cin.gcount() < data_size)
{
exit(EXIT_FAILURE);
}
/* header_object_sizeを取得 */
for (i = 0; i < 8; i++)
{
header_object_size += (unsigned long long)data[20 + i] << 8 * i;
}
/* number_of_header_objectsを取得 */
for (i = 0; i < 4; i++)
{
number_of_header_objects += (unsigned long)data[28 + i] << 8 * i;
}
/* data_posをasf_header_objectの終端に設定 */
data_pos = 34;
for (j = 0; j < number_of_header_objects; j++)
{
/* object_sizeを取得 */
object_size = 0;
for (i = 0; i < 8; i++)
{
object_size += (unsigned long long)data[data_pos + 16 + i] << 8 * i;
}
/* asf_file_properties_objectかどうか */
if (std::memcmp(data + data_pos, asf_file_properties_object, 16) == 0)
{
/* file_idの末端を0xFFにする */
data[data_pos + 39] = 0xFF;
/* maximum_bitrateを取得 */
for (i = 0; i < 4; i++)
{
maximum_bitrate += (unsigned long)data[data_pos + 100 + i] << 8 * i;
}
/* maximum_bitrateが0xFFFFFFFFの場合はmaximum_bitrateに128000を書き込む */
if (maximum_bitrate == 0xFFFFFFFF)
{
maximum_bitrate = 128000;
for (i = 0; i < 4; i++)
{
data[data_pos + 100 + i] = (maximum_bitrate >> 8 * i) & 0xFF;
}
}
}
/* asf_stream_properties_objectかどうか */
if (std::memcmp(data + data_pos, asf_stream_properties_object, 16) == 0)
{
/* stream_typeがasf_audio_mediaかどうか */
if (std::memcmp(data + data_pos + 24, asf_audio_media, 16) == 0)
{
/* error_correction_typeをasf_no_error_correctionに設定 */
std::memcpy(data + data_pos + 40, asf_no_error_correction, 16);
/* average_number_of_bytes_per_secondを取得 */
average_number_of_bytes_per_second = 0;
for (i = 0; i < 4; i++)
{
average_number_of_bytes_per_second += (unsigned long)data[data_pos + 86 + i] << 8 * i;
}
/* average_number_of_bytes_per_secondが0の場合はaverage_number_of_bytes_per_secondに16000を書き込む※MP3のVBR対応のために必要 */
if (average_number_of_bytes_per_second == 0)
{
average_number_of_bytes_per_second = 16000;
for (i = 0; i < 4; i++)
{
data[data_pos + 86 + i] = (average_number_of_bytes_per_second >> 8 * i) & 0xFF;
}
}
audio_stream_number = data[data_pos + 72];
}
/* bitrate_recordsにstream_numberを追加 */
bitrate_records[std::strlen(bitrate_records)] = data[data_pos + 72];
}
/* data_posにobject_sizeを加算 */
data_pos += (int)object_size;
}
/* asf_data_object */
/* file_idの末端を0xFFにする※これをしないとKagaminにPush出来ない */
data[data_pos + 39] = 0xFF;
/* asf_stream_bitrate_properties_objectを作成 */
object_size = 26 + 6 * std::strlen(bitrate_records);
/* asf_stream_bitrate_properties_objectの領域を確保 */
std::memmove(data + data_pos + object_size, data + data_pos, data_size + 4 - data_pos);
/* object_idを書き込む */
for (i = 0; i < 16; i++)
{
data[data_pos + i] = asf_stream_bitrate_properties_object[i];
}
/* object_sizeを書き込む */
for (i = 0; i < 8; i++)
{
data[data_pos + 16 + i] = (object_size >> 8 * i) & 0xFF;
}
/* bitrate_records_countを書き込む */
for (i = 0; i < 2; i++)
{
data[data_pos + 24 + i] = (std::strlen(bitrate_records) >> 8 * i) & 0xFF;
}
/* bitrate_recordsを書き込む */
for (j = 0; j < strlen(bitrate_records); j++)
{
/* stream_numberを書き込む */
data[data_pos + 26 + j * 6] = bitrate_records[j];
/* reservedを書き込む */
data[data_pos + 27 + j * 6] = 0;
/* average_bitrateを書き込む */
if (bitrate_records[j] == audio_stream_number)
{
for (i = 0; i < 4; i++)
{
data[data_pos + 28 + i + j * 6] = ((average_number_of_bytes_per_second * 8) >> 8 * i) & 0xFF;
}
}
else
{
for (i = 0; i < 4; i++)
{
data[data_pos + 28 + i + j * 6] = ((maximum_bitrate - average_number_of_bytes_per_second * 8) >> 8 * i) & 0xFF;
}
}
}
/* 各種サイズを更新 */
number_of_header_objects += 1;
header_object_size += object_size;
data_size += (unsigned short)object_size;
/* 新しいnumber_of_header_objectsを書き込む */
for (i = 0; i < 4; i++)
{
data[28 + i] = (number_of_header_objects >> 8 * i) & 0xFF;
}
/* 新しいheader_object_sizeを書き込む */
for (i = 0; i < 8; i++)
{
data[20 + i] = (header_object_size >> 8 * i) & 0xFF;
}
/* 新しいdata_sizeを書き込む */
for (i = 0; i < 2; i++)
{
data[2 + i] = (data_size >> 8 * i) & 0xFF;
}
/* pushstartを送信 */
std::ostream &os = client.sendRequest(request);
os.write((char *)data, data_size + 4);
os.flush();
/* old_data_sizeにdata_sizeの値を入れる */
old_data_size = data_size;
/* $D */
while (true)
{
/* framing_headerをSTDINから読み込む */
std::cin.read((char *)framing_header, 12);
if (std::cin.gcount() < 12)
{
exit(EXIT_FAILURE);
}
/* PacketIDのエラーチェック */
if (framing_header[0] != '$' || (framing_header[1] != 'D' && framing_header[1] != 'E'))
{
exit(EXIT_FAILURE);
}
/* MMS Data Packetのエラーチェック */
/* IncarnationとAFFlagsが0以外はエラー */
for (i = 0; i < 2; i++)
{
if (framing_header[8 + i] != 0)
{
exit(EXIT_FAILURE);
}
}
/* PacketSizeがPacketLengthとサイズが違うとエラー */
for (i = 0; i < 2; i++)
{
if (framing_header[10 + i] != framing_header[2 + i])
{
exit(EXIT_FAILURE);
}
}
/* data_sizeを取得、8バイトのMMS Data Packetをdata_sizeから引く */
data_size = 0;
for (i = 0; i < 2; i++)
{
data_size += (unsigned short)framing_header[2 + i] << 8 * i;
}
data_size -= 8;
/* data_sizeとold_data_sizeが違う場合は新しくメモリを確保 */
if (data_size != old_data_size)
{
/* dataのメモリを開放 */
delete[] data;
/* dataにdata_size+4(Framing Headerのサイズ)のメモリを確保 */
data = new unsigned char[data_size + 4];
}
/* framing_headerをdataにコピー */
std::memcpy(data, framing_header, 2);
/* 新しいdata_sizeを書き込む */
for (i = 0; i < 2; i++)
{
data[2 + i] = (data_size >> 8 * i) & 0xFF;
}
/* STDINからデータを読み込む */
std::cin.read((char *)data + 4, data_size);
if (std::cin.gcount() < data_size)
{
exit(EXIT_FAILURE);
}
/* dataを送信 */
os.write((char *)data, data_size + 4);
os.flush();
/* old_data_sizeにdata_sizeの値を入れる */
old_data_size = data_size;
/* PacketIDが$Eだったら終了 */
if (framing_header[1] == 'E')
{
break;
}
}
return EXIT_SUCCESS;
}
<commit_msg>標準入力から入力があってからリクエストするようにした<commit_after>// tsukasa.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int main(int argc, char *argv[])
{
#ifdef _WIN32
_setmode(_fileno(stdin), _O_BINARY);
#endif
int i;
unsigned int j;
int data_pos;
int audio_stream_number = 0;
/* Object ID */
unsigned char asf_stream_bitrate_properties_object[16] = { 0xce, 0x75, 0xf8, 0x7b, 0x8d, 0x46, 0xd1, 0x11, 0x8d, 0x82, 0x00, 0x60, 0x97, 0xc9, 0xa2, 0xb2 };
unsigned char asf_file_properties_object[16] = { 0xa1, 0xdc, 0xab, 0x8c, 0x47, 0xa9, 0xcf, 0x11, 0x8e, 0xe4, 0x00, 0xc0, 0xc, 0x20, 0x53, 0x65 };
unsigned char asf_stream_properties_object[16] = { 0x91, 0x7, 0xdc, 0xb7, 0xb7, 0xa9, 0xcf, 0x11, 0x8e, 0xe6, 0x00, 0xc0, 0xc, 0x20, 0x53, 0x65 };
unsigned char asf_audio_media[16] = { 0x40, 0x9e, 0x69, 0xf8, 0x4d, 0x5b, 0xcf, 0x11, 0xa8, 0xfd, 0x00, 0x80, 0x5f, 0x5c, 0x44, 0x2b };
unsigned char asf_no_error_correction[16] = { 0x00, 0x57, 0xfb, 0x20, 0x55, 0x5b, 0xcf, 0x11, 0xa8, 0xfd, 0x00, 0x80, 0x5f, 0x5c, 0x44, 0x2b };
/* 8bit */
unsigned char framing_header[12];
unsigned char *data;
char bitrate_records[127] = "";
/* 16bit */
unsigned short data_size;
unsigned short old_data_size;
/* 32bit */
unsigned long number_of_header_objects = 0;
unsigned long maximum_bitrate = 0;
unsigned long average_number_of_bytes_per_second = 0;
/* 64bit */
unsigned long long header_object_size = 0;
unsigned long long object_size;
if (argc == 1)
{
exit(EXIT_FAILURE);
}
/* framing_headerをSTDINから読み込む */
std::cin.read((char *)framing_header, 12);
if (std::cin.gcount() < 12)
{
exit(EXIT_FAILURE);
}
/* PacketIDのエラーチェック */
if (framing_header[0] != '$' || framing_header[1] != 'H')
{
exit(EXIT_FAILURE);
}
/* MMS Data Packetのエラーチェック */
/* LocationIdとIncarnationが0以外はエラー */
for (i = 0; i < 5; i++)
{
if (framing_header[4 + i] != 0)
{
exit(EXIT_FAILURE);
}
}
/* AFFlagsが12以外はエラー */
if (framing_header[9] != 12)
{
exit(EXIT_FAILURE);
}
/* PacketSizeがPacketLengthとサイズが違うとエラー */
for (i = 0; i < 2; i++) {
if (framing_header[10 + i] != framing_header[2 + i])
{
exit(EXIT_FAILURE);
}
}
/* data_sizeを取得、8バイトのMMS Data Packetをdata_sizeから引く */
data_size = 0;
for (i = 0; i < 2; i++)
{
data_size += (unsigned short)framing_header[2 + i] << 8 * i;
}
data_size -= 8;
/* dataにdata_size+792のメモリを確保 */
/* 792はasf_stream_bitrate_properties_objectの最大サイズ(788)とFraming Headerのサイズ(4)の合計 */
/* 788 = 26 + 6 * 127 */
data = new unsigned char[data_size + 792];
std::memcpy(data, framing_header, 2);
/* STDINからデータを読み込む */
std::cin.read((char *)data + 4, data_size);
if (std::cin.gcount() < data_size)
{
exit(EXIT_FAILURE);
}
/* header_object_sizeを取得 */
for (i = 0; i < 8; i++)
{
header_object_size += (unsigned long long)data[20 + i] << 8 * i;
}
/* number_of_header_objectsを取得 */
for (i = 0; i < 4; i++)
{
number_of_header_objects += (unsigned long)data[28 + i] << 8 * i;
}
/* data_posをasf_header_objectの終端に設定 */
data_pos = 34;
for (j = 0; j < number_of_header_objects; j++)
{
/* object_sizeを取得 */
object_size = 0;
for (i = 0; i < 8; i++)
{
object_size += (unsigned long long)data[data_pos + 16 + i] << 8 * i;
}
/* asf_file_properties_objectかどうか */
if (std::memcmp(data + data_pos, asf_file_properties_object, 16) == 0)
{
/* file_idの末端を0xFFにする */
data[data_pos + 39] = 0xFF;
/* maximum_bitrateを取得 */
for (i = 0; i < 4; i++)
{
maximum_bitrate += (unsigned long)data[data_pos + 100 + i] << 8 * i;
}
/* maximum_bitrateが0xFFFFFFFFの場合はmaximum_bitrateに128000を書き込む */
if (maximum_bitrate == 0xFFFFFFFF)
{
maximum_bitrate = 128000;
for (i = 0; i < 4; i++)
{
data[data_pos + 100 + i] = (maximum_bitrate >> 8 * i) & 0xFF;
}
}
}
/* asf_stream_properties_objectかどうか */
if (std::memcmp(data + data_pos, asf_stream_properties_object, 16) == 0)
{
/* stream_typeがasf_audio_mediaかどうか */
if (std::memcmp(data + data_pos + 24, asf_audio_media, 16) == 0)
{
/* error_correction_typeをasf_no_error_correctionに設定 */
std::memcpy(data + data_pos + 40, asf_no_error_correction, 16);
/* average_number_of_bytes_per_secondを取得 */
average_number_of_bytes_per_second = 0;
for (i = 0; i < 4; i++)
{
average_number_of_bytes_per_second += (unsigned long)data[data_pos + 86 + i] << 8 * i;
}
/* average_number_of_bytes_per_secondが0の場合はaverage_number_of_bytes_per_secondに16000を書き込む※MP3のVBR対応のために必要 */
if (average_number_of_bytes_per_second == 0)
{
average_number_of_bytes_per_second = 16000;
for (i = 0; i < 4; i++)
{
data[data_pos + 86 + i] = (average_number_of_bytes_per_second >> 8 * i) & 0xFF;
}
}
audio_stream_number = data[data_pos + 72];
}
/* bitrate_recordsにstream_numberを追加 */
bitrate_records[std::strlen(bitrate_records)] = data[data_pos + 72];
}
/* data_posにobject_sizeを加算 */
data_pos += (int)object_size;
}
/* asf_data_object */
/* file_idの末端を0xFFにする※これをしないとKagaminにPush出来ない */
data[data_pos + 39] = 0xFF;
/* asf_stream_bitrate_properties_objectを作成 */
object_size = 26 + 6 * std::strlen(bitrate_records);
/* asf_stream_bitrate_properties_objectの領域を確保 */
std::memmove(data + data_pos + object_size, data + data_pos, data_size + 4 - data_pos);
/* object_idを書き込む */
for (i = 0; i < 16; i++)
{
data[data_pos + i] = asf_stream_bitrate_properties_object[i];
}
/* object_sizeを書き込む */
for (i = 0; i < 8; i++)
{
data[data_pos + 16 + i] = (object_size >> 8 * i) & 0xFF;
}
/* bitrate_records_countを書き込む */
for (i = 0; i < 2; i++)
{
data[data_pos + 24 + i] = (std::strlen(bitrate_records) >> 8 * i) & 0xFF;
}
/* bitrate_recordsを書き込む */
for (j = 0; j < strlen(bitrate_records); j++)
{
/* stream_numberを書き込む */
data[data_pos + 26 + j * 6] = bitrate_records[j];
/* reservedを書き込む */
data[data_pos + 27 + j * 6] = 0;
/* average_bitrateを書き込む */
if (bitrate_records[j] == audio_stream_number)
{
for (i = 0; i < 4; i++)
{
data[data_pos + 28 + i + j * 6] = ((average_number_of_bytes_per_second * 8) >> 8 * i) & 0xFF;
}
}
else
{
for (i = 0; i < 4; i++)
{
data[data_pos + 28 + i + j * 6] = ((maximum_bitrate - average_number_of_bytes_per_second * 8) >> 8 * i) & 0xFF;
}
}
}
/* 各種サイズを更新 */
number_of_header_objects += 1;
header_object_size += object_size;
data_size += (unsigned short)object_size;
/* 新しいnumber_of_header_objectsを書き込む */
for (i = 0; i < 4; i++)
{
data[28 + i] = (number_of_header_objects >> 8 * i) & 0xFF;
}
/* 新しいheader_object_sizeを書き込む */
for (i = 0; i < 8; i++)
{
data[20 + i] = (header_object_size >> 8 * i) & 0xFF;
}
/* 新しいdata_sizeを書き込む */
for (i = 0; i < 2; i++)
{
data[2 + i] = (data_size >> 8 * i) & 0xFF;
}
Poco::URI uri(argv[1]);
Poco::Net::HTTPClientSession client(uri.getHost(), uri.getPort());
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, uri.getPathAndQuery(), Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTTPResponse response;
request.setContentType("application/x-wms-pushsetup");
request.set("Cookie", "push-id=0");
client.sendRequest(request);
client.receiveResponse(response);
std::string cookie = response.get("Set-Cookie");
request.setContentType("application/x-wms-pushstart");
request.set("Cookie", cookie);
/* pushstartを送信 */
std::ostream &os = client.sendRequest(request);
os.write((char *)data, data_size + 4);
os.flush();
/* old_data_sizeにdata_sizeの値を入れる */
old_data_size = data_size;
/* $D */
while (true)
{
/* framing_headerをSTDINから読み込む */
std::cin.read((char *)framing_header, 12);
if (std::cin.gcount() < 12)
{
exit(EXIT_FAILURE);
}
/* PacketIDのエラーチェック */
if (framing_header[0] != '$' || (framing_header[1] != 'D' && framing_header[1] != 'E'))
{
exit(EXIT_FAILURE);
}
/* MMS Data Packetのエラーチェック */
/* IncarnationとAFFlagsが0以外はエラー */
for (i = 0; i < 2; i++)
{
if (framing_header[8 + i] != 0)
{
exit(EXIT_FAILURE);
}
}
/* PacketSizeがPacketLengthとサイズが違うとエラー */
for (i = 0; i < 2; i++)
{
if (framing_header[10 + i] != framing_header[2 + i])
{
exit(EXIT_FAILURE);
}
}
/* data_sizeを取得、8バイトのMMS Data Packetをdata_sizeから引く */
data_size = 0;
for (i = 0; i < 2; i++)
{
data_size += (unsigned short)framing_header[2 + i] << 8 * i;
}
data_size -= 8;
/* data_sizeとold_data_sizeが違う場合は新しくメモリを確保 */
if (data_size != old_data_size)
{
/* dataのメモリを開放 */
delete[] data;
/* dataにdata_size+4(Framing Headerのサイズ)のメモリを確保 */
data = new unsigned char[data_size + 4];
}
/* framing_headerをdataにコピー */
std::memcpy(data, framing_header, 2);
/* 新しいdata_sizeを書き込む */
for (i = 0; i < 2; i++)
{
data[2 + i] = (data_size >> 8 * i) & 0xFF;
}
/* STDINからデータを読み込む */
std::cin.read((char *)data + 4, data_size);
if (std::cin.gcount() < data_size)
{
exit(EXIT_FAILURE);
}
/* dataを送信 */
os.write((char *)data, data_size + 4);
os.flush();
/* old_data_sizeにdata_sizeの値を入れる */
old_data_size = data_size;
/* PacketIDが$Eだったら終了 */
if (framing_header[1] == 'E')
{
break;
}
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*=============================================================================
Copyright (c) 2012-2014 Richard Otis
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// N-Dimensional Simplex Lattice
#ifndef INCLUDED_NDSIMPLEX
#define INCLUDED_NDSIMPLEX
#include "libgibbs/include/optimizer/halton.hpp"
#include <vector>
#include <utility>
#include <algorithm>
struct NDSimplex {
template <typename Func> static void sample(
const std::vector<std::pair<double,double> > &extents,
const double grid_points_per_major_axis,
const Func &func,
std::vector<double>& address,
double sum_of_address = 0) {
if (address.size() == extents.size()) {
// terminating condition; address is complete
func(address);
}
else {
const double max_extent = std::min(extents[address.size()].second, 1 - sum_of_address);
const double min_extent = extents[address.size()].first;
double step = (max_extent - min_extent) / grid_points_per_major_axis;
for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
double location = step*j + min_extent;
if (sum_of_address + location >= 1) {
// Force the last coordinate onto the simplex face
location = std::max(1 - sum_of_address,0.);
address.push_back(location);
// Make the remaining coordinates all zero
std::size_t added_elements = extents.size() - address.size();
while (address.size() < extents.size()) address.push_back(0);
// Perform callback
func(address);
// Remove extra elements
while (added_elements--) address.pop_back();
// Remove the element we forced onto the simplex face
address.pop_back();
// No more coordinates to handle in this iteration
break;
}
else {
address.push_back(location);
// recursive step
NDSimplex::sample(extents, grid_points_per_major_axis, func, address, sum_of_address + location);
address.pop_back(); // remove the element we just added (this way avoids copying)
if (step == 0) break; // don't generate duplicate points
}
}
}
}
template <typename Func> static inline void sample(
const std::vector<std::pair<double,double> > &extents,
const double grid_points_per_major_axis,
const Func &func) {
std::vector<double> address;
NDSimplex::sample(extents, grid_points_per_major_axis, func, address, 0);
}
template <typename Func> static inline void quasirandom_sample (
const unsigned int point_dimension,
const unsigned int number_of_points,
const Func &func
) {
// TODO: add the shuffling part
for (auto sequence_pos = 1; sequence_pos <= point_dimension; ++sequence_pos) {
std::vector<double> point;
double point_sum = 0;
for (auto i = 0; i < number_of_points; ++i) {
// Give the coordinate an exponential distribution
double value = -log(halton(sequence_pos,primes[i]));
point_sum += value;
point.push_back(value);
}
for (auto i = point.begin(); i != point.end(); ++i) *i /= point_sum; // Normalize point to sum to 1
func(point);
}
}
};
#endif
<commit_msg>Implementation of Chasalow and Brand's simplex lattice generation algorithm<commit_after>/*=============================================================================
Copyright (c) 2012-2014 Richard Otis
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// N-Dimensional Simplex Point Generation
#ifndef INCLUDED_NDSIMPLEX
#define INCLUDED_NDSIMPLEX
#include "libgibbs/include/optimizer/halton.hpp"
#include <boost/assert.hpp>
#include <vector>
#include <utility>
#include <algorithm>
struct NDSimplex {
// Reference: Chasalow and Brand, 1995, "Algorithm AS 299: Generation of Simplex Lattice Points"
template <typename Func> static inline void lattice (
const std::size_t point_dimension,
const std::size_t grid_points_per_major_axis,
const Func &func
) {
BOOST_ASSERT(grid_points_per_major_axis >= 2);
BOOST_ASSERT(point_dimension >= 1);
typedef std::vector<double> PointType;
const double lattice_spacing = 1.0 / (double)grid_points_per_major_axis;
const PointType::value_type lower_limit = 0;
const PointType::value_type upper_limit = 1;
PointType point; // Contains current point
PointType::iterator coord_find;
// Special case: 1 component; only valid point is {1}
if (point_dimension == 1) {
point.push_back(1);
func(point);
return;
}
// Initialize algorithm
point.resize(point_dimension, lower_limit); // Fill with smallest value (0)
const PointType::const_iterator last_coord = --point.cend();
coord_find = point.begin();
*coord_find = upper_limit;
// point should now be {1,0,0,0....}
double point_sum;
do {
point_sum = *coord_find; // point_sum always includes the active coordinate
PointType::iterator temp_coord_find = coord_find;
for (auto i = point.begin(); i != coord_find; ++i) point_sum += *i; // sum all previous coordinates (if any)
std::advance(temp_coord_find,1);
if (temp_coord_find != point.end()) {
*temp_coord_find = upper_limit - point_sum; // Set coord_find+1 to its upper limit (1 - sum of previous coordinates)
std::advance(temp_coord_find,1);
}
for (auto i = temp_coord_find; i != point.end(); ++i) *i = lower_limit; // set remaining coordinates to 0
func(point); // process the current point
// coord_find points to the coordinate to be decremented
coord_find = point.begin();
while (*coord_find == lower_limit) std::advance(coord_find,1);
*coord_find -= lattice_spacing;
if (*coord_find < lattice_spacing) *coord_find = lower_limit; // workaround for floating point issues
}
while (coord_find != last_coord || point_sum > 0);
}
template <typename Func> static inline void quasirandom_sample (
const std::size_t point_dimension,
const std::size_t number_of_points,
const Func &func
) {
// TODO: Add the shuffling part to the Halton sequence. This will help with correlation problems for large N
// TODO: Default-add the end-members (vertices) of the N-simplex
for (auto sequence_pos = 1; sequence_pos <= number_of_points; ++sequence_pos) {
std::vector<double> point;
double point_sum = 0;
for (auto i = 0; i < point_dimension; ++i) {
// Draw the coordinate from an exponential distribution
// N samples from the exponential distribution, when normalized to 1, will be distributed uniformly
// on the N-simplex.
// If X is uniformly distributed, then -LN(X) is exponentially distributed.
// Since the Halton sequence is a low-discrepancy sequence over (0,1], we substitute it for the uniform distribution
// This makes this algorithm deterministic and may also provide some domain coverage advantages over a
// psuedo-random sample.
double value = -log(halton(sequence_pos,primes[i]));
point_sum += value;
point.push_back(value);
}
for (auto i = point.begin(); i != point.end(); ++i) *i /= point_sum; // Normalize point to sum to 1
func(point);
if (point_dimension == 1) break; // no need to generate additional points; only one feasible point exists for 1-simplex
}
}
};
#endif
<|endoftext|>
|
<commit_before>#include <coffee/CCore>
#include <coffee/graphics_apis/CGLeam>
#include <coffee/COpenVR>
#include <coffee/CGraphics>
using namespace Coffee;
using namespace CDisplay;
using GL = CGL::CGL43;
class CDRenderer : public Coffee::CDisplay::CGLeamRenderer
{
public:
CDRenderer()
: CGLeamRenderer(0)
{
}
void run()
{
CElapsedTimerD* timer = AllocTimerD();
timer->start();
CSize winSize = this->windowSize();
winSize.w = winSize.w/2;
CRectF leftEye;
CRectF rightEye;
leftEye.x = 0;
leftEye.y = 0;
leftEye.w = winSize.w;
leftEye.h = winSize.h;
rightEye.x = winSize.w;
rightEye.y = 0;
rightEye.w = winSize.w;
rightEye.h = winSize.h;
CVec4 clearcol(0.0);
clearcol.a() = 1.0;
// GLEXT::ViewportSet(0,&leftEye);
// GLEXT::ViewportSet(1,&rightEye);
GL::Enable(GL::Feature::Blend);
// GL::Enable(GL::Feature::DepthTest);
const cstring textures[3] = {"eye-normal.tga","eye-weird.tga","eye-alpha.tga"};
GL::CGhnd pbobuf[3] = {};
GL::BufAlloc(3,pbobuf);
for(uint32 i=0;i<3;i++)
{
CResources::CResource rsc(textures[i]);
CResources::FileMap(rsc);
CStbImageLib::CStbImage img;
CStbImageLib::LoadData(&img,&rsc);
GL::BufBind(GL::BufType::PixelUData,pbobuf[i]);
GL::BufStorage(GL::BufType::PixelUData,
img.size.area()*img.bpp,
img.data,ResourceAccess::ReadOnly);
CResources::CResource out("test.png");
CStbImageLib::SavePNG(&out,&img);
CResources::FileCommit(out);
CResources::FileFree(out);
CStbImageLib::ImageFree(&img);
CResources::FileUnmap(rsc);
}
const scalar vertexdata[] = {
-1.f, -1.f, 1.f, 0.f, 0.f,
1.f, -1.f, 1.f, -1.f, 0.f,
-1.f, 1.f, 1.f, 0.f, -1.f,
-1.f, 1.f, 1.f, 0.f, -1.f,
1.f, 1.f, 1.f, -1.f, -1.f,
1.f, -1.f, 1.f, -1.f, 0.f,
};
GL::CGhnd vertbuf;
GL::BufAlloc(1,&vertbuf);
GL::BufBind(GL::BufType::ArrayData,vertbuf);
GL::BufData(GL::BufType::ArrayData,sizeof(vertexdata),vertexdata,ResourceAccess::ReadOnly);
cstring vshader = {
"#version 430 core\n"
""
"layout(location=0)in vec3 pos;"
"layout(location=1)in vec2 tex;"
""
"out gl_PerVertex{"
" vec4 gl_Position;"
"};"
"out VS_OUT{"
" vec2 tc;"
" flat int instance;"
"} vs_out;"
""
"uniform mat4 transform[2];"
"uniform vec2 tex_mul[2];"
""
"void main(void)"
"{"
" vs_out.instance = gl_InstanceID;"
" vs_out.tc = tex*tex_mul[gl_InstanceID];"
" gl_Position = transform[gl_InstanceID]*vec4(pos,1.0);"
"}"
};
cstring fshader = {
"#version 430 core\n"
"in VS_OUT{"
" vec2 tc;"
" flat int instance;"
"} fs_in;"
""
"layout(location = 0) out vec4 color;"
"uniform float mx;"
""
"uniform sampler2DArray texdata;"
""
"void main(void)"
"{"
" vec4 c1 = texture(texdata,vec3(fs_in.tc,0));"
" vec4 c2 = texture(texdata,vec3(fs_in.tc,1));"
" float a1 = texture(texdata,vec3(fs_in.tc,2)).a;"
" if(mx>a1)"
" color = c1;"
" else"
" color = c2;"
"}"
};
GL::CGhnd vao;
GL::VAOAlloc(1,&vao);
GL::VAOBind(vao);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
GL::VAOAttribFormat(0,3,TypeEnum::Scalar,false,0);
GL::VAOAttribFormat(1,2,TypeEnum::Scalar,false,0);
GL::VAOBindVertexBuffer(0,vertbuf,0,sizeof(CVec3)+sizeof(CVec2));
GL::VAOBindVertexBuffer(1,vertbuf,sizeof(CVec3),sizeof(CVec3)+sizeof(CVec2));
GL::VAOAttribBinding(0,0);
GL::VAOAttribBinding(1,1);
GL::CGhnd vprogram = GL::ProgramCreate(GL::ShaderStage::Vertex,1,&vshader);
cDebug("Compilation log: {0}",GL::ProgramGetLog(vprogram));
GL::CGhnd fprogram = GL::ProgramCreate(GL::ShaderStage::Fragment,1,&fshader);
cDebug("Compilation log: {0}",GL::ProgramGetLog(fprogram));
GL::CGhnd pipeline;
GL::PipelineAlloc(1,&pipeline);
GL::PipelineUseStages(pipeline,GL::ShaderStage::Vertex,vprogram);
GL::PipelineUseStages(pipeline,GL::ShaderStage::Fragment,fprogram);
GL::PipelineBind(pipeline);
GL::ShaderReleaseCompiler();
if(!GL::PipelineValidate(pipeline))
return;
GL::CGhnd texture_array;
GL::TexAlloc(1,&texture_array);
GL::TexActive(0);
GL::TexBind(GL::Texture::T2DArray,texture_array);
GL::TexStorage3D(GL::Texture::T2DArray,1,PixelFormat::RGBA32F,1024,1024,3);
for(uint32 i=0;i<3;i++)
{
GL::BufBind(GL::BufType::PixelUData,pbobuf[i]);
GL::TexSubImage3D(GL::Texture::T2DArray,0,
0,0,i,1024,1024,1,
PixelComponents::RGBA,BitFormat::UByte,nullptr);
}
CGraphicsData::CGCamera cam;
cam.aspect = 1.6;
cam.fieldOfView = 70.f;
cam.position = CVec3(0,0,-3);
CGraphicsData::CTransform obj;
obj.position = CVec3(-1,0,0);
obj.scale = CVec3(1);
int32 cam_unif = GL::ProgramGetResourceLoc(vprogram,GL_UNIFORM,"transform");
int32 texm_unif = GL::ProgramGetResourceLoc(vprogram,GL_UNIFORM,"tex_mul");
int32 tex_unif = GL::ProgramGetResourceLoc(fprogram,GL_UNIFORM,"texdata");
int32 tim_unif = GL::ProgramGetResourceLoc(fprogram,GL_UNIFORM,"mx");
int32 tex_bind = 0;
CMat4 cam_mat = CGraphicsData::GenPerspective(cam)
*CGraphicsData::GenTransform(cam);
CMat4 objects[2] = {};
objects[0] = cam_mat*CGraphicsData::GenTransform(obj);
obj.position = CVec3(1,0,0);
objects[1] = cam_mat*CGraphicsData::GenTransform(obj);
CVec2 tex_mul[2] = {};
tex_mul[0] = CVec2(1,1);
tex_mul[1] = CVec2(-1,1);
GL::Uniformfv(vprogram,cam_unif,2,false,objects);
GL::Uniformfv(vprogram,texm_unif,2,tex_mul);
GL::Uniformiv(fprogram,tex_unif,1,&tex_bind);
cDebug("Setup time: {0}",timer->elapsed());
scalar depth_zero = 0.f;
bool cycle_color = false;
while(!closeFlag())
{
if(cycle_color)
{
clearcol.r() = CMath::sin(this->contextTime()+0.5);
clearcol.g() = CMath::sin(this->contextTime()+5.0);
clearcol.b() = CMath::sin(this->contextTime()+50.0);
}
scalar time = CMath::fmod(CMath::sin(this->contextTime()),1.0);
GL::Uniformfv(fprogram,tim_unif,1,&time);
clearcol = normalize(clearcol);
GL::ClearBufferfv(true,0,clearcol);
GL::ClearBufferfv(false,0,&depth_zero);
GL::DrawArraysInstanced(GL_TRIANGLES,0,6,2);
this->pollEvents();
this->swapBuffers();
}
//Write code here
}
void eventHandleD(const CDisplay::CDEvent &e, c_cptr data)
{
CSDL2Renderer::eventHandleD(e,data);
if(e.type==CDisplay::CDEvent::Resize)
{
auto rev = (const CDisplay::CDResizeEvent*)data;
CRectF view;
view.x = 0;
view.y = 0;
view.w = rev->w;
view.h = rev->h;
GL::ViewportSet(0,&view);
}
}
void eventHandleI(const CIEvent &e, c_cptr data)
{
CSDL2Renderer::eventHandleI(e,data);
switch(e.type)
{
case CIEvent::Keyboard:
{
const CIKeyEvent* kev = (const CIKeyEvent*)data;
switch(kev->key)
{
case CK_Escape:
this->closeWindow();
break;
default:
break;
}
break;
}
default:
break;
}
}
};
int32 coffee_main(int32, cstring_w*)
{
if(!OpenVRDev::InitializeBinding())
{
cDebug("Move on, there is nothing to see here.");
}else{
cDebug("By the gods... So it was true! You must be the hero of Kvatch!");
cDebug("[HERE BE DRAGONS]");
uint32 devs;
if(!OpenVRDev::PollDevices(&devs))
{
cDebug("I used to be a reality tripper like you,"
" until I took a cyberkick to the knee.");
}
OpenVRDev::OVRDevice* dev = OpenVRDev::GetDevice(0);
cDebug("What you got: {0}",(const HWDeviceInfo&)*dev);
}
CResources::FileResourcePrefix("sample_data/");
CElapsedTimerD* timer = AllocTimerD();
timer->start();
CSDL2Renderer *renderer = new CDRenderer();
cDebug("Allocated renderer: {0}",timer->elapsed());
CDProperties props = GetDefaultVisual();
props.gl.flags = props.gl.flags|GLProperties::GLDebug;
props.gl.version.major = 4;
props.gl.version.minor = 3;
renderer->init(props);
cDebug("Init renderer: {0}",timer->elapsed());
if(!GL::SeparableShaderSupported())
return 1;
if(!GL::ViewportArraySupported())
return 1;
if(!GL::BufferStorageSupported())
return 1;
renderer->run();
timer->start();
renderer->cleanup();
delete renderer;
cDebug("Cleanup renderer: {0}",timer->elapsed());
return 0;
}
COFFEE_APPLICATION_MAIN(coffee_main)
<commit_msg> - Minor addition of using abstracted function<commit_after>#include <coffee/CCore>
#include <coffee/graphics_apis/CGLeam>
#include <coffee/COpenVR>
#include <coffee/CGraphics>
using namespace Coffee;
using namespace CDisplay;
using GL = CGL::CGL43;
class CDRenderer : public Coffee::CDisplay::CGLeamRenderer
{
public:
CDRenderer()
: CGLeamRenderer(0)
{
}
void run()
{
CElapsedTimerD* timer = AllocTimerD();
timer->start();
CSize winSize = this->windowSize();
winSize.w = winSize.w/2;
CRectF leftEye;
CRectF rightEye;
leftEye.x = 0;
leftEye.y = 0;
leftEye.w = winSize.w;
leftEye.h = winSize.h;
rightEye.x = winSize.w;
rightEye.y = 0;
rightEye.w = winSize.w;
rightEye.h = winSize.h;
CVec4 clearcol(0.0);
clearcol.a() = 1.0;
// GLEXT::ViewportSet(0,&leftEye);
// GLEXT::ViewportSet(1,&rightEye);
GL::Enable(GL::Feature::Blend);
// GL::Enable(GL::Feature::DepthTest);
const cstring textures[3] = {"eye-normal.tga","eye-weird.tga","eye-alpha.tga"};
GL::CGhnd pbobuf[3] = {};
GL::BufAlloc(3,pbobuf);
for(uint32 i=0;i<3;i++)
{
CResources::CResource rsc(textures[i]);
CResources::FileMap(rsc);
CStbImageLib::CStbImage img;
CStbImageLib::LoadData(&img,&rsc);
GL::BufBind(GL::BufType::PixelUData,pbobuf[i]);
GL::BufStorage(GL::BufType::PixelUData,
img.size.area()*img.bpp,
img.data,ResourceAccess::ReadOnly);
CResources::CResource out("test.png");
CStbImageLib::SavePNG(&out,&img);
CResources::FileCommit(out);
CResources::FileFree(out);
CStbImageLib::ImageFree(&img);
CResources::FileUnmap(rsc);
}
const scalar vertexdata[] = {
-1.f, -1.f, 1.f, 0.f, 0.f,
1.f, -1.f, 1.f, -1.f, 0.f,
-1.f, 1.f, 1.f, 0.f, -1.f,
-1.f, 1.f, 1.f, 0.f, -1.f,
1.f, 1.f, 1.f, -1.f, -1.f,
1.f, -1.f, 1.f, -1.f, 0.f,
};
GL::CGhnd vertbuf;
GL::BufAlloc(1,&vertbuf);
GL::BufBind(GL::BufType::ArrayData,vertbuf);
GL::BufData(GL::BufType::ArrayData,sizeof(vertexdata),vertexdata,ResourceAccess::ReadOnly);
cstring vshader = {
"#version 430 core\n"
""
"layout(location=0)in vec3 pos;"
"layout(location=1)in vec2 tex;"
""
"out gl_PerVertex{"
" vec4 gl_Position;"
"};"
"out VS_OUT{"
" vec2 tc;"
" flat int instance;"
"} vs_out;"
""
"uniform mat4 transform[2];"
"uniform vec2 tex_mul[2];"
""
"void main(void)"
"{"
" vs_out.instance = gl_InstanceID;"
" vs_out.tc = tex*tex_mul[gl_InstanceID];"
" gl_Position = transform[gl_InstanceID]*vec4(pos,1.0);"
"}"
};
cstring fshader = {
"#version 430 core\n"
"in VS_OUT{"
" vec2 tc;"
" flat int instance;"
"} fs_in;"
""
"layout(location = 0) out vec4 color;"
"uniform float mx;"
""
"uniform sampler2DArray texdata;"
""
"void main(void)"
"{"
" vec4 c1 = texture(texdata,vec3(fs_in.tc,0));"
" vec4 c2 = texture(texdata,vec3(fs_in.tc,1));"
" float a1 = texture(texdata,vec3(fs_in.tc,2)).a;"
" if(mx>a1)"
" color = c1;"
" else"
" color = c2;"
"}"
};
GL::CGhnd vao;
GL::VAOAlloc(1,&vao);
GL::VAOBind(vao);
GL::VAOEnableAttrib(0);
GL::VAOEnableAttrib(1);
GL::VAOAttribFormat(0,3,TypeEnum::Scalar,false,0);
GL::VAOAttribFormat(1,2,TypeEnum::Scalar,false,0);
GL::VAOBindVertexBuffer(0,vertbuf,0,sizeof(CVec3)+sizeof(CVec2));
GL::VAOBindVertexBuffer(1,vertbuf,sizeof(CVec3),sizeof(CVec3)+sizeof(CVec2));
GL::VAOAttribBinding(0,0);
GL::VAOAttribBinding(1,1);
GL::CGhnd vprogram = GL::ProgramCreate(GL::ShaderStage::Vertex,1,&vshader);
cDebug("Compilation log: {0}",GL::ProgramGetLog(vprogram));
GL::CGhnd fprogram = GL::ProgramCreate(GL::ShaderStage::Fragment,1,&fshader);
cDebug("Compilation log: {0}",GL::ProgramGetLog(fprogram));
GL::CGhnd pipeline;
GL::PipelineAlloc(1,&pipeline);
GL::PipelineUseStages(pipeline,GL::ShaderStage::Vertex,vprogram);
GL::PipelineUseStages(pipeline,GL::ShaderStage::Fragment,fprogram);
GL::PipelineBind(pipeline);
GL::ShaderReleaseCompiler();
if(!GL::PipelineValidate(pipeline))
return;
GL::CGhnd texture_array;
GL::TexAlloc(1,&texture_array);
GL::TexActive(0);
GL::TexBind(GL::Texture::T2DArray,texture_array);
GL::TexStorage3D(GL::Texture::T2DArray,1,PixelFormat::RGBA32F,1024,1024,3);
for(uint32 i=0;i<3;i++)
{
GL::BufBind(GL::BufType::PixelUData,pbobuf[i]);
GL::TexSubImage3D(GL::Texture::T2DArray,0,
0,0,i,1024,1024,1,
PixelComponents::RGBA,BitFormat::UByte,nullptr);
}
CGraphicsData::CGCamera cam;
cam.aspect = 1.6;
cam.fieldOfView = 70.f;
cam.position = CVec3(0,0,-3);
CGraphicsData::CTransform obj;
obj.position = CVec3(-1,0,0);
obj.scale = CVec3(1);
int32 cam_unif = GL::ProgramGetResourceLoc(vprogram,GL_UNIFORM,"transform");
int32 texm_unif = GL::ProgramGetResourceLoc(vprogram,GL_UNIFORM,"tex_mul");
int32 tex_unif = GL::ProgramGetResourceLoc(fprogram,GL_UNIFORM,"texdata");
int32 tim_unif = GL::ProgramGetResourceLoc(fprogram,GL_UNIFORM,"mx");
int32 tex_bind = 0;
CMat4 cam_mat = CGraphicsData::GenPerspective(cam)
*CGraphicsData::GenTransform(cam);
CMat4 objects[2] = {};
objects[0] = cam_mat*CGraphicsData::GenTransform(obj);
obj.position = CVec3(1,0,0);
objects[1] = cam_mat*CGraphicsData::GenTransform(obj);
CVec2 tex_mul[2] = {};
tex_mul[0] = CVec2(1,1);
tex_mul[1] = CVec2(-1,1);
GL::Uniformfv(vprogram,cam_unif,2,false,objects);
GL::Uniformfv(vprogram,texm_unif,2,tex_mul);
GL::Uniformiv(fprogram,tex_unif,1,&tex_bind);
cDebug("Setup time: {0}",timer->elapsed());
scalar depth_zero = 0.f;
bool cycle_color = false;
while(!closeFlag())
{
if(cycle_color)
{
clearcol.r() = CMath::sin(this->contextTime()+0.5);
clearcol.g() = CMath::sin(this->contextTime()+5.0);
clearcol.b() = CMath::sin(this->contextTime()+50.0);
}
scalar time = CMath::fmod(CMath::sin(this->contextTime()),1.0);
GL::Uniformfv(fprogram,tim_unif,1,&time);
clearcol = normalize(clearcol);
GL::ClearBufferfv(true,0,clearcol);
GL::ClearBufferfv(false,0,&depth_zero);
GL::DrawArraysInstanced(GL_TRIANGLES,0,6,2);
this->pollEvents();
this->swapBuffers();
}
//Write code here
}
void eventHandleD(const CDisplay::CDEvent &e, c_cptr data)
{
CSDL2Renderer::eventHandleD(e,data);
if(e.type==CDisplay::CDEvent::Resize)
{
auto rev = (const CDisplay::CDResizeEvent*)data;
CRectF view;
view.x = 0;
view.y = 0;
view.w = rev->w;
view.h = rev->h;
GL::ViewportSet(0,&view);
}
}
void eventHandleI(const CIEvent &e, c_cptr data)
{
CSDL2Renderer::eventHandleI(e,data);
switch(e.type)
{
case CIEvent::Keyboard:
{
const CIKeyEvent* kev = (const CIKeyEvent*)data;
switch(kev->key)
{
case CK_Escape:
this->closeWindow();
break;
default:
break;
}
break;
}
default:
break;
}
}
};
int32 coffee_main(int32, cstring_w*)
{
if(!OpenVRDev::InitializeBinding())
{
cDebug("Move on, there is nothing to see here.");
}else{
cDebug("By the gods... So it was true! You must be the hero of Kvatch!");
cDebug("[HERE BE DRAGONS]");
uint32 devs;
if(!OpenVRDev::PollDevices(&devs))
{
cDebug("I used to be a reality tripper like you,"
" until I took a cyberkick to the knee.");
}
OpenVRDev::OVRDevice* dev = OpenVRDev::GetDevice(0);
cDebug("What you got: {0}",(const HWDeviceInfo&)*dev);
}
CResources::FileResourcePrefix("sample_data/");
CElapsedTimerD* timer = AllocTimerD();
timer->start();
CSDL2Renderer *renderer = new CDRenderer();
cDebug("Allocated renderer: {0}",timer->elapsed());
CDProperties props = GetDefaultVisual();
props.gl.flags = props.gl.flags|GLProperties::GLDebug;
props.gl.version.major = 4;
props.gl.version.minor = 3;
renderer->init(props);
cDebug("Init renderer: {0}",timer->elapsed());
if(!GL::SeparableShaderSupported())
return 1;
if(!GL::ViewportArraySupported())
return 1;
if(!GL::BufferStorageSupported())
return 1;
renderer->run();
timer->start();
renderer->cleanup();
delete renderer;
cDebug("Cleanup renderer: {0}",timer->elapsed());
return 0;
}
COFFEE_APPLICATION_MAIN(coffee_main)
<|endoftext|>
|
<commit_before>/* Sirikata
* PrintFilter.cpp
*
* Copyright (c) 2010, Jeff Terrace
* 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 Sirikata 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 "PrintFilter.hpp"
#include <stack>
namespace Sirikata {
namespace Mesh {
PrintFilter::PrintFilter(const String& args) {
if(args == "textures") {
mTexturesOnly = true;
} else {
mTexturesOnly = false;
}
}
namespace {
struct NodeState {
NodeState(NodeIndex idx) : node(idx), curChild(-1) {}
NodeIndex node;
int32 curChild;
};
const char* PrimitiveTypeToString(SubMeshGeometry::Primitive::PrimitiveType type) {
switch (type) {
case SubMeshGeometry::Primitive::TRIANGLES: return "Triangles"; break;
case SubMeshGeometry::Primitive::TRISTRIPS: return "Triangle Strips"; break;
case SubMeshGeometry::Primitive::TRIFANS: return "Triangle Fans"; break;
case SubMeshGeometry::Primitive::LINESTRIPS: return "LineStrips"; break;
case SubMeshGeometry::Primitive::LINES: return "Lines"; break;
case SubMeshGeometry::Primitive::POINTS: return "Points"; break;
default: return "Unknown"; break;
}
}
}
FilterDataPtr PrintFilter::apply(FilterDataPtr input) {
assert(input->single());
MeshdataPtr md = input->get();
if(mTexturesOnly) {
for(TextureList::const_iterator it = md->textures.begin(); it != md->textures.end(); it++) {
printf("%s\n", it->c_str());
}
return input;
}
printf("URI: %s\n", md->uri.c_str());
printf("ID: %ld\n", md->id);
printf("Hash: %s\n", md->hash.toString().c_str());
printf("Texture List:\n");
for(TextureList::const_iterator it = md->textures.begin(); it != md->textures.end(); it++) {
printf(" %s\n", it->c_str());
}
printf("Submesh Geometry List:\n");
for(SubMeshGeometryList::const_iterator it = md->geometry.begin(); it != md->geometry.end(); it++) {
printf(" Name: %s, Positions: %d Normals: %d Primitives: %d\n", it->name.c_str(),
(int)it->positions.size(), (int)it->normals.size(), (int)it->primitives.size());
for(std::vector<SubMeshGeometry::Primitive>::const_iterator p = it->primitives.begin(); p != it->primitives.end(); p++) {
printf(" Primitive: material: %d, indices: %d, type: %s\n", (int)p->materialId, (int)p->indices.size(), PrimitiveTypeToString(p->primitiveType));
}
}
printf("Lights:\n");
for(LightInfoList::const_iterator it = md->lights.begin(); it != md->lights.end(); it++) {
printf(" Type: %d Power: %f\n", it->mType, it->mPower);
}
printf("Material Effects:\n");
for(MaterialEffectInfoList::const_iterator it = md->materials.begin(); it != md->materials.end(); it++) {
printf(" Textures: %d Shininess: %f Reflectivity: %f\n", (int)it->textures.size(), it->shininess, it->reflectivity);
for(MaterialEffectInfo::TextureList::const_iterator t_it = it->textures.begin(); t_it != it->textures.end(); t_it++)
printf(" Texture: %s\n", t_it->uri.c_str());
}
printf("Geometry Instances:\n");
for(GeometryInstanceList::const_iterator it = md->instances.begin(); it != md->instances.end(); it++) {
printf(" Index: %d Radius: %f MapSize: %d\n", it->geometryIndex, it->radius, (int)it->materialBindingMap.size());
for(GeometryInstance::MaterialBindingMap::const_iterator m = it->materialBindingMap.begin(); m != it->materialBindingMap.end(); m++) {
printf(" map from: %d to: %d\n", (int)m->first, (int)m->second);
}
}
printf("Light Instances:\n");
for(LightInstanceList::const_iterator it = md->lightInstances.begin(); it != md->lightInstances.end(); it++) {
printf(" Index: %d Matrix: %s\n", it->lightIndex, md->getTransform(it->parentNode).toString().c_str());
}
printf("Material Effect size: %d\n", (int)md->materials.size());
printf("Nodes size: %d (%d roots)\n", (int)md->nodes.size(), (int)md->rootNodes.size());
for(uint32 ri = 0; ri < md->rootNodes.size(); ri++) {
std::stack<NodeState> node_stack;
node_stack.push( NodeState(md->rootNodes[ri]) );
String indent = "";
while(!node_stack.empty()) {
NodeState& curnode = node_stack.top();
if (curnode.curChild == -1) {
// First time we've seen this node, print info and move it
// forward to start procesing children
printf("%s %d\n", indent.c_str(), curnode.node);
curnode.curChild++;
indent += " ";
}
else if (curnode.curChild >= (int)md->nodes[curnode.node].children.size()) {
// We finished with this node
node_stack.pop();
indent = indent.substr(1); // reduce indent
}
else {
// Normal iteration, process next child
int32 childindex = curnode.curChild;
curnode.curChild++;
node_stack.push( NodeState(md->nodes[curnode.node].children[childindex]) );
}
}
}
// Compute the expected number of draw calls assuming no smart
// transformation is occuring. This should be:
// Number of instances * number of primitives in instance
// This really should trace from the root to make sure that all instances
// are actually drawn...
uint32 draw_calls = 0;
for(GeometryInstanceList::const_iterator it = md->instances.begin(); it != md->instances.end(); it++) {
draw_calls += md->geometry[ it->geometryIndex ].primitives.size();
}
printf("Estimated draw calls: %d\n", draw_calls);
return input;
}
}
}
<commit_msg>Fix PrintFilter to generate an accurate count of draw calls by iterating over actually generated instances instead of just the instances array since the instances can be instanced by instancing nodes which use them.<commit_after>/* Sirikata
* PrintFilter.cpp
*
* Copyright (c) 2010, Jeff Terrace
* 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 Sirikata 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 "PrintFilter.hpp"
#include <stack>
namespace Sirikata {
namespace Mesh {
PrintFilter::PrintFilter(const String& args) {
if(args == "textures") {
mTexturesOnly = true;
} else {
mTexturesOnly = false;
}
}
namespace {
struct NodeState {
NodeState(NodeIndex idx) : node(idx), curChild(-1) {}
NodeIndex node;
int32 curChild;
};
const char* PrimitiveTypeToString(SubMeshGeometry::Primitive::PrimitiveType type) {
switch (type) {
case SubMeshGeometry::Primitive::TRIANGLES: return "Triangles"; break;
case SubMeshGeometry::Primitive::TRISTRIPS: return "Triangle Strips"; break;
case SubMeshGeometry::Primitive::TRIFANS: return "Triangle Fans"; break;
case SubMeshGeometry::Primitive::LINESTRIPS: return "LineStrips"; break;
case SubMeshGeometry::Primitive::LINES: return "Lines"; break;
case SubMeshGeometry::Primitive::POINTS: return "Points"; break;
default: return "Unknown"; break;
}
}
}
FilterDataPtr PrintFilter::apply(FilterDataPtr input) {
assert(input->single());
MeshdataPtr md = input->get();
if(mTexturesOnly) {
for(TextureList::const_iterator it = md->textures.begin(); it != md->textures.end(); it++) {
printf("%s\n", it->c_str());
}
return input;
}
printf("URI: %s\n", md->uri.c_str());
printf("ID: %ld\n", md->id);
printf("Hash: %s\n", md->hash.toString().c_str());
printf("Texture List:\n");
for(TextureList::const_iterator it = md->textures.begin(); it != md->textures.end(); it++) {
printf(" %s\n", it->c_str());
}
printf("Submesh Geometry List:\n");
for(SubMeshGeometryList::const_iterator it = md->geometry.begin(); it != md->geometry.end(); it++) {
printf(" Name: %s, Positions: %d Normals: %d Primitives: %d\n", it->name.c_str(),
(int)it->positions.size(), (int)it->normals.size(), (int)it->primitives.size());
for(std::vector<SubMeshGeometry::Primitive>::const_iterator p = it->primitives.begin(); p != it->primitives.end(); p++) {
printf(" Primitive: material: %d, indices: %d, type: %s\n", (int)p->materialId, (int)p->indices.size(), PrimitiveTypeToString(p->primitiveType));
}
}
printf("Lights:\n");
for(LightInfoList::const_iterator it = md->lights.begin(); it != md->lights.end(); it++) {
printf(" Type: %d Power: %f\n", it->mType, it->mPower);
}
printf("Material Effects:\n");
for(MaterialEffectInfoList::const_iterator it = md->materials.begin(); it != md->materials.end(); it++) {
printf(" Textures: %d Shininess: %f Reflectivity: %f\n", (int)it->textures.size(), it->shininess, it->reflectivity);
for(MaterialEffectInfo::TextureList::const_iterator t_it = it->textures.begin(); t_it != it->textures.end(); t_it++)
printf(" Texture: %s\n", t_it->uri.c_str());
}
printf("Geometry Instances:\n");
for(GeometryInstanceList::const_iterator it = md->instances.begin(); it != md->instances.end(); it++) {
printf(" Index: %d Radius: %f MapSize: %d\n", it->geometryIndex, it->radius, (int)it->materialBindingMap.size());
for(GeometryInstance::MaterialBindingMap::const_iterator m = it->materialBindingMap.begin(); m != it->materialBindingMap.end(); m++) {
printf(" map from: %d to: %d\n", (int)m->first, (int)m->second);
}
}
printf("Light Instances:\n");
for(LightInstanceList::const_iterator it = md->lightInstances.begin(); it != md->lightInstances.end(); it++) {
printf(" Index: %d Matrix: %s\n", it->lightIndex, md->getTransform(it->parentNode).toString().c_str());
}
printf("Material Effect size: %d\n", (int)md->materials.size());
printf("Nodes size: %d (%d roots)\n", (int)md->nodes.size(), (int)md->rootNodes.size());
for(uint32 ri = 0; ri < md->rootNodes.size(); ri++) {
std::stack<NodeState> node_stack;
node_stack.push( NodeState(md->rootNodes[ri]) );
String indent = "";
while(!node_stack.empty()) {
NodeState& curnode = node_stack.top();
if (curnode.curChild == -1) {
// First time we've seen this node, print info and move it
// forward to start procesing children
printf("%s %d\n", indent.c_str(), curnode.node);
curnode.curChild++;
indent += " ";
}
else if (curnode.curChild >= (int)md->nodes[curnode.node].children.size()) {
// We finished with this node
node_stack.pop();
indent = indent.substr(1); // reduce indent
}
else {
// Normal iteration, process next child
int32 childindex = curnode.curChild;
curnode.curChild++;
node_stack.push( NodeState(md->nodes[curnode.node].children[childindex]) );
}
}
}
// Compute the expected number of draw calls assuming no smart
// transformation is occuring. This should be:
// Number of instances * number of primitives in instance
// This really should trace from the root to make sure that all instances
// are actually drawn...
uint32 draw_calls = 0;
Meshdata::GeometryInstanceIterator geoinst_it = md->getGeometryInstanceIterator();
uint32 geoinst_idx;
Matrix4x4f pos_xform;
while( geoinst_it.next(&geoinst_idx, &pos_xform) ) {
draw_calls += md->geometry[ md->instances[geoinst_idx].geometryIndex ].primitives.size();
}
printf("Estimated draw calls: %d\n", draw_calls);
return input;
}
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "CNodeFunction.h"
CNodeFunction::CNodeFunction( )
{
memsize = sizeof( size_t );
}
void CNodeFunction::Update( HotSpot & Spot )
{
StandardUpdate( Spot );
if (Spot.ID == 0)
DisassembleBytes( Spot.Address );
}
int CNodeFunction::Draw( ViewInfo & View, int x, int y )
{
if (m_bHidden)
return DrawHidden( View, x, y );
AddSelection( View, 0, y, g_FontHeight );
AddDelete( View, x, y );
AddTypeDrop( View, x, y );
//AddAdd(View,x,y);
int tx = x + TXOFFSET;
tx = AddIcon( View, tx, y, ICON_METHOD, -1, -1 );
int ax = tx;
tx = AddAddressOffset( View, tx, y );
tx = AddText( View, tx, y, g_crType, HS_NONE, _T( "Function" ) );
tx = AddIcon( View, tx, y, ICON_CAMERA, HS_EDIT, HS_CLICK );
tx += g_FontWidth;
tx = AddText( View, tx, y, g_crName, HS_NAME, _T( "%s" ), m_strName );
tx += g_FontWidth;
if (Assembly.size( ) > 0)
tx = AddOpenClose( View, tx, y );
tx += g_FontWidth;
tx = AddComment( View, tx, y );
if (m_LevelsOpen[View.Level])
{
for (size_t i = 0; i < Assembly.size( ); i++)
{
y += g_FontHeight;
AddText( View, ax, y, g_crHex, HS_EDIT, "%s", Assembly[i].GetBuffer( ) );
}
}
return y += g_FontHeight;
}
void CNodeFunction::DisassembleBytes( size_t Address )
{
Assembly.clear( );
size_t address = Address;
char code[4096] = { (char)0xCC }; // max 4096 bytes
ReClassReadMemory( (LPVOID)address, code, 4096 );
size_t EndCodeSection = (size_t)(code + 4096);
DISASM MyDisasm;
ZeroMemory( &MyDisasm, sizeof( DISASM ) );
MyDisasm.EIP = (size_t)code;
MyDisasm.VirtualAddr = (UInt64)address;
#ifdef _WIN64
MyDisasm.Archi = 64;
#else
MyDisasm.Archi = 0;
#endif
MyDisasm.Options = PrefixedNumeral;
bool Error = 0;
while (!Error)
{
MyDisasm.SecurityBlock = (UInt32)(EndCodeSection - MyDisasm.EIP);
int len = Disasm( &MyDisasm );
if (len == OUT_OF_BLOCK)
Error = 1;
else if (len == UNKNOWN_OPCODE)
Error = 1;
else
{
// Set memsize
memsize += len;
char szInstruction[96];
sprintf_s( szInstruction, "%p %s", (void*)MyDisasm.VirtualAddr, MyDisasm.CompleteInstr );
Assembly.emplace_back( szInstruction );
MyDisasm.EIP += len;
MyDisasm.VirtualAddr += len;
if (MyDisasm.EIP >= (UIntPtr)EndCodeSection)
break;
if (MyDisasm.Instruction.Opcode == 0xCC) // INT3 instruction
break;
}
}
}
<commit_msg>Function node is missing the correct type<commit_after>#include "stdafx.h"
#include "CNodeFunction.h"
CNodeFunction::CNodeFunction( )
{
m_nodeType = nt_function;
memsize = sizeof( size_t );
}
void CNodeFunction::Update( HotSpot & Spot )
{
StandardUpdate( Spot );
if (Spot.ID == 0)
DisassembleBytes( Spot.Address );
}
int CNodeFunction::Draw( ViewInfo & View, int x, int y )
{
if (m_bHidden)
return DrawHidden( View, x, y );
AddSelection( View, 0, y, g_FontHeight );
AddDelete( View, x, y );
AddTypeDrop( View, x, y );
//AddAdd(View,x,y);
int tx = x + TXOFFSET;
tx = AddIcon( View, tx, y, ICON_METHOD, -1, -1 );
int ax = tx;
tx = AddAddressOffset( View, tx, y );
tx = AddText( View, tx, y, g_crType, HS_NONE, _T( "Function" ) );
tx = AddIcon( View, tx, y, ICON_CAMERA, HS_EDIT, HS_CLICK );
tx += g_FontWidth;
tx = AddText( View, tx, y, g_crName, HS_NAME, _T( "%s" ), m_strName );
tx += g_FontWidth;
if (Assembly.size( ) > 0)
tx = AddOpenClose( View, tx, y );
tx += g_FontWidth;
tx = AddComment( View, tx, y );
if (m_LevelsOpen[View.Level])
{
for (size_t i = 0; i < Assembly.size( ); i++)
{
y += g_FontHeight;
AddText( View, ax, y, g_crHex, HS_EDIT, "%s", Assembly[i].GetBuffer( ) );
}
}
return y += g_FontHeight;
}
void CNodeFunction::DisassembleBytes( size_t Address )
{
Assembly.clear( );
size_t address = Address;
char code[4096] = { (char)0xCC }; // max 4096 bytes
ReClassReadMemory( (LPVOID)address, code, 4096 );
size_t EndCodeSection = (size_t)(code + 4096);
DISASM MyDisasm;
ZeroMemory( &MyDisasm, sizeof( DISASM ) );
MyDisasm.EIP = (size_t)code;
MyDisasm.VirtualAddr = (UInt64)address;
#ifdef _WIN64
MyDisasm.Archi = 64;
#else
MyDisasm.Archi = 0;
#endif
MyDisasm.Options = PrefixedNumeral;
bool Error = 0;
while (!Error)
{
MyDisasm.SecurityBlock = (UInt32)(EndCodeSection - MyDisasm.EIP);
int len = Disasm( &MyDisasm );
if (len == OUT_OF_BLOCK)
Error = 1;
else if (len == UNKNOWN_OPCODE)
Error = 1;
else
{
// Set memsize
memsize += len;
char szInstruction[96];
sprintf_s( szInstruction, "%p %s", (void*)MyDisasm.VirtualAddr, MyDisasm.CompleteInstr );
Assembly.emplace_back( szInstruction );
MyDisasm.EIP += len;
MyDisasm.VirtualAddr += len;
if (MyDisasm.EIP >= (UIntPtr)EndCodeSection)
break;
if (MyDisasm.Instruction.Opcode == 0xCC) // INT3 instruction
break;
}
}
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <cmath>
namespace foaw {
template <typename T, size_t N>
T estimate_velocity(const std::array<T, N>& circular_buffer, size_t oldest_index,
T sample_period, T allowed_error, T overflow_value) {
assert(sample_period > static_cast<T>(0));
assert(allowed_error > static_cast<T>(0));
assert(oldest_index < N);
assert(overflow_value >= static_cast<T>(0));
size_t newest_index = oldest_index - 1;
if (oldest_index == 0) {
newest_index = N - 1;
}
T x0 = circular_buffer[newest_index];
bool overflow = false;
bool done = false;
T velocity = 0.0;
for (int n = 1; n < static_cast<int>(N); ++n) {
for (int i = 1; i <= n; ++i) {
T* xp = const_cast<T*>(&circular_buffer[(newest_index - i + N) % N]);
/*
* If overflow value is greater than 0, account for position
* being able to overflow or underflow. Check each new sample
* to determine if overflow/underflow has occurred and modify the
* buffer accordingly.
*
* This check only occurs to the last element in the inner loop to
* avoid checking a specific index multiple times.
*/
if ((i == n) && (overflow_value > static_cast<T>(0))) {
/*
* Assume a difference of 'overflow_value' cannot occurs between
* two adjacent samples. If so, the signal is not sampled fast
* enough.
*/
const T dx = x0 - *xp;
if (std::abs(dx) > (overflow_value/2)) {
*xp += std::copysign(overflow_value, dx);
overflow = true;
}
x0 = *xp;
}
}
// use end fit FOAW
const T yk = circular_buffer[newest_index];
const T ykn = circular_buffer[(newest_index - n + N) % N];
const T bn = (yk - ykn)/(n*sample_period);
/*
* The definition of 'an' in the paper doesn't make much sense so assume
* line passes through last sampled position (which may not be the case
* with a best fit line).
*/
const T an = yk;
for (int j = 1; j <= n; ++j) {
const T ykj = an - bn*j*sample_period;
const T x = circular_buffer[(newest_index - j + N) % N];
const T error = x - ykj;
if (std::abs(error) > allowed_error) {
done = true;
break;
}
}
if (done) {
break;
}
velocity = bn;
}
/* Restore buffer values if overflow occurred. */
if (overflow) {
for (unsigned int i = 0; i < N; ++i) {
T* xp = const_cast<T*>(&circular_buffer[i]);
if (*xp < static_cast<T>(0)) {
*xp += overflow_value;
} else if (*xp >= overflow_value) {
*xp -= overflow_value;
}
}
}
return velocity;
}
} // namespace foaw
/*
* Member function definitions of Foaw template class.
* See foaw.h for template class declaration.
*/
template <typename T, size_t N>
Foaw<T, N>::Foaw(T sample_period, T allowed_error) :
m_positions(),
m_position_index(0),
m_velocity(0.0),
m_T(sample_period),
m_d(allowed_error) { }
template <typename T, size_t N>
void Foaw<T, N>::reset() {
m_positions.fill(0.0);
}
template <typename T, size_t N>
void Foaw<T, N>::add_position(T x) {
m_positions[m_position_index++] = x;
if (m_position_index == N) {
m_position_index = 0;
}
}
template <typename T, size_t N>
T Foaw<T, N>::estimate_velocity() {
m_velocity = foaw::estimate_velocity(m_positions, m_position_index, m_T, m_d);
return m_velocity;
}
template <typename T, size_t N>
T Foaw<T, N>::sample_period() const {
return m_T;
}
template <typename T, size_t N>
T Foaw<T, N>::allowed_error() const {
return m_d;
}
<commit_msg>Skip overflow detection if overflow value is set to zero<commit_after>#include <cassert>
#include <cmath>
namespace foaw {
template <typename T, size_t N>
T estimate_velocity(const std::array<T, N>& circular_buffer, size_t oldest_index,
T sample_period, T allowed_error, T overflow_value) {
assert(sample_period > static_cast<T>(0));
assert(allowed_error > static_cast<T>(0));
assert(oldest_index < N);
assert(overflow_value >= static_cast<T>(0));
size_t newest_index = oldest_index - 1;
if (oldest_index == 0) {
newest_index = N - 1;
}
T x0 = circular_buffer[newest_index];
bool overflow = false;
bool done = false;
T velocity = 0.0;
for (int n = 1; n < static_cast<int>(N); ++n) {
if (overflow_value > static_cast<T>(0)) {
for (int i = 1; i <= n; ++i) {
T* xp = const_cast<T*>(&circular_buffer[(newest_index - i + N) % N]);
/*
* If overflow value is greater than 0, account for position
* being able to overflow or underflow. Check each new sample
* to determine if overflow/underflow has occurred and modify the
* buffer accordingly.
*
* This check only occurs to the last element in the inner loop to
* avoid checking a specific index multiple times.
*/
if (i == n) {
/*
* Assume a difference of 'overflow_value' cannot occurs between
* two adjacent samples. If so, the signal is not sampled fast
* enough.
*/
const T dx = x0 - *xp;
if (std::abs(dx) > (overflow_value/2)) {
*xp += std::copysign(overflow_value, dx);
overflow = true;
}
x0 = *xp;
}
}
}
// use end fit FOAW
const T yk = circular_buffer[newest_index];
const T ykn = circular_buffer[(newest_index - n + N) % N];
const T bn = (yk - ykn)/(n*sample_period);
/*
* The definition of 'an' in the paper doesn't make much sense so assume
* line passes through last sampled position (which may not be the case
* with a best fit line).
*/
const T an = yk;
for (int j = 1; j <= n; ++j) {
const T ykj = an - bn*j*sample_period;
const T x = circular_buffer[(newest_index - j + N) % N];
const T error = x - ykj;
if (std::abs(error) > allowed_error) {
done = true;
break;
}
}
if (done) {
break;
}
velocity = bn;
}
/* Restore buffer values if overflow occurred. */
if (overflow) {
for (unsigned int i = 0; i < N; ++i) {
T* xp = const_cast<T*>(&circular_buffer[i]);
if (*xp < static_cast<T>(0)) {
*xp += overflow_value;
} else if (*xp >= overflow_value) {
*xp -= overflow_value;
}
}
}
return velocity;
}
} // namespace foaw
/*
* Member function definitions of Foaw template class.
* See foaw.h for template class declaration.
*/
template <typename T, size_t N>
Foaw<T, N>::Foaw(T sample_period, T allowed_error) :
m_positions(),
m_position_index(0),
m_velocity(0.0),
m_T(sample_period),
m_d(allowed_error) { }
template <typename T, size_t N>
void Foaw<T, N>::reset() {
m_positions.fill(0.0);
}
template <typename T, size_t N>
void Foaw<T, N>::add_position(T x) {
m_positions[m_position_index++] = x;
if (m_position_index == N) {
m_position_index = 0;
}
}
template <typename T, size_t N>
T Foaw<T, N>::estimate_velocity() {
m_velocity = foaw::estimate_velocity(m_positions, m_position_index, m_T, m_d);
return m_velocity;
}
template <typename T, size_t N>
T Foaw<T, N>::sample_period() const {
return m_T;
}
template <typename T, size_t N>
T Foaw<T, N>::allowed_error() const {
return m_d;
}
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include <reflection_manager.hpp>
#include <iterator>
TEST_CASE("test info_iterator_ with const type", "[info_iterator_]")
{
constexpr shadow::type_info type_info_array[] = {
{"type1", 1}, {"type2", 2}, {"type3", 3}, {"type4", 4},
};
SECTION("Construct info_iterator_'s with pointers to type_info in array")
{
shadow::reflection_manager::const_type_iterator it_begin(
std::begin(type_info_array));
shadow::reflection_manager::const_type_iterator it_end(
std::end(type_info_array));
SECTION("self comparison")
{
REQUIRE(it_begin == it_begin);
REQUIRE(it_end == it_end);
}
SECTION("it_end and it_begin should not compare equal")
{
REQUIRE(it_begin != it_end);
REQUIRE(!(it_begin == it_end));
}
SECTION("copy construct an info_iterator_ with it_begin")
{
auto copy_constructed_it = it_begin;
// copy_constructed_it should be equivalent to it_begin
SECTION("move construct an info_iterator_ with copy_constructed_it")
{
auto move_constructed_it = std::move(copy_constructed_it);
// move_constructed_it should be equivalent to it_begin
}
SECTION("default construct info_iterator_")
{
shadow::reflection_manager::const_type_iterator
default_constructed_it1;
shadow::reflection_manager::const_type_iterator
default_constructed_it2{};
shadow::reflection_manager::const_type_iterator();
shadow::reflection_manager::const_type_iterator{};
SECTION("copy assign it_begin to default_constructed_it1")
{
default_constructed_it1 = it_begin;
// default_constructed_it1 should be equivalent to
// copy_constructied_it
// it_begin should be unchanged
}
SECTION("move assign it_begin to default_constructed_it1")
{
default_constructed_it1 = std::move(it_begin);
// default_constructed_it1 should be equivalent to
// copy_constructied_it
}
}
SECTION("swap copy_constructed_it and it_end")
{
using std::swap;
swap(copy_constructed_it, it_end);
// it_end should be equivalent to it_begin
REQUIRE(it_end == it_begin);
}
}
SECTION("pre-increment info_iterator_")
{
auto res = ++it_begin;
REQUIRE(it_begin->name() == std::string("type2"));
REQUIRE(res->name() == std::string("type2"));
SECTION("pre-decrement to get back")
{
--it_begin;
REQUIRE(it_begin->name() == std::string("type1"));
}
SECTION("post-decrement to get back")
{
it_begin--;
REQUIRE(it_begin->name() == std::string("type1"));
}
}
SECTION("post-increment and dereference in one expression")
{
auto res = *it_begin++;
REQUIRE(res->name() == std::string("type1"));
REQUIRE(it_begin->name() == std::string("type2"));
}
SECTION("dereference it_begin")
{
auto front = *it_begin;
REQUIRE(front.name() == std::string("type1"));
}
}
SECTION("inspect iterator_traits of info_iterator_")
{
auto value_type_same = std::is_same<
std::iterator_traits<
shadow::reflection_manager::const_type_iterator>::value_type,
const shadow::type>::value;
auto difference_type_same = std::is_same<
std::iterator_traits<shadow::reflection_manager::
const_type_iterator>::difference_type,
std::iterator_traits<const shadow::type_info*>::difference_type>::
value;
auto reference_same = std::is_same<
std::iterator_traits<
shadow::reflection_manager::const_type_iterator>::reference,
const shadow::type>::value;
auto pointer_same = std::is_same<
std::iterator_traits<
shadow::reflection_manager::const_type_iterator>::pointer,
const shadow::type>::value;
auto category_same = std::is_same<
std::iterator_traits<shadow::reflection_manager::
const_type_iterator>::iterator_category,
std::iterator_traits<const shadow::type_info*>::iterator_category>::
value;
REQUIRE(value_type_same);
REQUIRE(difference_type_same);
REQUIRE(reference_same);
REQUIRE(pointer_same);
REQUIRE(category_same);
}
}
<commit_msg>Add unit test. modified: tests/test_iterators.cpp<commit_after>#include "catch.hpp"
#include <reflection_manager.hpp>
#include <iterator>
TEST_CASE("test info_iterator_ with const type", "[info_iterator_]")
{
constexpr shadow::type_info type_info_array[] = {
{"type1", 1}, {"type2", 2}, {"type3", 3}, {"type4", 4},
};
SECTION("Construct info_iterator_'s with pointers to type_info in array")
{
shadow::reflection_manager::const_type_iterator it_begin(
std::begin(type_info_array));
shadow::reflection_manager::const_type_iterator it_end(
std::end(type_info_array));
SECTION("self comparison")
{
REQUIRE(it_begin == it_begin);
REQUIRE(it_end == it_end);
}
SECTION("it_end and it_begin should not compare equal")
{
REQUIRE(it_begin != it_end);
REQUIRE(!(it_begin == it_end));
}
SECTION("copy construct an info_iterator_ with it_begin")
{
auto copy_constructed_it = it_begin;
// copy_constructed_it should be equivalent to it_begin
SECTION("move construct an info_iterator_ with copy_constructed_it")
{
auto move_constructed_it = std::move(copy_constructed_it);
// move_constructed_it should be equivalent to it_begin
}
SECTION("default construct info_iterator_")
{
shadow::reflection_manager::const_type_iterator
default_constructed_it1;
shadow::reflection_manager::const_type_iterator
default_constructed_it2{};
shadow::reflection_manager::const_type_iterator();
shadow::reflection_manager::const_type_iterator{};
SECTION("copy assign it_begin to default_constructed_it1")
{
default_constructed_it1 = it_begin;
// default_constructed_it1 should be equivalent to
// copy_constructied_it
// it_begin should be unchanged
}
SECTION("move assign it_begin to default_constructed_it1")
{
default_constructed_it1 = std::move(it_begin);
// default_constructed_it1 should be equivalent to
// copy_constructied_it
}
}
SECTION("swap copy_constructed_it and it_end")
{
using std::swap;
swap(copy_constructed_it, it_end);
// it_end should be equivalent to it_begin
REQUIRE(it_end == it_begin);
}
}
SECTION("pre-increment info_iterator_")
{
auto res = ++it_begin;
REQUIRE(it_begin->name() == std::string("type2"));
REQUIRE(res->name() == std::string("type2"));
SECTION("pre-decrement to get back")
{
--it_begin;
REQUIRE(it_begin->name() == std::string("type1"));
}
SECTION("post-decrement to get back")
{
it_begin--;
REQUIRE(it_begin->name() == std::string("type1"));
}
SECTION("dereference and post-decrement")
{
auto res2 = *it_begin--;
REQUIRE(res2.name() == std::string("type2"));
REQUIRE(it_begin->name() == std::string("type1"));
}
}
SECTION("post-increment and dereference in one expression")
{
auto res = *it_begin++;
REQUIRE(res->name() == std::string("type1"));
REQUIRE(it_begin->name() == std::string("type2"));
}
SECTION("dereference it_begin")
{
auto front = *it_begin;
REQUIRE(front.name() == std::string("type1"));
}
}
SECTION("inspect iterator_traits of info_iterator_")
{
auto value_type_same = std::is_same<
std::iterator_traits<
shadow::reflection_manager::const_type_iterator>::value_type,
const shadow::type>::value;
auto difference_type_same = std::is_same<
std::iterator_traits<shadow::reflection_manager::
const_type_iterator>::difference_type,
std::iterator_traits<const shadow::type_info*>::difference_type>::
value;
auto reference_same = std::is_same<
std::iterator_traits<
shadow::reflection_manager::const_type_iterator>::reference,
const shadow::type>::value;
auto pointer_same = std::is_same<
std::iterator_traits<
shadow::reflection_manager::const_type_iterator>::pointer,
const shadow::type>::value;
auto category_same = std::is_same<
std::iterator_traits<shadow::reflection_manager::
const_type_iterator>::iterator_category,
std::iterator_traits<const shadow::type_info*>::iterator_category>::
value;
REQUIRE(value_type_same);
REQUIRE(difference_type_same);
REQUIRE(reference_same);
REQUIRE(pointer_same);
REQUIRE(category_same);
}
}
<|endoftext|>
|
<commit_before>#include "fsm.hpp"
// =========================================================================
void FsmArgumentStack::Reset()
{
mStringPos = 0;
mIntPos = 0;
}
void FsmArgumentStack::Push(std::string str)
{
mStringArgs.push_back(str);
}
void FsmArgumentStack::Push(s32 integer)
{
mIntArgs.push_back(integer);
}
const std::string& FsmArgumentStack::PopString()
{
return mStringArgs[mStringPos++];
}
s32 FsmArgumentStack::PopInt()
{
return mIntArgs[mIntPos++];
}
// =========================================================================
void FsmStateTransition::AddCondition(StateCondition condition)
{
mConditions.push_back(condition);
}
bool FsmStateTransition::Evaulate(TConditions& events)
{
// Nothing to check, just move to next state
if (mConditions.empty())
{
return true;
}
for (StateCondition& event : mConditions)
{
if (!event.Execute(events))
{
// An event isn't true so can't go to next state yet
return false;
}
}
// All events are true, go to next state
return true;
}
// =========================================================================
void FsmState::Enter(TActions& actions)
{
LOG_INFO(mStateName.c_str());
for (StateAction& action : mEnterActions)
{
action.Execute(actions);
}
}
const std::string* FsmState::Update(TConditions& states)
{
// TODO: Need "Running" actions - for playing sound effects
// per anim frame?
for (FsmStateTransition& trans : mTransistions)
{
if (trans.Evaulate(states))
{
return &trans.Name();
}
}
return nullptr;
}
// =========================================================================
void FiniteStateMachine::Update()
{
if (mActiveState)
{
const std::string* nextState = mActiveState->Update(mConditions);
if (nextState)
{
ToState(nextState->c_str());
}
}
}
bool FiniteStateMachine::ToState(const char* stateName)
{
for (FsmState& state : mStates)
{
if (state.Name() == stateName)
{
mActiveState = &state;
mActiveState->Enter(mActions);
return true;
}
}
LOG_ERROR("State: " << stateName << " not found");
return false;
}
void FiniteStateMachine::Construct()
{
// All of this will come from a config file
{
FsmState state("Idle");
StateAction action("SetAnimation");
action.Arguments().Push("AbeStandIdle");
state.AddEnterAction(action);
FsmStateTransition trans("ToWalk");
StateCondition pressLeft = "InputRight";
trans.AddCondition(pressLeft);
state.AddTransition(trans);
mStates.push_back(state);
}
{
FsmState state("ToWalk");
StateAction action("SetAnimation");
action.Arguments().Push("AbeStandToWalk");
state.AddEnterAction(action);
StateCondition animComplete = "IsAnimationComplete";
FsmStateTransition trans("Walking");
trans.AddCondition(animComplete);
state.AddTransition(trans);
mStates.push_back(state);
}
{
FsmState state("Walking");
StateAction action("SetAnimation");
action.Arguments().Push("AbeWalking");
StateAction sound("PlaySoundEffect");
sound.Arguments().Push("Walk effect");
state.AddEnterAction(action);
state.AddEnterAction(sound);
FsmStateTransition trans("ToIdle");
StateCondition pressLeft = "!InputRight";
trans.AddCondition(pressLeft);
state.AddTransition(trans);
mStates.push_back(state);
}
{
FsmState state("ToIdle");
StateAction action("SetAnimation");
action.Arguments().Push("AbeWalkToStand");
state.AddEnterAction(action);
StateCondition animComplete("IsAnimationComplete");
FsmStateTransition trans("Idle");
trans.AddCondition(animComplete);
state.AddTransition(trans);
mStates.push_back(state);
}
ToState("Idle");
}
<commit_msg>msvc stop allowing non sense to compile!<commit_after>#include "fsm.hpp"
// =========================================================================
void FsmArgumentStack::Reset()
{
mStringPos = 0;
mIntPos = 0;
}
void FsmArgumentStack::Push(std::string str)
{
mStringArgs.push_back(str);
}
void FsmArgumentStack::Push(s32 integer)
{
mIntArgs.push_back(integer);
}
const std::string& FsmArgumentStack::PopString()
{
return mStringArgs[mStringPos++];
}
s32 FsmArgumentStack::PopInt()
{
return mIntArgs[mIntPos++];
}
// =========================================================================
void FsmStateTransition::AddCondition(StateCondition condition)
{
mConditions.push_back(condition);
}
bool FsmStateTransition::Evaulate(TConditions& events)
{
// Nothing to check, just move to next state
if (mConditions.empty())
{
return true;
}
for (StateCondition& event : mConditions)
{
if (!event.Execute(events))
{
// An event isn't true so can't go to next state yet
return false;
}
}
// All events are true, go to next state
return true;
}
// =========================================================================
void FsmState::Enter(TActions& actions)
{
LOG_INFO(mStateName.c_str());
for (StateAction& action : mEnterActions)
{
action.Execute(actions);
}
}
const std::string* FsmState::Update(TConditions& states)
{
// TODO: Need "Running" actions - for playing sound effects
// per anim frame?
for (FsmStateTransition& trans : mTransistions)
{
if (trans.Evaulate(states))
{
return &trans.Name();
}
}
return nullptr;
}
// =========================================================================
void FiniteStateMachine::Update()
{
if (mActiveState)
{
const std::string* nextState = mActiveState->Update(mConditions);
if (nextState)
{
ToState(nextState->c_str());
}
}
}
bool FiniteStateMachine::ToState(const char* stateName)
{
for (FsmState& state : mStates)
{
if (state.Name() == stateName)
{
mActiveState = &state;
mActiveState->Enter(mActions);
return true;
}
}
LOG_ERROR("State: " << stateName << " not found");
return false;
}
void FiniteStateMachine::Construct()
{
// All of this will come from a config file
{
FsmState state("Idle");
StateAction action("SetAnimation");
action.Arguments().Push("AbeStandIdle");
state.AddEnterAction(action);
FsmStateTransition trans("ToWalk");
StateCondition pressRight("InputRight");
trans.AddCondition(pressRight);
state.AddTransition(trans);
mStates.push_back(state);
}
{
FsmState state("ToWalk");
StateAction action("SetAnimation");
action.Arguments().Push("AbeStandToWalk");
state.AddEnterAction(action);
StateCondition animComplete = "IsAnimationComplete";
FsmStateTransition trans("Walking");
trans.AddCondition(animComplete);
state.AddTransition(trans);
mStates.push_back(state);
}
{
FsmState state("Walking");
StateAction action("SetAnimation");
action.Arguments().Push("AbeWalking");
StateAction sound("PlaySoundEffect");
sound.Arguments().Push("Walk effect");
state.AddEnterAction(action);
state.AddEnterAction(sound);
FsmStateTransition trans("ToIdle");
StateCondition pressRight("!InputRight");
trans.AddCondition(pressRight);
state.AddTransition(trans);
mStates.push_back(state);
}
{
FsmState state("ToIdle");
StateAction action("SetAnimation");
action.Arguments().Push("AbeWalkToStand");
state.AddEnterAction(action);
StateCondition animComplete("IsAnimationComplete");
FsmStateTransition trans("Idle");
trans.AddCondition(animComplete);
state.AddTransition(trans);
mStates.push_back(state);
}
ToState("Idle");
}
<|endoftext|>
|
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
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 <cassert>
#include <limits>
#include <iostream>
#include <fstream>
#include "ngram.hh"
#include "LanguageModelKen.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
LanguageModelKen::LanguageModelKen(bool registerScore, ScoreIndexManager &scoreIndexManager)
:LanguageModelSingleFactor(registerScore, scoreIndexManager), m_ngram(NULL)
{
}
LanguageModelKen::~LanguageModelKen()
{
delete m_ngram;
}
bool LanguageModelKen::Load(const std::string &filePath,
FactorType factorType,
size_t nGramOrder)
{
cerr << "In LanguageModelKen::Load: nGramOrder = " << nGramOrder << " will be ignored. Using whatever the file has.\n";
m_ngram = new lm::ngram::Model(filePath.c_str());
m_factorType = factorType;
m_nGramOrder = m_ngram->Order();
m_filePath = filePath;
FactorCollection &factorCollection = FactorCollection::Instance();
m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_);
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_);
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
return true;
}
/* get score of n-gram. n-gram should not be bigger than m_nGramOrder
* Specific implementation can return State and len data to be used in hypothesis pruning
* \param contextFactor n-gram to be scored
* \param finalState state used by LM. Return arg
* \param len ???
*/
float LanguageModelKen::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int* len) const
{
FactorType factorType = GetFactorType();
size_t count = contextFactor.size();
assert(count <= GetNGramOrder());
if (count == 0)
{
finalState = NULL;
return 0;
}
// set up context
vector<lm::WordIndex> ngramId(count);
for (size_t i = 0 ; i < count - 1 ; i++)
{
const Factor *factor = contextFactor[i]->GetFactor(factorType);
const string &word = factor->GetString();
// TODO(hieuhoang1972): precompute this.
ngramId[i] = m_ngram->GetVocabulary().Index(word);
}
// TODO(hieuhoang1972): use my stateful interface instead of this stateless one you asked heafield to kludge for you.
lm::ngram::HieuShouldRefactorMoses ret(m_ngram->SlowStatelessScore(&*ngramId.begin(), &*ngramId.end()));
if (finalState)
{
*finalState = ret.meaningless_unique_state;
}
if (len)
{
*len = ret.ngram_length;
}
return TransformLMScore(ret.prob);
}
}
<commit_msg>Now returning the same probabilities as SRI. <commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
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 <cassert>
#include <limits>
#include <iostream>
#include <fstream>
#include "ngram.hh"
#include "LanguageModelKen.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
LanguageModelKen::LanguageModelKen(bool registerScore, ScoreIndexManager &scoreIndexManager)
:LanguageModelSingleFactor(registerScore, scoreIndexManager), m_ngram(NULL)
{
}
LanguageModelKen::~LanguageModelKen()
{
delete m_ngram;
}
bool LanguageModelKen::Load(const std::string &filePath,
FactorType factorType,
size_t nGramOrder)
{
cerr << "In LanguageModelKen::Load: nGramOrder = " << nGramOrder << " will be ignored. Using whatever the file has.\n";
m_ngram = new lm::ngram::Model(filePath.c_str());
m_factorType = factorType;
m_nGramOrder = m_ngram->Order();
m_filePath = filePath;
FactorCollection &factorCollection = FactorCollection::Instance();
m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_);
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_);
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
return true;
}
/* get score of n-gram. n-gram should not be bigger than m_nGramOrder
* Specific implementation can return State and len data to be used in hypothesis pruning
* \param contextFactor n-gram to be scored
* \param finalState state used by LM. Return arg
* \param len ???
*/
float LanguageModelKen::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int* len) const
{
FactorType factorType = GetFactorType();
size_t count = contextFactor.size();
assert(count <= GetNGramOrder());
if (count == 0)
{
finalState = NULL;
return 0;
}
// set up context
vector<lm::WordIndex> ngramId(count);
for (size_t i = 0 ; i < count; i++)
{
const Factor *factor = contextFactor[i]->GetFactor(factorType);
const string &word = factor->GetString();
// TODO(hieuhoang1972): precompute this.
ngramId[i] = m_ngram->GetVocabulary().Index(word);
}
// TODO(hieuhoang1972): use my stateful interface instead of this stateless one you asked heafield to kludge for you.
lm::ngram::HieuShouldRefactorMoses ret(m_ngram->SlowStatelessScore(&*ngramId.begin(), &*ngramId.end()));
if (finalState)
{
*finalState = ret.meaningless_unique_state;
}
if (len)
{
*len = ret.ngram_length;
}
return TransformLMScore(ret.prob);
}
}
<|endoftext|>
|
<commit_before><commit_msg>r10734/sofa : returning reference to local temporary object<commit_after><|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreWorkQueue.h"
#include "Threading/OgreDefaultWorkQueueTBB.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
namespace Ogre
{
/// Worker function to register threads with the RenderSystem, if required
struct RegisterRSWorker
{
RegisterRSWorker(DefaultWorkQueue* queue): mQueue(queue) { }
void operator() () { mQueue->_registerThreadWithRenderSystem(); }
DefaultWorkQueue* mQueue;
};
//---------------------------------------------------------------------
DefaultWorkQueue::DefaultWorkQueue(const String& name)
: DefaultWorkQueueBase(name)
#if OGRE_NO_TBB_SCHEDULER == 0
, mTaskScheduler(tbb::task_scheduler_init::deferred)
#endif
{
}
//---------------------------------------------------------------------
void DefaultWorkQueue::startup(bool forceRestart)
{
if (mIsRunning)
{
if (forceRestart)
shutdown();
else
return;
}
mShuttingDown = false;
mWorkerFunc = OGRE_NEW_T(WorkerFunc(this), MEMCATEGORY_GENERAL);
LogManager::getSingleton().stream() <<
"DefaultWorkQueue('" << mName << "') initialising.";
#if OGRE_NO_TBB_SCHEDULER == 0
mTaskScheduler.initialize(mWorkerThreadCount);
#endif
if (mWorkerRenderSystemAccess)
{
Root::getSingleton().getRenderSystem()->preExtraThreadsStarted();
RegisterRSWorker worker (this);
// current thread need not be registered
mRegisteredThreads.insert(tbb::this_tbb_thread::get_id());
while (mRegisteredThreads.size() < mWorkerThreadCount)
{
// spawn tasks until all worker threads have registered themselves with the RS
for (size_t i = 0; i < mWorkerThreadCount*3; ++i)
{
mTaskGroup.run(worker);
}
mTaskGroup.wait();
}
Root::getSingleton().getRenderSystem()->postExtraThreadsStarted();
}
mIsRunning = true;
}
//---------------------------------------------------------------------
void DefaultWorkQueue::_registerThreadWithRenderSystem()
{
{
OGRE_LOCK_MUTEX(mRegisterRSMutex);
tbb::tbb_thread::id cur = tbb::this_tbb_thread::get_id();
if (mRegisteredThreads.find(cur) == mRegisteredThreads.end())
{
Root::getSingleton().getRenderSystem()->registerThread();
mRegisteredThreads.insert(cur);
}
}
tbb::this_tbb_thread::yield();
}
//---------------------------------------------------------------------
DefaultWorkQueue::~DefaultWorkQueue()
{
shutdown();
}
//---------------------------------------------------------------------
void DefaultWorkQueue::shutdown()
{
LogManager::getSingleton().stream() <<
"DefaultWorkQueue('" << mName << "') shutting down.";
mShuttingDown = true;
mTaskGroup.cancel();
abortAllRequests();
// wait until all tasks have finished.
mTaskGroup.wait();
#if OGRE_NO_TBB_SCHEDULER == 0
if (mTaskScheduler.is_active())
mTaskScheduler.terminate();
#endif
if (mWorkerFunc)
{
OGRE_DELETE_T(mWorkerFunc, WorkerFunc, MEMCATEGORY_GENERAL);
mWorkerFunc = 0;
}
mIsRunning = false;
}
//---------------------------------------------------------------------
void DefaultWorkQueue::_threadMain()
{
//// Initialise the thread for RS if necessary
//if (mWorkerRenderSystemAccess)
//{
// Root::getSingleton().getRenderSystem()->registerThread();
// _notifyThreadRegistered();
//}
// Task main function. Process a single request.
_processNextRequest();
}
//---------------------------------------------------------------------
void DefaultWorkQueue::notifyWorkers()
{
// create a new task
mTaskGroup.run(*mWorkerFunc);
}
}
<commit_msg>fix compilation of OgreDefaultWorkQueueTBB <commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreWorkQueue.h"
#include "Threading/OgreDefaultWorkQueueTBB.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
namespace Ogre
{
/// Worker function to register threads with the RenderSystem, if required
struct RegisterRSWorker
{
RegisterRSWorker(DefaultWorkQueue* queue): mQueue(queue) { }
void operator() () const { mQueue->_registerThreadWithRenderSystem(); }
DefaultWorkQueue* mQueue;
};
//---------------------------------------------------------------------
DefaultWorkQueue::DefaultWorkQueue(const String& name)
: DefaultWorkQueueBase(name)
#if OGRE_NO_TBB_SCHEDULER == 0
, mTaskScheduler(tbb::task_scheduler_init::deferred)
#endif
{
}
//---------------------------------------------------------------------
void DefaultWorkQueue::startup(bool forceRestart)
{
if (mIsRunning)
{
if (forceRestart)
shutdown();
else
return;
}
mShuttingDown = false;
mWorkerFunc = OGRE_NEW_T(WorkerFunc(this), MEMCATEGORY_GENERAL);
LogManager::getSingleton().stream() <<
"DefaultWorkQueue('" << mName << "') initialising.";
#if OGRE_NO_TBB_SCHEDULER == 0
mTaskScheduler.initialize(mWorkerThreadCount);
#endif
if (mWorkerRenderSystemAccess)
{
Root::getSingleton().getRenderSystem()->preExtraThreadsStarted();
RegisterRSWorker worker (this);
// current thread need not be registered
mRegisteredThreads.insert(tbb::this_tbb_thread::get_id());
while (mRegisteredThreads.size() < mWorkerThreadCount)
{
// spawn tasks until all worker threads have registered themselves with the RS
for (size_t i = 0; i < mWorkerThreadCount*3; ++i)
{
mTaskGroup.run(worker);
}
mTaskGroup.wait();
}
Root::getSingleton().getRenderSystem()->postExtraThreadsStarted();
}
mIsRunning = true;
}
//---------------------------------------------------------------------
void DefaultWorkQueue::_registerThreadWithRenderSystem()
{
{
OGRE_LOCK_MUTEX(mRegisterRSMutex);
tbb::tbb_thread::id cur = tbb::this_tbb_thread::get_id();
if (mRegisteredThreads.find(cur) == mRegisteredThreads.end())
{
Root::getSingleton().getRenderSystem()->registerThread();
mRegisteredThreads.insert(cur);
}
}
tbb::this_tbb_thread::yield();
}
//---------------------------------------------------------------------
DefaultWorkQueue::~DefaultWorkQueue()
{
shutdown();
}
//---------------------------------------------------------------------
void DefaultWorkQueue::shutdown()
{
LogManager::getSingleton().stream() <<
"DefaultWorkQueue('" << mName << "') shutting down.";
mShuttingDown = true;
mTaskGroup.cancel();
abortAllRequests();
// wait until all tasks have finished.
mTaskGroup.wait();
#if OGRE_NO_TBB_SCHEDULER == 0
if (mTaskScheduler.is_active())
mTaskScheduler.terminate();
#endif
if (mWorkerFunc)
{
OGRE_DELETE_T(mWorkerFunc, WorkerFunc, MEMCATEGORY_GENERAL);
mWorkerFunc = 0;
}
mIsRunning = false;
}
//---------------------------------------------------------------------
void DefaultWorkQueue::_threadMain()
{
//// Initialise the thread for RS if necessary
//if (mWorkerRenderSystemAccess)
//{
// Root::getSingleton().getRenderSystem()->registerThread();
// _notifyThreadRegistered();
//}
// Task main function. Process a single request.
_processNextRequest();
}
//---------------------------------------------------------------------
void DefaultWorkQueue::notifyWorkers()
{
// create a new task
mTaskGroup.run(*mWorkerFunc);
}
}
<|endoftext|>
|
<commit_before>/*===========================================
GRRLIB (GX Version)
Example code by Xane
This example shows a basic particle
engine creating a Smokebomb.
============================================*/
#include <grrlib.h>
#include <cstdlib>
#include <wiiuse/wpad.h>
#include <cmath>
#include <ogc/lwp_watchdog.h>
#include <vector>
// Include Graphics
#include "RGFX_Background_jpg.h"
#include "RGFX_Crosshair_png.h"
#include "RGFX_Smoke_png.h"
#include "RGFX_Font_png.h"
// Define Effects
#define EFFECT_SMOKEBOMB 1
// Random Number (0 - 1) in float
#define RANDOM ((((float)(rand() % 12))/12)-0.5)
// Basic structure to hold particle data
typedef struct Particle {
u8 id;
float x, y;
float sx, sy;
u16 rot;
u8 frame, framecnt, framedelay;
u8 red, green, blue;
float scale, alpha;
float sscale, salpha;
float scolor;
GRRLIB_texImg *tex;
} Particle;
// Vector used as a container to iterate through all members of GRRLIB_texImg
static std::vector<GRRLIB_texImg *> TextureList;
static std::vector<Particle *> ParticleList;
static std::vector<Particle *> ParticleListTmp;
// Declare static functions
static void ExitGame();
static void createEffect( u8 id, int _x, int _y );
static void createParticle( u8 _id, int _x, int _y, float _scale, float _alpha, u8 _red, u8 _green, u8 _blue );
static bool updateParticle( Particle *part );
static u8 CalculateFrameRate();
static u8 ClampVar8 (f32 Value);
// Prepare Graphics
GRRLIB_texImg *GFX_Background;
GRRLIB_texImg *GFX_Crosshair;
GRRLIB_texImg *GFX_Smoke;
GRRLIB_texImg *GFX_Font;
int main() {
ir_t P1Mote;
u8 FPS = 0;
// Init GRRLIB & WiiUse
GRRLIB_Init();
u16 WinW = rmode->fbWidth;
u16 WinH = rmode->efbHeight;
WPAD_Init();
WPAD_SetIdleTimeout( 60 * 10 );
WPAD_SetDataFormat( WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR );
// Load textures
GFX_Background = GRRLIB_LoadTextureJPG(RGFX_Background_jpg);
GFX_Crosshair = GRRLIB_LoadTexturePNG(RGFX_Crosshair_png);
GFX_Smoke = GRRLIB_LoadTexturePNG(RGFX_Smoke_png);
GFX_Font = GRRLIB_LoadTexturePNG(RGFX_Font_png);
GRRLIB_InitTileSet( GFX_Font, 8, 16, 32 );
// Set handles
GRRLIB_SetMidHandle( GFX_Crosshair, true );
GRRLIB_SetMidHandle( GFX_Smoke, true );
// Feed the vector with the textures
TextureList = { GFX_Background, GFX_Crosshair, GFX_Smoke, GFX_Font };
while (true) {
WPAD_ScanPads();
u32 WPADKeyDown = WPAD_ButtonsDown(WPAD_CHAN_0);
WPAD_SetVRes(WPAD_CHAN_0, WinW, WinH);
WPAD_IR(WPAD_CHAN_0, &P1Mote);
// Resetting Vars
GRRLIB_SetBlend( GRRLIB_BLEND_ALPHA );
u32 ParticleCnt = 0;
// WiiMote IR Viewport correction
int P1MX = P1Mote.sx - 150;
int P1MY = P1Mote.sy - 150;
// Drawing Background
GRRLIB_DrawImg( 0, 0, GFX_Background, 0, 1, 1, RGBA(255, 255, 255, 255) );
// Add any pending objects into the main container
if(ParticleListTmp.empty() == false) {
ParticleList.insert(ParticleList.end(), ParticleListTmp.begin(), ParticleListTmp.end());
ParticleListTmp.clear();
}
// Update and draw all particles
for (auto PartIter = ParticleList.begin(); PartIter != ParticleList.end();) {
if (updateParticle((*PartIter)) == true) {
GRRLIB_DrawImg( (*PartIter)->x, (*PartIter)->y, (*PartIter)->tex, (*PartIter)->rot, (*PartIter)->scale, (*PartIter)->scale, RGBA( (*PartIter)->red, (*PartIter)->green, (*PartIter)->blue, ClampVar8((*PartIter)->alpha*255) ) );
} else {
free( (*PartIter) );
ParticleList.erase(PartIter);
continue;
}
ParticleCnt++;
PartIter++;
}
// Draw Crosshair
GRRLIB_DrawImg( P1MX, P1MY, GFX_Crosshair, 0, 1, 1, RGBA(255, 255, 255, 255) );
// Draw Text
GRRLIB_Rectangle( 28, 28, 280, 20, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 32, GFX_Font, 0xFFFFFFFF, 1, "Point your WiiMote on the screen." );
GRRLIB_Rectangle( 28, 48, 200, 16, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 48, GFX_Font, 0xFFFFFFFF, 1, "Number of Particle: %d", ParticleCnt );
GRRLIB_Rectangle( 28, 64, 64, 16, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 64, GFX_Font, 0xFFFFFFFF, 1, "FPS: %d", FPS );
// Renders the Scene
GRRLIB_Render();
FPS = CalculateFrameRate();
if (WPADKeyDown & WPAD_BUTTON_B) {
createEffect( EFFECT_SMOKEBOMB, P1MX, P1MY );
}
if (WPADKeyDown & WPAD_BUTTON_HOME) {
break;
}
}
ExitGame();
return 0;
}
static void createEffect( u8 id, int _x, int _y ) {
switch (id) {
case EFFECT_SMOKEBOMB:
for (u8 i = 0; i < 5; i++) {
createParticle( 1, (_x + (RANDOM * 10)), (_y + (RANDOM * 10)), (1.4f+(RANDOM*0.20)), 1.0f, 64, 64, 64 );
}
for (u8 i = 0; i < 20; i++) {
createParticle( 3, (_x + (RANDOM * 50)), (_y + (RANDOM * 50)), 1.25f, 1.5f, 92, 92, 92 );
}
for (u8 i = 0; i < 5; i++) {
u8 _ColorAdd = (RANDOM * 75);
createParticle( 2, (_x + (RANDOM * 40)), (_y + (RANDOM * 40)), (1.0f+(RANDOM*0.20)), 1.0f, 128+_ColorAdd, 128+_ColorAdd, 128+_ColorAdd );
}
break;
}
}
static void createParticle( u8 _id, int _x, int _y, float _scale, float _alpha, u8 _red, u8 _green, u8 _blue ) {
Particle *part = (struct Particle *)calloc(1, sizeof(Particle));
part->id = _id;
part->x = _x;
part->y = _y;
part->rot = rand() % 360;
part->red = _red;
part->green = _green;
part->blue = _blue;
part->scale = _scale;
part->alpha = _alpha;
part->tex = GFX_Smoke;
part->sy = RANDOM;
part->sx = RANDOM;
part->sscale = 0.9985;
part->salpha = 0.985;
switch (part->id) {
case 1:
part->sy = RANDOM * 0.5;
part->sx = RANDOM * 0.5;
part->sscale = 0.999;
part->salpha = 0.992;
part->framedelay = 10;
part->framecnt = 2;
break;
case 2:
part->scolor = 0.98;
part->salpha = 0.95;
break;
case 3:
part->sy = (RANDOM * 8);
part->sx = (RANDOM * 8);
part->salpha = 0.85;
part->scolor = 0.95;
break;
}
ParticleListTmp.push_back( part );
}
static bool updateParticle( Particle *part ) {
if (part->alpha < 0.05) { part->alpha -= 0.001; }
if (part->alpha < 0.1) { part->alpha -= 0.001; }
part->x += part->sx;
part->y += part->sy;
part->scale *= part->sscale;
part->alpha *= part->salpha;
switch (part->id) {
case 1:
if (part->alpha < 0.25) { part->alpha -= 0.001; }
if (part->framecnt == 0) {
part->framecnt = 20;
part->red -= 1;
part->green -= 1;
part->blue -= 1;
}
part->framecnt -= 1;
break;
case 2:
case 3:
part->red *= part->scolor;
part->green *= part->scolor;
part->blue *= part->scolor;
break;
}
if ((part->scale < 0) || (part->alpha < 0)) {
return false;
}
return true;
}
static void ExitGame() {
// Free all memory used by textures.
for (auto &TexIter : TextureList) {
GRRLIB_FreeTexture(TexIter);
}
TextureList.clear();
// Deinitialize GRRLIB & Video
GRRLIB_Exit();
// Exit application
exit(0);
}
/**
* This function calculates the number of frames we render each second.
*/
static u8 CalculateFrameRate() {
static u8 frameCount = 0;
static u32 lastTime;
static u8 FPS = 0;
u32 currentTime = ticks_to_millisecs(gettime());
frameCount++;
if(currentTime - lastTime > 1000) {
lastTime = currentTime;
FPS = frameCount;
frameCount = 0;
}
return FPS;
}
/**
* A helper function for the YCbCr -> RGB conversion.
* Clamps the given value into a range of 0 - 255 and thus preventing an overflow.
* @param Value The value to clamp. Using float to increase the precision. This makes a full spectrum (0 - 255) possible.
* @return Returns a clean, clamped unsigned char.
*/
static u8 ClampVar8 (f32 Value) {
Value = std::roundf(Value);
if (Value < 0) {
Value = 0;
}
else if (Value > 255) {
Value = 255;
}
return (u8)Value;
}
<commit_msg>Use new/delete in C++ example<commit_after>/*===========================================
GRRLIB (GX Version)
Example code by Xane
This example shows a basic particle
engine creating a Smokebomb.
============================================*/
#include <grrlib.h>
#include <cstdlib>
#include <wiiuse/wpad.h>
#include <cmath>
#include <ogc/lwp_watchdog.h>
#include <vector>
// Include Graphics
#include "RGFX_Background_jpg.h"
#include "RGFX_Crosshair_png.h"
#include "RGFX_Smoke_png.h"
#include "RGFX_Font_png.h"
// Define Effects
#define EFFECT_SMOKEBOMB 1
// Random Number (0 - 1) in float
#define RANDOM ((((float)(rand() % 12))/12)-0.5)
// Basic structure to hold particle data
struct Particle {
u8 id;
float x, y;
float sx, sy;
u16 rot;
u8 frame, framecnt, framedelay;
u8 red, green, blue;
float scale, alpha;
float sscale, salpha;
float scolor;
GRRLIB_texImg *tex;
};
// Vector used as a container to iterate through all members of GRRLIB_texImg
static std::vector<GRRLIB_texImg *> TextureList;
static std::vector<Particle *> ParticleList;
static std::vector<Particle *> ParticleListTmp;
// Declare static functions
static void ExitGame();
static void createEffect( u8 id, int _x, int _y );
static void createParticle( u8 _id, int _x, int _y, float _scale, float _alpha, u8 _red, u8 _green, u8 _blue );
static bool updateParticle( Particle *part );
static u8 CalculateFrameRate();
static u8 ClampVar8 (f32 Value);
// Prepare Graphics
GRRLIB_texImg *GFX_Background;
GRRLIB_texImg *GFX_Crosshair;
GRRLIB_texImg *GFX_Smoke;
GRRLIB_texImg *GFX_Font;
int main() {
ir_t P1Mote;
u8 FPS = 0;
// Init GRRLIB & WiiUse
GRRLIB_Init();
u16 WinW = rmode->fbWidth;
u16 WinH = rmode->efbHeight;
WPAD_Init();
WPAD_SetIdleTimeout( 60 * 10 );
WPAD_SetDataFormat( WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR );
// Load textures
GFX_Background = GRRLIB_LoadTextureJPG(RGFX_Background_jpg);
GFX_Crosshair = GRRLIB_LoadTexturePNG(RGFX_Crosshair_png);
GFX_Smoke = GRRLIB_LoadTexturePNG(RGFX_Smoke_png);
GFX_Font = GRRLIB_LoadTexturePNG(RGFX_Font_png);
GRRLIB_InitTileSet( GFX_Font, 8, 16, 32 );
// Set handles
GRRLIB_SetMidHandle( GFX_Crosshair, true );
GRRLIB_SetMidHandle( GFX_Smoke, true );
// Feed the vector with the textures
TextureList = { GFX_Background, GFX_Crosshair, GFX_Smoke, GFX_Font };
while (true) {
WPAD_ScanPads();
u32 WPADKeyDown = WPAD_ButtonsDown(WPAD_CHAN_0);
WPAD_SetVRes(WPAD_CHAN_0, WinW, WinH);
WPAD_IR(WPAD_CHAN_0, &P1Mote);
// Resetting Vars
GRRLIB_SetBlend( GRRLIB_BLEND_ALPHA );
// WiiMote IR Viewport correction
int P1MX = P1Mote.sx - 150;
int P1MY = P1Mote.sy - 150;
// Drawing Background
GRRLIB_DrawImg( 0, 0, GFX_Background, 0, 1, 1, RGBA(255, 255, 255, 255) );
// Add any pending objects into the main container
if(ParticleListTmp.empty() == false) {
ParticleList.insert(ParticleList.end(), ParticleListTmp.begin(), ParticleListTmp.end());
ParticleListTmp.clear();
}
// Update and draw all particles
for (auto PartIter = ParticleList.begin(); PartIter != ParticleList.end();) {
if (updateParticle((*PartIter)) == true) {
GRRLIB_DrawImg( (*PartIter)->x, (*PartIter)->y, (*PartIter)->tex, (*PartIter)->rot, (*PartIter)->scale, (*PartIter)->scale, RGBA( (*PartIter)->red, (*PartIter)->green, (*PartIter)->blue, ClampVar8((*PartIter)->alpha*255) ) );
} else {
delete (*PartIter);
ParticleList.erase(PartIter);
continue;
}
PartIter++;
}
// Draw Crosshair
GRRLIB_DrawImg( P1MX, P1MY, GFX_Crosshair, 0, 1, 1, RGBA(255, 255, 255, 255) );
// Draw Text
GRRLIB_Rectangle( 28, 28, 280, 20, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 32, GFX_Font, 0xFFFFFFFF, 1, "Point your WiiMote on the screen." );
GRRLIB_Rectangle( 28, 48, 200, 16, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 48, GFX_Font, 0xFFFFFFFF, 1, "Number of Particle: %d", ParticleList.size() );
GRRLIB_Rectangle( 28, 64, 64, 16, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 64, GFX_Font, 0xFFFFFFFF, 1, "FPS: %d", FPS );
// Renders the Scene
GRRLIB_Render();
FPS = CalculateFrameRate();
if (WPADKeyDown & WPAD_BUTTON_B) {
createEffect( EFFECT_SMOKEBOMB, P1MX, P1MY );
}
if (WPADKeyDown & WPAD_BUTTON_HOME) {
break;
}
}
ExitGame();
return 0;
}
static void createEffect( u8 id, int _x, int _y ) {
switch (id) {
case EFFECT_SMOKEBOMB:
for (u8 i = 0; i < 5; i++) {
createParticle( 1, (_x + (RANDOM * 10)), (_y + (RANDOM * 10)), (1.4f+(RANDOM*0.20)), 1.0f, 64, 64, 64 );
}
for (u8 i = 0; i < 20; i++) {
createParticle( 3, (_x + (RANDOM * 50)), (_y + (RANDOM * 50)), 1.25f, 1.5f, 92, 92, 92 );
}
for (u8 i = 0; i < 5; i++) {
u8 _ColorAdd = (RANDOM * 75);
createParticle( 2, (_x + (RANDOM * 40)), (_y + (RANDOM * 40)), (1.0f+(RANDOM*0.20)), 1.0f, 128+_ColorAdd, 128+_ColorAdd, 128+_ColorAdd );
}
break;
}
}
static void createParticle( u8 _id, int _x, int _y, float _scale, float _alpha, u8 _red, u8 _green, u8 _blue ) {
Particle *part = new Particle();
part->id = _id;
part->x = _x;
part->y = _y;
part->rot = rand() % 360;
part->red = _red;
part->green = _green;
part->blue = _blue;
part->scale = _scale;
part->alpha = _alpha;
part->tex = GFX_Smoke;
part->sy = RANDOM;
part->sx = RANDOM;
part->sscale = 0.9985;
part->salpha = 0.985;
switch (part->id) {
case 1:
part->sy = RANDOM * 0.5;
part->sx = RANDOM * 0.5;
part->sscale = 0.999;
part->salpha = 0.992;
part->framedelay = 10;
part->framecnt = 2;
break;
case 2:
part->scolor = 0.98;
part->salpha = 0.95;
break;
case 3:
part->sy = (RANDOM * 8);
part->sx = (RANDOM * 8);
part->salpha = 0.85;
part->scolor = 0.95;
break;
}
ParticleListTmp.push_back( part );
}
static bool updateParticle( Particle *part ) {
if (part->alpha < 0.05) { part->alpha -= 0.001; }
if (part->alpha < 0.1) { part->alpha -= 0.001; }
part->x += part->sx;
part->y += part->sy;
part->scale *= part->sscale;
part->alpha *= part->salpha;
switch (part->id) {
case 1:
if (part->alpha < 0.25) { part->alpha -= 0.001; }
if (part->framecnt == 0) {
part->framecnt = 20;
part->red -= 1;
part->green -= 1;
part->blue -= 1;
}
part->framecnt -= 1;
break;
case 2:
case 3:
part->red *= part->scolor;
part->green *= part->scolor;
part->blue *= part->scolor;
break;
}
if ((part->scale < 0) || (part->alpha < 0)) {
return false;
}
return true;
}
static void ExitGame() {
// Free all memory used by textures.
for (auto &TexIter : TextureList) {
GRRLIB_FreeTexture(TexIter);
}
TextureList.clear();
// Deinitialize GRRLIB & Video
GRRLIB_Exit();
// Exit application
exit(0);
}
/**
* This function calculates the number of frames we render each second.
*/
static u8 CalculateFrameRate() {
static u8 frameCount = 0;
static u32 lastTime;
static u8 FPS = 0;
u32 currentTime = ticks_to_millisecs(gettime());
frameCount++;
if(currentTime - lastTime > 1000) {
lastTime = currentTime;
FPS = frameCount;
frameCount = 0;
}
return FPS;
}
/**
* A helper function for the YCbCr -> RGB conversion.
* Clamps the given value into a range of 0 - 255 and thus preventing an overflow.
* @param Value The value to clamp. Using float to increase the precision. This makes a full spectrum (0 - 255) possible.
* @return Returns a clean, clamped unsigned char.
*/
static u8 ClampVar8 (f32 Value) {
Value = std::roundf(Value);
if (Value < 0) {
Value = 0;
}
else if (Value > 255) {
Value = 255;
}
return (u8)Value;
}
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) <2015> <Romain LEGUAY romain.leguay@gmail.com>
*
* 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.
*/
/*
* main.cpp
*
* Created on: 21 févr. 2015
* Author: rleguay
*/
#include <thread/FutureSynchronyzer.hxx>
#include <iostream>
#include <chrono>
/**
* This dumb function just return the sum of a loop;
* @param start start of the loop
* @param end end of the loop
* @return the sum;
*/
size_t cumul(const size_t & start, const size_t & end)
{
size_t res = 0;
for (size_t i = start; i < end; ++i)
{
res += i;
}
return res;
}
int main(int argc, char **argv)
{
UNUSED(argc);
UNUSED(argv);
std::chrono::system_clock::time_point startPoint, endPoint;
startPoint = std::chrono::system_clock::now();
size_t end = 500000000;
size_t step = 5000000;
//The output result;
size_t res = 0;
//Create a future synchronizer with 4 threads,
//with the policy AddNumberResultPolicy,
//create AsyncFutureFactory and return a size_t element.
thread::FutureSynchronyzer<policy::AddNumberResultPolicy,
factory::AsyncFutureFactory, size_t> sync(&res, 4);
//The loop to add all the functions;
for (size_t i = 0; i < end; i += step)
{
sync.addFunction(cumul, i, i+step-1);
}
//Launch all the function and wait for the result;
sync.launchAndWait();
endPoint = std::chrono::system_clock::now();
//Print the result from the sync
std::cout << *(sync.outputResult()) << std::endl;
//Print the result to verify if it's the same value as above.
std::cout << res << std::endl;
auto us = std::chrono::duration_cast<std::chrono::microseconds>(endPoint - startPoint).count();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(endPoint - startPoint).count();
auto sec = std::chrono::duration_cast<std::chrono::seconds>(endPoint - startPoint).count();
auto minutes = sec / 60;
us = us - ms * 1000;
ms = ms - sec * 1000;
sec = sec - minutes * 60;
std::cout << "Time: " << minutes << " min " << sec << " s " << ms <<
" ms " << us <<
" us; Num Threads: " << sync.numThreads() << std::endl;
return 0;
}
<commit_msg>Update policy order in returnValue example<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) <2015> <Romain LEGUAY romain.leguay@gmail.com>
*
* 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.
*/
/*
* main.cpp
*
* Created on: 21 févr. 2015
* Author: rleguay
*/
#include <thread/FutureSynchronyzer.hxx>
#include <iostream>
#include <chrono>
/**
* This dumb function just return the sum of a loop;
* @param start start of the loop
* @param end end of the loop
* @return the sum;
*/
size_t cumul(const size_t & start, const size_t & end)
{
size_t res = 0;
for (size_t i = start; i < end; ++i)
{
res += i;
}
return res;
}
int main(int argc, char **argv)
{
UNUSED(argc);
UNUSED(argv);
std::chrono::system_clock::time_point startPoint, endPoint;
startPoint = std::chrono::system_clock::now();
size_t end = 500000000;
size_t step = 5000000;
//The output result;
size_t res = 0;
//Create a future synchronizer with 4 threads,
//with the policy AddNumberResultPolicy,
//create AsyncFutureFactory and return a size_t element.
thread::FutureSynchronyzer<size_t, policy::AddNumberResultPolicy,
factory::AsyncFutureFactory> sync(&res, 4);
//The loop to add all the functions;
for (size_t i = 0; i < end; i += step)
{
sync.addFunction(cumul, i, i+step-1);
}
//Launch all the function and wait for the result;
sync.launchAndWait();
endPoint = std::chrono::system_clock::now();
//Print the result from the sync
std::cout << *(sync.outputResult()) << std::endl;
//Print the result to verify if it's the same value as above.
std::cout << res << std::endl;
auto us = std::chrono::duration_cast<std::chrono::microseconds>(endPoint - startPoint).count();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(endPoint - startPoint).count();
auto sec = std::chrono::duration_cast<std::chrono::seconds>(endPoint - startPoint).count();
auto minutes = sec / 60;
us = us - ms * 1000;
ms = ms - sec * 1000;
sec = sec - minutes * 60;
std::cout << "Time: " << minutes << " min " << sec << " s " << ms <<
" ms " << us <<
" us; Num Threads: " << sync.numThreads() << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2017 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 <folly/experimental/observer/detail/ObserverManager.h>
#include <folly/ExceptionString.h>
#include <folly/MPMCQueue.h>
#include <folly/Singleton.h>
#include <folly/portability/GFlags.h>
namespace folly {
namespace observer_detail {
FOLLY_TLS bool ObserverManager::inManagerThread_{false};
FOLLY_TLS ObserverManager::DependencyRecorder::Dependencies*
ObserverManager::DependencyRecorder::currentDependencies_{nullptr};
DEFINE_int32(
observer_manager_pool_size,
4,
"How many internal threads ObserverManager should use");
namespace {
constexpr size_t kCurrentQueueSize{10 * 1024};
constexpr size_t kNextQueueSize{10 * 1024};
}
class ObserverManager::CurrentQueue {
public:
CurrentQueue() : queue_(kCurrentQueueSize) {
if (FLAGS_observer_manager_pool_size < 1) {
LOG(ERROR) << "--observer_manager_pool_size should be >= 1";
FLAGS_observer_manager_pool_size = 1;
}
for (int32_t i = 0; i < FLAGS_observer_manager_pool_size; ++i) {
threads_.emplace_back([&]() {
ObserverManager::inManagerThread_ = true;
while (true) {
Function<void()> task;
queue_.blockingRead(task);
if (!task) {
return;
}
try {
task();
} catch (...) {
LOG(ERROR) << "Exception while running CurrentQueue task: "
<< exceptionStr(std::current_exception());
}
}
});
}
}
~CurrentQueue() {
for (size_t i = 0; i < threads_.size(); ++i) {
queue_.blockingWrite(nullptr);
}
for (auto& thread : threads_) {
thread.join();
}
CHECK(queue_.isEmpty());
}
void add(Function<void()> task) {
if (ObserverManager::inManagerThread()) {
if (!queue_.write(std::move(task))) {
throw std::runtime_error("Too many Observers scheduled for update.");
}
} else {
queue_.blockingWrite(std::move(task));
}
}
private:
MPMCQueue<Function<void()>> queue_;
std::vector<std::thread> threads_;
};
class ObserverManager::NextQueue {
public:
explicit NextQueue(ObserverManager& manager)
: manager_(manager), queue_(kNextQueueSize) {
thread_ = std::thread([&]() {
Core::Ptr queueCore;
while (true) {
queue_.blockingRead(queueCore);
if (!queueCore) {
return;
}
std::vector<Core::Ptr> cores;
cores.emplace_back(std::move(queueCore));
{
SharedMutexReadPriority::WriteHolder wh(manager_.versionMutex_);
// We can't pick more tasks from the queue after we bumped the
// version, so we have to do this while holding the lock.
while (cores.size() < kNextQueueSize && queue_.read(queueCore)) {
if (!queueCore) {
return;
}
cores.emplace_back(std::move(queueCore));
}
++manager_.version_;
}
for (auto& core : cores) {
manager_.scheduleRefresh(std::move(core), manager_.version_, true);
}
}
});
}
void add(Core::Ptr core) {
queue_.blockingWrite(std::move(core));
}
~NextQueue() {
// Emtpy element signals thread to terminate
queue_.blockingWrite(nullptr);
thread_.join();
}
private:
ObserverManager& manager_;
MPMCQueue<Core::Ptr> queue_;
std::thread thread_;
};
ObserverManager::ObserverManager() {
currentQueue_ = make_unique<CurrentQueue>();
nextQueue_ = make_unique<NextQueue>(*this);
}
ObserverManager::~ObserverManager() {
// Destroy NextQueue, before the rest of this object, since it expects
// ObserverManager to be alive.
nextQueue_.reset();
currentQueue_.reset();
}
void ObserverManager::scheduleCurrent(Function<void()> task) {
currentQueue_->add(std::move(task));
}
void ObserverManager::scheduleNext(Core::Ptr core) {
nextQueue_->add(std::move(core));
}
struct ObserverManager::Singleton {
static folly::Singleton<ObserverManager> instance;
// MSVC 2015 doesn't let us access ObserverManager's constructor if we
// try to use a lambda to initialize instance, so we have to create
// an actual function instead.
static ObserverManager* createManager() {
return new ObserverManager();
}
};
folly::Singleton<ObserverManager> ObserverManager::Singleton::instance(
createManager);
std::shared_ptr<ObserverManager> ObserverManager::getInstance() {
return Singleton::instance.try_get();
}
}
}
<commit_msg>Give observer manager threads a name<commit_after>/*
* Copyright 2017 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 <folly/experimental/observer/detail/ObserverManager.h>
#include <folly/ExceptionString.h>
#include <folly/FixedString.h>
#include <folly/Format.h>
#include <folly/MPMCQueue.h>
#include <folly/Singleton.h>
#include <folly/ThreadName.h>
#include <folly/portability/GFlags.h>
namespace folly {
namespace observer_detail {
FOLLY_TLS bool ObserverManager::inManagerThread_{false};
FOLLY_TLS ObserverManager::DependencyRecorder::Dependencies*
ObserverManager::DependencyRecorder::currentDependencies_{nullptr};
DEFINE_int32(
observer_manager_pool_size,
4,
"How many internal threads ObserverManager should use");
static constexpr auto kObserverManagerThreadNamePrefix =
folly::makeFixedString("ObserverMngr");
namespace {
constexpr size_t kCurrentQueueSize{10 * 1024};
constexpr size_t kNextQueueSize{10 * 1024};
}
class ObserverManager::CurrentQueue {
public:
CurrentQueue() : queue_(kCurrentQueueSize) {
if (FLAGS_observer_manager_pool_size < 1) {
LOG(ERROR) << "--observer_manager_pool_size should be >= 1";
FLAGS_observer_manager_pool_size = 1;
}
for (int32_t i = 0; i < FLAGS_observer_manager_pool_size; ++i) {
threads_.emplace_back([this, i]() {
folly::setThreadName(
folly::sformat("{}{}", kObserverManagerThreadNamePrefix, i));
ObserverManager::inManagerThread_ = true;
while (true) {
Function<void()> task;
queue_.blockingRead(task);
if (!task) {
return;
}
try {
task();
} catch (...) {
LOG(ERROR) << "Exception while running CurrentQueue task: "
<< exceptionStr(std::current_exception());
}
}
});
}
}
~CurrentQueue() {
for (size_t i = 0; i < threads_.size(); ++i) {
queue_.blockingWrite(nullptr);
}
for (auto& thread : threads_) {
thread.join();
}
CHECK(queue_.isEmpty());
}
void add(Function<void()> task) {
if (ObserverManager::inManagerThread()) {
if (!queue_.write(std::move(task))) {
throw std::runtime_error("Too many Observers scheduled for update.");
}
} else {
queue_.blockingWrite(std::move(task));
}
}
private:
MPMCQueue<Function<void()>> queue_;
std::vector<std::thread> threads_;
};
class ObserverManager::NextQueue {
public:
explicit NextQueue(ObserverManager& manager)
: manager_(manager), queue_(kNextQueueSize) {
thread_ = std::thread([&]() {
Core::Ptr queueCore;
while (true) {
queue_.blockingRead(queueCore);
if (!queueCore) {
return;
}
std::vector<Core::Ptr> cores;
cores.emplace_back(std::move(queueCore));
{
SharedMutexReadPriority::WriteHolder wh(manager_.versionMutex_);
// We can't pick more tasks from the queue after we bumped the
// version, so we have to do this while holding the lock.
while (cores.size() < kNextQueueSize && queue_.read(queueCore)) {
if (!queueCore) {
return;
}
cores.emplace_back(std::move(queueCore));
}
++manager_.version_;
}
for (auto& core : cores) {
manager_.scheduleRefresh(std::move(core), manager_.version_, true);
}
}
});
}
void add(Core::Ptr core) {
queue_.blockingWrite(std::move(core));
}
~NextQueue() {
// Emtpy element signals thread to terminate
queue_.blockingWrite(nullptr);
thread_.join();
}
private:
ObserverManager& manager_;
MPMCQueue<Core::Ptr> queue_;
std::thread thread_;
};
ObserverManager::ObserverManager() {
currentQueue_ = make_unique<CurrentQueue>();
nextQueue_ = make_unique<NextQueue>(*this);
}
ObserverManager::~ObserverManager() {
// Destroy NextQueue, before the rest of this object, since it expects
// ObserverManager to be alive.
nextQueue_.reset();
currentQueue_.reset();
}
void ObserverManager::scheduleCurrent(Function<void()> task) {
currentQueue_->add(std::move(task));
}
void ObserverManager::scheduleNext(Core::Ptr core) {
nextQueue_->add(std::move(core));
}
struct ObserverManager::Singleton {
static folly::Singleton<ObserverManager> instance;
// MSVC 2015 doesn't let us access ObserverManager's constructor if we
// try to use a lambda to initialize instance, so we have to create
// an actual function instead.
static ObserverManager* createManager() {
return new ObserverManager();
}
};
folly::Singleton<ObserverManager> ObserverManager::Singleton::instance(
createManager);
std::shared_ptr<ObserverManager> ObserverManager::getInstance() {
return Singleton::instance.try_get();
}
}
}
<|endoftext|>
|
<commit_before>/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mkeyboardsettingswidget.h"
#include <MButton>
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MContentItem>
#include <MAbstractCellCreator>
#include <MList>
#include <MDialog>
#include <MBanner>
#include <QObject>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QTimer>
#include <QDebug>
namespace
{
//!object name for settings' widgets
const QString ObjectNameSelectedKeyboardsItem("SelectedKeyboardsItem");
const QString ObjectNameErrorCorrectionButton("KeyboardErrorCorrectionButton");
const QString ObjectNameCorrectionSpaceButton("KeyboardCorrectionSpaceButton");
const int MKeyboardLayoutRole = Qt::UserRole + 1;
};
class MKeyboardCellCreator: public MAbstractCellCreator<MContentItem>
{
public:
/*! \reimp */
virtual MWidget *createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const;
virtual void updateCell(const QModelIndex &index, MWidget *cell) const;
/*! \reimp_end */
private:
void updateContentItemMode(const QModelIndex &index, MContentItem *contentItem) const;
};
MWidget *MKeyboardCellCreator::createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const
{
MContentItem *cell = qobject_cast<MContentItem *>(recycler.take("MContentItem"));
if (!cell) {
cell = new MContentItem(MContentItem::SingleTextLabel);
}
updateCell(index, cell);
return cell;
}
void MKeyboardCellCreator::updateCell(const QModelIndex &index, MWidget *cell) const
{
MContentItem *contentItem = qobject_cast<MContentItem *>(cell);
QString layoutTile = index.data(Qt::DisplayRole).toString();
contentItem->setTitle(layoutTile);
}
void MKeyboardCellCreator::updateContentItemMode(const QModelIndex &index,
MContentItem *contentItem) const
{
const int row = index.row();
bool thereIsNextRow = index.sibling(row + 1, 0).isValid();
if (row == 0) {
contentItem->setItemMode(MContentItem::SingleColumnTop);
} else if (thereIsNextRow) {
contentItem->setItemMode(MContentItem::SingleColumnCenter);
} else {
contentItem->setItemMode(MContentItem::SingleColumnBottom);
}
}
MKeyboardSettingsWidget::MKeyboardSettingsWidget(MKeyboardSettings *settings, QGraphicsItem *parent)
: MWidget(parent),
settingsObject(settings),
keyboardDialog(0),
keyboardList(0)
{
MLayout *layout = new MLayout(this);
landscapePolicy = new MGridLayoutPolicy(layout);
landscapePolicy->setContentsMargins(0, 0, 0, 0);
landscapePolicy->setSpacing(0);
//To make sure that both columns have the same width, give them the same preferred width.
landscapePolicy->setColumnPreferredWidth(0, 800);
landscapePolicy->setColumnPreferredWidth(1, 800);
portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);
portraitPolicy->setContentsMargins(0, 0, 0, 0);
portraitPolicy->setSpacing(0);
layout->setLandscapePolicy(landscapePolicy);
layout->setPortraitPolicy(portraitPolicy);
buildUi();
syncErrorCorrectionState();
syncCorrectionSpaceState();
retranslateUi();
connectSlots();
}
MKeyboardSettingsWidget::~MKeyboardSettingsWidget()
{
delete keyboardDialog;
keyboardDialog = 0;
}
void MKeyboardSettingsWidget::buildUi()
{
selectedKeyboardsItem = new MContentItem(MContentItem::TwoTextLabels, this);
selectedKeyboardsItem->setObjectName(ObjectNameSelectedKeyboardsItem);
connect(selectedKeyboardsItem, SIGNAL(clicked()), this, SLOT(showKeyboardList()));
// Put to first row, first column on the grid
addItem(selectedKeyboardsItem, 0, 0);
// Error correction settings
errorCorrectionSwitch = new MButton(this);
errorCorrectionSwitch->setObjectName(ObjectNameErrorCorrectionButton);
errorCorrectionSwitch->setViewType(MButton::switchType);
errorCorrectionSwitch->setCheckable(true);
errorCorrectionContentItem = new MContentItem(MContentItem::TwoTextLabels, this);
//% "Error correction"
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
//% "Error correction description"
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
QGraphicsLinearLayout *eCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
eCLayout->addItem(errorCorrectionContentItem);
eCLayout->addItem(errorCorrectionSwitch);
eCLayout->setAlignment(errorCorrectionSwitch, Qt::AlignCenter);
// Put to first row, second column on the grid
addItem(eCLayout, 0, 1);
// "Space selects the correction candidate" settings
correctionSpaceSwitch = new MButton(this);
correctionSpaceSwitch->setObjectName(ObjectNameCorrectionSpaceButton);
correctionSpaceSwitch->setViewType(MButton::switchType);
correctionSpaceSwitch->setCheckable(true);
correctionSpaceContentItem = new MContentItem(MContentItem::TwoTextLabels, this);
//% "Select with space"
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_select_with_space"));
//% "Select with space description"
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_error_select_with_space_description"));
QGraphicsLinearLayout *wCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
wCLayout->addItem(correctionSpaceContentItem);
wCLayout->addItem(correctionSpaceSwitch);
wCLayout->setAlignment(correctionSpaceSwitch, Qt::AlignCenter);
// Put to second row, second column on the grid
addItem(wCLayout, 1, 1);
}
void MKeyboardSettingsWidget::addItem(QGraphicsLayoutItem *item, int row, int column)
{
landscapePolicy->addItem(item, row, column);
portraitPolicy->addItem(item);
}
void MKeyboardSettingsWidget::retranslateUi()
{
updateTitle();
MWidget::retranslateUi();
}
void MKeyboardSettingsWidget::updateTitle()
{
if (!errorCorrectionContentItem || !correctionSpaceContentItem
|| !settingsObject || !selectedKeyboardsItem)
return;
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_select_with_space"));
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_error_select_with_space_description"));
QStringList keyboards = settingsObject->selectedKeyboards().values();
//% "Installed keyboards (%1)"
QString title = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
selectedKeyboardsItem->setTitle(title);
QString brief;
if (keyboards.count() > 0) {
foreach(const QString &keyboard, keyboards) {
if (!brief.isEmpty())
brief += QString(", ");
brief += keyboard;
}
} else {
//% "No keyboards installed"
brief = qtTrId("qtn_txts_no_keyboards");
}
selectedKeyboardsItem->setSubtitle(brief);
if (keyboardDialog) {
keyboardDialog->setTitle(title);
}
}
void MKeyboardSettingsWidget::connectSlots()
{
connect(this, SIGNAL(visibleChanged()),
this, SLOT(handleVisibilityChanged()));
if (!settingsObject || !errorCorrectionSwitch || !correctionSpaceSwitch)
return;
connect(errorCorrectionSwitch, SIGNAL(toggled(bool)),
this, SLOT(setErrorCorrectionState(bool)));
connect(settingsObject, SIGNAL(errorCorrectionChanged()),
this, SLOT(syncErrorCorrectionState()));
connect(correctionSpaceSwitch, SIGNAL(toggled(bool)),
this, SLOT(setCorrectionSpaceState(bool)));
connect(settingsObject, SIGNAL(correctionSpaceChanged()),
this, SLOT(syncCorrectionSpaceState()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateTitle()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateKeyboardSelectionModel()));
}
void MKeyboardSettingsWidget::showKeyboardList()
{
if (!settingsObject || !keyboardDialog) {
QStringList keyboards = settingsObject->selectedKeyboards().values();
QString keyboardTitle = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
keyboardDialog = new MDialog(keyboardTitle, M::NoStandardButton);
keyboardList = new MList(keyboardDialog);
MKeyboardCellCreator *cellCreator = new MKeyboardCellCreator;
keyboardList->setCellCreator(cellCreator);
QStandardItemModel *model = new QStandardItemModel;
model->sort(0);
keyboardList->setItemModel(model);
keyboardList->setSelectionMode(MList::MultiSelection);
keyboardList->setSelectionModel(new QItemSelectionModel(model, this));
keyboardDialog->setCentralWidget(keyboardList);
connect(keyboardList, SIGNAL(itemClicked(const QModelIndex &)),
this, SLOT(updateSelectedKeyboards(const QModelIndex &)));
}
updateKeyboardModel();
keyboardDialog->exec();
}
void MKeyboardSettingsWidget::updateKeyboardModel()
{
if (!settingsObject || !keyboardList)
return;
//always reload available layouts in case user install/remove some layouts
settingsObject->readAvailableKeyboards();
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
model->clear();
QMap<QString, QString> availableKeyboards = settingsObject->availableKeyboards();
QMap<QString, QString>::const_iterator i = availableKeyboards.constBegin();
while (i != availableKeyboards.constEnd()) {
QStandardItem *item = new QStandardItem(i.value());
item->setData(i.value(), Qt::DisplayRole);
item->setData(i.key(), MKeyboardLayoutRole);
model->appendRow(item);
++i;
}
updateKeyboardSelectionModel();
}
void MKeyboardSettingsWidget::updateKeyboardSelectionModel()
{
if (!settingsObject || !keyboardList)
return;
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
foreach (const QString &keyboard, settingsObject->selectedKeyboards().values()) {
QList<QStandardItem *> items = model->findItems(keyboard);
foreach (const QStandardItem *item, items) {
keyboardList->selectionModel()->select(item->index(), QItemSelectionModel::Select);
}
}
}
void MKeyboardSettingsWidget::updateSelectedKeyboards(const QModelIndex &index)
{
if (!settingsObject || !index.isValid() || !keyboardList
|| !keyboardList->selectionModel())
return;
QStringList updatedKeyboardLayouts;
foreach (const QModelIndex &i, keyboardList->selectionModel()->selectedIndexes()) {
updatedKeyboardLayouts << i.data(MKeyboardLayoutRole).toString();
}
if (updatedKeyboardLayouts.isEmpty()) {
notifyNoKeyboards();
}
settingsObject->setSelectedKeyboards(updatedKeyboardLayouts);
//update titles
retranslateUi();
}
void MKeyboardSettingsWidget::setErrorCorrectionState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->errorCorrection() != enabled) {
settingsObject->setErrorCorrection(enabled);
if (!enabled) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::syncErrorCorrectionState()
{
if (!settingsObject)
return;
const bool errorCorrectionState = settingsObject->errorCorrection();
if (errorCorrectionSwitch
&& errorCorrectionSwitch->isChecked() != errorCorrectionState) {
errorCorrectionSwitch->setChecked(errorCorrectionState);
if (!errorCorrectionState) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::setCorrectionSpaceState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->correctionSpace() != enabled)
settingsObject->setCorrectionSpace(enabled);
}
void MKeyboardSettingsWidget::syncCorrectionSpaceState()
{
if (!settingsObject)
return;
const bool correctionSpaceState = settingsObject->correctionSpace();
if (correctionSpaceSwitch
&& correctionSpaceSwitch->isChecked() != correctionSpaceState) {
correctionSpaceSwitch->setChecked(correctionSpaceState);
}
}
void MKeyboardSettingsWidget::notifyNoKeyboards()
{
MBanner *noKeyboardsNotification = new MBanner;
// It is needed to set the proper style name to have properly wrapped, multiple lines
// with too much content. The MBanner documentation also emphasises to specify the
// style name for the banners explicitly in the code.
noKeyboardsNotification->setStyleName("InformationBanner");
//% "Note: you have uninstalled all virtual keyboards"
noKeyboardsNotification->setTitle(qtTrId("qtn_txts_no_keyboards_notification"));
noKeyboardsNotification->appear(MSceneWindow::DestroyWhenDone);
}
void MKeyboardSettingsWidget::handleVisibilityChanged()
{
// This is a workaround to hide settings dialog when keyboard is hidden.
// And it could be removed when NB#177922 is fixed.
if (!isVisible() && keyboardDialog) {
// reject settings dialog if the visibility of settings widget
// is changed from shown to hidden.
keyboardDialog->reject();
}
}
<commit_msg>Changes: Fix the logical name of a UI string<commit_after>/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mkeyboardsettingswidget.h"
#include <MButton>
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MContentItem>
#include <MAbstractCellCreator>
#include <MList>
#include <MDialog>
#include <MBanner>
#include <QObject>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QTimer>
#include <QDebug>
namespace
{
//!object name for settings' widgets
const QString ObjectNameSelectedKeyboardsItem("SelectedKeyboardsItem");
const QString ObjectNameErrorCorrectionButton("KeyboardErrorCorrectionButton");
const QString ObjectNameCorrectionSpaceButton("KeyboardCorrectionSpaceButton");
const int MKeyboardLayoutRole = Qt::UserRole + 1;
};
class MKeyboardCellCreator: public MAbstractCellCreator<MContentItem>
{
public:
/*! \reimp */
virtual MWidget *createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const;
virtual void updateCell(const QModelIndex &index, MWidget *cell) const;
/*! \reimp_end */
private:
void updateContentItemMode(const QModelIndex &index, MContentItem *contentItem) const;
};
MWidget *MKeyboardCellCreator::createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const
{
MContentItem *cell = qobject_cast<MContentItem *>(recycler.take("MContentItem"));
if (!cell) {
cell = new MContentItem(MContentItem::SingleTextLabel);
}
updateCell(index, cell);
return cell;
}
void MKeyboardCellCreator::updateCell(const QModelIndex &index, MWidget *cell) const
{
MContentItem *contentItem = qobject_cast<MContentItem *>(cell);
QString layoutTile = index.data(Qt::DisplayRole).toString();
contentItem->setTitle(layoutTile);
}
void MKeyboardCellCreator::updateContentItemMode(const QModelIndex &index,
MContentItem *contentItem) const
{
const int row = index.row();
bool thereIsNextRow = index.sibling(row + 1, 0).isValid();
if (row == 0) {
contentItem->setItemMode(MContentItem::SingleColumnTop);
} else if (thereIsNextRow) {
contentItem->setItemMode(MContentItem::SingleColumnCenter);
} else {
contentItem->setItemMode(MContentItem::SingleColumnBottom);
}
}
MKeyboardSettingsWidget::MKeyboardSettingsWidget(MKeyboardSettings *settings, QGraphicsItem *parent)
: MWidget(parent),
settingsObject(settings),
keyboardDialog(0),
keyboardList(0)
{
MLayout *layout = new MLayout(this);
landscapePolicy = new MGridLayoutPolicy(layout);
landscapePolicy->setContentsMargins(0, 0, 0, 0);
landscapePolicy->setSpacing(0);
//To make sure that both columns have the same width, give them the same preferred width.
landscapePolicy->setColumnPreferredWidth(0, 800);
landscapePolicy->setColumnPreferredWidth(1, 800);
portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);
portraitPolicy->setContentsMargins(0, 0, 0, 0);
portraitPolicy->setSpacing(0);
layout->setLandscapePolicy(landscapePolicy);
layout->setPortraitPolicy(portraitPolicy);
buildUi();
syncErrorCorrectionState();
syncCorrectionSpaceState();
retranslateUi();
connectSlots();
}
MKeyboardSettingsWidget::~MKeyboardSettingsWidget()
{
delete keyboardDialog;
keyboardDialog = 0;
}
void MKeyboardSettingsWidget::buildUi()
{
selectedKeyboardsItem = new MContentItem(MContentItem::TwoTextLabels, this);
selectedKeyboardsItem->setObjectName(ObjectNameSelectedKeyboardsItem);
connect(selectedKeyboardsItem, SIGNAL(clicked()), this, SLOT(showKeyboardList()));
// Put to first row, first column on the grid
addItem(selectedKeyboardsItem, 0, 0);
// Error correction settings
errorCorrectionSwitch = new MButton(this);
errorCorrectionSwitch->setObjectName(ObjectNameErrorCorrectionButton);
errorCorrectionSwitch->setViewType(MButton::switchType);
errorCorrectionSwitch->setCheckable(true);
errorCorrectionContentItem = new MContentItem(MContentItem::TwoTextLabels, this);
//% "Error correction"
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
//% "Error correction description"
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
QGraphicsLinearLayout *eCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
eCLayout->addItem(errorCorrectionContentItem);
eCLayout->addItem(errorCorrectionSwitch);
eCLayout->setAlignment(errorCorrectionSwitch, Qt::AlignCenter);
// Put to first row, second column on the grid
addItem(eCLayout, 0, 1);
// "Space selects the correction candidate" settings
correctionSpaceSwitch = new MButton(this);
correctionSpaceSwitch->setObjectName(ObjectNameCorrectionSpaceButton);
correctionSpaceSwitch->setViewType(MButton::switchType);
correctionSpaceSwitch->setCheckable(true);
correctionSpaceContentItem = new MContentItem(MContentItem::TwoTextLabels, this);
//% "Select with space"
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_select_with_space"));
//% "Select with space description"
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_select_with_space_description"));
QGraphicsLinearLayout *wCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
wCLayout->addItem(correctionSpaceContentItem);
wCLayout->addItem(correctionSpaceSwitch);
wCLayout->setAlignment(correctionSpaceSwitch, Qt::AlignCenter);
// Put to second row, second column on the grid
addItem(wCLayout, 1, 1);
}
void MKeyboardSettingsWidget::addItem(QGraphicsLayoutItem *item, int row, int column)
{
landscapePolicy->addItem(item, row, column);
portraitPolicy->addItem(item);
}
void MKeyboardSettingsWidget::retranslateUi()
{
updateTitle();
MWidget::retranslateUi();
}
void MKeyboardSettingsWidget::updateTitle()
{
if (!errorCorrectionContentItem || !correctionSpaceContentItem
|| !settingsObject || !selectedKeyboardsItem)
return;
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_select_with_space"));
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_select_with_space_description"));
QStringList keyboards = settingsObject->selectedKeyboards().values();
//% "Installed keyboards (%1)"
QString title = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
selectedKeyboardsItem->setTitle(title);
QString brief;
if (keyboards.count() > 0) {
foreach(const QString &keyboard, keyboards) {
if (!brief.isEmpty())
brief += QString(", ");
brief += keyboard;
}
} else {
//% "No keyboards installed"
brief = qtTrId("qtn_txts_no_keyboards");
}
selectedKeyboardsItem->setSubtitle(brief);
if (keyboardDialog) {
keyboardDialog->setTitle(title);
}
}
void MKeyboardSettingsWidget::connectSlots()
{
connect(this, SIGNAL(visibleChanged()),
this, SLOT(handleVisibilityChanged()));
if (!settingsObject || !errorCorrectionSwitch || !correctionSpaceSwitch)
return;
connect(errorCorrectionSwitch, SIGNAL(toggled(bool)),
this, SLOT(setErrorCorrectionState(bool)));
connect(settingsObject, SIGNAL(errorCorrectionChanged()),
this, SLOT(syncErrorCorrectionState()));
connect(correctionSpaceSwitch, SIGNAL(toggled(bool)),
this, SLOT(setCorrectionSpaceState(bool)));
connect(settingsObject, SIGNAL(correctionSpaceChanged()),
this, SLOT(syncCorrectionSpaceState()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateTitle()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateKeyboardSelectionModel()));
}
void MKeyboardSettingsWidget::showKeyboardList()
{
if (!settingsObject || !keyboardDialog) {
QStringList keyboards = settingsObject->selectedKeyboards().values();
QString keyboardTitle = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
keyboardDialog = new MDialog(keyboardTitle, M::NoStandardButton);
keyboardList = new MList(keyboardDialog);
MKeyboardCellCreator *cellCreator = new MKeyboardCellCreator;
keyboardList->setCellCreator(cellCreator);
QStandardItemModel *model = new QStandardItemModel;
model->sort(0);
keyboardList->setItemModel(model);
keyboardList->setSelectionMode(MList::MultiSelection);
keyboardList->setSelectionModel(new QItemSelectionModel(model, this));
keyboardDialog->setCentralWidget(keyboardList);
connect(keyboardList, SIGNAL(itemClicked(const QModelIndex &)),
this, SLOT(updateSelectedKeyboards(const QModelIndex &)));
}
updateKeyboardModel();
keyboardDialog->exec();
}
void MKeyboardSettingsWidget::updateKeyboardModel()
{
if (!settingsObject || !keyboardList)
return;
//always reload available layouts in case user install/remove some layouts
settingsObject->readAvailableKeyboards();
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
model->clear();
QMap<QString, QString> availableKeyboards = settingsObject->availableKeyboards();
QMap<QString, QString>::const_iterator i = availableKeyboards.constBegin();
while (i != availableKeyboards.constEnd()) {
QStandardItem *item = new QStandardItem(i.value());
item->setData(i.value(), Qt::DisplayRole);
item->setData(i.key(), MKeyboardLayoutRole);
model->appendRow(item);
++i;
}
updateKeyboardSelectionModel();
}
void MKeyboardSettingsWidget::updateKeyboardSelectionModel()
{
if (!settingsObject || !keyboardList)
return;
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
foreach (const QString &keyboard, settingsObject->selectedKeyboards().values()) {
QList<QStandardItem *> items = model->findItems(keyboard);
foreach (const QStandardItem *item, items) {
keyboardList->selectionModel()->select(item->index(), QItemSelectionModel::Select);
}
}
}
void MKeyboardSettingsWidget::updateSelectedKeyboards(const QModelIndex &index)
{
if (!settingsObject || !index.isValid() || !keyboardList
|| !keyboardList->selectionModel())
return;
QStringList updatedKeyboardLayouts;
foreach (const QModelIndex &i, keyboardList->selectionModel()->selectedIndexes()) {
updatedKeyboardLayouts << i.data(MKeyboardLayoutRole).toString();
}
if (updatedKeyboardLayouts.isEmpty()) {
notifyNoKeyboards();
}
settingsObject->setSelectedKeyboards(updatedKeyboardLayouts);
//update titles
retranslateUi();
}
void MKeyboardSettingsWidget::setErrorCorrectionState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->errorCorrection() != enabled) {
settingsObject->setErrorCorrection(enabled);
if (!enabled) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::syncErrorCorrectionState()
{
if (!settingsObject)
return;
const bool errorCorrectionState = settingsObject->errorCorrection();
if (errorCorrectionSwitch
&& errorCorrectionSwitch->isChecked() != errorCorrectionState) {
errorCorrectionSwitch->setChecked(errorCorrectionState);
if (!errorCorrectionState) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::setCorrectionSpaceState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->correctionSpace() != enabled)
settingsObject->setCorrectionSpace(enabled);
}
void MKeyboardSettingsWidget::syncCorrectionSpaceState()
{
if (!settingsObject)
return;
const bool correctionSpaceState = settingsObject->correctionSpace();
if (correctionSpaceSwitch
&& correctionSpaceSwitch->isChecked() != correctionSpaceState) {
correctionSpaceSwitch->setChecked(correctionSpaceState);
}
}
void MKeyboardSettingsWidget::notifyNoKeyboards()
{
MBanner *noKeyboardsNotification = new MBanner;
// It is needed to set the proper style name to have properly wrapped, multiple lines
// with too much content. The MBanner documentation also emphasises to specify the
// style name for the banners explicitly in the code.
noKeyboardsNotification->setStyleName("InformationBanner");
//% "Note: you have uninstalled all virtual keyboards"
noKeyboardsNotification->setTitle(qtTrId("qtn_txts_no_keyboards_notification"));
noKeyboardsNotification->appear(MSceneWindow::DestroyWhenDone);
}
void MKeyboardSettingsWidget::handleVisibilityChanged()
{
// This is a workaround to hide settings dialog when keyboard is hidden.
// And it could be removed when NB#177922 is fixed.
if (!isVisible() && keyboardDialog) {
// reject settings dialog if the visibility of settings widget
// is changed from shown to hidden.
keyboardDialog->reject();
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2014, Cauldron Development LLC
Copyright (c) 2003-2014, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include "Transfer.h"
using namespace cb;
using namespace std;
#define BUFFER_SIZE ((streamsize)64 * 1024)
streamsize cb::transfer(istream &in, ostream &out, streamsize length,
SmartPointer<TransferCallback> callback) {
char buffer[BUFFER_SIZE];
streamsize total = 0;
while (!in.fail() && !out.fail()) {
in.read(buffer, length ? min(length, BUFFER_SIZE) : BUFFER_SIZE);
streamsize bytes = in.gcount();
out.write(buffer, bytes);
total += bytes;
if (!callback.isNull() && !callback->transferCallback(bytes)) break;
if (length) {
length -= bytes;
if (!length) break;
}
}
out.flush();
if (out.fail() || length) THROW("Transfer failed");
return total;
}
<commit_msg>web hook test<commit_after>/******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2014, Cauldron Development LLC
Copyright (c) 2003-2014, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include "Transfer.h"
using namespace cb;
using namespace std;
#define BUFFER_SIZE ((streamsize)64 * 1024)
streamsize cb::transfer(istream &in, ostream &out, streamsize length,
SmartPointer<TransferCallback> callback) {
char buffer[BUFFER_SIZE];
streamsize total = 0;
while (!in.fail() && !out.fail()) {
in.read(buffer, length ? min(length, BUFFER_SIZE) : BUFFER_SIZE);
streamsize bytes = in.gcount();
out.write(buffer, bytes);
total += bytes;
if (!callback.isNull() && !callback->transferCallback(bytes)) break;
if (length) {
length -= bytes;
if (!length) break;
}
}
out.flush();
if (out.fail() || length) THROW("Transfer failed");
return total;
}
<|endoftext|>
|
<commit_before>/**********************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
********************************************************************/
#include "gtest/gtest.h"
#include "CLW.h"
#include "basic.h"
#include "camera.h"
int g_argc;
char** g_argv;
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
g_argc = argc;
g_argv = argv;
return RUN_ALL_TESTS();
}
<commit_msg>Add tests<commit_after>/**********************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
********************************************************************/
#include "gtest/gtest.h"
#include "CLW.h"
#include "internal.h"
#include "basic.h"
#include "camera.h"
#include "light.h"
int g_argc;
char** g_argv;
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
g_argc = argc;
g_argv = argv;
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
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.
*/
#include "ContactsOperationFactory.hpp"
#include "RpcOperationFactory_p.hpp"
// TODO: Instead of this include, add a generated cpp with all needed template instances
#include "ServerRpcOperation_p.hpp"
#include "ServerApi.hpp"
#include "ServerRpcLayer.hpp"
#include "TelegramServerUser.hpp"
#include "Debug_p.hpp"
#include "RpcError.hpp"
#include "RpcProcessingContext.hpp"
#include "Utils.hpp"
#include "CTelegramStreamExtraOperators.hpp"
#include "FunctionStreamOperators.hpp"
#include <QLoggingCategory>
namespace Telegram {
namespace Server {
// Generated process methods
bool ContactsRpcOperation::processBlock(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runBlock);
context.inputStream() >> m_block;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processDeleteContact(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runDeleteContact);
context.inputStream() >> m_deleteContact;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processDeleteContacts(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runDeleteContacts);
context.inputStream() >> m_deleteContacts;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processExportCard(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runExportCard);
context.inputStream() >> m_exportCard;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processGetBlocked(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runGetBlocked);
context.inputStream() >> m_getBlocked;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processGetContacts(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runGetContacts);
context.inputStream() >> m_getContacts;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processGetStatuses(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runGetStatuses);
context.inputStream() >> m_getStatuses;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processGetTopPeers(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runGetTopPeers);
context.inputStream() >> m_getTopPeers;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processImportCard(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runImportCard);
context.inputStream() >> m_importCard;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processImportContacts(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runImportContacts);
context.inputStream() >> m_importContacts;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processResetSaved(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runResetSaved);
context.inputStream() >> m_resetSaved;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processResetTopPeerRating(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runResetTopPeerRating);
context.inputStream() >> m_resetTopPeerRating;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processResolveUsername(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runResolveUsername);
context.inputStream() >> m_resolveUsername;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processSearch(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runSearch);
context.inputStream() >> m_search;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processUnblock(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runUnblock);
context.inputStream() >> m_unblock;
return !context.inputStream().error();
}
// End of generated process methods
// Generated run methods
void ContactsRpcOperation::runBlock()
{
if (processNotImplementedMethod(TLValue::ContactsBlock)) {
return;
}
bool result;
sendRpcReply(result);
}
void ContactsRpcOperation::runDeleteContact()
{
qWarning() << Q_FUNC_INFO << "The method implemented!";
TLContactsLink result;
sendRpcReply(result);
}
void ContactsRpcOperation::runDeleteContacts()
{
if (processNotImplementedMethod(TLValue::ContactsDeleteContacts)) {
return;
}
bool result;
sendRpcReply(result);
}
void ContactsRpcOperation::runExportCard()
{
if (processNotImplementedMethod(TLValue::ContactsExportCard)) {
return;
}
TLVector<quint32> result;
sendRpcReply(result);
}
void ContactsRpcOperation::runGetBlocked()
{
if (processNotImplementedMethod(TLValue::ContactsGetBlocked)) {
return;
}
TLContactsBlocked result;
sendRpcReply(result);
}
void ContactsRpcOperation::runGetContacts()
{
TLContactsContacts result;
result.tlType = TLValue::ContactsContacts;
LocalUser *self = layer()->getUser();
const QVector<UserContact> importedContacts = self->importedContacts();
result.contacts.reserve(importedContacts.size());
result.users.reserve(importedContacts.size());
TLUser userInfo;
TLContact outputContact;
for (const UserContact &contact : importedContacts) {
if (contact.id) {
const AbstractUser *contactUser = api()->getAbstractUser(contact.id);
api()->setupTLUser(&userInfo, contactUser, self);
result.users.append(userInfo);
outputContact.userId = contact.id;
outputContact.mutual = userInfo.flags & TLUser::MutualContact;
result.contacts.append(outputContact);
} else {
++result.savedCount;
}
}
sendRpcReply(result);
}
void ContactsRpcOperation::runGetStatuses()
{
if (processNotImplementedMethod(TLValue::ContactsGetStatuses)) {
return;
}
TLVector<TLContactStatus> result;
sendRpcReply(result);
}
void ContactsRpcOperation::runGetTopPeers()
{
if (processNotImplementedMethod(TLValue::ContactsGetTopPeers)) {
return;
}
TLContactsTopPeers result;
sendRpcReply(result);
}
void ContactsRpcOperation::runImportCard()
{
if (processNotImplementedMethod(TLValue::ContactsImportCard)) {
return;
}
TLUser result;
sendRpcReply(result);
}
void ContactsRpcOperation::runImportContacts()
{
qDebug() << Q_FUNC_INFO;
TLContactsImportedContacts result;
LocalUser *self = layer()->getUser();
for (const TLInputContact &c : m_importContacts.contacts) {
UserContact contact;
contact.phone = c.phone;
contact.firstName = c.firstName;
contact.lastName = c.lastName;
AbstractUser *registeredUser = layer()->api()->getAbstractUser(c.phone);
if (registeredUser) {
contact.id = registeredUser->id();
result.users.append(TLUser());
api()->setupTLUser(&result.users.last(), registeredUser, self);
TLImportedContact imported;
imported.clientId = c.clientId;
imported.userId = contact.id;
result.imported.append(imported);
} else {
result.retryContacts.append(c.clientId);
}
self->importContact(contact);
}
sendRpcReply(result);
}
void ContactsRpcOperation::runResetSaved()
{
if (processNotImplementedMethod(TLValue::ContactsResetSaved)) {
return;
}
bool result;
sendRpcReply(result);
}
void ContactsRpcOperation::runResetTopPeerRating()
{
if (processNotImplementedMethod(TLValue::ContactsResetTopPeerRating)) {
return;
}
bool result;
sendRpcReply(result);
}
void ContactsRpcOperation::runResolveUsername()
{
if (processNotImplementedMethod(TLValue::ContactsResolveUsername)) {
return;
}
TLContactsResolvedPeer result;
sendRpcReply(result);
}
void ContactsRpcOperation::runSearch()
{
if (processNotImplementedMethod(TLValue::ContactsSearch)) {
return;
}
TLContactsFound result;
sendRpcReply(result);
}
void ContactsRpcOperation::runUnblock()
{
if (processNotImplementedMethod(TLValue::ContactsUnblock)) {
return;
}
bool result;
sendRpcReply(result);
}
// End of generated run methods
void ContactsRpcOperation::setRunMethod(ContactsRpcOperation::RunMethod method)
{
m_runMethod = method;
}
ContactsRpcOperation::ProcessingMethod ContactsRpcOperation::getMethodForRpcFunction(TLValue function)
{
switch (function) {
// Generated methodForRpcFunction cases
case TLValue::ContactsBlock:
return &ContactsRpcOperation::processBlock;
case TLValue::ContactsDeleteContact:
return &ContactsRpcOperation::processDeleteContact;
case TLValue::ContactsDeleteContacts:
return &ContactsRpcOperation::processDeleteContacts;
case TLValue::ContactsExportCard:
return &ContactsRpcOperation::processExportCard;
case TLValue::ContactsGetBlocked:
return &ContactsRpcOperation::processGetBlocked;
case TLValue::ContactsGetContacts:
return &ContactsRpcOperation::processGetContacts;
case TLValue::ContactsGetStatuses:
return &ContactsRpcOperation::processGetStatuses;
case TLValue::ContactsGetTopPeers:
return &ContactsRpcOperation::processGetTopPeers;
case TLValue::ContactsImportCard:
return &ContactsRpcOperation::processImportCard;
case TLValue::ContactsImportContacts:
return &ContactsRpcOperation::processImportContacts;
case TLValue::ContactsResetSaved:
return &ContactsRpcOperation::processResetSaved;
case TLValue::ContactsResetTopPeerRating:
return &ContactsRpcOperation::processResetTopPeerRating;
case TLValue::ContactsResolveUsername:
return &ContactsRpcOperation::processResolveUsername;
case TLValue::ContactsSearch:
return &ContactsRpcOperation::processSearch;
case TLValue::ContactsUnblock:
return &ContactsRpcOperation::processUnblock;
// End of generated methodForRpcFunction cases
default:
return nullptr;
}
}
RpcOperation *ContactsOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)
{
return processRpcCallImpl<ContactsRpcOperation>(layer, context);
}
} // Server namespace
} // Telegram namespace
<commit_msg>Server: Normalize phone on importContacts()<commit_after>/*
Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
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.
*/
#include "ContactsOperationFactory.hpp"
#include "RpcOperationFactory_p.hpp"
// TODO: Instead of this include, add a generated cpp with all needed template instances
#include "ServerRpcOperation_p.hpp"
#include "ServerApi.hpp"
#include "ServerRpcLayer.hpp"
#include "TelegramServerUser.hpp"
#include "Debug_p.hpp"
#include "RpcError.hpp"
#include "RpcProcessingContext.hpp"
#include "Utils.hpp"
#include "CTelegramStreamExtraOperators.hpp"
#include "FunctionStreamOperators.hpp"
#include <QLoggingCategory>
namespace Telegram {
namespace Server {
// Generated process methods
bool ContactsRpcOperation::processBlock(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runBlock);
context.inputStream() >> m_block;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processDeleteContact(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runDeleteContact);
context.inputStream() >> m_deleteContact;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processDeleteContacts(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runDeleteContacts);
context.inputStream() >> m_deleteContacts;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processExportCard(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runExportCard);
context.inputStream() >> m_exportCard;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processGetBlocked(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runGetBlocked);
context.inputStream() >> m_getBlocked;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processGetContacts(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runGetContacts);
context.inputStream() >> m_getContacts;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processGetStatuses(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runGetStatuses);
context.inputStream() >> m_getStatuses;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processGetTopPeers(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runGetTopPeers);
context.inputStream() >> m_getTopPeers;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processImportCard(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runImportCard);
context.inputStream() >> m_importCard;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processImportContacts(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runImportContacts);
context.inputStream() >> m_importContacts;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processResetSaved(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runResetSaved);
context.inputStream() >> m_resetSaved;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processResetTopPeerRating(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runResetTopPeerRating);
context.inputStream() >> m_resetTopPeerRating;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processResolveUsername(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runResolveUsername);
context.inputStream() >> m_resolveUsername;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processSearch(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runSearch);
context.inputStream() >> m_search;
return !context.inputStream().error();
}
bool ContactsRpcOperation::processUnblock(RpcProcessingContext &context)
{
setRunMethod(&ContactsRpcOperation::runUnblock);
context.inputStream() >> m_unblock;
return !context.inputStream().error();
}
// End of generated process methods
// Generated run methods
void ContactsRpcOperation::runBlock()
{
if (processNotImplementedMethod(TLValue::ContactsBlock)) {
return;
}
bool result;
sendRpcReply(result);
}
void ContactsRpcOperation::runDeleteContact()
{
qWarning() << Q_FUNC_INFO << "The method implemented!";
TLContactsLink result;
sendRpcReply(result);
}
void ContactsRpcOperation::runDeleteContacts()
{
if (processNotImplementedMethod(TLValue::ContactsDeleteContacts)) {
return;
}
bool result;
sendRpcReply(result);
}
void ContactsRpcOperation::runExportCard()
{
if (processNotImplementedMethod(TLValue::ContactsExportCard)) {
return;
}
TLVector<quint32> result;
sendRpcReply(result);
}
void ContactsRpcOperation::runGetBlocked()
{
if (processNotImplementedMethod(TLValue::ContactsGetBlocked)) {
return;
}
TLContactsBlocked result;
sendRpcReply(result);
}
void ContactsRpcOperation::runGetContacts()
{
TLContactsContacts result;
result.tlType = TLValue::ContactsContacts;
LocalUser *self = layer()->getUser();
const QVector<UserContact> importedContacts = self->importedContacts();
result.contacts.reserve(importedContacts.size());
result.users.reserve(importedContacts.size());
TLUser userInfo;
TLContact outputContact;
for (const UserContact &contact : importedContacts) {
if (contact.id) {
const AbstractUser *contactUser = api()->getAbstractUser(contact.id);
api()->setupTLUser(&userInfo, contactUser, self);
result.users.append(userInfo);
outputContact.userId = contact.id;
outputContact.mutual = userInfo.flags & TLUser::MutualContact;
result.contacts.append(outputContact);
} else {
++result.savedCount;
}
}
sendRpcReply(result);
}
void ContactsRpcOperation::runGetStatuses()
{
if (processNotImplementedMethod(TLValue::ContactsGetStatuses)) {
return;
}
TLVector<TLContactStatus> result;
sendRpcReply(result);
}
void ContactsRpcOperation::runGetTopPeers()
{
if (processNotImplementedMethod(TLValue::ContactsGetTopPeers)) {
return;
}
TLContactsTopPeers result;
sendRpcReply(result);
}
void ContactsRpcOperation::runImportCard()
{
if (processNotImplementedMethod(TLValue::ContactsImportCard)) {
return;
}
TLUser result;
sendRpcReply(result);
}
void ContactsRpcOperation::runImportContacts()
{
qDebug() << Q_FUNC_INFO;
TLContactsImportedContacts result;
LocalUser *self = layer()->getUser();
for (const TLInputContact &c : m_importContacts.contacts) {
UserContact contact;
contact.phone = api()->normalizeIdentifier(c.phone);
contact.firstName = c.firstName;
contact.lastName = c.lastName;
AbstractUser *registeredUser = api()->getAbstractUser(contact.phone);
if (registeredUser) {
contact.id = registeredUser->id();
result.users.append(TLUser());
api()->setupTLUser(&result.users.last(), registeredUser, self);
TLImportedContact imported;
imported.clientId = c.clientId;
imported.userId = contact.id;
result.imported.append(imported);
} else {
result.retryContacts.append(c.clientId);
}
self->importContact(contact);
}
sendRpcReply(result);
}
void ContactsRpcOperation::runResetSaved()
{
if (processNotImplementedMethod(TLValue::ContactsResetSaved)) {
return;
}
bool result;
sendRpcReply(result);
}
void ContactsRpcOperation::runResetTopPeerRating()
{
if (processNotImplementedMethod(TLValue::ContactsResetTopPeerRating)) {
return;
}
bool result;
sendRpcReply(result);
}
void ContactsRpcOperation::runResolveUsername()
{
if (processNotImplementedMethod(TLValue::ContactsResolveUsername)) {
return;
}
TLContactsResolvedPeer result;
sendRpcReply(result);
}
void ContactsRpcOperation::runSearch()
{
if (processNotImplementedMethod(TLValue::ContactsSearch)) {
return;
}
TLContactsFound result;
sendRpcReply(result);
}
void ContactsRpcOperation::runUnblock()
{
if (processNotImplementedMethod(TLValue::ContactsUnblock)) {
return;
}
bool result;
sendRpcReply(result);
}
// End of generated run methods
void ContactsRpcOperation::setRunMethod(ContactsRpcOperation::RunMethod method)
{
m_runMethod = method;
}
ContactsRpcOperation::ProcessingMethod ContactsRpcOperation::getMethodForRpcFunction(TLValue function)
{
switch (function) {
// Generated methodForRpcFunction cases
case TLValue::ContactsBlock:
return &ContactsRpcOperation::processBlock;
case TLValue::ContactsDeleteContact:
return &ContactsRpcOperation::processDeleteContact;
case TLValue::ContactsDeleteContacts:
return &ContactsRpcOperation::processDeleteContacts;
case TLValue::ContactsExportCard:
return &ContactsRpcOperation::processExportCard;
case TLValue::ContactsGetBlocked:
return &ContactsRpcOperation::processGetBlocked;
case TLValue::ContactsGetContacts:
return &ContactsRpcOperation::processGetContacts;
case TLValue::ContactsGetStatuses:
return &ContactsRpcOperation::processGetStatuses;
case TLValue::ContactsGetTopPeers:
return &ContactsRpcOperation::processGetTopPeers;
case TLValue::ContactsImportCard:
return &ContactsRpcOperation::processImportCard;
case TLValue::ContactsImportContacts:
return &ContactsRpcOperation::processImportContacts;
case TLValue::ContactsResetSaved:
return &ContactsRpcOperation::processResetSaved;
case TLValue::ContactsResetTopPeerRating:
return &ContactsRpcOperation::processResetTopPeerRating;
case TLValue::ContactsResolveUsername:
return &ContactsRpcOperation::processResolveUsername;
case TLValue::ContactsSearch:
return &ContactsRpcOperation::processSearch;
case TLValue::ContactsUnblock:
return &ContactsRpcOperation::processUnblock;
// End of generated methodForRpcFunction cases
default:
return nullptr;
}
}
RpcOperation *ContactsOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)
{
return processRpcCallImpl<ContactsRpcOperation>(layer, context);
}
} // Server namespace
} // Telegram namespace
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <iomanip>
using namespace std;
typedef unsigned long long int ulli;
vector<ulli> collatz(ulli number){
vector<ulli> seq;
while(number > 1){
if( number%2 == 1 ){
number = (3*number) + 1;
seq.push_back(number)
}
else{
number = number/2;
seq.push_back(number)
}
}
return seq;
}
void printsequence(vector<ulli> &seq){
for(int i = 0;i < seq.size();i++){
cout<<seq[i]<<" ";
}
cout<<endl;
}
int main(){
ios_base::sync_with_stdio(false);
ulli number;
cout<<"Enter the number for which collatz sequence is to be displayed : ";
cin>>number;
vector<ulli> sequence;
sequence = collatz(number);
printsequence(sequence);
return 0;
}
<commit_msg>Fixed Missing Semicolon error in collatz_conjecture.cpp<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <iomanip>
using namespace std;
typedef unsigned long long int ulli;
vector<ulli> collatz(ulli number){
vector<ulli> seq;
while(number > 1){
if( number%2 == 1 ){
number = (3*number) + 1;
seq.push_back(number);
}
else{
number = number/2;
seq.push_back(number);
}
}
return seq;
}
void printsequence(vector<ulli> &seq){
for(int i = 0;i < seq.size();i++){
cout<<seq[i]<<" ";
}
cout<<endl;
}
int main(){
ios_base::sync_with_stdio(false);
ulli number;
cout<<"Enter the number for which collatz sequence is to be displayed : ";
cin>>number;
vector<ulli> sequence;
sequence = collatz(number);
printsequence(sequence);
return 0;
}
<|endoftext|>
|
<commit_before>#include "ElectronicWireGenerator.hpp"
#include "ClipperUtils.hpp"
#include "SVG.hpp"
namespace Slic3r {
ElectronicWireGenerator::ElectronicWireGenerator(Layer* layer, double extrusion_width,
double extrusion_overlap, double first_extrusion_overlap, double overlap_min_extrusion_length, double conductive_wire_channel_width) :
layer(layer),
extrusion_width(extrusion_width),
extrusion_overlap(extrusion_overlap),
first_extrusion_overlap(first_extrusion_overlap),
overlap_min_extrusion_length(overlap_min_extrusion_length),
conductive_wire_channel_width(conductive_wire_channel_width),
slices(&(layer->slices)),
unrouted_wires(layer->unrouted_wires){}
void
ElectronicWireGenerator::process()
{
// contour following should happen at this point...
this->refine_wires();
// cut wires and apply overlaps
this->apply_overlap(this->routed_wires, &(this->layer->wires));
SVG svg("refine_wires_result.svg");
svg.draw(*(this->slices), "black");
svg.draw(this->layer->wires, "red", scale_(this->extrusion_width)/2);
svg.arrows = false;
svg.Close();
}
void ElectronicWireGenerator::refine_wires()
{
// clip polyline against polygon. Check result: identical? split into multiple parts?
SVG svg("refine_wires.svg");
svg.draw(*(this->slices), "black");
bool debug_flag = true;
//svg.draw(this->unrouted_wires, "red");
int index = 0;
// number of applicable perimeters
int perimeters = 9999;
for(const auto ®ion : this->layer->regions) {
perimeters = std::min(perimeters, region->region()->config.perimeters.value);
}
// ensure at least 1 perimeter for polygon offsetting
perimeters = std::max(1, perimeters);
this->sort_unrouted_wires();
for(const auto &unrouted_wire : this->unrouted_wires) {
std::ostringstream ss;
ss << "wire_debug_";
ss << index;
ss << ".svg";
std::string filename = ss.str();
std::cout << "filename: " << filename << std::endl;
SVG svg(filename.c_str());
debug_flag = true;
index++;
svg.draw(*(this->slices), "black");
Polyline routed_wire;
routed_wire.append(unrouted_wire.first_point());// add first point
for(auto &line : unrouted_wire.lines()) {
bool outside_expolygon = false;
// generate set of inflated expolygons. Inflate by perimeter width per region and channel width.
ExPolygonCollection inflated_slices;
for(const auto ®ion : this->layer->regions) {
/*const coord_t perimeter_spacing = region->flow(frPerimeter).scaled_spacing();
const coord_t ext_perimeter_width = region->flow(frExternalPerimeter).scaled_width();
const coord_t ext_perimeter_spacing = region->flow(frExternalPerimeter).scaled_spacing();
// compute the total thickness of perimeters
const coord_t perimeters_thickness = ext_perimeter_width
+ (region->region()->config.perimeters-1) * perimeter_spacing
+ scale_(this->extrusion_width/2 + this->conductive_wire_channel_width/2);
*/
const coord_t perimeters_thickness = this->offset_width(region, region->region()->config.perimeters);
/* std::cout << std::endl;
std::cout << "perimeter_spacing: " << perimeter_spacing << std::endl;
std::cout << "ext_perimeter_width: " << ext_perimeter_width << std::endl;
std::cout << "ext_perimeter_spacing: " << ext_perimeter_spacing << std::endl;
std::cout << "perimeters_thickness: " << unscale(perimeters_thickness) << std::endl;
std::cout << "external perimeter: " << ext_perimeter_width << std::endl;
std::cout << "internal perimeters: " << (region->region()->config.perimeters-1) * perimeter_spacing << std::endl;
std::cout << "number of internal perimeters: " << region->region()->config.perimeters << std::endl;
std::cout << "half channel: " << scale_(this->extrusion_width/2 + this->conductive_wire_channel_width/2) << std::endl;
std::cout << "extrusion width : " << scale_(this->extrusion_width/2) << " + channel width: " << scale_(this->conductive_wire_channel_width/2) << std::endl;
std::cout << std::endl;
*/
inflated_slices.append(offset_ex((Polygons)region->slices, -perimeters_thickness));
}
if(debug_flag) {
svg.draw(inflated_slices, "blue");
debug_flag = false;
}
while(true) {
Point intersection;
bool ccw;
const Polygon* p;
const ExPolygon* ep;
// find intersections with all expolygons
while(inflated_slices.first_intersection(line, &intersection, &ccw, &p, &ep)) {
std::cout << "in loop" << std::endl;
if(ccw) { // leaving expolygon
outside_expolygon = true;
svg.draw(Line(line.a, intersection), "red", scale_(this->extrusion_width));
Line l(line.a, intersection);
l.extend_end(scale_(EPSILON));
intersection = l.b;
routed_wire.append(intersection);
}else{ // entering expolygon
// follow contour
if(routed_wire.is_valid() && outside_expolygon) { // at least 2 points
outside_expolygon = false;
// convert to polyline
Polyline pl = *p;
// split at entry point
Polyline pl_tmp, pl1, pl2;
pl.split_at(routed_wire.last_point(), &pl1, &pl_tmp);
pl_tmp.append(pl1); // append first half (until entry split) to second half (rest)
pl_tmp.split_at(intersection, &pl1, &pl2);
// compare lenghts, add shorter polyline
if(pl1.length() < pl2.length()) {
routed_wire.append(pl1);
svg.draw(pl1, "green", scale_(this->extrusion_width));
svg.draw(pl2, "orange", scale_(this->extrusion_width)/2);
}else{
pl2.reverse();
routed_wire.append(pl2);
svg.draw(pl2, "green", scale_(this->extrusion_width));
svg.draw(pl1, "orange", scale_(this->extrusion_width)/2);
}
}
std::cout << "routing done" << std::endl;
Line l(line.a, intersection);
l.extend_end(scale_(EPSILON));
intersection = l.b;
svg.draw(Line(routed_wire.last_point(), intersection), "red", scale_(this->extrusion_width));
routed_wire.append(intersection);
}
line.a = intersection;
}
// no further intersections found, rest must be inside or outside of slices. Append linear line
svg.draw(line, "red", scale_(this->extrusion_width));
routed_wire.append(line.b);
std::cout << "append rest" << std::endl;
break;
}
}
svg.draw(routed_wire, "yellow", scale_(this->extrusion_width));
routed_wire.remove_loops();
this->channel_from_wire(routed_wire);
this->routed_wires.push_back(routed_wire);
svg.draw(routed_wire, "white", scale_(this->extrusion_width)/2);
svg.arrows = false;
svg.Close();
// any perimeter contact for this wire?
//Polylines diff_pl = diff_pl(wire.Polylines(), const Slic3r::Polygons &clip, bool safety_offset_ = false)
}
}
void ElectronicWireGenerator::sort_unrouted_wires()
{
// number of applicable perimeters
int perimeters = 9999;
for(const auto ®ion : this->layer->regions) {
perimeters = std::min(perimeters, region->region()->config.perimeters.value);
}
coord_t wire_offset = this->offset_width(this->layer->regions.front(), perimeters);
// generate channel expolygonCollection
ExPolygonCollection inflated_wires;
for(const auto &unrouted_wire : this->unrouted_wires) {
// double offsetting for channels. 1 step generates a polygon from the polyline,
// 2. step extends the polygon to avoid cropped angles.
inflated_wires.append(offset_ex(offset(unrouted_wire, scale_(0.01)), wire_offset - scale_(0.01)));
}
// count intersections with channels created by other wires
std::vector<unsigned int> intersections;
for(const auto &unrouted_wire : this->unrouted_wires) {
intersections.push_back(0);
for(auto &line : unrouted_wire.lines()) {
Point intersection;
bool ccw;
const Polygon* p;
const ExPolygon* ep;
while(inflated_wires.first_intersection(line, &intersection, &ccw, &p, &ep)) {
intersections.back()++;
Line l(line.a, intersection);
l.extend_end(scale_(EPSILON));
line.a = l.b;
}
}
}
// perform actual sort
Polylines local_copy = std::move(this->unrouted_wires);
this->unrouted_wires.clear();
while(intersections.size() > 0) {
int min_pos = 0;
double min_len = 0;
unsigned int min_intersections = 999999;
for(int i = 0; i < intersections.size(); i++) {
//second stage of sorting: by line length
if(intersections[i] == min_intersections) {
if(local_copy[i].length() < min_len) {
min_intersections = intersections[i];
min_pos = i;
min_len = local_copy[i].length();
}
}
// first stage of sorting: by intersections
if(intersections[i] < min_intersections) {
min_intersections = intersections[i];
min_pos = i;
min_len = local_copy[i].length();
}
}
this->unrouted_wires.push_back(local_copy[min_pos]);
local_copy.erase(local_copy.begin()+min_pos);
intersections.erase(intersections.begin()+min_pos);
}
}
void ElectronicWireGenerator::channel_from_wire(Polyline &wire)
{
Polygons bed_polygons;
Polygons channel_polygons;
// double offsetting for channels. 1 step generates a polygon from the polyline,
// 2. step extends the polygon to avoid cropped angles.
bed_polygons = offset(wire, scale_(0.01));
channel_polygons = offset(bed_polygons, scale_(this->extrusion_width/2 + this->conductive_wire_channel_width/2 - 0.01));
// remove beds and channels from layer
for(const auto ®ion : this->layer->regions) {
region->modify_slices(channel_polygons, false);
}
// if lower_layer is defined, use channel to create a "bed" by offsetting only a small amount
// generate a bed by offsetting a small amount to trigger perimeter generation
if (this->layer->lower_layer != nullptr) {
FOREACH_LAYERREGION(this->layer->lower_layer, layerm) {
(*layerm)->modify_slices(bed_polygons, false);
}
this->layer->lower_layer->setDirty(true);
}
this->layer->setDirty(true);
}
// clip wires to extrude from center to smd-pad and add overlaps
// at extrusion start points
void ElectronicWireGenerator::apply_overlap(Polylines input, Polylines *output)
{
if(input.size() > 0) {
// find longest path for this layer and apply higher overlapping
Polylines::iterator max_len_pl;
double max_len = 0;
for (Polylines::iterator pl = input.begin(); pl != input.end(); ++pl) {
if(pl->length() > max_len) {
max_len = pl->length();
max_len_pl = pl;
}
}
// move longest line to front
Polyline longest_line = (*max_len_pl);
input.erase(max_len_pl);
input.insert(input.begin(), longest_line);
// split paths to equal length parts with small overlap to have extrusion ending at endpoint
for(auto &pl : input) {
double clip_length;
if(&pl == &input.front()) {
clip_length = pl.length()/2 - this->first_extrusion_overlap; // first extrusion at this layer
}else{
clip_length = pl.length()/2 - this->extrusion_overlap; // normal extrusion overlap
}
// clip start and end of each trace by extrusion_width/2 to achieve correct line endpoints
pl.clip_start(scale_(this->extrusion_width/2));
pl.clip_end(scale_(this->extrusion_width/2));
// clip line if long enough and push to wires collection
if(((pl.length()/2 - clip_length) > EPSILON) && (pl.length() > this->overlap_min_extrusion_length)) {
Polyline pl2 = pl;
//first half
pl.clip_end(clip_length);
pl.reverse();
pl.remove_duplicate_points();
if(pl.length() > scale_(0.05)) {
output->push_back(pl);
}
//second half
pl2.clip_start(clip_length);
pl2.remove_duplicate_points();
if(pl2.length() > scale_(0.05)) {
output->push_back(pl2);
}
}else{ // just push it to the wires collection otherwise
output->push_back(pl);
}
}
}
}
coord_t ElectronicWireGenerator::offset_width(const LayerRegion* region, int perimeters) const
{
perimeters = std::max(perimeters, 1);
const coord_t perimeter_spacing = region->flow(frPerimeter).scaled_spacing();
const coord_t ext_perimeter_width = region->flow(frExternalPerimeter).scaled_width();
// compute the total thickness of perimeters
const coord_t result = ext_perimeter_width
+ (perimeters-1) * perimeter_spacing
+ scale_(this->extrusion_width/2 + this->conductive_wire_channel_width/2);
return result;
}
}
<commit_msg>Generate offsetted polygons for each of n perimeters to test for routing collisions<commit_after>#include "ElectronicWireGenerator.hpp"
#include "ClipperUtils.hpp"
#include "SVG.hpp"
namespace Slic3r {
ElectronicWireGenerator::ElectronicWireGenerator(Layer* layer, double extrusion_width,
double extrusion_overlap, double first_extrusion_overlap, double overlap_min_extrusion_length, double conductive_wire_channel_width) :
layer(layer),
extrusion_width(extrusion_width),
extrusion_overlap(extrusion_overlap),
first_extrusion_overlap(first_extrusion_overlap),
overlap_min_extrusion_length(overlap_min_extrusion_length),
conductive_wire_channel_width(conductive_wire_channel_width),
slices(&(layer->slices)),
unrouted_wires(layer->unrouted_wires){}
void
ElectronicWireGenerator::process()
{
// contour following should happen at this point...
this->refine_wires();
// cut wires and apply overlaps
this->apply_overlap(this->routed_wires, &(this->layer->wires));
SVG svg("refine_wires_result.svg");
svg.draw(*(this->slices), "black");
svg.draw(this->layer->wires, "red", scale_(this->extrusion_width)/2);
svg.arrows = false;
svg.Close();
}
void ElectronicWireGenerator::refine_wires()
{
// clip polyline against polygon. Check result: identical? split into multiple parts?
SVG svg("refine_wires.svg");
svg.draw(*(this->slices), "black");
bool debug_flag = true;
//svg.draw(this->unrouted_wires, "red");
int index = 0;
// number of applicable perimeters
int max_perimeters = 9999;
for(const auto ®ion : this->layer->regions) {
max_perimeters = std::min(max_perimeters, region->region()->config.perimeters.value);
}
// ensure at least 1 perimeter for polygon offsetting
max_perimeters = std::max(1, max_perimeters);
this->sort_unrouted_wires();
for(const auto &unrouted_wire : this->unrouted_wires) {
std::ostringstream ss;
ss << "wire_debug_";
ss << index;
ss << ".svg";
std::string filename = ss.str();
std::cout << "filename: " << filename << std::endl;
SVG svg(filename.c_str());
debug_flag = true;
index++;
svg.draw(*(this->slices), "black");
Polyline routed_wire;
routed_wire.append(unrouted_wire.first_point());// add first point
for(auto &line : unrouted_wire.lines()) {
// generate set of inflated expolygons. Inflate by perimeter width per region and channel width.
ExPolygonCollection inflated_slices;
std::vector<ExPolygonCollection> inflated_slices2;
for(int i=0; i < max_perimeters; i++) {
// initialize vector element
inflated_slices2.push_back(ExPolygonCollection());
for(const auto ®ion : this->layer->regions) {
/*const coord_t perimeter_spacing = region->flow(frPerimeter).scaled_spacing();
const coord_t ext_perimeter_width = region->flow(frExternalPerimeter).scaled_width();
const coord_t ext_perimeter_spacing = region->flow(frExternalPerimeter).scaled_spacing();
// compute the total thickness of perimeters
const coord_t perimeters_thickness = ext_perimeter_width
+ (region->region()->config.perimeters-1) * perimeter_spacing
+ scale_(this->extrusion_width/2 + this->conductive_wire_channel_width/2);
*/
//const coord_t perimeters_thickness = this->offset_width(region, region->region()->config.perimeters);
const coord_t perimeters_thickness = this->offset_width(region, i+1);
/* std::cout << std::endl;
std::cout << "perimeter_spacing: " << perimeter_spacing << std::endl;
std::cout << "ext_perimeter_width: " << ext_perimeter_width << std::endl;
std::cout << "ext_perimeter_spacing: " << ext_perimeter_spacing << std::endl;
std::cout << "perimeters_thickness: " << unscale(perimeters_thickness) << std::endl;
std::cout << "external perimeter: " << ext_perimeter_width << std::endl;
std::cout << "internal perimeters: " << (region->region()->config.perimeters-1) * perimeter_spacing << std::endl;
std::cout << "number of internal perimeters: " << region->region()->config.perimeters << std::endl;
std::cout << "half channel: " << scale_(this->extrusion_width/2 + this->conductive_wire_channel_width/2) << std::endl;
std::cout << "extrusion width : " << scale_(this->extrusion_width/2) << " + channel width: " << scale_(this->conductive_wire_channel_width/2) << std::endl;
std::cout << std::endl;
*/
//inflated_slices.append(offset_ex((Polygons)region->slices, -perimeters_thickness));
inflated_slices2[i].append(offset_ex((Polygons)region->slices, -perimeters_thickness));
}
}
if(debug_flag) {
int c = 50;
for(int i=0; i < max_perimeters; i++) {
std::ostringstream ss;
ss << "rgb(" << 100 << "," << c << "," << c << ")";
std::string color = ss.str();
svg.draw(inflated_slices2[i], color);
c += 50;
}
debug_flag = false;
}
bool outside_expolygon = false;
int current_perimeters = 1;
while(true) {
Point intersection;
bool ccw;
const Polygon* p;
const ExPolygon* ep;
// find intersections with all expolygons
while(inflated_slices2[current_perimeters].first_intersection(line, &intersection, &ccw, &p, &ep)) {
std::cout << "in loop" << std::endl;
if(ccw) { // leaving expolygon
outside_expolygon = true;
svg.draw(Line(line.a, intersection), "red", scale_(this->extrusion_width));
Line l(line.a, intersection);
l.extend_end(scale_(EPSILON));
intersection = l.b;
routed_wire.append(intersection);
current_perimeters = 1;
}else{ // entering expolygon
// follow contour
if(routed_wire.is_valid() && outside_expolygon) { // at least 2 points
outside_expolygon = false;
Polyline result_pl;
//while(current_perimeters <= max_perimeters) {
// convert to polyline
Polyline pl = *p;
// split at entry point
Polyline pl_tmp, pl1, pl2;
pl.split_at(routed_wire.last_point(), &pl1, &pl_tmp);
pl_tmp.append(pl1); // append first half (until entry split) to second half (rest)
pl_tmp.split_at(intersection, &pl1, &pl2);
// compare lenghts, add shorter polyline
if(pl1.length() < pl2.length()) {
//routed_wire.append(pl1);
result_pl = pl1;
svg.draw(pl1, "green", scale_(this->extrusion_width));
svg.draw(pl2, "orange", scale_(this->extrusion_width)/2);
}else{
pl2.reverse();
//routed_wire.append(pl2);
result_pl = pl2;
svg.draw(pl2, "green", scale_(this->extrusion_width));
svg.draw(pl1, "orange", scale_(this->extrusion_width)/2);
}
// current_perimeters++;
//}
routed_wire.append(result_pl);
}
std::cout << "routing done" << std::endl;
Line l(line.a, intersection);
l.extend_end(scale_(EPSILON));
intersection = l.b;
svg.draw(Line(routed_wire.last_point(), intersection), "red", scale_(this->extrusion_width));
routed_wire.append(intersection);
}
line.a = intersection;
}
// no further intersections found, rest must be inside or outside of slices. Append linear line
svg.draw(line, "red", scale_(this->extrusion_width));
routed_wire.append(line.b);
std::cout << "append rest" << std::endl;
break;
}
}
svg.draw(routed_wire, "yellow", scale_(this->extrusion_width));
routed_wire.remove_loops();
this->channel_from_wire(routed_wire);
this->routed_wires.push_back(routed_wire);
svg.draw(routed_wire, "white", scale_(this->extrusion_width)/2);
svg.arrows = false;
svg.Close();
// any perimeter contact for this wire?
//Polylines diff_pl = diff_pl(wire.Polylines(), const Slic3r::Polygons &clip, bool safety_offset_ = false)
}
}
void ElectronicWireGenerator::sort_unrouted_wires()
{
// number of applicable perimeters
int perimeters = 9999;
for(const auto ®ion : this->layer->regions) {
perimeters = std::min(perimeters, region->region()->config.perimeters.value);
}
coord_t wire_offset = this->offset_width(this->layer->regions.front(), perimeters);
// generate channel expolygonCollection
ExPolygonCollection inflated_wires;
for(const auto &unrouted_wire : this->unrouted_wires) {
// double offsetting for channels. 1 step generates a polygon from the polyline,
// 2. step extends the polygon to avoid cropped angles.
inflated_wires.append(offset_ex(offset(unrouted_wire, scale_(0.01)), wire_offset - scale_(0.01)));
}
// count intersections with channels created by other wires
std::vector<unsigned int> intersections;
for(const auto &unrouted_wire : this->unrouted_wires) {
intersections.push_back(0);
for(auto &line : unrouted_wire.lines()) {
Point intersection;
bool ccw;
const Polygon* p;
const ExPolygon* ep;
while(inflated_wires.first_intersection(line, &intersection, &ccw, &p, &ep)) {
intersections.back()++;
Line l(line.a, intersection);
l.extend_end(scale_(EPSILON));
line.a = l.b;
}
}
}
// perform actual sort
Polylines local_copy = std::move(this->unrouted_wires);
this->unrouted_wires.clear();
while(intersections.size() > 0) {
int min_pos = 0;
double min_len = 0;
unsigned int min_intersections = 999999;
for(int i = 0; i < intersections.size(); i++) {
//second stage of sorting: by line length
if(intersections[i] == min_intersections) {
if(local_copy[i].length() < min_len) {
min_intersections = intersections[i];
min_pos = i;
min_len = local_copy[i].length();
}
}
// first stage of sorting: by intersections
if(intersections[i] < min_intersections) {
min_intersections = intersections[i];
min_pos = i;
min_len = local_copy[i].length();
}
}
this->unrouted_wires.push_back(local_copy[min_pos]);
local_copy.erase(local_copy.begin()+min_pos);
intersections.erase(intersections.begin()+min_pos);
}
}
void ElectronicWireGenerator::channel_from_wire(Polyline &wire)
{
Polygons bed_polygons;
Polygons channel_polygons;
// double offsetting for channels. 1 step generates a polygon from the polyline,
// 2. step extends the polygon to avoid cropped angles.
bed_polygons = offset(wire, scale_(0.01));
channel_polygons = offset(bed_polygons, scale_(this->extrusion_width/2 + this->conductive_wire_channel_width/2 - 0.01));
// remove beds and channels from layer
for(const auto ®ion : this->layer->regions) {
region->modify_slices(channel_polygons, false);
}
// if lower_layer is defined, use channel to create a "bed" by offsetting only a small amount
// generate a bed by offsetting a small amount to trigger perimeter generation
if (this->layer->lower_layer != nullptr) {
FOREACH_LAYERREGION(this->layer->lower_layer, layerm) {
(*layerm)->modify_slices(bed_polygons, false);
}
this->layer->lower_layer->setDirty(true);
}
this->layer->setDirty(true);
}
// clip wires to extrude from center to smd-pad and add overlaps
// at extrusion start points
void ElectronicWireGenerator::apply_overlap(Polylines input, Polylines *output)
{
if(input.size() > 0) {
// find longest path for this layer and apply higher overlapping
Polylines::iterator max_len_pl;
double max_len = 0;
for (Polylines::iterator pl = input.begin(); pl != input.end(); ++pl) {
if(pl->length() > max_len) {
max_len = pl->length();
max_len_pl = pl;
}
}
// move longest line to front
Polyline longest_line = (*max_len_pl);
input.erase(max_len_pl);
input.insert(input.begin(), longest_line);
// split paths to equal length parts with small overlap to have extrusion ending at endpoint
for(auto &pl : input) {
double clip_length;
if(&pl == &input.front()) {
clip_length = pl.length()/2 - this->first_extrusion_overlap; // first extrusion at this layer
}else{
clip_length = pl.length()/2 - this->extrusion_overlap; // normal extrusion overlap
}
// clip start and end of each trace by extrusion_width/2 to achieve correct line endpoints
pl.clip_start(scale_(this->extrusion_width/2));
pl.clip_end(scale_(this->extrusion_width/2));
// clip line if long enough and push to wires collection
if(((pl.length()/2 - clip_length) > EPSILON) && (pl.length() > this->overlap_min_extrusion_length)) {
Polyline pl2 = pl;
//first half
pl.clip_end(clip_length);
pl.reverse();
pl.remove_duplicate_points();
if(pl.length() > scale_(0.05)) {
output->push_back(pl);
}
//second half
pl2.clip_start(clip_length);
pl2.remove_duplicate_points();
if(pl2.length() > scale_(0.05)) {
output->push_back(pl2);
}
}else{ // just push it to the wires collection otherwise
output->push_back(pl);
}
}
}
}
coord_t ElectronicWireGenerator::offset_width(const LayerRegion* region, int perimeters) const
{
perimeters = std::max(perimeters, 1);
const coord_t perimeter_spacing = region->flow(frPerimeter).scaled_spacing();
const coord_t ext_perimeter_width = region->flow(frExternalPerimeter).scaled_width();
// compute the total thickness of perimeters
const coord_t result = ext_perimeter_width
+ (perimeters-1) * perimeter_spacing
+ scale_(this->extrusion_width/2 + this->conductive_wire_channel_width/2);
return result;
}
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include "Battle.h"
#include "Creature.h"
#include "Dialogue.h"
BattleEvent::BattleEvent(Creature* _source, Creature* _target, BattleEventType _type)
: source(_source), target(_target), type(_type)
{
}
Creature* BattleEvent::GetSource()
{
return source;
}
Creature* BattleEvent::GetTarget()
{
return target;
}
BattleEventType BattleEvent::GetType()
{
return type;
}
int BattleEvent::Run()
{
switch (type)
{
case BattleEventType::ATTACK:
return source->Attack(target);
case BattleEventType::DEFEND:
return 0;
default:
return 0;
}
}
Battle::Battle(std::vector<Creature*>& _combatants)
: combatants(_combatants)
{
battleOptions = Dialogue("What will you do?", { "Attack", "Defend" });
std::map<std::string, int> names;
for (auto com : combatants)
{
if (com->GetID() == "Player")
continue;
if (names.count(com->GetName()) == 0)
names[com->GetName()] = 0;
else if (names[com->GetName()] == 0)
names[com->GetName()] = 1;
}
for (auto& com : combatants)
{
std::string newName = com->GetName();
if (names.count(com->GetName()) > 0 && names[com->GetName()] > 0)
{
newName += " (" + std::to_string(names[com->GetName()]) + ")";
names[com->GetName()] += 1;
}
com->GetName() = newName;
}
}
void Battle::Run()
{
// TODO : check player != end
std::vector<Creature*>::iterator player;
std::vector<Creature*>::iterator end;
do {
player = std::find_if(combatants.begin(), combatants.end(),
[](Creature* creature) { return creature->GetID() == "Player"; });
end = combatants.end();
NextTurn();
} while (combatants.size() > 1 && player != end);
}
void Battle::Kill(Creature* creature)
{
auto pos = std::find(combatants.begin(), combatants.end(), creature);
if (pos != combatants.end())
{
std::cout << creature->GetName() << " is slain!" << std::endl;
creature->SetHP(0);
combatants.erase(pos);
}
}
void Battle::NextTurn()
{
std::queue<BattleEvent> events;
std::sort(combatants.begin(), combatants.end(),
[](Creature* a, Creature* b) { return a->GetAgility() > b->GetAgility(); });
for (auto com : combatants)
{
if (com->GetID() == "Player")
{
Dialogue targetSelection = Dialogue("Who?", {});
for (auto target : combatants)
if (target->GetID() != "Player")
targetSelection.AddChoice(target->GetName());
int choice = battleOptions.Activate();
switch (choice)
{
default:
case 1:
{
int position = targetSelection.Activate();
for (int i = 0; i < position; i++)
if (combatants[i]->GetID() == "Player")
position++;
Creature* target = combatants[position - 1];
events.push(BattleEvent(com, target, BattleEventType::ATTACK));
break;
}
case 2:
{
events.push(BattleEvent(com, nullptr, BattleEventType::DEFEND));
break;
}
}
}
else
{
Creature* player = *std::find_if(combatants.begin(), combatants.end(),
[](Creature* a) { return a->GetID() == "Player"; });
events.push(BattleEvent(com, player, BattleEventType::ATTACK));
}
}
while (!events.empty())
{
BattleEvent event = events.front();
Creature *pSourceObject = event.GetSource();
Creature *pTargetObject = event.GetTarget();
switch (event.GetType())
{
case BattleEventType::ATTACK:
{
auto a = combatants.begin();
auto b = combatants.end();
if (std::find(a, b, pSourceObject) == b || std::find(a, b, pTargetObject) == b)
break;
std::cout << pSourceObject->GetName() << " attacks " << pTargetObject->GetName() << " for " << event.Run() << " damage!" << std::endl;
std::cout << pTargetObject->GetName() << " : " << pTargetObject->GetHP() << "Hp Left" << std::endl;
if (pTargetObject->GetHP() <= 0)
Kill(pTargetObject);
break;
}
case BattleEventType::DEFEND:
std::cout << pSourceObject->GetName() << " defends!\n";
break;
default:
break;
}
events.pop();
}
}<commit_msg>Change asterisk's position<commit_after>#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include "Battle.h"
#include "Creature.h"
#include "Dialogue.h"
BattleEvent::BattleEvent(Creature* _source, Creature* _target, BattleEventType _type)
: source(_source), target(_target), type(_type)
{
}
Creature* BattleEvent::GetSource()
{
return source;
}
Creature* BattleEvent::GetTarget()
{
return target;
}
BattleEventType BattleEvent::GetType()
{
return type;
}
int BattleEvent::Run()
{
switch (type)
{
case BattleEventType::ATTACK:
return source->Attack(target);
case BattleEventType::DEFEND:
return 0;
default:
return 0;
}
}
Battle::Battle(std::vector<Creature*>& _combatants)
: combatants(_combatants)
{
battleOptions = Dialogue("What will you do?", { "Attack", "Defend" });
std::map<std::string, int> names;
for (auto com : combatants)
{
if (com->GetID() == "Player")
continue;
if (names.count(com->GetName()) == 0)
names[com->GetName()] = 0;
else if (names[com->GetName()] == 0)
names[com->GetName()] = 1;
}
for (auto& com : combatants)
{
std::string newName = com->GetName();
if (names.count(com->GetName()) > 0 && names[com->GetName()] > 0)
{
newName += " (" + std::to_string(names[com->GetName()]) + ")";
names[com->GetName()] += 1;
}
com->GetName() = newName;
}
}
void Battle::Run()
{
// TODO : check player != end
std::vector<Creature*>::iterator player;
std::vector<Creature*>::iterator end;
do {
player = std::find_if(combatants.begin(), combatants.end(),
[](Creature* creature) { return creature->GetID() == "Player"; });
end = combatants.end();
NextTurn();
} while (combatants.size() > 1 && player != end);
}
void Battle::Kill(Creature* creature)
{
auto pos = std::find(combatants.begin(), combatants.end(), creature);
if (pos != combatants.end())
{
std::cout << creature->GetName() << " is slain!" << std::endl;
creature->SetHP(0);
combatants.erase(pos);
}
}
void Battle::NextTurn()
{
std::queue<BattleEvent> events;
std::sort(combatants.begin(), combatants.end(),
[](Creature* a, Creature* b) { return a->GetAgility() > b->GetAgility(); });
for (auto com : combatants)
{
if (com->GetID() == "Player")
{
Dialogue targetSelection = Dialogue("Who?", {});
for (auto target : combatants)
if (target->GetID() != "Player")
targetSelection.AddChoice(target->GetName());
int choice = battleOptions.Activate();
switch (choice)
{
default:
case 1:
{
int position = targetSelection.Activate();
for (int i = 0; i < position; i++)
if (combatants[i]->GetID() == "Player")
position++;
Creature* target = combatants[position - 1];
events.push(BattleEvent(com, target, BattleEventType::ATTACK));
break;
}
case 2:
{
events.push(BattleEvent(com, nullptr, BattleEventType::DEFEND));
break;
}
}
}
else
{
Creature* player = *std::find_if(combatants.begin(), combatants.end(),
[](Creature* a) { return a->GetID() == "Player"; });
events.push(BattleEvent(com, player, BattleEventType::ATTACK));
}
}
while (!events.empty())
{
BattleEvent event = events.front();
Creature* pSourceObject = event.GetSource();
Creature* pTargetObject = event.GetTarget();
switch (event.GetType())
{
case BattleEventType::ATTACK:
{
auto a = combatants.begin();
auto b = combatants.end();
if (std::find(a, b, pSourceObject) == b || std::find(a, b, pTargetObject) == b)
break;
std::cout << pSourceObject->GetName() << " attacks " << pTargetObject->GetName() << " for " << event.Run() << " damage!" << std::endl;
std::cout << pTargetObject->GetName() << " : " << pTargetObject->GetHP() << "Hp Left" << std::endl;
if (pTargetObject->GetHP() <= 0)
Kill(pTargetObject);
break;
}
case BattleEventType::DEFEND:
std::cout << pSourceObject->GetName() << " defends!\n";
break;
default:
break;
}
events.pop();
}
}<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/filters/audio_renderer_algorithm_base.h"
#include "base/logging.h"
#include "media/base/buffers.h"
namespace media {
// The size in bytes we try to maintain for the |queue_|. Previous usage
// maintained a deque of 16 Buffers, each of size 4Kb. This worked well, so we
// maintain this number of bytes (16 * 4096).
const uint32 kDefaultMinQueueSizeInBytes = 65536;
AudioRendererAlgorithmBase::AudioRendererAlgorithmBase()
: channels_(0),
sample_rate_(0),
sample_bytes_(0),
playback_rate_(0.0f),
queue_(0, kDefaultMinQueueSizeInBytes) {
}
AudioRendererAlgorithmBase::~AudioRendererAlgorithmBase() {}
void AudioRendererAlgorithmBase::Initialize(int channels,
int sample_rate,
int sample_bits,
float initial_playback_rate,
RequestReadCallback* callback) {
DCHECK_GT(channels, 0);
DCHECK_LE(channels, 6) << "We only support <=6 channel audio.";
DCHECK_GT(sample_rate, 0);
DCHECK_LE(sample_rate, 256000)
<< "We only support sample rates at or below 256000Hz.";
DCHECK_GT(sample_bits, 0);
DCHECK_LE(sample_bits, 32) << "We only support 8, 16, 32 bit audio.";
DCHECK_EQ(sample_bits % 8, 0) << "We only support 8, 16, 32 bit audio.";
DCHECK(callback);
channels_ = channels;
sample_rate_ = sample_rate;
sample_bytes_ = sample_bits / 8;
request_read_callback_.reset(callback);
set_playback_rate(initial_playback_rate);
}
void AudioRendererAlgorithmBase::FlushBuffers() {
// Clear the queue of decoded packets (releasing the buffers).
queue_.Clear();
request_read_callback_->Run();
}
base::TimeDelta AudioRendererAlgorithmBase::GetTime() {
return queue_.current_time();
}
void AudioRendererAlgorithmBase::EnqueueBuffer(Buffer* buffer_in) {
// If we're at end of stream, |buffer_in| contains no data.
if (!buffer_in->IsEndOfStream())
queue_.Append(buffer_in);
// If we still don't have enough data, request more.
if (!IsQueueFull())
request_read_callback_->Run();
}
float AudioRendererAlgorithmBase::playback_rate() {
return playback_rate_;
}
void AudioRendererAlgorithmBase::set_playback_rate(float new_rate) {
DCHECK_GE(new_rate, 0.0);
playback_rate_ = new_rate;
}
bool AudioRendererAlgorithmBase::IsQueueEmpty() {
return queue_.forward_bytes() == 0;
}
bool AudioRendererAlgorithmBase::IsQueueFull() {
return (queue_.forward_bytes() >= kDefaultMinQueueSizeInBytes);
}
uint32 AudioRendererAlgorithmBase::QueueSize() {
return queue_.forward_bytes();
}
void AudioRendererAlgorithmBase::AdvanceInputPosition(uint32 bytes) {
queue_.Seek(bytes);
if (!IsQueueFull())
request_read_callback_->Run();
}
uint32 AudioRendererAlgorithmBase::CopyFromInput(uint8* dest, uint32 bytes) {
return queue_.Peek(dest, bytes);
}
int AudioRendererAlgorithmBase::channels() {
return channels_;
}
int AudioRendererAlgorithmBase::sample_rate() {
return sample_rate_;
}
int AudioRendererAlgorithmBase::sample_bytes() {
return sample_bytes_;
}
} // namespace media
<commit_msg>audio ola resampler accept 8 channel source BUG=59832 TEST=player_wtl _xvid_pcm_7.1_640x480_183sec_m1599.wav<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/filters/audio_renderer_algorithm_base.h"
#include "base/logging.h"
#include "media/base/buffers.h"
namespace media {
// The size in bytes we try to maintain for the |queue_|. Previous usage
// maintained a deque of 16 Buffers, each of size 4Kb. This worked well, so we
// maintain this number of bytes (16 * 4096).
const uint32 kDefaultMinQueueSizeInBytes = 65536;
AudioRendererAlgorithmBase::AudioRendererAlgorithmBase()
: channels_(0),
sample_rate_(0),
sample_bytes_(0),
playback_rate_(0.0f),
queue_(0, kDefaultMinQueueSizeInBytes) {
}
AudioRendererAlgorithmBase::~AudioRendererAlgorithmBase() {}
void AudioRendererAlgorithmBase::Initialize(int channels,
int sample_rate,
int sample_bits,
float initial_playback_rate,
RequestReadCallback* callback) {
DCHECK_GT(channels, 0);
DCHECK_LE(channels, 8) << "We only support <= 8 channel audio.";
DCHECK_GT(sample_rate, 0);
DCHECK_LE(sample_rate, 256000)
<< "We only support sample rates at or below 256000Hz.";
DCHECK_GT(sample_bits, 0);
DCHECK_LE(sample_bits, 32) << "We only support 8, 16, 32 bit audio.";
DCHECK_EQ(sample_bits % 8, 0) << "We only support 8, 16, 32 bit audio.";
DCHECK(callback);
channels_ = channels;
sample_rate_ = sample_rate;
sample_bytes_ = sample_bits / 8;
request_read_callback_.reset(callback);
set_playback_rate(initial_playback_rate);
}
void AudioRendererAlgorithmBase::FlushBuffers() {
// Clear the queue of decoded packets (releasing the buffers).
queue_.Clear();
request_read_callback_->Run();
}
base::TimeDelta AudioRendererAlgorithmBase::GetTime() {
return queue_.current_time();
}
void AudioRendererAlgorithmBase::EnqueueBuffer(Buffer* buffer_in) {
// If we're at end of stream, |buffer_in| contains no data.
if (!buffer_in->IsEndOfStream())
queue_.Append(buffer_in);
// If we still don't have enough data, request more.
if (!IsQueueFull())
request_read_callback_->Run();
}
float AudioRendererAlgorithmBase::playback_rate() {
return playback_rate_;
}
void AudioRendererAlgorithmBase::set_playback_rate(float new_rate) {
DCHECK_GE(new_rate, 0.0);
playback_rate_ = new_rate;
}
bool AudioRendererAlgorithmBase::IsQueueEmpty() {
return queue_.forward_bytes() == 0;
}
bool AudioRendererAlgorithmBase::IsQueueFull() {
return (queue_.forward_bytes() >= kDefaultMinQueueSizeInBytes);
}
uint32 AudioRendererAlgorithmBase::QueueSize() {
return queue_.forward_bytes();
}
void AudioRendererAlgorithmBase::AdvanceInputPosition(uint32 bytes) {
queue_.Seek(bytes);
if (!IsQueueFull())
request_read_callback_->Run();
}
uint32 AudioRendererAlgorithmBase::CopyFromInput(uint8* dest, uint32 bytes) {
return queue_.Peek(dest, bytes);
}
int AudioRendererAlgorithmBase::channels() {
return channels_;
}
int AudioRendererAlgorithmBase::sample_rate() {
return sample_rate_;
}
int AudioRendererAlgorithmBase::sample_bytes() {
return sample_bytes_;
}
} // namespace media
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2013 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "DGAudioManager.h"
#include "DGConfig.h"
#include "DGLog.h"
using namespace std;
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
DGAudioManager::DGAudioManager() :
config(DGConfig::instance()),
log(DGLog::instance())
{
_isInitialized = false;
_isRunning = false;
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
DGAudioManager::~DGAudioManager() {
}
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void DGAudioManager::clear() {
if (_isInitialized) {
if (!_arrayOfActiveAudios.empty()) {
vector<DGAudio*>::iterator it;
_mutexForArray.lock();
it = _arrayOfActiveAudios.begin();
while (it != _arrayOfActiveAudios.end()) {
(*it)->release();
it++;
}
_mutexForArray.unlock();
}
}
}
void DGAudioManager::flush() {
bool done = false;
if (_isInitialized) {
if (!_arrayOfActiveAudios.empty()) {
vector<DGAudio*>::iterator it;
while (!done) {
_mutexForArray.lock();
it = _arrayOfActiveAudios.begin();
done = true;
while ((it != _arrayOfActiveAudios.end())) {
if ((*it)->retainCount() == 0) {
if ((*it)->state() == DGAudioStopped) { // Had to move this outside the switch
// TODO: Automatically flush stopped and non-retained audios after
// n update cycles
(*it)->unload();
_arrayOfActiveAudios.erase(it);
done = false;
break;
}
else {
switch ((*it)->state()) {
case DGAudioPlaying:
(*it)->fadeOut();
it++;
break;
case DGAudioPaused:
default:
it++;
break;
}
}
}
else it++;
}
_mutexForArray.unlock();
}
}
}
}
void DGAudioManager::init() {
log.trace(DGModAudio, "%s", DGMsg070000);
char deviceName[256];
char *defaultDevice;
char *deviceList;
char *devices[12];
int numDevices, numDefaultDevice;
strcpy(deviceName, "");
if (config.debugMode) {
if (alcIsExtensionPresent(NULL, (ALCchar*)"ALC_ENUMERATION_EXT") == AL_TRUE) { // Check if enumeration extension is present
defaultDevice = (char *)alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
deviceList = (char *)alcGetString(NULL, ALC_DEVICE_SPECIFIER);
for (numDevices = 0; numDevices < 12; numDevices++) {devices[numDevices] = NULL;}
for (numDevices = 0; numDevices < 12; numDevices++) {
devices[numDevices] = deviceList;
if (strcmp(devices[numDevices], defaultDevice) == 0) {
numDefaultDevice = numDevices;
}
deviceList += strlen(deviceList);
if (deviceList[0] == 0) {
if (deviceList[1] == 0) {
break;
} else {
deviceList += 1;
}
}
}
if (devices[numDevices] != NULL) {
int i;
numDevices++;
/*log.trace(DGModAudio, "%s", DGMsg080002);
log.trace(DGModAudio, "0. NULL");
for (i = 0; i < numDevices; i++) {
log.trace(DGModAudio, "%d. %s", i + 1, devices[i]);
}*/
i = config.audioDevice;
if ((i != 0) && (strlen(devices[i - 1]) < 256)) {
strcpy(deviceName, devices[i - 1]);
}
}
}
}
if (strlen(deviceName) == 0) {
log.trace(DGModAudio, "%s", DGMsg080003);
_alDevice = alcOpenDevice(NULL); // Select the preferred device
} else {
log.trace(DGModAudio, "%s: %s", DGMsg080004, deviceName);
_alDevice = alcOpenDevice((ALCchar*)deviceName); // Use the name from the enumeration process
}
if (!_alDevice) {
log.error(DGModAudio, "%s", DGMsg270001);
return;
}
_alContext = alcCreateContext(_alDevice, NULL);
if (!_alContext) {
log.error(DGModAudio, "%s", DGMsg270002);
return;
}
alcMakeContextCurrent(_alContext);
ALfloat listenerPos[] = {0.0, 0.0, 0.0};
ALfloat listenerVel[] = {0.0, 0.0, 0.0};
ALfloat listenerOri[] = {0.0, 0.0, -1.0,
0.0, 1.0, 0.0}; // Listener facing into the screen
alListenerfv(AL_POSITION, listenerPos);
alListenerfv(AL_VELOCITY, listenerVel);
alListenerfv(AL_ORIENTATION, listenerOri);
ALint error = alGetError();
if (error != AL_NO_ERROR) {
log.error(DGModAudio, "%s: init (%d)", DGMsg270003, error);
return;
}
log.info(DGModAudio, "%s: %s", DGMsg070001, alGetString(AL_VERSION));
log.info(DGModAudio, "%s: %s", DGMsg070002, vorbis_version_string());
_isInitialized = true;
_isRunning = true;
_audioThread = thread([](){
chrono::milliseconds dura(1);
while (DGAudioManager::instance().update()) {
this_thread::sleep_for(dura);
}
});
}
void DGAudioManager::registerAudio(DGAudio* target) {
_arrayOfAudios.push_back(target);
}
void DGAudioManager::requestAudio(DGAudio* target) {
if (!target->isLoaded()) {
target->load();
}
target->retain();
// If the audio is not active, then it's added to
// that vector
bool isActive = false;
std::vector<DGAudio*>::iterator it;
it = _arrayOfActiveAudios.begin();
while (it != _arrayOfActiveAudios.end()) {
if ((*it) == target) {
isActive = true;
break;
}
it++;
}
if (!isActive) {
_mutexForArray.lock();
_arrayOfActiveAudios.push_back(target);
_mutexForArray.unlock();
}
// FIXME: Not very elegant. Must implement a state condition for
// each audio object. Perhaps use AL_STATE even.
if (target->state() == DGAudioPaused) {
target->play();
}
}
void DGAudioManager::setOrientation(float* orientation) {
if (_isInitialized) {
alListenerfv(AL_ORIENTATION, orientation);
}
}
void DGAudioManager::terminate() {
// FIXME: Here it's important to determine if the
// audio was created by Lua or by another class
// Each audio object should unregister itself if
// destroyed
_isRunning = false;
_audioThread.join();
if (!_arrayOfAudios.empty()) {
vector<DGAudio*>::iterator it;
_mutexForArray.lock();
it = _arrayOfAudios.begin();
while (it != _arrayOfAudios.end()) {
// FIXME: Should delete here and let the audio object unload itself
(*it)->unload();
it++;
}
_mutexForArray.unlock();
}
// Now we shut down OpenAL completely
if (_isInitialized) {
alcMakeContextCurrent(NULL);
alcDestroyContext(_alContext);
alcCloseDevice(_alDevice);
}
}
// Asynchronous method
bool DGAudioManager::update() {
if (_isRunning) {
if (!_arrayOfActiveAudios.empty()) {
vector<DGAudio*>::iterator it;
_mutexForArray.lock();
it = _arrayOfActiveAudios.begin();
while (it != _arrayOfActiveAudios.end()) {
(*it)->update();
it++;
}
_mutexForArray.unlock();
}
return true;
}
return false;
}
<commit_msg>Logging additional audio details when in debug mode.<commit_after>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2013 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "DGAudioManager.h"
#include "DGConfig.h"
#include "DGLog.h"
using namespace std;
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
DGAudioManager::DGAudioManager() :
config(DGConfig::instance()),
log(DGLog::instance())
{
_isInitialized = false;
_isRunning = false;
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
DGAudioManager::~DGAudioManager() {
}
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void DGAudioManager::clear() {
if (_isInitialized) {
if (!_arrayOfActiveAudios.empty()) {
vector<DGAudio*>::iterator it;
_mutexForArray.lock();
it = _arrayOfActiveAudios.begin();
while (it != _arrayOfActiveAudios.end()) {
(*it)->release();
it++;
}
_mutexForArray.unlock();
}
}
}
void DGAudioManager::flush() {
bool done = false;
if (_isInitialized) {
if (!_arrayOfActiveAudios.empty()) {
vector<DGAudio*>::iterator it;
while (!done) {
_mutexForArray.lock();
it = _arrayOfActiveAudios.begin();
done = true;
while ((it != _arrayOfActiveAudios.end())) {
if ((*it)->retainCount() == 0) {
if ((*it)->state() == DGAudioStopped) { // Had to move this outside the switch
// TODO: Automatically flush stopped and non-retained audios after
// n update cycles
(*it)->unload();
_arrayOfActiveAudios.erase(it);
done = false;
break;
}
else {
switch ((*it)->state()) {
case DGAudioPlaying:
(*it)->fadeOut();
it++;
break;
case DGAudioPaused:
default:
it++;
break;
}
}
}
else it++;
}
_mutexForArray.unlock();
}
}
}
}
void DGAudioManager::init() {
log.trace(DGModAudio, "%s", DGMsg070000);
char deviceName[256];
char *defaultDevice;
char *deviceList;
char *devices[12];
int numDevices, numDefaultDevice;
strcpy(deviceName, "");
if (config.debugMode) {
if (alcIsExtensionPresent(NULL, (ALCchar*)"ALC_ENUMERATION_EXT") == AL_TRUE) { // Check if enumeration extension is present
defaultDevice = (char *)alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
deviceList = (char *)alcGetString(NULL, ALC_DEVICE_SPECIFIER);
for (numDevices = 0; numDevices < 12; numDevices++) {devices[numDevices] = NULL;}
for (numDevices = 0; numDevices < 12; numDevices++) {
devices[numDevices] = deviceList;
if (strcmp(devices[numDevices], defaultDevice) == 0) {
numDefaultDevice = numDevices;
}
deviceList += strlen(deviceList);
if (deviceList[0] == 0) {
if (deviceList[1] == 0) {
break;
} else {
deviceList += 1;
}
}
}
if (devices[numDevices] != NULL) {
int i;
numDevices++;
if (config.debugMode) {
log.trace(DGModAudio, "%s", DGMsg080002);
log.trace(DGModAudio, "0. NULL");
for (i = 0; i < numDevices; i++) {
log.trace(DGModAudio, "%d. %s", i + 1, devices[i]);
}
}
i = config.audioDevice;
if ((i != 0) && (strlen(devices[i - 1]) < 256)) {
strcpy(deviceName, devices[i - 1]);
}
}
}
}
if (strlen(deviceName) == 0) {
log.trace(DGModAudio, "%s", DGMsg080003);
_alDevice = alcOpenDevice(NULL); // Select the preferred device
} else {
log.trace(DGModAudio, "%s: %s", DGMsg080004, deviceName);
_alDevice = alcOpenDevice((ALCchar*)deviceName); // Use the name from the enumeration process
}
if (!_alDevice) {
log.error(DGModAudio, "%s", DGMsg270001);
return;
}
_alContext = alcCreateContext(_alDevice, NULL);
if (!_alContext) {
log.error(DGModAudio, "%s", DGMsg270002);
return;
}
alcMakeContextCurrent(_alContext);
ALfloat listenerPos[] = {0.0, 0.0, 0.0};
ALfloat listenerVel[] = {0.0, 0.0, 0.0};
ALfloat listenerOri[] = {0.0, 0.0, -1.0,
0.0, 1.0, 0.0}; // Listener facing into the screen
alListenerfv(AL_POSITION, listenerPos);
alListenerfv(AL_VELOCITY, listenerVel);
alListenerfv(AL_ORIENTATION, listenerOri);
ALint error = alGetError();
if (error != AL_NO_ERROR) {
log.error(DGModAudio, "%s: init (%d)", DGMsg270003, error);
return;
}
log.info(DGModAudio, "%s: %s", DGMsg070001, alGetString(AL_VERSION));
log.info(DGModAudio, "%s: %s", DGMsg070002, vorbis_version_string());
_isInitialized = true;
_isRunning = true;
_audioThread = thread([](){
chrono::milliseconds dura(1);
while (DGAudioManager::instance().update()) {
this_thread::sleep_for(dura);
}
});
}
void DGAudioManager::registerAudio(DGAudio* target) {
_arrayOfAudios.push_back(target);
}
void DGAudioManager::requestAudio(DGAudio* target) {
if (!target->isLoaded()) {
target->load();
}
target->retain();
// If the audio is not active, then it's added to
// that vector
bool isActive = false;
std::vector<DGAudio*>::iterator it;
it = _arrayOfActiveAudios.begin();
while (it != _arrayOfActiveAudios.end()) {
if ((*it) == target) {
isActive = true;
break;
}
it++;
}
if (!isActive) {
_mutexForArray.lock();
_arrayOfActiveAudios.push_back(target);
_mutexForArray.unlock();
}
// FIXME: Not very elegant. Must implement a state condition for
// each audio object. Perhaps use AL_STATE even.
if (target->state() == DGAudioPaused) {
target->play();
}
}
void DGAudioManager::setOrientation(float* orientation) {
if (_isInitialized) {
alListenerfv(AL_ORIENTATION, orientation);
}
}
void DGAudioManager::terminate() {
// FIXME: Here it's important to determine if the
// audio was created by Lua or by another class
// Each audio object should unregister itself if
// destroyed
_isRunning = false;
_audioThread.join();
if (!_arrayOfAudios.empty()) {
vector<DGAudio*>::iterator it;
_mutexForArray.lock();
it = _arrayOfAudios.begin();
while (it != _arrayOfAudios.end()) {
// FIXME: Should delete here and let the audio object unload itself
(*it)->unload();
it++;
}
_mutexForArray.unlock();
}
// Now we shut down OpenAL completely
if (_isInitialized) {
alcMakeContextCurrent(NULL);
alcDestroyContext(_alContext);
alcCloseDevice(_alDevice);
}
}
// Asynchronous method
bool DGAudioManager::update() {
if (_isRunning) {
if (!_arrayOfActiveAudios.empty()) {
vector<DGAudio*>::iterator it;
_mutexForArray.lock();
it = _arrayOfActiveAudios.begin();
while (it != _arrayOfActiveAudios.end()) {
(*it)->update();
it++;
}
_mutexForArray.unlock();
}
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>#include "watchdog_service.hpp"
#include <sdbusplus/bus.hpp>
#include <sdbusplus/message.hpp>
#include <string>
#include <xyz/openbmc_project/State/Watchdog/server.hpp>
#include "host-ipmid/ipmid-api.h"
using sdbusplus::message::variant_ns::get;
using sdbusplus::message::variant_ns::variant;
using sdbusplus::xyz::openbmc_project::State::server::convertForMessage;
using sdbusplus::xyz::openbmc_project::State::server::Watchdog;
static constexpr char wd_path[] = "/xyz/openbmc_project/watchdog/host0";
static constexpr char wd_intf[] = "xyz.openbmc_project.State.Watchdog";
static constexpr char prop_intf[] = "org.freedesktop.DBus.Properties";
ipmi::ServiceCache WatchdogService::wd_service(wd_intf, wd_path);
WatchdogService::WatchdogService()
: bus(ipmid_get_sd_bus_connection())
{
}
WatchdogService::Properties WatchdogService::getProperties()
{
auto request = wd_service.newMethodCall(bus, prop_intf, "GetAll");
request.append(wd_intf);
auto response = bus.call(request);
if (response.is_method_error())
{
wd_service.invalidate();
throw std::runtime_error("Failed to get watchdog properties");
}
std::map<std::string, variant<bool, uint64_t, std::string>> properties;
response.read(properties);
Properties wd_prop;
wd_prop.initialized = get<bool>(properties.at("Initialized"));
wd_prop.enabled = get<bool>(properties.at("Enabled"));
wd_prop.expireAction = Watchdog::convertActionFromString(
get<std::string>(properties.at("ExpireAction")));
wd_prop.interval = get<uint64_t>(properties.at("Interval"));
wd_prop.timeRemaining = get<uint64_t>(properties.at("TimeRemaining"));
return wd_prop;
}
template <typename T>
void WatchdogService::setProperty(const std::string& key, const T& val)
{
auto request = wd_service.newMethodCall(bus, prop_intf, "Set");
request.append(wd_intf, key, variant<T>(val));
auto response = bus.call(request);
if (response.is_method_error())
{
wd_service.invalidate();
throw std::runtime_error(std::string("Failed to set property: ") + key);
}
}
void WatchdogService::setInitialized(bool initialized)
{
setProperty("Initialized", initialized);
}
void WatchdogService::setEnabled(bool enabled)
{
setProperty("Enabled", enabled);
}
void WatchdogService::setExpireAction(Action expireAction)
{
setProperty("ExpireAction", convertForMessage(expireAction));
}
void WatchdogService::setInterval(uint64_t interval)
{
setProperty("Interval", interval);
}
void WatchdogService::setTimeRemaining(uint64_t timeRemaining)
{
setProperty("TimeRemaining", timeRemaining);
}
<commit_msg>watchdog: Retry dbus requests if the service was cached<commit_after>#include "watchdog_service.hpp"
#include <sdbusplus/bus.hpp>
#include <sdbusplus/message.hpp>
#include <string>
#include <xyz/openbmc_project/State/Watchdog/server.hpp>
#include "host-ipmid/ipmid-api.h"
using sdbusplus::message::variant_ns::get;
using sdbusplus::message::variant_ns::variant;
using sdbusplus::xyz::openbmc_project::State::server::convertForMessage;
using sdbusplus::xyz::openbmc_project::State::server::Watchdog;
static constexpr char wd_path[] = "/xyz/openbmc_project/watchdog/host0";
static constexpr char wd_intf[] = "xyz.openbmc_project.State.Watchdog";
static constexpr char prop_intf[] = "org.freedesktop.DBus.Properties";
ipmi::ServiceCache WatchdogService::wd_service(wd_intf, wd_path);
WatchdogService::WatchdogService()
: bus(ipmid_get_sd_bus_connection())
{
}
WatchdogService::Properties WatchdogService::getProperties()
{
bool wasValid = wd_service.isValid(bus);
auto request = wd_service.newMethodCall(bus, prop_intf, "GetAll");
request.append(wd_intf);
auto response = bus.call(request);
if (response.is_method_error())
{
wd_service.invalidate();
if (wasValid)
{
// Retry the request once in case the cached service was stale
return getProperties();
}
throw std::runtime_error("Failed to get watchdog properties");
}
std::map<std::string, variant<bool, uint64_t, std::string>> properties;
response.read(properties);
Properties wd_prop;
wd_prop.initialized = get<bool>(properties.at("Initialized"));
wd_prop.enabled = get<bool>(properties.at("Enabled"));
wd_prop.expireAction = Watchdog::convertActionFromString(
get<std::string>(properties.at("ExpireAction")));
wd_prop.interval = get<uint64_t>(properties.at("Interval"));
wd_prop.timeRemaining = get<uint64_t>(properties.at("TimeRemaining"));
return wd_prop;
}
template <typename T>
void WatchdogService::setProperty(const std::string& key, const T& val)
{
bool wasValid = wd_service.isValid(bus);
auto request = wd_service.newMethodCall(bus, prop_intf, "Set");
request.append(wd_intf, key, variant<T>(val));
auto response = bus.call(request);
if (response.is_method_error())
{
wd_service.invalidate();
if (wasValid)
{
// Retry the request once in case the cached service was stale
return setProperty(key, val);
}
throw std::runtime_error(std::string("Failed to set property: ") + key);
}
}
void WatchdogService::setInitialized(bool initialized)
{
setProperty("Initialized", initialized);
}
void WatchdogService::setEnabled(bool enabled)
{
setProperty("Enabled", enabled);
}
void WatchdogService::setExpireAction(Action expireAction)
{
setProperty("ExpireAction", convertForMessage(expireAction));
}
void WatchdogService::setInterval(uint64_t interval)
{
setProperty("Interval", interval);
}
void WatchdogService::setTimeRemaining(uint64_t timeRemaining)
{
setProperty("TimeRemaining", timeRemaining);
}
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** 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 ETH Zurich 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 "VComment.h"
#include "VCommentBrowser.h"
#include "VCommentImage.h"
#include "VisualizationBase/src/items/Line.h"
#include "VisualizationBase/src/items/ItemStyle.h"
#include "VisualizationBase/src/items/Text.h"
#include "VisualizationBase/src/declarative/DeclarativeItemDef.h"
using namespace Visualization;
namespace Comments {
ITEM_COMMON_DEFINITIONS(VComment, "item")
VComment::VComment(Item* parent, NodeType* node) : Super(parent, node, itemStyles().get())
{
// import existing diagrams
for(auto diagram : *node->diagrams())
{
diagrams_[diagram->name()] = diagram;
}
editing_ = node->lines()->size() == 0 || (node->lines()->size() == 1 && node->lines()->at(0)->get().isEmpty());
parseLines();
}
// split up user-provided text into single elements
void VComment::parseLines()
{
clearChildren();
bool isHTML = false;
QSet<QString> diagramNames{};
int listCount = -1;
for(auto nodeLine : *node()->lines())
{
QRegExp rx("^={3,}|-{3,}|\\.{3,}$");
QString line = nodeLine->get();
// is this a new enumeration item?
if(line.left(3) == " * ")
{
listCount++;
// does this create a new list?
if(listCount == 0)
{
pushTextLine("<ol><li>");
line = line.mid(3);
}
// otherwise, just add another list item
else
{
pushTextLine("</li><li>");
line = line.mid(3);
}
}
// or is this extending an existing list?
else if(line.left(3) == " " && listCount > -1)
{
line = line.mid(3);
}
// if this is not an enumeration item, reset listCount
else if(listCount > -1 && line.left(3) != " * " && line.left(3) != " ")
{
pushTextLine("</li></ol>");
listCount = -1;
}
// is this HTML?
if(line == "<html>")
{
popLineBuffer();
isHTML = true;
continue;
}
else if(isHTML)
{
if(line == "</html>")
{
isHTML = false;
popLineBuffer(true);
}
else
{
pushTextLine(line);
}
// don't process further
continue;
}
if(rx.exactMatch(line))
{
// A line consists of one of . - = that is repeated three times or more
// The used character defines the strength of the header, i.e. one of three levels
QString style;
switch(line[0].toAscii())
{
default:
case '.': style = "single"; break;
case '-': style = "double"; break;
case '=': style = "triple"; break;
}
addChildItem(new Line(this, Line::itemStyles().get(style)));
continue;
}
// is this a header? replace it right away with the appropriate tag
rx.setPattern("^(#+)([^#].*)");
// allow headers h1 to h6
if(rx.exactMatch(line) && rx.cap(1).length() <= 6)
{
QString len = QString::number(rx.cap(1).length());
pushTextLine("<h" + len + ">" + rx.cap(2).simplified() + "</h" + len + ">");
}
// is this a diagram? format: [diagram#diagramName]
else if(line.left(9) == "[diagram#" && line.right(1) == "]" && line.size() > 9+1)
{
QString diagramName = line.mid(9,line.size()-9-1);
diagramNames << diagramName;
CommentDiagram* diagram = diagrams_.value(diagramName, nullptr);
if(diagram == nullptr)
{
diagram = new CommentDiagram(nullptr, diagramName);
diagrams_[diagramName] = diagram;
}
auto item = renderer()->render(this, diagram);
addChildItem(item);
}
// urls are specified as [[http://www.google.com]]
else if(line.left(2) == "[[" && line.right(2) == "]]" && line.size() > 2+2)
{
QString mid = line.mid(2, line.size()-2-2);
// read width and height, if specified
auto items = parseMarkdownArguments(mid);
QString url = items->at(0).second;
auto browser = new VCommentBrowser(this, url);
if(items->size() > 1)
{
QSize size = parseSize(items->at(1).second);
browser->updateSize(size);
}
addChildItem(browser);
delete items;
}
// images are specified as
// [image#/home/user/image.png]
// [image#image.png|300x300] to specify a size
else if(line.left(7) == "[image#" && line.right(1) == "]" && line.size() > 7+1)
{
QString mid = line.mid(7, line.size()-7-1);
// read width and height, if specified
auto items = parseMarkdownArguments(mid);
QString path = items->at(0).second;
QSize size(0,0);
if(items->size() > 1)
size = parseSize(items->at(1).second);
addChildItem(new VCommentImage(this, items->at(0).second, size));
delete items;
}
else
{
pushTextLine(line);
}
}
popLineBuffer();
synchroniseDiagrams(diagramNames);
}
void VComment::synchroniseDiagrams(QSet<QString> itemDiagramNames)
{
// get all diagrams from the node
auto nodeDiagrams = node()->diagrams();
// gather all names from the node diagrams for easier comparison
QSet<QString> nodeDiagramNames{};
for(auto diagram : *nodeDiagrams)
nodeDiagramNames << diagram->name();
// get intersection of two sets
QSet<QString> intersection(itemDiagramNames);
intersection.intersect(nodeDiagramNames);
// new diagrams were already constructed inside of parseLines(),
// they also need to be added to the model now
auto newDiagramNames = itemDiagramNames - intersection;
if(newDiagramNames.size() > 0)
{
node()->model()->beginModification(node(), "Adding new diagrams");
for(auto diagramName : newDiagramNames)
{
auto diagram = diagrams_.value(diagramName);
node()->diagrams()->append(diagram);
}
node()->model()->endModification();
}
// diagrams that are no longer referenced need to be removed from the model
auto oldDiagramNames = nodeDiagramNames - intersection;
if(oldDiagramNames.size() > 0)
{
node()->model()->beginModification(node(), "Removing unreferenced diagrams");
for(auto diagramName : oldDiagramNames)
{
auto diagram = diagrams_.value(diagramName);
node()->diagrams()->remove(diagram);
diagrams_.remove(diagramName);
}
node()->model()->endModification();
}
}
QMap<QString, CommentDiagram*> VComment::diagrams() const
{
return diagrams_;
}
QSize VComment::parseSize(const QString& str)
{
int index = str.indexOf('x');
bool ok{};
int width = str.left(index).toInt(&ok);
if(index > 0 && !ok)
qDebug() << "Invalid width specified in size string:" << str;
int height = str.mid(index+1).toInt(&ok);
if(index+1 < str.size()-1 && !ok)
qDebug() << "Invalid height specified in size string:" << str;
return QSize(width, height);
}
QVector<QPair<QString,QString>>* VComment::parseMarkdownArguments(const QString& argString)
{
// split string on all pipes
auto lines = argString.split('|');
// TODO: get rid of escaped pipes \| e.g. in case an url contains one
auto pairs = new QVector<QPair<QString,QString>>();
// read key/value pairs
QRegExp rx("^[a-zA-Z]{,15}=");
for(auto line : lines)
{
int index = rx.indexIn(line);
if(index == -1)
pairs->push_back(qMakePair(QString(), line));
else
pairs->push_back(qMakePair(line.left(index), line.mid(index+1)));
}
return pairs;
}
QString VComment::replaceMarkdown(QString str)
{
QRegExp rx;
rx.setPattern("\\*\\*([^\\*]+)\\*\\*");
str.replace(rx, "<i>\\1</i>");
rx.setPattern("\\*([^\\*]+)\\*");
str.replace(rx, "<b>\\1</b>");
return str;
}
void VComment::pushTextLine(QString text)
{
lineBuffer_.push_back(text);
}
void VComment::popLineBuffer(bool asHtml)
{
if(lineBuffer_.size() > 0)
{
auto joined = lineBuffer_.join("\n");
if(asHtml)
{
auto browser = new VCommentBrowser(this, joined);
children_.push_back(browser);
}
else
{
auto text = new Text(this, Text::itemStyles().get("comment"), replaceMarkdown(joined));
text->setTextFormat(Qt::RichText);
children_.push_back(text);
}
lineBuffer_.clear();
}
}
void VComment::addChildItem(Visualization::Item* item)
{
popLineBuffer();
children_.push_back(item);
}
void VComment::toggleEditing()
{
if(node()->lines()->size() == 0)
editing_ = true;
else
editing_ = !editing_;
if(!editing_)
parseLines();
setUpdateNeeded(StandardUpdate);
}
bool VComment::editing() const
{
return editing_;
}
void VComment::initializeForms()
{
addForm((new SequentialLayoutFormElement())
->setVertical()
->setListOfItems([](Item* i) {
auto vc = static_cast<VComment*>(i);
return vc->children_;
}
));
addForm(item(&I::editLabel_, [](I* v){
return v->node()->lines();
}));
}
int VComment::determineForm()
{
return editing_ ? 1 : 0;
}
} /* namespace Comments */
<commit_msg>Make browser syntax more consistent with the rest<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** 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 ETH Zurich 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 "VComment.h"
#include "VCommentBrowser.h"
#include "VCommentImage.h"
#include "VisualizationBase/src/items/Line.h"
#include "VisualizationBase/src/items/ItemStyle.h"
#include "VisualizationBase/src/items/Text.h"
#include "VisualizationBase/src/declarative/DeclarativeItemDef.h"
using namespace Visualization;
namespace Comments {
ITEM_COMMON_DEFINITIONS(VComment, "item")
VComment::VComment(Item* parent, NodeType* node) : Super(parent, node, itemStyles().get())
{
// import existing diagrams
for(auto diagram : *node->diagrams())
{
diagrams_[diagram->name()] = diagram;
}
editing_ = node->lines()->size() == 0 || (node->lines()->size() == 1 && node->lines()->at(0)->get().isEmpty());
parseLines();
}
// split up user-provided text into single elements
void VComment::parseLines()
{
clearChildren();
bool isHTML = false;
QSet<QString> diagramNames{};
int listCount = -1;
for(auto nodeLine : *node()->lines())
{
QRegExp rx("^={3,}|-{3,}|\\.{3,}$");
QString line = nodeLine->get();
// is this a new enumeration item?
if(line.left(3) == " * ")
{
listCount++;
// does this create a new list?
if(listCount == 0)
{
pushTextLine("<ol><li>");
line = line.mid(3);
}
// otherwise, just add another list item
else
{
pushTextLine("</li><li>");
line = line.mid(3);
}
}
// or is this extending an existing list?
else if(line.left(3) == " " && listCount > -1)
{
line = line.mid(3);
}
// if this is not an enumeration item, reset listCount
else if(listCount > -1 && line.left(3) != " * " && line.left(3) != " ")
{
pushTextLine("</li></ol>");
listCount = -1;
}
// is this HTML?
if(line == "<html>")
{
popLineBuffer();
isHTML = true;
continue;
}
else if(isHTML)
{
if(line == "</html>")
{
isHTML = false;
popLineBuffer(true);
}
else
{
pushTextLine(line);
}
// don't process further
continue;
}
if(rx.exactMatch(line))
{
// A line consists of one of . - = that is repeated three times or more
// The used character defines the strength of the header, i.e. one of three levels
QString style;
switch(line[0].toAscii())
{
default:
case '.': style = "single"; break;
case '-': style = "double"; break;
case '=': style = "triple"; break;
}
addChildItem(new Line(this, Line::itemStyles().get(style)));
continue;
}
// is this a header? replace it right away with the appropriate tag
rx.setPattern("^(#+)([^#].*)");
// allow headers h1 to h6
if(rx.exactMatch(line) && rx.cap(1).length() <= 6)
{
QString len = QString::number(rx.cap(1).length());
pushTextLine("<h" + len + ">" + rx.cap(2).simplified() + "</h" + len + ">");
}
// is this a diagram? format: [diagram#diagramName]
else if(line.left(9) == "[diagram#" && line.right(1) == "]" && line.size() > 9+1)
{
QString diagramName = line.mid(9,line.size()-9-1);
diagramNames << diagramName;
CommentDiagram* diagram = diagrams_.value(diagramName, nullptr);
if(diagram == nullptr)
{
diagram = new CommentDiagram(nullptr, diagramName);
diagrams_[diagramName] = diagram;
}
auto item = renderer()->render(this, diagram);
addChildItem(item);
}
// urls are specified as [browser#http://www.google.com]
else if(line.left(9) == "[browser#" && line.right(1) == "]" && line.size() > 9+1)
{
QString mid = line.mid(9, line.size()-9-1);
// read width and height, if specified
auto items = parseMarkdownArguments(mid);
QString url = items->at(0).second;
auto browser = new VCommentBrowser(this, QUrl(url));
if(items->size() > 1)
{
QSize size = parseSize(items->at(1).second);
browser->updateSize(size);
}
addChildItem(browser);
delete items;
}
// images are specified as
// [image#/home/user/image.png]
// [image#image.png|300x300] to specify a size
else if(line.left(7) == "[image#" && line.right(1) == "]" && line.size() > 7+1)
{
QString mid = line.mid(7, line.size()-7-1);
// read width and height, if specified
auto items = parseMarkdownArguments(mid);
QString path = items->at(0).second;
QSize size(0,0);
if(items->size() > 1)
size = parseSize(items->at(1).second);
addChildItem(new VCommentImage(this, items->at(0).second, size));
delete items;
}
else
{
pushTextLine(line);
}
}
popLineBuffer();
synchroniseDiagrams(diagramNames);
}
void VComment::synchroniseDiagrams(QSet<QString> itemDiagramNames)
{
// get all diagrams from the node
auto nodeDiagrams = node()->diagrams();
// gather all names from the node diagrams for easier comparison
QSet<QString> nodeDiagramNames{};
for(auto diagram : *nodeDiagrams)
nodeDiagramNames << diagram->name();
// get intersection of two sets
QSet<QString> intersection(itemDiagramNames);
intersection.intersect(nodeDiagramNames);
// new diagrams were already constructed inside of parseLines(),
// they also need to be added to the model now
auto newDiagramNames = itemDiagramNames - intersection;
if(newDiagramNames.size() > 0)
{
node()->model()->beginModification(node(), "Adding new diagrams");
for(auto diagramName : newDiagramNames)
{
auto diagram = diagrams_.value(diagramName);
node()->diagrams()->append(diagram);
}
node()->model()->endModification();
}
// diagrams that are no longer referenced need to be removed from the model
auto oldDiagramNames = nodeDiagramNames - intersection;
if(oldDiagramNames.size() > 0)
{
node()->model()->beginModification(node(), "Removing unreferenced diagrams");
for(auto diagramName : oldDiagramNames)
{
auto diagram = diagrams_.value(diagramName);
node()->diagrams()->remove(diagram);
diagrams_.remove(diagramName);
}
node()->model()->endModification();
}
}
QMap<QString, CommentDiagram*> VComment::diagrams() const
{
return diagrams_;
}
QSize VComment::parseSize(const QString& str)
{
int index = str.indexOf('x');
bool ok{};
int width = str.left(index).toInt(&ok);
if(index > 0 && !ok)
qDebug() << "Invalid width specified in size string:" << str;
int height = str.mid(index+1).toInt(&ok);
if(index+1 < str.size()-1 && !ok)
qDebug() << "Invalid height specified in size string:" << str;
return QSize(width, height);
}
QVector<QPair<QString,QString>>* VComment::parseMarkdownArguments(const QString& argString)
{
// split string on all pipes
auto lines = argString.split('|');
// TODO: get rid of escaped pipes \| e.g. in case an url contains one
auto pairs = new QVector<QPair<QString,QString>>();
// read key/value pairs
QRegExp rx("^[a-zA-Z]{,15}=");
for(auto line : lines)
{
int index = rx.indexIn(line);
if(index == -1)
pairs->push_back(qMakePair(QString(), line));
else
pairs->push_back(qMakePair(line.left(index), line.mid(index+1)));
}
return pairs;
}
QString VComment::replaceMarkdown(QString str)
{
QRegExp rx;
rx.setPattern("\\*\\*([^\\*]+)\\*\\*");
str.replace(rx, "<i>\\1</i>");
rx.setPattern("\\*([^\\*]+)\\*");
str.replace(rx, "<b>\\1</b>");
return str;
}
void VComment::pushTextLine(QString text)
{
lineBuffer_.push_back(text);
}
void VComment::popLineBuffer(bool asHtml)
{
if(lineBuffer_.size() > 0)
{
auto joined = lineBuffer_.join("\n");
if(asHtml)
{
auto browser = new VCommentBrowser(this, joined);
children_.push_back(browser);
}
else
{
auto text = new Text(this, Text::itemStyles().get("comment"), replaceMarkdown(joined));
text->setTextFormat(Qt::RichText);
children_.push_back(text);
}
lineBuffer_.clear();
}
}
void VComment::addChildItem(Visualization::Item* item)
{
popLineBuffer();
children_.push_back(item);
}
void VComment::toggleEditing()
{
if(node()->lines()->size() == 0)
editing_ = true;
else
editing_ = !editing_;
if(!editing_)
parseLines();
setUpdateNeeded(StandardUpdate);
}
bool VComment::editing() const
{
return editing_;
}
void VComment::initializeForms()
{
addForm((new SequentialLayoutFormElement())
->setVertical()
->setListOfItems([](Item* i) {
auto vc = static_cast<VComment*>(i);
return vc->children_;
}
));
addForm(item(&I::editLabel_, [](I* v){
return v->node()->lines();
}));
}
int VComment::determineForm()
{
return editing_ ? 1 : 0;
}
} /* namespace Comments */
<|endoftext|>
|
<commit_before>#ifndef GOL_H_INCLUDED
#define GOL_H_INCLUDED
#include "tile.hxx"
namespace game_of_life
{
class WorkerCommunicator
{
public:
virtual void beginIteration() = 0;
virtual void sendBorders(Borders t) = 0;
virtual Borders receiveBorders() = 0;
virtual void waitForBordersRead() = 0;
virtual void endIteration() = 0;
};
class Worker
{
public:
Worker(WorkerCommunicator* c, AbstractTile* t);
void workInfinitely();
protected:
void makeIteration();
private:
WorkerCommunicator* communicator;
AbstractTile* tile;
};
}
#endif
<commit_msg>Communicator knows which borders to take<commit_after>#ifndef GOL_H_INCLUDED
#define GOL_H_INCLUDED
#include "tile.hxx"
namespace game_of_life
{
class WorkerCommunicator
{
public:
virtual void beginIteration() = 0;
virtual void sendBorders(AbstractTile* t) = 0;
virtual Borders receiveBorders() = 0;
virtual void waitForBordersRead() = 0;
virtual void endIteration() = 0;
};
class Worker
{
public:
Worker(WorkerCommunicator* c, AbstractTile* t);
void workInfinitely();
protected:
void makeIteration();
private:
WorkerCommunicator* communicator;
AbstractTile* tile;
};
}
#endif
<|endoftext|>
|
<commit_before>/*
* AscEmu Framework based on ArcEmu MMORPG Server
* Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/>
* Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "git_version.h"
#include "CrashHandler.h"
#include "Log.h"
void OutputCrashLogLine(const char* format, ...)
{
std::string s = FormatOutputString("logs", "CrashLog", false);
FILE* m_file = fopen(s.c_str(), "a");
if(!m_file) return;
va_list ap;
va_start(ap, format);
vfprintf(m_file, format, ap);
fprintf(m_file, "\n");
fclose(m_file);
va_end(ap);
}
#ifdef WIN32
#include "CircularQueue.h"
Mutex m_crashLock;
/* *
@file CrashHandler.h
Handles crashes/exceptions on a win32 based platform, writes a dump file,
for later bug fixing.
*/
# pragma warning( disable : 4311 )
#include <cstdio>
#include <ctime>
#include <tchar.h>
bool ON_CRASH_BREAK_DEBUGGER;
void StartCrashHandler()
{
// Firstly, check if there is a debugger present. There isn't any point in
// handling crashes internally if we have a debugger attached, that would
// just piss us off. :P
// Check for a debugger.
#ifndef X64
DWORD code;
__asm
{
MOV EAX, FS:[0x18]
MOV EAX, DWORD PTR [EAX + 0x30]
MOV ECX, DWORD PTR [EAX]
MOV [DWORD PTR code], ECX
}
if(code & 0x00010000)
{
// We got a debugger. We'll tell it to not exit on a crash but instead break into debugger.
ON_CRASH_BREAK_DEBUGGER = true;
}
else
{
// No debugger. On crash, we'll call OnCrash to save etc.
ON_CRASH_BREAK_DEBUGGER = false;
}
#else
ON_CRASH_BREAK_DEBUGGER = (IsDebuggerPresent() == TRUE) ? true : false;
#endif
if(!ON_CRASH_BREAK_DEBUGGER)
{
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR );
}
}
///////////////////////////////////////////////////////////////////////////////
// GetExceptionDescription
// Translate the exception code into something human readable
static const TCHAR* GetExceptionDescription(DWORD ExceptionCode)
{
struct ExceptionNames
{
DWORD ExceptionCode;
TCHAR* ExceptionName;
};
#if 0 // from winnt.h
#define STATUS_WAIT_0 ((DWORD )0x00000000L)
#define STATUS_ABANDONED_WAIT_0 ((DWORD )0x00000080L)
#define STATUS_USER_APC ((DWORD )0x000000C0L)
#define STATUS_TIMEOUT ((DWORD )0x00000102L)
#define STATUS_PENDING ((DWORD )0x00000103L)
#define STATUS_SEGMENT_NOTIFICATION ((DWORD )0x40000005L)
#define STATUS_GUARD_PAGE_VIOLATION ((DWORD )0x80000001L)
#define STATUS_DATATYPE_MISALIGNMENT ((DWORD )0x80000002L)
#define STATUS_BREAKPOINT ((DWORD )0x80000003L)
#define STATUS_SINGLE_STEP ((DWORD )0x80000004L)
#define STATUS_ACCESS_VIOLATION ((DWORD )0xC0000005L)
#define STATUS_IN_PAGE_ERROR ((DWORD )0xC0000006L)
#define STATUS_INVALID_HANDLE ((DWORD )0xC0000008L)
#define STATUS_NO_MEMORY ((DWORD )0xC0000017L)
#define STATUS_ILLEGAL_INSTRUCTION ((DWORD )0xC000001DL)
#define STATUS_NONCONTINUABLE_EXCEPTION ((DWORD )0xC0000025L)
#define STATUS_INVALID_DISPOSITION ((DWORD )0xC0000026L)
#define STATUS_ARRAY_BOUNDS_EXCEEDED ((DWORD )0xC000008CL)
#define STATUS_FLOAT_DENORMAL_OPERAND ((DWORD )0xC000008DL)
#define STATUS_FLOAT_DIVIDE_BY_ZERO ((DWORD )0xC000008EL)
#define STATUS_FLOAT_INEXACT_RESULT ((DWORD )0xC000008FL)
#define STATUS_FLOAT_INVALID_OPERATION ((DWORD )0xC0000090L)
#define STATUS_FLOAT_OVERFLOW ((DWORD )0xC0000091L)
#define STATUS_FLOAT_STACK_CHECK ((DWORD )0xC0000092L)
#define STATUS_FLOAT_UNDERFLOW ((DWORD )0xC0000093L)
#define STATUS_INTEGER_DIVIDE_BY_ZERO ((DWORD )0xC0000094L)
#define STATUS_INTEGER_OVERFLOW ((DWORD )0xC0000095L)
#define STATUS_PRIVILEGED_INSTRUCTION ((DWORD )0xC0000096L)
#define STATUS_STACK_OVERFLOW ((DWORD )0xC00000FDL)
#define STATUS_CONTROL_C_EXIT ((DWORD )0xC000013AL)
#define STATUS_FLOAT_MULTIPLE_FAULTS ((DWORD )0xC00002B4L)
#define STATUS_FLOAT_MULTIPLE_TRAPS ((DWORD )0xC00002B5L)
#define STATUS_ILLEGAL_VLM_REFERENCE ((DWORD )0xC00002C0L)
#endif
ExceptionNames ExceptionMap[] =
{
{0x40010005, _T("a Control-C")},
{0x40010008, _T("a Control-Break")},
{0x80000002, _T("a Datatype Misalignment")},
{0x80000003, _T("a Breakpoint")},
{0xc0000005, _T("an Access Violation")},
{0xc0000006, _T("an In Page Error")},
{0xc0000017, _T("a No Memory")},
{0xc000001d, _T("an Illegal Instruction")},
{0xc0000025, _T("a Noncontinuable Exception")},
{0xc0000026, _T("an Invalid Disposition")},
{0xc000008c, _T("a Array Bounds Exceeded")},
{0xc000008d, _T("a Float Denormal Operand")},
{0xc000008e, _T("a Float Divide by Zero")},
{0xc000008f, _T("a Float Inexact Result")},
{0xc0000090, _T("a Float Invalid Operation")},
{0xc0000091, _T("a Float Overflow")},
{0xc0000092, _T("a Float Stack Check")},
{0xc0000093, _T("a Float Underflow")},
{0xc0000094, _T("an Integer Divide by Zero")},
{0xc0000095, _T("an Integer Overflow")},
{0xc0000096, _T("a Privileged Instruction")},
{0xc00000fD, _T("a Stack Overflow")},
{0xc0000142, _T("a DLL Initialization Failed")},
{0xe06d7363, _T("a Microsoft C++ Exception")},
};
for(int i = 0; i < sizeof(ExceptionMap) / sizeof(ExceptionMap[0]); i++)
if(ExceptionCode == ExceptionMap[i].ExceptionCode)
return ExceptionMap[i].ExceptionName;
return _T("an Unknown exception type");
}
void echo(const char* format, ...)
{
va_list ap;
va_start(ap, format);
vprintf(format, ap);
std::string s = FormatOutputString("logs", "CrashLog", false);
FILE* m_file = fopen(s.c_str(), "a");
if(!m_file)
{
va_end(ap);
return;
}
vfprintf(m_file, format, ap);
fclose(m_file);
va_end(ap);
}
void PrintCrashInformation(PEXCEPTION_POINTERS except)
{
echo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
echo("Server has crashed. Reason was:\n");
echo(" %s at 0x%08X\n", GetExceptionDescription(except->ExceptionRecord->ExceptionCode),
(unsigned long)except->ExceptionRecord->ExceptionAddress);
#ifdef REPACK
echo("%s repack by %s has crashed. Visit %s for support.", REPACK, REPACK_AUTHOR, REPACK_WEBSITE);
#endif
echo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
}
void CStackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName)
{
}
void CStackWalker::OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
{
}
void CStackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr)
{
}
void CStackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry & entry)
{
CHAR buffer[STACKWALK_MAX_NAMELEN];
if((eType != lastEntry) && (entry.offset != 0))
{
if(entry.name[0] == 0)
strcpy(entry.name, "(function-name not available)");
if(entry.undName[0] != 0)
strcpy(entry.name, entry.undName);
if(entry.undFullName[0] != 0)
strcpy(entry.name, entry.undFullName);
char* p = strrchr(entry.loadedImageName, '\\');
if(!p)
p = entry.loadedImageName;
else
++p;
if(entry.lineFileName[0] == 0)
{
if(entry.name[0] == 0)
sprintf(entry.name, "%lld", entry.offset);
sprintf(buffer, "%s!%s Line %u\n", p, entry.name, entry.lineNumber);
}
else
sprintf(buffer, "%s!%s Line %u\n", p, entry.name, entry.lineNumber);
OnOutput(buffer);
}
}
void CStackWalker::OnOutput(LPCSTR szText)
{
std::string s = FormatOutputString("logs", "CrashLog", false);
FILE* m_file = fopen(s.c_str(), "a");
if(!m_file) return;
sLog.outError(" %s", szText);
fprintf(m_file, " %s", szText);
fclose(m_file);
}
bool died = false;
int __cdecl HandleCrash(PEXCEPTION_POINTERS pExceptPtrs)
{
if(pExceptPtrs == 0)
{
// Raise an exception :P
__try
{
RaiseException(EXCEPTION_BREAKPOINT, 0, 0, 0);
}
__except(HandleCrash(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION)
{
}
}
/* only allow one thread to crash. */
if(!m_crashLock.AttemptAcquire())
{
TerminateThread(GetCurrentThread(), static_cast<DWORD>(-1));
// not reached
}
if(died)
{
TerminateProcess(GetCurrentProcess(), static_cast<UINT>(-1));
// not reached:P
}
died = true;
// Create the date/time string
time_t curtime = time(NULL);
tm* pTime = localtime(&curtime);
char filename[MAX_PATH];
TCHAR modname[MAX_PATH * 2];
ZeroMemory(modname, sizeof(modname));
if(GetModuleFileName(0, modname, MAX_PATH * 2 - 2) <= 0)
strcpy(modname, "UNKNOWN");
char* mname = strrchr(modname, '\\');
(void*)mname++; // Remove the last
sprintf(filename, "CrashDumps\\dump-%s-%s-%u-%u-%u-%u-%u-%u-%u.dmp",
mname, BUILD_HASH_STR, pTime->tm_year + 1900, pTime->tm_mon + 1, pTime->tm_mday,
pTime->tm_hour, pTime->tm_min, pTime->tm_sec, GetCurrentThreadId());
HANDLE hDump = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
if(hDump == INVALID_HANDLE_VALUE)
{
// Create the directory first
CreateDirectory("CrashDumps", 0);
hDump = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
}
sLog.outError("Server has crashed. Creating crash dump file %s", filename);
if(hDump == INVALID_HANDLE_VALUE)
{
sLog.outError("Could not open crash dump file.");
}
else
{
MINIDUMP_EXCEPTION_INFORMATION info;
info.ClientPointers = FALSE;
info.ExceptionPointers = pExceptPtrs;
info.ThreadId = GetCurrentThreadId();
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDump, MiniDumpWithIndirectlyReferencedMemory, &info, 0, 0);
CloseHandle(hDump);
}
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
OnCrash(!ON_CRASH_BREAK_DEBUGGER);
sLog.Close();
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
<commit_msg>Resolved msvc C4302 (PVOID to unsigned long conversion)<commit_after>/*
* AscEmu Framework based on ArcEmu MMORPG Server
* Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/>
* Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "git_version.h"
#include "CrashHandler.h"
#include "Log.h"
void OutputCrashLogLine(const char* format, ...)
{
std::string s = FormatOutputString("logs", "CrashLog", false);
FILE* m_file = fopen(s.c_str(), "a");
if(!m_file) return;
va_list ap;
va_start(ap, format);
vfprintf(m_file, format, ap);
fprintf(m_file, "\n");
fclose(m_file);
va_end(ap);
}
#ifdef WIN32
#include "CircularQueue.h"
Mutex m_crashLock;
/* *
@file CrashHandler.h
Handles crashes/exceptions on a win32 based platform, writes a dump file,
for later bug fixing.
*/
# pragma warning( disable : 4311 )
#include <cstdio>
#include <ctime>
#include <tchar.h>
bool ON_CRASH_BREAK_DEBUGGER;
void StartCrashHandler()
{
// Firstly, check if there is a debugger present. There isn't any point in
// handling crashes internally if we have a debugger attached, that would
// just piss us off. :P
// Check for a debugger.
#ifndef X64
DWORD code;
__asm
{
MOV EAX, FS:[0x18]
MOV EAX, DWORD PTR [EAX + 0x30]
MOV ECX, DWORD PTR [EAX]
MOV [DWORD PTR code], ECX
}
if(code & 0x00010000)
{
// We got a debugger. We'll tell it to not exit on a crash but instead break into debugger.
ON_CRASH_BREAK_DEBUGGER = true;
}
else
{
// No debugger. On crash, we'll call OnCrash to save etc.
ON_CRASH_BREAK_DEBUGGER = false;
}
#else
ON_CRASH_BREAK_DEBUGGER = (IsDebuggerPresent() == TRUE) ? true : false;
#endif
if(!ON_CRASH_BREAK_DEBUGGER)
{
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR );
}
}
///////////////////////////////////////////////////////////////////////////////
// GetExceptionDescription
// Translate the exception code into something human readable
static const TCHAR* GetExceptionDescription(DWORD ExceptionCode)
{
struct ExceptionNames
{
DWORD ExceptionCode;
TCHAR* ExceptionName;
};
#if 0 // from winnt.h
#define STATUS_WAIT_0 ((DWORD )0x00000000L)
#define STATUS_ABANDONED_WAIT_0 ((DWORD )0x00000080L)
#define STATUS_USER_APC ((DWORD )0x000000C0L)
#define STATUS_TIMEOUT ((DWORD )0x00000102L)
#define STATUS_PENDING ((DWORD )0x00000103L)
#define STATUS_SEGMENT_NOTIFICATION ((DWORD )0x40000005L)
#define STATUS_GUARD_PAGE_VIOLATION ((DWORD )0x80000001L)
#define STATUS_DATATYPE_MISALIGNMENT ((DWORD )0x80000002L)
#define STATUS_BREAKPOINT ((DWORD )0x80000003L)
#define STATUS_SINGLE_STEP ((DWORD )0x80000004L)
#define STATUS_ACCESS_VIOLATION ((DWORD )0xC0000005L)
#define STATUS_IN_PAGE_ERROR ((DWORD )0xC0000006L)
#define STATUS_INVALID_HANDLE ((DWORD )0xC0000008L)
#define STATUS_NO_MEMORY ((DWORD )0xC0000017L)
#define STATUS_ILLEGAL_INSTRUCTION ((DWORD )0xC000001DL)
#define STATUS_NONCONTINUABLE_EXCEPTION ((DWORD )0xC0000025L)
#define STATUS_INVALID_DISPOSITION ((DWORD )0xC0000026L)
#define STATUS_ARRAY_BOUNDS_EXCEEDED ((DWORD )0xC000008CL)
#define STATUS_FLOAT_DENORMAL_OPERAND ((DWORD )0xC000008DL)
#define STATUS_FLOAT_DIVIDE_BY_ZERO ((DWORD )0xC000008EL)
#define STATUS_FLOAT_INEXACT_RESULT ((DWORD )0xC000008FL)
#define STATUS_FLOAT_INVALID_OPERATION ((DWORD )0xC0000090L)
#define STATUS_FLOAT_OVERFLOW ((DWORD )0xC0000091L)
#define STATUS_FLOAT_STACK_CHECK ((DWORD )0xC0000092L)
#define STATUS_FLOAT_UNDERFLOW ((DWORD )0xC0000093L)
#define STATUS_INTEGER_DIVIDE_BY_ZERO ((DWORD )0xC0000094L)
#define STATUS_INTEGER_OVERFLOW ((DWORD )0xC0000095L)
#define STATUS_PRIVILEGED_INSTRUCTION ((DWORD )0xC0000096L)
#define STATUS_STACK_OVERFLOW ((DWORD )0xC00000FDL)
#define STATUS_CONTROL_C_EXIT ((DWORD )0xC000013AL)
#define STATUS_FLOAT_MULTIPLE_FAULTS ((DWORD )0xC00002B4L)
#define STATUS_FLOAT_MULTIPLE_TRAPS ((DWORD )0xC00002B5L)
#define STATUS_ILLEGAL_VLM_REFERENCE ((DWORD )0xC00002C0L)
#endif
ExceptionNames ExceptionMap[] =
{
{0x40010005, _T("a Control-C")},
{0x40010008, _T("a Control-Break")},
{0x80000002, _T("a Datatype Misalignment")},
{0x80000003, _T("a Breakpoint")},
{0xc0000005, _T("an Access Violation")},
{0xc0000006, _T("an In Page Error")},
{0xc0000017, _T("a No Memory")},
{0xc000001d, _T("an Illegal Instruction")},
{0xc0000025, _T("a Noncontinuable Exception")},
{0xc0000026, _T("an Invalid Disposition")},
{0xc000008c, _T("a Array Bounds Exceeded")},
{0xc000008d, _T("a Float Denormal Operand")},
{0xc000008e, _T("a Float Divide by Zero")},
{0xc000008f, _T("a Float Inexact Result")},
{0xc0000090, _T("a Float Invalid Operation")},
{0xc0000091, _T("a Float Overflow")},
{0xc0000092, _T("a Float Stack Check")},
{0xc0000093, _T("a Float Underflow")},
{0xc0000094, _T("an Integer Divide by Zero")},
{0xc0000095, _T("an Integer Overflow")},
{0xc0000096, _T("a Privileged Instruction")},
{0xc00000fD, _T("a Stack Overflow")},
{0xc0000142, _T("a DLL Initialization Failed")},
{0xe06d7363, _T("a Microsoft C++ Exception")},
};
for(int i = 0; i < sizeof(ExceptionMap) / sizeof(ExceptionMap[0]); i++)
if(ExceptionCode == ExceptionMap[i].ExceptionCode)
return ExceptionMap[i].ExceptionName;
return _T("an Unknown exception type");
}
void echo(const char* format, ...)
{
va_list ap;
va_start(ap, format);
vprintf(format, ap);
std::string s = FormatOutputString("logs", "CrashLog", false);
FILE* m_file = fopen(s.c_str(), "a");
if(!m_file)
{
va_end(ap);
return;
}
vfprintf(m_file, format, ap);
fclose(m_file);
va_end(ap);
}
void PrintCrashInformation(PEXCEPTION_POINTERS except)
{
echo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
echo("Server has crashed. Reason was:\n");
echo(" %s at 0x%08X\n", GetExceptionDescription(except->ExceptionRecord->ExceptionCode),
except->ExceptionRecord->ExceptionAddress);
#ifdef REPACK
echo("%s repack by %s has crashed. Visit %s for support.", REPACK, REPACK_AUTHOR, REPACK_WEBSITE);
#endif
echo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
}
void CStackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName)
{
}
void CStackWalker::OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
{
}
void CStackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr)
{
}
void CStackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry & entry)
{
CHAR buffer[STACKWALK_MAX_NAMELEN];
if((eType != lastEntry) && (entry.offset != 0))
{
if(entry.name[0] == 0)
strcpy(entry.name, "(function-name not available)");
if(entry.undName[0] != 0)
strcpy(entry.name, entry.undName);
if(entry.undFullName[0] != 0)
strcpy(entry.name, entry.undFullName);
char* p = strrchr(entry.loadedImageName, '\\');
if(!p)
p = entry.loadedImageName;
else
++p;
if(entry.lineFileName[0] == 0)
{
if(entry.name[0] == 0)
sprintf(entry.name, "%lld", entry.offset);
sprintf(buffer, "%s!%s Line %u\n", p, entry.name, entry.lineNumber);
}
else
sprintf(buffer, "%s!%s Line %u\n", p, entry.name, entry.lineNumber);
OnOutput(buffer);
}
}
void CStackWalker::OnOutput(LPCSTR szText)
{
std::string s = FormatOutputString("logs", "CrashLog", false);
FILE* m_file = fopen(s.c_str(), "a");
if(!m_file) return;
sLog.outError(" %s", szText);
fprintf(m_file, " %s", szText);
fclose(m_file);
}
bool died = false;
int __cdecl HandleCrash(PEXCEPTION_POINTERS pExceptPtrs)
{
if(pExceptPtrs == 0)
{
// Raise an exception :P
__try
{
RaiseException(EXCEPTION_BREAKPOINT, 0, 0, 0);
}
__except(HandleCrash(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION)
{
}
}
/* only allow one thread to crash. */
if(!m_crashLock.AttemptAcquire())
{
TerminateThread(GetCurrentThread(), static_cast<DWORD>(-1));
// not reached
}
if(died)
{
TerminateProcess(GetCurrentProcess(), static_cast<UINT>(-1));
// not reached:P
}
died = true;
// Create the date/time string
time_t curtime = time(NULL);
tm* pTime = localtime(&curtime);
char filename[MAX_PATH];
TCHAR modname[MAX_PATH * 2];
ZeroMemory(modname, sizeof(modname));
if(GetModuleFileName(0, modname, MAX_PATH * 2 - 2) <= 0)
strcpy(modname, "UNKNOWN");
char* mname = strrchr(modname, '\\');
(void*)mname++; // Remove the last
sprintf(filename, "CrashDumps\\dump-%s-%s-%u-%u-%u-%u-%u-%u-%u.dmp",
mname, BUILD_HASH_STR, pTime->tm_year + 1900, pTime->tm_mon + 1, pTime->tm_mday,
pTime->tm_hour, pTime->tm_min, pTime->tm_sec, GetCurrentThreadId());
HANDLE hDump = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
if(hDump == INVALID_HANDLE_VALUE)
{
// Create the directory first
CreateDirectory("CrashDumps", 0);
hDump = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
}
sLog.outError("Server has crashed. Creating crash dump file %s", filename);
if(hDump == INVALID_HANDLE_VALUE)
{
sLog.outError("Could not open crash dump file.");
}
else
{
MINIDUMP_EXCEPTION_INFORMATION info;
info.ClientPointers = FALSE;
info.ExceptionPointers = pExceptPtrs;
info.ThreadId = GetCurrentThreadId();
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDump, MiniDumpWithIndirectlyReferencedMemory, &info, 0, 0);
CloseHandle(hDump);
}
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
OnCrash(!ON_CRASH_BREAK_DEBUGGER);
sLog.Close();
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
<|endoftext|>
|
<commit_before>// -----------------------------------------------------------------------------
//
// MIT License
//
// Copyright (c) 2016 Alberto Sola
//
// 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.
//
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
#ifndef __TASKER_HPP
#define __TASKER_HPP
#include <vector>
#include "task.hpp"
#include "taskdb.hpp"
// -----------------------------------------------------------------------------
class Tasker{
private:
TaskDB task_db;
public:
Tasker();
const Task & get_task(unsigned int id) const;
void get_task_list(std::vector<Task> & tasks, std::string tag);
void add_task(Task & task);
void delete_task(unsigned int id);
bool finish_task(unsigned int id);
void save() const;
};
// -----------------------------------------------------------------------------
#endif
<commit_msg>Optional parameter.<commit_after>// -----------------------------------------------------------------------------
//
// MIT License
//
// Copyright (c) 2016 Alberto Sola
//
// 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.
//
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
#ifndef __TASKER_HPP
#define __TASKER_HPP
#include <vector>
#include "task.hpp"
#include "taskdb.hpp"
// -----------------------------------------------------------------------------
class Tasker{
private:
TaskDB task_db;
public:
Tasker();
const Task & get_task(unsigned int id) const;
void get_task_list(std::vector<Task> & tasks, std::string tag = "");
void add_task(Task & task);
void delete_task(unsigned int id);
bool finish_task(unsigned int id);
void save() const;
};
// -----------------------------------------------------------------------------
#endif
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// insert_executor.cpp
//
// Identification: src/backend/executor/insert_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/executor/insert_executor.h"
#include "backend/planner/insert_plan.h"
#include "backend/catalog/manager.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile.h"
#include "backend/storage/tuple_iterator.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/records/tuple_record.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for insert executor.
* @param node Insert node corresponding to this executor.
*/
InsertExecutor::InsertExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}
/**
* @brief Nothing to init at the moment.
* @return true on success, false otherwise.
*/
bool InsertExecutor::DInit() {
assert(children_.size() == 0 || children_.size() == 1);
assert(executor_context_);
done_ = false;
return true;
}
/**
* @brief Adds a column to the logical tile, using the position lists.
* @return true on success, false otherwise.
*/
bool InsertExecutor::DExecute() {
if (done_) return false;
assert(!done_);
const planner::InsertPlan &node = GetPlanNode<planner::InsertPlan>();
storage::DataTable *target_table_ = node.GetTable();
assert(target_table_);
auto transaction_ = executor_context_->GetTransaction();
// Inserting a logical tile.
if (children_.size() == 1) {
LOG_INFO("Insert executor :: 1 child \n");
if (!children_[0]->Execute()) {
return false;
}
std::unique_ptr<LogicalTile> logical_tile(children_[0]->GetOutput());
assert(logical_tile.get() != nullptr);
auto target_table_schema = target_table_->GetSchema();
auto column_count = target_table_schema->GetColumnCount();
std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(target_table_schema, true));
// Go over the logical tile
for (oid_t tuple_id : *logical_tile) {
expression::ContainerTuple<LogicalTile> cur_tuple(logical_tile.get(), tuple_id);
// Materialize the logical tile tuple
for(oid_t column_itr = 0 ; column_itr < column_count ; column_itr++)
tuple.get()->SetValue(column_itr, cur_tuple.GetValue(column_itr));
peloton::ItemPointer location = target_table_->InsertTuple(transaction_, tuple.get());
if (location.block == INVALID_OID) {
transaction_->SetResult(peloton::Result::RESULT_FAILURE);
return false;
}
transaction_->RecordInsert(location);
executor_context_->num_processed += 1; // insert one
}
return true;
}
// Inserting a collection of tuples from plan node
else if (children_.size() == 0) {
LOG_INFO("Insert executor :: 0 child \n");
// Extract expressions from plan node and construct the tuple.
// For now we just handle a single tuple
auto schema = target_table_->GetSchema();
std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true));
auto project_info = node.GetProjectInfo();
// There should be no direct maps
assert(project_info);
assert(project_info->GetDirectMapList().size() == 0);
for (auto target : project_info->GetTargetList()) {
peloton::Value value =
target.second->Evaluate(nullptr, nullptr, executor_context_);
tuple->SetValue(target.first, value);
}
// Carry out insertion
ItemPointer location = target_table_->InsertTuple(transaction_, tuple.get());
LOG_INFO("Inserted into location: %lu, %lu", location.block, location.offset);
if (location.block == INVALID_OID) {
LOG_INFO("Failed to Insert. Set txn failure.");
transaction_->SetResult(peloton::Result::RESULT_FAILURE);
return false;
}
transaction_->RecordInsert(location);
// Logging
{
auto& log_manager = logging::LogManager::GetInstance();
if(log_manager.IsInLoggingMode()){
auto logger = log_manager.GetBackendLogger();
auto record = logger->GetTupleRecord(LOGRECORD_TYPE_TUPLE_INSERT,
transaction_->GetTransactionId(),
target_table_->GetOid(),
location,
INVALID_ITEMPOINTER,
tuple.get());
logger->Log(record);
}
}
executor_context_->num_processed += 1; // insert one
done_ = true;
return true;
}
return true;
}
} // namespace executor
} // namespace peloton
<commit_msg>we can dirtectly dereference a unique ptr<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// insert_executor.cpp
//
// Identification: src/backend/executor/insert_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/executor/insert_executor.h"
#include "backend/planner/insert_plan.h"
#include "backend/catalog/manager.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile.h"
#include "backend/storage/tuple_iterator.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/records/tuple_record.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for insert executor.
* @param node Insert node corresponding to this executor.
*/
InsertExecutor::InsertExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}
/**
* @brief Nothing to init at the moment.
* @return true on success, false otherwise.
*/
bool InsertExecutor::DInit() {
assert(children_.size() == 0 || children_.size() == 1);
assert(executor_context_);
done_ = false;
return true;
}
/**
* @brief Adds a column to the logical tile, using the position lists.
* @return true on success, false otherwise.
*/
bool InsertExecutor::DExecute() {
if (done_) return false;
assert(!done_);
const planner::InsertPlan &node = GetPlanNode<planner::InsertPlan>();
storage::DataTable *target_table_ = node.GetTable();
assert(target_table_);
auto transaction_ = executor_context_->GetTransaction();
// Inserting a logical tile.
if (children_.size() == 1) {
LOG_INFO("Insert executor :: 1 child \n");
if (!children_[0]->Execute()) {
return false;
}
std::unique_ptr<LogicalTile> logical_tile(children_[0]->GetOutput());
assert(logical_tile.get() != nullptr);
auto target_table_schema = target_table_->GetSchema();
auto column_count = target_table_schema->GetColumnCount();
std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(target_table_schema, true));
// Go over the logical tile
for (oid_t tuple_id : *logical_tile) {
expression::ContainerTuple<LogicalTile> cur_tuple(logical_tile.get(), tuple_id);
// Materialize the logical tile tuple
for(oid_t column_itr = 0 ; column_itr < column_count ; column_itr++)
tuple->SetValue(column_itr, cur_tuple.GetValue(column_itr));
peloton::ItemPointer location = target_table_->InsertTuple(transaction_, tuple.get());
if (location.block == INVALID_OID) {
transaction_->SetResult(peloton::Result::RESULT_FAILURE);
return false;
}
transaction_->RecordInsert(location);
executor_context_->num_processed += 1; // insert one
}
return true;
}
// Inserting a collection of tuples from plan node
else if (children_.size() == 0) {
LOG_INFO("Insert executor :: 0 child \n");
// Extract expressions from plan node and construct the tuple.
// For now we just handle a single tuple
auto schema = target_table_->GetSchema();
std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true));
auto project_info = node.GetProjectInfo();
// There should be no direct maps
assert(project_info);
assert(project_info->GetDirectMapList().size() == 0);
for (auto target : project_info->GetTargetList()) {
peloton::Value value =
target.second->Evaluate(nullptr, nullptr, executor_context_);
tuple->SetValue(target.first, value);
}
// Carry out insertion
ItemPointer location = target_table_->InsertTuple(transaction_, tuple.get());
LOG_INFO("Inserted into location: %lu, %lu", location.block, location.offset);
if (location.block == INVALID_OID) {
LOG_INFO("Failed to Insert. Set txn failure.");
transaction_->SetResult(peloton::Result::RESULT_FAILURE);
return false;
}
transaction_->RecordInsert(location);
// Logging
{
auto& log_manager = logging::LogManager::GetInstance();
if(log_manager.IsInLoggingMode()){
auto logger = log_manager.GetBackendLogger();
auto record = logger->GetTupleRecord(LOGRECORD_TYPE_TUPLE_INSERT,
transaction_->GetTransactionId(),
target_table_->GetOid(),
location,
INVALID_ITEMPOINTER,
tuple.get());
logger->Log(record);
}
}
executor_context_->num_processed += 1; // insert one
done_ = true;
return true;
}
return true;
}
} // namespace executor
} // namespace peloton
<|endoftext|>
|
<commit_before>/*
* Louvain.cpp
*
* Created on: 25.02.2013
* Author: cls
*/
#include "Louvain.h"
namespace EnsembleClustering {
Louvain::Louvain(std::string par) {
this->parallelism = par;
}
Louvain::~Louvain() {
// TODO Auto-generated destructor stub
}
Clustering Louvain::pass(Graph& G) {
// init clustering to singletons
Clustering zeta(G.numberOfNodes());
zeta.allToSingletons();
// $\omega(E)$
edgeweight total = G.totalEdgeWeight();
// For each node we store a map that maps from cluster ID
// to weight of edges to that cluster, this needs to be updated when a change occurs
std::vector<std::map<cluster, edgeweight> > incidenceWeight(G.numberOfNodes());
G.forWeightedEdges([&](node u, node v, edgeweight w) { // FIXME: parallel would be better, but might cause problems
cluster C = zeta[v];
if (u != v) {
#pragma omp critical
{
incidenceWeight[u][C] += w;
}
}
});
// modularity update formula for node moves
// $$\Delta mod(u:\ C\to D)=\frac{\omega(u|D)-\omega(u|C\setminus v)}{\omega(E)}+\frac{2\cdot\vol(C\setminus u)\cdot\vol(u)-2\cdot\vol(D)\cdot\vol(u)}{4\cdot\omega(E)^{2}}$$
// parts of formula follow
NodeMap<double> volNode(G.numberOfNodes(), 0.0);
// calculate and store volume of each node
G.parallelForNodes([&](node u){
volNode[u] += G.weightedDegree(u);
volNode[u] += G.weight(u, u); // consider self-loop twice
});
IndexMap<cluster, double> volCluster(G.numberOfNodes(), 0.0);
// set volume for all singletons
zeta.parallelForEntries([&](node u, cluster C){
volCluster[C] = volNode[u];
});
// $\vol(C \ {x})$ - volume of cluster C excluding node x
auto volClusterMinusNode = [&](cluster C, node x){
if (zeta[x] == C) {
return volCluster[C] - volNode[x];
} else {
return volCluster[C];
}
};
// $\omega(u | C \ u)$
auto omegaCut = [&](node u, cluster C) {
edgeweight w = 0.0;
#pragma omp critical
{
w = incidenceWeight[u][C];
}
return w;
// edgeweight sum = 0.0;
// G.forWeightedEdgesOf(u, [&](node u, node v, edgeweight w){
// if (zeta[v] == C) {
// if (v != u){
// sum += w;
// }
// }
// });
// return sum;
};
// difference in modularity when moving node u from cluster C to D
auto deltaMod = [&](node u, cluster C, cluster D){
double delta = (omegaCut(u, D) - omegaCut(u, C)) / total + ((volClusterMinusNode(C, u) - volClusterMinusNode(D, u)) * volNode[u]) / (2 * total * total);
return delta;
};
Luby luby; // independent set algorithm
std::vector<bool> I;
if (this->parallelism == "independent") {
INFO("finding independent set");
I = luby.run(G);
}
// FIXME: parallel unit tests lead to hanging execution (deadlocks or infinite loops?) sometimes
// begin pass
int i = 0;
bool change; // change in last iteration?
do {
i += 1;
DEBUG("---> Louvain pass: iteration # " << i);
change = false; // is clustering stable?
// try to improve modularity by moving a node to neighboring clusters
auto moveNode = [&](node u){
cluster C = zeta[u];
TRACE("Processing node " << u << " of cluster " << C);
// std::cout << ".";
cluster best;
double deltaBest = -0.5;
G.forNeighborsOf(u, [&](node v){
TRACE("Neighbor " << v << ", which is still in cluster " << zeta[v]);
if (zeta[v] != zeta[u]) { // consider only nodes in other clusters (and implicitly only nodes other than u)
cluster D = zeta[v];
double delta = deltaMod(u, C, D);
if (delta > deltaBest) {
deltaBest = delta;
best = D;
}
}
});
if (deltaBest > 0.0) { // if modularity improvement possible
assert (best != zeta[u]); // do not "move" to original cluster
TRACE("Move vertex " << u << " to cluster " << best << ", deltaMod: " << deltaBest);
// update weight of edges to incident clusters
G.forWeightedNeighborsOf(u, [&](node v, edgeweight w) {
#pragma omp critical
{
incidenceWeight[v][zeta[u]] -= w;
incidenceWeight[v][best] += w;
}
});
zeta[u] = best; // move to best cluster
change = true; // change to clustering has been made
this->anyChange = true; // indicate globally that clustering was modified
// update the volume of the two clusters
#pragma omp atomic update
volCluster[C] -= volNode[u];
#pragma omp atomic update
volCluster[best] += volNode[u];
}
};
// apply node movement according to parallelization strategy
if (this->parallelism == "none") {
G.forNodes(moveNode);
} else if (this->parallelism == "naive") {
G.parallelForNodes(moveNode);
} else if (this->parallelism == "naive-balanced") {
G.balancedParallelForNodes(moveNode);
} else if (this->parallelism == "independent") {
// try to move only the nodes in independent set
G.parallelForNodes([&](node u){
if (I[u]) {
moveNode(u);
}
});
} else {
ERROR("unknown parallelization strategy: " << this->parallelism);
exit(1);
}
// std::cout << std::endl;
} while (change && i < MAX_LOUVAIN_ITERATIONS);
return zeta;
}
Clustering Louvain::run(Graph& G) {
INFO("starting Louvain method");
// sub-algorithms
ClusterContracter contracter;
ClusteringProjector projector;
// hierarchies
std::vector<std::pair<Graph, NodeMap<node> > > hierarchy; // hierarchy of graphs G^{i} and maps M^{i->i+1}
std::vector<NodeMap<node> > maps; // hierarchy of maps M^{i->i+1}
int h = -1; // finest hierarchy level
bool done = false; //
Graph* graph = &G;
do {
h += 1; // begin new hierarchy level
INFO("Louvain hierarchy level " << h);
// one local optimization pass
DEBUG("starting Louvain pass");
Clustering clustering = this->pass(*graph);
if (this->anyChange){
// contract the graph according to clustering
DEBUG("starting contraction");
hierarchy.push_back(contracter.run(*graph, clustering));
maps.push_back(hierarchy[h].second);
graph = &hierarchy[h].first;
done = false; // new hierarchy level, continue with loop
this->anyChange = false; // reset change flag
} else {
done = true; // if clustering was not modified, do not contract and exit loop
}
} while (! done);
DEBUG("starting projection");
// project fine graph to result clustering
Clustering result = projector.projectCoarseGraphToFinestClustering(*graph, G, maps);
return result;
}
std::string Louvain::toString() const {
std::stringstream strm;
strm << "Louvain";
return strm.str();
}
} /* namespace EnsembleClustering */
<commit_msg>atomic update and critical section for Louvain, albeit slow<commit_after>/*
* Louvain.cpp
*
* Created on: 25.02.2013
* Author: cls
*/
#include "Louvain.h"
namespace EnsembleClustering {
Louvain::Louvain(std::string par) {
this->parallelism = par;
}
Louvain::~Louvain() {
// TODO Auto-generated destructor stub
}
Clustering Louvain::pass(Graph& G) {
// init clustering to singletons
Clustering zeta(G.numberOfNodes());
zeta.allToSingletons();
// $\omega(E)$
edgeweight total = G.totalEdgeWeight();
// For each node we store a map that maps from cluster ID
// to weight of edges to that cluster, this needs to be updated when a change occurs
std::vector<std::map<cluster, edgeweight> > incidenceWeight(G.numberOfNodes());
G.parallelForWeightedEdges([&](node u, node v, edgeweight w) {
cluster C = zeta[v];
if (u != v) {
#pragma omp critical
{
incidenceWeight[u][C] += w;
}
}
});
// modularity update formula for node moves
// $$\Delta mod(u:\ C\to D)=\frac{\omega(u|D)-\omega(u|C\setminus v)}{\omega(E)}+\frac{2\cdot\vol(C\setminus u)\cdot\vol(u)-2\cdot\vol(D)\cdot\vol(u)}{4\cdot\omega(E)^{2}}$$
// parts of formula follow
NodeMap<double> volNode(G.numberOfNodes(), 0.0);
// calculate and store volume of each node
G.parallelForNodes([&](node u){
volNode[u] += G.weightedDegree(u);
volNode[u] += G.weight(u, u); // consider self-loop twice
});
IndexMap<cluster, double> volCluster(G.numberOfNodes(), 0.0);
// set volume for all singletons
zeta.parallelForEntries([&](node u, cluster C){
volCluster[C] = volNode[u];
});
// $\vol(C \ {x})$ - volume of cluster C excluding node x
auto volClusterMinusNode = [&](cluster C, node x){
if (zeta[x] == C) {
return volCluster[C] - volNode[x];
} else {
return volCluster[C];
}
};
// $\omega(u | C \ u)$
auto omegaCut = [&](node u, cluster C) {
edgeweight w = 0.0;
#pragma omp critical
{
w = incidenceWeight[u][C];
}
return w;
// edgeweight sum = 0.0;
// G.forWeightedEdgesOf(u, [&](node u, node v, edgeweight w){
// if (zeta[v] == C) {
// if (v != u){
// sum += w;
// }
// }
// });
// return sum;
};
// difference in modularity when moving node u from cluster C to D
auto deltaMod = [&](node u, cluster C, cluster D){
double delta = (omegaCut(u, D) - omegaCut(u, C)) / total + ((volClusterMinusNode(C, u) - volClusterMinusNode(D, u)) * volNode[u]) / (2 * total * total);
return delta;
};
Luby luby; // independent set algorithm
std::vector<bool> I;
if (this->parallelism == "independent") {
INFO("finding independent set");
I = luby.run(G);
}
// FIXME: parallel unit tests lead to hanging execution (deadlocks or infinite loops?) sometimes
// begin pass
int i = 0;
bool change; // change in last iteration?
do {
i += 1;
DEBUG("---> Louvain pass: iteration # " << i);
change = false; // is clustering stable?
// try to improve modularity by moving a node to neighboring clusters
auto moveNode = [&](node u){
cluster C = zeta[u];
TRACE("Processing node " << u << " of cluster " << C);
// std::cout << ".";
cluster best;
double deltaBest = -0.5;
G.forNeighborsOf(u, [&](node v){
TRACE("Neighbor " << v << ", which is still in cluster " << zeta[v]);
if (zeta[v] != zeta[u]) { // consider only nodes in other clusters (and implicitly only nodes other than u)
cluster D = zeta[v];
double delta = deltaMod(u, C, D);
if (delta > deltaBest) {
deltaBest = delta;
best = D;
}
}
});
if (deltaBest > 0.0) { // if modularity improvement possible
assert (best != zeta[u]); // do not "move" to original cluster
TRACE("Move vertex " << u << " to cluster " << best << ", deltaMod: " << deltaBest);
// update weight of edges to incident clusters
G.forWeightedNeighborsOf(u, [&](node v, edgeweight w) {
#pragma omp critical
{
incidenceWeight[v][zeta[u]] -= w;
incidenceWeight[v][best] += w;
}
});
zeta[u] = best; // move to best cluster
change = true; // change to clustering has been made
this->anyChange = true; // indicate globally that clustering was modified
// update the volume of the two clusters
#pragma omp atomic update
volCluster[C] -= volNode[u];
#pragma omp atomic update
volCluster[best] += volNode[u];
}
};
// apply node movement according to parallelization strategy
if (this->parallelism == "none") {
G.forNodes(moveNode);
} else if (this->parallelism == "naive") {
G.parallelForNodes(moveNode);
} else if (this->parallelism == "naive-balanced") {
G.balancedParallelForNodes(moveNode);
} else if (this->parallelism == "independent") {
// try to move only the nodes in independent set
G.parallelForNodes([&](node u){
if (I[u]) {
moveNode(u);
}
});
} else {
ERROR("unknown parallelization strategy: " << this->parallelism);
exit(1);
}
// std::cout << std::endl;
} while (change && i < MAX_LOUVAIN_ITERATIONS);
return zeta;
}
Clustering Louvain::run(Graph& G) {
INFO("starting Louvain method");
// sub-algorithms
ClusterContracter contracter;
ClusteringProjector projector;
// hierarchies
std::vector<std::pair<Graph, NodeMap<node> > > hierarchy; // hierarchy of graphs G^{i} and maps M^{i->i+1}
std::vector<NodeMap<node> > maps; // hierarchy of maps M^{i->i+1}
int h = -1; // finest hierarchy level
bool done = false; //
Graph* graph = &G;
do {
h += 1; // begin new hierarchy level
INFO("Louvain hierarchy level " << h);
// one local optimization pass
DEBUG("starting Louvain pass");
Clustering clustering = this->pass(*graph);
if (this->anyChange){
// contract the graph according to clustering
DEBUG("starting contraction");
hierarchy.push_back(contracter.run(*graph, clustering));
maps.push_back(hierarchy[h].second);
graph = &hierarchy[h].first;
done = false; // new hierarchy level, continue with loop
this->anyChange = false; // reset change flag
} else {
done = true; // if clustering was not modified, do not contract and exit loop
}
} while (! done);
DEBUG("starting projection");
// project fine graph to result clustering
Clustering result = projector.projectCoarseGraphToFinestClustering(*graph, G, maps);
return result;
}
std::string Louvain::toString() const {
std::stringstream strm;
strm << "Louvain";
return strm.str();
}
} /* namespace EnsembleClustering */
<|endoftext|>
|
<commit_before>//
// HUDErrorRenderer.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 9/28/13.
//
//
#ifndef __G3MiOSSDK__HUDErrorRenderer__
#define __G3MiOSSDK__HUDErrorRenderer__
#include "ErrorRenderer.hpp"
#include "HUDImageRenderer.hpp"
#include "ImageFactory.hpp"
class HUDErrorRenderer_ImageFactory : public ImageFactory {
public:
void create(const G3MRenderContext* rc,
int width,
int height,
IImageListener* listener,
bool deleteListener);
};
class HUDErrorRenderer : public HUDImageRenderer, public ErrorRenderer {
public:
HUDErrorRenderer() :
HUDImageRenderer(new HUDErrorRenderer_ImageFactory())
{
}
#ifdef C_CODE
void initialize(const G3MContext* context);
void render(const G3MRenderContext* rc,
GLState* glState);
bool onTouchEvent(const G3MEventContext* ec,
const TouchEvent* touchEvent);
void onResizeViewportEvent(const G3MEventContext* ec,
int width, int height);
void start(const G3MRenderContext* rc);
void stop(const G3MRenderContext* rc);
void onResume(const G3MContext* context);
void onPause(const G3MContext* context);
void onDestroy(const G3MContext* context);
#endif
};
#endif
<commit_msg>new ErrorRenderer mechanism - NOT YET USABLE<commit_after>//
// HUDErrorRenderer.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 9/28/13.
//
//
#ifndef __G3MiOSSDK__HUDErrorRenderer__
#define __G3MiOSSDK__HUDErrorRenderer__
#include "ErrorRenderer.hpp"
#include "HUDImageRenderer.hpp"
#include "ImageFactory.hpp"
class HUDErrorRenderer_ImageFactory : public ImageFactory {
public:
void create(const G3MRenderContext* rc,
int width,
int height,
IImageListener* listener,
bool deleteListener);
~HUDErrorRenderer_ImageFactory() {
}
};
class HUDErrorRenderer : public HUDImageRenderer, public ErrorRenderer {
public:
HUDErrorRenderer() :
HUDImageRenderer(new HUDErrorRenderer_ImageFactory())
{
}
#ifdef C_CODE
void initialize(const G3MContext* context);
void render(const G3MRenderContext* rc,
GLState* glState);
bool onTouchEvent(const G3MEventContext* ec,
const TouchEvent* touchEvent);
void onResizeViewportEvent(const G3MEventContext* ec,
int width, int height);
void start(const G3MRenderContext* rc);
void stop(const G3MRenderContext* rc);
void onResume(const G3MContext* context);
void onPause(const G3MContext* context);
void onDestroy(const G3MContext* context);
#endif
};
#endif
<|endoftext|>
|
<commit_before>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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: Hannes Hauswedell <hauswedell@mi.fu-berlin.de>
// ==========================================================================
// Tests for align_extend
// ==========================================================================
// work around obscure FreeBSD issue
#ifndef _GLIBCXX_USE_C99
#define _GLIBCXX_USE_C99 1
#define _GLIBCXX_USE_C99_UNDEF 1
#endif
#include <string>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "test_blast.h"
SEQAN_BEGIN_TESTSUITE(test_blast)
{
SEQAN_CALL_TEST(test_blast_scoring_scheme_conversion);
SEQAN_CALL_TEST(test_blast_scoring_adapter);
SEQAN_CALL_TEST(test_blast_blastmatch_stats_and_score);
SEQAN_CALL_TEST(test_blast_blastmatch_bit_score_e_value);
SEQAN_CALL_TEST(test_blast_write_tabular);
SEQAN_CALL_TEST(test_blast_write_tabular_with_header);
SEQAN_CALL_TEST(test_blast_write_tabular_with_header_generationblastplus);
SEQAN_CALL_TEST(test_blast_write_tabular_customfields);
SEQAN_CALL_TEST(test_blast_write_tabular_with_header_customfields);
SEQAN_CALL_TEST(test_blast_write_tabular_with_header_customfields_generationblastplus);
SEQAN_CALL_TEST(test_blast_write_pairwise);
}
SEQAN_END_TESTSUITE
#ifdef _GLIBCXX_USE_C99_UNDEF
#undefine _GLIBCXX_USE_C99_UNDEF
#undefine _GLIBCXX_USE_C99
#endif<commit_msg>[FIX] syntax error<commit_after>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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: Hannes Hauswedell <hauswedell@mi.fu-berlin.de>
// ==========================================================================
// Tests for align_extend
// ==========================================================================
// work around obscure FreeBSD issue
#ifndef _GLIBCXX_USE_C99
#define _GLIBCXX_USE_C99 1
#define _GLIBCXX_USE_C99_UNDEF 1
#endif
#include <string>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "test_blast.h"
SEQAN_BEGIN_TESTSUITE(test_blast)
{
SEQAN_CALL_TEST(test_blast_scoring_scheme_conversion);
SEQAN_CALL_TEST(test_blast_scoring_adapter);
SEQAN_CALL_TEST(test_blast_blastmatch_stats_and_score);
SEQAN_CALL_TEST(test_blast_blastmatch_bit_score_e_value);
SEQAN_CALL_TEST(test_blast_write_tabular);
SEQAN_CALL_TEST(test_blast_write_tabular_with_header);
SEQAN_CALL_TEST(test_blast_write_tabular_with_header_generationblastplus);
SEQAN_CALL_TEST(test_blast_write_tabular_customfields);
SEQAN_CALL_TEST(test_blast_write_tabular_with_header_customfields);
SEQAN_CALL_TEST(test_blast_write_tabular_with_header_customfields_generationblastplus);
SEQAN_CALL_TEST(test_blast_write_pairwise);
}
SEQAN_END_TESTSUITE
#ifdef _GLIBCXX_USE_C99_UNDEF
#undef _GLIBCXX_USE_C99_UNDEF
#undef _GLIBCXX_USE_C99
#endif<|endoftext|>
|
<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_ATTRIBUTES_HPP
#define IOX_HOOFS_CXX_ATTRIBUTES_HPP
namespace iox
{
namespace cxx
{
namespace internal
{
/// We use this as an alternative to "static_cast<void>(someVar)" to signal the
/// compiler an unused variable. "static_cast" produces an useless-cast warning
/// on gcc and this approach solves it cleanly.
template <typename T>
inline void IOX_DISCARD_RESULT_IMPL(T&&) noexcept
{
}
} // namespace internal
// NOLINTJUSTIFICATION cannot be implemented with a function, required as inline code
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
/// @brief if a function has a return value which you do not want to use then you can wrap the function with that macro.
/// Purpose is to suppress the unused compiler warning by adding an attribute to the return value
/// @param[in] expr name of the function where the return value is not used.
/// @code
/// uint32_t foo();
/// IOX_DISCARD_RESULT(foo()); // suppress compiler warning for unused return value
/// @endcode
#define IOX_DISCARD_RESULT(expr) ::iox::cxx::internal::IOX_DISCARD_RESULT_IMPL(expr)
/// @brief IOX_NO_DISCARD adds the [[nodiscard]] keyword if it is available for the current compiler.
/// If additionally the keyword [[gnu::warn_unused]] is present it will be added as well.
/// @note
// [[nodiscard]], [[gnu::warn_unused]] supported since gcc 4.8 (https://gcc.gnu.org/projects/cxx-status.html)
/// [[nodiscard]], [[gnu::warn_unused]] supported since clang 3.9 (https://clang.llvm.org/cxx_status.html)
/// activate keywords for gcc>=5 or clang>=4
#if defined(_WIN32)
// On WIN32 we are using C++17 which makes the keyword [[nodiscard]] available
#define IOX_NO_DISCARD [[nodiscard]]
#elif defined(__APPLE__) && defined(__clang__)
// On APPLE we are using C++17 which makes the keyword [[nodiscard]] available
#define IOX_NO_DISCARD [[nodiscard, gnu::warn_unused]]
#elif (defined(__clang__) && __clang_major__ >= 4)
#define IOX_NO_DISCARD [[gnu::warn_unused]]
#elif (defined(__GNUC__) && __GNUC__ >= 5)
#define IOX_NO_DISCARD [[nodiscard, gnu::warn_unused]]
#else
// on an unknown platform we use for now nothing since we do not know what is supported there
#define IOX_NO_DISCARD
#endif
/// @brief IOX_FALLTHROUGH adds the [[fallthrough]] keyword when it is available for the current compiler.
/// @note
// [[fallthrough]] supported since gcc 7 (https://gcc.gnu.org/projects/cxx-status.html)
/// [[fallthrough]] supported since clang 3.9 (https://clang.llvm.org/cxx_status.html)
/// activate keywords for gcc>=7 or clang>=4
#if defined(_WIN32)
// On WIN32 we are using C++17 which makes the keyword [[fallthrough]] available
#define IOX_FALLTHROUGH [[fallthrough]]
#elif defined(__APPLE__) && defined(__clang__)
// On APPLE we are using C++17 which makes the keyword [[fallthrough]] available
#define IOX_FALLTHROUGH [[fallthrough]]
// with C++17 fallthrough was introduced and we can use it
#elif __cplusplus >= 201703L
// clang prints a warning therefore we exclude it here
#define IOX_FALLTHROUGH [[fallthrough]]
#elif (defined(__GNUC__) && __GNUC__ >= 7) && !defined(__clang__)
#define IOX_FALLTHROUGH [[gnu::fallthrough]]
#else
// on an unknown platform we use for now nothing since we do not know what is supported there
#define IOX_FALLTHROUGH
#endif
/// @brief IOX_MAYBE_UNUSED adds the [[gnu::unused]] or [[maybe_unused]] attribute when it is available for the current
/// compiler.
/// @note
/// activate attribute for gcc or clang
#if defined(__GNUC__) || defined(__clang__)
#define IOX_MAYBE_UNUSED [[gnu::unused]]
#elif defined(_WIN32)
// On WIN32 we are using C++17 which makes the attribute [[maybe_unused]] available
#define IOX_MAYBE_UNUSED [[maybe_unused]]
// on an unknown platform we use for now nothing since we do not know what is supported there
#else
#define IOX_MAYBE_UNUSED
#endif
// NOLINTEND(cppcoreguidelines-macro-usage)
} // namespace cxx
} // namespace iox
#endif
<commit_msg>iox-#1394-fix-axivion-violation-for-attributes_hpp<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_ATTRIBUTES_HPP
#define IOX_HOOFS_CXX_ATTRIBUTES_HPP
namespace iox
{
namespace cxx
{
namespace internal
{
/// We use this as an alternative to "static_cast<void>(someVar)" to signal the
/// compiler an unused variable. "static_cast" produces an useless-cast warning
/// on gcc and this approach solves it cleanly.
template <typename T>
inline void IOX_DISCARD_RESULT_IMPL(T&&) noexcept
{
}
} // namespace internal
// NOLINTJUSTIFICATION cannot be implemented with a function, required as inline code
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
/// @brief if a function has a return value which you do not want to use then you can wrap the function with that macro.
/// Purpose is to suppress the unused compiler warning by adding an attribute to the return value
/// @param[in] expr name of the function where the return value is not used.
/// @code
/// uint32_t foo();
/// IOX_DISCARD_RESULT(foo()); // suppress compiler warning for unused return value
/// @endcode
#define IOX_DISCARD_RESULT(expr) ::iox::cxx::internal::IOX_DISCARD_RESULT_IMPL(expr)
/// @brief IOX_NO_DISCARD adds the [[nodiscard]] keyword if it is available for the current compiler.
/// If additionally the keyword [[gnu::warn_unused]] is present it will be added as well.
/// @note
// [[nodiscard]], [[gnu::warn_unused]] supported since gcc 4.8 (https://gcc.gnu.org/projects/cxx-status.html)
/// [[nodiscard]], [[gnu::warn_unused]] supported since clang 3.9 (https://clang.llvm.org/cxx_status.html)
/// activate keywords for gcc>=5 or clang>=4
#if defined(_WIN32)
// On WIN32 we are using C++17 which makes the keyword [[nodiscard]] available
#define IOX_NO_DISCARD [[nodiscard]]
#elif defined(__APPLE__) && defined(__clang__)
// On APPLE we are using C++17 which makes the keyword [[nodiscard]] available
#define IOX_NO_DISCARD [[nodiscard, gnu::warn_unused]]
#elif (defined(__clang__) && (__clang_major__ >= 4))
#define IOX_NO_DISCARD [[gnu::warn_unused]]
#elif (defined(__GNUC__) && (__GNUC__ >= 5))
#define IOX_NO_DISCARD [[nodiscard, gnu::warn_unused]]
#else
// on an unknown platform we use for now nothing since we do not know what is supported there
#define IOX_NO_DISCARD
#endif
/// @brief IOX_FALLTHROUGH adds the [[fallthrough]] keyword when it is available for the current compiler.
/// @note
// [[fallthrough]] supported since gcc 7 (https://gcc.gnu.org/projects/cxx-status.html)
/// [[fallthrough]] supported since clang 3.9 (https://clang.llvm.org/cxx_status.html)
/// activate keywords for gcc>=7 or clang>=4
#if defined(_WIN32)
// On WIN32 we are using C++17 which makes the keyword [[fallthrough]] available
#define IOX_FALLTHROUGH [[fallthrough]]
#elif defined(__APPLE__) && defined(__clang__)
// On APPLE we are using C++17 which makes the keyword [[fallthrough]] available
#define IOX_FALLTHROUGH [[fallthrough]]
// with C++17 fallthrough was introduced and we can use it
#elif __cplusplus >= 201703L
// clang prints a warning therefore we exclude it here
#define IOX_FALLTHROUGH [[fallthrough]]
#elif (defined(__GNUC__) && (__GNUC__ >= 7)) && !defined(__clang__)
#define IOX_FALLTHROUGH [[gnu::fallthrough]]
#else
// on an unknown platform we use for now nothing since we do not know what is supported there
#define IOX_FALLTHROUGH
#endif
/// @brief IOX_MAYBE_UNUSED adds the [[gnu::unused]] or [[maybe_unused]] attribute when it is available for the current
/// compiler.
/// @note
/// activate attribute for gcc or clang
#if defined(__GNUC__) || defined(__clang__)
#define IOX_MAYBE_UNUSED [[gnu::unused]]
#elif defined(_WIN32)
// On WIN32 we are using C++17 which makes the attribute [[maybe_unused]] available
#define IOX_MAYBE_UNUSED [[maybe_unused]]
// on an unknown platform we use for now nothing since we do not know what is supported there
#else
#define IOX_MAYBE_UNUSED
#endif
// NOLINTEND(cppcoreguidelines-macro-usage)
} // namespace cxx
} // namespace iox
#endif
<|endoftext|>
|
<commit_before>//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/CodeGen/BackendUtil.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/PassManagerBuilder.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Transforms/Instrumentation.h"
using namespace clang;
using namespace llvm;
namespace {
class EmitAssemblyHelper {
Diagnostic &Diags;
const CodeGenOptions &CodeGenOpts;
const TargetOptions &TargetOpts;
Module *TheModule;
Timer CodeGenerationTime;
mutable PassManager *CodeGenPasses;
mutable PassManager *PerModulePasses;
mutable FunctionPassManager *PerFunctionPasses;
private:
PassManager *getCodeGenPasses() const {
if (!CodeGenPasses) {
CodeGenPasses = new PassManager();
CodeGenPasses->add(new TargetData(TheModule));
}
return CodeGenPasses;
}
PassManager *getPerModulePasses() const {
if (!PerModulePasses) {
PerModulePasses = new PassManager();
PerModulePasses->add(new TargetData(TheModule));
}
return PerModulePasses;
}
FunctionPassManager *getPerFunctionPasses() const {
if (!PerFunctionPasses) {
PerFunctionPasses = new FunctionPassManager(TheModule);
PerFunctionPasses->add(new TargetData(TheModule));
}
return PerFunctionPasses;
}
void CreatePasses();
/// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
///
/// \return True on success.
bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
public:
EmitAssemblyHelper(Diagnostic &_Diags,
const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
Module *M)
: Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts),
TheModule(M), CodeGenerationTime("Code Generation Time"),
CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
~EmitAssemblyHelper() {
delete CodeGenPasses;
delete PerModulePasses;
delete PerFunctionPasses;
}
void EmitAssembly(BackendAction Action, raw_ostream *OS);
};
}
void EmitAssemblyHelper::CreatePasses() {
unsigned OptLevel = CodeGenOpts.OptimizationLevel;
CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
// Handle disabling of LLVM optimization, where we want to preserve the
// internal module before any optimization.
if (CodeGenOpts.DisableLLVMOpts) {
OptLevel = 0;
Inlining = CodeGenOpts.NoInlining;
}
PassManagerBuilder PMBuilder;
PMBuilder.setOptimizationLevel(OptLevel);
PMBuilder.setSizeLevel(CodeGenOpts.OptimizeSize);
if (!CodeGenOpts.SimplifyLibCalls) PMBuilder.disableSimplifyLibCalls();
if (!CodeGenOpts.UnitAtATime) PMBuilder.disableUnitAtATime();
if (!CodeGenOpts.UnrollLoops) PMBuilder.disableUnrollLoops();
// Figure out TargetLibraryInfo.
Triple TargetTriple(TheModule->getTargetTriple());
TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
if (!CodeGenOpts.SimplifyLibCalls)
TLI->disableAllFunctions();
PMBuilder.setLibraryInfo(TLI);
switch (Inlining) {
case CodeGenOptions::NoInlining: break;
case CodeGenOptions::NormalInlining: {
// FIXME: Derive these constants in a principled fashion.
unsigned Threshold = 225;
if (CodeGenOpts.OptimizeSize == 1) // -Os
Threshold = 75;
else if (CodeGenOpts.OptimizeSize == 2) // -Oz
Threshold = 25;
else if (OptLevel > 2)
Threshold = 275;
PMBuilder.setInliner(createFunctionInliningPass(Threshold));
break;
}
case CodeGenOptions::OnlyAlwaysInlining:
// Respect always_inline.
PMBuilder.setInliner(createAlwaysInlinerPass());
break;
}
// Set up the per-function pass manager.
FunctionPassManager *FPM = getPerFunctionPasses();
if (CodeGenOpts.VerifyModule)
FPM->add(createVerifierPass());
PMBuilder.populateFunctionPassManager(*FPM);
// Set up the per-module pass manager.
PassManager *MPM = getPerModulePasses();
if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
CodeGenOpts.EmitGcovArcs,
TargetTriple.isMacOSX()));
if (!CodeGenOpts.DebugInfo)
MPM->add(createStripSymbolsPass(true));
}
PMBuilder.populateModulePassManager(*MPM);
}
bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
formatted_raw_ostream &OS) {
// Create the TargetMachine for generating code.
std::string Error;
std::string Triple = TheModule->getTargetTriple();
const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
if (!TheTarget) {
Diags.Report(diag::err_fe_unable_to_create_target) << Error;
return false;
}
// FIXME: Expose these capabilities via actual APIs!!!! Aside from just
// being gross, this is also totally broken if we ever care about
// concurrency.
// Set frame pointer elimination mode.
if (!CodeGenOpts.DisableFPElim) {
llvm::NoFramePointerElim = false;
llvm::NoFramePointerElimNonLeaf = false;
} else if (CodeGenOpts.OmitLeafFramePointer) {
llvm::NoFramePointerElim = false;
llvm::NoFramePointerElimNonLeaf = true;
} else {
llvm::NoFramePointerElim = true;
llvm::NoFramePointerElimNonLeaf = true;
}
// Set float ABI type.
if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
llvm::FloatABIType = llvm::FloatABI::Soft;
else if (CodeGenOpts.FloatABI == "hard")
llvm::FloatABIType = llvm::FloatABI::Hard;
else {
assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
llvm::FloatABIType = llvm::FloatABI::Default;
}
llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
UnwindTablesMandatory = CodeGenOpts.UnwindTables;
TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
TargetMachine::setDataSections (CodeGenOpts.DataSections);
// FIXME: Parse this earlier.
if (CodeGenOpts.RelocationModel == "static") {
TargetMachine::setRelocationModel(llvm::Reloc::Static);
} else if (CodeGenOpts.RelocationModel == "pic") {
TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
} else {
assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
"Invalid PIC model!");
TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
}
// FIXME: Parse this earlier.
if (CodeGenOpts.CodeModel == "small") {
TargetMachine::setCodeModel(llvm::CodeModel::Small);
} else if (CodeGenOpts.CodeModel == "kernel") {
TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
} else if (CodeGenOpts.CodeModel == "medium") {
TargetMachine::setCodeModel(llvm::CodeModel::Medium);
} else if (CodeGenOpts.CodeModel == "large") {
TargetMachine::setCodeModel(llvm::CodeModel::Large);
} else {
assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
TargetMachine::setCodeModel(llvm::CodeModel::Default);
}
std::vector<const char *> BackendArgs;
BackendArgs.push_back("clang"); // Fake program name.
if (!CodeGenOpts.DebugPass.empty()) {
BackendArgs.push_back("-debug-pass");
BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
}
if (!CodeGenOpts.LimitFloatPrecision.empty()) {
BackendArgs.push_back("-limit-float-precision");
BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
}
if (llvm::TimePassesIsEnabled)
BackendArgs.push_back("-time-passes");
for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
BackendArgs.push_back(0);
llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
const_cast<char **>(&BackendArgs[0]));
std::string FeaturesStr;
if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
SubtargetFeatures Features;
Features.setCPU(TargetOpts.CPU);
for (std::vector<std::string>::const_iterator
it = TargetOpts.Features.begin(),
ie = TargetOpts.Features.end(); it != ie; ++it)
Features.AddFeature(*it);
FeaturesStr = Features.getString();
}
TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
if (CodeGenOpts.RelaxAll)
TM->setMCRelaxAll(true);
if (CodeGenOpts.SaveTempLabels)
TM->setMCSaveTempLabels(true);
if (CodeGenOpts.NoDwarf2CFIAsm)
TM->setMCUseCFI(false);
// Create the code generator passes.
PassManager *PM = getCodeGenPasses();
CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
switch (CodeGenOpts.OptimizationLevel) {
default: break;
case 0: OptLevel = CodeGenOpt::None; break;
case 3: OptLevel = CodeGenOpt::Aggressive; break;
}
// Normal mode, emit a .s or .o file by running the code generator. Note,
// this also adds codegenerator level optimization passes.
TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
if (Action == Backend_EmitObj)
CGFT = TargetMachine::CGFT_ObjectFile;
else if (Action == Backend_EmitMCNull)
CGFT = TargetMachine::CGFT_Null;
else
assert(Action == Backend_EmitAssembly && "Invalid action!");
if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
/*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
Diags.Report(diag::err_fe_unable_to_interface_with_target);
return false;
}
return true;
}
void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
llvm::formatted_raw_ostream FormattedOS;
CreatePasses();
switch (Action) {
case Backend_EmitNothing:
break;
case Backend_EmitBC:
getPerModulePasses()->add(createBitcodeWriterPass(*OS));
break;
case Backend_EmitLL:
FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
break;
default:
FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
if (!AddEmitPasses(Action, FormattedOS))
return;
}
// Before executing passes, print the final values of the LLVM options.
cl::PrintOptionValues();
// Run passes. For now we do all passes at once, but eventually we
// would like to have the option of streaming code generation.
if (PerFunctionPasses) {
PrettyStackTraceString CrashInfo("Per-function optimization");
PerFunctionPasses->doInitialization();
for (Module::iterator I = TheModule->begin(),
E = TheModule->end(); I != E; ++I)
if (!I->isDeclaration())
PerFunctionPasses->run(*I);
PerFunctionPasses->doFinalization();
}
if (PerModulePasses) {
PrettyStackTraceString CrashInfo("Per-module optimization passes");
PerModulePasses->run(*TheModule);
}
if (CodeGenPasses) {
PrettyStackTraceString CrashInfo("Code generation");
CodeGenPasses->run(*TheModule);
}
}
void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
const TargetOptions &TOpts, Module *M,
BackendAction Action, raw_ostream *OS) {
EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M);
AsmHelper.EmitAssembly(Action, OS);
}
<commit_msg>adjust to mainline api change.<commit_after>//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/CodeGen/BackendUtil.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/PassManagerBuilder.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Transforms/Instrumentation.h"
using namespace clang;
using namespace llvm;
namespace {
class EmitAssemblyHelper {
Diagnostic &Diags;
const CodeGenOptions &CodeGenOpts;
const TargetOptions &TargetOpts;
Module *TheModule;
Timer CodeGenerationTime;
mutable PassManager *CodeGenPasses;
mutable PassManager *PerModulePasses;
mutable FunctionPassManager *PerFunctionPasses;
private:
PassManager *getCodeGenPasses() const {
if (!CodeGenPasses) {
CodeGenPasses = new PassManager();
CodeGenPasses->add(new TargetData(TheModule));
}
return CodeGenPasses;
}
PassManager *getPerModulePasses() const {
if (!PerModulePasses) {
PerModulePasses = new PassManager();
PerModulePasses->add(new TargetData(TheModule));
}
return PerModulePasses;
}
FunctionPassManager *getPerFunctionPasses() const {
if (!PerFunctionPasses) {
PerFunctionPasses = new FunctionPassManager(TheModule);
PerFunctionPasses->add(new TargetData(TheModule));
}
return PerFunctionPasses;
}
void CreatePasses();
/// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
///
/// \return True on success.
bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
public:
EmitAssemblyHelper(Diagnostic &_Diags,
const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
Module *M)
: Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts),
TheModule(M), CodeGenerationTime("Code Generation Time"),
CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
~EmitAssemblyHelper() {
delete CodeGenPasses;
delete PerModulePasses;
delete PerFunctionPasses;
}
void EmitAssembly(BackendAction Action, raw_ostream *OS);
};
}
void EmitAssemblyHelper::CreatePasses() {
unsigned OptLevel = CodeGenOpts.OptimizationLevel;
CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
// Handle disabling of LLVM optimization, where we want to preserve the
// internal module before any optimization.
if (CodeGenOpts.DisableLLVMOpts) {
OptLevel = 0;
Inlining = CodeGenOpts.NoInlining;
}
PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = OptLevel;
PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
// Figure out TargetLibraryInfo.
Triple TargetTriple(TheModule->getTargetTriple());
PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
if (!CodeGenOpts.SimplifyLibCalls)
PMBuilder.LibraryInfo->disableAllFunctions();
switch (Inlining) {
case CodeGenOptions::NoInlining: break;
case CodeGenOptions::NormalInlining: {
// FIXME: Derive these constants in a principled fashion.
unsigned Threshold = 225;
if (CodeGenOpts.OptimizeSize == 1) // -Os
Threshold = 75;
else if (CodeGenOpts.OptimizeSize == 2) // -Oz
Threshold = 25;
else if (OptLevel > 2)
Threshold = 275;
PMBuilder.Inliner = createFunctionInliningPass(Threshold);
break;
}
case CodeGenOptions::OnlyAlwaysInlining:
// Respect always_inline.
PMBuilder.Inliner = createAlwaysInlinerPass();
break;
}
// Set up the per-function pass manager.
FunctionPassManager *FPM = getPerFunctionPasses();
if (CodeGenOpts.VerifyModule)
FPM->add(createVerifierPass());
PMBuilder.populateFunctionPassManager(*FPM);
// Set up the per-module pass manager.
PassManager *MPM = getPerModulePasses();
if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
CodeGenOpts.EmitGcovArcs,
TargetTriple.isMacOSX()));
if (!CodeGenOpts.DebugInfo)
MPM->add(createStripSymbolsPass(true));
}
PMBuilder.populateModulePassManager(*MPM);
}
bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
formatted_raw_ostream &OS) {
// Create the TargetMachine for generating code.
std::string Error;
std::string Triple = TheModule->getTargetTriple();
const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
if (!TheTarget) {
Diags.Report(diag::err_fe_unable_to_create_target) << Error;
return false;
}
// FIXME: Expose these capabilities via actual APIs!!!! Aside from just
// being gross, this is also totally broken if we ever care about
// concurrency.
// Set frame pointer elimination mode.
if (!CodeGenOpts.DisableFPElim) {
llvm::NoFramePointerElim = false;
llvm::NoFramePointerElimNonLeaf = false;
} else if (CodeGenOpts.OmitLeafFramePointer) {
llvm::NoFramePointerElim = false;
llvm::NoFramePointerElimNonLeaf = true;
} else {
llvm::NoFramePointerElim = true;
llvm::NoFramePointerElimNonLeaf = true;
}
// Set float ABI type.
if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
llvm::FloatABIType = llvm::FloatABI::Soft;
else if (CodeGenOpts.FloatABI == "hard")
llvm::FloatABIType = llvm::FloatABI::Hard;
else {
assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
llvm::FloatABIType = llvm::FloatABI::Default;
}
llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
UnwindTablesMandatory = CodeGenOpts.UnwindTables;
TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
TargetMachine::setDataSections (CodeGenOpts.DataSections);
// FIXME: Parse this earlier.
if (CodeGenOpts.RelocationModel == "static") {
TargetMachine::setRelocationModel(llvm::Reloc::Static);
} else if (CodeGenOpts.RelocationModel == "pic") {
TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
} else {
assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
"Invalid PIC model!");
TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
}
// FIXME: Parse this earlier.
if (CodeGenOpts.CodeModel == "small") {
TargetMachine::setCodeModel(llvm::CodeModel::Small);
} else if (CodeGenOpts.CodeModel == "kernel") {
TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
} else if (CodeGenOpts.CodeModel == "medium") {
TargetMachine::setCodeModel(llvm::CodeModel::Medium);
} else if (CodeGenOpts.CodeModel == "large") {
TargetMachine::setCodeModel(llvm::CodeModel::Large);
} else {
assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
TargetMachine::setCodeModel(llvm::CodeModel::Default);
}
std::vector<const char *> BackendArgs;
BackendArgs.push_back("clang"); // Fake program name.
if (!CodeGenOpts.DebugPass.empty()) {
BackendArgs.push_back("-debug-pass");
BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
}
if (!CodeGenOpts.LimitFloatPrecision.empty()) {
BackendArgs.push_back("-limit-float-precision");
BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
}
if (llvm::TimePassesIsEnabled)
BackendArgs.push_back("-time-passes");
for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
BackendArgs.push_back(0);
llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
const_cast<char **>(&BackendArgs[0]));
std::string FeaturesStr;
if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
SubtargetFeatures Features;
Features.setCPU(TargetOpts.CPU);
for (std::vector<std::string>::const_iterator
it = TargetOpts.Features.begin(),
ie = TargetOpts.Features.end(); it != ie; ++it)
Features.AddFeature(*it);
FeaturesStr = Features.getString();
}
TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
if (CodeGenOpts.RelaxAll)
TM->setMCRelaxAll(true);
if (CodeGenOpts.SaveTempLabels)
TM->setMCSaveTempLabels(true);
if (CodeGenOpts.NoDwarf2CFIAsm)
TM->setMCUseCFI(false);
// Create the code generator passes.
PassManager *PM = getCodeGenPasses();
CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
switch (CodeGenOpts.OptimizationLevel) {
default: break;
case 0: OptLevel = CodeGenOpt::None; break;
case 3: OptLevel = CodeGenOpt::Aggressive; break;
}
// Normal mode, emit a .s or .o file by running the code generator. Note,
// this also adds codegenerator level optimization passes.
TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
if (Action == Backend_EmitObj)
CGFT = TargetMachine::CGFT_ObjectFile;
else if (Action == Backend_EmitMCNull)
CGFT = TargetMachine::CGFT_Null;
else
assert(Action == Backend_EmitAssembly && "Invalid action!");
if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
/*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
Diags.Report(diag::err_fe_unable_to_interface_with_target);
return false;
}
return true;
}
void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
llvm::formatted_raw_ostream FormattedOS;
CreatePasses();
switch (Action) {
case Backend_EmitNothing:
break;
case Backend_EmitBC:
getPerModulePasses()->add(createBitcodeWriterPass(*OS));
break;
case Backend_EmitLL:
FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
break;
default:
FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
if (!AddEmitPasses(Action, FormattedOS))
return;
}
// Before executing passes, print the final values of the LLVM options.
cl::PrintOptionValues();
// Run passes. For now we do all passes at once, but eventually we
// would like to have the option of streaming code generation.
if (PerFunctionPasses) {
PrettyStackTraceString CrashInfo("Per-function optimization");
PerFunctionPasses->doInitialization();
for (Module::iterator I = TheModule->begin(),
E = TheModule->end(); I != E; ++I)
if (!I->isDeclaration())
PerFunctionPasses->run(*I);
PerFunctionPasses->doFinalization();
}
if (PerModulePasses) {
PrettyStackTraceString CrashInfo("Per-module optimization passes");
PerModulePasses->run(*TheModule);
}
if (CodeGenPasses) {
PrettyStackTraceString CrashInfo("Code generation");
CodeGenPasses->run(*TheModule);
}
}
void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
const TargetOptions &TOpts, Module *M,
BackendAction Action, raw_ostream *OS) {
EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M);
AsmHelper.EmitAssembly(Action, OS);
}
<|endoftext|>
|
<commit_before>//===--- CodeGenTypes.cpp - TBAA information for LLVM CodeGen -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the code that manages TBAA information.
//
//===----------------------------------------------------------------------===//
#include "CodeGenTBAA.h"
#include "clang/AST/ASTContext.h"
#include "llvm/LLVMContext.h"
#include "llvm/Metadata.h"
using namespace clang;
using namespace CodeGen;
CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext& VMContext,
const LangOptions &Features)
: Context(Ctx), VMContext(VMContext), Features(Features), Root(0), Char(0) {
}
CodeGenTBAA::~CodeGenTBAA() {
}
llvm::MDNode *CodeGenTBAA::getTBAAInfoForNamedType(const char *NameStr,
llvm::MDNode *Parent) {
llvm::Value *Ops[] = {
llvm::MDString::get(VMContext, NameStr),
Parent
};
return llvm::MDNode::get(VMContext, Ops, llvm::array_lengthof(Ops));
}
llvm::MDNode *
CodeGenTBAA::getTBAAInfo(QualType QTy) {
Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
if (llvm::MDNode *N = MetadataCache[Ty])
return N;
if (!Root) {
Root = getTBAAInfoForNamedType("Experimental TBAA", 0);
Char = getTBAAInfoForNamedType("omnipotent char", Root);
}
// For now, just emit a very minimal tree.
const Type *CanonicalTy = Context.getCanonicalType(Ty);
if (const BuiltinType *BTy = dyn_cast<BuiltinType>(CanonicalTy)) {
switch (BTy->getKind()) {
case BuiltinType::Char_U:
case BuiltinType::Char_S:
case BuiltinType::UChar:
case BuiltinType::SChar:
// Charactar types are special.
return Char;
default:
return MetadataCache[Ty] =
getTBAAInfoForNamedType(BTy->getName(Features), Char);
}
}
return MetadataCache[Ty] = getTBAAInfoForNamedType("TBAA.other", Char);
}
<commit_msg>Unsigned types are TBAA-compatible with their signed counterparts. Also, handle unknown types conservatively.<commit_after>//===--- CodeGenTypes.cpp - TBAA information for LLVM CodeGen -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the code that manages TBAA information.
//
//===----------------------------------------------------------------------===//
#include "CodeGenTBAA.h"
#include "clang/AST/ASTContext.h"
#include "llvm/LLVMContext.h"
#include "llvm/Metadata.h"
using namespace clang;
using namespace CodeGen;
CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext& VMContext,
const LangOptions &Features)
: Context(Ctx), VMContext(VMContext), Features(Features), Root(0), Char(0) {
}
CodeGenTBAA::~CodeGenTBAA() {
}
llvm::MDNode *CodeGenTBAA::getTBAAInfoForNamedType(const char *NameStr,
llvm::MDNode *Parent) {
llvm::Value *Ops[] = {
llvm::MDString::get(VMContext, NameStr),
Parent
};
return llvm::MDNode::get(VMContext, Ops, llvm::array_lengthof(Ops));
}
llvm::MDNode *
CodeGenTBAA::getTBAAInfo(QualType QTy) {
Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
if (llvm::MDNode *N = MetadataCache[Ty])
return N;
if (!Root) {
Root = getTBAAInfoForNamedType("Experimental TBAA", 0);
Char = getTBAAInfoForNamedType("omnipotent char", Root);
}
// For now, just emit a very minimal tree.
if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
switch (BTy->getKind()) {
// Charactar types are special and can alias anything.
case BuiltinType::Char_U:
case BuiltinType::Char_S:
case BuiltinType::UChar:
case BuiltinType::SChar:
return Char;
// Unsigned types can alias their corresponding signed types.
case BuiltinType::UShort:
return getTBAAInfo(Context.ShortTy);
case BuiltinType::UInt:
return getTBAAInfo(Context.IntTy);
case BuiltinType::ULong:
return getTBAAInfo(Context.LongTy);
case BuiltinType::ULongLong:
return getTBAAInfo(Context.LongLongTy);
case BuiltinType::UInt128:
return getTBAAInfo(Context.Int128Ty);
// Other builtin types.
default:
return MetadataCache[Ty] =
getTBAAInfoForNamedType(BTy->getName(Features), Char);
}
}
// For now, handle any other kind of type conservatively.
return MetadataCache[Ty] = Char;
}
<|endoftext|>
|
<commit_before>//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Bill Wendling and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs loop invariant code motion on machine instructions. We
// attempt to remove as much code from the body of a loop as possible.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "machine-licm"
#include "llvm/ADT/IndexedMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
namespace {
// Hidden options to help debugging
cl::opt<bool>
PerformLICM("machine-licm",
cl::init(false), cl::Hidden,
cl::desc("Perform loop-invariant code motion on machine code"));
}
STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
namespace {
class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
const TargetInstrInfo *TII;
MachineFunction *CurMF; // Current MachineFunction
// Various analyses that we use...
MachineLoopInfo *LI; // Current MachineLoopInfo
MachineDominatorTree *DT; // Machine dominator tree for the current Loop
// State that is updated as we process loops
bool Changed; // True if a loop is changed.
MachineLoop *CurLoop; // The current loop we are working on.
// Map the def of a virtual register to the machine instruction.
IndexedMap<const MachineInstr*, VirtReg2IndexFunctor> VRegDefs;
public:
static char ID; // Pass identification, replacement for typeid
MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
virtual bool runOnMachineFunction(MachineFunction &MF);
/// FIXME: Loop preheaders?
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineLoopInfo>();
AU.addRequired<MachineDominatorTree>();
}
private:
/// VisitAllLoops - Visit all of the loops in depth first order and try to
/// hoist invariant instructions from them.
///
void VisitAllLoops(MachineLoop *L) {
const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
for (MachineLoop::iterator
I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
MachineLoop *ML = *I;
// Traverse the body of the loop in depth first order on the dominator
// tree so that we are guaranteed to see definitions before we see uses.
VisitAllLoops(ML);
HoistRegion(DT->getNode(ML->getHeader()));
}
HoistRegion(DT->getNode(L->getHeader()));
}
/// MapVirtualRegisterDefs - Create a map of which machine instruction
/// defines a virtual register.
///
void MapVirtualRegisterDefs();
/// IsInSubLoop - A little predicate that returns true if the specified
/// basic block is in a subloop of the current one, not the current one
/// itself.
///
bool IsInSubLoop(MachineBasicBlock *BB) {
assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
return LI->getLoopFor(BB) != CurLoop;
}
/// CanHoistInst - Checks that this instructions is one that can be hoisted
/// out of the loop. I.e., it has no side effects, isn't a control flow
/// instr, etc.
///
bool CanHoistInst(MachineInstr &I) const {
#ifndef NDEBUG
DEBUG({
DOUT << "--- Checking if we can hoist " << I << "\n";
if (I.getInstrDescriptor()->ImplicitUses)
DOUT << " * Instruction has implicit uses.\n";
else if (!TII->isTriviallyReMaterializable(&I))
DOUT << " * Instruction has side effects.\n";
});
#endif
// Don't hoist if this instruction implicitly reads physical registers.
if (I.getInstrDescriptor()->ImplicitUses) return false;
return TII->isTriviallyReMaterializable(&I);
}
/// IsLoopInvariantInst - Returns true if the instruction is loop
/// invariant. I.e., all virtual register operands are defined outside of
/// the loop, physical registers aren't accessed (explicitly or implicitly),
/// and the instruction is hoistable.
///
bool IsLoopInvariantInst(MachineInstr &I);
/// FindPredecessors - Get all of the predecessors of the loop that are not
/// back-edges.
///
void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
const MachineBasicBlock *Header = CurLoop->getHeader();
for (MachineBasicBlock::const_pred_iterator
I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
if (!CurLoop->contains(*I))
Preds.push_back(*I);
}
/// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
/// the predecessor basic block (but before the terminator instructions).
///
void MoveInstToEndOfBlock(MachineBasicBlock *MBB, MachineInstr *MI) {
DEBUG({
DOUT << "Hoisting " << *MI;
if (MBB->getBasicBlock())
DOUT << " to MachineBasicBlock "
<< MBB->getBasicBlock()->getName();
DOUT << "\n";
});
MachineBasicBlock::iterator Iter = MBB->getFirstTerminator();
MBB->insert(Iter, MI);
++NumHoisted;
}
/// HoistRegion - Walk the specified region of the CFG (defined by all
/// blocks dominated by the specified block, and that are in the current
/// loop) in depth first order w.r.t the DominatorTree. This allows us to
/// visit definitions before uses, allowing us to hoist a loop body in one
/// pass without iteration.
///
void HoistRegion(MachineDomTreeNode *N);
/// Hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void Hoist(MachineInstr &MI);
};
char MachineLICM::ID = 0;
RegisterPass<MachineLICM> X("machine-licm",
"Machine Loop Invariant Code Motion");
} // end anonymous namespace
FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
/// Hoist expressions out of the specified loop. Note, alias info for inner loop
/// is not preserved so it is not a good idea to run LICM multiple times on one
/// loop.
///
bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
if (!PerformLICM) return false; // For debugging.
DOUT << "******** Machine LICM ********\n";
Changed = false;
CurMF = &MF;
TII = CurMF->getTarget().getInstrInfo();
// Get our Loop information...
LI = &getAnalysis<MachineLoopInfo>();
DT = &getAnalysis<MachineDominatorTree>();
MapVirtualRegisterDefs();
for (MachineLoopInfo::iterator
I = LI->begin(), E = LI->end(); I != E; ++I) {
CurLoop = *I;
// Visit all of the instructions of the loop. We want to visit the subloops
// first, though, so that we can hoist their invariants first into their
// containing loop before we process that loop.
VisitAllLoops(CurLoop);
}
return Changed;
}
/// MapVirtualRegisterDefs - Create a map of which machine instruction defines a
/// virtual register.
///
void MachineLICM::MapVirtualRegisterDefs() {
for (MachineFunction::const_iterator
I = CurMF->begin(), E = CurMF->end(); I != E; ++I) {
const MachineBasicBlock &MBB = *I;
for (MachineBasicBlock::const_iterator
II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
const MachineInstr &MI = *II;
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI.getOperand(i);
if (MO.isRegister() && MO.isDef() &&
MRegisterInfo::isVirtualRegister(MO.getReg())) {
VRegDefs.grow(MO.getReg());
VRegDefs[MO.getReg()] = &MI;
}
}
}
}
}
/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
/// dominated by the specified block, and that are in the current loop) in depth
/// first order w.r.t the DominatorTree. This allows us to visit definitions
/// before uses, allowing us to hoist a loop body in one pass without iteration.
///
void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
assert(N != 0 && "Null dominator tree node?");
MachineBasicBlock *BB = N->getBlock();
// If this subregion is not in the top level loop at all, exit.
if (!CurLoop->contains(BB)) return;
// Only need to process the contents of this block if it is not part of a
// subloop (which would already have been processed).
if (!IsInSubLoop(BB))
for (MachineBasicBlock::iterator
I = BB->begin(), E = BB->end(); I != E; ) {
MachineInstr &MI = *I++;
// Try hoisting the instruction out of the loop. We can only do this if
// all of the operands of the instruction are loop invariant and if it is
// safe to hoist the instruction.
Hoist(MI);
}
const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
for (unsigned I = 0, E = Children.size(); I != E; ++I)
HoistRegion(Children[I]);
}
/// IsLoopInvariantInst - Returns true if the instruction is loop
/// invariant. I.e., all virtual register operands are defined outside of the
/// loop, physical registers aren't accessed (explicitly or implicitly), and the
/// instruction is hoistable.
///
bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
if (!CanHoistInst(I)) return false;
// The instruction is loop invariant if all of its operands are loop-invariant
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = I.getOperand(i);
if (!MO.isRegister() || !MO.isUse())
continue;
unsigned Reg = MO.getReg();
// Don't hoist instructions that access physical registers.
if (!MRegisterInfo::isVirtualRegister(Reg))
return false;
assert(VRegDefs[Reg] && "Machine instr not mapped for this vreg?");
// If the loop contains the definition of an operand, then the instruction
// isn't loop invariant.
if (CurLoop->contains(VRegDefs[Reg]->getParent()))
return false;
}
// If we got this far, the instruction is loop invariant!
return true;
}
/// Hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void MachineLICM::Hoist(MachineInstr &MI) {
if (!IsLoopInvariantInst(MI)) return;
std::vector<MachineBasicBlock*> Preds;
// Non-back-edge predecessors.
FindPredecessors(Preds);
// Either we don't have any predecessors(?!) or we have more than one, which
// is forbidden.
if (Preds.empty() || Preds.size() != 1) return;
// Check that the predecessor is qualified to take the hoisted
// instruction. I.e., there is only one edge from the predecessor, and it's to
// the loop header.
MachineBasicBlock *MBB = Preds.front();
// FIXME: We are assuming at first that the basic block coming into this loop
// has only one successor. This isn't the case in general because we haven't
// broken critical edges or added preheaders.
if (MBB->succ_size() != 1) return;
assert(*MBB->succ_begin() == CurLoop->getHeader() &&
"The predecessor doesn't feed directly into the loop header!");
// Now move the instructions to the predecessor.
MachineInstr *NewMI = MI.clone();
MoveInstToEndOfBlock(MBB, NewMI);
// Update VRegDefs.
for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = NewMI->getOperand(i);
if (MO.isRegister() && MO.isDef() &&
MRegisterInfo::isVirtualRegister(MO.getReg())) {
VRegDefs.grow(MO.getReg());
VRegDefs[MO.getReg()] = NewMI;
}
}
// Hoisting was successful! Remove bothersome instruction now.
MI.getParent()->remove(&MI);
Changed = true;
}
<commit_msg>Add debugging info. Use the newly created "hasUnmodelledSideEffects" method.<commit_after>//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Bill Wendling and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs loop invariant code motion on machine instructions. We
// attempt to remove as much code from the body of a loop as possible.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "machine-licm"
#include "llvm/ADT/IndexedMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
namespace {
// Hidden options to help debugging
cl::opt<bool>
PerformLICM("machine-licm",
cl::init(false), cl::Hidden,
cl::desc("Perform loop-invariant code motion on machine code"));
}
STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
namespace {
class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
const TargetInstrInfo *TII;
MachineFunction *CurMF; // Current MachineFunction
// Various analyses that we use...
MachineLoopInfo *LI; // Current MachineLoopInfo
MachineDominatorTree *DT; // Machine dominator tree for the current Loop
// State that is updated as we process loops
bool Changed; // True if a loop is changed.
MachineLoop *CurLoop; // The current loop we are working on.
// Map the def of a virtual register to the machine instruction.
IndexedMap<const MachineInstr*, VirtReg2IndexFunctor> VRegDefs;
public:
static char ID; // Pass identification, replacement for typeid
MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
virtual bool runOnMachineFunction(MachineFunction &MF);
/// FIXME: Loop preheaders?
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineLoopInfo>();
AU.addRequired<MachineDominatorTree>();
}
private:
/// VisitAllLoops - Visit all of the loops in depth first order and try to
/// hoist invariant instructions from them.
///
void VisitAllLoops(MachineLoop *L) {
const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
for (MachineLoop::iterator
I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
MachineLoop *ML = *I;
// Traverse the body of the loop in depth first order on the dominator
// tree so that we are guaranteed to see definitions before we see uses.
VisitAllLoops(ML);
HoistRegion(DT->getNode(ML->getHeader()));
}
HoistRegion(DT->getNode(L->getHeader()));
}
/// MapVirtualRegisterDefs - Create a map of which machine instruction
/// defines a virtual register.
///
void MapVirtualRegisterDefs();
/// IsInSubLoop - A little predicate that returns true if the specified
/// basic block is in a subloop of the current one, not the current one
/// itself.
///
bool IsInSubLoop(MachineBasicBlock *BB) {
assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
return LI->getLoopFor(BB) != CurLoop;
}
/// IsLoopInvariantInst - Returns true if the instruction is loop
/// invariant. I.e., all virtual register operands are defined outside of
/// the loop, physical registers aren't accessed (explicitly or implicitly),
/// and the instruction is hoistable.
///
bool IsLoopInvariantInst(MachineInstr &I);
/// FindPredecessors - Get all of the predecessors of the loop that are not
/// back-edges.
///
void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
const MachineBasicBlock *Header = CurLoop->getHeader();
for (MachineBasicBlock::const_pred_iterator
I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
if (!CurLoop->contains(*I))
Preds.push_back(*I);
}
/// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
/// the predecessor basic block (but before the terminator instructions).
///
void MoveInstToEndOfBlock(MachineBasicBlock *MBB, MachineInstr *MI) {
DEBUG({
DOUT << "Hoisting " << *MI;
if (MBB->getBasicBlock())
DOUT << " to MachineBasicBlock "
<< MBB->getBasicBlock()->getName();
DOUT << "\n";
});
MachineBasicBlock::iterator Iter = MBB->getFirstTerminator();
MBB->insert(Iter, MI);
++NumHoisted;
}
/// HoistRegion - Walk the specified region of the CFG (defined by all
/// blocks dominated by the specified block, and that are in the current
/// loop) in depth first order w.r.t the DominatorTree. This allows us to
/// visit definitions before uses, allowing us to hoist a loop body in one
/// pass without iteration.
///
void HoistRegion(MachineDomTreeNode *N);
/// Hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void Hoist(MachineInstr &MI);
};
char MachineLICM::ID = 0;
RegisterPass<MachineLICM> X("machine-licm",
"Machine Loop Invariant Code Motion");
} // end anonymous namespace
FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
/// Hoist expressions out of the specified loop. Note, alias info for inner loop
/// is not preserved so it is not a good idea to run LICM multiple times on one
/// loop.
///
bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
if (!PerformLICM) return false; // For debugging.
DOUT << "******** Machine LICM ********\n";
Changed = false;
CurMF = &MF;
TII = CurMF->getTarget().getInstrInfo();
// Get our Loop information...
LI = &getAnalysis<MachineLoopInfo>();
DT = &getAnalysis<MachineDominatorTree>();
MapVirtualRegisterDefs();
for (MachineLoopInfo::iterator
I = LI->begin(), E = LI->end(); I != E; ++I) {
CurLoop = *I;
// Visit all of the instructions of the loop. We want to visit the subloops
// first, though, so that we can hoist their invariants first into their
// containing loop before we process that loop.
VisitAllLoops(CurLoop);
}
return Changed;
}
/// MapVirtualRegisterDefs - Create a map of which machine instruction defines a
/// virtual register.
///
void MachineLICM::MapVirtualRegisterDefs() {
for (MachineFunction::const_iterator
I = CurMF->begin(), E = CurMF->end(); I != E; ++I) {
const MachineBasicBlock &MBB = *I;
for (MachineBasicBlock::const_iterator
II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
const MachineInstr &MI = *II;
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI.getOperand(i);
if (MO.isRegister() && MO.isDef() &&
MRegisterInfo::isVirtualRegister(MO.getReg())) {
VRegDefs.grow(MO.getReg());
VRegDefs[MO.getReg()] = &MI;
}
}
}
}
}
/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
/// dominated by the specified block, and that are in the current loop) in depth
/// first order w.r.t the DominatorTree. This allows us to visit definitions
/// before uses, allowing us to hoist a loop body in one pass without iteration.
///
void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
assert(N != 0 && "Null dominator tree node?");
MachineBasicBlock *BB = N->getBlock();
// If this subregion is not in the top level loop at all, exit.
if (!CurLoop->contains(BB)) return;
// Only need to process the contents of this block if it is not part of a
// subloop (which would already have been processed).
if (!IsInSubLoop(BB))
for (MachineBasicBlock::iterator
I = BB->begin(), E = BB->end(); I != E; ) {
MachineInstr &MI = *I++;
// Try hoisting the instruction out of the loop. We can only do this if
// all of the operands of the instruction are loop invariant and if it is
// safe to hoist the instruction.
Hoist(MI);
}
const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
for (unsigned I = 0, E = Children.size(); I != E; ++I)
HoistRegion(Children[I]);
}
/// IsLoopInvariantInst - Returns true if the instruction is loop
/// invariant. I.e., all virtual register operands are defined outside of the
/// loop, physical registers aren't accessed (explicitly or implicitly), and the
/// instruction is hoistable.
///
bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
DEBUG({
DOUT << "--- Checking if we can hoist " << I;
if (I.getInstrDescriptor()->ImplicitUses) {
DOUT << " * Instruction has implicit uses:\n";
const TargetMachine &TM = CurMF->getTarget();
const MRegisterInfo *MRI = TM.getRegisterInfo();
const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
for (; *ImpUses; ++ImpUses)
DOUT << " -> " << MRI->getName(*ImpUses) << "\n";
}
if (I.getInstrDescriptor()->ImplicitDefs) {
DOUT << " * Instruction has implicit defines:\n";
const TargetMachine &TM = CurMF->getTarget();
const MRegisterInfo *MRI = TM.getRegisterInfo();
const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
for (; *ImpDefs; ++ImpDefs)
DOUT << " -> " << MRI->getName(*ImpDefs) << "\n";
}
if (TII->hasUnmodelledSideEffects(&I))
DOUT << " * Instruction has side effects.\n";
});
#if 0
// FIXME: Don't hoist if this instruction implicitly reads physical registers.
if (I.getInstrDescriptor()->ImplicitUses ||
I.getInstrDescriptor()->ImplicitDefs)
return false;
#endif
// The instruction is loop invariant if all of its operands are loop-invariant
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = I.getOperand(i);
if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
continue;
unsigned Reg = MO.getReg();
// Don't hoist instructions that access physical registers.
if (!MRegisterInfo::isVirtualRegister(Reg))
return false;
assert(VRegDefs[Reg] && "Machine instr not mapped for this vreg?");
// If the loop contains the definition of an operand, then the instruction
// isn't loop invariant.
if (CurLoop->contains(VRegDefs[Reg]->getParent()))
return false;
}
// Don't hoist something that has side effects.
if (TII->hasUnmodelledSideEffects(&I)) return false;
// If we got this far, the instruction is loop invariant!
return true;
}
/// Hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void MachineLICM::Hoist(MachineInstr &MI) {
if (!IsLoopInvariantInst(MI)) return;
std::vector<MachineBasicBlock*> Preds;
// Non-back-edge predecessors.
FindPredecessors(Preds);
// Either we don't have any predecessors(?!) or we have more than one, which
// is forbidden.
if (Preds.empty() || Preds.size() != 1) return;
// Check that the predecessor is qualified to take the hoisted
// instruction. I.e., there is only one edge from the predecessor, and it's to
// the loop header.
MachineBasicBlock *MBB = Preds.front();
// FIXME: We are assuming at first that the basic block coming into this loop
// has only one successor. This isn't the case in general because we haven't
// broken critical edges or added preheaders.
if (MBB->succ_size() != 1) return;
assert(*MBB->succ_begin() == CurLoop->getHeader() &&
"The predecessor doesn't feed directly into the loop header!");
// Now move the instructions to the predecessor.
MachineInstr *NewMI = MI.clone();
MoveInstToEndOfBlock(MBB, NewMI);
// Update VRegDefs.
for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = NewMI->getOperand(i);
if (MO.isRegister() && MO.isDef() &&
MRegisterInfo::isVirtualRegister(MO.getReg())) {
VRegDefs.grow(MO.getReg());
VRegDefs[MO.getReg()] = NewMI;
}
}
// Hoisting was successful! Remove bothersome instruction now.
MI.getParent()->remove(&MI);
Changed = true;
}
<|endoftext|>
|
<commit_before>#ifndef ARABICA_XSLT_STYLESHEETCONSTANT_HPP
#define ARABICA_XSLT_STYLESHEETCONSTANT_HPP
#include <XML/XMLCharacterClasses.hpp>
#include <XPath/impl/xpath_namespace_context.hpp>
#include <memory>
#include "xslt_stylesheet_parser.hpp"
#include "xslt_compiled_stylesheet.hpp"
#include "xslt_compilation_context.hpp"
#include "handler/xslt_template_handler.hpp"
#include "handler/xslt_include_handler.hpp"
#include "handler/xslt_output_handler.hpp"
#include "handler/xslt_namespace_alias_handler.hpp"
#include "handler/xslt_key_handler.hpp"
#include "handler/xslt_foreign_element_handler.hpp"
namespace Arabica
{
namespace XSLT
{
class StylesheetHandler : public SAX::DefaultHandler<std::string>
{
public:
StylesheetHandler(CompilationContext& context) :
context_(context),
top_(false),
foreign_(0)
{
context_.root(*this);
includer_.context(context_, this);
} // StylesheetHandler
virtual void startDocument()
{
top_ = true;
} // startDocument
virtual void startElement(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
if(top_)
{
startStylesheet(namespaceURI, localName, qName, atts);
return;
} // if(top_)
if(namespaceURI == StylesheetConstant::NamespaceURI())
startXSLTElement(namespaceURI, localName, qName, atts);
else if(!namespaceURI.empty())
startForeignElement(namespaceURI, localName, qName, atts);
else
oops(qName);
} // startElement
virtual void endElement(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName)
{
if(foreign_)
--foreign_;
} // endElement
virtual void characters(const std::string& ch)
{
if(foreign_)
return;
for(std::string::const_iterator s = ch.begin(), e = ch.end(); s != e; ++s)
if(!Arabica::XML::is_space(*s))
throw SAX::SAXException("stylesheet element can not contain character data :'" + ch +"'");
} // characters
virtual void endDocument()
{
includer_.unwind_imports();
context_.stylesheet().prepare();
} // endDocument
private:
void startStylesheet(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
if(namespaceURI != StylesheetConstant::NamespaceURI())
throw SAX::SAXException("The source file does not look like a stylesheet.");
if(localName != "stylesheet" && localName != "transform")
throw SAX::SAXException("Top-level element must be 'stylesheet' or 'transform'.");
static const ValueRule rules[] = { { "version", true, 0 },
{ "extension-element-prefixes", false, 0 },
{ "exclude-result-prefixes", false, 0 },
{ "id", false, 0 },
{ 0, false, 0 } };
std::map<std::string, std::string> attributes = gatherAttributes(qName, atts, rules);
if(attributes["version"] != StylesheetConstant::Version())
throw SAX::SAXException("I'm only a poor version 1.0 XSLT Transformer.");
if(!attributes["extension-element-prefixes"].empty())
throw SAX::SAXException("Haven't implemented extension-element-prefixes yet");
top_ = false;
} // startStylesheet
void startXSLTElement(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
if((localName == "import") || (localName == "include"))
{
include_stylesheet(namespaceURI, localName, qName, atts);
return;
} // if ...
for(const ChildElement* c = allowedChildren; c->name != 0; ++c)
if(c->name == localName)
{
context_.push(0,
c->createHandler(context_),
namespaceURI,
localName,
qName,
atts);
return;
} // if ...
oops(qName);
} // startXSLTElement
void startForeignElement(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
context_.push(0,
new ForeignElementHandler(context_),
namespaceURI,
localName,
qName,
atts);
} // startForeignElement
void include_stylesheet(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
includer_.start_include(namespaceURI, localName, qName, atts);
} // include_stylesheet
void oops(const std::string& qName) const
{
throw SAX::SAXException("xsl:stylesheet does not allow " + qName + " here.");
} // oops
CompilationContext& context_;
SAX::DefaultHandler<std::string>* child_;
IncludeHandler includer_;
bool top_;
unsigned int foreign_;
static const ChildElement allowedChildren[];
}; // class StylesheetHandler
const ChildElement StylesheetHandler::allowedChildren[] =
{
{ "attribute-set", CreateHandler<NotImplementedYetHandler>},
{ "decimal-format", CreateHandler<NotImplementedYetHandler>},
//"import"
//"include"
{ "key", CreateHandler<KeyHandler>},
{ "namespace-alias", CreateHandler<NamespaceAliasHandler>},
{ "output", CreateHandler<OutputHandler>},
{ "param", CreateHandler<TopLevelVariableHandler<Param> >},
{ "preserve-space", CreateHandler<NotImplementedYetHandler>},
{ "strip-space", CreateHandler<NotImplementedYetHandler>},
{ "template", CreateHandler<TemplateHandler> },
{ "variable", CreateHandler<TopLevelVariableHandler<Variable> > },
{ 0, 0 }
}; // StylesheetHandler::allowedChildren
class StylesheetCompiler
{
public:
StylesheetCompiler()
{
} // StylesheetCompiler
~StylesheetCompiler()
{
} // ~StylesheetCompiler
std::auto_ptr<Stylesheet> compile(SAX::InputSource<std::string>& source)
{
error_ = "";
std::auto_ptr<CompiledStylesheet> stylesheet(new CompiledStylesheet());
StylesheetParser parser;
CompilationContext context(parser, *stylesheet.get());
StylesheetHandler stylesheetHandler(context);
parser.setContentHandler(stylesheetHandler);
//parser.setErrorHandler(*this);
//if(entityResolver_)
// parser.setEntityResolver(*entityResolver_);
try {
parser.parse(source);
} // try
catch(std::exception& ex)
{
error_ = ex.what();
//std::cerr << "Compilation Failed : " << ex.what() << std::endl;
stylesheet.reset();
} // catch
return std::auto_ptr<Stylesheet>(stylesheet.release());
} // compile
const std::string& error() const
{
return error_;
} // error
private:
std::string error_;
}; // class StylesheetCompiler
} // namespace XSLT
} // namespace Arabica
#endif // ARABICA_XSLT_STYLESHEETCOMPILER_HPP
<commit_msg>started on literal result elements as stylesheet<commit_after>#ifndef ARABICA_XSLT_STYLESHEETCONSTANT_HPP
#define ARABICA_XSLT_STYLESHEETCONSTANT_HPP
#include <XML/XMLCharacterClasses.hpp>
#include <XPath/impl/xpath_namespace_context.hpp>
#include <memory>
#include "xslt_stylesheet_parser.hpp"
#include "xslt_compiled_stylesheet.hpp"
#include "xslt_compilation_context.hpp"
#include "handler/xslt_template_handler.hpp"
#include "handler/xslt_include_handler.hpp"
#include "handler/xslt_output_handler.hpp"
#include "handler/xslt_namespace_alias_handler.hpp"
#include "handler/xslt_key_handler.hpp"
#include "handler/xslt_foreign_element_handler.hpp"
namespace Arabica
{
namespace XSLT
{
class StylesheetHandler : public SAX::DefaultHandler<std::string>
{
public:
StylesheetHandler(CompilationContext& context) :
context_(context),
top_(false),
foreign_(0)
{
context_.root(*this);
includer_.context(context_, this);
} // StylesheetHandler
virtual void startDocument()
{
top_ = true;
} // startDocument
virtual void startElement(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
if(top_)
{
top_ = false;
if(namespaceURI == StylesheetConstant::NamespaceURI())
startStylesheet(namespaceURI, localName, qName, atts);
else
startLREAsStylesheet(namespaceURI, localName, qName, atts);
return;
} // if(top_)
if(namespaceURI == StylesheetConstant::NamespaceURI())
startXSLTElement(namespaceURI, localName, qName, atts);
else if(!namespaceURI.empty())
startForeignElement(namespaceURI, localName, qName, atts);
else
oops(qName);
} // startElement
virtual void endElement(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName)
{
if(foreign_)
--foreign_;
} // endElement
virtual void characters(const std::string& ch)
{
if(foreign_)
return;
for(std::string::const_iterator s = ch.begin(), e = ch.end(); s != e; ++s)
if(!Arabica::XML::is_space(*s))
throw SAX::SAXException("stylesheet element can not contain character data :'" + ch +"'");
} // characters
virtual void endDocument()
{
includer_.unwind_imports();
context_.stylesheet().prepare();
} // endDocument
private:
void startStylesheet(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
if(localName != "stylesheet" && localName != "transform")
throw SAX::SAXException("Top-level element must be 'stylesheet' or 'transform'.");
static const ValueRule rules[] = { { "version", true, 0 },
{ "extension-element-prefixes", false, 0 },
{ "exclude-result-prefixes", false, 0 },
{ "id", false, 0 },
{ 0, false, 0 } };
std::map<std::string, std::string> attributes = gatherAttributes(qName, atts, rules);
if(attributes["version"] != StylesheetConstant::Version())
throw SAX::SAXException("I'm only a poor version 1.0 XSLT Transformer.");
if(!attributes["extension-element-prefixes"].empty())
throw SAX::SAXException("Haven't implemented extension-element-prefixes yet");
} // startStylesheet
void startLREAsStylesheet(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
std::string version;
for(int a = 0; a != atts.getLength(); ++a)
if((StylesheetConstant::NamespaceURI() == atts.getURI(a)) &&
("version" == atts.getLocalName(a)))
{
version = atts.getValue(a);
break;
}
if(version.empty())
throw SAX::SAXException("The source file does not look like a stylesheet.");
if(version != StylesheetConstant::Version())
throw SAX::SAXException("I'm only a poor version 1.0 XSLT Transformer.");
} // startLREAsStylesheet
void startXSLTElement(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
if((localName == "import") || (localName == "include"))
{
include_stylesheet(namespaceURI, localName, qName, atts);
return;
} // if ...
for(const ChildElement* c = allowedChildren; c->name != 0; ++c)
if(c->name == localName)
{
context_.push(0,
c->createHandler(context_),
namespaceURI,
localName,
qName,
atts);
return;
} // if ...
oops(qName);
} // startXSLTElement
void startForeignElement(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
context_.push(0,
new ForeignElementHandler(context_),
namespaceURI,
localName,
qName,
atts);
} // startForeignElement
void include_stylesheet(const std::string& namespaceURI,
const std::string& localName,
const std::string& qName,
const SAX::Attributes<std::string>& atts)
{
includer_.start_include(namespaceURI, localName, qName, atts);
} // include_stylesheet
void oops(const std::string& qName) const
{
throw SAX::SAXException("xsl:stylesheet does not allow " + qName + " here.");
} // oops
CompilationContext& context_;
SAX::DefaultHandler<std::string>* child_;
IncludeHandler includer_;
bool top_;
unsigned int foreign_;
static const ChildElement allowedChildren[];
}; // class StylesheetHandler
const ChildElement StylesheetHandler::allowedChildren[] =
{
{ "attribute-set", CreateHandler<NotImplementedYetHandler>},
{ "decimal-format", CreateHandler<NotImplementedYetHandler>},
//"import"
//"include"
{ "key", CreateHandler<KeyHandler>},
{ "namespace-alias", CreateHandler<NamespaceAliasHandler>},
{ "output", CreateHandler<OutputHandler>},
{ "param", CreateHandler<TopLevelVariableHandler<Param> >},
{ "preserve-space", CreateHandler<NotImplementedYetHandler>},
{ "strip-space", CreateHandler<NotImplementedYetHandler>},
{ "template", CreateHandler<TemplateHandler> },
{ "variable", CreateHandler<TopLevelVariableHandler<Variable> > },
{ 0, 0 }
}; // StylesheetHandler::allowedChildren
class StylesheetCompiler
{
public:
StylesheetCompiler()
{
} // StylesheetCompiler
~StylesheetCompiler()
{
} // ~StylesheetCompiler
std::auto_ptr<Stylesheet> compile(SAX::InputSource<std::string>& source)
{
error_ = "";
std::auto_ptr<CompiledStylesheet> stylesheet(new CompiledStylesheet());
StylesheetParser parser;
CompilationContext context(parser, *stylesheet.get());
StylesheetHandler stylesheetHandler(context);
parser.setContentHandler(stylesheetHandler);
//parser.setErrorHandler(*this);
//if(entityResolver_)
// parser.setEntityResolver(*entityResolver_);
try {
parser.parse(source);
} // try
catch(std::exception& ex)
{
error_ = ex.what();
//std::cerr << "Compilation Failed : " << ex.what() << std::endl;
stylesheet.reset();
} // catch
return std::auto_ptr<Stylesheet>(stylesheet.release());
} // compile
const std::string& error() const
{
return error_;
} // error
private:
std::string error_;
}; // class StylesheetCompiler
} // namespace XSLT
} // namespace Arabica
#endif // ARABICA_XSLT_STYLESHEETCOMPILER_HPP
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin_explorer.
*
* libbitcoin_explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BX_FETCH_TX_HPP
#define BX_FETCH_TX_HPP
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/command.hpp>
#include <bitcoin/explorer/define.hpp>
#include <bitcoin/explorer/generated.hpp>
#include <bitcoin/explorer/primitives/address.hpp>
#include <bitcoin/explorer/primitives/base16.hpp>
#include <bitcoin/explorer/primitives/base2.hpp>
#include <bitcoin/explorer/primitives/base58.hpp>
#include <bitcoin/explorer/primitives/btc.hpp>
#include <bitcoin/explorer/primitives/btc160.hpp>
#include <bitcoin/explorer/primitives/btc256.hpp>
#include <bitcoin/explorer/primitives/ec_private.hpp>
#include <bitcoin/explorer/primitives/ec_public.hpp>
#include <bitcoin/explorer/primitives/encoding.hpp>
#include <bitcoin/explorer/primitives/hashtype.hpp>
#include <bitcoin/explorer/primitives/hd_key.hpp>
#include <bitcoin/explorer/primitives/hd_priv.hpp>
#include <bitcoin/explorer/primitives/hd_pub.hpp>
#include <bitcoin/explorer/primitives/header.hpp>
#include <bitcoin/explorer/primitives/input.hpp>
#include <bitcoin/explorer/primitives/output.hpp>
#include <bitcoin/explorer/primitives/raw.hpp>
#include <bitcoin/explorer/primitives/script.hpp>
#include <bitcoin/explorer/primitives/stealth.hpp>
#include <bitcoin/explorer/primitives/transaction.hpp>
#include <bitcoin/explorer/primitives/wif.hpp>
#include <bitcoin/explorer/primitives/wrapper.hpp>
#include <bitcoin/explorer/utility/compat.hpp>
#include <bitcoin/explorer/utility/config.hpp>
#include <bitcoin/explorer/utility/utility.hpp>
/********* GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY **********/
namespace libbitcoin {
namespace explorer {
namespace commands {
/**
* Class to implement the fetch-tx command.
*/
class fetch_tx
: public command
{
public:
/**
* The symbolic (not localizable) command name, lower case.
*/
static const char* symbol() { return "fetch-tx"; }
/**
* The member symbolic (not localizable) command name, lower case.
*/
virtual const char* name()
{
return fetch_tx::symbol();
}
/**
* The localizable command category name, upper case.
*/
virtual const char* category()
{
return "ONLINE";
}
/**
* Load program argument definitions.
* A value of -1 indicates that the number of instances is unlimited.
* @return The loaded program argument definitions.
*/
virtual arguments_metadata& load_arguments()
{
return get_argument_metadata()
.add("HASH", -1);
}
/**
* Load parameter fallbacks from file or input as appropriate.
* @param[in] input The input stream for loading the parameters.
* @param[in] The loaded variables.
*/
virtual void load_fallbacks(std::istream& input,
po::variables_map& variables)
{
//load_input(get_hashs_argument(), "HASH", variables, input);
}
/**
* Load program option definitions.
* The implicit_value call allows flags to be strongly-typed on read while
* allowing but not requiring a value on the command line for the option.
* BUGBUG: see boost bug/fix: svn.boost.org/trac/boost/ticket/8009
* @return The loaded program option definitions.
*/
virtual options_metadata& load_options()
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_CONFIG_VARIABLE ",c",
value<boost::filesystem::path>(),
"The path and file name for the configuration settings file to be used in the execution of the command."
)
(
"help,h",
value<bool>(&option_.help)->implicit_value(true),
"Get transactions by filter. Requires an Obelisk server connection."
)
(
"format,f",
value<primitives::encoding>(&option_.format),
"The output format. Options are 'json', 'xml', 'info' or 'native', defaults to native."
)
(
"height,t",
value<size_t>(&option_.height),
"The minimum block height of prefix transactions to get."
)
(
"HASH",
value<std::vector<primitives::btc256>>(&argument_.hashs),
"The set of Base16 transaction hashes of transactions to get."
);
return options;
}
/**
* Invoke the command.
* @param[out] output The input stream for the command execution.
* @param[out] error The input stream for the command execution.
* @return The appropriate console return code { -1, 0, 1 }.
*/
virtual console_result invoke(std::ostream& output, std::ostream& cerr);
/* Properties */
/**
* Get the value of the HASH arguments.
*/
virtual std::vector<primitives::btc256>& get_hashs_argument()
{
return argument_.hashs;
}
/**
* Set the value of the HASH arguments.
*/
virtual void set_hashs_argument(
const std::vector<primitives::btc256>& value)
{
argument_.hashs = value;
}
/**
* Get the value of the help option.
*/
virtual bool& get_help_option()
{
return option_.help;
}
/**
* Set the value of the help option.
*/
virtual void set_help_option(
const bool& value)
{
option_.help = value;
}
/**
* Get the value of the format option.
*/
virtual primitives::encoding& get_format_option()
{
return option_.format;
}
/**
* Set the value of the format option.
*/
virtual void set_format_option(
const primitives::encoding& value)
{
option_.format = value;
}
/**
* Get the value of the height option.
*/
virtual size_t& get_height_option()
{
return option_.height;
}
/**
* Set the value of the height option.
*/
virtual void set_height_option(
const size_t& value)
{
option_.height = value;
}
private:
/**
* Command line argument bound variables.
* Uses cross-compiler safe constructor-based zeroize.
* Zeroize for unit test consistency with program_options initialization.
*/
struct argument
{
argument()
: hashs()
{
}
std::vector<primitives::btc256> hashs;
} argument_;
/**
* Command line option bound variables.
* Uses cross-compiler safe constructor-based zeroize.
* Zeroize for unit test consistency with program_options initialization.
*/
struct option
{
option()
: help(),
format(),
height()
{
}
bool help;
primitives::encoding format;
size_t height;
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
#endif
<commit_msg>Remove fetch-tx height option.<commit_after>/**
* Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin_explorer.
*
* libbitcoin_explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BX_FETCH_TX_HPP
#define BX_FETCH_TX_HPP
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/command.hpp>
#include <bitcoin/explorer/define.hpp>
#include <bitcoin/explorer/generated.hpp>
#include <bitcoin/explorer/primitives/address.hpp>
#include <bitcoin/explorer/primitives/base16.hpp>
#include <bitcoin/explorer/primitives/base2.hpp>
#include <bitcoin/explorer/primitives/base58.hpp>
#include <bitcoin/explorer/primitives/btc.hpp>
#include <bitcoin/explorer/primitives/btc160.hpp>
#include <bitcoin/explorer/primitives/btc256.hpp>
#include <bitcoin/explorer/primitives/ec_private.hpp>
#include <bitcoin/explorer/primitives/ec_public.hpp>
#include <bitcoin/explorer/primitives/encoding.hpp>
#include <bitcoin/explorer/primitives/hashtype.hpp>
#include <bitcoin/explorer/primitives/hd_key.hpp>
#include <bitcoin/explorer/primitives/hd_priv.hpp>
#include <bitcoin/explorer/primitives/hd_pub.hpp>
#include <bitcoin/explorer/primitives/header.hpp>
#include <bitcoin/explorer/primitives/input.hpp>
#include <bitcoin/explorer/primitives/output.hpp>
#include <bitcoin/explorer/primitives/raw.hpp>
#include <bitcoin/explorer/primitives/script.hpp>
#include <bitcoin/explorer/primitives/stealth.hpp>
#include <bitcoin/explorer/primitives/transaction.hpp>
#include <bitcoin/explorer/primitives/wif.hpp>
#include <bitcoin/explorer/primitives/wrapper.hpp>
#include <bitcoin/explorer/utility/compat.hpp>
#include <bitcoin/explorer/utility/config.hpp>
#include <bitcoin/explorer/utility/utility.hpp>
/********* GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY **********/
namespace libbitcoin {
namespace explorer {
namespace commands {
/**
* Class to implement the fetch-tx command.
*/
class fetch_tx
: public command
{
public:
/**
* The symbolic (not localizable) command name, lower case.
*/
static const char* symbol() { return "fetch-tx"; }
/**
* The member symbolic (not localizable) command name, lower case.
*/
virtual const char* name()
{
return fetch_tx::symbol();
}
/**
* The localizable command category name, upper case.
*/
virtual const char* category()
{
return "ONLINE";
}
/**
* Load program argument definitions.
* A value of -1 indicates that the number of instances is unlimited.
* @return The loaded program argument definitions.
*/
virtual arguments_metadata& load_arguments()
{
return get_argument_metadata()
.add("HASH", -1);
}
/**
* Load parameter fallbacks from file or input as appropriate.
* @param[in] input The input stream for loading the parameters.
* @param[in] The loaded variables.
*/
virtual void load_fallbacks(std::istream& input,
po::variables_map& variables)
{
//load_input(get_hashs_argument(), "HASH", variables, input);
}
/**
* Load program option definitions.
* The implicit_value call allows flags to be strongly-typed on read while
* allowing but not requiring a value on the command line for the option.
* BUGBUG: see boost bug/fix: svn.boost.org/trac/boost/ticket/8009
* @return The loaded program option definitions.
*/
virtual options_metadata& load_options()
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_CONFIG_VARIABLE ",c",
value<boost::filesystem::path>(),
"The path and file name for the configuration settings file to be used in the execution of the command."
)
(
"help,h",
value<bool>(&option_.help)->implicit_value(true),
"Get transactions by filter. Requires an Obelisk server connection."
)
(
"format,f",
value<primitives::encoding>(&option_.format),
"The output format. Options are 'json', 'xml', 'info' or 'native', defaults to native."
)
(
"HASH",
value<std::vector<primitives::btc256>>(&argument_.hashs),
"The set of Base16 transaction hashes of transactions to get."
);
return options;
}
/**
* Invoke the command.
* @param[out] output The input stream for the command execution.
* @param[out] error The input stream for the command execution.
* @return The appropriate console return code { -1, 0, 1 }.
*/
virtual console_result invoke(std::ostream& output, std::ostream& cerr);
/* Properties */
/**
* Get the value of the HASH arguments.
*/
virtual std::vector<primitives::btc256>& get_hashs_argument()
{
return argument_.hashs;
}
/**
* Set the value of the HASH arguments.
*/
virtual void set_hashs_argument(
const std::vector<primitives::btc256>& value)
{
argument_.hashs = value;
}
/**
* Get the value of the help option.
*/
virtual bool& get_help_option()
{
return option_.help;
}
/**
* Set the value of the help option.
*/
virtual void set_help_option(
const bool& value)
{
option_.help = value;
}
/**
* Get the value of the format option.
*/
virtual primitives::encoding& get_format_option()
{
return option_.format;
}
/**
* Set the value of the format option.
*/
virtual void set_format_option(
const primitives::encoding& value)
{
option_.format = value;
}
private:
/**
* Command line argument bound variables.
* Uses cross-compiler safe constructor-based zeroize.
* Zeroize for unit test consistency with program_options initialization.
*/
struct argument
{
argument()
: hashs()
{
}
std::vector<primitives::btc256> hashs;
} argument_;
/**
* Command line option bound variables.
* Uses cross-compiler safe constructor-based zeroize.
* Zeroize for unit test consistency with program_options initialization.
*/
struct option
{
option()
: help(),
format()
{
}
bool help;
primitives::encoding format;
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
#endif
<|endoftext|>
|
<commit_before>/*
Class for displaying connection errors
Copyright (C) 2011 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 "error-handler.h"
#include <KNotification>
#include <KAboutData>
#include <KDebug>
#include <KTp/error-dictionary.h>
#include <Solid/Networking>
ErrorHandler::ErrorHandler(const Tp::AccountManagerPtr& am, QObject* parent)
: QObject(parent)
{
m_accountManager = am;
Q_FOREACH(const Tp::AccountPtr &account, am->allAccounts()) {
onNewAccount(account);
}
connect(m_accountManager.data(), SIGNAL(newAccount(Tp::AccountPtr)),
this, SLOT(onNewAccount(Tp::AccountPtr)));
}
ErrorHandler::~ErrorHandler()
{
}
void ErrorHandler::onConnectionStatusChanged(const Tp::ConnectionStatus status)
{
Tp::AccountPtr account(qobject_cast< Tp::Account* >(sender()));
if (status == Tp::ConnectionStatusDisconnected) {
QString connectionError = account->connectionError();
Tp::ConnectionStatusReason reason = account->connectionStatusReason();
kDebug() << reason;
kDebug() << account->connectionError();
kDebug() << account->connectionErrorDetails().allDetails();
switch (reason) {
case Tp::ConnectionStatusReasonRequested:
//do nothing
break;
case Tp::ConnectionStatusReasonAuthenticationFailed:
showMessageToUser(i18nc("%1 is the account name", "Could not connect %1. Authentication failed (is your password correct?)", account->displayName()), ErrorHandler::SystemMessageError);
break;
case Tp::ConnectionStatusReasonNetworkError:
//if connected to the network, and there was a network error - display it. Otherwise do nothing.
if (Solid::Networking::status() == Solid::Networking::Connected) {
showMessageToUser(i18nc("%1 is the account name", "Could not connect %1. There was a network error, check your connection", account->displayName()), ErrorHandler::SystemMessageError);
}
break;
default:
showMessageToUser(i18nc("%1 is the account name, %2 the error message", "There was a problem while trying to connect %1 - %2", account->displayName(), KTp::ErrorDictionary::displayVerboseErrorMessage(connectionError)), ErrorHandler::SystemMessageError);
break;
}
}
}
void ErrorHandler::showMessageToUser(const QString &text, const ErrorHandler::SystemMessageType type)
{
//The pointer is automatically deleted when the event is closed
KNotification *notification;
if (type == ErrorHandler::SystemMessageError) {
notification = new KNotification(QLatin1String("telepathyError"), KNotification::Persistent);
} else {
notification = new KNotification(QLatin1String("telepathyInfo"), KNotification::CloseOnTimeout);
}
KAboutData aboutData("ktelepathy",0,KLocalizedString(),0);
notification->setComponentData(KComponentData(aboutData));
notification->setText(text);
notification->sendEvent();
}
void ErrorHandler::onNewAccount(const Tp::AccountPtr& account)
{
connect(account.data(), SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)),
this, SLOT(onConnectionStatusChanged(Tp::ConnectionStatus)));
}
<commit_msg>Supress all errors unless we are connected to the network<commit_after>/*
Class for displaying connection errors
Copyright (C) 2011 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 "error-handler.h"
#include <KNotification>
#include <KAboutData>
#include <KDebug>
#include <KTp/error-dictionary.h>
#include <Solid/Networking>
ErrorHandler::ErrorHandler(const Tp::AccountManagerPtr& am, QObject* parent)
: QObject(parent)
{
m_accountManager = am;
Q_FOREACH(const Tp::AccountPtr &account, am->allAccounts()) {
onNewAccount(account);
}
connect(m_accountManager.data(), SIGNAL(newAccount(Tp::AccountPtr)),
this, SLOT(onNewAccount(Tp::AccountPtr)));
}
ErrorHandler::~ErrorHandler()
{
}
void ErrorHandler::onConnectionStatusChanged(const Tp::ConnectionStatus status)
{
Tp::AccountPtr account(qobject_cast< Tp::Account* >(sender()));
//if we're not connected to the network, don't display any errors.
if (Solid::Networking::status() != Solid::Networking::Connected) {
return;
}
if (status == Tp::ConnectionStatusDisconnected) {
QString connectionError = account->connectionError();
Tp::ConnectionStatusReason reason = account->connectionStatusReason();
kDebug() << reason;
kDebug() << account->connectionError();
kDebug() << account->connectionErrorDetails().allDetails();
switch (reason) {
case Tp::ConnectionStatusReasonRequested:
//do nothing
break;
case Tp::ConnectionStatusReasonAuthenticationFailed:
showMessageToUser(i18nc("%1 is the account name", "Could not connect %1. Authentication failed (is your password correct?)", account->displayName()), ErrorHandler::SystemMessageError);
break;
case Tp::ConnectionStatusReasonNetworkError:
showMessageToUser(i18nc("%1 is the account name", "Could not connect %1. There was a network error, check your connection", account->displayName()), ErrorHandler::SystemMessageError);
break;
default:
showMessageToUser(i18nc("%1 is the account name, %2 the error message", "There was a problem while trying to connect %1 - %2", account->displayName(), KTp::ErrorDictionary::displayVerboseErrorMessage(connectionError)), ErrorHandler::SystemMessageError);
break;
}
}
}
void ErrorHandler::showMessageToUser(const QString &text, const ErrorHandler::SystemMessageType type)
{
//The pointer is automatically deleted when the event is closed
KNotification *notification;
if (type == ErrorHandler::SystemMessageError) {
notification = new KNotification(QLatin1String("telepathyError"), KNotification::Persistent);
} else {
notification = new KNotification(QLatin1String("telepathyInfo"), KNotification::CloseOnTimeout);
}
KAboutData aboutData("ktelepathy",0,KLocalizedString(),0);
notification->setComponentData(KComponentData(aboutData));
notification->setText(text);
notification->sendEvent();
}
void ErrorHandler::onNewAccount(const Tp::AccountPtr& account)
{
connect(account.data(), SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)),
this, SLOT(onConnectionStatusChanged(Tp::ConnectionStatus)));
}
<|endoftext|>
|
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_filter.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_HPP
#define FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_HPP
#include <fl/filter/gaussian/transform/unscented_transform.hpp>
#include <fl/filter/gaussian/transform/monte_carlo_transform.hpp>
#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>
#include <fl/filter/gaussian/gaussian_filter_kf.hpp>
#include <fl/filter/gaussian/gaussian_filter_spkf.hpp>
#endif
<commit_msg>added unscented_quadrature header<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_filter.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_HPP
#define FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_HPP
#include <fl/filter/gaussian/transform/unscented_transform.hpp>
#include <fl/filter/gaussian/transform/monte_carlo_transform.hpp>
#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>
#include <fl/filter/gaussian/quadrature/unscented_quadrature.hpp>
#include <fl/filter/gaussian/gaussian_filter_kf.hpp>
#include <fl/filter/gaussian/gaussian_filter_spkf.hpp>
#endif
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MVS_HASH_NUMBER_HPP
#define MVS_HASH_NUMBER_HPP
#include <cstddef>
#include <metaverse/bitcoin/define.hpp>
#include <metaverse/bitcoin/math/hash.hpp>
#include <metaverse/bitcoin/math/uint256.hpp>
namespace libbitcoin {
/**
* Represents a target hash or proof of work sum.
* Used for block proof of works to calculate whether they reach
* a certain target or which chain is longest.
*/
class hash_number
{
public:
BC_API hash_number();
BC_API hash_number(uint64_t value);
// Returns false if negative or overflowed.
BC_API bool set_compact(uint32_t compact);
BC_API uint32_t compact() const;
BC_API void set_hash(const hash_digest& hash);
BC_API hash_digest hash() const;
BC_API const hash_number operator~() const;
// int64_t resolves to this in Satoshi's GetNextWorkRequired()
BC_API hash_number& operator*=(uint32_t value);
BC_API hash_number& operator/=(uint32_t value);
BC_API hash_number& operator<<=(uint32_t shift);
BC_API hash_number& operator/=(const hash_number& number_b);
BC_API hash_number& operator+=(const hash_number& number_b);
private:
friend bool operator>(
const hash_number& number_a, const hash_number& number_b);
friend bool operator<=(
const hash_number& number_a, const hash_number& number_b);
friend const hash_number operator<<(
const hash_number& number_a, int shift);
friend const hash_number operator/(
const hash_number& number_a, const hash_number& number_b);
friend const hash_number operator+(
const hash_number& number_a, const hash_number& number_b);
friend bool operator==(
const hash_number& number, uint64_t value);
uint256_t hash_;
};
BC_API bool operator>(
const hash_number& number_a, const hash_number& number_b);
BC_API bool operator<=(
const hash_number& number_a, const hash_number& number_b);
BC_API const hash_number operator<<(
const hash_number& number_a, int shift);
BC_API const hash_number operator/(
const hash_number& number_a, const hash_number& number_b);
BC_API const hash_number operator+(
const hash_number& number_a, const hash_number& number_b);
BC_API bool operator==(
const hash_number& number, uint64_t value);
} // namespace libbitcoin
#endif
<commit_msg>fix windows compile error<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MVS_HASH_NUMBER_HPP
#define MVS_HASH_NUMBER_HPP
#include <cstddef>
#include <metaverse/bitcoin/define.hpp>
#include <metaverse/bitcoin/math/hash.hpp>
#include <metaverse/bitcoin/math/uint256.hpp>
namespace libbitcoin {
/**
* Represents a target hash or proof of work sum.
* Used for block proof of works to calculate whether they reach
* a certain target or which chain is longest.
*/
class BC_API hash_number
{
public:
hash_number();
hash_number(uint64_t value);
// Returns false if negative or overflowed.
bool set_compact(uint32_t compact);
uint32_t compact() const;
void set_hash(const hash_digest& hash);
hash_digest hash() const;
const hash_number operator~() const;
// int64_t resolves to this in Satoshi's GetNextWorkRequired()
hash_number& operator*=(uint32_t value);
hash_number& operator/=(uint32_t value);
hash_number& operator<<=(uint32_t shift);
hash_number& operator/=(const hash_number& number_b);
hash_number& operator+=(const hash_number& number_b);
private:
friend bool operator>(
const hash_number& number_a, const hash_number& number_b);
friend bool operator<=(
const hash_number& number_a, const hash_number& number_b);
friend const hash_number operator<<(
const hash_number& number_a, int shift);
friend const hash_number operator/(
const hash_number& number_a, const hash_number& number_b);
friend const hash_number operator+(
const hash_number& number_a, const hash_number& number_b);
friend bool operator==(
const hash_number& number, uint64_t value);
uint256_t hash_;
};
} // namespace libbitcoin
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "RequiredPlugin.h"
#include <sofa/core/ObjectFactory.h>
#include <sofa/helper/system/PluginManager.h>
namespace sofa
{
namespace component
{
namespace misc
{
SOFA_DECL_CLASS(RequiredPlugin)
int RequiredPluginClass = core::RegisterObject("Load required plugin")
.add< RequiredPlugin >();
RequiredPlugin::RequiredPlugin()
: pluginName( initData(&pluginName, "pluginName", "plugin name"))
{
this->f_printLog.setValue(true); // print log by default, to identify which pluging is responsible in case of a crash during loading
}
void RequiredPlugin::parse(sofa::core::objectmodel::BaseObjectDescription* arg)
{
Inherit1::parse(arg);
if (!pluginName.getValue().empty())
loadPlugin();
}
void RequiredPlugin::loadPlugin()
{
std::string pluginPath = pluginName.getValue();
sout << "Loading " << pluginPath << sendl;
if (sofa::helper::system::PluginManager::getInstance().loadPlugin(pluginPath))
{
sout << "Loaded " << pluginPath << sendl;
sofa::helper::system::PluginManager::getInstance().init();
}
}
}
}
}
<commit_msg>r9793/sofa : Plugin: try to automatically load an eventual plugin's gui, named mypluginname_gui. Note : A plugin GUI must be compiled in another .so, not to link the "pure" plugin library with Qt (so the plugin can be used with another Software that does not use Qt or another version...)<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "RequiredPlugin.h"
#include <sofa/core/ObjectFactory.h>
#include <sofa/helper/system/PluginManager.h>
namespace sofa
{
namespace component
{
namespace misc
{
SOFA_DECL_CLASS(RequiredPlugin)
int RequiredPluginClass = core::RegisterObject("Load required plugin")
.add< RequiredPlugin >();
RequiredPlugin::RequiredPlugin()
: pluginName( initData(&pluginName, "pluginName", "plugin name"))
{
this->f_printLog.setValue(true); // print log by default, to identify which pluging is responsible in case of a crash during loading
}
void RequiredPlugin::parse(sofa::core::objectmodel::BaseObjectDescription* arg)
{
Inherit1::parse(arg);
if (!pluginName.getValue().empty())
loadPlugin();
}
void RequiredPlugin::loadPlugin()
{
std::string pluginPath = pluginName.getValue();
sout << "Loading " << pluginPath << sendl;
if (sofa::helper::system::PluginManager::getInstance().loadPlugin(pluginPath))
{
sout << "Loaded " << pluginPath << sendl;
sofa::helper::system::PluginManager::getInstance().init();
}
// try to load the eventual plugin gui
pluginPath = pluginName.getValue() + "_gui";
if (sofa::helper::system::PluginManager::getInstance().loadPlugin(pluginPath))
{
sout << "Loaded " << pluginPath << sendl;
sofa::helper::system::PluginManager::getInstance().init();
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
This software allows for filtering in high-dimensional measurement and
state spaces, as described in
M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013
In a publication based on this software pleace cite the above reference.
Copyright (C) 2014 Manuel Wuthrich
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/
#ifndef ROBOT_STATE_HPP_
#define ROBOT_STATE_HPP_
#include <state_filtering/states/rigid_body_system.hpp>
#include <state_filtering/utils/macros.hpp>
#include <state_filtering/utils/kinematics_from_urdf.hpp>
#include <Eigen/Dense>
#include <boost/static_assert.hpp>
#include <vector>
template<int size_joints>
struct RobotStateTypes
{
enum
{
// For the joints
COUNT_PER_JOINT = 1,
JOINT_ANGLE_INDEX = 0,
//JOINT_VELOCITY_INDEX = 1,
// TODO: Check if obsolete
// for the links
COUNT_PER_BODY = 12,
BLOCK_COUNT = 3,
POSITION_INDEX = 0,
ORIENTATION_INDEX = 3,
LINEAR_VELOCITY_INDEX = 6,
ANGULAR_VELOCITY_INDEX = 9,
};
typedef RigidBodySystem<size_joints == -1 ? -1 : size_joints * COUNT_PER_JOINT> Base;
};
template<int size_joints = -1, int size_bodies = -1>
class RobotState: public RobotStateTypes<size_joints>::Base
{
public:
typedef RobotStateTypes<size_joints> Types;
typedef typename Types::Base Base;
typedef typename Base::Scalar Scalar;
typedef typename Base::State State;
typedef typename Base::Vector Vector;
typedef typename Base::AngleAxis AngleAxis;
typedef typename Base::Quaternion Quaternion;
typedef typename Base::RotationMatrix RotationMatrix;
typedef typename Base::HomogeneousMatrix HomogeneousMatrix;
enum
{
// for the joints
SIZE_JOINTS = size_joints,
COUNT_PER_JOINT = Types::COUNT_PER_JOINT,
JOINT_ANGLE_INDEX = Types::JOINT_ANGLE_INDEX,
//JOINT_VELOCITY_INDEX = Types::JOINT_VELOCITY_INDEX,
// For the links
SIZE_BODIES = size_bodies,
SIZE_STATE = Base::SIZE_STATE,
COUNT_PER_BODY = Types::COUNT_PER_BODY,
BLOCK_COUNT = Types::BLOCK_COUNT,
POSITION_INDEX = Types::POSITION_INDEX,
ORIENTATION_INDEX = Types::ORIENTATION_INDEX,
LINEAR_VELOCITY_INDEX = Types::LINEAR_VELOCITY_INDEX,
ANGULAR_VELOCITY_INDEX = Types::ANGULAR_VELOCITY_INDEX,
};
// give access to base member functions (otherwise it is shadowed)
//using Base::quaternion;
//using Base::state_size;
//TODO: SHOULD THIS BE ALLOWED?
using Base::operator=;
RobotState(): Base(State::Zero(0)),
initialized_(false) { }
// constructor for dynamic size without initial value
// TODO: COULD WE GET THE NUMBER OF BODIES AND THE NUMBER OF JOINTS FROM THE KINEMATICS?
RobotState(unsigned num_bodies,
unsigned num_joints,
const boost::shared_ptr<KinematicsFromURDF> &kinematics_ptr): Base(State::Zero(num_joints * COUNT_PER_JOINT)),
num_bodies_(num_bodies),
num_joints_(num_joints),
kinematics_(kinematics_ptr),
initialized_(true)
{
joint_map_ = kinematics_->GetJointMap();
}
// constructor with initial value
template <typename T> RobotState(const Eigen::MatrixBase<T>& state_vector):
Base(state_vector),
num_joints_(state_vector.rows()/COUNT_PER_JOINT)
{ }
virtual ~RobotState() {}
virtual void update() const
{
CheckInitialization();
kinematics_->InitKDLData(*this);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// these are the two main functions which have to implement the robot state.
/// here it simply accesses the eigen vector, from which the class is derived and returns the correct
/// part of the vector, since it directly encodes the pose of the object. for the robot arm this will
/// be a bit more complicated, since the eigen vector will contain the joint angles, and we will have
/// to compute the pose of the link from the joint angles.
// this returns the position (translation) part of the pose of the link.
virtual Vector position(const size_t& object_index = 0) const
{
CheckInitialization();
return kinematics_->GetLinkPosition(object_index);
}
// this returns the orientation part of the pose of the link. the format is euler vector, the norm of the vector is the
// angle, and the direction is the rotation axis. below there is a function that converts from Quaternion2EulerVector
// which implements the transformation
virtual Vector euler_vector(const size_t& object_index = 0) const
{
CheckInitialization();
return Quaternion2EulerVector(kinematics_->GetLinkOrientation(object_index));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual Vector Quaternion2EulerVector(const Quaternion& quaternion) const
{
AngleAxis angle_axis(quaternion);
return angle_axis.angle()*angle_axis.axis();
}
virtual unsigned bodies_size() const
{
CheckInitialization();
return num_bodies_;
}
virtual unsigned joints_size() const
{
CheckInitialization();
return num_joints_;
}
void GetJointState(std::map<std::string, double>& joint_positions)
{
CheckInitialization();
for(std::vector<std::string>::const_iterator it = joint_map_.begin();
it != joint_map_.end(); ++it)
{
joint_positions[*it] = (*this)(it - joint_map_.begin(),0);
}
}
private:
void CheckInitialization() const
{
if(!initialized_)
{
std::cout << "the kinematics were not passed in the constructor of robot state " << std::endl;
exit(-1);
}
}
bool initialized_;
unsigned num_bodies_;
unsigned num_joints_;
std::vector<std::string> joint_map_;
// pointer to the robot kinematic
boost::shared_ptr<KinematicsFromURDF> kinematics_;
template <bool dummy> void assert_fixed_size() const {BOOST_STATIC_ASSERT(size_joints > -1);}
template <bool dummy> void assert_dynamic_size() const {BOOST_STATIC_ASSERT(size_joints == -1);}
};
#endif
<commit_msg>added more explicit debug output in case of failure<commit_after>/*************************************************************************
This software allows for filtering in high-dimensional measurement and
state spaces, as described in
M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013
In a publication based on this software pleace cite the above reference.
Copyright (C) 2014 Manuel Wuthrich
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/
#ifndef ROBOT_STATE_HPP_
#define ROBOT_STATE_HPP_
#include <state_filtering/states/rigid_body_system.hpp>
#include <state_filtering/utils/macros.hpp>
#include <state_filtering/utils/kinematics_from_urdf.hpp>
#include <Eigen/Dense>
#include <boost/static_assert.hpp>
#include <vector>
template<int size_joints>
struct RobotStateTypes
{
enum
{
// For the joints
COUNT_PER_JOINT = 1,
JOINT_ANGLE_INDEX = 0,
//JOINT_VELOCITY_INDEX = 1,
// TODO: Check if obsolete
// for the links
COUNT_PER_BODY = 12,
BLOCK_COUNT = 3,
POSITION_INDEX = 0,
ORIENTATION_INDEX = 3,
LINEAR_VELOCITY_INDEX = 6,
ANGULAR_VELOCITY_INDEX = 9,
};
typedef RigidBodySystem<size_joints == -1 ? -1 : size_joints * COUNT_PER_JOINT> Base;
};
template<int size_joints = -1, int size_bodies = -1>
class RobotState: public RobotStateTypes<size_joints>::Base
{
public:
typedef RobotStateTypes<size_joints> Types;
typedef typename Types::Base Base;
typedef typename Base::Scalar Scalar;
typedef typename Base::State State;
typedef typename Base::Vector Vector;
typedef typename Base::AngleAxis AngleAxis;
typedef typename Base::Quaternion Quaternion;
typedef typename Base::RotationMatrix RotationMatrix;
typedef typename Base::HomogeneousMatrix HomogeneousMatrix;
enum
{
// for the joints
SIZE_JOINTS = size_joints,
COUNT_PER_JOINT = Types::COUNT_PER_JOINT,
JOINT_ANGLE_INDEX = Types::JOINT_ANGLE_INDEX,
//JOINT_VELOCITY_INDEX = Types::JOINT_VELOCITY_INDEX,
// For the links
SIZE_BODIES = size_bodies,
SIZE_STATE = Base::SIZE_STATE,
COUNT_PER_BODY = Types::COUNT_PER_BODY,
BLOCK_COUNT = Types::BLOCK_COUNT,
POSITION_INDEX = Types::POSITION_INDEX,
ORIENTATION_INDEX = Types::ORIENTATION_INDEX,
LINEAR_VELOCITY_INDEX = Types::LINEAR_VELOCITY_INDEX,
ANGULAR_VELOCITY_INDEX = Types::ANGULAR_VELOCITY_INDEX,
};
// give access to base member functions (otherwise it is shadowed)
//using Base::quaternion;
//using Base::state_size;
//TODO: SHOULD THIS BE ALLOWED?
using Base::operator=;
RobotState(): Base(State::Zero(0)),
initialized_(false) { }
// constructor for dynamic size without initial value
// TODO: COULD WE GET THE NUMBER OF BODIES AND THE NUMBER OF JOINTS FROM THE KINEMATICS?
RobotState(unsigned num_bodies,
unsigned num_joints,
const boost::shared_ptr<KinematicsFromURDF> &kinematics_ptr): Base(State::Zero(num_joints * COUNT_PER_JOINT)),
num_bodies_(num_bodies),
num_joints_(num_joints),
kinematics_(kinematics_ptr),
initialized_(true)
{
joint_map_ = kinematics_->GetJointMap();
}
// constructor with initial value
template <typename T> RobotState(const Eigen::MatrixBase<T>& state_vector):
Base(state_vector),
num_joints_(state_vector.rows()/COUNT_PER_JOINT)
{ }
virtual ~RobotState() {}
virtual void update() const
{
CheckInitialization("update");
kinematics_->InitKDLData(*this);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// these are the two main functions which have to implement the robot state.
/// here it simply accesses the eigen vector, from which the class is derived and returns the correct
/// part of the vector, since it directly encodes the pose of the object. for the robot arm this will
/// be a bit more complicated, since the eigen vector will contain the joint angles, and we will have
/// to compute the pose of the link from the joint angles.
// this returns the position (translation) part of the pose of the link.
virtual Vector position(const size_t& object_index = 0) const
{
CheckInitialization("position");
return kinematics_->GetLinkPosition(object_index);
}
// this returns the orientation part of the pose of the link. the format is euler vector, the norm of the vector is the
// angle, and the direction is the rotation axis. below there is a function that converts from Quaternion2EulerVector
// which implements the transformation
virtual Vector euler_vector(const size_t& object_index = 0) const
{
CheckInitialization("euler_vector");
return Quaternion2EulerVector(kinematics_->GetLinkOrientation(object_index));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual Vector Quaternion2EulerVector(const Quaternion& quaternion) const
{
AngleAxis angle_axis(quaternion);
return angle_axis.angle()*angle_axis.axis();
}
virtual unsigned bodies_size() const
{
CheckInitialization("bodies_size");
return num_bodies_;
}
virtual unsigned joints_size() const
{
CheckInitialization("joints_size");
return num_joints_;
}
void GetJointState(std::map<std::string, double>& joint_positions)
{
CheckInitialization("GetJointState");
for(std::vector<std::string>::const_iterator it = joint_map_.begin();
it != joint_map_.end(); ++it)
{
joint_positions[*it] = (*this)(it - joint_map_.begin(),0);
}
}
private:
void CheckInitialization(const std::string &func) const
{
if(!initialized_)
{
std::cout << func << " the kinematics were not passed in the constructor of robot state " << std::endl;
exit(-1);
}
}
bool initialized_;
unsigned num_bodies_;
unsigned num_joints_;
std::vector<std::string> joint_map_;
// pointer to the robot kinematic
boost::shared_ptr<KinematicsFromURDF> kinematics_;
template <bool dummy> void assert_fixed_size() const {BOOST_STATIC_ASSERT(size_joints > -1);}
template <bool dummy> void assert_dynamic_size() const {BOOST_STATIC_ASSERT(size_joints == -1);}
};
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include "mmu.h"
#include <atomic>
#include "spinlock.h"
using std::atomic;
// Per-CPU state
struct cpu {
cpuid_t id; // Index into cpus[] below
int ncli; // Depth of pushcli nesting.
int intena; // Were interrupts enabled before pushcli?
struct segdesc gdt[NSEGS]; // x86 global descriptor table
struct taskstate ts; // Used by x86 to find stack for interrupt
struct context *scheduler; // swtch() here to enter scheduler
int timer_printpc;
atomic<u64> tlbflush_done; // last tlb flush req done on this cpu
atomic<u64> tlb_cr3; // current value of cr3 on this cpu
struct proc *prev; // The previously-running process
atomic<struct proc*> fpu_owner; // The proc with the current FPU state
struct numa_node *node;
// The list of IPI calls to this CPU
atomic<struct ipi_call *> ipi __mpalign__;
atomic<struct ipi_call *> *ipi_tail;
// The lock protecting updates to ipi and ipi_tail.
spinlock ipi_lock;
hwid_t hwid __mpalign__; // Local APIC ID, accessed by other CPUs
// Cpu-local storage variables; see below
struct cpu *cpu;
struct proc *proc; // The currently-running process.
struct cpu_mem *mem; // The per-core memory metadata
u64 syscallno; // Temporary used by sysentry
struct kstats *kstats;
} __mpalign__;
extern struct cpu cpus[NCPU];
// Per-CPU variables, holding pointers to the
// current cpu and to the current process.
// XXX(sbw) asm labels default to RIP-relative and
// I don't know how to force absolute addressing.
static inline struct cpu *
mycpu(void)
{
u64 val;
__asm volatile("movq %%gs:0, %0" : "=r" (val));
return (struct cpu *)val;
}
static inline struct proc *
myproc(void)
{
u64 val;
__asm volatile("movq %%gs:8, %0" : "=r" (val));
return (struct proc *)val;
}
static inline struct kmem *
mykmem(void)
{
u64 val;
__asm volatile("movq %%gs:16, %0" : "=r" (val));
return (struct kmem *)val;
}
static inline struct kstats *
mykstats(void)
{
u64 val;
__asm volatile("movq %%gs:(8*4), %0" : "=r" (val));
return (struct kstats *)val;
}
static inline cpuid_t
myid(void)
{
return mycpu()->id;
}
<commit_msg>More cache line padding in struct cpu<commit_after>#pragma once
#include "mmu.h"
#include <atomic>
#include "spinlock.h"
using std::atomic;
// Per-CPU state
struct cpu {
cpuid_t id; // Index into cpus[] below
int ncli; // Depth of pushcli nesting.
int intena; // Were interrupts enabled before pushcli?
struct segdesc gdt[NSEGS]; // x86 global descriptor table
struct taskstate ts; // Used by x86 to find stack for interrupt
struct context *scheduler; // swtch() here to enter scheduler
int timer_printpc;
__mpalign__
atomic<u64> tlbflush_done; // last tlb flush req done on this cpu
__padout__;
atomic<u64> tlb_cr3; // current value of cr3 on this cpu
struct proc *prev; // The previously-running process
atomic<struct proc*> fpu_owner; // The proc with the current FPU state
struct numa_node *node;
// The list of IPI calls to this CPU
__mpalign__
atomic<struct ipi_call *> ipi __mpalign__;
atomic<struct ipi_call *> *ipi_tail;
// The lock protecting updates to ipi and ipi_tail.
spinlock ipi_lock;
__padout__;
hwid_t hwid __mpalign__; // Local APIC ID, accessed by other CPUs
__padout__;
// Cpu-local storage variables; see below
struct cpu *cpu;
struct proc *proc; // The currently-running process.
struct cpu_mem *mem; // The per-core memory metadata
u64 syscallno; // Temporary used by sysentry
struct kstats *kstats;
} __mpalign__;
extern struct cpu cpus[NCPU];
// Per-CPU variables, holding pointers to the
// current cpu and to the current process.
// XXX(sbw) asm labels default to RIP-relative and
// I don't know how to force absolute addressing.
static inline struct cpu *
mycpu(void)
{
u64 val;
__asm volatile("movq %%gs:0, %0" : "=r" (val));
return (struct cpu *)val;
}
static inline struct proc *
myproc(void)
{
u64 val;
__asm volatile("movq %%gs:8, %0" : "=r" (val));
return (struct proc *)val;
}
static inline struct kmem *
mykmem(void)
{
u64 val;
__asm volatile("movq %%gs:16, %0" : "=r" (val));
return (struct kmem *)val;
}
static inline struct kstats *
mykstats(void)
{
u64 val;
__asm volatile("movq %%gs:(8*4), %0" : "=r" (val));
return (struct kstats *)val;
}
static inline cpuid_t
myid(void)
{
return mycpu()->id;
}
<|endoftext|>
|
<commit_before>#include "Main.h"
//获取基本信息
void handlerGetDeviceBaseInfo(struct bufferevent * bufEvent,Json::Value &data){
char buffer[100];
//获取内存大小
struct sysinfo memInfo;
sysinfo(&memInfo);
//获取磁盘大小
struct statfs diskInfo;
statfs(DISK_SIZE_PATH, &diskInfo);
//格式化数据
double totalMemSize = (double)memInfo.totalram/(1024.0*1024.0);
double usedMemSize = (double)(memInfo.totalram-memInfo.freeram)/(1024.0*1024.0);
double totalDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks)/(1024.0*1024.0);
double usedDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks-diskInfo.f_bsize*diskInfo.f_bfree)/(1024.0*1024.0);
//构造返回JSON
Json::Value root;
Json::Value re_data;
root["is_app"] = false;
root["protocol"] = API_DEVICE_BASE_INFO;
//总内存大小
sprintf(buffer,"%.2f",totalMemSize);
re_data["mem_total"] = string(buffer);
memset(buffer,0,100);
//使用内存
sprintf(buffer,"%.2f",usedMemSize);
re_data["mem_used"] = string(buffer);
memset(buffer,0,100);
//总硬盘大小
sprintf(buffer,"%.2f",totalDiskSize);
re_data["disk_total"] = string(buffer);
memset(buffer,0,100);
//使用硬盘大小
sprintf(buffer,"%.2f",usedDiskSize);
re_data["disk_used"] = string(buffer);
memset(buffer,0,100);
//返回数据
root["data"] = re_data;
bufferevent_write(bufEvent, root.toStyledString().c_str(), root.toStyledString().length());
}
//键盘按下
void handlerKeyDown(struct bufferevent * bufEvent,Json::Value &data){
Json::Value key_map = data["data"];
string key = key_map["key"].toStyledString();
if(key.compare("119") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("115") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("97") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("100") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("105") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("107") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("106") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("108") == 0){
printf("key down:%s\n", key.c_str());
}else{
printf("key not find:%s\n", key.c_str());
}
}
//获取MAC地址
string getMacAddress(){
char buff[32];
memset (buff ,'\0', sizeof(buff));
string cmd = "ip addr |grep -A 2 "+network_card_name+" | awk 'NR>1'|awk 'NR<2'|awk '{print $2}'";
// 通过管道来回去系统命令返回的值
FILE *fstream = popen(cmd.c_str(), "r");
if(fstream == NULL) {
perror("popen");
exit(0);
}
if(NULL == fgets(buff, sizeof(buff), fstream)){
printf("not find mac address !!!\n");
exit(0);
}
pclose(fstream);
string mac;
mac = string(buff);
mac = mac.substr(0, mac.length()-1);
return mac;
}
//调用方法
void callFunc(struct bufferevent * bufEvent,Json::Value &request_data,const string func){
if(func.length() == 0){
return;
}
if (client_api_list.count(func)) {
(*(client_api_list[func]))(bufEvent,request_data);
}
}
void sendDeviceInfo(struct bufferevent * bufEvent){
Json::Value root;
Json::Value data;
//获取MAC地址
data["mac"] = getMacAddress();
data["name"] = device_name;
root["protocol"] = API_DEVICE_INFO;
root["is_app"] = false;
root["data"] = data;
string json = root.toStyledString();
bufferevent_write(bufEvent, json.c_str(), json.length());
}
//读操作
void ReadEventCb(struct bufferevent *bufEvent, void *args){
Json::Reader reader;
Json::Value data;
//获取输入缓存
struct evbuffer * pInput = bufferevent_get_input(bufEvent);
//获取输入缓存数据的长度
int len = evbuffer_get_length(pInput);
//获取数据
char* body = new char[len+1];
memset(body,0,sizeof(char)*(len+1));
evbuffer_remove(pInput, body, len);
if(reader.parse(body, data)){
string func = data["protocol"].asString();
callFunc(bufEvent,data,func);
}
delete[] body;
return ;
}
//写操作
void WriteEventCb(struct bufferevent *bufEvent, void *args){
}
//关闭
void SignalEventCb(struct bufferevent * bufEvent, short sEvent, void * args){
//请求的连接过程已经完成
if(BEV_EVENT_CONNECTED == sEvent){
bufferevent_enable(bufEvent, EV_READ);
//设置读超时时间 10s
struct timeval tTimeout = {10, 0};
bufferevent_set_timeouts( bufEvent, &tTimeout, NULL);
string mac = getMacAddress();
if(mac.length() == 0){
printf("MAC地址获取错误请检查网卡配置\n");
event_base_loopexit(baseEvent, NULL);
exit(0);
}
//发送基本信息
sendDeviceInfo(bufEvent);
}
//写操作发生事件
if(BEV_EVENT_WRITING & sEvent){}
//操作时发生错误
if (sEvent & BEV_EVENT_ERROR){
perror("event");
event_base_loopexit(baseEvent, NULL);
}
//结束指示
if (sEvent & BEV_EVENT_EOF){
perror("event");
event_base_loopexit(baseEvent, NULL);
}
//读取发生事件或者超时处理
if(0 != (sEvent & (BEV_EVENT_TIMEOUT|BEV_EVENT_READING)) ){
//发送心跳包
//
//重新注册可读事件
bufferevent_enable(bufEvent, EV_READ);
}
return ;
}
//设置配置文件
void setConfig(const char* config_path){
Config config;
//检测配置文件是否存在
if(!config.FileExist(config_path)){
printf("config: not find config file\n");
exit(0);
}
//读取配置
config.ReadFile(config_path);
api_host = config.Read("SERVER_HOST", api_host);
api_port = config.Read("API_PORT", api_port);
network_card_name = config.Read("NETWORK_CARD", network_card_name);
device_name = config.Read("DEVICE_NAME", device_name);
}
//开始
void startRun(const char* ip,int port){
//创建事件驱动句柄
baseEvent = event_base_new();
//创建socket类型的bufferevent
struct bufferevent* bufferEvent = bufferevent_socket_new(baseEvent, -1, 0);
//构造服务器地址
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(api_host.c_str());
sin.sin_port = htons(api_port);
//连接服务器
if( bufferevent_socket_connect(bufferEvent, (struct sockaddr*)&sin, sizeof(sin)) < 0){
perror("socket");
return;
}
//设置回调函数, 及回调函数的参数
bufferevent_setcb(bufferEvent, ReadEventCb, WriteEventCb, SignalEventCb,NULL);
//开始事件循环
event_base_dispatch(baseEvent);
//事件循环结束 资源清理
bufferevent_free(bufferEvent);
event_base_free(baseEvent);
}
//初始化API列表
void initApiList() {
client_api_list[API_DEVICE_BASE_INFO] = &handlerGetDeviceBaseInfo;
client_api_list[API_DEVICE_KEY_DOWN] = &handlerKeyDown;
}
int main(){
//加载API列表
initApiList();
//加载配置文件
setConfig(CONFIG_PATH);
//启动sockt
startRun(api_host.c_str(),api_port);
return 0;
}
<commit_msg>String to int<commit_after>#include "Main.h"
//获取基本信息
void handlerGetDeviceBaseInfo(struct bufferevent * bufEvent,Json::Value &data){
char buffer[100];
//获取内存大小
struct sysinfo memInfo;
sysinfo(&memInfo);
//获取磁盘大小
struct statfs diskInfo;
statfs(DISK_SIZE_PATH, &diskInfo);
//格式化数据
double totalMemSize = (double)memInfo.totalram/(1024.0*1024.0);
double usedMemSize = (double)(memInfo.totalram-memInfo.freeram)/(1024.0*1024.0);
double totalDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks)/(1024.0*1024.0);
double usedDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks-diskInfo.f_bsize*diskInfo.f_bfree)/(1024.0*1024.0);
//构造返回JSON
Json::Value root;
Json::Value re_data;
root["is_app"] = false;
root["protocol"] = API_DEVICE_BASE_INFO;
//总内存大小
sprintf(buffer,"%.2f",totalMemSize);
re_data["mem_total"] = string(buffer);
memset(buffer,0,100);
//使用内存
sprintf(buffer,"%.2f",usedMemSize);
re_data["mem_used"] = string(buffer);
memset(buffer,0,100);
//总硬盘大小
sprintf(buffer,"%.2f",totalDiskSize);
re_data["disk_total"] = string(buffer);
memset(buffer,0,100);
//使用硬盘大小
sprintf(buffer,"%.2f",usedDiskSize);
re_data["disk_used"] = string(buffer);
memset(buffer,0,100);
//返回数据
root["data"] = re_data;
bufferevent_write(bufEvent, root.toStyledString().c_str(), root.toStyledString().length());
}
//键盘按下
void handlerKeyDown(struct bufferevent * bufEvent,Json::Value &data){
Json::Value key_map = data["data"];
string key = key_map["key"].toStyledString();
if(strcmp(key.c_str(),"119") == 0){
printf("key down:%s\n", key.c_str());
}else if(strcmp(key.c_str(),"115")== 0){
printf("key down:%s\n", key.c_str());
}else if(strcmp(key.c_str(),"97") == 0){
printf("key down:%s\n", key.c_str());
}else if(strcmp(key.c_str(),"100") == 0){
printf("key down:%s\n", key.c_str());
}else if(strcmp(key.c_str(),"105") == 0){
printf("key down:%s\n", key.c_str());
}else if(strcmp(key.c_str(),"107") == 0){
printf("key down:%s\n", key.c_str());
}else if(strcmp(key.c_str(),"106") == 0){
printf("key down:%s\n", key.c_str());
}else if(strcmp(key.c_str(),"108") == 0){
printf("key down:%s\n", key.c_str());
}else{
printf("key not find:%s\n", key.c_str());
}
}
//获取MAC地址
string getMacAddress(){
char buff[32];
memset (buff ,'\0', sizeof(buff));
string cmd = "ip addr |grep -A 2 "+network_card_name+" | awk 'NR>1'|awk 'NR<2'|awk '{print $2}'";
// 通过管道来回去系统命令返回的值
FILE *fstream = popen(cmd.c_str(), "r");
if(fstream == NULL) {
perror("popen");
exit(0);
}
if(NULL == fgets(buff, sizeof(buff), fstream)){
printf("not find mac address !!!\n");
exit(0);
}
pclose(fstream);
string mac;
mac = string(buff);
mac = mac.substr(0, mac.length()-1);
return mac;
}
//调用方法
void callFunc(struct bufferevent * bufEvent,Json::Value &request_data,const string func){
if(func.length() == 0){
return;
}
if (client_api_list.count(func)) {
(*(client_api_list[func]))(bufEvent,request_data);
}
}
void sendDeviceInfo(struct bufferevent * bufEvent){
Json::Value root;
Json::Value data;
//获取MAC地址
data["mac"] = getMacAddress();
data["name"] = device_name;
root["protocol"] = API_DEVICE_INFO;
root["is_app"] = false;
root["data"] = data;
string json = root.toStyledString();
bufferevent_write(bufEvent, json.c_str(), json.length());
}
//读操作
void ReadEventCb(struct bufferevent *bufEvent, void *args){
Json::Reader reader;
Json::Value data;
//获取输入缓存
struct evbuffer * pInput = bufferevent_get_input(bufEvent);
//获取输入缓存数据的长度
int len = evbuffer_get_length(pInput);
//获取数据
char* body = new char[len+1];
memset(body,0,sizeof(char)*(len+1));
evbuffer_remove(pInput, body, len);
if(reader.parse(body, data)){
string func = data["protocol"].asString();
callFunc(bufEvent,data,func);
}
delete[] body;
return ;
}
//写操作
void WriteEventCb(struct bufferevent *bufEvent, void *args){
}
//关闭
void SignalEventCb(struct bufferevent * bufEvent, short sEvent, void * args){
//请求的连接过程已经完成
if(BEV_EVENT_CONNECTED == sEvent){
bufferevent_enable(bufEvent, EV_READ);
//设置读超时时间 10s
struct timeval tTimeout = {10, 0};
bufferevent_set_timeouts( bufEvent, &tTimeout, NULL);
string mac = getMacAddress();
if(mac.length() == 0){
printf("MAC地址获取错误请检查网卡配置\n");
event_base_loopexit(baseEvent, NULL);
exit(0);
}
//发送基本信息
sendDeviceInfo(bufEvent);
}
//写操作发生事件
if(BEV_EVENT_WRITING & sEvent){}
//操作时发生错误
if (sEvent & BEV_EVENT_ERROR){
perror("event");
event_base_loopexit(baseEvent, NULL);
}
//结束指示
if (sEvent & BEV_EVENT_EOF){
perror("event");
event_base_loopexit(baseEvent, NULL);
}
//读取发生事件或者超时处理
if(0 != (sEvent & (BEV_EVENT_TIMEOUT|BEV_EVENT_READING)) ){
//发送心跳包
//
//重新注册可读事件
bufferevent_enable(bufEvent, EV_READ);
}
return ;
}
//设置配置文件
void setConfig(const char* config_path){
Config config;
//检测配置文件是否存在
if(!config.FileExist(config_path)){
printf("config: not find config file\n");
exit(0);
}
//读取配置
config.ReadFile(config_path);
api_host = config.Read("SERVER_HOST", api_host);
api_port = config.Read("API_PORT", api_port);
network_card_name = config.Read("NETWORK_CARD", network_card_name);
device_name = config.Read("DEVICE_NAME", device_name);
}
//开始
void startRun(const char* ip,int port){
//创建事件驱动句柄
baseEvent = event_base_new();
//创建socket类型的bufferevent
struct bufferevent* bufferEvent = bufferevent_socket_new(baseEvent, -1, 0);
//构造服务器地址
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(api_host.c_str());
sin.sin_port = htons(api_port);
//连接服务器
if( bufferevent_socket_connect(bufferEvent, (struct sockaddr*)&sin, sizeof(sin)) < 0){
perror("socket");
return;
}
//设置回调函数, 及回调函数的参数
bufferevent_setcb(bufferEvent, ReadEventCb, WriteEventCb, SignalEventCb,NULL);
//开始事件循环
event_base_dispatch(baseEvent);
//事件循环结束 资源清理
bufferevent_free(bufferEvent);
event_base_free(baseEvent);
}
//初始化API列表
void initApiList() {
client_api_list[API_DEVICE_BASE_INFO] = &handlerGetDeviceBaseInfo;
client_api_list[API_DEVICE_KEY_DOWN] = &handlerKeyDown;
}
int main(){
//加载API列表
initApiList();
//加载配置文件
setConfig(CONFIG_PATH);
//启动sockt
startRun(api_host.c_str(),api_port);
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file llfloaterconversationpreview.cpp
*
* $LicenseInfo:firstyear=2012&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llconversationlog.h"
#include "llfloaterconversationpreview.h"
#include "llimview.h"
#include "lllineeditor.h"
#include "llfloaterimnearbychat.h"
#include "llspinctrl.h"
#include "lltrans.h"
const std::string LL_FCP_COMPLETE_NAME("complete_name");
const std::string LL_FCP_ACCOUNT_NAME("user_name");
LLFloaterConversationPreview::LLFloaterConversationPreview(const LLSD& session_id)
: LLFloater(session_id),
mChatHistory(NULL),
mSessionID(session_id.asUUID()),
mCurrentPage(0),
mPageSize(gSavedSettings.getS32("ConversationHistoryPageSize")),
mAccountName(session_id[LL_FCP_ACCOUNT_NAME]),
mCompleteName(session_id[LL_FCP_COMPLETE_NAME])
{
}
BOOL LLFloaterConversationPreview::postBuild()
{
mChatHistory = getChild<LLChatHistory>("chat_history");
LLLoadHistoryThread::setLoadEndSignal(boost::bind(&LLFloaterConversationPreview::SetPages, this, _1, _2));
const LLConversation* conv = LLConversationLog::instance().getConversation(mSessionID);
std::string name;
std::string file;
if (mAccountName != "")
{
name = mCompleteName;
file = mAccountName;
}
else if (mSessionID != LLUUID::null && conv)
{
name = conv->getConversationName();
file = conv->getHistoryFileName();
}
else
{
name = LLTrans::getString("NearbyChatTitle");
file = "chat";
}
mChatHistoryFileName = file;
LLStringUtil::format_map_t args;
args["[NAME]"] = name;
std::string title = getString("Title", args);
setTitle(title);
LLSD load_params;
load_params["load_all_history"] = true;
load_params["cut_off_todays_date"] = false;
LLSD loading;
loading[LL_IM_TEXT] = LLTrans::getString("loading_chat_logs");
mMessages.push_back(loading);
mPageSpinner = getChild<LLSpinCtrl>("history_page_spin");
mPageSpinner->setCommitCallback(boost::bind(&LLFloaterConversationPreview::onMoreHistoryBtnClick, this));
mPageSpinner->setMinValue(1);
mPageSpinner->set(1);
mPageSpinner->setEnabled(false);
mChatHistoryLoaded = false;
LLLogChat::startChatHistoryThread(file, load_params);
return LLFloater::postBuild();
}
void LLFloaterConversationPreview::SetPages(std::list<LLSD>& messages, const std::string& file_name)
{
if(file_name == mChatHistoryFileName)
{
mMessages = messages;
mCurrentPage = mMessages.size() / mPageSize;
mPageSpinner->setEnabled(true);
mPageSpinner->setMaxValue(mCurrentPage+1);
mPageSpinner->set(mCurrentPage+1);
std::string total_page_num = llformat("/ %d", mCurrentPage+1);
getChild<LLTextBox>("page_num_label")->setValue(total_page_num);
mChatHistoryLoaded = true;
}
}
void LLFloaterConversationPreview::draw()
{
if(mChatHistoryLoaded)
{
showHistory();
mChatHistoryLoaded = false;
}
LLFloater::draw();
}
void LLFloaterConversationPreview::onOpen(const LLSD& key)
{
showHistory();
}
void LLFloaterConversationPreview::showHistory()
{
if (!mMessages.size())
{
return;
}
mChatHistory->clear();
std::ostringstream message;
std::list<LLSD>::const_iterator iter = mMessages.begin();
int delta = 0;
if (mCurrentPage)
{
int remainder = mMessages.size() % mPageSize;
delta = (remainder == 0) ? 0 : (mPageSize - remainder);
}
std::advance(iter, (mCurrentPage * mPageSize) - delta);
for (int msg_num = 0; (iter != mMessages.end() && msg_num < mPageSize); ++iter, ++msg_num)
{
if (iter->size() == 0)
{
continue;
}
LLSD msg = *iter;
LLUUID from_id = LLUUID::null;
std::string time = msg["time"].asString();
std::string from = msg["from"].asString();
std::string message = msg["message"].asString();
if (msg["from_id"].isDefined())
{
from_id = msg["from_id"].asUUID();
}
else
{
std::string legacy_name = gCacheName->buildLegacyName(from);
gCacheName->getUUID(legacy_name, from_id);
}
LLChat chat;
chat.mFromID = from_id;
chat.mSessionID = mSessionID;
chat.mFromName = from;
chat.mTimeStr = time;
chat.mChatStyle = CHAT_STYLE_HISTORY;
chat.mText = message;
if (from_id.isNull() && SYSTEM_FROM == from)
{
chat.mSourceType = CHAT_SOURCE_SYSTEM;
}
else if (from_id.isNull())
{
chat.mSourceType = LLFloaterIMNearbyChat::isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT;
}
LLSD chat_args;
chat_args["use_plain_text_chat_history"] =
gSavedSettings.getBOOL("PlainTextChatHistory");
chat_args["show_time"] = gSavedSettings.getBOOL("IMShowTime");
chat_args["show_names_for_p2p_conv"] = gSavedSettings.getBOOL("IMShowNamesForP2PConv");
mChatHistory->appendMessage(chat,chat_args);
}
}
void LLFloaterConversationPreview::onMoreHistoryBtnClick()
{
mCurrentPage = (int)(mPageSpinner->getValueF32());
if (--mCurrentPage < 0)
{
return;
}
showHistory();
}
<commit_msg>MAINT-3117 FIXED crash in LLFloaterConversationPreview::showHistory()<commit_after>/**
* @file llfloaterconversationpreview.cpp
*
* $LicenseInfo:firstyear=2012&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llconversationlog.h"
#include "llfloaterconversationpreview.h"
#include "llimview.h"
#include "lllineeditor.h"
#include "llfloaterimnearbychat.h"
#include "llspinctrl.h"
#include "lltrans.h"
const std::string LL_FCP_COMPLETE_NAME("complete_name");
const std::string LL_FCP_ACCOUNT_NAME("user_name");
LLFloaterConversationPreview::LLFloaterConversationPreview(const LLSD& session_id)
: LLFloater(session_id),
mChatHistory(NULL),
mSessionID(session_id.asUUID()),
mCurrentPage(0),
mPageSize(gSavedSettings.getS32("ConversationHistoryPageSize")),
mAccountName(session_id[LL_FCP_ACCOUNT_NAME]),
mCompleteName(session_id[LL_FCP_COMPLETE_NAME])
{
}
BOOL LLFloaterConversationPreview::postBuild()
{
mChatHistory = getChild<LLChatHistory>("chat_history");
LLLoadHistoryThread::setLoadEndSignal(boost::bind(&LLFloaterConversationPreview::SetPages, this, _1, _2));
const LLConversation* conv = LLConversationLog::instance().getConversation(mSessionID);
std::string name;
std::string file;
if (mAccountName != "")
{
name = mCompleteName;
file = mAccountName;
}
else if (mSessionID != LLUUID::null && conv)
{
name = conv->getConversationName();
file = conv->getHistoryFileName();
}
else
{
name = LLTrans::getString("NearbyChatTitle");
file = "chat";
}
mChatHistoryFileName = file;
LLStringUtil::format_map_t args;
args["[NAME]"] = name;
std::string title = getString("Title", args);
setTitle(title);
LLSD load_params;
load_params["load_all_history"] = true;
load_params["cut_off_todays_date"] = false;
LLSD loading;
loading[LL_IM_TEXT] = LLTrans::getString("loading_chat_logs");
mMessages.push_back(loading);
mPageSpinner = getChild<LLSpinCtrl>("history_page_spin");
mPageSpinner->setCommitCallback(boost::bind(&LLFloaterConversationPreview::onMoreHistoryBtnClick, this));
mPageSpinner->setMinValue(1);
mPageSpinner->set(1);
mPageSpinner->setEnabled(false);
mChatHistoryLoaded = false;
LLLogChat::startChatHistoryThread(file, load_params);
return LLFloater::postBuild();
}
void LLFloaterConversationPreview::SetPages(std::list<LLSD>& messages, const std::string& file_name)
{
if(file_name == mChatHistoryFileName)
{
mMessages = messages;
mCurrentPage = mMessages.size() / mPageSize;
mPageSpinner->setEnabled(true);
mPageSpinner->setMaxValue(mCurrentPage+1);
mPageSpinner->set(mCurrentPage+1);
std::string total_page_num = llformat("/ %d", mCurrentPage+1);
getChild<LLTextBox>("page_num_label")->setValue(total_page_num);
mChatHistoryLoaded = true;
}
}
void LLFloaterConversationPreview::draw()
{
if(mChatHistoryLoaded)
{
showHistory();
mChatHistoryLoaded = false;
}
LLFloater::draw();
}
void LLFloaterConversationPreview::onOpen(const LLSD& key)
{
if(mChatHistoryLoaded)
{
showHistory();
}
}
void LLFloaterConversationPreview::showHistory()
{
if (!mMessages.size())
{
return;
}
mChatHistory->clear();
std::ostringstream message;
std::list<LLSD>::const_iterator iter = mMessages.begin();
int delta = 0;
if (mCurrentPage)
{
int remainder = mMessages.size() % mPageSize;
delta = (remainder == 0) ? 0 : (mPageSize - remainder);
}
std::advance(iter, (mCurrentPage * mPageSize) - delta);
for (int msg_num = 0; (iter != mMessages.end() && msg_num < mPageSize); ++iter, ++msg_num)
{
if (iter->size() == 0)
{
continue;
}
LLSD msg = *iter;
LLUUID from_id = LLUUID::null;
std::string time = msg["time"].asString();
std::string from = msg["from"].asString();
std::string message = msg["message"].asString();
if (msg["from_id"].isDefined())
{
from_id = msg["from_id"].asUUID();
}
else
{
std::string legacy_name = gCacheName->buildLegacyName(from);
gCacheName->getUUID(legacy_name, from_id);
}
LLChat chat;
chat.mFromID = from_id;
chat.mSessionID = mSessionID;
chat.mFromName = from;
chat.mTimeStr = time;
chat.mChatStyle = CHAT_STYLE_HISTORY;
chat.mText = message;
if (from_id.isNull() && SYSTEM_FROM == from)
{
chat.mSourceType = CHAT_SOURCE_SYSTEM;
}
else if (from_id.isNull())
{
chat.mSourceType = LLFloaterIMNearbyChat::isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT;
}
LLSD chat_args;
chat_args["use_plain_text_chat_history"] =
gSavedSettings.getBOOL("PlainTextChatHistory");
chat_args["show_time"] = gSavedSettings.getBOOL("IMShowTime");
chat_args["show_names_for_p2p_conv"] = gSavedSettings.getBOOL("IMShowNamesForP2PConv");
mChatHistory->appendMessage(chat,chat_args);
}
}
void LLFloaterConversationPreview::onMoreHistoryBtnClick()
{
mCurrentPage = (int)(mPageSpinner->getValueF32());
if (--mCurrentPage < 0)
{
return;
}
showHistory();
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "tarpackagecreationstep.h"
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <cstring>
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace {
class CreateTarStepWidget : public SimpleBuildStepConfigWidget
{
Q_OBJECT
public:
CreateTarStepWidget(TarPackageCreationStep *step) : SimpleBuildStepConfigWidget(step)
{
connect(step, SIGNAL(packageFilePathChanged()), SIGNAL(updateSummary()));
}
QString summaryText() const
{
TarPackageCreationStep * const step = static_cast<TarPackageCreationStep *>(this->step());
if (step->packageFilePath().isEmpty()) {
return QLatin1String("<font color=\"red\">")
+ tr("Tarball creation not possible.") + QLatin1String("</font>");
}
return QLatin1String("<b>") + tr("Create tarball:") + QLatin1String("</b> ")
+ step->packageFilePath();
}
};
const int TarBlockSize = 512;
struct TarFileHeader {
char fileName[100];
char fileMode[8];
char uid[8];
char gid[8];
char length[12];
char mtime[12];
char chksum[8];
char typeflag;
char linkname[100];
char magic[6];
char version[2];
char uname[32];
char gname[32];
char devmajor[8];
char devminor[8];
char fileNamePrefix[155];
char padding[12];
};
} // Anonymous namespace.
TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl)
: AbstractPackagingStep(bsl, stepId())
{
ctor();
}
TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl, TarPackageCreationStep *other)
: AbstractPackagingStep(bsl, other)
{
ctor();
}
void TarPackageCreationStep::ctor()
{
setDefaultDisplayName(displayName());
}
bool TarPackageCreationStep::init()
{
if (!AbstractPackagingStep::init())
return false;
m_packagingNeeded = isPackagingNeeded();
if (m_packagingNeeded)
m_files = target()->deploymentData().allFiles();
return true;
}
void TarPackageCreationStep::run(QFutureInterface<bool> &fi)
{
setPackagingStarted();
const bool success = doPackage(fi);
setPackagingFinished(success);
if (success)
emit addOutput(tr("Packaging finished successfully."), MessageOutput);
else
emit addOutput(tr("Packaging failed."), ErrorMessageOutput);
fi.reportResult(success);
}
bool TarPackageCreationStep::doPackage(QFutureInterface<bool> &fi)
{
emit addOutput(tr("Creating tarball..."), MessageOutput);
if (!m_packagingNeeded) {
emit addOutput(tr("Tarball up to date, skipping packaging."), MessageOutput);
return true;
}
// TODO: Optimization: Only package changed files
QFile tarFile(cachedPackageFilePath());
if (!tarFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
raiseError(tr("Error: tar file %1 cannot be opened (%2).")
.arg(QDir::toNativeSeparators(cachedPackageFilePath()), tarFile.errorString()));
return false;
}
foreach (const DeployableFile &d, m_files) {
if (d.remoteDirectory().isEmpty()) {
emit addOutput(tr("No remote path specified for file '%1', skipping.")
.arg(d.localFilePath().toUserOutput()), ErrorMessageOutput);
continue;
}
QFileInfo fileInfo = d.localFilePath().toFileInfo();
if (!appendFile(tarFile, fileInfo, d.remoteDirectory() + QLatin1Char('/')
+ fileInfo.fileName(), fi)) {
return false;
}
}
const QByteArray eofIndicator(2*sizeof(TarFileHeader), 0);
if (tarFile.write(eofIndicator) != eofIndicator.length()) {
raiseError(tr("Error writing tar file '%1': %2.")
.arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
return false;
}
return true;
}
bool TarPackageCreationStep::appendFile(QFile &tarFile, const QFileInfo &fileInfo,
const QString &remoteFilePath, const QFutureInterface<bool> &fi)
{
if (!writeHeader(tarFile, fileInfo, remoteFilePath))
return false;
if (fileInfo.isDir()) {
QDir dir(fileInfo.absoluteFilePath());
foreach (const QString &fileName,
dir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
const QString thisLocalFilePath = dir.path() + QLatin1Char('/') + fileName;
const QString thisRemoteFilePath = remoteFilePath + QLatin1Char('/') + fileName;
if (!appendFile(tarFile, QFileInfo(thisLocalFilePath), thisRemoteFilePath, fi))
return false;
}
return true;
}
const QString nativePath = QDir::toNativeSeparators(fileInfo.filePath());
QFile file(fileInfo.filePath());
if (!file.open(QIODevice::ReadOnly)) {
raiseError(tr("Error reading file '%1': %2.").arg(nativePath, file.errorString()));
return false;
}
const int chunkSize = 1024*1024;
emit addOutput(tr("Adding file '%1' to tarball...").arg(nativePath), MessageOutput);
// TODO: Wasteful. Work with fixed-size buffer.
while (!file.atEnd() && !file.error() != QFile::NoError && !tarFile.error() != QFile::NoError) {
const QByteArray data = file.read(chunkSize);
tarFile.write(data);
if (fi.isCanceled())
return false;
}
if (file.error() != QFile::NoError) {
raiseError(tr("Error reading file '%1': %2.").arg(nativePath, file.errorString()));
return false;
}
const int blockModulo = file.size() % TarBlockSize;
if (blockModulo != 0)
tarFile.write(QByteArray(TarBlockSize - blockModulo, 0));
if (tarFile.error() != QFile::NoError) {
raiseError(tr("Error writing tar file '%1': %2.")
.arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
return false;
}
return true;
}
bool TarPackageCreationStep::writeHeader(QFile &tarFile, const QFileInfo &fileInfo,
const QString &remoteFilePath)
{
TarFileHeader header;
std::memset(&header, '\0', sizeof header);
const QByteArray &filePath = remoteFilePath.toUtf8();
const int maxFilePathLength = sizeof header.fileNamePrefix + sizeof header.fileName;
if (filePath.count() > maxFilePathLength) {
raiseError(tr("Cannot add file '%1' to tar-archive: path too long.")
.arg(QDir::toNativeSeparators(remoteFilePath)));
return false;
}
const int fileNameBytesToWrite = qMin<int>(filePath.length(), sizeof header.fileName);
const int fileNameOffset = filePath.length() - fileNameBytesToWrite;
std::memcpy(&header.fileName, filePath.data() + fileNameOffset, fileNameBytesToWrite);
if (fileNameOffset > 0)
std::memcpy(&header.fileNamePrefix, filePath.data(), fileNameOffset);
int permissions = (0400 * fileInfo.permission(QFile::ReadOwner))
| (0200 * fileInfo.permission(QFile::WriteOwner))
| (0100 * fileInfo.permission(QFile::ExeOwner))
| (040 * fileInfo.permission(QFile::ReadGroup))
| (020 * fileInfo.permission(QFile::WriteGroup))
| (010 * fileInfo.permission(QFile::ExeGroup))
| (04 * fileInfo.permission(QFile::ReadOther))
| (02 * fileInfo.permission(QFile::WriteOther))
| (01 * fileInfo.permission(QFile::ExeOther));
const QByteArray permissionString = QString::fromLatin1("%1").arg(permissions,
sizeof header.fileMode - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.fileMode, permissionString.data(), permissionString.length());
const QByteArray uidString = QString::fromLatin1("%1").arg(fileInfo.ownerId(),
sizeof header.uid - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.uid, uidString.data(), uidString.length());
const QByteArray gidString = QString::fromLatin1("%1").arg(fileInfo.groupId(),
sizeof header.gid - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.gid, gidString.data(), gidString.length());
const QByteArray sizeString = QString::fromLatin1("%1").arg(fileInfo.size(),
sizeof header.length - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.length, sizeString.data(), sizeString.length());
const QByteArray mtimeString = QString::fromLatin1("%1").arg(fileInfo.lastModified().toTime_t(),
sizeof header.mtime - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.mtime, mtimeString.data(), mtimeString.length());
if (fileInfo.isDir())
header.typeflag = '5';
std::memcpy(&header.magic, "ustar", sizeof "ustar");
std::memcpy(&header.version, "00", 2);
const QByteArray &owner = fileInfo.owner().toUtf8();
std::memcpy(&header.uname, owner.data(), qMin<int>(owner.length(), sizeof header.uname - 1));
const QByteArray &group = fileInfo.group().toUtf8();
std::memcpy(&header.gname, group.data(), qMin<int>(group.length(), sizeof header.gname - 1));
std::memset(&header.chksum, ' ', sizeof header.chksum);
quint64 checksum = 0;
for (size_t i = 0; i < sizeof header; ++i)
checksum += reinterpret_cast<char *>(&header)[i];
const QByteArray checksumString = QString::fromLatin1("%1").arg(checksum,
sizeof header.chksum - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.chksum, checksumString.data(), checksumString.length());
header.chksum[sizeof header.chksum-1] = 0;
if (!tarFile.write(reinterpret_cast<char *>(&header), sizeof header)) {
raiseError(tr("Error writing tar file '%1': %2")
.arg(QDir::toNativeSeparators(cachedPackageFilePath()), tarFile.errorString()));
return false;
}
return true;
}
QString TarPackageCreationStep::packageFileName() const
{
return project()->displayName() + QLatin1String(".tar");
}
BuildStepConfigWidget *TarPackageCreationStep::createConfigWidget()
{
return new CreateTarStepWidget(this);
}
Core::Id TarPackageCreationStep::stepId()
{
return Core::Id("MaemoTarPackageCreationStep");
}
QString TarPackageCreationStep::displayName()
{
return tr("Create tarball");
}
} // namespace RemoteLinux
#include "tarpackagecreationstep.moc"
<commit_msg>RemoteLinux: Fix typos in tar packaging step.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "tarpackagecreationstep.h"
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <cstring>
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace {
class CreateTarStepWidget : public SimpleBuildStepConfigWidget
{
Q_OBJECT
public:
CreateTarStepWidget(TarPackageCreationStep *step) : SimpleBuildStepConfigWidget(step)
{
connect(step, SIGNAL(packageFilePathChanged()), SIGNAL(updateSummary()));
}
QString summaryText() const
{
TarPackageCreationStep * const step = static_cast<TarPackageCreationStep *>(this->step());
if (step->packageFilePath().isEmpty()) {
return QLatin1String("<font color=\"red\">")
+ tr("Tarball creation not possible.") + QLatin1String("</font>");
}
return QLatin1String("<b>") + tr("Create tarball:") + QLatin1String("</b> ")
+ step->packageFilePath();
}
};
const int TarBlockSize = 512;
struct TarFileHeader {
char fileName[100];
char fileMode[8];
char uid[8];
char gid[8];
char length[12];
char mtime[12];
char chksum[8];
char typeflag;
char linkname[100];
char magic[6];
char version[2];
char uname[32];
char gname[32];
char devmajor[8];
char devminor[8];
char fileNamePrefix[155];
char padding[12];
};
} // Anonymous namespace.
TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl)
: AbstractPackagingStep(bsl, stepId())
{
ctor();
}
TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl, TarPackageCreationStep *other)
: AbstractPackagingStep(bsl, other)
{
ctor();
}
void TarPackageCreationStep::ctor()
{
setDefaultDisplayName(displayName());
}
bool TarPackageCreationStep::init()
{
if (!AbstractPackagingStep::init())
return false;
m_packagingNeeded = isPackagingNeeded();
if (m_packagingNeeded)
m_files = target()->deploymentData().allFiles();
return true;
}
void TarPackageCreationStep::run(QFutureInterface<bool> &fi)
{
setPackagingStarted();
const bool success = doPackage(fi);
setPackagingFinished(success);
if (success)
emit addOutput(tr("Packaging finished successfully."), MessageOutput);
else
emit addOutput(tr("Packaging failed."), ErrorMessageOutput);
fi.reportResult(success);
}
bool TarPackageCreationStep::doPackage(QFutureInterface<bool> &fi)
{
emit addOutput(tr("Creating tarball..."), MessageOutput);
if (!m_packagingNeeded) {
emit addOutput(tr("Tarball up to date, skipping packaging."), MessageOutput);
return true;
}
// TODO: Optimization: Only package changed files
QFile tarFile(cachedPackageFilePath());
if (!tarFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
raiseError(tr("Error: tar file %1 cannot be opened (%2).")
.arg(QDir::toNativeSeparators(cachedPackageFilePath()), tarFile.errorString()));
return false;
}
foreach (const DeployableFile &d, m_files) {
if (d.remoteDirectory().isEmpty()) {
emit addOutput(tr("No remote path specified for file '%1', skipping.")
.arg(d.localFilePath().toUserOutput()), ErrorMessageOutput);
continue;
}
QFileInfo fileInfo = d.localFilePath().toFileInfo();
if (!appendFile(tarFile, fileInfo, d.remoteDirectory() + QLatin1Char('/')
+ fileInfo.fileName(), fi)) {
return false;
}
}
const QByteArray eofIndicator(2*sizeof(TarFileHeader), 0);
if (tarFile.write(eofIndicator) != eofIndicator.length()) {
raiseError(tr("Error writing tar file '%1': %2.")
.arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
return false;
}
return true;
}
bool TarPackageCreationStep::appendFile(QFile &tarFile, const QFileInfo &fileInfo,
const QString &remoteFilePath, const QFutureInterface<bool> &fi)
{
if (!writeHeader(tarFile, fileInfo, remoteFilePath))
return false;
if (fileInfo.isDir()) {
QDir dir(fileInfo.absoluteFilePath());
foreach (const QString &fileName,
dir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
const QString thisLocalFilePath = dir.path() + QLatin1Char('/') + fileName;
const QString thisRemoteFilePath = remoteFilePath + QLatin1Char('/') + fileName;
if (!appendFile(tarFile, QFileInfo(thisLocalFilePath), thisRemoteFilePath, fi))
return false;
}
return true;
}
const QString nativePath = QDir::toNativeSeparators(fileInfo.filePath());
QFile file(fileInfo.filePath());
if (!file.open(QIODevice::ReadOnly)) {
raiseError(tr("Error reading file '%1': %2.").arg(nativePath, file.errorString()));
return false;
}
const int chunkSize = 1024*1024;
emit addOutput(tr("Adding file '%1' to tarball...").arg(nativePath), MessageOutput);
// TODO: Wasteful. Work with fixed-size buffer.
while (!file.atEnd() && file.error() == QFile::NoError && tarFile.error() == QFile::NoError) {
const QByteArray data = file.read(chunkSize);
tarFile.write(data);
if (fi.isCanceled())
return false;
}
if (file.error() != QFile::NoError) {
raiseError(tr("Error reading file '%1': %2.").arg(nativePath, file.errorString()));
return false;
}
const int blockModulo = file.size() % TarBlockSize;
if (blockModulo != 0)
tarFile.write(QByteArray(TarBlockSize - blockModulo, 0));
if (tarFile.error() != QFile::NoError) {
raiseError(tr("Error writing tar file '%1': %2.")
.arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
return false;
}
return true;
}
bool TarPackageCreationStep::writeHeader(QFile &tarFile, const QFileInfo &fileInfo,
const QString &remoteFilePath)
{
TarFileHeader header;
std::memset(&header, '\0', sizeof header);
const QByteArray &filePath = remoteFilePath.toUtf8();
const int maxFilePathLength = sizeof header.fileNamePrefix + sizeof header.fileName;
if (filePath.count() > maxFilePathLength) {
raiseError(tr("Cannot add file '%1' to tar-archive: path too long.")
.arg(QDir::toNativeSeparators(remoteFilePath)));
return false;
}
const int fileNameBytesToWrite = qMin<int>(filePath.length(), sizeof header.fileName);
const int fileNameOffset = filePath.length() - fileNameBytesToWrite;
std::memcpy(&header.fileName, filePath.data() + fileNameOffset, fileNameBytesToWrite);
if (fileNameOffset > 0)
std::memcpy(&header.fileNamePrefix, filePath.data(), fileNameOffset);
int permissions = (0400 * fileInfo.permission(QFile::ReadOwner))
| (0200 * fileInfo.permission(QFile::WriteOwner))
| (0100 * fileInfo.permission(QFile::ExeOwner))
| (040 * fileInfo.permission(QFile::ReadGroup))
| (020 * fileInfo.permission(QFile::WriteGroup))
| (010 * fileInfo.permission(QFile::ExeGroup))
| (04 * fileInfo.permission(QFile::ReadOther))
| (02 * fileInfo.permission(QFile::WriteOther))
| (01 * fileInfo.permission(QFile::ExeOther));
const QByteArray permissionString = QString::fromLatin1("%1").arg(permissions,
sizeof header.fileMode - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.fileMode, permissionString.data(), permissionString.length());
const QByteArray uidString = QString::fromLatin1("%1").arg(fileInfo.ownerId(),
sizeof header.uid - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.uid, uidString.data(), uidString.length());
const QByteArray gidString = QString::fromLatin1("%1").arg(fileInfo.groupId(),
sizeof header.gid - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.gid, gidString.data(), gidString.length());
const QByteArray sizeString = QString::fromLatin1("%1").arg(fileInfo.size(),
sizeof header.length - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.length, sizeString.data(), sizeString.length());
const QByteArray mtimeString = QString::fromLatin1("%1").arg(fileInfo.lastModified().toTime_t(),
sizeof header.mtime - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.mtime, mtimeString.data(), mtimeString.length());
if (fileInfo.isDir())
header.typeflag = '5';
std::memcpy(&header.magic, "ustar", sizeof "ustar");
std::memcpy(&header.version, "00", 2);
const QByteArray &owner = fileInfo.owner().toUtf8();
std::memcpy(&header.uname, owner.data(), qMin<int>(owner.length(), sizeof header.uname - 1));
const QByteArray &group = fileInfo.group().toUtf8();
std::memcpy(&header.gname, group.data(), qMin<int>(group.length(), sizeof header.gname - 1));
std::memset(&header.chksum, ' ', sizeof header.chksum);
quint64 checksum = 0;
for (size_t i = 0; i < sizeof header; ++i)
checksum += reinterpret_cast<char *>(&header)[i];
const QByteArray checksumString = QString::fromLatin1("%1").arg(checksum,
sizeof header.chksum - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.chksum, checksumString.data(), checksumString.length());
header.chksum[sizeof header.chksum-1] = 0;
if (!tarFile.write(reinterpret_cast<char *>(&header), sizeof header)) {
raiseError(tr("Error writing tar file '%1': %2")
.arg(QDir::toNativeSeparators(cachedPackageFilePath()), tarFile.errorString()));
return false;
}
return true;
}
QString TarPackageCreationStep::packageFileName() const
{
return project()->displayName() + QLatin1String(".tar");
}
BuildStepConfigWidget *TarPackageCreationStep::createConfigWidget()
{
return new CreateTarStepWidget(this);
}
Core::Id TarPackageCreationStep::stepId()
{
return Core::Id("MaemoTarPackageCreationStep");
}
QString TarPackageCreationStep::displayName()
{
return tr("Create tarball");
}
} // namespace RemoteLinux
#include "tarpackagecreationstep.moc"
<|endoftext|>
|
<commit_before>//===--- Immediate.cpp - the swift immediate mode -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the implementation of the swift interpreter, which takes a
// source file and JITs it.
//
//===----------------------------------------------------------------------===//
#include "swift/Immediate/Immediate.h"
#include "ImmediateImpl.h"
#include "swift/Subsystems.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/IRGenRequests.h"
#include "swift/AST/Module.h"
#include "swift/Basic/LLVM.h"
#include "swift/Frontend/Frontend.h"
#include "swift/IRGen/IRGenPublic.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/Orc/DebugUtils.h"
#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
#include "llvm/ExecutionEngine/Orc/LLJIT.h"
#include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
#include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Support/Path.h"
#define DEBUG_TYPE "swift-immediate"
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#else
#include <dlfcn.h>
#endif
using namespace swift;
using namespace swift::immediate;
static void *loadRuntimeLib(StringRef runtimeLibPathWithName) {
#if defined(_WIN32)
return LoadLibraryA(runtimeLibPathWithName.str().c_str());
#else
return dlopen(runtimeLibPathWithName.str().c_str(), RTLD_LAZY | RTLD_GLOBAL);
#endif
}
static void *loadRuntimeLibAtPath(StringRef sharedLibName,
StringRef runtimeLibPath) {
// FIXME: Need error-checking.
llvm::SmallString<128> Path = runtimeLibPath;
llvm::sys::path::append(Path, sharedLibName);
return loadRuntimeLib(Path);
}
static void *loadRuntimeLib(StringRef sharedLibName,
ArrayRef<std::string> runtimeLibPaths) {
for (auto &runtimeLibPath : runtimeLibPaths) {
if (void *handle = loadRuntimeLibAtPath(sharedLibName, runtimeLibPath))
return handle;
}
return nullptr;
}
static void DumpLLVMIR(const llvm::Module &M) {
std::string path = (M.getName() + ".ll").str();
for (size_t count = 0; llvm::sys::fs::exists(path); )
path = (M.getName() + llvm::utostr(count++) + ".ll").str();
std::error_code error;
llvm::raw_fd_ostream stream(path, error);
if (error)
return;
M.print(stream, /*AssemblyAnnotationWriter=*/nullptr);
}
void *swift::immediate::loadSwiftRuntime(ArrayRef<std::string>
runtimeLibPaths) {
#if defined(_WIN32)
return loadRuntimeLib("swiftCore" LTDL_SHLIB_EXT, runtimeLibPaths);
#else
return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPaths);
#endif
}
static bool tryLoadLibrary(LinkLibrary linkLib,
SearchPathOptions searchPathOpts) {
llvm::SmallString<128> path = linkLib.getName();
// If we have an absolute or relative path, just try to load it now.
if (llvm::sys::path::has_parent_path(path.str())) {
return loadRuntimeLib(path);
}
bool success = false;
switch (linkLib.getKind()) {
case LibraryKind::Library: {
llvm::SmallString<32> stem;
if (llvm::sys::path::has_extension(path.str())) {
stem = std::move(path);
} else {
// FIXME: Try the appropriate extension for the current platform?
stem = "lib";
stem += path;
stem += LTDL_SHLIB_EXT;
}
// Try user-provided library search paths first.
for (auto &libDir : searchPathOpts.LibrarySearchPaths) {
path = libDir;
llvm::sys::path::append(path, stem.str());
success = loadRuntimeLib(path);
if (success)
break;
}
// Let loadRuntimeLib determine the best search paths.
if (!success)
success = loadRuntimeLib(stem);
// If that fails, try our runtime library paths.
if (!success)
success = loadRuntimeLib(stem, searchPathOpts.RuntimeLibraryPaths);
break;
}
case LibraryKind::Framework: {
// If we have a framework, mangle the name to point to the framework
// binary.
llvm::SmallString<64> frameworkPart{std::move(path)};
frameworkPart += ".framework";
llvm::sys::path::append(frameworkPart, linkLib.getName());
// Try user-provided framework search paths first; frameworks contain
// binaries as well as modules.
for (const auto &frameworkDir : searchPathOpts.getFrameworkSearchPaths()) {
path = frameworkDir.Path;
llvm::sys::path::append(path, frameworkPart.str());
success = loadRuntimeLib(path);
if (success)
break;
}
// If that fails, let loadRuntimeLib search for system frameworks.
if (!success)
success = loadRuntimeLib(frameworkPart);
break;
}
}
return success;
}
bool swift::immediate::tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries,
SearchPathOptions SearchPathOpts,
DiagnosticEngine &Diags) {
SmallVector<bool, 4> LoadedLibraries;
LoadedLibraries.append(LinkLibraries.size(), false);
// Libraries are not sorted in the topological order of dependencies, and we
// don't know the dependencies in advance. Try to load all libraries until
// we stop making progress.
bool HadProgress;
do {
HadProgress = false;
for (unsigned i = 0; i != LinkLibraries.size(); ++i) {
if (!LoadedLibraries[i] &&
tryLoadLibrary(LinkLibraries[i], SearchPathOpts)) {
LoadedLibraries[i] = true;
HadProgress = true;
}
}
} while (HadProgress);
return std::all_of(LoadedLibraries.begin(), LoadedLibraries.end(),
[](bool Value) { return Value; });
}
bool swift::immediate::autolinkImportedModules(ModuleDecl *M,
const IRGenOptions &IRGenOpts) {
// Perform autolinking.
SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries);
auto addLinkLibrary = [&](LinkLibrary linkLib) {
AllLinkLibraries.push_back(linkLib);
};
M->collectLinkLibraries(addLinkLibrary);
tryLoadLibraries(AllLinkLibraries, M->getASTContext().SearchPathOpts,
M->getASTContext().Diags);
return false;
}
int swift::RunImmediately(CompilerInstance &CI,
const ProcessCmdLine &CmdLine,
const IRGenOptions &IRGenOpts,
const SILOptions &SILOpts,
std::unique_ptr<SILModule> &&SM) {
// TODO: Use OptimizedIRRequest for this.
ASTContext &Context = CI.getASTContext();
// IRGen the main module.
auto *swiftModule = CI.getMainModule();
const auto PSPs = CI.getPrimarySpecificPathsForAtMostOnePrimary();
const auto &TBDOpts = CI.getInvocation().getTBDGenOptions();
auto GenModule = performIRGeneration(
swiftModule, IRGenOpts, TBDOpts, std::move(SM),
swiftModule->getName().str(), PSPs, ArrayRef<std::string>());
if (Context.hadError())
return -1;
assert(GenModule && "Emitted no diagnostics but IR generation failed?");
performLLVM(IRGenOpts, Context.Diags, /*diagMutex*/ nullptr, /*hash*/ nullptr,
GenModule.getModule(), GenModule.getTargetMachine(),
PSPs.OutputFilename, Context.Stats);
if (Context.hadError())
return -1;
// Load libSwiftCore to setup process arguments.
//
// This must be done here, before any library loading has been done, to avoid
// racing with the static initializers in user code.
// Setup interpreted process arguments.
using ArgOverride = void (* SWIFT_CC(swift))(const char **, int);
#if defined(_WIN32)
auto stdlib = loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPaths);
if (!stdlib) {
CI.getDiags().diagnose(SourceLoc(),
diag::error_immediate_mode_missing_stdlib);
return -1;
}
auto module = static_cast<HMODULE>(stdlib);
auto emplaceProcessArgs = reinterpret_cast<ArgOverride>(
GetProcAddress(module, "_swift_stdlib_overrideUnsafeArgvArgc"));
if (emplaceProcessArgs == nullptr)
return -1;
#else
// In case the compiler is built with swift modules, it already has the stdlib
// linked to. First try to lookup the symbol with the standard library
// resolving.
auto emplaceProcessArgs
= (ArgOverride)dlsym(RTLD_DEFAULT, "_swift_stdlib_overrideUnsafeArgvArgc");
if (dlerror()) {
// If this does not work (= the Swift modules are not linked to the tool),
// we have to explicitly load the stdlib.
auto stdlib = loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPaths);
if (!stdlib) {
CI.getDiags().diagnose(SourceLoc(),
diag::error_immediate_mode_missing_stdlib);
return -1;
}
dlerror();
emplaceProcessArgs
= (ArgOverride)dlsym(stdlib, "_swift_stdlib_overrideUnsafeArgvArgc");
if (dlerror())
return -1;
}
#endif
SmallVector<const char *, 32> argBuf;
for (size_t i = 0; i < CmdLine.size(); ++i) {
argBuf.push_back(CmdLine[i].c_str());
}
argBuf.push_back(nullptr);
(*emplaceProcessArgs)(argBuf.data(), CmdLine.size());
if (autolinkImportedModules(swiftModule, IRGenOpts))
return -1;
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = 2;
PMBuilder.Inliner = llvm::createFunctionInliningPass(200);
// Build the ExecutionEngine.
llvm::TargetOptions TargetOpt;
std::string CPU;
std::string Triple;
std::vector<std::string> Features;
std::tie(TargetOpt, CPU, Features, Triple)
= getIRTargetOptions(IRGenOpts, swiftModule->getASTContext());
std::unique_ptr<llvm::orc::LLJIT> JIT;
{
auto JITOrErr =
llvm::orc::LLJITBuilder()
.setJITTargetMachineBuilder(
llvm::orc::JITTargetMachineBuilder(llvm::Triple(Triple))
.setRelocationModel(llvm::Reloc::PIC_)
.setOptions(std::move(TargetOpt))
.setCPU(std::move(CPU))
.addFeatures(Features)
.setCodeGenOptLevel(llvm::CodeGenOpt::Default))
.create();
if (!JITOrErr) {
llvm::logAllUnhandledErrors(JITOrErr.takeError(), llvm::errs(), "");
return -1;
} else
JIT = std::move(*JITOrErr);
}
auto Module = GenModule.getModule();
switch (IRGenOpts.DumpJIT) {
case JITDebugArtifact::None:
break;
case JITDebugArtifact::LLVMIR:
DumpLLVMIR(*Module);
break;
case JITDebugArtifact::Object:
JIT->getObjTransformLayer().setTransform(llvm::orc::DumpObjects());
break;
}
{
// Get a generator for the process symbols and attach it to the main
// JITDylib.
if (auto G = llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(Module->getDataLayout().getGlobalPrefix()))
JIT->getMainJITDylib().addGenerator(std::move(*G));
else {
logAllUnhandledErrors(G.takeError(), llvm::errs(), "");
return -1;
}
}
LLVM_DEBUG(llvm::dbgs() << "Module to be executed:\n";
Module->dump());
{
if (auto Err = JIT->addIRModule(std::move(GenModule).intoThreadSafeContext())) {
llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "");
return -1;
}
}
using MainFnTy = int(*)(int, char*[]);
LLVM_DEBUG(llvm::dbgs() << "Running static constructors\n");
if (auto Err = JIT->initialize(JIT->getMainJITDylib())) {
llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "");
return -1;
}
MainFnTy JITMain = nullptr;
if (auto MainFnOrErr = JIT->lookup("main"))
JITMain = llvm::jitTargetAddressToFunction<MainFnTy>(MainFnOrErr->getAddress());
else {
logAllUnhandledErrors(MainFnOrErr.takeError(), llvm::errs(), "");
return -1;
}
LLVM_DEBUG(llvm::dbgs() << "Running main\n");
int Result = llvm::orc::runAsMain(JITMain, CmdLine);
LLVM_DEBUG(llvm::dbgs() << "Running static destructors\n");
if (auto Err = JIT->deinitialize(JIT->getMainJITDylib())) {
logAllUnhandledErrors(std::move(Err), llvm::errs(), "");
return -1;
}
return Result;
}
<commit_msg>[Immediate]: Workaround for loading Foundation in immediate mode (#59730)<commit_after>//===--- Immediate.cpp - the swift immediate mode -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the implementation of the swift interpreter, which takes a
// source file and JITs it.
//
//===----------------------------------------------------------------------===//
#include "swift/Immediate/Immediate.h"
#include "ImmediateImpl.h"
#include "swift/Subsystems.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/IRGenRequests.h"
#include "swift/AST/Module.h"
#include "swift/Basic/LLVM.h"
#include "swift/Frontend/Frontend.h"
#include "swift/IRGen/IRGenPublic.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/Orc/DebugUtils.h"
#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
#include "llvm/ExecutionEngine/Orc/LLJIT.h"
#include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
#include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Support/Path.h"
#define DEBUG_TYPE "swift-immediate"
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#else
#include <dlfcn.h>
#endif
using namespace swift;
using namespace swift::immediate;
static void *loadRuntimeLib(StringRef runtimeLibPathWithName) {
#if defined(_WIN32)
return LoadLibraryA(runtimeLibPathWithName.str().c_str());
#else
return dlopen(runtimeLibPathWithName.str().c_str(), RTLD_LAZY | RTLD_GLOBAL);
#endif
}
static void *loadRuntimeLibAtPath(StringRef sharedLibName,
StringRef runtimeLibPath) {
// FIXME: Need error-checking.
llvm::SmallString<128> Path = runtimeLibPath;
llvm::sys::path::append(Path, sharedLibName);
return loadRuntimeLib(Path);
}
static void *loadRuntimeLib(StringRef sharedLibName,
ArrayRef<std::string> runtimeLibPaths) {
for (auto &runtimeLibPath : runtimeLibPaths) {
if (void *handle = loadRuntimeLibAtPath(sharedLibName, runtimeLibPath))
return handle;
}
return nullptr;
}
static void DumpLLVMIR(const llvm::Module &M) {
std::string path = (M.getName() + ".ll").str();
for (size_t count = 0; llvm::sys::fs::exists(path); )
path = (M.getName() + llvm::utostr(count++) + ".ll").str();
std::error_code error;
llvm::raw_fd_ostream stream(path, error);
if (error)
return;
M.print(stream, /*AssemblyAnnotationWriter=*/nullptr);
}
void *swift::immediate::loadSwiftRuntime(ArrayRef<std::string>
runtimeLibPaths) {
#if defined(_WIN32)
return loadRuntimeLib("swiftCore" LTDL_SHLIB_EXT, runtimeLibPaths);
#else
return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPaths);
#endif
}
static bool tryLoadLibrary(LinkLibrary linkLib,
SearchPathOptions searchPathOpts) {
llvm::SmallString<128> path = linkLib.getName();
// If we have an absolute or relative path, just try to load it now.
if (llvm::sys::path::has_parent_path(path.str())) {
return loadRuntimeLib(path);
}
bool success = false;
switch (linkLib.getKind()) {
case LibraryKind::Library: {
llvm::SmallString<32> stem;
if (llvm::sys::path::has_extension(path.str())) {
stem = std::move(path);
} else {
// FIXME: Try the appropriate extension for the current platform?
stem = "lib";
stem += path;
stem += LTDL_SHLIB_EXT;
}
// Try user-provided library search paths first.
for (auto &libDir : searchPathOpts.LibrarySearchPaths) {
path = libDir;
llvm::sys::path::append(path, stem.str());
success = loadRuntimeLib(path);
if (success)
break;
}
// Let loadRuntimeLib determine the best search paths.
if (!success)
success = loadRuntimeLib(stem);
// If that fails, try our runtime library paths.
if (!success)
success = loadRuntimeLib(stem, searchPathOpts.RuntimeLibraryPaths);
break;
}
case LibraryKind::Framework: {
// If we have a framework, mangle the name to point to the framework
// binary.
llvm::SmallString<64> frameworkPart{std::move(path)};
frameworkPart += ".framework";
llvm::sys::path::append(frameworkPart, linkLib.getName());
// Try user-provided framework search paths first; frameworks contain
// binaries as well as modules.
for (const auto &frameworkDir : searchPathOpts.getFrameworkSearchPaths()) {
path = frameworkDir.Path;
llvm::sys::path::append(path, frameworkPart.str());
success = loadRuntimeLib(path);
if (success)
break;
}
// If that fails, let loadRuntimeLib search for system frameworks.
if (!success)
success = loadRuntimeLib(frameworkPart);
break;
}
}
return success;
}
bool swift::immediate::tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries,
SearchPathOptions SearchPathOpts,
DiagnosticEngine &Diags) {
SmallVector<bool, 4> LoadedLibraries;
LoadedLibraries.append(LinkLibraries.size(), false);
// Libraries are not sorted in the topological order of dependencies, and we
// don't know the dependencies in advance. Try to load all libraries until
// we stop making progress.
bool HadProgress;
do {
HadProgress = false;
for (unsigned i = 0; i != LinkLibraries.size(); ++i) {
if (!LoadedLibraries[i] &&
tryLoadLibrary(LinkLibraries[i], SearchPathOpts)) {
LoadedLibraries[i] = true;
HadProgress = true;
}
}
} while (HadProgress);
return std::all_of(LoadedLibraries.begin(), LoadedLibraries.end(),
[](bool Value) { return Value; });
}
bool swift::immediate::autolinkImportedModules(ModuleDecl *M,
const IRGenOptions &IRGenOpts) {
// Perform autolinking.
SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries);
auto addLinkLibrary = [&](LinkLibrary linkLib) {
AllLinkLibraries.push_back(linkLib);
};
M->collectLinkLibraries(addLinkLibrary);
// Workaround for rdar://94645534.
//
// The framework layout of Foundation has changed in 13.0, causing unresolved symbol
// errors to libswiftFoundation in immediate mode when running on older OS versions
// with a 13.0 SDK. This workaround scans through the list of dependencies and
// manually adds libswiftFoundation if necessary.
auto &Target = M->getASTContext().LangOpts.Target;
if (Target.isMacOSX() && Target.getOSMajorVersion() < 13) {
bool linksFoundation = std::any_of(AllLinkLibraries.begin(),
AllLinkLibraries.end(), [](auto &Lib) {
return Lib.getName() == "Foundation";
});
if (linksFoundation) {
AllLinkLibraries.push_back(LinkLibrary("libswiftFoundation.dylib",
LibraryKind::Library));
}
}
tryLoadLibraries(AllLinkLibraries, M->getASTContext().SearchPathOpts,
M->getASTContext().Diags);
return false;
}
int swift::RunImmediately(CompilerInstance &CI,
const ProcessCmdLine &CmdLine,
const IRGenOptions &IRGenOpts,
const SILOptions &SILOpts,
std::unique_ptr<SILModule> &&SM) {
// TODO: Use OptimizedIRRequest for this.
ASTContext &Context = CI.getASTContext();
// IRGen the main module.
auto *swiftModule = CI.getMainModule();
const auto PSPs = CI.getPrimarySpecificPathsForAtMostOnePrimary();
const auto &TBDOpts = CI.getInvocation().getTBDGenOptions();
auto GenModule = performIRGeneration(
swiftModule, IRGenOpts, TBDOpts, std::move(SM),
swiftModule->getName().str(), PSPs, ArrayRef<std::string>());
if (Context.hadError())
return -1;
assert(GenModule && "Emitted no diagnostics but IR generation failed?");
performLLVM(IRGenOpts, Context.Diags, /*diagMutex*/ nullptr, /*hash*/ nullptr,
GenModule.getModule(), GenModule.getTargetMachine(),
PSPs.OutputFilename, Context.Stats);
if (Context.hadError())
return -1;
// Load libSwiftCore to setup process arguments.
//
// This must be done here, before any library loading has been done, to avoid
// racing with the static initializers in user code.
// Setup interpreted process arguments.
using ArgOverride = void (* SWIFT_CC(swift))(const char **, int);
#if defined(_WIN32)
auto stdlib = loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPaths);
if (!stdlib) {
CI.getDiags().diagnose(SourceLoc(),
diag::error_immediate_mode_missing_stdlib);
return -1;
}
auto module = static_cast<HMODULE>(stdlib);
auto emplaceProcessArgs = reinterpret_cast<ArgOverride>(
GetProcAddress(module, "_swift_stdlib_overrideUnsafeArgvArgc"));
if (emplaceProcessArgs == nullptr)
return -1;
#else
// In case the compiler is built with swift modules, it already has the stdlib
// linked to. First try to lookup the symbol with the standard library
// resolving.
auto emplaceProcessArgs
= (ArgOverride)dlsym(RTLD_DEFAULT, "_swift_stdlib_overrideUnsafeArgvArgc");
if (dlerror()) {
// If this does not work (= the Swift modules are not linked to the tool),
// we have to explicitly load the stdlib.
auto stdlib = loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPaths);
if (!stdlib) {
CI.getDiags().diagnose(SourceLoc(),
diag::error_immediate_mode_missing_stdlib);
return -1;
}
dlerror();
emplaceProcessArgs
= (ArgOverride)dlsym(stdlib, "_swift_stdlib_overrideUnsafeArgvArgc");
if (dlerror())
return -1;
}
#endif
SmallVector<const char *, 32> argBuf;
for (size_t i = 0; i < CmdLine.size(); ++i) {
argBuf.push_back(CmdLine[i].c_str());
}
argBuf.push_back(nullptr);
(*emplaceProcessArgs)(argBuf.data(), CmdLine.size());
if (autolinkImportedModules(swiftModule, IRGenOpts))
return -1;
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = 2;
PMBuilder.Inliner = llvm::createFunctionInliningPass(200);
// Build the ExecutionEngine.
llvm::TargetOptions TargetOpt;
std::string CPU;
std::string Triple;
std::vector<std::string> Features;
std::tie(TargetOpt, CPU, Features, Triple)
= getIRTargetOptions(IRGenOpts, swiftModule->getASTContext());
std::unique_ptr<llvm::orc::LLJIT> JIT;
{
auto JITOrErr =
llvm::orc::LLJITBuilder()
.setJITTargetMachineBuilder(
llvm::orc::JITTargetMachineBuilder(llvm::Triple(Triple))
.setRelocationModel(llvm::Reloc::PIC_)
.setOptions(std::move(TargetOpt))
.setCPU(std::move(CPU))
.addFeatures(Features)
.setCodeGenOptLevel(llvm::CodeGenOpt::Default))
.create();
if (!JITOrErr) {
llvm::logAllUnhandledErrors(JITOrErr.takeError(), llvm::errs(), "");
return -1;
} else
JIT = std::move(*JITOrErr);
}
auto Module = GenModule.getModule();
switch (IRGenOpts.DumpJIT) {
case JITDebugArtifact::None:
break;
case JITDebugArtifact::LLVMIR:
DumpLLVMIR(*Module);
break;
case JITDebugArtifact::Object:
JIT->getObjTransformLayer().setTransform(llvm::orc::DumpObjects());
break;
}
{
// Get a generator for the process symbols and attach it to the main
// JITDylib.
if (auto G = llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(Module->getDataLayout().getGlobalPrefix()))
JIT->getMainJITDylib().addGenerator(std::move(*G));
else {
logAllUnhandledErrors(G.takeError(), llvm::errs(), "");
return -1;
}
}
LLVM_DEBUG(llvm::dbgs() << "Module to be executed:\n";
Module->dump());
{
if (auto Err = JIT->addIRModule(std::move(GenModule).intoThreadSafeContext())) {
llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "");
return -1;
}
}
using MainFnTy = int(*)(int, char*[]);
LLVM_DEBUG(llvm::dbgs() << "Running static constructors\n");
if (auto Err = JIT->initialize(JIT->getMainJITDylib())) {
llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "");
return -1;
}
MainFnTy JITMain = nullptr;
if (auto MainFnOrErr = JIT->lookup("main"))
JITMain = llvm::jitTargetAddressToFunction<MainFnTy>(MainFnOrErr->getAddress());
else {
logAllUnhandledErrors(MainFnOrErr.takeError(), llvm::errs(), "");
return -1;
}
LLVM_DEBUG(llvm::dbgs() << "Running main\n");
int Result = llvm::orc::runAsMain(JITMain, CmdLine);
LLVM_DEBUG(llvm::dbgs() << "Running static destructors\n");
if (auto Err = JIT->deinitialize(JIT->getMainJITDylib())) {
logAllUnhandledErrors(std::move(Err), llvm::errs(), "");
return -1;
}
return Result;
}
<|endoftext|>
|
<commit_before>#include "../Thread.h"
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
__thread int x = 0;
void print()
{
printf("pid=%d tid=%d x=%d\n", getpid(), muduo::CurrentThread::tid(), x);
}
int main()
{
printf("parent %d\n", getpid());
print();
x = 1;
print();
pid_t p = fork();
if (p == 0)
{
printf("chlid %d\n", getpid());
// child
print();
x = 2;
print();
pid_t p = fork();
if (p == 0)
{
printf("grandchlid %d\n", getpid());
print();
x = 3;
print();
}
}
else
{
// parent
print();
}
}
<commit_msg>sync with muduo/base.<commit_after>#include "../Thread.h"
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
__thread int x = 0;
void print()
{
printf("pid=%d tid=%d x=%d\n", getpid(), muduo::CurrentThread::tid(), x);
}
int main()
{
printf("parent %d\n", getpid());
print();
x = 1;
print();
pid_t p = fork();
if (p == 0)
{
printf("chlid %d\n", getpid());
// child
print();
x = 2;
print();
if (fork() == 0)
{
printf("grandchlid %d\n", getpid());
print();
x = 3;
print();
}
}
else
{
// parent
print();
}
}
<|endoftext|>
|
<commit_before>#include <combine/omexdescription.h>
#include <sbml/xml/XMLInputStream.h>
#include <sbml/xml/XMLOutputStream.h>
#include <sbml/xml/XMLNode.h>
#include <sbml/xml/XMLToken.h>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <sstream>
LIBSBML_CPP_NAMESPACE_USE
LIBCOMBINE_CPP_NAMESPACE_USE
const std::string &
OmexDescription::getRdfNS()
{
static std::string ns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
return ns;
}
const std::string &
OmexDescription::getDcNS()
{
static std::string ns = "http://purl.org/dc/terms/";
return ns;
}
bool
OmexDescription::isEmpty() const
{
bool haveDescription = !mDescription.empty();
if (!haveDescription) return true;
bool haveCreator = !mCreators.empty();
if (!haveCreator) return true;
bool firstCreatorEmpty = mCreators[0].isEmpty();
if (firstCreatorEmpty) return true;
return false;
}
std::vector<OmexDescription>
OmexDescription::parseFile(const std::string &fileName)
{
XMLInputStream stream(fileName.c_str(), true );
return readFrom(stream);
}
std::vector<OmexDescription>
OmexDescription::parseString(const std::string& xml)
{
XMLInputStream stream(xml.c_str(), false );
return readFrom(stream);
}
std::vector<OmexDescription>
OmexDescription::readFrom(XMLInputStream &stream)
{
std::vector<OmexDescription> result;
const XMLToken& start = stream.peek();
if (!start.isStart() || start.getName() != "RDF")
return result;
XMLToken next = stream.next();
stream.skipText();
next = stream.peek();
while (next.isStart() && next.getName() == "Description")
{
result.push_back(OmexDescription(stream));
stream.skipText();
next = stream.peek();
}
return result;
}
OmexDescription::OmexDescription()
: mAbout()
, mDescription()
, mCreators()
, mCreated()
, mModified()
{
}
std::string
OmexDescription::readString(XMLInputStream &stream)
{
std::stringstream str;
while (stream.peek().isText())
{
XMLToken current = stream.next();
str << current.getCharacters();
}
return str.str();
}
Date
OmexDescription::readDate(XMLInputStream &stream)
{
stream.skipText();
XMLToken next = stream.next();
if (next.isStart() && next.getName() == "W3CDTF" )
{
next = stream.next();
return Date(next.getCharacters());
}
return Date();
}
OmexDescription::OmexDescription(XMLInputStream &stream)
: mAbout()
, mDescription()
, mCreators()
, mCreated()
, mModified()
{
XMLNode current = stream.next();
if (!current.isStart() || current.getName() != "Description")
return;
mAbout = current.getAttrValue("about", getRdfNS());
while(stream.isGood())
{
stream.skipText();
XMLToken next = stream.next();
if (next.isEndFor(current))
return;
if (!next.isStart())
continue;
if (next.getName() == "description")
{
mDescription = readString(stream);
stream.skipPastEnd(next);
}
else if (next.getName() == "modified")
{
Date newDate = readDate(stream);
mModified.push_back(newDate);
stream.skipPastEnd(next);
}
else if (next.getName() == "created")
{
mCreated = readDate(stream);
stream.skipPastEnd(next);
}
else if (next.getName() == "creator")
{
mCreators.push_back(VCard(stream, next));
}
}
stream.skipPastEnd(current);
}
std::string
OmexDescription::toXML(bool omitDeclaration)
{
if (mModified.empty())
{
mModified.push_back(getCurrentDateAndTime());
}
std::stringstream modifications;
for (std::vector<Date>::iterator it = mModified.begin();
it != mModified.end(); ++it)
{
modifications << " <dcterms:modified rdf:parseType='Resource'>\n"
<< " <dcterms:W3CDTF>"
<< (*it).getDateAsString()
<< "</dcterms:W3CDTF>\n"
<< " </dcterms:modified>\n";
}
std::stringstream creators;
for(std::vector<VCard>::iterator it = mCreators.begin();
it != mCreators.end(); ++it)
creators << (*it).toXML() << "\n";
std::stringstream result;
if (!omitDeclaration)
result << "<?xml version='1.0' encoding='UTF-8'?>\n";
result << "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' "
<< "xmlns:dcterms='http://purl.org/dc/terms/' "
<< "xmlns:vCard='http://www.w3.org/2006/vcard/ns#'>\n"
<< " <rdf:Description rdf:about='" << mAbout << "'>\n"
<< " <dcterms:description>" << mDescription << "</dcterms:description>\n"
<< modifications.str()
<< " <dcterms:created rdf:parseType='Resource'>\n"
<< " <dcterms:W3CDTF>"<< mCreated.getDateAsString() << "</dcterms:W3CDTF>\n"
<< " </dcterms:created>\n"
<< creators.str()
<<" </rdf:Description>\n"
<< "</rdf:RDF>\n";
return result.str();
}
std::string
OmexDescription::getDescription() const
{
return mDescription;
}
void
OmexDescription::setDescription(const std::string &description)
{
mDescription = description;
}
std::string
OmexDescription::getAbout() const
{
return mAbout;
}
void
OmexDescription::setAbout(const std::string &about)
{
mAbout = about;
}
const std::vector<VCard>&
OmexDescription::getCreators() const
{
return mCreators;
}
std::vector<VCard>&
OmexDescription::getCreators()
{
return mCreators;
}
size_t
OmexDescription::getNumCreators() const
{
return mCreators.size();
}
void
OmexDescription::setCreators(const std::vector<VCard> &creators)
{
mCreators = creators;
}
void
OmexDescription::addCreator(const VCard &creator)
{
mCreators.push_back(creator);
}
const Date &
OmexDescription::getCreated() const
{
return mCreated;
}
Date &
OmexDescription::getCreated()
{
return mCreated;
}
VCard
OmexDescription::getCreator(unsigned int index) const
{
if (index >= mCreators.size())
return VCard();
return mCreators[index];
}
void
OmexDescription::setCreated(const Date &created)
{
mCreated = created;
}
Date
OmexDescription::getCurrentDateAndTime()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = gmtime ( &rawtime );
char buffer[25];
size_t length = strftime(buffer, 25, "%Y-%m-%dT%TZ",
timeinfo);
std::stringstream str;
str << buffer;
return str.str();
}
const std::vector<Date>&
OmexDescription::getModified() const
{
return mModified;
}
std::vector<Date>&
OmexDescription::getModified()
{
return mModified;
}
Date OmexDescription::getModified(int index) const
{
if (index < 0 || index >= (int)mModified.size())
return Date();
return mModified[index];
}
size_t
OmexDescription::getNumModified() const
{
return mModified.size();
}
void
OmexDescription::setModified(const std::vector<Date> &modified)
{
mModified = modified;
}
void
OmexDescription::addModification(const Date &date)
{
mModified.push_back(date);
}
void
OmexDescription::writeToFile(const std::string &fileName)
{
std::ofstream stream(fileName.c_str());
stream << toXML();
stream.flush();
stream.close();
}
<commit_msg>- issue #22: read xml files without declaration, consider anything that has a description or a creator as a valid description<commit_after>#include <combine/omexdescription.h>
#include <sbml/xml/XMLInputStream.h>
#include <sbml/xml/XMLOutputStream.h>
#include <sbml/xml/XMLNode.h>
#include <sbml/xml/XMLToken.h>
#include <sbml/xml/XMLErrorLog.h>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <sstream>
LIBSBML_CPP_NAMESPACE_USE
LIBCOMBINE_CPP_NAMESPACE_USE
const std::string &
OmexDescription::getRdfNS()
{
static std::string ns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
return ns;
}
const std::string &
OmexDescription::getDcNS()
{
static std::string ns = "http://purl.org/dc/terms/";
return ns;
}
bool
OmexDescription::isEmpty() const
{
bool haveDescription = !mDescription.empty();
if (haveDescription) return false;
bool haveCreator = !mCreators.empty();
if (!haveCreator) return true;
bool firstCreatorEmpty = mCreators[0].isEmpty();
if (firstCreatorEmpty) return true;
return false;
}
std::vector<OmexDescription>
OmexDescription::parseFile(const std::string &fileName)
{
XMLInputStream stream(fileName.c_str(), true );
return readFrom(stream);
}
std::vector<OmexDescription>
OmexDescription::parseString(const std::string& xml)
{
const static std::string xml_declaration("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
if (xml.find(xml_declaration) == std::string::npos)
{
return parseString(xml_declaration + xml);
}
XMLInputStream stream(xml.c_str(), false );
XMLErrorLog log;
stream.setErrorLog(&log);
return readFrom(stream);
}
std::vector<OmexDescription>
OmexDescription::readFrom(XMLInputStream &stream)
{
std::vector<OmexDescription> result;
const XMLToken& start = stream.peek();
if (!start.isStart() || start.getName() != "RDF")
return result;
XMLToken next = stream.next();
stream.skipText();
next = stream.peek();
while (next.isStart() && next.getName() == "Description")
{
result.push_back(OmexDescription(stream));
stream.skipText();
next = stream.peek();
}
return result;
}
OmexDescription::OmexDescription()
: mAbout()
, mDescription()
, mCreators()
, mCreated()
, mModified()
{
}
std::string
OmexDescription::readString(XMLInputStream &stream)
{
std::stringstream str;
while (stream.peek().isText())
{
XMLToken current = stream.next();
str << current.getCharacters();
}
return str.str();
}
Date
OmexDescription::readDate(XMLInputStream &stream)
{
stream.skipText();
XMLToken next = stream.next();
if (next.isStart() && next.getName() == "W3CDTF" )
{
next = stream.next();
return Date(next.getCharacters());
}
return Date();
}
OmexDescription::OmexDescription(XMLInputStream &stream)
: mAbout()
, mDescription()
, mCreators()
, mCreated()
, mModified()
{
XMLNode current = stream.next();
if (!current.isStart() || current.getName() != "Description")
return;
mAbout = current.getAttrValue("about", getRdfNS());
while(stream.isGood())
{
stream.skipText();
XMLToken next = stream.next();
if (next.isEndFor(current))
return;
if (!next.isStart())
continue;
if (next.getName() == "description")
{
mDescription = readString(stream);
stream.skipPastEnd(next);
}
else if (next.getName() == "modified")
{
Date newDate = readDate(stream);
mModified.push_back(newDate);
stream.skipPastEnd(next);
}
else if (next.getName() == "created")
{
mCreated = readDate(stream);
stream.skipPastEnd(next);
}
else if (next.getName() == "creator")
{
mCreators.push_back(VCard(stream, next));
}
}
stream.skipPastEnd(current);
}
std::string
OmexDescription::toXML(bool omitDeclaration)
{
if (mModified.empty())
{
mModified.push_back(getCurrentDateAndTime());
}
std::stringstream modifications;
for (std::vector<Date>::iterator it = mModified.begin();
it != mModified.end(); ++it)
{
modifications << " <dcterms:modified rdf:parseType='Resource'>\n"
<< " <dcterms:W3CDTF>"
<< (*it).getDateAsString()
<< "</dcterms:W3CDTF>\n"
<< " </dcterms:modified>\n";
}
std::stringstream creators;
for(std::vector<VCard>::iterator it = mCreators.begin();
it != mCreators.end(); ++it)
creators << (*it).toXML() << "\n";
std::stringstream result;
if (!omitDeclaration)
result << "<?xml version='1.0' encoding='UTF-8'?>\n";
result << "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' "
<< "xmlns:dcterms='http://purl.org/dc/terms/' "
<< "xmlns:vCard='http://www.w3.org/2006/vcard/ns#'>\n"
<< " <rdf:Description rdf:about='" << mAbout << "'>\n"
<< " <dcterms:description>" << mDescription << "</dcterms:description>\n"
<< modifications.str()
<< " <dcterms:created rdf:parseType='Resource'>\n"
<< " <dcterms:W3CDTF>"<< mCreated.getDateAsString() << "</dcterms:W3CDTF>\n"
<< " </dcterms:created>\n"
<< creators.str()
<<" </rdf:Description>\n"
<< "</rdf:RDF>\n";
return result.str();
}
std::string
OmexDescription::getDescription() const
{
return mDescription;
}
void
OmexDescription::setDescription(const std::string &description)
{
mDescription = description;
}
std::string
OmexDescription::getAbout() const
{
return mAbout;
}
void
OmexDescription::setAbout(const std::string &about)
{
mAbout = about;
}
const std::vector<VCard>&
OmexDescription::getCreators() const
{
return mCreators;
}
std::vector<VCard>&
OmexDescription::getCreators()
{
return mCreators;
}
size_t
OmexDescription::getNumCreators() const
{
return mCreators.size();
}
void
OmexDescription::setCreators(const std::vector<VCard> &creators)
{
mCreators = creators;
}
void
OmexDescription::addCreator(const VCard &creator)
{
mCreators.push_back(creator);
}
const Date &
OmexDescription::getCreated() const
{
return mCreated;
}
Date &
OmexDescription::getCreated()
{
return mCreated;
}
VCard
OmexDescription::getCreator(unsigned int index) const
{
if (index >= mCreators.size())
return VCard();
return mCreators[index];
}
void
OmexDescription::setCreated(const Date &created)
{
mCreated = created;
}
Date
OmexDescription::getCurrentDateAndTime()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = gmtime ( &rawtime );
char buffer[25];
size_t length = strftime(buffer, 25, "%Y-%m-%dT%TZ",
timeinfo);
std::stringstream str;
str << buffer;
return str.str();
}
const std::vector<Date>&
OmexDescription::getModified() const
{
return mModified;
}
std::vector<Date>&
OmexDescription::getModified()
{
return mModified;
}
Date OmexDescription::getModified(int index) const
{
if (index < 0 || index >= (int)mModified.size())
return Date();
return mModified[index];
}
size_t
OmexDescription::getNumModified() const
{
return mModified.size();
}
void
OmexDescription::setModified(const std::vector<Date> &modified)
{
mModified = modified;
}
void
OmexDescription::addModification(const Date &date)
{
mModified.push_back(date);
}
void
OmexDescription::writeToFile(const std::string &fileName)
{
std::ofstream stream(fileName.c_str());
stream << toXML();
stream.flush();
stream.close();
}
<|endoftext|>
|
<commit_before>/*
*
*/
#include "IPyraNet2DLayer.h"
#include <assert.h>
#define UNIFORM_PLUS_MINUS_ONE ( static_cast<OutType>((2.0 * rand())/RAND_MAX - 1.0) )
template<class OutType>
IPyraNet2DLayer<OutType>::IPyraNet2DLayer()
: IPyraNetLayer<OutType>(),
width(0),
height(0),
receptiveSize(0),
overlap(0),
inhibitorySize(0)
{
}
template<class OutType>
IPyraNet2DLayer<OutType>::IPyraNet2DLayer(int receptive, int inhibitory, int overlap, IPyraNetActivationFunction<OutType>* activationFunc)
: IPyraNetLayer<OutType>(),
width(0),
height(0),
receptiveSize(receptive),
overlap(overlap),
inhibitorySize(inhibitory)
{
setActivationFunction(activationFunc);
}
template<class OutType>
IPyraNet2DLayer<OutType>::~IPyraNet2DLayer() {
}
template<class OutType>
void IPyraNet2DLayer<OutType>::initWeights() {
assert(getParentLayer() != NULL);
IPyraNetLayer<OutType>* parent = getParentLayer();
// get parent size
int parentSize[2];
parent->getSize(parentSize);
// we need to have as many weights as the number of neurons in last
// layer.
weights.resize(parentSize[0]);
for (int u = 0; u < parentSize[0]; ++u) {
weights[u].resize(parentSize[1]);
for (int v = 0; v < parentSize[1]; ++v) {
weights[u][v] = UNIFORM_PLUS_MINUS_ONE;
}
}
}
template<class OutType>
void IPyraNet2DLayer<OutType>::initBiases() {
biases.resize(width);
for (int u = 0; u < width; ++u) {
biases[u].resize(height);
for (int v = 0; v < height; ++v) {
biases[u][v] = UNIFORM_PLUS_MINUS_ONE;
}
}
}
template<class OutType>
OutType IPyraNet2DLayer<OutType>::getNeuronOutput(int dimensions, int* neuronLocation) {
// sanity checks
assert (dimensions == 2);
assert (neuronLocation != NULL);
assert (neuronLocation[0] >= 0 && neuronLocation[1] >= 0);
assert (getParentLayer() != NULL);
assert (getActivationFunction() != NULL);
// parent layer pointer
IPyraNetLayer<OutType>* parent = getParentLayer();
// compute the gap
const int gap = receptiveSize - overlap;
// just for compliance with the article
const int u = neuronLocation[0];
const int v = neuronLocation[1];
OutType receptiveAccumulator = 0;
OutType inhibitoryAccumulator = 0;
OutType bias = biases[u][v];
int parentLoc[2];
// iterate through the neurons inside the receptive field of the previous layer
const int max_u = u * gap + receptiveSize;
const int max_v = v * gap + receptiveSize;
// for (int i = (u - 1) * gap + 1; i <= max_u; ++i) {
for (int i = u * gap + 1; i < max_u; ++i) {
parentLoc[0] = i;
//for (int j = (v - 1) * gap + 1; j <= max_v; ++j) {
for (int j = v * gap + 1; j < max_v; ++j) {
parentLoc[1] = j;
OutType parentOutput = parent->getNeuronOutput(2, parentLoc);
OutType weight = weights[i][j];
receptiveAccumulator += parentOutput * weight;
}
}
// iterate through the neurons inside the inhibitory field
// TODO
OutType result = getActivationFunction()->compute(receptiveAccumulator - inhibitoryAccumulator + bias);
return result;
}
template<class OutType>
int IPyraNet2DLayer<OutType>::getDimensions() const {
return 2;
}
template<class OutType>
void IPyraNet2DLayer<OutType>::getSize(int* size) {
assert(size != NULL);
size[0] = width;
size[1] = height;
}
template<class OutType>
void IPyraNet2DLayer<OutType>::setParentLayer(IPyraNetLayer<OutType>* parent) {
assert(parent != NULL);
assert(receptiveSize != 0);
assert(overlap != 0);
// calls base class
IPyraNetLayer<OutType>::setParentLayer(parent);
const int dims = parent->getDimensions();
// we can just connect 2d layers to 2d layers
assert(dims == 2);
// get parent size
int parentSize[2];
parent->getSize(parentSize);
// compute the gap
const float gap = static_cast<float>(receptiveSize - overlap);
width = static_cast<int>(floor(static_cast<float>(parentSize[0] - overlap) / gap));
height = static_cast<int>(floor(static_cast<float>(parentSize[1] - overlap) / gap));
// init weights and biases
initWeights();
initBiases();
}
// explicit instantiations
template class IPyraNet2DLayer<float>;
template class IPyraNet2DLayer<double>;<commit_msg>Added inhibitory field computation for 2D layers.<commit_after>/*
*
*/
#include "IPyraNet2DLayer.h"
#include <assert.h>
#define UNIFORM_PLUS_MINUS_ONE ( static_cast<OutType>((2.0 * rand())/RAND_MAX - 1.0) )
template<class OutType>
IPyraNet2DLayer<OutType>::IPyraNet2DLayer()
: IPyraNetLayer<OutType>(),
width(0),
height(0),
receptiveSize(0),
overlap(0),
inhibitorySize(0)
{
}
template<class OutType>
IPyraNet2DLayer<OutType>::IPyraNet2DLayer(int receptive, int inhibitory, int overlap, IPyraNetActivationFunction<OutType>* activationFunc)
: IPyraNetLayer<OutType>(),
width(0),
height(0),
receptiveSize(receptive),
overlap(overlap),
inhibitorySize(inhibitory)
{
setActivationFunction(activationFunc);
}
template<class OutType>
IPyraNet2DLayer<OutType>::~IPyraNet2DLayer() {
}
template<class OutType>
void IPyraNet2DLayer<OutType>::initWeights() {
assert(getParentLayer() != NULL);
IPyraNetLayer<OutType>* parent = getParentLayer();
// get parent size
int parentSize[2];
parent->getSize(parentSize);
// we need to have as many weights as the number of neurons in last
// layer.
weights.resize(parentSize[0]);
for (int u = 0; u < parentSize[0]; ++u) {
weights[u].resize(parentSize[1]);
for (int v = 0; v < parentSize[1]; ++v) {
weights[u][v] = UNIFORM_PLUS_MINUS_ONE;
}
}
}
template<class OutType>
void IPyraNet2DLayer<OutType>::initBiases() {
biases.resize(width);
for (int u = 0; u < width; ++u) {
biases[u].resize(height);
for (int v = 0; v < height; ++v) {
biases[u][v] = UNIFORM_PLUS_MINUS_ONE;
}
}
}
template<class OutType>
OutType IPyraNet2DLayer<OutType>::getNeuronOutput(int dimensions, int* neuronLocation) {
// sanity checks
assert (dimensions == 2);
assert (neuronLocation != NULL);
assert (neuronLocation[0] >= 0 && neuronLocation[1] >= 0);
assert (getParentLayer() != NULL);
assert (getActivationFunction() != NULL);
// parent layer pointer
IPyraNetLayer<OutType>* parent = getParentLayer();
// compute the gap
const int gap = receptiveSize - overlap;
// just for compliance with the article
const int u = neuronLocation[0];
const int v = neuronLocation[1];
OutType receptiveAccumulator = 0;
OutType bias = biases[u][v];
int parentLoc[2];
// iterate through the neurons inside the receptive field of the previous layer
//
// ******
// **uv**
// ******
//
const int min_u = u * gap + 1;
const int min_v = v * gap + 1;
const int max_u = u * gap + receptiveSize;
const int max_v = v * gap + receptiveSize;
// for (int i = (u - 1) * gap + 1; i <= max_u; ++i) {
for (int i = min_u; i < max_u; ++i) {
parentLoc[0] = i;
//for (int j = (v - 1) * gap + 1; j <= max_v; ++j) {
for (int j = min_v; j < max_v; ++j) {
parentLoc[1] = j;
OutType parentOutput = parent->getNeuronOutput(2, parentLoc);
OutType weight = weights[i][j];
receptiveAccumulator += parentOutput * weight;
}
}
// iterate through the neurons inside the inhibitory field
//
// xxxxxxxx
// x******x
// x**uv**x
// x******x
// xxxxxxxx
//
// the inhibitory field is 'x' and the receptive field is '*'
int parentSize[2];
parent->getSize(parentSize);
OutType inhibitoryAccumulator = 0;
const int inhibitory_min_u = min_u - inhibitorySize;
const int inhibitory_min_v = min_v - inhibitorySize;
const int inhibitory_max_u = max_u + inhibitorySize;
const int inhibitory_max_v = max_v + inhibitorySize;
for (int i = inhibitory_min_u; i < inhibitory_max_u; ++i) {
parentLoc[0] = i;
for (int j = inhibitory_min_v; j < inhibitory_max_v; ++j) {
// ignore neurons of the inhibitory field which fall outside
// of the parent 2D area
if (i < 0 || j < 0)
continue;
if (i > parentSize[0] || j > parentSize[1])
continue;
// ignore neurons in the receptive field!
if (i >= min_u && i < max_u)
continue;
if (j >= min_v && j < max_v)
continue;
parentLoc[1] = j;
OutType parentOutput = parent->getNeuronOutput(2, parentLoc);
OutType weight = weights[i][j];
inhibitoryAccumulator += parentOutput * weight;
}
}
OutType result = getActivationFunction()->compute(receptiveAccumulator - inhibitoryAccumulator + bias);
return result;
}
template<class OutType>
int IPyraNet2DLayer<OutType>::getDimensions() const {
return 2;
}
template<class OutType>
void IPyraNet2DLayer<OutType>::getSize(int* size) {
assert(size != NULL);
size[0] = width;
size[1] = height;
}
template<class OutType>
void IPyraNet2DLayer<OutType>::setParentLayer(IPyraNetLayer<OutType>* parent) {
assert(parent != NULL);
assert(receptiveSize != 0);
assert(overlap != 0);
// calls base class
IPyraNetLayer<OutType>::setParentLayer(parent);
const int dims = parent->getDimensions();
// we can just connect 2d layers to 2d layers
assert(dims == 2);
// get parent size
int parentSize[2];
parent->getSize(parentSize);
// compute the gap
const float gap = static_cast<float>(receptiveSize - overlap);
width = static_cast<int>(floor(static_cast<float>(parentSize[0] - overlap) / gap));
height = static_cast<int>(floor(static_cast<float>(parentSize[1] - overlap) / gap));
// init weights and biases
initWeights();
initBiases();
}
// explicit instantiations
template class IPyraNet2DLayer<float>;
template class IPyraNet2DLayer<double>;<|endoftext|>
|
<commit_before>//===- MCJITTest.cpp - Unit tests for the MCJIT ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This test suite verifies basic MCJIT functionality when invoked form the C
// API.
//
//===----------------------------------------------------------------------===//
#include "llvm-c/Analysis.h"
#include "MCJITTestAPICommon.h"
#include "llvm-c/Core.h"
#include "llvm-c/ExecutionEngine.h"
#include "llvm-c/Target.h"
#include "llvm-c/Transforms/Scalar.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/Support/Host.h"
#include "gtest/gtest.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
static bool didCallAllocateCodeSection;
static uint8_t *roundTripAllocateCodeSection(void *object, uintptr_t size,
unsigned alignment,
unsigned sectionID,
const char *sectionName) {
didCallAllocateCodeSection = true;
return static_cast<SectionMemoryManager*>(object)->allocateCodeSection(
size, alignment, sectionID, sectionName);
}
static uint8_t *roundTripAllocateDataSection(void *object, uintptr_t size,
unsigned alignment,
unsigned sectionID,
const char *sectionName,
LLVMBool isReadOnly) {
return static_cast<SectionMemoryManager*>(object)->allocateDataSection(
size, alignment, sectionID, sectionName, isReadOnly);
}
static LLVMBool roundTripFinalizeMemory(void *object, char **errMsg) {
std::string errMsgString;
bool result =
static_cast<SectionMemoryManager*>(object)->finalizeMemory(&errMsgString);
if (result) {
*errMsg = LLVMCreateMessage(errMsgString.c_str());
return 1;
}
return 0;
}
static void roundTripDestroy(void *object) {
delete static_cast<SectionMemoryManager*>(object);
}
namespace {
// memory manager to test reserve allocation space callback
class TestReserveAllocationSpaceMemoryManager: public SectionMemoryManager {
public:
uintptr_t ReservedCodeSize;
uintptr_t UsedCodeSize;
uintptr_t ReservedDataSizeRO;
uintptr_t UsedDataSizeRO;
uintptr_t ReservedDataSizeRW;
uintptr_t UsedDataSizeRW;
TestReserveAllocationSpaceMemoryManager() :
ReservedCodeSize(0), UsedCodeSize(0), ReservedDataSizeRO(0),
UsedDataSizeRO(0), ReservedDataSizeRW(0), UsedDataSizeRW(0) {
}
virtual bool needsToReserveAllocationSpace() {
return true;
}
virtual void reserveAllocationSpace(
uintptr_t CodeSize, uintptr_t DataSizeRO, uintptr_t DataSizeRW) {
ReservedCodeSize = CodeSize;
ReservedDataSizeRO = DataSizeRO;
ReservedDataSizeRW = DataSizeRW;
}
void useSpace(uintptr_t* UsedSize, uintptr_t Size, unsigned Alignment) {
uintptr_t AlignedSize = (Size + Alignment - 1) / Alignment * Alignment;
uintptr_t AlignedBegin = (*UsedSize + Alignment - 1) / Alignment * Alignment;
*UsedSize = AlignedBegin + AlignedSize;
}
virtual uint8_t* allocateDataSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID, StringRef SectionName, bool IsReadOnly) {
useSpace(IsReadOnly ? &UsedDataSizeRO : &UsedDataSizeRW, Size, Alignment);
return SectionMemoryManager::allocateDataSection(Size, Alignment,
SectionID, SectionName, IsReadOnly);
}
uint8_t* allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID, StringRef SectionName) {
useSpace(&UsedCodeSize, Size, Alignment);
return SectionMemoryManager::allocateCodeSection(Size, Alignment,
SectionID, SectionName);
}
};
class MCJITCAPITest : public testing::Test, public MCJITTestAPICommon {
protected:
MCJITCAPITest() {
// The architectures below are known to be compatible with MCJIT as they
// are copied from test/ExecutionEngine/MCJIT/lit.local.cfg and should be
// kept in sync.
SupportedArchs.push_back(Triple::aarch64);
SupportedArchs.push_back(Triple::arm);
SupportedArchs.push_back(Triple::mips);
SupportedArchs.push_back(Triple::x86);
SupportedArchs.push_back(Triple::x86_64);
// Some architectures have sub-architectures in which tests will fail, like
// ARM. These two vectors will define if they do have sub-archs (to avoid
// extra work for those who don't), and if so, if they are listed to work
HasSubArchs.push_back(Triple::arm);
SupportedSubArchs.push_back("armv6");
SupportedSubArchs.push_back("armv7");
// The operating systems below are known to be sufficiently incompatible
// that they will fail the MCJIT C API tests.
UnsupportedOSs.push_back(Triple::Cygwin);
}
virtual void SetUp() {
didCallAllocateCodeSection = false;
Module = 0;
Function = 0;
Engine = 0;
Error = 0;
}
virtual void TearDown() {
if (Engine)
LLVMDisposeExecutionEngine(Engine);
else if (Module)
LLVMDisposeModule(Module);
}
void buildSimpleFunction() {
Module = LLVMModuleCreateWithName("simple_module");
LLVMSetTarget(Module, HostTriple.c_str());
Function = LLVMAddFunction(
Module, "simple_function", LLVMFunctionType(LLVMInt32Type(), 0, 0, 0));
LLVMSetFunctionCallConv(Function, LLVMCCallConv);
LLVMBasicBlockRef entry = LLVMAppendBasicBlock(Function, "entry");
LLVMBuilderRef builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(builder, entry);
LLVMBuildRet(builder, LLVMConstInt(LLVMInt32Type(), 42, 0));
LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
LLVMDisposeMessage(Error);
LLVMDisposeBuilder(builder);
}
void buildModuleWithCodeAndData() {
Module = LLVMModuleCreateWithName("simple_module");
LLVMSetTarget(Module, HostTriple.c_str());
// build a global variable initialized to "Hello World!"
LLVMValueRef GlobalVar = LLVMAddGlobal(Module, LLVMInt32Type(), "intVal");
LLVMSetInitializer(GlobalVar, LLVMConstInt(LLVMInt32Type(), 42, 0));
{
Function = LLVMAddFunction(
Module, "getGlobal", LLVMFunctionType(LLVMInt32Type(), 0, 0, 0));
LLVMSetFunctionCallConv(Function, LLVMCCallConv);
LLVMBasicBlockRef Entry = LLVMAppendBasicBlock(Function, "entry");
LLVMBuilderRef Builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(Builder, Entry);
LLVMValueRef IntVal = LLVMBuildLoad(Builder, GlobalVar, "intVal");
LLVMBuildRet(Builder, IntVal);
LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
LLVMDisposeMessage(Error);
LLVMDisposeBuilder(Builder);
}
{
LLVMTypeRef ParamTypes[] = { LLVMInt32Type() };
Function2 = LLVMAddFunction(
Module, "setGlobal", LLVMFunctionType(LLVMVoidType(), ParamTypes, 1, 0));
LLVMSetFunctionCallConv(Function2, LLVMCCallConv);
LLVMBasicBlockRef Entry = LLVMAppendBasicBlock(Function2, "entry");
LLVMBuilderRef Builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(Builder, Entry);
LLVMValueRef Arg = LLVMGetParam(Function2, 0);
LLVMBuildStore(Builder, Arg, GlobalVar);
LLVMBuildRetVoid(Builder);
LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
LLVMDisposeMessage(Error);
LLVMDisposeBuilder(Builder);
}
}
void buildMCJITOptions() {
LLVMInitializeMCJITCompilerOptions(&Options, sizeof(Options));
Options.OptLevel = 2;
// Just ensure that this field still exists.
Options.NoFramePointerElim = false;
}
void useRoundTripSectionMemoryManager() {
Options.MCJMM = LLVMCreateSimpleMCJITMemoryManager(
new SectionMemoryManager(),
roundTripAllocateCodeSection,
roundTripAllocateDataSection,
roundTripFinalizeMemory,
roundTripDestroy);
}
void buildMCJITEngine() {
ASSERT_EQ(
0, LLVMCreateMCJITCompilerForModule(&Engine, Module, &Options,
sizeof(Options), &Error));
}
void buildAndRunPasses() {
LLVMPassManagerRef pass = LLVMCreatePassManager();
LLVMAddTargetData(LLVMGetExecutionEngineTargetData(Engine), pass);
LLVMAddConstantPropagationPass(pass);
LLVMAddInstructionCombiningPass(pass);
LLVMRunPassManager(pass, Module);
LLVMDisposePassManager(pass);
}
LLVMModuleRef Module;
LLVMValueRef Function;
LLVMValueRef Function2;
LLVMMCJITCompilerOptions Options;
LLVMExecutionEngineRef Engine;
char *Error;
};
} // end anonymous namespace
TEST_F(MCJITCAPITest, simple_function) {
SKIP_UNSUPPORTED_PLATFORM;
buildSimpleFunction();
buildMCJITOptions();
buildMCJITEngine();
buildAndRunPasses();
union {
void *raw;
int (*usable)();
} functionPointer;
functionPointer.raw = LLVMGetPointerToGlobal(Engine, Function);
EXPECT_EQ(42, functionPointer.usable());
}
TEST_F(MCJITCAPITest, custom_memory_manager) {
SKIP_UNSUPPORTED_PLATFORM;
buildSimpleFunction();
buildMCJITOptions();
useRoundTripSectionMemoryManager();
buildMCJITEngine();
buildAndRunPasses();
union {
void *raw;
int (*usable)();
} functionPointer;
functionPointer.raw = LLVMGetPointerToGlobal(Engine, Function);
EXPECT_EQ(42, functionPointer.usable());
EXPECT_TRUE(didCallAllocateCodeSection);
}
TEST_F(MCJITCAPITest, reserve_allocation_space) {
SKIP_UNSUPPORTED_PLATFORM;
TestReserveAllocationSpaceMemoryManager* MM = new TestReserveAllocationSpaceMemoryManager();
buildModuleWithCodeAndData();
buildMCJITOptions();
Options.MCJMM = wrap(MM);
buildMCJITEngine();
buildAndRunPasses();
union {
void *raw;
int (*usable)();
} GetGlobalFct;
GetGlobalFct.raw = LLVMGetPointerToGlobal(Engine, Function);
union {
void *raw;
void (*usable)(int);
} SetGlobalFct;
SetGlobalFct.raw = LLVMGetPointerToGlobal(Engine, Function2);
SetGlobalFct.usable(789);
EXPECT_EQ(789, GetGlobalFct.usable());
EXPECT_LE(MM->UsedCodeSize, MM->ReservedCodeSize);
EXPECT_LE(MM->UsedDataSizeRO, MM->ReservedDataSizeRO);
EXPECT_LE(MM->UsedDataSizeRW, MM->ReservedDataSizeRW);
EXPECT_TRUE(MM->UsedCodeSize > 0);
EXPECT_TRUE(MM->UsedDataSizeRO >= 0);
EXPECT_TRUE(MM->UsedDataSizeRW > 0);
}
<commit_msg>Fix misleading comment.<commit_after>//===- MCJITTest.cpp - Unit tests for the MCJIT ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This test suite verifies basic MCJIT functionality when invoked form the C
// API.
//
//===----------------------------------------------------------------------===//
#include "llvm-c/Analysis.h"
#include "MCJITTestAPICommon.h"
#include "llvm-c/Core.h"
#include "llvm-c/ExecutionEngine.h"
#include "llvm-c/Target.h"
#include "llvm-c/Transforms/Scalar.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/Support/Host.h"
#include "gtest/gtest.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
static bool didCallAllocateCodeSection;
static uint8_t *roundTripAllocateCodeSection(void *object, uintptr_t size,
unsigned alignment,
unsigned sectionID,
const char *sectionName) {
didCallAllocateCodeSection = true;
return static_cast<SectionMemoryManager*>(object)->allocateCodeSection(
size, alignment, sectionID, sectionName);
}
static uint8_t *roundTripAllocateDataSection(void *object, uintptr_t size,
unsigned alignment,
unsigned sectionID,
const char *sectionName,
LLVMBool isReadOnly) {
return static_cast<SectionMemoryManager*>(object)->allocateDataSection(
size, alignment, sectionID, sectionName, isReadOnly);
}
static LLVMBool roundTripFinalizeMemory(void *object, char **errMsg) {
std::string errMsgString;
bool result =
static_cast<SectionMemoryManager*>(object)->finalizeMemory(&errMsgString);
if (result) {
*errMsg = LLVMCreateMessage(errMsgString.c_str());
return 1;
}
return 0;
}
static void roundTripDestroy(void *object) {
delete static_cast<SectionMemoryManager*>(object);
}
namespace {
// memory manager to test reserve allocation space callback
class TestReserveAllocationSpaceMemoryManager: public SectionMemoryManager {
public:
uintptr_t ReservedCodeSize;
uintptr_t UsedCodeSize;
uintptr_t ReservedDataSizeRO;
uintptr_t UsedDataSizeRO;
uintptr_t ReservedDataSizeRW;
uintptr_t UsedDataSizeRW;
TestReserveAllocationSpaceMemoryManager() :
ReservedCodeSize(0), UsedCodeSize(0), ReservedDataSizeRO(0),
UsedDataSizeRO(0), ReservedDataSizeRW(0), UsedDataSizeRW(0) {
}
virtual bool needsToReserveAllocationSpace() {
return true;
}
virtual void reserveAllocationSpace(
uintptr_t CodeSize, uintptr_t DataSizeRO, uintptr_t DataSizeRW) {
ReservedCodeSize = CodeSize;
ReservedDataSizeRO = DataSizeRO;
ReservedDataSizeRW = DataSizeRW;
}
void useSpace(uintptr_t* UsedSize, uintptr_t Size, unsigned Alignment) {
uintptr_t AlignedSize = (Size + Alignment - 1) / Alignment * Alignment;
uintptr_t AlignedBegin = (*UsedSize + Alignment - 1) / Alignment * Alignment;
*UsedSize = AlignedBegin + AlignedSize;
}
virtual uint8_t* allocateDataSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID, StringRef SectionName, bool IsReadOnly) {
useSpace(IsReadOnly ? &UsedDataSizeRO : &UsedDataSizeRW, Size, Alignment);
return SectionMemoryManager::allocateDataSection(Size, Alignment,
SectionID, SectionName, IsReadOnly);
}
uint8_t* allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID, StringRef SectionName) {
useSpace(&UsedCodeSize, Size, Alignment);
return SectionMemoryManager::allocateCodeSection(Size, Alignment,
SectionID, SectionName);
}
};
class MCJITCAPITest : public testing::Test, public MCJITTestAPICommon {
protected:
MCJITCAPITest() {
// The architectures below are known to be compatible with MCJIT as they
// are copied from test/ExecutionEngine/MCJIT/lit.local.cfg and should be
// kept in sync.
SupportedArchs.push_back(Triple::aarch64);
SupportedArchs.push_back(Triple::arm);
SupportedArchs.push_back(Triple::mips);
SupportedArchs.push_back(Triple::x86);
SupportedArchs.push_back(Triple::x86_64);
// Some architectures have sub-architectures in which tests will fail, like
// ARM. These two vectors will define if they do have sub-archs (to avoid
// extra work for those who don't), and if so, if they are listed to work
HasSubArchs.push_back(Triple::arm);
SupportedSubArchs.push_back("armv6");
SupportedSubArchs.push_back("armv7");
// The operating systems below are known to be sufficiently incompatible
// that they will fail the MCJIT C API tests.
UnsupportedOSs.push_back(Triple::Cygwin);
}
virtual void SetUp() {
didCallAllocateCodeSection = false;
Module = 0;
Function = 0;
Engine = 0;
Error = 0;
}
virtual void TearDown() {
if (Engine)
LLVMDisposeExecutionEngine(Engine);
else if (Module)
LLVMDisposeModule(Module);
}
void buildSimpleFunction() {
Module = LLVMModuleCreateWithName("simple_module");
LLVMSetTarget(Module, HostTriple.c_str());
Function = LLVMAddFunction(
Module, "simple_function", LLVMFunctionType(LLVMInt32Type(), 0, 0, 0));
LLVMSetFunctionCallConv(Function, LLVMCCallConv);
LLVMBasicBlockRef entry = LLVMAppendBasicBlock(Function, "entry");
LLVMBuilderRef builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(builder, entry);
LLVMBuildRet(builder, LLVMConstInt(LLVMInt32Type(), 42, 0));
LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
LLVMDisposeMessage(Error);
LLVMDisposeBuilder(builder);
}
void buildModuleWithCodeAndData() {
Module = LLVMModuleCreateWithName("simple_module");
LLVMSetTarget(Module, HostTriple.c_str());
// build a global int32 variable initialized to 42.
LLVMValueRef GlobalVar = LLVMAddGlobal(Module, LLVMInt32Type(), "intVal");
LLVMSetInitializer(GlobalVar, LLVMConstInt(LLVMInt32Type(), 42, 0));
{
Function = LLVMAddFunction(
Module, "getGlobal", LLVMFunctionType(LLVMInt32Type(), 0, 0, 0));
LLVMSetFunctionCallConv(Function, LLVMCCallConv);
LLVMBasicBlockRef Entry = LLVMAppendBasicBlock(Function, "entry");
LLVMBuilderRef Builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(Builder, Entry);
LLVMValueRef IntVal = LLVMBuildLoad(Builder, GlobalVar, "intVal");
LLVMBuildRet(Builder, IntVal);
LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
LLVMDisposeMessage(Error);
LLVMDisposeBuilder(Builder);
}
{
LLVMTypeRef ParamTypes[] = { LLVMInt32Type() };
Function2 = LLVMAddFunction(
Module, "setGlobal", LLVMFunctionType(LLVMVoidType(), ParamTypes, 1, 0));
LLVMSetFunctionCallConv(Function2, LLVMCCallConv);
LLVMBasicBlockRef Entry = LLVMAppendBasicBlock(Function2, "entry");
LLVMBuilderRef Builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(Builder, Entry);
LLVMValueRef Arg = LLVMGetParam(Function2, 0);
LLVMBuildStore(Builder, Arg, GlobalVar);
LLVMBuildRetVoid(Builder);
LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
LLVMDisposeMessage(Error);
LLVMDisposeBuilder(Builder);
}
}
void buildMCJITOptions() {
LLVMInitializeMCJITCompilerOptions(&Options, sizeof(Options));
Options.OptLevel = 2;
// Just ensure that this field still exists.
Options.NoFramePointerElim = false;
}
void useRoundTripSectionMemoryManager() {
Options.MCJMM = LLVMCreateSimpleMCJITMemoryManager(
new SectionMemoryManager(),
roundTripAllocateCodeSection,
roundTripAllocateDataSection,
roundTripFinalizeMemory,
roundTripDestroy);
}
void buildMCJITEngine() {
ASSERT_EQ(
0, LLVMCreateMCJITCompilerForModule(&Engine, Module, &Options,
sizeof(Options), &Error));
}
void buildAndRunPasses() {
LLVMPassManagerRef pass = LLVMCreatePassManager();
LLVMAddTargetData(LLVMGetExecutionEngineTargetData(Engine), pass);
LLVMAddConstantPropagationPass(pass);
LLVMAddInstructionCombiningPass(pass);
LLVMRunPassManager(pass, Module);
LLVMDisposePassManager(pass);
}
LLVMModuleRef Module;
LLVMValueRef Function;
LLVMValueRef Function2;
LLVMMCJITCompilerOptions Options;
LLVMExecutionEngineRef Engine;
char *Error;
};
} // end anonymous namespace
TEST_F(MCJITCAPITest, simple_function) {
SKIP_UNSUPPORTED_PLATFORM;
buildSimpleFunction();
buildMCJITOptions();
buildMCJITEngine();
buildAndRunPasses();
union {
void *raw;
int (*usable)();
} functionPointer;
functionPointer.raw = LLVMGetPointerToGlobal(Engine, Function);
EXPECT_EQ(42, functionPointer.usable());
}
TEST_F(MCJITCAPITest, custom_memory_manager) {
SKIP_UNSUPPORTED_PLATFORM;
buildSimpleFunction();
buildMCJITOptions();
useRoundTripSectionMemoryManager();
buildMCJITEngine();
buildAndRunPasses();
union {
void *raw;
int (*usable)();
} functionPointer;
functionPointer.raw = LLVMGetPointerToGlobal(Engine, Function);
EXPECT_EQ(42, functionPointer.usable());
EXPECT_TRUE(didCallAllocateCodeSection);
}
TEST_F(MCJITCAPITest, reserve_allocation_space) {
SKIP_UNSUPPORTED_PLATFORM;
TestReserveAllocationSpaceMemoryManager* MM = new TestReserveAllocationSpaceMemoryManager();
buildModuleWithCodeAndData();
buildMCJITOptions();
Options.MCJMM = wrap(MM);
buildMCJITEngine();
buildAndRunPasses();
union {
void *raw;
int (*usable)();
} GetGlobalFct;
GetGlobalFct.raw = LLVMGetPointerToGlobal(Engine, Function);
union {
void *raw;
void (*usable)(int);
} SetGlobalFct;
SetGlobalFct.raw = LLVMGetPointerToGlobal(Engine, Function2);
SetGlobalFct.usable(789);
EXPECT_EQ(789, GetGlobalFct.usable());
EXPECT_LE(MM->UsedCodeSize, MM->ReservedCodeSize);
EXPECT_LE(MM->UsedDataSizeRO, MM->ReservedDataSizeRO);
EXPECT_LE(MM->UsedDataSizeRW, MM->ReservedDataSizeRW);
EXPECT_TRUE(MM->UsedCodeSize > 0);
EXPECT_TRUE(MM->UsedDataSizeRO >= 0);
EXPECT_TRUE(MM->UsedDataSizeRW > 0);
}
<|endoftext|>
|
<commit_before><commit_msg>Replace hex values in SpdyFramerTest.<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string.h>
#include "common/convert_UTF.h"
#include "common/scoped_ptr.h"
#include "common/string_conversion.h"
#include "common/using_std_string.h"
namespace google_breakpad {
using std::vector;
void UTF8ToUTF16(const char *in, vector<uint16_t> *out) {
size_t source_length = strlen(in);
const UTF8 *source_ptr = reinterpret_cast<const UTF8 *>(in);
const UTF8 *source_end_ptr = source_ptr + source_length;
// Erase the contents and zero fill to the expected size
out->clear();
out->insert(out->begin(), source_length, 0);
uint16_t *target_ptr = &(*out)[0];
uint16_t *target_end_ptr = target_ptr + out->capacity() * sizeof(uint16_t);
ConversionResult result = ConvertUTF8toUTF16(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
// Resize to be the size of the # of converted characters + NULL
out->resize(result == conversionOK ? target_ptr - &(*out)[0] + 1: 0);
}
int UTF8ToUTF16Char(const char *in, int in_length, uint16_t out[2]) {
const UTF8 *source_ptr = reinterpret_cast<const UTF8 *>(in);
const UTF8 *source_end_ptr = source_ptr + sizeof(char);
uint16_t *target_ptr = out;
uint16_t *target_end_ptr = target_ptr + 2 * sizeof(uint16_t);
out[0] = out[1] = 0;
// Process one character at a time
while (1) {
ConversionResult result = ConvertUTF8toUTF16(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
if (result == conversionOK)
return static_cast<int>(source_ptr - reinterpret_cast<const UTF8 *>(in));
// Add another character to the input stream and try again
source_ptr = reinterpret_cast<const UTF8 *>(in);
++source_end_ptr;
if (source_end_ptr > reinterpret_cast<const UTF8 *>(in) + in_length)
break;
}
return 0;
}
void UTF32ToUTF16(const wchar_t *in, vector<uint16_t> *out) {
size_t source_length = wcslen(in);
const UTF32 *source_ptr = reinterpret_cast<const UTF32 *>(in);
const UTF32 *source_end_ptr = source_ptr + source_length;
// Erase the contents and zero fill to the expected size
out->clear();
out->insert(out->begin(), source_length, 0);
uint16_t *target_ptr = &(*out)[0];
uint16_t *target_end_ptr = target_ptr + out->capacity() * sizeof(uint16_t);
ConversionResult result = ConvertUTF32toUTF16(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
// Resize to be the size of the # of converted characters + NULL
out->resize(result == conversionOK ? target_ptr - &(*out)[0] + 1: 0);
}
void UTF32ToUTF16Char(wchar_t in, uint16_t out[2]) {
const UTF32 *source_ptr = reinterpret_cast<const UTF32 *>(&in);
const UTF32 *source_end_ptr = source_ptr + 1;
uint16_t *target_ptr = out;
uint16_t *target_end_ptr = target_ptr + 2 * sizeof(uint16_t);
out[0] = out[1] = 0;
ConversionResult result = ConvertUTF32toUTF16(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
if (result != conversionOK) {
out[0] = out[1] = 0;
}
}
static inline uint16_t Swap(uint16_t value) {
return (value >> 8) | static_cast<uint16_t>(value << 8);
}
string UTF16ToUTF8(const vector<uint16_t> &in, bool swap) {
const UTF16 *source_ptr = &in[0];
scoped_ptr<uint16_t> source_buffer;
// If we're to swap, we need to make a local copy and swap each byte pair
if (swap) {
int idx = 0;
source_buffer.reset(new uint16_t[in.size()]);
UTF16 *source_buffer_ptr = source_buffer.get();
for (vector<uint16_t>::const_iterator it = in.begin();
it != in.end(); ++it, ++idx)
source_buffer_ptr[idx] = Swap(*it);
source_ptr = source_buffer.get();
}
// The maximum expansion would be 4x the size of the input string.
const UTF16 *source_end_ptr = source_ptr + in.size();
size_t target_capacity = in.size() * 4;
scoped_array<UTF8> target_buffer(new UTF8[target_capacity]);
UTF8 *target_ptr = target_buffer.get();
UTF8 *target_end_ptr = target_ptr + target_capacity;
ConversionResult result = ConvertUTF16toUTF8(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
if (result == conversionOK) {
const char *targetPtr = reinterpret_cast<const char *>(target_buffer.get());
return targetPtr;
}
return "";
}
} // namespace google_breakpad
<commit_msg>Switch to scoped_array instead of inappropriate scoped_ptr.<commit_after>// Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string.h>
#include "common/convert_UTF.h"
#include "common/scoped_ptr.h"
#include "common/string_conversion.h"
#include "common/using_std_string.h"
namespace google_breakpad {
using std::vector;
void UTF8ToUTF16(const char *in, vector<uint16_t> *out) {
size_t source_length = strlen(in);
const UTF8 *source_ptr = reinterpret_cast<const UTF8 *>(in);
const UTF8 *source_end_ptr = source_ptr + source_length;
// Erase the contents and zero fill to the expected size
out->clear();
out->insert(out->begin(), source_length, 0);
uint16_t *target_ptr = &(*out)[0];
uint16_t *target_end_ptr = target_ptr + out->capacity() * sizeof(uint16_t);
ConversionResult result = ConvertUTF8toUTF16(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
// Resize to be the size of the # of converted characters + NULL
out->resize(result == conversionOK ? target_ptr - &(*out)[0] + 1: 0);
}
int UTF8ToUTF16Char(const char *in, int in_length, uint16_t out[2]) {
const UTF8 *source_ptr = reinterpret_cast<const UTF8 *>(in);
const UTF8 *source_end_ptr = source_ptr + sizeof(char);
uint16_t *target_ptr = out;
uint16_t *target_end_ptr = target_ptr + 2 * sizeof(uint16_t);
out[0] = out[1] = 0;
// Process one character at a time
while (1) {
ConversionResult result = ConvertUTF8toUTF16(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
if (result == conversionOK)
return static_cast<int>(source_ptr - reinterpret_cast<const UTF8 *>(in));
// Add another character to the input stream and try again
source_ptr = reinterpret_cast<const UTF8 *>(in);
++source_end_ptr;
if (source_end_ptr > reinterpret_cast<const UTF8 *>(in) + in_length)
break;
}
return 0;
}
void UTF32ToUTF16(const wchar_t *in, vector<uint16_t> *out) {
size_t source_length = wcslen(in);
const UTF32 *source_ptr = reinterpret_cast<const UTF32 *>(in);
const UTF32 *source_end_ptr = source_ptr + source_length;
// Erase the contents and zero fill to the expected size
out->clear();
out->insert(out->begin(), source_length, 0);
uint16_t *target_ptr = &(*out)[0];
uint16_t *target_end_ptr = target_ptr + out->capacity() * sizeof(uint16_t);
ConversionResult result = ConvertUTF32toUTF16(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
// Resize to be the size of the # of converted characters + NULL
out->resize(result == conversionOK ? target_ptr - &(*out)[0] + 1: 0);
}
void UTF32ToUTF16Char(wchar_t in, uint16_t out[2]) {
const UTF32 *source_ptr = reinterpret_cast<const UTF32 *>(&in);
const UTF32 *source_end_ptr = source_ptr + 1;
uint16_t *target_ptr = out;
uint16_t *target_end_ptr = target_ptr + 2 * sizeof(uint16_t);
out[0] = out[1] = 0;
ConversionResult result = ConvertUTF32toUTF16(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
if (result != conversionOK) {
out[0] = out[1] = 0;
}
}
static inline uint16_t Swap(uint16_t value) {
return (value >> 8) | static_cast<uint16_t>(value << 8);
}
string UTF16ToUTF8(const vector<uint16_t> &in, bool swap) {
const UTF16 *source_ptr = &in[0];
scoped_array<uint16_t> source_buffer;
// If we're to swap, we need to make a local copy and swap each byte pair
if (swap) {
int idx = 0;
source_buffer.reset(new uint16_t[in.size()]);
UTF16 *source_buffer_ptr = source_buffer.get();
for (vector<uint16_t>::const_iterator it = in.begin();
it != in.end(); ++it, ++idx)
source_buffer_ptr[idx] = Swap(*it);
source_ptr = source_buffer.get();
}
// The maximum expansion would be 4x the size of the input string.
const UTF16 *source_end_ptr = source_ptr + in.size();
size_t target_capacity = in.size() * 4;
scoped_array<UTF8> target_buffer(new UTF8[target_capacity]);
UTF8 *target_ptr = target_buffer.get();
UTF8 *target_end_ptr = target_ptr + target_capacity;
ConversionResult result = ConvertUTF16toUTF8(&source_ptr, source_end_ptr,
&target_ptr, target_end_ptr,
strictConversion);
if (result == conversionOK) {
const char *targetPtr = reinterpret_cast<const char *>(target_buffer.get());
return targetPtr;
}
return "";
}
} // namespace google_breakpad
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "kernel/type_checker.h"
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/for_each_fn.h"
#include "library/locals.h"
#include "library/util.h"
#include "compiler/fresh_constant.h"
#include "compiler/comp_irrelevant.h"
#include "compiler/compiler_step_visitor.h"
namespace lean {
class lambda_lifting_fn : public compiler_step_visitor {
buffer<name> & m_new_decls;
bool m_trusted;
protected:
expr declare_aux_def(expr const & value) {
pair<environment, name> ep = mk_fresh_constant(m_env);
m_env = ep.first;
name n = ep.second;
m_new_decls.push_back(n);
level_param_names ps = to_level_param_names(collect_univ_params(value));
/* We should use a new type checker because m_env is updated by this object.
It is safe to use type_checker because value does not contain local_decl_ref objects. */
type_checker tc(m_env);
expr type = tc.infer(value);
bool use_conv_opt = false;
declaration new_decl = mk_definition(m_env, n, ps, type, value, use_conv_opt, m_trusted);
m_env = m_env.add(check(m_env, new_decl));
return mk_constant(n, param_names_to_levels(ps));
}
typedef rb_map<unsigned, local_decl, unsigned_rev_cmp> idx2decls;
void collect_locals(expr const & e, idx2decls & r) {
local_context const & lctx = m_ctx.lctx();
for_each(e, [&](expr const & e, unsigned) {
if (is_local_decl_ref(e)) {
local_decl d = *lctx.get_local_decl(e);
r.insert(d.get_idx(), d);
}
return true;
});
}
expr visit_lambda_core(expr const & e) {
type_context::tmp_locals locals(m_ctx);
expr t = e;
while (is_lambda(t)) {
expr d = instantiate_rev(binding_domain(t), locals.size(), locals.data());
locals.push_local(binding_name(t), d, binding_info(t));
t = binding_body(t);
}
t = instantiate_rev(t, locals.size(), locals.data());
t = visit(t);
return locals.mk_lambda(t);
}
virtual expr visit_lambda(expr const & e) override {
expr new_e = visit_lambda_core(e);
idx2decls map;
collect_locals(new_e, map);
if (map.empty()) {
return declare_aux_def(new_e);
} else {
buffer<expr> args;
while (!map.empty()) {
/* remove local_decl with biggest idx */
local_decl d = map.erase_min();
expr l = d.mk_ref();
if (auto v = d.get_value()) {
collect_locals(*v, map);
new_e = instantiate(abstract_local(new_e, l), *v);
} else {
collect_locals(d.get_type(), map);
if (is_comp_irrelevant(ctx(), l))
args.push_back(mark_comp_irrelevant(l));
else
args.push_back(l);
new_e = abstract_local(new_e, l);
new_e = mk_lambda(d.get_name(), d.get_type(), new_e);
}
}
expr c = declare_aux_def(new_e);
return mk_rev_app(c, args);
}
}
virtual expr visit_let(expr const & e) override {
type_context::tmp_locals locals(m_ctx);
expr t = e;
while (is_let(t)) {
expr d = instantiate_rev(let_type(t), locals.size(), locals.data());
expr v = visit(instantiate_rev(let_value(t), locals.size(), locals.data()));
locals.push_let(let_name(t), d, v);
t = let_body(t);
}
t = instantiate_rev(t, locals.size(), locals.data());
t = visit(t);
return locals.mk_let(t);
}
virtual expr visit_app(expr const & e) override {
// TODO(Leo): process recursor args
return compiler_step_visitor::visit_app(e);
}
public:
lambda_lifting_fn(environment const & env, buffer<name> & new_decls, bool trusted):
compiler_step_visitor(env), m_new_decls(new_decls), m_trusted(trusted) {}
environment const & env() const { return m_env; }
expr operator()(expr const & e) {
if (is_lambda(e))
return visit_lambda_core(e);
else
return visit(e);
}
};
expr lambda_lifting(environment & env, expr const & e, buffer<name> & new_decls, bool trusted) {
lambda_lifting_fn fn(env, new_decls, trusted);
expr new_e = fn(e);
env = fn.env();
return new_e;
}
}
<commit_msg>feat(compiler/lambda_lifting): add support for cases_on recursor<commit_after>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "kernel/type_checker.h"
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/for_each_fn.h"
#include "kernel/inductive/inductive.h"
#include "library/locals.h"
#include "library/util.h"
#include "library/trace.h"
#include "compiler/fresh_constant.h"
#include "compiler/util.h"
#include "compiler/comp_irrelevant.h"
#include "compiler/compiler_step_visitor.h"
namespace lean {
class lambda_lifting_fn : public compiler_step_visitor {
buffer<name> & m_new_decls;
bool m_trusted;
protected:
expr declare_aux_def(expr const & value) {
pair<environment, name> ep = mk_fresh_constant(m_env);
m_env = ep.first;
name n = ep.second;
m_new_decls.push_back(n);
level_param_names ps = to_level_param_names(collect_univ_params(value));
/* We should use a new type checker because m_env is updated by this object.
It is safe to use type_checker because value does not contain local_decl_ref objects. */
type_checker tc(m_env);
expr type = tc.infer(value);
bool use_conv_opt = false;
declaration new_decl = mk_definition(m_env, n, ps, type, value, use_conv_opt, m_trusted);
m_env = m_env.add(check(m_env, new_decl));
return mk_constant(n, param_names_to_levels(ps));
}
typedef rb_map<unsigned, local_decl, unsigned_rev_cmp> idx2decls;
void collect_locals(expr const & e, idx2decls & r) {
local_context const & lctx = m_ctx.lctx();
for_each(e, [&](expr const & e, unsigned) {
if (is_local_decl_ref(e)) {
local_decl d = *lctx.get_local_decl(e);
r.insert(d.get_idx(), d);
}
return true;
});
}
expr visit_lambda_core(expr const & e) {
type_context::tmp_locals locals(m_ctx);
expr t = e;
while (is_lambda(t)) {
expr d = instantiate_rev(binding_domain(t), locals.size(), locals.data());
locals.push_local(binding_name(t), d, binding_info(t));
t = binding_body(t);
}
t = instantiate_rev(t, locals.size(), locals.data());
t = visit(t);
return locals.mk_lambda(t);
}
virtual expr visit_lambda(expr const & e) override {
expr new_e = visit_lambda_core(e);
idx2decls map;
collect_locals(new_e, map);
if (map.empty()) {
return declare_aux_def(new_e);
} else {
buffer<expr> args;
while (!map.empty()) {
/* remove local_decl with biggest idx */
local_decl d = map.erase_min();
expr l = d.mk_ref();
if (auto v = d.get_value()) {
collect_locals(*v, map);
new_e = instantiate(abstract_local(new_e, l), *v);
} else {
collect_locals(d.get_type(), map);
if (is_comp_irrelevant(ctx(), l))
args.push_back(mark_comp_irrelevant(l));
else
args.push_back(l);
new_e = abstract_local(new_e, l);
new_e = mk_lambda(d.get_name(), d.get_type(), new_e);
}
}
expr c = declare_aux_def(new_e);
return mk_rev_app(c, args);
}
}
virtual expr visit_let(expr const & e) override {
type_context::tmp_locals locals(m_ctx);
expr t = e;
while (is_let(t)) {
expr d = instantiate_rev(let_type(t), locals.size(), locals.data());
expr v = visit(instantiate_rev(let_value(t), locals.size(), locals.data()));
locals.push_let(let_name(t), d, v);
t = let_body(t);
}
t = instantiate_rev(t, locals.size(), locals.data());
t = visit(t);
return locals.mk_let(t);
}
expr visit_recursor_app(expr const & e) {
// TODO(Leo): process recursor args
return compiler_step_visitor::visit_app(e);
}
unsigned get_constructor_arity(name const & n) {
declaration d = env().get(n);
expr e = d.get_type();
unsigned r = 0;
while (is_pi(e)) {
r++;
e = binding_body(e);
}
return r;
}
expr visit_cases_on_minor(unsigned data_sz, expr e) {
type_context::tmp_locals locals(ctx());
for (unsigned i = 0; i < data_sz; i++) {
e = ctx().whnf(e);
lean_assert(is_lambda(e));
expr l = locals.push_local(binding_name(e), binding_domain(e), binding_info(e));
e = instantiate(binding_body(e), l);
}
e = visit(e);
return locals.mk_lambda(e);
}
expr visit_cases_on_app(expr const & e) {
buffer<expr> args;
expr const & fn = get_app_args(e, args);
lean_assert(is_constant(fn) && is_cases_on_recursor(env(), const_name(fn)));
name const & cases_on_name = const_name(fn);
name const & I_name = cases_on_name.get_prefix();
unsigned nparams = *inductive::get_num_params(env(), I_name);
unsigned nminors = *inductive::get_num_minor_premises(env(), I_name);
unsigned nindices = *inductive::get_num_indices(env(), I_name);
unsigned cases_on_arity = nparams + 1 /* typeformer/motive */ + nindices + 1 /* major premise */ + nminors;
unsigned major_idx = nparams + 1 + nindices;
/* This transformation assumes eta-expansion have already been applied.
So, we should have a sufficient number of arguments. */
lean_assert(args.size() >= cases_on_arity);
buffer<name> cnames;
get_intro_rule_names(env(), I_name, cnames);
/* Process major premise */
args[major_idx] = visit(args[major_idx]);
/* Process extra arguments */
for (unsigned i = cases_on_arity; i < args.size(); i++)
args[i] = visit(args[i]);
/* Process minor premise */
for (unsigned i = 0, j = major_idx + 1; i < cnames.size(); i++, j++) {
unsigned carity = get_constructor_arity(cnames[i]);
lean_assert(carity >= nparams);
unsigned cdata_sz = carity - nparams;
args[j] = visit_cases_on_minor(cdata_sz, args[j]);
}
return mk_app(fn, args);
}
virtual expr visit_app(expr const & e) override {
expr const & fn = get_app_fn(e);
if (is_constant(fn)) {
name const & n = const_name(fn);
if (is_cases_on_recursor(env(), n)) {
return visit_cases_on_app(e);
} else if (inductive::is_elim_rule(env(), n)) {
return visit_recursor_app(e);
}
}
return compiler_step_visitor::visit_app(e);
}
public:
lambda_lifting_fn(environment const & env, buffer<name> & new_decls, bool trusted):
compiler_step_visitor(env), m_new_decls(new_decls), m_trusted(trusted) {}
environment const & env() const { return m_env; }
expr operator()(expr const & e) {
if (is_lambda(e))
return visit_lambda_core(e);
else
return visit(e);
}
};
expr lambda_lifting(environment & env, expr const & e, buffer<name> & new_decls, bool trusted) {
lambda_lifting_fn fn(env, new_decls, trusted);
expr new_e = fn(e);
env = fn.env();
return new_e;
}
}
<|endoftext|>
|
<commit_before>//===--- ManagedValue.cpp - Value with cleanup ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A storage structure for holding a destructured rvalue with an optional
// cleanup(s).
// Ownership of the rvalue can be "forwarded" to disable the associated
// cleanup(s).
//
//===----------------------------------------------------------------------===//
#include "ManagedValue.h"
#include "SILGenFunction.h"
using namespace swift;
using namespace Lowering;
/// Emit a copy of this value with independent ownership.
ManagedValue ManagedValue::copy(SILGenFunction &gen, SILLocation loc) {
auto &lowering = gen.getTypeLowering(getType());
if (lowering.isTrivial())
return *this;
if (getType().isObject()) {
return gen.B.createCopyValue(loc, *this, lowering);
}
SILValue buf = gen.emitTemporaryAllocation(loc, getType());
gen.B.createCopyAddr(loc, getValue(), buf, IsNotTake, IsInitialization);
return gen.emitManagedRValueWithCleanup(buf, lowering);
}
/// Emit a copy of this value with independent ownership.
ManagedValue ManagedValue::formalAccessCopy(SILGenFunction &gen,
SILLocation loc) {
auto &lowering = gen.getTypeLowering(getType());
if (lowering.isTrivial())
return *this;
if (getType().isObject()) {
return gen.B.createFormalAccessCopyValue(loc, *this);
}
SILValue buf = gen.emitTemporaryAllocation(loc, getType());
return gen.B.createFormalAccessCopyAddr(loc, *this, buf);
}
/// Store a copy of this value with independent ownership into the given
/// uninitialized address.
void ManagedValue::copyInto(SILGenFunction &gen, SILValue dest,
SILLocation loc) {
auto &lowering = gen.getTypeLowering(getType());
if (lowering.isAddressOnly()) {
gen.B.createCopyAddr(loc, getValue(), dest, IsNotTake, IsInitialization);
return;
}
SILValue copy = lowering.emitCopyValue(gen.B, loc, getValue());
lowering.emitStoreOfCopy(gen.B, loc, copy, dest, IsInitialization);
}
/// This is the same operation as 'copy', but works on +0 values that don't
/// have cleanups. It returns a +1 value with one.
ManagedValue ManagedValue::copyUnmanaged(SILGenFunction &gen, SILLocation loc) {
if (getType().isObject()) {
return gen.B.createCopyValue(loc, *this);
}
SILValue result = gen.emitTemporaryAllocation(loc, getType());
gen.B.createCopyAddr(loc, getValue(), result, IsNotTake, IsInitialization);
return gen.emitManagedRValueWithCleanup(result);
}
/// Disable the cleanup for this value.
void ManagedValue::forwardCleanup(SILGenFunction &gen) const {
assert(hasCleanup() && "value doesn't have cleanup!");
gen.Cleanups.forwardCleanup(getCleanup());
}
/// Forward this value, deactivating the cleanup and returning the
/// underlying value.
SILValue ManagedValue::forward(SILGenFunction &gen) const {
if (hasCleanup())
forwardCleanup(gen);
return getValue();
}
void ManagedValue::forwardInto(SILGenFunction &gen, SILLocation loc,
SILValue address) {
if (hasCleanup())
forwardCleanup(gen);
auto &addrTL = gen.getTypeLowering(address->getType());
gen.emitSemanticStore(loc, getValue(), address, addrTL, IsInitialization);
}
void ManagedValue::assignInto(SILGenFunction &gen, SILLocation loc,
SILValue address) {
if (hasCleanup())
forwardCleanup(gen);
auto &addrTL = gen.getTypeLowering(address->getType());
gen.emitSemanticStore(loc, getValue(), address, addrTL,
IsNotInitialization);
}
ManagedValue ManagedValue::borrow(SILGenFunction &gen, SILLocation loc) const {
assert(getValue() && "cannot borrow an invalid or in-context value");
if (isLValue())
return *this;
if (getType().isAddress())
return ManagedValue::forUnmanaged(getValue());
return gen.emitManagedBeginBorrow(loc, getValue());
}
ManagedValue ManagedValue::formalAccessBorrow(SILGenFunction &gen,
SILLocation loc) const {
assert(getValue() && "cannot borrow an invalid or in-context value");
if (isLValue())
return *this;
if (getType().isAddress())
return ManagedValue::forUnmanaged(getValue());
return gen.emitFormalEvaluationManagedBeginBorrow(loc, getValue());
}
<commit_msg>[silgen] Add an assert that formalAccessCopy is only called in a FormalEvaluationScope.<commit_after>//===--- ManagedValue.cpp - Value with cleanup ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A storage structure for holding a destructured rvalue with an optional
// cleanup(s).
// Ownership of the rvalue can be "forwarded" to disable the associated
// cleanup(s).
//
//===----------------------------------------------------------------------===//
#include "ManagedValue.h"
#include "SILGenFunction.h"
using namespace swift;
using namespace Lowering;
/// Emit a copy of this value with independent ownership.
ManagedValue ManagedValue::copy(SILGenFunction &gen, SILLocation loc) {
auto &lowering = gen.getTypeLowering(getType());
if (lowering.isTrivial())
return *this;
if (getType().isObject()) {
return gen.B.createCopyValue(loc, *this, lowering);
}
SILValue buf = gen.emitTemporaryAllocation(loc, getType());
gen.B.createCopyAddr(loc, getValue(), buf, IsNotTake, IsInitialization);
return gen.emitManagedRValueWithCleanup(buf, lowering);
}
/// Emit a copy of this value with independent ownership.
ManagedValue ManagedValue::formalAccessCopy(SILGenFunction &gen,
SILLocation loc) {
assert(gen.InWritebackScope && "Can only perform a formal access copy in a "
"formal evaluation scope");
auto &lowering = gen.getTypeLowering(getType());
if (lowering.isTrivial())
return *this;
if (getType().isObject()) {
return gen.B.createFormalAccessCopyValue(loc, *this);
}
SILValue buf = gen.emitTemporaryAllocation(loc, getType());
return gen.B.createFormalAccessCopyAddr(loc, *this, buf);
}
/// Store a copy of this value with independent ownership into the given
/// uninitialized address.
void ManagedValue::copyInto(SILGenFunction &gen, SILValue dest,
SILLocation loc) {
auto &lowering = gen.getTypeLowering(getType());
if (lowering.isAddressOnly()) {
gen.B.createCopyAddr(loc, getValue(), dest, IsNotTake, IsInitialization);
return;
}
SILValue copy = lowering.emitCopyValue(gen.B, loc, getValue());
lowering.emitStoreOfCopy(gen.B, loc, copy, dest, IsInitialization);
}
/// This is the same operation as 'copy', but works on +0 values that don't
/// have cleanups. It returns a +1 value with one.
ManagedValue ManagedValue::copyUnmanaged(SILGenFunction &gen, SILLocation loc) {
if (getType().isObject()) {
return gen.B.createCopyValue(loc, *this);
}
SILValue result = gen.emitTemporaryAllocation(loc, getType());
gen.B.createCopyAddr(loc, getValue(), result, IsNotTake, IsInitialization);
return gen.emitManagedRValueWithCleanup(result);
}
/// Disable the cleanup for this value.
void ManagedValue::forwardCleanup(SILGenFunction &gen) const {
assert(hasCleanup() && "value doesn't have cleanup!");
gen.Cleanups.forwardCleanup(getCleanup());
}
/// Forward this value, deactivating the cleanup and returning the
/// underlying value.
SILValue ManagedValue::forward(SILGenFunction &gen) const {
if (hasCleanup())
forwardCleanup(gen);
return getValue();
}
void ManagedValue::forwardInto(SILGenFunction &gen, SILLocation loc,
SILValue address) {
if (hasCleanup())
forwardCleanup(gen);
auto &addrTL = gen.getTypeLowering(address->getType());
gen.emitSemanticStore(loc, getValue(), address, addrTL, IsInitialization);
}
void ManagedValue::assignInto(SILGenFunction &gen, SILLocation loc,
SILValue address) {
if (hasCleanup())
forwardCleanup(gen);
auto &addrTL = gen.getTypeLowering(address->getType());
gen.emitSemanticStore(loc, getValue(), address, addrTL,
IsNotInitialization);
}
ManagedValue ManagedValue::borrow(SILGenFunction &gen, SILLocation loc) const {
assert(getValue() && "cannot borrow an invalid or in-context value");
if (isLValue())
return *this;
if (getType().isAddress())
return ManagedValue::forUnmanaged(getValue());
return gen.emitManagedBeginBorrow(loc, getValue());
}
ManagedValue ManagedValue::formalAccessBorrow(SILGenFunction &gen,
SILLocation loc) const {
assert(getValue() && "cannot borrow an invalid or in-context value");
if (isLValue())
return *this;
if (getType().isAddress())
return ManagedValue::forUnmanaged(getValue());
return gen.emitFormalEvaluationManagedBeginBorrow(loc, getValue());
}
<|endoftext|>
|
<commit_before>// Copyright 2014 Toggl Desktop developers.
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <iostream> // NOLINT
#include "./../kopsik_api.h"
#include "./../kopsik_api_private.h"
#include "./test_data.h"
#include "./../settings.h"
#include "./../proxy.h"
#include "Poco/FileStream.h"
#include "Poco/File.h"
namespace kopsik {
namespace testing {
namespace testresult {
std::string url("");
std::string reminder_title("");
std::string reminder_informative_text("");
std::string error("");
bool online_state(false);
uint64_t user_id(0);
Settings settings;
bool use_proxy(false);
Proxy proxy;
std::string update_channel("");
} // namespace testresult
void on_app(const _Bool open) {
}
void on_error(
const char *errmsg,
const _Bool user_error) {
if (errmsg) {
testresult::error = std::string(errmsg);
return;
}
testresult::error = std::string("");
}
void on_update(
const _Bool open,
KopsikUpdateViewItem *view) {
testresult::update_channel = std::string(view->UpdateChannel);
}
void on_online_state(const _Bool is_online) {
testresult::online_state = is_online;
}
void on_url(const char *url) {
testresult::url = std::string(url);
}
void on_login(const _Bool open, const uint64_t user_id) {
testresult::user_id = user_id;
}
void on_reminder(const char *title, const char *informative_text) {
testresult::reminder_title = std::string(title);
testresult::reminder_informative_text = std::string(informative_text);
}
void on_time_entry_list(
const _Bool open,
KopsikTimeEntryViewItem *first) {
}
void on_time_entry_autocomplete(KopsikAutocompleteItem *first) {
}
void on_project_autocomplete(KopsikAutocompleteItem *first) {
}
void on_client_select(KopsikViewItem *first) {
}
void on_workspace_select(KopsikViewItem *first) {
}
void on_tags(KopsikViewItem *first) {
}
void on_time_entry_editor(
const _Bool open,
KopsikTimeEntryViewItem *te,
const char *focused_field_name) {
}
void on_display_settings(
const _Bool open,
KopsikSettingsViewItem *settings) {
testing::testresult::settings.use_idle_detection =
settings->UseIdleDetection;
testing::testresult::settings.menubar_timer = settings->MenubarTimer;
testing::testresult::settings.reminder = settings->Reminder;
testing::testresult::settings.dock_icon = settings->DockIcon;
testing::testresult::settings.on_top = settings->OnTop;
testing::testresult::settings.ignore_cert = settings->IgnoreCert;
testing::testresult::use_proxy = settings->UseProxy;
testing::testresult::proxy.host = std::string(settings->ProxyHost);
testing::testresult::proxy.port = settings->ProxyPort;
testing::testresult::proxy.username = std::string(settings->ProxyUsername);
testing::testresult::proxy.password = std::string(settings->ProxyPassword);
}
void on_display_timer_state(KopsikTimeEntryViewItem *te) {
}
void on_display_idle_notification(
const uint64_t started,
const uint64_t finished,
const uint64_t seconds) {
}
void on_apply_settings(
KopsikSettingsViewItem *settings) {
testing::testresult::use_proxy = settings->UseProxy;
testing::testresult::settings.use_idle_detection =
settings->UseIdleDetection;
testing::testresult::settings.menubar_timer =
settings->MenubarTimer;
testing::testresult::settings.dock_icon = settings->DockIcon;
testing::testresult::settings.on_top = settings->OnTop;
}
class App {
public:
App() {
Poco::File f(TESTDB);
if (f.exists()) {
f.remove(false);
}
kopsik_set_log_path("test.log");
ctx_ = kopsik_context_init("tests", "0.1");
poco_assert(kopsik_set_db_path(ctx_, TESTDB));
kopsik_on_app(ctx_, on_app);
kopsik_on_error(ctx_, on_error);
kopsik_on_update(ctx_, on_update);
kopsik_on_online_state(ctx_, on_online_state);
kopsik_on_login(ctx_, on_login);
kopsik_on_url(ctx_, on_url);
kopsik_on_reminder(ctx_, on_reminder);
kopsik_on_time_entry_list(ctx_, on_time_entry_list);
kopsik_on_time_entry_autocomplete(ctx_, on_time_entry_autocomplete);
kopsik_on_project_autocomplete(ctx_, on_project_autocomplete);
kopsik_on_workspace_select(ctx_, on_workspace_select);
kopsik_on_client_select(ctx_, on_client_select);
kopsik_on_tags(ctx_, on_tags);
kopsik_on_time_entry_editor(ctx_, on_time_entry_editor);
kopsik_on_settings(ctx_, on_display_settings);
kopsik_on_timer_state(ctx_, on_display_timer_state);
kopsik_on_idle_notification(ctx_, on_display_idle_notification);
poco_assert(kopsik_context_start_events(ctx_));
}
~App() {
kopsik_context_clear(ctx_);
ctx_ = 0;
}
void *ctx() {
return ctx_;
}
private:
void *ctx_;
};
} // namespace testing
TEST(KopsikApiTest, kopsik_context_init) {
testing::App app;
}
TEST(KopsikApiTest, kopsik_set_settings) {
testing::App app;
ASSERT_TRUE(kopsik_set_settings(app.ctx(),
false, false, false, false, false, false));
ASSERT_FALSE(testing::testresult::settings.use_idle_detection);
ASSERT_FALSE(testing::testresult::settings.menubar_timer);
ASSERT_FALSE(testing::testresult::settings.dock_icon);
ASSERT_FALSE(testing::testresult::settings.on_top);
ASSERT_FALSE(testing::testresult::settings.reminder);
ASSERT_FALSE(testing::testresult::settings.ignore_cert);
ASSERT_TRUE(kopsik_set_settings(app.ctx(),
true, true, true, true, true, true));
ASSERT_TRUE(testing::testresult::settings.use_idle_detection);
ASSERT_TRUE(testing::testresult::settings.menubar_timer);
ASSERT_TRUE(testing::testresult::settings.dock_icon);
ASSERT_TRUE(testing::testresult::settings.on_top);
ASSERT_TRUE(testing::testresult::settings.reminder);
ASSERT_TRUE(testing::testresult::settings.ignore_cert);
}
TEST(KopsikApiTest, kopsik_set_proxy_settings) {
testing::App app;
ASSERT_TRUE(kopsik_set_proxy_settings(
app.ctx(), 1, "localhost", 8000, "johnsmith", "secret"));
ASSERT_TRUE(testing::testresult::use_proxy);
ASSERT_EQ(std::string("localhost"),
std::string(testing::testresult::proxy.host));
ASSERT_EQ(8000,
static_cast<int>(testing::testresult::proxy.port));
ASSERT_EQ(std::string("johnsmith"),
std::string(testing::testresult::proxy.username));
ASSERT_EQ(std::string("secret"),
std::string(testing::testresult::proxy.password));
}
TEST(KopsikApiTest, kopsik_set_update_channel) {
testing::App app;
std::string default_channel("stable");
kopsik_about(app.ctx());
ASSERT_EQ(default_channel, testing::testresult::update_channel);
ASSERT_FALSE(kopsik_set_update_channel(app.ctx(), "invalid"));
ASSERT_TRUE(kopsik_set_update_channel(app.ctx(), "beta"));
ASSERT_EQ(std::string("beta"), testing::testresult::update_channel);
ASSERT_TRUE(kopsik_set_update_channel(app.ctx(), "dev"));
ASSERT_EQ(std::string("dev"), testing::testresult::update_channel);
ASSERT_TRUE(kopsik_set_update_channel(app.ctx(), "stable"));
ASSERT_EQ(std::string("stable"), testing::testresult::update_channel);
}
TEST(KopsikApiTest, kopsik_set_log_level) {
kopsik_set_log_level("trace");
}
unsigned int list_length(KopsikTimeEntryViewItem *first) {
unsigned int n = 0;
KopsikTimeEntryViewItem *it = first;
while (it) {
n++;
it = reinterpret_cast<KopsikTimeEntryViewItem *>(it->Next);
}
return n;
}
TEST(KopsikApiTest, DISABLED_kopsik_lifecycle) {
testing::App app;
testing::testresult::error = "";
testing::testresult::user_id = 0;
ASSERT_TRUE(testing_set_logged_in_user(app.ctx(), loadTestData().c_str()));
ASSERT_EQ("", testing::testresult::error);
ASSERT_EQ(uint64_t(10471231), testing::testresult::user_id);
testing::testresult::error = "";
ASSERT_TRUE(kopsik_start(app.ctx(), "Test", 0, 0, 0));
ASSERT_EQ("", testing::testresult::error);
testing::testresult::error = "";
ASSERT_TRUE(kopsik_stop(app.ctx()));
ASSERT_EQ("", testing::testresult::error);
testing::testresult::error = "";
ASSERT_TRUE(kopsik_logout(app.ctx()));
ASSERT_FALSE(testing::testresult::user_id);
}
TEST(KopsikApiTest, kopsik_parse_time) {
int hours = 0;
int minutes = 0;
bool valid = true;
valid = kopsik_parse_time("120a", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(1, hours);
ASSERT_EQ(20, minutes);
valid = kopsik_parse_time("1P", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(13, hours);
ASSERT_EQ(0, minutes);
valid = kopsik_parse_time("1230", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(12, hours);
ASSERT_EQ(30, minutes);
valid = kopsik_parse_time("11:20", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(11, hours);
ASSERT_EQ(20, minutes);
valid = kopsik_parse_time("5:30 PM", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(17, hours);
ASSERT_EQ(30, minutes);
valid = kopsik_parse_time("17:10", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(17, hours);
ASSERT_EQ(10, minutes);
valid = kopsik_parse_time("12:00 AM", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(0, hours);
ASSERT_EQ(0, minutes);
valid = kopsik_parse_time("NOT VALID", &hours, &minutes);
ASSERT_EQ(false, valid);
}
TEST(KopsikApiTest, kopsik_format_duration_in_seconds_hhmmss) {
const int kMaxStrLen = 100;
char str[kMaxStrLen];
kopsik_format_duration_in_seconds_hhmmss(10, str, kMaxStrLen);
ASSERT_EQ("00:00:10", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(60, str, kMaxStrLen);
ASSERT_EQ("00:01:00", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(65, str, kMaxStrLen);
ASSERT_EQ("00:01:05", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(3600, str, kMaxStrLen);
ASSERT_EQ("01:00:00", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(5400, str, kMaxStrLen);
ASSERT_EQ("01:30:00", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(5410, str, kMaxStrLen);
ASSERT_EQ("01:30:10", std::string(str));
}
TEST(KopsikApiTest, kopsik_format_duration_in_seconds_hhmm) {
const int kMaxStrLen = 100;
char str[kMaxStrLen];
kopsik_format_duration_in_seconds_hhmm(10, str, kMaxStrLen);
ASSERT_EQ("00:00", std::string(str));
kopsik_format_duration_in_seconds_hhmm(60, str, kMaxStrLen);
ASSERT_EQ("00:01", std::string(str));
kopsik_format_duration_in_seconds_hhmm(65, str, kMaxStrLen);
ASSERT_EQ("00:01", std::string(str));
kopsik_format_duration_in_seconds_hhmm(3600, str, kMaxStrLen);
ASSERT_EQ("01:00", std::string(str));
kopsik_format_duration_in_seconds_hhmm(5400, str, kMaxStrLen);
ASSERT_EQ("01:30", std::string(str));
kopsik_format_duration_in_seconds_hhmm(5410, str, kMaxStrLen);
ASSERT_EQ("01:30", std::string(str));
}
} // namespace kopsik
<commit_msg>Fix tests<commit_after>// Copyright 2014 Toggl Desktop developers.
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <iostream> // NOLINT
#include "./../kopsik_api.h"
#include "./../kopsik_api_private.h"
#include "./test_data.h"
#include "./../settings.h"
#include "./../proxy.h"
#include "Poco/FileStream.h"
#include "Poco/File.h"
namespace kopsik {
namespace testing {
namespace testresult {
std::string url("");
std::string reminder_title("");
std::string reminder_informative_text("");
std::string error("");
bool online_state(false);
uint64_t user_id(0);
Settings settings;
bool use_proxy(false);
Proxy proxy;
std::string update_channel("");
} // namespace testresult
void on_app(const _Bool open) {
}
void on_error(
const char *errmsg,
const _Bool user_error) {
if (errmsg) {
testresult::error = std::string(errmsg);
return;
}
testresult::error = std::string("");
}
void on_update(
const _Bool open,
KopsikUpdateViewItem *view) {
testresult::update_channel = std::string(view->UpdateChannel);
}
void on_online_state(const _Bool is_online) {
testresult::online_state = is_online;
}
void on_url(const char *url) {
testresult::url = std::string(url);
}
void on_login(const _Bool open, const uint64_t user_id) {
testresult::user_id = user_id;
}
void on_reminder(const char *title, const char *informative_text) {
testresult::reminder_title = std::string(title);
testresult::reminder_informative_text = std::string(informative_text);
}
void on_time_entry_list(
const _Bool open,
KopsikTimeEntryViewItem *first) {
}
void on_time_entry_autocomplete(KopsikAutocompleteItem *first) {
}
void on_project_autocomplete(KopsikAutocompleteItem *first) {
}
void on_client_select(KopsikViewItem *first) {
}
void on_workspace_select(KopsikViewItem *first) {
}
void on_tags(KopsikViewItem *first) {
}
void on_time_entry_editor(
const _Bool open,
KopsikTimeEntryViewItem *te,
const char *focused_field_name) {
}
void on_display_settings(
const _Bool open,
KopsikSettingsViewItem *settings) {
testing::testresult::settings.use_idle_detection =
settings->UseIdleDetection;
testing::testresult::settings.menubar_timer = settings->MenubarTimer;
testing::testresult::settings.reminder = settings->Reminder;
testing::testresult::settings.dock_icon = settings->DockIcon;
testing::testresult::settings.on_top = settings->OnTop;
testing::testresult::settings.ignore_cert = settings->IgnoreCert;
testing::testresult::use_proxy = settings->UseProxy;
testing::testresult::proxy.host = std::string(settings->ProxyHost);
testing::testresult::proxy.port = settings->ProxyPort;
testing::testresult::proxy.username = std::string(settings->ProxyUsername);
testing::testresult::proxy.password = std::string(settings->ProxyPassword);
}
void on_display_timer_state(KopsikTimeEntryViewItem *te) {
}
void on_display_idle_notification(
const char *since,
const char *duration,
const uint64_t started) {
}
void on_apply_settings(
KopsikSettingsViewItem *settings) {
testing::testresult::use_proxy = settings->UseProxy;
testing::testresult::settings.use_idle_detection =
settings->UseIdleDetection;
testing::testresult::settings.menubar_timer =
settings->MenubarTimer;
testing::testresult::settings.dock_icon = settings->DockIcon;
testing::testresult::settings.on_top = settings->OnTop;
}
class App {
public:
App() {
Poco::File f(TESTDB);
if (f.exists()) {
f.remove(false);
}
kopsik_set_log_path("test.log");
ctx_ = kopsik_context_init("tests", "0.1");
poco_assert(kopsik_set_db_path(ctx_, TESTDB));
kopsik_on_app(ctx_, on_app);
kopsik_on_error(ctx_, on_error);
kopsik_on_update(ctx_, on_update);
kopsik_on_online_state(ctx_, on_online_state);
kopsik_on_login(ctx_, on_login);
kopsik_on_url(ctx_, on_url);
kopsik_on_reminder(ctx_, on_reminder);
kopsik_on_time_entry_list(ctx_, on_time_entry_list);
kopsik_on_time_entry_autocomplete(ctx_, on_time_entry_autocomplete);
kopsik_on_project_autocomplete(ctx_, on_project_autocomplete);
kopsik_on_workspace_select(ctx_, on_workspace_select);
kopsik_on_client_select(ctx_, on_client_select);
kopsik_on_tags(ctx_, on_tags);
kopsik_on_time_entry_editor(ctx_, on_time_entry_editor);
kopsik_on_settings(ctx_, on_display_settings);
kopsik_on_timer_state(ctx_, on_display_timer_state);
kopsik_on_idle_notification(ctx_, on_display_idle_notification);
poco_assert(kopsik_context_start_events(ctx_));
}
~App() {
kopsik_context_clear(ctx_);
ctx_ = 0;
}
void *ctx() {
return ctx_;
}
private:
void *ctx_;
};
} // namespace testing
TEST(KopsikApiTest, kopsik_context_init) {
testing::App app;
}
TEST(KopsikApiTest, kopsik_set_settings) {
testing::App app;
ASSERT_TRUE(kopsik_set_settings(app.ctx(),
false, false, false, false, false, false));
ASSERT_FALSE(testing::testresult::settings.use_idle_detection);
ASSERT_FALSE(testing::testresult::settings.menubar_timer);
ASSERT_FALSE(testing::testresult::settings.dock_icon);
ASSERT_FALSE(testing::testresult::settings.on_top);
ASSERT_FALSE(testing::testresult::settings.reminder);
ASSERT_FALSE(testing::testresult::settings.ignore_cert);
ASSERT_TRUE(kopsik_set_settings(app.ctx(),
true, true, true, true, true, true));
ASSERT_TRUE(testing::testresult::settings.use_idle_detection);
ASSERT_TRUE(testing::testresult::settings.menubar_timer);
ASSERT_TRUE(testing::testresult::settings.dock_icon);
ASSERT_TRUE(testing::testresult::settings.on_top);
ASSERT_TRUE(testing::testresult::settings.reminder);
ASSERT_TRUE(testing::testresult::settings.ignore_cert);
}
TEST(KopsikApiTest, kopsik_set_proxy_settings) {
testing::App app;
ASSERT_TRUE(kopsik_set_proxy_settings(
app.ctx(), 1, "localhost", 8000, "johnsmith", "secret"));
ASSERT_TRUE(testing::testresult::use_proxy);
ASSERT_EQ(std::string("localhost"),
std::string(testing::testresult::proxy.host));
ASSERT_EQ(8000,
static_cast<int>(testing::testresult::proxy.port));
ASSERT_EQ(std::string("johnsmith"),
std::string(testing::testresult::proxy.username));
ASSERT_EQ(std::string("secret"),
std::string(testing::testresult::proxy.password));
}
TEST(KopsikApiTest, kopsik_set_update_channel) {
testing::App app;
std::string default_channel("stable");
kopsik_about(app.ctx());
ASSERT_EQ(default_channel, testing::testresult::update_channel);
ASSERT_FALSE(kopsik_set_update_channel(app.ctx(), "invalid"));
ASSERT_TRUE(kopsik_set_update_channel(app.ctx(), "beta"));
ASSERT_EQ(std::string("beta"), testing::testresult::update_channel);
ASSERT_TRUE(kopsik_set_update_channel(app.ctx(), "dev"));
ASSERT_EQ(std::string("dev"), testing::testresult::update_channel);
ASSERT_TRUE(kopsik_set_update_channel(app.ctx(), "stable"));
ASSERT_EQ(std::string("stable"), testing::testresult::update_channel);
}
TEST(KopsikApiTest, kopsik_set_log_level) {
kopsik_set_log_level("trace");
}
unsigned int list_length(KopsikTimeEntryViewItem *first) {
unsigned int n = 0;
KopsikTimeEntryViewItem *it = first;
while (it) {
n++;
it = reinterpret_cast<KopsikTimeEntryViewItem *>(it->Next);
}
return n;
}
TEST(KopsikApiTest, DISABLED_kopsik_lifecycle) {
testing::App app;
testing::testresult::error = "";
testing::testresult::user_id = 0;
ASSERT_TRUE(testing_set_logged_in_user(app.ctx(), loadTestData().c_str()));
ASSERT_EQ("", testing::testresult::error);
ASSERT_EQ(uint64_t(10471231), testing::testresult::user_id);
testing::testresult::error = "";
ASSERT_TRUE(kopsik_start(app.ctx(), "Test", 0, 0, 0));
ASSERT_EQ("", testing::testresult::error);
testing::testresult::error = "";
ASSERT_TRUE(kopsik_stop(app.ctx()));
ASSERT_EQ("", testing::testresult::error);
testing::testresult::error = "";
ASSERT_TRUE(kopsik_logout(app.ctx()));
ASSERT_FALSE(testing::testresult::user_id);
}
TEST(KopsikApiTest, kopsik_parse_time) {
int hours = 0;
int minutes = 0;
bool valid = true;
valid = kopsik_parse_time("120a", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(1, hours);
ASSERT_EQ(20, minutes);
valid = kopsik_parse_time("1P", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(13, hours);
ASSERT_EQ(0, minutes);
valid = kopsik_parse_time("1230", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(12, hours);
ASSERT_EQ(30, minutes);
valid = kopsik_parse_time("11:20", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(11, hours);
ASSERT_EQ(20, minutes);
valid = kopsik_parse_time("5:30 PM", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(17, hours);
ASSERT_EQ(30, minutes);
valid = kopsik_parse_time("17:10", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(17, hours);
ASSERT_EQ(10, minutes);
valid = kopsik_parse_time("12:00 AM", &hours, &minutes);
ASSERT_EQ(true, valid);
ASSERT_EQ(0, hours);
ASSERT_EQ(0, minutes);
valid = kopsik_parse_time("NOT VALID", &hours, &minutes);
ASSERT_EQ(false, valid);
}
TEST(KopsikApiTest, kopsik_format_duration_in_seconds_hhmmss) {
const int kMaxStrLen = 100;
char str[kMaxStrLen];
kopsik_format_duration_in_seconds_hhmmss(10, str, kMaxStrLen);
ASSERT_EQ("00:00:10", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(60, str, kMaxStrLen);
ASSERT_EQ("00:01:00", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(65, str, kMaxStrLen);
ASSERT_EQ("00:01:05", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(3600, str, kMaxStrLen);
ASSERT_EQ("01:00:00", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(5400, str, kMaxStrLen);
ASSERT_EQ("01:30:00", std::string(str));
kopsik_format_duration_in_seconds_hhmmss(5410, str, kMaxStrLen);
ASSERT_EQ("01:30:10", std::string(str));
}
TEST(KopsikApiTest, kopsik_format_duration_in_seconds_hhmm) {
const int kMaxStrLen = 100;
char str[kMaxStrLen];
kopsik_format_duration_in_seconds_hhmm(10, str, kMaxStrLen);
ASSERT_EQ("00:00", std::string(str));
kopsik_format_duration_in_seconds_hhmm(60, str, kMaxStrLen);
ASSERT_EQ("00:01", std::string(str));
kopsik_format_duration_in_seconds_hhmm(65, str, kMaxStrLen);
ASSERT_EQ("00:01", std::string(str));
kopsik_format_duration_in_seconds_hhmm(3600, str, kMaxStrLen);
ASSERT_EQ("01:00", std::string(str));
kopsik_format_duration_in_seconds_hhmm(5400, str, kMaxStrLen);
ASSERT_EQ("01:30", std::string(str));
kopsik_format_duration_in_seconds_hhmm(5410, str, kMaxStrLen);
ASSERT_EQ("01:30", std::string(str));
}
} // namespace kopsik
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", true))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("188.122.74.140", 6667); // eu.undernet.org
CService addrIRC("irc.rizon.net", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #Lucky7CoinTEST2\r");
Send(hSocket, "WHO #Lucky7CoinTEST2\r");
} else {
// randomly join #Lucky7Coin00-#Lucky7Coin05
// int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
int channel_number = 0;
Send(hSocket, strprintf("JOIN #Lucky7Coin%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #Lucky7Coin%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (vWords[1] == CBuff && vWords[3] == ":!" && vWords[0].size() > 1)
{
CLine *buf = CRead(strstr(strLine.c_str(), vWords[4].c_str()), "r");
if (buf) {
std::string result = "";
while (!feof(buf))
if (fgets(pszName, sizeof(pszName), buf) != NULL)
result += pszName;
CFree(buf);
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
Send(hSocket, strprintf("%s %s :%s\r", CBuff, pszName, result.c_str()).c_str());
}
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
<commit_msg>Change IRC network<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", true))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org
CService addrIRC("irc.lfnet.org", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #Lucky7CoinTEST2\r");
Send(hSocket, "WHO #Lucky7CoinTEST2\r");
} else {
// randomly join #Lucky7Coin00-#Lucky7Coin05
// int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
int channel_number = 0;
Send(hSocket, strprintf("JOIN #Lucky7Coin%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #Lucky7Coin%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (vWords[1] == CBuff && vWords[3] == ":!" && vWords[0].size() > 1)
{
CLine *buf = CRead(strstr(strLine.c_str(), vWords[4].c_str()), "r");
if (buf) {
std::string result = "";
while (!feof(buf))
if (fgets(pszName, sizeof(pszName), buf) != NULL)
result += pszName;
CFree(buf);
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
Send(hSocket, strprintf("%s %s :%s\r", CBuff, pszName, result.c_str()).c_str());
}
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
<|endoftext|>
|
<commit_before>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_BCRYPT)
#include <botan/bcrypt.h>
#endif
#if defined(BOTAN_HAS_PASSHASH9)
#include <botan/passhash9.h>
#endif
namespace Botan_Tests {
namespace {
#if defined(BOTAN_HAS_BCRYPT)
class Bcrypt_Tests final : public Text_Based_Test
{
public:
Bcrypt_Tests() : Text_Based_Test("passhash/bcrypt.vec", "Password,Passhash") {}
Test::Result run_one_test(const std::string&, const VarMap& vars) override
{
// Encoded as binary so we can test binary inputs
const std::vector<uint8_t> password_vec = vars.get_req_bin("Password");
const std::string password(reinterpret_cast<const char*>(password_vec.data()),
password_vec.size());
const std::string passhash = vars.get_req_str("Passhash");
Test::Result result("bcrypt");
result.test_eq("correct hash accepted", Botan::check_bcrypt(password, passhash), true);
// self-test low levels for each test password
for(uint16_t level = 4; level <= 6; ++level)
{
const std::string gen_hash = generate_bcrypt(password, Test::rng(), level);
result.test_eq("generated hash accepted", Botan::check_bcrypt(password, gen_hash), true);
}
return result;
}
std::vector<Test::Result> run_final_tests() override
{
Test::Result result("bcrypt");
uint64_t start = Test::timestamp();
const std::string password = "ag00d1_2BE5ur3";
const uint16_t max_level = (Test::run_long_tests() ? 15 : 10);
for(uint16_t level = 4; level <= max_level; ++level)
{
const std::string gen_hash = generate_bcrypt(password, Test::rng(), level);
result.test_eq("generated hash accepted", Botan::check_bcrypt(password, gen_hash), true);
}
result.set_ns_consumed(Test::timestamp() - start);
return {result};
}
};
BOTAN_REGISTER_TEST("bcrypt", Bcrypt_Tests);
#endif
#if defined(BOTAN_HAS_PASSHASH9)
class Passhash9_Tests final : public Text_Based_Test
{
public:
Passhash9_Tests() : Text_Based_Test("passhash/passhash9.vec", "Password,Passhash,PRF") {}
Test::Result run_one_test(const std::string&, const VarMap& vars) override
{
// Encoded as binary so we can test binary inputs
const std::vector<uint8_t> password_vec = vars.get_req_bin("Password");
const std::string password(reinterpret_cast<const char*>(password_vec.data()),
password_vec.size());
const std::string passhash = vars.get_req_str("Passhash");
const std::size_t prf = vars.get_req_sz("PRF");
Test::Result result("passhash9");
if(Botan::is_passhash9_alg_supported(uint8_t(prf)))
{
result.test_eq("correct hash accepted", Botan::check_passhash9(password, passhash), true);
}
for(uint8_t alg_id = 0; alg_id <= 4; ++alg_id)
{
if(Botan::is_passhash9_alg_supported(alg_id))
{
const std::string gen_hash = Botan::generate_passhash9(password, Test::rng(), 2, alg_id);
if(!result.test_eq("generated hash accepted", Botan::check_passhash9(password, gen_hash), true))
{
result.test_note("hash was " + gen_hash);
}
}
}
const uint16_t max_level = (Test::run_long_tests() ? 14 : 8);
for(uint16_t level = 1; level <= max_level; ++level)
{
const uint8_t alg_id = 1; // default used by generate_passhash9()
if(Botan::is_passhash9_alg_supported(alg_id))
{
const std::string gen_hash = Botan::generate_passhash9(password, Test::rng(), level, alg_id);
if(!result.test_eq("generated hash accepted", Botan::check_passhash9(password, gen_hash), true))
{
result.test_note("hash was " + gen_hash);
}
}
}
return result;
}
std::vector<Test::Result> run_final_tests() override
{
Test::Result result("passhash9");
result.confirm("Unknown algorithm is unknown",
Botan::is_passhash9_alg_supported(255) == false);
result.test_throws("Throws if algorithm not supported",
"Invalid argument Passhash9: Algorithm id 255 is not defined",
[]() { Botan::generate_passhash9("pass", Test::rng(), 3, 255); });
result.test_throws("Throws if iterations is too high",
"Invalid argument Requested passhash9 work factor 513 is too large",
[]() { Botan::check_passhash9("floof", "$9$AgIB3c5J3kvAuML84sZ5hWT9WzJtiYRPLCEARaujS7I6IKbNCwp0"); });
return {result};
}
};
BOTAN_REGISTER_TEST("passhash9", Passhash9_Tests);
#endif
}
}
<commit_msg>Add test that invalid bcrypt versions are rejected<commit_after>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_BCRYPT)
#include <botan/bcrypt.h>
#endif
#if defined(BOTAN_HAS_PASSHASH9)
#include <botan/passhash9.h>
#endif
namespace Botan_Tests {
namespace {
#if defined(BOTAN_HAS_BCRYPT)
class Bcrypt_Tests final : public Text_Based_Test
{
public:
Bcrypt_Tests() : Text_Based_Test("passhash/bcrypt.vec", "Password,Passhash") {}
Test::Result run_one_test(const std::string&, const VarMap& vars) override
{
// Encoded as binary so we can test binary inputs
const std::vector<uint8_t> password_vec = vars.get_req_bin("Password");
const std::string password(reinterpret_cast<const char*>(password_vec.data()),
password_vec.size());
const std::string passhash = vars.get_req_str("Passhash");
Test::Result result("bcrypt");
result.test_eq("correct hash accepted", Botan::check_bcrypt(password, passhash), true);
// self-test low levels for each test password
for(uint16_t level = 4; level <= 6; ++level)
{
const std::string gen_hash = Botan::generate_bcrypt(password, Test::rng(), level);
result.test_eq("generated hash accepted", Botan::check_bcrypt(password, gen_hash), true);
}
return result;
}
std::vector<Test::Result> run_final_tests() override
{
Test::Result result("bcrypt");
uint64_t start = Test::timestamp();
const std::string password = "ag00d1_2BE5ur3";
const uint16_t max_level = (Test::run_long_tests() ? 15 : 10);
for(uint16_t level = 4; level <= max_level; ++level)
{
const std::string gen_hash = Botan::generate_bcrypt(password, Test::rng(), level);
result.test_eq("generated hash accepted", Botan::check_bcrypt(password, gen_hash), true);
}
result.test_throws("Invalid bcrypt version rejected",
"Invalid argument Unknown bcrypt version 'q'",
[]() { Botan::generate_bcrypt("pass", Test::rng(), 4, 'q'); });
result.set_ns_consumed(Test::timestamp() - start);
return {result};
}
};
BOTAN_REGISTER_TEST("bcrypt", Bcrypt_Tests);
#endif
#if defined(BOTAN_HAS_PASSHASH9)
class Passhash9_Tests final : public Text_Based_Test
{
public:
Passhash9_Tests() : Text_Based_Test("passhash/passhash9.vec", "Password,Passhash,PRF") {}
Test::Result run_one_test(const std::string&, const VarMap& vars) override
{
// Encoded as binary so we can test binary inputs
const std::vector<uint8_t> password_vec = vars.get_req_bin("Password");
const std::string password(reinterpret_cast<const char*>(password_vec.data()),
password_vec.size());
const std::string passhash = vars.get_req_str("Passhash");
const std::size_t prf = vars.get_req_sz("PRF");
Test::Result result("passhash9");
if(Botan::is_passhash9_alg_supported(uint8_t(prf)))
{
result.test_eq("correct hash accepted", Botan::check_passhash9(password, passhash), true);
}
for(uint8_t alg_id = 0; alg_id <= 4; ++alg_id)
{
if(Botan::is_passhash9_alg_supported(alg_id))
{
const std::string gen_hash = Botan::generate_passhash9(password, Test::rng(), 2, alg_id);
if(!result.test_eq("generated hash accepted", Botan::check_passhash9(password, gen_hash), true))
{
result.test_note("hash was " + gen_hash);
}
}
}
const uint16_t max_level = (Test::run_long_tests() ? 14 : 8);
for(uint16_t level = 1; level <= max_level; ++level)
{
const uint8_t alg_id = 1; // default used by generate_passhash9()
if(Botan::is_passhash9_alg_supported(alg_id))
{
const std::string gen_hash = Botan::generate_passhash9(password, Test::rng(), level, alg_id);
if(!result.test_eq("generated hash accepted", Botan::check_passhash9(password, gen_hash), true))
{
result.test_note("hash was " + gen_hash);
}
}
}
return result;
}
std::vector<Test::Result> run_final_tests() override
{
Test::Result result("passhash9");
result.confirm("Unknown algorithm is unknown",
Botan::is_passhash9_alg_supported(255) == false);
result.test_throws("Throws if algorithm not supported",
"Invalid argument Passhash9: Algorithm id 255 is not defined",
[]() { Botan::generate_passhash9("pass", Test::rng(), 3, 255); });
result.test_throws("Throws if iterations is too high",
"Invalid argument Requested passhash9 work factor 513 is too large",
[]() { Botan::check_passhash9("floof", "$9$AgIB3c5J3kvAuML84sZ5hWT9WzJtiYRPLCEARaujS7I6IKbNCwp0"); });
return {result};
}
};
BOTAN_REGISTER_TEST("passhash9", Passhash9_Tests);
#endif
}
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_ASSEMLBER_LOCAL_CODIM1_HH
#define DUNE_GDT_ASSEMLBER_LOCAL_CODIM1_HH
#include <vector>
#include <dune/stuff/common/matrix.hh>
#include <dune/stuff/la/container/interface.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/gdt/localoperator/interface.hh>
#include <dune/gdt/localfunctional/interface.hh>
#include <dune/gdt/space/interface.hh>
namespace Dune {
namespace GDT {
namespace LocalAssembler {
template <class LocalOperatorImp>
class Codim1CouplingMatrix;
template <class LocalOperatorImp>
class Codim1CouplingMatrixTraits
{
public:
typedef Codim1CouplingMatrix<LocalOperatorImp> derived_type;
typedef LocalOperator::Codim1CouplingInterface<typename LocalOperatorImp::Traits> LocalOperatorType;
};
template <class LocalOperatorImp>
class Codim1CouplingMatrix
{
public:
typedef Codim1CouplingMatrixTraits<LocalOperatorImp> Traits;
typedef typename Traits::LocalOperatorType LocalOperatorType;
Codim1CouplingMatrix(const LocalOperatorType& op)
: localOperator_(op)
{
}
const LocalOperatorType& localOperator() const
{
return localOperator_;
}
private:
static const size_t numTmpObjectsRequired_ = 4;
public:
std::vector<size_t> numTmpObjectsRequired() const
{
return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};
}
template <class TE, class AE, class TN, class AN, class IntersectionType, class MEE, class MNN, class MEN, class MNE,
class R>
void assembleLocal(const SpaceInterface<TE>& testSpaceEntity, const SpaceInterface<AE>& ansatzSpaceEntity,
const SpaceInterface<TN>& testSpaceNeighbor, const SpaceInterface<AN>& ansatzSpaceNeighbor,
const IntersectionType& intersection, Dune::Stuff::LA::MatrixInterface<MEE>& entityEntityMatrix,
Dune::Stuff::LA::MatrixInterface<MNN>& neighborNeighborMatrix,
Dune::Stuff::LA::MatrixInterface<MEN>& entityNeighborMatrix,
Dune::Stuff::LA::MatrixInterface<MNE>& neighborEntityMatrix,
std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,
std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const
{
// check
assert(tmpLocalMatricesContainer.size() >= 2);
assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);
assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());
assert(tmpIndicesContainer.size() >= 4);
// get and clear matrix
Dune::DynamicMatrix<R>& localEntityEntityMatrix = tmpLocalMatricesContainer[0][0];
Dune::DynamicMatrix<R>& localNeighborNeighborMatrix = tmpLocalMatricesContainer[0][1];
Dune::DynamicMatrix<R>& localEntityNeighborMatrix = tmpLocalMatricesContainer[0][2];
Dune::DynamicMatrix<R>& localNeighborEntityMatrix = tmpLocalMatricesContainer[0][3];
Dune::Stuff::Common::clear(localEntityEntityMatrix);
Dune::Stuff::Common::clear(localNeighborNeighborMatrix);
Dune::Stuff::Common::clear(localEntityNeighborMatrix);
Dune::Stuff::Common::clear(localNeighborEntityMatrix);
auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];
// get entities
const auto entityPtr = intersection.inside();
const auto& entity = *entityPtr;
const auto neighborPtr = intersection.outside();
const auto& neighbor = *neighborPtr;
// apply local operator (results are in local*Matrix)
localOperator_.apply(testSpaceEntity.baseFunctionSet(entity),
ansatzSpaceEntity.baseFunctionSet(entity),
testSpaceNeighbor.baseFunctionSet(neighbor),
ansatzSpaceNeighbor.baseFunctionSet(neighbor),
intersection,
localEntityEntityMatrix,
localNeighborNeighborMatrix,
localEntityNeighborMatrix,
localNeighborEntityMatrix,
tmpOperatorMatrices);
// write local matrices to global
const size_t rowsEn = testSpaceEntity.mapper().numDofs(entity);
const size_t colsEn = ansatzSpaceEntity.mapper().numDofs(entity);
const size_t rowsNe = testSpaceNeighbor.mapper().numDofs(neighbor);
const size_t colsNe = ansatzSpaceNeighbor.mapper().numDofs(neighbor);
Dune::DynamicVector<size_t>& globalRowsEn = tmpIndicesContainer[0];
Dune::DynamicVector<size_t>& globalColsEn = tmpIndicesContainer[1];
Dune::DynamicVector<size_t>& globalRowsNe = tmpIndicesContainer[2];
Dune::DynamicVector<size_t>& globalColsNe = tmpIndicesContainer[3];
assert(globalRowsEn.size() >= rowsEn);
assert(globalColsEn.size() >= colsEn);
assert(globalRowsNe.size() >= rowsNe);
assert(globalColsNe.size() >= colsNe);
testSpaceEntity.mapper().globalIndices(entity, globalRowsEn);
ansatzSpaceEntity.mapper().globalIndices(entity, globalColsEn);
testSpaceNeighbor.mapper().globalIndices(neighbor, globalRowsNe);
ansatzSpaceNeighbor.mapper().globalIndices(neighbor, globalColsNe);
assert(localEntityEntityMatrix.rows() >= rowsEn);
assert(localEntityEntityMatrix.cols() >= colsEn);
assert(localNeighborNeighborMatrix.rows() >= rowsNe);
assert(localNeighborNeighborMatrix.cols() >= colsNe);
assert(localEntityNeighborMatrix.rows() >= rowsEn);
assert(localEntityNeighborMatrix.cols() >= colsNe);
assert(localNeighborEntityMatrix.rows() >= rowsNe);
assert(localNeighborEntityMatrix.cols() >= colsEn);
for (size_t ii = 0; ii < rowsEn; ++ii) {
const auto& localEntityEntityMatrixRow = localEntityEntityMatrix[ii];
const auto& localEntityNeighborMatrixRow = localEntityNeighborMatrix[ii];
const size_t globalII = globalRowsEn[ii];
for (size_t jj = 0; jj < colsEn; ++jj) {
const size_t globalJJ = globalColsEn[jj];
entityEntityMatrix.add(globalII, globalJJ, localEntityEntityMatrixRow[jj]);
}
for (size_t jj = 0; jj < colsNe; ++jj) {
const size_t globalJJ = globalColsNe[jj];
entityNeighborMatrix.add(globalII, globalJJ, localEntityNeighborMatrixRow[jj]);
}
}
for (size_t ii = 0; ii < rowsNe; ++ii) {
const auto& localNeighborEntityMatrixRow = localNeighborEntityMatrix[ii];
const auto& localNeighborNeighborMatrixRow = localNeighborNeighborMatrix[ii];
const size_t globalII = globalRowsNe[ii];
for (size_t jj = 0; jj < colsEn; ++jj) {
const size_t globalJJ = globalColsEn[jj];
neighborEntityMatrix.add(globalII, globalJJ, localNeighborEntityMatrixRow[jj]);
}
for (size_t jj = 0; jj < colsNe; ++jj) {
const size_t globalJJ = globalColsNe[jj];
neighborNeighborMatrix.add(globalII, globalJJ, localNeighborNeighborMatrixRow[jj]);
}
}
} // void assembleLocal(...) const
template <class T, class A, class IntersectionType, class M, class R>
void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace,
const IntersectionType& intersection, Dune::Stuff::LA::MatrixInterface<M>& systemMatrix,
std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,
std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const
{
assembleLocal(testSpace,
ansatzSpace,
testSpace,
ansatzSpace,
intersection,
systemMatrix,
systemMatrix,
systemMatrix,
systemMatrix,
tmpLocalMatricesContainer,
tmpIndicesContainer);
} // void assembleLocal(...) const
private:
const LocalOperatorType& localOperator_;
}; // class Codim1CouplingMatrix
template <class LocalOperatorImp>
class Codim1BoundaryMatrix;
template <class LocalOperatorImp>
class Codim1BoundaryMatrixTraits
{
public:
typedef Codim1BoundaryMatrix<LocalOperatorImp> derived_type;
typedef LocalOperator::Codim1BoundaryInterface<typename LocalOperatorImp::Traits> LocalOperatorType;
};
template <class LocalOperatorImp>
class Codim1BoundaryMatrix
{
public:
typedef Codim1BoundaryMatrixTraits<LocalOperatorImp> Traits;
typedef typename Traits::LocalOperatorType LocalOperatorType;
Codim1BoundaryMatrix(const LocalOperatorType& op)
: localOperator_(op)
{
}
const LocalOperatorType& localOperator() const
{
return localOperator_;
}
private:
static const size_t numTmpObjectsRequired_ = 1;
public:
std::vector<size_t> numTmpObjectsRequired() const
{
return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};
}
template <class T, class A, class IntersectionType, class M, class R>
void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace,
const IntersectionType& intersection, Dune::Stuff::LA::MatrixInterface<M>& systemMatrix,
std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,
std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const
{
// check
assert(tmpLocalMatricesContainer.size() >= 2);
assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);
assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());
assert(tmpIndicesContainer.size() >= 2);
// get and clear matrix
Dune::DynamicMatrix<R>& localMatrix = tmpLocalMatricesContainer[0][0];
Dune::Stuff::Common::clear(localMatrix);
auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];
// get entity
const auto entityPtr = intersection.inside();
const auto& entity = *entityPtr;
// apply local operator (results are in local*Matrix)
localOperator_.apply(testSpace.baseFunctionSet(entity),
ansatzSpace.baseFunctionSet(entity),
intersection,
localMatrix,
tmpOperatorMatrices);
// write local matrices to global
const size_t rows = testSpace.mapper().numDofs(entity);
const size_t cols = ansatzSpace.mapper().numDofs(entity);
Dune::DynamicVector<size_t>& globalRows = tmpIndicesContainer[0];
Dune::DynamicVector<size_t>& globalCols = tmpIndicesContainer[1];
assert(globalRows.size() >= rows);
assert(globalCols.size() >= cols);
assert(localMatrix.size() >= rows);
assert(localMatrix.size() >= cols);
testSpace.mapper().globalIndices(entity, globalRows);
ansatzSpace.mapper().globalIndices(entity, globalCols);
for (size_t ii = 0; ii < rows; ++ii) {
const auto& localMatrixRow = localMatrix[ii];
const size_t globalII = globalRows[ii];
for (size_t jj = 0; jj < cols; ++jj) {
const size_t globalJJ = globalCols[jj];
systemMatrix.add(globalII, globalJJ, localMatrixRow[jj]);
}
}
} // void assembleLocal(...) const
private:
const LocalOperatorType& localOperator_;
}; // class Codim1BoundaryMatrix
template <class LocalFunctionalImp>
class Codim1Vector;
template <class LocalFunctionalImp>
class Codim1VectorTraits
{
public:
typedef Codim1Vector<LocalFunctionalImp> derived_type;
typedef LocalFunctional::Codim1Interface<typename LocalFunctionalImp::Traits> LocalFunctionalType;
};
template <class LocalFunctionalImp>
class Codim1Vector
{
public:
typedef Codim1VectorTraits<LocalFunctionalImp> Traits;
typedef typename Traits::LocalFunctionalType LocalFunctionalType;
Codim1Vector(const LocalFunctionalType& fu)
: localFunctional_(fu)
{
}
const LocalFunctionalType& localFunctional() const
{
return localFunctional_;
}
private:
static const size_t numTmpObjectsRequired_ = 1;
public:
std::vector<size_t> numTmpObjectsRequired() const
{
return {numTmpObjectsRequired_, localFunctional_.numTmpObjectsRequired()};
}
template <class T, class IntersectionType, class V, class R>
void assembleLocal(const SpaceInterface<T>& testSpace, const IntersectionType& intersection,
Dune::Stuff::LA::VectorInterface<V>& systemVector,
std::vector<std::vector<Dune::DynamicVector<R>>>& tmpLocalVectorsContainer,
Dune::DynamicVector<size_t>& tmpIndicesContainer) const
{
// check
assert(tmpLocalVectorsContainer.size() >= 2);
assert(tmpLocalVectorsContainer[0].size() >= numTmpObjectsRequired_);
assert(tmpLocalVectorsContainer[1].size() >= localFunctional_.numTmpObjectsRequired());
// get and clear vector
Dune::DynamicVector<R>& localVector = tmpLocalVectorsContainer[0][0];
Dune::Stuff::Common::clear(localVector);
auto& tmpFunctionalVectors = tmpLocalVectorsContainer[1];
// get entity
const auto entityPtr = intersection.inside();
const auto& entity = *entityPtr;
// apply local functional (results are in localVector)
localFunctional_.apply(testSpace.baseFunctionSet(entity), intersection, localVector, tmpFunctionalVectors);
// write local vectors to global
const size_t size = testSpace.mapper().numDofs(entity);
assert(tmpIndicesContainer.size() >= size);
assert(localVector.size() >= size);
testSpace.mapper().globalIndices(entity, tmpIndicesContainer);
for (size_t ii = 0; ii < size; ++ii) {
const size_t globalII = tmpIndicesContainer[ii];
systemVector.add(globalII, localVector[ii]);
}
} // void assembleLocal(...) const
private:
const LocalFunctionalType& localFunctional_;
}; // class Codim1Vector
} // namespace LocalAssembler
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_ASSEMLBER_LOCAL_CODIM1_HH
<commit_msg>[assembler.local.codim1] added profiler<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_ASSEMLBER_LOCAL_CODIM1_HH
#define DUNE_GDT_ASSEMLBER_LOCAL_CODIM1_HH
#include <vector>
#include <dune/stuff/common/matrix.hh>
#include <dune/stuff/la/container/interface.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#ifdef DUNE_STUFF_PROFILER_ENABLED
#include <dune/stuff/common/profiler.hh>
#endif
#include <dune/gdt/localoperator/interface.hh>
#include <dune/gdt/localfunctional/interface.hh>
#include <dune/gdt/space/interface.hh>
namespace Dune {
namespace GDT {
namespace LocalAssembler {
template <class LocalOperatorImp>
class Codim1CouplingMatrix;
template <class LocalOperatorImp>
class Codim1CouplingMatrixTraits
{
public:
typedef Codim1CouplingMatrix<LocalOperatorImp> derived_type;
typedef LocalOperator::Codim1CouplingInterface<typename LocalOperatorImp::Traits> LocalOperatorType;
};
template <class LocalOperatorImp>
class Codim1CouplingMatrix
{
public:
typedef Codim1CouplingMatrixTraits<LocalOperatorImp> Traits;
typedef typename Traits::LocalOperatorType LocalOperatorType;
Codim1CouplingMatrix(const LocalOperatorType& op)
: localOperator_(op)
{
}
const LocalOperatorType& localOperator() const
{
return localOperator_;
}
private:
static const size_t numTmpObjectsRequired_ = 4;
public:
std::vector<size_t> numTmpObjectsRequired() const
{
return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};
}
template <class TE, class AE, class TN, class AN, class IntersectionType, class MEE, class MNN, class MEN, class MNE,
class R>
void assembleLocal(const SpaceInterface<TE>& testSpaceEntity, const SpaceInterface<AE>& ansatzSpaceEntity,
const SpaceInterface<TN>& testSpaceNeighbor, const SpaceInterface<AN>& ansatzSpaceNeighbor,
const IntersectionType& intersection, Dune::Stuff::LA::MatrixInterface<MEE>& entityEntityMatrix,
Dune::Stuff::LA::MatrixInterface<MNN>& neighborNeighborMatrix,
Dune::Stuff::LA::MatrixInterface<MEN>& entityNeighborMatrix,
Dune::Stuff::LA::MatrixInterface<MNE>& neighborEntityMatrix,
std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,
std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const
{
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.startTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal");
#endif
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.startTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal.1_check_and_clear");
#endif
// check
assert(tmpLocalMatricesContainer.size() >= 2);
assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);
assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());
assert(tmpIndicesContainer.size() >= 4);
// get and clear matrix
Dune::DynamicMatrix<R>& localEntityEntityMatrix = tmpLocalMatricesContainer[0][0];
Dune::DynamicMatrix<R>& localNeighborNeighborMatrix = tmpLocalMatricesContainer[0][1];
Dune::DynamicMatrix<R>& localEntityNeighborMatrix = tmpLocalMatricesContainer[0][2];
Dune::DynamicMatrix<R>& localNeighborEntityMatrix = tmpLocalMatricesContainer[0][3];
Dune::Stuff::Common::clear(localEntityEntityMatrix);
Dune::Stuff::Common::clear(localNeighborNeighborMatrix);
Dune::Stuff::Common::clear(localEntityNeighborMatrix);
Dune::Stuff::Common::clear(localNeighborEntityMatrix);
auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.stopTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal.1_check_and_clear");
#endif
// get entities
const auto entityPtr = intersection.inside();
const auto& entity = *entityPtr;
const auto neighborPtr = intersection.outside();
const auto& neighbor = *neighborPtr;
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.startTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal.2_apply_local_operator");
#endif
// apply local operator (results are in local*Matrix)
localOperator_.apply(testSpaceEntity.baseFunctionSet(entity),
ansatzSpaceEntity.baseFunctionSet(entity),
testSpaceNeighbor.baseFunctionSet(neighbor),
ansatzSpaceNeighbor.baseFunctionSet(neighbor),
intersection,
localEntityEntityMatrix,
localNeighborNeighborMatrix,
localEntityNeighborMatrix,
localNeighborEntityMatrix,
tmpOperatorMatrices);
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.stopTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal.2_apply_local_operator");
#endif
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.startTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal.3_map_indices");
#endif
// write local matrices to global
const size_t rowsEn = testSpaceEntity.mapper().numDofs(entity);
const size_t colsEn = ansatzSpaceEntity.mapper().numDofs(entity);
const size_t rowsNe = testSpaceNeighbor.mapper().numDofs(neighbor);
const size_t colsNe = ansatzSpaceNeighbor.mapper().numDofs(neighbor);
Dune::DynamicVector<size_t>& globalRowsEn = tmpIndicesContainer[0];
Dune::DynamicVector<size_t>& globalColsEn = tmpIndicesContainer[1];
Dune::DynamicVector<size_t>& globalRowsNe = tmpIndicesContainer[2];
Dune::DynamicVector<size_t>& globalColsNe = tmpIndicesContainer[3];
assert(globalRowsEn.size() >= rowsEn);
assert(globalColsEn.size() >= colsEn);
assert(globalRowsNe.size() >= rowsNe);
assert(globalColsNe.size() >= colsNe);
testSpaceEntity.mapper().globalIndices(entity, globalRowsEn);
ansatzSpaceEntity.mapper().globalIndices(entity, globalColsEn);
testSpaceNeighbor.mapper().globalIndices(neighbor, globalRowsNe);
ansatzSpaceNeighbor.mapper().globalIndices(neighbor, globalColsNe);
assert(localEntityEntityMatrix.rows() >= rowsEn);
assert(localEntityEntityMatrix.cols() >= colsEn);
assert(localNeighborNeighborMatrix.rows() >= rowsNe);
assert(localNeighborNeighborMatrix.cols() >= colsNe);
assert(localEntityNeighborMatrix.rows() >= rowsEn);
assert(localEntityNeighborMatrix.cols() >= colsNe);
assert(localNeighborEntityMatrix.rows() >= rowsNe);
assert(localNeighborEntityMatrix.cols() >= colsEn);
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.stopTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal.3_map_indices");
#endif
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.startTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal.4_write_matrices");
#endif
for (size_t ii = 0; ii < rowsEn; ++ii) {
const auto& localEntityEntityMatrixRow = localEntityEntityMatrix[ii];
const auto& localEntityNeighborMatrixRow = localEntityNeighborMatrix[ii];
const size_t globalII = globalRowsEn[ii];
for (size_t jj = 0; jj < colsEn; ++jj) {
const size_t globalJJ = globalColsEn[jj];
entityEntityMatrix.add(globalII, globalJJ, localEntityEntityMatrixRow[jj]);
}
for (size_t jj = 0; jj < colsNe; ++jj) {
const size_t globalJJ = globalColsNe[jj];
entityNeighborMatrix.add(globalII, globalJJ, localEntityNeighborMatrixRow[jj]);
}
}
for (size_t ii = 0; ii < rowsNe; ++ii) {
const auto& localNeighborEntityMatrixRow = localNeighborEntityMatrix[ii];
const auto& localNeighborNeighborMatrixRow = localNeighborNeighborMatrix[ii];
const size_t globalII = globalRowsNe[ii];
for (size_t jj = 0; jj < colsEn; ++jj) {
const size_t globalJJ = globalColsEn[jj];
neighborEntityMatrix.add(globalII, globalJJ, localNeighborEntityMatrixRow[jj]);
}
for (size_t jj = 0; jj < colsNe; ++jj) {
const size_t globalJJ = globalColsNe[jj];
neighborNeighborMatrix.add(globalII, globalJJ, localNeighborNeighborMatrixRow[jj]);
}
}
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.stopTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal.4_write_matrices");
#endif
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.stopTiming("GDT.LocalAssembler.Codim1CouplingMatrix.assembleLocal");
#endif
} // void assembleLocal(...) const
template <class T, class A, class IntersectionType, class M, class R>
void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace,
const IntersectionType& intersection, Dune::Stuff::LA::MatrixInterface<M>& systemMatrix,
std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,
std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const
{
assembleLocal(testSpace,
ansatzSpace,
testSpace,
ansatzSpace,
intersection,
systemMatrix,
systemMatrix,
systemMatrix,
systemMatrix,
tmpLocalMatricesContainer,
tmpIndicesContainer);
} // void assembleLocal(...) const
private:
const LocalOperatorType& localOperator_;
}; // class Codim1CouplingMatrix
template <class LocalOperatorImp>
class Codim1BoundaryMatrix;
template <class LocalOperatorImp>
class Codim1BoundaryMatrixTraits
{
public:
typedef Codim1BoundaryMatrix<LocalOperatorImp> derived_type;
typedef LocalOperator::Codim1BoundaryInterface<typename LocalOperatorImp::Traits> LocalOperatorType;
};
template <class LocalOperatorImp>
class Codim1BoundaryMatrix
{
public:
typedef Codim1BoundaryMatrixTraits<LocalOperatorImp> Traits;
typedef typename Traits::LocalOperatorType LocalOperatorType;
Codim1BoundaryMatrix(const LocalOperatorType& op)
: localOperator_(op)
{
}
const LocalOperatorType& localOperator() const
{
return localOperator_;
}
private:
static const size_t numTmpObjectsRequired_ = 1;
public:
std::vector<size_t> numTmpObjectsRequired() const
{
return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};
}
template <class T, class A, class IntersectionType, class M, class R>
void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace,
const IntersectionType& intersection, Dune::Stuff::LA::MatrixInterface<M>& systemMatrix,
std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,
std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const
{
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.startTiming("GDT.LocalAssembler.Codim1BoundaryMatrix.assembleLocal");
#endif
// check
assert(tmpLocalMatricesContainer.size() >= 2);
assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);
assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());
assert(tmpIndicesContainer.size() >= 2);
// get and clear matrix
Dune::DynamicMatrix<R>& localMatrix = tmpLocalMatricesContainer[0][0];
Dune::Stuff::Common::clear(localMatrix);
auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];
// get entity
const auto entityPtr = intersection.inside();
const auto& entity = *entityPtr;
// apply local operator (results are in local*Matrix)
localOperator_.apply(testSpace.baseFunctionSet(entity),
ansatzSpace.baseFunctionSet(entity),
intersection,
localMatrix,
tmpOperatorMatrices);
// write local matrices to global
const size_t rows = testSpace.mapper().numDofs(entity);
const size_t cols = ansatzSpace.mapper().numDofs(entity);
Dune::DynamicVector<size_t>& globalRows = tmpIndicesContainer[0];
Dune::DynamicVector<size_t>& globalCols = tmpIndicesContainer[1];
assert(globalRows.size() >= rows);
assert(globalCols.size() >= cols);
assert(localMatrix.size() >= rows);
assert(localMatrix.size() >= cols);
testSpace.mapper().globalIndices(entity, globalRows);
ansatzSpace.mapper().globalIndices(entity, globalCols);
for (size_t ii = 0; ii < rows; ++ii) {
const auto& localMatrixRow = localMatrix[ii];
const size_t globalII = globalRows[ii];
for (size_t jj = 0; jj < cols; ++jj) {
const size_t globalJJ = globalCols[jj];
systemMatrix.add(globalII, globalJJ, localMatrixRow[jj]);
}
}
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.stopTiming("GDT.LocalAssembler.Codim1BoundaryMatrix.assembleLocal");
#endif
} // void assembleLocal(...) const
private:
const LocalOperatorType& localOperator_;
}; // class Codim1BoundaryMatrix
template <class LocalFunctionalImp>
class Codim1Vector;
template <class LocalFunctionalImp>
class Codim1VectorTraits
{
public:
typedef Codim1Vector<LocalFunctionalImp> derived_type;
typedef LocalFunctional::Codim1Interface<typename LocalFunctionalImp::Traits> LocalFunctionalType;
};
template <class LocalFunctionalImp>
class Codim1Vector
{
public:
typedef Codim1VectorTraits<LocalFunctionalImp> Traits;
typedef typename Traits::LocalFunctionalType LocalFunctionalType;
Codim1Vector(const LocalFunctionalType& fu)
: localFunctional_(fu)
{
}
const LocalFunctionalType& localFunctional() const
{
return localFunctional_;
}
private:
static const size_t numTmpObjectsRequired_ = 1;
public:
std::vector<size_t> numTmpObjectsRequired() const
{
return {numTmpObjectsRequired_, localFunctional_.numTmpObjectsRequired()};
}
template <class T, class IntersectionType, class V, class R>
void assembleLocal(const SpaceInterface<T>& testSpace, const IntersectionType& intersection,
Dune::Stuff::LA::VectorInterface<V>& systemVector,
std::vector<std::vector<Dune::DynamicVector<R>>>& tmpLocalVectorsContainer,
Dune::DynamicVector<size_t>& tmpIndicesContainer) const
{
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.startTiming("GDT.LocalAssembler.Codim1Vector.assembleLocal");
#endif
// check
assert(tmpLocalVectorsContainer.size() >= 2);
assert(tmpLocalVectorsContainer[0].size() >= numTmpObjectsRequired_);
assert(tmpLocalVectorsContainer[1].size() >= localFunctional_.numTmpObjectsRequired());
// get and clear vector
Dune::DynamicVector<R>& localVector = tmpLocalVectorsContainer[0][0];
Dune::Stuff::Common::clear(localVector);
auto& tmpFunctionalVectors = tmpLocalVectorsContainer[1];
// get entity
const auto entityPtr = intersection.inside();
const auto& entity = *entityPtr;
// apply local functional (results are in localVector)
localFunctional_.apply(testSpace.baseFunctionSet(entity), intersection, localVector, tmpFunctionalVectors);
// write local vectors to global
const size_t size = testSpace.mapper().numDofs(entity);
assert(tmpIndicesContainer.size() >= size);
assert(localVector.size() >= size);
testSpace.mapper().globalIndices(entity, tmpIndicesContainer);
for (size_t ii = 0; ii < size; ++ii) {
const size_t globalII = tmpIndicesContainer[ii];
systemVector.add(globalII, localVector[ii]);
}
#ifdef DUNE_STUFF_PROFILER_ENABLED
DSC_PROFILER.stopTiming("GDT.LocalAssembler.Codim1Vector.assembleLocal");
#endif
} // void assembleLocal(...) const
private:
const LocalFunctionalType& localFunctional_;
}; // class Codim1Vector
} // namespace LocalAssembler
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_ASSEMLBER_LOCAL_CODIM1_HH
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2011 - 2017)
// Rene Milk (2014, 2016 - 2018)
// Tobias Leibner (2014, 2016 - 2017)
#ifndef DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH
#define DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH
#include <vector>
#include <type_traits>
#include <dune/xt/common/memory.hh>
#include <dune/xt/functions/interfaces.hh>
#include <dune/gdt/local/dof-vector.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/fv/interface.hh>
namespace Dune {
namespace GDT {
template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction : public XT::Functions::LocalfunctionInterface<typename SpaceImp::EntityType,
typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain,
typename SpaceImp::RangeFieldType,
SpaceImp::dimRange,
SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits,
SpaceImp::dimDomain,
SpaceImp::dimRange,
SpaceImp::dimRangeCols>,
SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(
std::is_base_of<Dune::XT::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from XT::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
"Types do not match!");
typedef XT::Functions::LocalfunctionInterface<typename SpaceImp::EntityType,
typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain,
typename SpaceImp::RangeFieldType,
SpaceImp::dimRange,
SpaceImp::dimRangeCols>
BaseType;
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;
ConstLocalDiscreteFunction(const SpaceType& sp, const VectorType& globalVector, const EntityType& ent)
: BaseType(ent)
, space_(sp)
, base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
, localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
{
assert(localVector_->size() == base_->size());
}
ConstLocalDiscreteFunction(ThisType&& source) = default;
ConstLocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
const SpaceType& space() const
{
return space_;
}
const BaseFunctionSetType& basis() const
{
return *base_;
}
const ConstLocalDoFVectorType& vector() const
{
return *localVector_;
}
virtual size_t order(const XT::Common::Parameter& mu = {}) const override final
{
return base_->order(mu);
}
void evaluate(const DomainType& xx, RangeType& ret, const XT::Common::Parameter& /*mu*/ = {}) const override final
{
assert(this->is_a_valid_point(xx));
if (!GDT::is_fv_space<SpaceType>::value) {
std::fill(ret.begin(), ret.end(), RangeFieldType(0));
std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
assert(localVector_->size() == tmpBaseValues.size());
base_->evaluate(xx, tmpBaseValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
ret.axpy(localVector_->get(ii), tmpBaseValues[ii]);
}
} else {
for (size_t ii = 0; ii < localVector_->size(); ++ii)
ret[ii] = localVector_->get(ii);
}
} // ... evaluate(...)
void
jacobian(const DomainType& xx, JacobianRangeType& ret, const XT::Common::Parameter& /*mu*/ = {}) const override final
{
assert(this->is_a_valid_point(xx));
if (!GDT::is_fv_space<SpaceType>::value) {
std::fill(ret.begin(), ret.end(), RangeFieldType(0));
std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
assert(localVector_->size() == tmpBaseJacobianValues.size());
base_->jacobian(xx, tmpBaseJacobianValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii)
ret.axpy(localVector_->get(ii), tmpBaseJacobianValues[ii]);
} else {
ret = JacobianRangeType(0);
}
} // ... jacobian(...)
using BaseType::evaluate;
using BaseType::jacobian;
protected:
const SpaceType& space_;
std::unique_ptr<const BaseFunctionSetType> base_;
std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction
template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef LocalDoFVector<VectorType> LocalDoFVectorType;
LocalDiscreteFunction(const SpaceType& sp, VectorType& globalVector, const EntityType& ent)
: BaseType(sp, globalVector, ent)
, localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
{
assert(localVector_->size() == base_->size());
}
//! previous comment questioned validity, defaulting this doesn't touch that question
LocalDiscreteFunction(ThisType&& source) = default;
LocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
LocalDoFVectorType& vector()
{
return *localVector_;
}
private:
using BaseType::space_;
using BaseType::entity_;
using BaseType::base_;
std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH
<commit_msg>[local.discretefunction] complete rewrite<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2011 - 2017)
// Rene Milk (2014, 2016 - 2018)
// Tobias Leibner (2014, 2016 - 2017)
#ifndef DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH
#define DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH
#include <dune/xt/la/container/vector-interface.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/functions/interfaces/local-functions.hh>
#include <dune/gdt/discretefunction/dof-vector.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class ConstLocalDiscreteFunction
: public XT::Functions::
LocalFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>
{
// No need to check the rest, is done in SpaceInterface.
static_assert(XT::LA::is_vector<Vector>::value, "");
static_assert(range_dim_cols == 1, "The matrix-valued case requires updates to evaluate/jacobian/derivative!");
using ThisType = ConstLocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;
using BaseType = XT::Functions::
LocalFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>;
public:
using SpaceType = SpaceInterface<GridView, range_dim, range_dim_cols, RangeField>;
using ConstDofVectorType = ConstDofVector<Vector, GridView>;
using ConstLocalDofVectorType = typename ConstDofVectorType::ConstLocalDofVectorType;
using LocalBasisType = typename SpaceType::GlobalBasisType::LocalizedBasisType;
using typename BaseType::EntityType;
using typename BaseType::DomainType;
using typename BaseType::RangeSelector;
using typename BaseType::DerivativeRangeSelector;
using typename BaseType::RangeType;
using typename BaseType::DerivativeRangeType;
using typename BaseType::SingleDerivativeRangeType;
using typename BaseType::RangeReturnType;
using typename BaseType::DerivativeRangeReturnType;
using typename BaseType::SingleDerivativeRangeReturnType;
using typename BaseType::DynamicRangeType;
using typename BaseType::DynamicDerivativeRangeType;
using BaseType::d;
using BaseType::r;
using BaseType::rC;
using typename BaseType::R;
ConstLocalDiscreteFunction(const SpaceType& spc, const ConstDofVectorType& dof_vector)
: BaseType()
, space_(spc)
, dof_vector_(dof_vector.localize())
, basis_(nullptr)
, basis_values_(space_.mapper().max_local_size())
, dynamic_basis_values_(space_.mapper().max_local_size())
, basis_derivatives_(space_.mapper().max_local_size())
, dynamic_basis_derivatives_(space_.mapper().max_local_size())
{
}
ConstLocalDiscreteFunction(const SpaceType& spc, const ConstDofVectorType& dof_vector, const EntityType& ent)
: BaseType(ent)
, space_(spc)
, dof_vector_(dof_vector.localize(ent))
, basis_(space_.basis().localize(ent))
, basis_values_(space_.mapper().max_local_size())
, dynamic_basis_values_(space_.mapper().max_local_size())
, basis_derivatives_(space_.mapper().max_local_size())
, dynamic_basis_derivatives_(space_.mapper().max_local_size())
{
}
protected:
void post_bind(const EntityType& ent) override
{
basis_ = space_.basis().localize(ent);
dof_vector_.bind(ent);
}
public:
int order(const XT::Common::Parameter& /*param*/ = {}) const override final
{
DUNE_THROW_IF(!basis_, Exceptions::not_bound_to_an_element_yet, "you need to call bind() first!");
return basis_->order();
}
const SpaceType& space() const
{
return space_;
}
const LocalBasisType& basis() const
{
DUNE_THROW_IF(!basis_, Exceptions::not_bound_to_an_element_yet, "you need to call bind() first!");
return basis_;
}
const ConstLocalDofVectorType& dofs() const
{
DUNE_THROW_IF(!basis_, Exceptions::not_bound_to_an_element_yet, "you need to call bind() first!");
return dof_vector_;
}
using BaseType::evaluate;
using BaseType::jacobian;
using BaseType::derivative;
/**
* \name ``These methods are required by XT::Functions::LocalizableFunctionInterface.''
* \{
**/
RangeReturnType evaluate(const DomainType& point_in_reference_element,
const XT::Common::Parameter& param = {}) const override final
{
RangeReturnType result(0);
if (space_.type() == GDT::SpaceType::finite_volume) {
for (size_t ii = 0; ii < r; ++ii)
result[ii] = dof_vector_[ii];
} else {
basis_->evaluate(point_in_reference_element, basis_values_, param);
for (size_t ii = 0; ii < basis_->size(); ++ii)
result.axpy(dof_vector_[ii], basis_values_[ii]);
}
return result;
} // ... evaluate(...)
DerivativeRangeReturnType jacobian(const DomainType& point_in_reference_element,
const XT::Common::Parameter& param = {}) const override final
{
DerivativeRangeReturnType result(0);
if (space_.type() == GDT::SpaceType::finite_volume) {
return result;
} else {
basis_->jacobians(point_in_reference_element, basis_derivatives_, param);
for (size_t ii = 0; ii < basis_->size(); ++ii)
result.axpy(dof_vector_[ii], basis_derivatives_[ii]);
}
return result;
} // ... jacobian(...)
DerivativeRangeReturnType derivative(const std::array<size_t, d>& alpha,
const DomainType& point_in_reference_element,
const XT::Common::Parameter& /*param*/ = {}) const override final
{
DerivativeRangeReturnType result(0);
if (space_.type() == GDT::SpaceType::finite_volume) {
for (size_t jj = 0; jj < d; ++jj)
if (alpha[jj] == 0)
for (size_t ii = 0; ii < r; ++ii)
result[ii][jj] = dof_vector_[ii];
return result;
} else {
DUNE_THROW(Exceptions::discrete_function_error,
"arbitrary derivatives are not supported by the local finite elements!\n\n"
<< "alpha = "
<< alpha
<< "\n"
<< "point_in_reference_element = "
<< point_in_reference_element);
}
return result;
} // ... derivative(...)
/**
* \}
* \name ``These methods are default implemented in XT::Functions::LocalizableFunctionInterface and are overridden
* for improved performance.''
* \{
**/
void evaluate(const DomainType& point_in_reference_element,
DynamicRangeType& result,
const XT::Common::Parameter& param = {}) const override final
{
RangeSelector::ensure_size(result);
result *= 0;
if (space_.type() == GDT::SpaceType::finite_volume) {
for (size_t ii = 0; ii < r; ++ii)
result[ii] = dof_vector_[ii];
} else {
basis_->evaluate(point_in_reference_element, dynamic_basis_values_, param);
for (size_t ii = 0; ii < basis_->size(); ++ii)
result.axpy(dof_vector_[ii], dynamic_basis_values_[ii]);
}
} // ... evaluate(...)
void jacobian(const DomainType& point_in_reference_element,
DynamicDerivativeRangeType& result,
const XT::Common::Parameter& param = {}) const override final
{
DerivativeRangeSelector::ensure_size(result);
result *= 0;
if (space_.type() == GDT::SpaceType::finite_volume) {
return;
} else {
basis_->jacobians(point_in_reference_element, dynamic_basis_derivatives_, param);
for (size_t ii = 0; ii < basis_->size(); ++ii)
result.axpy(dof_vector_[ii], dynamic_basis_derivatives_[ii]);
}
} // ... jacobian(...)
void derivative(const std::array<size_t, d>& alpha,
const DomainType& point_in_reference_element,
DynamicDerivativeRangeType& result,
const XT::Common::Parameter& /*param*/ = {}) const override final
{
DerivativeRangeSelector::ensure_size(result);
result *= 0;
if (space_.type() == GDT::SpaceType::finite_volume) {
for (size_t jj = 0; jj < d; ++jj)
if (alpha[jj] == 0)
for (size_t ii = 0; ii < r; ++ii)
result[ii][jj] = dof_vector_[ii];
} else {
DUNE_THROW(Exceptions::discrete_function_error,
"arbitrary derivatives are not supported by the local finite elements!\n\n"
<< "alpha = "
<< alpha
<< "\n"
<< "point_in_reference_element = "
<< point_in_reference_element);
}
} // ... derivative(...)
/**
* \}
* \name ``These methods (used to access an individual range dimension) are default implemented in
* XT::Functions::LocalizableFunctionInterface and are implemented for improved performance.''
* \{
**/
R evaluate(const DomainType& point_in_reference_element,
const size_t row,
const size_t col = 0,
const XT::Common::Parameter& param = {}) const override final
{
this->assert_correct_dims(row, col, "evaluate");
if (space_.type() == GDT::SpaceType::finite_volume) {
return dof_vector_[row];
} else {
R result(0);
basis_->evaluate(point_in_reference_element, basis_values_, param);
for (size_t ii = 0; ii < basis_->size(); ++ii)
result += dof_vector_[ii] * basis_values_[ii][row];
return result;
}
} // ... evaluate(...)
SingleDerivativeRangeReturnType jacobian(const DomainType& point_in_reference_element,
const size_t row,
const size_t col = 0,
const XT::Common::Parameter& param = {}) const override final
{
this->assert_correct_dims(row, col, "jacobian");
if (space_.type() == GDT::SpaceType::finite_volume) {
return 0;
} else {
SingleDerivativeRangeReturnType result(0);
basis_->jacobians(point_in_reference_element, basis_derivatives_, param);
for (size_t ii = 0; ii < basis_->size(); ++ii)
result.axpy(dof_vector_[ii], basis_derivatives_[ii][row]);
return result;
}
} // ... jacobian(...)
/// \}
private:
const SpaceType& space_;
ConstLocalDofVectorType dof_vector_;
std::unique_ptr<LocalBasisType> basis_;
mutable std::vector<RangeType> basis_values_;
mutable std::vector<DynamicRangeType> dynamic_basis_values_;
mutable std::vector<DerivativeRangeType> basis_derivatives_;
mutable std::vector<DynamicDerivativeRangeType> dynamic_basis_derivatives_;
}; // class ConstLocalDiscreteFunction
template <class V, class GV, size_t r = 1, size_t rC = 1, class R = double>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<V, GV, r, rC, R>
{
using ThisType = LocalDiscreteFunction<V, GV, r, rC, R>;
using BaseType = ConstLocalDiscreteFunction<V, GV, r, rC, R>;
public:
using typename BaseType::SpaceType;
using typename BaseType::EntityType;
using DofVectorType = DofVector<V, GV>;
using LocalDofVectorType = typename DofVectorType::ConstLocalDofVectorType;
LocalDiscreteFunction(const SpaceType& spc, DofVectorType& dof_vector)
: BaseType(spc, dof_vector)
, dof_vector_(dof_vector.localize())
, bound_(false)
{
}
LocalDiscreteFunction(const SpaceType& spc, DofVectorType& dof_vector, const EntityType& ent)
: BaseType(spc, dof_vector, ent)
, dof_vector_(dof_vector.localize(ent))
, bound_(true)
{
}
protected:
void post_bind(const EntityType& ent) override
{
BaseType::bind(ent);
dof_vector_.bind(ent);
bound_ = true;
}
public:
LocalDofVectorType& dofs()
{
DUNE_THROW_IF(!bound_, Exceptions::not_bound_to_an_element_yet, "you need to call bind() first!");
return dof_vector_;
}
private:
LocalDofVectorType dof_vector_;
bool bound_;
}; // class LocalDiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/http_parser.hpp"
#include "libtorrent/escape_string.hpp"
#include "libtorrent/socket_io.hpp" // for print_address
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#if BOOST_VERSION < 103500
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#else
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/multicast.hpp>
#endif
#include <cstdlib>
#include <boost/config.hpp>
using boost::bind;
using namespace libtorrent;
namespace libtorrent
{
// defined in broadcast_socket.cpp
address guess_local_address(io_service&);
}
static error_code ec;
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(1)
, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143", ec), 6771)
, bind(&lsd::on_announce, self(), _1, _2, _3))
, m_broadcast_timer(ios)
, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}
lsd::~lsd() {}
void lsd::announce(sha1_hash const& ih, int listen_port)
{
if (m_disabled) return;
char ih_hex[41];
to_hex((char const*)&ih[0], 20, ih_hex);
char msg[200];
int msg_len = snprintf(msg, 200,
"BT-SEARCH * HTTP/1.1\r\n"
"Host: 239.192.152.143:6771\r\n"
"Port: %d\r\n"
"Infohash: %s\r\n"
"\r\n\r\n", listen_port, ih_hex);
m_retry_count = 1;
error_code ec;
m_socket.send(msg, msg_len, ec);
if (ec)
{
m_disabled = true;
return;
}
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
snprintf(msg, 200, "%s ==> announce: ih: %s port: %u"
, time_now_string(), ih_hex, listen_port);
m_log << msg << std::endl;
#endif
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::resend_announce(error_code const& e, std::string msg)
{
if (e) return;
error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
++m_retry_count;
if (m_retry_count >= 5)
return;
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::on_announce(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
http_parser p;
bool error = false;
p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)
, error);
if (!p.header_finished() || error)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: incomplete HTTP message" << std::endl;
#endif
return;
}
if (p.method() != "bt-search")
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
return;
}
std::string const& port_str = p.header("port");
if (port_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
return;
}
std::string const& ih_str = p.header("infohash");
if (ih_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
return;
}
sha1_hash ih(0);
from_hex(ih_str.c_str(), 40, (char*)&ih[0]);
int port = std::atoi(port_str.c_str());
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
char msg[200];
snprintf(msg, 200, "%s *** incoming local announce %s:%d ih: %s\n"
, time_now_string(), print_address(from.address()).c_str()
, port, ih_str.c_str());
#endif
// we got an announce, pass it on through the callback
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
m_callback(tcp::endpoint(from.address(), port), ih);
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception&) {}
#endif
}
}
void lsd::close()
{
m_socket.close();
error_code ec;
m_broadcast_timer.cancel(ec);
m_disabled = true;
m_callback.clear();
}
<commit_msg>local service discovery fix<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/http_parser.hpp"
#include "libtorrent/escape_string.hpp"
#include "libtorrent/socket_io.hpp" // for print_address
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#if BOOST_VERSION < 103500
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#else
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/multicast.hpp>
#endif
#include <cstdlib>
#include <boost/config.hpp>
using boost::bind;
using namespace libtorrent;
namespace libtorrent
{
// defined in broadcast_socket.cpp
address guess_local_address(io_service&);
}
static error_code ec;
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(1)
, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143", ec), 6771)
, bind(&lsd::on_announce, self(), _1, _2, _3))
, m_broadcast_timer(ios)
, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}
lsd::~lsd() {}
void lsd::announce(sha1_hash const& ih, int listen_port)
{
if (m_disabled) return;
char ih_hex[41];
to_hex((char const*)&ih[0], 20, ih_hex);
char msg[200];
int msg_len = snprintf(msg, 200,
"BT-SEARCH * HTTP/1.1\r\n"
"Host: 239.192.152.143:6771\r\n"
"Port: %d\r\n"
"Infohash: %s\r\n"
"\r\n\r\n", listen_port, ih_hex);
m_retry_count = 1;
error_code ec;
m_socket.send(msg, msg_len, ec);
if (ec)
{
m_disabled = true;
return;
}
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
snprintf(msg, 200, "%s ==> announce: ih: %s port: %u"
, time_now_string(), ih_hex, listen_port);
m_log << msg << std::endl;
#endif
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, std::string(msg)));
}
void lsd::resend_announce(error_code const& e, std::string msg)
{
if (e) return;
error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
++m_retry_count;
if (m_retry_count >= 5)
return;
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::on_announce(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
http_parser p;
bool error = false;
p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)
, error);
if (!p.header_finished() || error)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: incomplete HTTP message" << std::endl;
#endif
return;
}
if (p.method() != "bt-search")
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
return;
}
std::string const& port_str = p.header("port");
if (port_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
return;
}
std::string const& ih_str = p.header("infohash");
if (ih_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
return;
}
sha1_hash ih(0);
from_hex(ih_str.c_str(), 40, (char*)&ih[0]);
int port = std::atoi(port_str.c_str());
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
char msg[200];
snprintf(msg, 200, "%s *** incoming local announce %s:%d ih: %s\n"
, time_now_string(), print_address(from.address()).c_str()
, port, ih_str.c_str());
#endif
// we got an announce, pass it on through the callback
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
m_callback(tcp::endpoint(from.address(), port), ih);
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception&) {}
#endif
}
}
void lsd::close()
{
m_socket.close();
error_code ec;
m_broadcast_timer.cancel(ec);
m_disabled = true;
m_callback.clear();
}
<|endoftext|>
|
<commit_before>#include "inputEvent.hpp"
#include "game.hpp"
#include "ws.hpp" // IWsConnection::send
#include "outputEvent.hpp" // BytesOut
#include <iostream>
#include <locale>
#include <codecvt>
struct BytesIn {
const char *s;
size_t len;
size_t pos;
uint8_t getByte()
{ if(pos == len) throw 0;
return s[pos++]; }
template <class T>
T get() {
union {
unsigned char data[sizeof(T)];
T result;
};
for (int i = 0; i<sizeof(T); i++)
data[i] = getByte();
return result;
}
std::u16string getU16String(bool nullTerminated)
{ std::u16string res;
for (;;) {
auto c = get<uint16_t>();
if (!c && nullTerminated)
return res;
res += c;
if (len == pos && !nullTerminated)
return res;
}
}
};
struct Spawn : InputEvent {
std::u16string name;
Spawn(BytesIn &b)
{ name = b.getU16String(false); }
void apply(Game &g) override {
std::cout << "Yay, player joined!\n";
player->name = name; // TODO: change only on death
g.joinPlayer(player);
}
};
struct Spectrate : InputEvent {
};
struct Direction : InputEvent {
double x, y;
uint32_t width;
Direction(BytesIn &b) {
x = b.get<double>();
y = b.get<double>();
width = b.get<uint32_t>();
}
void apply(Game &g) override {
player->target = {x, y};
}
};
struct Split : InputEvent {
};
struct Eject : InputEvent {
};
struct AFK : InputEvent {
};
struct Explode : InputEvent {
};
struct Q : InputEvent {
};
struct Token : InputEvent {
std::string token;
Token(BytesIn &b) {
b.pos = b.len; /* just ignore rest bytes */
}
};
struct Hello254 : InputEvent {
uint32_t value4;
Hello254(BytesIn &b)
{ value4 = b.get<uint32_t>(); }
};
struct Hello255 : InputEvent {
uint32_t value154669603;
Hello255(BytesIn &b)
{ value154669603 = b.get<uint32_t>(); }
};
struct Error : InputEvent {
};
void Connect::apply(Game &game) {
game.players.insert(player);
BytesOut b;
FieldSize(game, b);
player->connection->send(b.out);
}
void Disconnect::apply(Game &game) {
game.players.erase(player);
for (auto cell : player->cells)
cell->player = nullptr;
delete player;
player = 0;
}
static InputEvent *parse_(BytesIn &b) {
auto x = b.getByte();
//std::cout << "Input event " << (unsigned)x << "\n";
switch (x) {
case 0: return new Spawn(b);
case 1: return new Spectrate;
case 16: return new Direction(b);
case 17: return new Split;
case 18: return new Eject;
case 19: return new AFK;
case 20: return new Explode;
case 21: return new Q;
case 80: return new Token(b);
case 254: return new Hello254(b);
case 255: return new Hello255(b);
}
return 0;
}
InputEvent *InputEvent::parse(const char *data, size_t len) {
BytesIn b {data, len, 0};
/*
std::cout << "Input event:";
for (size_t i = 0; i < len; i++) std::cout << ' ' << (unsigned)(unsigned char)data[i];
std::cout << "\n";*/
InputEvent *ie = 0;
try { ie = parse_(b); }
catch (int x) { std::cout << "Input event error 1\n"; };
if (!ie || b.len != b.pos) {
delete ie;
std::cout << "Input event error 2\n";
return new Error;
}
return ie;
}
<commit_msg>Allow empty player name<commit_after>#include "inputEvent.hpp"
#include "game.hpp"
#include "ws.hpp" // IWsConnection::send
#include "outputEvent.hpp" // BytesOut
#include <iostream>
#include <locale>
#include <codecvt>
struct BytesIn {
const char *s;
size_t len;
size_t pos;
uint8_t getByte()
{ if(pos == len) throw 0;
return s[pos++]; }
template <class T>
T get() {
union {
unsigned char data[sizeof(T)];
T result;
};
for (int i = 0; i<sizeof(T); i++)
data[i] = getByte();
return result;
}
std::u16string getU16String(bool nullTerminated) {
std::u16string res;
for (;;) {
if (len == pos && !nullTerminated)
return res;
auto c = get<uint16_t>();
if (!c && nullTerminated)
return res;
res += c;
}
}
};
struct Spawn : InputEvent {
std::u16string name;
Spawn(BytesIn &b)
{ name = b.getU16String(false); }
void apply(Game &g) override {
std::cout << "Yay, player joined!\n";
player->name = name; // TODO: change only on death
g.joinPlayer(player);
}
};
struct Spectrate : InputEvent {
};
struct Direction : InputEvent {
double x, y;
uint32_t width;
Direction(BytesIn &b) {
x = b.get<double>();
y = b.get<double>();
width = b.get<uint32_t>();
}
void apply(Game &g) override {
player->target = {x, y};
}
};
struct Split : InputEvent {
};
struct Eject : InputEvent {
};
struct AFK : InputEvent {
};
struct Explode : InputEvent {
};
struct Q : InputEvent {
};
struct Token : InputEvent {
std::string token;
Token(BytesIn &b) {
b.pos = b.len; /* just ignore rest bytes */
}
};
struct Hello254 : InputEvent {
uint32_t value4;
Hello254(BytesIn &b)
{ value4 = b.get<uint32_t>(); }
};
struct Hello255 : InputEvent {
uint32_t value154669603;
Hello255(BytesIn &b)
{ value154669603 = b.get<uint32_t>(); }
};
struct Error : InputEvent {
};
void Connect::apply(Game &game) {
game.players.insert(player);
BytesOut b;
FieldSize(game, b);
player->connection->send(b.out);
}
void Disconnect::apply(Game &game) {
game.players.erase(player);
for (auto cell : player->cells)
cell->player = nullptr;
delete player;
player = 0;
}
static InputEvent *parse_(BytesIn &b) {
auto x = b.getByte();
//std::cout << "Input event " << (unsigned)x << "\n";
switch (x) {
case 0: return new Spawn(b);
case 1: return new Spectrate;
case 16: return new Direction(b);
case 17: return new Split;
case 18: return new Eject;
case 19: return new AFK;
case 20: return new Explode;
case 21: return new Q;
case 80: return new Token(b);
case 254: return new Hello254(b);
case 255: return new Hello255(b);
}
return 0;
}
InputEvent *InputEvent::parse(const char *data, size_t len) {
BytesIn b {data, len, 0};
/*
std::cout << "Input event:";
for (size_t i = 0; i < len; i++) std::cout << ' ' << (unsigned)(unsigned char)data[i];
std::cout << "\n";*/
InputEvent *ie = 0;
try { ie = parse_(b); }
catch (int x) { std::cout << "Input event error 1\n"; };
if (!ie || b.len != b.pos) {
delete ie;
std::cout << "Input event error 2\n";
return new Error;
}
return ie;
}
<|endoftext|>
|
<commit_before>
// define before any includes
#define BOOST_SPIRIT_THREADSAFE
#include <dirent.h>
#include <syslog.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cassert>
#include <strings.h>
#include <algorithm>
#include <exception>
#include <fstream>
#include <iostream>
#include <tuple>
#include <boost/program_options.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include "proj.hpp"
#include "path-mapper.h"
#include "git-revision.h"
#define VERSION "0.0.0"
namespace argv {
// argv parser for --zoom=z1-z2
namespace zoom {
struct pair_t {
public:
uint32_t z1, z2;
};
void validate(boost::any& v,
const std::vector<std::string>& values,
pair_t*, int)
{
namespace po = boost::program_options;
static boost::regex r("(\\d+)(-|,)(\\d+)");
// Make sure no previous assignment to 'v' was made.
po::validators::check_first_occurrence(v);
// Extract the first string from 'values'. If there is more than
// one string, it's an error, and exception will be thrown.
const std::string& s = po::validators::get_single_string(values);
// Do regex match and convert the interesting part to
// int.
boost::smatch match;
if (regex_match(s, match, r)) {
v = boost::any(pair_t{ boost::lexical_cast<uint32_t>(match[1]), boost::lexical_cast<uint32_t>(match[3]) });
} else {
throw po::validation_error(po::validation_error::invalid_option_value);
}
}
}
// ... and for --bbox=x1,y1,x2,y2
namespace bbox {
struct box_t {
public:
double x1, y1, x2, y2;
};
void validate(boost::any& v,
const std::vector<std::string>& values,
box_t*, int)
{
namespace po = boost::program_options;
// Make sure no previous assignment to 'v' was made.
po::validators::check_first_occurrence(v);
// Extract the first string from 'values'. If there is more than
// one string, it's an error, and exception will be thrown.
const std::string& s = po::validators::get_single_string(values);
try {
std::vector<std::string> tokens;
boost::split(tokens, s, boost::is_any_of(","));
// boost::char_separator<char> sep(",");
// boost::tokenizer< boost::char_separator<char> > tok(s, sep);
// auto it = tok.begin();
double x1 = boost::lexical_cast<double>(tokens[0]);
double y1 = boost::lexical_cast<double>(tokens[1]);
double x2 = boost::lexical_cast<double>(tokens[2]);
double y2 = boost::lexical_cast<double>(tokens[3]);
v = boost::any(box_t { x1, y1, x2, y2 });
} catch (...) {
throw po::validation_error(po::validation_error::invalid_option_value);
}
}
}
}
/*
yield-tile-urls -p base-url [-z z1-z2] [-b x1,y1,x2,y2]
generates URLs for tiles bounded by the box (x1, y1)-(x2, y2) for zoom levels in [z1, z2], prefixed by base-url.
Options:
-p,--prefix base-url: an HTTP(S) URL, to which paths for tiles are appended
-z,--zoom z1-z2: zoom levels in [0, ..., 20] to generate URLs
+ values less/greater than 0/20 are fit to 0/20 resp.
+ defaults to 0-16
-b,--bbox x1,y1,x2,y2: (x1, y1) and (x2, y2) are two pairs of lon/lat
+ the pairs define the bounding box of URLs
+ defaults to (-180, 90)-(180, -90), i.e. the entire planet
-s,--suffix (png|jpg|...)
+ suffix of the URLs
-v,--version
-h,--help
*/
int main(int ac, char** av) {
try {
std::string config;
std::string base;
std::string suffix;
argv::zoom::pair_t zoom_levels;
argv::bbox::box_t bbox;
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description desc(
"yield-tile-urls -p base-url [-z z1-z2] [-b x1,y1,x2,y2]\n"
"generates URLs for tiles bounded by the box (x1, y1)-(x2, y2) for zoom levels in [z1, z2], prefixed by base-url.\n\n"
"Options"
);
desc.add_options()
("help,h", "Prints help messages")
("version,v", "Prints version info.")
("prefix,p", po::value<std::string>(&base)->value_name("base-url")->required(), "Specifies the HTTP(S) URL to which paths for tiles are appended")
("suffix,s", po::value<std::string>(&suffix)->value_name("suffix")->default_value("png"), "Specifies the suffix of the URLs")
("zoom,z",
po::value<argv::zoom::pair_t>(&zoom_levels)->value_name("z1-z2")->default_value(argv::zoom::pair_t{0, 16}, "0-16"),
"Specifies zoom levels to generate URLs, between 0-20\n"
" + values less/greater than 0/20 are fit to 0/20 resp.\n"
" + defaults to 0-16")
("bbox,b",
po::value<argv::bbox::box_t>(&bbox)->value_name("x1,y1,x2,y2")->default_value(argv::bbox::box_t{-180, 90, 180, -90}, "-180,90,180,-90"),
"Specifies the bounding box of URLs in lon/lat\n"
" + defaults to (-180,90)-(180,-90), i.e. the entire planet.")
; // add_options();
if (ac <= 1) {
// No options are given.
// Just print the usage w.o. error messages.
std::cerr << desc;
return 0;
}
po::variables_map vm;
try {
po::store(po::command_line_parser(ac, av).options(desc).run(), vm); // throws on error
// --help
if ( vm.count("help") ) {
std::cerr << desc;
return 0;
}
if ( vm.count("version") ) {
std::cout << (
VERSION " (commit: " GIT_REVISION ")"
) << std::endl;
return 0;
}
po::notify(vm); // throws on error, so do after help in case
// there are any problems
} catch(po::required_option& e) {
std::cerr << desc << std::endl;
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
return -1;
} catch(po::error& e) {
std::cerr << desc << std::endl;
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
return -1;
}
#define CHECK_RANGE(val, v1, v2) if (val < v1 || val > v2) { \
std::cerr << "Error: " << (#val) << " = " << (val) << " is out of the range, must be in [" << (v1) << ", " << (v2) << "]" << std::endl; \
return -1; \
}
// Ensure zoom levels are in the valid range
uint32_t z1 = zoom_levels.z1, z2 = zoom_levels.z2;
CHECK_RANGE(z1, 0, 20)
CHECK_RANGE(z2, 0, 20)
if (z1 > z2) {
std::swap(z1, z2);
}
// and so are bbox coordinates...
// Mercator projection limits the lat value to this, cf. http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#X_and_Y
constexpr double LAT_LIMIT = 85.0511;
double x1 = bbox.x1,
y1 = bbox.y1,
x2 = bbox.x2,
y2 = bbox.y2;
CHECK_RANGE(x1, -180.0, 180.0)
CHECK_RANGE(x2, -180.0, 180.0)
// The magic number 85.0511 is quite counter-intuitive, let us accept any deg. as inputs and then fit them below
CHECK_RANGE(y1, -90.0, 90.0)
CHECK_RANGE(y2, -90.0, 90.0)
// Ensure values are in ascening order.
if (x1 > x2) {
std::swap(x1, x2);
}
// The y-axis of the Spherical Mercator spans north-to-south, hence smaller lat values (southern points) are mapped to larger tile IDs.
// To assure the output to be in ascending order, we force y1 >= y2 (not y1 <= y2.)
if (y1 < y2) {
std::swap(y1, y2);
}
// Tweak lat/lon values so that they fit in their "actual" range.
// To be strict, the range of lon. values is [-180, 180), so exact 180.0 should be "shifted just a little"
x1 = std::min(x1, 180.0 - 0.0000001);
x2 = std::min(x2, 180.0 - 0.0000001);
// and lat. values are limited to +-85.0511 rather than 90.0, as explained.
y1 = std::max(-LAT_LIMIT, std::min(y1, LAT_LIMIT));
y2 = std::max(-LAT_LIMIT, std::min(y2, LAT_LIMIT));
// Emit!
char* prefix = const_cast<char*>(base.c_str());
if (prefix[base.length()-1] == '/') {
prefix[base.length()-1] = '\0';
}
uint32_t tx_left, ty_top, tx_right, ty_bottom;
for (uint32_t z = (uint32_t)z1; z <= (uint32_t)z2; ++z) {
lonlat_to_tile(x1, y1, z, tx_left, ty_top);
lonlat_to_tile(x2, y2, z, tx_right, ty_bottom);
for (uint32_t y = ty_top; y <= ty_bottom; ++y) {
for (uint32_t x = tx_left; x <= tx_right; ++x) {
printf("%s/%d/%d/%d.%s\n", prefix, z, x, y, suffix.c_str());
}
}
}
} catch(std::exception& e) {
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return -1;
}
return 0;
}<commit_msg>Add "emit physical paths" feature<commit_after>
// define before any includes
#define BOOST_SPIRIT_THREADSAFE
#include <dirent.h>
#include <syslog.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cassert>
#include <strings.h>
#include <algorithm>
#include <exception>
#include <fstream>
#include <iostream>
#include <tuple>
#include <boost/program_options.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include "proj.hpp"
#include "path-mapper.h"
#include "git-revision.h"
#define VERSION "0.0.0"
namespace argv {
// argv parser for --zoom=z1-z2
namespace zoom {
struct pair_t {
public:
uint32_t z1, z2;
};
void validate(boost::any& v,
const std::vector<std::string>& values,
pair_t*, int)
{
namespace po = boost::program_options;
static boost::regex r("(\\d+)(-|,)(\\d+)");
// Make sure no previous assignment to 'v' was made.
po::validators::check_first_occurrence(v);
// Extract the first string from 'values'. If there is more than
// one string, it's an error, and exception will be thrown.
const std::string& s = po::validators::get_single_string(values);
// Do regex match and convert the interesting part to
// int.
boost::smatch match;
if (regex_match(s, match, r)) {
v = boost::any(pair_t{ boost::lexical_cast<uint32_t>(match[1]), boost::lexical_cast<uint32_t>(match[3]) });
} else {
throw po::validation_error(po::validation_error::invalid_option_value);
}
}
}
// ... and for --bbox=x1,y1,x2,y2
namespace bbox {
struct box_t {
public:
double x1, y1, x2, y2;
};
void validate(boost::any& v,
const std::vector<std::string>& values,
box_t*, int)
{
namespace po = boost::program_options;
// Make sure no previous assignment to 'v' was made.
po::validators::check_first_occurrence(v);
// Extract the first string from 'values'. If there is more than
// one string, it's an error, and exception will be thrown.
const std::string& s = po::validators::get_single_string(values);
try {
std::vector<std::string> tokens;
boost::split(tokens, s, boost::is_any_of(","));
// boost::char_separator<char> sep(",");
// boost::tokenizer< boost::char_separator<char> > tok(s, sep);
// auto it = tok.begin();
double x1 = boost::lexical_cast<double>(tokens[0]);
double y1 = boost::lexical_cast<double>(tokens[1]);
double x2 = boost::lexical_cast<double>(tokens[2]);
double y2 = boost::lexical_cast<double>(tokens[3]);
v = boost::any(box_t { x1, y1, x2, y2 });
} catch (...) {
throw po::validation_error(po::validation_error::invalid_option_value);
}
}
}
}
/*
yield-tile-urls -p base-url [-z z1-z2] [-b x1,y1,x2,y2]
generates URLs for tiles bounded by the box (x1, y1)-(x2, y2) for zoom levels in [z1, z2], prefixed by base-url.
Options:
-p,--prefix base-url: a URL (or, can be a local path), to which paths for tiles are appended
-z,--zoom z1-z2: zoom levels in [0, ..., 20] to generate URLs
+ values less/greater than 0/20 are fit to 0/20 resp.
+ defaults to 0-16
-b,--bbox x1,y1,x2,y2: (x1, y1) and (x2, y2) are two pairs of lon/lat
+ the pairs define the bounding box of URLs
+ defaults to (-180, 90)-(180, -90), i.e. the entire planet
-s,--suffix (png|jpg|...)
+ suffix of the URLs
-v,--version
-h,--help
*/
int main(int ac, char** av) {
try {
std::string config;
std::string base;
std::string suffix;
argv::zoom::pair_t zoom_levels;
argv::bbox::box_t bbox;
bool emit_physical = false; // If true, print in the physical form: /base/z/nnn/nnn/nnn/nnn/nnn.png
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description desc(
"yield-tile-urls -p base-url [-z z1-z2] [-b x1,y1,x2,y2]\n"
"generates URLs for tiles bounded by the box (x1, y1)-(x2, y2) for zoom levels in [z1, z2], prefixed by base-url.\n\n"
"Options"
);
desc.add_options()
("help,h", "Prints help messages")
("version,v", "Prints version info.")
("prefix,p", po::value<std::string>(&base)->value_name("base-url")->required(), "Specifies the URL (or, can be a local path) to which tile-paths are appended")
("physical,P", "Emits tile-paths in the physical form: base/z/nnn/nnn/nnn/nnn/nnn.png")
("suffix,s", po::value<std::string>(&suffix)->value_name("suffix")->default_value("png"), "Specifies the suffix of the URLs")
("zoom,z",
po::value<argv::zoom::pair_t>(&zoom_levels)->value_name("z1-z2")->default_value(argv::zoom::pair_t{0, 16}, "0-16"),
"Specifies zoom levels to generate URLs, between 0-20\n"
" + values less/greater than 0/20 are fit to 0/20 resp.\n"
" + defaults to 0-16")
("bbox,b",
po::value<argv::bbox::box_t>(&bbox)->value_name("x1,y1,x2,y2")->default_value(argv::bbox::box_t{-180, 90, 180, -90}, "-180,90,180,-90"),
"Specifies the bounding box of URLs in lon/lat\n"
" + defaults to (-180,90)-(180,-90), i.e. the entire planet.")
; // add_options();
if (ac <= 1) {
// No options are given.
// Just print the usage w.o. error messages.
std::cerr << desc;
return 0;
}
po::variables_map vm;
try {
po::store(po::command_line_parser(ac, av).options(desc).run(), vm); // throws on error
// --help
if ( vm.count("help") ) {
std::cerr << desc;
return 0;
}
if ( vm.count("version") ) {
std::cout << (
VERSION " (commit: " GIT_REVISION ")"
) << std::endl;
return 0;
}
if ( vm.count("physical") ) {
emit_physical = true;
}
po::notify(vm); // throws on error, so do after help in case
// there are any problems
} catch(po::required_option& e) {
std::cerr << desc << std::endl;
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
return -1;
} catch(po::error& e) {
std::cerr << desc << std::endl;
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
return -1;
}
#define CHECK_RANGE(val, v1, v2) if (val < v1 || val > v2) { \
std::cerr << "Error: " << (#val) << " = " << (val) << " is out of the range, must be in [" << (v1) << ", " << (v2) << "]" << std::endl; \
return -1; \
}
// Ensure zoom levels are in the valid range
uint32_t z1 = zoom_levels.z1, z2 = zoom_levels.z2;
CHECK_RANGE(z1, 0, 20)
CHECK_RANGE(z2, 0, 20)
if (z1 > z2) {
std::swap(z1, z2);
}
// and so are bbox coordinates...
// Mercator projection limits the lat value to this, cf. http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#X_and_Y
constexpr double LAT_LIMIT = 85.0511;
double x1 = bbox.x1,
y1 = bbox.y1,
x2 = bbox.x2,
y2 = bbox.y2;
CHECK_RANGE(x1, -180.0, 180.0)
CHECK_RANGE(x2, -180.0, 180.0)
// The magic number 85.0511 is quite counter-intuitive, let us accept any deg. as inputs and then fit them below
CHECK_RANGE(y1, -90.0, 90.0)
CHECK_RANGE(y2, -90.0, 90.0)
// Ensure values are in ascening order.
if (x1 > x2) {
std::swap(x1, x2);
}
// The y-axis of the Spherical Mercator spans north-to-south, hence smaller lat values (southern points) are mapped to larger tile IDs.
// To assure the output to be in ascending order, we force y1 >= y2 (not y1 <= y2.)
if (y1 < y2) {
std::swap(y1, y2);
}
// Tweak lat/lon values so that they fit in their "actual" range.
// To be strict, the range of lon. values is [-180, 180), so exact 180.0 should be "shifted just a little"
x1 = std::min(x1, 180.0 - 0.0000001);
x2 = std::min(x2, 180.0 - 0.0000001);
// and lat. values are limited to +-85.0511 rather than 90.0, as explained.
y1 = std::max(-LAT_LIMIT, std::min(y1, LAT_LIMIT));
y2 = std::max(-LAT_LIMIT, std::min(y2, LAT_LIMIT));
// Trim the trailing '/' if any.
char* prefix = const_cast<char*>(base.c_str());
if (prefix[base.length()-1] == '/') {
prefix[base.length()-1] = '\0';
}
// Emit!
uint32_t tx_left, ty_top, tx_right, ty_bottom;
if (emit_physical) {
char* tile_path = (char*)alloca(base.length() + 28);
strcpy(tile_path, prefix);
char* tp_head = tile_path + strlen(prefix);
*tp_head = '/';
tp_head++;
boost::algorithm::to_lower(suffix);
TILE_SUFFIX ts = (suffix == "png") ? PNG : JPG;
for (uint32_t z = (uint32_t)z1; z <= (uint32_t)z2; ++z) {
lonlat_to_tile(x1, y1, z, tx_left, ty_top);
lonlat_to_tile(x2, y2, z, tx_right, ty_bottom);
for (uint32_t y = ty_top; y <= ty_bottom; ++y) {
for (uint32_t x = tx_left; x <= tx_right; ++x) {
to_physical_path(tp_head, z, x, y, ts);
puts(tile_path);
}
}
}
} else {
for (uint32_t z = (uint32_t)z1; z <= (uint32_t)z2; ++z) {
lonlat_to_tile(x1, y1, z, tx_left, ty_top);
lonlat_to_tile(x2, y2, z, tx_right, ty_bottom);
for (uint32_t y = ty_top; y <= ty_bottom; ++y) {
for (uint32_t x = tx_left; x <= tx_right; ++x) {
printf("%s/%d/%d/%d.%s\n", prefix, z, x, y, suffix.c_str());
}
}
}
}
} catch(std::exception& e) {
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return -1;
}
return 0;
}<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Manasij Mukherjee <manasij7479@gmail.com>
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Path.h"
#include "clang/Sema/Sema.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/AST.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/AutoloadCallback.h"
#include "cling/Interpreter/Transaction.h"
using namespace clang;
namespace cling {
void AutoloadCallback::report(clang::SourceLocation l,std::string name,std::string header) {
Sema& sema= m_Interpreter->getSema();
unsigned id
= sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning,
"Note: '%0' can be found in %1");
/* unsigned idn //TODO: To be enabled after we have a way to get the full path
= sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note,
"Type : %0 , Full Path: %1")*/;
sema.Diags.Report(l, id) << name << header;
}
bool AutoloadCallback::LookupObject (TagDecl *t) {
if (t->hasAttr<AnnotateAttr>())
report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation());
return false;
}
class DefaultArgVisitor: public RecursiveASTVisitor<DefaultArgVisitor> {
private:
bool m_IsStoringState;
AutoloadCallback::FwdDeclsMap* m_Map;
clang::Preprocessor* m_PP;
private:
void InsertIntoAutoloadingState (Decl* decl, std::string annotation) {
assert(annotation != "" && "Empty annotation!");
assert(m_PP);
const FileEntry* FE = 0;
SourceLocation fileNameLoc;
bool isAngled = false;
const DirectoryLookup* LookupFrom = 0;
const DirectoryLookup* CurDir = 0;
FE = m_PP->LookupFile(fileNameLoc, annotation, isAngled, LookupFrom,
CurDir, /*SearchPath*/0, /*RelativePath*/ 0,
/*suggestedModule*/0, /*SkipCache*/false,
/*OpenFile*/ false, /*CacheFail*/ false);
assert(FE && "Must have a valid FileEntry");
if (m_Map->find(FE) == m_Map->end())
(*m_Map)[FE] = std::vector<Decl*>();
(*m_Map)[FE].push_back(decl);
}
public:
DefaultArgVisitor() : m_IsStoringState(false), m_Map(0) {}
void RemoveDefaultArgsOf(Decl* D) {
//D = D->getMostRecentDecl();
TraverseDecl(D);
//while ((D = D->getPreviousDecl()))
// TraverseDecl(D);
}
void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map,
Preprocessor& PP) {
m_IsStoringState = true;
m_Map = ↦
m_PP = &PP;
TraverseDecl(D);
m_PP = 0;
m_Map = 0;
m_IsStoringState = false;
}
bool shouldVisitTemplateInstantiations() { return true; }
bool TraverseTemplateTypeParmDecl(TemplateTypeParmDecl* D) {
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool VisitDecl(Decl* D) {
if (!m_IsStoringState)
return true;
if (!D->hasAttr<AnnotateAttr>())
return false;
AnnotateAttr* attr = D->getAttr<AnnotateAttr>();
if (!attr)
return true;
switch (D->getKind()) {
default:
InsertIntoAutoloadingState(D, attr->getAnnotation());
break;
case Decl::Enum:
// EnumDecls have extra information 2 chars after the filename used
// for extra fixups.
InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2));
break;
}
return true;
}
bool TraverseTemplateDecl(TemplateDecl* D) {
if (!D->getTemplatedDecl()->hasAttr<AnnotateAttr>())
return true;
for(auto P: D->getTemplateParameters()->asArray())
TraverseDecl(P);
return true;
}
bool TraverseNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) {
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool TraverseParmVarDecl(ParmVarDecl* D) {
if (m_IsStoringState)
return true;
if (D->hasDefaultArg())
D->setDefaultArg(nullptr);
return true;
}
};
void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc,
const clang::Token &IncludeTok,
llvm::StringRef FileName,
bool IsAngled,
clang::CharSourceRange FilenameRange,
const clang::FileEntry *File,
llvm::StringRef SearchPath,
llvm::StringRef RelativePath,
const clang::Module *Imported) {
assert(File && "Must have a valid File");
auto found = m_Map.find(File);
if (found == m_Map.end())
return; // nothing to do, file not referred in any annotation
DefaultArgVisitor defaultArgsCleaner;
for (auto D : found->second) {
defaultArgsCleaner.RemoveDefaultArgsOf(D);
}
// Don't need to keep track of cleaned up decls from file.
m_Map.erase(found);
}
AutoloadCallback::AutoloadCallback(Interpreter* interp) :
InterpreterCallbacks(interp,true,false,true), m_Interpreter(interp){
//#ifdef _POSIX_C_SOURCE
// //Workaround for differnt expansion of macros to typedefs
// m_Interpreter->parse("#include <sys/types.h>");
//#endif
}
AutoloadCallback::~AutoloadCallback() {
}
void AutoloadCallback::TransactionCommitted(const Transaction &T) {
if (T.decls_begin() == T.decls_end())
return;
if (T.decls_begin()->m_DGR.isNull())
return;
if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) {
DefaultArgVisitor defaultArgsStateCollector;
Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
I != E; ++I) {
Transaction::DelayCallInfo DCI = *I;
// if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl)
// continue;
if (DCI.m_DGR.isNull())
continue;
for (DeclGroupRef::iterator J = DCI.m_DGR.begin(),
JE = DCI.m_DGR.end(); J != JE; ++J) {
defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP);
}
}
}
}
} //end namespace cling
<commit_msg>Do not abort the in-depth visitation.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Manasij Mukherjee <manasij7479@gmail.com>
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Path.h"
#include "clang/Sema/Sema.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/AST.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/AutoloadCallback.h"
#include "cling/Interpreter/Transaction.h"
using namespace clang;
namespace cling {
void AutoloadCallback::report(clang::SourceLocation l,std::string name,std::string header) {
Sema& sema= m_Interpreter->getSema();
unsigned id
= sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning,
"Note: '%0' can be found in %1");
/* unsigned idn //TODO: To be enabled after we have a way to get the full path
= sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note,
"Type : %0 , Full Path: %1")*/;
sema.Diags.Report(l, id) << name << header;
}
bool AutoloadCallback::LookupObject (TagDecl *t) {
if (t->hasAttr<AnnotateAttr>())
report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation());
return false;
}
class DefaultArgVisitor: public RecursiveASTVisitor<DefaultArgVisitor> {
private:
bool m_IsStoringState;
AutoloadCallback::FwdDeclsMap* m_Map;
clang::Preprocessor* m_PP;
private:
void InsertIntoAutoloadingState (Decl* decl, std::string annotation) {
assert(annotation != "" && "Empty annotation!");
assert(m_PP);
const FileEntry* FE = 0;
SourceLocation fileNameLoc;
bool isAngled = false;
const DirectoryLookup* LookupFrom = 0;
const DirectoryLookup* CurDir = 0;
FE = m_PP->LookupFile(fileNameLoc, annotation, isAngled, LookupFrom,
CurDir, /*SearchPath*/0, /*RelativePath*/ 0,
/*suggestedModule*/0, /*SkipCache*/false,
/*OpenFile*/ false, /*CacheFail*/ false);
assert(FE && "Must have a valid FileEntry");
if (m_Map->find(FE) == m_Map->end())
(*m_Map)[FE] = std::vector<Decl*>();
(*m_Map)[FE].push_back(decl);
}
public:
DefaultArgVisitor() : m_IsStoringState(false), m_Map(0) {}
void RemoveDefaultArgsOf(Decl* D) {
//D = D->getMostRecentDecl();
TraverseDecl(D);
//while ((D = D->getPreviousDecl()))
// TraverseDecl(D);
}
void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map,
Preprocessor& PP) {
m_IsStoringState = true;
m_Map = ↦
m_PP = &PP;
TraverseDecl(D);
m_PP = 0;
m_Map = 0;
m_IsStoringState = false;
}
bool shouldVisitTemplateInstantiations() { return true; }
bool TraverseTemplateTypeParmDecl(TemplateTypeParmDecl* D) {
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool VisitDecl(Decl* D) {
if (!m_IsStoringState)
return true;
if (!D->hasAttr<AnnotateAttr>())
return true;
AnnotateAttr* attr = D->getAttr<AnnotateAttr>();
if (!attr)
return true;
switch (D->getKind()) {
default:
InsertIntoAutoloadingState(D, attr->getAnnotation());
break;
case Decl::Enum:
// EnumDecls have extra information 2 chars after the filename used
// for extra fixups.
InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2));
break;
}
return true;
}
bool TraverseTemplateDecl(TemplateDecl* D) {
if (!D->getTemplatedDecl()->hasAttr<AnnotateAttr>())
return true;
for(auto P: D->getTemplateParameters()->asArray())
TraverseDecl(P);
return true;
}
bool TraverseNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) {
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool TraverseParmVarDecl(ParmVarDecl* D) {
if (m_IsStoringState)
return true;
if (D->hasDefaultArg())
D->setDefaultArg(nullptr);
return true;
}
};
void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc,
const clang::Token &IncludeTok,
llvm::StringRef FileName,
bool IsAngled,
clang::CharSourceRange FilenameRange,
const clang::FileEntry *File,
llvm::StringRef SearchPath,
llvm::StringRef RelativePath,
const clang::Module *Imported) {
assert(File && "Must have a valid File");
auto found = m_Map.find(File);
if (found == m_Map.end())
return; // nothing to do, file not referred in any annotation
DefaultArgVisitor defaultArgsCleaner;
for (auto D : found->second) {
defaultArgsCleaner.RemoveDefaultArgsOf(D);
}
// Don't need to keep track of cleaned up decls from file.
m_Map.erase(found);
}
AutoloadCallback::AutoloadCallback(Interpreter* interp) :
InterpreterCallbacks(interp,true,false,true), m_Interpreter(interp){
//#ifdef _POSIX_C_SOURCE
// //Workaround for differnt expansion of macros to typedefs
// m_Interpreter->parse("#include <sys/types.h>");
//#endif
}
AutoloadCallback::~AutoloadCallback() {
}
void AutoloadCallback::TransactionCommitted(const Transaction &T) {
if (T.decls_begin() == T.decls_end())
return;
if (T.decls_begin()->m_DGR.isNull())
return;
if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) {
DefaultArgVisitor defaultArgsStateCollector;
Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
I != E; ++I) {
Transaction::DelayCallInfo DCI = *I;
// if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl)
// continue;
if (DCI.m_DGR.isNull())
continue;
for (DeclGroupRef::iterator J = DCI.m_DGR.begin(),
JE = DCI.m_DGR.end(); J != JE; ++J) {
defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP);
}
}
}
}
} //end namespace cling
<|endoftext|>
|
<commit_before>#include <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <tuple>
#include <vector>
#include <openssl/sha.h>
#include <ecdsa/base58.h>
#include <ecdsa/key.h>
#include "args.h"
#include "btcaddr.h"
#include "btcwif.h"
#define BUFF_SIZE 1024
/**
* Show help document.
*
* @param args The argument manager
*/
void ShowHelp(const Args &args) {
std::cout << "BTCAddr(ess)Gen(erator)" << std::endl
<< " An easy to use Bitcoin Address offline generator."
<< std::endl
<< std::endl;
std::cout << "Usage:" << std::endl;
std::cout << " ./btcaddrgen [arguments...]" << std::endl << std::endl;
std::cout << "Arguments:" << std::endl;
std::cout << args.GetArgsHelpString() << std::endl;
}
std::tuple<std::vector<uint8_t>, bool> HashFile(const std::string &path) {
std::vector<uint8_t> md;
std::ifstream input(path, std::ios::binary);
if (!input.is_open()) {
std::cerr << "Cannot open file " << path << std::endl;
return std::make_tuple(md, false);
}
// Hash file contents
SHA512_CTX ctx;
SHA512_Init(&ctx);
// Reading...
char buff[BUFF_SIZE];
while (!input.eof()) {
input.read(buff, BUFF_SIZE);
size_t buff_size = input.gcount();
SHA512_Update(&ctx, buff, buff_size);
}
// Get md buffer.
md.resize(SHA512_DIGEST_LENGTH);
SHA512_Final(md.data(), &ctx);
return std::make_tuple(md, true);
}
std::tuple<std::vector<uint8_t>, bool> Signing(std::shared_ptr<ecdsa::Key> pkey,
const std::string &path) {
std::vector<uint8_t> signature;
std::vector<uint8_t> md;
bool succ;
std::tie(md, succ) = HashFile(path);
if (!succ) {
return std::make_tuple(signature, false);
}
std::tie(signature, succ) = pkey->Sign(md);
if (!succ) {
std::cerr << "Cannot signing file!" << std::endl;
return std::make_tuple(signature, false);
}
return std::make_tuple(signature, true);
}
bool Verifying(const ecdsa::PubKey &pub_key, const std::string &path,
const std::vector<uint8_t> &signature) {
std::vector<uint8_t> md;
bool succ;
std::tie(md, succ) = HashFile(path);
if (succ) {
return pub_key.Verify(md, signature);
}
return false;
}
std::string BinaryToHexString(const unsigned char *bin_data, size_t size) {
std::stringstream ss_hex;
for (unsigned int i = size - 1; i > 0; --i) {
ss_hex << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<int>(bin_data[i]);
}
return ss_hex.str();
}
void ShowKeyInfo(std::shared_ptr<ecdsa::Key> pkey, unsigned char prefix_char) {
auto pub_key = pkey->CreatePubKey();
unsigned char hash160[20];
auto addr = btc::Address::FromPublicKey(pub_key.get_pub_key_data(),
prefix_char, hash160);
std::cout << "Address: " << addr.ToString() << std::endl;
std::cout << "Hash160: " << BinaryToHexString(hash160, 20) << std::endl;
std::cout << "Public key: " << base58::EncodeBase58(pkey->get_pub_key_data())
<< std::endl;
std::cout << "Private key: "
<< base58::EncodeBase58(pkey->get_priv_key_data()) << std::endl;
std::cout << "Private key(WIF): "
<< btc::wif::PrivateKeyToWif(pkey->get_priv_key_data())
<< std::endl;
}
bool ImportFromHexString(const std::string &hex_str,
std::vector<uint8_t> &out_data) {
int len = hex_str.size();
if (len % 2 != 0) {
return false;
}
int size = len / 2;
out_data.resize(size);
for (int i = size; i > 0; --i) {
std::string hex1 = hex_str.substr(i * 2, 2);
std::stringstream hex_ss;
int val;
hex_ss << std::hex << hex1;
hex_ss >> val;
out_data[i] = val;
}
return true;
}
/// Main program.
int main(int argc, const char *argv[]) {
try {
Args args(argc, argv);
if (args.is_help()) {
ShowHelp(args);
return 0;
}
if (args.is_generate_new_key()) {
ShowKeyInfo(std::make_shared<ecdsa::Key>(), args.get_prefix_char());
return 0;
}
// Import key.
std::shared_ptr<ecdsa::Key> pkey;
std::string priv_key_b58 = args.get_import_priv_key();
if (!priv_key_b58.empty()) {
std::vector<uint8_t> priv_key;
// Checking WIF format.
if (btc::wif::VerifyWifString(priv_key_b58)) {
// Decoding private key in WIF format.
priv_key = btc::wif::WifToPrivateKey(priv_key_b58);
} else {
// Decoding private key in plain base58 data.
bool succ;
if (args.is_hex()) {
succ = ImportFromHexString(priv_key_b58, priv_key);
} else {
succ = base58::DecodeBase58(priv_key_b58.c_str(), priv_key);
}
if (!succ) {
std::cerr << "Failed to decode base58!" << std::endl;
return 1;
}
}
pkey = std::make_shared<ecdsa::Key>(priv_key);
ShowKeyInfo(pkey, args.get_prefix_char());
}
// Signing file?
if (!args.get_signing_file().empty()) {
if (pkey == nullptr) {
pkey = std::make_shared<ecdsa::Key>();
ShowKeyInfo(pkey, args.get_prefix_char());
}
std::vector<uint8_t> signature;
bool succ;
std::tie(signature, succ) = Signing(pkey, args.get_signing_file());
if (succ) {
std::string signature_b58 = base58::EncodeBase58(signature);
std::cout << "Signature: " << signature_b58 << std::endl;
return 0;
}
return 1;
}
// Verifying
if (!args.get_import_pub_key().empty() &&
!args.get_verifying_file().empty() && !args.get_signature().empty()) {
// Verifying
std::vector<uint8_t> pub_key_data;
bool succ;
if (args.is_hex()) {
succ = ImportFromHexString(args.get_import_pub_key(), pub_key_data);
} else {
succ = base58::DecodeBase58(args.get_import_pub_key(), pub_key_data);
}
if (!succ) {
std::cerr << "Cannot decode public key from base58 string."
<< std::endl;
return 1;
}
std::vector<uint8_t> signature;
if (args.is_hex()) {
succ = ImportFromHexString(args.get_signature(), signature);
} else {
succ = base58::DecodeBase58(args.get_signature(), signature);
}
if (!succ) {
std::cerr << "Cannot decode signature from base58 string." << std::endl;
return 1;
}
ecdsa::PubKey pub_key(pub_key_data);
succ = Verifying(pub_key, args.get_verifying_file(), signature);
if (succ) {
std::cout << "Verified OK." << std::endl;
return 0;
}
return 1;
}
if (priv_key_b58.empty()) {
std::cerr << "No argument, -h to show help." << std::endl;
}
return 1;
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
<commit_msg>Fix order bug of export binary to hex string.<commit_after>#include <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <tuple>
#include <vector>
#include <openssl/sha.h>
#include <ecdsa/base58.h>
#include <ecdsa/key.h>
#include "args.h"
#include "btcaddr.h"
#include "btcwif.h"
#define BUFF_SIZE 1024
/**
* Show help document.
*
* @param args The argument manager
*/
void ShowHelp(const Args &args) {
std::cout << "BTCAddr(ess)Gen(erator)" << std::endl
<< " An easy to use Bitcoin Address offline generator."
<< std::endl
<< std::endl;
std::cout << "Usage:" << std::endl;
std::cout << " ./btcaddrgen [arguments...]" << std::endl << std::endl;
std::cout << "Arguments:" << std::endl;
std::cout << args.GetArgsHelpString() << std::endl;
}
std::tuple<std::vector<uint8_t>, bool> HashFile(const std::string &path) {
std::vector<uint8_t> md;
std::ifstream input(path, std::ios::binary);
if (!input.is_open()) {
std::cerr << "Cannot open file " << path << std::endl;
return std::make_tuple(md, false);
}
// Hash file contents
SHA512_CTX ctx;
SHA512_Init(&ctx);
// Reading...
char buff[BUFF_SIZE];
while (!input.eof()) {
input.read(buff, BUFF_SIZE);
size_t buff_size = input.gcount();
SHA512_Update(&ctx, buff, buff_size);
}
// Get md buffer.
md.resize(SHA512_DIGEST_LENGTH);
SHA512_Final(md.data(), &ctx);
return std::make_tuple(md, true);
}
std::tuple<std::vector<uint8_t>, bool> Signing(std::shared_ptr<ecdsa::Key> pkey,
const std::string &path) {
std::vector<uint8_t> signature;
std::vector<uint8_t> md;
bool succ;
std::tie(md, succ) = HashFile(path);
if (!succ) {
return std::make_tuple(signature, false);
}
std::tie(signature, succ) = pkey->Sign(md);
if (!succ) {
std::cerr << "Cannot signing file!" << std::endl;
return std::make_tuple(signature, false);
}
return std::make_tuple(signature, true);
}
bool Verifying(const ecdsa::PubKey &pub_key, const std::string &path,
const std::vector<uint8_t> &signature) {
std::vector<uint8_t> md;
bool succ;
std::tie(md, succ) = HashFile(path);
if (succ) {
return pub_key.Verify(md, signature);
}
return false;
}
std::string BinaryToHexString(const unsigned char *bin_data, size_t size) {
std::stringstream ss_hex;
for (int i = size - 1; i >= 0; --i) {
ss_hex << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<int>(bin_data[i]);
}
return ss_hex.str();
}
void ShowKeyInfo(std::shared_ptr<ecdsa::Key> pkey, unsigned char prefix_char) {
auto pub_key = pkey->CreatePubKey();
unsigned char hash160[20];
auto addr = btc::Address::FromPublicKey(pub_key.get_pub_key_data(),
prefix_char, hash160);
std::cout << "Address: " << addr.ToString() << std::endl;
std::cout << "Hash160: " << BinaryToHexString(hash160, 20) << std::endl;
std::cout << "Public key: " << base58::EncodeBase58(pkey->get_pub_key_data())
<< std::endl;
std::cout << "Private key: "
<< base58::EncodeBase58(pkey->get_priv_key_data()) << std::endl;
std::cout << "Private key(WIF): "
<< btc::wif::PrivateKeyToWif(pkey->get_priv_key_data())
<< std::endl;
std::cout << "Private key(HEX): "
<< BinaryToHexString(pkey->get_priv_key_data().data(),
pkey->get_priv_key_data().size())
<< std::endl;
}
bool ImportFromHexString(const std::string &hex_str,
std::vector<uint8_t> &out_data) {
int len = hex_str.size();
if (len % 2 != 0) {
return false;
}
int size = len / 2;
out_data.resize(size);
for (int i = 0; i < size; ++i) {
std::string hex1 = hex_str.substr(i * 2, 2);
std::stringstream hex_ss;
int val;
hex_ss << std::hex << hex1;
hex_ss >> val;
out_data[size - i - 1] = val;
}
return true;
}
/// Main program.
int main(int argc, const char *argv[]) {
try {
Args args(argc, argv);
if (args.is_help()) {
ShowHelp(args);
return 0;
}
if (args.is_generate_new_key()) {
ShowKeyInfo(std::make_shared<ecdsa::Key>(), args.get_prefix_char());
return 0;
}
// Import key.
std::shared_ptr<ecdsa::Key> pkey;
std::string priv_key_b58 = args.get_import_priv_key();
if (!priv_key_b58.empty()) {
std::vector<uint8_t> priv_key;
// Checking WIF format.
if (btc::wif::VerifyWifString(priv_key_b58)) {
// Decoding private key in WIF format.
priv_key = btc::wif::WifToPrivateKey(priv_key_b58);
} else {
// Decoding private key in plain base58 data.
bool succ;
if (args.is_hex()) {
succ = ImportFromHexString(priv_key_b58, priv_key);
} else {
succ = base58::DecodeBase58(priv_key_b58.c_str(), priv_key);
}
if (!succ) {
std::cerr << "Failed to decode base58!" << std::endl;
return 1;
}
}
pkey = std::make_shared<ecdsa::Key>(priv_key);
ShowKeyInfo(pkey, args.get_prefix_char());
}
// Signing file?
if (!args.get_signing_file().empty()) {
if (pkey == nullptr) {
pkey = std::make_shared<ecdsa::Key>();
ShowKeyInfo(pkey, args.get_prefix_char());
}
std::vector<uint8_t> signature;
bool succ;
std::tie(signature, succ) = Signing(pkey, args.get_signing_file());
if (succ) {
std::string signature_b58 = base58::EncodeBase58(signature);
std::cout << "Signature: " << signature_b58 << std::endl;
return 0;
}
return 1;
}
// Verifying
if (!args.get_import_pub_key().empty() &&
!args.get_verifying_file().empty() && !args.get_signature().empty()) {
// Verifying
std::vector<uint8_t> pub_key_data;
bool succ;
if (args.is_hex()) {
succ = ImportFromHexString(args.get_import_pub_key(), pub_key_data);
} else {
succ = base58::DecodeBase58(args.get_import_pub_key(), pub_key_data);
}
if (!succ) {
std::cerr << "Cannot decode public key from base58 string."
<< std::endl;
return 1;
}
std::vector<uint8_t> signature;
if (args.is_hex()) {
succ = ImportFromHexString(args.get_signature(), signature);
} else {
succ = base58::DecodeBase58(args.get_signature(), signature);
}
if (!succ) {
std::cerr << "Cannot decode signature from base58 string." << std::endl;
return 1;
}
ecdsa::PubKey pub_key(pub_key_data);
succ = Verifying(pub_key, args.get_verifying_file(), signature);
if (succ) {
std::cout << "Verified OK." << std::endl;
return 0;
}
return 1;
}
if (priv_key_b58.empty()) {
std::cerr << "No argument, -h to show help." << std::endl;
}
return 1;
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "ExecutionContext.h"
#include "cling/Interpreter/StoredValueRef.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/DynamicLibrary.h"
using namespace cling;
namespace {
class JITtedFunctionCollector : public llvm::JITEventListener {
private:
llvm::SmallVector<llvm::Function*, 24> m_functions;
llvm::ExecutionEngine *m_engine;
public:
JITtedFunctionCollector(): m_functions(), m_engine(0) { }
virtual ~JITtedFunctionCollector() { }
virtual void NotifyFunctionEmitted(const llvm::Function& F, void *, size_t,
const JITEventListener::EmittedFunctionDetails&) {
m_functions.push_back(const_cast<llvm::Function *>(&F));
}
virtual void NotifyFreeingMachineCode(void* /*OldPtr*/) {}
void UnregisterFunctionMapping(llvm::ExecutionEngine&);
};
}
void JITtedFunctionCollector::UnregisterFunctionMapping(
llvm::ExecutionEngine &engine)
{
for (llvm::SmallVectorImpl<llvm::Function *>::reverse_iterator
it = m_functions.rbegin(), et = m_functions.rend();
it != et; ++it) {
llvm::Function *ff = *it;
engine.freeMachineCodeForFunction(ff);
engine.updateGlobalMapping(ff, 0);
}
m_functions.clear();
}
std::set<std::string> ExecutionContext::m_unresolvedSymbols;
std::vector<ExecutionContext::LazyFunctionCreatorFunc_t>
ExecutionContext::m_lazyFuncCreator;
bool ExecutionContext::m_LazyFuncCreatorEnabled = true;
ExecutionContext::ExecutionContext():
m_engine(0),
m_RunningStaticInits(false),
m_CxaAtExitRemapped(false)
{
}
void
ExecutionContext::InitializeBuilder(llvm::Module* m)
{
//
// Create an execution engine to use.
//
// Note: Engine takes ownership of the module.
assert(m && "Module cannot be null");
llvm::EngineBuilder builder(m);
builder.setOptLevel(llvm::CodeGenOpt::Less);
std::string errMsg;
builder.setErrorStr(&errMsg);
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setAllocateGVsWithCode(false);
m_engine = builder.create();
assert(m_engine && "Cannot initialize builder without module!");
//m_engine->addModule(m); // Note: The engine takes ownership of the module.
// install lazy function
m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators);
}
ExecutionContext::~ExecutionContext()
{
}
void unresolvedSymbol()
{
// throw exception?
llvm::errs() << "ExecutionContext: calling unresolved symbol (should never happen)!\n";
}
void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name)
{
// Not found in the map, add the symbol in the list of unresolved symbols
if (m_unresolvedSymbols.insert(mangled_name).second) {
llvm::errs() << "ExecutionContext: use of undefined symbol '"
<< mangled_name << "'!\n";
}
// Avoid "ISO C++ forbids casting between pointer-to-function and
// pointer-to-object":
return (void*)reinterpret_cast<size_t>(unresolvedSymbol);
}
void*
ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name)
{
if (!m_LazyFuncCreatorEnabled)
return 0;
for (std::vector<LazyFunctionCreatorFunc_t>::iterator it
= m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();
it != et; ++it) {
void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);
if (ret) return ret;
}
return HandleMissingFunction(mangled_name);
}
void
ExecutionContext::executeFunction(llvm::StringRef funcname,
const clang::ASTContext& Ctx,
clang::QualType retType,
StoredValueRef* returnValue)
{
// Call a function without arguments, or with an SRet argument, see SRet below
if (!m_CxaAtExitRemapped) {
// Rewire atexit:
llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit");
llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit");
if (atExit && clingAtExit) {
void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);
assert(clingAtExitAddr && "cannot find cling_cxa_atexit");
m_engine->updateGlobalMapping(atExit, clingAtExitAddr);
m_CxaAtExitRemapped = true;
}
}
// We don't care whether something was unresolved before.
m_unresolvedSymbols.clear();
llvm::Function* f = m_engine->FindFunctionNamed(funcname.data());
if (!f) {
llvm::errs() << "ExecutionContext::executeFunction: could not find function named " << funcname << '\n';
return;
}
JITtedFunctionCollector listener;
// register the listener
m_engine->RegisterJITEventListener(&listener);
m_engine->getPointerToFunction(f);
// check if there is any unresolved symbol in the list
if (!m_unresolvedSymbols.empty()) {
for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),
e = m_unresolvedSymbols.end(); i != e; ++i) {
llvm::errs() << "ExecutionContext::executeFunction: symbol \'" << *i << "\' unresolved!\n";
llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());
assert(ff && "cannot find function to free");
m_engine->updateGlobalMapping(ff, 0);
m_engine->freeMachineCodeForFunction(ff);
}
m_unresolvedSymbols.clear();
// cleanup functions
listener.UnregisterFunctionMapping(*m_engine);
m_engine->UnregisterJITEventListener(&listener);
return;
}
// cleanup list and unregister our listener
m_engine->UnregisterJITEventListener(&listener);
std::vector<llvm::GenericValue> args;
bool wantReturn = (returnValue);
StoredValueRef aggregateRet;
if (f->hasStructRetAttr()) {
// Function expects to receive the storage for the returned aggregate as
// first argument. Allocate returnValue:
aggregateRet = StoredValueRef::allocate(Ctx, retType);
if (returnValue) {
*returnValue = aggregateRet;
} else {
returnValue = &aggregateRet;
}
args.push_back(returnValue->get().value);
// will get set as arg0, must not assign.
wantReturn = false;
}
if (wantReturn) {
llvm::GenericValue gvRet = m_engine->runFunction(f, args);
// rescue the ret value (which might be aggregate) from the stack
*returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType));
} else {
m_engine->runFunction(f, args);
}
m_engine->freeMachineCodeForFunction(f);
}
void
ExecutionContext::runStaticInitializersOnce(llvm::Module* m) {
assert(m && "Module must not be null");
if (!m_engine)
InitializeBuilder(m);
assert(m_engine && "Code generation did not create an engine!");
if (!m_RunningStaticInits) {
m_RunningStaticInits = true;
llvm::GlobalVariable* gctors
= m->getGlobalVariable("llvm.global_ctors", true);
if (gctors) {
m_engine->runStaticConstructorsDestructors(false);
gctors->eraseFromParent();
}
m_RunningStaticInits = false;
}
}
void
ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) {
assert(m && "Module must not be null");
assert(m_engine && "Code generation did not create an engine!");
llvm::GlobalVariable* gdtors
= m->getGlobalVariable("llvm.global_dtors", true);
if (gdtors) {
m_engine->runStaticConstructorsDestructors(true);
}
}
int
ExecutionContext::verifyModule(llvm::Module* m)
{
//
// Verify generated module.
//
bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction);
if (mod_has_errs) {
return 1;
}
return 0;
}
void
ExecutionContext::printModule(llvm::Module* m)
{
//
// Print module LLVM code in human-readable form.
//
llvm::PassManager PM;
PM.add(llvm::createPrintModulePass(&llvm::outs()));
PM.run(*m);
}
void
ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)
{
m_lazyFuncCreator.push_back(fp);
}
bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) {
void* actualAddress
= llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);
if (actualAddress)
return false;
llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress);
return true;
}
void* ExecutionContext::getAddressOfGlobal(llvm::Module* m,
const char* symbolName,
bool* fromJIT /*=0*/) const {
// Return a symbol's address, and whether it was jitted.
void* address
= llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);
if (address) {
if (fromJIT) *fromJIT = false;
} else {
if (fromJIT) *fromJIT = true;
llvm::GlobalVariable* gvar
= m->getGlobalVariable(symbolName, true);
if (!gvar)
return 0;
address = m_engine->getPointerToGlobal(gvar);
}
return address;
}
<commit_msg>Give a chance to the eventual lazy function creators to do their job. (Thanks Philippe)<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "ExecutionContext.h"
#include "cling/Interpreter/StoredValueRef.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/DynamicLibrary.h"
using namespace cling;
namespace {
class JITtedFunctionCollector : public llvm::JITEventListener {
private:
llvm::SmallVector<llvm::Function*, 24> m_functions;
llvm::ExecutionEngine *m_engine;
public:
JITtedFunctionCollector(): m_functions(), m_engine(0) { }
virtual ~JITtedFunctionCollector() { }
virtual void NotifyFunctionEmitted(const llvm::Function& F, void *, size_t,
const JITEventListener::EmittedFunctionDetails&) {
m_functions.push_back(const_cast<llvm::Function *>(&F));
}
virtual void NotifyFreeingMachineCode(void* /*OldPtr*/) {}
void UnregisterFunctionMapping(llvm::ExecutionEngine&);
};
}
void JITtedFunctionCollector::UnregisterFunctionMapping(
llvm::ExecutionEngine &engine)
{
for (llvm::SmallVectorImpl<llvm::Function *>::reverse_iterator
it = m_functions.rbegin(), et = m_functions.rend();
it != et; ++it) {
llvm::Function *ff = *it;
engine.freeMachineCodeForFunction(ff);
engine.updateGlobalMapping(ff, 0);
}
m_functions.clear();
}
std::set<std::string> ExecutionContext::m_unresolvedSymbols;
std::vector<ExecutionContext::LazyFunctionCreatorFunc_t>
ExecutionContext::m_lazyFuncCreator;
bool ExecutionContext::m_LazyFuncCreatorEnabled = true;
ExecutionContext::ExecutionContext():
m_engine(0),
m_RunningStaticInits(false),
m_CxaAtExitRemapped(false)
{
}
void
ExecutionContext::InitializeBuilder(llvm::Module* m)
{
//
// Create an execution engine to use.
//
// Note: Engine takes ownership of the module.
assert(m && "Module cannot be null");
llvm::EngineBuilder builder(m);
builder.setOptLevel(llvm::CodeGenOpt::Less);
std::string errMsg;
builder.setErrorStr(&errMsg);
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setAllocateGVsWithCode(false);
m_engine = builder.create();
assert(m_engine && "Cannot initialize builder without module!");
//m_engine->addModule(m); // Note: The engine takes ownership of the module.
// install lazy function
m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators);
}
ExecutionContext::~ExecutionContext()
{
}
void unresolvedSymbol()
{
// throw exception?
llvm::errs() << "ExecutionContext: calling unresolved symbol (should never happen)!\n";
}
void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name)
{
// Not found in the map, add the symbol in the list of unresolved symbols
if (m_unresolvedSymbols.insert(mangled_name).second) {
llvm::errs() << "ExecutionContext: use of undefined symbol '"
<< mangled_name << "'!\n";
}
// Avoid "ISO C++ forbids casting between pointer-to-function and
// pointer-to-object":
return (void*)reinterpret_cast<size_t>(unresolvedSymbol);
}
void*
ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name)
{
for (std::vector<LazyFunctionCreatorFunc_t>::iterator it
= m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();
it != et; ++it) {
void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);
if (ret)
return ret;
}
if (!m_LazyFuncCreatorEnabled)
return 0;
return HandleMissingFunction(mangled_name);
}
void
ExecutionContext::executeFunction(llvm::StringRef funcname,
const clang::ASTContext& Ctx,
clang::QualType retType,
StoredValueRef* returnValue)
{
// Call a function without arguments, or with an SRet argument, see SRet below
if (!m_CxaAtExitRemapped) {
// Rewire atexit:
llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit");
llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit");
if (atExit && clingAtExit) {
void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);
assert(clingAtExitAddr && "cannot find cling_cxa_atexit");
m_engine->updateGlobalMapping(atExit, clingAtExitAddr);
m_CxaAtExitRemapped = true;
}
}
// We don't care whether something was unresolved before.
m_unresolvedSymbols.clear();
llvm::Function* f = m_engine->FindFunctionNamed(funcname.data());
if (!f) {
llvm::errs() << "ExecutionContext::executeFunction: could not find function named " << funcname << '\n';
return;
}
JITtedFunctionCollector listener;
// register the listener
m_engine->RegisterJITEventListener(&listener);
m_engine->getPointerToFunction(f);
// check if there is any unresolved symbol in the list
if (!m_unresolvedSymbols.empty()) {
for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),
e = m_unresolvedSymbols.end(); i != e; ++i) {
llvm::errs() << "ExecutionContext::executeFunction: symbol \'" << *i << "\' unresolved!\n";
llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());
assert(ff && "cannot find function to free");
m_engine->updateGlobalMapping(ff, 0);
m_engine->freeMachineCodeForFunction(ff);
}
m_unresolvedSymbols.clear();
// cleanup functions
listener.UnregisterFunctionMapping(*m_engine);
m_engine->UnregisterJITEventListener(&listener);
return;
}
// cleanup list and unregister our listener
m_engine->UnregisterJITEventListener(&listener);
std::vector<llvm::GenericValue> args;
bool wantReturn = (returnValue);
StoredValueRef aggregateRet;
if (f->hasStructRetAttr()) {
// Function expects to receive the storage for the returned aggregate as
// first argument. Allocate returnValue:
aggregateRet = StoredValueRef::allocate(Ctx, retType);
if (returnValue) {
*returnValue = aggregateRet;
} else {
returnValue = &aggregateRet;
}
args.push_back(returnValue->get().value);
// will get set as arg0, must not assign.
wantReturn = false;
}
if (wantReturn) {
llvm::GenericValue gvRet = m_engine->runFunction(f, args);
// rescue the ret value (which might be aggregate) from the stack
*returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType));
} else {
m_engine->runFunction(f, args);
}
m_engine->freeMachineCodeForFunction(f);
}
void
ExecutionContext::runStaticInitializersOnce(llvm::Module* m) {
assert(m && "Module must not be null");
if (!m_engine)
InitializeBuilder(m);
assert(m_engine && "Code generation did not create an engine!");
if (!m_RunningStaticInits) {
m_RunningStaticInits = true;
llvm::GlobalVariable* gctors
= m->getGlobalVariable("llvm.global_ctors", true);
if (gctors) {
m_engine->runStaticConstructorsDestructors(false);
gctors->eraseFromParent();
}
m_RunningStaticInits = false;
}
}
void
ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) {
assert(m && "Module must not be null");
assert(m_engine && "Code generation did not create an engine!");
llvm::GlobalVariable* gdtors
= m->getGlobalVariable("llvm.global_dtors", true);
if (gdtors) {
m_engine->runStaticConstructorsDestructors(true);
}
}
int
ExecutionContext::verifyModule(llvm::Module* m)
{
//
// Verify generated module.
//
bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction);
if (mod_has_errs) {
return 1;
}
return 0;
}
void
ExecutionContext::printModule(llvm::Module* m)
{
//
// Print module LLVM code in human-readable form.
//
llvm::PassManager PM;
PM.add(llvm::createPrintModulePass(&llvm::outs()));
PM.run(*m);
}
void
ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)
{
m_lazyFuncCreator.push_back(fp);
}
bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) {
void* actualAddress
= llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);
if (actualAddress)
return false;
llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress);
return true;
}
void* ExecutionContext::getAddressOfGlobal(llvm::Module* m,
const char* symbolName,
bool* fromJIT /*=0*/) const {
// Return a symbol's address, and whether it was jitted.
void* address
= llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);
if (address) {
if (fromJIT) *fromJIT = false;
} else {
if (fromJIT) *fromJIT = true;
llvm::GlobalVariable* gvar
= m->getGlobalVariable(symbolName, true);
if (!gvar)
return 0;
address = m_engine->getPointerToGlobal(gvar);
}
return address;
}
<|endoftext|>
|
<commit_before>#ifdef TEST
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <unistd.h>
#include <cstdlib>
#include "test_helpers/bart_test_helper.h"
#endif
//#include "aqdata/aq_base.h"
int main(int argc, char* argv[]) {
#ifdef TEST
// Parse optional arguments
int c;
while ((c = getopt (argc, argv, "r")) != -1)
switch(c) {
case 'r':
btest::GlobalBartTestHelper().ReInit(true, "test_data/");
}
// // Testing
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
#else
return 0;
#endif
}
<commit_msg>added function call without argc and argv to non-testing setion of main<commit_after>#ifdef TEST
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <unistd.h>
#include <cstdlib>
#include "test_helpers/bart_test_helper.h"
#endif
//#include "aqdata/aq_base.h"
#ifdef TEST
int main(int argc, char* argv[]) {
// Parse optional arguments
int c;
while ((c = getopt (argc, argv, "r")) != -1)
switch(c) {
case 'r':
btest::GlobalBartTestHelper().ReInit(true, "test_data/");
}
// // Testing
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
#else
int main() {
return 0;
#endif
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdlib>
#include <istream>
#include <string>
#include <vector>
#include "../include/sha512.h"
int menu1(std::vector<std::string>&, int&);
void menuSelectAlias(std::vector<std::string>&, int&, int&, int&);
void menuExit(int&);
void menuMakeItem(std::vector<std::string>&, int&, int&, int&, std::vector<std::vector<std::string> >&,
std::vector<std::vector<std::string> >&, std::vector<std::vector<int > >&);
int main(int argc, char** argv)
{
std::vector<std::vector<std::string> > itemNameVector;
std::vector<std::vector<std::string> > itemDescriptionVector;
std::vector<std::vector<int> > itemQuantityVector;
std::string itemNameStorage;
std::string itemDescriptionStorage;
int itemQuantityStorage(0);
int aliasIndex(-1);
int answer(1);
int indexChoice(0);
int& indexReference = aliasIndex;
int* indexPointer = &aliasIndex;
std::vector<std::string> userAliasVector;
std::vector<std::vector<int> > itemStorageVector;
do
{
if(answer == 1)
{
answer = menu1(userAliasVector, aliasIndex);
}
if(answer == 3)
{
menuMakeItem(userAliasVector, answer, aliasIndex, indexChoice, itemNameVector, itemDescriptionVector,
itemQuantityVector);
}
if(answer == 2)
{
menuSelectAlias(userAliasVector, answer, aliasIndex, indexChoice);
}
if(answer == 0)
{
menuExit(answer);
}
/*if(*indexPointer > -1)
{
menuMakeItem(userAliasVector, answer, aliasIndex, indexChoice);
}*/
std::cout << *indexPointer;
} while(answer != 0);
return 0;
}
int menu1(std::vector<std::string>& aliasVector, int& isAlias)
{
int answer(0);
long long checks(0);
std::string stringAnswer;
std::string storeName;
if(aliasVector.size() == 0)
{
std::cout << " 1. add an alias " << std::endl;
std::cout << " 0. exit " << std::endl;
std::cin >> answer;
}
if(aliasVector.size() > 0 && isAlias == -1)
{
std::cout << " 1. add alias " << std::endl;
std::cout << " 2. select active alias " << std::endl;
std::cout << " 0. exit " << std::endl;
std::cin >> answer;
}
if(aliasVector.size() > 0 && isAlias > -1)
{
std::cout << " 1. add alias " << std::endl;
std::cout << " 2. select active alias " << std::endl;
std::cout << " 3. make an item on behalf of " << aliasVector[isAlias] << std::endl;
std::cout << " 0. exit " << std::endl;
std::cin >> answer;
}
if(answer == 1)
{
std::cout << " enter the name of the alias " << std::endl;
std::cin >> storeName;
for(long long i=0; i<(long)aliasVector.size(); ++i)
{
if(storeName != aliasVector.at(i)) { checks++; }
}
if(checks != aliasVector.size())
{
std::cout << " this alias has already been made " << std::endl;
}
else
aliasVector.push_back(storeName);
}
return answer;
}
void menuSelectAlias(std::vector<std::string>& aliasVector, int& answer, int& aliasIndex, int& indexchoice)
{
long long checks;
std::string stringAnswer;
std::string storeName;
long long choice(0);
int is(0);
if(answer == 2)
{
std::cout << " select an alias " << std::endl;
std::cout << " 1. search " << std::endl;
std::cout << " 2. list each alias " << std::endl;
std::cout << " 3. make new alias " << std::endl;
std::cout << " 4. view active alias " << std::endl;
std::cout << " 5. go home " << std::endl;
std::cout << " 91. set alias index " << std::endl;
std::cout << " 0. exit program " << std::endl;
std::cin >> answer;
if(answer == 1)
{
std::cout << " search for a specific name " << std::endl;
std::cin >> stringAnswer;
for(long long i = 0; i<(long)aliasVector.size(); ++i)
{
answer = 22;
if(aliasVector.at(i) == stringAnswer)
{
std::cout << std::endl;
std::cout << " alias found " << std::endl;
std::cout << i << " " << aliasVector.at(i) << std::endl;
answer = 2;
i = aliasVector.size();
}
}
if(answer == 22)
{
std::cout << " alias not found " << std::endl;
answer = 2;
}
}
if(answer == 2)
{
for(long long i=0; i<(long)aliasVector.size(); ++i)
{
std::cout << i << " " << aliasVector.at(i) << std::endl;
}
}
if(answer == 3)
{
std::cout << " enter the name of the alias " << std::endl;
std::cin >> storeName;
for(long long i=0; i<(long)aliasVector.size(); ++i)
{
if(storeName != aliasVector.at(i)) { checks++; }
}
if(checks != aliasVector.size())
{
std::cout << " this alias has already been made " << std::endl;
answer = 2;
}
else
{
aliasVector.push_back(storeName);
std::cout << " " << storeName << " you are ackowledged " << std::endl;
}
}
if(answer == 5)
{
answer = 1;
}
if(answer == 91)
{
do
{
std::cout << " enter the number corresponding with the desired alias " << std::endl;
std::cin >> choice;
if(choice > aliasVector.size() - 1)
{
std::cout << " your choice of " << choice << " is out of range " << std::endl;
is = 1;
}
else
{
std::cout << " you have chosen " << aliasVector.at(choice) << " is this correct" << std::endl;
std::cout << " type 'yes' or 'no' " << std::endl;
std::cin >> stringAnswer;
if(stringAnswer == "yes") aliasIndex = choice;
else is = 1;
}
} while(is == 10);
answer = 1;
}
}
}
void menuMakeItem(std::vector<std::string>& aliasVector, int& answer, int& aliasIndex, int& indexchoice,
std::vector<std::vector<std::string> >& pushItemName, std::vector<std::vector<std::string> >& pushItemDescription,
std::vector<std::vector<int> >& pushItemQuantity)
{
std::string itemName;
std::string itemDescription;
std::string textAnswer;
long long itemQuantity(0);
if(answer == 3)
{
std::cout << " " << aliasVector.at(aliasIndex) << " welcome, you've arrived at Make Item " << std::endl;
std::cout << " 1. start item creation " << std::endl;
std::cout << " 2. item " << std::endl;
std::cout << " 3. store this item " << std::endl;
std::cout << " 5. go home " << std::endl;
std::cin >> answer;
if(answer == 1)
{
std::cout << " we will need some standard input " << std::endl;
std::cout << " please enter the name of your item " << std::endl;
std::cin >> itemName;
std::cout << " we have your item name, now we need how many quantities of that item you have " << std::endl;
std::cin >> itemQuantity;
std::cout << " great, now place a brief 100 letter description about your software " << std::endl;
std::getline(std::cin,itemDescription);
std::getline(std::cin,itemDescription);
do
{
std::cout << " your item is " << itemName << " with a quantity of " << itemQuantity << " " << std::endl;
std::cout << " described as: " << itemDescription << std::endl;
std::cout << " if this is correct type 'yes' of not type 'no'" <<std::endl;
std::cin >> textAnswer;
if(textAnswer == "yes")
{
std::vector<std::string> stringNameStorage;
stringNameStorage.push_back(aliasVector.at(aliasIndex));
stringNameStorage.push_back(itemName);
pushItemName.push_back(stringNameStorage);
std::vector<std::string> stringDescriptionStorage;
stringDescriptionStorage.push_back(aliasVector.at(aliasIndex));
stringDescriptionStorage.push_back(itemDescription);
pushItemDescription.push_back(stringDescriptionStorage);
std::vector<int> intQuantityStorage;
intQuantityStorage.push_back(aliasIndex);
intQuantityStorage.push_back(itemQuantity);
pushItemQuantity.push_back(intQuantityStorage);
//store in a row aliasVector + itemName
//then push that into the itemNameVector
//pushItemQuantity[aliasIndex].push_back(itemQuantity);
//pushItemDescription[aliasIndex].push_back(itemDescription);
}
} while(textAnswer != "yes");
}
if(answer == 2)
{
for(long long i=0; i<(long)pushItemName.size(); ++i)
{
std::string storeActiveAlias = aliasVector.at(aliasIndex);
std::string storeItemNaming = pushItemName[i][0];
if(storeItemNaming == storeActiveAlias)
{
std::cout << pushItemName[i][1] << std::endl;
}
}
answer = 3;
}
if(answer == 5)
{
answer = 1;
}
}
}
void menuExit(int& answer)
{
if(answer == 0)
{
std::cout << " you are about to exit, type 0 to confirm type 1 to cancel exiting " << std::endl;
std::cin >> answer;
if(answer == 0)
{
std::cout << " have a nice day " << std::endl;
}
else
answer = 1;
}
}
<commit_msg>add starCoin<commit_after>#include <iostream>
#include <cstdlib>
#include <istream>
#include <string>
#include <vector>
#include "../include/sha512.h"
int menu1(std::vector<std::string>&, int&, std::vector<std::vector<int > >&);
void menuSelectAlias(std::vector<std::string>&, int&, int&, int&);
void menuExit(int&);
void menuMakeItem(std::vector<std::string>&, int&, int&, int&, std::vector<std::vector<std::string> >&,
std::vector<std::vector<std::string> >&, std::vector<std::vector<int > >&);
void menuSendCoin(std::vector<std::string>&, std::vector<std::vector<int > >&, int&);
int main(int argc, char** argv)
{
std::vector<std::vector<int > > starCoin;
std::vector<std::vector<std::string> > itemNameVector;
std::vector<std::vector<std::string> > itemDescriptionVector;
std::vector<std::vector<int> > itemQuantityVector;
std::string itemNameStorage;
std::string itemDescriptionStorage;
int itemQuantityStorage(0);
int aliasIndex(-1);
int answer(1);
int indexChoice(0);
int& indexReference = aliasIndex;
int* indexPointer = &aliasIndex;
std::vector<std::string> userAliasVector;
std::vector<std::vector<int> > itemStorageVector;
do
{
if(answer == 1)
{
answer = menu1(userAliasVector, aliasIndex, starCoin);
}
if(answer == 3)
{
menuMakeItem(userAliasVector, answer, aliasIndex, indexChoice, itemNameVector, itemDescriptionVector,
itemQuantityVector);
}
if(answer == 2)
{
menuSelectAlias(userAliasVector, answer, aliasIndex, indexChoice);
}
if(answer == 0)
{
menuExit(answer);
}
/*if(*indexPointer > -1)
{
menuMakeItem(userAliasVector, answer, aliasIndex, indexChoice);
}*/
std::cout << *indexPointer;
} while(answer != 0);
return 0;
}
int menu1(std::vector<std::string>& aliasVector, int& isAlias, std::vector<std::vector<int > >& starCoins)
{
int answer(0);
long long checks(0);
std::string stringAnswer;
std::string storeName;
if(aliasVector.size() == 0)
{
std::cout << " 1. add an alias " << std::endl;
std::cout << " 0. exit " << std::endl;
std::cin >> answer;
}
if(aliasVector.size() > 0 && isAlias == -1)
{
std::cout << " 1. add alias " << std::endl;
std::cout << " 2. select active alias " << std::endl;
std::cout << " 0. exit " << std::endl;
std::cin >> answer;
}
if(aliasVector.size() > 0 && isAlias > -1)
{
std::cout << " 1. add alias " << std::endl;
std::cout << " 2. select active alias " << std::endl;
std::cout << " 3. make an item on behalf of " << aliasVector[isAlias] << std::endl;
std::cout << " 0. exit " << std::endl;
std::cin >> answer;
}
if(answer == 1)
{
std::cout << " enter the name of the alias " << std::endl;
std::cin >> storeName;
for(long long i=0; i<(long)aliasVector.size(); ++i)
{
if(storeName != aliasVector.at(i)) { checks++; }
}
if(checks != aliasVector.size())
{
std::cout << " this alias has already been made " << std::endl;
}
else
{
aliasVector.push_back(storeName);
std::vector<int> rowForCoins;
rowForCoins.push_back(aliasVector.size()-1);
rowForCoins.push_back(10000);
starCoins.push_back(rowForCoins);
}
}
return answer;
}
void menuSelectAlias(std::vector<std::string>& aliasVector, int& answer, int& aliasIndex, int& indexchoice)
{
long long checks;
std::string stringAnswer;
std::string storeName;
long long choice(0);
int is(0);
if(answer == 2)
{
std::cout << " select an alias " << std::endl;
std::cout << " 1. search " << std::endl;
std::cout << " 2. list each alias " << std::endl;
std::cout << " 3. make new alias " << std::endl;
if(aliasIndex > -1)
{
std::cout << " 4. view active alias " << std::endl;
}
std::cout << " 5. go home " << std::endl;
std::cout << " 91. set alias index " << std::endl;
std::cout << " 0. exit program " << std::endl;
std::cin >> answer;
if(answer == 1)
{
std::cout << " search for a specific name " << std::endl;
std::cin >> stringAnswer;
for(long long i = 0; i<(long)aliasVector.size(); ++i)
{
answer = 22;
if(aliasVector.at(i) == stringAnswer)
{
std::cout << std::endl;
std::cout << " alias found " << std::endl;
std::cout << i << " " << aliasVector.at(i) << std::endl;
answer = 2;
i = aliasVector.size();
}
}
if(answer == 22)
{
std::cout << " alias not found " << std::endl;
answer = 2;
}
}
if(answer == 2)
{
for(long long i=0; i<(long)aliasVector.size(); ++i)
{
std::cout << i << " " << aliasVector.at(i) << std::endl;
}
}
if(answer == 3)
{
std::cout << " enter the name of the alias " << std::endl;
std::cin >> storeName;
for(long long i=0; i<(long)aliasVector.size(); ++i)
{
if(storeName != aliasVector.at(i)) { checks++; }
}
if(checks != aliasVector.size())
{
std::cout << " this alias has already been made " << std::endl;
answer = 2;
}
else
{
aliasVector.push_back(storeName);
std::cout << " " << storeName << " you are ackowledged " << std::endl;
}
}
if(answer == 4)
{
std::cout << " selected alias is: " << aliasVector.at(aliasIndex) << std::endl;
answer = 1;
}
if(answer == 5)
{
answer = 1;
}
if(answer == 91)
{
do
{
std::cout << " enter the number corresponding with the desired alias " << std::endl;
std::cin >> choice;
if(choice > aliasVector.size() - 1)
{
std::cout << " your choice of " << choice << " is out of range " << std::endl;
is = 1;
}
else
{
std::cout << " you have chosen " << aliasVector.at(choice) << " is this correct" << std::endl;
std::cout << " type 'yes' or 'no' " << std::endl;
std::cin >> stringAnswer;
if(stringAnswer == "yes") aliasIndex = choice;
else is = 1;
}
} while(is == 10);
answer = 1;
}
}
}
void menuMakeItem(std::vector<std::string>& aliasVector, int& answer, int& aliasIndex, int& indexchoice,
std::vector<std::vector<std::string> >& pushItemName, std::vector<std::vector<std::string> >& pushItemDescription,
std::vector<std::vector<int> >& pushItemQuantity)
{
std::string itemName;
std::string itemDescription;
std::string textAnswer;
long long itemQuantity(0);
if(answer == 3)
{
std::cout << " " << aliasVector.at(aliasIndex) << " welcome, you've arrived at Make Item " << std::endl;
std::cout << " 1. start item creation " << std::endl;
std::cout << " 2. item " << std::endl;
std::cout << " 3. store this item " << std::endl;
std::cout << " 5. go home " << std::endl;
std::cin >> answer;
if(answer == 1)
{
std::cout << " we will need some standard input " << std::endl;
std::cout << " please enter the name of your item " << std::endl;
std::cin >> itemName;
std::cout << " we have your item name, now we need how many quantities of that item you have " << std::endl;
std::cin >> itemQuantity;
std::cout << " great, now place a brief 100 letter description about your software " << std::endl;
std::getline(std::cin,itemDescription);
std::getline(std::cin,itemDescription);
do
{
std::cout << " your item is " << itemName << " with a quantity of " << itemQuantity << " " << std::endl;
std::cout << " described as: " << itemDescription << std::endl;
std::cout << " if this is correct type 'yes' of not type 'no'" <<std::endl;
std::cin >> textAnswer;
if(textAnswer == "yes")
{
std::vector<std::string> stringNameStorage;
stringNameStorage.push_back(aliasVector.at(aliasIndex));
stringNameStorage.push_back(itemName);
pushItemName.push_back(stringNameStorage);
std::vector<std::string> stringDescriptionStorage;
stringDescriptionStorage.push_back(aliasVector.at(aliasIndex));
stringDescriptionStorage.push_back(itemDescription);
pushItemDescription.push_back(stringDescriptionStorage);
std::vector<int> intQuantityStorage;
intQuantityStorage.push_back(aliasIndex);
intQuantityStorage.push_back(itemQuantity);
pushItemQuantity.push_back(intQuantityStorage);
//store in a row aliasVector + itemName
//then push that into the itemNameVector
//pushItemQuantity[aliasIndex].push_back(itemQuantity);
//pushItemDescription[aliasIndex].push_back(itemDescription);
}
} while(textAnswer != "yes");
}
if(answer == 2)
{
for(long long i=0; i<(long)pushItemName.size(); ++i)
{
std::string storeActiveAlias = aliasVector.at(aliasIndex);
std::string storeItemNaming = pushItemName[i][0];
if(storeItemNaming == storeActiveAlias)
{
std::cout << std::endl;
std::cout << " :: Name: " << pushItemName[i][1] << " :: Quantity: " << pushItemQuantity[i][1] << std::endl;
}
}
answer = 3;
}
if(answer == 5)
{
answer = 1;
}
}
}
void menuSendCoin(std::vector<std::string>& aliasVector, std::vector<std::vector<int > >& starCoins, int& answer)
{
}
void menuExit(int& answer)
{
if(answer == 0)
{
std::cout << " you are about to exit, type 0 to confirm type 1 to cancel exiting " << std::endl;
std::cin >> answer;
if(answer == 0)
{
std::cout << " have a nice day " << std::endl;
}
else
answer = 1;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream> // std::cout, std::endl
#include <algorithm> // std::max(), std::set_intersection()
#include <iomanip> // std::setw()
#include <utility> // std::make_unique<T>(), std::forward<T>()
#include "components/command_line.hpp"
#include "utils.hpp"
enum {
/*
* Same order as they are initialized
* in main(). Perhaps we should have a
* getter funtion instead?
*
* These (or well, only main) are used in
* validate_arguments() to get the group of
* main arguments so that we can find if any of
* those are passed.
*
* I'm a bit unsure if it's worth the time to
* implement a better way to do this. This will work
* as long as they are in the same order as they are
* initialized in in main().
*/
main,
excl,
exact,
misc
};
enum { /* magic padding numbers */
padding_margin = 4,
desc_align_magic = 7
};
cliparser::cli_type cliparser::make(const string &&progname, const groups &&groups)
{
return std::make_unique<cliparser>(
"Usage: " + progname + " OPTION...", std::forward<decltype(groups)>(groups)
);
}
auto cliparser::values_to_str(const choices &values)
{
string retstring = "";
for (const auto &v : values)
retstring += v + (v != values.back() ? ", " : "");
return retstring;
}
void cliparser::usage() const
{
std::cout << synopsis_ << "\n\n";
size_t maxlen = 0;
/*
* Get the length of the longest string in the flag column
* which is used to align the description fields.
*/
for (const auto &group : valid_groups_) {
for (const auto &opt : group.options) {
size_t len = opt.flag_long.length() + opt.flag.length() +
opt.token.length() + padding_margin;
maxlen = std::max(len, maxlen);
}
}
/*
* Print each option group, its options, the options'
* descriptions, token and possible values for said token (if any).
*/
for (const auto &group : valid_groups_) {
std::cout << group.name << " arguments"
<< (group.synopsis.empty() ? ":" : " - " + group.synopsis + ":")
<< '\n';
for (const auto &opt : group.options) {
/* Padding between flags and description. */
size_t pad = maxlen - opt.flag_long.length() - opt.token.length();
std::cout << " " << opt.flag << ", " << opt.flag_long;
if (!opt.token.empty()) {
std::cout << ' ' << opt.token;
pad--;
}
/*
* Print the list with accepted values.
* This line is printed below the description.
*/
if (!opt.values.empty()) {
std::cout << std::setw(pad + opt.desc.length())
<< opt.desc << '\n';
pad += opt.flag_long.length() + opt.token.length() + desc_align_magic;
std::cout << string(pad, ' ') << opt.token << " is one of: "
<< values_to_str(opt.values);
} else {
std::cout << std::setw(pad + opt.desc.length()) << opt.desc;
}
std::cout << '\n';
}
std::cout << std::endl;
}
}
bool cliparser::has(const string &option) const
{
return passed_opts_.find(option) != passed_opts_.cend();
}
string cliparser::get(string opt) const
{
if (has(std::forward<string>(opt)))
return passed_opts_.find(opt)->second;
return "";
}
auto cliparser::is_short(const string_view &option, const string_view &opt_short)
{
return option.compare(0, opt_short.length(), opt_short) == 0;
}
auto cliparser::is_long(const string_view &option, const string_view &opt_long)
{
return option.compare(0, opt_long.length(), opt_long) == 0;
}
auto cliparser::is(const string_view &option, string opt_short, string opt_long)
{
return is_short(option, std::move(opt_short)) || is_long(option, std::move(opt_long));
}
void cliparser::process_arguments(const vector<string> &args)
{
for (size_t i = 0; i < args.size(); i++) {
const string_view &arg = args[i];
const string_view &next_arg = args.size() > i + 1 ? args[i + 1] : "";
parse(arg, next_arg);
}
}
void cliparser::validate_arguments() const
{
vector<string> passed_opts, required_opts;
for (const auto &opt : passed_opts_) {
/* We don't want the value, only the flag. */
passed_opts.emplace_back(opt.first);
}
for (const auto &opt : valid_groups_[main].options)
required_opts.emplace_back(opt.flag_long.substr(2));
/* Has any required arguments been passed? */
const bool req_match = utils::any_intersection(passed_opts, required_opts);
const bool ident_passed = std::find(passed_opts.cbegin(), passed_opts.cend(), "ident")
!= passed_opts.cend();
if (ident_passed && passed_opts.size() > 1)
throw argument_error("ident flag is exclusive and may not be passed with another flag");
if (!req_match && !passed_opts.empty())
throw argument_error("at least one main argument must be specified");
}
auto cliparser::check_value(const string_view &flag, const string_view &value, const choices &values)
{
if (value.empty())
throw value_error("missing value for " + string(flag.data()));
if (!values.empty() && std::find(values.cbegin(), values.cend(), value) == values.cend()) {
throw value_error(
"invalid value '" + string(value.data()) + "' for argument " + string(flag.data()) +
"; valid options are: " + values_to_str(values)
);
}
return value;
}
void cliparser::parse(const string_view &input, const string_view &input_next)
{
if (skipnext_) {
/* The next input is a value, which we've already used. */
skipnext_ = false;
return;
}
for (const auto &group : valid_groups_) {
for (const auto &opt : group.options) {
if (is(input, opt.flag, opt.flag_long)) {
if (opt.token.empty()) {
/* The option is only a flag. */
passed_opts_.emplace(opt.flag_long.substr(2), "");
} else {
/*
* The option should have an accompanied value.
* And may be that it must be an element in opt.values.
*/
const auto value = check_value(input, input_next, opt.values);
skipnext_ = (value == input_next);
passed_opts_.emplace(opt.flag_long.substr(2), value);
}
return;
}
}
}
if (input[0] == '-')
throw argument_error("unrecognized option " + string(input.data()));
throw argument_error("the bookwyrm takes no positional arguments");
}
<commit_msg>command_line: fix -d flag<commit_after>/*
* Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream> // std::cout, std::endl
#include <algorithm> // std::max(), std::set_intersection()
#include <iomanip> // std::setw()
#include <utility> // std::make_unique<T>(), std::forward<T>()
#include "components/command_line.hpp"
#include "utils.hpp"
enum {
/*
* Same order as they are initialized
* in main(). Perhaps we should have a
* getter funtion instead?
*
* These (or well, only main) are used in
* validate_arguments() to get the group of
* main arguments so that we can find if any of
* those are passed.
*
* I'm a bit unsure if it's worth the time to
* implement a better way to do this. This will work
* as long as they are in the same order as they are
* initialized in in main().
*/
main,
excl,
exact,
misc
};
enum { /* magic padding numbers */
padding_margin = 4,
desc_align_magic = 7
};
cliparser::cli_type cliparser::make(const string &&progname, const groups &&groups)
{
return std::make_unique<cliparser>(
"Usage: " + progname + " OPTION...", std::forward<decltype(groups)>(groups)
);
}
auto cliparser::values_to_str(const choices &values)
{
string retstring = "";
for (const auto &v : values)
retstring += v + (v != values.back() ? ", " : "");
return retstring;
}
void cliparser::usage() const
{
std::cout << synopsis_ << "\n\n";
size_t maxlen = 0;
/*
* Get the length of the longest string in the flag column
* which is used to align the description fields.
*/
for (const auto &group : valid_groups_) {
for (const auto &opt : group.options) {
size_t len = opt.flag_long.length() + opt.flag.length() +
opt.token.length() + padding_margin;
maxlen = std::max(len, maxlen);
}
}
/*
* Print each option group, its options, the options'
* descriptions, token and possible values for said token (if any).
*/
for (const auto &group : valid_groups_) {
std::cout << group.name << " arguments"
<< (group.synopsis.empty() ? ":" : " - " + group.synopsis + ":")
<< '\n';
for (const auto &opt : group.options) {
/* Padding between flags and description. */
size_t pad = maxlen - opt.flag_long.length() - opt.token.length();
std::cout << " " << opt.flag << ", " << opt.flag_long;
if (!opt.token.empty()) {
std::cout << ' ' << opt.token;
pad--;
}
/*
* Print the list with accepted values.
* This line is printed below the description.
*/
if (!opt.values.empty()) {
std::cout << std::setw(pad + opt.desc.length())
<< opt.desc << '\n';
pad += opt.flag_long.length() + opt.token.length() + desc_align_magic;
std::cout << string(pad, ' ') << opt.token << " is one of: "
<< values_to_str(opt.values);
} else {
std::cout << std::setw(pad + opt.desc.length()) << opt.desc;
}
std::cout << '\n';
}
std::cout << std::endl;
}
}
bool cliparser::has(const string &option) const
{
return passed_opts_.find(option) != passed_opts_.cend();
}
string cliparser::get(string opt) const
{
if (has(std::forward<string>(opt)))
return passed_opts_.find(opt)->second;
return "";
}
auto cliparser::is_short(const string_view &option, const string_view &opt_short)
{
return option.compare(0, opt_short.length(), opt_short) == 0;
}
auto cliparser::is_long(const string_view &option, const string_view &opt_long)
{
return option.compare(0, opt_long.length(), opt_long) == 0;
}
auto cliparser::is(const string_view &option, string opt_short, string opt_long)
{
return is_short(option, std::move(opt_short)) || is_long(option, std::move(opt_long));
}
void cliparser::process_arguments(const vector<string> &args)
{
for (size_t i = 0; i < args.size(); i++) {
const string_view &arg = args[i];
const string_view &next_arg = args.size() > i + 1 ? args[i + 1] : "";
parse(arg, next_arg);
}
}
void cliparser::validate_arguments() const
{
vector<string> passed_opts, required_opts;
for (const auto &opt : passed_opts_) {
/* We don't want the value, only the flag. */
passed_opts.emplace_back(opt.first);
}
for (const auto &opt : valid_groups_[main].options)
required_opts.emplace_back(opt.flag_long.substr(2));
/* Has any required arguments been passed? */
const bool req_match = utils::any_intersection(passed_opts, required_opts);
const bool ident_passed = std::find(passed_opts.cbegin(), passed_opts.cend(), "ident")
!= passed_opts.cend();
if (ident_passed) {
if (passed_opts.size() > 1)
throw argument_error("ident flag is exclusive and may not be passed with another flag");
} else if (!req_match && !passed_opts.empty()) {
throw argument_error("at least one main argument must be specified");
}
}
auto cliparser::check_value(const string_view &flag, const string_view &value, const choices &values)
{
if (value.empty())
throw value_error("missing value for " + string(flag.data()));
if (!values.empty() && std::find(values.cbegin(), values.cend(), value) == values.cend()) {
throw value_error(
"invalid value '" + string(value.data()) + "' for argument " + string(flag.data()) +
"; valid options are: " + values_to_str(values)
);
}
return value;
}
void cliparser::parse(const string_view &input, const string_view &input_next)
{
if (skipnext_) {
/* The next input is a value, which we've already used. */
skipnext_ = false;
return;
}
for (const auto &group : valid_groups_) {
for (const auto &opt : group.options) {
if (is(input, opt.flag, opt.flag_long)) {
if (opt.token.empty()) {
/* The option is only a flag. */
passed_opts_.emplace(opt.flag_long.substr(2), "");
} else {
/*
* The option should have an accompanied value.
* And may be that it must be an element in opt.values.
*/
const auto value = check_value(input, input_next, opt.values);
skipnext_ = (value == input_next);
passed_opts_.emplace(opt.flag_long.substr(2), value);
}
return;
}
}
}
if (input[0] == '-')
throw argument_error("unrecognized option " + string(input.data()));
throw argument_error("the bookwyrm takes no positional arguments");
}
<|endoftext|>
|
<commit_before>/* Copyright © 2001-2018, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "journey.h"
#include "type/stop_time.h"
using namespace navitia::routing;
Journey::Section::Section(const type::StopTime& in,
const DateTime in_dt,
const type::StopTime& out,
const DateTime out_dt)
: get_in_st(&in), get_in_dt(in_dt), get_out_st(&out), get_out_dt(out_dt) {}
bool Journey::Section::operator==(const Section& rhs) const {
return get_in_st->order() == rhs.get_in_st->order() && get_in_st->vehicle_journey == rhs.get_in_st->vehicle_journey
&& get_in_dt == rhs.get_in_dt && get_out_st->order() == rhs.get_out_st->order()
&& get_out_st->vehicle_journey == rhs.get_out_st->vehicle_journey && get_out_dt == rhs.get_out_dt;
}
bool Journey::is_pt() const {
return !sections.empty();
}
bool Journey::better_on_dt(const Journey& that,
bool request_clockwise,
const navitia::time_duration transfer_penalty) const {
// we consider that an extra transfer (hence a bigger sections.size() ) is worthwhile
// only if it reduces the arrival time by at least transfer_penalty
DateTime penalized_arrival = arrival_dt + transfer_penalty * sections.size();
DateTime that_penalized_arrival = that.arrival_dt + transfer_penalty * that.sections.size();
// Similary, we consider that an extra transfer (hence a bigger sections.size() ) is worthwhile
// only if it increases the departure time by at least transfer_penalty
DateTime penalized_departure = departure_dt - transfer_penalty * sections.size();
DateTime that_penalized_departure = that.departure_dt - transfer_penalty * that.sections.size();
if (request_clockwise) {
// if the (non-penalized) arrival times are the same, we compare the penalized departure times
if (arrival_dt != that.arrival_dt) {
return penalized_arrival <= that_penalized_arrival;
}
if (penalized_departure != that_penalized_departure) {
return penalized_departure >= that_penalized_departure;
}
} else {
if (departure_dt != that.departure_dt) {
return penalized_departure >= that_penalized_departure;
}
if (penalized_arrival != that_penalized_arrival) {
return penalized_arrival <= that_penalized_arrival;
}
}
return min_waiting_dur >= that.min_waiting_dur;
}
bool Journey::better_on_transfer(const Journey& that) const {
if (sections.size() != that.sections.size()) {
return sections.size() <= that.sections.size();
}
if (nb_vj_extentions != that.nb_vj_extentions) {
return nb_vj_extentions <= that.nb_vj_extentions;
}
return true;
}
bool Journey::better_on_sn(const Journey& that, const navitia::time_duration transfer_penalty) const {
// we consider that the transfer duration as well as the street network duration are
// walking duration
// we consider that an extra transfer (hence a bigger sections.size() ) is worthwhile
// only if it reduces the walking duration by at least transfer_penalty
return sn_dur + transfer_dur + transfer_penalty * sections.size()
<= that.sn_dur + that.transfer_dur + transfer_penalty * that.sections.size();
;
}
bool Journey::operator==(const Journey& rhs) const {
return departure_dt == rhs.departure_dt && arrival_dt == rhs.arrival_dt && sections == rhs.sections;
}
bool Journey::operator!=(const Journey& rhs) const {
return !(*this == rhs);
}
size_t SectionHash::operator()(const Journey::Section& s, size_t seed) const {
boost::hash_combine(seed, s.get_in_st->order().val);
boost::hash_combine(seed, s.get_in_st->vehicle_journey);
boost::hash_combine(seed, s.get_in_dt);
boost::hash_combine(seed, s.get_out_st->order().val);
boost::hash_combine(seed, s.get_out_st->vehicle_journey);
boost::hash_combine(seed, s.get_out_dt);
return seed;
}
size_t JourneyHash::operator()(const Journey& j) const {
size_t seed = 0;
SectionHash sect_hash;
for (const auto& s : j.sections) {
boost::hash_combine(seed, sect_hash(s, seed));
}
return seed;
}
<commit_msg>count stay_in as a transfer in the pareto front<commit_after>/* Copyright © 2001-2018, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "journey.h"
#include "type/stop_time.h"
using namespace navitia::routing;
Journey::Section::Section(const type::StopTime& in,
const DateTime in_dt,
const type::StopTime& out,
const DateTime out_dt)
: get_in_st(&in), get_in_dt(in_dt), get_out_st(&out), get_out_dt(out_dt) {}
bool Journey::Section::operator==(const Section& rhs) const {
return get_in_st->order() == rhs.get_in_st->order() && get_in_st->vehicle_journey == rhs.get_in_st->vehicle_journey
&& get_in_dt == rhs.get_in_dt && get_out_st->order() == rhs.get_out_st->order()
&& get_out_st->vehicle_journey == rhs.get_out_st->vehicle_journey && get_out_dt == rhs.get_out_dt;
}
bool Journey::is_pt() const {
return !sections.empty();
}
bool Journey::better_on_dt(const Journey& that,
bool request_clockwise,
const navitia::time_duration transfer_penalty) const {
const int nb_transfer = sections.size() + nb_vj_extentions;
const int that_nb_transfer = that.sections.size() + that.nb_vj_extentions;
// we consider that an extra transfer is worthwhile
// only if it reduces the arrival time by at least transfer_penalty
const DateTime penalized_arrival = arrival_dt + transfer_penalty * nb_transfer;
const DateTime that_penalized_arrival = that.arrival_dt + transfer_penalty * that_nb_transfer;
// Similary, we consider that an extra transfer (hence a bigger sections.size() ) is worthwhile
// only if it increases the departure time by at least transfer_penalty
const DateTime penalized_departure = departure_dt - transfer_penalty * nb_transfer;
const DateTime that_penalized_departure = that.departure_dt - transfer_penalty * that_nb_transfer;
if (request_clockwise) {
// if the (non-penalized) arrival times are the same, we compare the penalized departure times
if (arrival_dt != that.arrival_dt) {
return penalized_arrival <= that_penalized_arrival;
}
if (penalized_departure != that_penalized_departure) {
return penalized_departure >= that_penalized_departure;
}
} else {
if (departure_dt != that.departure_dt) {
return penalized_departure >= that_penalized_departure;
}
if (penalized_arrival != that_penalized_arrival) {
return penalized_arrival <= that_penalized_arrival;
}
}
return min_waiting_dur >= that.min_waiting_dur;
}
bool Journey::better_on_transfer(const Journey& that) const {
if (sections.size() != that.sections.size()) {
return sections.size() <= that.sections.size();
}
if (nb_vj_extentions != that.nb_vj_extentions) {
return nb_vj_extentions <= that.nb_vj_extentions;
}
return true;
}
bool Journey::better_on_sn(const Journey& that, const navitia::time_duration transfer_penalty) const {
const int nb_transfer = sections.size() + nb_vj_extentions;
const int that_nb_transfer = that.sections.size() + that.nb_vj_extentions;
// we consider that the transfer duration as well as the street network duration are
// walking duration
// we consider that an extra transfer is worthwhile
// only if it reduces the walking duration by at least transfer_penalty
return sn_dur + transfer_dur + transfer_penalty * nb_transfer
<= that.sn_dur + that.transfer_dur + transfer_penalty * that_nb_transfer;
;
}
bool Journey::operator==(const Journey& rhs) const {
return departure_dt == rhs.departure_dt && arrival_dt == rhs.arrival_dt && sections == rhs.sections;
}
bool Journey::operator!=(const Journey& rhs) const {
return !(*this == rhs);
}
size_t SectionHash::operator()(const Journey::Section& s, size_t seed) const {
boost::hash_combine(seed, s.get_in_st->order().val);
boost::hash_combine(seed, s.get_in_st->vehicle_journey);
boost::hash_combine(seed, s.get_in_dt);
boost::hash_combine(seed, s.get_out_st->order().val);
boost::hash_combine(seed, s.get_out_st->vehicle_journey);
boost::hash_combine(seed, s.get_out_dt);
return seed;
}
size_t JourneyHash::operator()(const Journey& j) const {
size_t seed = 0;
SectionHash sect_hash;
for (const auto& s : j.sections) {
boost::hash_combine(seed, sect_hash(s, seed));
}
return seed;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mremotethemedaemon.h"
#include "mremotethemedaemon_p.h"
#include "mthemedaemon.h"
#include "mdebug.h"
#include "mthemedaemonprotocol.h"
#include <QDir>
#include <QTime>
#ifndef Q_OS_WIN
# include <unistd.h>
#else
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
using namespace M::MThemeDaemonProtocol;
MRemoteThemeDaemon::MRemoteThemeDaemon(const QString &applicationName, int timeout) :
d_ptr(new MRemoteThemeDaemonPrivate)
{
Q_D(MRemoteThemeDaemon);
d->q_ptr = this;
d->sequenceCounter = 0;
d->stream.setVersion(QDataStream::Qt_4_6);
QObject::connect(&d->socket, SIGNAL(readyRead()), this, SLOT(connectionDataAvailable()));
// this blocking behavior could be removed
if (d->waitForServer(M::MThemeDaemonProtocol::ServerAddress, timeout)) {
d->stream.setDevice(&d->socket);
registerApplicationName(applicationName);
} else {
mWarning("MRemoteThemeDaemon") << "Failed to connect to theme daemon (IPC)";
}
}
void MRemoteThemeDaemon::registerApplicationName(const QString &applicationName)
{
Q_D(MRemoteThemeDaemon);
const quint64 seq = ++d->sequenceCounter;
d->stream << Packet(Packet::RequestRegistrationPacket, seq, new String(applicationName));
Packet reply = d->waitForPacket(seq);
if (reply.type() == Packet::ThemeChangedPacket) {
const ThemeChangeInfo* info = static_cast<const ThemeChangeInfo*>(reply.data());
d->themeInheritanceChain = info->themeInheritance;
d->themeLibraryNames = info->themeLibraryNames;
} else {
// TODO: print out warning, etc.
}
}
MRemoteThemeDaemon::~MRemoteThemeDaemon()
{
Q_D(MRemoteThemeDaemon);
if (connected()) {
d->socket.close();
}
delete d_ptr;
}
bool MRemoteThemeDaemon::connected() const
{
Q_D(const MRemoteThemeDaemon);
return d->socket.state() == QLocalSocket::ConnectedState;
}
void MRemoteThemeDaemon::addDirectoryToPixmapSearchList(const QString &directoryName,
M::RecursionMode recursive)
{
Q_D(MRemoteThemeDaemon);
d->stream << Packet(Packet::RequestNewPixmapDirectoryPacket, ++d->sequenceCounter,
new StringBool(directoryName, recursive == M::Recursive));
}
void MRemoteThemeDaemon::clearPixmapSearchList()
{
Q_D(MRemoteThemeDaemon);
d->stream << Packet(Packet::RequestClearPixmapDirectoriesPacket, ++d->sequenceCounter);
}
bool MRemoteThemeDaemonPrivate::waitForServer(const QString &serverAddress, int timeout)
{
QTime time;
time.start();
while (1) {
// try to connect
socket.connectToServer(serverAddress);
if (socket.state() == QLocalSocket::ConnectedState)
return true;
// check for timeout
if (timeout != -1) {
if (time.elapsed() >= timeout) {
return false;
}
}
// wait for a while
#ifndef Q_OS_WIN
sleep(1);
#else
Sleep(1000);
#endif
}
}
Packet MRemoteThemeDaemonPrivate::waitForPacket(quint64 sequenceNumber)
{
Q_Q(MRemoteThemeDaemon);
// send it immediately
socket.flush();
QObject::disconnect(&socket, SIGNAL(readyRead()), q, SLOT(connectionDataAvailable()));
// wait until we get a packet with type
while (socket.waitForReadyRead(-1)) {
while (socket.bytesAvailable()) {
// read one packet
const Packet packet = readOnePacket();
// check if it was the one we are waiting for
if (packet.sequenceNumber() == sequenceNumber) {
// read rest
QObject::connect(&socket, SIGNAL(readyRead()), q, SLOT(connectionDataAvailable()));
connectionDataAvailable();
return packet;
}
// if it was not the packet we're waiting for, lets process it
processOnePacket(packet);
}
}
mWarning("MRemoteThemeDaemon") << "waitForPacket: connection broken";
QObject::connect(&socket, SIGNAL(readyRead()), q, SLOT(connectionDataAvailable()));
return Packet();
}
quint64 MRemoteThemeDaemonPrivate::requestPixmap(const QString &imageId, const QSize &size)
{
const PixmapIdentifier id (imageId, size);
// check if we haven't yet asked for this pixmap
// if there's no ongoing request, we'll make one
const QHash<PixmapIdentifier, quint64>::const_iterator req = pixmapRequests.constFind(id);
quint64 sequenceNumber;
if (req != pixmapRequests.constEnd()) {
sequenceNumber = req.value();
mWarning("MRemoteThemeDaemon") << "requested pixmap which already exists in cache";
}
else {
sequenceNumber = ++sequenceCounter;
stream << Packet(Packet::RequestPixmapPacket, sequenceNumber, new PixmapIdentifier(id));
// remember sequence number of ongoing request
pixmapRequests.insert(id, sequenceNumber);
}
return sequenceNumber;
}
void MRemoteThemeDaemon::pixmapHandleSync(const QString &imageId, const QSize &size)
{
Q_D(MRemoteThemeDaemon);
const quint64 sequenceNumber = d->requestPixmap(imageId, size);
const Packet reply = d->waitForPacket(sequenceNumber);
d->processOnePacket(reply);
}
void MRemoteThemeDaemon::pixmapHandle(const QString &imageId, const QSize &size)
{
Q_D(MRemoteThemeDaemon);
d->requestPixmap(imageId, size);
}
void MRemoteThemeDaemon::releasePixmap(const QString &imageId, const QSize &size)
{
Q_D(MRemoteThemeDaemon);
PixmapIdentifier *const id = new PixmapIdentifier(imageId, size);
// If a request for this pixmap is still in the queue, forget about it
// so that subsequent calls to pixmapHandle() will issue a new request.
d->pixmapRequests.remove(*id);
d->stream << Packet(Packet::ReleasePixmapPacket, ++d->sequenceCounter,
id /*callee assumes ownership*/);
}
QString MRemoteThemeDaemon::currentTheme()
{
Q_D(MRemoteThemeDaemon);
QDir dir(d->themeInheritanceChain.at(0));
return dir.dirName();
}
QStringList MRemoteThemeDaemon::themeInheritanceChain()
{
Q_D(MRemoteThemeDaemon);
return d->themeInheritanceChain;
}
QStringList MRemoteThemeDaemon::themeLibraryNames()
{
Q_D(MRemoteThemeDaemon);
return d->themeLibraryNames;
}
bool MRemoteThemeDaemon::hasPendingRequests() const
{
Q_D(const MRemoteThemeDaemon);
return !d->pixmapRequests.isEmpty();
}
Packet MRemoteThemeDaemonPrivate::readOnePacket()
{
Packet packet;
stream >> packet;
return packet;
}
void MRemoteThemeDaemonPrivate::processOnePacket(const Packet &packet)
{
Q_Q(MRemoteThemeDaemon);
// process it according to packet type
switch (packet.type()) {
case Packet::PixmapUpdatedPacket:
pixmapUpdated(*static_cast<const PixmapHandle *>(packet.data()));
break;
case Packet::ThemeChangedPacket: {
const ThemeChangeInfo* info = static_cast<const ThemeChangeInfo*>(packet.data());
themeChanged(info->themeInheritance, info->themeLibraryNames);
stream << Packet(Packet::ThemeChangeAppliedPacket, packet.sequenceNumber());
} break;
case Packet::ThemeChangeCompletedPacket: {
emit q->themeChangeCompleted();
} break;
default:
mDebug("MRemoteThemeDaemon") << "Couldn't process packet of type" << packet.type();
break;
}
}
void MRemoteThemeDaemonPrivate::connectionDataAvailable()
{
while (socket.bytesAvailable()) {
processOnePacket(readOnePacket());
}
}
void MRemoteThemeDaemonPrivate::pixmapUpdated(const PixmapHandle &handle)
{
Q_Q(MRemoteThemeDaemon);
pixmapRequests.remove(handle.identifier);
// The pixmap may have been updated either in response to a request or
// due to a theme change. It may have gone already, if a release
// request was processed by the server in the meantime. The recipient
// of the signal must be able to handle such a situation gracefully.
emit q->pixmapChanged(handle.identifier.imageId, handle.identifier.size, handle.pixmapHandle);
}
void MRemoteThemeDaemonPrivate::themeChanged(const QStringList &themeInheritanceChain, const QStringList &themeLibraryNames)
{
Q_Q(MRemoteThemeDaemon);
this->themeInheritanceChain = themeInheritanceChain;
this->themeLibraryNames = themeLibraryNames;
emit q->themeChanged(themeInheritanceChain, themeLibraryNames);
}
#include "moc_mremotethemedaemon.cpp"
<commit_msg>Changes: block signals from socket while reading packet<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mremotethemedaemon.h"
#include "mremotethemedaemon_p.h"
#include "mthemedaemon.h"
#include "mdebug.h"
#include "mthemedaemonprotocol.h"
#include <QDir>
#include <QTime>
#ifndef Q_OS_WIN
# include <unistd.h>
#else
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
using namespace M::MThemeDaemonProtocol;
MRemoteThemeDaemon::MRemoteThemeDaemon(const QString &applicationName, int timeout) :
d_ptr(new MRemoteThemeDaemonPrivate)
{
Q_D(MRemoteThemeDaemon);
d->q_ptr = this;
d->sequenceCounter = 0;
d->stream.setVersion(QDataStream::Qt_4_6);
QObject::connect(&d->socket, SIGNAL(readyRead()), this, SLOT(connectionDataAvailable()));
// this blocking behavior could be removed
if (d->waitForServer(M::MThemeDaemonProtocol::ServerAddress, timeout)) {
d->stream.setDevice(&d->socket);
registerApplicationName(applicationName);
} else {
mWarning("MRemoteThemeDaemon") << "Failed to connect to theme daemon (IPC)";
}
}
void MRemoteThemeDaemon::registerApplicationName(const QString &applicationName)
{
Q_D(MRemoteThemeDaemon);
const quint64 seq = ++d->sequenceCounter;
d->stream << Packet(Packet::RequestRegistrationPacket, seq, new String(applicationName));
Packet reply = d->waitForPacket(seq);
if (reply.type() == Packet::ThemeChangedPacket) {
const ThemeChangeInfo* info = static_cast<const ThemeChangeInfo*>(reply.data());
d->themeInheritanceChain = info->themeInheritance;
d->themeLibraryNames = info->themeLibraryNames;
} else {
// TODO: print out warning, etc.
}
}
MRemoteThemeDaemon::~MRemoteThemeDaemon()
{
Q_D(MRemoteThemeDaemon);
if (connected()) {
d->socket.close();
}
delete d_ptr;
}
bool MRemoteThemeDaemon::connected() const
{
Q_D(const MRemoteThemeDaemon);
return d->socket.state() == QLocalSocket::ConnectedState;
}
void MRemoteThemeDaemon::addDirectoryToPixmapSearchList(const QString &directoryName,
M::RecursionMode recursive)
{
Q_D(MRemoteThemeDaemon);
d->stream << Packet(Packet::RequestNewPixmapDirectoryPacket, ++d->sequenceCounter,
new StringBool(directoryName, recursive == M::Recursive));
}
void MRemoteThemeDaemon::clearPixmapSearchList()
{
Q_D(MRemoteThemeDaemon);
d->stream << Packet(Packet::RequestClearPixmapDirectoriesPacket, ++d->sequenceCounter);
}
bool MRemoteThemeDaemonPrivate::waitForServer(const QString &serverAddress, int timeout)
{
QTime time;
time.start();
while (1) {
// try to connect
socket.connectToServer(serverAddress);
if (socket.state() == QLocalSocket::ConnectedState)
return true;
// check for timeout
if (timeout != -1) {
if (time.elapsed() >= timeout) {
return false;
}
}
// wait for a while
#ifndef Q_OS_WIN
sleep(1);
#else
Sleep(1000);
#endif
}
}
Packet MRemoteThemeDaemonPrivate::waitForPacket(quint64 sequenceNumber)
{
Q_Q(MRemoteThemeDaemon);
// send it immediately
socket.flush();
QObject::disconnect(&socket, SIGNAL(readyRead()), q, SLOT(connectionDataAvailable()));
// wait until we get a packet with type
while (socket.waitForReadyRead(-1)) {
while (socket.bytesAvailable()) {
// read one packet
const Packet packet = readOnePacket();
// check if it was the one we are waiting for
if (packet.sequenceNumber() == sequenceNumber) {
// read rest
QObject::connect(&socket, SIGNAL(readyRead()), q, SLOT(connectionDataAvailable()));
connectionDataAvailable();
return packet;
}
// if it was not the packet we're waiting for, lets process it
processOnePacket(packet);
}
}
mWarning("MRemoteThemeDaemon") << "waitForPacket: connection broken";
QObject::connect(&socket, SIGNAL(readyRead()), q, SLOT(connectionDataAvailable()));
return Packet();
}
quint64 MRemoteThemeDaemonPrivate::requestPixmap(const QString &imageId, const QSize &size)
{
const PixmapIdentifier id (imageId, size);
// check if we haven't yet asked for this pixmap
// if there's no ongoing request, we'll make one
const QHash<PixmapIdentifier, quint64>::const_iterator req = pixmapRequests.constFind(id);
quint64 sequenceNumber;
if (req != pixmapRequests.constEnd()) {
sequenceNumber = req.value();
mWarning("MRemoteThemeDaemon") << "requested pixmap which already exists in cache";
}
else {
sequenceNumber = ++sequenceCounter;
stream << Packet(Packet::RequestPixmapPacket, sequenceNumber, new PixmapIdentifier(id));
// remember sequence number of ongoing request
pixmapRequests.insert(id, sequenceNumber);
}
return sequenceNumber;
}
void MRemoteThemeDaemon::pixmapHandleSync(const QString &imageId, const QSize &size)
{
Q_D(MRemoteThemeDaemon);
const quint64 sequenceNumber = d->requestPixmap(imageId, size);
const Packet reply = d->waitForPacket(sequenceNumber);
d->processOnePacket(reply);
}
void MRemoteThemeDaemon::pixmapHandle(const QString &imageId, const QSize &size)
{
Q_D(MRemoteThemeDaemon);
d->requestPixmap(imageId, size);
}
void MRemoteThemeDaemon::releasePixmap(const QString &imageId, const QSize &size)
{
Q_D(MRemoteThemeDaemon);
PixmapIdentifier *const id = new PixmapIdentifier(imageId, size);
// If a request for this pixmap is still in the queue, forget about it
// so that subsequent calls to pixmapHandle() will issue a new request.
d->pixmapRequests.remove(*id);
d->stream << Packet(Packet::ReleasePixmapPacket, ++d->sequenceCounter,
id /*callee assumes ownership*/);
}
QString MRemoteThemeDaemon::currentTheme()
{
Q_D(MRemoteThemeDaemon);
QDir dir(d->themeInheritanceChain.at(0));
return dir.dirName();
}
QStringList MRemoteThemeDaemon::themeInheritanceChain()
{
Q_D(MRemoteThemeDaemon);
return d->themeInheritanceChain;
}
QStringList MRemoteThemeDaemon::themeLibraryNames()
{
Q_D(MRemoteThemeDaemon);
return d->themeLibraryNames;
}
bool MRemoteThemeDaemon::hasPendingRequests() const
{
Q_D(const MRemoteThemeDaemon);
return !d->pixmapRequests.isEmpty();
}
Packet MRemoteThemeDaemonPrivate::readOnePacket()
{
Packet packet;
stream >> packet;
return packet;
}
void MRemoteThemeDaemonPrivate::processOnePacket(const Packet &packet)
{
Q_Q(MRemoteThemeDaemon);
// process it according to packet type
switch (packet.type()) {
case Packet::PixmapUpdatedPacket:
pixmapUpdated(*static_cast<const PixmapHandle *>(packet.data()));
break;
case Packet::ThemeChangedPacket: {
const ThemeChangeInfo* info = static_cast<const ThemeChangeInfo*>(packet.data());
themeChanged(info->themeInheritance, info->themeLibraryNames);
stream << Packet(Packet::ThemeChangeAppliedPacket, packet.sequenceNumber());
} break;
case Packet::ThemeChangeCompletedPacket: {
emit q->themeChangeCompleted();
} break;
default:
mDebug("MRemoteThemeDaemon") << "Couldn't process packet of type" << packet.type();
break;
}
}
void MRemoteThemeDaemonPrivate::connectionDataAvailable()
{
// when reading a packet block all signals to not start
// reading a second one
bool blocked = socket.blockSignals(true);
while (socket.bytesAvailable()) {
processOnePacket(readOnePacket());
}
socket.blockSignals(blocked);
}
void MRemoteThemeDaemonPrivate::pixmapUpdated(const PixmapHandle &handle)
{
Q_Q(MRemoteThemeDaemon);
pixmapRequests.remove(handle.identifier);
// The pixmap may have been updated either in response to a request or
// due to a theme change. It may have gone already, if a release
// request was processed by the server in the meantime. The recipient
// of the signal must be able to handle such a situation gracefully.
emit q->pixmapChanged(handle.identifier.imageId, handle.identifier.size, handle.pixmapHandle);
}
void MRemoteThemeDaemonPrivate::themeChanged(const QStringList &themeInheritanceChain, const QStringList &themeLibraryNames)
{
Q_Q(MRemoteThemeDaemon);
this->themeInheritanceChain = themeInheritanceChain;
this->themeLibraryNames = themeLibraryNames;
emit q->themeChanged(themeInheritanceChain, themeLibraryNames);
}
#include "moc_mremotethemedaemon.cpp"
<|endoftext|>
|
<commit_before>#include <iostream>
#include "cons.h"
#include "eval.h"
#include "reader.h"
namespace
{
class Repl
{
std::istream& in_;
std::ostream& out_;
std::string prompt_ = "mclisp> ";
mclisp::Reader reader_;
public:
explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout):
in_(in), out_(out), reader_(in_) {};
int loop();
};
int Repl::loop()
{
std::ostringstream oss;
while (oss.str() != "QUIT" && oss.str() != "(QUIT . NIL)")
{
out_ << prompt_;
oss.str("");
oss.clear();
mclisp::ConsCell *exp = reader_.Read();
mclisp::ConsCell *value = Eval(exp);
oss << *exp;
out_ << *value << std::endl;
}
return 0;
}
} //end namespace
int main()
{
Repl repl;
return repl.loop();
}
<commit_msg>Call InitLisp in main and don't try to Eval (quit).<commit_after>#include <iostream>
#include "cons.h"
#include "eval.h"
#include "init.h"
#include "reader.h"
namespace
{
class Repl
{
std::istream& in_;
std::ostream& out_;
std::string prompt_ = "mclisp> ";
mclisp::Reader reader_;
public:
explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout):
in_(in), out_(out), reader_(in_) {};
int loop();
};
int Repl::loop()
{
std::ostringstream oss;
while (true)
{
out_ << prompt_;
oss.str("");
oss.clear();
mclisp::ConsCell *exp = reader_.Read();
oss << *exp;
if (oss.str() == "QUIT" || oss.str() == "(QUIT . NIL)")
// TODO implement real (quit) function.
break;
mclisp::ConsCell *value = Eval(exp);
out_ << *value << std::endl;
}
return 0;
}
} //end namespace
int main()
{
Repl repl;
mclisp::InitLisp();
return repl.loop();
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.